runner.py 103 KB

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