IamBishal
AI Engineering

Structured Outputs from LLMs: JSON Schema, Constrained Decoding and Validation

Constrained decoding fixes broken JSON. Wrong values in correct shapes are still yours to catch, with business rules, cross-field checks and bounded retries.

Bishal Saha

21 min read

The grammar knows the type, not the arithmetic.
Bishal Saha

Picture an invoice extraction call that comes back clean. The JSON parses, passes schema validation and deserialises into a typed Invoice object. The line items add up to one amount, but the total field shows the same digits in a different order. Nothing throws. The record moves into the payables queue looking exactly like a correct one.

Broken JSON used to be the failure you could see: a Markdown fence around the payload, a chatty sentence after it, a missing brace. Providers now ship features built to remove it. Anthropic, for example, says its structured outputs guarantee schema-compliant responses. What's left is harder to see: wrong values in correct shapes. Constrained decoding solves syntax, not semantics. Use the strongest structural guarantee your provider offers, design schemas the model can fill well, and still check every field against business rules.

1. What each mechanism actually promises

Compare the mechanisms on one question: what does each guarantee?

Instructions only. You ask for JSON in the prompt and hope, then parse defensively and validate everything.

JSON mode. OpenAI's Structured Outputs guide says JSON mode guarantees only valid, parseable JSON, not that the output matches your schema, and points you to Structured Outputs or to a validation library plus retries. It also has a sharp edge: leave out an instruction to produce JSON and the model may emit an unending stream of whitespace, and the API returns an error if the string "JSON" appears nowhere in the context.

OpenAI recommends Structured Outputs over JSON mode whenever possible, but only some models support response_format with json_schema, and the guide lists which. If the model you pin isn't on that list, you're in the JSON mode row of the table below.

Schema-constrained decoding (structured outputs). Anthropic's structured outputs documentation says its structured outputs guarantee schema-compliant responses through constrained decoding: no JSON.parse() errors, guaranteed field types and required fields, and no retries for schema violations. The same page lists the exceptions. A refusal, or a response cut off at max_tokens, might not match your schema.

Tool or function calling. Tool arguments are structured output aimed at a function signature, but strictness is often a separate setting. Anthropic's strict tool use page says that without strict mode, Claude might return incompatible types ("2" instead of 2) or omit required fields, and that strict: true constrains sampling to schema-valid inputs. Check whether your provider has a strict flag, and whether it's on.

The Amazon Bedrock page for Claude structured outputs even says the response conforms to the schema, so no additional validation is required. That holds for schema validation only: a schema can say total is a number, not that the number is right.

MechanismGuaranteesDoesn't guaranteeWhen to use
Instructions onlyNothing structuralParseable JSON, schema compliance, correct valuesNo structured feature available; quick prototypes
JSON modeValid, parseable JSONYour schema, required fields, correct valuesYour model lacks schema support; validate everything and retry
Schema-constrained decodingSchema-compliant output: types and required fieldsCorrect values; refusals and responses cut off at max_tokensThe default wherever your provider and model support it
Tool calling (strict)Schema-valid tool argumentsCorrect values; that the call should happen at allAgent tool arguments and routing decisions

2. What constrained decoding does at each token

The schema is compiled into a grammar or finite-state machine. At each step the model produces logits over its whole vocabulary, and those logits are masked based on the machine's current state, so only tokens that keep the output valid can be sampled. The Outlines paper, Efficient Guided Generation for Large Language Models, describes this FSM-guided approach. Preprocessing the vocabulary once against the machine's states turns finding the allowed tokens into a dictionary lookup.

The mask limits which tokens can come next, not which value is right.

A schema that refers to itself needs a context-free grammar: OpenAI's CFG-based approach allows recursive schemas, and Anthropic lists them as unsupported. Compilation has a cost too: on Anthropic, more complex schemas take longer to compile, so the API enforces complexity limits, and a compiled grammar is cached for 24 hours after its last use, so the first request with a new schema is the slow one.

