Structured Outputs and JSON Schema
Make models return data your code can trust: JSON mode, schema-constrained outputs, validation and repair.
Beginner · about 5 hours · difficulty 3/5
Learn first: Messages APIs and Provider SDKs
Most real applications need data, not prose: extracted fields, a classification label, a list of steps. Parsing free text with regexes is fragile. Structured outputs solve this.
Levels of reliability
- Ask nicely: "Respond only with JSON matching this shape." Works most of the time, fails in production at scale.
- JSON mode: the provider guarantees syntactically valid JSON, but not your schema.
- Schema-constrained output: you pass a JSON Schema and the provider constrains decoding so the output matches it. Most major APIs support this directly or through tool calling.
- Validate anyway: parse into a Pydantic model or Zod schema. Constrained decoding guarantees shape, not truth.
Designing good schemas
- Keep schemas flat and small; deeply nested optional structures confuse models.
- Use enums for categories and describe each field with a
description. - Add a field for uncertainty (for example
"confidence"or"not_found") so the model is not forced to invent values. - Put a reasoning field before the answer field if you want the model to think first.
Pitfalls
Schema-valid output can still be wrong: a date in the wrong format, a hallucinated invoice number. Add business-rule validation and, where needed, a retry with the validation error fed back to the model.
Good enough to move on
You can extract typed records from messy text with a schema, validate them, and handle the cases where the data is genuinely missing.
Key concepts
- JSON mode vs schema-constrained output
- Writing JSON Schemas
- Pydantic / Zod validation
- Enums and field descriptions
- Handling missing data
- Retry with validation feedback
- Instructor and similar libraries
Mini project
Build an invoice or job-posting extractor that turns 20 messy text samples into validated JSON records using a schema, with a report of which fields were missing or failed validation.
Check yourself
Your output always matches the schema, but a customer reports wrong prices. What does schema enforcement guarantee and what does it not?
Free resources
- OpenAI docs: structured outputs (OpenAI)
- Gemini API: structured output (Google)
- JSON Schema: getting started (json-schema.org)