Defining Tools for Your Agent
Create custom tools with the @tool decorator, write clear descriptions the LLM uses to decide when to call each tool, and add input validation with Pydantic.
Defining Tools for Your Agent is a free AI Engineering Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Engineering Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Tools Give Agents Superpowers
An agent without tools can only reason about what it already knows — it cannot search the web, query a database, or send an email. Tools are Python functions that extend the agent's capabilities by letting it take real-world actions and retrieve fresh information. Defining tools clearly is one of the most important steps in building a reliable agent.
The @tool Decorator in LangChain
LangChain's @tool decorator transforms any Python function into a tool the agent can call. The function's docstring becomes the tool description that the LLM uses to decide when to call it. A clear, specific description dramatically improves the agent's tool selection accuracy.
from langchain_core.tools import tool
@tool
def get_weather(city: str) -> str:
'''Get the current weather conditions for a given city.
Use this tool when the user asks about weather in a specific location.
Input should be just the city name, e.g. 'London' or 'New York'.
'''
# Real implementation would call a weather API
return f'The weather in {city} is 18 degrees Celsius and partly cloudy.'
print(get_weather.name) # 'get_weather'
print(get_weather.description) # The docstring aboveType Annotations and Schema Generation
LangChain automatically generates a JSON Schema for each tool from its Python type annotations. The agent receives this schema in the system prompt so it knows what arguments are required, their types, and any constraints. Always annotate your tool functions with precise types.
from langchain_core.tools import tool
@tool
def calculate_compound_interest(
principal: float,
annual_rate: float,
years: int
) -> float:
'''Calculate compound interest earned over a number of years.
Args:
principal: Initial investment amount in dollars.
annual_rate: Annual interest rate as a decimal (e.g. 0.05 for 5%).
years: Number of years to compound.
Returns:
Final amount after compounding.
'''
return principal * (1 + annual_rate) ** years
# Inspect the auto-generated schema
print(calculate_compound_interest.args_schema.schema())Input Validation with Pydantic
For tools with complex inputs, define a Pydantic model as the args_schema. This gives you automatic validation, type coercion, and descriptive field-level documentation that the LLM sees when deciding how to call the tool.
from langchain_core.tools import tool
from pydantic import BaseModel, Field
class SearchInput(BaseModel):
query: str = Field(description='The search query to look up.')
num_results: int = Field(default=5, ge=1, le=20, description='Number of results to return (1-20).')
@tool(args_schema=SearchInput)
def web_search(query: str, num_results: int = 5) -> str:
'''Search the web for current information on any topic.
Use this for facts that may have changed after the model training cutoff.
'''
return f'Searching for "{query}", returning {num_results} results...'Writing Effective Tool Descriptions
The tool description is the most important part of your tool definition — the LLM reads it to decide when and how to call the tool. A good description answers: What does this tool do? When should it be used? What should the input look like? What will the output be?
- Bad: 'Search tool.'
- Good: 'Search the web for current news, facts, or data. Use when the user asks about recent events or facts not in training data. Input: a concise search query.'
Tool Return Types
Tools can return strings, dictionaries, or structured Pydantic objects. However, the agent ultimately needs the result as text to include in the conversation. If you return a dict, LangChain serializes it to a string. For complex nested data, format it as a readable summary rather than raw JSON to help the model reason about it.
from langchain_core.tools import tool
import json
@tool
def get_stock_price(ticker: str) -> str:
'''Look up the current stock price for a given ticker symbol.
Input should be the stock ticker symbol in uppercase, e.g. AAPL or MSFT.
'''
# Stub — real implementation calls a financial API
data = {'ticker': ticker, 'price': 182.50, 'currency': 'USD', 'change': '+1.2%'}
return f'{ticker}: ${data["price"]} ({data["change"]})'Handling Tool Errors Gracefully
Tools fail. APIs go down, network timeouts happen, and users provide invalid inputs. Instead of letting exceptions crash your agent loop, wrap tool logic in try/except and return a descriptive error string. The agent can then reason about the failure and decide whether to retry or use a different approach.
from langchain_core.tools import tool
import requests
@tool
def fetch_url(url: str) -> str:
'''Fetch the text content of a web page given its URL.
Use for accessing specific documents or web pages the user references.
'''
try:
resp = requests.get(url, timeout=10)
resp.raise_for_status()
return resp.text[:2000] # Return first 2000 chars
except requests.Timeout:
return 'Error: Request timed out after 10 seconds.'
except requests.HTTPError as e:
return f'Error: HTTP {e.response.status_code}'
except Exception as e:
return f'Error fetching URL: {str(e)}'Asynchronous Tools
When your agent runs many tool calls or your tools make I/O-bound network requests, define async tool functions to avoid blocking the event loop. LangChain's agent executor supports async tools natively — just use async def in your tool function.
from langchain_core.tools import tool
import httpx
@tool
async def async_fetch(url: str) -> str:
'''Asynchronously fetch content from a URL.
Preferred over fetch_url when making multiple concurrent requests.
'''
async with httpx.AsyncClient(timeout=10) as client:
try:
resp = await client.get(url)
resp.raise_for_status()
return resp.text[:2000]
except Exception as e:
return f'Error: {str(e)}'Organizing Tools into a Toolkit
When you have many related tools, group them into a toolkit — a class that returns a list of tools. LangChain toolkits follow a common pattern: they accept configuration like API keys in the constructor and expose a get_tools() method. This makes tool management clean and reusable across different agents.
from langchain_core.tools import BaseTool
from typing import List
class WeatherToolkit:
def __init__(self, api_key: str):
self.api_key = api_key
def get_tools(self) -> List[BaseTool]:
return [
get_weather, # defined earlier with @tool
get_weather_forecast, # another tool
get_weather_alert # another tool
]
# Usage
toolkit = WeatherToolkit(api_key='your_weather_api_key')
tools = toolkit.get_tools()
print(f'Loaded {len(tools)} weather tools')Limiting Tool Access by User Role
Not every user should have access to every tool. A read-only user should not trigger a send_email or delete_record tool. Implement role-based tool access by selecting which tools to pass to the agent based on the authenticated user's permissions.
def get_tools_for_user(user_role: str) -> list:
read_tools = [web_search, get_weather, calculate_compound_interest]
write_tools = [send_email, create_calendar_event, update_record]
if user_role == 'admin':
return read_tools + write_tools
elif user_role == 'member':
return read_tools
else:
return [web_search] # Guest: only public searchTool Documentation Best Practices
Well-documented tools dramatically reduce agent errors. Follow these best practices: use a clear verb-first name (search_web, not websearch), describe the expected input format explicitly, mention when NOT to use the tool to avoid false positives, and describe what the output looks like so the model can parse it correctly.
Quick Check
Test your understanding of defining tools for LangChain agents.
Lesson Recap
In this lesson you learned: the @tool decorator turns Python functions into agent-callable tools using their docstrings as descriptions, Pydantic schemas add validated typed inputs, and tools should handle errors gracefully by returning descriptive error strings. Next up we assemble a full ReAct agent with LangChain and trace its reasoning steps.
Frequently asked questions
Is the “Defining Tools for Your Agent” lesson free?
Yes — the full text of “Defining Tools for Your Agent” is free to read here on the web, and the AI Engineering Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Engineering Academy course, upgrade to CoddyKit PRO.
What will I learn in “Defining Tools for Your Agent”?
Create custom tools with the @tool decorator, write clear descriptions the LLM uses to decide when to call each tool, and add input validation with Pydantic. You practise AI Engineering Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Engineering Academy?
No prior experience is required. AI Engineering Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Defining Tools for Your Agent” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Engineering Academy lesson?
Yes. Every AI Engineering Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The ReAct Framework: Think, Act, Observe
- Defining Tools for Your Agent
- Building a ReAct Agent with LangChain
- Handling Agent Failures and Loops