Structured output — study guide
The concept's fragments, read in order.
When the reader is a program
A language model writes text, and text is a fine thing to hand a person. A person skims past a friendly opening line, copes with an answer phrased three different ways, and asks a follow-up when something is unclear. A program does none of that. When the next thing to read a model's output is code, which wants a field called category holding one of three known values, fluent prose stops being a feature and becomes a problem.
Structured output is the practice of getting a model to emit data instead: text in an agreed format, commonly JSON, with an agreed shape, so a parser can read it and the rest of the program can rely on it. The formats themselves are old news, since data formats are exactly the agreements between writer and reader that make bytes mean something. What is new is the writer. A model produces its output one token at a time by prediction, so the agreement has to be pursued, enforced, and checked rather than assumed.
That gives the concept three moving parts. There are ways to get the format: asking for it in the prompt, and constraining generation so that only valid output can come out. There is a contract, a schema, that says exactly what valid means. And there is the checking that happens when the response arrives, with a plan for what to do when it fails. Running through all three is one distinction worth holding onto: output that parses, output that fits the schema, and output that is actually right are three different things.
Why prose is a poor interface
Ask a model for an order total in plain words and the answer can arrive as "The order total is 42.50.", as "Sure! 2 items, total 42.50.", or as "It comes to forty-two fifty." All three are correct, and a person reads them identically. Code that has to pull the number out needs a rule, something like "take the first number in the text", and that rule gets the first reply right, picks up the 2 from the second, and finds nothing at all in the third.
This is the core trouble with free text as an interface between a model and a program. The same content can come back in a different wording, a different order, with a polite preamble, with a closing remark, or wrapped in formatting meant for a human eye. Every scraping rule is a bet that the next response will look like the ones it was tested on, and the model is under no obligation to keep that bet. The failure is also quiet: the rule does not crash on the second reply, it confidently returns the wrong number.
Data with a known shape removes the guessing like the difference between a letter and a filled-in form: both can carry the same facts, but only the form puts each one in a labeled box a clerk can find without reading the whole thing. If the reply is the object {"total": 42.50}, a parser reads the field named total and gets the same value however the model might have phrased a sentence about it. The program no longer interprets language; it reads a named field. Everything else in structured output is about getting that object to arrive reliably, and knowing what it still does not promise.
Asking for a format
The first tool is the obvious one: say what you want. A prompt can carry an output contract that names the format, lists the fields, gives an example of a correct reply, and asks for nothing else. Prompt structure covers how to write that request well. The question here is what the request actually buys, and the honest answer is a strong tendency rather than a rule. The model treats the instruction as context that makes a well-formed reply likely; nothing in the generation process stops it from writing something else.
When a prompted format slips, it slips in recognizable ways. The object arrives with a sentence of explanation before or after it, or wrapped in the code fences people use to display code, so the response as a whole is no longer bare JSON. The syntax breaks: a missing comma, a trailing comma, an unescaped quote, a brace that never closes. Or the syntax is fine and the shape is wrong: a field missing, an extra one invented, a number where a string was promised. A separate failure has nothing to do with obedience at all: if the reply runs into the response's length limit, it stops, mid-object.
How often this happens depends on the model, the task and the shape requested. One 2024 benchmark of prompt-only JSON found success ranging from 0 to 100 percent depending on model, task and prompt wording, with lists and nested objects hardest. Even a far better rate is not a guarantee at volume. Take an illustrative format that holds 99 times in 100: across 1,000 calls that is 1,000 x 0.01 = 10 failures, every one of which reaches whatever code reads the result. Prompting for a format is worth doing, and on its own it is not enough.
Constraining generation to a schema
Asking leaves the model free to write anything. Constraining takes that freedom away at the only point where it exists: the moment each next token is chosen. A model generates by scoring every token it could emit next and picking one. Constrained decoding puts a checker in that loop. The checker tracks the output so far against a grammar, plain JSON syntax or a particular schema, works out which candidate tokens could still lead to a valid finished output, and removes the rest before the choice is made. Removed tokens get zero probability; the remaining ones keep their relative order, so the model still chooses, just among moves that cannot break the format like writing through a stencil, where the hand still chooses each stroke but the cut-outs make it impossible to draw outside the outline.
Because tokens are word pieces rather than single characters, the checker has to judge each candidate's whole text against the output so far, but the effect is simple to state. After the opening {"category": ", a schema that allows only billing, shipping and other lets no other value through, however strongly the model favored writing delivery. Two levels of constraint are worth telling apart: a plain JSON-only mode can make the output parse without enforcing any particular shape, while schema-constrained generation also enforces the fields, types and allowed values the schema names.
The guarantee is real and narrower than it sounds. It covers a response that finished normally. Output cut off by a length limit is still incomplete, and in some services, a refusal arrives outside the format. It covers only the parts of the schema the mechanism actually enforces: there is no universal supported subset of JSON Schema, keywords such as numeric limits, string patterns or recursion are enforced by some implementations and not others, and an unsupported keyword may be rejected with an error or silently dropped. Some strict modes add requirements of their own, such as insisting that every object forbid extra properties. Whether a given system enforces a schema strictly or on a best-effort basis is something to check in its documentation, not assume.
The constraint also shapes the answer, not just its wrapping. If the honest answer is not among the allowed values, the model has to pick one that is, which is a reason to leave room such as an other value in a schema. And forcing a format can cost quality: published research has found that strict format restrictions can lower accuracy on reasoning tasks, with the size of the effect depending on the model, the task and how the schema is designed, so it is worth testing the exact setup on representative inputs.
The schema is the contract
"Return JSON" is not yet a contract; it says nothing about which fields, of which types, holding which values. A schema is where that gets written down. For JSON, the established way to write one is JSON Schema, an open standard in which a schema is itself a JSON document describing what valid instances look like. A small one for sorting support messages might say the output is an object with three properties: category, a string that must be one of billing, shipping or other; order_id, a string; and urgent, a boolean.
Two rules in that schema do more work than they appear to. A property listed under properties is optional unless its name also appears in required, so a schema that forgets required quietly accepts an empty object. And unless the schema says "additionalProperties": false, an object may carry extra keys the schema never mentions. Writing both down is what turns a description into a contract that says exactly three fields, these types, nothing else.
The payoff is that one file can serve every party at the boundary. The same schema can be handed to the generation side to steer or constrain what the model emits, run by a validator on whatever comes back, and read by the developers of the code that consumes the result. When the shape changes, it changes in one place, and every side that reads the schema sees the change, instead of a prompt saying one thing, a parser expecting another, and the code assuming a third.
Parses, fits, is right
Three different properties hide behind the phrase "good output", and they are worth naming separately. Output is well-formed when a parser accepts it: {"category": "ship is not, because it stops before it closes. It is schema-valid when it also has the agreed fields with the agreed types and values: {"category": "delivery"} parses but fails, with a value the schema does not allow and two required fields missing. And it is correct when the values are actually true of the input it was produced from.
Each property depends on the ones before it and promises nothing about the one after. Text that does not parse cannot be checked against a schema, and an object that fits the schema can still be wrong. Picture a customer's message about a parcel that never arrived, sorted as {"category": "billing", "order_id": "A-1042", "urgent": false}. Every field is present, every type is right, billing is an allowed value, and the answer is false like a form filled in neatly, every box in the right place with the right kind of entry, that gives a false answer: processing it perfectly does not make it true. If the message actually quoted order A-1024, the id is false too, and no schema could have known.
The tools line up against the three levels unevenly. A parser checks the first. A schema validator checks the second, and constrained generation can secure both for a completed response, within what the mechanism enforces. Nothing about format reaches the third. Correctness is checked against the truth, by rules that compare the output with its source, by people, or by measuring a system's answers against known-good ones across many examples, which is a discipline of its own.
That makes the schema-valid wrong answer the dangerous case. Malformed output fails loudly at the parser, and output with the wrong shape fails at the validator, but a well-shaped falsehood passes both and flows on into whatever the program does next, looking exactly like a right answer.
Validate what comes back
Constrained generation does not make validation optional; it makes validation fail less often. Run a parser and a schema validator on every response before the program acts on it, whatever produced the response. The reasons are concrete. Enforcement can be partial, with schema keywords the generation side did not support quietly left unenforced. A response can be cut off by a length limit or replaced by a refusal, and neither is the requested object. And the validator is the check that does not depend on any particular model, setting or provider behaving as documented.
A schema also cannot say everything that matters. It can require that order_id is a string, not that the order exists. It cannot easily say that an end date must fall after a start date, that a number must have come from the source text rather than been invented, or that a template placeholder must not survive into the output. Those are business rules, and they belong in code that runs after schema validation and before anything acts on the result.
Underneath both reasons is a security one. Model output is untrusted input to the rest of the program, in exactly the sense data formats warn about for any data arriving from outside: the text a model read can steer what it writes, so a perfectly valid object can still carry hostile markup, an unsafe command or a request for an action nobody authorized. Security guidance on applications built around language models treats passing such output downstream unchecked as a risk in its own right, one that can lead to cross-site scripting, server-side request forgery or worse. Validate the values, check that the action is permitted, and handle each field safely for wherever it is going, the way any input from outside would be handled.
When the output does not fit
Validation will fail sometimes, so the program needs a decision ready for when it does. There are three responses, and they suit different failures. The cheapest is a narrow repair: when the flaw is purely in how the JSON is written, such as code fences around the object or a sentence before it, strip the wrapper or cut out the object and validate again. Practitioner guidance draws the line sharply: a repair may fix how the data is written but never what it means. Swapping a value the schema rejects for the nearest allowed one, or quietly clamping a number into range, is not repair; it is the program inventing an answer and hiding that it did.
The second response is a retry that carries the error. Sending the same request again tends to reproduce the same mistake, while sending back the exact validation message, which field, which rule, gives the model something specific to correct like a form sent back with a note saying exactly which box is wrong, so the second attempt fixes that box instead of guessing. Retries need a hard limit, because each one costs another full call and adds latency; the guidance in circulation ranges from a single retry to about three attempts in total, and agrees that a request still failing after that rarely recovers with more. Some failures should not be retried as they are: an output cut off by the length limit is likely to be cut off again unless the limit is raised or the output made smaller, and a refusal is better routed to a person than asked again.
The third response is giving up, deliberately. When the attempts run out, the program takes a path decided in advance: a safe default the caller knows to treat as uncertain, a queue for human review, or a plain error. What it must not do is pass partial or unvalidated data onward as if it were good. Log every failure with the raw response and the error, since those failures are the best evidence for fixing the prompt or the schema.
Where this carries weight
Anywhere a model's output drives code instead of being read by a person, this boundary is load-bearing. An agent deciding its next action has to express that decision as data its harness can act on. An application feature that pulls fields out of a customer's message has to hand the rest of the system a record, not a paragraph. A planner that turns a goal into commands for hardware has to produce commands the controller will accept, every time, including on the inputs nobody tested.
In each case the same pieces carry the weight. A schema states the contract once. Constrained generation, where it is available and enforced, makes malformed and misshapen output rare. Validation on every response catches what slips through and applies the rules no schema can express. A bounded plan for failure keeps a bad response from becoming bad data. Leave any one out and the system works in demonstrations and fails quietly in use.
What none of this settles is whether the answers are right, and that is the honest edge of the concept. Structured output gives a program something it can safely read; the concepts that build on it use that footing to let a model call functions with what it produced, and to measure, across many examples, how often what it produced was true.