Structured Output and JSON

Updated · 6 min read
mediumPython 3.13aiapipythonjsonstructured-output

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

Text for people, JSON for code

Ways to Get JSON

MethodDescription
Ask in the promptIt is used for quick tests; the model usually complies, but nothing guarantees it
response_format with a JSON schemaIt 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 modelIt is used to send the schema and get back a validated Python object, in one step
Strict tool inputIt is used when the JSON is the input to a tool (see "Tool Use and Function Calling")

Example: The Checkpoint Script

Python
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.

Output
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:

  1. What does a schema define?
  2. What does the helper's parse() return?
  3. Why check for None?

Quick check: structured output

4 questions
1When is structured output most useful?
2What does Literal["fees", "admission", "timetable", "other"] do?
3What does a valid schema guarantee?
4When does parse() return None for the object?

Key Takeaways

Quick reference

NeedCode
Define a schemaclass Info(BaseModel): ...
Fixed valuesLiteral["a", "b"]
Callinfo, reply = client.parse(messages, Info, system=...)
Resultinfo (or None)
To JSONinfo.model_dump_json()

Was this tutorial helpful?

Lesson 86 of 186