How to use Pydantic AI with Anthropic
Quick answer
Use
pydantic_ai with anthropic.Anthropic by creating an Anthropic client and passing it to instructor.from_anthropic(). Then define a pydantic.BaseModel for structured output and call client.chat.completions.create() with response_model to parse responses automatically.PREREQUISITES
Python 3.8+Anthropic API keypip install anthropic>=0.20 pydantic-ai>=0.1
Setup
Install the required packages and set your Anthropic API key as an environment variable.
- Install packages:
pip install anthropic pydantic-ai - Set environment variable:
export ANTHROPIC_API_KEY='your_api_key'(Linux/macOS) orset ANTHROPIC_API_KEY=your_api_key(Windows)
pip install anthropic pydantic-ai output
Collecting anthropic Collecting pydantic-ai Successfully installed anthropic-0.20.0 pydantic-ai-0.1.0
Step by step
Use pydantic_ai with Anthropic by creating an Anthropic client and wrapping it with instructor.from_anthropic(). Define a pydantic.BaseModel to specify the expected structured response. Then call client.chat.completions.create() with response_model to get typed output.
import os
from anthropic import Anthropic
import instructor
from pydantic import BaseModel
# Initialize Anthropic client
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
# Wrap Anthropic client with Pydantic AI instructor
pydantic_client = instructor.from_anthropic(client)
# Define Pydantic model for structured extraction
class UserInfo(BaseModel):
name: str
age: int
# Prepare prompt
messages = [{"role": "user", "content": "Extract: John is 30 years old"}]
# Call Anthropic with response_model for structured output
response = pydantic_client.chat.completions.create(
model="claude-3-5-sonnet-20241022",
system="You are a helpful assistant.",
messages=messages,
response_model=UserInfo
)
# Access typed fields
print(f"Name: {response.name}, Age: {response.age}") output
Name: John, Age: 30
Common variations
You can use async calls with pydantic_ai by awaiting the create() method. To use a different Anthropic model, change the model parameter accordingly. For OpenAI, use instructor.from_openai() similarly.
import asyncio
async def main():
response = await pydantic_client.chat.completions.create(
model="claude-3-5-sonnet-20241022",
system="You are a helpful assistant.",
messages=[{"role": "user", "content": "Extract: Alice is 25 years old"}],
response_model=UserInfo
)
print(f"Name: {response.name}, Age: {response.age}")
asyncio.run(main()) output
Name: Alice, Age: 25
Troubleshooting
- If you get a
ValidationError, check that yourBaseModelfields match the expected response format. - If the API returns unexpected text, ensure your prompt clearly instructs the model to respond in JSON matching your model.
- Verify your
ANTHROPIC_API_KEYenvironment variable is set correctly.
Key Takeaways
- Use
instructor.from_anthropic()to integrate Pydantic AI with Anthropic easily. - Define a
pydantic.BaseModelto parse structured responses automatically. - Always set
response_modelinchat.completions.create()for typed output. - Async calls are supported by awaiting the
create()method. - Clear prompt instructions help avoid validation errors and parsing issues.