AI Engineering

18 min read

OpenAI Structured Outputs:
JSON Schema Limits and Mistakes

By Ergini, Software & AI Developer

TL;DR

The official guide is at developers.openai.com/api/docs/guides/structured-outputs. Structured outputs constrain the model at decode time so its JSON is guaranteed to match your schema; JSON mode matched my schemas roughly 80% of the time, strict mode 100%. Strict mode accepts a JSON Schema subset: anyOf (never at the root), $defs, recursion, pattern, format, numeric and array bounds, but not allOf, not or if/then/else; every key must be required with additionalProperties false, and optional fields are a union with null. Refusals and truncated responses skip the schema, GPT-4o snapshots shut down on 14 January 2027, and OpenAI's own docs say the values can still be wrong.

The official docs: OpenAI's Structured Outputs guide is at developers.openai.com/api/docs/guides/structured-outputs (the old platform.openai.com address redirects there), and strict tool schemas are covered in the function calling guide. Read those for the reference. This page, checked against both on 17 November 2026, covers what they leave between the lines:

  • Strict mode is a JSON Schema subset. No allOf, not or if/then/else, no anyOf at the root, every key in required, and additionalProperties: false on every object. An unsupported schema is an error, not a silent downgrade. The full table.
  • Optional means nullable. A field the model may leave out is a union with null, not a key missing from required.
  • The shape is guaranteed, the values are not. The docs say outright that structured outputs can still contain mistakes, and that forcing a schema onto unrelated input can produce hallucinated values.
  • Three responses skip your schema: refusals, responses cut off at the token limit, and API errors. Check for each before you parse.
  • Tools are strict only if you ask, in Chat Completions. The Responses API tries to normalize function schemas to strict mode; Chat Completions stays non-strict unless you set strict: true.
  • GPT-4o is on its way out. OpenAI has deprecated the GPT-4o and GPT-4o mini snapshots that most structured outputs examples still use, with shutdown on 14 January 2027. The examples below use a current model.

