OpenAI Strict JSON Schema & Structured Outputs
OpenAI Structured Outputs ("strict": true) rejects many completely valid Draft-07 and 2020-12 JSON Schemas because constrained decoding compiles your schema into a deterministic token-level grammar.
You can lint any response or tool schema across OpenAI, Gemini, and Claude—and apply one-click strict auto-fixes—using the Seoffix Structured Output & Strict JSON Schema Validator.
JSON Mode vs. Strict Structured Outputs: What Changed?
Legacy JSON Mode ({"type": "json_object"}) only guaranteed that model output parsed as syntactically valid JSON, leaving missing keys, hallucinated field names, and wrong types to break downstream code.
Structured Outputs with "strict": true converts your JSON Schema into a context-free grammar (CFG) mask applied directly over logits during token generation.
Because invalid tokens are masked to zero probability before sampling, schema adherence reaches 100%—provided your schema obeys every grammar-compilation constraint.
The 6 Rules That Trigger OpenAI 400 invalid_json_schema Errors
When an API request fails with Invalid schema for response_format or Invalid schema for function, inspect these six structural rules first.
1. Every Object Node Must Declare additionalProperties: false
Setting "additionalProperties": false only on the root object is the single most common bug when migrating Pydantic, Zod, or hand-written schemas.
Every nested object—inside properties, array items, $defs, and anyOf branches—must explicitly include "additionalProperties": false so the grammar knows no arbitrary keys can follow.
2. Every Declared Property Must Appear in required[]
In standard JSON Schema, omitting a field from required marks it optional. In OpenAI strict mode, omitting any key from required raises an immediate HTTP 400 error.
To represent an optional field under strict mode, list the key inside required and allow null in its type union: "type": ["string", "null"].
3. Root Schema Must Be an Object (Not a Bare Array or Scalar)
Top-level schemas passed to json_schema must begin with "type": "object" (or an object-Typed anyOf); wrap top-level lists inside a single container key such as {"items": [...]}.
4. Unsupported Validation Keywords Must Move to Descriptions or Code
Grammar compilation cannot enforce arbitrary numeric multiples or unanchored regex lookarounds efficiently without exploding state-machine memory.
Keywords frequently rejected or restricted in strict grammar compilers include patternProperties, unevaluatedProperties, minProperties, maxProperties, and complex dynamic conditionals (if / then / else).
5. AllOf Composition & Unresolved External $ref Pointers
External HTTP $ref URLs are never fetched by model APIs at inference time; local #/$defs/NodeName pointers work, provided a $ref node does not mix sibling keywords unmerged.
6. Total Property Count, Enum Size, and Nesting Depth Caps
Large enterprise schemas hit hard grammar-compilation ceilings when a single schema exceeds roughly 100 total object properties, 5 levels of deep object nesting, or hundreds of verbose enum strings.
Before & After: Fixing a Failing Schema for Strict Mode
Compare a standard Draft-07 extraction schema (which fails strict mode in three places) against its normalized, strict-compliant equivalent:
// FAILS OpenAI strict: true (3 errors: missing root & nested additionalProperties,
// and "discount_code" omitted from required[])
{
"type": "object",
"properties": {
"invoice_id": { "type": "string" },
"discount_code": { "type": "string" },
"customer": {
"type": "object",
"properties": {
"email": { "type": "string" }
},
"required": ["email"]
}
},
"required": ["invoice_id", "customer"]
}
Applying strict-mode normalization closes both object nodes and converts discount_code into a required nullable union:
// PASSES OpenAI strict: true, Gemini JSON Schema, and Claude input_schema
{
"type": "object",
"additionalProperties": false,
"properties": {
"invoice_id": { "type": "string" },
"discount_code": {
"type": ["string", "null"],
"description": "Promo code applied to invoice, or null if none."
},
"customer": {
"type": "object",
"additionalProperties": false,
"properties": {
"email": { "type": "string" }
},
"required": ["email"]
}
},
"required": ["invoice_id", "discount_code", "customer"]
} Cross-Provider Schema Differences: OpenAI vs. Gemini vs. Claude
Multi-model routers and MCP servers often pass the exact same tool schema to OpenAI, Google Gemini, and Anthropic Claude—only to hit provider-specific edge cases.
| Schema Feature | OpenAI (strict: true) |
Google Gemini (responseSchema / JSON Schema) |
Anthropic Claude (Tool input_schema) |
|---|---|---|---|
additionalProperties: false |
Mandatory on every object | Rejected in legacy OpenAPI subset; supported in JSON Schema field | Supported (recommended for strict tool inputs) |
All keys in required[] |
Mandatory (use ["T", "null"] for optional) |
Optional keys allowed; propertyOrdering recommended |
Optional keys allowed natively |
$schema URI header |
Ignored or stripped | Causes 400 error in legacy OpenAPI responseSchema |
Supported / ignored |
Recursive #/$defs |
Supported on simple closed trees | Limited recursion depth; flatten cyclic ASTs | Supported in JSON Schema; keep shallow for reliability |
anyOf / Union Types |
Supported (each object branch must also be strict) | Supported in JSON Schema mode; avoid mixed scalar/object unions in legacy mode | Supported |
When building cross-client MCP servers, validate your server configuration in the MCP Config Validator and test every tool's inputSchema in the Structured Output Validator so one schema works across all three providers.
Handling Model Refusals & Streaming Partial Structured JSON
Even with 100% grammar-enforced decoding, two runtime cases can still return a response without a parsed schema object if your application forgets to check for them:
- Safety Refusals: When a user prompt triggers a safety refusal, OpenAI populates
message.refusalinstead ofmessage.content; always check for refusal before callingJSON.parse(). finish_reason: "length"Truncation: Ifmax_completion_tokensruns out mid-object, the stream terminates early with incomplete JSON; reserve generous output headroom using our LLM Context Window Calculator.
Pydantic, Zod, and Discriminated Unions in Strict Mode
Most production Python and TypeScript teams generate JSON Schemas programmatically from Pydantic models or Zod schemas rather than maintaining raw JSON by hand.
Even with official SDK helpers (zodResponseFormat or pydantic_function_tool), three subtle modeling patterns regularly trip strict-mode validation when exported across services:
- Default Values on Fields: Standard Pydantic omits fields with defaults from
required[]; strict converters strip defaults or move them intodescriptionwhile keeping every key required. - Discriminated Unions via
anyOf: Model polymorphic actions using an explicit"type": "string", "enum": ["search_action"]discriminator inside each closed object branch. - Dictionary Maps (
Record): Because arbitrary dynamic keys requireadditionalPropertiesto remain open, replace open maps with an array of{"key": "...", "value": "..."}entry objects.
// Strict-safe replacement for dynamic Record metadata maps
{
"type": "object",
"additionalProperties": false,
"properties": {
"attributes": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"name": { "type": "string" },
"value": { "type": "string" }
},
"required": ["name", "value"]
}
}
},
"required": ["attributes"]
} Field Ordering & Chain-of-Thought Reasoning Keys
Because autoregressive models emit JSON tokens sequentially from top to bottom, property order inside your schema directly shapes output accuracy.
Placing a short reasoning_summary or evidence_span string property before a boolean verdict or classification enum lets the model ground its reasoning prior to committing to the label.
Conversely, placing the classification enum first forces the model to guess on token one and rationalize backward inside later explanation fields.
Frequently Asked Questions on Strict Structured Outputs
Why does OpenAI reject optional properties unless they allow null?
Strict grammar compilation enforces a fixed sequence of keys per object so the model cannot skip fields unpredictably; unioning with "null" preserves explicit optionality safely.
Can I enforce regex patterns or email formats inside strict schemas?
Support for pattern and format varies by model snapshot and provider; enforce critical format checks in deterministic post-parse application validators as defense in depth.
How do I validate schemas locally before burning API credits?
Run every generated schema through the browser-local Seoffix Structured Output Schema Validator during development to catch violations in zero milliseconds.
Reducing Schema Token Overhead & First-Request Compile Latency
OpenAI caches compiled context-free grammars after the first request for a given schema fingerprint, which explains why the initial call to a brand-new schema takes 2 to 8 extra seconds.
However, every property name, enum literal, and verbose description inside your schema still counts toward prompt input tokens on every turn.
- Keep Key Names Concise & Self-Documenting: Prefer clear keys like
due_date_isoover 40-word explanatory descriptions that repeat obvious types. - Split Mega-Tools Into Focused Tools: Instead of one 90-property swiss-army tool schema, expose 3–5 small single-purpose tools with shallow schemas.
- Compress Input Context Separately: Keep output schemas strict JSON for your parser, while compressing large tabular input arrays with our JSON to TOON Converter to cut input token costs by up to 45%.
Auto-Fix Failing Schemas for Strict Mode in One Click
Paste your JSON Schema, Pydantic export, or MCP tool definition into the Structured Output & Strict JSON Schema Validator to inspect OpenAI, Gemini, and Claude errors side by side and copy a strict-ready schema instantly.