Session 5· 03· 15 min
Schema Output — force a specific shape
What you'll learn
- ▸Provide a JSON Schema to response_format
- ▸Force the model to return data in the EXACT shape you define
- ▸See the difference between json_object and json_schema
From "valid JSON" to "exact shape"
JSON mode (lesson 02) only promised valid JSON. This lesson goes further: you attach a JSON Schema and the API enforces that the output matches that schema — required fields, types, nothing extra.
Three levels of structure
Plain text
lesson 01
Valid JSON
lesson 02
Exact shape
lesson 03 (here)
Writing your first schema
03_schema_output_intro.py
schema = { ①
"type": "object",
"properties": {
"topic": {"type": "string"},
"key_points": {"type": "array", "items": {"type": "string"}},
},
"required": ["topic", "key_points"], ②
"additionalProperties": False, ③
}
response = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": "You are a teacher."},
{"role": "user", "content": "Give beginner notes on structured outputs."},
],
response_format={
"type": "json_schema", ④
"json_schema": {
"name": "lesson_note",
"schema": schema,
"strict": True, ⑤
},
},
)①A standard JSON Schema: top-level object with two fields.
②required means these keys MUST appear in the output.
③additionalProperties: false blocks the model from inventing extra keys.
④response_format type is now "json_schema", not "json_object".
⑤strict: true makes the API enforce the schema at decode time, not just after the fact.
strict mode is your best friend
Without strict: true the schema is advisory. With it, the API constrains every generated token to fit the schema — so the output is guaranteed valid on arrival. Always use strict: true unless you have a specific reason not to.
Run it
$ python 03_schema_output_intro.py
Knowledge check
Knowledge Check
What does strict: true do that regular json_schema does not?
Code Check
What happens if the model tries to output an extra field like "bonus_tip" when additionalProperties is false?
Recap — what you just learned
- ✓response_format type changes from json_object → json_schema when you attach a schema
- ✓required[] and additionalProperties: false define the exact shape
- ✓strict: true enforces the schema during decoding, not after
- ✓This is the foundation for reliable data extraction