Définir des outils pour votre Agent
Créez des outils personnalisés avec le décorateur @tool, rédigez des descriptions claires permettant au LLM de décider quand appeler chaque outil et ajoutez une validation des entrées avec Pydantic.
Définir des outils pour votre Agent est une leçon AI Engineering Academy gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage AI Engineering Academy, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours AI Engineering Academy comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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.
Questions Fréquemment Posées
La leçon « Définir des outils pour votre Agent » est-elle gratuite ?
Oui — le texte complet de « Définir des outils pour votre Agent » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours AI Engineering Academy, passe à CoddyKit PRO. Le cours AI Engineering Academy comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Définir des outils pour votre Agent » ?
Créez des outils personnalisés avec le décorateur @tool, rédigez des descriptions claires permettant au LLM de décider quand appeler chaque outil et ajoutez une validation des entrées avec Pydantic. Tu pratiques AI Engineering Academy avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer AI Engineering Academy ?
Aucune expérience préalable n'est requise. AI Engineering Academy sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.
Combien de temps prend la leçon « Définir des outils pour votre Agent » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon AI Engineering Academy ?
Oui. Chaque leçon AI Engineering Academy inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Le cadre ReAct : réfléchir, agir, observer
- Définir des outils pour votre Agent
- Construire un Agent ReAct avec LangChain
- Gérer les échecs et les boucles des agents