runner.py 52 KB

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