""" 一键执行智能引擎 - 临时脚本 """ import asyncio import os import sys from pathlib import Path # 代理设置 os.environ.setdefault("HTTP_PROXY", "http://127.0.0.1:29758") os.environ.setdefault("HTTPS_PROXY", "http://127.0.0.1:29758") # 添加项目根目录到 Python 路径 sys.path.insert(0, str(Path(__file__).parent.parent.parent)) from dotenv import load_dotenv load_dotenv() from agent.core.runner import AgentRunner from agent.trace import FileSystemTraceStore, Trace, Message from agent.llm import create_openrouter_llm_call from agent.utils import setup_logging from examples.auto_put_ad_mini.config import ( MAIN_CONFIG, SKILLS_DIR, TRACE_STORE_PATH, LOG_LEVEL, LOG_FILE, ) # 导入自定义工具 from examples.auto_put_ad_mini.tools.data_query import fetch_creative_data, merge_creative_data from examples.auto_put_ad_mini.tools.roi_calculator import calculate_roi_metrics from examples.auto_put_ad_mini.tools.ad_decision import analyze_ads, get_ads_for_review, apply_decisions, query_ad_detail, modify_decisions from examples.auto_put_ad_mini.tools.report_generator import generate_report, compare_decisions from examples.auto_put_ad_mini.tools.guardrails import validate_decisions from examples.auto_put_ad_mini.tools.execution_engine import execute_decisions, check_execution_feedback from examples.auto_put_ad_mini.tools.im_approval import send_approval_request, check_approval_status # 尝试导入飞书文档工具(如果存在) try: from examples.auto_put_ad_mini.tools.feishu_doc import import_to_feishu except ImportError: pass # 工具不存在,忽略 async def main(): base_dir = Path(__file__).parent setup_logging(level=LOG_LEVEL, file=LOG_FILE) # 加载 system prompt prompt_path = base_dir / "prompts" / "system.prompt" system_prompt = "" if prompt_path.exists(): system_prompt = prompt_path.read_text(encoding="utf-8") # 加载 presets presets_path = base_dir / "presets.json" if presets_path.exists(): from agent.core.presets import load_presets_from_json load_presets_from_json(str(presets_path)) store = FileSystemTraceStore(base_path=TRACE_STORE_PATH) runner = AgentRunner( trace_store=store, llm_call=create_openrouter_llm_call(model=MAIN_CONFIG.model), skills_dir=SKILLS_DIR if Path(SKILLS_DIR).exists() else None, logger_name="agents.auto_put_ad_mini", ) config = MAIN_CONFIG if system_prompt: config.system_prompt = system_prompt print("=" * 70) print(" 广告智能调控助手 — 智能引擎执行") print("=" * 70) print() print("🚀 自动执行:分析广告") print() print("=" * 70) print(" 流程:数据拉取 → ROI计算 → 分类(A/B/C) → AI推理 → 保存决策 → 护栏验证 → 生成报告") print("=" * 70) print() # 让Agent自动决定使用哪天的数据(默认yesterday) messages = [{"role": "user", "content": "分析广告,执行完整的ROI计算和决策流程。"}] config.trace_id = None step_count = 0 try: async for item in runner.run(messages=messages, config=config): if isinstance(item, Trace): if item.status == "completed": print(f"\n✅ [Trace] 完成") elif item.status == "failed": print(f"\n❌ [Trace] 失败") elif isinstance(item, Message): if item.role == "assistant" and item.content: content = item.content text = content.get("text", "") if isinstance(content, dict) else content if text and text.strip(): print(f"\n💭 {text}\n") elif item.role == "tool" and item.content: content = item.content if isinstance(content, dict): tool_name = content.get("tool_name", "unknown") result = content.get("result", content.get("text", str(content))) # 识别关键步骤 if tool_name == "fetch_creative_data": step_count += 1 print(f"\n{'='*70}") print(f"📌 步骤 {step_count}: 数据拉取") print(f"{'='*70}") elif tool_name == "calculate_roi_metrics": step_count += 1 print(f"\n{'='*70}") print(f"📌 步骤 {step_count}: ROI 计算") print(f"{'='*70}") elif tool_name == "get_ads_for_review": step_count += 1 print(f"\n{'='*70}") print(f"📌 步骤 {step_count}: 广告分类(A/B/C)") print(f"{'='*70}") elif tool_name == "apply_decisions": step_count += 1 print(f"\n{'='*70}") print(f"📌 步骤 {step_count}: 保存智能引擎决策") print(f"{'='*70}") elif tool_name == "validate_decisions": step_count += 1 print(f"\n{'='*70}") print(f"📌 步骤 {step_count}: 安全护栏验证") print(f"{'='*70}") elif tool_name == "execute_decisions": step_count += 1 print(f"\n{'='*70}") print(f"📌 步骤 {step_count}: 分级执行") print(f"{'='*70}") elif tool_name == "send_approval_request": step_count += 1 print(f"\n{'='*70}") print(f"📌 步骤 {step_count}: IM 审批请求") print(f"{'='*70}") elif tool_name == "generate_report": step_count += 1 print(f"\n{'='*70}") print(f"📌 步骤 {step_count}: 生成最终报告") print(f"{'='*70}") elif tool_name == "check_execution_feedback": step_count += 1 print(f"\n{'='*70}") print(f"📌 步骤 {step_count}: 执行效果检查") print(f"{'='*70}") # 打印简化结果 if isinstance(result, str): text = result else: text = str(result) if len(text) > 500: text = text[:500] + "..." print(f" {text}") print("\n" + "=" * 70) print("✅ 执行完成") print("=" * 70) print() print("📁 输出文件:") print(f" - 智能引擎决策:examples/auto_put_ad_mini/outputs/reports/llm_decisions_*.csv") print(f" - 最终报告(带格式):examples/auto_put_ad_mini/outputs/reports/decision_*.xlsx") print() except Exception as e: print(f"\n❌ 执行失败: {e}") import traceback traceback.print_exc() if __name__ == "__main__": asyncio.run(main())