runner.py 70 KB

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