Sub topic 3
Retrying Structured Output Safely
Assume you know basic Python exceptions, JSON, Pydantic, and how to call an LLM API. This chapter focuses on what happens after the first response fails validation.
Retrying with validation errors
Validate every response before your program uses it. If validation fails, send a concise error back to the model and limit the number of retries.
from typing import Literal
from pydantic import BaseModel, Field, ValidationError
class TicketTriage(BaseModel):
category: Literal["billing", "bug", "feature_request", "other"]
priority: int = Field(ge=1, le=3)
summary: str = Field(max_length=200)
def extract_ticket(ticket_text: str, call_llm, max_attempts: int = 3):
prompt = (
"Return one JSON object with category, priority, and summary. "
"Return JSON only.\n\nTicket:\n" + ticket_text
)
for attempt in range(max_attempts):
raw = call_llm(prompt).strip()
try:
return TicketTriage.model_validate_json(raw)
except ValidationError as error:
if attempt == max_attempts - 1:
raise ValueError("The model did not return valid ticket data") from error
prompt = (
"Correct your previous JSON response.\n"
f"Previous response:\n{raw}\n\n"
f"Validation errors:\n{error}\n\n"
"Return only corrected JSON.\n\n"
f"Ticket:\n{ticket_text}"
)The retry is bounded. Without a limit, a provider outage or persistent model error can create high cost and latency.
Designing schemas that models fill in well
Prefer a small schema with explicit choices and useful descriptions.
- Use enums, such as
Literal, when values come from a fixed set. - Add numeric bounds with
geandle. - Set string length limits.
- Use field descriptions for meanings the field name does not express.
- Avoid optional fields unless missing data is genuinely acceptable.
A schema that is too large or ambiguous increases both validation failures and semantic errors.
What still goes wrong
| Failure | Detection | Response |
|---|---|---|
| Truncated JSON | JSON or schema validation error | Retry, then record failure |
| Refusal or empty output | Missing or unexpected text | Handle separately and do not retry forever |
| Wrong but valid value | Business-rule or human review check | Add tests, rules, or escalation |
Testing and monitoring
Create a fixed test set containing ordinary tickets, missing details, long text, ambiguous requests, refusals, and malformed responses. Run it whenever you change the prompt, schema, model, or provider.
Track:
- validation failures per 100 requests;
- retry rate and average attempts;
- refusal and truncation counts;
- semantic errors found by reviewers;
- latency and token cost.
A declining validation rate is useful, but it does not replace checking whether accepted values are correct.
Exercise
Why should a retry loop stop after a fixed number of attempts?
Show answer
To bound cost and latency, and to route persistent failures to logging or human handling instead of looping indefinitely.