The Cost of Untyped LLM Pipelines
Building an LLM prototype usually feels deceptively easy: glue a few prompts together, parse some raw JSON, and inspect the console. It works locally. In production, however, raw string wrangling falls apart fast.
Standard LLM frameworks pass untyped dictionaries and raw strings across your codebase. You ask a model for a user record. Instead, you get back an unescaped markdown block, missing keys, or random null values where an integer was promised. Even worse, tool calling often relies on global state to manage database pools or API tokens. That pattern inevitably breeds race conditions, unmockable dependencies, and sudden 3:00 AM KeyError crashes.
LLMs should be treated like any other typed component in your stack. They need strict input contracts, typed dependencies, and automated schema enforcement.
Core Architecture of PydanticAI
Built by the team behind Pydantic, PydanticAI skips heavy orchestration graphs and proprietary DSLs. Instead, it leans directly on Python’s native type system. Three core design decisions set it apart:
1. Self-Healing Schema Validation
Manual JSON parsing is brittle. With PydanticAI, you provide a standard Pydantic model as your target schema. The framework validates model responses against this contract immediately. If GPT-4o hallucinates an unexpected field or drops a required property, PydanticAI intercepts the validation failure, sends the raw error back into the conversation context, and prompts the model to correct itself.
2. Schema-Driven Tool Calling
Tools are plain Python functions decorated with @agent.tool. PydanticAI analyzes your type hints, function signatures, and docstrings to generate valid JSON Schema definitions for the model provider. When the model invokes a tool, arguments are parsed and validated through Pydantic before your business logic touches them.
3. Typed Dependency Injection
Global database sessions and ambient context variables break concurrency and complicate testing. PydanticAI solves this with RunContext[Deps]. You package HTTP clients, database connection pools, or request-scoped user tokens into a typed dataclass and pass it directly to agent.run(). Your tools access these resources through the context parameter without touching global scope.
Hands-on Practice: Building a Customer Support Agent
Let’s build a practical service: a tier-1 customer support agent that queries an internal shipping system and returns strongly validated operational data.
Step 1: Set Up the Environment
python3 -m venv venv
source venv/bin/activate
pip install pydantic-ai httpx
export OPENAI_API_KEY="sk-proj-your-key-here"
Step 2: Define Output Schemas and Dependencies
First, define your runtime contracts. You need an output model for structured responses and a dependency dataclass containing an HTTP client and customer metadata.
from dataclasses import dataclass
import httpx
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext
# 1. Output Schema
class OrderResolution(BaseModel):
order_id: str = Field(description="Unique order identifier")
status: str = Field(description="Current shipping status")
message_to_user: str = Field(description="Direct update tailored for the customer")
requires_escalation: bool = Field(
default=False,
description="True if an order is lost or delayed past 5 business days"
)
# 2. Injected Dependencies Container
@dataclass
class SupportDependencies:
customer_id: str
http_client: httpx.AsyncClient
base_api_url: str = "https://api.internal.example.com"
Step 3: Initialize the Agent
Configure the agent instance by pairing the model identifier with your dependency and output types:
support_agent = Agent(
"openai:gpt-4o",
deps_type=SupportDependencies,
result_type=OrderResolution,
system_prompt=(
"You are a tier-1 customer support assistant. "
"Always use fetch_order_details to verify order progress. "
"If an order is lost or ETA exceeds 5 days, set requires_escalation to True."
),
)
Step 4: Register Typed Tools
Next, implement your retrieval tool. Declaring ctx: RunContext[SupportDependencies] exposes your injected HTTP client without relying on module globals:
@support_agent.tool
async def fetch_order_details(
ctx: RunContext[SupportDependencies],
order_id: str
) -> dict:
"""Fetch current delivery status and tracking details for an order."""
# In production: response = await ctx.deps.http_client.get(f"{ctx.deps.base_api_url}/orders/{order_id}")
# Simulating API response:
if order_id == "ORD-9912":
return {
"order_id": order_id,
"customer": ctx.deps.customer_id,
"status": "delayed",
"eta_days": 7
}
return {
"order_id": order_id,
"customer": ctx.deps.customer_id,
"status": "not_found",
"eta_days": None
}
Step 5: Execute the Agent Loop
Manage connection lifecycles cleanly with an async context manager and run the agent query:
import asyncio
async def main():
async with httpx.AsyncClient(timeout=10.0) as client:
deps = SupportDependencies(
customer_id="CUST-402",
http_client=client
)
prompt = "Hi, can you check the delivery status for order ORD-9912?"
result = await support_agent.run(prompt, deps=deps)
# Access validated, typed attributes directly
resolution: OrderResolution = result.data
print(f"Order: {resolution.order_id}")
print(f"Status: {resolution.status}")
print(f"Escalate: {resolution.requires_escalation}")
print(f"Message: {resolution.message_to_user}")
if __name__ == "__main__":
asyncio.run(main())
In teams processing over 50,000 requests per day, schema enforcement like this eliminates nearly all downstream serialization crashes. Tool inputs are guarded before execution, while outputs are validated before they hit production databases.
Conclusion
Reliable AI integration does not require massive orchestration frameworks. Combining Python type hints with PydanticAI delivers three immediate production advantages:
- Instant IDE autocompletion and static type checking with mypy or pyright.
- Self-correcting JSON extraction backed by battle-tested Pydantic models.
- Isolated, mockable tool suites with zero global state.
Pick one fragile prompt pipeline in your repository today. Wrap its output in a Pydantic model, inject your dependencies, and run it through PydanticAI.

