0
0
LangChainframework~5 mins

Creating tools for agents in LangChain

Choose your learning style9 modes available
Introduction

Tools help agents do specific jobs easily. They let agents get information or perform tasks quickly.

When you want an agent to search the internet for answers.
When you need an agent to access a calculator or do math.
When an agent should check the weather or current news.
When you want to connect an agent to a database or API.
When you want to add custom commands for an agent to use.
Syntax
LangChain
from langchain.agents import Tool

tool = Tool(
    name="tool_name",
    func=your_function,
    description="What this tool does"
)

The name is how the agent calls the tool.

The func is the function the tool runs when used.

Examples
This tool adds numbers from a text input.
LangChain
def add_numbers(text: str) -> str:
    numbers = list(map(int, text.split()))
    return str(sum(numbers))

add_tool = Tool(
    name="Adder",
    func=add_numbers,
    description="Adds numbers given in text"
)
This tool returns the current time when called.
LangChain
def get_time(_input: str) -> str:
    from datetime import datetime
    return datetime.now().strftime('%H:%M')

time_tool = Tool(
    name="TimeChecker",
    func=get_time,
    description="Returns the current time"
)
Sample Program

This example creates a tool that greets someone by name. Then it uses the tool to greet "Alice".

LangChain
from langchain.agents import Tool

# Define a simple tool function

def greet(name: str) -> str:
    return f"Hello, {name}!"

# Create the tool
hello_tool = Tool(
    name="GreetTool",
    func=greet,
    description="Greets a person by name"
)

# Use the tool
result = hello_tool.func("Alice")
print(result)
OutputSuccess
Important Notes

Tools must have clear descriptions so agents know when to use them.

Functions used in tools should accept a single string argument and return a string.

Test your tool functions separately before adding them to agents.

Summary

Tools let agents perform specific tasks easily.

Create tools by defining a function and wrapping it with Tool.

Give tools clear names and descriptions for best results.