Stage 2 · Teens · Working with LLMs

Structured Output

Getting parseable JSON (and other schemas) instead of hoping the model formats it.

A lot of production LLM use is not "write a paragraph" — it is "fill in these fields so another program can run." That means the output has to be structured: valid JSON, a known enum, a row that matches a schema.

Asking "please return JSON" in the prompt helps, and still fails. Models wrap objects in prose, forget quotes, invent extra keys, or slightly change field names. A 2% parse failure is invisible in a demo and a pager at 50,000 requests/day.

Constrained decoding (JSON mode, grammar-constrained sampling, tool/function schemas) changes the rules: at each step, tokens that would make the output invalid against the schema are simply not allowed. You still need the model to choose the right values; you no longer need it to remember JSON syntax.

Constrained Decoding, Token by Token
{|
" }SureHere
After `{`, a string key or a closing brace can keep JSON valid. Prose is illegal.

Green tokens are legal next pieces of JSON. Struck-through tokens are masked out.

All lessons in Stage 2: How AI works