Skip to main content
In this section, you will learn how to define custom tools using LangChain’s core constructors: Tool for simple single-argument inputs, and StructuredTool for complex multi-argument configurations validated with Pydantic.

Objectives

  1. Define custom functions for greeting users, reversing strings, and concatenating values.
  2. Formulate Pydantic schemas using BaseModel and Field to describe and validate tool inputs.
  3. Instantiate Tool and StructuredTool classes and bind them to a tool-calling agent.

Implementation Plan

Goal

Construct a set of custom utility tools using constructors, compile them within an OpenAI tools agent, and verify executions on text inputs.

Sample Input

Sample Output

Plan

  1. Define functions: greet_user, reverse_string, and concatenate_strings.
  2. Define a Pydantic class ConcatenateStringsArgs containing validation schemas for parameters a and b.
  3. Wrap greeting and reversing functions inside the Tool(...) class constructor.
  4. Wrap string concatenation inside StructuredTool.from_function(...) mapping the arguments schema.
  5. Load the prompt hwchase17/openai-tools-agent and initialize the agent executor with create_tool_calling_agent.
  6. Invoke the agent with query strings.

Step-by-Step Implementation

Step 1: Define Functions and Pydantic Schema

We write our Python operations and define the Pydantic validation schema for multiple arguments.

Step 2: Instantiate Constructors

We wrap the functions into Tool and StructuredTool objects.

Step 3: Create and Invoke Tool-Calling Agent

We pull the specialized tools-agent prompt, initialize the model, build the agent executor, and run tests.

Complete Combined Code

Below is the complete, consolidated Python script uniting all of the steps above:

Practice & Exercises

To practice setting up tools using standard constructors, open the interactive notebook:

Practice & Exercises

Practice initializing Tool and StructuredTool constructor wrappers.💻 VS Code | 🚀 Colab | 📥 Download