entry
No. 20
date
filed under
structured outputs, debugging, tool use
checked against
8 sources

Invalid schema for response_format: Fix OpenAI Strict Schemas

OpenAI's API returns Invalid schema for response_format when a JSON Schema sent with strict: true breaks one of the rules of strict mode. The message names the rule and where it broke, for example In context=(), 'required' is required to be supplied and to be an array including every key in properties. Missing 'groupby'. Four rules cause almost all of these errors: every object needs additionalProperties: false, every key in properties must be listed in required, the root must be type: "object" and not an anyOf, and the schema may only use the keywords strict mode supports. Fix the schema at the path the message gives, and make optional fields nullable instead of leaving them out of required.

This post goes through each rule with the messages developers have reported, shows what the Python and Node SDK helpers do with Pydantic and Zod models, and gives a small checker you can run before a request. The SDK results below come from running openai-python 3.58.0 with Pydantic 2.14.4, and openai-node 7.63.0 with Zod 4.6.7, locally. No request was sent to the API, so the API's own messages are quoted from the docs and from reports on the OpenAI developer forum.

Where the error comes from

Structured Outputs constrains the model's output to your schema, but only a subset of JSON Schema. OpenAI's guide says: "If you turn on Structured Outputs by supplying strict: true and call the API with an unsupported JSON Schema, you will receive an error." The guide's Go example shows that error as an HTTP 400 with the code invalid_json_schema.

You can hit it in three places:

  • text.format with type: "json_schema" and strict: true on the Responses API.
  • response_format with type: "json_schema" on Chat Completions.
  • A function tool with strict: true. The function calling guide says strict mode "works by leveraging our structured outputs feature" and has the same requirements. On the Responses API, if you leave strict out, the API tries to normalize the schema into strict mode and falls back to non-strict calling if it can't. Chat Completions is non-strict by default.

Because it is a 400, retrying never helps. The schema has to change. If you want the background on when to use a response schema and when to use a tool, see structured outputs vs function calling.

Rule 1: additionalProperties must be false on every object

The guide says Structured Outputs "only supports generating specified keys / values, so we require developers to set additionalProperties: false to opt into Structured Outputs." That applies to every object in the schema, nested ones and $defs included, not only the root. A forum report shows the message for a nested object:

Invalid schema for response_format 'ModelComparisonResponse': In context=('properties', 'v1_approach'), 'additionalProperties' is required to be supplied and to be false.

context=() means the root. context=('properties', 'v1_approach') means the object at that property. That poster's error went away after upgrading the Python SDK to 1.68.2.

The harder case is a map. A field like dict[str, str] in Pydantic or z.record() in Zod becomes an object whose additionalProperties is a schema, not false, and no setting makes that strict. We ran a Pydantic model with a tags: dict[str, str] field through the Python SDK's converter, to_strict_json_schema, which is what responses.parse() uses. It added additionalProperties: false to every object that lacked it, but left tags as {"type": "object", "additionalProperties": {"type": "string"}}, because the code only fills the key in when it is missing. The same happens with model_config = ConfigDict(extra="allow"), which Pydantic turns into additionalProperties: true. The Node helper refuses the record before sending:

Object schema at `properties/tags` must set `additionalProperties: false` to be compatible with strict Structured Outputs.

The fix is to turn the map into a list of key and value pairs:

from pydantic import BaseModel


class Tag(BaseModel):
    key: str
    value: str


class Ticket(BaseModel):
    title: str
    tags: list[Tag]  # instead of dict[str, str]

If the keys are known in advance, list them as properties instead.

Rule 2: every key in properties must be in required

The guide's heading is blunt: all fields must be required. Leaving one out gives:

Invalid schema for response_format 'Vega-Lite': In context=(), 'required' is required to be supplied and to be an array including every key in properties. Missing 'groupby'

The guide's answer for optional fields is to "emulate an optional parameter by using a union type with null." The field stays in required, and the model writes null when it has nothing to put there:

{
  "type": "object",
  "properties": {
    "location": {"type": "string"},
    "unit": {"type": ["string", "null"], "enum": ["F", "C"]}
  },
  "required": ["location", "unit"],
  "additionalProperties": false
}

The Python SDK does this for you. A Pydantic field assignee: Optional[str] = None came out of to_strict_json_schema as anyOf string or null, with assignee added to required. The converter sets required to every key in properties on every object.

