How to build AI agent with Pydantic AI
Quick answer
Use the pydantic-ai package to build AI agents by defining Pydantic models for structured input/output and instantiating an Agent with a model like openai:gpt-4o-mini. Call agent.run_sync() with a prompt to get typed, validated responses.
PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install pydantic-ai openai>=1.0
Setup
Install the pydantic-ai package along with openai SDK. Set your OpenAI API key as an environment variable OPENAI_API_KEY for authentication.
pip install pydantic-ai openai output
Collecting pydantic-ai Collecting openai Installing collected packages: openai, pydantic-ai Successfully installed openai-1.x.x pydantic-ai-x.x.x
Step by step
Define a Pydantic model for the AI agent's structured output. Create an Agent instance specifying the OpenAI model and system prompt. Use agent.run_sync() to send a prompt and receive a typed response.
import os
from pydantic import BaseModel
from pydantic_ai import Agent
# Define structured output model
class Result(BaseModel):
answer: str
confidence: float
# Instantiate the agent with OpenAI GPT-4o-mini
agent = Agent(
"openai:gpt-4o-mini",
result_type=Result,
system_prompt="You are a helpful assistant that provides answers with confidence scores."
)
# Run the agent synchronously with a prompt
result = agent.run_sync("What is Retrieval-Augmented Generation (RAG)?")
print(f"Answer: {result.data.answer}")
print(f"Confidence: {result.data.confidence}") output
Answer: Retrieval-Augmented Generation (RAG) is a technique that combines retrieval of relevant documents with generative models to produce accurate and context-aware responses. Confidence: 0.95
Common variations
- Use
await agent.run()for asynchronous calls in async functions. - Change the model by specifying other OpenAI models like
openai:gpt-4oor Anthropic models withpydantic-aisupport. - Define more complex
Pydanticmodels to extract structured data or multiple fields from AI responses.
import asyncio
async def async_example():
result = await agent.run("Explain RAG in simple terms.")
print(result.data.answer)
asyncio.run(async_example()) output
Retrieval-Augmented Generation (RAG) combines document retrieval with AI generation to improve answer accuracy.
Troubleshooting
- If you get validation errors, ensure your
Pydanticmodel matches the expected AI response structure. - Set
OPENAI_API_KEYcorrectly in your environment to avoid authentication errors. - Use smaller models like
openai:gpt-4o-minifor faster responses during development.
Key Takeaways
- Define structured output with Pydantic models for reliable AI agent responses.
- Use pydantic-ai Agent with OpenAI models for typed, validated AI interactions.
- Support async calls with agent.run() for scalable applications.
- Always set your API key in environment variables to avoid auth issues.
- Customize system prompts and models to tailor agent behavior.