Every LLM pipeline has the same failure moment. The model returns something that looks like JSON, your code trusts it, and three functions deeper a KeyError fires on a field that was never there. The bug is not in the model — it is that you validated nothing at the boundary where the untrusted text entered your program.
Pydantic is the right tool for this, but most teams bolt it on as an afterthought: call the API, parse the string, then validate at the end of the function or, worse, in a test. This post shows the opposite order — schema first, validate immediately, retry with the error text fed back into the conversation, and stop the moment retrying stops helping. All examples run against the OpenAI SDK pointed at AiCredits.
Why Parse-Then-Pray Fails
JSON mode is a syntax guarantee, not a schema guarantee. When you set response_format to json_object, the model will produce parseable JSON — but nothing stops it from returning severity as "High", a numeric ID as a string, or a list where you expected a single object. It also does nothing about truncation: if the model hits its output ceiling mid-object you get an unterminated string and json.loads throws.
The second failure is drift. A schema that passes 200 test cases can still break on the one input where the model has to infer a field that is not explicitly present in the source text. That is not a bug in your prompt; it is the normal operating condition of probabilistic systems. The fix is not cleverer parsing — it is making the failure loud, cheap, and recoverable.
Step 1: Make the Pydantic Model the Contract
Generate the prompt from the model itself. Pydantic v2 gives you model_json_schema() for free, which means the schema you validate against and the schema you show the model can never drift apart. Use Literal types rather than regex patterns for enums — a Literal shows up in the schema as an explicit set of allowed values, which is far easier for a model to satisfy than a pattern string it has to reason about.
Keep the model small. Every optional field you add gives the model another chance to invent something. If a field can be derived downstream, derive it downstream.
import json
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel, Field
client = OpenAI(
base_url="https://api.aicreditsapi.com/v1",
api_key="AICREDITS_API_KEY",
)
class Ticket(BaseModel):
title: str = Field(min_length=3, max_length=80)
severity: Literal["low", "medium", "high"]
tags: list[str] = Field(default_factory=list, max_length=5)
summary: str = Field(min_length=10, max_length=400)
SCHEMA_JSON = json.dumps(Ticket.model_json_schema(), indent=2)
def extract_ticket(text: str) -> Ticket:
resp = client.chat.completions.create(
model="deepseek-v4-flash",
temperature=0,
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "You are a ticket extractor. Return JSON only, no prose."},
{"role": "user", "content": f"JSON Schema:\n{SCHEMA_JSON}\n\nTicket text:\n{text}"},
],
)
return Ticket.model_validate_json(resp.choices[0].message.content or "")
Step 2: Fail Fast at the Boundary
model_validate_json is deliberately strict about structure: it parses and validates in one step, so a malformed string never becomes a half-populated dict that wanders through your codebase. Call it on the very next line after the API response and let the exception escape the wrapper function — not the request handler.
Fail fast also means failing on the input side. If your caller passes an empty string, reject it before you spend a single token. A ValidationError raised locally costs nothing; one raised after a model call costs a round trip and, on a long document, a meaningful chunk of context.
Step 3: Retry Smart, Not Blind
A blind retry loop on identical messages is a bill generator: at temperature 0 the model will usually reproduce the same broken output. The productive pattern is an error-feedback loop — append the failed assistant message and a user message containing the exact validation errors, then ask for a correction. Models are good at local repair when told precisely what is wrong.
Two guardrails make this safe. First, fingerprint the error set; if the same errors come back twice, stop, because the model is not making progress. Second, check finish_reason — a truncated response needs a shorter answer, not a stricter one.
class ValidationFailed(Exception):
pass
def extract_ticket_retry(text: str, max_attempts: int = 3) -> Ticket:
messages = [
{"role": "system", "content": "You are a ticket extractor. Return JSON only, no prose."},
{"role": "user", "content": f"JSON Schema:\n{SCHEMA_JSON}\n\nTicket text:\n{text}"},
]
seen_errors: set[str] = set()
last_error: str | None = None
for attempt in range(1, max_attempts + 1):
resp = client.chat.completions.create(
model="deepseek-v4-flash",
temperature=0,
response_format={"type": "json_object"},
messages=messages,
)
choice = resp.choices[0]
raw = choice.message.content or ""
if choice.finish_reason == "length":
last_error = "truncated output"
messages.append({
"role": "user",
"content": "Your previous JSON was truncated. Return a shorter, complete object.",
})
continue
try:
return Ticket.model_validate_json(raw)
except ValidationError as err:
fingerprint = json.dumps(err.errors(include_url=False), sort_keys=True)
if fingerprint in seen_errors:
raise ValidationFailed("Identical validation error repeated; retrying will not help.") from err
seen_errors.add(fingerprint)
last_error = fingerprint
messages.append({"role": "assistant", "content": raw})
messages.append({
"role": "user",
"content": "That output failed schema validation. Return corrected JSON only.\n"
f"Validation errors:\n{fingerprint}",
})
raise ValidationFailed(f"Gave up after {max_attempts} attempts. Last error: {last_error}")
Cap attempts at two or three. Beyond that you are almost always re-asking a question the prompt answered badly.
Keep temperature at 0 during retries so failures are reproducible and your regression suite means something.
Echo the Pydantic error list verbatim — vague instructions like "fix the JSON" produce vague fixes.
Fingerprint errors to detect no-progress loops instead of burning attempts.
Cache successful results by input hash so a retry storm never re-bills the same document.
Which Failures Deserve a Retry
| Failure | Retry? | Better fix |
|---|---|---|
| json_invalid (prose wrapper or truncation) | Yes, once | Enforce json_object mode, shorten output fields |
| Missing required field | Yes, with error text | Drop optional fields, list required ones explicitly in the prompt |
| Literal or enum mismatch | Yes, once | Use Literal types instead of regex patterns |
| String too short or too long | Sometimes | Loosen min_length or ask for a compact summary |
| Business rule violated (date in the past, mismatched ID) | No | Validate against your own database and route to human review |
| Same error twice | No | Escalate model tier or queue for a human |
Escalate the Model Tier Only After Cheap Attempts Fail
deepseek-v4-flash is the right default: it is the fast, low-cost tier and handles structured extraction well for the overwhelming majority of inputs. deepseek-v4-pro costs more but reasons more reliably on dense or ambiguous documents — long contracts, nested tables, tickets written in three languages at once.
The mistake is choosing the tier per request. Choose it per failure. Run flash first, and only after two failed validations spend on one pro pass. On typical traffic this keeps the expensive tier for the small tail of genuinely hard inputs, and on a stable system prompt with repeated prefixes the cached portion of each call is billed at a lower rate, so the flash attempts stay cheap. Current rates are listed at aicreditsapi.com/deepseek-prices.
def extract_escalating(text: str) -> Ticket:
try:
return extract_ticket_retry(text, max_attempts=2)
except ValidationFailed:
# One stronger pass beats a fourth flash retry on genuinely hard input.
resp = client.chat.completions.create(
model="deepseek-v4-pro",
temperature=0,
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "You are a ticket extractor. Return JSON only, no prose."},
{"role": "user", "content": f"JSON Schema:\n{SCHEMA_JSON}\n\nTicket text:\n{text}"},
],
)
return Ticket.model_validate_json(resp.choices[0].message.content or "")
A retry loop without a stopping rule is not resilience — it is an unmetered spending policy with a timeout.
Log the Raw Output, Not Just the Exception
Store the raw model output alongside the ValidationError fingerprint for every failure. After a week you have a corpus of real failures, which is worth more than any synthetic test suite: replay them against a new prompt or a new schema before you ship. Two extra fields — input hash and error fingerprint — let you spot the moment a prompt change starts producing a new class of error.
Streaming deserves a caveat. You cannot validate a partial JSON object token by token, so either buffer the stream and validate at the end, or validate per-item after an incremental parser emits each completed list element. Validating mid-object only produces false failures.
Frequently Asked Questions
No. response_format json_object guarantees syntactically valid JSON, not your field names, types, or enums. Pydantic's model_validate_json is what actually enforces the contract — JSON mode just reduces how often it fails.
Use strict on fields where a wrong type is dangerous downstream, such as numeric IDs and amounts, and stay lenient on free text. Strict everywhere raises the retry rate for little gain.
Two or three. Past that, escalate to a stronger model tier or route the input to a human queue. The fingerprint check usually catches the hopeless cases after one attempt anyway.
Not at the object level — partial JSON is invalid by definition. Buffer the full response and validate once, or parse list items incrementally and validate each completed item as it lands.