execute_once.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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.portfolio_metrics import calculate_portfolio_summary
  26. from examples.auto_put_ad_mini.tools.ad_decision import get_ads_for_review, apply_decisions, query_ad_detail, modify_decisions
  27. from examples.auto_put_ad_mini.tools.report_generator import generate_report
  28. from examples.auto_put_ad_mini.tools.guardrails import validate_decisions
  29. from examples.auto_put_ad_mini.tools.execution_engine import execute_decisions, check_execution_feedback
  30. from examples.auto_put_ad_mini.tools.im_approval import send_approval_request, check_approval_status, send_feishu_text_message
  31. # 尝试导入飞书文档工具(如果存在)
  32. try:
  33. from examples.auto_put_ad_mini.tools.feishu_doc import import_to_feishu
  34. except ImportError:
  35. pass # 工具不存在,忽略
  36. async def main():
  37. base_dir = Path(__file__).parent
  38. setup_logging(level=LOG_LEVEL, file=LOG_FILE)
  39. # 加载 system prompt
  40. prompt_path = base_dir / "prompts" / "system.prompt"
  41. system_prompt = ""
  42. if prompt_path.exists():
  43. system_prompt = prompt_path.read_text(encoding="utf-8")
  44. # 加载 presets
  45. presets_path = base_dir / "presets.json"
  46. if presets_path.exists():
  47. from agent.core.presets import load_presets_from_json
  48. load_presets_from_json(str(presets_path))
  49. store = FileSystemTraceStore(base_path=TRACE_STORE_PATH)
  50. runner = AgentRunner(
  51. trace_store=store,
  52. llm_call=create_openrouter_llm_call(model=MAIN_CONFIG.model),
  53. skills_dir=SKILLS_DIR if Path(SKILLS_DIR).exists() else None,
  54. logger_name="agents.auto_put_ad_mini",
  55. )
  56. config = MAIN_CONFIG
  57. if system_prompt:
  58. config.system_prompt = system_prompt
  59. print("=" * 70)
  60. print(" 广告智能调控助手 — 智能引擎执行")
  61. print("=" * 70)
  62. print()
  63. print("🚀 自动执行:分析广告")
  64. print()
  65. print("=" * 70)
  66. print(" 流程:数据拉取 → ROI计算 → 人群包基线 → 候选筛选 → AI推理 → 保存决策 → 护栏验证 → 生成报告")
  67. print("=" * 70)
  68. print()
  69. # 让Agent自动决定使用哪天的数据(默认yesterday)
  70. messages = [{"role": "user", "content": "分析广告,执行完整的ROI计算和决策流程。请使用 2026-04-19(end_date=20260419)作为数据截止日期,因为 2026-04-20 的数据尚未回流。"}]
  71. config.trace_id = None
  72. step_count = 0
  73. try:
  74. async for item in runner.run(messages=messages, config=config):
  75. if isinstance(item, Trace):
  76. if item.status == "completed":
  77. print(f"\n✅ [Trace] 完成")
  78. elif item.status == "failed":
  79. print(f"\n❌ [Trace] 失败")
  80. elif isinstance(item, Message):
  81. if item.role == "assistant" and item.content:
  82. content = item.content
  83. text = content.get("text", "") if isinstance(content, dict) else content
  84. if text and text.strip():
  85. print(f"\n💭 {text}\n")
  86. elif item.role == "tool" and item.content:
  87. content = item.content
  88. if isinstance(content, dict):
  89. tool_name = content.get("tool_name", "unknown")
  90. result = content.get("result", content.get("text", str(content)))
  91. # 识别关键步骤
  92. if tool_name == "fetch_creative_data":
  93. step_count += 1
  94. print(f"\n{'='*70}")
  95. print(f"📌 步骤 {step_count}: 数据拉取")
  96. print(f"{'='*70}")
  97. elif tool_name == "calculate_roi_metrics":
  98. step_count += 1
  99. print(f"\n{'='*70}")
  100. print(f"📌 步骤 {step_count}: ROI 计算")
  101. print(f"{'='*70}")
  102. elif tool_name == "calculate_portfolio_summary":
  103. step_count += 1
  104. print(f"\n{'='*70}")
  105. print(f"📌 步骤 {step_count}: 人群包基线计算")
  106. print(f"{'='*70}")
  107. elif tool_name == "get_ads_for_review":
  108. step_count += 1
  109. print(f"\n{'='*70}")
  110. print(f"📌 步骤 {step_count}: 候选筛选(零消耗/待评估/正常运行)")
  111. print(f"{'='*70}")
  112. elif tool_name == "apply_decisions":
  113. step_count += 1
  114. print(f"\n{'='*70}")
  115. print(f"📌 步骤 {step_count}: 保存智能引擎决策")
  116. print(f"{'='*70}")
  117. elif tool_name == "validate_decisions":
  118. step_count += 1
  119. print(f"\n{'='*70}")
  120. print(f"📌 步骤 {step_count}: 安全护栏验证")
  121. print(f"{'='*70}")
  122. elif tool_name == "execute_decisions":
  123. step_count += 1
  124. print(f"\n{'='*70}")
  125. print(f"📌 步骤 {step_count}: 分级执行")
  126. print(f"{'='*70}")
  127. elif tool_name == "send_approval_request":
  128. step_count += 1
  129. print(f"\n{'='*70}")
  130. print(f"📌 步骤 {step_count}: IM 审批请求")
  131. print(f"{'='*70}")
  132. elif tool_name == "generate_report":
  133. step_count += 1
  134. print(f"\n{'='*70}")
  135. print(f"📌 步骤 {step_count}: 生成最终报告")
  136. print(f"{'='*70}")
  137. elif tool_name == "check_execution_feedback":
  138. step_count += 1
  139. print(f"\n{'='*70}")
  140. print(f"📌 步骤 {step_count}: 执行效果检查")
  141. print(f"{'='*70}")
  142. # 打印简化结果
  143. if isinstance(result, str):
  144. text = result
  145. else:
  146. text = str(result)
  147. if len(text) > 500:
  148. text = text[:500] + "..."
  149. print(f" {text}")
  150. print("\n" + "=" * 70)
  151. print("✅ 执行完成")
  152. print("=" * 70)
  153. print()
  154. print("📁 输出文件:")
  155. print(f" - 智能引擎决策:examples/auto_put_ad_mini/outputs/reports/llm_decisions_*.csv")
  156. print(f" - 最终报告(带格式):examples/auto_put_ad_mini/outputs/reports/decision_*.xlsx")
  157. print()
  158. except Exception as e:
  159. print(f"\n❌ 执行失败: {e}")
  160. import traceback
  161. traceback.print_exc()
  162. if __name__ == "__main__":
  163. asyncio.run(main())