Now run the invoice through it. After the decoder has emitted "total":, the grammar accepts only tokens that can begin a JSON number, and blocks quotes and braces. The correct total and its transposed twin are both valid numbers, so both stay allowed, and the model's own probabilities choose between them. The grammar knows the type, not the arithmetic.

So when the most likely valid token is wrong (a transposed digit, a subtotal read as the total, a tax line counted twice), constrained decoding gives you a perfectly formed wrong answer.

3. Designing a schema the model can fill well

A schema is part of the prompt, because the model reads its names and descriptions, and the contract your code deserialises against. Version it with the prompt, and treat a changed field as a breaking change.

Start with field order. With OpenAI Structured Outputs, fields are produced in the same order as the keys in the schema; Anthropic keeps schema order too, but puts required properties before optional ones. So make a short notes field required and list it first, and the model writes down where it found the total, or what looked ambiguous, before it commits to a number. Keep it a short explanation, not step-by-step reasoning: Anthropic warns that a property asking for the model's step-by-step reasoning might lead to a reasoning_extraction refusal. I treat the field as a design choice worth testing, not a measured gain.

OpenAI's tips are to name keys clearly, add titles and descriptions to important keys, and build evals. On an invoice, describing total as "amount due including tax, as printed" targets an obvious ambiguity: subtotal versus total.

Use enums for currency and document type, which keeps "US Dollars", "usd" and "$" out of your code. But a closed enum under constrained decoding must pick one of its values even when none fits: a yen invoice can only come out as one of your four currencies. Add an explicit OTHER value and route it straight to review, since a retry can't fix it. Anthropic also doesn't guarantee the capitalisation of enum values, so normalise case before validating, as the code below does. Prefer required-but-nullable to optional: a missing dueDate could mean "not on the document" or "the model forgot", and null makes the model say which.

Then there are provider limits. Anthropic doesn't support numeric constraints such as minimum, string length limits, or minItems other than 0 or 1, though it does support formats such as date. So "at least one line item" fits as minItems: 1, while "no negative amounts" moves into your validator. OpenAI's Structured Outputs supports only a subset of JSON Schema too, strict: true with an unsupported schema returns an error, and fine-tuned models lose string formats, number bounds and array length limits.

Here's the invoice shape the rest of the article builds on:

invoice-shape.ts
import { z } from "zod";

export const LineItem = z.object({
  description: z.string(),
  quantity: z.number(),
  unitPrice: z.number(),
  amount: z.number().describe("line amount as printed, before tax"),
});

export const InvoiceShape = z.object({
  notes: z.string().describe("Short explanation: where the totals were found, any ambiguity"),
  vendorName: z.string(),
  invoiceNumber: z.string(),
  issueDate: z.string().describe("ISO 8601 date, YYYY-MM-DD"),
  dueDate: z.string().nullable().describe("null if the document shows no due date"),
  currency: z.enum(["EUR", "GBP", "USD", "INR", "OTHER"]).describe("OTHER if the currency is none of these"),
  lineItems: z.array(LineItem),
  subtotal: z.number().describe("sum of line amounts before tax, as printed"),
  tax: z.number().describe("total tax as printed; 0 if none is shown"),
  total: z.number().describe("amount due including tax, as printed"),
});

Only the shape is converted to JSON Schema and sent to the provider; the rules stay in code. Check what survives the conversion, because the model sees only the converted version. Anthropic's SDK helpers, for example, remove constraints the API doesn't support and append them to the field's description instead of enforcing them.

4. Does a strict format cost you accuracy?

It can. Let Me Speak Freely? found that constrained decoding can hinder reasoning while improving classification accuracy, and that looser format restrictions improve reasoning performance. Parsing errors weren't the main cause of the difference, and corrective prompting can mitigate them.

Classification sits on the side that benefits; whether field extraction does is something to measure on your own data. Where a constrained call has to weigh evidence, test the explanation-first field, or split the work into an unconstrained reasoning call and a constrained formatting call, at the cost of a round trip. It's one study, a reason to measure rather than a settled rule.

5. Catching the invoice whose totals don't add up

