tool.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from typing import Any, Callable, Optional
  2. from ..abstractions import R2RSerializable
  3. class Tool(R2RSerializable):
  4. name: str
  5. description: str
  6. results_function: Callable
  7. llm_format_function: Optional[Callable] = None
  8. stream_function: Optional[Callable] = None
  9. parameters: Optional[dict[str, Any]] = None
  10. context: Optional[Any] = None
  11. class Config:
  12. populate_by_name = True
  13. arbitrary_types_allowed = True
  14. def set_context(self, context: Any) -> None:
  15. """Set the context for this tool."""
  16. self.context = context
  17. async def execute(self, *args, **kwargs):
  18. """
  19. Execute the tool with context awareness.
  20. This wraps the results_function to ensure context is available.
  21. """
  22. if self.context is None:
  23. raise ValueError(
  24. f"Tool '{self.name}' requires context but none was provided"
  25. )
  26. # Call the actual implementation with context
  27. return await self.results_function(context=self.context, **kwargs)
  28. class ToolResult(R2RSerializable):
  29. raw_result: Any
  30. llm_formatted_result: str
  31. stream_result: Optional[str] = None