Skip to content
Eldan.ai

Engineering, , 7 min read

Structured output is a contract, not a prompt

A JSON schema is the interface between a model and your code. Treat it like one: write it first, check every response, and give it a version.

On this page

A feature needs the model to return data instead of prose, so someone adds a line to the prompt: “Respond in JSON with the fields vendor, total and currency.” It works on the first ten tries. Then a response arrives with a friendly sentence before the opening brace, or with the total as the string “1,200.00”, or with a field called amount because the model decided that name was better. The parser throws, and the fix is another sentence in the prompt.

The trouble is the framing. A line in a prompt is a request. What the rest of your program needs is a contract: an exact description of the shape it will receive, enforced in code, with defined behaviour when it is broken. Once you see it that way, the work becomes ordinary software engineering.

Write the schema first

Start with the type your code wants, not with the instructions. If the next function takes an invoice with a vendor, an issue date, a total in minor units and a currency, write that down before you write a word of the prompt.

Python
from datetime import datefrom enum import Enumfrom pydantic import BaseModel, Field class Currency(str, Enum):    USD = "USD"    EUR = "EUR"    KZT = "KZT" class Invoice(BaseModel):    vendor: str = Field(min_length=1)    issued_on: date    due_on: date | None = Field(description="null if the document has no due date")    total_minor: int = Field(ge=0, description="Total including tax, in minor units (cents)")    currency: Currency

Writing the type first does three things. It forces you to decide what each field means while a change is cheap: tax included or not, cents or whole units, what to do when there is no due date. It gives the prompt and the validator one source of truth, because the JSON Schema is generated from the type (Invoice.model_json_schema() in Pydantic, a converter for Zod in TypeScript). And a diff of a schema is easier to review than a diff of a paragraph.

Note that due_on is required but nullable. I prefer that to an optional field: null is an explicit statement that there is no due date, while a missing key could mean absent or forgotten.

Field names and descriptions are part of the prompt. A description on total_minor does more work than an instruction three paragraphs away.

Constrained decoding helps, and it is not the end

The large providers can now constrain generation to a schema. OpenAI’s Structured Outputs accept a JSON Schema with strict: true, and Anthropic’s structured outputs compile your schema into a grammar for constrained decoding. Use them: they remove the failures where the JSON does not even parse.

They do not remove the need to validate. Both providers document cases where the output may not match: a refusal, or a response cut off at the token limit. Both support a subset of JSON Schema, so some of your constraints are never seen by the decoder.1 And no grammar can tell you that the total is correct. OpenAI’s guide says it directly: your application still has to validate the business rules the schema does not express.

1Anthropic lists numeric and length constraints, such as minimum and maxLength, among the JSON Schema features it does not enforce during generation. Your validator still has to check them.

So the rule is short. Whatever the provider promises, every response goes through your validator before any other code touches it.

Validate, then retry with the error

When validation fails, the most useful thing you have is the error. Pydantic’s ValidationError says which field failed and why. Send that back to the model.

Python
from pydantic import ValidationError class ExtractionFailed(Exception):    pass def extract_invoice(text: str, call_model, max_attempts: int = 2) -> Invoice:    messages = [{"role": "user", "content": text}]    schema = Invoice.model_json_schema()    problems = "no attempts made"    for _ in range(max_attempts):        raw = call_model(messages, schema=schema)        try:            return Invoice.model_validate_json(raw)        except ValidationError as err:            problems = "; ".join(                f"{'.'.join(map(str, e['loc']))}: {e['msg']}" for e in err.errors()            )            messages += [                {"role": "assistant", "content": raw},                {"role": "user", "content": f"Validation failed: {problems}. Return corrected JSON only."},            ]    raise ExtractionFailed(problems)

Two details matter. Retry once, perhaps twice, never in a loop until it passes: a response that fails twice usually means the input is outside what the schema describes, and you want to see that, not hide it. And when you give up, fail with a typed error that the caller handles. Do not return a half-filled object with defaults that look like real data.

After the shape passes, check the rules a schema cannot say: the issue date is not in the future, the due date is not before the issue date, the total equals the sum of the lines if you extracted them.

Version the schema

A schema is an interface, and interfaces change. Adding a field, splitting one, tightening an enum: each can break stored outputs, cached responses, eval labels and every consumer of the data.

Treat it like an API. Give the schema a version number and store it next to every output. Prefer additive changes. When a change breaks compatibility, bump the version, migrate stored records if you keep them, and re-run your evals, because a new field the model must fill is a new chance to be wrong. The version also belongs in every cache key, so an answer produced under the old contract is never served as if it met the new one.

Measure the parse rate

For every call, record one of three outcomes: valid on the first try, valid after a retry, or failed. Track the first-try rate per schema version and per model, in your eval runs and in production.

It is cheap and says a lot. A drop after a prompt change means the instructions now fight the schema. A drop after a model upgrade means you look closer before rolling it out. A steady stream of failures on one kind of input means the schema is missing a case, which is a requirements bug, not a model bug.

Parse rate is not quality. A response can be perfectly shaped and completely wrong.2 Keep the parse rate next to your accuracy metrics as the floor under them: if the output does not parse, nothing else you measure about it matters.

2A total of zero passes a schema whose minimum is zero. Shape checks catch format errors. Only evals with labelled answers catch wrong values.

The short version

Define the type first and generate the schema from it. Validate every response in code, even with constrained decoding. Retry once with the validation error, then fail loudly. Put a version on the schema and on everything produced under it. Count how often it parses.

The glossary entry on structured output sums up the term on one page. The section “Structured output and tools” in LLM Apps in Production builds this extractor step by step, including the retry and the failure states.