execute_once.py 8.6 KB

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