PydanticAI Tutorial: Building Reliable AI Agents in Python

AI agents are becoming useful tools for automating research, answering questions, processing business information, and interacting with external applications. Python developers can now build these systems using frameworks that simplify communication between large language models (LLMs), application logic, and external tools.

One framework worth exploring is PydanticAI. Developed by the team behind Pydantic, it brings Python’s type system and data validation capabilities into AI agent development. It helps developers create agents that return structured information, use custom tools, and work with application dependencies.

This PydanticAI tutorial explains how the framework works, how to create a basic agent in Python, and how to extend it with tools and structured outputs. It also explores practical business applications and important considerations before deployment.

What Is PydanticAI?

PydanticAI is a Python framework for building applications powered by large language models. It provides an agent interface that connects an LLM with instructions, tools, dependencies, and optional structured output types.

Its main advantage is its emphasis on type safety. Developers can define the expected format of an agent’s response using Python types or Pydantic models. The framework can then validate the generated output, helping applications work with predictable data instead of relying entirely on unstructured text.

PydanticAI supports multiple model providers, allowing developers to select a compatible model without redesigning the entire application. It can also be used in different environments, including web applications, command-line programs, and background tasks.

Why Use PydanticAI for Agent Development?

Traditional LLM applications often send a prompt to a model and display the response. An AI agent can go further by using tools, accessing application data, and completing multiple steps.

PydanticAI makes this process easier to structure through several capabilities.

Type-safe outputs: Developers can define the expected response format, such as a customer record, product summary, or classification result.

Function tools: Agents can call Python functions to retrieve information or perform specific operations.

Dependency injection: Application resources, such as database connections and service clients, can be passed into agent tools in a structured way.

Model flexibility: Developers can configure supported model providers according to project requirements.

Validation and retries: Invalid tool arguments or structured outputs can trigger retry behavior, depending on the configured limits.

These features help developers create applications that are easier to test, maintain, and integrate with existing Python systems.

PydanticAI Tutorial: How to Build Your First Agent

Let’s create a simple AI agent that classifies customer messages. The example uses Python and a model provider configured through an environment variable.

Step 1: Set Up Your Python Environment

Start by creating a new project and installing PydanticAI. The framework requires Python 3.11 or newer.

You can install it using pip:

pip install pydantic-ai

Alternatively, if you use the uv package manager:

uv add pydantic-ai

You will also need an API key for the model provider you choose. Store the key in an environment variable rather than placing it directly inside your source code.

For example, when using an OpenAI-compatible provider:

export OPENAI_API_KEY=”your-api-key”

On Windows PowerShell, you can set the variable with:

$env:OPENAI_API_KEY=”your-api-key”

Step 2: Create a Basic AI Agent

Create a Python file named customer_agent.py. Import the Agent class and define the model you want to use.

from pydantic_ai import Agent

agent = Agent(

    “openai:gpt-4o”,

    instructions=”You are a helpful customer support assistant. “

                 “Give clear and concise answers.”

)

result = agent.run_sync(

    “A customer says their order has not arrived. “

    “Suggest a helpful response.”

)

print(result.output)

This example creates an agent with a defined role and sends it a customer support request. The model generates a response based on the instructions.

The model name is an example; choose a currently supported model available through your provider account. You can also configure a different provider using its supported model identifier and credentials.

Step 3: Define Structured Output

For business applications, receiving predictable data can be more useful than receiving a paragraph of text.

PydanticAI supports structured outputs through Pydantic models. For example, a customer message can be classified by category and urgency.

from typing import Literal

from pydantic import BaseModel

from pydantic_ai import Agent

class TicketAnalysis(BaseModel):

    category: Literal[“delivery”, “payment”, “product”, “other”]

    priority: Literal[“low”, “medium”, “high”]

    summary: str

agent = Agent(

    “openai:gpt-4o”,

    output_type=TicketAnalysis,

    instructions=”Analyze customer support messages.”

)

result = agent.run_sync(

    “My payment was deducted, but I have not received an order confirmation.”

)

print(result.output)

The expected output is a TicketAnalysis object with a category, priority, and summary. The model is guided by the defined schema, and the result is validated against the expected type.

This is useful when another part of an application needs to process the agent’s response automatically.

Step 4: Add a Custom Python Tool

An agent becomes more useful when it can interact with application functions. PydanticAI allows developers to register Python functions as tools.

For example, a simple inventory lookup tool could look like this:

from pydantic_ai import Agent

agent = Agent(

    “openai:gpt-4o”,

    instructions=”Help users check product stock.”

)

@agent.tool_plain

def check_stock(product_name: str) -> str:

    “””Check the availability of a product.”””

    inventory = {

        “laptop”: “12 units available”,

        “keyboard”: “35 units available”,

        “mouse”: “20 units available”

    }

    return inventory.get(

        product_name.lower(),

        “Product not found”

    )

result = agent.run_sync(

    “How many keyboards are currently available?”

)

print(result.output)

The agent can use the registered function when it needs inventory information. This example uses a small Python dictionary for demonstration. A real application would connect the function to a database or inventory service.

How to Connect PydanticAI With Business Applications

PydanticAI can be integrated into existing Python applications through tools, dependencies, and external service connections. This creates opportunities to automate repetitive operations while keeping business logic under developer control.

For example, an e-commerce company could build an agent that classifies customer questions, checks product availability, and prepares order-related responses. The agent could retrieve stock information through an inventory tool rather than relying on information stored in the language model.

Businesses exploring software for managing products, stock levels, and orders can also read best inventory management software for e-commerce stores. Connecting an AI agent with a suitable inventory platform could help teams retrieve product information and support routine stock-related workflows.

The integration should use authorized APIs, appropriate permissions, and validation before any important inventory changes are made.

Testing and Monitoring PydanticAI Agents

A working example is not automatically a reliable production application. Developers should test how an agent handles incomplete requests, unexpected responses, unavailable services, and incorrect tool arguments.

PydanticAI supports testing with tools such as TestModel and FunctionModel, allowing developers to exercise application logic without making real model requests in every test. Standard Python testing frameworks such as pytest can be used to verify tools, dependencies, validation, and failure handling.

For production monitoring, developers can also explore Pydantic Logfire and OpenTelemetry-based instrumentation. Tracing can help teams understand model interactions, tool calls, errors, and application performance.

Retry settings should be configured thoughtfully. Repeated model requests can increase latency and API costs, so retries need sensible limits.

Advantages and Limitations of PydanticAI

PydanticAI is useful for developers who want a structured approach to building Python-based AI applications. Its integration with Pydantic models makes it particularly attractive for data extraction, classification, customer support, and applications that depend on predictable output formats.

Its tool system also allows agents to interact with existing Python functions and services. Model flexibility provides additional choice when selecting an LLM provider.

However, developers still need to understand Python, API configuration, model behavior, and application security. Type validation does not guarantee that an AI-generated answer is factually correct. External actions should also include permission checks and appropriate safeguards.

Conclusion

PydanticAI provides Python developers with a practical foundation for building structured and reliable AI agents. Its combination of typed outputs, function tools, dependency injection, model flexibility, and testing support makes it suitable for applications that need more control than a basic chatbot.

Start with a small use case, such as customer message classification or product information lookup. Add tools only when the application needs them, validate important outputs, and test failure scenarios before deployment.

With thoughtful design and monitoring, PydanticAI can help turn language model capabilities into useful Python applications that support real business workflows.