Calling an LLM often returns unpredictable plain text that breaks downstream Python code when you try to parse JSON manually. Pydantic AI solves this by bringing the same BaseModel validation used in FastAPI directly into Python AI agents. In this beginner guide, you will build a typed study advisor agent whose response is always validated into a Python class.
Student Question → Agent(output_type=StudyPlan) → Pydantic BaseModel Validation → Typed result.output
1. Install Pydantic AI
Install the package and set your API key environment variable (for example, OPENAI_API_KEY):
uv add pydantic-ai
# or: pip install pydantic-ai
2. Create a Typed Agent with output_type
Define a Pydantic BaseModel describing the exact fields you want back, then pass it as output_type to Agent(...):
from pydantic import BaseModel, Field
from pydantic_ai import Agent
class StudyPlan(BaseModel):
topic: str = Field(description="Main subject name")
hours_needed: int = Field(ge=1, le=40)
next_step: str = Field(description="One concrete practice task")
agent = Agent(
"openai:gpt-4o",
output_type=StudyPlan,
instructions="Give concise, practical study plans for beginners.",
)
result = agent.run_sync("I want to learn C# LINQ this weekend.")
print(result.output.topic)
print(result.output.hours_needed)
print(result.output.next_step)
Understand the Key Parts
output_type=StudyPlantells Pydantic AI to validate the model's output against yourBaseModelschema automatically.Field(ge=1, le=40)enforces numeric bounds just like FastAPI request validation.result.outputis an actualStudyPlaninstance with full IDE autocomplete rather than an untyped dictionary.
Practice
- Add a
difficulty: strfield toStudyPlanand print it fromresult.output. - Switch
agent.run_sync(...)toawait agent.run(...)inside anasync def main()function. - Register a Python helper tool using
@agent.tool_plainthat returns recommended prerequisites for a course name.
Continue learning: Python Tutorial for Beginners: Complete Learning Path.
References: Pydantic AI Official Documentation.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.