runner.py 67 KB

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