base_tool.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from abc import ABC
  2. from typing import Type, Dict, Any, Optional
  3. from langchain.tools import BaseTool as LCBaseTool
  4. from langchain.tools.render import format_tool_to_openai_function
  5. from pydantic import BaseModel, Field
  6. class BaseToolInput(BaseModel):
  7. """
  8. Base schema for tool input arguments.
  9. """
  10. input: str = Field(..., description="input")
  11. class BaseTool(ABC):
  12. """
  13. Base class for tools.
  14. Attributes:
  15. name (str): The name of the tool.
  16. description (str): The description of the tool.
  17. args_schema (Optional[Type[BaseModel]]): The schema for the tool's input arguments.
  18. openai_function (Dict): The OpenAI function representation of the tool.
  19. """
  20. name: str
  21. description: str
  22. args_schema: Optional[Type[BaseModel]] = BaseToolInput
  23. openai_function: Dict
  24. def __init_subclass__(cls) -> None:
  25. lc_tool = LCTool(
  26. name=cls.name,
  27. description=cls.description,
  28. args_schema=cls.args_schema,
  29. _run=lambda x: x,
  30. )
  31. cls.openai_function = {
  32. "type": "function",
  33. "function": dict(format_tool_to_openai_function(lc_tool)),
  34. }
  35. def configure(self, **kwargs):
  36. """
  37. Configure the tool with the provided keyword arguments.
  38. Args:
  39. **kwargs: Additional configuration parameters.
  40. """
  41. return
  42. def run(self, **kwargs) -> Any:
  43. """
  44. Executes the tool with the given arguments.
  45. Args:
  46. **kwargs: Additional keyword arguments for the tool.
  47. Returns:
  48. Any: The result of executing the tool.
  49. """
  50. raise NotImplementedError()
  51. def instruction_supplement(self) -> str:
  52. """
  53. Provides additional instructions to supplement the run instruction for the tool.
  54. Returns:
  55. str: The additional instructions.
  56. """
  57. return ""
  58. class LCTool(LCBaseTool):
  59. name: str = ""
  60. description: str = ""
  61. def _run(self):
  62. pass