run_single.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. from typing import Dict, Any, Optional
  2. import os
  3. from pathlib import Path
  4. from tools import fetch_account_article_list, fetch_weixin_account, weixin_search
  5. from agent import AgentRunner, RunConfig, FileSystemTraceStore, Trace, Message
  6. from agent.llm import create_openrouter_llm_call
  7. from agent.llm.prompts import SimplePrompt
  8. from agent.tools.builtin.knowledge import KnowledgeConfig
  9. # 默认搜索词
  10. DEFAULT_QUERY = "伊朗、以色列、和平是永恒的主题"
  11. DEFAULT_DEMAND_ID = 1
  12. import logging
  13. logger = logging.getLogger(__name__)
  14. PROJECT_ROOT = Path(__file__).resolve().parent
  15. async def run_agent(
  16. query: Optional[str] = None,
  17. demand_id: Optional[int] = None,
  18. stream_output: bool = True,
  19. ) -> Dict[str, Any]:
  20. """
  21. 执行 agent 任务
  22. Args:
  23. query: 查询内容(搜索词),None 则使用默认值
  24. demand_id: 本次搜索任务 id(int,关联 demand_content 表)
  25. stream_output: 是否流式输出到 stdout(run.py 需要,server.py 不需要)
  26. Returns:
  27. {
  28. "trace_id": "20260317_103046_xyz789",
  29. "status": "completed" | "failed",
  30. "error": "错误信息" # 失败时
  31. }
  32. """
  33. query = query or DEFAULT_QUERY
  34. demand_id = demand_id or DEFAULT_DEMAND_ID
  35. # 加载 prompt
  36. prompt_path = PROJECT_ROOT / "content_finder.prompt"
  37. prompt = SimplePrompt(prompt_path)
  38. # output 目录
  39. output_dir = str(PROJECT_ROOT / "tests" / "output")
  40. # 构建消息(替换 %query%、%output_dir%、%demand_id%)
  41. demand_id_str = str(demand_id) if demand_id is not None else ""
  42. messages = prompt.build_messages(query=query, output_dir=output_dir, demand_id=demand_id_str)
  43. # 初始化配置
  44. api_key = "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"
  45. if not api_key:
  46. raise ValueError("OPEN_ROUTER_API_KEY 未设置")
  47. model_name = prompt.config.get("model", "sonnet-4.6")
  48. model = os.getenv("MODEL", f"anthropic/claude-{model_name}")
  49. temperature = float(prompt.config.get("temperature", 0.3))
  50. max_iterations = 30
  51. trace_dir = str(PROJECT_ROOT / "traces")
  52. skills_dir = str(PROJECT_ROOT / "skills")
  53. Path(trace_dir).mkdir(parents=True, exist_ok=True)
  54. store = FileSystemTraceStore(base_path=trace_dir)
  55. allowed_tools = [
  56. "weixin_search",
  57. "fetch_weixin_account",
  58. "fetch_account_article_list",
  59. ]
  60. runner = AgentRunner(
  61. llm_call=create_openrouter_llm_call(model=model),
  62. trace_store=store,
  63. skills_dir=skills_dir,
  64. )
  65. config = RunConfig(
  66. name="内容寻找",
  67. model=model,
  68. temperature=temperature,
  69. max_iterations=max_iterations,
  70. tools=allowed_tools,
  71. extra_llm_params={"max_tokens": 8192},
  72. knowledge=KnowledgeConfig(
  73. enable_extraction=True,
  74. enable_completion_extraction=True,
  75. enable_injection=True,
  76. owner="content_finder_agent",
  77. default_tags={"project": "content_finder"},
  78. default_scopes=["com.piaoquantv.supply"],
  79. default_search_types=["tool", "usecase", "definition"],
  80. default_search_owner="content_finder_agent"
  81. )
  82. )
  83. # 执行
  84. trace_id = None
  85. try:
  86. async for item in runner.run(messages=messages, config=config):
  87. if isinstance(item, Trace):
  88. trace_id = item.trace_id
  89. if item.status == "completed":
  90. logger.info(f"Agent 执行完成: trace_id={trace_id}")
  91. return {
  92. "trace_id": trace_id,
  93. "status": "completed"
  94. }
  95. elif item.status == "failed":
  96. logger.error(f"Agent 执行失败: {item.error_message}")
  97. return {
  98. "trace_id": trace_id,
  99. "status": "failed",
  100. "error": item.error_message
  101. }
  102. elif isinstance(item, Message) and stream_output:
  103. # 流式输出(仅 run.py 需要)
  104. if item.role == "assistant":
  105. content = item.content
  106. if isinstance(content, dict):
  107. text = content.get("text", "")
  108. tool_calls = content.get("tool_calls", [])
  109. if text:
  110. # 如果有推荐结果,完整输出
  111. if len(text) > 500 and ("推荐结果" in text or "推荐内容" in text or "🎯" in text):
  112. print(f"\n{text}")
  113. # 如果有工具调用且文本较短,只输出摘要
  114. elif tool_calls and len(text) > 100:
  115. print(f"[思考] {text[:100]}...")
  116. # 其他情况输出完整文本
  117. else:
  118. print(f"\n{text}")
  119. # 输出工具调用信息
  120. if tool_calls:
  121. for tc in tool_calls:
  122. tool_name = tc.get("function", {}).get("name", "unknown")
  123. # 跳过 goal 工具的输出,减少噪音
  124. if tool_name != "goal":
  125. print(f"[工具] {tool_name}")
  126. elif isinstance(content, str) and content:
  127. print(f"\n{content}")
  128. elif item.role == "tool":
  129. content = item.content
  130. if isinstance(content, dict):
  131. tool_name = content.get("tool_name", "unknown")
  132. print(f"[结果] {tool_name} ✓")
  133. # 如果循环结束但没有返回,说明异常退出
  134. return {
  135. "trace_id": trace_id,
  136. "status": "failed",
  137. "error": "Agent 异常退出"
  138. }
  139. except KeyboardInterrupt:
  140. logger.info("用户中断")
  141. if stream_output:
  142. print("\n用户中断")
  143. return {
  144. "trace_id": trace_id,
  145. "status": "failed",
  146. "error": "用户中断"
  147. }
  148. except Exception as e:
  149. logger.error(f"Agent 执行异常: {e}", exc_info=True)
  150. if stream_output:
  151. print(f"\n执行失败: {e}")
  152. return {
  153. "trace_id": trace_id,
  154. "status": "failed",
  155. "error": str(e)
  156. }
  157. if __name__ == "__main__":
  158. import asyncio
  159. asyncio.run(run_agent())