execute_once.py 8.5 KB

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