runner.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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, insert_after 等)
  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.memory.models import Skill
  26. from agent.memory.protocols import MemoryStore, StateStore
  27. from agent.memory.skill_loader import load_skills_from_dir
  28. from agent.tools import ToolRegistry, get_tool_registry
  29. logger = logging.getLogger(__name__)
  30. # ===== 运行配置 =====
  31. @dataclass
  32. class RunConfig:
  33. """
  34. 运行参数 — 控制 Agent 如何执行
  35. 分为模型层参数(由上游 agent 或用户决定)和框架层参数(由系统注入)。
  36. """
  37. # --- 模型层参数 ---
  38. model: str = "gpt-4o"
  39. temperature: float = 0.3
  40. max_iterations: int = 200
  41. tools: Optional[List[str]] = None # None = 全部内置工具
  42. # --- 框架层参数 ---
  43. agent_type: str = "default"
  44. uid: Optional[str] = None
  45. system_prompt: Optional[str] = None # None = 从 skills 自动构建
  46. enable_memory: bool = True
  47. auto_execute_tools: bool = True
  48. name: Optional[str] = None # 显示名称(空则由 utility_llm 自动生成)
  49. # --- Trace 控制 ---
  50. trace_id: Optional[str] = None # None = 新建
  51. parent_trace_id: Optional[str] = None # 子 Agent 专用
  52. parent_goal_id: Optional[str] = None
  53. # --- 续跑控制 ---
  54. insert_after: Optional[int] = None # 回溯插入点(message sequence)
  55. # --- 额外 LLM 参数(传给 llm_call 的 **kwargs)---
  56. extra_llm_params: Dict[str, Any] = field(default_factory=dict)
  57. # 内置工具列表(始终自动加载)
  58. BUILTIN_TOOLS = [
  59. # 文件操作工具
  60. "read_file",
  61. "edit_file",
  62. "write_file",
  63. "glob_files",
  64. "grep_content",
  65. # 系统工具
  66. "bash_command",
  67. # 技能和目标管理
  68. "skill",
  69. "list_skills",
  70. "goal",
  71. "agent",
  72. "evaluate",
  73. # 搜索工具
  74. "search_posts",
  75. "get_search_suggestions",
  76. # 沙箱工具
  77. "sandbox_create_environment",
  78. "sandbox_run_shell",
  79. "sandbox_rebuild_with_ports",
  80. "sandbox_destroy_environment",
  81. # 浏览器工具
  82. "browser_navigate_to_url",
  83. "browser_search_web",
  84. "browser_go_back",
  85. "browser_wait",
  86. "browser_click_element",
  87. "browser_input_text",
  88. "browser_send_keys",
  89. "browser_upload_file",
  90. "browser_scroll_page",
  91. "browser_find_text",
  92. "browser_screenshot",
  93. "browser_switch_tab",
  94. "browser_close_tab",
  95. "browser_get_dropdown_options",
  96. "browser_select_dropdown_option",
  97. "browser_extract_content",
  98. "browser_read_long_content",
  99. "browser_get_page_html",
  100. "browser_get_selector_map",
  101. "browser_evaluate",
  102. "browser_ensure_login_with_cookies",
  103. "browser_wait_for_user_action",
  104. "browser_done",
  105. ]
  106. # ===== 向后兼容 =====
  107. @dataclass
  108. class AgentConfig:
  109. """[向后兼容] Agent 配置,新代码请使用 RunConfig"""
  110. agent_type: str = "default"
  111. max_iterations: int = 200
  112. enable_memory: bool = True
  113. auto_execute_tools: bool = True
  114. @dataclass
  115. class CallResult:
  116. """单次调用结果"""
  117. reply: str
  118. tool_calls: Optional[List[Dict]] = None
  119. trace_id: Optional[str] = None
  120. step_id: Optional[str] = None
  121. tokens: Optional[Dict[str, int]] = None
  122. cost: float = 0.0
  123. # ===== 执行引擎 =====
  124. CONTEXT_INJECTION_INTERVAL = 10 # 每 N 轮注入一次 GoalTree + Collaborators
  125. class AgentRunner:
  126. """
  127. Agent 执行引擎
  128. 支持三种运行模式(通过 RunConfig 区分):
  129. 1. 新建:trace_id=None
  130. 2. 续跑:trace_id=已有ID, insert_after=None
  131. 3. 回溯:trace_id=已有ID, insert_after=N
  132. """
  133. def __init__(
  134. self,
  135. trace_store: Optional[TraceStore] = None,
  136. memory_store: Optional[MemoryStore] = None,
  137. state_store: Optional[StateStore] = None,
  138. tool_registry: Optional[ToolRegistry] = None,
  139. llm_call: Optional[Callable] = None,
  140. utility_llm_call: Optional[Callable] = None,
  141. config: Optional[AgentConfig] = None,
  142. skills_dir: Optional[str] = None,
  143. experiences_path: Optional[str] = "./cache/experiences.md",
  144. goal_tree: Optional[GoalTree] = None,
  145. debug: bool = False,
  146. ):
  147. """
  148. 初始化 AgentRunner
  149. Args:
  150. trace_store: Trace 存储
  151. memory_store: Memory 存储(可选)
  152. state_store: State 存储(可选)
  153. tool_registry: 工具注册表(默认使用全局注册表)
  154. llm_call: 主 LLM 调用函数
  155. utility_llm_call: 轻量 LLM(用于生成任务标题等),可选
  156. config: [向后兼容] AgentConfig
  157. skills_dir: Skills 目录路径
  158. experiences_path: 经验文件路径(默认 ./cache/experiences.md)
  159. goal_tree: 初始 GoalTree(可选)
  160. debug: 保留参数(已废弃)
  161. """
  162. self.trace_store = trace_store
  163. self.memory_store = memory_store
  164. self.state_store = state_store
  165. self.tools = tool_registry or get_tool_registry()
  166. self.llm_call = llm_call
  167. self.utility_llm_call = utility_llm_call
  168. self.config = config or AgentConfig()
  169. self.skills_dir = skills_dir
  170. self.experiences_path = experiences_path
  171. self.goal_tree = goal_tree
  172. self.debug = debug
  173. self._cancel_events: Dict[str, asyncio.Event] = {} # trace_id → cancel event
  174. # ===== 核心公开方法 =====
  175. async def run(
  176. self,
  177. messages: List[Dict],
  178. config: Optional[RunConfig] = None,
  179. ) -> AsyncIterator[Union[Trace, Message]]:
  180. """
  181. Agent 模式执行(核心方法)
  182. Args:
  183. messages: OpenAI SDK 格式的输入消息
  184. 新建: 初始任务消息 [{"role": "user", "content": "..."}]
  185. 续跑: 追加的新消息
  186. 回溯: 在插入点之后追加的消息
  187. config: 运行配置
  188. Yields:
  189. Union[Trace, Message]: Trace 对象(状态变化)或 Message 对象(执行过程)
  190. """
  191. if not self.llm_call:
  192. raise ValueError("llm_call function not provided")
  193. config = config or RunConfig()
  194. trace = None
  195. try:
  196. # Phase 1: PREPARE TRACE
  197. trace, goal_tree, sequence = await self._prepare_trace(messages, config)
  198. # 注册取消事件
  199. self._cancel_events[trace.trace_id] = asyncio.Event()
  200. yield trace
  201. # Phase 2: BUILD HISTORY
  202. history, sequence, created_messages, head_seq = await self._build_history(
  203. trace.trace_id, messages, goal_tree, config, sequence
  204. )
  205. # Update trace's head_sequence in memory
  206. trace.head_sequence = head_seq
  207. for msg in created_messages:
  208. yield msg
  209. # Phase 3: AGENT LOOP
  210. async for event in self._agent_loop(trace, history, goal_tree, config, sequence):
  211. yield event
  212. except Exception as e:
  213. logger.error(f"Agent run failed: {e}")
  214. tid = config.trace_id or (trace.trace_id if trace else None)
  215. if self.trace_store and tid:
  216. await self.trace_store.update_trace(
  217. tid,
  218. status="failed",
  219. error_message=str(e),
  220. completed_at=datetime.now()
  221. )
  222. trace_obj = await self.trace_store.get_trace(tid)
  223. if trace_obj:
  224. yield trace_obj
  225. raise
  226. finally:
  227. # 清理取消事件
  228. if trace:
  229. self._cancel_events.pop(trace.trace_id, None)
  230. async def run_result(
  231. self,
  232. messages: List[Dict],
  233. config: Optional[RunConfig] = None,
  234. ) -> Dict[str, Any]:
  235. """
  236. 结果模式 — 消费 run(),返回结构化结果。
  237. 主要用于 agent/evaluate 工具内部。
  238. """
  239. last_assistant_text = ""
  240. final_trace: Optional[Trace] = None
  241. async for item in self.run(messages=messages, config=config):
  242. if isinstance(item, Message) and item.role == "assistant":
  243. content = item.content
  244. text = ""
  245. if isinstance(content, dict):
  246. text = content.get("text", "") or ""
  247. elif isinstance(content, str):
  248. text = content
  249. if text and text.strip():
  250. last_assistant_text = text
  251. elif isinstance(item, Trace):
  252. final_trace = item
  253. config = config or RunConfig()
  254. if not final_trace and config.trace_id and self.trace_store:
  255. final_trace = await self.trace_store.get_trace(config.trace_id)
  256. status = final_trace.status if final_trace else "unknown"
  257. error = final_trace.error_message if final_trace else None
  258. summary = last_assistant_text
  259. if not summary:
  260. status = "failed"
  261. error = error or "Agent 没有产生 assistant 文本结果"
  262. return {
  263. "status": status,
  264. "summary": summary,
  265. "trace_id": final_trace.trace_id if final_trace else config.trace_id,
  266. "error": error,
  267. "stats": {
  268. "total_messages": final_trace.total_messages if final_trace else 0,
  269. "total_tokens": final_trace.total_tokens if final_trace else 0,
  270. "total_cost": final_trace.total_cost if final_trace else 0.0,
  271. },
  272. }
  273. async def stop(self, trace_id: str) -> bool:
  274. """
  275. 停止运行中的 Trace
  276. 设置取消信号,agent loop 在下一个 LLM 调用前检查并退出。
  277. Trace 状态置为 "stopped"。
  278. Returns:
  279. True 如果成功发送停止信号,False 如果该 trace 不在运行中
  280. """
  281. cancel_event = self._cancel_events.get(trace_id)
  282. if cancel_event is None:
  283. return False
  284. cancel_event.set()
  285. return True
  286. # ===== 单次调用(保留)=====
  287. async def call(
  288. self,
  289. messages: List[Dict],
  290. model: str = "gpt-4o",
  291. tools: Optional[List[str]] = None,
  292. uid: Optional[str] = None,
  293. trace: bool = True,
  294. **kwargs
  295. ) -> CallResult:
  296. """
  297. 单次 LLM 调用(无 Agent Loop)
  298. """
  299. if not self.llm_call:
  300. raise ValueError("llm_call function not provided")
  301. trace_id = None
  302. message_id = None
  303. tool_names = BUILTIN_TOOLS.copy()
  304. if tools:
  305. for tool in tools:
  306. if tool not in tool_names:
  307. tool_names.append(tool)
  308. tool_schemas = self.tools.get_schemas(tool_names)
  309. if trace and self.trace_store:
  310. trace_obj = Trace.create(mode="call", uid=uid, model=model, tools=tool_schemas, llm_params=kwargs)
  311. trace_id = await self.trace_store.create_trace(trace_obj)
  312. result = await self.llm_call(messages=messages, model=model, tools=tool_schemas, **kwargs)
  313. if trace and self.trace_store and trace_id:
  314. msg = Message.create(
  315. trace_id=trace_id, role="assistant", sequence=1, goal_id=None,
  316. content={"text": result.get("content", ""), "tool_calls": result.get("tool_calls")},
  317. prompt_tokens=result.get("prompt_tokens", 0),
  318. completion_tokens=result.get("completion_tokens", 0),
  319. finish_reason=result.get("finish_reason"),
  320. cost=result.get("cost", 0),
  321. )
  322. message_id = await self.trace_store.add_message(msg)
  323. await self.trace_store.update_trace(trace_id, status="completed", completed_at=datetime.now())
  324. return CallResult(
  325. reply=result.get("content", ""),
  326. tool_calls=result.get("tool_calls"),
  327. trace_id=trace_id,
  328. step_id=message_id,
  329. tokens={"prompt": result.get("prompt_tokens", 0), "completion": result.get("completion_tokens", 0)},
  330. cost=result.get("cost", 0)
  331. )
  332. # ===== Phase 1: PREPARE TRACE =====
  333. async def _prepare_trace(
  334. self,
  335. messages: List[Dict],
  336. config: RunConfig,
  337. ) -> Tuple[Trace, Optional[GoalTree], int]:
  338. """
  339. 准备 Trace:创建新的或加载已有的
  340. Returns:
  341. (trace, goal_tree, next_sequence)
  342. """
  343. if config.trace_id:
  344. return await self._prepare_existing_trace(config)
  345. else:
  346. return await self._prepare_new_trace(messages, config)
  347. async def _prepare_new_trace(
  348. self,
  349. messages: List[Dict],
  350. config: RunConfig,
  351. ) -> Tuple[Trace, Optional[GoalTree], int]:
  352. """创建新 Trace"""
  353. trace_id = str(uuid.uuid4())
  354. # 生成任务名称
  355. task_name = config.name or await self._generate_task_name(messages)
  356. # 准备工具 Schema
  357. tool_schemas = self._get_tool_schemas(config.tools)
  358. trace_obj = Trace(
  359. trace_id=trace_id,
  360. mode="agent",
  361. task=task_name,
  362. agent_type=config.agent_type,
  363. parent_trace_id=config.parent_trace_id,
  364. parent_goal_id=config.parent_goal_id,
  365. uid=config.uid,
  366. model=config.model,
  367. tools=tool_schemas,
  368. llm_params={"temperature": config.temperature, **config.extra_llm_params},
  369. status="running",
  370. )
  371. goal_tree = self.goal_tree or GoalTree(mission=task_name)
  372. if self.trace_store:
  373. await self.trace_store.create_trace(trace_obj)
  374. await self.trace_store.update_goal_tree(trace_id, goal_tree)
  375. return trace_obj, goal_tree, 1
  376. async def _prepare_existing_trace(
  377. self,
  378. config: RunConfig,
  379. ) -> Tuple[Trace, Optional[GoalTree], int]:
  380. """加载已有 Trace(续跑或回溯)"""
  381. if not self.trace_store:
  382. raise ValueError("trace_store required for continue/rewind")
  383. trace_obj = await self.trace_store.get_trace(config.trace_id)
  384. if not trace_obj:
  385. raise ValueError(f"Trace not found: {config.trace_id}")
  386. goal_tree = await self.trace_store.get_goal_tree(config.trace_id)
  387. if config.insert_after is not None:
  388. # 回溯模式
  389. sequence = await self._rewind(config.trace_id, config.insert_after, goal_tree)
  390. else:
  391. # 续跑模式:从 last_sequence + 1 开始
  392. sequence = trace_obj.last_sequence + 1
  393. # 状态置为 running
  394. await self.trace_store.update_trace(
  395. config.trace_id,
  396. status="running",
  397. completed_at=None,
  398. )
  399. trace_obj.status = "running"
  400. return trace_obj, goal_tree, sequence
  401. # ===== Phase 2: BUILD HISTORY =====
  402. async def _build_history(
  403. self,
  404. trace_id: str,
  405. new_messages: List[Dict],
  406. goal_tree: Optional[GoalTree],
  407. config: RunConfig,
  408. sequence: int,
  409. ) -> Tuple[List[Dict], int, List[Message]]:
  410. """
  411. 构建完整的 LLM 消息历史
  412. 1. 从 head_sequence 沿 parent chain 加载主路径消息(续跑/回溯场景)
  413. 2. 构建 system prompt(新建时注入 skills)
  414. 3. 新建时:在第一条 user message 末尾注入当前经验
  415. 4. 追加 input messages(设置 parent_sequence 链接到当前 head)
  416. Returns:
  417. (history, next_sequence, created_messages, head_sequence)
  418. created_messages: 本次新创建并持久化的 Message 列表,供 run() yield 给调用方
  419. head_sequence: 当前主路径头节点的 sequence
  420. """
  421. history: List[Dict] = []
  422. created_messages: List[Message] = []
  423. head_seq: Optional[int] = None # 当前主路径的头节点 sequence
  424. # 1. 加载已有 messages(通过主路径遍历)
  425. if config.trace_id and self.trace_store:
  426. trace_obj = await self.trace_store.get_trace(trace_id)
  427. if trace_obj and trace_obj.head_sequence > 0:
  428. main_path = await self.trace_store.get_main_path_messages(
  429. trace_id, trace_obj.head_sequence
  430. )
  431. history = [msg.to_llm_dict() for msg in main_path]
  432. if main_path:
  433. head_seq = main_path[-1].sequence
  434. # 2. 构建 system prompt(如果历史中没有 system message)
  435. has_system = any(m.get("role") == "system" for m in history)
  436. has_system_in_new = any(m.get("role") == "system" for m in new_messages)
  437. if not has_system and not has_system_in_new:
  438. system_prompt = await self._build_system_prompt(config)
  439. if system_prompt:
  440. history = [{"role": "system", "content": system_prompt}] + history
  441. if self.trace_store:
  442. system_msg = Message.create(
  443. trace_id=trace_id, role="system", sequence=sequence,
  444. goal_id=None, content=system_prompt,
  445. parent_sequence=None, # system message 是 root
  446. )
  447. await self.trace_store.add_message(system_msg)
  448. created_messages.append(system_msg)
  449. head_seq = sequence
  450. sequence += 1
  451. # 3. 新建时:在第一条 user message 末尾注入当前经验
  452. if not config.trace_id: # 新建模式
  453. experiences_text = self._load_experiences()
  454. if experiences_text:
  455. for msg in new_messages:
  456. if msg.get("role") == "user" and isinstance(msg.get("content"), str):
  457. msg["content"] += f"\n\n## 参考经验\n\n{experiences_text}"
  458. break
  459. # 4. 追加新 messages(设置 parent_sequence 链接到当前 head)
  460. for msg_dict in new_messages:
  461. history.append(msg_dict)
  462. if self.trace_store:
  463. stored_msg = Message.from_llm_dict(
  464. msg_dict, trace_id=trace_id, sequence=sequence,
  465. goal_id=None, parent_sequence=head_seq,
  466. )
  467. await self.trace_store.add_message(stored_msg)
  468. created_messages.append(stored_msg)
  469. head_seq = sequence
  470. sequence += 1
  471. # 5. 更新 trace 的 head_sequence
  472. if self.trace_store and head_seq is not None:
  473. await self.trace_store.update_trace(trace_id, head_sequence=head_seq)
  474. return history, sequence, created_messages, head_seq or 0
  475. # ===== Phase 3: AGENT LOOP =====
  476. async def _agent_loop(
  477. self,
  478. trace: Trace,
  479. history: List[Dict],
  480. goal_tree: Optional[GoalTree],
  481. config: RunConfig,
  482. sequence: int,
  483. ) -> AsyncIterator[Union[Trace, Message]]:
  484. """ReAct 循环"""
  485. trace_id = trace.trace_id
  486. tool_schemas = self._get_tool_schemas(config.tools)
  487. # 当前主路径头节点的 sequence(用于设置 parent_sequence)
  488. head_seq = trace.head_sequence
  489. # 设置 goal_tree 到 goal 工具
  490. if goal_tree and self.trace_store:
  491. from agent.trace.goal_tool import set_goal_tree
  492. set_goal_tree(goal_tree)
  493. for iteration in range(config.max_iterations):
  494. # 检查取消信号
  495. cancel_event = self._cancel_events.get(trace_id)
  496. if cancel_event and cancel_event.is_set():
  497. logger.info(f"Trace {trace_id} stopped by user")
  498. if self.trace_store:
  499. await self.trace_store.update_trace(
  500. trace_id,
  501. status="stopped",
  502. completed_at=datetime.now(),
  503. )
  504. trace_obj = await self.trace_store.get_trace(trace_id)
  505. if trace_obj:
  506. yield trace_obj
  507. return
  508. # 构建 LLM messages(注入上下文)
  509. llm_messages = list(history)
  510. # 周期性注入 GoalTree + Collaborators
  511. if iteration % CONTEXT_INJECTION_INTERVAL == 0:
  512. context_injection = self._build_context_injection(trace, goal_tree)
  513. if context_injection:
  514. llm_messages.append({"role": "system", "content": context_injection})
  515. # 调用 LLM
  516. result = await self.llm_call(
  517. messages=llm_messages,
  518. model=config.model,
  519. tools=tool_schemas,
  520. temperature=config.temperature,
  521. **config.extra_llm_params,
  522. )
  523. response_content = result.get("content", "")
  524. tool_calls = result.get("tool_calls")
  525. finish_reason = result.get("finish_reason")
  526. prompt_tokens = result.get("prompt_tokens", 0)
  527. completion_tokens = result.get("completion_tokens", 0)
  528. step_cost = result.get("cost", 0)
  529. # 按需自动创建 root goal
  530. if goal_tree and not goal_tree.goals and tool_calls:
  531. has_goal_call = any(
  532. tc.get("function", {}).get("name") == "goal"
  533. for tc in tool_calls
  534. )
  535. if not has_goal_call:
  536. mission = goal_tree.mission
  537. root_desc = mission[:200] if len(mission) > 200 else mission
  538. goal_tree.add_goals(
  539. descriptions=[root_desc],
  540. reasons=["系统自动创建:Agent 未显式创建目标"],
  541. parent_id=None
  542. )
  543. goal_tree.focus(goal_tree.goals[0].id)
  544. if self.trace_store:
  545. await self.trace_store.update_goal_tree(trace_id, goal_tree)
  546. await self.trace_store.add_goal(trace_id, goal_tree.goals[0])
  547. logger.info(f"自动创建 root goal: {goal_tree.goals[0].id}")
  548. # 获取当前 goal_id
  549. current_goal_id = goal_tree.current_id if (goal_tree and goal_tree.current_id) else None
  550. # 记录 assistant Message(parent_sequence 指向当前 head)
  551. assistant_msg = Message.create(
  552. trace_id=trace_id,
  553. role="assistant",
  554. sequence=sequence,
  555. goal_id=current_goal_id,
  556. parent_sequence=head_seq if head_seq > 0 else None,
  557. content={"text": response_content, "tool_calls": tool_calls},
  558. prompt_tokens=prompt_tokens,
  559. completion_tokens=completion_tokens,
  560. finish_reason=finish_reason,
  561. cost=step_cost,
  562. )
  563. if self.trace_store:
  564. await self.trace_store.add_message(assistant_msg)
  565. yield assistant_msg
  566. head_seq = sequence
  567. sequence += 1
  568. # 处理工具调用
  569. if tool_calls and config.auto_execute_tools:
  570. history.append({
  571. "role": "assistant",
  572. "content": response_content,
  573. "tool_calls": tool_calls,
  574. })
  575. for tc in tool_calls:
  576. current_goal_id = goal_tree.current_id if (goal_tree and goal_tree.current_id) else None
  577. tool_name = tc["function"]["name"]
  578. tool_args = tc["function"]["arguments"]
  579. if isinstance(tool_args, str):
  580. tool_args = json.loads(tool_args) if tool_args.strip() else {}
  581. elif tool_args is None:
  582. tool_args = {}
  583. tool_result = await self.tools.execute(
  584. tool_name,
  585. tool_args,
  586. uid=config.uid or "",
  587. context={
  588. "store": self.trace_store,
  589. "trace_id": trace_id,
  590. "goal_id": current_goal_id,
  591. "runner": self,
  592. }
  593. )
  594. tool_msg = Message.create(
  595. trace_id=trace_id,
  596. role="tool",
  597. sequence=sequence,
  598. goal_id=current_goal_id,
  599. parent_sequence=head_seq,
  600. tool_call_id=tc["id"],
  601. content={"tool_name": tool_name, "result": tool_result},
  602. )
  603. if self.trace_store:
  604. await self.trace_store.add_message(tool_msg)
  605. yield tool_msg
  606. head_seq = sequence
  607. sequence += 1
  608. history.append({
  609. "role": "tool",
  610. "tool_call_id": tc["id"],
  611. "name": tool_name,
  612. "content": str(tool_result),
  613. })
  614. continue # 继续循环
  615. # 无工具调用,任务完成
  616. break
  617. # 更新 head_sequence 并完成 Trace
  618. if self.trace_store:
  619. await self.trace_store.update_trace(
  620. trace_id,
  621. status="completed",
  622. head_sequence=head_seq,
  623. completed_at=datetime.now(),
  624. )
  625. trace_obj = await self.trace_store.get_trace(trace_id)
  626. if trace_obj:
  627. yield trace_obj
  628. # ===== 回溯(Rewind)=====
  629. async def _rewind(
  630. self,
  631. trace_id: str,
  632. insert_after: int,
  633. goal_tree: Optional[GoalTree],
  634. ) -> int:
  635. """
  636. 执行回溯:快照 GoalTree,重建干净树,设置 head_sequence
  637. 新消息的 parent_sequence 将指向 rewind 点,旧消息通过树结构自然脱离主路径。
  638. Returns:
  639. 下一个可用的 sequence 号
  640. """
  641. if not self.trace_store:
  642. raise ValueError("trace_store required for rewind")
  643. # 1. 加载所有 messages
  644. all_messages = await self.trace_store.get_trace_messages(
  645. trace_id, include_abandoned=True
  646. )
  647. if not all_messages:
  648. return 1
  649. # 2. 找到安全截断点(确保不截断在 tool_call 和 tool response 之间)
  650. cutoff = self._find_safe_cutoff(all_messages, insert_after)
  651. # 3. 快照并重建 GoalTree
  652. if goal_tree:
  653. # 找出 rewind 点之前已完成的 goal IDs
  654. # 通过主路径消息来判断:cutoff 之前的消息引用的 completed goals
  655. messages_before = [m for m in all_messages if m.sequence <= cutoff]
  656. completed_goal_ids = set()
  657. for goal in goal_tree.goals:
  658. if goal.status == "completed":
  659. # 检查该 goal 是否在 rewind 点之前就已完成(有关联消息在 cutoff 之前)
  660. goal_msgs = [m for m in messages_before if m.goal_id == goal.id]
  661. if goal_msgs:
  662. completed_goal_ids.add(goal.id)
  663. # 快照到 events
  664. await self.trace_store.append_event(trace_id, "rewind", {
  665. "insert_after_sequence": cutoff,
  666. "goal_tree_snapshot": goal_tree.to_dict(),
  667. })
  668. # 重建干净的 GoalTree
  669. new_tree = goal_tree.rebuild_for_rewind(completed_goal_ids)
  670. await self.trace_store.update_goal_tree(trace_id, new_tree)
  671. # 更新内存中的引用
  672. goal_tree.goals = new_tree.goals
  673. goal_tree.current_id = new_tree.current_id
  674. # 4. 更新 head_sequence 到 rewind 点
  675. await self.trace_store.update_trace(trace_id, head_sequence=cutoff)
  676. # 5. 返回 next sequence(全局递增,不复用)
  677. max_seq = max((m.sequence for m in all_messages), default=0)
  678. return max_seq + 1
  679. def _find_safe_cutoff(self, messages: List[Message], insert_after: int) -> int:
  680. """
  681. 找到安全的截断点。
  682. 如果 insert_after 指向一条带 tool_calls 的 assistant message,
  683. 则自动扩展到其所有对应的 tool response 之后。
  684. """
  685. cutoff = insert_after
  686. # 找到 insert_after 对应的 message
  687. target_msg = None
  688. for msg in messages:
  689. if msg.sequence == insert_after:
  690. target_msg = msg
  691. break
  692. if not target_msg:
  693. return cutoff
  694. # 如果是 assistant 且有 tool_calls,找到所有对应的 tool responses
  695. if target_msg.role == "assistant":
  696. content = target_msg.content
  697. if isinstance(content, dict) and content.get("tool_calls"):
  698. tool_call_ids = set()
  699. for tc in content["tool_calls"]:
  700. if isinstance(tc, dict) and tc.get("id"):
  701. tool_call_ids.add(tc["id"])
  702. # 找到这些 tool_call 对应的 tool messages
  703. for msg in messages:
  704. if (msg.role == "tool" and msg.tool_call_id
  705. and msg.tool_call_id in tool_call_ids):
  706. cutoff = max(cutoff, msg.sequence)
  707. return cutoff
  708. # ===== 上下文注入 =====
  709. def _build_context_injection(
  710. self,
  711. trace: Trace,
  712. goal_tree: Optional[GoalTree],
  713. ) -> str:
  714. """构建周期性注入的上下文(GoalTree + Active Collaborators)"""
  715. parts = []
  716. # GoalTree
  717. if goal_tree and goal_tree.goals:
  718. parts.append(f"## Current Plan\n\n{goal_tree.to_prompt()}")
  719. # Active Collaborators
  720. collaborators = trace.context.get("collaborators", [])
  721. if collaborators:
  722. lines = ["## Active Collaborators"]
  723. for c in collaborators:
  724. status_str = c.get("status", "unknown")
  725. ctype = c.get("type", "agent")
  726. summary = c.get("summary", "")
  727. name = c.get("name", "unnamed")
  728. lines.append(f"- {name} [{ctype}, {status_str}]: {summary}")
  729. parts.append("\n".join(lines))
  730. return "\n\n".join(parts)
  731. # ===== 辅助方法 =====
  732. def _get_tool_schemas(self, tools: Optional[List[str]]) -> List[Dict]:
  733. """获取工具 Schema"""
  734. tool_names = BUILTIN_TOOLS.copy()
  735. if tools:
  736. for tool in tools:
  737. if tool not in tool_names:
  738. tool_names.append(tool)
  739. return self.tools.get_schemas(tool_names)
  740. async def _build_system_prompt(self, config: RunConfig) -> Optional[str]:
  741. """构建 system prompt(注入 skills)"""
  742. system_prompt = config.system_prompt
  743. # 加载 Skills
  744. skills_text = ""
  745. skills = load_skills_from_dir(self.skills_dir)
  746. if skills:
  747. skills_text = self._format_skills(skills)
  748. # 拼装
  749. if system_prompt:
  750. if skills_text:
  751. system_prompt += f"\n\n## Skills\n{skills_text}"
  752. elif skills_text:
  753. system_prompt = f"## Skills\n{skills_text}"
  754. return system_prompt
  755. async def _generate_task_name(self, messages: List[Dict]) -> str:
  756. """生成任务名称:优先使用 utility_llm,fallback 到文本截取"""
  757. # 提取 messages 中的文本内容
  758. text_parts = []
  759. for msg in messages:
  760. content = msg.get("content", "")
  761. if isinstance(content, str):
  762. text_parts.append(content)
  763. elif isinstance(content, list):
  764. for part in content:
  765. if isinstance(part, dict) and part.get("type") == "text":
  766. text_parts.append(part.get("text", ""))
  767. raw_text = " ".join(text_parts).strip()
  768. if not raw_text:
  769. return "未命名任务"
  770. # 尝试使用 utility_llm 生成标题
  771. if self.utility_llm_call:
  772. try:
  773. result = await self.utility_llm_call(
  774. messages=[
  775. {"role": "system", "content": "用中文为以下任务生成一个简短标题(10-30字),只输出标题本身:"},
  776. {"role": "user", "content": raw_text[:2000]},
  777. ],
  778. model="gpt-4o-mini", # 使用便宜模型
  779. )
  780. title = result.get("content", "").strip()
  781. if title and len(title) < 100:
  782. return title
  783. except Exception:
  784. pass
  785. # Fallback: 截取前 50 字符
  786. return raw_text[:50] + ("..." if len(raw_text) > 50 else "")
  787. def _format_skills(self, skills: List[Skill]) -> str:
  788. if not skills:
  789. return ""
  790. return "\n\n".join(s.to_prompt_text() for s in skills)
  791. def _load_experiences(self) -> str:
  792. """从文件加载经验(./cache/experiences.md)"""
  793. if not self.experiences_path:
  794. return ""
  795. try:
  796. if os.path.exists(self.experiences_path):
  797. with open(self.experiences_path, "r", encoding="utf-8") as f:
  798. return f.read().strip()
  799. except Exception as e:
  800. logger.warning(f"Failed to load experiences from {self.experiences_path}: {e}")
  801. return ""