Practical guide · AI engineering

How to validate structured LLM outputs

Structured output solves a formatting problem. It can guarantee that a model returns the required keys and types, but it cannot prove that an identifier exists, a date is possible, a quotation appears in the source, or the user may perform the requested action. This guide separates those checks and turns them into one testable boundary.

Published November 24, 2026 · 13 minute read

The short answer

Constrain the response with the smallest schema that describes the application contract. Handle refusals, truncation and provider errors before parsing. Validate the parsed object again in application code, then check semantic rules, source evidence, current database state and authorization. Reject invented or contradictory values. Send only repairable errors back to the model, cap the attempts, and preserve failed cases as regression fixtures.

Schema-valid does not mean correct

OpenAI's structured output documentation says the boundary plainly: completed, non-refusal output can be constrained to a supported JSON Schema, while the application still has to handle refusals, incomplete responses, API errors and business rules the schema cannot express.

A schema can require customer_id to be a string. It cannot know whether that customer exists in the signed-in tenant. It can require an ISO-looking date. It cannot know whether the source document actually states that date. It can constrain a refund reason to an enum. It cannot decide whether the order is refundable now.

Four validation layers for structured LLM output
LayerQuestionOwner
TransportDid the request complete without refusal, truncation or API failure?Provider adapter
SchemaAre the required keys, types, enums and object boundaries valid?Runtime validator
SemanticDo values agree with one another, the evidence and current domain state?Application service
PolicyMay this user perform this exact action on this exact record now?Authorization and approval code

Use four validation layers

1. Check the response envelope

Inspect the provider's response status before reading the payload. Refusal and incomplete output are named outcomes, not malformed successes. Record which case occurred. Retry only when the failure is transient and the remaining deadline allows it.

2. Parse with the application schema

Anthropic's structured output guide documents constrained JSON output and strict tool inputs, along with a supported subset of JSON Schema. Provider support differs, so compile and test each schema against every model route you use. Run your own Pydantic, Zod, Sorbet or JSON Schema validator after receipt rather than treating successful generation as the only check.

3. Validate meaning against trusted state

Look up model-produced identifiers inside the authenticated tenant. Recalculate totals from line items. Confirm that a start date precedes an end date. Require quotations and extracted fields to point to the source span that supports them. The model may suggest a relationship, but deterministic code should verify it.

4. Apply policy at execution time

Authorization can change between generation and execution. Load the record again, check ownership and current state, then apply limits and approval policy. Never copy trusted tenant, user, price or permission fields from model output when the application already knows them.

Represent missing and uncertain values honestly

Required fields often make a model invent a value when the source is silent. Give the contract an honest escape path: nullable fields, a bounded unknown status, and an evidence list. Keep absence separate from a negative answer. A missing cancellation date means the date was not found; it does not mean the order was never cancelled.

{
  "customer_id": "cust_1842",
  "decision": "unknown",
  "amount_cents": null,
  "evidence": [
    { "source_id": "invoice_27", "quote": "Total pending review" }
  ],
  "missing_fields": ["amount_cents"],
  "next_action": "request_human_review"
}

Google's Gemini structured output documentation describes JSON Schema output for extraction, classification and agent workflows. The schema still needs field descriptions that distinguish observed values, inferred values and unknown values. Test those distinctions with source text that deliberately omits the answer.

Put business rules in code

Use the schema for local shape constraints and application code for rules that depend on other fields or live state. JSON Schema can express some conditional relationships. The JSON Schema conditional validation reference documents dependentRequired and if/then/else. Provider subsets may reject valid standard features, and a schema still cannot query your database.

  • Reject IDs that do not resolve in the tenant rather than asking the model to try another tenant.
  • Recalculate money, counts and derived statuses from trusted inputs.
  • Compare cited text with the normalized source span and reject unsupported quotations.
  • Check mutually dependent fields, such as approved requiring an approver and timestamp.
  • Use database constraints and transactions for invariants that must survive concurrent writes.

Check authorization after validation

A well-formed tool call is still an untrusted request. Resolve the actor from the authenticated session, the tenant from application context and the target from an authorized query. Compare the normalized action with any recorded approval. If the action, record, amount or destination changed, the old approval does not apply.

For state-changing operations, pair this boundary with the agent approval-gate workflow and the retry and idempotency guide. Validation prevents malformed or impossible requests. Approval and idempotency control who can execute them and what happens when delivery is uncertain.

Build a failure matrix

A happy-path fixture proves that the parser works. A useful suite attacks each boundary and asserts the application outcome, not only the generated object.

Failure cases for structured LLM output
CaseExpected outcome
Provider refusalNamed refusal state; no parse or write attempt.
Output truncatedIncomplete state; bounded retry or review.
Unsupported schema featureFail deployment preflight, not a user request.
Invented but well-formed IDSemantic rejection; no cross-tenant search.
Valid fields with contradictory datesBusiness-rule rejection with a precise error code.
Quote absent from sourceEvidence rejection and preserved trace.
Authorized record changes before executionFresh policy check fails closed.
Repair loop repeats the same errorAttempt cap reached; route to review.

Keep the original input, schema version, model route, response envelope, parsed object, validation errors and final state in the test artifact. Add reviewed production failures to the agent test-set workflow.

Structured output validation checklist

  • The response envelope distinguishes completion, refusal, truncation and API failure.
  • The application validates the parsed object with its own versioned schema.
  • Missing information has an explicit null, unknown or review path.
  • Identifiers resolve only inside trusted tenant and user context.
  • Cross-field rules, totals, dates and evidence are checked deterministically.
  • Authorization and approval are checked against fresh state immediately before execution.
  • Repair prompts receive precise validation errors and have a strict attempt limit.
  • Failure fixtures assert the final application state and external side effects.

Continue learning