# Getting reliable structured output from language models

> Software needs fields it can parse, and a model writes prose. Dependable structured output comes from four layers used together: a schema designed for the model, constrained generation, validation in code and a defined route for whatever fails.

Generative AI · How-to · November 16, 2026 · 8 minute read · By Nabil Ahmed
Canonical: https://farside.works/insights/reliable-structured-output-from-llms/

![The lunar surface near 24°N, 141°E, lit by a low Sun with night falling across one side.](https://farside.works/content/images/2026/11/reliable-structured-output-from-llms.webp)

A language model produces text, while the systems around it need data such as a category code to route on, an amount to post or a date to schedule against. Somewhere between the model and those systems the prose has to be turned into fields, and a surprising number of AI features break in production at exactly that step.

The failure usually starts small. The model returns valid JSON for the first thousand requests and then wraps one response in a sentence of explanation, adds a trailing comma, puts "N/A" in a field that the code expects to hold a number, or invents a category that is not on the list. When the parser throws an error and the job stops, someone adds a regular expression to strip out the extra text, and a month later the code carries six patches of that kind.

Structured output means model output that conforms to a schema your code defines in advance, so that it can be parsed and used without anyone interpreting it. We treat reliability here as a problem of interface design rather than prompt writing, and we approach it the way other interfaces are made reliable, with a contract, enforcement of that contract, validation, and a plan for the cases that fail.

## In brief

- Reliable structured output depends on four layers used together: a schema designed for the model, generation constrained to that schema, validation in code, and explicit handling of failures.
- Constrained decoding guarantees that the output has the shape the schema describes, although it gives no guarantee that the values are correct.
- Every field that might be unknown needs an explicit way to say so, because a model that is forced to fill a required field will produce a plausible value.
- Semantic validation against your own systems (whether the order exists, whether the line items add up to the total) catches the errors that schema validation cannot.
- Output that still fails validation after a bounded number of retries should go to a human queue with the reason attached, and should never be rescued by making the parser more and more lenient.

## Layer 1: design the schema for the model

The schema is the contract between the model and your code, and most of the reliability of the arrangement depends on its design, where a handful of rules do most of the work.

**Give every uncertain field a way out.** When a field is required and typed as a string, the model has to put something in it, and if the source text does not contain the answer, that something will be a guess. Make such fields nullable or add an explicit value such as `"not_stated"`, and use the field description to say when that value applies.

**Use enumerations for anything you branch on.** If your code routes on a category, list the allowed values in the schema. Include an `"other"` value as well, and when it starts to appear often, take that as a sign that the list needs revisiting.

**Describe what each field means.** The model reads field descriptions as instructions, so a description like "The date the customer wants delivery, in ISO 8601 format, null if not stated" does far more work than a field that is only named `date`.

**Keep it flat and small.** Deeply nested schemas full of optional fields produce more errors than flat ones, so if one call has to return thirty fields across four levels, consider splitting it into two calls.

**Put reasoning before conclusions.** Because a model generates tokens in order, a short justification field placed ahead of the decision field lets it work through the evidence before committing. When the justification comes after the decision, it tends to be written to fit a choice that has already been made.

**Ask the model for evidence.** In extraction tasks, a field holding the exact quoted text that supports each value makes the output checkable, both by code, which can test whether the quote appears in the source, and by the people who review it.

```json
{
  "type": "object",
  "additionalProperties": false,
  "required": ["evidence_quote", "category", "order_number", "requested_action"],
  "properties": {
    "evidence_quote": {
      "type": "string",
      "description": "Exact sentence from the message that best shows the customer's request."
    },
    "category": {
      "type": "string",
      "enum": ["delivery_delay", "damaged_goods", "invoice_query", "cancellation", "other"]
    },
    "order_number": {
      "type": ["string", "null"],
      "description": "Order number exactly as written. Null if none appears. Never guess."
    },
    "requested_action": {
      "type": "string",
      "enum": ["refund", "replacement", "information", "none_stated"]
    }
  }
}
```

## Layer 2: constrain generation

At generation time there are three levels of enforcement, each stronger than the one before it.

The weakest level is instruction, where the prompt asks for a JSON response and shows an example. That works most of the time and fails at unpredictable moments, which is the least useful kind of reliability for a production system.

The middle level is the JSON mode that several providers offer, which guarantees syntactically valid JSON although it does nothing to make the output match your schema.

The strongest level is constrained decoding, where the generation process is restricted at each step to tokens that keep the output valid against a supplied schema or grammar. Several hosted providers offer this as a structured output feature that accepts a JSON Schema, and open-source libraries do the same for self-hosted models. Function or tool calling, in which the model fills in the arguments of a declared function, is a closely related mechanism and is often the most convenient way of getting typed output. Wherever strict schema enforcement is available, it should be used.

Constrained decoding has limits. Providers support only a subset of JSON Schema, so some keywords may be rejected or ignored. It also guarantees the shape of the output without guaranteeing its truth, so the `order_number` field will be a string or null, but nothing ensures that it holds the right order number. Truncation is a further gap, because a response that reaches the maximum output token limit stops in the middle of an object. Your code should always check the reason the model stopped and treat a length stop as a failure, even when the partial text happens to parse.

## Layer 3: validate in code, twice

Do not rely on the generation layer alone. Parse the output and validate it against the schema in your own code with a schema library such as Pydantic in Python, Zod in TypeScript or a JSON Schema validator. This costs little and protects you when a provider changes behavior, when a fallback model without a strict mode is called, or when someone updates the schema in one place and not the other.

The second round of validation concerns meaning. Schema validation tells you the output is well-formed, whereas semantic validation tells you whether it makes sense for your business, and the checks involved are ordinary code:

- Referential checks, for example that the order number exists and the customer identifier belongs to the sender.
- Arithmetic checks, such as whether the line items add up to the stated total.
- Range and plausibility checks, for instance that the delivery date is in the future and the quantity is positive.
- Grounding checks, which confirm that the evidence quote really does appear in the source text.
- Cross-field rules, so that a requested action of "refund" is paired with a category of "invoice_query" only if your policy allows it.

When validation fails, send the validation error back to the model so that it can correct the specific problem, and allow one or two retries at most. A request that has failed three times usually points to something about the input itself, and a fourth attempt is unlikely to get a different result.

```python
def extract(message: str, max_attempts: int = 3) -> Result:
    feedback = None
    for attempt in range(max_attempts):
        resp = call_model(message, schema=TICKET_SCHEMA, feedback=feedback)
        if resp.stop_reason == "length":
            feedback = "Output was cut off. Be more concise."
            continue
        try:
            ticket = Ticket.model_validate_json(resp.text)   # shape
            check_semantics(ticket, message)                 # meaning
            return Result.ok(ticket, attempts=attempt + 1)
        except (ValidationError, SemanticError) as err:
            feedback = f"Previous output was rejected: {err}"
    return Result.needs_review(message, reason=feedback)
```

## Layer 4: decide what happens to failures

However good the schema is, some inputs will not produce a valid result, for example a message in an unexpected language or one that contains two requests, or an attachment that cannot be read. The design question is where those inputs should end up.

They belong in a queue that a person works through, with the original input, the model's last output and the validation error all visible. Making the parser more forgiving until everything gets through is the wrong response, because lenient parsing turns a failure that people can see into a wrong value that nobody notices. Document extraction calls for the same explicit threshold for human review, as we describe in [intelligent document processing: setting confidence thresholds that hold](https://farside.works/insights/document-processing-confidence-thresholds/).

Two more points belong in this layer. When the structured output triggers an action in another system, a retry must not cause that action to happen twice, which is the subject of [idempotency](https://farside.works/insights/idempotency-explained/). The schema is also a contract with downstream consumers, so it should carry a version number and go through the same change process as an API, bearing in mind that adding an enumeration value breaks any code that uses an exhaustive switch over that field.

## Support triage at a software vendor

Consider a B2B software vendor that routes inbound support emails. A model reads each email and returns a JSON object containing the product area, the severity and the customer account, and a workflow then assigns the ticket. The original implementation uses a prompt ending in "Return JSON only" and a parser that has gathered workarounds over time.

Three failures keep recurring. The model sometimes puts a sentence in front of the JSON, which the workarounds mostly handle. It returns severity values like "High" and "urgent" when the workflow expects one of four codes, so those tickets drop into a default queue and wait there. When an email does not mention an account, the model fills in the name of some company the sender mentioned in passing, and the ticket is attached to the wrong customer. That third failure is the serious one, and nothing in the system reports it.

The fix works through the four layers in turn. The schema is rewritten so that severity is an enumeration, the account field is nullable with a description telling the model to return null unless the sender states their account, and an evidence quote supports the severity. The call is moved to the provider's strict structured output feature. Validation in code checks the schema and then confirms both that any account returned matches the sender's email domain in the CRM and that the evidence quote appears in the email. A failure is retried once with the error attached and then goes to a triage queue.

The team also adds the measure that had been missing, a daily count of the share of requests that pass first time, pass on retry or go to review, so that a shift in those figures after a model upgrade gives early warning. The correctness of the values themselves is checked with a labeled test set that runs on every change, as is standard practice in [AI evaluation](https://farside.works/services/artificial-intelligence/ai-evaluation/).

## What to do next

Wherever your [AI application](https://farside.works/services/artificial-intelligence/ai-application-development/) has code that parses model output, check the following points.

1. Is there a written schema in version control, with a description on every field?
2. Can every field that might be missing from the input be returned as null or as an explicit "not stated" value?
3. Is every value that the code branches on defined as an enumeration?
4. Is generation constrained by the provider's strict structured output or tool-calling feature, or by a grammar in the case of self-hosted models?
5. Does your own code validate against the schema independently and check the stop reason for truncation?
6. Which semantic checks against your own systems would catch an answer that is well-formed but wrong, and have they been written?
7. Are retries bounded, and does a final failure go to a named queue with the reason attached?
8. Do you record the first-pass, retry and review rates, and raise an alert when they move?

Where the output feeds a business process directly, as in [intelligent automation](https://farside.works/services/artificial-intelligence/intelligent-automation/) of routing and exception handling, or where it is written into a system of record through an [integration layer](https://farside.works/services/artificial-intelligence/ai-integration/), items 6 and 7 should be treated as conditions for release rather than improvements for later.
