runner.py 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130
  1. """
  2. Agent Runner - Agent 执行引擎
  3. 核心职责:
  4. 1. 执行 Agent 任务(循环调用 LLM + 工具)
  5. 2. 记录执行轨迹(Trace + Messages + GoalTree)
  6. 3. 检索和注入记忆(Experience + Skill)
  7. 4. 管理执行计划(GoalTree)
  8. 5. 支持续跑(continue)和回溯重跑(rewind)
  9. 参数分层:
  10. - Infrastructure: AgentRunner 构造时设置(trace_store, llm_call 等)
  11. - RunConfig: 每次 run 时指定(model, trace_id, after_sequence 等)
  12. - Messages: OpenAI SDK 格式的任务消息
  13. """
  14. import asyncio
  15. import json
  16. import logging
  17. import os
  18. import uuid
  19. from dataclasses import dataclass, field
  20. from datetime import datetime
  21. from typing import AsyncIterator, Optional, Dict, Any, List, Callable, Literal, Tuple, Union
  22. from agent.trace.models import Trace, Message
  23. from agent.trace.protocols import TraceStore
  24. from agent.trace.goal_models import GoalTree
  25. from agent.tools.builtin.experience import _get_structured_experiences, _batch_update_experiences
  26. from agent.trace.compaction import (
  27. CompressionConfig,
  28. filter_by_goal_status,
  29. estimate_tokens,
  30. needs_level2_compression,
  31. build_compression_prompt,
  32. build_reflect_prompt,
  33. )
  34. from agent.memory.models import Skill
  35. from agent.memory.protocols import MemoryStore, StateStore
  36. from agent.memory.skill_loader import load_skills_from_dir
  37. from agent.tools import ToolRegistry, get_tool_registry
  38. logger = logging.getLogger(__name__)
  39. # ===== 运行配置 =====
  40. @dataclass
  41. class RunConfig:
  42. """
  43. 运行参数 — 控制 Agent 如何执行
  44. 分为模型层参数(由上游 agent 或用户决定)和框架层参数(由系统注入)。
  45. """
  46. # --- 模型层参数 ---
  47. model: str = "gpt-4o"
  48. temperature: float = 0.3
  49. max_iterations: int = 200
  50. tools: Optional[List[str]] = None # None = 全部已注册工具
  51. # --- 框架层参数 ---
  52. agent_type: str = "default"
  53. uid: Optional[str] = None
  54. system_prompt: Optional[str] = None # None = 从 skills 自动构建
  55. skills: Optional[List[str]] = None # 注入 system prompt 的 skill 名称列表;None = 按 preset 决定
  56. enable_memory: bool = True
  57. auto_execute_tools: bool = True
  58. name: Optional[str] = None # 显示名称(空则由 utility_llm 自动生成)
  59. enable_prompt_caching: bool = True # 启用 Anthropic Prompt Caching(仅 Claude 模型有效)
  60. # --- Trace 控制 ---
  61. trace_id: Optional[str] = None # None = 新建
  62. parent_trace_id: Optional[str] = None # 子 Agent 专用
  63. parent_goal_id: Optional[str] = None
  64. # --- 续跑控制 ---
  65. after_sequence: Optional[int] = None # 从哪条消息后续跑(message sequence)
  66. # --- 额外 LLM 参数(传给 llm_call 的 **kwargs)---
  67. extra_llm_params: Dict[str, Any] = field(default_factory=dict)
  68. # --- 研究流程控制 ---
  69. enable_research_flow: bool = True # 是否启用自动研究流程(知识检索→经验检索→调研→计划)
  70. # 内置工具列表(始终自动加载)
  71. BUILTIN_TOOLS = [
  72. # 文件操作工具
  73. "read_file",
  74. "edit_file",
  75. "write_file",
  76. "glob_files",
  77. "grep_content",
  78. # 系统工具
  79. "bash_command",
  80. # 技能和目标管理
  81. "skill",
  82. "list_skills",
  83. "goal",
  84. "agent",
  85. "evaluate",
  86. # 搜索工具
  87. "search_posts",
  88. "get_experience",
  89. "get_search_suggestions",
  90. # 知识管理工具
  91. "search_knowledge",
  92. "save_knowledge",
  93. "update_knowledge",
  94. "list_knowledge",
  95. # 沙箱工具
  96. # "sandbox_create_environment",
  97. # "sandbox_run_shell",
  98. # "sandbox_rebuild_with_ports",
  99. # "sandbox_destroy_environment",
  100. # 浏览器工具
  101. "browser_navigate_to_url",
  102. "browser_search_web",
  103. "browser_go_back",
  104. "browser_wait",
  105. "browser_click_element",
  106. "browser_input_text",
  107. "browser_send_keys",
  108. "browser_upload_file",
  109. "browser_scroll_page",
  110. "browser_find_text",
  111. "browser_screenshot",
  112. "browser_switch_tab",
  113. "browser_close_tab",
  114. "browser_get_dropdown_options",
  115. "browser_select_dropdown_option",
  116. "browser_extract_content",
  117. "browser_read_long_content",
  118. "browser_download_direct_url",
  119. "browser_get_page_html",
  120. "browser_get_visual_selector_map",
  121. "browser_evaluate",
  122. "browser_ensure_login_with_cookies",
  123. "browser_wait_for_user_action",
  124. "browser_done",
  125. "browser_export_cookies",
  126. "browser_load_cookies"
  127. ]
  128. # ===== 向后兼容 =====
  129. @dataclass
  130. class AgentConfig:
  131. """[向后兼容] Agent 配置,新代码请使用 RunConfig"""
  132. agent_type: str = "default"
  133. max_iterations: int = 200
  134. enable_memory: bool = True
  135. auto_execute_tools: bool = True
  136. @dataclass
  137. class CallResult:
  138. """单次调用结果"""
  139. reply: str
  140. tool_calls: Optional[List[Dict]] = None
  141. trace_id: Optional[str] = None
  142. step_id: Optional[str] = None
  143. tokens: Optional[Dict[str, int]] = None
  144. cost: float = 0.0
  145. # ===== 执行引擎 =====
  146. CONTEXT_INJECTION_INTERVAL = 10 # 每 N 轮注入一次 GoalTree + Collaborators
  147. class AgentRunner:
  148. """
  149. Agent 执行引擎
  150. 支持三种运行模式(通过 RunConfig 区分):
  151. 1. 新建:trace_id=None
  152. 2. 续跑:trace_id=已有ID, after_sequence=None 或 == head
  153. 3. 回溯:trace_id=已有ID, after_sequence=N(N < head_sequence)
  154. """
  155. def __init__(
  156. self,
  157. trace_store: Optional[TraceStore] = None,
  158. memory_store: Optional[MemoryStore] = None,
  159. state_store: Optional[StateStore] = None,
  160. tool_registry: Optional[ToolRegistry] = None,
  161. llm_call: Optional[Callable] = None,
  162. utility_llm_call: Optional[Callable] = None,
  163. embedding_call: Optional[Callable] = None,
  164. config: Optional[AgentConfig] = None,
  165. skills_dir: Optional[str] = None,
  166. experiences_path: Optional[str] = "./.cache/experiences.md",
  167. goal_tree: Optional[GoalTree] = None,
  168. debug: bool = False,
  169. ):
  170. """
  171. 初始化 AgentRunner
  172. Args:
  173. trace_store: Trace 存储
  174. memory_store: Memory 存储(可选)
  175. state_store: State 存储(可选)
  176. tool_registry: 工具注册表(默认使用全局注册表)
  177. llm_call: 主 LLM 调用函数
  178. embedding_call: 语义嵌入向量LLM
  179. utility_llm_call: 轻量 LLM(用于生成任务标题等),可选
  180. config: [向后兼容] AgentConfig
  181. skills_dir: Skills 目录路径
  182. experiences_path: 经验文件路径(默认 ./.cache/experiences.md)
  183. goal_tree: 初始 GoalTree(可选)
  184. debug: 保留参数(已废弃)
  185. """
  186. self.trace_store = trace_store
  187. self.memory_store = memory_store
  188. self.state_store = state_store
  189. self.tools = tool_registry or get_tool_registry()
  190. self.llm_call = llm_call
  191. self.embedding_call = embedding_call
  192. self.utility_llm_call = utility_llm_call
  193. self.config = config or AgentConfig()
  194. self.skills_dir = skills_dir
  195. # 确保 experiences_path 不为 None,且文件存在
  196. self.experiences_path = experiences_path or "./.cache/experiences.md"
  197. if not os.path.exists(self.experiences_path):
  198. os.makedirs(os.path.dirname(self.experiences_path), exist_ok=True)
  199. with open(self.experiences_path, "w", encoding="utf-8") as f:
  200. f.write("")
  201. logger.info(f"自动创建经验文件: {self.experiences_path}")
  202. self.goal_tree = goal_tree
  203. self.debug = debug
  204. self._cancel_events: Dict[str, asyncio.Event] = {} # trace_id → cancel event
  205. self.used_ex_ids: List[str] = [] # 当前运行中使用过的经验 ID
  206. # 研究流程状态管理(每个 trace 独立)
  207. self._research_states: Dict[str, Dict[str, Any]] = {} # trace_id → research_state
  208. # ===== 核心公开方法 =====
  209. async def run(
  210. self,
  211. messages: List[Dict],
  212. config: Optional[RunConfig] = None,
  213. ) -> AsyncIterator[Union[Trace, Message]]:
  214. """
  215. Agent 模式执行(核心方法)
  216. Args:
  217. messages: OpenAI SDK 格式的输入消息
  218. 新建: 初始任务消息 [{"role": "user", "content": "..."}]
  219. 续跑: 追加的新消息
  220. 回溯: 在插入点之后追加的消息
  221. config: 运行配置
  222. Yields:
  223. Union[Trace, Message]: Trace 对象(状态变化)或 Message 对象(执行过程)
  224. """
  225. if not self.llm_call:
  226. raise ValueError("llm_call function not provided")
  227. config = config or RunConfig()
  228. trace = None
  229. try:
  230. # Phase 1: PREPARE TRACE
  231. trace, goal_tree, sequence = await self._prepare_trace(messages, config)
  232. # 注册取消事件
  233. self._cancel_events[trace.trace_id] = asyncio.Event()
  234. yield trace
  235. # Phase 2: BUILD HISTORY
  236. history, sequence, created_messages, head_seq = await self._build_history(
  237. trace.trace_id, messages, goal_tree, config, sequence
  238. )
  239. # Update trace's head_sequence in memory
  240. trace.head_sequence = head_seq
  241. for msg in created_messages:
  242. yield msg
  243. # Phase 3: AGENT LOOP
  244. async for event in self._agent_loop(trace, history, goal_tree, config, sequence):
  245. yield event
  246. except Exception as e:
  247. logger.error(f"Agent run failed: {e}")
  248. tid = config.trace_id or (trace.trace_id if trace else None)
  249. if self.trace_store and tid:
  250. # 读取当前 last_sequence 作为 head_sequence,确保续跑时能加载完整历史
  251. current = await self.trace_store.get_trace(tid)
  252. head_seq = current.last_sequence if current else None
  253. await self.trace_store.update_trace(
  254. tid,
  255. status="failed",
  256. head_sequence=head_seq,
  257. error_message=str(e),
  258. completed_at=datetime.now()
  259. )
  260. trace_obj = await self.trace_store.get_trace(tid)
  261. if trace_obj:
  262. yield trace_obj
  263. raise
  264. finally:
  265. # 清理取消事件
  266. if trace:
  267. self._cancel_events.pop(trace.trace_id, None)
  268. async def run_result(
  269. self,
  270. messages: List[Dict],
  271. config: Optional[RunConfig] = None,
  272. on_event: Optional[Callable] = None,
  273. ) -> Dict[str, Any]:
  274. """
  275. 结果模式 — 消费 run(),返回结构化结果。
  276. 主要用于 agent/evaluate 工具内部。
  277. Args:
  278. on_event: 可选回调,每个 Trace/Message 事件触发一次,用于实时输出子 Agent 执行过程。
  279. """
  280. last_assistant_text = ""
  281. final_trace: Optional[Trace] = None
  282. async for item in self.run(messages=messages, config=config):
  283. if on_event:
  284. on_event(item)
  285. if isinstance(item, Message) and item.role == "assistant":
  286. content = item.content
  287. text = ""
  288. if isinstance(content, dict):
  289. text = content.get("text", "") or ""
  290. elif isinstance(content, str):
  291. text = content
  292. if text and text.strip():
  293. last_assistant_text = text
  294. elif isinstance(item, Trace):
  295. final_trace = item
  296. config = config or RunConfig()
  297. if not final_trace and config.trace_id and self.trace_store:
  298. final_trace = await self.trace_store.get_trace(config.trace_id)
  299. status = final_trace.status if final_trace else "unknown"
  300. error = final_trace.error_message if final_trace else None
  301. summary = last_assistant_text
  302. if not summary:
  303. status = "failed"
  304. error = error or "Agent 没有产生 assistant 文本结果"
  305. return {
  306. "status": status,
  307. "summary": summary,
  308. "trace_id": final_trace.trace_id if final_trace else config.trace_id,
  309. "error": error,
  310. "stats": {
  311. "total_messages": final_trace.total_messages if final_trace else 0,
  312. "total_tokens": final_trace.total_tokens if final_trace else 0,
  313. "total_cost": final_trace.total_cost if final_trace else 0.0,
  314. },
  315. }
  316. async def stop(self, trace_id: str) -> bool:
  317. """
  318. 停止运行中的 Trace
  319. 设置取消信号,agent loop 在下一个 LLM 调用前检查并退出。
  320. Trace 状态置为 "stopped"。
  321. Returns:
  322. True 如果成功发送停止信号,False 如果该 trace 不在运行中
  323. """
  324. cancel_event = self._cancel_events.get(trace_id)
  325. if cancel_event is None:
  326. return False
  327. cancel_event.set()
  328. return True
  329. # ===== 单次调用(保留)=====
  330. async def call(
  331. self,
  332. messages: List[Dict],
  333. model: str = "gpt-4o",
  334. tools: Optional[List[str]] = None,
  335. uid: Optional[str] = None,
  336. trace: bool = True,
  337. **kwargs
  338. ) -> CallResult:
  339. """
  340. 单次 LLM 调用(无 Agent Loop)
  341. """
  342. if not self.llm_call:
  343. raise ValueError("llm_call function not provided")
  344. trace_id = None
  345. message_id = None
  346. tool_schemas = self._get_tool_schemas(tools)
  347. if trace and self.trace_store:
  348. trace_obj = Trace.create(mode="call", uid=uid, model=model, tools=tool_schemas, llm_params=kwargs)
  349. trace_id = await self.trace_store.create_trace(trace_obj)
  350. result = await self.llm_call(messages=messages, model=model, tools=tool_schemas, **kwargs)
  351. if trace and self.trace_store and trace_id:
  352. msg = Message.create(
  353. trace_id=trace_id, role="assistant", sequence=1, goal_id=None,
  354. content={"text": result.get("content", ""), "tool_calls": result.get("tool_calls")},
  355. prompt_tokens=result.get("prompt_tokens", 0),
  356. completion_tokens=result.get("completion_tokens", 0),
  357. finish_reason=result.get("finish_reason"),
  358. cost=result.get("cost", 0),
  359. )
  360. message_id = await self.trace_store.add_message(msg)
  361. await self.trace_store.update_trace(trace_id, status="completed", completed_at=datetime.now())
  362. return CallResult(
  363. reply=result.get("content", ""),
  364. tool_calls=result.get("tool_calls"),
  365. trace_id=trace_id,
  366. step_id=message_id,
  367. tokens={"prompt": result.get("prompt_tokens", 0), "completion": result.get("completion_tokens", 0)},
  368. cost=result.get("cost", 0)
  369. )
  370. # ===== Phase 1: PREPARE TRACE =====
  371. async def _prepare_trace(
  372. self,
  373. messages: List[Dict],
  374. config: RunConfig,
  375. ) -> Tuple[Trace, Optional[GoalTree], int]:
  376. """
  377. 准备 Trace:创建新的或加载已有的
  378. Returns:
  379. (trace, goal_tree, next_sequence)
  380. """
  381. if config.trace_id:
  382. return await self._prepare_existing_trace(config)
  383. else:
  384. return await self._prepare_new_trace(messages, config)
  385. async def _prepare_new_trace(
  386. self,
  387. messages: List[Dict],
  388. config: RunConfig,
  389. ) -> Tuple[Trace, Optional[GoalTree], int]:
  390. """创建新 Trace"""
  391. trace_id = str(uuid.uuid4())
  392. # 生成任务名称
  393. task_name = config.name or await self._generate_task_name(messages)
  394. # 准备工具 Schema
  395. tool_schemas = self._get_tool_schemas(config.tools)
  396. trace_obj = Trace(
  397. trace_id=trace_id,
  398. mode="agent",
  399. task=task_name,
  400. agent_type=config.agent_type,
  401. parent_trace_id=config.parent_trace_id,
  402. parent_goal_id=config.parent_goal_id,
  403. uid=config.uid,
  404. model=config.model,
  405. tools=tool_schemas,
  406. llm_params={"temperature": config.temperature, **config.extra_llm_params},
  407. status="running",
  408. )
  409. goal_tree = self.goal_tree or GoalTree(mission=task_name)
  410. if self.trace_store:
  411. await self.trace_store.create_trace(trace_obj)
  412. await self.trace_store.update_goal_tree(trace_id, goal_tree)
  413. return trace_obj, goal_tree, 1
  414. async def _prepare_existing_trace(
  415. self,
  416. config: RunConfig,
  417. ) -> Tuple[Trace, Optional[GoalTree], int]:
  418. """加载已有 Trace(续跑或回溯)"""
  419. if not self.trace_store:
  420. raise ValueError("trace_store required for continue/rewind")
  421. trace_obj = await self.trace_store.get_trace(config.trace_id)
  422. if not trace_obj:
  423. raise ValueError(f"Trace not found: {config.trace_id}")
  424. goal_tree = await self.trace_store.get_goal_tree(config.trace_id)
  425. if goal_tree is None:
  426. # 防御性兜底:trace 存在但 goal.json 丢失时,创建空树
  427. goal_tree = GoalTree(mission=trace_obj.task or "Agent task")
  428. await self.trace_store.update_goal_tree(config.trace_id, goal_tree)
  429. # 自动判断行为:after_sequence 为 None 或 == head → 续跑;< head → 回溯
  430. after_seq = config.after_sequence
  431. # 如果 after_seq > head_sequence,说明 generator 被强制关闭时 store 的
  432. # head_sequence 未来得及更新(仍停在 Phase 2 写入的初始值)。
  433. # 用 last_sequence 修正 head_sequence,确保续跑时能看到完整历史。
  434. if after_seq is not None and after_seq > trace_obj.head_sequence:
  435. trace_obj.head_sequence = trace_obj.last_sequence
  436. await self.trace_store.update_trace(
  437. config.trace_id, head_sequence=trace_obj.head_sequence
  438. )
  439. if after_seq is not None and after_seq < trace_obj.head_sequence:
  440. # 回溯模式
  441. sequence = await self._rewind(config.trace_id, after_seq, goal_tree)
  442. else:
  443. # 续跑模式:从 last_sequence + 1 开始
  444. sequence = trace_obj.last_sequence + 1
  445. # 状态置为 running
  446. await self.trace_store.update_trace(
  447. config.trace_id,
  448. status="running",
  449. completed_at=None,
  450. )
  451. trace_obj.status = "running"
  452. return trace_obj, goal_tree, sequence
  453. # ===== Phase 2: BUILD HISTORY =====
  454. async def _get_embedding(self, text: str) -> List[float]:
  455. """
  456. 获取文本的嵌入向量(Embedding)
  457. Args:
  458. text: 需要向量化的文本
  459. Returns:
  460. List[float]: 嵌入向量
  461. """
  462. if not text or not text.strip():
  463. return []
  464. # 优先使用注入的 embedding_call
  465. if self.embedding_call:
  466. try:
  467. return await self.embedding_call(text)
  468. except Exception as e:
  469. logger.error(f"Error in embedding_call: {e}")
  470. raise
  471. # 兜底方案:如果没有注入 embedding_call,但有 llm_call,
  472. # 某些 SDK 封装可能支持通过 llm_call 的客户端直接获取
  473. # 这里建议强制要求基础设施层提供该函数以保证分层清晰
  474. raise ValueError("embedding_call function not provided to AgentRunner")
  475. async def _build_history(
  476. self,
  477. trace_id: str,
  478. new_messages: List[Dict],
  479. goal_tree: Optional[GoalTree],
  480. config: RunConfig,
  481. sequence: int,
  482. ) -> Tuple[List[Dict], int, List[Message]]:
  483. """
  484. 构建完整的 LLM 消息历史
  485. 1. 从 head_sequence 沿 parent chain 加载主路径消息(续跑/回溯场景)
  486. 2. 构建 system prompt(新建时注入 skills)
  487. 3. 新建时:在第一条 user message 末尾注入当前经验
  488. 4. 追加 input messages(设置 parent_sequence 链接到当前 head)
  489. Returns:
  490. (history, next_sequence, created_messages, head_sequence)
  491. created_messages: 本次新创建并持久化的 Message 列表,供 run() yield 给调用方
  492. head_sequence: 当前主路径头节点的 sequence
  493. """
  494. history: List[Dict] = []
  495. created_messages: List[Message] = []
  496. head_seq: Optional[int] = None # 当前主路径的头节点 sequence
  497. # 1. 加载已有 messages(通过主路径遍历)
  498. if config.trace_id and self.trace_store:
  499. trace_obj = await self.trace_store.get_trace(trace_id)
  500. if trace_obj and trace_obj.head_sequence > 0:
  501. main_path = await self.trace_store.get_main_path_messages(
  502. trace_id, trace_obj.head_sequence
  503. )
  504. # 修复 orphaned tool_calls(中断导致的 tool_call 无 tool_result)
  505. main_path, sequence = await self._heal_orphaned_tool_calls(
  506. main_path, trace_id, goal_tree, sequence,
  507. )
  508. history = [msg.to_llm_dict() for msg in main_path]
  509. if main_path:
  510. head_seq = main_path[-1].sequence
  511. # 2. 构建/注入 skills 到 system prompt
  512. has_system = any(m.get("role") == "system" for m in history)
  513. has_system_in_new = any(m.get("role") == "system" for m in new_messages)
  514. if not has_system:
  515. if has_system_in_new:
  516. # 入参消息已含 system,将 skills 注入其中(在 step 4 持久化之前)
  517. augmented = []
  518. for msg in new_messages:
  519. if msg.get("role") == "system":
  520. base = msg.get("content") or ""
  521. enriched = await self._build_system_prompt(config, base_prompt=base)
  522. augmented.append({**msg, "content": enriched or base})
  523. else:
  524. augmented.append(msg)
  525. new_messages = augmented
  526. else:
  527. # 没有 system,自动构建并插入历史
  528. system_prompt = await self._build_system_prompt(config)
  529. if system_prompt:
  530. history = [{"role": "system", "content": system_prompt}] + history
  531. if self.trace_store:
  532. system_msg = Message.create(
  533. trace_id=trace_id, role="system", sequence=sequence,
  534. goal_id=None, content=system_prompt,
  535. parent_sequence=None, # system message 是 root
  536. )
  537. await self.trace_store.add_message(system_msg)
  538. created_messages.append(system_msg)
  539. head_seq = sequence
  540. sequence += 1
  541. # 3. 追加新 messages(设置 parent_sequence 链接到当前 head)
  542. for msg_dict in new_messages:
  543. history.append(msg_dict)
  544. if self.trace_store:
  545. stored_msg = Message.from_llm_dict(
  546. msg_dict, trace_id=trace_id, sequence=sequence,
  547. goal_id=None, parent_sequence=head_seq,
  548. )
  549. await self.trace_store.add_message(stored_msg)
  550. created_messages.append(stored_msg)
  551. head_seq = sequence
  552. sequence += 1
  553. # 5. 更新 trace 的 head_sequence
  554. if self.trace_store and head_seq is not None:
  555. await self.trace_store.update_trace(trace_id, head_sequence=head_seq)
  556. # 6. 初始化研究流程(仅在新建 trace 且启用研究流程时)
  557. if config.enable_research_flow and not config.trace_id:
  558. await self._init_research_flow(trace_id, new_messages, goal_tree, config)
  559. return history, sequence, created_messages, head_seq or 0
  560. async def _init_research_flow(
  561. self,
  562. trace_id: str,
  563. messages: List[Dict],
  564. goal_tree: Optional[GoalTree],
  565. config: RunConfig,
  566. ):
  567. """
  568. 初始化研究流程状态
  569. 研究流程阶段:
  570. 1. knowledge_search: 知识库检索
  571. 2. experience_search: 经验库检索
  572. 3. research_decision: 决定是否需要调研
  573. 4. research: 执行调研(如果需要)
  574. 5. planning: 制定计划
  575. 6. execution: 正常执行
  576. """
  577. # 提取任务描述
  578. task_desc = self._extract_task_description(messages)
  579. # 初始化研究状态
  580. self._research_states[trace_id] = {
  581. "stage": "knowledge_search", # 当前阶段
  582. "task_desc": task_desc,
  583. "knowledge_found": False,
  584. "experience_found": False,
  585. "need_research": False,
  586. "research_completed": False,
  587. "planning_completed": False,
  588. "knowledge_results": [],
  589. "experience_results": [],
  590. }
  591. logger.info(f"[Research Flow] 初始化研究流程: {task_desc[:50]}...")
  592. def _extract_task_description(self, messages: List[Dict]) -> str:
  593. """从消息中提取任务描述"""
  594. for msg in messages:
  595. if msg.get("role") == "user":
  596. content = msg.get("content", "")
  597. if isinstance(content, str):
  598. return content
  599. elif isinstance(content, list):
  600. for part in content:
  601. if isinstance(part, dict) and part.get("type") == "text":
  602. return part.get("text", "")
  603. return "未知任务"
  604. def _get_research_state(self, trace_id: str) -> Optional[Dict[str, Any]]:
  605. """获取研究流程状态"""
  606. return self._research_states.get(trace_id)
  607. def _update_research_stage(self, trace_id: str, stage: str, **kwargs):
  608. """更新研究流程阶段"""
  609. if trace_id in self._research_states:
  610. self._research_states[trace_id]["stage"] = stage
  611. self._research_states[trace_id].update(kwargs)
  612. logger.info(f"[Research Flow] 阶段切换: {stage}")
  613. def _build_research_guide(self, research_state: Dict[str, Any]) -> str:
  614. """根据研究流程状态构建引导消息"""
  615. stage = research_state["stage"]
  616. task_desc = research_state["task_desc"]
  617. if stage == "knowledge_search":
  618. return f"""
  619. ## 🔍 研究流程 - 阶段 1: 知识库检索
  620. 当前任务: {task_desc}
  621. **请立即执行以下操作**:
  622. 1. 使用 `search_knowledge(query="{task_desc[:100]}")` 检索知识库
  623. 2. 检查返回的知识是否足够完成任务
  624. 3. 如果找到相关知识,记录下来并继续下一阶段
  625. 注意:这是强制步骤,必须先检索知识库再继续。
  626. """
  627. elif stage == "experience_search":
  628. knowledge_results = research_state.get("knowledge_results", [])
  629. knowledge_summary = f"找到 {len(knowledge_results)} 条相关知识" if knowledge_results else "未找到相关知识"
  630. return f"""
  631. ## 🔍 研究流程 - 阶段 2: 经验库检索
  632. 知识库检索结果: {knowledge_summary}
  633. **请立即执行以下操作**:
  634. 1. 使用 `get_experience(query="{task_desc[:100]}", k=3)` 检索经验库
  635. 2. 结合知识库和经验库的结果,评估是否需要进行调研
  636. 3. 如果知识+经验足够,可以跳过调研直接进入计划阶段
  637. 注意:这是强制步骤,必须检索经验库。
  638. """
  639. elif stage == "research_decision":
  640. knowledge_results = research_state.get("knowledge_results", [])
  641. experience_results = research_state.get("experience_results", [])
  642. # 构建知识库摘要
  643. knowledge_summary = "### 知识库检索结果\n\n"
  644. if knowledge_results:
  645. knowledge_summary += f"找到 {len(knowledge_results)} 条相关知识:\n\n"
  646. for i, item in enumerate(knowledge_results[:5], 1): # 最多显示 5 条
  647. tags = item.get("tags", [])
  648. summary = item.get("summary", "")
  649. knowledge_summary += f"{i}. [{', '.join(tags)}] {summary[:150]}...\n"
  650. if len(knowledge_results) > 5:
  651. knowledge_summary += f"\n(还有 {len(knowledge_results) - 5} 条知识未显示)\n"
  652. else:
  653. knowledge_summary += "❌ 未找到相关知识\n"
  654. # 构建经验库摘要
  655. experience_summary = "\n### 经验库检索结果\n\n"
  656. if experience_results:
  657. experience_summary += f"找到 {len(experience_results)} 条相关经验:\n\n"
  658. for i, item in enumerate(experience_results[:5], 1): # 最多显示 5 条
  659. exp_id = item.get("id", "unknown")
  660. content = item.get("content", "")
  661. # 提取第一行作为摘要
  662. first_line = content.split('\n')[0] if content else ""
  663. experience_summary += f"{i}. [{exp_id}] {first_line[:150]}...\n"
  664. if len(experience_results) > 5:
  665. experience_summary += f"\n(还有 {len(experience_results) - 5} 条经验未显示)\n"
  666. else:
  667. experience_summary += "❌ 未找到相关经验\n"
  668. return f"""
  669. ## 🤔 研究流程 - 阶段 3: 决定是否调研
  670. 当前任务: {task_desc}
  671. {knowledge_summary}
  672. {experience_summary}
  673. ---
  674. **现在请你评估并明确回答以下问题**:
  675. 1. **现有信息是否足够完成任务?**
  676. - 如果知识库和经验库的信息已经足够,请回答:"无需调研,现有信息充足"
  677. - 如果信息不足或缺少关键知识,请回答:"需要调研"
  678. 2. **如果需要调研,请列出具体需要调研的问题**:
  679. - 缺少哪些工具或方法的信息?
  680. - 缺少哪些案例或最佳实践?
  681. - 需要了解哪些定义或原理?
  682. **重要**:
  683. - 请在回复中明确包含"无需调研"或"需要调研"这几个字,以便系统自动判断下一步操作
  684. - **本阶段只需要回复判断结果,不要调用任何工具(包括 goal 工具)**
  685. - 系统会根据你的判断自动进入下一阶段(调研或计划)
  686. 根据你的判断,系统会自动进入下一阶段(调研或计划)。
  687. """
  688. elif stage == "research":
  689. # 读取 research.md 的内容
  690. research_skill_content = ""
  691. research_skill_path = os.path.join(
  692. os.path.dirname(__file__),
  693. "..", "memory", "skills", "research.md"
  694. )
  695. try:
  696. with open(research_skill_path, "r", encoding="utf-8") as f:
  697. research_skill_content = f.read()
  698. except Exception as e:
  699. logger.warning(f"无法读取 research.md: {e}")
  700. research_skill_content = "(无法加载 research.md 内容)"
  701. return f"""
  702. ## 📚 研究流程 - 阶段 4: 执行调研
  703. 现有信息不足,需要进行调研。
  704. ---
  705. {research_skill_content}
  706. ---
  707. **请按照上述 research.md 中的方法执行调研**:
  708. 1. **拆解搜索维度**:使用 `goal(add="...")` 创建调研子目标
  709. 2. **多维度搜索**:使用 `search_posts` 搜索相关信息
  710. 3. **结构化记录**:使用 `save_knowledge` 保存每条有价值的知识
  711. 4. **完成标记**:调研完成后,使用 `goal(done="...")` 标记完成
  712. **注意**:
  713. - 每发现一条有价值的信息,立即使用 `save_knowledge` 保存
  714. - 调研完成后会自动进入计划阶段
  715. """
  716. elif stage == "planning":
  717. return f"""
  718. ## 📋 研究流程 - 阶段 5: 制定计划
  719. 调研已完成,现在需要制定执行计划。
  720. **请使用 goal 工具制定计划**:
  721. 1. 参考 `agent/memory/skills/planning.md` 中的计划方法
  722. 2. 使用 `goal(add="...")` 创建目标树
  723. 3. 将任务拆解为可执行的子目标
  724. 4. 使用 `goal(focus="...")` 聚焦到第一个目标
  725. 计划完成后会自动打印 goal tree 并进入执行阶段。
  726. """
  727. return ""
  728. async def _handle_research_flow_transition(
  729. self,
  730. trace_id: str,
  731. tool_name: str,
  732. tool_result: Any,
  733. goal_tree: Optional[GoalTree],
  734. ):
  735. """处理研究流程的状态转换"""
  736. research_state = self._get_research_state(trace_id)
  737. if not research_state:
  738. return
  739. stage = research_state["stage"]
  740. # 阶段 1: 知识库检索完成
  741. if stage == "knowledge_search" and tool_name == "search_knowledge":
  742. # 提取知识检索结果
  743. # tool_result 现在总是 dict,包含 {"text": ..., "metadata": ...}
  744. items = []
  745. if isinstance(tool_result, dict):
  746. metadata = tool_result.get("metadata", {})
  747. items = metadata.get("items", [])
  748. self._update_research_stage(
  749. trace_id,
  750. "experience_search",
  751. knowledge_found=len(items) > 0,
  752. knowledge_results=items
  753. )
  754. logger.info(f"[Research Flow] 知识检索完成,找到 {len(items)} 条知识")
  755. # 阶段 2: 经验库检索完成
  756. elif stage == "experience_search" and tool_name == "get_experience":
  757. # 提取经验检索结果
  758. experience_items = []
  759. if isinstance(tool_result, dict):
  760. experience_items = tool_result.get("items", [])
  761. elif isinstance(tool_result, str):
  762. # 解析字符串结果
  763. try:
  764. import json
  765. parsed = json.loads(tool_result)
  766. experience_items = parsed.get("items", [])
  767. except:
  768. pass
  769. self._update_research_stage(
  770. trace_id,
  771. "research_decision",
  772. experience_found=len(experience_items) > 0,
  773. experience_results=experience_items
  774. )
  775. logger.info(f"[Research Flow] 经验检索完成,找到 {len(experience_items)} 条经验")
  776. # 阶段 3: 调研决策(通过 assistant 的文本回复判断)
  777. # 这个阶段的转换在 assistant 回复后处理,不在这里
  778. # 阶段 4: 调研完成(检测到 save_knowledge 调用)
  779. elif stage == "research" and tool_name == "save_knowledge":
  780. # 标记调研完成,进入计划阶段
  781. self._update_research_stage(
  782. trace_id,
  783. "planning",
  784. research_completed=True
  785. )
  786. logger.info(f"[Research Flow] 调研完成,进入计划阶段")
  787. # 阶段 5: 计划完成(检测到 goal 工具调用)
  788. elif stage == "planning" and tool_name == "goal":
  789. # 检查是否创建了 goal tree
  790. if goal_tree and goal_tree.goals:
  791. self._update_research_stage(
  792. trace_id,
  793. "execution",
  794. planning_completed=True
  795. )
  796. logger.info(f"[Research Flow] 计划完成,进入执行阶段")
  797. # 打印 goal tree
  798. print("\n" + "="*60)
  799. print("📋 Goal Tree 已创建:")
  800. print("="*60)
  801. print(goal_tree.to_prompt())
  802. print("="*60 + "\n")
  803. # ===== Phase 3: AGENT LOOP =====
  804. async def _agent_loop(
  805. self,
  806. trace: Trace,
  807. history: List[Dict],
  808. goal_tree: Optional[GoalTree],
  809. config: RunConfig,
  810. sequence: int,
  811. ) -> AsyncIterator[Union[Trace, Message]]:
  812. """ReAct 循环"""
  813. trace_id = trace.trace_id
  814. tool_schemas = self._get_tool_schemas(config.tools)
  815. # 当前主路径头节点的 sequence(用于设置 parent_sequence)
  816. head_seq = trace.head_sequence
  817. # 经验检索缓存:只在 goal 切换时重新检索
  818. _last_goal_id = None
  819. _cached_exp_text = ""
  820. for iteration in range(config.max_iterations):
  821. # 检查取消信号
  822. cancel_event = self._cancel_events.get(trace_id)
  823. if cancel_event and cancel_event.is_set():
  824. logger.info(f"Trace {trace_id} stopped by user")
  825. if self.trace_store:
  826. await self.trace_store.update_trace(
  827. trace_id,
  828. status="stopped",
  829. head_sequence=head_seq,
  830. completed_at=datetime.now(),
  831. )
  832. trace_obj = await self.trace_store.get_trace(trace_id)
  833. if trace_obj:
  834. yield trace_obj
  835. return
  836. # Level 1 压缩:GoalTree 过滤(当消息超过阈值时触发)
  837. compression_config = CompressionConfig()
  838. token_count = estimate_tokens(history)
  839. max_tokens = compression_config.get_max_tokens(config.model)
  840. # 压缩评估日志
  841. progress_pct = (token_count / max_tokens * 100) if max_tokens > 0 else 0
  842. msg_count = len(history)
  843. img_count = sum(
  844. 1 for msg in history
  845. if isinstance(msg.get("content"), list)
  846. for part in msg["content"]
  847. if isinstance(part, dict) and part.get("type") in ("image", "image_url")
  848. )
  849. # 检查是否需要压缩(token 或消息数量超限)
  850. needs_compression_by_tokens = token_count > max_tokens
  851. needs_compression_by_count = (
  852. compression_config.max_messages > 0 and
  853. msg_count > compression_config.max_messages
  854. )
  855. needs_compression = needs_compression_by_tokens or needs_compression_by_count
  856. print(f"\n[压缩评估] 消息数: {msg_count} / {compression_config.max_messages} | 图片数: {img_count} | Token: {token_count:,} / {max_tokens:,} ({progress_pct:.1f}%)")
  857. if needs_compression:
  858. if needs_compression_by_count:
  859. print(f"[压缩评估] ⚠️ 消息数超过阈值 ({msg_count} > {compression_config.max_messages}),触发压缩流程")
  860. if needs_compression_by_tokens:
  861. print(f"[压缩评估] ⚠️ Token 数超过阈值,触发压缩流程")
  862. else:
  863. print(f"[压缩评估] ✅ 未超阈值,无需压缩")
  864. if needs_compression and self.trace_store and goal_tree:
  865. # 使用本地 head_seq(store 中的 head_sequence 在 loop 期间未更新,是过时的)
  866. if head_seq > 0:
  867. main_path_msgs = await self.trace_store.get_main_path_messages(
  868. trace_id, head_seq
  869. )
  870. filtered_msgs = filter_by_goal_status(main_path_msgs, goal_tree)
  871. if len(filtered_msgs) < len(main_path_msgs):
  872. filtered_tokens = estimate_tokens([msg.to_llm_dict() for msg in filtered_msgs])
  873. print(
  874. f"[Level 1 压缩] 消息: {len(main_path_msgs)} → {len(filtered_msgs)} 条 | "
  875. f"Token: {token_count:,} → ~{filtered_tokens:,}"
  876. )
  877. logger.info(
  878. "Level 1 压缩: %d -> %d 条消息 (tokens ~%d, 阈值 %d)",
  879. len(main_path_msgs), len(filtered_msgs), token_count, max_tokens,
  880. )
  881. history = [msg.to_llm_dict() for msg in filtered_msgs]
  882. else:
  883. print(
  884. f"[Level 1 压缩] 无可过滤消息 ({len(main_path_msgs)} 条全部保留, "
  885. f"completed/abandoned goals={sum(1 for g in goal_tree.goals if g.status in ('completed', 'abandoned'))})"
  886. )
  887. logger.info(
  888. "Level 1 压缩: 无可过滤消息 (%d 条全部保留, completed/abandoned goals=%d)",
  889. len(main_path_msgs),
  890. sum(1 for g in goal_tree.goals
  891. if g.status in ("completed", "abandoned")),
  892. )
  893. elif needs_compression:
  894. print("[压缩评估] ⚠️ 无法执行 Level 1 压缩(缺少 store 或 goal_tree)")
  895. logger.warning(
  896. "消息数 (%d) 或 token 数 (%d) 超过阈值 (max_messages=%d, max_tokens=%d),但无法执行 Level 1 压缩(缺少 store 或 goal_tree)",
  897. msg_count, token_count, compression_config.max_messages, max_tokens,
  898. )
  899. # Level 2 压缩:LLM 总结(Level 1 后仍超阈值时触发)
  900. token_count_after = estimate_tokens(history)
  901. msg_count_after = len(history)
  902. needs_level2_by_tokens = token_count_after > max_tokens
  903. needs_level2_by_count = (
  904. compression_config.max_messages > 0 and
  905. msg_count_after > compression_config.max_messages
  906. )
  907. needs_level2 = needs_level2_by_tokens or needs_level2_by_count
  908. if needs_level2:
  909. progress_pct_after = (token_count_after / max_tokens * 100) if max_tokens > 0 else 0
  910. reason = []
  911. if needs_level2_by_count:
  912. reason.append(f"消息数 {msg_count_after} > {compression_config.max_messages}")
  913. if needs_level2_by_tokens:
  914. reason.append(f"Token {token_count_after:,} > {max_tokens:,} ({progress_pct_after:.1f}%)")
  915. print(
  916. f"[Level 2 压缩] Level 1 后仍超阈值: {' | '.join(reason)} "
  917. f"→ 触发 LLM 总结"
  918. )
  919. logger.info(
  920. "Level 1 后仍超阈值 (消息数=%d/%d, token=%d/%d),触发 Level 2 压缩",
  921. msg_count_after, compression_config.max_messages, token_count_after, max_tokens,
  922. )
  923. history, head_seq, sequence = await self._compress_history(
  924. trace_id, history, goal_tree, config, sequence, head_seq,
  925. )
  926. final_tokens = estimate_tokens(history)
  927. print(f"[Level 2 压缩] 完成: Token {token_count_after:,} → {final_tokens:,}")
  928. elif needs_compression:
  929. # Level 1 压缩成功,未触发 Level 2
  930. print(f"[压缩评估] ✅ Level 1 压缩后达标: 消息数 {msg_count_after} | Token {token_count_after:,} / {max_tokens:,}")
  931. print() # 空行分隔
  932. # 构建 LLM messages(注入上下文)
  933. llm_messages = list(history)
  934. # 收集需要持久化的 system 消息
  935. system_messages_to_persist = []
  936. # 研究流程引导(仅在启用且处于研究阶段时)
  937. research_state = self._get_research_state(trace_id)
  938. if research_state and research_state["stage"] != "execution":
  939. research_guide = self._build_research_guide(research_state)
  940. if research_guide:
  941. system_msg = {"role": "system", "content": research_guide}
  942. llm_messages.append(system_msg)
  943. system_messages_to_persist.append(("研究流程引导", system_msg))
  944. # 周期性注入 GoalTree + Collaborators
  945. if iteration % CONTEXT_INJECTION_INTERVAL == 0:
  946. context_injection = self._build_context_injection(trace, goal_tree)
  947. if context_injection:
  948. system_msg = {"role": "system", "content": context_injection}
  949. llm_messages.append(system_msg)
  950. system_messages_to_persist.append(("上下文注入", system_msg))
  951. # 经验检索:goal 切换时重新检索,注入为 system message
  952. current_goal_id = goal_tree.current_id if goal_tree else None
  953. if current_goal_id and current_goal_id != _last_goal_id:
  954. _last_goal_id = current_goal_id
  955. current_goal = goal_tree.find(current_goal_id)
  956. if current_goal:
  957. try:
  958. relevant_exps = await _get_structured_experiences(
  959. query_text=current_goal.description,
  960. top_k=3,
  961. context={"runner": self}
  962. )
  963. if relevant_exps:
  964. self.used_ex_ids = [exp['id'] for exp in relevant_exps]
  965. parts = [f"[{exp['id']}] {exp['content']}" for exp in relevant_exps]
  966. _cached_exp_text = "## 参考历史经验\n" + "\n\n".join(parts)
  967. logger.info(
  968. "经验检索: goal='%s', 命中 %d 条 %s",
  969. current_goal.description[:40],
  970. len(relevant_exps),
  971. self.used_ex_ids,
  972. )
  973. else:
  974. _cached_exp_text = ""
  975. except Exception as e:
  976. logger.warning("经验检索失败: %s", e)
  977. _cached_exp_text = ""
  978. if _cached_exp_text:
  979. system_msg = {"role": "system", "content": _cached_exp_text}
  980. llm_messages.append(system_msg)
  981. system_messages_to_persist.append(("经验检索", system_msg))
  982. # 持久化 system 消息到 trace 和 history
  983. for label, sys_msg in system_messages_to_persist:
  984. # 添加到 history(这样会被包含在后续的对话中)
  985. history.append(sys_msg)
  986. # 保存到 trace store
  987. if self.trace_store:
  988. system_message = Message.create(
  989. trace_id=trace_id,
  990. role="system",
  991. sequence=sequence,
  992. goal_id=current_goal_id,
  993. parent_sequence=head_seq if head_seq > 0 else None,
  994. content=sys_msg["content"],
  995. description=f"[{label}]" # 添加标签说明这是什么类型的 system 消息
  996. )
  997. await self.trace_store.add_message(system_message)
  998. yield system_message
  999. head_seq = sequence
  1000. sequence += 1
  1001. # 应用 Prompt Caching(不修改原始 history,只在发送给 LLM 时添加缓存标记)
  1002. llm_messages = self._add_cache_control(
  1003. llm_messages,
  1004. config.model,
  1005. config.enable_prompt_caching
  1006. )
  1007. # 调用 LLM
  1008. result = await self.llm_call(
  1009. messages=llm_messages,
  1010. model=config.model,
  1011. tools=tool_schemas,
  1012. temperature=config.temperature,
  1013. **config.extra_llm_params,
  1014. )
  1015. response_content = result.get("content", "")
  1016. tool_calls = result.get("tool_calls")
  1017. finish_reason = result.get("finish_reason")
  1018. prompt_tokens = result.get("prompt_tokens", 0)
  1019. completion_tokens = result.get("completion_tokens", 0)
  1020. step_cost = result.get("cost", 0)
  1021. cache_creation_tokens = result.get("cache_creation_tokens")
  1022. cache_read_tokens = result.get("cache_read_tokens")
  1023. # 研究流程:处理 research_decision 阶段的转换
  1024. research_state = self._get_research_state(trace_id)
  1025. research_decision_handled = False
  1026. if research_state and research_state["stage"] == "research_decision":
  1027. # 根据 assistant 的回复判断是否需要调研
  1028. response_lower = response_content.lower()
  1029. if "需要调研" in response_content or "need research" in response_lower:
  1030. self._update_research_stage(trace_id, "research", need_research=True)
  1031. logger.info(f"[Research Flow] 决定需要调研,进入调研阶段")
  1032. research_decision_handled = True
  1033. # 如果 Agent 错误地调用了工具,忽略它们
  1034. if tool_calls:
  1035. logger.warning(f"[Research Flow] 在 research_decision 阶段不应调用工具,已忽略 {len(tool_calls)} 个工具调用")
  1036. tool_calls = None
  1037. elif "无需调研" in response_content or "不需要调研" in response_content or "信息充足" in response_content:
  1038. self._update_research_stage(trace_id, "planning", need_research=False)
  1039. logger.info(f"[Research Flow] 决定无需调研,直接进入计划阶段")
  1040. research_decision_handled = True
  1041. # 如果 Agent 错误地调用了工具,忽略它们
  1042. if tool_calls:
  1043. logger.warning(f"[Research Flow] 在 research_decision 阶段不应调用工具,已忽略 {len(tool_calls)} 个工具调用")
  1044. tool_calls = None
  1045. # 按需自动创建 root goal
  1046. if goal_tree and not goal_tree.goals and tool_calls:
  1047. has_goal_call = any(
  1048. tc.get("function", {}).get("name") == "goal"
  1049. for tc in tool_calls
  1050. )
  1051. if not has_goal_call:
  1052. mission = goal_tree.mission
  1053. root_desc = mission[:200] if len(mission) > 200 else mission
  1054. goal_tree.add_goals(
  1055. descriptions=[root_desc],
  1056. reasons=["系统自动创建:Agent 未显式创建目标"],
  1057. parent_id=None
  1058. )
  1059. goal_tree.focus(goal_tree.goals[0].id)
  1060. if self.trace_store:
  1061. await self.trace_store.add_goal(trace_id, goal_tree.goals[0])
  1062. await self.trace_store.update_goal_tree(trace_id, goal_tree)
  1063. logger.info(f"自动创建 root goal: {goal_tree.goals[0].id}")
  1064. # 获取当前 goal_id
  1065. current_goal_id = goal_tree.current_id if (goal_tree and goal_tree.current_id) else None
  1066. # 记录 assistant Message(parent_sequence 指向当前 head)
  1067. assistant_msg = Message.create(
  1068. trace_id=trace_id,
  1069. role="assistant",
  1070. sequence=sequence,
  1071. goal_id=current_goal_id,
  1072. parent_sequence=head_seq if head_seq > 0 else None,
  1073. content={"text": response_content, "tool_calls": tool_calls},
  1074. prompt_tokens=prompt_tokens,
  1075. completion_tokens=completion_tokens,
  1076. cache_creation_tokens=cache_creation_tokens,
  1077. cache_read_tokens=cache_read_tokens,
  1078. finish_reason=finish_reason,
  1079. cost=step_cost,
  1080. )
  1081. if self.trace_store:
  1082. await self.trace_store.add_message(assistant_msg)
  1083. yield assistant_msg
  1084. head_seq = sequence
  1085. sequence += 1
  1086. # 处理工具调用
  1087. # 截断兜底:finish_reason == "length" 说明响应被 max_tokens 截断,
  1088. # tool call 参数很可能不完整,不应执行,改为提示模型分批操作
  1089. if tool_calls and finish_reason == "length":
  1090. logger.warning(
  1091. "[Runner] 响应被 max_tokens 截断,跳过 %d 个不完整的 tool calls",
  1092. len(tool_calls),
  1093. )
  1094. truncation_hint = (
  1095. "你的响应因为 max_tokens 限制被截断,tool call 参数不完整,未执行。"
  1096. "请将大内容拆分为多次小的工具调用(例如用 write_file 的 append 模式分批写入)。"
  1097. )
  1098. history.append({
  1099. "role": "assistant",
  1100. "content": response_content,
  1101. "tool_calls": tool_calls,
  1102. })
  1103. # 为每个被截断的 tool call 返回错误结果
  1104. for tc in tool_calls:
  1105. history.append({
  1106. "role": "tool",
  1107. "tool_call_id": tc["id"],
  1108. "content": truncation_hint,
  1109. })
  1110. continue
  1111. if tool_calls and config.auto_execute_tools:
  1112. history.append({
  1113. "role": "assistant",
  1114. "content": response_content,
  1115. "tool_calls": tool_calls,
  1116. })
  1117. for tc in tool_calls:
  1118. current_goal_id = goal_tree.current_id if (goal_tree and goal_tree.current_id) else None
  1119. tool_name = tc["function"]["name"]
  1120. tool_args = tc["function"]["arguments"]
  1121. if isinstance(tool_args, str):
  1122. tool_args = json.loads(tool_args) if tool_args.strip() else {}
  1123. elif tool_args is None:
  1124. tool_args = {}
  1125. tool_result = await self.tools.execute(
  1126. tool_name,
  1127. tool_args,
  1128. uid=config.uid or "",
  1129. context={
  1130. "store": self.trace_store,
  1131. "trace_id": trace_id,
  1132. "goal_id": current_goal_id,
  1133. "runner": self,
  1134. "goal_tree": goal_tree,
  1135. }
  1136. )
  1137. # --- 支持多模态工具反馈 ---
  1138. # execute() 返回 dict{"text", "images", "metadata"} 或 str
  1139. if isinstance(tool_result, dict):
  1140. tool_result_text = tool_result.get("text", str(tool_result))
  1141. # 处理图片
  1142. if tool_result.get("images"):
  1143. # 构建多模态消息格式
  1144. tool_content_for_llm = [{"type": "text", "text": tool_result_text}]
  1145. for img in tool_result["images"]:
  1146. if img.get("type") == "base64" and img.get("data"):
  1147. media_type = img.get("media_type", "image/png")
  1148. tool_content_for_llm.append({
  1149. "type": "image_url",
  1150. "image_url": {
  1151. "url": f"data:{media_type};base64,{img['data']}"
  1152. }
  1153. })
  1154. img_count = len(tool_content_for_llm) - 1 # 减去 text 块
  1155. print(f"[Runner] 多模态工具反馈: tool={tool_name}, images={img_count}, text_len={len(tool_result_text)}")
  1156. else:
  1157. # 无图片,只有文本
  1158. tool_content_for_llm = tool_result_text
  1159. else:
  1160. tool_result_text = str(tool_result)
  1161. tool_content_for_llm = tool_result_text
  1162. tool_msg = Message.create(
  1163. trace_id=trace_id,
  1164. role="tool",
  1165. sequence=sequence,
  1166. goal_id=current_goal_id,
  1167. parent_sequence=head_seq,
  1168. tool_call_id=tc["id"],
  1169. # 存储完整内容:有图片时保留 list(含 image_url),纯文本时存字符串
  1170. content={"tool_name": tool_name, "result": tool_content_for_llm},
  1171. )
  1172. if self.trace_store:
  1173. await self.trace_store.add_message(tool_msg)
  1174. # 截图单独存为同名 PNG 文件
  1175. if isinstance(tool_result, dict) and tool_result.get("images"):
  1176. import base64 as b64mod
  1177. for img in tool_result["images"]:
  1178. if img.get("data"):
  1179. png_path = self.trace_store._get_messages_dir(trace_id) / f"{tool_msg.message_id}.png"
  1180. png_path.write_bytes(b64mod.b64decode(img["data"]))
  1181. print(f"[Runner] 截图已保存: {png_path.name}")
  1182. break # 只存第一张
  1183. yield tool_msg
  1184. head_seq = sequence
  1185. sequence += 1
  1186. history.append({
  1187. "role": "tool",
  1188. "tool_call_id": tc["id"],
  1189. "name": tool_name,
  1190. "content": tool_content_for_llm, # 这里传入 list 即可触发模型的视觉能力
  1191. })
  1192. # ------------------------------------------
  1193. # 研究流程状态转换
  1194. await self._handle_research_flow_transition(
  1195. trace_id, tool_name, tool_result, goal_tree
  1196. )
  1197. continue # 继续循环
  1198. # 研究流程决策阶段:即使没有工具调用也要继续
  1199. if research_decision_handled:
  1200. logger.info(f"[Research Flow] 研究决策完成,继续下一轮循环")
  1201. continue
  1202. # 无工具调用,任务完成
  1203. break
  1204. # 更新 head_sequence 并完成 Trace
  1205. if self.trace_store:
  1206. await self.trace_store.update_trace(
  1207. trace_id,
  1208. status="completed",
  1209. head_sequence=head_seq,
  1210. completed_at=datetime.now(),
  1211. )
  1212. trace_obj = await self.trace_store.get_trace(trace_id)
  1213. if trace_obj:
  1214. yield trace_obj
  1215. # ===== Level 2: LLM 压缩 =====
  1216. async def _compress_history(
  1217. self,
  1218. trace_id: str,
  1219. history: List[Dict],
  1220. goal_tree: Optional[GoalTree],
  1221. config: RunConfig,
  1222. sequence: int,
  1223. head_seq: int,
  1224. ) -> Tuple[List[Dict], int, int]:
  1225. """
  1226. Level 2 压缩:LLM 总结
  1227. Step 1: 经验提取(reflect)— 纯内存 LLM 调用 + 文件追加,不影响 trace
  1228. Step 2: 压缩总结 — LLM 生成 summary
  1229. Step 3: 存储 summary 为新消息,parent_sequence 跳到 system msg
  1230. Step 4: 重建 history
  1231. Returns:
  1232. (new_history, new_head_seq, next_sequence)
  1233. """
  1234. logger.info("Level 2 压缩开始: trace=%s, 当前 history 长度=%d", trace_id, len(history))
  1235. # 找到 system message 的 sequence(主路径第一条消息)
  1236. system_msg_seq = None
  1237. system_msg_dict = None
  1238. if self.trace_store:
  1239. trace_obj = await self.trace_store.get_trace(trace_id)
  1240. if trace_obj and trace_obj.head_sequence > 0:
  1241. main_path = await self.trace_store.get_main_path_messages(
  1242. trace_id, trace_obj.head_sequence
  1243. )
  1244. for msg in main_path:
  1245. if msg.role == "system":
  1246. system_msg_seq = msg.sequence
  1247. system_msg_dict = msg.to_llm_dict()
  1248. break
  1249. # Fallback: 从 history 中找 system message
  1250. if system_msg_dict is None:
  1251. for msg_dict in history:
  1252. if msg_dict.get("role") == "system":
  1253. system_msg_dict = msg_dict
  1254. break
  1255. if system_msg_dict is None:
  1256. logger.warning("Level 2 压缩跳过:未找到 system message")
  1257. return history, head_seq, sequence
  1258. # --- Step 1: 经验提取(reflect)---
  1259. try:
  1260. # 1. 构造 Reflect Prompt(确保包含格式要求)
  1261. # 建议在 build_reflect_prompt() 里加入:
  1262. # "请使用格式:- [intent: 意图, state: 状态描述] 具体的经验内容"
  1263. reflect_prompt = build_reflect_prompt()
  1264. reflect_messages = list(history) + [{"role": "user", "content": reflect_prompt}]
  1265. # 应用 Prompt Caching
  1266. reflect_messages = self._add_cache_control(
  1267. reflect_messages,
  1268. config.model,
  1269. config.enable_prompt_caching
  1270. )
  1271. reflect_result = await self.llm_call(
  1272. messages=reflect_messages,
  1273. model=config.model,
  1274. tools=[],
  1275. temperature=0.2, # 略微保持一点发散性
  1276. **config.extra_llm_params,
  1277. )
  1278. reflection_text = reflect_result.get("content", "").strip()
  1279. if reflection_text:
  1280. import re as _re2
  1281. import uuid as _uuid2
  1282. pattern = r"-\s*\[(?P<tags>.*?)\]\s*(?P<content>.*)"
  1283. matches = list(_re2.finditer(pattern, reflection_text))
  1284. structured_entries = []
  1285. for match in matches:
  1286. tags_str = match.group("tags")
  1287. content = match.group("content")
  1288. intent_match = _re2.search(r"intent:\s*(.*?)(?:,|$)", tags_str, _re2.IGNORECASE)
  1289. state_match = _re2.search(r"state:\s*(.*?)(?:,|$)", tags_str, _re2.IGNORECASE)
  1290. intents = [i.strip() for i in intent_match.group(1).split(",")] if intent_match and intent_match.group(1) else []
  1291. states = [s.strip() for s in state_match.group(1).split(",")] if state_match and state_match.group(1) else []
  1292. ex_id = f"ex_{datetime.now().strftime('%m%d%H%M')}_{_uuid2.uuid4().hex[:4]}"
  1293. entry = f"""---
  1294. id: {ex_id}
  1295. trace_id: {trace_id}
  1296. tags: {{intent: {intents}, state: {states}}}
  1297. metrics: {{helpful: 1, harmful: 0}}
  1298. created_at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
  1299. ---
  1300. - {content}
  1301. - 经验ID: [{ex_id}]"""
  1302. structured_entries.append(entry)
  1303. if structured_entries:
  1304. os.makedirs(os.path.dirname(self.experiences_path), exist_ok=True)
  1305. with open(self.experiences_path, "a", encoding="utf-8") as f:
  1306. f.write("\n\n" + "\n\n".join(structured_entries))
  1307. logger.info(f"已提取并保存 {len(structured_entries)} 条结构化经验")
  1308. else:
  1309. logger.warning("未能解析出符合格式的经验条目,请检查 REFLECT_PROMPT。")
  1310. logger.debug(f"LLM Raw Output:\n{reflection_text}")
  1311. else:
  1312. logger.warning("LLM 未生成反思内容")
  1313. except Exception as e:
  1314. logger.error(f"Level 2 经验提取失败: {e}")
  1315. # --- Step 2: 压缩总结 + 经验评估 ---
  1316. compress_prompt = build_compression_prompt(goal_tree, used_ex_ids=self.used_ex_ids)
  1317. compress_messages = list(history) + [{"role": "user", "content": compress_prompt}]
  1318. # 应用 Prompt Caching
  1319. compress_messages = self._add_cache_control(
  1320. compress_messages,
  1321. config.model,
  1322. config.enable_prompt_caching
  1323. )
  1324. compress_result = await self.llm_call(
  1325. messages=compress_messages,
  1326. model=config.model,
  1327. tools=[],
  1328. temperature=config.temperature,
  1329. **config.extra_llm_params,
  1330. )
  1331. raw_output = compress_result.get("content", "").strip()
  1332. if not raw_output:
  1333. logger.warning("Level 2 压缩跳过:LLM 未返回内容")
  1334. return history, head_seq, sequence
  1335. # 解析 [[EVALUATION]] 块并更新经验
  1336. if self.used_ex_ids:
  1337. try:
  1338. eval_block = ""
  1339. if "[[EVALUATION]]" in raw_output:
  1340. eval_start = raw_output.index("[[EVALUATION]]") + len("[[EVALUATION]]")
  1341. eval_end = raw_output.index("[[SUMMARY]]") if "[[SUMMARY]]" in raw_output else len(raw_output)
  1342. eval_block = raw_output[eval_start:eval_end].strip()
  1343. if eval_block:
  1344. import re as _re
  1345. update_map = {}
  1346. for line in eval_block.splitlines():
  1347. m = _re.search(r"ID:\s*(ex_\S+)\s*\|\s*Result:\s*(\w+)", line)
  1348. if m:
  1349. ex_id, result = m.group(1), m.group(2).lower()
  1350. if result in ("helpful", "harmful"):
  1351. update_map[ex_id] = {"action": result, "feedback": ""}
  1352. elif result == "mixed":
  1353. update_map[ex_id] = {"action": "helpful", "feedback": ""}
  1354. if update_map:
  1355. count = await _batch_update_experiences(update_map, context={"runner": self})
  1356. logger.info("经验评估完成,更新了 %s 条经验", count)
  1357. except Exception as e:
  1358. logger.warning("经验评估解析失败(不影响压缩): %s", e)
  1359. # 提取 [[SUMMARY]] 块
  1360. summary_text = raw_output
  1361. if "[[SUMMARY]]" in raw_output:
  1362. summary_text = raw_output[raw_output.index("[[SUMMARY]]") + len("[[SUMMARY]]"):].strip()
  1363. # 压缩完成后清空 used_ex_ids
  1364. self.used_ex_ids = []
  1365. if not summary_text:
  1366. logger.warning("Level 2 压缩跳过:LLM 未返回 summary")
  1367. return history, head_seq, sequence
  1368. # --- Step 3: 存储 summary 消息 ---
  1369. summary_with_header = (
  1370. f"## 对话历史摘要(自动压缩)\n\n{summary_text}\n\n"
  1371. "---\n请基于以上摘要和当前 GoalTree 继续执行任务。"
  1372. )
  1373. summary_msg = Message.create(
  1374. trace_id=trace_id,
  1375. role="user",
  1376. sequence=sequence,
  1377. goal_id=None,
  1378. parent_sequence=system_msg_seq, # 跳到 system msg,跳过所有中间消息
  1379. content=summary_with_header,
  1380. )
  1381. if self.trace_store:
  1382. await self.trace_store.add_message(summary_msg)
  1383. new_head_seq = sequence
  1384. sequence += 1
  1385. # --- Step 4: 重建 history ---
  1386. new_history = [system_msg_dict, summary_msg.to_llm_dict()]
  1387. # 更新 trace head_sequence
  1388. if self.trace_store:
  1389. await self.trace_store.update_trace(
  1390. trace_id,
  1391. head_sequence=new_head_seq,
  1392. )
  1393. logger.info(
  1394. "Level 2 压缩完成: 旧 history %d 条 → 新 history %d 条, summary 长度=%d",
  1395. len(history), len(new_history), len(summary_text),
  1396. )
  1397. return new_history, new_head_seq, sequence
  1398. # ===== 回溯(Rewind)=====
  1399. async def _rewind(
  1400. self,
  1401. trace_id: str,
  1402. after_sequence: int,
  1403. goal_tree: Optional[GoalTree],
  1404. ) -> int:
  1405. """
  1406. 执行回溯:快照 GoalTree,重建干净树,设置 head_sequence
  1407. 新消息的 parent_sequence 将指向 rewind 点,旧消息通过树结构自然脱离主路径。
  1408. Returns:
  1409. 下一个可用的 sequence 号
  1410. """
  1411. if not self.trace_store:
  1412. raise ValueError("trace_store required for rewind")
  1413. # 1. 加载所有 messages(用于 safe cutoff 和 max sequence)
  1414. all_messages = await self.trace_store.get_trace_messages(trace_id)
  1415. if not all_messages:
  1416. return 1
  1417. # 2. 找到安全截断点(确保不截断在 tool_call 和 tool response 之间)
  1418. cutoff = self._find_safe_cutoff(all_messages, after_sequence)
  1419. # 3. 快照并重建 GoalTree
  1420. if goal_tree:
  1421. # 获取截断点消息的 created_at 作为时间界限
  1422. cutoff_msg = None
  1423. for msg in all_messages:
  1424. if msg.sequence == cutoff:
  1425. cutoff_msg = msg
  1426. break
  1427. cutoff_time = cutoff_msg.created_at if cutoff_msg else datetime.now()
  1428. # 快照到 events(含 head_sequence 供前端感知分支切换)
  1429. await self.trace_store.append_event(trace_id, "rewind", {
  1430. "after_sequence": cutoff,
  1431. "head_sequence": cutoff,
  1432. "goal_tree_snapshot": goal_tree.to_dict(),
  1433. })
  1434. # 按时间重建干净的 GoalTree
  1435. new_tree = goal_tree.rebuild_for_rewind(cutoff_time)
  1436. await self.trace_store.update_goal_tree(trace_id, new_tree)
  1437. # 更新内存中的引用
  1438. goal_tree.goals = new_tree.goals
  1439. goal_tree.current_id = new_tree.current_id
  1440. # 4. 更新 head_sequence 到 rewind 点
  1441. await self.trace_store.update_trace(trace_id, head_sequence=cutoff)
  1442. # 5. 返回 next sequence(全局递增,不复用)
  1443. max_seq = max((m.sequence for m in all_messages), default=0)
  1444. return max_seq + 1
  1445. def _find_safe_cutoff(self, messages: List[Message], after_sequence: int) -> int:
  1446. """
  1447. 找到安全的截断点。
  1448. 如果 after_sequence 指向一条带 tool_calls 的 assistant message,
  1449. 则自动扩展到其所有对应的 tool response 之后。
  1450. """
  1451. cutoff = after_sequence
  1452. # 找到 after_sequence 对应的 message
  1453. target_msg = None
  1454. for msg in messages:
  1455. if msg.sequence == after_sequence:
  1456. target_msg = msg
  1457. break
  1458. if not target_msg:
  1459. return cutoff
  1460. # 如果是 assistant 且有 tool_calls,找到所有对应的 tool responses
  1461. if target_msg.role == "assistant":
  1462. content = target_msg.content
  1463. if isinstance(content, dict) and content.get("tool_calls"):
  1464. tool_call_ids = set()
  1465. for tc in content["tool_calls"]:
  1466. if isinstance(tc, dict) and tc.get("id"):
  1467. tool_call_ids.add(tc["id"])
  1468. # 找到这些 tool_call 对应的 tool messages
  1469. for msg in messages:
  1470. if (msg.role == "tool" and msg.tool_call_id
  1471. and msg.tool_call_id in tool_call_ids):
  1472. cutoff = max(cutoff, msg.sequence)
  1473. return cutoff
  1474. async def _heal_orphaned_tool_calls(
  1475. self,
  1476. messages: List[Message],
  1477. trace_id: str,
  1478. goal_tree: Optional[GoalTree],
  1479. sequence: int,
  1480. ) -> tuple:
  1481. """
  1482. 检测并修复消息历史中的 orphaned tool_calls。
  1483. 当 agent 被 stop/crash 中断时,可能有 assistant 的 tool_calls 没有对应的
  1484. tool results(包括多 tool_call 部分完成的情况)。直接发给 LLM 会导致 400。
  1485. 修复策略:为每个缺失的 tool_result 插入合成的"中断通知"消息,而非裁剪。
  1486. - 普通工具:简短中断提示
  1487. - agent/evaluate:包含 sub_trace_id、执行统计、continue_from 指引
  1488. 合成消息持久化到 store,确保幂等(下次续跑不再触发)。
  1489. Returns:
  1490. (healed_messages, next_sequence)
  1491. """
  1492. if not messages:
  1493. return messages, sequence
  1494. # 收集所有 tool_call IDs → (assistant_msg, tool_call_dict)
  1495. tc_map: Dict[str, tuple] = {}
  1496. result_ids: set = set()
  1497. for msg in messages:
  1498. if msg.role == "assistant":
  1499. content = msg.content
  1500. if isinstance(content, dict) and content.get("tool_calls"):
  1501. for tc in content["tool_calls"]:
  1502. tc_id = tc.get("id")
  1503. if tc_id:
  1504. tc_map[tc_id] = (msg, tc)
  1505. elif msg.role == "tool" and msg.tool_call_id:
  1506. result_ids.add(msg.tool_call_id)
  1507. orphaned_ids = [tc_id for tc_id in tc_map if tc_id not in result_ids]
  1508. if not orphaned_ids:
  1509. return messages, sequence
  1510. logger.info(
  1511. "检测到 %d 个 orphaned tool_calls,生成合成中断通知",
  1512. len(orphaned_ids),
  1513. )
  1514. healed = list(messages)
  1515. head_seq = messages[-1].sequence
  1516. for tc_id in orphaned_ids:
  1517. assistant_msg, tc = tc_map[tc_id]
  1518. tool_name = tc.get("function", {}).get("name", "unknown")
  1519. if tool_name in ("agent", "evaluate"):
  1520. result_text = self._build_agent_interrupted_result(
  1521. tc, goal_tree, assistant_msg,
  1522. )
  1523. else:
  1524. result_text = (
  1525. f"⚠️ 工具 {tool_name} 执行被中断(进程异常退出),"
  1526. "未获得执行结果。请根据需要重新调用。"
  1527. )
  1528. synthetic_msg = Message.create(
  1529. trace_id=trace_id,
  1530. role="tool",
  1531. sequence=sequence,
  1532. goal_id=assistant_msg.goal_id,
  1533. parent_sequence=head_seq,
  1534. tool_call_id=tc_id,
  1535. content={"tool_name": tool_name, "result": result_text},
  1536. )
  1537. if self.trace_store:
  1538. await self.trace_store.add_message(synthetic_msg)
  1539. healed.append(synthetic_msg)
  1540. head_seq = sequence
  1541. sequence += 1
  1542. # 更新 trace head/last sequence
  1543. if self.trace_store:
  1544. await self.trace_store.update_trace(
  1545. trace_id,
  1546. head_sequence=head_seq,
  1547. last_sequence=max(head_seq, sequence - 1),
  1548. )
  1549. return healed, sequence
  1550. def _build_agent_interrupted_result(
  1551. self,
  1552. tc: Dict,
  1553. goal_tree: Optional[GoalTree],
  1554. assistant_msg: Message,
  1555. ) -> str:
  1556. """为中断的 agent/evaluate 工具调用构建合成结果(对齐正常返回值格式)"""
  1557. args_str = tc.get("function", {}).get("arguments", "{}")
  1558. try:
  1559. args = json.loads(args_str) if isinstance(args_str, str) else args_str
  1560. except json.JSONDecodeError:
  1561. args = {}
  1562. task = args.get("task", "未知任务")
  1563. if isinstance(task, list):
  1564. task = "; ".join(task)
  1565. tool_name = tc.get("function", {}).get("name", "agent")
  1566. mode = "evaluate" if tool_name == "evaluate" else "delegate"
  1567. # 从 goal_tree 查找 sub_trace 信息
  1568. sub_trace_id = None
  1569. stats = None
  1570. if goal_tree and assistant_msg.goal_id:
  1571. goal = goal_tree.find(assistant_msg.goal_id)
  1572. if goal and goal.sub_trace_ids:
  1573. first = goal.sub_trace_ids[0]
  1574. if isinstance(first, dict):
  1575. sub_trace_id = first.get("trace_id")
  1576. elif isinstance(first, str):
  1577. sub_trace_id = first
  1578. if goal.cumulative_stats:
  1579. s = goal.cumulative_stats
  1580. if s.message_count > 0:
  1581. stats = {
  1582. "message_count": s.message_count,
  1583. "total_tokens": s.total_tokens,
  1584. "total_cost": round(s.total_cost, 4),
  1585. }
  1586. result: Dict[str, Any] = {
  1587. "mode": mode,
  1588. "status": "interrupted",
  1589. "summary": "⚠️ 子Agent执行被中断(进程异常退出)",
  1590. "task": task,
  1591. }
  1592. if sub_trace_id:
  1593. result["sub_trace_id"] = sub_trace_id
  1594. result["hint"] = (
  1595. f'使用 continue_from="{sub_trace_id}" 可继续执行,保留已有进度'
  1596. )
  1597. if stats:
  1598. result["stats"] = stats
  1599. return json.dumps(result, ensure_ascii=False, indent=2)
  1600. # ===== 上下文注入 =====
  1601. def _build_context_injection(
  1602. self,
  1603. trace: Trace,
  1604. goal_tree: Optional[GoalTree],
  1605. ) -> str:
  1606. """构建周期性注入的上下文(GoalTree + Active Collaborators + Focus 提醒)"""
  1607. parts = []
  1608. # GoalTree
  1609. if goal_tree and goal_tree.goals:
  1610. parts.append(f"## Current Plan\n\n{goal_tree.to_prompt()}")
  1611. # 检测 focus 在有子节点的父目标上:提醒模型 focus 到具体子目标
  1612. if goal_tree.current_id:
  1613. children = goal_tree.get_children(goal_tree.current_id)
  1614. pending_children = [c for c in children if c.status in ("pending", "in_progress")]
  1615. if pending_children:
  1616. child_ids = ", ".join(
  1617. goal_tree._generate_display_id(c) for c in pending_children[:3]
  1618. )
  1619. parts.append(
  1620. f"**提醒**:当前焦点在父目标上,建议用 `goal(focus=\"...\")` "
  1621. f"切换到具体子目标(如 {child_ids})再执行。"
  1622. )
  1623. # Active Collaborators
  1624. collaborators = trace.context.get("collaborators", [])
  1625. if collaborators:
  1626. lines = ["## Active Collaborators"]
  1627. for c in collaborators:
  1628. status_str = c.get("status", "unknown")
  1629. ctype = c.get("type", "agent")
  1630. summary = c.get("summary", "")
  1631. name = c.get("name", "unnamed")
  1632. lines.append(f"- {name} [{ctype}, {status_str}]: {summary}")
  1633. parts.append("\n".join(lines))
  1634. return "\n\n".join(parts)
  1635. # ===== 辅助方法 =====
  1636. def _add_cache_control(
  1637. self,
  1638. messages: List[Dict],
  1639. model: str,
  1640. enable: bool
  1641. ) -> List[Dict]:
  1642. """
  1643. 为支持的模型添加 Prompt Caching 标记
  1644. 策略:
  1645. 1. system message 添加缓存(如果存在且足够长)
  1646. 2. 倒数第 3-5 条 user/assistant 消息添加缓存点
  1647. Args:
  1648. messages: 原始消息列表
  1649. model: 模型名称
  1650. enable: 是否启用缓存
  1651. Returns:
  1652. 添加了 cache_control 的消息列表(深拷贝)
  1653. """
  1654. if not enable:
  1655. return messages
  1656. # 只对 Claude 模型启用
  1657. if "claude" not in model.lower():
  1658. return messages
  1659. # 深拷贝避免修改原始数据
  1660. import copy
  1661. messages = copy.deepcopy(messages)
  1662. # 策略 1: 为 system message 添加缓存
  1663. for msg in messages:
  1664. if msg.get("role") == "system":
  1665. content = msg.get("content", "")
  1666. # 只有足够长的 system prompt 才值得缓存(>1024 tokens 约 4000 字符)
  1667. if isinstance(content, str) and len(content) > 1000:
  1668. # Anthropic API 格式:在 content 的最后一个 block 添加 cache_control
  1669. # 如果 content 是 string,需要转换为 list 格式
  1670. msg["content"] = [
  1671. {
  1672. "type": "text",
  1673. "text": content,
  1674. "cache_control": {"type": "ephemeral"}
  1675. }
  1676. ]
  1677. logger.debug(f"[Cache] 为 system message 添加缓存标记 (len={len(content)})")
  1678. break
  1679. # 策略 2: 为倒数第 3-5 条消息添加缓存点
  1680. # 这样可以缓存大部分历史对话,只有最新的几条消息是新的
  1681. cache_positions = []
  1682. user_assistant_msgs = [
  1683. (i, msg) for i, msg in enumerate(messages)
  1684. if msg.get("role") in ("user", "assistant")
  1685. ]
  1686. if len(user_assistant_msgs) >= 5:
  1687. # 在倒数第 5 条添加缓存点
  1688. cache_positions.append(user_assistant_msgs[-5][0])
  1689. elif len(user_assistant_msgs) >= 3:
  1690. # 在倒数第 3 条添加缓存点
  1691. cache_positions.append(user_assistant_msgs[-3][0])
  1692. for idx in cache_positions:
  1693. msg = messages[idx]
  1694. content = msg.get("content", "")
  1695. # 处理 string content
  1696. if isinstance(content, str):
  1697. msg["content"] = [
  1698. {
  1699. "type": "text",
  1700. "text": content,
  1701. "cache_control": {"type": "ephemeral"}
  1702. }
  1703. ]
  1704. logger.debug(f"[Cache] 为 message[{idx}] ({msg.get('role')}) 添加缓存标记")
  1705. # 处理 list content(多模态消息)
  1706. elif isinstance(content, list) and len(content) > 0:
  1707. # 在最后一个 text block 添加 cache_control
  1708. for i in range(len(content) - 1, -1, -1):
  1709. if isinstance(content[i], dict) and content[i].get("type") == "text":
  1710. content[i]["cache_control"] = {"type": "ephemeral"}
  1711. logger.debug(f"[Cache] 为 message[{idx}] ({msg.get('role')}) 的 content[{i}] 添加缓存标记")
  1712. break
  1713. return messages
  1714. def _get_tool_schemas(self, tools: Optional[List[str]]) -> List[Dict]:
  1715. """
  1716. 获取工具 Schema
  1717. - tools=None: 使用 registry 中全部已注册工具(含内置 + 外部注册的)
  1718. - tools=["a", "b"]: 在 BUILTIN_TOOLS 基础上追加指定工具
  1719. """
  1720. if tools is None:
  1721. # 全部已注册工具
  1722. tool_names = self.tools.get_tool_names()
  1723. else:
  1724. # BUILTIN_TOOLS + 显式指定的额外工具
  1725. tool_names = BUILTIN_TOOLS.copy()
  1726. for t in tools:
  1727. if t not in tool_names:
  1728. tool_names.append(t)
  1729. return self.tools.get_schemas(tool_names)
  1730. # 默认 system prompt 前缀(当 config.system_prompt 和前端都未提供 system message 时使用)
  1731. DEFAULT_SYSTEM_PREFIX = "你是最顶尖的AI助手,可以拆分并调用工具逐步解决复杂问题。"
  1732. async def _build_system_prompt(self, config: RunConfig, base_prompt: Optional[str] = None) -> Optional[str]:
  1733. """构建 system prompt(注入 skills)
  1734. 优先级:
  1735. 1. config.skills 显式指定 → 按名称过滤
  1736. 2. config.skills 为 None → 查 preset 的默认 skills 列表
  1737. 3. preset 也无 skills(None)→ 加载全部(向后兼容)
  1738. Args:
  1739. base_prompt: 已有 system 内容(来自消息或 config.system_prompt),
  1740. None 时使用 config.system_prompt
  1741. """
  1742. from agent.core.presets import AGENT_PRESETS
  1743. system_prompt = base_prompt if base_prompt is not None else config.system_prompt
  1744. # 确定要加载哪些 skills
  1745. skills_filter: Optional[List[str]] = config.skills
  1746. if skills_filter is None:
  1747. preset = AGENT_PRESETS.get(config.agent_type)
  1748. if preset is not None:
  1749. skills_filter = preset.skills # 可能仍为 None(加载全部)
  1750. # 加载并过滤
  1751. all_skills = load_skills_from_dir(self.skills_dir)
  1752. if skills_filter is not None:
  1753. skills = [s for s in all_skills if s.name in skills_filter]
  1754. else:
  1755. skills = all_skills
  1756. skills_text = self._format_skills(skills) if skills else ""
  1757. if system_prompt:
  1758. if skills_text:
  1759. system_prompt += f"\n\n## Skills\n{skills_text}"
  1760. else:
  1761. system_prompt = self.DEFAULT_SYSTEM_PREFIX
  1762. if skills_text:
  1763. system_prompt += f"\n\n## Skills\n{skills_text}"
  1764. return system_prompt
  1765. async def _generate_task_name(self, messages: List[Dict]) -> str:
  1766. """生成任务名称:优先使用 utility_llm,fallback 到文本截取"""
  1767. # 提取 messages 中的文本内容
  1768. text_parts = []
  1769. for msg in messages:
  1770. content = msg.get("content", "")
  1771. if isinstance(content, str):
  1772. text_parts.append(content)
  1773. elif isinstance(content, list):
  1774. for part in content:
  1775. if isinstance(part, dict) and part.get("type") == "text":
  1776. text_parts.append(part.get("text", ""))
  1777. raw_text = " ".join(text_parts).strip()
  1778. if not raw_text:
  1779. return "未命名任务"
  1780. # 尝试使用 utility_llm 生成标题
  1781. if self.utility_llm_call:
  1782. try:
  1783. result = await self.utility_llm_call(
  1784. messages=[
  1785. {"role": "system", "content": "用中文为以下任务生成一个简短标题(10-30字),只输出标题本身:"},
  1786. {"role": "user", "content": raw_text[:2000]},
  1787. ],
  1788. model="gpt-4o-mini", # 使用便宜模型
  1789. )
  1790. title = result.get("content", "").strip()
  1791. if title and len(title) < 100:
  1792. return title
  1793. except Exception:
  1794. pass
  1795. # Fallback: 截取前 50 字符
  1796. return raw_text[:50] + ("..." if len(raw_text) > 50 else "")
  1797. def _format_skills(self, skills: List[Skill]) -> str:
  1798. if not skills:
  1799. return ""
  1800. return "\n\n".join(s.to_prompt_text() for s in skills)
  1801. def _load_experiences(self) -> str:
  1802. """从文件加载经验(./.cache/experiences.md)"""
  1803. if not self.experiences_path:
  1804. return ""
  1805. try:
  1806. if os.path.exists(self.experiences_path):
  1807. with open(self.experiences_path, "r", encoding="utf-8") as f:
  1808. return f.read().strip()
  1809. except Exception as e:
  1810. logger.warning(f"Failed to load experiences from {self.experiences_path}: {e}")
  1811. return ""