runner.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. """
  2. Agent Runner - Agent 执行引擎
  3. 核心职责:
  4. 1. 执行 Agent 任务(循环调用 LLM + 工具)
  5. 2. 记录执行图(Trace + Steps)
  6. 3. 检索和注入记忆(Experience + Skill)
  7. 4. 收集反馈,提取经验
  8. """
  9. import logging
  10. from dataclasses import dataclass, field
  11. from datetime import datetime
  12. from typing import AsyncIterator, Optional, Dict, Any, List, Callable, Literal
  13. from agent.events import AgentEvent
  14. from agent.trace import Trace, Step, TraceStore
  15. from agent.models.memory import Experience, Skill
  16. from agent.storage.protocols import MemoryStore, StateStore
  17. from agent.storage.skill_loader import load_skills_from_dir
  18. from agent.tools import ToolRegistry, get_tool_registry
  19. from agent.debug import dump_tree, dump_markdown
  20. logger = logging.getLogger(__name__)
  21. # 内置工具列表(始终自动加载)
  22. BUILTIN_TOOLS = [
  23. "read_file",
  24. "edit_file",
  25. "write_file",
  26. "glob_files",
  27. "grep_content",
  28. "bash_command",
  29. "skill",
  30. "list_skills",
  31. ]
  32. @dataclass
  33. class AgentConfig:
  34. """Agent 配置"""
  35. agent_type: str = "default"
  36. max_iterations: int = 10
  37. enable_memory: bool = True
  38. auto_execute_tools: bool = True
  39. @dataclass
  40. class CallResult:
  41. """单次调用结果"""
  42. reply: str
  43. tool_calls: Optional[List[Dict]] = None
  44. trace_id: Optional[str] = None
  45. step_id: Optional[str] = None
  46. tokens: Optional[Dict[str, int]] = None
  47. cost: float = 0.0
  48. class AgentRunner:
  49. """
  50. Agent 执行引擎
  51. 支持两种模式:
  52. 1. call(): 单次 LLM 调用(简洁 API)
  53. 2. run(): Agent 模式(循环 + 记忆 + 追踪)
  54. """
  55. def __init__(
  56. self,
  57. trace_store: Optional[TraceStore] = None,
  58. memory_store: Optional[MemoryStore] = None,
  59. state_store: Optional[StateStore] = None,
  60. tool_registry: Optional[ToolRegistry] = None,
  61. llm_call: Optional[Callable] = None,
  62. config: Optional[AgentConfig] = None,
  63. skills_dir: Optional[str] = None,
  64. debug: bool = False,
  65. ):
  66. """
  67. 初始化 AgentRunner
  68. Args:
  69. trace_store: Trace 存储(可选,不提供则不记录)
  70. memory_store: Memory 存储(可选,不提供则不使用记忆)
  71. state_store: State 存储(可选,用于任务状态)
  72. tool_registry: 工具注册表(可选,默认使用全局注册表)
  73. llm_call: LLM 调用函数(必须提供,用于实际调用 LLM)
  74. config: Agent 配置
  75. skills_dir: Skills 目录路径(可选,不提供则不加载 skills)
  76. debug: 是否启用 debug 模式(输出 step tree 到 .trace/tree.txt)
  77. """
  78. self.trace_store = trace_store
  79. self.memory_store = memory_store
  80. self.state_store = state_store
  81. self.tools = tool_registry or get_tool_registry()
  82. self.llm_call = llm_call
  83. self.config = config or AgentConfig()
  84. self.skills_dir = skills_dir
  85. self.debug = debug
  86. def _generate_id(self) -> str:
  87. """生成唯一 ID"""
  88. import uuid
  89. return str(uuid.uuid4())
  90. async def _dump_debug(self, trace_id: str) -> None:
  91. """Debug 模式下输出 step tree(txt + markdown 两种格式)"""
  92. if not self.debug or not self.trace_store:
  93. return
  94. trace = await self.trace_store.get_trace(trace_id)
  95. steps = await self.trace_store.get_trace_steps(trace_id)
  96. # 输出 tree.txt(简洁格式,兼容旧版)
  97. dump_tree(trace, steps)
  98. # 输出 tree.md(完整可折叠格式)
  99. dump_markdown(trace, steps)
  100. # ===== 单次调用 =====
  101. async def call(
  102. self,
  103. messages: List[Dict],
  104. model: str = "gpt-4o",
  105. tools: Optional[List[str]] = None,
  106. uid: Optional[str] = None,
  107. trace: bool = True,
  108. **kwargs
  109. ) -> CallResult:
  110. """
  111. 单次 LLM 调用
  112. Args:
  113. messages: 消息列表
  114. model: 模型名称
  115. tools: 工具名称列表
  116. uid: 用户 ID
  117. trace: 是否记录 Trace
  118. **kwargs: 其他参数传递给 LLM
  119. Returns:
  120. CallResult
  121. """
  122. if not self.llm_call:
  123. raise ValueError("llm_call function not provided")
  124. trace_id = None
  125. step_id = None
  126. # 创建 Trace
  127. if trace and self.trace_store:
  128. trace_obj = Trace.create(
  129. mode="call",
  130. uid=uid,
  131. context={"model": model}
  132. )
  133. trace_id = await self.trace_store.create_trace(trace_obj)
  134. # 准备工具 Schema
  135. # 合并内置工具 + 用户指定工具
  136. tool_names = BUILTIN_TOOLS.copy()
  137. if tools:
  138. # 添加用户指定的工具(去重)
  139. for tool in tools:
  140. if tool not in tool_names:
  141. tool_names.append(tool)
  142. tool_schemas = self.tools.get_schemas(tool_names)
  143. # 调用 LLM
  144. result = await self.llm_call(
  145. messages=messages,
  146. model=model,
  147. tools=tool_schemas,
  148. **kwargs
  149. )
  150. # 记录 Step
  151. if trace and self.trace_store and trace_id:
  152. step = Step.create(
  153. trace_id=trace_id,
  154. step_type="thought",
  155. sequence=0,
  156. status="completed",
  157. description=f"LLM 调用 ({model})",
  158. data={
  159. "messages": messages,
  160. "response": result.get("content", ""),
  161. "model": model,
  162. "tools": tool_schemas, # 记录传给模型的 tools schema
  163. "tool_calls": result.get("tool_calls"),
  164. },
  165. tokens=result.get("prompt_tokens", 0) + result.get("completion_tokens", 0),
  166. cost=result.get("cost", 0),
  167. )
  168. step_id = await self.trace_store.add_step(step)
  169. await self._dump_debug(trace_id)
  170. # 完成 Trace
  171. await self.trace_store.update_trace(
  172. trace_id,
  173. status="completed",
  174. completed_at=datetime.now(),
  175. total_tokens=result.get("prompt_tokens", 0) + result.get("completion_tokens", 0),
  176. total_cost=result.get("cost", 0)
  177. )
  178. return CallResult(
  179. reply=result.get("content", ""),
  180. tool_calls=result.get("tool_calls"),
  181. trace_id=trace_id,
  182. step_id=step_id,
  183. tokens={
  184. "prompt": result.get("prompt_tokens", 0),
  185. "completion": result.get("completion_tokens", 0),
  186. },
  187. cost=result.get("cost", 0)
  188. )
  189. # ===== Agent 模式 =====
  190. async def run(
  191. self,
  192. task: str,
  193. messages: Optional[List[Dict]] = None,
  194. system_prompt: Optional[str] = None,
  195. model: str = "gpt-4o",
  196. tools: Optional[List[str]] = None,
  197. agent_type: Optional[str] = None,
  198. uid: Optional[str] = None,
  199. max_iterations: Optional[int] = None,
  200. enable_memory: Optional[bool] = None,
  201. auto_execute_tools: Optional[bool] = None,
  202. **kwargs
  203. ) -> AsyncIterator[AgentEvent]:
  204. """
  205. Agent 模式执行
  206. Args:
  207. task: 任务描述
  208. messages: 初始消息(可选)
  209. system_prompt: 系统提示(可选)
  210. model: 模型名称
  211. tools: 工具名称列表
  212. agent_type: Agent 类型
  213. uid: 用户 ID
  214. max_iterations: 最大迭代次数
  215. enable_memory: 是否启用记忆
  216. auto_execute_tools: 是否自动执行工具
  217. **kwargs: 其他参数
  218. Yields:
  219. AgentEvent
  220. """
  221. if not self.llm_call:
  222. raise ValueError("llm_call function not provided")
  223. # 使用配置默认值
  224. agent_type = agent_type or self.config.agent_type
  225. max_iterations = max_iterations or self.config.max_iterations
  226. enable_memory = enable_memory if enable_memory is not None else self.config.enable_memory
  227. auto_execute_tools = auto_execute_tools if auto_execute_tools is not None else self.config.auto_execute_tools
  228. # 创建 Trace
  229. trace_id = self._generate_id()
  230. if self.trace_store:
  231. trace_obj = Trace(
  232. trace_id=trace_id,
  233. mode="agent",
  234. task=task,
  235. agent_type=agent_type,
  236. uid=uid,
  237. context={"model": model, **kwargs}
  238. )
  239. await self.trace_store.create_trace(trace_obj)
  240. yield AgentEvent("trace_started", {
  241. "trace_id": trace_id,
  242. "task": task,
  243. "agent_type": agent_type
  244. })
  245. try:
  246. # 加载记忆(Experience 和 Skill)
  247. experiences_text = ""
  248. skills_text = ""
  249. if enable_memory and self.memory_store:
  250. scope = f"agent:{agent_type}"
  251. experiences = await self.memory_store.search_experiences(scope, task)
  252. experiences_text = self._format_experiences(experiences)
  253. # 记录 memory_read Step
  254. if self.trace_store:
  255. mem_step = Step.create(
  256. trace_id=trace_id,
  257. step_type="memory_read",
  258. sequence=0,
  259. status="completed",
  260. description=f"加载 {len(experiences)} 条经验",
  261. data={
  262. "experiences_count": len(experiences),
  263. "experiences": [e.to_dict() for e in experiences],
  264. }
  265. )
  266. await self.trace_store.add_step(mem_step)
  267. await self._dump_debug(trace_id)
  268. yield AgentEvent("memory_loaded", {
  269. "experiences_count": len(experiences)
  270. })
  271. # 加载 Skills(如果提供了 skills_dir)
  272. if self.skills_dir:
  273. skills = load_skills_from_dir(self.skills_dir)
  274. if skills:
  275. skills_text = self._format_skills(skills)
  276. logger.info(f"加载 {len(skills)} 个 skills 从 {self.skills_dir}")
  277. # 构建初始消息
  278. if messages is None:
  279. messages = []
  280. if system_prompt:
  281. # 注入记忆和 skills 到 system prompt
  282. full_system = system_prompt
  283. if skills_text:
  284. full_system += f"\n\n## Skills\n{skills_text}"
  285. if experiences_text:
  286. full_system += f"\n\n## 相关经验\n{experiences_text}"
  287. messages = [{"role": "system", "content": full_system}] + messages
  288. # 添加任务描述
  289. messages.append({"role": "user", "content": task})
  290. # 准备工具 Schema
  291. # 合并内置工具 + 用户指定工具
  292. tool_names = BUILTIN_TOOLS.copy()
  293. if tools:
  294. # 添加用户指定的工具(去重)
  295. for tool in tools:
  296. if tool not in tool_names:
  297. tool_names.append(tool)
  298. tool_schemas = self.tools.get_schemas(tool_names)
  299. # 执行循环
  300. current_goal_id = None # 当前焦点 goal
  301. sequence = 1
  302. total_tokens = 0
  303. total_cost = 0.0
  304. for iteration in range(max_iterations):
  305. yield AgentEvent("step_started", {
  306. "iteration": iteration,
  307. "step_type": "thought"
  308. })
  309. # 调用 LLM
  310. result = await self.llm_call(
  311. messages=messages,
  312. model=model,
  313. tools=tool_schemas,
  314. **kwargs
  315. )
  316. response_content = result.get("content", "")
  317. tool_calls = result.get("tool_calls")
  318. step_tokens = result.get("prompt_tokens", 0) + result.get("completion_tokens", 0)
  319. step_cost = result.get("cost", 0)
  320. total_tokens += step_tokens
  321. total_cost += step_cost
  322. # 记录 LLM 调用 Step
  323. llm_step_id = self._generate_id()
  324. if self.trace_store:
  325. # 推断 step_type
  326. step_type = "thought"
  327. if tool_calls:
  328. step_type = "thought" # 有工具调用的思考
  329. elif not tool_calls and iteration > 0:
  330. step_type = "response" # 无工具调用,可能是最终回复
  331. llm_step = Step(
  332. step_id=llm_step_id,
  333. trace_id=trace_id,
  334. step_type=step_type,
  335. status="completed",
  336. sequence=sequence,
  337. parent_id=current_goal_id,
  338. description=response_content[:100] + "..." if len(response_content) > 100 else response_content,
  339. data={
  340. "messages": messages, # 记录完整的 messages(包含 system prompt)
  341. "content": response_content,
  342. "model": model,
  343. "tools": tool_schemas, # 记录传给模型的 tools schema
  344. "tool_calls": tool_calls,
  345. },
  346. tokens=step_tokens,
  347. cost=step_cost,
  348. )
  349. await self.trace_store.add_step(llm_step)
  350. await self._dump_debug(trace_id)
  351. sequence += 1
  352. yield AgentEvent("llm_call_completed", {
  353. "step_id": llm_step_id,
  354. "content": response_content,
  355. "tool_calls": tool_calls,
  356. "tokens": step_tokens,
  357. "cost": step_cost
  358. })
  359. # 处理工具调用
  360. if tool_calls and auto_execute_tools:
  361. # 检查是否需要用户确认
  362. if self.tools.check_confirmation_required(tool_calls):
  363. yield AgentEvent("awaiting_user_action", {
  364. "tool_calls": tool_calls,
  365. "confirmation_flags": self.tools.get_confirmation_flags(tool_calls),
  366. "editable_params": self.tools.get_editable_params_map(tool_calls)
  367. })
  368. # TODO: 等待用户确认
  369. break
  370. # 执行工具
  371. messages.append({"role": "assistant", "content": response_content, "tool_calls": tool_calls})
  372. for tc in tool_calls:
  373. tool_name = tc["function"]["name"]
  374. tool_args = tc["function"]["arguments"]
  375. if isinstance(tool_args, str):
  376. import json
  377. tool_args = json.loads(tool_args)
  378. yield AgentEvent("tool_executing", {
  379. "tool_name": tool_name,
  380. "arguments": tool_args
  381. })
  382. # 执行工具
  383. tool_result = await self.tools.execute(
  384. tool_name,
  385. tool_args,
  386. uid=uid or ""
  387. )
  388. # 记录 action Step
  389. action_step_id = self._generate_id()
  390. if self.trace_store:
  391. action_step = Step(
  392. step_id=action_step_id,
  393. trace_id=trace_id,
  394. step_type="action",
  395. status="completed",
  396. sequence=sequence,
  397. parent_id=llm_step_id,
  398. description=f"{tool_name}({', '.join(f'{k}={v}' for k, v in list(tool_args.items())[:2])})",
  399. data={
  400. "tool_name": tool_name,
  401. "arguments": tool_args,
  402. }
  403. )
  404. await self.trace_store.add_step(action_step)
  405. await self._dump_debug(trace_id)
  406. sequence += 1
  407. # 记录 result Step
  408. result_step_id = self._generate_id()
  409. if self.trace_store:
  410. result_step = Step(
  411. step_id=result_step_id,
  412. trace_id=trace_id,
  413. step_type="result",
  414. status="completed",
  415. sequence=sequence,
  416. parent_id=action_step_id,
  417. description=str(tool_result)[:100] if tool_result else "",
  418. data={
  419. "tool_name": tool_name,
  420. "output": tool_result,
  421. }
  422. )
  423. await self.trace_store.add_step(result_step)
  424. await self._dump_debug(trace_id)
  425. sequence += 1
  426. yield AgentEvent("tool_result", {
  427. "step_id": result_step_id,
  428. "tool_name": tool_name,
  429. "result": tool_result
  430. })
  431. # 添加到消息(Gemini 需要 name 字段!)
  432. messages.append({
  433. "role": "tool",
  434. "tool_call_id": tc["id"],
  435. "name": tool_name,
  436. "content": tool_result
  437. })
  438. continue # 继续循环
  439. # 无工具调用,任务完成
  440. # 记录 response Step
  441. response_step_id = self._generate_id()
  442. if self.trace_store:
  443. response_step = Step(
  444. step_id=response_step_id,
  445. trace_id=trace_id,
  446. step_type="response",
  447. status="completed",
  448. sequence=sequence,
  449. parent_id=current_goal_id,
  450. description=response_content[:100] + "..." if len(response_content) > 100 else response_content,
  451. data={
  452. "content": response_content,
  453. "is_final": True
  454. }
  455. )
  456. await self.trace_store.add_step(response_step)
  457. await self._dump_debug(trace_id)
  458. yield AgentEvent("conclusion", {
  459. "step_id": response_step_id,
  460. "content": response_content,
  461. "is_final": True
  462. })
  463. break
  464. # 完成 Trace
  465. if self.trace_store:
  466. await self.trace_store.update_trace(
  467. trace_id,
  468. status="completed",
  469. completed_at=datetime.now(),
  470. total_tokens=total_tokens,
  471. total_cost=total_cost
  472. )
  473. yield AgentEvent("trace_completed", {
  474. "trace_id": trace_id,
  475. "total_tokens": total_tokens,
  476. "total_cost": total_cost
  477. })
  478. except Exception as e:
  479. logger.error(f"Agent run failed: {e}")
  480. if self.trace_store:
  481. await self.trace_store.update_trace(
  482. trace_id,
  483. status="failed",
  484. completed_at=datetime.now()
  485. )
  486. yield AgentEvent("trace_failed", {
  487. "trace_id": trace_id,
  488. "error": str(e)
  489. })
  490. raise
  491. # ===== 反馈 =====
  492. async def add_feedback(
  493. self,
  494. trace_id: str,
  495. target_step_id: str,
  496. feedback_type: Literal["positive", "negative", "correction"],
  497. content: str,
  498. extract_experience: bool = True
  499. ) -> Optional[str]:
  500. """
  501. 添加人工反馈
  502. Args:
  503. trace_id: Trace ID
  504. target_step_id: 反馈针对的 Step ID
  505. feedback_type: 反馈类型
  506. content: 反馈内容
  507. extract_experience: 是否自动提取经验
  508. Returns:
  509. experience_id: 如果提取了经验
  510. """
  511. if not self.trace_store:
  512. return None
  513. # 获取 Trace
  514. trace = await self.trace_store.get_trace(trace_id)
  515. if not trace:
  516. logger.warning(f"Trace not found: {trace_id}")
  517. return None
  518. # 创建 feedback Step
  519. steps = await self.trace_store.get_trace_steps(trace_id)
  520. max_seq = max(s.sequence for s in steps) if steps else 0
  521. feedback_step = Step.create(
  522. trace_id=trace_id,
  523. step_type="feedback",
  524. sequence=max_seq + 1,
  525. status="completed",
  526. description=f"{feedback_type}: {content[:50]}...",
  527. parent_id=target_step_id,
  528. data={
  529. "target_step_id": target_step_id,
  530. "feedback_type": feedback_type,
  531. "content": content
  532. }
  533. )
  534. await self.trace_store.add_step(feedback_step)
  535. await self._dump_debug(trace_id)
  536. # 提取经验
  537. exp_id = None
  538. if extract_experience and self.memory_store and feedback_type in ("positive", "correction"):
  539. exp = Experience.create(
  540. scope=f"agent:{trace.agent_type}" if trace.agent_type else "agent:default",
  541. condition=f"执行类似 '{trace.task}' 任务时" if trace.task else "通用场景",
  542. rule=content,
  543. evidence=[target_step_id, feedback_step.step_id],
  544. source="feedback",
  545. confidence=0.8 if feedback_type == "positive" else 0.6
  546. )
  547. exp_id = await self.memory_store.add_experience(exp)
  548. # 记录 memory_write Step
  549. mem_step = Step.create(
  550. trace_id=trace_id,
  551. step_type="memory_write",
  552. sequence=max_seq + 2,
  553. status="completed",
  554. description=f"保存经验: {exp.condition[:30]}...",
  555. parent_id=feedback_step.step_id,
  556. data={
  557. "experience_id": exp_id,
  558. "condition": exp.condition,
  559. "rule": exp.rule
  560. }
  561. )
  562. await self.trace_store.add_step(mem_step)
  563. await self._dump_debug(trace_id)
  564. return exp_id
  565. # ===== 辅助方法 =====
  566. def _format_skills(self, skills: List[Skill]) -> str:
  567. """格式化技能为 Prompt 文本"""
  568. if not skills:
  569. return ""
  570. return "\n\n".join(s.to_prompt_text() for s in skills)
  571. def _format_experiences(self, experiences: List[Experience]) -> str:
  572. """格式化经验为 Prompt 文本"""
  573. if not experiences:
  574. return ""
  575. return "\n".join(f"- {e.to_prompt_text()}" for e in experiences)
  576. def _format_skills(self, skills: List[Skill]) -> str:
  577. """格式化 Skills 为 Prompt 文本"""
  578. if not skills:
  579. return ""
  580. return "\n\n".join(s.to_prompt_text() for s in skills)