The provider says the output is guaranteed. Why did my parse still throw, and why does the same schema 400 on the other provider?
Curated. Written from research and curation. Not run in our harness yet.
The job
We hear this from teams who just switched on structured outputs. The provider says the response is guaranteed to match the schema, the first hundred calls agree, and then a parse throws for no clear reason. Or the same schema that works on one provider comes back as a 400 from another. The fault is usually not in the model. It is in the subset of JSON Schema each vendor accepts, in the refusal and truncation paths that the guarantee does not cover, and in the grammar engine that compiled a keyword it silently ignores.
This recipe covers constraining a single model call to a declared schema: on hosted frontier APIs, and on self-hosted inference servers we run ourselves.
The approach
Send the schema to the model API and let the provider constrain sampling at the sampler, before a violating token can be emitted.
- OpenAI:
text.formatwithtype: "json_schema"andstrict: trueon the Responses API, orstrict: trueon a function definition. - Anthropic:
output_config.formatwithtype: "json_schema"on/v1/messages, orstrict: trueon a tool definition. - Google:
responseSchemaon the Gemini API.
Author the schema once as a typed object (Pydantic BaseModel, Zod z.object), cut it to the intersection of the three vendor subsets, and let each SDK derive the provider format rather than hand-rolling the conversion. When we own the server instead of calling a hosted API, we run a grammar engine: llguidance directly, or XGrammar and llguidance through vLLM and SGLang. On either path we validate the response in our own process before use, and we branch on refusal and truncation before we parse. The constraint removes most schema violations. It does not remove the checks.
Alternatives and why not. Client-side validate-and-retry (Instructor, BAML) is strictly worse wherever native constrained decoding exists: the first attempt can still fail, the retry costs tokens and latency, and it shares the same failure mode. We keep it for OpenAI-compatible shims with no native constraint, for semantic checks no schema can express, and for one schema across a multi-provider fleet. A grammar engine at the inference server does not apply at all to a hosted frontier model, and the self-hosted path is where the silent under-enforcement lives. Guidance, lm-format-enforcer and jsonformer are stale on release dates or are no longer named among the current vLLM backends.
What you need
| Component | Version | Licence | Link |
|---|---|---|---|
| OpenAI Structured Outputs | n/a (API feature) | proprietary, per OpenAI terms | https://platform.openai.com/docs/guides/structured-outputs |
| OpenAI function calling, strict mode | n/a (API feature) | proprietary, per OpenAI terms | https://developers.openai.com/api/docs/guides/function-calling |
Anthropic Structured outputs (output_config.format) | n/a (API feature, GA) | proprietary, per Anthropic terms | https://platform.claude.com/docs/en/build-with-claude/structured-outputs |
Anthropic Strict tool use (strict: true) | n/a (API feature) | proprietary, per Anthropic terms | https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use |
| Google Gemini Structured outputs | n/a (API feature) | proprietary, per Google terms | https://ai.google.dev/gemini-api/docs/structured-output |
| Pydantic (Python) | 2.14.1 | MIT | https://github.com/pydantic/pydantic |
| Zod (TypeScript) | 4.6.7 | MIT | https://github.com/colinhacks/zod |
| jsonschema (Python validator) | 4.26.0 | MIT | https://github.com/python-jsonschema/jsonschema |
| Ajv (JavaScript validator) | 8.20.0 | MIT | https://github.com/ajv-validator/ajv |
| JSON Schema specification | unconfirmed (current published draft not stated on the page fetched) | n/a | https://json-schema.org/ |
| Instructor (Python) | 1.17.0 | MIT | https://github.com/567-labs/instructor |
| Instructor docs | n/a (docs) | n/a | https://python.useinstructor.com/ |
| BAML | 0.226.2 (PyPI baml-py and npm @boundaryml/baml) | unconfirmed: PyPI license field is null, GitHub API reports Apache-2.0, npm reports MIT | https://github.com/BoundaryML/baml |
| BAML docs | n/a (docs) | n/a | https://docs.boundaryml.com/home |
| Outlines | 1.3.3 | Apache-2.0 | https://github.com/dottxt-ai/outlines |
| Outlines docs | n/a (docs) | n/a | https://dottxt-ai.github.io/outlines/latest/ |
| Guidance | 0.3.1 on PyPI, 0.3.2 GitHub release | MIT | https://github.com/guidance-ai/guidance |
| lm-format-enforcer | 0.11.3 | MIT | https://github.com/noamgat/lm-format-enforcer |
| jsonformer | 0.12.0 | unconfirmed (PyPI exposes no licence field) | https://github.com/1rgs/jsonformer |
| llguidance | 1.9.1 | MIT | https://github.com/guidance-ai/llguidance |
| XGrammar | 0.2.8 | Apache-2.0 | https://github.com/mlc-ai/xgrammar |
| XGrammar docs | n/a (docs) | n/a | https://xgrammar.mlc.ai/docs/ |
| vLLM | 0.31.0 | Apache-2.0 | https://github.com/vllm-project/vllm |
| vLLM structured outputs docs | n/a (docs) | n/a | https://docs.vllm.ai/en/latest/features/structured_outputs.html |
| SGLang | 0.5.21 | Apache-2.0 | https://github.com/sgl-project/sglang |
| SGLang structured outputs docs | n/a (docs) | n/a | https://docs.sglang.ai/advanced_features/structured_outputs.html |
Named and deliberately not used: the hosted Dottxt API (advertised on the Outlines landing page, no canonical URL confirmed). LangChain structured output helpers, Genkit, PydanticAI and the vendor agent SDKs are wrappers over the components above and do not carry the guarantee themselves.
Steps
- Write the schema as a typed object in your language, not a raw JSON blob. Pydantic
BaseModelin Python,z.objectin TypeScript. Keep it in one file that both the request path and the test path import, so the same definition derives the provider schema and validates the response.
- Cut the schema to the intersection subset of the three vendor schemas before writing provider code. Check by name:
additionalPropertieshandling, whether every field must berequired, whether a root-levelanyOfis allowed, whichformatstrings are supported, and whetherminimum/maximum/minLength/maxLengthsurvive. Move an unsupported constraint into the fielddescriptionrather than deleting it. Anthropic'stransform_schema()does this move and accepts a Pydantic model.
- Make every field required and express optionality as a union with
null. OpenAI requires all fields or function parameters to be listed asrequiredand emulates an optional parameter with a union type withnull. This is the single schema decision most likely to turn a working schema into a 400.
- Wrap any discriminated union in an object so the root is an object. OpenAI states the root level must be an object and must not use
anyOf, and names the ZoddiscriminatedUnionpattern as the thing that produces a root-levelanyOf.
- Budget the schema against the published hardness limits before shipping. OpenAI: up to 5000 object properties total, up to 10 levels of nesting, total string length across property names, definition names, enum values and const values not exceeding 120,000 characters, up to 1000 enum values across all enum properties, and a single string enum with more than 250 values capped at 15,000 characters of enum value text. Anthropic: 24 total optional parameters and 16 parameters with union types across all strict schemas in one request, with unions expensive because they create exponential compilation cost. Exceeding the internal limits returns a 400 reading "Schema is too complex for compilation". If we are near a limit, we split the extraction into two calls rather than trimming fields that matter.
- Send the schema with the provider's native strict flag and use the SDK helper. OpenAI Responses API:
text: { format: { type: "json_schema", name: ..., strict: true, schema: ... } }, orclient.responses.parse(..., text_format=Model)in Python andopenai.responses.parse({ text: { format: zodTextFormat(S, "name") } })in JavaScript. Anthropic:output_config.formatwithtype: "json_schema", ormessages.parse(..., output_config={"format": zodOutputFormat(S)}). Google:responseSchemaor the SDK schema parameter with Pydantic or Zod. Do not hand-roll the conversion, but read what the SDK produced the first time, because a bad conversion is a silent schema change.
- Warm the schema at deploy time and keep it stable. Both vendors charge a grammar compilation cost on first use. Anthropic documents extra first-request latency, caching of compiled grammars for 24 hours from last use, and invalidation when the JSON schema structure changes or when the set of tools in the request changes. Changing only a field
nameordescriptiondoes not invalidate the cache. Issue one throwaway request per schema on each deploy, and do not generate schema names or descriptions per request from user data.
- If the model is self-hosted, pick the engine and turn it on explicitly. SGLang defaults to XGrammar and switches with
--grammar-backend outlinesor--grammar-backend llguidance, and only one ofjson_schema,regexorebnfmay be set per request. vLLM supports xgrammar or guidance as backends. vLLM removed the old fields in v0.12.0:guided_json,guided_regex,guided_choice,guided_grammar,guided_whitespace_patternandstructural_tagare gone, replaced by astructured_outputsobject withjson,regex,choice,grammar,whitespace_patternandstructural_tag, orStructuredOutputsParams(...)in Python. Removeguided_decoding_backendfrom the request entirely.
- State the format in the prompt as well. This is not redundant with the grammar, and SGLang's docs say it outright: include explicit instructions describing the desired format for better output quality. The grammar stops invalid tokens. It does not tell the model which valid values are the right ones.
- Handle refusal before you parse. OpenAI returns a content item of type
refusalthat we must branch on, and lists refusal and hitting the token limit as the cases where the response does not match the schema. Anthropic returns HTTP 200 withstop_reason: "refusal", bills the tokens, and states the output may not match the schema because the refusal message takes precedence over schema constraints. Atry/exceptaroundjson.loadsis the wrong shape: the payload parses fine and is simply not our object.
- Handle truncation before you parse. Check the stop reason or completion reason against the token limit. Constrained decoding produces prefix-valid output, so a truncated response is a syntactically broken JSON document that fails in a way that looks like a provider bug.
- Validate anyway, with the same type you authored. Refusal and truncation mean the guarantee has holes even on a GA provider. Validate with Pydantic, jsonschema or Ajv. It costs microseconds and is the difference between a bad row and a bad agent.
- Define the fallback once, at the call site. One retry with a different temperature or a repaired prompt, then a typed failure the caller handles. Never let a constrained call fail open into free text, because downstream code that assumed a schema will do something worse than throw.
- Keep reasoning out of the schema. Anthropic documents that a property asking for the model's thinking or step-by-step reasoning may produce a
reasoning_extractionrefusal, and recommends asking for a short explanation instead. Where thinking is enabled, the grammar applies only to Claude's direct output, not to tool calls, tool results or thinking tags, and grammar state resets between sections. Take reasoning from the thinking blocks, not from a schema field.
- Test the schema against the engine, not against your reading of the spec. Write one conformance test per schema construct you used, run it against each provider and each self-hosted engine you deploy, and assert on the failure as well as the success. An engine that compiles the schema and quietly ignores a keyword passes a test that only checks "does it accept a valid object".
Traps
- Assuming JSON Schema is JSON Schema. The three vendors support different subsets and the differences sit exactly where agents author: OpenAI requires
additionalProperties: falseon every object, requires every field to berequired, and forbids a root-levelanyOf; Anthropic supports a documented subset and rejects unsupported constraints at SDK validation time. Agents make this mistake because the schema is written before the provider is chosen. Fix: author to the intersection, then transform per provider, using Anthropic'stransform_schema()and reading the transformed schema the first time.
- Trusting a grammar engine to enforce a keyword it silently ignores. This is the worst trap because it fails silently and the agent ships. XGrammar open issues filed against 0.2.7 include
patternandformatwithminLength/maxLengthignored (issue 966), an unknown string format compiling and then accepting arbitrary strings (967),contains,minContainsandmaxContainsnot enforced (968), and value schemas OR-ed where JSON Schema says AND (964, 965). Agents make this mistake because a compiling schema looks like an enforced schema. Fix: validate the output in our own process with jsonschema or Ajv, and treat every construct we rely on as untested until a conformance test fails when the engine ignores it.
- Treating the response as always schema-shaped. Both frontier vendors document the exceptions: OpenAI refusal or max token limit, Anthropic HTTP 200 with
stop_reason: "refusal", billed tokens, and output that may not match the schema. Agents make this mistake because the docs say "guaranteed" and the first hundred calls agree. Fix: branch on refusal and stop reason before parsing, and keep post-validation on a GA provider.
- Writing a parser instead of checking a stop reason. A truncated constrained response is prefix-valid JSON, so it fails to parse in a way that reads like a provider or library bug, and agents debug the wrong layer for a day. Fix: check truncation first, parse second.
- Root-level
anyOffrom a discriminated union. Zod'sdiscriminatedUnionis the common source and OpenAI's docs call the pattern out by name as not working. Fix: wrap it in an object with a single field.
- Optional fields authored as optional. Pydantic's
Optional[str]and TypeScript's?are the natural way to write it and the wrong way to send it. Fix: emit"required"listing all fields, and encode optionality as a union withnull.
- Schema complexity blowing the grammar budget. Anthropic returns a 400 reading "Schema is too complex for compilation" when union types, optional parameters and nested objects interact; OpenAI caps at 5000 properties, 10 nesting levels and 1000 enum values. Agents make this mistake by generating schemas programmatically from a database or a class hierarchy and never measuring them. Fix: count unions and optional parameters explicitly before sending, and split the call when near a limit.
- Paying the grammar compilation cost on every request. Anthropic caches compiled grammars for 24 hours from last use and invalidates on schema structure change or tool set change. Agents that build schema
nameanddescriptionstrings from user input change the cache key every call and silently pay first-request latency forever. Fix: static schema identity, warm at deploy.
- Using JSON mode and calling it structured output.
json_objectguarantees valid JSON, not adherence to our schema, and agents pick it because it looks like the same parameter. Fix: usejson_schemawithstrict: true.
- Reasoning inside the schema. A
reasoningorchain_of_thoughtstring field is the instinct, and Anthropic documents it may trigger areasoning_extractionrefusal. Fix: keep reasoning in the thinking blocks, and ask for a short explanation field only when we need it.
- Assuming the server applied the constraint. vLLM issue 57726 is structured outputs not applied on
/v1/completionswhen--reasoning-parseris configured, and issue 59608 is structured output skipping the<tool_call>that ends reasoning. Both return unconstrained output from a request that asked for constrained output. Fix: validate in-process, and pin and upgrade the server deliberately.
- Reaching the wrong object through an OpenAI-compatible shim. The Groq plus Instructor Stack Overflow question (79576484) is the shape: a valid response model, a
tool_use_failederror, and function call output that looks correct. Shims implement subsets of the strict-mode contract. Fix: treat structured output as unverified behind an OpenAI-compatiblebase_urluntil we have a smoke test per provider.
- Adopting a stale library because it was right two years ago. Guidance is 0.3.1 on PyPI from 2026-02-03 with the repo last pushed 2026-05-21; lm-format-enforcer is 0.11.3 from 2025-08-24 and is no longer named among the vLLM backends; jsonformer has not shipped since 2023-05-08. Fix: check the last release date before adopting. The successor to Guidance is llguidance.
- Not reading what the SDK put on the wire. Pydantic-to-JSON-Schema conversion has produced schemas nobody intended, including
Fieldmetadata producing an invalid schema and dictionary-bearing models converting wrongly. Fix: log the derived schema once per schema version and assert on it in a test.
Scope
Covers: constraining a single model call's output to a declared schema, on hosted frontier APIs and on self-hosted inference servers. The two provider-native surfaces, JSON outputs and strict schemas on tool inputs. The three layers: provider constrained decoding, client-side validate-and-retry, and a grammar engine at the inference server. Schema authoring in a typed object and conversion to each provider format. The published hardness limits. The refusal and truncation paths. Cache and compilation behaviour of compiled grammars. The validation step that survives on a GA feature. Conformance testing of a schema against a specific engine.
Does not cover: correctness, since a schema-valid extraction can still be factually wrong and nothing here makes the model right. Retrieval, context assembly and prompting for accuracy. Multi-step agent loops and state. Evaluation of output quality, which covers whether the schema is enforced and not whether the extraction is good. Streaming partial objects as a user-facing concern, though Outlines and BAML both offer type-safe streaming. Fine-tuning to improve schema adherence, and the OpenAI docs note some type-specific keywords are not supported for fine-tuned models. Non-JSON output shapes, since regex, EBNF and context-free grammars are named only as the escape hatch the self-hosted engines accept. The security of the schema itself, including the OWASP ASI06 memory poisoning defence requested in Instructor issue 2316, which belongs to agent memory security. A hosted structured-output service as a component (the Dottxt API, named without a canonical URL). Cost modelling, since token overhead, retry cost and compilation cost are described qualitatively and not measured.
Sources
Tool and specification pages are linked in the table above. The evidence cited in the traps:
- XGrammar issues 964, 965, 966, 967, 968 (filed against 0.2.7): https://github.com/mlc-ai/xgrammar
- vLLM issues 57726 and 59608: https://github.com/vllm-project/vllm
- Instructor issue 2316: https://github.com/567-labs/instructor
- Groq plus Instructor Stack Overflow question 79576484: https://stackoverflow.com/questions/79576484
- SGLang structured outputs docs, for the prompt-format note and the
--grammar-backendflag: https://docs.sglang.ai/advanced_features/structured_outputs.html - vLLM structured outputs docs, for the v0.12.0 field removal: https://docs.vllm.ai/en/latest/features/structured_outputs.html
- Anthropic structured outputs docs, for
transform_schema(), cache behaviour and the complexity limits: https://platform.claude.com/docs/en/build-with-claude/structured-outputs - OpenAI structured outputs docs, for the strict-mode schema rules and the hardness limits: https://platform.openai.com/docs/guides/structured-outputs
- Google Gemini structured outputs docs: https://ai.google.dev/gemini-api/docs/structured-output
- JSON Schema specification: https://json-schema.org/
Versions, licences and dates were read on 2026-10-14 from PyPI, the npm registry, the GitHub API and vendor documentation. Nothing in this recipe has been run end to end by us, so it carries no tested mark.
Rules and labels: How we choose · machine form: /recipes/constrain-structured-output.json · all recipes