Skip to content
Agentic Levels
Start hereLevelsTracksPromptsAbout
Get my levelGet my level

  • Start hereYour first useful task with AI.
  • Level quiz8 questions. No AI needed.
  • Fluency ScoreYour Level and a score, from your own AI.

  • LevelsThe 11 levels, in order.
  • LessonsShort lessons, filter by level.
  • TracksGuided paths by tool, role or goal.
  • Set up your AI tool
  • Starter packFree files that help AI remember.

  • PromptsReady prompts to copy and adapt.
  • ChatGPT vs Claude vs GeminiPick the right one for the job.
  • How-tos
  • ReferenceCommands for Claude Code, Codex, Antigravity.
  • ResourcesHand-picked reading and tools.

  • Your progress
  • Your next moveAn interview that picks your next skill.
  • Your next lessonsThe next lessons at your level.
  • Updates

  • Pricing
  • About
  • FAQ & Feedback
  • Work with us
  • How we handle your data
Sign inPreferences
AboutPricingHow-tosPromptsStarter packMy stackHow we handle your data

© 2026 Fuentes Studio

PrivacyTermsRefundsAccessibilityAI content policyCredits
yourCouncil
Ready to help
✦

What do you want to understand?

Ask anything about what you're learning.

←How-to guides
  1. Resources
  2. ›How-to guides

How to use PydanticAI

Production Python agent framework with type-safe Pydantic validation, durable execution, A2A communication, and Logfire observability, model-agnostic.

Levels 3 to 5On GitHub

Your agent returns freeform text and downstream code has to parse it incorrectly. You want typed, validated outputs, but also durable execution that survives failures and auto-resumes, human-in-the-loop approval workflows, and Agent-to-Agent communication without custom protocol code. PydanticAI is a production-grade Python framework that delivers all of these: type safety via Pydantic, graph-based workflows, MCP protocol support, Logfire observability integration, and model-agnostic routing across all major providers.

Before you start

Python 3.10+ • pip install pydantic-ai

  1. 1Install PydanticAI and define your first result model
  2. 2Add tool use and dependency injection
  3. 3Add observability and test the validation contract

Steps

01

Install PydanticAI and define your first result model

Define a Pydantic model for the shape of output you want from the agent. PydanticAI wraps the model call and validates the response before returning it, bad shape = exception, not a silently broken dict.

Design your result model
I'm building an agent that [AGENT_DOES]. The output should contain: [OUTPUT_FIELDS]. Write a PydanticAI agent with a result model that captures this structure. Include validation rules for any fields with constraints.
[AGENT_DOES]What your agent does e.g. extracts structured data from customer emails
[OUTPUT_FIELDS]Output fields and types e.g. customer_name: str, intent: Literal['refund','question','complaint'], urgency: int 1-5
02

Add tool use and dependency injection

PydanticAI supports typed tools and dependency injection, making agents testable. Define tools as typed Python functions. The agent calls them and the return values are validated too.

Scaffold a tool-using agent
I'm building a PydanticAI agent that needs access to: [TOOLS_NEEDED]. Show me how to define these as @agent.tool functions with typed inputs and outputs. Include the dependency injection setup so the tools can share a DB connection or HTTP client without passing it explicitly.
[TOOLS_NEEDED]Tools your agent needs e.g. web search, file read, a database query function
03

Add observability and test the validation contract

PydanticAI integrates with Logfire for structured tracing of every agent run, tool call, and validation step. Set LOGFIRE_TOKEN and call logfire.configure() before running, then write a test that passes bad input and asserts the validation error, proving your schema contract works.

Write a validation contract test
My PydanticAI agent has this result model: [RESULT_MODEL]. Write a pytest test that (1) runs the agent with a prompt that should produce valid output and asserts the fields, (2) mocks an invalid LLM response and asserts a ValidationError is raised. Show me the test setup with a TestModel backend so I don't need a real API key.
[RESULT_MODEL]Your Pydantic result model e.g. class SupportTicket(BaseModel): category: Literal['billing','tech','other']; urgency: int; summary: str

How do you know it worked?

  • Agent returns typed, validated output, not raw strings
  • Invalid output raises a validation error instead of silently passing
  • At least one tool defined with typed inputs and outputs

If something looks off

Schema round-trip cost
PydanticAI adds a schema round-trip, slightly more expensive per call; worth it for production pipelines but profile it first.
Test with your actual model
Complex nested models can confuse smaller models. Verify the schema works with your specific model before assuming it handles it.

Skills & Commands Reference

PydanticAI's core building blocks, result models, tools, dependency injection, and Graph for durable workflows.

Command / SkillWhat it doesWhen to use it
result_type=YourModelDeclare the output shape as a Pydantic model, agent validates and returns typed output, not raw textAny agent where downstream code needs to parse the response, always use this over string outputs
@agent.toolDecorator that exposes a typed Python function as a tool the agent can callGiving the agent access to external data, APIs, or computations, type hints become the tool schema
RunContext[Deps]Typed dependency injection container, share HTTP clients, DB connections, and config across toolsAny agent with tools that need shared resources, enables testing without mocking the LLM
agent.run() / run_sync()Async and sync entry points, run() for FastAPI/async contexts, run_sync() for scripts and notebooksChoose based on your runtime: async app = run(), script = run_sync()
PydanticAI GraphadvancedDurable graph-based workflows, checkpointed state, resumable runs, human-in-the-loop nodesMulti-step workflows that must survive failures or need a human approval checkpoint between steps
Logfire integrationadvancedBuilt-in observability, traces every agent run, tool call, and validation event with structured logsSet LOGFIRE_TOKEN before writing any agent logic, debugging without it is significantly harder

See also

  • FastMCP: build MCP servers
  • AI Engineering Hub

What you'll do, 3 steps

  1. 1Install PydanticAI and define your first result model
  2. 2Add tool use and dependency injection
  3. 3Add observability and test the validation contract

Was this helpful?