runner.py 73 KB

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