runner.py 91 KB

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