Structured LLM Outputs: JSON Schema and Semantic Validation
Validate structured LLM outputs beyond JSON syntax with evidence checks, domain rules, refusal handling, bounded retries, and explicit action boundaries.
Abhishek Raj · · 8 min read
Prepared with AI research assistance. Sources are linked throughout; worked examples are illustrative unless stated otherwise. Editorial approach.
Structured LLM outputs solve an interface problem: an application needs predictable fields rather than prose it must interpret. They do not establish that the extracted facts are true, that two fields agree, or that an action is authorized. A useful design separates those responsibilities instead of treating successful JSON parsing as the end of validation.
This guide develops a hypothetical maintenance-scheduling extractor. Its proposed contracts, failure policies, and examples are illustrative engineering choices, not a tested integration or a claim about a deployed service.
Separate four different acceptance questions
Consider a message asking a building-management assistant to arrange a repair. The extraction pipeline should answer four questions in order:
| Layer | Question | Example failure |
|---|---|---|
| Response envelope | Did generation finish in an expected state? | Refusal or truncated response |
| Syntax and schema | Does the result have the agreed structure? | Missing field or wrong type |
| Evidence and semantics | Do the values match the message and each other? | End time precedes start time |
| Execution authority | May this actor schedule this work now? | Site belongs to another customer |
A failure at one layer should not be relabeled as another. An authorization rejection is not an invitation to regenerate a different site identifier. A refusal is not a malformed appointment. Keeping these distinctions visible produces better recovery decisions and more useful operational metrics.
The extraction result should be a proposal that application code checks. If it will eventually drive a tool, keep the tool's independent authorization and current-state checks. See agent tool contracts for that execution boundary.
Design a contract that can express missing information
A schema should describe the information the application actually needs. Required fields can prevent accidental omissions, but making every business fact a mandatory nonempty value can encourage unsupported guesses. Give the contract an explicit representation for unavailable evidence.
For the proposed scheduler, separate an extracted fact from its verification state. A nullable preferred time can mean the message did not provide enough information; it should not silently mean “any time is acceptable.” Distinguish absence, an explicit customer preference, and a value supplied by a deterministic business default.
JSON Schema does not make listed properties required automatically, and additional properties are allowed unless constrained. Declare required and the intended additional-property behavior deliberately. JSON Schema object reference.
An illustrative local application contract could include:
{
"type": "object",
"properties": {
"site_id": {"type": ["string", "null"]},
"window_start": {"type": ["string", "null"]},
"window_end": {"type": ["string", "null"]},
"issue_code": {"enum": ["heating", "water", "electrical", "unknown"]},
"missing_fields": {"type": "array", "items": {"type": "string"}}
},
"required": ["site_id", "window_start", "window_end", "issue_code", "missing_fields"],
"additionalProperties": false
}
This is deliberately a small example, not a complete provider request. A production application also needs source references, a contract version, and rules restricting the values in missing_fields. Check the selected provider's supported schema subset before sending a richer application schema to its generation endpoint.
Keep machine-controlled identifiers outside model ownership. The server should attach the authenticated tenant, run identifier, source-document version, and authorization context. Asking the model to reproduce these fields adds opportunities for accidental substitution without adding useful reasoning.
Validate meanings that types cannot establish
A timestamp-shaped string may represent the wrong day. A valid site identifier may identify a different building. Two individually valid dates may create an impossible interval. Those conditions require checks against domain rules and source evidence.
Even familiar schema keywords need attention. JSON Schema's format is normally an annotation; validators can offer assertion behavior, and implementations may differ in which formats they enforce. Do not assume that adding format: "date-time" guarantees your runtime rejects an invalid timestamp. JSON Schema format behavior.
For the proposed scheduler, use a semantic-validation stage that:
- Parses both interval boundaries with an explicit timezone policy.
- Checks that the start precedes the end and that the duration is allowed.
- Resolves the site identifier against the authenticated customer's accessible sites.
- Verifies that the issue classification is supported by cited message text.
- Detects contradictions between populated fields and
missing_fields.
Separate reproducible checks from judgments. Interval arithmetic is code. Determining whether “the radiators never warm up” supports a heating issue can involve language interpretation, but the original passage should remain available for review.
Validation libraries can organize these checks. Pydantic supports custom field and model validators, allowing constraints on individual values and relationships across a model. That capability is useful plumbing; the application still defines which relationships are valid. Pydantic validator documentation.
Inspect completion state before decoding the payload
Treat the model provider's response envelope as its own interface. A successful HTTP response does not necessarily contain a completed extraction. Check the documented completion status, refusal indication, and expected content type before passing text into the business parser.
For a concrete provider example, Anthropic documents refusal responses that can use HTTP 200 and take precedence over the requested schema. It also documents token-limit responses that can leave structured output incomplete. Its structured-output feature supports a constrained schema subset rather than every JSON Schema feature. Claude structured-output documentation.
Keep provider-specific handling in an adapter. The rest of the scheduler should receive normalized outcomes such as completed, refused, incomplete, or unavailable, with the original provider status retained for diagnosis. Do not force a refusal into a fabricated business object just to satisfy the next function's signature.
If streaming, a partial object is progress information rather than an accepted record. Displaying a tentative field can be useful, but execution should wait for completed generation and validation. A field seen early in the stream can be corrected or contradicted later.
Walk through a hypothetical scheduling ambiguity
Suppose a customer writes: “The heating at the annex is broken. Please send someone next Tuesday afternoon.” The authenticated account has two sites with “annex” in their names. The message's receipt timestamp and customer timezone are available to the application.
The extractor proposes an issue code of heating, leaves site_id null, and records the site ambiguity. It may extract a date preference relative to the supplied reference timestamp, but “afternoon” remains a preference rather than a precise appointment interval. The application should not transform that phrase into an accepted booking without a documented product rule and customer confirmation where required.
Now suppose the first result instead contains the identifier of one annex and a 13:00–17:00 interval. Structural validation passes. Semantic validation finds that the supporting message does not identify which annex, and the time range was inferred without an applicable default. The correct next step is clarification, not a retry asking the model to choose more confidently.
After clarification, the system extracts the exact site and preferred window. Before booking, the action service checks current availability and the actor's authority. A valid extraction from five minutes earlier does not prove that the slot remains open. This final check belongs at the mutation boundary.
Store the accepted extraction with the source version and validation results. If the customer edits the request, invalidate conclusions that depended on the previous text instead of reusing an apparently clean object.
Make retries depend on the failure class
A retry policy should improve information or recover a transient condition. Repeating the same request without changing either can consume budget while concealing the real problem.
| Failure | Proposed next step |
|---|---|
| Unsupported schema rejected before generation | Fix the integration contract |
| Output truncated | Retry within budget with a suitable output allowance or smaller task |
| Missing source fact | Ask for clarification or return an incomplete extraction |
| Cross-field inconsistency | Provide bounded validation feedback and preserve original evidence |
| Authorization rejection | Stop the action or obtain legitimate authorization |
| Provider unavailable | Apply a documented transient-failure policy |
Repair feedback should identify the violated condition, such as window_end must follow window_start, rather than expose internal stack traces. Preserve the original source and prior attempt for diagnosis. Never let repair instructions broaden permissions or invent facts needed to make a validator pass.
Bound attempts by task deadline and resource budget. The broader failure classification is discussed in agent retries and timeouts.
Measure accepted correctness rather than parse rate alone
Build fixtures that separate structural success from factual success: valid-looking nonexistent sites, reversed intervals, ambiguous local times, conflicting source passages, explicit unknowns, refusals, truncation, and stale source versions. Include examples where the correct outcome is clarification.
For each fixture, define the expected accepted fields, missing facts, evidence references, and permitted next action. Check that invalid records never enter the booking service. Measure both false acceptance and unnecessary rejection; a pipeline that refuses every request can appear safe while providing no useful service.
Track parse success, schema success, semantic acceptance, clarification rate, final task outcome, and retry cost separately. These measurements reveal whether a schema change actually improves the workflow or merely makes its JSON easier to consume.
Frequently asked questions
Does constrained generation remove the need for application validation?
No. It can reduce formatting and structural failures within the provider's supported contract. Evidence matching, business relationships, authorization, and current-state checks remain application responsibilities.
Should invalid fields be silently coerced?
Use only explicitly documented normalizations with preserved provenance. Trimming harmless whitespace differs from changing a date, choosing a site, or substituting an enum value that alters the customer's intent.
Should the model return a confidence score?
Only if the product has a defined use for it and evaluates its behavior. A self-reported score does not establish that evidence exists. Missing-fact indicators and source references are often more actionable for deciding whether to clarify.
Source reference list
Related reading
- AI Agent Tool Design: Schemas, Contracts, and Error Semantics
Design reliable AI agent tools with precise schemas, bounded permissions, structured results, and error contracts that handle retries and uncertain outcomes.
- AI Agent Retries and Timeouts: Deadlines, Jitter, and Retry Budgets
Design AI agent retries around end-to-end deadlines, classified failures, jitter, shared budgets, and cancellation without multiplying unsafe side effects.
- Document Processing with AI Agents: Extraction and Reconciliation
Design document-processing agents that preserve field provenance, reconcile records, handle OCR uncertainty, and route meaningful exceptions for review.