base.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """Tool base class and registry."""
  2. from __future__ import annotations
  3. from abc import ABC, abstractmethod
  4. from typing import Any
  5. class Tool(ABC):
  6. """Abstract base class for agent tools."""
  7. @property
  8. @abstractmethod
  9. def name(self) -> str:
  10. ...
  11. @property
  12. @abstractmethod
  13. def description(self) -> str:
  14. ...
  15. @property
  16. @abstractmethod
  17. def parameters(self) -> dict[str, Any]:
  18. ...
  19. @abstractmethod
  20. async def execute(self, **kwargs: Any) -> str:
  21. ...
  22. def to_schema(self) -> dict[str, Any]:
  23. """Convert to OpenAI function-calling schema."""
  24. return {
  25. "type": "function",
  26. "function": {
  27. "name": self.name,
  28. "description": self.description,
  29. "parameters": self.parameters,
  30. },
  31. }
  32. class ToolRegistry:
  33. """Dynamic registry for agent tools."""
  34. _HINT = "\n\n[Analyze the error above and try a different approach.]"
  35. def __init__(self) -> None:
  36. self._tools: dict[str, Tool] = {}
  37. def register(self, tool: Tool) -> None:
  38. self._tools[tool.name] = tool
  39. def get(self, name: str) -> Tool | None:
  40. return self._tools.get(name)
  41. def get_definitions(self) -> list[dict[str, Any]]:
  42. """Return all tool schemas in OpenAI format."""
  43. return [t.to_schema() for t in self._tools.values()]
  44. async def execute(self, name: str, params: dict[str, Any]) -> str:
  45. """Look up a tool by *name*, run it, and return the string result."""
  46. tool = self._tools.get(name)
  47. if not tool:
  48. avail = ", ".join(self._tools)
  49. return f"Error: Tool '{name}' not found. Available: {avail}"
  50. try:
  51. result = await tool.execute(**params)
  52. if isinstance(result, str) and result.startswith("Error"):
  53. return result + self._HINT
  54. return result
  55. except Exception as exc:
  56. return f"Error executing {name}: {exc}" + self._HINT
  57. @property
  58. def names(self) -> list[str]:
  59. return list(self._tools)