Tool

Build production-grade GenAI agents with type-safe Python

Pydantic AI is a type-safe Python agent framework with model-agnostic support and built-in observability.

Works with openaianthropicgeminideepseekgrok

91
Spark score
out of 100
Updated today
Version 2.20.0

Add to Favorites

Why it matters

Build reliable, production-ready generative AI agents and workflows in Python with full type safety, structured outputs, observability, and support for virtually every LLM provider-bringing the FastAPI developer experience to GenAI application development.

Outcomes

What it gets done

01

Create type-safe agents with structured outputs validated by Pydantic

02

Connect agents to external tools via MCP and custom capabilities

03

Monitor agent behavior and costs with built-in Logfire observability

04

Build durable workflows with human-in-the-loop approval and streaming

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/pydantic-pydantic-ai | bash

Overview

Pydantic Ai

Pydantic AI is a Python agent framework from the Pydantic team, bringing FastAPI-level type safety and ergonomics to GenAI agent development, with model-agnostic support and built-in observability. Use it to build production GenAI agents in Python needing type-safe structured output, model flexibility, and observability. Fits teams already using Pydantic Validation elsewhere.

What it does

Pydantic AI is a Python agent framework built by the Pydantic team to bring the same ergonomic, type-safe feel that FastAPI brought to web development to GenAI agent development. Agents are built from composable capabilities - tools, hooks, instructions, and model settings - with built-in capabilities for web search, thinking, and MCP, a capability library called the Pydantic AI Harness, and support for defining agents entirely in YAML/JSON with no code.

When to use - and when NOT to

Use it to build production-grade GenAI applications and agents in Python when type safety, structured output validation, and observability matter - it integrates Pydantic Logfire, or any other OpenTelemetry backend, for real-time debugging, tracing, and cost tracking, and ships systematic evals to test and monitor agent performance over time. It is model-agnostic - OpenAI, Anthropic, Gemini, DeepSeek, Grok, Cohere, Mistral, Perplexity, and providers like Azure AI Foundry, Amazon Bedrock, Google Cloud, Ollama, LiteLLM, Groq, OpenRouter, and more, plus custom models - so it fits regardless of which model a team standardizes on. It is a natural fit for teams already using Pydantic Validation elsewhere in their stack - it is the same validation layer already underpinning the OpenAI SDK, Google ADK, Anthropic SDK, LangChain, LlamaIndex, and several other frameworks.

Inputs and outputs

Input: an Agent definition (model string, instructions, optional dependencies type and output type) plus registered tools and capabilities. Output: validated, typed agent responses - either plain text or a Pydantic-modeled structured output that's guaranteed to match its schema, retried automatically if validation fails.

from pydantic_ai import Agent

agent = Agent(
    'anthropic:claude-sonnet-4-6',
    instructions='Be concise, reply with one sentence.',
)

result = agent.run_sync('Where does "hello world" come from?')
print(result.output)

Dependency injection carries typed context, such as a database connection and customer ID, into both dynamic instructions and @agent.tool-decorated functions via RunContext, with tool docstrings automatically becoming the tool's LLM-facing description and argument validation errors fed back to the model so it can retry. Beyond a single request/response, it supports human-in-the-loop tool approval (flagging specific tool calls for approval based on arguments or context), durable execution that preserves progress across transient failures and restarts, continuously streamed structured output, and type-hint-defined graphs for complex control flow.

Integrations

Speaks the Model Context Protocol, Agent2Agent (A2A), and various UI event-stream standards for external tool access, cross-agent interoperability, and streaming interactive applications, and connects to Pydantic Logfire, or any OTel-compatible observability backend, for tracing and cost monitoring.

Who it's for

Python developers building production GenAI applications and agents who want FastAPI-level ergonomics and type safety, model flexibility across virtually every major provider, and built-in observability and evals rather than assembling those pieces from separate libraries.

Source README

GenAI Agent Framework, the Pydantic way

CI Coverage PyPI versions license Join Slack

Documentation: ai.pydantic.dev


Pydantic AI is a Python agent framework designed to help you quickly, confidently, and painlessly build production grade applications and workflows with Generative AI.

