Structured Output and JSON
Structured output means asking a model to reply in a fixed data format, usually JSON that matches a schema, instead of free text. It is used whenever code, not a person, reads the reply: to route a question, fill a database row or trigger an action. A schema lists the fields, their types and their allowed values.
This lesson builds the chapter's checkpoint: a script that takes a student's question and returns a short answer plus its category as JSON.
Free Text vs Structured Output
Ways to Get JSON
| Method | Description |
|---|---|
| Ask in the prompt | It is used for quick tests; the model usually complies, but nothing guarantees it |
response_format with a JSON schema | It is used to ask the API to return JSON that matches your schema; providers that support it constrain the reply to the schema |
The helper's parse() with a Pydantic model | It is used to send the schema and get back a validated Python object, in one step |
| Strict tool input | It is used when the JSON is the input to a tool (see "Tool Use and Function Calling") |
Example: The Checkpoint Script
from typing import Literal
from pydantic import BaseModel
from model_api import ModelClient
class QuestionInfo(BaseModel):
category: Literal["fees", "admission", "timetable", "other"]
short_answer: str
needs_staff: bool
SYSTEM = (
"You are Campus Helper, a school assistant. Use only these facts. "
"Fees: lab $45, due September 30; field trip $30, due October 15. "
"Spring term starts January 12. Admission forms are due March 1. "
"If the facts don't answer the question, say so and set needs_staff to true."
)
client = ModelClient()
for question in ["When does spring term start?", "Can my daughter get a fee waiver?"]:
info, reply = client.parse(
[{"role": "user", "content": question}], QuestionInfo, system=SYSTEM, max_tokens=1000
)
if info is None: # cut off or not valid JSON: never use a missing result
print("No valid answer; finish reason:", reply.finish_reason)
continue
print(question)
print(" Answer:", info.short_answer)
print(" JSON:", info.model_dump_json())Example output. The answers were produced by an AI model on November 16, 2026, to show the shape; this code wasn't run against a live API for the lesson. The script itself ran end to end against a local test server that returned these replies.
When does spring term start?
Answer: Spring term starts on January 12.
JSON: {"category":"timetable","short_answer":"Spring term starts on January 12.","needs_staff":false}
Can my daughter get a fee waiver?
Answer: The fee facts don't cover waivers. Please contact the school office.
JSON: {"category":"fees","short_answer":"The fee facts don't cover waivers. Please contact the school office.","needs_staff":true}Explanation: The QuestionInfo class is the schema: category may only be one of four values, and needs_staff must be true or false. The helper's parse() sends that schema as response_format, and providers that support it constrain the reply to match it. The helper then checks the JSON with Pydantic and returns a QuestionInfo object, so info.category is safe to use. If the reply was cut off or isn't valid JSON for the schema, info is None, which the code checks before using it.
Designing a Good Schema
Keep schemas small and specific: only the fields your code uses, with fixed values wherever the code makes a decision.
Common Mistakes
Parsing free text with string matching. Use a schema and a parser instead.
Trusting the values because the format is valid. Valid JSON can still contain a wrong category.
Skipping the None check. A cut-off reply has no valid result.
Interview Corner
How do you get reliable JSON from a model?
Define a schema and send it with the request (structured output), then validate the result in code, for example with Pydantic, before using it. Validate even when the provider enforces the schema.
Does a schema make the output correct?
No. It guarantees the format, not the facts. You still test the values on real examples and keep a person in the loop where mistakes matter.
Practice
Exercise: extend the checkpoint. Add a language field (Literal["English", "Spanish", "other"]) and test the script with a question in Spanish. Then send questions with needs_staff true to a list called office_queue and print it.
Check your understanding:
- What does a schema define?
- What does the helper's
parse()return? - Why check for
None?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Define a schema | class Info(BaseModel): ... |
| Fixed values | Literal["a", "b"] |
| Call | info, reply = client.parse(messages, Info, system=...) |
| Result | info (or None) |
| To JSON | info.model_dump_json() |
Was this tutorial helpful?