runner.py 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295
  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.trace.compaction import (
  26. CompressionConfig,
  27. filter_by_goal_status,
  28. estimate_tokens,
  29. needs_level2_compression,
  30. build_compression_prompt,
  31. )
  32. from agent.skill.models import Skill
  33. from agent.skill.skill_loader import load_skills_from_dir
  34. from agent.tools import ToolRegistry, get_tool_registry
  35. from agent.tools.builtin.knowledge import KnowledgeConfig
  36. from agent.core.prompts import (
  37. DEFAULT_SYSTEM_PREFIX,
  38. TRUNCATION_HINT,
  39. TOOL_INTERRUPTED_MESSAGE,
  40. AGENT_INTERRUPTED_SUMMARY,
  41. AGENT_CONTINUE_HINT_TEMPLATE,
  42. TASK_NAME_GENERATION_SYSTEM_PROMPT,
  43. TASK_NAME_FALLBACK,
  44. SUMMARY_HEADER_TEMPLATE,
  45. build_summary_header,
  46. build_tool_interrupted_message,
  47. build_agent_continue_hint,
  48. )
  49. logger = logging.getLogger(__name__)
  50. @dataclass
  51. class ContextUsage:
  52. """Context 使用情况"""
  53. trace_id: str
  54. message_count: int
  55. token_count: int
  56. max_tokens: int
  57. usage_percent: float
  58. image_count: int = 0
  59. @dataclass
  60. class SideBranchContext:
  61. """侧分支上下文(压缩/反思)"""
  62. type: Literal["compression", "reflection"]
  63. branch_id: str
  64. start_head_seq: int # 侧分支起点的 head_seq
  65. start_sequence: int # 侧分支第一条消息的 sequence
  66. start_history_length: int # 侧分支起点的 history 长度
  67. start_iteration: int # 侧分支开始时的 iteration
  68. max_turns: int = 5 # 最大轮次
  69. def to_dict(self) -> Dict[str, Any]:
  70. """转换为字典(用于持久化和传递给工具)"""
  71. return {
  72. "type": self.type,
  73. "branch_id": self.branch_id,
  74. "start_head_seq": self.start_head_seq,
  75. "start_sequence": self.start_sequence,
  76. "start_iteration": self.start_iteration,
  77. "max_turns": self.max_turns,
  78. "is_side_branch": True,
  79. "started_at": datetime.now().isoformat(),
  80. }
  81. # ===== 运行配置 =====
  82. @dataclass
  83. class RunConfig:
  84. """
  85. 运行参数 — 控制 Agent 如何执行
  86. 分为模型层参数(由上游 agent 或用户决定)和框架层参数(由系统注入)。
  87. """
  88. # --- 模型层参数 ---
  89. model: str = "gpt-4o"
  90. temperature: float = 0.3
  91. max_iterations: int = 200
  92. tools: Optional[List[str]] = None # None = 全部已注册工具
  93. side_branch_max_turns: int = 5 # 侧分支最大轮次(压缩/反思)
  94. # --- 强制侧分支(用于 API 手动触发或自动压缩流程)---
  95. # 使用列表作为侧分支队列,每次完成一个侧分支后 pop(0) 取下一个
  96. force_side_branch: Optional[List[Literal["compression", "reflection"]]] = None
  97. # --- 框架层参数 ---
  98. agent_type: str = "default"
  99. uid: Optional[str] = None
  100. system_prompt: Optional[str] = None # None = 从 skills 自动构建
  101. skills: Optional[List[str]] = None # 注入 system prompt 的 skill 名称列表;None = 按 preset 决定
  102. enable_memory: bool = True
  103. auto_execute_tools: bool = True
  104. name: Optional[str] = None # 显示名称(空则由 utility_llm 自动生成)
  105. enable_prompt_caching: bool = True # 启用 Anthropic Prompt Caching(仅 Claude 模型有效)
  106. # --- Trace 控制 ---
  107. trace_id: Optional[str] = None # None = 新建
  108. parent_trace_id: Optional[str] = None # 子 Agent 专用
  109. parent_goal_id: Optional[str] = None
  110. # --- 续跑控制 ---
  111. after_sequence: Optional[int] = None # 从哪条消息后续跑(message sequence)
  112. # --- 额外 LLM 参数(传给 llm_call 的 **kwargs)---
  113. extra_llm_params: Dict[str, Any] = field(default_factory=dict)
  114. # --- 自定义元数据上下文 ---
  115. context: Dict[str, Any] = field(default_factory=dict)
  116. # --- 研究流程控制 ---
  117. enable_research_flow: bool = True # 是否启用自动研究流程(知识检索→经验检索→调研→计划)
  118. # --- 知识管理配置 ---
  119. knowledge: KnowledgeConfig = field(default_factory=KnowledgeConfig)
  120. # 内置工具列表(始终自动加载)
  121. BUILTIN_TOOLS = [
  122. # 文件操作工具
  123. "read_file",
  124. "edit_file",
  125. "write_file",
  126. "glob_files",
  127. "grep_content",
  128. # 系统工具
  129. "bash_command",
  130. # 技能和目标管理
  131. "skill",
  132. "list_skills",
  133. "goal",
  134. "agent",
  135. "evaluate",
  136. "get_current_context",
  137. # 搜索工具
  138. "search_posts",
  139. "get_search_suggestions",
  140. # 知识管理工具
  141. "knowledge_search",
  142. "knowledge_save",
  143. "knowledge_update",
  144. "knowledge_batch_update",
  145. "knowledge_list",
  146. "knowledge_slim",
  147. # 沙箱工具
  148. # "sandbox_create_environment",
  149. # "sandbox_run_shell",
  150. # "sandbox_rebuild_with_ports",
  151. # "sandbox_destroy_environment",
  152. # 浏览器工具
  153. "browser_get_live_url",
  154. "browser_navigate_to_url",
  155. "browser_search_web",
  156. "browser_go_back",
  157. "browser_wait",
  158. "browser_click_element",
  159. "browser_input_text",
  160. "browser_send_keys",
  161. "browser_upload_file",
  162. "browser_scroll_page",
  163. "browser_find_text",
  164. "browser_screenshot",
  165. "browser_switch_tab",
  166. "browser_close_tab",
  167. "browser_get_dropdown_options",
  168. "browser_select_dropdown_option",
  169. "browser_extract_content",
  170. "browser_read_long_content",
  171. "browser_download_direct_url",
  172. "browser_get_page_html",
  173. "browser_get_visual_selector_map",
  174. "browser_evaluate",
  175. "browser_ensure_login_with_cookies",
  176. # 可以暂时由飞书消息替代
  177. #"browser_wait_for_user_action",
  178. "browser_done",
  179. "browser_export_cookies",
  180. "browser_load_cookies",
  181. # 飞书工具
  182. "feishu_send_message_to_contact",
  183. "feishu_get_chat_history",
  184. "feishu_get_contact_replies",
  185. "feishu_get_contact_list",
  186. ]
  187. @dataclass
  188. class CallResult:
  189. """单次调用结果"""
  190. reply: str
  191. tool_calls: Optional[List[Dict]] = None
  192. trace_id: Optional[str] = None
  193. step_id: Optional[str] = None
  194. tokens: Optional[Dict[str, int]] = None
  195. cost: float = 0.0
  196. # ===== 执行引擎 =====
  197. CONTEXT_INJECTION_INTERVAL = 10 # 每 N 轮注入一次 GoalTree + Collaborators
  198. class AgentRunner:
  199. """
  200. Agent 执行引擎
  201. 支持三种运行模式(通过 RunConfig 区分):
  202. 1. 新建:trace_id=None
  203. 2. 续跑:trace_id=已有ID, after_sequence=None 或 == head
  204. 3. 回溯:trace_id=已有ID, after_sequence=N(N < head_sequence)
  205. """
  206. def __init__(
  207. self,
  208. trace_store: Optional[TraceStore] = None,
  209. tool_registry: Optional[ToolRegistry] = None,
  210. llm_call: Optional[Callable] = None,
  211. utility_llm_call: Optional[Callable] = None,
  212. skills_dir: Optional[str] = None,
  213. goal_tree: Optional[GoalTree] = None,
  214. debug: bool = False,
  215. ):
  216. """
  217. 初始化 AgentRunner
  218. Args:
  219. trace_store: Trace 存储
  220. tool_registry: 工具注册表(默认使用全局注册表)
  221. llm_call: 主 LLM 调用函数
  222. utility_llm_call: 轻量 LLM(用于生成任务标题等),可选
  223. skills_dir: Skills 目录路径
  224. goal_tree: 初始 GoalTree(可选)
  225. debug: 保留参数(已废弃)
  226. """
  227. self.trace_store = trace_store
  228. self.tools = tool_registry or get_tool_registry()
  229. self.llm_call = llm_call
  230. self.utility_llm_call = utility_llm_call
  231. self.skills_dir = skills_dir
  232. self.goal_tree = goal_tree
  233. self.debug = debug
  234. self._cancel_events: Dict[str, asyncio.Event] = {} # trace_id → cancel event
  235. # 知识保存跟踪(每个 trace 独立)
  236. self._saved_knowledge_ids: Dict[str, List[str]] = {} # trace_id → [knowledge_ids]
  237. # Context 使用跟踪
  238. self._context_warned: Dict[str, set] = {} # trace_id → {30, 50, 80} 已警告过的阈值
  239. self._context_usage: Dict[str, ContextUsage] = {} # trace_id → 当前用量快照
  240. # ===== 核心公开方法 =====
  241. def get_context_usage(self, trace_id: str) -> Optional[ContextUsage]:
  242. """获取指定 trace 的 context 使用情况"""
  243. return self._context_usage.get(trace_id)
  244. async def run(
  245. self,
  246. messages: List[Dict],
  247. config: Optional[RunConfig] = None,
  248. ) -> AsyncIterator[Union[Trace, Message]]:
  249. """
  250. Agent 模式执行(核心方法)
  251. Args:
  252. messages: OpenAI SDK 格式的输入消息
  253. 新建: 初始任务消息 [{"role": "user", "content": "..."}]
  254. 续跑: 追加的新消息
  255. 回溯: 在插入点之后追加的消息
  256. config: 运行配置
  257. Yields:
  258. Union[Trace, Message]: Trace 对象(状态变化)或 Message 对象(执行过程)
  259. """
  260. if not self.llm_call:
  261. raise ValueError("llm_call function not provided")
  262. config = config or RunConfig()
  263. trace = None
  264. try:
  265. # Phase 1: PREPARE TRACE
  266. trace, goal_tree, sequence = await self._prepare_trace(messages, config)
  267. # 注册取消事件
  268. self._cancel_events[trace.trace_id] = asyncio.Event()
  269. yield trace
  270. # 检查是否有未完成的侧分支(用于用户追加消息场景)
  271. side_branch_ctx_for_build: Optional[SideBranchContext] = None
  272. if trace.context.get("active_side_branch") and messages:
  273. side_branch_data = trace.context["active_side_branch"]
  274. # 创建侧分支上下文(用于标记用户追加的消息)
  275. side_branch_ctx_for_build = SideBranchContext(
  276. type=side_branch_data["type"],
  277. branch_id=side_branch_data["branch_id"],
  278. start_head_seq=side_branch_data["start_head_seq"],
  279. start_sequence=side_branch_data["start_sequence"],
  280. start_history_length=0,
  281. start_iteration=side_branch_data.get("start_iteration", 0),
  282. max_turns=side_branch_data.get("max_turns", config.side_branch_max_turns),
  283. )
  284. # Phase 2: BUILD HISTORY
  285. history, sequence, created_messages, head_seq = await self._build_history(
  286. trace.trace_id, messages, goal_tree, config, sequence, side_branch_ctx_for_build
  287. )
  288. # Update trace's head_sequence in memory
  289. trace.head_sequence = head_seq
  290. for msg in created_messages:
  291. yield msg
  292. # Phase 3: AGENT LOOP
  293. async for event in self._agent_loop(trace, history, goal_tree, config, sequence):
  294. yield event
  295. except Exception as e:
  296. logger.error(f"Agent run failed: {e}")
  297. tid = config.trace_id or (trace.trace_id if trace else None)
  298. if self.trace_store and tid:
  299. # 读取当前 last_sequence 作为 head_sequence,确保续跑时能加载完整历史
  300. current = await self.trace_store.get_trace(tid)
  301. head_seq = current.last_sequence if current else None
  302. await self.trace_store.update_trace(
  303. tid,
  304. status="failed",
  305. head_sequence=head_seq,
  306. error_message=str(e),
  307. completed_at=datetime.now()
  308. )
  309. trace_obj = await self.trace_store.get_trace(tid)
  310. if trace_obj:
  311. yield trace_obj
  312. raise
  313. finally:
  314. # 清理取消事件
  315. if trace:
  316. self._cancel_events.pop(trace.trace_id, None)
  317. async def run_result(
  318. self,
  319. messages: List[Dict],
  320. config: Optional[RunConfig] = None,
  321. on_event: Optional[Callable] = None,
  322. ) -> Dict[str, Any]:
  323. """
  324. 结果模式 — 消费 run(),返回结构化结果。
  325. 主要用于 agent/evaluate 工具内部。
  326. Args:
  327. on_event: 可选回调,每个 Trace/Message 事件触发一次,用于实时输出子 Agent 执行过程。
  328. """
  329. last_assistant_text = ""
  330. final_trace: Optional[Trace] = None
  331. async for item in self.run(messages=messages, config=config):
  332. if on_event:
  333. on_event(item)
  334. if isinstance(item, Message) and item.role == "assistant":
  335. content = item.content
  336. text = ""
  337. if isinstance(content, dict):
  338. text = content.get("text", "") or ""
  339. elif isinstance(content, str):
  340. text = content
  341. if text and text.strip():
  342. last_assistant_text = text
  343. elif isinstance(item, Trace):
  344. final_trace = item
  345. config = config or RunConfig()
  346. if not final_trace and config.trace_id and self.trace_store:
  347. final_trace = await self.trace_store.get_trace(config.trace_id)
  348. status = final_trace.status if final_trace else "unknown"
  349. error = final_trace.error_message if final_trace else None
  350. summary = last_assistant_text
  351. if not summary:
  352. status = "failed"
  353. error = error or "Agent 没有产生 assistant 文本结果"
  354. # 获取保存的知识 ID
  355. trace_id = final_trace.trace_id if final_trace else config.trace_id
  356. saved_knowledge_ids = self._saved_knowledge_ids.get(trace_id, [])
  357. return {
  358. "status": status,
  359. "summary": summary,
  360. "trace_id": trace_id,
  361. "error": error,
  362. "saved_knowledge_ids": saved_knowledge_ids, # 新增:返回保存的知识 ID
  363. "stats": {
  364. "total_messages": final_trace.total_messages if final_trace else 0,
  365. "total_tokens": final_trace.total_tokens if final_trace else 0,
  366. "total_cost": final_trace.total_cost if final_trace else 0.0,
  367. },
  368. }
  369. async def stop(self, trace_id: str) -> bool:
  370. """
  371. 停止运行中的 Trace
  372. 设置取消信号,agent loop 在下一个 LLM 调用前检查并退出。
  373. Trace 状态置为 "stopped"。
  374. Returns:
  375. True 如果成功发送停止信号,False 如果该 trace 不在运行中
  376. """
  377. cancel_event = self._cancel_events.get(trace_id)
  378. if cancel_event is None:
  379. return False
  380. cancel_event.set()
  381. return True
  382. # ===== 单次调用(保留)=====
  383. async def call(
  384. self,
  385. messages: List[Dict],
  386. model: str = "gpt-4o",
  387. tools: Optional[List[str]] = None,
  388. uid: Optional[str] = None,
  389. trace: bool = True,
  390. **kwargs
  391. ) -> CallResult:
  392. """
  393. 单次 LLM 调用(无 Agent Loop)
  394. """
  395. if not self.llm_call:
  396. raise ValueError("llm_call function not provided")
  397. trace_id = None
  398. message_id = None
  399. tool_schemas = self._get_tool_schemas(tools)
  400. if trace and self.trace_store:
  401. trace_obj = Trace.create(mode="call", uid=uid, model=model, tools=tool_schemas, llm_params=kwargs)
  402. trace_id = await self.trace_store.create_trace(trace_obj)
  403. result = await self.llm_call(messages=messages, model=model, tools=tool_schemas, **kwargs)
  404. if trace and self.trace_store and trace_id:
  405. msg = Message.create(
  406. trace_id=trace_id, role="assistant", sequence=1, goal_id=None,
  407. content={"text": result.get("content", ""), "tool_calls": result.get("tool_calls")},
  408. prompt_tokens=result.get("prompt_tokens", 0),
  409. completion_tokens=result.get("completion_tokens", 0),
  410. finish_reason=result.get("finish_reason"),
  411. cost=result.get("cost", 0),
  412. )
  413. message_id = await self.trace_store.add_message(msg)
  414. await self.trace_store.update_trace(trace_id, status="completed", completed_at=datetime.now())
  415. return CallResult(
  416. reply=result.get("content", ""),
  417. tool_calls=result.get("tool_calls"),
  418. trace_id=trace_id,
  419. step_id=message_id,
  420. tokens={"prompt": result.get("prompt_tokens", 0), "completion": result.get("completion_tokens", 0)},
  421. cost=result.get("cost", 0)
  422. )
  423. # ===== Phase 1: PREPARE TRACE =====
  424. async def _prepare_trace(
  425. self,
  426. messages: List[Dict],
  427. config: RunConfig,
  428. ) -> Tuple[Trace, Optional[GoalTree], int]:
  429. """
  430. 准备 Trace:创建新的或加载已有的
  431. Returns:
  432. (trace, goal_tree, next_sequence)
  433. """
  434. if config.trace_id:
  435. return await self._prepare_existing_trace(config)
  436. else:
  437. return await self._prepare_new_trace(messages, config)
  438. async def _prepare_new_trace(
  439. self,
  440. messages: List[Dict],
  441. config: RunConfig,
  442. ) -> Tuple[Trace, Optional[GoalTree], int]:
  443. """创建新 Trace"""
  444. trace_id = str(uuid.uuid4())
  445. # 生成任务名称
  446. task_name = config.name or await self._generate_task_name(messages)
  447. # 准备工具 Schema
  448. tool_schemas = self._get_tool_schemas(config.tools)
  449. trace_obj = Trace(
  450. trace_id=trace_id,
  451. mode="agent",
  452. task=task_name,
  453. agent_type=config.agent_type,
  454. parent_trace_id=config.parent_trace_id,
  455. parent_goal_id=config.parent_goal_id,
  456. uid=config.uid,
  457. model=config.model,
  458. tools=tool_schemas,
  459. llm_params={"temperature": config.temperature, **config.extra_llm_params},
  460. context=config.context,
  461. status="running",
  462. )
  463. goal_tree = self.goal_tree or GoalTree(mission=task_name)
  464. if self.trace_store:
  465. await self.trace_store.create_trace(trace_obj)
  466. await self.trace_store.update_goal_tree(trace_id, goal_tree)
  467. return trace_obj, goal_tree, 1
  468. async def _prepare_existing_trace(
  469. self,
  470. config: RunConfig,
  471. ) -> Tuple[Trace, Optional[GoalTree], int]:
  472. """加载已有 Trace(续跑或回溯)"""
  473. if not self.trace_store:
  474. raise ValueError("trace_store required for continue/rewind")
  475. trace_obj = await self.trace_store.get_trace(config.trace_id)
  476. if not trace_obj:
  477. raise ValueError(f"Trace not found: {config.trace_id}")
  478. goal_tree = await self.trace_store.get_goal_tree(config.trace_id)
  479. if goal_tree is None:
  480. # 防御性兜底:trace 存在但 goal.json 丢失时,创建空树
  481. goal_tree = GoalTree(mission=trace_obj.task or "Agent task")
  482. await self.trace_store.update_goal_tree(config.trace_id, goal_tree)
  483. # 自动判断行为:after_sequence 为 None 或 == head → 续跑;< head → 回溯
  484. after_seq = config.after_sequence
  485. # 如果 after_seq > head_sequence,说明 generator 被强制关闭时 store 的
  486. # head_sequence 未来得及更新(仍停在 Phase 2 写入的初始值)。
  487. # 用 last_sequence 修正 head_sequence,确保续跑时能看到完整历史。
  488. if after_seq is not None and after_seq > trace_obj.head_sequence:
  489. trace_obj.head_sequence = trace_obj.last_sequence
  490. await self.trace_store.update_trace(
  491. config.trace_id, head_sequence=trace_obj.head_sequence
  492. )
  493. if after_seq is not None and after_seq < trace_obj.head_sequence:
  494. # 回溯模式
  495. sequence = await self._rewind(config.trace_id, after_seq, goal_tree)
  496. else:
  497. # 续跑模式:从 last_sequence + 1 开始
  498. sequence = trace_obj.last_sequence + 1
  499. # 状态置为 running
  500. await self.trace_store.update_trace(
  501. config.trace_id,
  502. status="running",
  503. completed_at=None,
  504. )
  505. trace_obj.status = "running"
  506. # 广播状态变化给前端
  507. try:
  508. from agent.trace.websocket import broadcast_trace_status_changed
  509. await broadcast_trace_status_changed(config.trace_id, "running")
  510. except Exception:
  511. pass
  512. return trace_obj, goal_tree, sequence
  513. # ===== Phase 2: BUILD HISTORY =====
  514. async def _build_history(
  515. self,
  516. trace_id: str,
  517. new_messages: List[Dict],
  518. goal_tree: Optional[GoalTree],
  519. config: RunConfig,
  520. sequence: int,
  521. side_branch_ctx: Optional[SideBranchContext] = None,
  522. ) -> Tuple[List[Dict], int, List[Message], int]:
  523. """
  524. 构建完整的 LLM 消息历史
  525. 1. 从 head_sequence 沿 parent chain 加载主路径消息(续跑/回溯场景)
  526. 2. 构建 system prompt(新建时注入 skills)
  527. 3. 新建时:在第一条 user message 末尾注入当前经验
  528. 4. 追加 input messages(设置 parent_sequence 链接到当前 head)
  529. 5. 如果在侧分支中,追加的消息自动标记为侧分支消息
  530. Returns:
  531. (history, next_sequence, created_messages, head_sequence)
  532. created_messages: 本次新创建并持久化的 Message 列表,供 run() yield 给调用方
  533. head_sequence: 当前主路径头节点的 sequence
  534. """
  535. history: List[Dict] = []
  536. created_messages: List[Message] = []
  537. head_seq: Optional[int] = None # 当前主路径的头节点 sequence
  538. # 1. 加载已有 messages(通过主路径遍历)
  539. if config.trace_id and self.trace_store:
  540. trace_obj = await self.trace_store.get_trace(trace_id)
  541. if trace_obj and trace_obj.head_sequence > 0:
  542. main_path = await self.trace_store.get_main_path_messages(
  543. trace_id, trace_obj.head_sequence
  544. )
  545. # 修复 orphaned tool_calls(中断导致的 tool_call 无 tool_result)
  546. main_path, sequence = await self._heal_orphaned_tool_calls(
  547. main_path, trace_id, goal_tree, sequence,
  548. )
  549. history = [msg.to_llm_dict() for msg in main_path]
  550. if main_path:
  551. head_seq = main_path[-1].sequence
  552. # 2. 构建/注入 skills 到 system prompt
  553. has_system = any(m.get("role") == "system" for m in history)
  554. has_system_in_new = any(m.get("role") == "system" for m in new_messages)
  555. if not has_system:
  556. if has_system_in_new:
  557. # 入参消息已含 system,将 skills 注入其中(在 step 4 持久化之前)
  558. augmented = []
  559. for msg in new_messages:
  560. if msg.get("role") == "system":
  561. base = msg.get("content") or ""
  562. enriched = await self._build_system_prompt(config, base_prompt=base)
  563. augmented.append({**msg, "content": enriched or base})
  564. else:
  565. augmented.append(msg)
  566. new_messages = augmented
  567. else:
  568. # 没有 system,自动构建并插入历史
  569. system_prompt = await self._build_system_prompt(config)
  570. if system_prompt:
  571. history = [{"role": "system", "content": system_prompt}] + history
  572. if self.trace_store:
  573. system_msg = Message.create(
  574. trace_id=trace_id, role="system", sequence=sequence,
  575. goal_id=None, content=system_prompt,
  576. parent_sequence=None, # system message 是 root
  577. )
  578. await self.trace_store.add_message(system_msg)
  579. created_messages.append(system_msg)
  580. head_seq = sequence
  581. sequence += 1
  582. # 3. 追加新 messages(设置 parent_sequence 链接到当前 head)
  583. for msg_dict in new_messages:
  584. history.append(msg_dict)
  585. if self.trace_store:
  586. # 如果在侧分支中,标记为侧分支消息
  587. if side_branch_ctx:
  588. stored_msg = Message.create(
  589. trace_id=trace_id,
  590. role=msg_dict["role"],
  591. sequence=sequence,
  592. goal_id=goal_tree.current_id if goal_tree else None,
  593. parent_sequence=head_seq,
  594. branch_type=side_branch_ctx.type,
  595. branch_id=side_branch_ctx.branch_id,
  596. content=msg_dict.get("content"),
  597. )
  598. logger.info(f"用户在侧分支 {side_branch_ctx.type} 中追加消息")
  599. else:
  600. stored_msg = Message.from_llm_dict(
  601. msg_dict, trace_id=trace_id, sequence=sequence,
  602. goal_id=None, parent_sequence=head_seq,
  603. )
  604. await self.trace_store.add_message(stored_msg)
  605. created_messages.append(stored_msg)
  606. head_seq = sequence
  607. sequence += 1
  608. # 5. 更新 trace 的 head_sequence
  609. if self.trace_store and head_seq is not None:
  610. await self.trace_store.update_trace(trace_id, head_sequence=head_seq)
  611. return history, sequence, created_messages, head_seq or 0
  612. # ===== Phase 3: AGENT LOOP =====
  613. async def _manage_context_usage(
  614. self,
  615. trace_id: str,
  616. history: List[Dict],
  617. goal_tree: Optional[GoalTree],
  618. config: RunConfig,
  619. sequence: int,
  620. head_seq: int,
  621. ) -> Tuple[List[Dict], int, int, bool]:
  622. """
  623. 管理 context 用量:检查、预警、压缩
  624. Returns:
  625. (updated_history, new_head_seq, next_sequence, needs_enter_compression_branch)
  626. """
  627. compression_config = CompressionConfig()
  628. token_count = estimate_tokens(history)
  629. max_tokens = compression_config.get_max_tokens(config.model)
  630. # 计算使用率
  631. progress_pct = (token_count / max_tokens * 100) if max_tokens > 0 else 0
  632. msg_count = len(history)
  633. img_count = sum(
  634. 1 for msg in history
  635. if isinstance(msg.get("content"), list)
  636. for part in msg["content"]
  637. if isinstance(part, dict) and part.get("type") in ("image", "image_url")
  638. )
  639. # 更新 context usage 快照
  640. self._context_usage[trace_id] = ContextUsage(
  641. trace_id=trace_id,
  642. message_count=msg_count,
  643. token_count=token_count,
  644. max_tokens=max_tokens,
  645. usage_percent=progress_pct,
  646. image_count=img_count,
  647. )
  648. # 阈值警告(30%, 50%, 80%)
  649. if trace_id not in self._context_warned:
  650. self._context_warned[trace_id] = set()
  651. for threshold in [30, 50, 80]:
  652. if progress_pct >= threshold and threshold not in self._context_warned[trace_id]:
  653. self._context_warned[trace_id].add(threshold)
  654. logger.warning(
  655. f"Context 使用率达到 {threshold}%: {token_count:,} / {max_tokens:,} tokens ({msg_count} 条消息)"
  656. )
  657. # 检查是否需要压缩(token 或消息数量超限)
  658. needs_compression_by_tokens = token_count > max_tokens
  659. needs_compression_by_count = (
  660. compression_config.max_messages > 0 and
  661. msg_count > compression_config.max_messages
  662. )
  663. needs_compression = needs_compression_by_tokens or needs_compression_by_count
  664. if not needs_compression:
  665. return history, head_seq, sequence, False
  666. # 知识提取:在任何压缩发生前,用完整 history 做反思(进入反思侧分支)
  667. if config.knowledge.enable_extraction and not config.force_side_branch:
  668. # 设置侧分支队列:先反思,再压缩
  669. config.force_side_branch = ["reflection", "compression"]
  670. return history, head_seq, sequence, True
  671. # Level 1 压缩:GoalTree 过滤
  672. if self.trace_store and goal_tree:
  673. if head_seq > 0:
  674. main_path_msgs = await self.trace_store.get_main_path_messages(
  675. trace_id, head_seq
  676. )
  677. filtered_msgs = filter_by_goal_status(main_path_msgs, goal_tree)
  678. if len(filtered_msgs) < len(main_path_msgs):
  679. logger.info(
  680. "Level 1 压缩: %d -> %d 条消息",
  681. len(main_path_msgs), len(filtered_msgs),
  682. )
  683. history = [msg.to_llm_dict() for msg in filtered_msgs]
  684. else:
  685. logger.info(
  686. "Level 1 压缩: 无可过滤消息 (%d 条全部保留)",
  687. len(main_path_msgs),
  688. )
  689. elif needs_compression:
  690. logger.warning(
  691. "消息数 (%d) 或 token 数 (%d) 超过阈值,但无法执行 Level 1 压缩(缺少 store 或 goal_tree)",
  692. msg_count, token_count,
  693. )
  694. # Level 2 压缩:检查 Level 1 后是否仍超阈值
  695. token_count_after = estimate_tokens(history)
  696. msg_count_after = len(history)
  697. needs_level2_by_tokens = token_count_after > max_tokens
  698. needs_level2_by_count = (
  699. compression_config.max_messages > 0 and
  700. msg_count_after > compression_config.max_messages
  701. )
  702. needs_level2 = needs_level2_by_tokens or needs_level2_by_count
  703. if needs_level2:
  704. logger.info(
  705. "Level 1 后仍超阈值 (消息数=%d/%d, token=%d/%d),需要进入压缩侧分支",
  706. msg_count_after, compression_config.max_messages, token_count_after, max_tokens,
  707. )
  708. # 如果还没有设置侧分支(说明没有启用知识提取),直接进入压缩
  709. if not config.force_side_branch:
  710. config.force_side_branch = ["compression"]
  711. # 返回标志,让主循环进入侧分支
  712. return history, head_seq, sequence, True
  713. # 压缩完成后,输出最终发给模型的消息列表
  714. logger.info("Level 1 压缩完成,发送给模型的消息列表:")
  715. for idx, msg in enumerate(history):
  716. role = msg.get("role", "unknown")
  717. content = msg.get("content", "")
  718. if isinstance(content, str):
  719. preview = content[:100] + ("..." if len(content) > 100 else "")
  720. elif isinstance(content, list):
  721. preview = f"[{len(content)} blocks]"
  722. else:
  723. preview = str(content)[:100]
  724. logger.info(f" [{idx}] {role}: {preview}")
  725. return history, head_seq, sequence, False
  726. async def _single_turn_compress(
  727. self,
  728. trace_id: str,
  729. history: List[Dict],
  730. goal_tree: Optional[GoalTree],
  731. config: RunConfig,
  732. sequence: int,
  733. start_head_seq: int,
  734. ) -> Tuple[List[Dict], int, int]:
  735. """单次 LLM 调用压缩(fallback 方案)"""
  736. logger.info("执行单次 LLM 压缩(fallback)")
  737. # 构建压缩 prompt
  738. compress_prompt = build_compression_prompt(goal_tree)
  739. compress_messages = list(history) + [
  740. {"role": "user", "content": compress_prompt}
  741. ]
  742. # 应用 Prompt Caching
  743. compress_messages = self._add_cache_control(
  744. compress_messages, config.model, config.enable_prompt_caching
  745. )
  746. # 单次 LLM 调用(无工具)
  747. result = await self.llm_call(
  748. messages=compress_messages,
  749. model=config.model,
  750. tools=[], # 不提供工具
  751. temperature=config.temperature,
  752. **config.extra_llm_params,
  753. )
  754. summary_text = result.get("content", "").strip()
  755. # 提取 [[SUMMARY]] 块
  756. if "[[SUMMARY]]" in summary_text:
  757. summary_text = summary_text[
  758. summary_text.index("[[SUMMARY]]") + len("[[SUMMARY]]"):
  759. ].strip()
  760. if not summary_text:
  761. logger.warning("单次压缩未返回有效内容,跳过压缩")
  762. return history, start_head_seq, sequence
  763. # 创建 summary 消息
  764. from agent.core.prompts import build_summary_header
  765. summary_msg = Message.create(
  766. trace_id=trace_id,
  767. role="user",
  768. sequence=sequence,
  769. parent_sequence=start_head_seq,
  770. branch_type=None, # 主路径
  771. content=build_summary_header(summary_text),
  772. )
  773. if self.trace_store:
  774. await self.trace_store.add_message(summary_msg)
  775. # 重建 history
  776. system_msg = history[0] if history and history[0].get("role") == "system" else None
  777. new_history = [system_msg, summary_msg.to_llm_dict()] if system_msg else [summary_msg.to_llm_dict()]
  778. new_head_seq = sequence
  779. sequence += 1
  780. logger.info(f"单次压缩完成: {len(history)} → {len(new_history)} 条消息")
  781. return new_history, new_head_seq, sequence
  782. async def _agent_loop(
  783. self,
  784. trace: Trace,
  785. history: List[Dict],
  786. goal_tree: Optional[GoalTree],
  787. config: RunConfig,
  788. sequence: int,
  789. ) -> AsyncIterator[Union[Trace, Message]]:
  790. """ReAct 循环"""
  791. trace_id = trace.trace_id
  792. tool_schemas = self._get_tool_schemas(config.tools)
  793. # 当前主路径头节点的 sequence(用于设置 parent_sequence)
  794. head_seq = trace.head_sequence
  795. # 侧分支状态(None = 主路径)
  796. side_branch_ctx: Optional[SideBranchContext] = None
  797. # 检查是否有未完成的侧分支需要恢复
  798. if trace.context.get("active_side_branch"):
  799. side_branch_data = trace.context["active_side_branch"]
  800. branch_id = side_branch_data["branch_id"]
  801. # 从数据库查询侧分支消息
  802. if self.trace_store:
  803. all_messages = await self.trace_store.get_trace_messages(trace_id)
  804. side_messages = [
  805. m for m in all_messages
  806. if m.branch_id == branch_id
  807. ]
  808. # 恢复侧分支上下文
  809. side_branch_ctx = SideBranchContext(
  810. type=side_branch_data["type"],
  811. branch_id=branch_id,
  812. start_head_seq=side_branch_data["start_head_seq"],
  813. start_sequence=side_branch_data["start_sequence"],
  814. start_history_length=0, # 稍后重新计算
  815. start_iteration=side_branch_data.get("start_iteration", 0),
  816. max_turns=side_branch_data.get("max_turns", config.side_branch_max_turns),
  817. )
  818. logger.info(
  819. f"恢复未完成的侧分支: {side_branch_ctx.type}, "
  820. f"max_turns={side_branch_ctx.max_turns}"
  821. )
  822. # 将侧分支消息追加到 history
  823. for m in side_messages:
  824. history.append(m.to_llm_dict())
  825. # 重新计算 start_history_length
  826. side_branch_ctx.start_history_length = len(history) - len(side_messages)
  827. for iteration in range(config.max_iterations):
  828. # 更新活动时间(表明trace正在活跃运行)
  829. if self.trace_store:
  830. await self.trace_store.update_trace(
  831. trace_id,
  832. last_activity_at=datetime.now()
  833. )
  834. # 检查取消信号
  835. cancel_event = self._cancel_events.get(trace_id)
  836. if cancel_event and cancel_event.is_set():
  837. logger.info(f"Trace {trace_id} stopped by user")
  838. if self.trace_store:
  839. await self.trace_store.update_trace(
  840. trace_id,
  841. status="stopped",
  842. head_sequence=head_seq,
  843. completed_at=datetime.now(),
  844. )
  845. # 广播状态变化给前端
  846. try:
  847. from agent.trace.websocket import broadcast_trace_status_changed
  848. await broadcast_trace_status_changed(trace_id, "stopped")
  849. except Exception:
  850. pass
  851. trace_obj = await self.trace_store.get_trace(trace_id)
  852. if trace_obj:
  853. yield trace_obj
  854. return
  855. # Context 管理(仅主路径)
  856. needs_enter_side_branch = False
  857. if not side_branch_ctx:
  858. # 检查是否强制进入侧分支(API 手动触发)
  859. if config.force_side_branch:
  860. needs_enter_side_branch = True
  861. logger.info(f"强制进入侧分支: {config.force_side_branch}")
  862. else:
  863. # 正常的 context 管理逻辑
  864. history, head_seq, sequence, needs_enter_side_branch = await self._manage_context_usage(
  865. trace_id, history, goal_tree, config, sequence, head_seq
  866. )
  867. # 进入侧分支
  868. if needs_enter_side_branch and not side_branch_ctx:
  869. # 从队列中取出第一个侧分支类型
  870. if config.force_side_branch and isinstance(config.force_side_branch, list) and len(config.force_side_branch) > 0:
  871. branch_type = config.force_side_branch.pop(0)
  872. logger.info(f"从队列取出侧分支: {branch_type}, 剩余队列: {config.force_side_branch}")
  873. elif config.knowledge.enable_extraction:
  874. # 兼容旧的单值模式(如果 force_side_branch 是字符串)
  875. branch_type = "reflection"
  876. else:
  877. # 自动触发:压缩
  878. branch_type = "compression"
  879. branch_id = f"{branch_type}_{uuid.uuid4().hex[:8]}"
  880. side_branch_ctx = SideBranchContext(
  881. type=branch_type,
  882. branch_id=branch_id,
  883. start_head_seq=head_seq,
  884. start_sequence=sequence,
  885. start_history_length=len(history),
  886. start_iteration=iteration,
  887. max_turns=config.side_branch_max_turns,
  888. )
  889. # 持久化侧分支状态
  890. if self.trace_store:
  891. trace.context["active_side_branch"] = {
  892. "type": side_branch_ctx.type,
  893. "branch_id": side_branch_ctx.branch_id,
  894. "start_head_seq": side_branch_ctx.start_head_seq,
  895. "start_sequence": side_branch_ctx.start_sequence,
  896. "start_iteration": side_branch_ctx.start_iteration,
  897. "max_turns": side_branch_ctx.max_turns,
  898. "started_at": datetime.now().isoformat(),
  899. }
  900. await self.trace_store.update_trace(
  901. trace_id,
  902. context=trace.context
  903. )
  904. # 追加侧分支 prompt
  905. if branch_type == "reflection":
  906. prompt = config.knowledge.get_reflect_prompt()
  907. else: # compression
  908. from agent.trace.compaction import build_compression_prompt
  909. prompt = build_compression_prompt(goal_tree)
  910. branch_user_msg = Message.create(
  911. trace_id=trace_id,
  912. role="user",
  913. sequence=sequence,
  914. parent_sequence=head_seq,
  915. goal_id=goal_tree.current_id if goal_tree else None,
  916. branch_type=branch_type,
  917. branch_id=branch_id,
  918. content=prompt,
  919. )
  920. if self.trace_store:
  921. await self.trace_store.add_message(branch_user_msg)
  922. history.append(branch_user_msg.to_llm_dict())
  923. head_seq = sequence
  924. sequence += 1
  925. logger.info(f"进入侧分支: {branch_type}, branch_id={branch_id}")
  926. continue # 跳过本轮,下一轮开始侧分支
  927. # 构建 LLM messages(注入上下文)
  928. llm_messages = list(history)
  929. # 对历史消息应用 Prompt Caching
  930. llm_messages = self._add_cache_control(
  931. llm_messages,
  932. config.model,
  933. config.enable_prompt_caching
  934. )
  935. # 调用 LLM(等待完成后再检查 cancel 信号,不中断正在进行的调用)
  936. result = await self.llm_call(
  937. messages=llm_messages,
  938. model=config.model,
  939. tools=tool_schemas,
  940. temperature=config.temperature,
  941. **config.extra_llm_params,
  942. )
  943. response_content = result.get("content", "")
  944. tool_calls = result.get("tool_calls")
  945. finish_reason = result.get("finish_reason")
  946. prompt_tokens = result.get("prompt_tokens", 0)
  947. completion_tokens = result.get("completion_tokens", 0)
  948. step_cost = result.get("cost", 0)
  949. cache_creation_tokens = result.get("cache_creation_tokens")
  950. cache_read_tokens = result.get("cache_read_tokens")
  951. # 周期性自动注入上下文(仅主路径)
  952. if not side_branch_ctx and iteration % CONTEXT_INJECTION_INTERVAL == 0:
  953. # 检查是否已经调用了 get_current_context
  954. if tool_calls:
  955. has_context_call = any(
  956. tc.get("function", {}).get("name") == "get_current_context"
  957. for tc in tool_calls
  958. )
  959. else:
  960. has_context_call = False
  961. tool_calls = []
  962. if not has_context_call:
  963. # 手动添加 get_current_context 工具调用
  964. import uuid
  965. context_call_id = f"call_context_{uuid.uuid4().hex[:8]}"
  966. tool_calls.append({
  967. "id": context_call_id,
  968. "type": "function",
  969. "function": {"name": "get_current_context", "arguments": "{}"}
  970. })
  971. logger.info(f"[周期性注入] 自动添加 get_current_context 工具调用 (iteration={iteration})")
  972. # 按需自动创建 root goal(仅主路径)
  973. if not side_branch_ctx and goal_tree and not goal_tree.goals and tool_calls:
  974. has_goal_call = any(
  975. tc.get("function", {}).get("name") == "goal"
  976. for tc in tool_calls
  977. )
  978. logger.debug(f"[Auto Root Goal] Before tool execution: goal_tree.goals={len(goal_tree.goals)}, has_goal_call={has_goal_call}, tool_calls={[tc.get('function', {}).get('name') for tc in tool_calls]}")
  979. if not has_goal_call:
  980. mission = goal_tree.mission
  981. root_desc = mission[:200] if len(mission) > 200 else mission
  982. goal_tree.add_goals(
  983. descriptions=[root_desc],
  984. reasons=["系统自动创建:Agent 未显式创建目标"],
  985. parent_id=None
  986. )
  987. if self.trace_store:
  988. await self.trace_store.add_goal(trace_id, goal_tree.goals[0])
  989. await self.trace_store.update_goal_tree(trace_id, goal_tree)
  990. logger.info(f"自动创建 root goal: {goal_tree.goals[0].id}(未自动 focus,等待模型决定)")
  991. else:
  992. logger.debug(f"[Auto Root Goal] 检测到 goal 工具调用,跳过自动创建")
  993. # 获取当前 goal_id
  994. current_goal_id = goal_tree.current_id if (goal_tree and goal_tree.current_id) else None
  995. # 记录 assistant Message(parent_sequence 指向当前 head)
  996. assistant_msg = Message.create(
  997. trace_id=trace_id,
  998. role="assistant",
  999. sequence=sequence,
  1000. goal_id=current_goal_id,
  1001. parent_sequence=head_seq if head_seq > 0 else None,
  1002. branch_type=side_branch_ctx.type if side_branch_ctx else None,
  1003. branch_id=side_branch_ctx.branch_id if side_branch_ctx else None,
  1004. content={"text": response_content, "tool_calls": tool_calls},
  1005. prompt_tokens=prompt_tokens,
  1006. completion_tokens=completion_tokens,
  1007. cache_creation_tokens=cache_creation_tokens,
  1008. cache_read_tokens=cache_read_tokens,
  1009. finish_reason=finish_reason,
  1010. cost=step_cost,
  1011. )
  1012. if self.trace_store:
  1013. await self.trace_store.add_message(assistant_msg)
  1014. # 记录模型使用
  1015. await self.trace_store.record_model_usage(
  1016. trace_id=trace_id,
  1017. sequence=sequence,
  1018. role="assistant",
  1019. model=config.model,
  1020. prompt_tokens=prompt_tokens,
  1021. completion_tokens=completion_tokens,
  1022. cache_read_tokens=cache_read_tokens or 0,
  1023. )
  1024. # 如果在侧分支,记录到 assistant_msg(已持久化,不需要额外维护)
  1025. yield assistant_msg
  1026. head_seq = sequence
  1027. sequence += 1
  1028. # 检查侧分支是否应该退出
  1029. if side_branch_ctx:
  1030. # 计算侧分支已执行的轮次
  1031. turns_in_branch = iteration - side_branch_ctx.start_iteration
  1032. # 检查是否达到最大轮次
  1033. if turns_in_branch >= side_branch_ctx.max_turns:
  1034. logger.warning(
  1035. f"侧分支 {side_branch_ctx.type} 达到最大轮次 "
  1036. f"{side_branch_ctx.max_turns},强制退出"
  1037. )
  1038. if side_branch_ctx.type == "compression":
  1039. # 压缩侧分支:fallback 到单次 LLM 调用
  1040. logger.info("Fallback 到单次 LLM 压缩")
  1041. # 清除侧分支状态
  1042. trace.context.pop("active_side_branch", None)
  1043. if self.trace_store:
  1044. await self.trace_store.update_trace(
  1045. trace_id, context=trace.context
  1046. )
  1047. # 恢复到侧分支开始前的 history
  1048. if self.trace_store:
  1049. main_path_messages = await self.trace_store.get_main_path_messages(
  1050. trace_id, side_branch_ctx.start_head_seq
  1051. )
  1052. history = [m.to_llm_dict() for m in main_path_messages]
  1053. # 执行单次 LLM 压缩
  1054. history, head_seq, sequence = await self._single_turn_compress(
  1055. trace_id, history, goal_tree, config, sequence,
  1056. side_branch_ctx.start_head_seq
  1057. )
  1058. # 清除强制侧分支配置
  1059. config.force_side_branch = None
  1060. side_branch_ctx = None
  1061. continue
  1062. elif side_branch_ctx.type == "reflection":
  1063. # 反思侧分支:直接退出,不管结果
  1064. logger.info("反思侧分支超时,直接退出")
  1065. # 清除侧分支状态
  1066. trace.context.pop("active_side_branch", None)
  1067. # 队列中如果还有侧分支,保持 force_side_branch;否则清空
  1068. if not config.force_side_branch or len(config.force_side_branch) == 0:
  1069. config.force_side_branch = None
  1070. logger.info("反思超时,队列为空")
  1071. if self.trace_store:
  1072. await self.trace_store.update_trace(
  1073. trace_id, context=trace.context
  1074. )
  1075. # 恢复到侧分支开始前的 history
  1076. if self.trace_store:
  1077. main_path_messages = await self.trace_store.get_main_path_messages(
  1078. trace_id, side_branch_ctx.start_head_seq
  1079. )
  1080. history = [m.to_llm_dict() for m in main_path_messages]
  1081. head_seq = side_branch_ctx.start_head_seq
  1082. # 清除强制侧分支配置
  1083. config.force_side_branch = None
  1084. side_branch_ctx = None
  1085. continue
  1086. # 检查是否无工具调用(侧分支完成)
  1087. if not tool_calls:
  1088. logger.info(f"侧分支 {side_branch_ctx.type} 完成(无工具调用)")
  1089. # 提取结果
  1090. if side_branch_ctx.type == "compression":
  1091. # 从数据库查询侧分支消息并提取 summary
  1092. summary_text = ""
  1093. if self.trace_store:
  1094. all_messages = await self.trace_store.get_trace_messages(trace_id)
  1095. side_messages = [
  1096. m for m in all_messages
  1097. if m.branch_id == side_branch_ctx.branch_id
  1098. ]
  1099. for msg in side_messages:
  1100. if msg.role == "assistant" and isinstance(msg.content, dict):
  1101. text = msg.content.get("text", "")
  1102. if "[[SUMMARY]]" in text:
  1103. summary_text = text[text.index("[[SUMMARY]]") + len("[[SUMMARY]]"):].strip()
  1104. break
  1105. elif text:
  1106. summary_text = text
  1107. if not summary_text:
  1108. logger.warning("侧分支未生成有效 summary,使用默认")
  1109. summary_text = "压缩完成"
  1110. # 创建主路径的 summary 消息(末尾追加详细 GoalTree)
  1111. from agent.core.prompts import build_summary_header
  1112. summary_content = build_summary_header(summary_text)
  1113. # 追加详细 GoalTree(压缩后立即注入)
  1114. if goal_tree and goal_tree.goals:
  1115. goal_tree_detail = goal_tree.to_prompt(include_summary=True)
  1116. summary_content += f"\n\n## Current Plan\n\n{goal_tree_detail}"
  1117. summary_msg = Message.create(
  1118. trace_id=trace_id,
  1119. role="user",
  1120. sequence=sequence,
  1121. parent_sequence=side_branch_ctx.start_head_seq,
  1122. branch_type=None, # 回到主路径
  1123. content=summary_content,
  1124. )
  1125. if self.trace_store:
  1126. await self.trace_store.add_message(summary_msg)
  1127. # 重建 history
  1128. if self.trace_store:
  1129. main_path_messages = await self.trace_store.get_main_path_messages(
  1130. trace_id, side_branch_ctx.start_head_seq
  1131. )
  1132. history = [m.to_llm_dict() for m in main_path_messages]
  1133. history.append(summary_msg.to_llm_dict())
  1134. head_seq = sequence
  1135. sequence += 1
  1136. logger.info(f"压缩侧分支完成,history 长度: {len(history)}")
  1137. # 清除侧分支队列
  1138. config.force_side_branch = None
  1139. elif side_branch_ctx.type == "reflection":
  1140. # 反思侧分支:直接恢复主路径
  1141. logger.info("反思侧分支完成")
  1142. if self.trace_store:
  1143. main_path_messages = await self.trace_store.get_main_path_messages(
  1144. trace_id, side_branch_ctx.start_head_seq
  1145. )
  1146. history = [m.to_llm_dict() for m in main_path_messages]
  1147. head_seq = side_branch_ctx.start_head_seq
  1148. # 队列中如果还有侧分支,保持 force_side_branch;否则清空
  1149. if not config.force_side_branch or len(config.force_side_branch) == 0:
  1150. config.force_side_branch = None
  1151. logger.info("反思完成,队列为空")
  1152. # 清除侧分支状态
  1153. trace.context.pop("active_side_branch", None)
  1154. if self.trace_store:
  1155. await self.trace_store.update_trace(
  1156. trace_id,
  1157. context=trace.context,
  1158. head_sequence=head_seq,
  1159. )
  1160. # 注意:不在这里清除 force_side_branch,因为反思侧分支可能已经设置了下一个侧分支
  1161. # force_side_branch 的清除由各个分支类型自己处理
  1162. side_branch_ctx = None
  1163. continue
  1164. # 处理工具调用
  1165. # 截断兜底:finish_reason == "length" 说明响应被 max_tokens 截断,
  1166. # tool call 参数很可能不完整,不应执行,改为提示模型分批操作
  1167. if tool_calls and finish_reason == "length":
  1168. logger.warning(
  1169. "[Runner] 响应被 max_tokens 截断,跳过 %d 个不完整的 tool calls",
  1170. len(tool_calls),
  1171. )
  1172. truncation_hint = TRUNCATION_HINT
  1173. history.append({
  1174. "role": "assistant",
  1175. "content": response_content,
  1176. "tool_calls": tool_calls,
  1177. })
  1178. # 为每个被截断的 tool call 返回错误结果
  1179. for tc in tool_calls:
  1180. history.append({
  1181. "role": "tool",
  1182. "tool_call_id": tc["id"],
  1183. "content": truncation_hint,
  1184. })
  1185. continue
  1186. if tool_calls and config.auto_execute_tools:
  1187. history.append({
  1188. "role": "assistant",
  1189. "content": response_content,
  1190. "tool_calls": tool_calls,
  1191. })
  1192. for tc in tool_calls:
  1193. current_goal_id = goal_tree.current_id if (goal_tree and goal_tree.current_id) else None
  1194. tool_name = tc["function"]["name"]
  1195. tool_args = tc["function"]["arguments"]
  1196. if isinstance(tool_args, str):
  1197. tool_args = json.loads(tool_args) if tool_args.strip() else {}
  1198. elif tool_args is None:
  1199. tool_args = {}
  1200. # 记录工具调用(INFO 级别,显示参数)
  1201. args_str = json.dumps(tool_args, ensure_ascii=False)
  1202. args_display = args_str[:100] + "..." if len(args_str) > 100 else args_str
  1203. logger.info(f"[Tool Call] {tool_name}({args_display})")
  1204. tool_result = await self.tools.execute(
  1205. tool_name,
  1206. tool_args,
  1207. uid=config.uid or "",
  1208. context={
  1209. "store": self.trace_store,
  1210. "trace_id": trace_id,
  1211. "goal_id": current_goal_id,
  1212. "runner": self,
  1213. "goal_tree": goal_tree,
  1214. "knowledge_config": config.knowledge,
  1215. # 新增:侧分支信息
  1216. "side_branch": {
  1217. "type": side_branch_ctx.type,
  1218. "branch_id": side_branch_ctx.branch_id,
  1219. "is_side_branch": True,
  1220. "max_turns": side_branch_ctx.max_turns,
  1221. } if side_branch_ctx else None,
  1222. },
  1223. )
  1224. # 如果是 goal 工具,记录执行后的状态
  1225. if tool_name == "goal" and goal_tree:
  1226. logger.debug(f"[Goal Tool] After execution: goal_tree.goals={len(goal_tree.goals)}, current_id={goal_tree.current_id}")
  1227. # 跟踪保存的知识 ID
  1228. if tool_name == "knowledge_save" and isinstance(tool_result, dict):
  1229. metadata = tool_result.get("metadata", {})
  1230. knowledge_id = metadata.get("knowledge_id")
  1231. if knowledge_id:
  1232. if trace_id not in self._saved_knowledge_ids:
  1233. self._saved_knowledge_ids[trace_id] = []
  1234. self._saved_knowledge_ids[trace_id].append(knowledge_id)
  1235. logger.info(f"[Knowledge Tracking] 记录保存的知识 ID: {knowledge_id}")
  1236. # --- 支持多模态工具反馈 ---
  1237. # execute() 返回 dict{"text","images","tool_usage"} 或 str
  1238. # 统一为dict格式
  1239. if isinstance(tool_result, str):
  1240. tool_result = {"text": tool_result}
  1241. tool_text = tool_result.get("text", str(tool_result))
  1242. tool_images = tool_result.get("images", [])
  1243. tool_usage = tool_result.get("tool_usage") # 新增:提取tool_usage
  1244. # 处理多模态消息
  1245. if tool_images:
  1246. tool_result_text = tool_text
  1247. # 构建多模态消息格式
  1248. tool_content_for_llm = [{"type": "text", "text": tool_text}]
  1249. for img in tool_images:
  1250. if img.get("type") == "base64" and img.get("data"):
  1251. media_type = img.get("media_type", "image/png")
  1252. tool_content_for_llm.append({
  1253. "type": "image_url",
  1254. "image_url": {
  1255. "url": f"data:{media_type};base64,{img['data']}"
  1256. }
  1257. })
  1258. img_count = len(tool_content_for_llm) - 1 # 减去 text 块
  1259. print(f"[Runner] 多模态工具反馈: tool={tool_name}, images={img_count}, text_len={len(tool_result_text)}")
  1260. else:
  1261. tool_result_text = tool_text
  1262. tool_content_for_llm = tool_text
  1263. tool_msg = Message.create(
  1264. trace_id=trace_id,
  1265. role="tool",
  1266. sequence=sequence,
  1267. goal_id=current_goal_id,
  1268. parent_sequence=head_seq,
  1269. tool_call_id=tc["id"],
  1270. branch_type=side_branch_ctx.type if side_branch_ctx else None,
  1271. branch_id=side_branch_ctx.branch_id if side_branch_ctx else None,
  1272. # 存储完整内容:有图片时保留 list(含 image_url),纯文本时存字符串
  1273. content={"tool_name": tool_name, "result": tool_content_for_llm},
  1274. )
  1275. if self.trace_store:
  1276. await self.trace_store.add_message(tool_msg)
  1277. # 记录工具的模型使用
  1278. if tool_usage:
  1279. await self.trace_store.record_model_usage(
  1280. trace_id=trace_id,
  1281. sequence=sequence,
  1282. role="tool",
  1283. tool_name=tool_name,
  1284. model=tool_usage.get("model"),
  1285. prompt_tokens=tool_usage.get("prompt_tokens", 0),
  1286. completion_tokens=tool_usage.get("completion_tokens", 0),
  1287. cache_read_tokens=tool_usage.get("cache_read_tokens", 0),
  1288. )
  1289. # 截图单独存为同名 PNG 文件
  1290. if tool_images:
  1291. import base64 as b64mod
  1292. for img in tool_images:
  1293. if img.get("data"):
  1294. png_path = self.trace_store._get_messages_dir(trace_id) / f"{tool_msg.message_id}.png"
  1295. png_path.write_bytes(b64mod.b64decode(img["data"]))
  1296. print(f"[Runner] 截图已保存: {png_path.name}")
  1297. break # 只存第一张
  1298. # 如果在侧分支,tool_msg 已持久化(不需要额外维护)
  1299. yield tool_msg
  1300. head_seq = sequence
  1301. sequence += 1
  1302. history.append({
  1303. "role": "tool",
  1304. "tool_call_id": tc["id"],
  1305. "name": tool_name,
  1306. "content": tool_content_for_llm,
  1307. })
  1308. continue # 继续循环
  1309. # 无工具调用,任务完成
  1310. break
  1311. # 任务完成后复盘提取
  1312. if config.knowledge.enable_completion_extraction:
  1313. await self._extract_knowledge_on_completion(trace_id, history, config)
  1314. # 清理 trace 相关的跟踪数据
  1315. self._context_warned.pop(trace_id, None)
  1316. self._context_usage.pop(trace_id, None)
  1317. self._saved_knowledge_ids.pop(trace_id, None)
  1318. # 更新 head_sequence 并完成 Trace
  1319. if self.trace_store:
  1320. await self.trace_store.update_trace(
  1321. trace_id,
  1322. status="completed",
  1323. head_sequence=head_seq,
  1324. completed_at=datetime.now(),
  1325. )
  1326. trace_obj = await self.trace_store.get_trace(trace_id)
  1327. if trace_obj:
  1328. yield trace_obj
  1329. # ===== Level 2: LLM 压缩 =====
  1330. async def _compress_history(
  1331. self,
  1332. trace_id: str,
  1333. history: List[Dict],
  1334. goal_tree: Optional[GoalTree],
  1335. config: RunConfig,
  1336. sequence: int,
  1337. head_seq: int,
  1338. ) -> Tuple[List[Dict], int, int]:
  1339. """
  1340. Level 2 压缩:LLM 总结
  1341. Step 1: 压缩总结 — LLM 生成 summary
  1342. Step 2: 存储 summary 为新消息,parent_sequence 跳到 system msg
  1343. Step 3: 重建 history
  1344. Returns:
  1345. (new_history, new_head_seq, next_sequence)
  1346. """
  1347. logger.info("Level 2 压缩开始: trace=%s, 当前 history 长度=%d", trace_id, len(history))
  1348. # 找到 system message 的 sequence(主路径第一条消息)
  1349. system_msg_seq = None
  1350. system_msg_dict = None
  1351. if self.trace_store:
  1352. trace_obj = await self.trace_store.get_trace(trace_id)
  1353. if trace_obj and trace_obj.head_sequence > 0:
  1354. main_path = await self.trace_store.get_main_path_messages(
  1355. trace_id, trace_obj.head_sequence
  1356. )
  1357. for msg in main_path:
  1358. if msg.role == "system":
  1359. system_msg_seq = msg.sequence
  1360. system_msg_dict = msg.to_llm_dict()
  1361. break
  1362. # Fallback: 从 history 中找 system message
  1363. if system_msg_dict is None:
  1364. for msg_dict in history:
  1365. if msg_dict.get("role") == "system":
  1366. system_msg_dict = msg_dict
  1367. break
  1368. if system_msg_dict is None:
  1369. logger.warning("Level 2 压缩跳过:未找到 system message")
  1370. return history, head_seq, sequence
  1371. # --- Step 1: 经验提取(reflect)---
  1372. try:
  1373. from agent.tools.builtin.knowledge import generate_and_save_reflection
  1374. await generate_and_save_reflection(
  1375. trace_id=trace_id,
  1376. messages=history,
  1377. llm_call_fn=self.llm_call,
  1378. model=config.model
  1379. )
  1380. except Exception as e:
  1381. logger.error(f"Level 2 经验提取失败: {e}")
  1382. # --- Step 2: 压缩总结 + 经验评估 ---
  1383. compress_prompt = build_compression_prompt(goal_tree)
  1384. compress_messages = list(history) + [{"role": "user", "content": compress_prompt}]
  1385. # 应用 Prompt Caching
  1386. compress_messages = self._add_cache_control(
  1387. compress_messages,
  1388. config.model,
  1389. config.enable_prompt_caching
  1390. )
  1391. compress_result = await self.llm_call(
  1392. messages=compress_messages,
  1393. model=config.model,
  1394. tools=[],
  1395. temperature=config.temperature,
  1396. **config.extra_llm_params,
  1397. )
  1398. raw_output = compress_result.get("content", "").strip()
  1399. if not raw_output:
  1400. logger.warning("Level 2 压缩跳过:LLM 未返回内容")
  1401. return history, head_seq, sequence
  1402. # 提取 [[SUMMARY]] 块
  1403. summary_text = raw_output
  1404. if "[[SUMMARY]]" in raw_output:
  1405. summary_text = raw_output[raw_output.index("[[SUMMARY]]") + len("[[SUMMARY]]"):].strip()
  1406. if not summary_text:
  1407. logger.warning("Level 2 压缩跳过:LLM 未返回 summary")
  1408. return history, head_seq, sequence
  1409. # --- Step 3: 存储 summary 消息 ---
  1410. summary_with_header = build_summary_header(summary_text)
  1411. summary_msg = Message.create(
  1412. trace_id=trace_id,
  1413. role="user",
  1414. sequence=sequence,
  1415. goal_id=None,
  1416. parent_sequence=system_msg_seq, # 跳到 system msg,跳过所有中间消息
  1417. content=summary_with_header,
  1418. )
  1419. if self.trace_store:
  1420. await self.trace_store.add_message(summary_msg)
  1421. new_head_seq = sequence
  1422. sequence += 1
  1423. # --- Step 4: 重建 history ---
  1424. new_history = [system_msg_dict, summary_msg.to_llm_dict()]
  1425. # 更新 trace head_sequence
  1426. if self.trace_store:
  1427. await self.trace_store.update_trace(
  1428. trace_id,
  1429. head_sequence=new_head_seq,
  1430. )
  1431. logger.info(
  1432. "Level 2 压缩完成: 旧 history %d 条 → 新 history %d 条, summary 长度=%d",
  1433. len(history), len(new_history), len(summary_text),
  1434. )
  1435. return new_history, new_head_seq, sequence
  1436. async def _run_reflect(
  1437. self,
  1438. trace_id: str,
  1439. history: List[Dict],
  1440. config: RunConfig,
  1441. reflect_prompt: str,
  1442. source_name: str,
  1443. ) -> None:
  1444. """
  1445. 执行反思提取:LLM 对历史消息进行反思,直接调用 knowledge_save 工具保存经验。
  1446. Args:
  1447. trace_id: Trace ID(作为知识的 message_id)
  1448. history: 当前对话历史
  1449. config: 运行配置
  1450. reflect_prompt: 反思 prompt
  1451. source_name: 来源名称(用于区分压缩时/完成时)
  1452. """
  1453. try:
  1454. reflect_messages = list(history) + [{"role": "user", "content": reflect_prompt}]
  1455. reflect_messages = self._add_cache_control(
  1456. reflect_messages, config.model, config.enable_prompt_caching
  1457. )
  1458. # 只暴露 knowledge_save 工具,让 LLM 直接调用
  1459. knowledge_save_schema = self._get_tool_schemas(["knowledge_save"])
  1460. reflect_result = await self.llm_call(
  1461. messages=reflect_messages,
  1462. model=config.model,
  1463. tools=knowledge_save_schema,
  1464. temperature=0.2,
  1465. **config.extra_llm_params,
  1466. )
  1467. tool_calls = reflect_result.get("tool_calls") or []
  1468. if not tool_calls:
  1469. logger.info("反思阶段无经验保存 (source=%s)", source_name)
  1470. return
  1471. saved_count = 0
  1472. for tc in tool_calls:
  1473. tool_name = tc.get("function", {}).get("name")
  1474. if tool_name != "knowledge_save":
  1475. continue
  1476. tool_args = tc.get("function", {}).get("arguments") or {}
  1477. if isinstance(tool_args, str):
  1478. tool_args = json.loads(tool_args) if tool_args.strip() else {}
  1479. # 注入来源信息(LLM 不需要填写这些字段)
  1480. tool_args.setdefault("source_name", source_name)
  1481. tool_args.setdefault("source_category", "exp")
  1482. tool_args.setdefault("message_id", trace_id)
  1483. try:
  1484. await self.tools.execute(
  1485. "knowledge_save",
  1486. tool_args,
  1487. uid=config.uid or "",
  1488. context={
  1489. "store": self.trace_store,
  1490. "trace_id": trace_id,
  1491. "knowledge_config": config.knowledge,
  1492. },
  1493. )
  1494. saved_count += 1
  1495. except Exception as e:
  1496. logger.warning("保存经验失败: %s", e)
  1497. logger.info("已提取并保存 %d 条经验 (source=%s)", saved_count, source_name)
  1498. except Exception as e:
  1499. logger.error("知识反思提取失败 (source=%s): %s", source_name, e)
  1500. async def _extract_knowledge_on_completion(
  1501. self,
  1502. trace_id: str,
  1503. history: List[Dict],
  1504. config: RunConfig,
  1505. ) -> None:
  1506. """任务完成后执行全局复盘,提取经验保存到知识库。"""
  1507. logger.info("任务完成后复盘提取: trace=%s", trace_id)
  1508. await self._run_reflect(
  1509. trace_id, history, config,
  1510. reflect_prompt=config.knowledge.get_completion_reflect_prompt(),
  1511. source_name="completion_reflection",
  1512. )
  1513. # ===== 回溯(Rewind)=====
  1514. async def _rewind(
  1515. self,
  1516. trace_id: str,
  1517. after_sequence: int,
  1518. goal_tree: Optional[GoalTree],
  1519. ) -> int:
  1520. """
  1521. 执行回溯:快照 GoalTree,重建干净树,设置 head_sequence
  1522. 新消息的 parent_sequence 将指向 rewind 点,旧消息通过树结构自然脱离主路径。
  1523. Returns:
  1524. 下一个可用的 sequence 号
  1525. """
  1526. if not self.trace_store:
  1527. raise ValueError("trace_store required for rewind")
  1528. # 1. 加载所有 messages(用于 safe cutoff 和 max sequence)
  1529. all_messages = await self.trace_store.get_trace_messages(trace_id)
  1530. if not all_messages:
  1531. return 1
  1532. # 2. 找到安全截断点(确保不截断在 tool_call 和 tool response 之间)
  1533. cutoff = self._find_safe_cutoff(all_messages, after_sequence)
  1534. # 3. 快照并重建 GoalTree
  1535. if goal_tree:
  1536. # 获取截断点消息的 created_at 作为时间界限
  1537. cutoff_msg = None
  1538. for msg in all_messages:
  1539. if msg.sequence == cutoff:
  1540. cutoff_msg = msg
  1541. break
  1542. cutoff_time = cutoff_msg.created_at if cutoff_msg else datetime.now()
  1543. # 快照到 events(含 head_sequence 供前端感知分支切换)
  1544. await self.trace_store.append_event(trace_id, "rewind", {
  1545. "after_sequence": cutoff,
  1546. "head_sequence": cutoff,
  1547. "goal_tree_snapshot": goal_tree.to_dict(),
  1548. })
  1549. # 按时间重建干净的 GoalTree
  1550. new_tree = goal_tree.rebuild_for_rewind(cutoff_time)
  1551. await self.trace_store.update_goal_tree(trace_id, new_tree)
  1552. # 更新内存中的引用
  1553. goal_tree.goals = new_tree.goals
  1554. goal_tree.current_id = new_tree.current_id
  1555. # 4. 更新 head_sequence 到 rewind 点
  1556. await self.trace_store.update_trace(trace_id, head_sequence=cutoff)
  1557. # 5. 返回 next sequence(全局递增,不复用)
  1558. max_seq = max((m.sequence for m in all_messages), default=0)
  1559. return max_seq + 1
  1560. def _find_safe_cutoff(self, messages: List[Message], after_sequence: int) -> int:
  1561. """
  1562. 找到安全的截断点。
  1563. 如果 after_sequence 指向一条带 tool_calls 的 assistant message,
  1564. 则自动扩展到其所有对应的 tool response 之后。
  1565. """
  1566. cutoff = after_sequence
  1567. # 找到 after_sequence 对应的 message
  1568. target_msg = None
  1569. for msg in messages:
  1570. if msg.sequence == after_sequence:
  1571. target_msg = msg
  1572. break
  1573. if not target_msg:
  1574. return cutoff
  1575. # 如果是 assistant 且有 tool_calls,找到所有对应的 tool responses
  1576. if target_msg.role == "assistant":
  1577. content = target_msg.content
  1578. if isinstance(content, dict) and content.get("tool_calls"):
  1579. tool_call_ids = set()
  1580. for tc in content["tool_calls"]:
  1581. if isinstance(tc, dict) and tc.get("id"):
  1582. tool_call_ids.add(tc["id"])
  1583. # 找到这些 tool_call 对应的 tool messages
  1584. for msg in messages:
  1585. if (msg.role == "tool" and msg.tool_call_id
  1586. and msg.tool_call_id in tool_call_ids):
  1587. cutoff = max(cutoff, msg.sequence)
  1588. return cutoff
  1589. async def _heal_orphaned_tool_calls(
  1590. self,
  1591. messages: List[Message],
  1592. trace_id: str,
  1593. goal_tree: Optional[GoalTree],
  1594. sequence: int,
  1595. ) -> tuple:
  1596. """
  1597. 检测并修复消息历史中的 orphaned tool_calls。
  1598. 当 agent 被 stop/crash 中断时,可能有 assistant 的 tool_calls 没有对应的
  1599. tool results(包括多 tool_call 部分完成的情况)。直接发给 LLM 会导致 400。
  1600. 修复策略:为每个缺失的 tool_result 插入合成的"中断通知"消息,而非裁剪。
  1601. - 普通工具:简短中断提示
  1602. - agent/evaluate:包含 sub_trace_id、执行统计、continue_from 指引
  1603. 合成消息持久化到 store,确保幂等(下次续跑不再触发)。
  1604. Returns:
  1605. (healed_messages, next_sequence)
  1606. """
  1607. if not messages:
  1608. return messages, sequence
  1609. # 收集所有 tool_call IDs → (assistant_msg, tool_call_dict)
  1610. tc_map: Dict[str, tuple] = {}
  1611. result_ids: set = set()
  1612. for msg in messages:
  1613. if msg.role == "assistant":
  1614. content = msg.content
  1615. if isinstance(content, dict) and content.get("tool_calls"):
  1616. for tc in content["tool_calls"]:
  1617. tc_id = tc.get("id")
  1618. if tc_id:
  1619. tc_map[tc_id] = (msg, tc)
  1620. elif msg.role == "tool" and msg.tool_call_id:
  1621. result_ids.add(msg.tool_call_id)
  1622. orphaned_ids = [tc_id for tc_id in tc_map if tc_id not in result_ids]
  1623. if not orphaned_ids:
  1624. return messages, sequence
  1625. logger.info(
  1626. "检测到 %d 个 orphaned tool_calls,生成合成中断通知",
  1627. len(orphaned_ids),
  1628. )
  1629. healed = list(messages)
  1630. head_seq = messages[-1].sequence
  1631. for tc_id in orphaned_ids:
  1632. assistant_msg, tc = tc_map[tc_id]
  1633. tool_name = tc.get("function", {}).get("name", "unknown")
  1634. if tool_name in ("agent", "evaluate"):
  1635. result_text = self._build_agent_interrupted_result(
  1636. tc, goal_tree, assistant_msg,
  1637. )
  1638. else:
  1639. result_text = build_tool_interrupted_message(tool_name)
  1640. synthetic_msg = Message.create(
  1641. trace_id=trace_id,
  1642. role="tool",
  1643. sequence=sequence,
  1644. goal_id=assistant_msg.goal_id,
  1645. parent_sequence=head_seq,
  1646. tool_call_id=tc_id,
  1647. content={"tool_name": tool_name, "result": result_text},
  1648. )
  1649. if self.trace_store:
  1650. await self.trace_store.add_message(synthetic_msg)
  1651. healed.append(synthetic_msg)
  1652. head_seq = sequence
  1653. sequence += 1
  1654. # 更新 trace head/last sequence
  1655. if self.trace_store:
  1656. await self.trace_store.update_trace(
  1657. trace_id,
  1658. head_sequence=head_seq,
  1659. last_sequence=max(head_seq, sequence - 1),
  1660. )
  1661. return healed, sequence
  1662. def _build_agent_interrupted_result(
  1663. self,
  1664. tc: Dict,
  1665. goal_tree: Optional[GoalTree],
  1666. assistant_msg: Message,
  1667. ) -> str:
  1668. """为中断的 agent/evaluate 工具调用构建合成结果(对齐正常返回值格式)"""
  1669. args_str = tc.get("function", {}).get("arguments", "{}")
  1670. try:
  1671. args = json.loads(args_str) if isinstance(args_str, str) else args_str
  1672. except json.JSONDecodeError:
  1673. args = {}
  1674. task = args.get("task", "未知任务")
  1675. if isinstance(task, list):
  1676. task = "; ".join(task)
  1677. tool_name = tc.get("function", {}).get("name", "agent")
  1678. mode = "evaluate" if tool_name == "evaluate" else "delegate"
  1679. # 从 goal_tree 查找 sub_trace 信息
  1680. sub_trace_id = None
  1681. stats = None
  1682. if goal_tree and assistant_msg.goal_id:
  1683. goal = goal_tree.find(assistant_msg.goal_id)
  1684. if goal and goal.sub_trace_ids:
  1685. first = goal.sub_trace_ids[0]
  1686. if isinstance(first, dict):
  1687. sub_trace_id = first.get("trace_id")
  1688. elif isinstance(first, str):
  1689. sub_trace_id = first
  1690. if goal.cumulative_stats:
  1691. s = goal.cumulative_stats
  1692. if s.message_count > 0:
  1693. stats = {
  1694. "message_count": s.message_count,
  1695. "total_tokens": s.total_tokens,
  1696. "total_cost": round(s.total_cost, 4),
  1697. }
  1698. result: Dict[str, Any] = {
  1699. "mode": mode,
  1700. "status": "interrupted",
  1701. "summary": AGENT_INTERRUPTED_SUMMARY,
  1702. "task": task,
  1703. }
  1704. if sub_trace_id:
  1705. result["sub_trace_id"] = sub_trace_id
  1706. result["hint"] = build_agent_continue_hint(sub_trace_id)
  1707. if stats:
  1708. result["stats"] = stats
  1709. return json.dumps(result, ensure_ascii=False, indent=2)
  1710. # ===== 上下文注入 =====
  1711. def _build_context_injection(
  1712. self,
  1713. trace: Trace,
  1714. goal_tree: Optional[GoalTree],
  1715. ) -> str:
  1716. """构建周期性注入的上下文(GoalTree + Active Collaborators + Focus 提醒)"""
  1717. parts = []
  1718. # GoalTree
  1719. if goal_tree and goal_tree.goals:
  1720. parts.append(f"## Current Plan\n\n{goal_tree.to_prompt()}")
  1721. if goal_tree.current_id:
  1722. # 检测 focus 在有子节点的父目标上:提醒模型 focus 到具体子目标
  1723. children = goal_tree.get_children(goal_tree.current_id)
  1724. pending_children = [c for c in children if c.status in ("pending", "in_progress")]
  1725. if pending_children:
  1726. child_ids = ", ".join(
  1727. goal_tree._generate_display_id(c) for c in pending_children[:3]
  1728. )
  1729. parts.append(
  1730. f"**提醒**:当前焦点在父目标上,建议用 `goal(focus=\"...\")` "
  1731. f"切换到具体子目标(如 {child_ids})再执行。"
  1732. )
  1733. else:
  1734. # 无焦点:提醒模型 focus
  1735. parts.append(
  1736. "**提醒**:当前没有焦点目标。请用 `goal(focus=\"...\")` 选择一个目标开始执行。"
  1737. )
  1738. # Active Collaborators
  1739. collaborators = trace.context.get("collaborators", [])
  1740. if collaborators:
  1741. lines = ["## Active Collaborators"]
  1742. for c in collaborators:
  1743. status_str = c.get("status", "unknown")
  1744. ctype = c.get("type", "agent")
  1745. summary = c.get("summary", "")
  1746. name = c.get("name", "unnamed")
  1747. lines.append(f"- {name} [{ctype}, {status_str}]: {summary}")
  1748. parts.append("\n".join(lines))
  1749. return "\n\n".join(parts)
  1750. # ===== 辅助方法 =====
  1751. def _add_cache_control(
  1752. self,
  1753. messages: List[Dict],
  1754. model: str,
  1755. enable: bool
  1756. ) -> List[Dict]:
  1757. """
  1758. 为支持的模型添加 Prompt Caching 标记
  1759. 策略:固定位置 + 延迟查找
  1760. 1. system message 添加缓存(如果足够长)
  1761. 2. 固定位置缓存点(20, 40, 60, 80),确保每个缓存点间隔 >= 1024 tokens
  1762. 3. 最多使用 4 个缓存点(含 system)
  1763. Args:
  1764. messages: 原始消息列表
  1765. model: 模型名称
  1766. enable: 是否启用缓存
  1767. Returns:
  1768. 添加了 cache_control 的消息列表(深拷贝)
  1769. """
  1770. if not enable:
  1771. return messages
  1772. # 只对 Claude 模型启用
  1773. if "claude" not in model.lower():
  1774. return messages
  1775. # 深拷贝避免修改原始数据
  1776. import copy
  1777. messages = copy.deepcopy(messages)
  1778. # 策略 1: 为 system message 添加缓存
  1779. system_cached = False
  1780. for msg in messages:
  1781. if msg.get("role") == "system":
  1782. content = msg.get("content", "")
  1783. if isinstance(content, str) and len(content) > 1000:
  1784. msg["content"] = [{
  1785. "type": "text",
  1786. "text": content,
  1787. "cache_control": {"type": "ephemeral"}
  1788. }]
  1789. system_cached = True
  1790. logger.debug(f"[Cache] 为 system message 添加缓存标记 (len={len(content)})")
  1791. break
  1792. # 策略 2: 固定位置缓存点
  1793. CACHE_INTERVAL = 20
  1794. MAX_POINTS = 3 if system_cached else 4
  1795. MIN_TOKENS = 1024
  1796. AVG_TOKENS_PER_MSG = 70
  1797. total_msgs = len(messages)
  1798. if total_msgs == 0:
  1799. return messages
  1800. cache_positions = []
  1801. last_cache_pos = 0
  1802. for i in range(1, MAX_POINTS + 1):
  1803. target_pos = i * CACHE_INTERVAL - 1 # 19, 39, 59, 79
  1804. if target_pos >= total_msgs:
  1805. break
  1806. # 从目标位置开始查找合适的 user/assistant 消息
  1807. for j in range(target_pos, total_msgs):
  1808. msg = messages[j]
  1809. if msg.get("role") not in ("user", "assistant"):
  1810. continue
  1811. content = msg.get("content", "")
  1812. if not content:
  1813. continue
  1814. # 检查 content 是否非空
  1815. is_valid = False
  1816. if isinstance(content, str):
  1817. is_valid = len(content) > 0
  1818. elif isinstance(content, list):
  1819. is_valid = any(
  1820. isinstance(block, dict) and
  1821. block.get("type") == "text" and
  1822. len(block.get("text", "")) > 0
  1823. for block in content
  1824. )
  1825. if not is_valid:
  1826. continue
  1827. # 检查 token 距离
  1828. msg_count = j - last_cache_pos
  1829. estimated_tokens = msg_count * AVG_TOKENS_PER_MSG
  1830. if estimated_tokens >= MIN_TOKENS:
  1831. cache_positions.append(j)
  1832. last_cache_pos = j
  1833. logger.debug(f"[Cache] 在位置 {j} 添加缓存点 (估算 {estimated_tokens} tokens)")
  1834. break
  1835. # 应用缓存标记
  1836. for idx in cache_positions:
  1837. msg = messages[idx]
  1838. content = msg.get("content", "")
  1839. if isinstance(content, str):
  1840. msg["content"] = [{
  1841. "type": "text",
  1842. "text": content,
  1843. "cache_control": {"type": "ephemeral"}
  1844. }]
  1845. logger.debug(f"[Cache] 为 message[{idx}] ({msg.get('role')}) 添加缓存标记")
  1846. elif isinstance(content, list):
  1847. # 在最后一个 text block 添加 cache_control
  1848. for block in reversed(content):
  1849. if isinstance(block, dict) and block.get("type") == "text":
  1850. block["cache_control"] = {"type": "ephemeral"}
  1851. logger.debug(f"[Cache] 为 message[{idx}] ({msg.get('role')}) 添加缓存标记")
  1852. break
  1853. logger.debug(
  1854. f"[Cache] 总消息: {total_msgs}, "
  1855. f"缓存点: {len(cache_positions)} at {cache_positions}"
  1856. )
  1857. return messages
  1858. def _get_tool_schemas(self, tools: Optional[List[str]]) -> List[Dict]:
  1859. """
  1860. 获取工具 Schema
  1861. - tools=None: 使用 registry 中全部已注册工具(含内置 + 外部注册的)
  1862. - tools=["a", "b"]: 在 BUILTIN_TOOLS 基础上追加指定工具
  1863. """
  1864. if tools is None:
  1865. # 全部已注册工具
  1866. tool_names = self.tools.get_tool_names()
  1867. else:
  1868. # BUILTIN_TOOLS + 显式指定的额外工具
  1869. tool_names = BUILTIN_TOOLS.copy()
  1870. for t in tools:
  1871. if t not in tool_names:
  1872. tool_names.append(t)
  1873. return self.tools.get_schemas(tool_names)
  1874. # 默认 system prompt 前缀(当 config.system_prompt 和前端都未提供 system message 时使用)
  1875. # 注意:此常量已迁移到 agent.core.prompts,这里保留引用以保持向后兼容
  1876. async def _build_system_prompt(self, config: RunConfig, base_prompt: Optional[str] = None) -> Optional[str]:
  1877. """构建 system prompt(注入 skills)
  1878. 优先级:
  1879. 1. config.skills 显式指定 → 按名称过滤
  1880. 2. config.skills 为 None → 查 preset 的默认 skills 列表
  1881. 3. preset 也无 skills(None)→ 加载全部(向后兼容)
  1882. Args:
  1883. base_prompt: 已有 system 内容(来自消息或 config.system_prompt),
  1884. None 时使用 config.system_prompt
  1885. """
  1886. from agent.core.presets import AGENT_PRESETS
  1887. system_prompt = base_prompt if base_prompt is not None else config.system_prompt
  1888. # 确定要加载哪些 skills
  1889. skills_filter: Optional[List[str]] = config.skills
  1890. if skills_filter is None:
  1891. preset = AGENT_PRESETS.get(config.agent_type)
  1892. if preset is not None:
  1893. skills_filter = preset.skills # 可能仍为 None(加载全部)
  1894. # 加载并过滤
  1895. all_skills = load_skills_from_dir(self.skills_dir)
  1896. if skills_filter is not None:
  1897. skills = [s for s in all_skills if s.name in skills_filter]
  1898. else:
  1899. skills = all_skills
  1900. skills_text = self._format_skills(skills) if skills else ""
  1901. if system_prompt:
  1902. if skills_text:
  1903. system_prompt += f"\n\n## Skills\n{skills_text}"
  1904. else:
  1905. system_prompt = DEFAULT_SYSTEM_PREFIX
  1906. if skills_text:
  1907. system_prompt += f"\n\n## Skills\n{skills_text}"
  1908. return system_prompt
  1909. async def _generate_task_name(self, messages: List[Dict]) -> str:
  1910. """生成任务名称:优先使用 utility_llm,fallback 到文本截取"""
  1911. # 提取 messages 中的文本内容
  1912. text_parts = []
  1913. for msg in messages:
  1914. content = msg.get("content", "")
  1915. if isinstance(content, str):
  1916. text_parts.append(content)
  1917. elif isinstance(content, list):
  1918. for part in content:
  1919. if isinstance(part, dict) and part.get("type") == "text":
  1920. text_parts.append(part.get("text", ""))
  1921. raw_text = " ".join(text_parts).strip()
  1922. if not raw_text:
  1923. return TASK_NAME_FALLBACK
  1924. # 尝试使用 utility_llm 生成标题
  1925. if self.utility_llm_call:
  1926. try:
  1927. result = await self.utility_llm_call(
  1928. messages=[
  1929. {"role": "system", "content": TASK_NAME_GENERATION_SYSTEM_PROMPT},
  1930. {"role": "user", "content": raw_text[:2000]},
  1931. ],
  1932. model="gpt-4o-mini", # 使用便宜模型
  1933. )
  1934. title = result.get("content", "").strip()
  1935. if title and len(title) < 100:
  1936. return title
  1937. except Exception:
  1938. pass
  1939. # Fallback: 截取前 50 字符
  1940. return raw_text[:50] + ("..." if len(raw_text) > 50 else "")
  1941. def _format_skills(self, skills: List[Skill]) -> str:
  1942. if not skills:
  1943. return ""
  1944. return "\n\n".join(s.to_prompt_text() for s in skills)