Structured Output — JSON Schema, Pydantic, Zod, Constrained Decoding

"Ask the model nicely to return JSON" fails 5 to 15 percent of the time, even on frontier models. Structured outputs close that gap with constrained decoding: the model is literally prevented from emitting a token that would violate the schema. OpenAI's strict mode, Anthropic's schema-typed tool use, Gemini's `responseSchema`, Pydantic AI's `output_type`, and Zod's `.parse` are five surface forms of the same idea. This lesson builds the schema validator and the strict-mode contract learners will use for every production extraction pipeline.

Build 1.3 hr Python (stdlib, JSON Schema 2020-12 subset)

Prerequisites: Phase 13 · 02 (function calling deep dive)

#Learning Objectives

  • Write a JSON Schema 2020-12 for an extraction target using the right constraints (enum, min/max, required, pattern).
  • Explain why strict mode and constrained decoding give different guarantees from "validate after generation".
  • Distinguish the three failure modes: parse error, schema violation, model refusal.
  • Ship an extraction pipeline with typed repair and typed refusal handling.
Full Access lesson

Keep going. The rest of this lesson is one step away.

Unlock all 503 lessons, video, code, quizzes and every future update. Pay in your own currency with Paystack.

The text and code of this lesson are based on AI Engineering from Scratch by Rohit Ghumare, MIT licensed.