Validation runs in layers. First, re-parse with Zod even when the provider guarantees compliance: you get real types instead of a cast, and can enforce what the provider's subset couldn't express. Next come field-level rules: dates are real and not in the future, amounts aren't negative unless the document is a credit note, and the vendor resolves to a row in your vendor table, a service step after parsing. Last are the cross-field checks: each line's quantity times unit price equals its amount, line amounts sum to the subtotal, and subtotal plus tax equals the total. That last layer catches our invoice.

The snippet below implements the cross-field layer and three field rules (a real calendar date, at least one line item, and a known currency), and leaves out the vendor lookup.

invoice-rules.ts
import { z } from "zod";
import { InvoiceShape } from "./invoice-shape";

export type Invoice = z.infer<typeof InvoiceShape>;

// Only the fields the rules need, so they still run when an unrelated field fails.
const RuleFields = InvoiceShape.pick({
  issueDate: true, currency: true, lineItems: true, subtotal: true, tax: true, total: true,
});

const MINOR_DIGITS: Record<Exclude<Invoice["currency"], "OTHER">, number> = { EUR: 2, GBP: 2, USD: 2, INR: 2 };
const TOLERANCE = 1; // in minor units, because floats don't sum exactly

const isRealDate = (s: string) => {
  const d = new Date(`${s}T00:00:00Z`);
  return /^\d{4}-\d{2}-\d{2}$/.test(s) && !Number.isNaN(d.getTime())
    && d.toISOString().slice(0, 10) === s; // rejects rollovers such as Feb 30
};

export function businessRuleIssues(inv: z.infer<typeof RuleFields>): string[] {
  const issues: string[] = [];
  if (!isRealDate(inv.issueDate))
    issues.push(`issueDate: "${inv.issueDate}" is not a real YYYY-MM-DD date`);
  if (inv.lineItems.length === 0) issues.push("lineItems: at least one line item is required");
  if (inv.currency === "OTHER") return issues; // no arithmetic without minor units; validateInvoice flags review

  const digits = MINOR_DIGITS[inv.currency];
  const m = (n: number) => Math.round(n * 10 ** digits);
  const fmt = (minor: number) => (minor / 10 ** digits).toFixed(digits);
  const off = (a: number, b: number) => Math.abs(a - b) > TOLERANCE;
  inv.lineItems.forEach((li, i) => {
    if (off(m(li.quantity * li.unitPrice), m(li.amount)))
      issues.push(`lineItems.${i}.amount: ${li.quantity} x ${li.unitPrice} is not ${li.amount}`);
  });
  const lines = inv.lineItems.reduce((sum, li) => sum + m(li.amount), 0);
  if (off(lines, m(inv.subtotal)))
    issues.push(`subtotal: line items sum to ${fmt(lines)} but subtotal is ${fmt(m(inv.subtotal))}`);
  const expected = m(inv.subtotal) + m(inv.tax);
  if (off(expected, m(inv.total)))
    issues.push(`total: subtotal plus tax is ${fmt(expected)} but total is ${fmt(m(inv.total))}`);
  return issues;
}

// Enum casing isn't guaranteed, so normalise before validating.
const normalise = (input: unknown) =>
  input && typeof input === "object" && typeof (input as { currency?: unknown }).currency === "string"
    ? { ...input, currency: (input as { currency: string }).currency.toUpperCase() }
    : input;

// Shape failures and rule failures in one list, so a single retry can fix both.
// review: a retry can't help (unsupported currency), so send it straight to a person.
export function validateInvoice(raw: unknown):
  | { ok: true; invoice: Invoice }
  | { ok: false; issues: string[]; review: boolean } {
  const input = normalise(raw);
  const shape = InvoiceShape.safeParse(input);
  const issues: string[] = shape.success ? [] : shape.error.issues.map(
    (i) => `${i.path.map(String).join(".") || "(root)"}: ${i.message}`);
  const view = RuleFields.safeParse(input);
  if (view.success) issues.push(...businessRuleIssues(view.data));
  const review = view.success && view.data.currency === "OTHER";
  if (review) issues.push("currency: not a supported currency");
  return shape.success && issues.length === 0
    ? { ok: true, invoice: shape.data }
    : { ok: false, issues, review };
}

