Forward Deployed EngineeringAI EngineeringStructured Outputs
You need guaranteed JSON from the model, but it keeps breaking the schema. What do you do?
Question 49 of 73 · Updated
On this page
- Interview-ready answer
- 1. Separate syntax, structure and semantics
- 2. Choose the strongest supported generation mechanism
- Why constrained decoding helps
- 3. Define a clear schema
- 4. Validate at the application boundary
- 5. Tested Python: strict Pydantic validation
- 6. Bounded correction attempts and explicit failure
- Worked example
- Actual local tests
- 7. Streaming, truncation and refusals
- 8. Fallback and availability policy
- 9. Production trade-offs and observability
- 10. Realistic hypothetical customer scenario
- Likely interviewer follow-ups
- Interview takeaway
Interview-ready answer#
I would first separate three requirements: valid JSON syntax, conformance to a specific schema, and correctness of the values inside that schema. They require different controls.
If the provider and selected model support schema-constrained structured output, I would use that feature rather than relying on a prompt that says "return JSON." JSON mode usually addresses syntax, while structured output can additionally constrain the generated response to a supported schema. For a self-hosted model, grammar-constrained decoding can provide similar structural controls. I would verify the exact runtime's schema support, refusal behavior, truncation rules and completion guarantees.
Regardless of the generation method, I would validate the completed output at the application boundary using a strict parser, JSON Schema or a typed validator such as Pydantic, followed by semantic and authorization checks. A correctly typed invoice amount can still be the wrong amount. I would use authoritative evidence or deterministic computations to verify important values.
For recoverable invalid responses, I would allow a small number of correction attempts with sanitized feedback. I would distinguish provider refusals, truncated generations and transport failures from an ordinary schema violation. After the retry budget is exhausted, return a typed failure, use an approved fallback or route the case to a human reviewer. Never silently substitute invented business data to make the schema pass.
The guarantee I can offer at the application boundary is that every accepted successful response has been validated against the declared contract. I cannot guarantee that every model invocation returns a successful answer or that a structurally valid answer is factually correct.
1. Separate syntax, structure and semantics#
Consider a customer invoice-extraction workflow requiring three fields: status, cents and source_id. A successful extraction must reference an authorized source and match the amount actually present in the evidence. A missing result must have null amount and source.
| Failure category | Example | Detection |
|---|---|---|
| Invalid JSON | A missing closing brace or prose surrounding the object | Strict JSON parser |
| Valid JSON, wrong structure | Amount supplied as a string or a required field absent | JSON Schema or typed runtime validation |
| Valid schema, inconsistent fields | Status is missing but an amount is present | Cross-field business rules |
| Valid schema, unsupported fact | A nonnegative integer amount that disagrees with the cited invoice | Evidence verification |
| Incomplete generation | Token cap or disconnected stream before completion | Provider completion metadata and final parsing |
| Provider refusal | An explicit refusal rather than a successful structured payload | Provider-specific refusal handling |
| Unauthorized operation | Correctly formatted data proposed for a resource outside the user's scope | Independent application policy |
Valid JSON may be a scalar, array or object. A JSON parsing success alone does not establish the expected object shape. Similarly, a refusal must not be interpreted as a missing business fact.
The preceding tool-calling lesson covers durable execution, authorization and retry ambiguity. This lesson focuses on the generation and validation contract, before structured data is consumed or passed to a tool.
2. Choose the strongest supported generation mechanism#
| Mechanism | What it can provide | Remaining responsibilities |
|---|---|---|
| Prompt-only JSON instruction | Encourages a desired format | Parse, validate and handle frequent format errors |
| JSON mode | Valid JSON under the provider's documented successful-completion conditions | Validate object shape, schema, semantics and exceptional responses |
| Schema-constrained structured output | Conformance to the supported schema for successful, complete responses under the documented contract | Check supported schema subset, refusals, truncation, semantics and policy |
| Strict tool arguments | Structured arguments for a selected tool, where supported | Correct tool selection, host validation, authorization and execution |
| Self-hosted grammar-constrained decoding | Output restricted by a configured grammar or schema-to-grammar compiler | Verify compiler coverage, completion and semantic validity |
Provider terminology is not standardized. Do not assume that an option named JSON mode guarantees every required key, that a strict tool schema validates the final natural-language answer, or that every model supports the same schema features.
Historically, OpenAI has distinguished JSON mode from Structured Outputs, with schema adherence tied to supported models and schemas and to successful non-refusal completions. Exact parameter names, supported keywords and response envelopes depend on the API and model version. This article does not assert current 2026 provider compatibility; confirm the documented deployed contract before implementation.
Why constrained decoding helps#
At each generation step, a constrained decoder can maintain a parser or grammar state and allow only tokens whose continuation can lead to a valid output. For example, after an object key expecting an integer, the decoder disallows continuations that would violate the supported grammar. Closing delimiters and string escaping must be handled correctly, including tokens that span several characters.
A schema-to-grammar compiler may restrict the language to required properties, enumerations, nesting and supported types. Some engines support only a subset of JSON Schema, and some constraints are enforced later by validators rather than during generation. Tokenizer interactions, grammar compilation, impossible constraints and maximum generation length matter.
Constraints change the available token choices. They cannot independently tell the model which invoice is correct, whether a customer is eligible, or whether a claimed event happened. A grammar may ensure a number is emitted while the number remains wrong.
3. Define a clear schema#
A simplified extraction schema can distinguish an amount found in evidence from an explicitly missing amount.
JSON{ "type": "object", "additionalProperties": false, "required": ["status", "cents", "source_id"], "properties": { "status": {"type": "string", "enum": ["found", "missing"]}, "cents": { "anyOf": [ {"type": "integer", "minimum": 0, "maximum": 100000000}, {"type": "null"} ] }, "source_id": { "anyOf": [{"type": "string"}, {"type": "null"}] } } }
This schema describes the example application's structural contract, not a promise that any specific provider accepts these keywords. A provider with a narrower schema subset may require an adapted generation schema while the application retains its full validation contract.
Use integer minor units rather than floating-point currency in this example. The actual contract must specify currency, scale, applicability and domain bounds. Explicitly distinguish null from zero, and missing required properties from properties whose values may be null. Restrict unexpected fields when appropriate.
For a production schema:
- Keep fields well named and descriptions unambiguous.
- Prefer simple types, bounded collections and enumerations when suitable.
- Use explicit missing or uncertain states rather than forcing the model to invent a required value.
- Version schemas and test compatibility between generators, parsers and downstream consumers.
- Generate schemas from application types where practical, but inspect the generated schema and verify provider compatibility.
A schema can sometimes encode cross-field relationships using conditional constructs; the deployed generation engine may not support them. More importantly, relationships involving real external state cannot generally be verified by a static schema alone.
4. Validate at the application boundary#
Parse the final payload strictly, reject duplicate keys where ambiguity is unacceptable, enforce input-size and nesting/resource limits, and validate the expected schema. Avoid using string evaluation, regular expressions as a general JSON parser, or permissive coercion that hides contract violations.
After structural validation, perform semantic checks. In the invoice example, verify that the source exists in the authorized applicable evidence, the extracted amount matches the canonical integer amount, and the status is consistent with the returned fields.
A successful syntactic repair is not evidence that repaired values are correct. For example, appending a missing brace could make a truncated object parse while still omitting a crucial field. Do not "repair" a missing monetary amount by inserting zero.
5. Tested Python: strict Pydantic validation#
The example uses Pydantic v2, the standard-library JSON parser, and synthetic evidence supplied by trusted application code. It makes every field required, even where null is permitted.
PYTHONimport json from typing import Literal from pydantic import BaseModel, ConfigDict, Field, ValidationError class Extract(BaseModel): model_config = ConfigDict(strict=True, extra='forbid') status: Literal['found', 'missing'] cents: int | None = Field(ge=0, le=100_000_000) source_id: str | None def unique(pairs): obj = {} for k, v in pairs: if k in obj: raise ValueError('duplicate key') obj[k] = v return obj def reject_constant(value): raise ValueError('non-JSON constant') def validate(raw, evidence): if type(raw) is not str or len(raw.encode('utf-8')) > 4096: raise ValueError('invalid payload size') record = Extract.model_validate(json.loads(raw, object_pairs_hook=unique, parse_constant=reject_constant)) if record.status == 'missing': if record.cents is not None or record.source_id is not None: raise ValueError('inconsistent missing result') elif (record.cents is None or record.source_id is None or evidence.get(record.source_id) != record.cents): raise ValueError('unsupported amount') return record
The code expects an evidence mapping of authorized source IDs to validated integer cents. It is not a semantic verifier for arbitrary prose or complex financial documents. A source lookup match is meaningful only if the upstream evidence is authoritative, current, correctly scoped and actually represents the intended field. The example's missing state checks field consistency, not whether extraction was exhaustive or the amount is truly absent. Where completeness is required, validate that separately or label the result as unverified missing.
Pydantic strict validation rejects ordinary coercions such as a numeric string used as an integer. The custom object-pairs hook rejects duplicate keys; the parse-constant hook rejects nonstandard constants such as NaN and Infinity. The byte limit is illustrative. Production code must handle hostile resource usage, encodings, nesting, maximum list sizes and safe error reporting according to the actual data contract.
The schema can be inspected with Extract.model_json_schema(). A Pydantic model's generated schema is not automatically a provider-compatible constrained-generation schema, and schema validation semantics can differ from the application's runtime semantics. In particular, a JSON Schema integer can include a mathematically integral number such as 100.0, while this strict Python validator rejects a float representation. Align both boundaries and test them.
6. Bounded correction attempts and explicit failure#
If the model cannot satisfy the schema, first check whether the problem is caused by unsupported schema features, wrong API options, contradictory instructions, an insufficient output budget, or an incompatible model. Retrying will not solve a persistent configuration error.
For recoverable output errors, send short, sanitized feedback describing the violated contract. Keep the original task and trusted evidence intact. Do not include arbitrary raw error text or tool content as privileged instructions. Use an overall deadline, a small attempt limit and a token/cost budget.
The following function uses a normalized provider adapter. The adapter returns a trusted completion status and a raw response. A refusal is terminal, and truncated, timed-out or other non-complete responses become unavailable in this deliberately conservative example.
PYTHONdef extract(generate, evidence, max_attempts=3): if type(max_attempts) is not int or not 1 <= max_attempts <= 3: raise ValueError('invalid attempt limit') feedback = None for _ in range(max_attempts): status, raw = generate(feedback) if status == 'refusal': return 'refused', None if status != 'complete': return 'unavailable', None try: return 'ok', validate(raw, evidence) except (ValueError, RecursionError): feedback = 'Return the required schema with source-supported values.' return 'invalid', None
The generate callback is assumed to implement the provider-specific adapter and convert known provider or transport outcomes into the declared status. Unexpected callback exceptions propagate; production orchestration must classify exceptions and enforce deadlines separately. The function does not perform model inference or invoke any side-effecting tool.
Only an ok result contains a validated Extract instance. The other statuses are application-defined failure outcomes, not fabricated successful extraction records.
Worked example#
PYTHONevidence = {'A': 100, 'B': 0} assert validate( '{"status":"found","cents":100,"source_id":"A"}', evidence ).cents == 100 # These would fail: wrong amount, numeric string, unknown source, # duplicate JSON keys, or a "missing" result with a non-null amount.
Actual local tests#
Python 3.13.5 and Pydantic 2.13.5 executed the two implementations in a local synthetic test harness. The tests were:
- 300 combinations of status, amount and source ID, independently classified from the declared type, enum and evidence rules.
- 11 additional malformed or contract-violating payloads, including duplicate keys, extra fields, missing keys, nonstandard constants, fenced output, oversized input and trailing JSON.
- 155 ordered completion sequences covering one through three attempts, with valid, invalid, refused, truncated and timeout outcomes. An independent expected-outcome rule checked call counts, terminal states, feedback and whether a validated object was returned.
- Four invalid attempt-limit cases.
All 470 checks passed (311 validation checks and 159 recovery-policy checks). The local tests do not establish actual model schema adherence, provider guarantees, streaming behavior or real-world extraction quality. No hosted model or customer data was used.
The validator's work is proportional to the bounded payload size for this simple schema, assuming ordinary parser and hash-table behavior; the recovery helper performs at most three generation attempts. Real latency and cost are dominated by generation and evidence acquisition, not this small object validator.
7. Streaming, truncation and refusals#
A partial JSON fragment is not generally a valid completed document. Buffer streamed deltas according to the API's message or tool-call correlation protocol; enforce size and time limits while accumulating. If the product needs a live preview, label it provisional and never commit it as an accepted structured record before completion and validation.
Some providers or parsers support incremental structured data. Incremental parsing still does not imply that cross-field semantics, complete collection coverage or final completion conditions are satisfied.
Inspect the actual completion indicators before trusting the payload. A length-limited response might coincidentally parse while omitting requested array elements. Do not consider that an exhaustive result. If truncation is a recoverable sizing problem, the outer orchestration may increase a supported output limit within budget, simplify the schema, or split a large task into independently validated pieces. This is a deliberate new attempt, not a way to treat incomplete output as complete.
A refusal is a separate outcome. Do not try to force the model to satisfy a prohibited request by repeatedly asking for the same content as JSON. An authorized fallback should respect the same safety and data-handling requirements.
8. Fallback and availability policy#
If structured generation is unavailable for the chosen model, choose a compatible model or grammar-constrained runtime, or use prompt-based generation with strict validation and bounded correction attempts. Avoid silently downgrading to accepting unvalidated responses.
For deterministic fields, prefer deriving the value from an authoritative record rather than asking the model to reconstruct it. For long lists, paginate or process bounded chunks with explicit coverage tracking. For uncertain extraction, route to a qualified reviewer when required.
A useful service interface distinguishes transport success from business success. For example, it can return a validated result envelope or a typed error envelope. Deterministically serializing that application envelope can guarantee valid JSON for responses produced by the application; network failures can still prevent a response from reaching the client. It does not guarantee the model always produces valid business data.
For mutations, no downstream tool should execute based on partial or invalid output. Use the authorization and idempotency controls from FDE-0043 independently of the schema.
9. Production trade-offs and observability#
| Strategy | Benefit | Cost or risk |
|---|---|---|
| Native structured output | Fewer format failures on supported configurations | Provider/model restrictions, schema-subset compatibility |
| Local grammar constraints | Runtime control over structural language | Grammar compilation and decoding overhead, integration maintenance |
| Strict application validation | Clear trust boundary and deterministic rejection | Schema upkeep and semantic-check development |
| Bounded correction | Recovers some formatting or evidence-selection errors | Extra model calls, tail latency and potential repeated mistakes |
| Human review or deterministic fallback | Handles unresolved or consequential cases | Review capacity, delay or limited automation |
Constraint overhead varies across engines, tokenizers and schemas; benchmark the actual configuration. Do not assume that structured output necessarily improves or worsens latency. Compare first-pass acceptance, final acceptance, semantic accuracy and end-to-end task completion.
Track invalid JSON rate, schema failure categories, semantic validation failures, refusals, truncation, retries, exhausted attempts, validation latency and cost per accepted correct result. Segment by model version, schema version, task and output length. Avoid logging sensitive raw responses unnecessarily.
For a customer workflow, test representative legitimate inputs, missing evidence, adversarial document text, invalid types, unexpected fields, duplicate keys, deeply nested or oversized inputs, partial streams and output-budget exhaustion. Measure both structural adherence and correctness against source evidence. Fault-injection tests should include transport errors and provider refusals, and downstream consumers should never receive an accepted result when validation fails.
10. Realistic hypothetical customer scenario#
A finance team needs to extract invoice amounts into a typed workflow. Prompt-only JSON initially produces occasional prose, numeric strings and incorrect values. I would first move to the strongest compatible structured-generation option, define a simple versioned schema with an explicit missing state, and retain strict Pydantic and evidence validation.
A response containing 100 cents in the correct JSON shape is rejected if the referenced invoice does not contain that amount. If the model chooses an incorrect source, a bounded correction attempt can ask it to use the supplied evidence. If the output is still invalid or the evidence is incomplete, return a typed failure or review request rather than writing a guessed value into the finance system.
The acceptance criteria would include no unvalidated payload entering the consumer, measured field accuracy and evidence support on a held-out dataset, appropriate handling of missing invoices, latency and review workload. This is an illustrative architecture, not a reported customer deployment.
Likely interviewer follow-ups#
Does JSON mode guarantee a schema? Not necessarily. JSON syntax and schema conformance are separate. Use the provider's documented structured-output mechanism where available and validate independently.
Does constrained decoding guarantee factual correctness? No. It restricts allowed output structures. It does not verify the facts chosen within them.
Can I parse the first valid JSON object from a stream? Not as a general success criterion. Wait for the relevant completion signal and validate the whole expected payload, including required coverage.
Why not fix every invalid response with another LLM? Additional calls add latency and cost and can change meaning or invent facts. Bound correction attempts, preserve evidence and verify the final result.
What if a supported schema has an impossible business requirement? Clarify the contract, include a legitimate unavailable or missing state, or change the workflow. Do not force arbitrary values just to satisfy required fields.
Should I trust a Pydantic model after validation? Trust its specific validated constraints, not untested semantic properties, provenance, authorization or completeness.
Interview takeaway#
Use schema-constrained generation to reduce structural failures, deterministic parsing and typed validation to enforce the application boundary, and independent semantic checks to verify important values. Treat refusal, truncation and unavailable evidence as explicit outcomes. Make successful structured responses reliable without claiming that every model invocation succeeds or that JSON guarantees truth.
References
- 1.
- 2.JSON Schema — Understanding JSON Schema (not live-verified)json-schema.org
- 3.OpenAI — Structured Outputs (not live-verified)platform.openai.com
- 4.Pydantic — Strict Mode (not live-verified)docs.pydantic.dev
- 5.Pydantic — JSON Schema (not live-verified)docs.pydantic.dev
- 6.Python — json (not live-verified)docs.python.org
- 7.
Related questions
- Design a customer-support agent with order-status and returns tools. How do you keep it safe and useful?
- Estimate the capacity and cost of an app with 50k DAU making 10 LLM calls each. What do you provision for?
- A customer wants the model to 'know our docs.' Prompting, RAG, or fine-tuning: how do you choose?
Explore other topics:AI AgentsAI System DesignLarge Language Models