CloudCodeTree LogoCloudCodeTree
AI NewsTutorialsAbout
CloudCodeTree Logo
CloudCodeTree
  • AI News
  • Tutorials
  • About
← Back to AI News
Type-Safe Agents: Use Pydantic AI to Get Validated Python Objects Instead of Raw LLM Strings

Type-Safe Agents: Use Pydantic AI to Get Validated Python Objects Instead of Raw LLM Strings

Chris Harper

2 min read

Aug 1, 2026 · 04:13 UTC

AI
Tutorial
Agents
Best Practices

Pydantic AI wraps your LLM call, sends your Pydantic model's JSON schema, validates the response, and retries on failure — you get a typed Python object back, never a raw string to parse.

What you'll be able to do after this:

  • Declare a BaseModel as your agent's output_type and receive a fully-validated Python object — with IDE autocomplete and type checking — after every call
  • Write agents that automatically retry when the LLM returns malformed JSON, without any try/except boilerplate
  • Swap between Anthropic Claude, OpenAI GPT, and a local Ollama model by changing one string in your agent constructor

Walk-through

Install:

pip install "pydantic-ai[anthropic]"

Define your output model and run:

from pydantic import BaseModel
from pydantic_ai import Agent

class BugReport(BaseModel):
    severity: str          # "low" | "medium" | "high" | "critical"
    component: str
    root_cause: str
    suggested_fix: str

agent = Agent(
    "anthropic:claude-sonnet-5",   # swap: "openai:gpt-5.6" or "ollama:llama3"
    output_type=BugReport,
)

result = agent.run_sync(
    "The login button does nothing on mobile Safari 17. "
    "Stack trace: TypeError: Cannot read properties of undefined (reading 'submit')"
)

# result.data is a validated BugReport — not a string
print(result.data.severity)       # e.g. "high"
print(result.data.suggested_fix)  # type-checked, IDE-autocomplete-ready

Pydantic AI translates your model's fields to a JSON schema, sends it alongside your prompt, validates the LLM's JSON response, and retries automatically (configurable max_retries) if validation fails. Add tools by decorating plain Python functions with @agent.tool — they get included in the schema automatically. For async workloads, replace run_sync with await agent.run(…).

Provider switching is one string change: "anthropic:claude-sonnet-5""openai:gpt-5.6""ollama:llama3". The framework supports 20+ providers. Full output patterns (streaming, union types, lists of models) are in the Output docs.

Sources: Output — Pydantic AI Docs · Pydantic AI overview · YouTube: Build 100% Reliable AI Agents with Structured Output · Building AI Agents in Python with Pydantic AI — Machine Learning Mastery