What You’ll Learn
- How to create custom tool functions
- How to register tools with agents
- How agents automatically decide when to use tools
- How to handle tool results
Prerequisites
Code Example
Create a weather assistant that can fetch weather data:Run the Example
Expected Output
How It Works
- Tool Definition: Functions are defined with type hints and docstrings
- Registration: Tools are passed to the agent via the
toolsparameter - Automatic Selection: The LLM decides when and which tools to use based on the task
- Execution: The agent calls the tool, receives the result, and incorporates it into the response
Tool Requirements
Function Signature
Key Requirements
- Type Hints: All parameters must have type annotations
- Annotated: Use
Annotatedto provide parameter descriptions - Docstring: Required - helps the LLM understand the tool’s purpose
- Return Type: Should return a string or serializable type
Advanced Tool Example
Here’s a more complex tool that performs calculations:Key Concepts
Tool Function
A Python function that extends agent capabilities with specific actions.
Annotated Types
Provides parameter descriptions to help the LLM use tools correctly.
Docstrings
Explains the tool’s purpose so the LLM knows when to use it.
Tool Selection
The LLM automatically decides which tool to use based on context.
Best Practices
- Clear Descriptions: Write detailed docstrings and parameter descriptions
- Error Handling: Always handle errors gracefully and return meaningful messages
- Type Safety: Use proper type hints to prevent runtime errors
- Tool Limits: Set
max_tool_iterationsto prevent infinite loops - Security: Validate inputs and avoid executing arbitrary code
Next Steps
Web Browsing
Use MCP servers to add web browsing capabilities
Code Execution
Execute Python code safely in agent workflows