runner.py 21 KB

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