runner.py 57 KB

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