Zod is stricter. The Node helper zodTextFormat threw on a schema with .optional():

Schema field at `properties/assignee` uses `.optional()` without `.nullable()` which is not supported by the API.

Changing the field to z.string().nullable() produced "type": ["string", "null"] and listed assignee in required. Your code then has to treat null as "not given".

Rule 3: the root must be an object, not anyOf

The guide says "the root level object of a schema must be an object, and not use anyOf," and names Zod's discriminated unions as one pattern that produces a root anyOf. A root without "type": "object" gets this message, from another forum report:

Invalid schema for response_format 'Vega-Lite': schema must be a JSON Schema of 'type: "object"', got 'type: "None"'.

Both SDKs catch the union case before sending. In Node, a root z.discriminatedUnion made zodTextFormat throw Root schema must have type: 'object' but got type: undefined. In Python, passing Union[Ok, Err] as the format raised TypeError: Unsupported response_format type, since the helper only takes a Pydantic model or a dataclass.

The fix is to wrap the union in an object. anyOf is allowed below the root, as long as each branch follows the same rules:

from typing import Literal, Union

from pydantic import BaseModel


class Ok(BaseModel):
    status: Literal["ok"]
    value: str


class Err(BaseModel):
    status: Literal["error"]
    error: str


class Result(BaseModel):
    result: Union[Ok, Err]

Result converted to a schema with anyOf under properties.result, and each branch got additionalProperties: false and a full required list. The Zod equivalent, z.object({ result: z.discriminatedUnion(...) }), passed the Node helper too.

Rule 4: only supported keywords

The guide lists the supported types: string, number, boolean, integer, object, array, enum and anyOf. On top of the type, you can use these constraints:

  • Strings: pattern, and format with date-time, time, date, duration, email, hostname, ipv4, ipv6 or uuid.
  • Numbers: multipleOf, maximum, exclusiveMaximum, minimum, exclusiveMinimum.
  • Arrays: minItems, maxItems.

The guide marks these composition keywords as not yet supported: allOf, not, dependentRequired, dependentSchemas, if, then and else. Fine-tuned models have a longer list: no minLength, maxLength, pattern or format on strings, no minimum, maximum or multipleOf on numbers, no patternProperties, and no minItems or maxItems. If a schema works on a base model and fails on your fine-tune, check those first.

allOf often comes from a code generator rather than from you. The Python converter unwraps an allOf with a single entry but leaves longer ones in place. $defs and references are fine: the guide's own examples use $defs and a recursive "$ref": "#".

Azure OpenAI documents its own, older subset. Its structured outputs page, updated 2026-08-24, still lists pattern, format, minimum, maximum, minItems and maxItems among unsupported keywords and allows 100 object properties with five levels of nesting. A schema that works on OpenAI can fail on Azure, so check the page for the platform you call.

Rule 5: size limits

The limits in OpenAI's guide are:

  • Up to 5,000 object properties in total, with up to 10 levels of nesting.
  • Up to 120,000 characters across all property names, definition names, enum values and const values.
  • Up to 1,000 enum values across all enum properties. For one string enum with more than 250 values, those values may total 15,000 characters at most.

These were raised in July 2025, according to a forum post that relayed an OpenAI announcement (object properties from 100 to 5,000, enum values from 500 to 1,000), so older blog posts and answers quote smaller numbers. Generated schemas for large forms or long enum lists are the usual way to hit them. Split the job into several calls, or replace a huge enum with a string and validate it in code.

Check a schema before you send it

This function checks the first four rules on a plain JSON Schema dict. It is not a full validator: it doesn't measure size limits or nesting depth, and it only walks properties, items, anyOf and $defs. It does catch the mistakes above with a readable path:

UNSUPPORTED = {"allOf", "not", "dependentRequired", "dependentSchemas", "if", "then", "else"}


