BaseTool class, which offers the highest level of control over tool metadata, schemas, and custom internal executions.
Objectives
- Define custom tools by subclassing the core abstract class
BaseTool. - Implement schema enforcement using Pydantic classes assigned to
args_schema. - Implement execution pathways by overriding the synchronous
_runmethod.
Implementation Plan
Goal
SubclassBaseTool to build a Tavily search tool and a multiplier tool, bind them to an agent, and execute queries.
Sample Input
Sample Output
Plan
- Define input validation Pydantic classes:
SimpleSearchInputandMultiplyNumbersArgs. - Subclass
BaseToolto defineSimpleSearchTool. Declarename,description,args_schema, and override_runto execute queries using theTavilyClient. - Subclass
BaseToolto defineMultiplyNumbersTool. Declare properties and override_runto multiply two floats. - Instantiate subclasses:
tools = [SimpleSearchTool(), MultiplyNumbersTool()]. - Pull the prompt
hwchase17/openai-tools-agent, create the agent executor, and run test queries.
Step-by-Step Implementation
Step 1: Define Schemas
We structure the validation schemas using Pydantic models.Step 2: Subclass BaseTool
We define the custom classes inheriting fromBaseTool, specifying properties and overriding the internal _run method.
Step 3: Run Subclassed Tools with Agent
We instantiate the custom classes and execute the agent loop.Complete Combined Code
Below is the complete, consolidated Python script uniting all of the steps above:Practice & Exercises
To practice subclassing tools, open the interactive notebook:Practice & Exercises
Practice subclassing BaseTool and customizing execution functions.💻 VS Code | 🚀 Colab | 📥 Download