#Why applications need structured output
AddedA chat window is read by a person, and a person can read anything: a sentence, a bulleted list, a table, an apology followed by the answer. Your code can't. The moment a model's reply feeds an if statement, a database insert or a React component, it has to arrive in a shape your program knows in advance: these fields, these types, these allowed values. That is what "structured output" means: the model's answer is data that follows a schema, and not prose that a human has to interpret.
The mental model: treat the model like an external service whose response body you don't control. You would never write JSON.parse(body).user.address.city against a third-party API without a contract and a validator. A model is a third-party API whose "response format" is whatever text was most likely given your prompt. Left alone, it answers the same question with "Refund: yes", with a paragraph, or with JSON wrapped in a Markdown code fence, depending on small changes in the input. Structured output replaces "most likely text" with a contract.
There are three levels of contract, and it helps to name them, because interviewers ask what guarantees each one gives:
| Level | How | What you can rely on |
|---|---|---|
| Ask nicely | "Reply with JSON only" in the prompt | Nothing. Usually works; fails on a long tail of inputs |
| Schema-constrained | output_config.format with a JSON schema | The reply always parses and always matches the schema (unless the reply was cut off or refused) |
| Schema + your validation | Constrained output, then your own checks | The shape and your business rules (totals add up, ids exist, dates are in the future) |
The example below shows why the first level isn't enough. It takes three replies to the same question, "should this customer get a refund?", and runs the parser a developer typically writes first. The three replies were written for the example, in styles that models really do produce: a bare sentence, JSON in a code fence with a comment before it, and a hedged answer.
// Three replies to the same prompt: "Should order 1042 be refunded? Answer yes or no and give the amount."
// (Written for the example, in three styles a model can produce.)
const replies = [
"Yes. The order qualifies for a full refund of $49.99.",
"Here is the result:\n```json\n{\"refund\": true, \"amount\": 49.99}\n```",
"I can't say yes or no with certainty, but the policy suggests no refund, since 45 days have passed (limit: 30).",
];
// Attempt 1: look for the word "yes".
const byKeyword = (text) => /\byes\b/i.test(text);
// Attempt 2: the prompt said "reply in JSON", so parse it.
const byJson = (text) => {
try { return JSON.parse(text).refund; } catch (err) { return `throws ${err.name}`; }
};
// Attempt 3: pull the first number out as the amount.
const amount = (text) => Number(text.match(/\d+(\.\d+)?/)?.[0]);
replies.forEach((text, i) => {
console.log(`reply ${i + 1}: keyword=${byKeyword(text)} json=${byJson(text)} amount=${amount(text)}`);
});reply 1: keyword=true json=throws SyntaxError amount=49.99
reply 2: keyword=false json=throws SyntaxError amount=49.99
reply 3: keyword=true json=throws SyntaxError amount=45- The three strings stand in for three replies to one prompt. Nothing about them is unusual: a direct sentence, JSON wrapped in a Markdown code fence with a line of introduction, and a careful answer that explains itself.
byKeywordlooks for the word "yes". Reply 1 givestrue(correct). Reply 2 means yes but never says the word, so it givesfalse. Reply 3 says "I can't say yes or no", so it givestruefor an answer that means no. One parser, two wrong results out of three.byJsoncallsJSON.parseon the whole reply. It throws aSyntaxErroron all three: replies 1 and 3 aren't JSON at all, and reply 2 contains JSON but starts withHere is the result:and a code fence. "Reply in JSON" in a prompt is a request, and the model's most likely text often includes a polite sentence around the data.amountgrabs the first number. Replies 1 and 2 happen to give49.99. Reply 3 gives45, which is the number of days in the explanation, not an amount of money. The parser has no idea which number means what.- No single attempt gets all three replies right, and each failure is silent: the code returns a wrong boolean or a wrong number and carries on. In production that's a refund issued for the wrong amount, with nothing in the logs.
- The fix isn't a cleverer regular expression. It's to stop parsing prose: make the model fill in
{ refund: boolean, amount: number }under a schema the API enforces, which is the next topic.
Where structured output shows up in a real product:
- Extraction: turning an email, a PDF or a support ticket into a row (
{ category, priority, order_id }). - Classification and routing: an enum your code switches on (
"billing" | "technical" | "sales"). - UI generation: a list of typed blocks the front end renders as components, never raw HTML from the model.
- Tool calls: the model asks your code to run a function, and the arguments are structured output with a schema. The second half of this chapter is about that.
- Model-to-model hand-offs in a pipeline or an agent: one step's output is the next step's input, so it has to be parseable every time, not 98% of the time.
A developer strips the sentence before the JSON and parses what's left. What does this print?
const reply = 'Sure! Here is the JSON:\n{"refund": true, "amount": "49.99"}';
const data = JSON.parse(reply.slice(reply.indexOf("{")));
console.log(data.amount + 10, data.amount > 100, data.refund === "true");Show answer
49.9910 false false. The JSON parsed, and two of the three results are still wrong.
reply.indexOf("{")finds the start of the object, soJSON.parsesucceeds: no exception, which is what makes this bug quiet.data.amountis the string"49.99": the model put quotes round the number."49.99" + 10is string concatenation, so the first value is49.9910. A refund of "49.9910" euros would go to the payment system.data.amount > 100compares a string with a number; JavaScript converts"49.99"to49.99, so this one happens to be right (false). Code that's right by accident is the hardest kind to notice.data.refundis the booleantrue, andtrue === "true"isfalse. Code written for a model that sometimes says"true"in quotes now refuses a refund the model approved.- "It's valid JSON" only says the brackets balance. Types and allowed values need a schema: with
output_config.format,amountis always a number andrefundalways a boolean, and a zod check on your side catches the rest.