def check_strict_schema(schema: dict) -> list[str]:
    """Flag the strict-mode rules most often behind 'Invalid schema' errors."""
    problems: list[str] = []
    if schema.get("type") != "object" or "anyOf" in schema:
        problems.append("root: must be type 'object' and not anyOf")

    def walk(node, path: str) -> None:
        if not isinstance(node, dict):
            return
        for key in UNSUPPORTED & node.keys():
            problems.append(f"{path}: unsupported keyword '{key}'")
        props = node.get("properties")
        if node.get("type") == "object" or isinstance(props, dict):
            if node.get("additionalProperties") is not False:
                problems.append(f"{path}: additionalProperties must be false")
            missing = set(props or {}) - set(node.get("required", []))
            if missing:
                problems.append(f"{path}: missing from required: {sorted(missing)}")
        for name, sub in (props or {}).items():
            walk(sub, f"{path}/properties/{name}")
        for name, sub in node.get("$defs", {}).items():
            walk(sub, f"{path}/$defs/{name}")
        walk(node.get("items"), f"{path}/items")
        for i, sub in enumerate(node.get("anyOf", [])):
            walk(sub, f"{path}/anyOf/{i}")

    walk(schema, "#")
    return problems

On a hand-written schema with required: ["title"], an assignee field and an array of label objects with no additionalProperties, it printed:

['#: additionalProperties must be false', "#: missing from required: ['assignee', 'labels']", '#/properties/labels/items: additionalProperties must be false', "#/properties/labels/items: missing from required: ['name']"]

On the Pydantic Ticket with dict[str, str] it flagged only #/properties/tags, and after the change to list[Tag] it returned an empty list. For Pydantic models, run it on to_strict_json_schema(YourModel) from openai.lib._pydantic, which is what the SDK sends. That is a private module, so pin your SDK version if you rely on it in a test. A unit test that runs every schema your agent uses through a check like this catches the error in CI instead of in production, the same idea as the agent evals starter guide.

After the schema is accepted

A valid schema is the start. The guide says your application "still needs to handle refusals, incomplete responses, and API errors," and that the model "will always try to adhere to the provided schema, which can result in hallucinations" when the input has nothing to do with it. Give the schema a nullable field or a status enum for "not found". If an agent loops only when it has a structured output type, test that output on its own, as in MaxTurnsExceeded in the OpenAI Agents SDK. And when the schema is a tool's parameters, clear descriptions matter as much as validity; see why your agent calls the wrong tool.

Checklist

  • Read the context=(...) path in the message. () is the root.
  • Set additionalProperties: false on every object, nested and in $defs.
  • List every property in required. Make optional fields nullable.
  • Replace dict[str, X], z.record() and extra="allow" with explicit fields or a list of pairs.
  • Wrap a root union in an object.
  • Remove allOf, not, if, then, else and the dependent* keywords.
  • On fine-tuned models, also drop length, pattern, format, range and item-count keywords.
  • Check Azure's own subset if you call Azure OpenAI.
  • Run a schema check in CI.

FAQ

What does 'additionalProperties' is required to be supplied and to be false mean?

An object in your schema, at the path in context=(...), does not have "additionalProperties": false. Strict mode requires it on every object. If the object is a map, such as dict[str, str], rewrite it as a list of key and value objects.

How do I make a field optional in OpenAI structured outputs?

Keep it in required and allow null, for example "type": ["string", "null"]. In Pydantic, Optional[str] = None does this through the SDK. In Zod, use .nullable(), not .optional().

Why does my Zod discriminated union fail?

A discriminated union at the root becomes anyOf, and the root must be an object. Put the union inside a property of a z.object.

Are pattern and format supported?

On OpenAI, yes for base models: pattern, and format with the nine formats listed in the guide. Fine-tuned models don't support them, and Azure OpenAI's documentation lists them as unsupported.

Does retrying help with invalid_json_schema?

No. It is a 400 error about the request itself. Fix the schema, then send it again.

Sources

Stuck on a different message? The error index lists every agent error covered here, by tool.

Next in the notebook

  1. No. 2AI Agent Calling the Wrong Tool? 7 Causes and How to Fix Them

    A debugging checklist for tool-calling agents: overlapping tools, vague descriptions, ambiguous parameters, noisy output and bad errors, with a fix for each.

  2. No. 6Structured Outputs vs Function Calling: Which to Use When

    Structured outputs vs function calling: use tools when the model must act, a JSON schema when you need the answer in a fixed shape, and strict mode for both.

  3. No. 7Agent Infinite Loop: How to Debug Agents That Never Stop

    Why AI agents get stuck in infinite loops, and how to stop them: turn caps, token budgets, repeated-call detection, better tool errors and clear stop rules.