Skip to content
All patterns
Reliability

Structured output validation

How structured output validation turns free text into a trusted object
1 / 4Constrain

Step 1 of 4

Constrain

The request carries a JSON schema, defined once as a Pydantic or Zod model, so the model is steered towards fields of the right type and enum values.

Constrain first, validate always, and cap the retries so a strict schema cannot loop forever.

Problem

LLMs produce malformed JSON, extra fields, wrong types, or hallucinate enum values. Downstream code crashes.

Pattern

Constrain decoding with a JSON schema (where supported), then validate the output with a strict schema validator. On failure, repair or retry.

Implementation
structured.py
import logging

from openai import OpenAI
from pydantic import BaseModel, field_validator

log = logging.getLogger(__name__)
client = OpenAI()
# Model names change often; check your provider's model list (as of 28 October 2026). Replace <...-model> with a model id from that list.

class Answer(BaseModel):
    summary: str
    sources: list[str]
    confidence: float

    @field_validator("confidence")
    @classmethod
    def clamp(cls, v: float) -> float:
        return max(0.0, min(1.0, v))

def call_structured(query: str, context: list[str], attempts: int = 2) -> Answer:
    joined = "\n\n".join(context)
    for attempt in range(attempts):
        # Structured Outputs: the API constrains the reply to Answer's JSON schema,
        # and the SDK parses it into Answer (running the validator above).
        response = client.responses.parse(
            model="<small-model>",
            input=[
                {"role": "system", "content": "Answer from the context only. Cite source ids."},
                {"role": "user", "content": f"Context:\n{joined}\n\nQuestion: {query}"},
            ],
            text_format=Answer,
        )
        if response.output_parsed is not None:
            return response.output_parsed
        # No parsed output usually means a safety refusal, which does not follow the schema.
        log.warning("Attempt %d returned no structured output", attempt)
    raise RuntimeError("Could not produce valid structured output")
Trade-offs
  • Downstream code can trust the shape
  • Schema-constrained decoding can fail on edge cases
  • Validation + retry adds latency
  • Over-strict schemas cause retry storms
Production checklist
  • Pydantic / Zod schema as single source of truth
  • Use Structured Outputs (JSON schema) where the model supports it; older JSON mode only guarantees valid JSON
  • Handle refusals and repair common malformations where schemas are not enforced
  • Log validation failure rate
  • Schema versioning