Adding Tools to Agents with LangChain¶

This tutorial teaches you how to extend AI agents with tools—functions that enable agents to perform actions beyond just generating text. By the end, you'll understand what tools are, how to create them, and how agents use them to accomplish tasks.

What Are Tools?¶

Tools are functions or capabilities that agents can call to interact with the world. Think of them as the agent's "hands"—they allow the agent to:

  • Perform calculations or data processing
  • Access external APIs or databases
  • Read or write files
  • Execute code or scripts
  • Search the web or query information

Without tools, agents are like very smart chatbots—they can reason and generate text, but they can't take actions. With tools, agents become active problem-solvers that can manipulate data, fetch real-time information, and automate tasks.

Why Tools Matter¶

Tools transform agents from passive responders into active automators. They enable:

  • Real-world actions: Agents can do things, not just talk about them
  • Up-to-date information: Access current data instead of relying only on training data
  • Specialized capabilities: Each tool can handle a specific task efficiently
  • Composability: Combine multiple tools to solve complex problems

What You'll Learn¶

In this tutorial, you'll:

  1. Understand what tools are and why agents need them
  2. Create a tool using the @tool decorator
  3. Add tools to an agent
  4. See how agents automatically decide when to use tools
  5. Test tools with different types of questions

Prerequisites¶

Before starting, make sure you have:

  • Python 3.10+ installed
  • OpenRouter API key (get one free at https://openrouter.ai)
  • Completed Tutorial 01 - You should understand basic agent creation

First time? See Tutorial 01 for detailed instructions on installing Python, setting up a virtual environment, and creating your API key.

Quick Setup Checklist¶

If you haven't set up yet, here's the short version:

  1. Install Python 3.10+: Download from python.org — verify with python3 --version
  2. Create a virtual environment: python3 -m venv venv && source venv/bin/activate
  3. Get an OpenRouter API key: Sign up at openrouter.ai → Keys → Create Key
  4. Create a .env file in the project root: touch .env, then add OPENROUTER_API_KEY=your-key-here

Setup Environment¶

Make sure you have a .env file in the project root with your API key:

OPENROUTER_API_KEY=your-api-key-here

If you completed Tutorial 01, you should already have this set up!

Installation¶

Install the required dependencies directly. This cell is self-contained—no external requirements.txt needed. We'll be using the tool decorator from LangChain to create our tools.

In [ ]:
%pip install langchain langchain-openai python-dotenv --quiet

Setup¶

Import the necessary libraries. Notice the new import: from langchain.tools import tool - this is the decorator we'll use to convert Python functions into agent tools.

The model configuration is similar to Tutorial 01, but notice the temperature is set to 0.1 instead of 0.7. Lower temperature makes the agent more deterministic and focused, which is often better when using tools—we want the agent to reliably choose the right tool rather than being creative about it.

In [ ]:
import os
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from langchain.tools import tool
from langchain_core.messages import HumanMessage

# Load environment variables from .env file
load_dotenv()

# Configure OpenRouter model
model = ChatOpenAI(
    api_key=os.getenv("OPENROUTER_API_KEY"),
    base_url="https://openrouter.ai/api/v1",
    model="gpt-4o-mini",
    temperature=0.1,
    max_tokens=1000,
)

Scenario: Temperature Conversion Assistant¶

We'll create a practical example: a temperature conversion assistant. This agent will help users convert between Celsius and Fahrenheit, but it needs a tool to perform the actual calculations.

Why This Example?¶

Temperature conversion is perfect for learning because:

  • It's a clear, specific task that requires a tool (the agent can't do math reliably without one)
  • It's easy to understand and verify the results
  • It demonstrates how agents decide when to use tools based on user questions

Create a Tool¶

Now we'll create our first tool! Tools in LangChain are regular Python functions decorated with @tool. Here's what makes a good tool:

Key Components of a Tool¶

  1. Function signature - Defines the inputs (parameters) and output (return type)
  2. Docstring - Describes what the tool does, its parameters, and return value
  3. Implementation - The actual code that performs the action

The docstring is crucial—the agent reads it to understand:

  • What the tool does
  • When to use it
  • What parameters it needs
  • What it returns

Let's create a temperature conversion tool:

In [ ]:
@tool
def convert_temperature(value: float, from_unit: str, to_unit: str) -> float:
    """
    Convert temperature between Celsius and Fahrenheit.
    
    Args:
        value: The temperature value to convert
        from_unit: Source unit ("celsius" or "fahrenheit")
        to_unit: Target unit ("celsius" or "fahrenheit")
    
    Returns:
        Converted temperature value
    """
    if from_unit.lower() == "celsius" and to_unit.lower() == "fahrenheit":
        return (value * 9/5) + 32
    elif from_unit.lower() == "fahrenheit" and to_unit.lower() == "celsius":
        return (value - 32) * 5/9
    elif from_unit.lower() == to_unit.lower():
        return value
    else:
        raise ValueError(f"Unsupported conversion from {from_unit} to {to_unit}")

