Multi-agent with Pydantic AI
Quick answer
Use pydantic_ai to create multiple typed AI agents by defining distinct Agent instances with specific roles and response models. Coordinate these agents by invoking them sequentially or in parallel, passing outputs as inputs to enable multi-agent workflows.
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 to authenticate requests.
- Install packages:
pip install pydantic-ai openai - Set environment variable:
export OPENAI_API_KEY='your_api_key'(Linux/macOS) orsetx OPENAI_API_KEY "your_api_key"(Windows)
pip install pydantic-ai openai output
Collecting pydantic-ai Collecting openai Successfully installed pydantic-ai-0.x.x openai-1.x.x
Step by step
Define two AI agents with pydantic_ai.Agent, each with a distinct role and response model. The first agent generates a question, and the second agent answers it. This demonstrates multi-agent orchestration by passing data between agents.
import os
from pydantic import BaseModel
from pydantic_ai import Agent
# Define response models
class Question(BaseModel):
question: str
class Answer(BaseModel):
answer: str
# Initialize agents with system prompts and models
agent_ask = Agent(
"openai:gpt-4o-mini",
result_type=Question,
system_prompt="You are a curious assistant that generates interesting questions."
)
agent_answer = Agent(
"openai:gpt-4o-mini",
result_type=Answer,
system_prompt="You are a knowledgeable assistant that answers questions clearly."
)
# Run first agent to generate a question
question_result = agent_ask.run_sync("Generate a thought-provoking question about AI.")
print(f"Generated question: {question_result.data.question}")
# Pass the question to the second agent to get an answer
answer_result = agent_answer.run_sync(question_result.data.question)
print(f"Answer: {answer_result.data.answer}") output
Generated question: What are the ethical implications of AI in decision-making? Answer: The ethical implications include bias, accountability, transparency, and the potential impact on privacy and employment.
Common variations
You can extend multi-agent workflows by:
- Using asynchronous calls with
await agent.run()for concurrency. - Defining agents with different models like
claude-sonnet-4-5orgpt-4o. - Adding tools or plugins to agents for enhanced capabilities.
- Chaining multiple agents to build complex pipelines.
import asyncio
async def async_multi_agent():
question = await agent_ask.run("Generate a question about climate change.")
answer = await agent_answer.run(question.data.question)
print(f"Async question: {question.data.question}")
print(f"Async answer: {answer.data.answer}")
asyncio.run(async_multi_agent()) output
Async question: How can AI help mitigate climate change? Async answer: AI can optimize energy use, improve climate modeling, and support sustainable practices.
Troubleshooting
- If you get authentication errors, verify your
OPENAI_API_KEYenvironment variable is set correctly. - For unexpected response parsing errors, ensure your
BaseModelmatches the expected AI output structure. - If agents return incomplete answers, increase
max_tokensin theAgentconstructor viamodel_kwargs.
Key Takeaways
- Use multiple Agent instances with typed BaseModel responses to build multi-agent workflows.
- Pass outputs from one agent as inputs to another to orchestrate complex AI interactions.
- Support async execution for concurrent multi-agent calls to improve efficiency.