execute_once.py 8.4 KB

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