core.py 6.9 KB

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