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.
Step 2 of 4
Generate
The model produces the reply. Constrained decoding is not a guarantee: a refusal or an edge case can still come back off-schema.
Step 3 of 4
Validate
A strict validator parses the output and checks types, ranges and required fields, for example clamping confidence between 0 and 1. Downstream code only ever sees a valid object.
Step 4 of 4
Repair or retry
On failure, repair a known malformation or retry within a small attempt limit. After that, raise a clear error and log the failure rate rather than passing bad data on.
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
~388 tokens
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