runner.py 132 KB

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