Create Agent with Tool¶

Now we'll create an agent and give it access to our tool. Notice two important changes from Tutorial 01:

Key Changes¶

  1. System prompt - We explicitly tell the agent to use the tool: "Always use the convert_temperature tool when users ask for temperature conversions." This guides the agent's behavior.

  2. tools parameter - We pass a list of tools: tools=[convert_temperature]. The agent can now see and use this tool when needed.

How Agents Use Tools¶

When you ask the agent a question, here's what happens:

  1. Agent receives your question
  2. Agent analyzes whether a tool is needed (e.g., "does this require temperature conversion?")
  3. Agent calls the tool with appropriate parameters (extracted from your question)
  4. Agent receives the tool's result
  5. Agent formulates a natural language response using the result

The agent automatically handles all of this—you don't need to manually call the tool!

Pro tip: You can add multiple tools by passing a list: tools=[tool1, tool2, tool3]. Start with 2-3 tools to keep things manageable.

In [ ]:
agent = create_agent(
    model=model,
    system_prompt="You are a helpful assistant that can convert temperatures between Celsius and Fahrenheit. Always use the convert_temperature tool when users ask for temperature conversions.",
    tools=[convert_temperature]
)

Test Agent with Tool¶

Let's test our agent with different types of questions. Watch how the agent:

  • Recognizes when a tool is needed
  • Extracts the right parameters from your question (value, from_unit, to_unit)
  • Calls the tool automatically
  • Uses the result to give you a natural answer

Notice in the output you'll see tool calls being made—this shows when the agent called the tool. The agent then uses the tool's result to craft its response.

Test Cases¶

We'll try three scenarios:

  1. Simple conversion - Direct request for conversion
  2. Reverse conversion - Same tool, different direction
  3. Complex question - Conversion plus additional reasoning

This demonstrates the agent's flexibility—it can handle the same tool in different contexts!

In [ ]:
# Test 1: Simple conversion
response = agent.invoke({"messages": [HumanMessage("Convert 25 degrees Celsius to Fahrenheit")]})
print(response["messages"][-1].content)
In [ ]:
# Test 2: Reverse conversion
response = agent.invoke({"messages": [HumanMessage("What is 77 degrees Fahrenheit in Celsius?")]})
print(response["messages"][-1].content)
In [ ]:
# Test 3: More complex question
response = agent.invoke({"messages": [HumanMessage("If it's 20°C outside, what would that be in Fahrenheit? Is that warm or cold?")]})
print(response["messages"][-1].content)

What You've Learned¶

Congratulations! You've successfully added tools to an AI agent. Here's what we covered:

✅ What tools are - Functions that enable agents to take actions
✅ How to create tools - Using the @tool decorator with clear docstrings
✅ How to add tools to agents - Using the tools parameter
✅ How agents use tools - Automatic tool selection and execution
✅ Testing tools - Verifying agents use tools correctly

Key Takeaways¶

  1. Tools extend capabilities - They transform agents from text generators into active problem-solvers
  2. Docstrings are crucial - The agent reads them to understand when and how to use tools
  3. Agents are smart - They automatically decide when tools are needed and extract parameters
  4. Start simple - Begin with 2-3 focused tools before adding complexity

How Tools Work Behind the Scenes¶

When you ask a question:

  1. The agent's language model analyzes your question
  2. It checks available tools and their descriptions
  3. If a tool matches, it extracts parameters from your question
  4. It calls the tool and receives the result
  5. It incorporates the result into a natural language response

This all happens automatically—you just ask questions naturally!

Best Practices¶

When creating tools:

  • Clear names - Use descriptive function names (convert_temperature not conv)
  • Good docstrings - Explain what, when, and how to use the tool
  • Type hints - Help the agent understand expected inputs/outputs
  • Error handling - Tools should handle edge cases gracefully
  • Start small - Add tools incrementally, test each one

Next Steps¶

Now that you can add tools, you're ready to:

  • Create multi-agent systems (Tutorial 03) - Use agents as tools for other agents
  • Manage resources (Tutorial 04) - Track costs when tools trigger multiple API calls

Experiment¶

Try these modifications:

  • Add another tool - Create a unit converter (length, weight, etc.)
  • Modify the system prompt - See how it affects tool usage
  • Test edge cases - What happens with invalid inputs?
  • Combine tools - Create an agent with multiple related tools

The more you experiment, the better you'll understand how to design effective tools!