runner.py 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241
  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.knowledge import _get_structured_knowledge, _batch_update_knowledge
  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. 如果经验和知识库不足时,必须调用子agent来执行调研
  637. 注意:这是强制步骤,必须检索经验库。
  638. """
  639. elif stage == "research":
  640. # 读取 research.md 的内容
  641. research_skill_content = ""
  642. research_skill_path = os.path.join(
  643. os.path.dirname(__file__),
  644. "..", "memory", "skills", "research.md"
  645. )
  646. try:
  647. with open(research_skill_path, "r", encoding="utf-8") as f:
  648. research_skill_content = f.read()
  649. except Exception as e:
  650. logger.warning(f"无法读取 research.md: {e}")
  651. research_skill_content = "(无法加载 research.md 内容)"
  652. return f"""
  653. ## 📚 研究流程 - 阶段 4: 执行调研
  654. 现有信息不足,需要进行调研。
  655. {research_skill_content}
  656. **重要提示**:
  657. - 调研完成后,请使用 `save_knowledge` 工具保存调研结果
  658. - 系统会自动检测到 save_knowledge 调用,并进入下一阶段(计划)
  659. """
  660. elif stage == "planning":
  661. return f"""
  662. ## 📋 研究流程 - 阶段 5: 制定计划
  663. 调研已完成(或无需调研),现在请制定执行计划。
  664. **请立即执行以下操作**:
  665. 1. 使用 `goal` 工具创建目标树
  666. 2. 将任务分解为可执行的子目标
  667. 3. 为每个子目标设置合理的优先级
  668. 注意:这是强制步骤,必须创建 goal tree 才能进入执行阶段。
  669. """
  670. # research_decision 阶段的引导消息已移到 _build_research_decision_guide
  671. return ""
  672. def _build_research_decision_guide(self, research_state: Dict[str, Any]) -> str:
  673. """构建调研决策阶段的引导消息(追加在经验检索消息后)"""
  674. knowledge_results = research_state.get("knowledge_results", [])
  675. experience_results = research_state.get("experience_results", [])
  676. task_desc = research_state.get("task_desc", "")
  677. # 构建知识库摘要
  678. knowledge_summary = "### 知识库检索结果\n\n"
  679. if knowledge_results:
  680. knowledge_summary += f"找到 {len(knowledge_results)} 条相关知识:\n\n"
  681. for i, item in enumerate(knowledge_results[:5], 1): # 最多显示 5 条
  682. tags = item.get("tags", [])
  683. summary = item.get("summary", "")
  684. knowledge_summary += f"{i}. [{', '.join(tags)}] {summary[:150]}...\n"
  685. if len(knowledge_results) > 5:
  686. knowledge_summary += f"\n(还有 {len(knowledge_results) - 5} 条知识未显示)\n"
  687. else:
  688. knowledge_summary += "❌ 未找到相关知识\n"
  689. # 构建经验库摘要
  690. experience_summary = "\n### 经验库检索结果\n\n"
  691. if experience_results:
  692. experience_summary += f"找到 {len(experience_results)} 条相关经验\n"
  693. else:
  694. experience_summary += "❌ 未找到相关经验\n"
  695. return f"""
  696. ---
  697. ## 🤔 调研决策
  698. {knowledge_summary}
  699. {experience_summary}
  700. ### 决策选项
  701. **选项 1: 无需调研,直接制定计划**
  702. - 如果现有知识和经验已经足够
  703. - 直接使用 `goal` 工具制定执行计划
  704. **选项 2: 需要深入调研** ⭐
  705. - 如果现有知识不足,需要进行网络搜索、文档查阅等调研
  706. - **立即调用 `agent` 工具启动调研子任务**:
  707. - 如果没有经验/知识,必须要先调研才可以继续执行
  708. - 无论任务描述是否确定。都需要先调研
  709. ```python
  710. agent(
  711. task=\"\"\"针对任务「{task_desc[:100]}」进行深入调研:
  712. 1. 使用 web_search 工具搜索相关技术文档、教程、最佳实践
  713. 2. 搜索关键词建议:
  714. - 核心技术名称 + "教程"
  715. - 核心技术名称 + "最佳实践"
  716. - 核心技术名称 + "示例代码"
  717. 3. 使用 read_file 工具查看项目中的相关文件
  718. 4. 对每条有价值的信息,使用 save_knowledge 工具保存,标签类型选择:
  719. - tool: 工具使用方法
  720. - definition: 概念定义
  721. - usercase: 使用案例
  722. - strategy: 策略经验
  723. 调研完成后,系统会自动进入计划阶段。
  724. \"\"\"
  725. )
  726. ```
  727. **重要提示**:
  728. - 如果知识库和经验库都没有找到相关内容,必须选择调研!但只需要简单调研,最多设立两个goal。
  729. """
  730. async def _handle_research_flow_transition(
  731. self,
  732. trace_id: str,
  733. tool_name: str,
  734. tool_result: Any,
  735. goal_tree: Optional[GoalTree],
  736. ):
  737. """处理研究流程的状态转换"""
  738. research_state = self._get_research_state(trace_id)
  739. if not research_state:
  740. return
  741. stage = research_state["stage"]
  742. # 阶段 1: 知识库检索完成
  743. if stage == "knowledge_search" and tool_name == "search_knowledge":
  744. # 提取知识检索结果
  745. # tool_result 现在总是 dict,包含 {"text": ..., "metadata": ...}
  746. items = []
  747. if isinstance(tool_result, dict):
  748. metadata = tool_result.get("metadata", {})
  749. items = metadata.get("items", [])
  750. self._update_research_stage(
  751. trace_id,
  752. "experience_search",
  753. knowledge_found=len(items) > 0,
  754. knowledge_results=items
  755. )
  756. logger.info(f"[Research Flow] 知识检索完成,找到 {len(items)} 条知识")
  757. # 阶段 2: 经验库检索完成
  758. elif stage == "experience_search" and tool_name == "get_experience":
  759. # 提取经验检索结果
  760. experience_items = []
  761. if isinstance(tool_result, dict):
  762. experience_items = tool_result.get("items", [])
  763. elif isinstance(tool_result, str):
  764. # 解析字符串结果
  765. try:
  766. import json
  767. parsed = json.loads(tool_result)
  768. experience_items = parsed.get("items", [])
  769. except:
  770. pass
  771. self._update_research_stage(
  772. trace_id,
  773. "research_decision",
  774. experience_found=len(experience_items) > 0,
  775. experience_results=experience_items
  776. )
  777. logger.info(f"[Research Flow] 经验检索完成,找到 {len(experience_items)} 条经验")
  778. # 阶段 3: 调研决策(通过 assistant 的文本回复判断)
  779. # 这个阶段的转换在 assistant 回复后处理,不在这里
  780. # 阶段 4: 调研完成
  781. # 情况 1: 检测到 save_knowledge 调用(直接调研)
  782. # 情况 2: 检测到 agent 工具执行完成(子 agent 调研)
  783. elif stage == "research":
  784. if tool_name == "save_knowledge":
  785. # 直接调研:检测到 save_knowledge 调用
  786. self._update_research_stage(
  787. trace_id,
  788. "planning",
  789. research_completed=True
  790. )
  791. logger.info(f"[Research Flow] 调研完成(直接调研),进入计划阶段")
  792. elif tool_name == "agent":
  793. # 子 agent 调研:agent 工具执行完成
  794. self._update_research_stage(
  795. trace_id,
  796. "planning",
  797. research_completed=True
  798. )
  799. logger.info(f"[Research Flow] 调研完成(子 agent 调研),进入计划阶段")
  800. # 阶段 5: 计划完成(检测到 goal 工具调用)
  801. elif stage == "planning" and tool_name == "goal":
  802. # 检查是否创建了 goal tree
  803. if goal_tree and goal_tree.goals:
  804. self._update_research_stage(
  805. trace_id,
  806. "execution",
  807. planning_completed=True
  808. )
  809. logger.info(f"[Research Flow] 计划完成,进入执行阶段")
  810. # 打印 goal tree
  811. print("\n" + "="*60)
  812. print("📋 Goal Tree 已创建:")
  813. print("="*60)
  814. print(goal_tree.to_prompt())
  815. print("="*60 + "\n")
  816. # ===== Phase 3: AGENT LOOP =====
  817. async def _agent_loop(
  818. self,
  819. trace: Trace,
  820. history: List[Dict],
  821. goal_tree: Optional[GoalTree],
  822. config: RunConfig,
  823. sequence: int,
  824. ) -> AsyncIterator[Union[Trace, Message]]:
  825. """ReAct 循环"""
  826. trace_id = trace.trace_id
  827. tool_schemas = self._get_tool_schemas(config.tools)
  828. # 当前主路径头节点的 sequence(用于设置 parent_sequence)
  829. head_seq = trace.head_sequence
  830. # 经验检索缓存:只在 goal 切换时重新检索
  831. _last_goal_id = None
  832. _cached_exp_text = ""
  833. for iteration in range(config.max_iterations):
  834. # 检查取消信号
  835. cancel_event = self._cancel_events.get(trace_id)
  836. if cancel_event and cancel_event.is_set():
  837. logger.info(f"Trace {trace_id} stopped by user")
  838. if self.trace_store:
  839. await self.trace_store.update_trace(
  840. trace_id,
  841. status="stopped",
  842. head_sequence=head_seq,
  843. completed_at=datetime.now(),
  844. )
  845. trace_obj = await self.trace_store.get_trace(trace_id)
  846. if trace_obj:
  847. yield trace_obj
  848. return
  849. # Level 1 压缩:GoalTree 过滤(当消息超过阈值时触发)
  850. compression_config = CompressionConfig()
  851. token_count = estimate_tokens(history)
  852. max_tokens = compression_config.get_max_tokens(config.model)
  853. # 压缩评估日志
  854. progress_pct = (token_count / max_tokens * 100) if max_tokens > 0 else 0
  855. msg_count = len(history)
  856. img_count = sum(
  857. 1 for msg in history
  858. if isinstance(msg.get("content"), list)
  859. for part in msg["content"]
  860. if isinstance(part, dict) and part.get("type") in ("image", "image_url")
  861. )
  862. # 检查是否需要压缩(token 或消息数量超限)
  863. needs_compression_by_tokens = token_count > max_tokens
  864. needs_compression_by_count = (
  865. compression_config.max_messages > 0 and
  866. msg_count > compression_config.max_messages
  867. )
  868. needs_compression = needs_compression_by_tokens or needs_compression_by_count
  869. print(f"\n[压缩评估] 消息数: {msg_count} / {compression_config.max_messages} | 图片数: {img_count} | Token: {token_count:,} / {max_tokens:,} ({progress_pct:.1f}%)")
  870. if needs_compression:
  871. if needs_compression_by_count:
  872. print(f"[压缩评估] ⚠️ 消息数超过阈值 ({msg_count} > {compression_config.max_messages}),触发压缩流程")
  873. if needs_compression_by_tokens:
  874. print(f"[压缩评估] ⚠️ Token 数超过阈值,触发压缩流程")
  875. else:
  876. print(f"[压缩评估] ✅ 未超阈值,无需压缩")
  877. if needs_compression and self.trace_store and goal_tree:
  878. # 使用本地 head_seq(store 中的 head_sequence 在 loop 期间未更新,是过时的)
  879. if head_seq > 0:
  880. main_path_msgs = await self.trace_store.get_main_path_messages(
  881. trace_id, head_seq
  882. )
  883. filtered_msgs = filter_by_goal_status(main_path_msgs, goal_tree)
  884. if len(filtered_msgs) < len(main_path_msgs):
  885. filtered_tokens = estimate_tokens([msg.to_llm_dict() for msg in filtered_msgs])
  886. print(
  887. f"[Level 1 压缩] 消息: {len(main_path_msgs)} → {len(filtered_msgs)} 条 | "
  888. f"Token: {token_count:,} → ~{filtered_tokens:,}"
  889. )
  890. logger.info(
  891. "Level 1 压缩: %d -> %d 条消息 (tokens ~%d, 阈值 %d)",
  892. len(main_path_msgs), len(filtered_msgs), token_count, max_tokens,
  893. )
  894. history = [msg.to_llm_dict() for msg in filtered_msgs]
  895. else:
  896. print(
  897. f"[Level 1 压缩] 无可过滤消息 ({len(main_path_msgs)} 条全部保留, "
  898. f"completed/abandoned goals={sum(1 for g in goal_tree.goals if g.status in ('completed', 'abandoned'))})"
  899. )
  900. logger.info(
  901. "Level 1 压缩: 无可过滤消息 (%d 条全部保留, completed/abandoned goals=%d)",
  902. len(main_path_msgs),
  903. sum(1 for g in goal_tree.goals
  904. if g.status in ("completed", "abandoned")),
  905. )
  906. elif needs_compression:
  907. print("[压缩评估] ⚠️ 无法执行 Level 1 压缩(缺少 store 或 goal_tree)")
  908. logger.warning(
  909. "消息数 (%d) 或 token 数 (%d) 超过阈值 (max_messages=%d, max_tokens=%d),但无法执行 Level 1 压缩(缺少 store 或 goal_tree)",
  910. msg_count, token_count, compression_config.max_messages, max_tokens,
  911. )
  912. # Level 2 压缩:LLM 总结(Level 1 后仍超阈值时触发)
  913. token_count_after = estimate_tokens(history)
  914. msg_count_after = len(history)
  915. needs_level2_by_tokens = token_count_after > max_tokens
  916. needs_level2_by_count = (
  917. compression_config.max_messages > 0 and
  918. msg_count_after > compression_config.max_messages
  919. )
  920. needs_level2 = needs_level2_by_tokens or needs_level2_by_count
  921. if needs_level2:
  922. progress_pct_after = (token_count_after / max_tokens * 100) if max_tokens > 0 else 0
  923. reason = []
  924. if needs_level2_by_count:
  925. reason.append(f"消息数 {msg_count_after} > {compression_config.max_messages}")
  926. if needs_level2_by_tokens:
  927. reason.append(f"Token {token_count_after:,} > {max_tokens:,} ({progress_pct_after:.1f}%)")
  928. print(
  929. f"[Level 2 压缩] Level 1 后仍超阈值: {' | '.join(reason)} "
  930. f"→ 触发 LLM 总结"
  931. )
  932. logger.info(
  933. "Level 1 后仍超阈值 (消息数=%d/%d, token=%d/%d),触发 Level 2 压缩",
  934. msg_count_after, compression_config.max_messages, token_count_after, max_tokens,
  935. )
  936. history, head_seq, sequence = await self._compress_history(
  937. trace_id, history, goal_tree, config, sequence, head_seq,
  938. )
  939. final_tokens = estimate_tokens(history)
  940. print(f"[Level 2 压缩] 完成: Token {token_count_after:,} → {final_tokens:,}")
  941. elif needs_compression:
  942. # Level 1 压缩成功,未触发 Level 2
  943. print(f"[压缩评估] ✅ Level 1 压缩后达标: 消息数 {msg_count_after} | Token {token_count_after:,} / {max_tokens:,}")
  944. print() # 空行分隔
  945. # 构建 LLM messages(注入上下文)
  946. llm_messages = list(history)
  947. # 收集需要持久化的消息
  948. user_messages_to_persist = [] # 研究流程引导和经验检索改为 user 消息
  949. system_messages_to_persist = [] # 上下文注入保持为 system 消息
  950. # 研究流程引导(仅在启用且处于研究阶段时)- 改为 user 消息
  951. research_state = self._get_research_state(trace_id)
  952. if research_state and research_state["stage"] != "execution":
  953. research_guide = self._build_research_guide(research_state)
  954. if research_guide:
  955. user_msg = {"role": "user", "content": research_guide}
  956. llm_messages.append(user_msg)
  957. user_messages_to_persist.append(("研究流程引导", user_msg))
  958. # 先对历史消息应用 Prompt Caching(在注入动态内容之前)
  959. # 这样可以确保历史消息的缓存点固定,不受动态注入影响
  960. llm_messages = self._add_cache_control(
  961. llm_messages,
  962. config.model,
  963. config.enable_prompt_caching
  964. )
  965. # 然后追加动态注入的内容(不影响已缓存的历史消息)
  966. # 周期性注入 GoalTree + Collaborators
  967. if iteration % CONTEXT_INJECTION_INTERVAL == 0:
  968. context_injection = self._build_context_injection(trace, goal_tree)
  969. if context_injection:
  970. system_msg = {"role": "system", "content": context_injection}
  971. llm_messages.append(system_msg)
  972. system_messages_to_persist.append(("上下文注入", system_msg))
  973. # 经验检索:goal 切换时重新检索,注入为 system message
  974. current_goal_id = goal_tree.current_id if goal_tree else None
  975. if current_goal_id and current_goal_id != _last_goal_id:
  976. _last_goal_id = current_goal_id
  977. current_goal = goal_tree.find(current_goal_id)
  978. if current_goal:
  979. try:
  980. relevant_exps = await _get_structured_knowledge(
  981. query_text=current_goal.description,
  982. top_k=3,
  983. context={"runner": self},
  984. tags_filter=["strategy"] # 只检索经验(strategy 标签)
  985. )
  986. if relevant_exps:
  987. self.used_ex_ids = [exp['id'] for exp in relevant_exps]
  988. parts = [f"[{exp['id']}] {exp['content']}" for exp in relevant_exps]
  989. _cached_exp_text = "## 参考历史经验\n" + "\n\n".join(parts)
  990. logger.info(
  991. "经验检索: goal='%s', 命中 %d 条 %s",
  992. current_goal.description[:40],
  993. len(relevant_exps),
  994. self.used_ex_ids,
  995. )
  996. else:
  997. _cached_exp_text = ""
  998. logger.info(
  999. "经验检索: goal='%s', 未找到相关经验",
  1000. current_goal.description[:40],
  1001. )
  1002. except Exception as e:
  1003. logger.warning("经验检索失败: %s", e)
  1004. _cached_exp_text = ""
  1005. # 如果处于 experience_search 阶段,自动转换到 research_decision 阶段
  1006. research_state = self._get_research_state(trace_id)
  1007. if research_state and research_state["stage"] == "experience_search":
  1008. self._update_research_stage(
  1009. trace_id,
  1010. "research_decision",
  1011. experience_found=len(relevant_exps) > 0 if relevant_exps else False,
  1012. experience_results=relevant_exps if relevant_exps else []
  1013. )
  1014. logger.info(f"[Research Flow] 经验检索完成(自动触发),找到 {len(relevant_exps) if relevant_exps else 0} 条经验,进入调研决策阶段")
  1015. # 经验注入:goal切换时注入相关历史经验 - 改为 user 消息
  1016. # 或者在 research_decision 阶段注入调研决策引导
  1017. if _cached_exp_text or (research_state and research_state["stage"] == "research_decision"):
  1018. exp_content = _cached_exp_text if _cached_exp_text else ""
  1019. # 如果处于 research_decision 阶段,追加引导消息
  1020. if research_state and research_state["stage"] == "research_decision":
  1021. if exp_content:
  1022. exp_content += "\n\n"
  1023. exp_content += self._build_research_decision_guide(research_state)
  1024. if exp_content: # 确保有内容才注入
  1025. user_msg = {"role": "user", "content": exp_content}
  1026. llm_messages.append(user_msg)
  1027. user_messages_to_persist.append(("经验检索", user_msg))
  1028. # 持久化 user 消息到 trace 和 history
  1029. for label, usr_msg in user_messages_to_persist:
  1030. # 添加到 history(这样会被包含在后续的对话中)
  1031. history.append(usr_msg)
  1032. # 保存到 trace store
  1033. if self.trace_store:
  1034. # 在 content 前添加标签,这样会自动出现在 description 中
  1035. labeled_content = f"[{label}]\n{usr_msg['content']}"
  1036. user_message = Message.create(
  1037. trace_id=trace_id,
  1038. role="user",
  1039. sequence=sequence,
  1040. goal_id=current_goal_id,
  1041. parent_sequence=head_seq if head_seq > 0 else None,
  1042. content=labeled_content,
  1043. )
  1044. await self.trace_store.add_message(user_message)
  1045. yield user_message
  1046. head_seq = sequence
  1047. sequence += 1
  1048. # 持久化 system 消息到 trace 和 history
  1049. for label, sys_msg in system_messages_to_persist:
  1050. # 添加到 history(这样会被包含在后续的对话中)
  1051. history.append(sys_msg)
  1052. # 保存到 trace store
  1053. if self.trace_store:
  1054. # 在 content 前添加标签,这样会自动出现在 description 中
  1055. labeled_content = f"[{label}]\n{sys_msg['content']}"
  1056. system_message = Message.create(
  1057. trace_id=trace_id,
  1058. role="system",
  1059. sequence=sequence,
  1060. goal_id=current_goal_id,
  1061. parent_sequence=head_seq if head_seq > 0 else None,
  1062. content=labeled_content,
  1063. )
  1064. await self.trace_store.add_message(system_message)
  1065. yield system_message
  1066. head_seq = sequence
  1067. sequence += 1
  1068. # 调用 LLM
  1069. result = await self.llm_call(
  1070. messages=llm_messages,
  1071. model=config.model,
  1072. tools=tool_schemas,
  1073. temperature=config.temperature,
  1074. **config.extra_llm_params,
  1075. )
  1076. response_content = result.get("content", "")
  1077. tool_calls = result.get("tool_calls")
  1078. finish_reason = result.get("finish_reason")
  1079. prompt_tokens = result.get("prompt_tokens", 0)
  1080. completion_tokens = result.get("completion_tokens", 0)
  1081. step_cost = result.get("cost", 0)
  1082. cache_creation_tokens = result.get("cache_creation_tokens")
  1083. cache_read_tokens = result.get("cache_read_tokens")
  1084. # 研究流程:处理 research_decision 阶段的转换
  1085. research_state = self._get_research_state(trace_id)
  1086. research_decision_handled = False
  1087. if research_state and research_state["stage"] == "research_decision":
  1088. # 检查是否调用了 agent 工具进行调研
  1089. if tool_calls:
  1090. has_agent_call = any(
  1091. tc.get("function", {}).get("name") == "agent"
  1092. for tc in tool_calls
  1093. )
  1094. if has_agent_call:
  1095. # LLM 决定使用子 agent 进行调研
  1096. self._update_research_stage(trace_id, "research", need_research=True)
  1097. logger.info(f"[Research Flow] LLM 决定使用子 agent 进行调研,进入调研阶段")
  1098. research_decision_handled = True
  1099. # 继续执行 agent 工具调用
  1100. else:
  1101. # 检查是否调用了 goal 工具(直接进入计划)
  1102. has_goal_call = any(
  1103. tc.get("function", {}).get("name") == "goal"
  1104. for tc in tool_calls
  1105. )
  1106. if has_goal_call:
  1107. self._update_research_stage(trace_id, "planning", need_research=False)
  1108. logger.info(f"[Research Flow] LLM 决定无需调研,直接进入计划阶段")
  1109. research_decision_handled = True
  1110. else:
  1111. # 根据 assistant 的文本回复判断
  1112. response_lower = response_content.lower()
  1113. if "无需调研" in response_content or "不需要调研" in response_content or "信息充足" in response_content:
  1114. self._update_research_stage(trace_id, "planning", need_research=False)
  1115. logger.info(f"[Research Flow] LLM 决定无需调研,直接进入计划阶段")
  1116. research_decision_handled = True
  1117. # 按需自动创建 root goal
  1118. if goal_tree and not goal_tree.goals and tool_calls:
  1119. has_goal_call = any(
  1120. tc.get("function", {}).get("name") == "goal"
  1121. for tc in tool_calls
  1122. )
  1123. if not has_goal_call:
  1124. mission = goal_tree.mission
  1125. root_desc = mission[:200] if len(mission) > 200 else mission
  1126. goal_tree.add_goals(
  1127. descriptions=[root_desc],
  1128. reasons=["系统自动创建:Agent 未显式创建目标"],
  1129. parent_id=None
  1130. )
  1131. goal_tree.focus(goal_tree.goals[0].id)
  1132. if self.trace_store:
  1133. await self.trace_store.add_goal(trace_id, goal_tree.goals[0])
  1134. await self.trace_store.update_goal_tree(trace_id, goal_tree)
  1135. logger.info(f"自动创建 root goal: {goal_tree.goals[0].id}")
  1136. # 获取当前 goal_id
  1137. current_goal_id = goal_tree.current_id if (goal_tree and goal_tree.current_id) else None
  1138. # 记录 assistant Message(parent_sequence 指向当前 head)
  1139. assistant_msg = Message.create(
  1140. trace_id=trace_id,
  1141. role="assistant",
  1142. sequence=sequence,
  1143. goal_id=current_goal_id,
  1144. parent_sequence=head_seq if head_seq > 0 else None,
  1145. content={"text": response_content, "tool_calls": tool_calls},
  1146. prompt_tokens=prompt_tokens,
  1147. completion_tokens=completion_tokens,
  1148. cache_creation_tokens=cache_creation_tokens,
  1149. cache_read_tokens=cache_read_tokens,
  1150. finish_reason=finish_reason,
  1151. cost=step_cost,
  1152. )
  1153. if self.trace_store:
  1154. await self.trace_store.add_message(assistant_msg)
  1155. yield assistant_msg
  1156. head_seq = sequence
  1157. sequence += 1
  1158. # 处理工具调用
  1159. # 截断兜底:finish_reason == "length" 说明响应被 max_tokens 截断,
  1160. # tool call 参数很可能不完整,不应执行,改为提示模型分批操作
  1161. if tool_calls and finish_reason == "length":
  1162. logger.warning(
  1163. "[Runner] 响应被 max_tokens 截断,跳过 %d 个不完整的 tool calls",
  1164. len(tool_calls),
  1165. )
  1166. truncation_hint = (
  1167. "你的响应因为 max_tokens 限制被截断,tool call 参数不完整,未执行。"
  1168. "请将大内容拆分为多次小的工具调用(例如用 write_file 的 append 模式分批写入)。"
  1169. )
  1170. history.append({
  1171. "role": "assistant",
  1172. "content": response_content,
  1173. "tool_calls": tool_calls,
  1174. })
  1175. # 为每个被截断的 tool call 返回错误结果
  1176. for tc in tool_calls:
  1177. history.append({
  1178. "role": "tool",
  1179. "tool_call_id": tc["id"],
  1180. "content": truncation_hint,
  1181. })
  1182. continue
  1183. if tool_calls and config.auto_execute_tools:
  1184. history.append({
  1185. "role": "assistant",
  1186. "content": response_content,
  1187. "tool_calls": tool_calls,
  1188. })
  1189. for tc in tool_calls:
  1190. current_goal_id = goal_tree.current_id if (goal_tree and goal_tree.current_id) else None
  1191. tool_name = tc["function"]["name"]
  1192. tool_args = tc["function"]["arguments"]
  1193. if isinstance(tool_args, str):
  1194. tool_args = json.loads(tool_args) if tool_args.strip() else {}
  1195. elif tool_args is None:
  1196. tool_args = {}
  1197. tool_result = await self.tools.execute(
  1198. tool_name,
  1199. tool_args,
  1200. uid=config.uid or "",
  1201. context={
  1202. "store": self.trace_store,
  1203. "trace_id": trace_id,
  1204. "goal_id": current_goal_id,
  1205. "runner": self,
  1206. "goal_tree": goal_tree,
  1207. }
  1208. )
  1209. # --- 支持多模态工具反馈 ---
  1210. # execute() 返回 dict{"text", "images", "metadata"} 或 str
  1211. if isinstance(tool_result, dict):
  1212. tool_result_text = tool_result.get("text", str(tool_result))
  1213. # 处理图片
  1214. if tool_result.get("images"):
  1215. # 构建多模态消息格式
  1216. tool_content_for_llm = [{"type": "text", "text": tool_result_text}]
  1217. for img in tool_result["images"]:
  1218. if img.get("type") == "base64" and img.get("data"):
  1219. media_type = img.get("media_type", "image/png")
  1220. tool_content_for_llm.append({
  1221. "type": "image_url",
  1222. "image_url": {
  1223. "url": f"data:{media_type};base64,{img['data']}"
  1224. }
  1225. })
  1226. img_count = len(tool_content_for_llm) - 1 # 减去 text 块
  1227. print(f"[Runner] 多模态工具反馈: tool={tool_name}, images={img_count}, text_len={len(tool_result_text)}")
  1228. else:
  1229. # 无图片,只有文本
  1230. tool_content_for_llm = tool_result_text
  1231. else:
  1232. tool_result_text = str(tool_result)
  1233. tool_content_for_llm = tool_result_text
  1234. tool_msg = Message.create(
  1235. trace_id=trace_id,
  1236. role="tool",
  1237. sequence=sequence,
  1238. goal_id=current_goal_id,
  1239. parent_sequence=head_seq,
  1240. tool_call_id=tc["id"],
  1241. # 存储完整内容:有图片时保留 list(含 image_url),纯文本时存字符串
  1242. content={"tool_name": tool_name, "result": tool_content_for_llm},
  1243. )
  1244. if self.trace_store:
  1245. await self.trace_store.add_message(tool_msg)
  1246. # 截图单独存为同名 PNG 文件
  1247. if isinstance(tool_result, dict) and tool_result.get("images"):
  1248. import base64 as b64mod
  1249. for img in tool_result["images"]:
  1250. if img.get("data"):
  1251. png_path = self.trace_store._get_messages_dir(trace_id) / f"{tool_msg.message_id}.png"
  1252. png_path.write_bytes(b64mod.b64decode(img["data"]))
  1253. print(f"[Runner] 截图已保存: {png_path.name}")
  1254. break # 只存第一张
  1255. yield tool_msg
  1256. head_seq = sequence
  1257. sequence += 1
  1258. history.append({
  1259. "role": "tool",
  1260. "tool_call_id": tc["id"],
  1261. "name": tool_name,
  1262. "content": tool_content_for_llm, # 这里传入 list 即可触发模型的视觉能力
  1263. })
  1264. # ------------------------------------------
  1265. # 研究流程状态转换
  1266. await self._handle_research_flow_transition(
  1267. trace_id, tool_name, tool_result, goal_tree
  1268. )
  1269. continue # 继续循环
  1270. # 研究流程决策阶段:即使没有工具调用也要继续
  1271. if research_decision_handled:
  1272. logger.info(f"[Research Flow] 研究决策完成,继续下一轮循环")
  1273. continue
  1274. # 无工具调用,任务完成
  1275. break
  1276. # 更新 head_sequence 并完成 Trace
  1277. if self.trace_store:
  1278. await self.trace_store.update_trace(
  1279. trace_id,
  1280. status="completed",
  1281. head_sequence=head_seq,
  1282. completed_at=datetime.now(),
  1283. )
  1284. trace_obj = await self.trace_store.get_trace(trace_id)
  1285. if trace_obj:
  1286. yield trace_obj
  1287. # ===== Level 2: LLM 压缩 =====
  1288. async def _compress_history(
  1289. self,
  1290. trace_id: str,
  1291. history: List[Dict],
  1292. goal_tree: Optional[GoalTree],
  1293. config: RunConfig,
  1294. sequence: int,
  1295. head_seq: int,
  1296. ) -> Tuple[List[Dict], int, int]:
  1297. """
  1298. Level 2 压缩:LLM 总结
  1299. Step 1: 经验提取(reflect)— 纯内存 LLM 调用 + 文件追加,不影响 trace
  1300. Step 2: 压缩总结 — LLM 生成 summary
  1301. Step 3: 存储 summary 为新消息,parent_sequence 跳到 system msg
  1302. Step 4: 重建 history
  1303. Returns:
  1304. (new_history, new_head_seq, next_sequence)
  1305. """
  1306. logger.info("Level 2 压缩开始: trace=%s, 当前 history 长度=%d", trace_id, len(history))
  1307. # 找到 system message 的 sequence(主路径第一条消息)
  1308. system_msg_seq = None
  1309. system_msg_dict = None
  1310. if self.trace_store:
  1311. trace_obj = await self.trace_store.get_trace(trace_id)
  1312. if trace_obj and trace_obj.head_sequence > 0:
  1313. main_path = await self.trace_store.get_main_path_messages(
  1314. trace_id, trace_obj.head_sequence
  1315. )
  1316. for msg in main_path:
  1317. if msg.role == "system":
  1318. system_msg_seq = msg.sequence
  1319. system_msg_dict = msg.to_llm_dict()
  1320. break
  1321. # Fallback: 从 history 中找 system message
  1322. if system_msg_dict is None:
  1323. for msg_dict in history:
  1324. if msg_dict.get("role") == "system":
  1325. system_msg_dict = msg_dict
  1326. break
  1327. if system_msg_dict is None:
  1328. logger.warning("Level 2 压缩跳过:未找到 system message")
  1329. return history, head_seq, sequence
  1330. # --- Step 1: 经验提取(reflect)---
  1331. try:
  1332. # 1. 构造 Reflect Prompt(确保包含格式要求)
  1333. # 建议在 build_reflect_prompt() 里加入:
  1334. # "请使用格式:- [intent: 意图, state: 状态描述] 具体的经验内容"
  1335. reflect_prompt = build_reflect_prompt()
  1336. reflect_messages = list(history) + [{"role": "user", "content": reflect_prompt}]
  1337. # 应用 Prompt Caching
  1338. reflect_messages = self._add_cache_control(
  1339. reflect_messages,
  1340. config.model,
  1341. config.enable_prompt_caching
  1342. )
  1343. reflect_result = await self.llm_call(
  1344. messages=reflect_messages,
  1345. model=config.model,
  1346. tools=[],
  1347. temperature=0.2, # 略微保持一点发散性
  1348. **config.extra_llm_params,
  1349. )
  1350. reflection_text = reflect_result.get("content", "").strip()
  1351. if reflection_text:
  1352. import re as _re2
  1353. import uuid as _uuid2
  1354. pattern = r"-\s*\[(?P<tags>.*?)\]\s*(?P<content>.*)"
  1355. matches = list(_re2.finditer(pattern, reflection_text))
  1356. structured_entries = []
  1357. for match in matches:
  1358. tags_str = match.group("tags")
  1359. content = match.group("content")
  1360. intent_match = _re2.search(r"intent:\s*(.*?)(?:,|$)", tags_str, _re2.IGNORECASE)
  1361. state_match = _re2.search(r"state:\s*(.*?)(?:,|$)", tags_str, _re2.IGNORECASE)
  1362. intents = [i.strip() for i in intent_match.group(1).split(",")] if intent_match and intent_match.group(1) else []
  1363. states = [s.strip() for s in state_match.group(1).split(",")] if state_match and state_match.group(1) else []
  1364. ex_id = f"ex_{datetime.now().strftime('%m%d%H%M')}_{_uuid2.uuid4().hex[:4]}"
  1365. entry = f"""---
  1366. id: {ex_id}
  1367. trace_id: {trace_id}
  1368. tags: {{intent: {intents}, state: {states}}}
  1369. metrics: {{helpful: 1, harmful: 0}}
  1370. created_at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
  1371. ---
  1372. - {content}
  1373. - 经验ID: [{ex_id}]"""
  1374. structured_entries.append(entry)
  1375. if structured_entries:
  1376. os.makedirs(os.path.dirname(self.experiences_path), exist_ok=True)
  1377. with open(self.experiences_path, "a", encoding="utf-8") as f:
  1378. f.write("\n\n" + "\n\n".join(structured_entries))
  1379. logger.info(f"已提取并保存 {len(structured_entries)} 条结构化经验")
  1380. else:
  1381. logger.warning("未能解析出符合格式的经验条目,请检查 REFLECT_PROMPT。")
  1382. logger.debug(f"LLM Raw Output:\n{reflection_text}")
  1383. else:
  1384. logger.warning("LLM 未生成反思内容")
  1385. except Exception as e:
  1386. logger.error(f"Level 2 经验提取失败: {e}")
  1387. # --- Step 2: 压缩总结 + 经验评估 ---
  1388. compress_prompt = build_compression_prompt(goal_tree, used_ex_ids=self.used_ex_ids)
  1389. compress_messages = list(history) + [{"role": "user", "content": compress_prompt}]
  1390. # 应用 Prompt Caching
  1391. compress_messages = self._add_cache_control(
  1392. compress_messages,
  1393. config.model,
  1394. config.enable_prompt_caching
  1395. )
  1396. compress_result = await self.llm_call(
  1397. messages=compress_messages,
  1398. model=config.model,
  1399. tools=[],
  1400. temperature=config.temperature,
  1401. **config.extra_llm_params,
  1402. )
  1403. raw_output = compress_result.get("content", "").strip()
  1404. if not raw_output:
  1405. logger.warning("Level 2 压缩跳过:LLM 未返回内容")
  1406. return history, head_seq, sequence
  1407. # 解析 [[EVALUATION]] 块并更新经验
  1408. if self.used_ex_ids:
  1409. try:
  1410. eval_block = ""
  1411. if "[[EVALUATION]]" in raw_output:
  1412. eval_start = raw_output.index("[[EVALUATION]]") + len("[[EVALUATION]]")
  1413. eval_end = raw_output.index("[[SUMMARY]]") if "[[SUMMARY]]" in raw_output else len(raw_output)
  1414. eval_block = raw_output[eval_start:eval_end].strip()
  1415. if eval_block:
  1416. import re as _re
  1417. update_map = {}
  1418. for line in eval_block.splitlines():
  1419. m = _re.search(r"ID:\s*(ex_\S+)\s*\|\s*Result:\s*(\w+)", line)
  1420. if m:
  1421. ex_id, result = m.group(1), m.group(2).lower()
  1422. if result in ("helpful", "harmful"):
  1423. update_map[ex_id] = {"action": result, "feedback": ""}
  1424. elif result == "mixed":
  1425. update_map[ex_id] = {"action": "helpful", "feedback": ""}
  1426. if update_map:
  1427. count = await _batch_update_knowledge(update_map, context={"runner": self})
  1428. logger.info("经验评估完成,更新了 %s 条经验", count)
  1429. except Exception as e:
  1430. logger.warning("经验评估解析失败(不影响压缩): %s", e)
  1431. # 提取 [[SUMMARY]] 块
  1432. summary_text = raw_output
  1433. if "[[SUMMARY]]" in raw_output:
  1434. summary_text = raw_output[raw_output.index("[[SUMMARY]]") + len("[[SUMMARY]]"):].strip()
  1435. # 压缩完成后清空 used_ex_ids
  1436. self.used_ex_ids = []
  1437. if not summary_text:
  1438. logger.warning("Level 2 压缩跳过:LLM 未返回 summary")
  1439. return history, head_seq, sequence
  1440. # --- Step 3: 存储 summary 消息 ---
  1441. summary_with_header = (
  1442. f"## 对话历史摘要(自动压缩)\n\n{summary_text}\n\n"
  1443. "---\n请基于以上摘要和当前 GoalTree 继续执行任务。"
  1444. )
  1445. summary_msg = Message.create(
  1446. trace_id=trace_id,
  1447. role="user",
  1448. sequence=sequence,
  1449. goal_id=None,
  1450. parent_sequence=system_msg_seq, # 跳到 system msg,跳过所有中间消息
  1451. content=summary_with_header,
  1452. )
  1453. if self.trace_store:
  1454. await self.trace_store.add_message(summary_msg)
  1455. new_head_seq = sequence
  1456. sequence += 1
  1457. # --- Step 4: 重建 history ---
  1458. new_history = [system_msg_dict, summary_msg.to_llm_dict()]
  1459. # 更新 trace head_sequence
  1460. if self.trace_store:
  1461. await self.trace_store.update_trace(
  1462. trace_id,
  1463. head_sequence=new_head_seq,
  1464. )
  1465. logger.info(
  1466. "Level 2 压缩完成: 旧 history %d 条 → 新 history %d 条, summary 长度=%d",
  1467. len(history), len(new_history), len(summary_text),
  1468. )
  1469. return new_history, new_head_seq, sequence
  1470. # ===== 回溯(Rewind)=====
  1471. async def _rewind(
  1472. self,
  1473. trace_id: str,
  1474. after_sequence: int,
  1475. goal_tree: Optional[GoalTree],
  1476. ) -> int:
  1477. """
  1478. 执行回溯:快照 GoalTree,重建干净树,设置 head_sequence
  1479. 新消息的 parent_sequence 将指向 rewind 点,旧消息通过树结构自然脱离主路径。
  1480. Returns:
  1481. 下一个可用的 sequence 号
  1482. """
  1483. if not self.trace_store:
  1484. raise ValueError("trace_store required for rewind")
  1485. # 1. 加载所有 messages(用于 safe cutoff 和 max sequence)
  1486. all_messages = await self.trace_store.get_trace_messages(trace_id)
  1487. if not all_messages:
  1488. return 1
  1489. # 2. 找到安全截断点(确保不截断在 tool_call 和 tool response 之间)
  1490. cutoff = self._find_safe_cutoff(all_messages, after_sequence)
  1491. # 3. 快照并重建 GoalTree
  1492. if goal_tree:
  1493. # 获取截断点消息的 created_at 作为时间界限
  1494. cutoff_msg = None
  1495. for msg in all_messages:
  1496. if msg.sequence == cutoff:
  1497. cutoff_msg = msg
  1498. break
  1499. cutoff_time = cutoff_msg.created_at if cutoff_msg else datetime.now()
  1500. # 快照到 events(含 head_sequence 供前端感知分支切换)
  1501. await self.trace_store.append_event(trace_id, "rewind", {
  1502. "after_sequence": cutoff,
  1503. "head_sequence": cutoff,
  1504. "goal_tree_snapshot": goal_tree.to_dict(),
  1505. })
  1506. # 按时间重建干净的 GoalTree
  1507. new_tree = goal_tree.rebuild_for_rewind(cutoff_time)
  1508. await self.trace_store.update_goal_tree(trace_id, new_tree)
  1509. # 更新内存中的引用
  1510. goal_tree.goals = new_tree.goals
  1511. goal_tree.current_id = new_tree.current_id
  1512. # 4. 更新 head_sequence 到 rewind 点
  1513. await self.trace_store.update_trace(trace_id, head_sequence=cutoff)
  1514. # 5. 返回 next sequence(全局递增,不复用)
  1515. max_seq = max((m.sequence for m in all_messages), default=0)
  1516. return max_seq + 1
  1517. def _find_safe_cutoff(self, messages: List[Message], after_sequence: int) -> int:
  1518. """
  1519. 找到安全的截断点。
  1520. 如果 after_sequence 指向一条带 tool_calls 的 assistant message,
  1521. 则自动扩展到其所有对应的 tool response 之后。
  1522. """
  1523. cutoff = after_sequence
  1524. # 找到 after_sequence 对应的 message
  1525. target_msg = None
  1526. for msg in messages:
  1527. if msg.sequence == after_sequence:
  1528. target_msg = msg
  1529. break
  1530. if not target_msg:
  1531. return cutoff
  1532. # 如果是 assistant 且有 tool_calls,找到所有对应的 tool responses
  1533. if target_msg.role == "assistant":
  1534. content = target_msg.content
  1535. if isinstance(content, dict) and content.get("tool_calls"):
  1536. tool_call_ids = set()
  1537. for tc in content["tool_calls"]:
  1538. if isinstance(tc, dict) and tc.get("id"):
  1539. tool_call_ids.add(tc["id"])
  1540. # 找到这些 tool_call 对应的 tool messages
  1541. for msg in messages:
  1542. if (msg.role == "tool" and msg.tool_call_id
  1543. and msg.tool_call_id in tool_call_ids):
  1544. cutoff = max(cutoff, msg.sequence)
  1545. return cutoff
  1546. async def _heal_orphaned_tool_calls(
  1547. self,
  1548. messages: List[Message],
  1549. trace_id: str,
  1550. goal_tree: Optional[GoalTree],
  1551. sequence: int,
  1552. ) -> tuple:
  1553. """
  1554. 检测并修复消息历史中的 orphaned tool_calls。
  1555. 当 agent 被 stop/crash 中断时,可能有 assistant 的 tool_calls 没有对应的
  1556. tool results(包括多 tool_call 部分完成的情况)。直接发给 LLM 会导致 400。
  1557. 修复策略:为每个缺失的 tool_result 插入合成的"中断通知"消息,而非裁剪。
  1558. - 普通工具:简短中断提示
  1559. - agent/evaluate:包含 sub_trace_id、执行统计、continue_from 指引
  1560. 合成消息持久化到 store,确保幂等(下次续跑不再触发)。
  1561. Returns:
  1562. (healed_messages, next_sequence)
  1563. """
  1564. if not messages:
  1565. return messages, sequence
  1566. # 收集所有 tool_call IDs → (assistant_msg, tool_call_dict)
  1567. tc_map: Dict[str, tuple] = {}
  1568. result_ids: set = set()
  1569. for msg in messages:
  1570. if msg.role == "assistant":
  1571. content = msg.content
  1572. if isinstance(content, dict) and content.get("tool_calls"):
  1573. for tc in content["tool_calls"]:
  1574. tc_id = tc.get("id")
  1575. if tc_id:
  1576. tc_map[tc_id] = (msg, tc)
  1577. elif msg.role == "tool" and msg.tool_call_id:
  1578. result_ids.add(msg.tool_call_id)
  1579. orphaned_ids = [tc_id for tc_id in tc_map if tc_id not in result_ids]
  1580. if not orphaned_ids:
  1581. return messages, sequence
  1582. logger.info(
  1583. "检测到 %d 个 orphaned tool_calls,生成合成中断通知",
  1584. len(orphaned_ids),
  1585. )
  1586. healed = list(messages)
  1587. head_seq = messages[-1].sequence
  1588. for tc_id in orphaned_ids:
  1589. assistant_msg, tc = tc_map[tc_id]
  1590. tool_name = tc.get("function", {}).get("name", "unknown")
  1591. if tool_name in ("agent", "evaluate"):
  1592. result_text = self._build_agent_interrupted_result(
  1593. tc, goal_tree, assistant_msg,
  1594. )
  1595. else:
  1596. result_text = (
  1597. f"⚠️ 工具 {tool_name} 执行被中断(进程异常退出),"
  1598. "未获得执行结果。请根据需要重新调用。"
  1599. )
  1600. synthetic_msg = Message.create(
  1601. trace_id=trace_id,
  1602. role="tool",
  1603. sequence=sequence,
  1604. goal_id=assistant_msg.goal_id,
  1605. parent_sequence=head_seq,
  1606. tool_call_id=tc_id,
  1607. content={"tool_name": tool_name, "result": result_text},
  1608. )
  1609. if self.trace_store:
  1610. await self.trace_store.add_message(synthetic_msg)
  1611. healed.append(synthetic_msg)
  1612. head_seq = sequence
  1613. sequence += 1
  1614. # 更新 trace head/last sequence
  1615. if self.trace_store:
  1616. await self.trace_store.update_trace(
  1617. trace_id,
  1618. head_sequence=head_seq,
  1619. last_sequence=max(head_seq, sequence - 1),
  1620. )
  1621. return healed, sequence
  1622. def _build_agent_interrupted_result(
  1623. self,
  1624. tc: Dict,
  1625. goal_tree: Optional[GoalTree],
  1626. assistant_msg: Message,
  1627. ) -> str:
  1628. """为中断的 agent/evaluate 工具调用构建合成结果(对齐正常返回值格式)"""
  1629. args_str = tc.get("function", {}).get("arguments", "{}")
  1630. try:
  1631. args = json.loads(args_str) if isinstance(args_str, str) else args_str
  1632. except json.JSONDecodeError:
  1633. args = {}
  1634. task = args.get("task", "未知任务")
  1635. if isinstance(task, list):
  1636. task = "; ".join(task)
  1637. tool_name = tc.get("function", {}).get("name", "agent")
  1638. mode = "evaluate" if tool_name == "evaluate" else "delegate"
  1639. # 从 goal_tree 查找 sub_trace 信息
  1640. sub_trace_id = None
  1641. stats = None
  1642. if goal_tree and assistant_msg.goal_id:
  1643. goal = goal_tree.find(assistant_msg.goal_id)
  1644. if goal and goal.sub_trace_ids:
  1645. first = goal.sub_trace_ids[0]
  1646. if isinstance(first, dict):
  1647. sub_trace_id = first.get("trace_id")
  1648. elif isinstance(first, str):
  1649. sub_trace_id = first
  1650. if goal.cumulative_stats:
  1651. s = goal.cumulative_stats
  1652. if s.message_count > 0:
  1653. stats = {
  1654. "message_count": s.message_count,
  1655. "total_tokens": s.total_tokens,
  1656. "total_cost": round(s.total_cost, 4),
  1657. }
  1658. result: Dict[str, Any] = {
  1659. "mode": mode,
  1660. "status": "interrupted",
  1661. "summary": "⚠️ 子Agent执行被中断(进程异常退出)",
  1662. "task": task,
  1663. }
  1664. if sub_trace_id:
  1665. result["sub_trace_id"] = sub_trace_id
  1666. result["hint"] = (
  1667. f'使用 continue_from="{sub_trace_id}" 可继续执行,保留已有进度'
  1668. )
  1669. if stats:
  1670. result["stats"] = stats
  1671. return json.dumps(result, ensure_ascii=False, indent=2)
  1672. # ===== 上下文注入 =====
  1673. def _build_context_injection(
  1674. self,
  1675. trace: Trace,
  1676. goal_tree: Optional[GoalTree],
  1677. ) -> str:
  1678. """构建周期性注入的上下文(GoalTree + Active Collaborators + Focus 提醒)"""
  1679. parts = []
  1680. # GoalTree
  1681. if goal_tree and goal_tree.goals:
  1682. parts.append(f"## Current Plan\n\n{goal_tree.to_prompt()}")
  1683. # 检测 focus 在有子节点的父目标上:提醒模型 focus 到具体子目标
  1684. if goal_tree.current_id:
  1685. children = goal_tree.get_children(goal_tree.current_id)
  1686. pending_children = [c for c in children if c.status in ("pending", "in_progress")]
  1687. if pending_children:
  1688. child_ids = ", ".join(
  1689. goal_tree._generate_display_id(c) for c in pending_children[:3]
  1690. )
  1691. parts.append(
  1692. f"**提醒**:当前焦点在父目标上,建议用 `goal(focus=\"...\")` "
  1693. f"切换到具体子目标(如 {child_ids})再执行。"
  1694. )
  1695. # Active Collaborators
  1696. collaborators = trace.context.get("collaborators", [])
  1697. if collaborators:
  1698. lines = ["## Active Collaborators"]
  1699. for c in collaborators:
  1700. status_str = c.get("status", "unknown")
  1701. ctype = c.get("type", "agent")
  1702. summary = c.get("summary", "")
  1703. name = c.get("name", "unnamed")
  1704. lines.append(f"- {name} [{ctype}, {status_str}]: {summary}")
  1705. parts.append("\n".join(lines))
  1706. return "\n\n".join(parts)
  1707. # ===== 辅助方法 =====
  1708. def _add_cache_control(
  1709. self,
  1710. messages: List[Dict],
  1711. model: str,
  1712. enable: bool
  1713. ) -> List[Dict]:
  1714. """
  1715. 为支持的模型添加 Prompt Caching 标记
  1716. 策略:固定位置 + 延迟查找
  1717. 1. system message 添加缓存(如果足够长)
  1718. 2. 固定位置缓存点(20, 40, 60, 80),确保每个缓存点间隔 >= 1024 tokens
  1719. 3. 最多使用 4 个缓存点(含 system)
  1720. Args:
  1721. messages: 原始消息列表
  1722. model: 模型名称
  1723. enable: 是否启用缓存
  1724. Returns:
  1725. 添加了 cache_control 的消息列表(深拷贝)
  1726. """
  1727. if not enable:
  1728. return messages
  1729. # 只对 Claude 模型启用
  1730. if "claude" not in model.lower():
  1731. return messages
  1732. # 深拷贝避免修改原始数据
  1733. import copy
  1734. messages = copy.deepcopy(messages)
  1735. # 策略 1: 为 system message 添加缓存
  1736. system_cached = False
  1737. for msg in messages:
  1738. if msg.get("role") == "system":
  1739. content = msg.get("content", "")
  1740. if isinstance(content, str) and len(content) > 1000:
  1741. msg["content"] = [{
  1742. "type": "text",
  1743. "text": content,
  1744. "cache_control": {"type": "ephemeral"}
  1745. }]
  1746. system_cached = True
  1747. logger.debug(f"[Cache] 为 system message 添加缓存标记 (len={len(content)})")
  1748. break
  1749. # 策略 2: 固定位置缓存点
  1750. CACHE_INTERVAL = 20
  1751. MAX_POINTS = 3 if system_cached else 4
  1752. MIN_TOKENS = 1024
  1753. AVG_TOKENS_PER_MSG = 70
  1754. total_msgs = len(messages)
  1755. if total_msgs == 0:
  1756. return messages
  1757. cache_positions = []
  1758. last_cache_pos = 0
  1759. for i in range(1, MAX_POINTS + 1):
  1760. target_pos = i * CACHE_INTERVAL - 1 # 19, 39, 59, 79
  1761. if target_pos >= total_msgs:
  1762. break
  1763. # 从目标位置开始查找合适的 user/assistant 消息
  1764. for j in range(target_pos, total_msgs):
  1765. msg = messages[j]
  1766. if msg.get("role") not in ("user", "assistant"):
  1767. continue
  1768. content = msg.get("content", "")
  1769. if not content:
  1770. continue
  1771. # 检查 content 是否非空
  1772. is_valid = False
  1773. if isinstance(content, str):
  1774. is_valid = len(content) > 0
  1775. elif isinstance(content, list):
  1776. is_valid = any(
  1777. isinstance(block, dict) and
  1778. block.get("type") == "text" and
  1779. len(block.get("text", "")) > 0
  1780. for block in content
  1781. )
  1782. if not is_valid:
  1783. continue
  1784. # 检查 token 距离
  1785. msg_count = j - last_cache_pos
  1786. estimated_tokens = msg_count * AVG_TOKENS_PER_MSG
  1787. if estimated_tokens >= MIN_TOKENS:
  1788. cache_positions.append(j)
  1789. last_cache_pos = j
  1790. logger.debug(f"[Cache] 在位置 {j} 添加缓存点 (估算 {estimated_tokens} tokens)")
  1791. break
  1792. # 应用缓存标记
  1793. for idx in cache_positions:
  1794. msg = messages[idx]
  1795. content = msg.get("content", "")
  1796. if isinstance(content, str):
  1797. msg["content"] = [{
  1798. "type": "text",
  1799. "text": content,
  1800. "cache_control": {"type": "ephemeral"}
  1801. }]
  1802. logger.debug(f"[Cache] 为 message[{idx}] ({msg.get('role')}) 添加缓存标记")
  1803. elif isinstance(content, list):
  1804. # 在最后一个 text block 添加 cache_control
  1805. for block in reversed(content):
  1806. if isinstance(block, dict) and block.get("type") == "text":
  1807. block["cache_control"] = {"type": "ephemeral"}
  1808. logger.debug(f"[Cache] 为 message[{idx}] ({msg.get('role')}) 添加缓存标记")
  1809. break
  1810. logger.debug(
  1811. f"[Cache] 总消息: {total_msgs}, "
  1812. f"缓存点: {len(cache_positions)} at {cache_positions}"
  1813. )
  1814. return messages
  1815. def _get_tool_schemas(self, tools: Optional[List[str]]) -> List[Dict]:
  1816. """
  1817. 获取工具 Schema
  1818. - tools=None: 使用 registry 中全部已注册工具(含内置 + 外部注册的)
  1819. - tools=["a", "b"]: 在 BUILTIN_TOOLS 基础上追加指定工具
  1820. """
  1821. if tools is None:
  1822. # 全部已注册工具
  1823. tool_names = self.tools.get_tool_names()
  1824. else:
  1825. # BUILTIN_TOOLS + 显式指定的额外工具
  1826. tool_names = BUILTIN_TOOLS.copy()
  1827. for t in tools:
  1828. if t not in tool_names:
  1829. tool_names.append(t)
  1830. return self.tools.get_schemas(tool_names)
  1831. # 默认 system prompt 前缀(当 config.system_prompt 和前端都未提供 system message 时使用)
  1832. DEFAULT_SYSTEM_PREFIX = "你是最顶尖的AI助手,可以拆分并调用工具逐步解决复杂问题。"
  1833. async def _build_system_prompt(self, config: RunConfig, base_prompt: Optional[str] = None) -> Optional[str]:
  1834. """构建 system prompt(注入 skills)
  1835. 优先级:
  1836. 1. config.skills 显式指定 → 按名称过滤
  1837. 2. config.skills 为 None → 查 preset 的默认 skills 列表
  1838. 3. preset 也无 skills(None)→ 加载全部(向后兼容)
  1839. Args:
  1840. base_prompt: 已有 system 内容(来自消息或 config.system_prompt),
  1841. None 时使用 config.system_prompt
  1842. """
  1843. from agent.core.presets import AGENT_PRESETS
  1844. system_prompt = base_prompt if base_prompt is not None else config.system_prompt
  1845. # 确定要加载哪些 skills
  1846. skills_filter: Optional[List[str]] = config.skills
  1847. if skills_filter is None:
  1848. preset = AGENT_PRESETS.get(config.agent_type)
  1849. if preset is not None:
  1850. skills_filter = preset.skills # 可能仍为 None(加载全部)
  1851. # 加载并过滤
  1852. all_skills = load_skills_from_dir(self.skills_dir)
  1853. if skills_filter is not None:
  1854. skills = [s for s in all_skills if s.name in skills_filter]
  1855. else:
  1856. skills = all_skills
  1857. skills_text = self._format_skills(skills) if skills else ""
  1858. if system_prompt:
  1859. if skills_text:
  1860. system_prompt += f"\n\n## Skills\n{skills_text}"
  1861. else:
  1862. system_prompt = self.DEFAULT_SYSTEM_PREFIX
  1863. if skills_text:
  1864. system_prompt += f"\n\n## Skills\n{skills_text}"
  1865. return system_prompt
  1866. async def _generate_task_name(self, messages: List[Dict]) -> str:
  1867. """生成任务名称:优先使用 utility_llm,fallback 到文本截取"""
  1868. # 提取 messages 中的文本内容
  1869. text_parts = []
  1870. for msg in messages:
  1871. content = msg.get("content", "")
  1872. if isinstance(content, str):
  1873. text_parts.append(content)
  1874. elif isinstance(content, list):
  1875. for part in content:
  1876. if isinstance(part, dict) and part.get("type") == "text":
  1877. text_parts.append(part.get("text", ""))
  1878. raw_text = " ".join(text_parts).strip()
  1879. if not raw_text:
  1880. return "未命名任务"
  1881. # 尝试使用 utility_llm 生成标题
  1882. if self.utility_llm_call:
  1883. try:
  1884. result = await self.utility_llm_call(
  1885. messages=[
  1886. {"role": "system", "content": "用中文为以下任务生成一个简短标题(10-30字),只输出标题本身:"},
  1887. {"role": "user", "content": raw_text[:2000]},
  1888. ],
  1889. model="gpt-4o-mini", # 使用便宜模型
  1890. )
  1891. title = result.get("content", "").strip()
  1892. if title and len(title) < 100:
  1893. return title
  1894. except Exception:
  1895. pass
  1896. # Fallback: 截取前 50 字符
  1897. return raw_text[:50] + ("..." if len(raw_text) > 50 else "")
  1898. def _format_skills(self, skills: List[Skill]) -> str:
  1899. if not skills:
  1900. return ""
  1901. return "\n\n".join(s.to_prompt_text() for s in skills)
  1902. def _load_experiences(self) -> str:
  1903. """从文件加载经验(./.cache/experiences.md)"""
  1904. if not self.experiences_path:
  1905. return ""
  1906. try:
  1907. if os.path.exists(self.experiences_path):
  1908. with open(self.experiences_path, "r", encoding="utf-8") as f:
  1909. return f.read().strip()
  1910. except Exception as e:
  1911. logger.warning(f"Failed to load experiences from {self.experiences_path}: {e}")
  1912. return ""