Skip to main content
In this section, you will learn how to define custom tools by subclassing LangChain’s base BaseTool class, which offers the highest level of control over tool metadata, schemas, and custom internal executions.

Objectives

  1. Define custom tools by subclassing the core abstract class BaseTool.
  2. Implement schema enforcement using Pydantic classes assigned to args_schema.
  3. Implement execution pathways by overriding the synchronous _run method.

Implementation Plan

Goal

Subclass BaseTool to build a Tavily search tool and a multiplier tool, bind them to an agent, and execute queries.

Sample Input

Sample Output

Plan

  1. Define input validation Pydantic classes: SimpleSearchInput and MultiplyNumbersArgs.
  2. Subclass BaseTool to define SimpleSearchTool. Declare name, description, args_schema, and override _run to execute queries using the TavilyClient.
  3. Subclass BaseTool to define MultiplyNumbersTool. Declare properties and override _run to multiply two floats.
  4. Instantiate subclasses: tools = [SimpleSearchTool(), MultiplyNumbersTool()].
  5. 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 from BaseTool, 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