Skip to main content

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

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

Always use Pydantic models for tool parameters when possible. They provide: - Automatic validation
  • Better type safety - Self-documenting schemas - IDE support

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)


Tools provide a powerful way to extend AI model capabilities with custom logic. Use Pydantic models for the best developer experience and type safety.
All tools are automatically validated and converted to the appropriate format for each provider. The SDK handles the complexity of provider-specific implementations.
While JSON schema is still supported for backward compatibility, Pydantic models are recommended for new development due to their superior type safety and validation capabilities.