Reliable structured output begins before the model generates its first token. This guide shows how to design JSON Schema contracts, validate LLM responses, recover from failures, and decide when partial results need human review. Use the checklists when you add an extraction task, change a response shape, switch providers, or troubleshoot an existing pipeline.
Overview
LLMs generate text; your application needs data. A structured-output workflow creates a contract between those two layers. The contract defines what fields may appear, which values are allowed, what is required, and how the application should respond when the model cannot produce a valid result.
A JSON object that merely looks correct is not enough for production. It may contain a missing field, an unexpected key, a number represented as text, an invalid enum value, or a nested object in the wrong shape. These failures can break downstream code or, more subtly, create records that appear complete but are semantically wrong.
The most dependable design separates four responsibilities:
- Generation: the prompt and model produce a candidate response.
- Structural enforcement: the API or application encourages or constrains the response to follow a schema, where supported.
- Validation: your code parses the response and checks the schema and business rules.
- Recovery: the system retries, repairs, queues, or escalates failures instead of silently accepting them.
Provider support for structured-output modes, schema keywords, SDK behavior, and refusal or error formats can vary. Treat the schema as an application contract, then test the exact model and integration path you plan to use. For broader release planning, compare this workflow with the AI Feature Launch Checklist.
Checklist by scenario
Scenario 1: Extracting fields from unstructured text
Examples include invoices, support tickets, resumes, contracts, and product feedback. Begin by defining the business decision the extracted data will support. That keeps the schema focused and helps you distinguish a missing value from a value that was not present in the source.
- List the smallest set of fields the next system actually needs.
- Mark each field as required, optional, or conditionally required.
- Use explicit types: string, number, integer, boolean, array, or object.
- Use enums for controlled categories such as
"urgent","normal", and"low". - Define how the model represents an unknown value:
null, an empty array, or an omitted optional field. - Preserve evidence when the result may need auditing, such as a source span or page reference.
- Validate semantic constraints separately from JSON Schema, such as a date range or a score between zero and one.
Do not force the model to invent a value merely because a property is required. A required field can still have a nullable type if the source may legitimately lack the information. Your application can then route that record for completion or review.
Scenario 2: Returning a nested response for an application feature
Nested objects are useful for responses such as a classification result with evidence, confidence, and recommended actions. They are also a common source of validation failures because one incorrect child object can invalidate the entire response.
- Give every nested object a clear purpose and stable property names.
- Keep arrays homogeneous unless there is a strong reason to support mixed item types.
- Set limits for arrays where excessive items create cost, latency, or interface problems.
- Specify whether an empty list is valid and how it differs from an unavailable result.
- Keep presentation text separate from machine-readable values.
- Version breaking changes rather than changing a live contract without notice.
A practical schema might resemble this simplified contract:
{
"type": "object",
"properties": {
"label": { "type": "string", "enum": ["bug", "question", "feedback"] },
"priority": { "type": "string", "enum": ["low", "normal", "urgent"] },
"summary": { "type": "string" },
"evidence": { "type": "array", "items": { "type": "string" } }
},
"required": ["label", "priority", "summary", "evidence"],
"additionalProperties": false
}
The exact keywords accepted by an LLM provider may be narrower than the full JSON Schema specification. Confirm supported features in your integration and retain a local validator as the final gate.
Scenario 3: Calling another tool or service
Tool arguments should be treated as untrusted input, even when they conform structurally. A valid-looking destination, query, account identifier, or filter can still be unsafe or unauthorized.
- Constrain arguments with types, enums, formats, and sensible length limits.
- Normalize values before execution, but do not silently change their meaning.
- Check authorization and resource ownership outside the model.
- Use an allowlist for operations the model may request.
- Require confirmation for irreversible or high-impact actions.
- Log the validated arguments and execution result without exposing sensitive data unnecessarily.
For a deeper treatment of tool-specific retries and safe execution, see the LLM Tool Calling Tutorial.
Scenario 4: Retrying or recovering after validation failure
First classify the failure. A transport error, malformed JSON, schema mismatch, policy refusal, and low-confidence extraction require different responses.
- Retry transient API or network failures with bounded backoff.
- For malformed output, retry with the original input and a concise description of the failed condition.
- For a repeated schema failure, inspect the schema and prompt instead of retrying indefinitely.
- Use a repair step only when it can operate on the original response and preserve uncertainty.
- Return partial results only when each field has an explicit status such as
confirmed,missing, orneeds_review. - Send unresolved cases to a queue or human reviewer with the source text and validation errors attached.
What to double-check
Schema design
Read the schema as an API consumer, not only as a model instruction. Are names unambiguous? Does a required field truly need to exist for every input? Are numbers measured in a defined unit? Can a date be partial, approximate, or unknown? Does an enum include an explicit fallback such as unknown when classification is uncertain?
Decide how strict to be with additional properties. Rejecting unknown keys protects a stable contract, while allowing them can help during experimentation. Whichever choice you make, test it deliberately and avoid relying on undocumented provider behavior.
Validation layers
Use at least two layers of validation:
- Parsing validation: confirm the response is valid JSON and has the expected top-level type.
- Schema validation: check required properties, types, arrays, enums, and nested objects with a standard validator.
- Business validation: check rules such as permitted account IDs, numeric ranges, cross-field dependencies, and source-grounded claims.
For example, a schema can require a start_date and end_date, but application logic still needs to verify that the end is not earlier than the start. Likewise, a schema can require a confidence number without proving that the number reflects a calibrated probability.
Prompts and test cases
Prompt wording should explain the task, input boundaries, definitions, and uncertainty behavior. It should not be the only enforcement mechanism. Maintain representative fixtures that include clean inputs, missing fields, conflicting evidence, long inputs, unusual characters, and adversarial instructions embedded in source text.
Track invalid-output rate, field-level accuracy, missing-value behavior, retry rate, latency, and review rate. A response can pass schema validation while still extracting the wrong value. The LLM Evaluation Framework for Developers provides a useful structure for organizing these tests. Keep prompt and schema changes versioned together; the Prompt Versioning and Change Management workflow covers that operational concern.
Common mistakes
- Using a prompt instead of validation: Instructions improve consistency but do not replace parsing, schema checks, or business rules.
- Making everything required: This encourages invented values when the source is incomplete. Model uncertainty explicitly.
- Accepting strings for every value: Stringly typed data pushes ambiguity into every downstream consumer.
- Repairing without preserving the original: Keep the raw response, validation error, and repaired result for debugging and review.
- Retrying forever: Set a maximum attempt count and a clear fallback path.
- Ignoring refusals and truncation: These may not be ordinary JSON errors and should have distinct handling.
- Changing schemas in place: A renamed field can break stored records, dashboards, and consumers even if new responses validate.
- Trusting model-generated URLs, IDs, or commands: Validate them against application-owned data and permissions before use.
- Testing only happy paths: Extraction systems fail at boundaries, including empty inputs, ambiguous wording, and conflicting instructions.
When to revisit
Revisit this checklist whenever the underlying contract or workflow changes. That includes adding an extraction field, changing an enum, introducing nested objects, modifying the prompt, changing the model, switching providers, or upgrading an SDK. Provider capabilities and restrictions can change, so re-test the exact structured-output mode rather than assuming portability.
Also review the implementation before seasonal planning cycles or other periods when input volume, document formats, staffing, or review capacity may change. Examine recent validation failures and manually sample accepted outputs. A low retry rate does not prove correctness if the validator is too permissive.
Before shipping a schema change, use this final action list:
- Write the intended contract in plain language.
- Update the schema, prompt, parser, and business validators together.
- Run fixture tests for valid, missing, ambiguous, oversized, and adversarial inputs.
- Compare field-level quality with the previous version.
- Confirm retry limits, logging, privacy handling, and human-review routing.
- Version the change and document migration behavior for stored responses.
- Monitor validation failures and review outcomes after release.
Structured output works best as a controlled application workflow, not as a formatting trick. Define a narrow contract, validate every boundary, preserve uncertainty, and make failure recovery explicit. Those habits make LLM features easier to test, operate, and change as your tools and requirements evolve.