Articles · Artificial intelligence · · 7 min read

Structured Outputs and Schema Design for LLM Agents

Schema-constrained generation gives you a parse guarantee, not a correctness one. How to design the output contract, the abstention path and the repair loop.

By Matthieu de La Mettrie · Founder, Skopura

What does a schema actually buy you?

A parse guarantee. Structured outputs constrain a model’s response to a supplied schema, which removes a whole class of failures — prose preamble, truncated JSON, a key renamed on a whim, a list where you expected an object. Every semantic failure survives intact. A field typed as a date will contain a date. It will not necessarily contain the right date.

That distinction decides where your effort goes. If you treat a validated payload as a validated answer, you have not removed the error; you have moved it from the parser, where it is loud and cheap, into the warehouse, where it is quiet and expensive. The parser used to catch the model having a bad day. Now nothing does.

So the design question is not whether to constrain the output. It is what shape the constraint takes, where it sits relative to your domain model, and what the system is supposed to do when the model cannot honestly fill the shape you gave it.

Where should the schema boundary sit?

Not on your domain model. The temptation is obvious — you already have a type for Invoice, the model is extracting an invoice, so hand it the type. What you have actually done is couple the generation contract to the persistence contract, so that adding a column for a downstream report changes the prompt surface and invalidates your evaluation set.

The alternative is a narrow extraction DTO that exists only at the model boundary, plus deterministic mapping code between that DTO and the domain object. The mapping code is where defaults get applied, enums get widened, identifiers get resolved against the real system, and anything the model got structurally right but semantically wrong gets rejected.

Narrow extraction DTODomain model as schema
Field count exposed to the modelOnly what must be read from the sourceEverything the domain needs, including fields derived elsewhere
Where defaults are appliedDeterministic mapping codeInferred by the model, invisibly
Effect of a downstream schema changeMapping layer absorbs itPrompt surface and eval set both move
Validation postureTwo gates: shape, then meaningOne gate that conflates the two
Typical failureMapping gaps show up as explicit rejectionsPlausible nulls land in storage
Two placements for the generation contract, and what each one makes hardqualitative comparison

The mapping layer looks like boilerplate until the first time a model fills a field it had no business filling, and you can point at the line that refused it.

Which fields should the model be allowed to invent?

As few as the task permits. The useful test is whether a wrong value in that field is detectable without a human reading the source document.

Closed sets should be enums, not strings. A free-text category field produces a long tail of near-synonyms and a mapping table that someone maintains for a while and then doesn’t. Identifiers should be selected from candidates you supplied in context, not generated — if the model can emit an account ID that was never in the retrieved material, you have an invented key with a valid type. Numbers that come from arithmetic belong to a tool, with the model quoting the result rather than computing it. Units and currencies belong in their own constrained field, never embedded in a string that someone will later parse with a regular expression.

Can the model fill this field freely?

Make it an enum — free text here becomes a mapping table nobody maintains

Deciding what the model is permitted to produce for a given fielddecision aid

What should happen when the source does not support an answer?

This is the decision most schemas get wrong. The default move is to mark uncertain fields optional, which makes omission ambiguous: a missing value could mean the document does not contain it, or the retrieval did not surface it, or the model simply declined. Three different operational responses, one indistinguishable payload.

Make abstention a branch rather than an absence. A discriminated union forces the model to commit to a mode — answered, not found in the supplied material, or ambiguous between several candidates — and gives each mode its own required fields. Now the routing logic downstream is explicit, and your evaluation set can contain cases whose correct answer is a refusal.

extraction-contract.tsts
1234567891011121314151617181920212223242526272829
import { z } from "zod";

const Evidence = z.object({
documentId: z.string(),   // must match a retrieved id
quote: z.string().max(400)
});

const Answered = z.object({
outcome: z.literal("answered"),
evidence: z.array(Evidence).min(1),
category: z.enum(["renewal", "termination", "amendment"]),
effectiveDate: z.string().date()
});

