runner.py 70 KB

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