How to define agents with Pydantic AI
Quick answer
Use the
pydantic_ai.Agent class to define agents by specifying the model string and a Pydantic BaseModel for structured output. Define your result schema with pydantic.BaseModel, instantiate the agent with a system prompt, then call agent.run_sync() to execute the agent with a prompt.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 for API access. Set your OpenAI API key as an environment variable OPENAI_API_KEY before running the code.
pip install pydantic-ai openai>=1.0 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 BaseModel for the agent's structured output, create an Agent instance with the model and system prompt, then run the agent synchronously with a user prompt.
import os
from pydantic import BaseModel
from pydantic_ai import Agent
# Define the structured output schema
class Result(BaseModel):
answer: str
confidence: float
# Instantiate the agent with OpenAI GPT-4o-mini model
agent = Agent(
"openai:gpt-4o-mini",
result_type=Result,
system_prompt="You are a helpful assistant that answers precisely."
)
# 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 string to other OpenAI or Anthropic models, e.g.,
"openai:gpt-4o"or"anthropic:claude-sonnet-4-5". - Define multiple tools or functions as agent methods decorated with
@agent.toolfor extended capabilities.
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 provide accurate and context-rich answers.
Troubleshooting
- If you see
ModuleNotFoundError, ensurepydantic-aiandopenaiare installed. - If the agent returns unexpected output, verify your
BaseModelfields match the expected response format. - For API authentication errors, confirm
OPENAI_API_KEYis set correctly in your environment.
Key Takeaways
- Define agents by combining
pydantic.BaseModelschemas withpydantic_ai.Agentfor structured AI outputs. - Use
agent.run_sync()for synchronous calls andagent.run()for async execution. - Always set your API key in
os.environand specify the model string with provider prefix, e.g.,openai:gpt-4o-mini. - Extend agents with tools by decorating functions with
@agent.toolfor custom capabilities. - Check your model and schema alignment to avoid parsing errors in agent responses.