Tool Basics
Tools in LangChain are defined using the@tool decorator or by extending BaseTool:
Simple Tool with Decorator
@tool decorator automatically:
- Extracts the function name as tool name
- Uses the docstring as tool description
- Infers parameter schema from type hints
- Creates a
BaseToolsubclass
/libs/core/langchain_core/tools/base.py
Tool with Pydantic Schema
For complex inputs, use Pydantic models:/libs/core/langchain_core/tools/base.py:289
BaseTool Class
For more control, extendBaseTool directly:
Tool Properties
Every tool has these key properties:name
Unique identifier for the tool:description
Helps the LLM understand when to use the tool:args_schema
Pydantic model defining input validation:/libs/core/langchain_core/tools/base.py:289
Tool Invocation
Tools are Runnables and support standard invocation methods:invoke / ainvoke
batch / abatch
With Configuration
Tool Integration with Models
Binding Tools to Models
Modern chat models support native tool calling:Executing Tool Calls
Handle tool call responses:Tool Choice Control
Force or prevent tool usage:Structured Tools
For tools that return structured data:/libs/core/langchain_core/tools/structured.py
Tool Error Handling
Handle tool failures gracefully:Retriever Tools
Convert retrievers to tools:/libs/core/langchain_core/tools/retriever.py
Tool Rendering
Convert tools to various formats:OpenAI Format
JSON Schema
Advanced Tool Patterns
Stateful Tools
Tools that maintain state:Tool with Callbacks
Tool Composition
Compose tools with other Runnables:Best Practices
Write clear tool descriptions
Write clear tool descriptions
The description is critical for LLM tool selection:
Validate inputs with Pydantic
Validate inputs with Pydantic
Use Pydantic models for type safety:
Return user-friendly messages
Return user-friendly messages
Tool outputs should be clear and actionable:
Keep tool scope focused
Keep tool scope focused
Single-purpose tools are easier for LLMs to use correctly:
Next Steps
Agents
Build agents that use tools dynamically
Runnables
Compose tools with other components
Messages
Handle tool messages in conversations
LangGraph
Build advanced tool-using systems