execute_once.py 8.1 KB

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