runner.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  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. if after_seq is not None and after_seq < trace_obj.head_sequence:
  400. # 回溯模式
  401. sequence = await self._rewind(config.trace_id, after_seq, goal_tree)
  402. else:
  403. # 续跑模式:从 last_sequence + 1 开始
  404. sequence = trace_obj.last_sequence + 1
  405. # 状态置为 running
  406. await self.trace_store.update_trace(
  407. config.trace_id,
  408. status="running",
  409. completed_at=None,
  410. )
  411. trace_obj.status = "running"
  412. return trace_obj, goal_tree, sequence
  413. # ===== Phase 2: BUILD HISTORY =====
  414. async def _build_history(
  415. self,
  416. trace_id: str,
  417. new_messages: List[Dict],
  418. goal_tree: Optional[GoalTree],
  419. config: RunConfig,
  420. sequence: int,
  421. ) -> Tuple[List[Dict], int, List[Message]]:
  422. """
  423. 构建完整的 LLM 消息历史
  424. 1. 从 head_sequence 沿 parent chain 加载主路径消息(续跑/回溯场景)
  425. 2. 构建 system prompt(新建时注入 skills)
  426. 3. 新建时:在第一条 user message 末尾注入当前经验
  427. 4. 追加 input messages(设置 parent_sequence 链接到当前 head)
  428. Returns:
  429. (history, next_sequence, created_messages, head_sequence)
  430. created_messages: 本次新创建并持久化的 Message 列表,供 run() yield 给调用方
  431. head_sequence: 当前主路径头节点的 sequence
  432. """
  433. history: List[Dict] = []
  434. created_messages: List[Message] = []
  435. head_seq: Optional[int] = None # 当前主路径的头节点 sequence
  436. # 1. 加载已有 messages(通过主路径遍历)
  437. if config.trace_id and self.trace_store:
  438. trace_obj = await self.trace_store.get_trace(trace_id)
  439. if trace_obj and trace_obj.head_sequence > 0:
  440. main_path = await self.trace_store.get_main_path_messages(
  441. trace_id, trace_obj.head_sequence
  442. )
  443. # 修复 orphaned tool_calls(中断导致的 tool_call 无 tool_result)
  444. main_path, sequence = await self._heal_orphaned_tool_calls(
  445. main_path, trace_id, goal_tree, sequence,
  446. )
  447. history = [msg.to_llm_dict() for msg in main_path]
  448. if main_path:
  449. head_seq = main_path[-1].sequence
  450. # 2. 构建 system prompt(如果历史中没有 system message)
  451. has_system = any(m.get("role") == "system" for m in history)
  452. has_system_in_new = any(m.get("role") == "system" for m in new_messages)
  453. if not has_system and not has_system_in_new:
  454. system_prompt = await self._build_system_prompt(config)
  455. if system_prompt:
  456. history = [{"role": "system", "content": system_prompt}] + history
  457. if self.trace_store:
  458. system_msg = Message.create(
  459. trace_id=trace_id, role="system", sequence=sequence,
  460. goal_id=None, content=system_prompt,
  461. parent_sequence=None, # system message 是 root
  462. )
  463. await self.trace_store.add_message(system_msg)
  464. created_messages.append(system_msg)
  465. head_seq = sequence
  466. sequence += 1
  467. # 3. 新建时:在第一条 user message 末尾注入当前经验
  468. if not config.trace_id: # 新建模式
  469. experiences_text = self._load_experiences()
  470. if experiences_text:
  471. for msg in new_messages:
  472. if msg.get("role") == "user" and isinstance(msg.get("content"), str):
  473. msg["content"] += f"\n\n## 参考经验\n\n{experiences_text}"
  474. break
  475. # 4. 追加新 messages(设置 parent_sequence 链接到当前 head)
  476. for msg_dict in new_messages:
  477. history.append(msg_dict)
  478. if self.trace_store:
  479. stored_msg = Message.from_llm_dict(
  480. msg_dict, trace_id=trace_id, sequence=sequence,
  481. goal_id=None, parent_sequence=head_seq,
  482. )
  483. await self.trace_store.add_message(stored_msg)
  484. created_messages.append(stored_msg)
  485. head_seq = sequence
  486. sequence += 1
  487. # 5. 更新 trace 的 head_sequence
  488. if self.trace_store and head_seq is not None:
  489. await self.trace_store.update_trace(trace_id, head_sequence=head_seq)
  490. return history, sequence, created_messages, head_seq or 0
  491. # ===== Phase 3: AGENT LOOP =====
  492. async def _agent_loop(
  493. self,
  494. trace: Trace,
  495. history: List[Dict],
  496. goal_tree: Optional[GoalTree],
  497. config: RunConfig,
  498. sequence: int,
  499. ) -> AsyncIterator[Union[Trace, Message]]:
  500. """ReAct 循环"""
  501. trace_id = trace.trace_id
  502. tool_schemas = self._get_tool_schemas(config.tools)
  503. # 当前主路径头节点的 sequence(用于设置 parent_sequence)
  504. head_seq = trace.head_sequence
  505. # 设置 goal_tree 到 goal 工具
  506. if goal_tree and self.trace_store:
  507. from agent.trace.goal_tool import set_goal_tree
  508. set_goal_tree(goal_tree)
  509. for iteration in range(config.max_iterations):
  510. # 检查取消信号
  511. cancel_event = self._cancel_events.get(trace_id)
  512. if cancel_event and cancel_event.is_set():
  513. logger.info(f"Trace {trace_id} stopped by user")
  514. if self.trace_store:
  515. await self.trace_store.update_trace(
  516. trace_id,
  517. status="stopped",
  518. head_sequence=head_seq,
  519. completed_at=datetime.now(),
  520. )
  521. trace_obj = await self.trace_store.get_trace(trace_id)
  522. if trace_obj:
  523. yield trace_obj
  524. return
  525. # Level 1 压缩:GoalTree 过滤(当消息超过阈值时触发)
  526. compression_config = CompressionConfig()
  527. token_count = estimate_tokens(history)
  528. max_tokens = compression_config.get_max_tokens(config.model)
  529. if token_count > max_tokens and self.trace_store and goal_tree:
  530. # 使用本地 head_seq(store 中的 head_sequence 在 loop 期间未更新,是过时的)
  531. if head_seq > 0:
  532. main_path_msgs = await self.trace_store.get_main_path_messages(
  533. trace_id, head_seq
  534. )
  535. filtered_msgs = filter_by_goal_status(main_path_msgs, goal_tree)
  536. if len(filtered_msgs) < len(main_path_msgs):
  537. logger.info(
  538. "Level 1 压缩: %d -> %d 条消息 (tokens ~%d, 阈值 %d)",
  539. len(main_path_msgs), len(filtered_msgs), token_count, max_tokens,
  540. )
  541. history = [msg.to_llm_dict() for msg in filtered_msgs]
  542. else:
  543. logger.info(
  544. "Level 1 压缩: 无可过滤消息 (%d 条全部保留, completed/abandoned goals=%d)",
  545. len(main_path_msgs),
  546. sum(1 for g in goal_tree.goals
  547. if g.status in ("completed", "abandoned")),
  548. )
  549. elif token_count > max_tokens:
  550. logger.warning(
  551. "消息 token 数 (%d) 超过阈值 (%d),但无法执行 Level 1 压缩(缺少 store 或 goal_tree)",
  552. token_count, max_tokens,
  553. )
  554. # Level 2 压缩:LLM 总结(Level 1 后仍超阈值时触发)
  555. token_count_after = estimate_tokens(history)
  556. if token_count_after > max_tokens:
  557. logger.info(
  558. "Level 1 后 token 仍超阈值 (%d > %d),触发 Level 2 压缩",
  559. token_count_after, max_tokens,
  560. )
  561. history, head_seq, sequence = await self._compress_history(
  562. trace_id, history, goal_tree, config, sequence, head_seq,
  563. )
  564. # 构建 LLM messages(注入上下文)
  565. llm_messages = list(history)
  566. # 周期性注入 GoalTree + Collaborators
  567. if iteration % CONTEXT_INJECTION_INTERVAL == 0:
  568. context_injection = self._build_context_injection(trace, goal_tree)
  569. if context_injection:
  570. llm_messages.append({"role": "system", "content": context_injection})
  571. # 调用 LLM
  572. result = await self.llm_call(
  573. messages=llm_messages,
  574. model=config.model,
  575. tools=tool_schemas,
  576. temperature=config.temperature,
  577. **config.extra_llm_params,
  578. )
  579. response_content = result.get("content", "")
  580. tool_calls = result.get("tool_calls")
  581. finish_reason = result.get("finish_reason")
  582. prompt_tokens = result.get("prompt_tokens", 0)
  583. completion_tokens = result.get("completion_tokens", 0)
  584. step_cost = result.get("cost", 0)
  585. # 按需自动创建 root goal
  586. if goal_tree and not goal_tree.goals and tool_calls:
  587. has_goal_call = any(
  588. tc.get("function", {}).get("name") == "goal"
  589. for tc in tool_calls
  590. )
  591. if not has_goal_call:
  592. mission = goal_tree.mission
  593. root_desc = mission[:200] if len(mission) > 200 else mission
  594. goal_tree.add_goals(
  595. descriptions=[root_desc],
  596. reasons=["系统自动创建:Agent 未显式创建目标"],
  597. parent_id=None
  598. )
  599. goal_tree.focus(goal_tree.goals[0].id)
  600. if self.trace_store:
  601. await self.trace_store.update_goal_tree(trace_id, goal_tree)
  602. await self.trace_store.add_goal(trace_id, goal_tree.goals[0])
  603. logger.info(f"自动创建 root goal: {goal_tree.goals[0].id}")
  604. # 获取当前 goal_id
  605. current_goal_id = goal_tree.current_id if (goal_tree and goal_tree.current_id) else None
  606. # 记录 assistant Message(parent_sequence 指向当前 head)
  607. assistant_msg = Message.create(
  608. trace_id=trace_id,
  609. role="assistant",
  610. sequence=sequence,
  611. goal_id=current_goal_id,
  612. parent_sequence=head_seq if head_seq > 0 else None,
  613. content={"text": response_content, "tool_calls": tool_calls},
  614. prompt_tokens=prompt_tokens,
  615. completion_tokens=completion_tokens,
  616. finish_reason=finish_reason,
  617. cost=step_cost,
  618. )
  619. if self.trace_store:
  620. await self.trace_store.add_message(assistant_msg)
  621. yield assistant_msg
  622. head_seq = sequence
  623. sequence += 1
  624. # 处理工具调用
  625. # 截断兜底:finish_reason == "length" 说明响应被 max_tokens 截断,
  626. # tool call 参数很可能不完整,不应执行,改为提示模型分批操作
  627. if tool_calls and finish_reason == "length":
  628. logger.warning(
  629. "[Runner] 响应被 max_tokens 截断,跳过 %d 个不完整的 tool calls",
  630. len(tool_calls),
  631. )
  632. truncation_hint = (
  633. "你的响应因为 max_tokens 限制被截断,tool call 参数不完整,未执行。"
  634. "请将大内容拆分为多次小的工具调用(例如用 write_file 的 append 模式分批写入)。"
  635. )
  636. history.append({
  637. "role": "assistant",
  638. "content": response_content,
  639. "tool_calls": tool_calls,
  640. })
  641. # 为每个被截断的 tool call 返回错误结果
  642. for tc in tool_calls:
  643. history.append({
  644. "role": "tool",
  645. "tool_call_id": tc["id"],
  646. "content": truncation_hint,
  647. })
  648. continue
  649. if tool_calls and config.auto_execute_tools:
  650. history.append({
  651. "role": "assistant",
  652. "content": response_content,
  653. "tool_calls": tool_calls,
  654. })
  655. for tc in tool_calls:
  656. current_goal_id = goal_tree.current_id if (goal_tree and goal_tree.current_id) else None
  657. tool_name = tc["function"]["name"]
  658. tool_args = tc["function"]["arguments"]
  659. if isinstance(tool_args, str):
  660. tool_args = json.loads(tool_args) if tool_args.strip() else {}
  661. elif tool_args is None:
  662. tool_args = {}
  663. tool_result = await self.tools.execute(
  664. tool_name,
  665. tool_args,
  666. uid=config.uid or "",
  667. context={
  668. "store": self.trace_store,
  669. "trace_id": trace_id,
  670. "goal_id": current_goal_id,
  671. "runner": self,
  672. }
  673. )
  674. # --- 支持多模态工具反馈 ---
  675. # execute() 返回 dict{"text","images"} 或 str
  676. if isinstance(tool_result, dict) and tool_result.get("images"):
  677. tool_result_text = tool_result["text"]
  678. # 构建多模态消息格式
  679. tool_content_for_llm = [{"type": "text", "text": tool_result_text}]
  680. for img in tool_result["images"]:
  681. if img.get("type") == "base64" and img.get("data"):
  682. media_type = img.get("media_type", "image/png")
  683. tool_content_for_llm.append({
  684. "type": "image_url",
  685. "image_url": {
  686. "url": f"data:{media_type};base64,{img['data']}"
  687. }
  688. })
  689. img_count = len(tool_content_for_llm) - 1 # 减去 text 块
  690. print(f"[Runner] 多模态工具反馈: tool={tool_name}, images={img_count}, text_len={len(tool_result_text)}")
  691. else:
  692. tool_result_text = str(tool_result)
  693. tool_content_for_llm = tool_result_text
  694. tool_msg = Message.create(
  695. trace_id=trace_id,
  696. role="tool",
  697. sequence=sequence,
  698. goal_id=current_goal_id,
  699. parent_sequence=head_seq,
  700. tool_call_id=tc["id"],
  701. content={"tool_name": tool_name, "result": tool_result_text},
  702. )
  703. if self.trace_store:
  704. await self.trace_store.add_message(tool_msg)
  705. # 截图单独存为同名 PNG 文件
  706. if isinstance(tool_result, dict) and tool_result.get("images"):
  707. import base64 as b64mod
  708. for img in tool_result["images"]:
  709. if img.get("data"):
  710. png_path = self.trace_store._get_messages_dir(trace_id) / f"{tool_msg.message_id}.png"
  711. png_path.write_bytes(b64mod.b64decode(img["data"]))
  712. print(f"[Runner] 截图已保存: {png_path.name}")
  713. break # 只存第一张
  714. yield tool_msg
  715. head_seq = sequence
  716. sequence += 1
  717. history.append({
  718. "role": "tool",
  719. "tool_call_id": tc["id"],
  720. "name": tool_name,
  721. "content": tool_content_for_llm, # 这里传入 list 即可触发模型的视觉能力
  722. })
  723. # ------------------------------------------
  724. continue # 继续循环
  725. # 无工具调用,任务完成
  726. break
  727. # 更新 head_sequence 并完成 Trace
  728. if self.trace_store:
  729. await self.trace_store.update_trace(
  730. trace_id,
  731. status="completed",
  732. head_sequence=head_seq,
  733. completed_at=datetime.now(),
  734. )
  735. trace_obj = await self.trace_store.get_trace(trace_id)
  736. if trace_obj:
  737. yield trace_obj
  738. # ===== Level 2: LLM 压缩 =====
  739. async def _compress_history(
  740. self,
  741. trace_id: str,
  742. history: List[Dict],
  743. goal_tree: Optional[GoalTree],
  744. config: RunConfig,
  745. sequence: int,
  746. head_seq: int,
  747. ) -> Tuple[List[Dict], int, int]:
  748. """
  749. Level 2 压缩:LLM 总结
  750. Step 1: 经验提取(reflect)— 纯内存 LLM 调用 + 文件追加,不影响 trace
  751. Step 2: 压缩总结 — LLM 生成 summary
  752. Step 3: 存储 summary 为新消息,parent_sequence 跳到 system msg
  753. Step 4: 重建 history
  754. Returns:
  755. (new_history, new_head_seq, next_sequence)
  756. """
  757. logger.info("Level 2 压缩开始: trace=%s, 当前 history 长度=%d", trace_id, len(history))
  758. # 找到 system message 的 sequence(主路径第一条消息)
  759. system_msg_seq = None
  760. system_msg_dict = None
  761. if self.trace_store:
  762. trace_obj = await self.trace_store.get_trace(trace_id)
  763. if trace_obj and trace_obj.head_sequence > 0:
  764. main_path = await self.trace_store.get_main_path_messages(
  765. trace_id, trace_obj.head_sequence
  766. )
  767. for msg in main_path:
  768. if msg.role == "system":
  769. system_msg_seq = msg.sequence
  770. system_msg_dict = msg.to_llm_dict()
  771. break
  772. # Fallback: 从 history 中找 system message
  773. if system_msg_dict is None:
  774. for msg_dict in history:
  775. if msg_dict.get("role") == "system":
  776. system_msg_dict = msg_dict
  777. break
  778. if system_msg_dict is None:
  779. logger.warning("Level 2 压缩跳过:未找到 system message")
  780. return history, head_seq, sequence
  781. # --- Step 1: 经验提取(reflect)---
  782. try:
  783. reflect_prompt = build_reflect_prompt()
  784. reflect_messages = list(history) + [{"role": "user", "content": reflect_prompt}]
  785. reflect_result = await self.llm_call(
  786. messages=reflect_messages,
  787. model=config.model,
  788. tools=[],
  789. temperature=config.temperature,
  790. **config.extra_llm_params,
  791. )
  792. reflect_content = reflect_result.get("content", "").strip()
  793. if reflect_content and self.experiences_path:
  794. try:
  795. os.makedirs(os.path.dirname(self.experiences_path), exist_ok=True)
  796. with open(self.experiences_path, "a", encoding="utf-8") as f:
  797. f.write(f"\n\n---\n\n{reflect_content}")
  798. logger.info("经验已追加到 %s", self.experiences_path)
  799. except Exception as e:
  800. logger.warning("写入经验文件失败: %s", e)
  801. except Exception as e:
  802. logger.warning("Level 2 经验提取失败(不影响压缩): %s", e)
  803. # --- Step 2: 压缩总结 ---
  804. compress_prompt = build_compression_prompt(goal_tree)
  805. compress_messages = list(history) + [{"role": "user", "content": compress_prompt}]
  806. compress_result = await self.llm_call(
  807. messages=compress_messages,
  808. model=config.model,
  809. tools=[],
  810. temperature=config.temperature,
  811. **config.extra_llm_params,
  812. )
  813. summary_text = compress_result.get("content", "").strip()
  814. if not summary_text:
  815. logger.warning("Level 2 压缩跳过:LLM 未返回 summary")
  816. return history, head_seq, sequence
  817. # --- Step 3: 存储 summary 消息 ---
  818. summary_with_header = (
  819. f"## 对话历史摘要(自动压缩)\n\n{summary_text}\n\n"
  820. "---\n请基于以上摘要和当前 GoalTree 继续执行任务。"
  821. )
  822. summary_msg = Message.create(
  823. trace_id=trace_id,
  824. role="user",
  825. sequence=sequence,
  826. goal_id=None,
  827. parent_sequence=system_msg_seq, # 跳到 system msg,跳过所有中间消息
  828. content=summary_with_header,
  829. )
  830. if self.trace_store:
  831. await self.trace_store.add_message(summary_msg)
  832. new_head_seq = sequence
  833. sequence += 1
  834. # --- Step 4: 重建 history ---
  835. new_history = [system_msg_dict, summary_msg.to_llm_dict()]
  836. # 更新 trace head_sequence
  837. if self.trace_store:
  838. await self.trace_store.update_trace(
  839. trace_id,
  840. head_sequence=new_head_seq,
  841. )
  842. logger.info(
  843. "Level 2 压缩完成: 旧 history %d 条 → 新 history %d 条, summary 长度=%d",
  844. len(history), len(new_history), len(summary_text),
  845. )
  846. return new_history, new_head_seq, sequence
  847. # ===== 回溯(Rewind)=====
  848. async def _rewind(
  849. self,
  850. trace_id: str,
  851. after_sequence: int,
  852. goal_tree: Optional[GoalTree],
  853. ) -> int:
  854. """
  855. 执行回溯:快照 GoalTree,重建干净树,设置 head_sequence
  856. 新消息的 parent_sequence 将指向 rewind 点,旧消息通过树结构自然脱离主路径。
  857. Returns:
  858. 下一个可用的 sequence 号
  859. """
  860. if not self.trace_store:
  861. raise ValueError("trace_store required for rewind")
  862. # 1. 加载所有 messages(用于 safe cutoff 和 max sequence)
  863. all_messages = await self.trace_store.get_trace_messages(trace_id)
  864. if not all_messages:
  865. return 1
  866. # 2. 找到安全截断点(确保不截断在 tool_call 和 tool response 之间)
  867. cutoff = self._find_safe_cutoff(all_messages, after_sequence)
  868. # 3. 快照并重建 GoalTree
  869. if goal_tree:
  870. # 获取截断点消息的 created_at 作为时间界限
  871. cutoff_msg = None
  872. for msg in all_messages:
  873. if msg.sequence == cutoff:
  874. cutoff_msg = msg
  875. break
  876. cutoff_time = cutoff_msg.created_at if cutoff_msg else datetime.now()
  877. # 快照到 events(含 head_sequence 供前端感知分支切换)
  878. await self.trace_store.append_event(trace_id, "rewind", {
  879. "after_sequence": cutoff,
  880. "head_sequence": cutoff,
  881. "goal_tree_snapshot": goal_tree.to_dict(),
  882. })
  883. # 按时间重建干净的 GoalTree
  884. new_tree = goal_tree.rebuild_for_rewind(cutoff_time)
  885. await self.trace_store.update_goal_tree(trace_id, new_tree)
  886. # 更新内存中的引用
  887. goal_tree.goals = new_tree.goals
  888. goal_tree.current_id = new_tree.current_id
  889. # 4. 更新 head_sequence 到 rewind 点
  890. await self.trace_store.update_trace(trace_id, head_sequence=cutoff)
  891. # 5. 返回 next sequence(全局递增,不复用)
  892. max_seq = max((m.sequence for m in all_messages), default=0)
  893. return max_seq + 1
  894. def _find_safe_cutoff(self, messages: List[Message], after_sequence: int) -> int:
  895. """
  896. 找到安全的截断点。
  897. 如果 after_sequence 指向一条带 tool_calls 的 assistant message,
  898. 则自动扩展到其所有对应的 tool response 之后。
  899. """
  900. cutoff = after_sequence
  901. # 找到 after_sequence 对应的 message
  902. target_msg = None
  903. for msg in messages:
  904. if msg.sequence == after_sequence:
  905. target_msg = msg
  906. break
  907. if not target_msg:
  908. return cutoff
  909. # 如果是 assistant 且有 tool_calls,找到所有对应的 tool responses
  910. if target_msg.role == "assistant":
  911. content = target_msg.content
  912. if isinstance(content, dict) and content.get("tool_calls"):
  913. tool_call_ids = set()
  914. for tc in content["tool_calls"]:
  915. if isinstance(tc, dict) and tc.get("id"):
  916. tool_call_ids.add(tc["id"])
  917. # 找到这些 tool_call 对应的 tool messages
  918. for msg in messages:
  919. if (msg.role == "tool" and msg.tool_call_id
  920. and msg.tool_call_id in tool_call_ids):
  921. cutoff = max(cutoff, msg.sequence)
  922. return cutoff
  923. async def _heal_orphaned_tool_calls(
  924. self,
  925. messages: List[Message],
  926. trace_id: str,
  927. goal_tree: Optional[GoalTree],
  928. sequence: int,
  929. ) -> tuple:
  930. """
  931. 检测并修复消息历史中的 orphaned tool_calls。
  932. 当 agent 被 stop/crash 中断时,可能有 assistant 的 tool_calls 没有对应的
  933. tool results(包括多 tool_call 部分完成的情况)。直接发给 LLM 会导致 400。
  934. 修复策略:为每个缺失的 tool_result 插入合成的"中断通知"消息,而非裁剪。
  935. - 普通工具:简短中断提示
  936. - agent/evaluate:包含 sub_trace_id、执行统计、continue_from 指引
  937. 合成消息持久化到 store,确保幂等(下次续跑不再触发)。
  938. Returns:
  939. (healed_messages, next_sequence)
  940. """
  941. if not messages:
  942. return messages, sequence
  943. # 收集所有 tool_call IDs → (assistant_msg, tool_call_dict)
  944. tc_map: Dict[str, tuple] = {}
  945. result_ids: set = set()
  946. for msg in messages:
  947. if msg.role == "assistant":
  948. content = msg.content
  949. if isinstance(content, dict) and content.get("tool_calls"):
  950. for tc in content["tool_calls"]:
  951. tc_id = tc.get("id")
  952. if tc_id:
  953. tc_map[tc_id] = (msg, tc)
  954. elif msg.role == "tool" and msg.tool_call_id:
  955. result_ids.add(msg.tool_call_id)
  956. orphaned_ids = [tc_id for tc_id in tc_map if tc_id not in result_ids]
  957. if not orphaned_ids:
  958. return messages, sequence
  959. logger.info(
  960. "检测到 %d 个 orphaned tool_calls,生成合成中断通知",
  961. len(orphaned_ids),
  962. )
  963. healed = list(messages)
  964. head_seq = messages[-1].sequence
  965. for tc_id in orphaned_ids:
  966. assistant_msg, tc = tc_map[tc_id]
  967. tool_name = tc.get("function", {}).get("name", "unknown")
  968. if tool_name in ("agent", "evaluate"):
  969. result_text = self._build_agent_interrupted_result(
  970. tc, goal_tree, assistant_msg,
  971. )
  972. else:
  973. result_text = (
  974. f"⚠️ 工具 {tool_name} 执行被中断(进程异常退出),"
  975. "未获得执行结果。请根据需要重新调用。"
  976. )
  977. synthetic_msg = Message.create(
  978. trace_id=trace_id,
  979. role="tool",
  980. sequence=sequence,
  981. goal_id=assistant_msg.goal_id,
  982. parent_sequence=head_seq,
  983. tool_call_id=tc_id,
  984. content={"tool_name": tool_name, "result": result_text},
  985. )
  986. if self.trace_store:
  987. await self.trace_store.add_message(synthetic_msg)
  988. healed.append(synthetic_msg)
  989. head_seq = sequence
  990. sequence += 1
  991. # 更新 trace head/last sequence
  992. if self.trace_store:
  993. await self.trace_store.update_trace(
  994. trace_id,
  995. head_sequence=head_seq,
  996. last_sequence=max(head_seq, sequence - 1),
  997. )
  998. return healed, sequence
  999. def _build_agent_interrupted_result(
  1000. self,
  1001. tc: Dict,
  1002. goal_tree: Optional[GoalTree],
  1003. assistant_msg: Message,
  1004. ) -> str:
  1005. """为中断的 agent/evaluate 工具调用构建合成结果(对齐正常返回值格式)"""
  1006. args_str = tc.get("function", {}).get("arguments", "{}")
  1007. try:
  1008. args = json.loads(args_str) if isinstance(args_str, str) else args_str
  1009. except json.JSONDecodeError:
  1010. args = {}
  1011. task = args.get("task", "未知任务")
  1012. if isinstance(task, list):
  1013. task = "; ".join(task)
  1014. tool_name = tc.get("function", {}).get("name", "agent")
  1015. mode = "evaluate" if tool_name == "evaluate" else "delegate"
  1016. # 从 goal_tree 查找 sub_trace 信息
  1017. sub_trace_id = None
  1018. stats = None
  1019. if goal_tree and assistant_msg.goal_id:
  1020. goal = goal_tree.find(assistant_msg.goal_id)
  1021. if goal and goal.sub_trace_ids:
  1022. first = goal.sub_trace_ids[0]
  1023. if isinstance(first, dict):
  1024. sub_trace_id = first.get("trace_id")
  1025. elif isinstance(first, str):
  1026. sub_trace_id = first
  1027. if goal.cumulative_stats:
  1028. s = goal.cumulative_stats
  1029. if s.message_count > 0:
  1030. stats = {
  1031. "message_count": s.message_count,
  1032. "total_tokens": s.total_tokens,
  1033. "total_cost": round(s.total_cost, 4),
  1034. }
  1035. result: Dict[str, Any] = {
  1036. "mode": mode,
  1037. "status": "interrupted",
  1038. "summary": "⚠️ 子Agent执行被中断(进程异常退出)",
  1039. "task": task,
  1040. }
  1041. if sub_trace_id:
  1042. result["sub_trace_id"] = sub_trace_id
  1043. result["hint"] = (
  1044. f'使用 continue_from="{sub_trace_id}" 可继续执行,保留已有进度'
  1045. )
  1046. if stats:
  1047. result["stats"] = stats
  1048. return json.dumps(result, ensure_ascii=False, indent=2)
  1049. # ===== 上下文注入 =====
  1050. def _build_context_injection(
  1051. self,
  1052. trace: Trace,
  1053. goal_tree: Optional[GoalTree],
  1054. ) -> str:
  1055. """构建周期性注入的上下文(GoalTree + Active Collaborators + Focus 提醒)"""
  1056. parts = []
  1057. # GoalTree
  1058. if goal_tree and goal_tree.goals:
  1059. parts.append(f"## Current Plan\n\n{goal_tree.to_prompt()}")
  1060. # 检测 focus 在有子节点的父目标上:提醒模型 focus 到具体子目标
  1061. if goal_tree.current_id:
  1062. children = goal_tree.get_children(goal_tree.current_id)
  1063. pending_children = [c for c in children if c.status in ("pending", "in_progress")]
  1064. if pending_children:
  1065. child_ids = ", ".join(
  1066. goal_tree._generate_display_id(c) for c in pending_children[:3]
  1067. )
  1068. parts.append(
  1069. f"**提醒**:当前焦点在父目标上,建议用 `goal(focus=\"...\")` "
  1070. f"切换到具体子目标(如 {child_ids})再执行。"
  1071. )
  1072. # Active Collaborators
  1073. collaborators = trace.context.get("collaborators", [])
  1074. if collaborators:
  1075. lines = ["## Active Collaborators"]
  1076. for c in collaborators:
  1077. status_str = c.get("status", "unknown")
  1078. ctype = c.get("type", "agent")
  1079. summary = c.get("summary", "")
  1080. name = c.get("name", "unnamed")
  1081. lines.append(f"- {name} [{ctype}, {status_str}]: {summary}")
  1082. parts.append("\n".join(lines))
  1083. return "\n\n".join(parts)
  1084. # ===== 辅助方法 =====
  1085. def _get_tool_schemas(self, tools: Optional[List[str]]) -> List[Dict]:
  1086. """
  1087. 获取工具 Schema
  1088. - tools=None: 使用 registry 中全部已注册工具(含内置 + 外部注册的)
  1089. - tools=["a", "b"]: 在 BUILTIN_TOOLS 基础上追加指定工具
  1090. """
  1091. if tools is None:
  1092. # 全部已注册工具
  1093. tool_names = self.tools.get_tool_names()
  1094. else:
  1095. # BUILTIN_TOOLS + 显式指定的额外工具
  1096. tool_names = BUILTIN_TOOLS.copy()
  1097. for t in tools:
  1098. if t not in tool_names:
  1099. tool_names.append(t)
  1100. return self.tools.get_schemas(tool_names)
  1101. # 默认 system prompt 前缀(当 config.system_prompt 和前端都未提供 system message 时使用)
  1102. DEFAULT_SYSTEM_PREFIX = "你是最顶尖的AI助手,可以拆分并调用工具逐步解决复杂问题。"
  1103. async def _build_system_prompt(self, config: RunConfig) -> Optional[str]:
  1104. """构建 system prompt(注入 skills)"""
  1105. system_prompt = config.system_prompt
  1106. # 加载 Skills
  1107. skills_text = ""
  1108. skills = load_skills_from_dir(self.skills_dir)
  1109. if skills:
  1110. skills_text = self._format_skills(skills)
  1111. # 拼装:有自定义 system_prompt 则用它,否则用默认前缀
  1112. if system_prompt:
  1113. if skills_text:
  1114. system_prompt += f"\n\n## Skills\n{skills_text}"
  1115. else:
  1116. system_prompt = self.DEFAULT_SYSTEM_PREFIX
  1117. if skills_text:
  1118. system_prompt += f"\n\n## Skills\n{skills_text}"
  1119. return system_prompt
  1120. async def _generate_task_name(self, messages: List[Dict]) -> str:
  1121. """生成任务名称:优先使用 utility_llm,fallback 到文本截取"""
  1122. # 提取 messages 中的文本内容
  1123. text_parts = []
  1124. for msg in messages:
  1125. content = msg.get("content", "")
  1126. if isinstance(content, str):
  1127. text_parts.append(content)
  1128. elif isinstance(content, list):
  1129. for part in content:
  1130. if isinstance(part, dict) and part.get("type") == "text":
  1131. text_parts.append(part.get("text", ""))
  1132. raw_text = " ".join(text_parts).strip()
  1133. if not raw_text:
  1134. return "未命名任务"
  1135. # 尝试使用 utility_llm 生成标题
  1136. if self.utility_llm_call:
  1137. try:
  1138. result = await self.utility_llm_call(
  1139. messages=[
  1140. {"role": "system", "content": "用中文为以下任务生成一个简短标题(10-30字),只输出标题本身:"},
  1141. {"role": "user", "content": raw_text[:2000]},
  1142. ],
  1143. model="gpt-4o-mini", # 使用便宜模型
  1144. )
  1145. title = result.get("content", "").strip()
  1146. if title and len(title) < 100:
  1147. return title
  1148. except Exception:
  1149. pass
  1150. # Fallback: 截取前 50 字符
  1151. return raw_text[:50] + ("..." if len(raw_text) > 50 else "")
  1152. def _format_skills(self, skills: List[Skill]) -> str:
  1153. if not skills:
  1154. return ""
  1155. return "\n\n".join(s.to_prompt_text() for s in skills)
  1156. def _load_experiences(self) -> str:
  1157. """从文件加载经验(./cache/experiences.md)"""
  1158. if not self.experiences_path:
  1159. return ""
  1160. try:
  1161. if os.path.exists(self.experiences_path):
  1162. with open(self.experiences_path, "r", encoding="utf-8") as f:
  1163. return f.read().strip()
  1164. except Exception as e:
  1165. logger.warning(f"Failed to load experiences from {self.experiences_path}: {e}")
  1166. return ""