runner.py 89 KB

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