execute_once.py 8.7 KB

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