Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 57

Agent Tooling

This lesson is built with resources from latenode.com and docs.langchain.com.

Hello! Welcome back to our module on the Foundations of AI Agents.

In our last lesson, we dove into the low-level mechanics of function calling. We successfully enabled an LLM to call a single external function by manually crafting JSON schemas, managing a multi-step conversation with the model, and parsing its responses. While this process is fundamental to understanding how agents work, you likely noticed it involves a significant amount of boilerplate code.

As a software engineer, you know that when you encounter repetitive, low-level patterns, it's often a sign that a good abstraction or framework can help. That's exactly what we'll explore today. This lesson focuses on using a framework—specifically LangChain—to streamline the process of giving an agent new abilities.

Our goal is to create custom tools and functions for an agent to extend its capabilities. We will move beyond the manual setup and learn how to efficiently define, manage, and use multiple tools, turning our agent into a much more versatile problem-solver.

Why a Framework for Tools?

The manual function calling workflow we implemented in the last lesson, while instructive, has a few practical drawbacks:

  • Verbose Schema Definition: Writing and maintaining JSON schemas for each function is tedious and error-prone.
  • Boilerplate Logic: The conversational loop (call, execute, respond) has to be re-implemented for every interaction.
  • Scalability Issues: Managing a large set of tools, each with its own schema and execution logic, can quickly become complex.

Frameworks like LangChain provide a higher-level API that handles this complexity for you. They let you focus on what your tools should do, not the plumbing required to connect them to the LLM.


The Anatomy of a LangChain Tool

Before we start building, let's understand what makes an effective tool from the LLM's perspective. A well-defined tool has several key components that guide the model in using it correctly.

LangChain Tools: Complete Guide to Creating and Using ...

The article "LangChain Tools: Complete Guide" provides an excellent breakdown of the core components that make up a LangChain tool. Understanding these will help you design better tools.

Please read the section titled LangChain Tool Architecture and Core Components. Focus on the five key components: Function Signature, Tool Descriptions, Parameter Schema, Return Handling, and Error Handling.

The key takeaway is that a tool isn't just a function; it's a function wrapped in a descriptive "package" for the LLM. The description and parameter schema are just as important as the code itself, as they form the API contract the LLM uses to make decisions.


Creating Custom Tools: The Two Main Approaches

LangChain offers two primary methods for creating your own tools, catering to different levels of complexity.

  1. The @tool decorator: The simplest and most common method. It turns any Python function into a LangChain tool with minimal code.
  2. Subclassing BaseTool: A more powerful, object-oriented approach for complex tools that require initialization (e.g., database connections, API clients) or internal state.

Let's explore both.

1. The Easy Way: The @tool Decorator

The @tool decorator is a perfect example of convention over configuration. It intelligently infers the tool's properties directly from your Python function:

  • Tool Name: Inferred from the function name.
  • Tool Description: Inferred from the function's docstring.
  • Parameter Schema: Inferred from the function's type hints.

This means you can create a tool just by writing a well-documented Python function. Let's create a simple calculator tool.

# You'll need to install langchain: pip install langchain
from langchain.tools import tool

@tool
def simple_calculator(expression: str) -> str:
    """
    Evaluates a simple mathematical expression.
    Use this tool for any math questions involving addition, subtraction, multiplication, or division.
    The input must be a string that can be evaluated by Python, e.g., '2 + 2' or '10 * 4'.
    """
    try:
        # Note: In a production system, using eval() is a security risk.
        # This is for demonstration purposes only.
        return str(eval(expression))
    except Exception as e:
        return f"Error: Could not evaluate the expression. {e}"

# Let's inspect the tool LangChain created
print(f"Tool Name: {simple_calculator.name}")
print(f"Tool Description: {simple_calculator.description}")
print(f"Tool Arguments Schema: {simple_calculator.args}")

When you run this, you'll see that LangChain automatically generated a complete tool definition, including a JSON schema for the arguments, just from the function's signature and docstring. This is a massive improvement over manually writing the schema yourself!

The Importance of Descriptions and Type Hints

Your docstring is no longer just documentation for other developers; it's the primary instruction set for the LLM. A clear, direct, and descriptive docstring is crucial for the model to know when and how to use your tool.

LangChain Tools: Complete Guide to Creating and Using ...

This guide offers excellent best practices for writing effective tool names and descriptions. A good description can be the difference between an agent that works and one that doesn't.

Read the section Best Practices for Tool Names and Descriptions. Pay close attention to the 'Poor description' vs. 'Effective description' examples.

Handling Complex Inputs with Pydantic

What if your tool needs more complex arguments than simple strings or numbers? For this, LangChain integrates seamlessly with Pydantic, a popular data validation library in the Python ecosystem. You might already be familiar with it from backend frameworks like FastAPI.

You can define a Pydantic BaseModel to represent your tool's arguments and pass it to the @tool decorator.

Tools - Docs by LangChain

The official LangChain documentation shows a clean example of using a Pydantic model to define a tool's input schema.

Review the code under the heading Advanced schema definition. Notice how the WeatherInput Pydantic model is used with the args_schema parameter in the @tool decorator.

This approach gives you fine-grained control over your tool's inputs, including default values, validation rules, and descriptions for each field.

2. The Advanced Way: Subclassing BaseTool

