OpenAI Structured Outputs Guide: JSON Schema and Pydantic

OpenAI Structured Outputs guarantees that the model’s response matches a JSON schema you define — not just valid JSON, but schema-valid JSON with exactly the fields and types you specified. Before structured outputs, developers used JSON mode (syntactically valid JSON but without schema enforcement) or function calling workarounds that produced inconsistent results. Structured outputs with strict mode achieves 100% schema compliance in OpenAI’s evaluations and is now the recommended approach for any application that parses model output programmatically.

JSON Mode vs Structured Outputs: The Key Difference

JSON mode (response_format: {type: “json_object”}) instructs the model to return valid JSON but does not enforce a schema — the model decides what fields to include, and any field might be missing, mistyped, or named differently than you expect. Structured outputs (response_format: {type: “json_schema”, json_schema: {…}}) constrain the model’s token generation at the decoding level: it cannot produce output that violates the schema. The result is guaranteed schema-valid output on every request. JSON mode is effectively deprecated for schema-bound use cases — use structured outputs instead.

Defining the Schema

The json_schema object in the response_format contains the name, a strict flag set to true, and a schema object following JSON Schema conventions with OpenAI-specific constraints. OpenAI’s strict mode supports a subset of JSON Schema: object and array types, string/number/integer/boolean/null primitives, enum values, required fields (all fields must be listed in required), and additionalProperties set to false. What it does not support: $ref references, anyOf with more than two options, pattern constraints on strings, and some advanced JSON Schema keywords. If your schema uses unsupported features, the request fails or falls back to non-strict mode — test your schema before deploying to production.

Figure 1 — Structured outputs vs alternatives

Approach Valid JSON? Enforces your schema? Prompt “return JSON”UsuallyNo — fields and types may vary JSON modeAlwaysNo — schema not enforced Structured outputsAlwaysYes — 100% schema compliance

Using Structured Outputs with the Python SDK

The OpenAI Python SDK (v1.40+) provides a parse() method that accepts a Pydantic model as the schema, handles the JSON schema generation automatically, and returns a parsed Python object rather than a JSON string. Define your response schema as a Pydantic BaseModel class with typed fields and optional Field descriptions. Call client.beta.chat.completions.parse() with your model, messages, and response_format=YourPydanticModel. The parsed attribute of the response message contains your Pydantic model instance with fully typed fields. This is cleaner than writing raw JSON schema and eliminates the json.loads() parsing step and validation code from your application.

Using Structured Outputs Without Pydantic

For applications not using Pydantic, pass the raw JSON schema directly as the json_schema value in the response_format parameter. Set strict to true and provide your schema as a standard JSON Schema object under the schema key. The response content is a JSON string you parse with json.loads(). All fields declared in the schema are guaranteed to be present with the correct types, so you can access them without additional validation checks. One important constraint: set additionalProperties to false at every nesting level in the schema — OpenAI’s strict mode requires this, and the request will fail or fall back to non-strict if it is missing.

Handling Refusals

Structured outputs introduces a refusal mechanism — when the model cannot or will not generate a response matching the schema (for example, a safety refusal on harmful content), it returns a refusal field instead of parsed content. Check for refusals before accessing the parsed response: if message.refusal is not None, the model declined and the message.parsed field is null. Handle refusals gracefully in production code — logging them separately from schema validation errors and surfacing appropriate user-facing messages rather than crashing on a null parse.

Structured Outputs for Function Calling

Structured outputs also applies to function calling (tool use). Set strict: true in the function definition alongside the parameters JSON schema, and the model’s function call arguments are guaranteed to match the schema. This eliminates the need to validate or sanitise function arguments before passing them to your function — the model cannot produce invalid argument structure. Combine strict function calling with structured outputs for the final response when your pipeline includes both tool calls and a structured final answer: the entire output path from model to application code is type-safe.

Frequently Asked Questions

Does structured outputs work with all OpenAI models?
Structured outputs with strict mode is supported on GPT-4o and GPT-4o-mini series and later models. It is not supported on older models (GPT-3.5, GPT-4, GPT-4-turbo). Check platform.openai.com for the current supported model list.
Does structured outputs work with streaming?
Yes. You can stream structured output responses and accumulate the JSON incrementally. The SDK’s stream_and_parse() helper handles partial JSON accumulation during streaming and delivers the complete parsed object when the stream completes.
What happens if my schema has unsupported features?
The request either fails with an error or falls back to non-strict mode depending on the feature. Test your schema independently by sending a minimal test request and checking whether the response uses strict mode. Simplify your schema — remove $ref, replace complex anyOf with simpler union types — until strict mode activates successfully.

Last updated: October 2026. Check developers.openai.com for the current supported JSON Schema subset and model compatibility list.

Structured Outputs Across Providers

OpenAI’s structured outputs implementation is the most mature, but Anthropic and Google Gemini both offer similar capabilities. Anthropic’s Claude API supports structured output through the response format parameter (specifying JSON schema in the API request), achieving reliable schema-valid output. Gemini supports a response_mime_type of application/json with a response_schema in the generation config. If you are building a multi-provider application or want to use Ollama locally, note that not all local models support strict schema-constrained decoding — Ollama’s format parameter enforces basic JSON structure but does not support arbitrary schema enforcement as reliably as OpenAI’s strict mode. For local inference, use a validation library like Pydantic to post-process the LLM output and retry on schema violations, since the model cannot be constrained at the decoding level the same way cloud providers implement it.

Common Schema Design Patterns

Several schema patterns appear repeatedly in production structured output applications. The classification schema: a single field of enum type listing all valid categories, combined with a confidence field of type number — the model returns exactly one category and a score. The extraction schema: an object with fields for each data point to extract, with required set for mandatory fields and the field type reflecting the expected data (number for amounts, string for names, a nested object for complex sub-structures). The list-of-items schema: an array of objects at the top level, each with a consistent structure — useful for extracting multiple entities from a document in one pass. The multi-output schema: an object with fields for different output types in a single call (classification AND summary AND extracted fields) — more efficient than multiple separate API calls when you need several things from the same input.

Structured outputs represent the shift from hoping LLMs return parseable data to knowing they will. The difference in production reliability between JSON mode and strict structured outputs is substantial — JSON mode might work 95% of the time, leaving 5% of requests that need error handling and retry logic, while structured outputs closes that gap to essentially zero for schema compliance failures. For any application where model output feeds downstream code, databases, or APIs, structured outputs should be the default choice. The schema design discipline it requires — being explicit about every field, type, and required status — is also a forcing function that improves API design clarity, since the schema documents exactly what your application expects from the model in a machine-readable form that can be version-controlled alongside your code.

Testing and Versioning Your Schemas

A schema is part of your application contract, so treat it like code. Keep each schema in version control next to the prompt that uses it, and write a small test suite that sends a handful of representative inputs through the real API and asserts that the parsed result has the fields and types you expect. Strict mode guarantees the shape of the output, but it cannot guarantee the content is correct, so your tests should also check values: a total that should be positive, a date that should fall within a plausible range, a category that should match a known label.

When you change a schema, remember that downstream code, databases, and dashboards may depend on the old field names. Add new fields as optional first, deploy the consumers, and only then make them required. Pin the model snapshot you tested against rather than using a floating alias, because a model update can shift borderline outputs even when the schema stays valid. Log the schema version alongside each response so that when a bad record appears in your data months later, you can trace exactly which schema and prompt produced it. This discipline costs very little and prevents the slow data-quality drift that catches teams who treat structured outputs as a set-and-forget feature.

Leave a Comment