Skip to main content
In this section, you will learn how to define custom tools using LangChain’s decorator approach, which simplifies tool configuration by automatically deriving descriptions and names from function docstrings.

Objectives

  1. Declare custom tools by adding the @tool decorator to Python functions.
  2. Bind Pydantic model schemas to the decorator using the args_schema property.
  3. Combine decorated functions into a tools array and load them inside a tool-calling agent.

Implementation Plan

Goal

Build and execute a tools agent utilizing decorated tools for greeting, reversing strings, and concatenating values.

Sample Input

Sample Output

Plan

  1. Define a simple function greet_user decorated with @tool().
  2. Define Pydantic argument structures: ReverseStringArgs and ConcatenateStringsArgs.
  3. Decorate reverse_string with @tool(args_schema=ReverseStringArgs).
  4. Decorate concatenate_strings with @tool(args_schema=ConcatenateStringsArgs).
  5. Group the decorated functions in a list: tools = [greet_user, reverse_string, concatenate_strings].
  6. Initialize the agent executor using create_tool_calling_agent and test the agent.

Step-by-Step Implementation

Step 1: Define Simple Decorated Tool

We write a simple greeting tool. The docstring """Greets the user by name.""" acts as the tool description.

Step 2: Define Structured Tools with Schemas

We bind Pydantic argument classes to decorated functions.

Step 3: Run Agent

We combine the tools list and execute the agent.

Complete Combined Code

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

Practice & Exercises

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

Practice & Exercises

Practice defining custom tools using the @tool decorator.💻 VS Code | 🚀 Colab | 📥 Download