Structured Outputs from LLMs: Reliable JSON with Schemas

Get reliable JSON from language models: JSON mode vs schema-constrained output, Pydantic and zod validation, retries, and designing schemas models follow.

Published December 1, 2026

Most real LLM features end in code, not chat: extract fields from an invoice, classify a ticket, produce a list of actions. That code needs predictable structure. Asking nicely for JSON works most of the time, which is not good enough for production. Structured output features and validation make it reliable.

The concept

There are three levels of strictness. Prompt-only: instructions and examples ask for JSON; the model usually complies but may add prose or miss fields. JSON mode: the provider guarantees syntactically valid JSON but not your fields. Schema-constrained output (often called structured outputs): you pass a JSON Schema and decoding is constrained so the output matches it.

Even with constrained decoding, validate on your side. A schema guarantees shape, not truth: the model can still put a wrong date in a valid date field. Libraries like Pydantic (Python) and zod (TypeScript) let you define the schema once, send it to the model, and parse the response into typed objects with clear errors when something is off.

Levels of strictness

ApproachGuaranteesUse when
Prompt onlyNothingPrototypes
JSON modeValid JSON syntaxFlexible shapes
Schema-constrainedMatches your JSON SchemaProduction extraction/classification
Tool / function callingArguments match tool schemaWhen output triggers an action

Schema-first workflow

exportrequestresponsePydantic / zod modelsingle sourceJSON Schemasent to APIConstrained outputmodelValidate + parsetyped object
Define once, use for both generation and validation.

Designing schemas models follow

  1. Keep schemas flat and small where possible
  2. Use enums for categories instead of free text
  3. Describe every field (descriptions guide the model)
  4. Allow null / "unknown" so the model does not invent values
  5. Validate business rules after parsing
Schema design tips.

Practical examples

Python: Pydantic model as the schema

Many SDKs accept a Pydantic model directly for structured output.

from pydantic import BaseModel, Field
from typing import Literal

class Ticket(BaseModel):
    category: Literal["billing", "bug", "feature", "account"]
    priority: int = Field(ge=1, le=4, description="1 = urgent")
    summary: str = Field(max_length=200)
    order_id: str | None = Field(None, description="Only if explicitly mentioned")

schema = Ticket.model_json_schema()        # pass to the API's structured output option
ticket = Ticket.model_validate_json(raw_output)

TypeScript: zod

Same idea, generated JSON Schema plus runtime parsing.

import { z } from 'zod'
const Invoice = z.object({
  invoiceNumber: z.string(),
  totalPaise: z.number().int().nonnegative(),
  dueDate: z.string().date().nullable(),
})
const parsed = Invoice.safeParse(JSON.parse(raw))
if (!parsed.success) console.error(parsed.error.issues)

Retry with the validation error

If validation fails, show the model the error once.

for attempt in range(2):
    raw = llm(prompt if attempt == 0 else f"{prompt}\nYour last output failed validation: {err}. Fix it.")
    try: return Ticket.model_validate_json(raw)
    except ValidationError as e: err = e
raise RuntimeError("could not get valid output")

Common mistakes

  • Parsing free-form text with regexes instead of using structured output.
  • Required fields with no "unknown" option, forcing the model to invent values.
  • Deeply nested, huge schemas that increase errors.
  • Trusting values because the shape is valid.

Key takeaways

  • Use schema-constrained output for production extraction.
  • Define schemas once (Pydantic, zod) and validate every response.
  • Use enums, descriptions and nullable fields.
  • Shape validity ≠ correctness; check business rules too.

FAQ

Is structured output slower?

Constrained decoding adds little latency in most APIs; the first request with a new schema may be slower on some providers while it is compiled.

Can I stream structured output?

Yes, many APIs stream partial JSON; use a partial JSON parser to update UIs progressively.

What about reasoning before answering?

Add a short "reasoning" field before the answer fields, or use a reasoning model, if quality improves with step-by-step thinking.

More AI articles