FastAPI revolutionized web development by offering an innovative and ergonomic design, built on the foundation of Pydantic Validation and modern Python features like type hints.

Yet despite virtually every Python agent framework and LLM library using Pydantic Validation, when we began to use LLMs in Pydantic Logfire, we couldn't find anything that gave us the same feeling.

We built Pydantic AI with one simple aim: to bring that FastAPI feeling to GenAI app and agent development.

Why use Pydantic AI

  1. Built by the Pydantic Team:
    Pydantic Validation is the validation layer of the OpenAI SDK, the Google ADK, the Anthropic SDK, LangChain, LlamaIndex, AutoGPT, Transformers, CrewAI, Instructor and many more. Why use the derivative when you can go straight to the source? :smiley:

  2. Model-agnostic:
    Supports virtually every model and provider: OpenAI, Anthropic, Gemini, DeepSeek, Grok, Cohere, Mistral, and Perplexity; Azure AI Foundry, Amazon Bedrock, Google Cloud, Ollama, LiteLLM, Groq, OpenRouter, Together AI, Fireworks AI, Cerebras, Hugging Face, GitHub, Heroku, Vercel, Nebius, OVHcloud, Alibaba Cloud, SambaNova, and Z.AI. If your favorite model or provider is not listed, you can easily implement a custom model.

  3. Seamless Observability:
    Tightly integrates with Pydantic Logfire, our general-purpose OpenTelemetry observability platform, for real-time debugging, evals-based performance monitoring, and behavior, tracing, and cost tracking. If you already have an observability platform that supports OTel, you can use that too.

  4. Fully Type-safe:
    Designed to give your IDE or AI coding agent as much context as possible for auto-completion and type checking, moving entire classes of errors from runtime to write-time for a bit of that Rust "if it compiles, it works" feel.

  5. Powerful Evals:
    Enables you to systematically test and evaluate the performance and accuracy of the agentic systems you build, and monitor the performance over time in Pydantic Logfire.

  6. Extensible by Design:
    Build agents from composable capabilities that bundle tools, hooks, instructions, and model settings into reusable units. Use built-in capabilities for web search, thinking, and MCP, pick from the Pydantic AI Harness capability library, build your own, or install third-party capability packages. Define agents entirely in YAML/JSON - no code required.

  7. MCP and UI:
    Integrates the Model Context Protocol and various UI event stream standards to give your agent access to external tools and data and build interactive applications with streaming event-based communication.

  8. Human-in-the-Loop Tool Approval:
    Easily lets you flag that certain tool calls require approval before they can proceed, possibly depending on tool call arguments, conversation history, or user preferences.

  9. Durable Execution:
    Enables you to build durable agents that can preserve their progress across transient API failures and application errors or restarts, and handle long-running, asynchronous, and human-in-the-loop workflows with production-grade reliability.

  10. Streamed Outputs:
    Provides the ability to stream structured output continuously, with immediate validation, ensuring real time access to generated data.

  11. Graph Support:
    Provides a powerful way to define graphs using type hints, for use in complex applications where standard control flow can degrade to spaghetti code.

Realistically though, no list is going to be as convincing as giving it a try and seeing how it makes you feel!

Hello World Example

Here's a minimal example of Pydantic AI:

from pydantic_ai import Agent

# Define a very simple agent including the model to use, you can also set the model when running the agent.
agent = Agent(
    'anthropic:claude-sonnet-4-6',
    # Register static instructions using a keyword argument to the agent.
    # For more complex dynamically-generated instructions, see the example below.
    instructions='Be concise, reply with one sentence.',
)

# Run the agent synchronously, conducting a conversation with the LLM.
result = agent.run_sync('Where does "hello world" come from?')
print(result.output)
"""
The first known use of "hello, world" was in a 1974 textbook about the C programming language.
"""

