execute_once.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. """
  2. 一键执行智能引擎 - 临时脚本
  3. """
  4. import asyncio
  5. import os
  6. import sys
  7. from pathlib import Path
  8. # 代理设置
  9. os.environ.setdefault("HTTP_PROXY", "http://127.0.0.1:29758")
  10. os.environ.setdefault("HTTPS_PROXY", "http://127.0.0.1:29758")
  11. # 添加项目根目录到 Python 路径
  12. sys.path.insert(0, str(Path(__file__).parent.parent.parent))
  13. from dotenv import load_dotenv
  14. load_dotenv()
  15. from agent.core.runner import AgentRunner
  16. from agent.trace import FileSystemTraceStore, Trace, Message
  17. from agent.llm import create_openrouter_llm_call
  18. from agent.utils import setup_logging
  19. from examples.auto_put_ad_mini.config import (
  20. MAIN_CONFIG, SKILLS_DIR, TRACE_STORE_PATH, LOG_LEVEL, LOG_FILE,
  21. )
  22. # 导入自定义工具
  23. from examples.auto_put_ad_mini.tools.data_query import fetch_creative_data, merge_creative_data
  24. from examples.auto_put_ad_mini.tools.roi_calculator import calculate_roi_metrics
  25. from examples.auto_put_ad_mini.tools.ad_decision import analyze_ads, get_ads_for_review, apply_decisions
  26. from examples.auto_put_ad_mini.tools.report_generator import generate_report, compare_decisions
  27. from examples.auto_put_ad_mini.tools.guardrails import validate_decisions
  28. from examples.auto_put_ad_mini.tools.execution_engine import execute_decisions, check_execution_feedback
  29. from examples.auto_put_ad_mini.tools.im_approval import send_approval_request, check_approval_status
  30. async def main():
  31. base_dir = Path(__file__).parent
  32. setup_logging(level=LOG_LEVEL, file=LOG_FILE)
  33. # 加载 system prompt
  34. prompt_path = base_dir / "prompts" / "system.prompt"
  35. system_prompt = ""
  36. if prompt_path.exists():
  37. system_prompt = prompt_path.read_text(encoding="utf-8")
  38. # 加载 presets
  39. presets_path = base_dir / "presets.json"
  40. if presets_path.exists():
  41. from agent.core.presets import load_presets_from_json
  42. load_presets_from_json(str(presets_path))
  43. store = FileSystemTraceStore(base_path=TRACE_STORE_PATH)
  44. runner = AgentRunner(
  45. trace_store=store,
  46. llm_call=create_openrouter_llm_call(model=MAIN_CONFIG.model),
  47. skills_dir=SKILLS_DIR if Path(SKILLS_DIR).exists() else None,
  48. logger_name="agents.auto_put_ad_mini",
  49. )
  50. config = MAIN_CONFIG
  51. if system_prompt:
  52. config.system_prompt = system_prompt
  53. print("=" * 70)
  54. print(" 广告智能调控助手 — 智能引擎执行")
  55. print("=" * 70)
  56. print()
  57. print("🚀 自动执行:分析广告")
  58. print()
  59. print("=" * 70)
  60. print(" 流程:数据拉取 → ROI计算 → 分类(A/B/C) → AI推理 → 保存决策 → 护栏验证 → 生成报告")
  61. print("=" * 70)
  62. print()
  63. messages = [{"role": "user", "content": "分析广告"}]
  64. config.trace_id = None
  65. step_count = 0
  66. try:
  67. async for item in runner.run(messages=messages, config=config):
  68. if isinstance(item, Trace):
  69. if item.status == "completed":
  70. print(f"\n✅ [Trace] 完成")
  71. elif item.status == "failed":
  72. print(f"\n❌ [Trace] 失败")
  73. elif isinstance(item, Message):
  74. if item.role == "assistant" and item.content:
  75. content = item.content
  76. text = content.get("text", "") if isinstance(content, dict) else content
  77. if text and text.strip():
  78. print(f"\n💭 {text}\n")
  79. elif item.role == "tool" and item.content:
  80. content = item.content
  81. if isinstance(content, dict):
  82. tool_name = content.get("tool_name", "unknown")
  83. result = content.get("result", content.get("text", str(content)))
  84. # 识别关键步骤
  85. if tool_name == "fetch_creative_data":
  86. step_count += 1
  87. print(f"\n{'='*70}")
  88. print(f"📌 步骤 {step_count}: 数据拉取")
  89. print(f"{'='*70}")
  90. elif tool_name == "calculate_roi_metrics":
  91. step_count += 1
  92. print(f"\n{'='*70}")
  93. print(f"📌 步骤 {step_count}: ROI 计算")
  94. print(f"{'='*70}")
  95. elif tool_name == "get_ads_for_review":
  96. step_count += 1
  97. print(f"\n{'='*70}")
  98. print(f"📌 步骤 {step_count}: 广告分类(A/B/C)")
  99. print(f"{'='*70}")
  100. elif tool_name == "apply_decisions":
  101. step_count += 1
  102. print(f"\n{'='*70}")
  103. print(f"📌 步骤 {step_count}: 保存智能引擎决策")
  104. print(f"{'='*70}")
  105. elif tool_name == "validate_decisions":
  106. step_count += 1
  107. print(f"\n{'='*70}")
  108. print(f"📌 步骤 {step_count}: 安全护栏验证")
  109. print(f"{'='*70}")
  110. elif tool_name == "execute_decisions":
  111. step_count += 1
  112. print(f"\n{'='*70}")
  113. print(f"📌 步骤 {step_count}: 分级执行")
  114. print(f"{'='*70}")
  115. elif tool_name == "send_approval_request":
  116. step_count += 1
  117. print(f"\n{'='*70}")
  118. print(f"📌 步骤 {step_count}: IM 审批请求")
  119. print(f"{'='*70}")
  120. elif tool_name == "generate_report":
  121. step_count += 1
  122. print(f"\n{'='*70}")
  123. print(f"📌 步骤 {step_count}: 生成最终报告")
  124. print(f"{'='*70}")
  125. elif tool_name == "check_execution_feedback":
  126. step_count += 1
  127. print(f"\n{'='*70}")
  128. print(f"📌 步骤 {step_count}: 执行效果检查")
  129. print(f"{'='*70}")
  130. # 打印简化结果
  131. if isinstance(result, str):
  132. text = result
  133. else:
  134. text = str(result)
  135. if len(text) > 500:
  136. text = text[:500] + "..."
  137. print(f" {text}")
  138. print("\n" + "=" * 70)
  139. print("✅ 执行完成")
  140. print("=" * 70)
  141. print()
  142. print("📁 输出文件:")
  143. print(f" - 智能引擎决策:examples/auto_put_ad_mini/outputs/reports/llm_decisions_*.csv")
  144. print(f" - 最终报告(带格式):examples/auto_put_ad_mini/outputs/reports/decision_*.xlsx")
  145. print()
  146. except Exception as e:
  147. print(f"\n❌ 执行失败: {e}")
  148. import traceback
  149. traceback.print_exc()
  150. if __name__ == "__main__":
  151. asyncio.run(main())