Custom tools allow you to extend LangChain agents with your own functions, APIs, and integrations. The framework provides multiple approaches depending on your needs, from simple function decorators to full class-based implementations.
The simplest way to create a tool is using the @tool decorator. The function signature and docstring automatically generate the tool schema.
from langchain_core.tools import tool@tooldef search_database(query: str, limit: int = 10) -> str: """Search the product database for matching items. Args: query: The search query string. limit: Maximum number of results to return. Returns: JSON string of matching products. """ # Your implementation here results = db.search(query, limit=limit) return json.dumps(results)
The @tool decorator automatically parses your function’s docstring (Google style) to extract parameter descriptions for the LLM.
For I/O-bound operations, define async tools for better performance:
from langchain_core.tools import toolimport aiohttp@toolasync def fetch_weather(city: str) -> str: """Get current weather for a city. Args: city: The city name to fetch weather for. Returns: Weather description and temperature. """ async with aiohttp.ClientSession() as session: async with session.get(f"https://api.weather.com/{city}") as resp: data = await resp.json() return f"{data['condition']}, {data['temp']}°F"
Tools can raise ToolException for graceful error handling:
from langchain_core.tools import tool, ToolException@tooldef validate_and_search(query: str) -> str: """Search with validation. Args: query: Search query to validate and execute. """ if len(query) < 3: raise ToolException( "Query too short. Please provide at least 3 characters." ) if contains_sql_injection(query): raise ToolException( "Invalid query detected. Please check your input." ) return search(query)
Tool names and descriptions are crucial for the LLM to select the right tool. Be specific about what the tool does and when to use it.
@tooldef calculate_roi(investment: float, return_value: float, period_years: int) -> str: """Calculate Return on Investment (ROI) percentage. Use this when the user asks about investment returns, profitability, or financial performance metrics. DO NOT use for simple arithmetic. Args: investment: Initial investment amount in dollars. return_value: Final value in dollars. period_years: Investment period in years. """ roi = ((return_value - investment) / investment) * 100 annual = roi / period_years return f"ROI: {roi:.2f}% ({annual:.2f}% annually)"
Use Type Hints
Type hints are required for automatic schema generation: