Pydantic AI: Building Type-Safe Python Agents with Validated Tools

Pydantic AI brings type-safe, validated outputs to Python agents. Learn how output models, validated tools, and typed dependencies work in five steps.

By Galactic News Editorial · Published 2026-11-28T02:06:21+00:00 · Updated 2026-11-28T02:06:21+00:00

Pydantic AI type-safe Python agents with validated tools

Pydantic AI: Building Type-Safe Python Agents with Validated Tools

Pydantic AI is a Python framework from the team behind Pydantic for building LLM agents that return validated, structured outputs. You define the output shape with a Pydantic model, register tools with decorators, and the framework validates everything the model produces. Bad output gets retried. Bad tool arguments never reach your code. This guide covers the core ideas and a first working agent.

The pitch will feel familiar if you have used FastAPI. You describe schemas with type hints, and the framework handles validation. Pydantic AI brings that same feeling to agents.

Why Type Safety Matters for Agents

Raw model output is text. A feature that parses it by hand works in a demo and breaks in production, usually on a Friday night. A missing field, a wrong type, or a stray sentence around the JSON can crash the next step. Type safety moves those failures earlier, where you can see them.

Pydantic AI makes the output contract part of the framework. You define a Pydantic model and pass it as the output type. The framework guarantees the value you get back matches that model. If the model returns something invalid, Pydantic AI sends the validation error back and asks it to try again. Your downstream code receives typed objects, not hopeful strings.

The same idea covers tools. When the model calls one of your tools, Pydantic AI validates the arguments against your function's type hints before the function runs. Bad arguments never reach your business logic.

Pydantic AI Type-Safe Python Agents: The Core Pieces

Five ideas cover most of what you will build.

Agents. The Agent class is the main entry point. You create one with a model identifier and optional instructions. The class is generic over two type parameters: the dependency type and the output type. That is what gives your editor and type checker real visibility into what run_sync returns.

Models as strings. Pydantic AI is provider-agnostic. You pick a model with a string like openai:gpt-4o or anthropic:claude-sonnet-5-5, and swapping providers is a string change. Google Gemini, OpenAI, and Anthropic models support structured outputs best. Other providers vary.

Structured output. Pass a Pydantic model as output_type, and the agent's result is validated against it. You get a typed object back, and your IDE knows every field.

Tools. Register a Python function with the @agent.tool decorator, or @agent.tool_plain when the function needs no context. Pydantic AI reads the function's type hints and docstring to build the schema the model sees. Then it validates every call against that schema.

Dependencies. The deps_type parameter declares the type of runtime context your agent needs, such as a database connection. System prompt functions and tools receive it through a RunContext object. That keeps dependencies typed and out of global state.

There are three ways to run an agent: agent.run() for async code, agent.run_sync() for plain synchronous code, and agent.run_stream() to stream the response. Each returns a result object with the typed output, the message history, and usage data.

Build Your First Agent in Five Steps

  1. Install the library. Run pip install pydantic-ai, or uv add pydantic-ai. Set the API key for your provider, such as OPENAI_API_KEY or ANTHROPIC_API_KEY.
  2. Define the output shape. A small Pydantic model sets the contract:
from pydantic import BaseModel, Field

class Sentiment(BaseModel):
    label: str
    score: float = Field(ge=-1, le=1)
  1. Create the agent. Pass the model string and the output type:
from pydantic_ai import Agent

agent = Agent(
    "openai:gpt-4o",
    output_type=Sentiment,
    instructions="Classify the sentiment of product reviews.",
)
  1. Add a validated tool. The decorator registers the function, and its type hints become the schema:
@agent.tool_plain
def multiply(a: float, b: float) -> float:
    """Multiply two numbers."""
    return a * b
  1. Run it. Call run_sync with a prompt and read the typed result:
result = agent.run_sync(
    "How are people feeling about the Extract app?"
)
print(result.output)

The result is a Sentiment object, not a string. If the model returns a label outside the expected shape, the framework retries with the validation error attached.

Validated Tools and Dependency Injection

Tools are where agents touch the real world: a database, a REST API, a calculation. Two patterns keep them safe.

First, validation happens before execution. The model sends arguments, Pydantic AI checks them against the function's type hints, and only valid calls run. If validation fails, the error goes back to the model so it can try again. A wrong type never reaches your database query.

Second, dependencies arrive through RunContext. A tool that needs a database connection takes a RunContext typed with your dependency class. The agent is created with deps_type set to that class, and you pass the live connection when you run it. Your tools stay testable, because you can pass a fake dependency in tests. Pydantic AI also ships a test model that replaces real calls, so you can unit test agent logic without network access.

Pydantic AI vs Other Python Frameworks

FrameworkBest forType safetyTrade-off
Pydantic AITyped agents and structured extractionBuilt in, end to endSmaller ecosystem than LangChain
LangChainLarge ecosystem of integrationsPartialMore moving parts to learn
LangGraphComplex multi-step workflowsPartialMore setup for simple agents
Raw provider SDKFull control, minimal dependenciesManualYou build validation and retries yourself

Pick Pydantic AI when validated, typed output is the point of the feature. Pick LangChain or LlamaIndex when you need a large ecosystem of pre-built integrations such as vector stores and retrievers. Pick LangGraph when one agent loop is not enough and you need explicit control flow. Pydantic AI itself offers Pydantic Graph for that case, a typed graph library for multi-step flows.

Limits to Know

Bottom Line

Pydantic AI is the right choice when your agent's output must fit a shape every time. Define the output model, register validated tools, inject typed dependencies, and let the framework handle validation and retries. The FastAPI-style experience transfers well. Start with one small agent, one output model, and one tool. Add complexity only after the typed contract proves itself in production.