Running it against the transposed-total case:

transposed-total.ts
import { businessRuleIssues } from "./invoice-rules";

console.log(businessRuleIssues({
  issueDate: "2026-03-14", currency: "EUR", subtotal: 1250, tax: 0, total: 1520,
  lineItems: [{ description: "Support plan", quantity: 10, unitPrice: 125, amount: 1250 }],
}));
// prints:
// [ 'total: subtotal plus tax is 1250.00 but total is 1520.00' ]

Integer minor units avoid float drift on ordinary sums, but rounded unit prices against large quantities need a tolerance that scales with quantity. Decimal strings would avoid floats altogether, at the cost of a less natural shape for the model to fill.

Running the rules on a narrower RuleFields view keeps them independent of a library's refinement semantics. Keep a fixture with a mistyped dueDate and a transposed total, and pin the library version, so an upgrade that changes issue reporting fails a test before a payment run.

The same split works in Python with Pydantic, with one trap. By default Pydantic coerces values where it can, so the string '123' becomes the integer 123, which is exactly the quoted-number failure from earlier. Validate model output in strict mode, and pass it the raw JSON string: Invoice.model_validate_json(raw, strict=True), or strict mode in the model's configuration with model_validate_json(). Strict validation of a dict from json.loads() is the wrong tool here, because it rejects the ISO date strings and enum values that JSON can only carry as strings.

Treat the LLM like an untrusted upstream service. You wouldn't trust a partner API's invoice totals just because its payload matched the OpenAPI spec; you'd check the arithmetic and reject anything that doesn't reconcile. My background is in backend and API integration work. Agent tool arguments get the same treatment: use strict tool calling, then validate the arguments as you would an HTTP request body before any side effect runs. A well-formed argument object doesn't show that this caller may make this call; authorisation is a separate check, and so are the guardrails around what an agent may do.

Cross-field checks have a blind spot. Suppose the model misreads a quantity, then adjusts the line amount, subtotal and total to match. Every check passes. A misread vendor name that happens to match a real vendor passes the lookup too. Where that matters, ask the model to quote the source text for the total and vendor and confirm each quote appears in the document, reconcile against purchase orders, and send a sample of accepted invoices to human review.

6. Bounded retries, useful feedback and a way out

Repair, retry and fallback form a control loop. Like any loop that calls an external service, it needs a cap.

Every failure path ends at a cap or a person, never in an unbounded loop.

The first gate isn't optional. Because a refusal or a max_tokens cut-off can fall outside the schema, check the stop reason before you parse anything: map the stop reasons your provider documents to "finished normally" or not, and send anything else to review.

The strategies, cheapest first:

  • Deterministic repair needs no model call. Strip Markdown fences, or coerce a quoted number when strict mode is off and you know the field is numeric.
  • Targeted retry sends the exact validation issues back and asks for a corrected object.
  • Full regeneration starts from scratch, sometimes with a different prompt or model.

A preprint on prompt-enforced Pydantic schemas looked at what retry messages actually said. In 354 of 1,101 retry messages (32.2%), the feedback named only a parse error, even though the fence-stripped payload already violated the schema; almost all of those (350) came from Haiku 4.5. The setting is prompt-enforced schemas, not constrained decoding, but it shows how easily a retry loop tells the model to fix the wrong problem. Run every validation layer before you retry and report every failure in one message. A model can't correct a total it was never told was wrong.

extract-invoice.ts
import { validateInvoice, type Invoice } from "./invoice-rules";

// Illustrative sketch: these declarations stand in for your own client code.
type Message = { role: "user" | "assistant"; content: string };
declare function callModel(messages: Message[]): Promise<{ text: string; stopReason: string }>;
declare function buildPrompt(doc: string): string;
declare function stripFences(text: string): string;

type Result =
  | { ok: true; invoice: Invoice }
  | { ok: false; issues: string[]; raw: string | null };

