Skip to content
Hitting 400 param/schema errors or context limits? Switch protocols or 1M+ context models behind one key

OpenAI 400 invalid_json_schema: Strict Structured Outputs & Tool Schema Fixes ​

Key Takeaways

  • Exact error payload: 400 {"error":{"message":"Invalid schema for response_format '...': In context=(), 'additionalProperties' is required to be supplied and to be false.","type":"invalid_request_error","param":"response_format","code":"invalid_json_schema"}}.
  • Root causes: Passing raw JSON Schema or Pydantic .model_json_schema() to strict: true without setting "additionalProperties": false on every nested object, omitting optional fields from "required", using a top-level "type": "array", or using oneOf / unsupported constraint keywords.
  • 1-minute fix: Set "additionalProperties": false at the root and every nested object, list every key from properties inside required (express optional fields as ["string", "null"]), wrap top-level arrays in an object, or let openai.pydantic_function_tool() / zodResponseFormat() transform schemas automatically.

OpenAI's Structured Outputs (response_format on /v1/chat/completions, text.format on /v1/responses, and strict: true function tools) compile your JSON Schema into a constrained-decoding grammar. Because grammar compilation happens before token generation, any schema rule violation immediately returns HTTP 400 invalid_json_schema.

Exact Error Messages & What Each One Means ​

json
{
  "error": {
    "message": "Invalid schema for response_format 'invoice_extract': In context=(), 'additionalProperties' is required to be supplied and to be false.",
    "type": "invalid_request_error",
    "param": "response_format",
    "code": "invalid_json_schema"
  }
}

Look at the In context=(...) breadcrumb in error.message — it pinpoints the exact path inside your schema that failed validation:

Error message snippetWhy strict grammar rejected itFix
'additionalProperties' is required to be supplied and to be falseRoot object or a nested properties.address / $defs.Item object lacks "additionalProperties": falseRule 1
'required' is required to be supplied and to be an array including every key in properties. Missing: '...'One or more keys in properties were left out of required to make them optionalRule 2
Invalid schema ... root type must be 'object' / 'anyOf' is not permitted at top levelSchema root is "type": "array" or top-level "anyOf" instead of "type": "object"Rule 3
'oneOf' is not permitted / keyword not supported (pattern, minLength, $ref siblings)Unsupported JSON Schema draft keyword or un-normalized Pydantic/Zod schemaRule 4
Missing required parameter: 'text.format.name' (on /v1/responses)Used Chat Completions nested response_format.json_schema wrapper on /v1/responsesRule 5

Broken vs. Fixed Raw JSON Schema (Copy-Paste Diff) ​

Broken Schema (Triggers 3 Separate invalid_json_schema Errors) ​

  1. Root is "type": "array" instead of "object".
  2. Nested item object omits "additionalProperties": false.
  3. Optional field coupon_code is left out of "required".
json
{
  "type": "json_schema",
  "json_schema": {
    "name": "order_items",
    "strict": true,
    "schema": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "sku": { "type": "string" },
          "qty": { "type": "integer" },
          "coupon_code": { "type": "string" }
        },
        "required": ["sku", "qty"]
      }
    }
  }
}

Fixed Schema (Passes strict: true Validation) ​

json
{
  "type": "json_schema",
  "json_schema": {
    "name": "order_items",
    "strict": true,
    "schema": {
      "type": "object",
      "properties": {
        "items": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "sku": { "type": "string" },
              "qty": { "type": "integer" },
              "coupon_code": {
                "type": ["string", "null"],
                "description": "Promo code if present, otherwise null"
              }
            },
            "required": ["sku", "qty", "coupon_code"],
            "additionalProperties": false
          }
        }
      },
      "required": ["items"],
      "additionalProperties": false
    }
  }
}

Five Strict-Mode Rules to Know Cold ​

Rule 1: Every Object Must Set "additionalProperties": false ​

