Sub topic 7
Getting structured output you can trust
This chapter assumes you can write basic Python, read JSON, and call a model through a function that takes a prompt and returns text. It builds on the classification chapter, where you saw a label check with a fallback.
Why structure needs checking
Downstream code expects fixed fields and types. A model produces text one token at a time, so it can return prose around the JSON, drop a field, or write "total": "129.5" as a string. If you pass that along unchecked, the failure shows up later, far from its cause.
The rule is simple: treat model output as untrusted input. Parse it, validate it, and fail loudly when it is wrong.
Ask for the shape you want
Put the schema in the prompt. Name each field, give its type, and say what to do when a value is missing, such as "use null". Add "Reply with JSON only, no other text." Many model APIs also offer a JSON mode or a way to supply a schema, which reduces malformed output. Even then, keep your own validation, because a valid shape does not guarantee correct values.
Parse and validate
This function parses the reply and checks each field before returning it.
import json
def parse_invoice(raw: str) -> dict:
data = json.loads(raw)
if not isinstance(data.get("vendor"), str):
raise ValueError("vendor must be a string")
if not isinstance(data.get("total"), (int, float)):
raise ValueError("total must be a number")
return data
print(parse_invoice('{"vendor": "Acme", "total": 129.5}'))json.loads raises an error on malformed JSON. The two checks catch missing fields and wrong types. Each failure is an exception, so bad data cannot slip into later steps.
Handle failures
When validation fails, you have three common options:
- Retry the same request. Output varies between calls, so a retry often succeeds.
- Retry with the error message added to the prompt, so the model can correct itself.
- Give up and route the item to a person or a default.
Cap the number of retries, usually at two or three. Each retry costs money and time.
Common errors
| Problem | Typical cause | Fix |
|---|---|---|
| `JSONDecodeError` | Reply wrapped in prose or a code fence | Ask for JSON only, or extract the braces before parsing |
| Wrong type | Number returned as a string | Check types, and convert only when you are sure it is safe |
| Missing field | Model skipped an unclear value | Require the field and allow null explicitly |
| Plausible but wrong value | Hallucination | Cross-check against the source text |
Exercise
Exercise
A reply parses as valid JSON, and vendor and total have the right types. Why might you still reject it, and what is one cheap check?
Show answer
The values may be invented or misread, since type checks do not test accuracy. One cheap check is to confirm that the vendor name and the total appear in the original document text, and send the item to review if they do not.