Sub topic 7
Validating structured output
This chapter assumes you can write basic Python, read JSON, and call an LLM through an SDK. You should also know where input and output checks sit around a model call, and you should have seen simple rule-based checks.
Why structured output needs its own check
Many applications ask the model for JSON so that other code can use the result. A ticket router might need a priority and a summary. If the model returns prose, a missing field, or a value like "urgent" that your code does not handle, the failure shows up later and far from its cause.
Structured output validation is an output guardrail. It treats the model's reply as untrusted data and checks it before anything else uses it.
A reply can fail at three levels:
- Syntax: the text is not valid JSON, for example because it has a trailing comma or extra prose around the object.
- Shape: the JSON is valid but has the wrong type or is missing a field.
- Values: the shape is right but a value is outside what you allow, such as an unknown priority.
Writing the validator
The validator below handles all three levels. It raises ValueError with a message that says what is wrong.
import json
def parse_ticket(raw: str) -> dict:
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError("expected a JSON object")
if data.get("priority") not in ("low", "medium", "high"):
raise ValueError("priority must be low, medium or high")
if not isinstance(data.get("summary"), str) or not data["summary"]:
raise ValueError("summary must be a non-empty string")
return datajson.loads checks syntax. The isinstance check covers shape. The membership test on priority is an allowlist, the same idea as in the earlier chapter on deterministic checks.
json.JSONDecodeError is a subclass of ValueError. One except ValueError therefore catches syntax, shape, and value failures.
Retrying with the error message
Models often fix a mistake when they are told what it was. The next function calls the model, validates the reply, and on failure adds the error to the prompt for another try. It stops after a fixed number of attempts.
def get_ticket(prompt: str, call_model, max_attempts: int = 3) -> dict:
last_error = ""
for _ in range(max_attempts):
suffix = f"\nPrevious attempt failed: {last_error}" if last_error else ""
raw = call_model(prompt + suffix)
try:
return parse_ticket(raw)
except ValueError as err: # json.JSONDecodeError is a ValueError
last_error = str(err)
raise RuntimeError(f"No valid output after {max_attempts} attempts: {last_error}")The loop looks like this:
Common errors
- No attempt limit. Without
max_attempts, a model that keeps failing makes an endless loop and an unbounded bill. - Checking only syntax. Valid JSON with
"priority": "urgent"still breaks downstream code. - Trusting extra fields. The validator returns the whole dictionary. If later code passes unknown keys onward, build a new dictionary that holds only the fields you expect.
- Echoing untrusted text. Error messages here are written by your code, so they are safe to put in the prompt. Do not paste raw model output or user text into the retry prompt, because that can carry injected instructions.
- Treating valid as true. The summary can be well formed and still wrong. Validation checks form, not facts. Grounding checks, covered later, address facts.
What to do after the last attempt
When retries run out, the function raises RuntimeError. The caller decides what happens next: show a generic error, queue the request for review, or fall back to a default. The chapter on handling guardrail failures covers these choices.
Exercise
A model returns {"priority": "urgent", "summary": "Printer is down"}. Which level of check catches this, and what does parse_ticket do with it?
Show answer
The value check catches it. The JSON is valid and has the right shape, but "urgent" is not in the allowed priorities. parseticket raises ValueError("priority must be low, medium or high"), and getticket adds that message to the next prompt.
Exercise
Why does get_ticket cap the number of attempts instead of retrying until the output is valid?
Show answer
A model can fail the same way every time. An uncapped loop would never end and would keep spending tokens and time. A cap bounds cost and latency and gives the caller a clear failure to handle.