runner.py 59 KB

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