Module 9 Lesson 2: Defining Custom Tools (The @tool Decorator)
Creating Superpowers. How to turn any Python function into a LangChain tool using a simple decorator.
Creating Custom Tools: The @tool Decorator
LangChain makes it incredibly easy to turn a standard Python function into an AI-ready tool. We use the @tool decorator. This automatically extracts the function name, its arguments, and its docstring to create the JSON schema required by the LLM.
1. The Basic Implementation
from langchain_core.tools import tool
@tool
def multiply(a: int, b: int) -> int:
"""Multiply two integers together."""
return a * b
# Inspect the tool
print(multiply.name)
print(multiply.description)
print(multiply.args)
2. The Docstring is Documentation
Notice the triple-quoted string """Multiply...""". LangChain uses this exact text as the "Instruction" for the LLM. If you forget the docstring, some models will refuse to use the tool because they don't know what it's for.
3. Sophisticated Arguments with Pydantic
If your tool needs complex logic (e.g., "Create a user with a name, age, and email"), you can define a Pydantic Schema to ensure the LLM sends you valid data.
from pydantic import BaseModel, Field
class SearchInput(BaseModel):
query: str = Field(description="The search term to look for.")
@tool("web_search", args_schema=SearchInput)
def search(query: str) -> str:
"""Search the internet for current events."""
return "Results for " + query
4. Visualizing Tool Conversion
graph LR
Code[Python Function] --> Decorator[@tool]
Decorator -->|Extract| Name[Name]
Decorator -->|Extract| Desc[Docstring]
Decorator -->|Extract| Args[JSON Schema]
Args --> LLM[Model Integration]
5. Engineering Tip: Error Handling
Always wrap your tool logic in a try/except block. If your multiply function crashes because the AI sent a string instead of an int, the agent will die. Instead, return the error as a string so the agent can "Read" it and try again.
- Return: "Error: 'a' must be a number. Please try again."
Key Takeaways
@toolis the fastest way to build custom capabilities.- Docstrings act as natural language instructions for the AI.
- Pydantic schemas enforce strict data types on the AI's output.
- Graceful failures in tools help agents recover and self-correct.