Pydantic-AI

Typed, validated LLM calls with RunContext, TestModel, and provider-neutral agents.

Built by the team behind Pydantic — the validation library already running inside FastAPI and most other Python AI tools. The core idea: treat an LLM call like a typed function call, not a string-in-string-out black box.

Core concepts

  1. Typed, validated output: Pass Agent() an output_type and get back a validated Pydantic model instead of a raw string, with automatic retries if the model returns something that doesn't fit. Pydantic-AI Docs
  2. @agent.tool and @agent.tool_plain: Register tools two ways — tool_plain for stateless functions, tool when a tool needs RunContext for dependency injection.
  3. RunContext dependency injection: Pass a database connection, an authenticated user, or an HTTP client into every tool call without reaching for global state.
  4. TestModel: A substitute for a real LLM in unit tests — deterministic, fast, offline test runs without burning API credits on every CI run.
  5. Provider-neutral: Supports OpenAI, Anthropic, Google, Groq, Mistral, Bedrock, and any OpenAI-compatible endpoint — swapping providers is usually one string.

Why it matters

Production agents need predictable structures for downstream APIs and UI. TestModel also lets CI run without spending tokens.

Where people get stuck

  • Loose schemas with dozens of optional fields. Models fill them with noise, so keep only what you use.
  • Skipping TestModel in CI. Tool routing regresses silently whenever a prompt changes.
  • One giant model class that mixes validation with business rules. Keep them apart.

Try this

Define a Pydantic model for a tool result, write a TestModel test that checks the parsing and run pytest in CI.

Interview question

Why validate LLM output with Pydantic?

Models get structure wrong. Validation fails fast before bad data reaches a database, a payment or a user, and the error message feeds a retry.

Resources

YouTube learning

Core concepts from video walkthroughs:

Threads in the same domain as this chapter — go deeper on iHateReading without leaving the roadmap.

Python AI agent SDKs in 2026: OpenAI vs Pydantic-AI vs smolagents vs Strands cover

Python AI agent SDKs in 2026: OpenAI vs Pydantic-AI vs smolagents vs Strands

Same three-tool agent in four frameworks — pick by execution model and testing needs.

Agent harnessing: the part of building AI agents nobody talks about cover

Agent harnessing: the part of building AI agents nobody talks about

Loop, tools, memory, sandbox, and tracing live in your code — not the model weights.

Smallest AI Agent cover

Smallest AI Agent

Minimal file-reading agent to learn LLM tool loops without framework magic.