(This example is complete, it can be run "as is", assuming you've installed the pydantic_ai package)

The exchange will be very short: Pydantic AI will send the instructions and the user prompt to the LLM, and the model will return a text response.

Not very interesting yet, but we can easily add tools, dynamic instructions, structured outputs, or composable capabilities to build more powerful agents.

Here's the same agent with thinking and web search capabilities:

from pydantic_ai import Agent
from pydantic_ai.capabilities import Thinking, WebSearch

agent = Agent(
    'anthropic:claude-sonnet-4-6',
    instructions='Be concise, reply with one sentence.',
    capabilities=[Thinking(), WebSearch()],
)

result = agent.run_sync('What was the mass of the largest meteorite found this year?')
print(result.output)

Tools & Dependency Injection Example

Here is a concise example using Pydantic AI to build a support agent for a bank:

(Better documented example in the docs)

from dataclasses import dataclass

from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext

from bank_database import DatabaseConn


# SupportDependencies is used to pass data, connections, and logic into the model that will be needed when running
# instructions and tool functions. Dependency injection provides a type-safe way to customise the behavior of your agents.
@dataclass
class SupportDependencies:
    customer_id: int
    db: DatabaseConn


# This Pydantic model defines the structure of the output returned by the agent.
class SupportOutput(BaseModel):
    support_advice: str = Field(description='Advice returned to the customer')
    block_card: bool = Field(description="Whether to block the customer's card")
    risk: int = Field(description='Risk level of query', ge=0, le=10)


# This agent will act as first-tier support in a bank.
# Agents are generic in the type of dependencies they accept and the type of output they return.
# In this case, the support agent has type `Agent[SupportDependencies, SupportOutput]`.
support_agent = Agent(
    'openai:gpt-5.2',
    deps_type=SupportDependencies,
    # The response from the agent will be guaranteed to be a SupportOutput,
    # if validation fails the agent is prompted to try again.
    output_type=SupportOutput,
    instructions=(
        'You are a support agent in our bank, give the '
        'customer support and judge the risk level of their query.'
    ),
)


# Dynamic instructions can make use of dependency injection.
# Dependencies are carried via the `RunContext` argument, which is parameterized with the `deps_type` from above.
# If the type annotation here is wrong, static type checkers will catch it.
@support_agent.instructions
async def add_customer_name(ctx: RunContext[SupportDependencies]) -> str:
    customer_name = await ctx.deps.db.customer_name(id=ctx.deps.customer_id)
    return f"The customer's name is {customer_name!r}"


# The `tool` decorator let you register functions which the LLM may call while responding to a user.
# Again, dependencies are carried via `RunContext`, any other arguments become the tool schema passed to the LLM.
# Pydantic is used to validate these arguments, and errors are passed back to the LLM so it can retry.
@support_agent.tool
async def customer_balance(
        ctx: RunContext[SupportDependencies], include_pending: bool
) -> float:
    """Returns the customer's current account balance."""
    # The docstring of a tool is also passed to the LLM as the description of the tool.
    # Parameter descriptions are extracted from the docstring and added to the parameter schema sent to the LLM.
    balance = await ctx.deps.db.customer_balance(
        id=ctx.deps.customer_id,
        include_pending=include_pending,
    )
    return balance


...  # In a real use case, you'd add more tools and a longer system prompt


async def main():
    deps = SupportDependencies(customer_id=123, db=DatabaseConn())
    # Run the agent asynchronously, conducting a conversation with the LLM until a final response is reached.
    # Even in this fairly simple case, the agent will exchange multiple messages with the LLM as tools are called to retrieve an output.
    result = await support_agent.run('What is my balance?', deps=deps)
    # The `result.output` will be validated with Pydantic to guarantee it is a `SupportOutput`. Since the agent is generic,
    # it'll also be typed as a `SupportOutput` to aid with static type checking.
    print(result.output)
    """
    support_advice='Hello John, your current account balance, including pending transactions, is $123.45.' block_card=False risk=1
    """

    result = await support_agent.run('I just lost my card!', deps=deps)
    print(result.output)
    """
    support_advice="I'm sorry to hear that, John. We are temporarily blocking your card to prevent unauthorized transactions." block_card=True risk=8
    """

Next Steps

To try Pydantic AI for yourself, install it and follow the instructions in the examples.

Read the docs to learn more about building applications with Pydantic AI.

Read the API Reference to understand Pydantic AI's interface.

Join Slack or file an issue on GitHub if you have any questions.

Part of the Pydantic Stack

The Pydantic Stack is everything you need to ship production-grade AI agents:

Discussion

Questions & comments ยท 0

Sign In Sign in to leave a comment.