runner.py 90 KB

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