Overview
The AI SDK provides a lightweight tool calling system that allows you to define functions that can be called by language models. Tools couple a JSON schema (name, description, parameters) with a Python handler function, enabling the model to execute custom logic.Quick Start
Using Pydantic Models (Recommended)
For better type safety and validation, use Pydantic models:JSON Schema (Legacy)
For backward compatibility, you can still use JSON schema:Using Tools with Language Models
Basic Usage
Streaming with Tools
Advanced Tool Examples
Complex Pydantic Model with Validation
Calculator with Multiple Operations
Async Tool Functions
Tool Validation
Automatic Validation with Pydantic
When using Pydantic models, the tool automatically validates inputs:Manual Validation
Tool Execution
Direct Tool Execution
Tool Execution with Validation
Best Practices
1. Use Pydantic Models
2. Provide Clear Descriptions
3. Handle Errors Gracefully
4. Use Async for I/O Operations
Tool Schema Generation
From Pydantic Models
The SDK automatically converts Pydantic models to JSON schema:Manual JSON Schema
For backward compatibility, you can still use manual JSON schema:Error Handling
Validation Errors
Runtime Errors
Provider Compatibility
OpenAI Function Calling
Tools are automatically converted to OpenAI’s function calling format:Anthropic Tool Use
Tools work with Claude models through the OpenAI compatibility layer:Advanced Patterns
Tool Composition
Tool with Context
Migration from JSON Schema
If you have existing tools using JSON schema, you can easily migrate to Pydantic models:Before (JSON Schema)
After (Pydantic Model)
All tools are automatically validated and converted to the appropriate format for each provider.
The SDK handles the complexity of provider-specific implementations.