OpenAI's constrained decoder must know the closed set of keys at every object level. Adding "additionalProperties": false only at the root is not enough — every nested "type": "object" inside properties, items, anyOf, and $defs must explicitly include "additionalProperties": false. Also note that free-form dictionary maps ("additionalProperties": { "type": "string" }) are rejected under strict: true; model dynamic key-value pairs as an array of {"key": string, "value": string} objects instead.

Rule 2: Every Property Must Be in required (Use "null" for Optional Fields) ​

In standard JSON Schema, omitting a key from required makes it optional. In OpenAI strict: true, every key defined in properties must appear in required. To allow the model to omit a value, keep the key in required and union its type with "null":

json
"middle_name": {
  "type": ["string", "null"]
}

When referencing a nested $ref object that might be absent, wrap it with anyOf:

json
"shipping_address": {
  "anyOf": [
    { "$ref": "#/$defs/Address" },
    { "type": "null" }
  ]
}

Rule 3: Root Schema Must Be type: "object" (Never a Top-Level Array) ​

Both response_format and strict: true function parameters require "type": "object" at the root, and neither allows anyOf at the very top level. Always wrap lists or polymorphic unions inside a single root key such as {"items": [...]} or {"result": {"anyOf": [...]}}.

Rule 4: Avoid Unsupported Keywords and Raw .model_json_schema() ​

Even on current models like gpt-6.2-sol and gpt-6-luna, strict schemas enforce structural restrictions:

  • Use anyOf, never oneOf or allOf.
  • No sibling keywords next to $ref: an object containing "$ref": "#/$defs/Node" cannot simultaneously carry "description" or "default" on the same JSON object unless wrapped in anyOf.
  • Constraint keyword limits: older snapshots and some cross-provider gateways reject minLength, maxLength, pattern, minimum, maximum, or multipleOf, or fail if regex patterns use lookarounds ((?=...)). When targeting maximum portability or lower compilation latency on first request, keep value-range rules in field description prompts and validate business constraints in application code after parsing.

Rule 5: Chat Completions vs. Responses API Wrapper Shape ​

When migrating from retired gpt-5 / o3 models to /v1/responses, notice that json_schema moves from response_format.json_schema to text.format without the extra json_schema nesting key:

json
// /v1/responses body fragment
{
  "model": "gpt-6.2-sol",
  "input": "Extract invoice fields from: Total USD 420 due 2026-12-30",
  "max_output_tokens": 4096,
  "text": {
    "format": {
      "type": "json_schema",
      "name": "invoice_extract",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "amount": { "type": "number" },
          "due_date": { "type": ["string", "null"] }
        },
        "required": ["amount", "due_date"],
        "additionalProperties": false
      }
    }
  }
}

Also remember not to pass legacy max_tokens or temperature on gpt-6.2-sol — see OpenAI Unsupported parameter: max_tokens Fix.

Copy-Paste SDK Fixes: Python (Pydantic) & TypeScript (Zod) ​

Python + Pydantic v2 (Why .model_json_schema() Fails & How to Fix It) ​

Calling Invoice.model_json_schema() directly fails because Pydantic v2 omits additionalProperties: false and leaves fields with = None defaults out of required. Use the OpenAI SDK's built-in .parse() or pydantic_function_tool() helpers instead:

python
from typing import Optional
from pydantic import BaseModel, ConfigDict
from openai import OpenAI, pydantic_function_tool

client = OpenAI(
    api_key="sk-YOUR_TOKEN",
    base_url="https://byesu.com/v1",
)

class LineItem(BaseModel):
    model_config = ConfigDict(extra="forbid")
    sku: str
    quantity: int
    discount_code: Optional[str]  # Use Optional[str] without '= None' or let SDK normalize

class InvoiceExtract(BaseModel):
    model_config = ConfigDict(extra="forbid")
    vendor: str
    items: list[LineItem]
    notes: Optional[str]

