Notes
Why structure
Picture an accounts payable feature. Invoices arrive as PDFs, and your app must save the vendor, dates, line items and total into a database. A person is happy with: the total is about two hundred and fifty dollars, due next month. Your code is not. It needs a number, a currency code and a date in a fixed format. And if the model opens with, sure, here is the JSON, your parser throws an error before it reads a single field.
a person is fine with:
"The total is about 250
dollars, due next month"
code needs:
{"total": 247.80,
"currency": "USD",
"due_date": "2026-12-15"}
one stray word breaks the parser The idea
There are three levels of control. Level one, ask in the prompt: reply only with JSON shaped like this example. It usually works, but nothing guarantees it. Level two, JSON mode: the reply always parses as JSON, but may not have your fields. Level three, schema enforced output: you pass a JSON Schema, and the reply is guaranteed to match it. Most providers offer this, often called structured outputs or strict mode. Use it whenever you can.
- 1 ask in the prompt "reply only with JSON like…" usually works, no guarantee
- 2 JSON mode always parses, any shape
- 3 schema-enforced output always matches your schema (constrained decoding)
- use level 3 when it is offered
Just asking
Here is how prompt only JSON breaks. A friendly sentence before the object. Markdown code fences around it. A number written as a string with the currency glued on. Due date renamed to payment due. Or the reply simply stops halfway because it hit the output token limit. Each one is rare on a single call. But at a million calls a day, a failure rate of one in a thousand is a thousand broken records, every day.
Sure! Here is the JSON:
```json
{"vendor": "Acme Ltd",
"total": "247.80 USD",
"payment_due": ...
• preamble and code fences
• a number written as a string
• a key renamed or missing
• cut off at the max token limit Constrained decoding
How can a provider guarantee the shape? Constrained decoding. The schema is compiled into a grammar, a small state machine that knows which characters may come next. At each step the model scores every possible next token as usual. Then the decoder sets every token that would break the grammar to zero and renormalises the rest. Here currency must be U S D, E U R or I N R. Dollar is blocked, so U S rises from fifty to about seventy one percent.
written so far: {"currency": "
schema: enum USD, EUR, INR
token prob allowed?
"US" 0.50 yes
"EUR" 0.20 yes
"Dollar" 0.25 no → 0
"\n" 0.05 no → 0
renormalise the allowed ones:
US 0.50/0.70 ≈ 0.71, EUR ≈ 0.29 An invoice schema
Here is a schema for the invoice. An object with a vendor string, a date string, a currency that must be one of three codes, and an array of line items, each with a description, a quantity and a unit price. Then tax and total as numbers. Every field is required, and additional properties false stops the model inventing extra keys. Add a short description to each field, like: the issue date, as year, month, day. Descriptions guide the model exactly like a prompt.
{"type": "object",
"properties": {
"vendor": {"type": "string"},
"date": {"type": "string"},
"currency": {"enum": ["USD","EUR","INR"]},
"items": {"type": "array", "items":
{desc, qty, unit_price}},
"tax": {"type": "number"},
"total": {"type": "number"}},
"required": [every field],
"additionalProperties": false} A worked extraction
Run it on a real invoice. Acme Limited, invoice four five seven, third of November twenty twenty six. Two cable kits at forty five dollars, one router at a hundred and twenty. Tax at eighteen percent is thirty seven eighty, total two hundred and forty seven eighty. The model returns exactly the schema: the vendor, the date as year month day, currency U S D, two line items with real numbers, then tax and total. No preamble, no fences, nothing to clean.
in: "Acme Ltd Inv 0457 3 Nov 2026
2 x Cable kit @ 45.00
1 x Router @ 120.00
Tax 18% 37.80 Total USD 247.80"
out: {"vendor": "Acme Ltd",
"date": "2026-11-03",
"currency": "USD", "items": [
{"desc": "Cable kit", "qty": 2,
"unit_price": 45}, {…Router…}],
"tax": 37.80, "total": 247.80} Enums and nulls
Two schema features do a lot of work. Enums turn free text into a fixed set of labels, so you never have to map U S dollars, the dollar sign and lowercase usd to one code. Required fields guarantee every key is present. But what if the invoice has no purchase order number? If the field must be a string, the model will invent one that looks right. Make it string or null, and say: null if not printed. Give the model an honest way to say it found nothing.
- enums currency: one of 3 codes never "US Dollars", "$", "usd"
- required + nullable po_number: string or null "null if not printed on the invoice"
- no null option → the model
- invents a plausible value
Small and flat
Keep schemas small and flat. Deep nesting and hundreds of fields make the model's job harder and can exceed the limits providers put on enforced schemas. Split a big extraction into two calls instead. Not every JSON Schema keyword is enforced everywhere, so check whether pattern, format or minimum really are. And the model writes keys in order. If you want a short justification, put it before the verdict, so the verdict is written after the evidence.
- flat beats deeply nested
- tens of fields, not hundreds: split big jobs into 2 calls
- short, clear key names
- not every keyword is enforced everywhere: check pattern, format, minimum, maxLength
- keys are written in order: evidence before the verdict
Valid is not correct
Now the most important rule. Constrained decoding guarantees the shape, never the truth. Say the model returns a total of two hundred and seventy four eighty. That is a valid number, so the schema passes. But your validator adds ninety, plus a hundred and twenty, plus thirty seven eighty tax, gets two hundred and forty seven eighty, and rejects it. Check types, ranges and business rules in code: sane dates, positive quantities, known vendors, totals that add up.
{"total": 274.80, ...} type: ok
checks a schema cannot do:
2x45 + 1x120 + 37.80 = 247.80
247.80 ≠ 274.80 → reject
date not in the future
qty > 0, prices > 0
vendor is a known supplier
currency matches that vendor Validate and retry
When validation fails, retry with the error. Send the same document plus a specific message: total is two seventy four eighty, but items plus tax come to two forty seven eighty, re read the totals line. Specific errors get fixed far more often than a bare try again. Cap it at two retries. If it still fails, send the invoice to a review queue rather than saving a guess. Every retry is a full model call, so track the retry rate as a quality signal.
for attempt in 1..3:
out = model(doc, errors)
problems = validate(out)
if not problems:
return save(out)
errors = problems
send_to_review(doc, out)
error: "total is 274.80 but items
+ tax = 247.80. Re-read the
totals line of the invoice." Forcing a tool call
There is a second route to structure. Define a tool called record invoice whose input schema is your invoice schema, and set tool choice so the model must call exactly that tool. You never run it. You just read the arguments, which are your extracted fields. This works where there is no dedicated structured output mode, and fits agents that already use tools. With strict tool mode turned on, the arguments are constrained to the schema too.
- define a tool record_invoice
- whose input schema is the invoice schema
- set tool choice to that tool: the model must call it
- you never run it. The arguments are your output
- strict tools: schema enforced
Streaming partial JSON
Long outputs can be streamed, so users see fields fill in as they are written. Chunks split anywhere, even mid key, so a normal JSON parser fails until the very end. A partial JSON parser closes the open strings and brackets to give a best guess so far. Use that for display only. A quantity of two may still become twenty five on the next chunk. Save, charge or trigger anything only from the final, complete object, after it passes validation.
chunk 1 {"vendor": "Ac
chunk 2 me Ltd", "items": [{"de
chunk 3 sc": "Cable kit", "qty": 2
a partial parser closes the open
strings and brackets for display:
vendor "Acme Ltd", desc "Cable
kit", qty 2 (may become 25!)
render early; act only on the
final, complete, validated object Common mistakes
The usual mistakes. Trusting values just because the JSON parsed. No null option, so missing fields get confident guesses. Regular expressions to strip code fences when strict mode is available. Ignoring the stop reason. Even with constrained decoding, a reply that hits the max token limit is cut off mid object, and a refusal may not match your schema, so check why the reply ended before parsing. And one giant nested schema doing ten jobs.
- trusting values because the JSON parsed
- no null option, so gaps get filled with guesses
- regex to strip code fences instead of strict mode
- ignoring the stop reason: max tokens = truncated JSON
- one giant nested schema
- acting on streamed partials
Numbers worth knowing
Some ballparks. Prompt only JSON fails rarely, but one in a thousand times a million calls a day is about a thousand bad records daily. Schema enforced output brings parse failures to about zero, apart from truncation and refusals. The first request with a new schema can be slower while its grammar is compiled, and later ones reuse it. Cap retries at about two. And since output tokens cost three to five times input, long key names add up at scale.
prompt-only parse failures: rare, but 0.1% of 1M calls a day = ~1,000 bad records a day schema-enforced parse fails ~0 (except truncation, refusals) first call, new schema can be slower: grammar is compiled retries per item ≤ 2 each retry full call output vs input ~3-5x price long keys, padding cost tokens
Say it like this
How to say it. We extract invoices with schema enforced output: a small, flat JSON Schema with enums for currency and nullable fields for anything optional. Constrained decoding guarantees the shape. Our validator then checks the values: totals add up, dates are sane, the vendor exists. Failures retry up to twice with a specific error, then go to a review queue. Shape is guaranteed, values are validated. That line shows you have shipped this.
- "We extract invoices with a small, flat JSON Schema in strict mode: enums for currency, nullable optional fields. The decoder guarantees the shape; our validator checks totals, dates and vendors. Failures retry twice with the error, then go to a review queue."