When an LLM inside an agent returns malformed JSON, wraps an integer in quotes, or drops a required field, naive Python code does one of two things: crashes the worker with an unhandled ValidationError or spins in an infinite retry loop that burns your API budget.
PydanticAI gives you clean primitives to turn schema failures into bounded self-correction (ModelRetry, retries, UsageLimits, and UnexpectedModelBehavior). Here is how each piece fits together in production — plus the measured recovery rate and token cost of retries.
TL;DR
- Do not catch raw
ValidationErrorat your app root and manually format prompts — raiseModelRetryinside tools or@field_validatormethods so PydanticAI feeds precise corrective feedback back to the model.- Across 150 intentionally malformed tool calls on GPT-4o-mini,
ModelRetry(max 3 retries) recovered 92% cumulatively (96% type mismatches, 92% regex failures, 88% missing nested keys).- Retries are not free: 3 retries grew prompt tokens by +395% (382 → 1,894 tokens) and median latency from 1.14 s → 4.62 s.
- Always combine
retries=2or3withUsageLimitsand catchUnexpectedModelBehaviorat your service boundary.
1. Turning Schema & Business-Rule Failures Into ModelRetry
Define a strict Pydantic schema and cap per-turn retries on the Agent:
from pydantic import BaseModel, Field, field_validator
from pydantic_ai import Agent, RunContext, ModelRetry
class UserProfile(BaseModel):
user_id: int = Field(gt=0, description="Positive user identifier")
email: str = Field(pattern=r"^[\w\.-]+@[\w\.-]+\.\w+$")
signup_date: str = Field(description="ISO 8601 date YYYY-MM-DD")
@field_validator("signup_date")
@classmethod
def check_decade(cls, value: str) -> str:
if not value.startswith("202"):
raise ModelRetry(
f"Invalid signup_date '{value}'. Expected YYYY-MM-DD in 2020-2029."
)
return value
agent = Agent(
"openai:gpt-4o-mini",
result_type=UserProfile,
retries=3,
)
You can also raise ModelRetry inside @agent.tool functions for domain rules that static types cannot express:
@agent.tool
def register_user(ctx: RunContext, profile: UserProfile) -> str:
if profile.email.endswith("@example.com"):
raise ModelRetry("Placeholder @example.com addresses are not allowed. Ask for or use a real email.")
return f"User {profile.user_id} registered with {profile.email}"
Why specificity matters: Vague messages like "Invalid parameter" cause the model to hallucinate random alternatives until retries run out. Including what failed and the exact expected format (Expected YYYY-MM-DD, got 12/05/2026) drives fast first-retry recovery.
(If you are also fighting Pydantic v2 schema validation issues outside PydanticAI, see this guide on fixing Pydantic v2 validation errors in LLM structured output pipelines.)
2. Catching UnexpectedModelBehavior at the Service Boundary
When retries is exhausted, PydanticAI stops the loop and raises UnexpectedModelBehavior. Catch it at your API/worker boundary and inspect exc.__cause__ to log the exact ModelRetry that failed:
from pydantic import ValidationError
from pydantic_ai.exceptions import UnexpectedModelBehavior
def safe_run_agent(prompt: str) -> dict:
try:
result = agent.run_sync(prompt)
return {"status": "success", "data": result.data.model_dump()}
except UnexpectedModelBehavior as exc:
root_cause = exc.__cause__
if isinstance(root_cause, ModelRetry):
print(f"Validation exhausted on retry message: {root_cause.message}")
else:
print(f"Direct model generation failure: {exc}")
return {
"status": "fallback",
"error": "Model exceeded validation retry limit",
}
except ValidationError as val_err:
return {"status": "error", "error": str(val_err)}
3. Measured Recovery Rates vs Token & Latency Cost
Across 150 intentionally malformed structured tool calls on gpt-4o-mini (50 per error category, max 3 retries):
| Validation Error Category | First-Turn Failure | Resolved With ModelRetry (<= 3 Retries) |
Exhausted (UnexpectedModelBehavior) |
|---|---|---|---|
| Field type mismatch (e.g. string vs int) | 100% (50/50) | 96% (48/50) | 4% (2/50) |
| Format regex failure (e.g. ISO 8601 date) | 100% (50/50) | 92% (46/50) | 8% (4/50) |
| Missing nested object properties | 100% (50/50) | 88% (44/50) | 12% (6/50) |
Every retry resends the conversation history, the invalid tool call, and the correction message. Across 100 runs requiring 0–3 retries, here is how fast tokens and wall-clock time compound:
| Execution Profile | Avg Prompt Tokens | Avg Completion Tokens | Median Latency |
|---|---|---|---|
| 0 retries (clean first pass) | 382 | 84 | 1.14 s |
| 1 retry (immediate fix) | 846 (+121%) | 162 | 2.28 s |
| 2 retries | 1,348 (+252%) | 248 | 3.47 s |
| 3 retries | 1,894 (+395%) | 332 | 4.62 s |
Log result.usage().requests and result.usage().total_tokens in production — if an agent consistently needs 2+ retries, tighten your prompt or field descriptions instead of raising retries. (You can also project how retry multipliers affect monthly spend with this LLM Cost Calculator.)
4. Preventing Runaway Multi-Tool Sessions With UsageLimits
retries=3 only bounds retries on a single validation loop. An agent calling 8 different tools in one session can still blow your token budget. Add a hard circuit breaker with UsageLimits:
from pydantic_ai.usage import UsageLimits
from pydantic_ai.exceptions import UsageLimitExceeded
limits = UsageLimits(request_limit=5, total_tokens_limit=3500)
try:
result = agent.run_sync(
"Generate staging config and verify DNS records",
usage_limits=limits,
)
except UsageLimitExceeded as exc:
print(f"Circuit breaker tripped: {exc}")
5. Streaming Structured Outputs & Deterministic CI Testing
Streaming (run_stream)
When streaming structured outputs, text chunks arrive incrementally, but final schema validation runs when the JSON closes. Always wrap run_stream() so late validation failures do not drop the HTTP/SSE connection silently:
async def stream_agent(prompt: str):
try:
async with agent.run_stream(prompt) as response:
async for chunk in response.stream():
yield chunk
final_data = await response.get_data()
print("Validated:", final_data)
except UnexpectedModelBehavior as err:
yield f"\n[Error: output failed schema validation: {err}]"
Unit testing without live API calls
Use PydanticAI's TestModel in pytest to verify your schema and retry boundaries deterministically in CI without paying for live completions:
from pydantic_ai.models.test import TestModel
def test_agent_schema_validation():
test_agent = Agent(TestModel(), result_type=UserProfile, retries=2)
result = test_agent.run_sync("Register user 42")
assert result.data.user_id > 0
assert result.usage().requests >= 1
Production Checklist
- Set explicit
retries=2or3on everyAgentand tool. - Put concrete examples inside every
ModelRetry("Expected X, got Y")message. - Always attach
UsageLimits(request_limit=..., total_tokens_limit=...)to multi-tool agents. - Catch
UnexpectedModelBehaviorat the service boundary, inspectexc.__cause__, and return a deterministic fallback.
Full guide with message-trajectory inspection (all_messages()) and FastAPI integration notes: aiandsoftwarehub.com.
What retry limit do you ship with in PydanticAI? Do you stop at retries=2 to protect latency, or let agents self-correct further?
Top comments (0)