# Option A: Chat Completions .parse() — auto-injects additionalProperties: false & full required
completion = client.beta.chat.completions.parse(
    model="gpt-6.2-sol",
    messages=[{"role": "user", "content": "Vendor: Acme Corp, 2x SKU-99, no discount."}],
    response_format=InvoiceExtract,
    max_completion_tokens=4096,
)
invoice: InvoiceExtract = completion.choices[0].message.parsed
print(invoice.model_dump())

# Option B: Strict function tool schema generator
strict_tool = pydantic_function_tool(InvoiceExtract, name="save_invoice")

Building full agent pipelines in Python? See our PydanticAI Integration Guide.

TypeScript + Zod (zodResponseFormat & .nullable()) ​

In Zod, .optional() (string | undefined) removes the key from required and triggers invalid_json_schema in strict mode! Always use .nullable() (string | null), or .nullish() paired with OpenAI's zodResponseFormat / zodTextFormat helper:

typescript
import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";

const client = new OpenAI({
  apiKey: process.env.BYESU_API_KEY,
  baseURL: "https://byesu.com/v1",
});

// Wrong in strict mode: z.string().optional() omits key from 'required'
// Right in strict mode: z.string().nullable() keeps key in 'required' with ["string", "null"]
const InvoiceSchema = z.object({
  vendor: z.string(),
  items: z.array(
    z.object({
      sku: z.string(),
      quantity: z.number().int(),
      discount_code: z.string().nullable(),
    })
  ),
  notes: z.string().nullable(),
});

const completion = await client.beta.chat.completions.parse({
  model: "gpt-6.2-sol",
  messages: [{ role: "user", content: "Vendor: Acme Corp, 2x SKU-99" }],
  response_format: zodResponseFormat(InvoiceSchema, "invoice_extract"),
  max_completion_tokens: 4096,
});

console.log(completion.choices[0].message.parsed);

Using Next.js generateObject / Output.object()? Check our Vercel AI SDK Setup Guide.

5-Second Gateway Diagnostic Test ​

Verify your endpoint connectivity and API key before testing complex schemas:

bash
curl -fsSL https://docs.byesu.com/setup/test.sh | sh
# Or pass your token directly:
curl -fsSL https://docs.byesu.com/setup/test.sh | bash -s -- sk-YOUR_TOKEN

FAQ ​

What causes OpenAI 400 code: "invalid_json_schema"? ​

When strict: true is enabled on response_format (Structured Outputs) or function tools, OpenAI compiles your JSON Schema into a context-free grammar before generation. Any object missing "additionalProperties": false, any property omitted from "required", a non-object root type, or unsupported JSON Schema keywords triggers HTTP 400 invalid_json_schema.

How do I mark a field optional in OpenAI Structured Outputs when every key must be in required? ​

Keep the field name inside the required array, and make its type nullable by specifying ["string", "null"] (or anyOf with {"type": "null"}). In Pydantic, declare Optional[str] with client.beta.chat.completions.parse / client.responses.parse; in Zod, use z.string().nullable() instead of z.string().optional().

Why does passing Pydantic MyModel.model_json_schema() directly fail with invalid_json_schema? ​

Pydantic's raw model_json_schema() omits additionalProperties: false by default and drops fields with default values from the required array. Pass the Pydantic class to client.beta.chat.completions.parse, client.responses.parse, or openai.pydantic_function_tool(MyModel), which recursively transforms the schema to satisfy OpenAI strict mode.

Can the root schema of OpenAI Structured Outputs be a JSON array? ​

No. The top-level schema must have "type": "object" (not "array" and not a root-level "anyOf"). Wrap your list inside a root object property, such as {"type": "object", "properties": {"items": {"type": "array", "items": {...}}}, "required": ["items"], "additionalProperties": false}.

How does the Responses API format differ from Chat Completions for json_schema? ​

Chat Completions nests the schema under response_format: {"type": "json_schema", "json_schema": {"name": "...", "strict": true, "schema": {...}}}. The Responses API flattens it into text: {"format": {"type": "json_schema", "name": "...", "strict": true, "schema": {...}}}.

Got a problem? Contact support or join our group.