runner.py 19 KB

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