Validate, Retry, Fallback, Log: Reliable LLM Steps in Python with Pydantic
Originally published on DEV. This version implements the same pattern in Python.
Treat an LLM call in a pipeline as a slow, flaky network call whose response must be parsed into typed data before anything else touches it. Four steps make that safe: Validate, Retry, Fallback and Log.
The running example classifies inbound enquiry emails for a CRM. It is a reference scenario, not a production system description.
Validate: a Pydantic model as the contract
from typing import Literal
from pydantic import BaseModel, Field, ValidationError, model_validator
class Enquiry(BaseModel):
category: Literal["sales", "support", "billing", "spam", "other"]
priority: Literal["low", "normal", "high"]
summary: str = Field(min_length=10, max_length=280)
confidence: float = Field(ge=0, le=1)
@model_validator(mode="after")
def billing_not_low(self):
if self.category == "billing" and self.priority == "low":
raise ValueError("billing enquiries must be normal or high priority")
return self
Literal types close the category set, and the model validator encodes a business rule a JSON-mode response would happily violate.
A small result type keeps failures explicit instead of raising through the pipeline:
from dataclasses import dataclass
@dataclass
class Ok:
value: Enquiry
@dataclass
class Err:
reason: Literal["invalid_json", "schema", "timeout", "api_error"]
detail: str
Result = Ok | Err
def validate(raw: str) -> Result:
try:
return Ok(Enquiry.model_validate_json(raw))
except ValidationError as e:
# Pydantic reports JSON syntax errors as ValidationError too
kind = "invalid_json" if any(err["type"] == "json_invalid" for err in e.errors()) else "schema"
return Err(kind, str(e))
Retry: bounded attempts, timeout per call, error fed back
import asyncio, os, random, time
async def classify(email: str, call_model, max_attempts: int = 3, timeout_s: float = 15.0):
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": email},
]
last: Result = Err("api_error", "not run")
for attempt in range(1, max_attempts + 1):
try:
raw = await asyncio.wait_for(call_model(messages), timeout=timeout_s)
except asyncio.TimeoutError:
last = Err("timeout", f"attempt {attempt}")
except Exception as e: # provider/network errors
last = Err("api_error", repr(e))
else:
last = validate(raw)
if isinstance(last, Ok):
return last, attempt
messages += [
{"role": "assistant", "content": raw},
{"role": "user", "content": f"Validation failed: {last.detail}. Return corrected JSON only."},
]
continue
await asyncio.sleep(min(8, 0.5 * 2 ** attempt) + random.random() * 0.25)
return last, max_attempts
Notes:
- Backoff applies to transport failures; validation failures retry immediately with the error appended, because the cause is the content, not the network.
asyncio.wait_forcancels the underlying task on timeout. Check that your client library handles cancellation cleanly, or wrap it.
Fallback: route to review, write nothing irreversible
CONFIDENCE_FLOOR = float(os.getenv("ENQUIRY_CONFIDENCE_FLOOR", "0.7"))
async def route_enquiry(email: str, ctx) -> str:
started = time.monotonic()
result, attempts = await classify(email, ctx.call_model)
auto = (
isinstance(result, Ok)
and result.value.confidence >= CONFIDENCE_FLOOR
and result.value.category != "other"
)
if auto:
await ctx.crm.create_lead(**result.value.model_dump(), source="llm", attempts=attempts)
route = "auto"
else:
await ctx.review_queue.put({
"email_ref": ctx.store_email(email),
"suggestion": result.value.model_dump() if isinstance(result, Ok) else None,
"failure": "low_confidence" if isinstance(result, Ok) else result.reason,
"attempts": attempts,
})
route = "review"
log_call(ctx, result, attempts, route, time.monotonic() - started)
return route
The review item stores a reference to the email rather than the body, keeps the model's suggestion for the reviewer, and records why it was routed. Reviewer corrections become labelled examples for testing the next prompt version.
Log: one structured event per call
import structlog
log = structlog.get_logger()
def log_call(ctx, result, attempts, route, elapsed_s):
log.info(
"llm_step",
workflow="enquiry_classify",
model=ctx.model_name,
prompt_version="enquiry-v4",
outcome="valid" if isinstance(result, Ok) else result.reason,
attempts=attempts,
route=route,
confidence=result.value.confidence if isinstance(result, Ok) else None,
latency_ms=round(elapsed_s * 1000),
)
Useful queries once this is in place: schema-failure share by prompt_version, review share by category, and p95 latency including retries.
Tests with a scripted model
import pytest
def scripted(*replies):
queue = list(replies)
async def call_model(_messages):
return queue.pop(0)
return call_model
@pytest.mark.asyncio
async def test_recovers_after_bad_json():
ctx = FakeCtx(call_model=scripted("nope", VALID_HIGH_CONF))
assert await route_enquiry("Quote for 20 units", ctx) == "auto"
@pytest.mark.asyncio
async def test_business_rule_violation_goes_to_review():
bad = '{"category":"billing","priority":"low","summary":"Invoice query for October","confidence":0.95}'
ctx = FakeCtx(call_model=scripted(bad, bad, bad))
assert await route_enquiry("Invoice question", ctx) == "review"
ctx.crm.create_lead.assert_not_called()
@pytest.mark.asyncio
async def test_timeout_path(monkeypatch):
async def slow(_):
await asyncio.sleep(1)
ctx = FakeCtx(call_model=slow)
result, attempts = await classify("x", ctx.call_model, max_attempts=2, timeout_s=0.01)
assert isinstance(result, Err) and result.reason == "timeout" and attempts == 2
Summary
| Step | Python tool | Guarantees |
|---|---|---|
| Validate | Pydantic model + validators | Only typed, rule-checked data moves on |
| Retry | asyncio.wait_for, capped loop |
Bounded latency and cost |
| Fallback | Review queue, configurable floor | No irreversible write from uncertain output |
| Log | structlog event per call | Measurable failure, review and latency rates |
More on how we structure AI steps in business automation: jctechlabs.com/services/ai-automation.
Originally published on DEV.
Comments
Join the discussionNo comments yet. Be the first to comment.

