Sub topic 7
Getting structured output you can trust
A language model produces text. Your program usually needs data: a dictionary, a database row, an argument for a function. This chapter covers how to turn model text into data your code can rely on. It assumes you can write basic Python, read JSON, and have seen the classification prompt pattern from the previous chapter.
Why structure needs enforcement
Asking for JSON in a prompt makes valid JSON likely. It does not make it certain. The model samples text one token at a time, so nothing in the process guarantees that braces balance, that a field is present, or that a number is not the string "129.5".
Typical failures:
- Wrapper text. The reply starts with "Here is the JSON:" or is wrapped in a Markdown code fence.
- Syntax errors. A trailing comma, single quotes, or a reply cut off at the output limit.
- Wrong types.
"total": "129.50 USD"where a number was expected. - Missing or extra fields. The model invents a key, or omits one it could not find.
- Invented values. The JSON is valid and well-typed, but the vendor name was never in the document.
The first four can be caught by code. The last one needs different defenses, covered below.
Three layers of defense
Treat structured output as a pipeline with three layers, from cheapest to most reliable.
- Ask clearly. Name the exact keys, their types, and what to do when a value is missing, such as
null. - Constrain generation. Many APIs offer a JSON mode, a schema-constrained mode, or tool calling with a declared parameter schema. These make syntax errors rare or impossible. Check your provider's documentation for what is guaranteed. Some modes guarantee valid JSON but not your schema.
- Validate in your code. Always. Even with constrained decoding, you validate, because it is the only layer you control.
Validate every field
The validator from the topic's earlier example checks types. This version also rejects non-object replies and booleans. In Python, True is an instance of int, so isinstance(True, (int, float)) is True, and a model returning "total": true would otherwise pass.
import json
def parse_invoice(raw: str) -> dict:
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError("reply must be a JSON object")
if not isinstance(data.get("vendor"), str) or not data["vendor"].strip():
raise ValueError("vendor must be a non-empty string")
total = data.get("total")
if isinstance(total, bool) or not isinstance(total, (int, float)):
raise ValueError("total must be a number")
if total < 0:
raise ValueError("total must not be negative")
return data
print(parse_invoice('{"vendor": "Acme", "total": 129.5}'))Libraries such as Pydantic or jsonschema express the same rules declaratively and scale better once you have many fields. The principle is the same: reject anything outside the contract.
Retry with the error message
When validation fails, you can often fix the problem by showing the model what went wrong. The loop must be bounded, or a persistent failure becomes an unbounded bill.
import json
def parse_invoice(raw: str) -> dict:
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError("reply must be a JSON object")
if not isinstance(data.get("vendor"), str) or not data["vendor"].strip():
raise ValueError("vendor must be a non-empty string")
total = data.get("total")
if isinstance(total, bool) or not isinstance(total, (int, float)):
raise ValueError("total must be a number")
return data
def json_slice(raw: str) -> str:
# Keep only the text from the first "{" to the last "}".
start, end = raw.find("{"), raw.rfind("}")
if start == -1 or end < start:
raise ValueError("no JSON object found")
return raw[start:end + 1]
def extract_invoice(text: str, complete, max_attempts: int = 3) -> dict:
base = (
'Extract the invoice as JSON with keys "vendor" (string) and '
'"total" (number). Reply with JSON only.\n\nInvoice: ' + text
)
prompt, last_error = base, None
for _ in range(max_attempts):
raw = complete(prompt)
try:
return parse_invoice(json_slice(raw))
except ValueError as err: # JSONDecodeError is a ValueError
last_error = err
prompt = base + "\n\nYour previous reply was rejected: " + str(err)
raise RuntimeError(f"no valid output after {max_attempts} attempts: {last_error}")
# A fake model that fails once, then succeeds.
replies = iter(['Sure! {"vendor": "Acme", "total": "129.5"}',
'{"vendor": "Acme", "total": 129.5}'])
print(extract_invoice("Acme, total due 129.50", lambda p: next(replies)))The first reply fails because total is a string. The second prompt includes the rejection reason, and the second reply passes.
Valid does not mean true
Validation checks shape, not correctness. A model can return a perfectly typed invoice with a total it made up. Add semantic checks where you can:
- Grounding. Confirm that an extracted vendor name appears in the source text.
- Cross-field rules. Line items should sum to the total. A due date should not precede the issue date.
- Closed vocabularies. Compare against an allowed list, as the classifier did with its labels.
- Allow "unknown". Let the schema say
nullfor missing values. If you require every field, the model will fill gaps with guesses.
For high-stakes fields such as payment amounts, send low-confidence or failed-check cases to a person.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Calling `json.loads` on the raw reply with no handling | Crash on wrapper text | Catch the error, slice out the object, or use a constrained mode |
| Checking only that keys exist | Wrong types reach downstream code | Check types and ranges |
| Using `isinstance(x, int)` for numbers | Booleans pass | Reject `bool` explicitly |
| Unbounded retries | Cost and latency spikes | Cap attempts, then fail safely |
| Silently substituting defaults | Bad data looks good | Log failures and count them |
| Ignoring truncation | Cut-off JSON on long outputs | Check the finish reason and raise the output limit |
Track your failure rate: the share of replies that fail on the first attempt. A rise after a model or prompt change is an early warning, and it gives you a metric to use in the evaluation chapter.
Exercises
Exercise
A model returns {"vendor": "Acme", "total": true}. Why can a check written as isinstance(data["total"], (int, float)) accept it, and how do you fix it?
Show answer
In Python, bool is a subclass of int, so True passes the isinstance check. Add an explicit isinstance(total, bool) rejection before the numeric check.
Exercise
Your retry loop retries forever when validation fails. Name two problems this causes and one design that avoids them.
Show answer
It can run up unbounded cost and latency, and it can hang a request whose input the model can never satisfy. Cap the attempts (for example 3), then fail safely or route the item to a human, and log the failure.
Exercise
A reply is valid JSON that passes your type checks, but the vendor name does not appear anywhere in the source document. What kind of check catches this, and why did the earlier checks miss it?
Show answer
A grounding (semantic) check that confirms the extracted value appears in the source text. Type and schema checks only test shape, so a well-formed invented value passes them.