Pydantic AI key concepts
Quick answer
pydantic-ai is a Python agent framework that uses Pydantic models to define structured input and output types for AI calls. It supports synchronous and asynchronous execution, typed results, and easy integration of tools as callable functions.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install pydantic-ai openai>=1.0
Setup
Install pydantic-ai and the openai SDK, then set your OpenAI API key as an environment variable.
- Run
pip install pydantic-ai openai - Set
OPENAI_API_KEYin your shell environment
pip install pydantic-ai openai output
Collecting pydantic-ai Collecting openai Successfully installed pydantic-ai openai
Step by step
Define a Pydantic model for the AI response, create an Agent with a model and system prompt, then run a synchronous query.
import os
from pydantic import BaseModel
from pydantic_ai import Agent
class Result(BaseModel):
answer: str
confidence: float
agent = Agent(
"openai:gpt-4o-mini",
result_type=Result,
system_prompt="You are a helpful assistant."
)
result = agent.run_sync("What is retrieval augmented generation?")
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 AI to produce accurate and context-aware responses. Confidence: 0.95
Common variations
You can run Agent asynchronously with await agent.run(), define multiple tools as decorated functions, and switch models by changing the model string.
import asyncio
@agent.tool
def calculator(ctx, expression: str) -> str:
# Simple eval for demo; use safe eval in production
return str(eval(expression))
async def main():
result = await agent.run("Calculate 12 * 7")
print(result.data.answer)
asyncio.run(main()) output
84
Troubleshooting
- If you see
ModuleNotFoundError, ensurepydantic-aiis installed. - If API calls fail, verify
OPENAI_API_KEYis set correctly in your environment. - For model errors, confirm you use a current model name like
gpt-4o-mini.
Key Takeaways
-
pydantic-aiusesPydanticmodels to enforce structured AI input/output. - Agents support both synchronous and asynchronous calls with typed results.
- Tools can be added as decorated Python functions for extended capabilities.
- Model selection is via string identifiers like
openai:gpt-4o-mini. - Always set API keys via environment variables for security and compatibility.