Skip to content
AgenticAIWiki
  1. Learn
  2. Part 2
  3. 14. Structured output
  4. 14.1

Lesson 14.1 · 1 of 8 · 5 min read · Reviewed 24 Nov 2026

JSON schemas for output

By the end, you can

  • Describe output with a JSON schema.
  • Design schemas that are easy for the model to fill correctly.

A JSON schema is a precise contract for the output.

{
  "type": "object",
  "properties": {
    "customer_name": {"type": "string"},
    "priority": {"type": "string", "enum": ["low", "medium", "high"]},
    "order_id": {"type": ["string", "null"], "description": "Null if no order ID appears"},
    "items": {"type": "array", "items": {"type": "string"}}
  },
  "required": ["customer_name", "priority", "order_id", "items"]
}

Design tips

  • Enums for fixed choices.
  • Descriptions on fields whose meaning isn’t obvious, including what to do when the value is missing.
  • Clear names: invoice_total_usd beats amount.
  • Keep it flat where you can. Deep nesting raises the error rate.
  • Required plus nullable for fields that may be absent (14.3).

Where schemas go

You can give the schema in three ways, from weakest to strongest:

  1. In the prompt as text. The model usually follows it.
  2. As a tool’s input_schema (14.6).
  3. With the API’s structured outputsStructured outputs: Making a model return data that matches a defined schema, such as JSON with required fields and types. feature, which constrains the reply to the schema on supported models.

Validate in code either way (14.4).

Key points

  • A JSON schema states the fields, their types, which are required and which values are allowed.
  • Enums for fixed choices stop the model inventing labels.
  • Flat, clearly named fields are filled more reliably than deep nesting.
Hands-on labRuns in the Playground

Tighten a loose schema and test it

Rewrite a loose output schema with enums, clear names and required fields, and check outputs against it in code.

You will have: A tight JSON schema and a small stdlib validator that reports every problem in three sample outputs.

Steps

  1. Read the loose schema and the three sample outputs in the starter.
  2. Fill in SCHEMA: an enum for priority, a clearly named total field, and every field listed in required.
  3. Complete validate so it checks required keys, types and enum values, returning a list of error strings.
  4. Run it and confirm the good sample passes and each bad sample gets a specific error.

Done when

  • Sample A passes with no errors.
  • Sample B fails with an error naming priority and its bad value 'moderate'.
  • Sample C fails with an error naming the missing field.
  • The script prints 'A: ok'.

Open in the Playground No API key needed.

Starter code (Python)
TYPES = {"string": str, "number": (int, float), "array": list}

SCHEMA = {
    "type": "object",
    "properties": {
        # TODO: customer_name (string), priority (string enum low/medium/high),
        # invoice_total_gbp (number), items (array)
    },
    "required": [],  # TODO: list every field
}

SAMPLES = {
    "A": {"customer_name": "Priya Shah", "priority": "high", "invoice_total_gbp": 410.0, "items": ["lid"]},
    "B": {"customer_name": "Tom Reed", "priority": "moderate", "invoice_total_gbp": 99.5, "items": []},
    "C": {"customer_name": "Ana Silva", "priority": "low", "items": ["mug"]},
}

def validate(obj, schema):
    errors = []
    # TODO: for each required key, report it if missing.
    # TODO: for each present property, check its type, and its enum if there is one.
    return errors

for name, obj in SAMPLES.items():
    errs = validate(obj, SCHEMA)
    print(f"{name}: ok" if not errs else f"{name}: " + "; ".join(errs))
Show a solution
TYPES = {"string": str, "number": (int, float), "array": list}

SCHEMA = {
    "type": "object",
    "properties": {
        "customer_name": {"type": "string"},
        "priority": {"type": "string", "enum": ["low", "medium", "high"]},
        "invoice_total_gbp": {"type": "number", "description": "Invoice total in pounds"},
        "items": {"type": "array"},
    },
    "required": ["customer_name", "priority", "invoice_total_gbp", "items"],
}

SAMPLES = {
    "A": {"customer_name": "Priya Shah", "priority": "high", "invoice_total_gbp": 410.0, "items": ["lid"]},
    "B": {"customer_name": "Tom Reed", "priority": "moderate", "invoice_total_gbp": 99.5, "items": []},
    "C": {"customer_name": "Ana Silva", "priority": "low", "items": ["mug"]},
}

def validate(obj, schema):
    errors = []
    for key in schema["required"]:
        if key not in obj:
            errors.append(f"missing required field {key}")
    for key, rule in schema["properties"].items():
        if key not in obj:
            continue
        value = obj[key]
        if not isinstance(value, TYPES[rule["type"]]):
            errors.append(f"{key} should be {rule['type']}")
        if "enum" in rule and value not in rule["enum"]:
            errors.append(f"{key} '{value}' is not one of {rule['enum']}")
    return errors

for name, obj in SAMPLES.items():
    errs = validate(obj, SCHEMA)
    print(f"{name}: ok" if not errs else f"{name}: " + "; ".join(errs))
Quick checkA field should only ever be 'low', 'medium' or 'high'. How should the schema express that?
How sure are you?
Pick an answer and how sure you are