Sometimes, a simple function isn't enough. You might need a tool that requires some setup, like connecting to a database or initializing an API client. This is where subclassing BaseTool comes in. This object-oriented approach is ideal for tools that are more than just a single, stateless operation.

A BaseTool subclass requires you to define:

  • name: The tool's name.
  • description: The tool's purpose.
  • args_schema: A Pydantic model for the arguments.
  • _run(): The method that contains the tool's execution logic.

Here’s a conceptual example that should feel familiar from your backend experience. Imagine a tool that needs to interact with a specific user's account.

# You'll need pydantic: pip install pydantic
from langchain.tools import BaseTool
from pydantic import BaseModel, Field
from typing import Type

# Define the input schema for the tool
class UserProfileInput(BaseModel):
    user_id: str = Field(description="The unique identifier for the user.")

# Define the tool by subclassing BaseTool
class GetUserProfileTool(BaseTool):
    name = "get_user_profile"
    description = "Fetches the profile for a specific user from the user service."
    args_schema: Type[BaseModel] = UserProfileInput
    
    # This is a placeholder for a real API client
    user_api_client: object 

    def _run(self, user_id: str) -> str:
        """Use the tool."""
        print(f"Fetching profile for user: {user_id}")
        # In a real app, you would use the client:
        # return self.user_api_client.get_user(user_id)
        if user_id == "user_123":
            return "User Profile: { 'name': 'Alice', 'plan': 'premium' }"
        else:
            return "User not found."

# How you would initialize it
class MockApiClient:
    def __init__(self, api_key):
        self.api_key = api_key

# During your application setup, you create an instance of the tool
api_client = MockApiClient(api_key="your-secret-key")
user_profile_tool = GetUserProfileTool(user_api_client=api_client)

# The agent can now use this initialized tool instance
print(user_profile_tool.run({"user_id": "user_123"}))

By using a class, you can inject dependencies like user_api_client during initialization. This is a much cleaner pattern for stateful or complex tools than using global variables.


Using Custom Tools with an Agent

Now that we know how to create tools, let's give them to an agent. The process is straightforward: you create instances of your tools and pass them as a list to the agent.

Let's build a simple agent that has two tools: our simple_calculator and a new get_word_length tool.

# You'll need: pip install langchain-openai
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage, AIMessage

# Define a second tool
@tool
def get_word_length(word: str) -> int:
    """Returns the length of a word."""
    return len(word)

# 1. Choose the LLM
# Make sure your OPENAI_API_KEY environment variable is set
llm = ChatOpenAI(model="gpt-4-turbo", temperature=0)

# 2. Create the list of tools
tools = [simple_calculator, get_word_length]

# 3. Create the prompt
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful assistant. You have access to two tools: a calculator and a word length checker."),
        ("user", "{input}"),
        # This placeholder is where the agent's intermediate steps (tool calls and results) will go
        ("placeholder", "{agent_scratchpad}"),
    ]
)

# 4. Create the agent
agent = create_openai_tools_agent(llm, tools, prompt)

# 5. Create the AgentExecutor to run the agent
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# Let's test it!
# Test Case 1: Using the calculator
response1 = agent_executor.invoke({"input": "What is 1024 divided by 16?"})
print("\nFinal Answer:", response1["output"])

# Test Case 2: Using the word length tool
response2 = agent_executor.invoke({"input": "How many letters are in the word 'antidisestablishmentarianism'?"})
print("\nFinal Answer:", response2["output"])

When you run this code (with verbose=True), you'll see the agent's "thought process." It will receive the input, identify the correct tool to use (simple_calculator or get_word_length), call it with the right arguments, get the result, and then formulate the final answer.

Test your understanding!

Create a new custom tool named reverse_string that takes a single string as input and returns the reversed string.

  1. Define the tool using the @tool decorator.
  2. Make sure it has a clear docstring explaining its purpose.
  3. Include proper type hints for the input and output.
Show answer

Here's one way to implement the reverse_string tool:

from langchain.tools import tool

@tool
def reverse_string(text: str) -> str:
    """
    Reverses the order of characters in a given string.
    Use this tool if you need to spell a word backwards or reverse any text.
    """
    return text[::-1]

# You can test it directly:
print(reverse_string.run("hello")) 
# Output: 'olleh'

# And inspect its properties:
print(f"\nTool Name: {reverse_string.name}")
print(f"Tool Description: {reverse_string.description}")

Conclusion

Today, we've taken a significant step in building more capable AI agents. We've moved from the manual, low-level details of function calling to a structured, scalable approach for creating and managing custom tools using LangChain.

Key Takeaways:

  • Frameworks like LangChain abstract away the boilerplate of function calling, letting you focus on tool logic.
  • The @tool decorator is the quickest way to convert a Python function into an agent tool, using docstrings for descriptions and type hints for arguments.
  • Pydantic models can be used to define complex, validated input schemas for your tools.
  • Subclassing BaseTool provides an object-oriented approach for more advanced tools that require initialization, state, or dependency injection.
  • A clear, descriptive docstring is critical, as it's the primary way an LLM understands what your tool does and when to use it.

What's Next?

We've successfully equipped our agent with a toolbox. But how does an agent decide which tool to use, and in what order, to solve a complex problem? In our next lesson, we will build a basic agent that follows the ReAct (Reason+Act) pattern. This foundational reasoning framework is what enables an agent to "think" its way through a problem, using the tools you provide to take actions and make progress toward a goal.