base.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """Agent 基类:所有专职 Agent 与 Controller 的公共接口"""
  2. from __future__ import annotations
  3. from typing import Any, Optional
  4. from backend.llm.client import DeepSeekClient
  5. from backend.llm.function_calling import ToolLoop
  6. from backend.tools.base import ToolRegistry
  7. class BaseAgent:
  8. """专职 Agent 基类:绑定角色提示词 + 工具子集,通过 ToolLoop 执行任务"""
  9. def __init__(
  10. self,
  11. name: str,
  12. role: str,
  13. client: DeepSeekClient,
  14. registry: ToolRegistry,
  15. tool_names: Optional[list[str]] = None,
  16. ):
  17. self.name = name
  18. self.role = role # system prompt 角色描述
  19. self.client = client
  20. self.registry = registry
  21. # 该 Agent 可用的工具子集(None 表示全部)
  22. self.tool_names = tool_names or registry.names()
  23. def _build_tools_schema(self) -> list[dict]:
  24. """构建该 Agent 可用工具的 JSON schema 列表"""
  25. all_schemas = {s["function"]["name"]: s for s in self.registry.get_schemas()}
  26. return [all_schemas[n] for n in self.tool_names if n in all_schemas]
  27. def _build_callables(self) -> dict:
  28. """构建该 Agent 可用工具的 name->func 字典"""
  29. all_callables = self.registry.get_callables()
  30. return {n: all_callables[n] for n in self.tool_names if n in all_callables}
  31. async def run(self, task: str, context: Optional[str] = None) -> dict:
  32. """执行任务:构造消息→ToolLoop 循环→返回结果与工具调用记录"""
  33. messages = [{"role": "system", "content": self.role}]
  34. user_content = task
  35. if context:
  36. user_content = f"上下文:\n{context}\n\n任务:\n{task}"
  37. messages.append({"role": "user", "content": user_content})
  38. tool_loop = ToolLoop(self.client, self._build_callables())
  39. result_text = await tool_loop.run(
  40. messages=messages,
  41. tools_schema=self._build_tools_schema(),
  42. max_iterations=15,
  43. )
  44. return {
  45. "agent": self.name,
  46. "result": result_text,
  47. "tool_calls": [tc.model_dump() for tc in tool_loop.get_tool_records()],
  48. }