run_single.py 6.4 KB

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