Founders BetaFounder price: US$ 9.90/month locked for as long as you subscribe.→
HomeBlogDicasPydantic AI: How to Build Type-Safe Agents in Python
Cover of the pydantic/pydantic-ai repository on GitHub, a type-safe agent framework in Python
Image: Pydantic
Dicas6 min

Pydantic AI: How to Build Type-Safe Agents in Python

Pydantic AI is a Python framework for AI agents with strong typing. See how to install and validate results.

Marcelo Santiago

Marcelo Santiago

Criador do bridgecode

Pydantic AI is a Python framework for building AI agents with strong typing. It brings the same philosophy as Pydantic, rigorous data validation, to the world of agents. The result is code that is safer, more testable and easier to maintain.

The biggest AI newsletter in the World

Get AI articles in your inbox

Technical curation on models, agents and coding tools. No spam, unsubscribe anytime.

Daily at 8:00 and 16:00 Brasília time. No spam.

If you have ever lost hours debugging an agent that received one field too many or too few, Pydantic AI tackles the problem at the root. It defines the expected structure for the agent's inputs and outputs and validates automatically. If something does not match, the error shows up early, not in the middle of execution.

The pydantic/pydantic-ai repository has over 21 thousand stars, MIT license and was updated on November 9, 2026. The community and development pace indicate maturity for production use.

In this article you will see:

  • What Pydantic AI does and how it organizes an agent
  • How to install and create your first typed agent
  • How to validate tools and results
  • When to use Pydantic AI and when a heavier framework makes sense
  • Limits and best practices

What is Pydantic AI and how does typing work

A typical agent calls a language model, receives text and tries to interpret it. Without typing, that interpretation is fragile. Pydantic AI flips the logic. You declare a Pydantic model for the expected result and the framework ensures the model's response is converted and validated into that format.

This also applies to the tools the agent uses. Each tool has typed parameters. If the model tries to call a tool with a wrong argument, validation fails clearly.

The approach is reminiscent of FastAPI, but for agents. You write less defensive code and more business code. Typing also improves editor autocomplete and automatic documentation.

How to install Pydantic AI and create your first agent

Installation is simple. The main package is pydantic-ai.

Terminal
pip install pydantic-ai

Then, define the expected result with a Pydantic model and create the agent.

Python
from pydantic import BaseModel
from pydantic_ai import Agent

class Resposta(BaseModel):
    resumo: str
    pontos: list[str]

agent = Agent(
    "openai:gpt-4o",
    result_type=Resposta,
)

result = agent.run_sync("Resuma as vantagens do Pydantic AI em 3 pontos.")
print(result.data.resumo)
print(result.data.pontos)

The run_sync method executes synchronously and returns an object with the data field already validated. If the model's response does not fit the Resposta model, the framework tries to fix it or raises a clear error.

You can swap the provider by changing the model string. Pydantic AI supports OpenAI, Anthropic, Groq, Google and local models via Ollama. The official documentation lists the providers and their configurations.

Cover image of the Pydantic AI documentation
Imagem: Pydantic

How to validate tools and results

Tools are functions the agent can call. In Pydantic AI, you decorate a function with @agent.tool and declare typed parameters. The framework generates the schema for the model and validates the call.

Python
from pydantic_ai import Agent, RunContext

agent = Agent("openai:gpt-4o")

@agent.tool
def busca_preco(ctx: RunContext, produto: str) -> float:
    # consulta o banco ou a API
    return 42.0

result = agent.run_sync("Qual o preço do produto X?")
print(result.data)

The ctx parameter gives access to the execution context, such as injected dependencies. This makes testing easier, because you can inject mocks instead of calling real services.

Result validation also helps in multi-step flows. If one agent needs to pass data to the next, typing ensures the contract is respected. In agent teams, this reduces integration errors.

When to use Pydantic AI and when a heavier framework makes sense

Pydantic AI is lightweight and focused. It does not try to be a complete orchestrator with queues, memory and dashboards. If you need complex coordination of multiple agents, you can combine Pydantic AI with an orchestrator or use a more complete framework.

Use Pydantic AI when the main problem is data reliability and code clarity. It shines in agents that call tools, extract structured information or classify content.

If you need persistent memory, see also Mem0: how to give persistent memory to AI agents. If the task requires browser control, see browser-use: how to connect AI agents to the browser.

Limits and best practices

Strong typing does not solve all problems. The model can produce a response that is valid in format but semantically wrong. Validation guarantees shape, not truth. For critical data, add business checks.

Another point is verbosity. Declaring models for each result adds code. In fast prototypes, that can feel like overkill. The payoff shows up as the project grows and needs automated tests.

Best practices that apply to any agent framework:

  • Define small, focused result models
  • Inject dependencies via RunContext instead of globals
  • Test tools in isolation, without calling the model
  • Monitor tokens and latency in production

If you coordinate multiple agents, each in its own role and isolated space, typing becomes a contract between them. With bridgecode you assemble that squad and follow each step, from planning to delivery.

Frequently asked questions about Pydantic AI

Is Pydantic AI free?

Yes. It is open source with an MIT license. Cost comes from the model provider you choose.

Do I need to know Pydantic to use Pydantic AI?

Basic Pydantic knowledge helps, but it is not required. The documentation examples cover the essentials. The framework encourages the use of models for results.

Does Pydantic AI replace LangChain?

No. They solve different problems. LangChain orchestrates chains and tools. Pydantic AI focuses on typing and validation. You can use both together.

Does it work with local models?

Yes, as long as the provider is compatible. Ollama and vLLM work. Check the supported version in the documentation.

How to test an agent without calling the model?

You can inject dependencies via RunContext and test tools in isolation. The documentation shows testing patterns with mocks.

Frequently asked questions about Pydantic AI

Is Pydantic AI free?

Yes. It is open source with an MIT license. Cost comes from the model provider you choose.

Do I need to know Pydantic to use Pydantic AI?

Basic Pydantic knowledge helps, but it is not required. The documentation examples cover the essentials. The framework encourages using models for results.

Does Pydantic AI replace LangChain?

No. They solve different problems. LangChain orchestrates chains and tools. Pydantic AI focuses on typing and validation. You can use both together.

Does it work with local models?

Yes, as long as the provider is compatible. Ollama and vLLM work. Check the supported version in the documentation.

How to test an agent without calling the model?

You can inject dependencies via RunContext and test tools in isolation. The documentation shows testing patterns with mocks.

Conclusion

Strong typing in AI agents stops being a luxury and becomes a necessity as the project grows. Pydantic AI delivers this layer with a lean API and a permissive license. Start with a simple agent, add typing to results, and expand to tools later.

If you coordinate multiple agents, typing becomes a contract between them. With bridgecode you assemble that squad and follow each step, from planning to delivery.

Source: pydantic/pydantic-ai

Share this article

Add bridgecode as a source on Google
Tags:#Pydantic AI#agentes de IA#Python#tipagem#validação
Marcelo Santiago
Marcelo Santiago·Creator of bridgecode

Developer and creator of bridgecode, an agentic development environment for orchestrating squads of AI agents. Helps people going from vibe coding to professional development move from idea to shipped product.

The biggest AI newsletter in the World

Enjoyed this content? Stay ahead in AI engineering.

Code analysis, multi-agent architecture, token benchmarks and tools selected by developers for developers.

Daily at 8:00 and 16:00 Brasília time. No spam.