Before structured outputs, every production JSON pipeline I shipped had a retry loop, a schema validator, and a graveyard of edge cases where the model would emit a stray {, a trailing comma, or a helpful preamble like "Sure! Here is your JSON:". JSON mode, released in 2023, fixed the syntax but not the shape - about 80% of responses matched my schema, and the other 20% paid the retry tax.

Structured outputs killed that loop. The reliability went from "mostly works" to "100% adherence" the first day I switched. Two years in, I have shipped them across five client projects - document extraction, ticket classification, agent routing, form generation, LLM-as-judge evals - and the failure surface is completely different now. This post is the production guide: schema design that actually works, refusals, streaming, migration, edge cases, and the comparison table I wish existed when I started.

Verified against, as of November 2026

Structured outputs have shipped across three API surfaces since 2024, so version drift is the main reason guides go stale. Everything in this post was checked on 17 November 2026 against the versions below and the official OpenAI guide. Where behaviour differs between the Chat Completions API and the Responses API, the post says so explicitly.

ComponentVerified againstNote
API surfaceResponses API and Chat Completions APIResponses API: text.format with type: "json_schema" and strict: true. Chat Completions: response_format with json_schema.
ModelsEvery current model, from gpt-4o-2024-08-06 and gpt-4o-mini through the GPT-6 family (gpt-6-astra, gpt-6.1-sol, gpt-6.1-terra, gpt-6-luna)Older models such as gpt-4-turbo support JSON mode only. The GPT-4o and GPT-4o mini snapshots are deprecated, with shutdown on 14 January 2027; OpenAI names gpt-6-luna as the replacement.
EnforcementConstrained decoding via a compiled grammarInvalid tokens are masked before generation, so non-conforming output is not possible rather than merely unlikely.
Known limitSchema adherence, not correctnessOpenAI's own docs: "Structured Outputs can still contain mistakes." The shape is guaranteed; the values are not.
Optional fieldsUnion with null, not omissionStrict mode requires every property to appear in required. Nullability is how you express optional.

What structured outputs actually do

Structured outputs constrain the model to emit only JSON that matches a JSON Schema supplied by the caller. Enforcement happens at decode time through a compiled grammar that masks any token which would break the schema, rather than through validation after generation. The practical consequence is that schema adherence stops being a probability and becomes a guarantee, which removes the retry loop entirely.

The grammar is built once per schema and cached on OpenAI's side, which is why the first request with a new schema is slower and later ones are not. Change the schema on every request and you pay that first-request cost every time.

The spec is OpenAI's official Structured Outputs guide, and the next section summarizes what it allows in strict mode. The practical headline is the table below - the difference between "our parser handles three formats now" and "we deleted the parser."

ModeAdherenceWhat it guaranteesWhen to use
Free text~40%Nothing. You parse a string.Chat answers, prose, anything human-read
JSON mode~80%Valid JSON syntax, no schemaLegacy. Migrate.
Function calling~99%Input matches tool schemaTool use, agent actions
Structured outputs (strict)100%Response matches your JSON Schema exactlyExtraction, classification, routing, evals

The dividing line is simple. If you want the model to do something (call an API, query a database, send an email), use function calling. If you want the model to return structured data, use structured outputs. If you want both - an agent that takes actions and produces a final structured report - use both, in the same call. Function calling is a special case of structured outputs under the hood.

What strict mode supports, per the official docs

Strict mode accepts a subset of JSON Schema, and an unsupported keyword is an error, not a silent downgrade. This is the subset as the official OpenAI guide lists it in November 2026. Check the guide itself before relying on an edge of it, because this list has grown since launch.

AreaSupported in strict modeNot supported
Typesstring, number, boolean, integer, object, array, enum, anyOfanyOf at the root: the root must be a plain object
Stringspattern, format (date-time, time, date, duration, email, hostname, ipv4, ipv6, uuid)Not listed as supported: minLength, maxLength
Numbersminimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf-
ArraysminItems, maxItems-
Reuse and recursion$defs with $ref, recursion to the root with #-
CompositionanyOf, each branch itself a valid strict schemaallOf, not, if / then / else, dependentRequired, dependentSchemas
ObjectsEvery property listed in required, and additionalProperties: false on every objectTruly optional keys: use a union with null instead
Size limitsUp to 5,000 object properties, 10 levels of nesting, 1,000 enum values, 120,000 characters across property names, definition names, enum and const values, and 15,000 characters of enum strings for a single enum with more than 250 values-

Fine-tuned models get a narrower subset: the docs list minLength, maxLength, pattern, format, minimum, maximum, multipleOf, patternProperties, minItems and maxItems as unsupported there. Output keys come back in the order the schema defines them, and the first request with a new schema is slower while OpenAI processes it; later requests with the same schema are not.

Structured outputs can still contain mistakes

That sentence is OpenAI's, from the guide's section on handling mistakes, and it is the most misread part of the feature. Strict mode guarantees the shape: every key present, every type right, every enum value one of yours. It does not guarantee the values are true. A model can return a well-formed invoice with the wrong total, and when the input has nothing to do with the schema, the guide warns that forcing the shape can produce hallucinated values. OpenAI's advice is to adjust the instructions, add examples, or split the task into simpler steps; mine is to add an explicit escape hatch (a nullable field or a status enum with an "insufficient_input" value) and to validate the business rules in code, the way you would for any other input.

Two cases also break the shape guarantee outright. A refusal comes back in its own field (refusal in Chat Completions, a content item of type refusal in the Responses API) rather than as schema-matching JSON. And a response cut off by the token limit is incomplete: check for status: "incomplete" with reason max_output_tokens in the Responses API, or finish_reason: "length" in Chat Completions, before you parse.

Setting up with Zod (TypeScript)

The TypeScript story is clean. Define your schema once with Zod, wrap it with the OpenAI SDK's helper, and you get a fully typed response. No JSON parsing, no manual validation - the SDK does both for you. The official guide now leads with the Responses API, so start there:

// lib/extract-invoice.ts - Responses API
import OpenAI from "openai";
import { zodTextFormat } from "openai/helpers/zod";
import { Invoice } from "./schemas"; // the Zod schema shown below

const openai = new OpenAI();

export async function extractInvoice(rawText: string) {
  const response = await openai.responses.parse({
    model: "gpt-6-luna",
    input: [
      { role: "system", content: "Extract structured invoice data." },
      { role: "user", content: rawText },
    ],
    text: { format: zodTextFormat(Invoice, "invoice") },
  });

  if (response.status === "incomplete") {
    throw new Error(`Incomplete: ${response.incomplete_details?.reason}`);
  }
  // output_parsed is null when there is no parsed text, for example after
  // a refusal, which arrives as an output content item of type "refusal".
  if (!response.output_parsed) throw new Error("No parsed output (refusal?)");
  return response.output_parsed;
}

The same schema works with Chat Completions, which plenty of production code still uses. Here is the full schema and the Chat Completions version of the call:

// lib/extract-invoice.ts
import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";

const openai = new OpenAI();

const LineItem = z.object({
  description: z.string(),
  quantity: z.number().int().positive(),
  unitPriceCents: z.number().int().nonnegative(),
});

const Invoice = z.object({
  invoiceNumber: z.string(),
  issueDate: z.string().describe("ISO 8601 date, e.g. 2026-05-27"),
  vendor: z.object({
    name: z.string(),
    taxId: z.string().nullable(),
  }),
  lineItems: z.array(LineItem).max(50),
  totalCents: z.number().int().nonnegative(),
  currency: z.enum(["USD", "EUR", "GBP", "CHF"]),
});

export async function extractInvoice(rawText: string) {
  const completion = await openai.chat.completions.parse({
    model: "gpt-6-luna",
    messages: [
      { role: "system", content: "Extract structured invoice data." },
      { role: "user", content: rawText },
    ],
    response_format: zodResponseFormat(Invoice, "invoice"),
  });

  const message = completion.choices[0].message;
  if (message.refusal) {
    throw new Error(`Model refused: ${message.refusal}`);
  }
  return message.parsed;
}

The return type of extractInvoice is inferred straight from the Zod schema, so downstream code is fully typed. No casts, no any, no runtime surprises. The .parse() method (note: not .create()) is what unlocks the structured response - it accepts a zodResponseFormat and returns a typed parsed field on the message.

A few details worth calling out. The model must support structured outputs: in Chat Completions that means gpt-4o-mini, gpt-4o-2024-08-06 or any later model, which today is every current one. Older models such as gpt-4-turbo only have JSON mode, and asking them for a strict schema fails with an error rather than quietly losing the guarantee. If you still pin a GPT-4o snapshot, it shuts down on 14 January 2027, so move to a current model and rerun your evals before then. Pin a model in production and bump it on a schedule. Also worth knowing: the second argument to zodResponseFormat (the "invoice" name above) shows up in OpenAI's telemetry and request logs, so pick something descriptive - future-you will thank present-you when grepping logs.

Setting up with Pydantic (Python)

The Python story mirrors the TypeScript one, using Pydantic instead of Zod. The SDK accepts a Pydantic model directly via the response_format parameter on the parse helper, and returns a fully typed instance.

# lib/extract_invoice.py
from openai import OpenAI
from pydantic import BaseModel, Field
from typing import Literal

client = OpenAI()

class LineItem(BaseModel):
    description: str
    quantity: int = Field(gt=0)
    unit_price_cents: int = Field(ge=0)

class Vendor(BaseModel):
    name: str
    tax_id: str | None

class Invoice(BaseModel):
    invoice_number: str
    issue_date: str = Field(description="ISO 8601 date, e.g. 2026-05-27")
    vendor: Vendor
    line_items: list[LineItem] = Field(max_length=50)
    total_cents: int = Field(ge=0)
    currency: Literal["USD", "EUR", "GBP", "CHF"]

def extract_invoice(raw_text: str) -> Invoice:
    completion = client.chat.completions.parse(
        model="gpt-6-luna",
        messages=[
            {"role": "system", "content": "Extract structured invoice data."},
            {"role": "user", "content": raw_text},
        ],
        response_format=Invoice,
    )

    message = completion.choices[0].message
    if message.refusal:
        raise RuntimeError(f"Model refused: {message.refusal}")
    return message.parsed

Same shape, same guarantees. Pick the SDK that matches your runtime, not the schema library - the wire format is identical, and so is the adherence guarantee. One Python-specific note: older tutorials call client.beta.chat.completions.parse. The openai-python 1.92.0 release (June 2025) moved the parse and stream helpers out of beta, so on a current SDK use client.chat.completions.parse, or client.responses.parse with text_format=Invoice for the Responses API, which is what the official guide shows.

Schema design that actually works

The hardest part of structured outputs is not the API - it is the schema. Strict mode rewards designs the model can satisfy and punishes designs that require it to invent values. After enough extraction pipelines I have a short list of patterns that hold up in production and a longer list of anti-patterns that bite.

Enums beat free text

Any field with a closed set of valid values should be an enum, not a string. Free-text fields are where you get model creativity you do not want - "Net 30", "net30", "Net 30 days", "NET-30" all show up. An enum collapses that variance to one canonical value and lets your downstream code do exact-match dispatch.

// Bad
priority: z.string(),

// Good
priority: z.enum(["low", "medium", "high", "urgent"]),

// Better - with description to disambiguate
priority: z
  .enum(["low", "medium", "high", "urgent"])
  .describe("urgent means immediate human attention required"),

Optional vs nullable

Strict mode requires every property in your schema to be present in the response - there is no optional in JSON Schema strict mode the way Zod thinks about it. The correct pattern is .nullable(): the field is always present, but its value can be null when the model has no value to put there. This is a frequent source of confusion when migrating.

// Bad - strict mode rejects this
taxId: z.string().optional(),

// Good - always present, may be null
taxId: z.string().nullable(),

Discriminated unions for polymorphism

If your response can take one of several shapes, use a discriminated union with a literal tag field. The model picks the tag, and the schema forces the rest of the object to match. This pattern is what powers agent routing in production - the model classifies the request and produces a payload typed for that specific branch.

const RoutingDecision = z.discriminatedUnion("kind", [
  z.object({
    kind: z.literal("answer"),
    text: z.string(),
    confidence: z.number().min(0).max(1),
  }),
  z.object({
    kind: z.literal("escalate"),
    reason: z.enum(["low_confidence", "policy", "missing_data"]),
    notes: z.string(),
  }),
  z.object({
    kind: z.literal("tool_call"),
    tool: z.enum(["lookup_order", "refund", "create_ticket"]),
    args: z.record(z.string(), z.string()),
  }),
]);

Bound arrays and strings

Always cap arrays with .max(N), which becomes maxItems and is enforced in strict mode, where N is a sensible upper bound. Without caps the model occasionally over-extracts - turning a five-line invoice into eighty fabricated line items because the prompt wording let it. Strings are different: minLength and maxLength are not in the guide's list of supported keywords, so state length limits in the field description and check them in your own validation.

Descriptions are instructions

The .describe() on a Zod field (or Field(description="...") in Pydantic) is fed to the model as part of the schema. Treat each one as a tiny prompt. Use them for format hints ("ISO 8601 date"), for disambiguation ("in cents, not dollars"), and for closed-domain instructions that would otherwise belong in the system prompt. Avoid narrative prose - short and imperative reads better.

Refusals - what they are and how to handle them

A refusal in OpenAI structured outputs is a separate response field that appears when the model declines a request on safety grounds. When a refusal is present the structured payload is absent, so code that parses the payload without checking the refusal field first will throw. Treat refusals as a first-class error path with their own logging and fallback, not as an exception to catch.

The docs are explicit that a refusal does not necessarily follow your schema. In Chat Completions it arrives as a populated refusal field on the message; in the Responses API it is an output content item of type refusal. Check for it on every call - pretending refusals do not happen produces silent NULL bugs in downstream tables.

const completion = await openai.chat.completions.parse({
  model: "gpt-6-luna",
  messages,
  response_format: zodResponseFormat(Schema, "result"),
});

const message = completion.choices[0].message;

if (message.refusal) {
  // Log it. Refusals are signal, not noise.
  await logRefusal({
    userId,
    refusal: message.refusal,
    inputHash: hashInput(messages),
  });

  // Fall back to a degraded but safe path.
  return {
    status: "refused",
    reason: message.refusal,
    fallback: await safeFallbackPath(messages),
  };
}

return { status: "ok", data: message.parsed };

In two years of production usage, refusals are rare on normal business workloads (well under 0.1% of calls in extraction pipelines) but common in adjacent territories - anything touching personal data, legal text, or medical content. Log them all, review them weekly, and either reshape the prompt to remove the trigger or accept refusal as a valid outcome. Burying refusals in a try/catch is how you ship the bug where 4% of your invoices silently fail to extract.

Streaming structured outputs

Streaming structured outputs emits partial JSON that progressively conforms to the schema, rather than one complete object at the end. Each chunk is a valid prefix of the final object, so a user interface can render fields as they arrive. The cost is that any consumer downstream of the stream must tolerate incomplete objects, which means validation belongs at the end of the stream rather than on every chunk.

OpenAI recommends letting the SDKs handle streaming with structured outputs rather than parsing deltas yourself. The Vercel AI SDK wraps this in a clean React hook.

// app/api/extract/route.ts
import { streamObject } from "ai";
import { openai } from "@ai-sdk/openai";
import { Invoice } from "@/lib/schemas";

export async function POST(req: Request) {
  const { rawText } = await req.json();

  const result = streamObject({
    model: openai("gpt-6-luna"),
    schema: Invoice,
    prompt: `Extract invoice data from:\n\n${rawText}`,
  });

  return result.toTextStreamResponse();
}

// app/extract/page.tsx - client
"use client";
import { experimental_useObject as useObject } from "@ai-sdk/react";
import { Invoice } from "@/lib/schemas";

export default function ExtractPage() {
  const { object, submit, isLoading } = useObject({
    api: "/api/extract",
    schema: Invoice,
  });

  return (
    <div>
      <button onClick={() => submit({ rawText: "..." })}>Extract</button>
      {object?.invoiceNumber && <p>Invoice: {object.invoiceNumber}</p>}
      {object?.lineItems?.map((item, i) => (
        <div key={i}>{item?.description} - {item?.quantity}</div>
      ))}
    </div>
  );
}

Note the optional chaining on every field inside the render - during streaming, any field can be undefined for a few hundred milliseconds before it lands. The schema is the same as for the non-streaming path; only the consumer changes. For deeper coverage of the streaming primitives, see my Next.js OpenAI streaming tutorial.

Common mistakes

Patterns that look fine in a notebook and detonate in production. The first group is about what the API accepts; each one is in the official guide, but scattered across sections:

  • An anyOf at the root. The root must be a plain object. If the answer can take several shapes, wrap them: { result: anyOf[...] }.
  • Reaching for oneOf or allOf. Strict mode has anyOf only. allOf, not, if/then/else, dependentRequired and dependentSchemas are rejected, so schemas generated from an OpenAPI spec often need flattening first.
  • A nested object without additionalProperties: false, or a key missing from required. Hand-rolled JSON Schema gets this wrong one level down. With strict: true the request fails with an error; the Zod and Pydantic helpers generate it correctly for you.
  • Expecting minLength to hold. The guide does not list minLength or maxLength among the supported string keywords, so enforce string length in your own validation. On fine-tuned models the list of unsupported keywords is longer, including pattern, format and the numeric bounds.
  • JSON mode without the word JSON. If you still use json_object, the API errors when "JSON" does not appear in the context, and without clear instructions the model can stream whitespace until it hits the token limit.
  • Strict tools assumed in Chat Completions. The Responses API tries to normalize function schemas into strict mode; Chat Completions stays non-strict unless each tool sets strict: true. Fine-tuned models also drop strict mode on turns where they call several functions at once; set parallel_tool_calls: false if you need zero or one call.
  • A new schema on every request. The first request with a schema carries extra latency while OpenAI processes it. Building the schema dynamically per user (say, with their custom fields inlined) pays that cost on every call.

The second group is design: the API accepts these, and they still fail.

  • Over-nesting. Schemas deeper than 3-4 levels are fragile. The model misplaces values across levels and strict mode eventually hits OpenAI's nesting cap (10 levels). Flatten when you can.
  • anyOf with many branches. Three discriminated union branches is fine, ten is not. The model gets confused about which branch fits and produces low-confidence picks. If you have ten, you actually have a classification task - do it in two steps.
  • Recursive schemas. Self-referential schemas ("a comment has replies which have replies") technically work via $ref but break under load. Flatten to a list with parent IDs.
  • Descriptions as system prompts. Field descriptions are seen but not strongly obeyed. A paragraph of instructions in a description does not replace clear messaging in the system prompt.
  • No escape hatch for bad input. If the user sends a photo of a cat to your invoice extractor, a schema with no way to say "this is not an invoice" forces the model to invent one. The guide warns about exactly this; add a status enum or nullable fields and say in the prompt when to use them.
  • Confusing optional with nullable. Covered above - every field must be present, use .nullable() when the value is genuinely absent.

Migrating from JSON mode to structured outputs

Migrating from JSON mode to structured outputs is a change of one parameter: response_format moves from json_object to a json_schema block with strict: true. In five production migrations I ran during 2025 and 2026, this removed the schema-mismatch retry path entirely and cut parse-failure incidents to zero. Keep the existing validator as defence in depth; it simply stops firing.

The migration is small in code and large in reliability. The before-and-after for a typical classification call:

// Before - JSON mode
const completion = await openai.chat.completions.create({
  model: "gpt-6-luna",
  response_format: { type: "json_object" },
  messages: [
    {
      role: "system",
      content: `Classify the ticket. Reply ONLY with JSON like:
{"category": "billing|technical|account", "urgency": "low|medium|high"}`,
    },
    { role: "user", content: ticketText },
  ],
});
const raw = completion.choices[0].message.content!;
const parsed = JSON.parse(raw); // throws ~5% of the time
const validated = schema.parse(parsed); // throws another ~15%

// After - structured outputs
const Ticket = z.object({
  category: z.enum(["billing", "technical", "account"]),
  urgency: z.enum(["low", "medium", "high"]),
});

const completion = await openai.chat.completions.parse({
  model: "gpt-6-luna",
  response_format: zodResponseFormat(Ticket, "ticket"),
  messages: [
    { role: "system", content: "Classify the support ticket." },
    { role: "user", content: ticketText },
  ],
});
const parsed = completion.choices[0].message.parsed; // never throws

Three things drop out of the system prompt: the JSON shape instructions, the "reply only with JSON" nag, and the example payload. The schema carries all of that intrinsically. My rule when migrating: cut the system prompt down to the actual task instruction in plain English, and let the schema express the shape.

5 real production use cases

1. Document extraction (PDFs to JSON)

The textbook use case. Layout-aware OCR extracts text; structured outputs map that text into a typed schema. Combined with a real document extraction pipeline you get end-to-end PDF-to-database in two model calls. The schema is the contract between OCR and the rest of your system.

2. Ticket classification

Enum-heavy schemas with confidence scores route inbound support tickets to queues. The classification is fast, the schema is small, and the discriminated-union pattern lets you add per-category fields (e.g. billing tickets carry an invoice number, technical tickets carry an environment).

3. Agent dispatch / routing

Discriminated unions excel at routing inside an agent. The model decides on the next action - answer, escalate, call a tool, ask for clarification - and produces a payload typed for that branch. See tool calling best practices and agentic RAG architecture for the broader pattern.

4. Form generation

Give the model a free-text user description and a form schema. It produces a filled-in form payload that you render directly in your UI - pre-filled invoices, contracts, applications. The schema doubles as documentation for the form builders downstream.

5. LLM-as-judge for evals

Judge schemas have a score per metric, a verdict, and a structured rationale field. Strict outputs make the judge a deterministic part of your test suite - every CI run produces parseable scores you can threshold on, with no flaky JSON parsing in the middle. The trick is keeping the schema small: one score per axis, one short rationale string, no nested objects. The narrower the judge schema, the more consistent the scores across runs. I keep judge schemas to under ten properties total and tune the rubric in the system prompt, not in layers of nested structure.

Performance and cost

Structured outputs add no token cost and one latency cost. The docs say the first request with a new schema carries extra latency and later requests with the same schema do not; in my measurements that first call paid roughly 200 to 400 milliseconds on typical extraction schemas. The practical implication is to keep schemas stable and defined at module scope, because generating a fresh schema per request forfeits the cache on every call.

Token cost is identical to non-structured calls. Structured outputs do not add a markup. What can creep in is schema verbosity sneaking into the system prompt token count - every property, description, and enum value is fed to the model. Trim descriptions to what is necessary, and watch your input token totals before and after migration. For a deeper cost picture, my OpenAI API cost breakdown covers the per-feature math.

Error rates collapse on the migration. The retry loop that surrounded every JSON-mode call goes away. In one client pipeline that processed 50K documents per day, the post-migration parse-failure rate went from 4.2% to 0.0% - and the refusal rate (the new tail) stayed under 0.05%.

Edge cases: large schemas, recursion, polymorphism

Three places where structured outputs stops being trivial:

Very large schemas. OpenAI caps a schema at 5,000 object properties, 10 levels of nesting, 1,000 enum values and 120,000 characters of property names, definition names and enum values. Long before you hit those, quality drops. If your schema is getting large, split the extraction into two calls: a router call that picks what to extract, then a follow-up extraction with the narrower schema. Splitting also tends to lift quality because the model is not distracted by fields irrelevant to the input.

Recursive types. A recursive schema (tree of comments, nested folders, file system) is technically possible with Zod's z.lazy plus a $ref but practically fragile. The cleaner pattern is to flatten: return a list of nodes, each with an id and a nullable parentId. Rebuild the tree client-side. Smaller schema, better quality, simpler validation.

Polymorphism with many branches. Up to about five discriminated-union branches the model handles well. Past that, split into a two-step classification: first call picks the branch, second call extracts the branch-specific payload. The token cost is similar, the quality is markedly better, and each step is independently evaluable.

OpenAI vs Anthropic vs Gemini: structured output compared

All three major providers can return schema-conforming JSON. OpenAI and, since late 2025, Anthropic both constrain the response itself with a JSON schema; Anthropic's older route, still common in existing code, is a forced tool call. Google Gemini takes a response schema on the generation config. The syntax differs enough that a shared abstraction is worth writing on any project that uses more than one of them.

CapabilityOpenAIAnthropic ClaudeGoogle Gemini
Mechanismtext.format (Responses) or response_format (Chat Completions) with json_schema and strict: trueoutput_config.format with json_schema; older code forces a tool callresponseSchema plus responseMimeType: application/json
Where the data landsParsed field on the messageText content block (JSON outputs) or the forced tool's inputResponse text, as JSON
Optional fieldsUnion with null; every key must be in requiredStandard JSON Schema optionalityStandard JSON Schema optionality
RefusalsDedicated refusal fieldstop_reason: "refusal", output may not match the schemaSurfaced through finish reason and safety ratings
StreamingPartial JSON snapshotsDelta-based tool input streamingChunked JSON text
Tools alongside the schemaNo documented restriction; strict function tools use the same engineSupported; JSON outputs and strict tool use combineSupported

Anthropic tool use in detail

Both major labs ship a way to get structured data out of their models, but the shape is different. OpenAI's structured outputs is a property of the response itself; Anthropic's approach is to route structured data through their tool use feature - you define a tool whose input is your schema and force the model to call it.

Update, October 2026: Claude now also has native structured outputs: JSON outputs through output_config.format with type: "json_schema", and strict: true on tool definitions, both generally available on current models. For new code, use those. The forced-tool pattern below still works and is what most code written before late 2025 does.

FeatureOpenAI structured outputsAnthropic tool use
Strict schema adherenceYes (constrained sampling)Strong but not guaranteed
Response shapeNative parsed field on messageTool call input on a forced tool
SDK ergonomicsZod / Pydantic helpers built inManual JSON Schema, parse yourself
StreamingPartial JSON snapshotsDelta-based tool input streaming
Refusal handlingSeparate refusal fieldRefusal as text content

For a project that needs both providers - common when you want failover or to A/B test models - wrap both behind a single typed interface that returns your Zod or Pydantic class regardless of the underlying call shape. My Claude vs ChatGPT comparison covers the broader provider tradeoff.

Where this fits in a real product

Structured outputs is rarely the whole feature. In OmniAPI, every function spec generated for a user passes through a structured outputs call that validates the shape against the target API schema - no malformed payloads ever leave the model. In Xandidate, candidate rubric scoring is a structured outputs call that returns per-criterion scores plus a rationale, so the recruiter sees the same shape every time and the audit log stays clean. Both ship because the schema is the contract - not the prose around it.

If you are starting a new AI feature in 2026, structured outputs is the default for any model response your app consumes programmatically. JSON mode is legacy. Free-text-and-pray belongs only in human-facing chat. If you want help wiring this into a real pipeline, an AI integration engagement starts where this post ends: your real documents, a schema with an escape hatch, refusal and truncation handling, and an eval set that shows field-level accuracy before the pipeline touches production. You can also hire an AI developer in Kosovo directly.

Frequently asked questions

Where are the official OpenAI structured outputs docs?

OpenAI's Structured Outputs guide is at developers.openai.com/api/docs/guides/structured-outputs; the old platform.openai.com/docs/guides/structured-outputs address redirects there. Strict mode for tools is documented in the function calling guide at developers.openai.com/api/docs/guides/function-calling. Both were checked for this post on 17 November 2026.

What are the most common OpenAI structured outputs mistakes?

Putting anyOf at the root of the schema, using allOf, oneOf, not or if/then/else, leaving a key out of required or additionalProperties: false off a nested object, expecting minLength or maxLength to be enforced, and parsing without first checking for a refusal or a response cut off at the token limit. The design mistake is a schema with no way to say the input does not fit, which forces the model to invent values; the docs themselves say structured outputs can still contain mistakes.

What are OpenAI structured outputs?

Structured outputs is a feature on the OpenAI API that constrains the model to produce JSON that matches a JSON Schema you supply, with 100% adherence rather than the ~80% you get from JSON mode. It is enforced at the decoding layer via constrained sampling, so the model literally cannot emit a token that would break the schema. You pass a schema (or a Zod / Pydantic class), and the response is guaranteed to parse.

Structured outputs vs JSON mode vs function calling - what is the difference?

JSON mode forces valid JSON but not a specific shape, so you still get schema drift. Function calling lets the model decide whether to call a tool, with structured arguments. Structured outputs forces a specific schema on the response itself, with strict mode guaranteeing 100% adherence. In practice: use structured outputs for extraction and classification, function calling for tool use, JSON mode almost never in 2026.

What is a refusal in structured outputs?

When the model decides a request violates safety policy, it returns a refusal string in a separate refusal field instead of the structured response. Your code must check for message.refusal before trying to parse the structured payload. Treat refusals as a first-class error path, log them, and have a fallback (degraded response, escalation to a human, or a different prompt).

Can I stream structured outputs?

Yes. The OpenAI SDK and the Vercel AI SDK both support streaming partial JSON that progressively conforms to the schema. In Vercel AI SDK this is useObject on the client and streamObject on the server. The partial object updates field-by-field, which is great for UI but means downstream consumers must handle incomplete shapes gracefully.

Do structured outputs support recursive schemas?

Recursive schemas are supported via $ref (to the root with # or to an entry in $defs) but practically fragile, especially with deep recursion. OpenAI's documented limits are 10 levels of nesting and 5,000 object properties per schema. For tree-shaped data, prefer flattening to a list with parent IDs rather than nested children. It is more reliable, easier to validate, and easier to render.

Is there a cost or latency penalty?

OpenAI's docs say the first request with a new schema has extra latency and later requests with the same schema do not; in my measurements that first call cost roughly 200 to 400 ms on typical extraction schemas. Token costs are unchanged. For high-throughput endpoints, keep your schemas stable so the cache stays warm.

How are structured outputs different from Anthropic tool use?

Since late 2025 Anthropic has a direct equivalent: JSON outputs through output_config.format with type json_schema, generally available on current Claude models as of October 2026, plus strict: true on tool definitions. Before that, the pattern was to wrap the schema as a tool and force tool use, which still works and is what a lot of existing code does. The main differences now are parameter names and each provider's supported JSON Schema subset.

Should I migrate from JSON mode to structured outputs?

Yes, almost always. The migration is a few lines (swap response_format from json_object to a zodResponseFormat or json_schema), and the reliability lift is significant - JSON mode breaks ~20% of the time on complex schemas in my benchmarks, structured outputs breaks 0%. Keep your existing validation as a defense-in-depth layer, but the parse failures essentially go away.