const NotInCorpus = z.object({
outcome: z.literal("not_in_corpus"),
searchedFor: z.string()
});

const Ambiguous = z.object({
outcome: z.literal("ambiguous"),
candidates: z.array(Evidence).min(2)
});

export const ExtractionResult = z.discriminatedUnion("outcome", [
Answered,
NotInCorpus,
Ambiguous
]);
Response schema shaped around branches rather than optional fieldsillustrative snippet

Note the ordering inside the answered branch. Generation is sequential, so anything the model should condition on has to be emitted before the thing it conditions. Evidence first, then the classification drawn from it. A rationale field placed after the verdict is a post-hoc story about a decision already made, and storing it as if it were the reason is a quiet form of self-deception.

While evidence belongs in the schema, it should be quoted spans tied to document identifiers you can resolve, not a prose summary. A summary cannot be checked. A span can.

How much repair should the pipeline do?

Some, bounded, and only for the right class of failure. A schema violation — wrong type, missing required field, enum member that does not exist — is worth one retry with the validator error fed back, because the model has concrete information it lacked. A semantic violation, such as an identifier that validates but does not exist in the context you supplied, is not worth retrying blind; it should be routed, logged and counted.

no

yes

no

yes

no

yes

Model call with schema

Parses against schema?

Repair budget left?

Retry with validator error attached

Dead-letter with raw payload

Semantic checks pass?

Route for review, do not retry

Map to domain object

Persist with schema version

Control flow around a constrained generation callconcept diagram

The repair budget is a real design parameter. Unbounded retries turn a bad input into a latency and token sink that is invisible until the bill or the queue depth says otherwise. Bounded retries with a dead-letter path turn the same input into a countable event. Keep the raw pre-validation payload on the dead letter; without it you cannot tell later whether a prompt change fixed the problem or merely stopped it being visible.

How do you version a schema two systems depend on?

Treat it like any other interface contract, with one extra consumer that cannot read your release notes. Additive changes are safe. Reusing a field name with a new meaning is not, because the stored payloads from before the change still parse and now mean something else. Stamp every persisted output with the schema version that produced it, and pin evaluation runs to a version so that a regression in scores is attributable to the prompt, the retrieval or the schema, rather than all three at once.

Generation contractBranch discriminatorAnsweredNot in corpusAmbiguousPayload fieldsClosed enumsIdentifiers constrained to supplied candidatesTyped scalars with explicit unitsEvidenceDocument identifierQuoted spanEnvelope metadataSchema versionRepair attemptsRaw payload reference
Decomposition of the generation contract and its surrounding metadatastructure only

What does this leave you to verify?

The schema is yours, not the provider’s — whether the call goes through Azure AI Foundry or directly to Claude, validate on your side and keep the semantic checks independent of whatever constrained decoding does for you. What is left to verify, once shape is guaranteed, is narrow and specific: do the identifiers resolve, do the quoted spans actually appear in the cited documents, does the branch the model chose match what a reviewer would choose, and does the rate of abstention move when retrieval changes.

Those are all checkable without reading prose. That is the real return on schema design — not fewer parse errors, but a set of failures you can count.

structured-outputs · llm-engineering · schema-design · agentic-ai

Share on LinkedIn ↗

Work with Skopura

Facing this bottleneck in your own estate?

Skopura builds production-grade lakehouse pipelines, evaluation harnesses, and provides fractional data leadership. Thirty-minute call, no deck.

Book a 30-min call →Email directly

Further reading

Artificial intelligence · 7 min

When a Deterministic Workflow Beats an LLM Agent

Agent autonomy is a control-flow decision, not a capability one. How to tell which steps deserve a planner and which should stay a hard-coded edge.

Artificial intelligence · 8 min

RAG Retrieval Design on Azure AI Foundry

Retrieval decisions made at index time — chunk unit, filters, freshness, the context contract — set the ceiling on what any RAG answer can be.