Topic 1 of 5 · 4 min read
Defining model output with JSON Schema
Goal: Write a schema that makes the model return exactly the fields, types and allowed values a downstream function needs.
A schema is the contract between the model and your code: it lists every field, its type and the values it may take, so the model has nothing left to improvise. Write it from what the next function needs, not from what the model might say.
Check yourself · 1 of 3
Your code reads a status field that must be one of three known values. How should the schema describe it?
Why it matters
Free text forces you to parse prose with regular expressions, and prose changes from one run to the next. A schema turns the reply into data. The model sees the schema as part of the request, so field names and descriptions also act as instructions.
How to do it
- Start from the consumer. List the fields your code reads. A ticket router needs
category,priorityandneeds_human. Nothing else. - Mark fields required. In strict modes every property usually has to be listed in
required. A missing field then becomes an error, not a surprise. - Use enums for closed sets.
"enum": ["billing", "bug", "other"]stops"Billing issue"and"billing-problem"from appearing. - Describe each field. The
descriptiontells the model what you mean bypriority. Put units, formats and examples there. - Make absence explicit. If a value may not exist, allow
nullwith a type like["string", "null"]. Otherwise the model invents a value to fill the slot. - Generate, do not hand-write. In Python define a Pydantic model and export its JSON Schema. In TypeScript define a Zod schema and convert it. You then get the validator and the schema from one source.
Before and after
{
"type": "object",
"properties": {
"category": { "type": "string" },
"priority": { "type": "number" }
}
}
Nothing is required, category accepts any text, and priority has no range. The fixed version:
{
"type": "object",
"properties": {
"category": { "type": "string", "enum": ["billing", "bug", "other"] },
"priority": { "type": "string", "enum": ["low", "normal", "urgent"],
"description": "urgent only if the customer cannot log in or pay" },
"order_id": { "type": ["string", "null"],
"description": "Order id from the message, or null if none is given" }
},
"required": ["category", "priority", "order_id"],
"additionalProperties": false
}
What goes wrong
- Free-text fields where an enum fits. You then compare strings with a long list of aliases.
- Optional fields the model fills anyway. If
order_idhas no null option, the model writes a plausible id. - Vague names. A field called
valueordatagives the model no hint. Name itrefund_amount_eurand say so in the description. - Schema drift. The hand-written schema says one thing and the validator in code says another. Generate both from one definition.
Examples
Pydantic model that exports the schema
from typing import Literal, Optional
from pydantic import BaseModel, Field
class Ticket(BaseModel):
category: Literal["billing", "bug", "other"]
priority: Literal["low", "normal", "urgent"] = Field(
description="urgent only if the customer cannot log in or pay")
order_id: Optional[str] = Field(
description="Order id from the message, or null")
schema = Ticket.model_json_schema()
The same class validates the reply later, so the two cannot disagree.
Zod schema in TypeScript
import { z } from "zod";
export const Ticket = z.object({
category: z.enum(["billing", "bug", "other"]),
priority: z.enum(["low", "normal", "urgent"]),
order_id: z.string().nullable(),
});
The inferred type is the type your router function takes.
Key points
- Design the schema from the fields the next function reads, not from what the model could say.
- Use enums for closed sets and list every property as required so a missing field is an error.
- Allow null for values that may be absent, or the model will invent something to fill the slot.
- Field names and descriptions are instructions: put units, formats and meaning there.
- Generate the JSON Schema from a Pydantic or Zod model so the schema and the validator cannot drift apart.
Common mistakes
- Leaving fields optional and then crashing when the model leaves one out.
- Typing a closed set such as status as a plain string.
- Giving fields generic names like data or value with no description.
- Maintaining a hand-written schema next to a separate validator.
Check yourself · 2 of 3
An invoice field due_date is sometimes missing from the source text. What stops the model from inventing a date?
Check yourself · 3 of 3
A TypeScript service already has a Zod schema for its input type. What is the best way to get the JSON Schema for the model request?
Practice items, not counted towards your mastery.
Start here
- Structured outputs (Claude docs) (opens in a new tab)DocsFree
How Claude constrains output to a JSON schema, which schema features are supported and what the limits are.
- Structured model outputs (OpenAI API docs) (opens in a new tab)DocsFree
Strict schema mode versus JSON mode, supported keywords and how refusals appear in a structured response.
- Structured output (Gemini API docs) (opens in a new tab)DocsFree
How Gemini takes a response schema and which schema subset it accepts.
More for this topic
- JSON Schema: getting started step by step (opens in a new tab)ArticleFree
The official walkthrough of properties, required fields, types and constraints used in every provider's schema mode.
- Pydantic documentation (opens in a new tab)DocsFree
Defining Python models that validate data and generate a JSON Schema from the same class.