export async function extractInvoice(doc: string, maxAttempts = 2): Promise<Result> {
  const messages: Message[] = [{ role: "user", content: buildPrompt(doc) }];
  let issues: string[] = [];
  let raw: string | null = null;
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const res = await callModel(messages); // maps provider stop reasons to "complete" | other
    raw = res.text;
    if (res.stopReason !== "complete") return { ok: false, issues: [`stopped: ${res.stopReason}`], raw };
    try {
      const v = validateInvoice(JSON.parse(stripFences(res.text)));
      if (v.ok) return { ok: true, invoice: v.invoice };
      if (v.review) return { ok: false, issues: v.issues, raw }; // a retry can't fix this
      issues = v.issues;
    } catch (err) {
      // Only JSON.parse throws here: report the parse error, not a misleading type error.
      issues = [`JSON parse failed: ${err instanceof Error ? err.message : String(err)}`];
    }
    messages.push({ role: "assistant", content: res.text },
      { role: "user", content: `The extraction failed these checks:\n${issues.join("\n")}\nRe-read the document and return corrected JSON.` });
  }
  return { ok: false, issues, raw };
}

Returning a discriminated result instead of throwing makes failure a normal outcome and keeps the raw text to log.

Retries aren't free. Each one adds a round trip of latency and tokens, and the same model given the same input may repeat the mistake. Keep the cap low, emit retry counts as a metric, and alert when they drift: the same discipline as putting a circuit breaker on an agent loop.

In my view, a business-rule failure that survives a targeted retry is more likely a document problem or a model limit, which another retry won't fix. Send it to a human review queue with the issues attached, and never auto-post a payment from an invoice that didn't validate.

7. Streaming partial JSON without acting on half an answer

Streaming helps user-facing extraction, where the vendor name can appear while line items are still arriving. Accumulate chunks, parse the unfinished buffer with a lenient incremental JSON parser, and type what you hold as a partial invoice:

partial-invoice.ts
import type { Invoice } from "./invoice-rules";

// Mid-stream, any field at any depth may be missing.
export type PartialInvoice = Partial<Omit<Invoice, "lineItems">> & {
  lineItems?: Partial<Invoice["lineItems"][number]>[];
};

// Illustrative output of a lenient parser over an unfinished buffer:
// buffer:  {"notes": "...", "vendorName": "Acme", "subtotal": 1250, "total": 13
// parsed:  { notes: "...", vendorName: "Acme", subtotal: 1250, total: 13 }
// settled: notes, vendorName, subtotal. `total` is still provisional.

Give the UI a settled-or-provisional contract: a field is settled once the parser has moved past it, to the next key or a closing brace, and provisional until then, because a lenient parser turns a half-written number into a value that looks complete: 13 could be the start of 1320. Show settled fields, but act on nothing until the object is complete and has passed validateInvoice; you can't check a total against line items that haven't arrived. A stream that ends with the object still open goes down the same failure path as any other. Schema order becomes a UX decision too, since an explanation-first notes field delays the first visible answer.

8. Testing extraction with property checks on a golden set

Exact-match assertions on model output are brittle. Test properties instead, on a golden set of real, anonymised invoices, including credit notes, invoices with no tax line, foreign currencies and handwritten totals. Assert that each output passes the schema and the production rules, that the vendor resolves to the labelled vendor ID, and that enum values match the labels; use exact match only for fields such as the invoice number. Labelled expectations catch the internally consistent errors the validators miss. Re-run the suite on every model, prompt or schema change, and track retry and rejection rates across runs.

9. One validator, one day of data

Pick one structured-output call already running in your system. Add a single business-rule validator: a cross-field sum, a date range, or a lookup against a table you trust. Log failures instead of blocking them, and count how many schema-valid responses it rejects over a day.

Treat the count as a rough signal. Near zero means this rule isn't where your errors are, not that the call is correct. A steady trickle calls for a retry path with good feedback; a pile points upstream, at the schema, prompt or model.

View All Articles

Bishal SahaLet's build together

Have a system to design, or an AI feature to get right?

Tell me about the problem. You'll get a clear, honest view of the best way forward.

  • Reply within 24 hoursOn business days, with my honest view and a next step.
  • Accepting select engagementsArchitecture, AI features and full builds.
  • Remote, worldwideWorking with startups, SMEs and enterprises.