Lompat ke konten

Pelajaran 8 ยท Structured Outputs

Structured Outputs with JSON Schema

Get predictable JSON from the OpenAI API with Structured Outputs: text.format with json_schema, strict mode rules, Pydantic parsing and refusals.

Text is great for people and awkward for programs. If you ask for "a list of tasks as JSON," you may get a friendly sentence before the JSON, a missing field, or a date written in three different ways. Structured Outputs solves the shape problem: you give the API a JSON Schema, and the model's output follows it.

You will learn to send a schema, use Pydantic as a shortcut, follow the strict-mode rules, and handle the cases where no valid object comes back.

Send a JSON Schema

A schema describes what a JSON value must look like. In the Responses API, you put it under text.format.

Python
# Read-only
response = client.responses.create(
    model="gpt-6.2-sol",
    input="Turn this into a task: 'Anna must send the Q4 report by Friday.'",
    text={
        "format": {
            "type": "json_schema",
            "name": "task",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "title": {"type": "string"},
                    "owner": {"type": ["string", "null"]},
                    "priority": {"type": "string", "enum": ["low", "normal", "high"]},
                },
                "required": ["title", "owner", "priority"],
                "additionalProperties": False,
            },
        }
    },
)

import json
task = json.loads(response.output_text)

The result is still a string, so you parse it with the json module. Check for problems first, as shown below.

The strict-mode rules

Strict mode accepts a subset of JSON Schema. These rules matter most.

  • The top level must be an object, not a union.
  • Every object needs "additionalProperties": false.
  • Every property must appear in required.
  • To make a value optional, allow null as one of its types, like owner above.

Supported building blocks include strings, numbers, integers, booleans, objects, arrays, enums, anyOf and reusable $defs. Some keywords, such as allOf, not and if / then, are not supported. There are also limits on the size and nesting depth of a schema. Fine-tuned models support fewer keywords. Check the current "supported schemas" section before you design something complex.

Check a schema before you send it

This runnable function finds two common strict-mode mistakes. It is a small helper, not the API's own validator, and it does not cover every rule.

Python Find strict-mode mistakes in a schema

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Fix the nested object in draft and run it again until no problems appear.

Pydantic: define the shape once

If you use Python, the SDK can build the schema from a Pydantic model and give you a typed object back.

Python
# Read-only
from typing import Literal
from pydantic import BaseModel

class Task(BaseModel):
    title: str
    owner: str | None
    priority: Literal["low", "normal", "high"]

response = client.responses.parse(
    model="gpt-6.2-sol",
    input="Anna must send the Q4 report by Friday.",
    text_format=Task,
)

task = response.output_parsed   # a Task instance, when parsing succeeds

In JavaScript, the SDK offers similar helpers that work with schema libraries. Either way, one definition serves both the request and your code.

Design fields the model can fill honestly

A schema forces a shape. It can also force a guess. If owner must be a string and the text names no one, the model has to invent something. Give it an honest way out:

  • Use ["string", "null"] for facts that may be absent.
  • Add an enum value such as "unclear" to a classification.
  • Use clear names and add description text to explain each field.
  • Say in the instructions: use null when the source does not state a value.

Keep schemas small. Ask only for fields your program will use.

When you do not get your object

Two situations need their own code paths.

Refusal. The model may refuse for safety reasons. A refusal does not follow your schema. It appears as a content part with the type refusal.

Incomplete output. If the reply hits the output token limit, the status is incomplete, and the JSON may be cut off.

Python
# Read-only
if response.status == "incomplete":
    raise RuntimeError(response.incomplete_details.reason)

for item in response.output:
    if item.type != "message":
        continue
    for part in item.content:
        if part.type == "refusal":
            print("Refused:", part.refusal)

Your caller should be able to tell these apart from a real result. A function that returns an empty object in every failure case hides problems.

Structured Outputs or JSON mode?

There is also an older JSON mode, set with {"type": "json_object"} as the format. It aims for valid JSON but does not enforce your fields. Use Structured Outputs with a schema whenever the model supports it.

The first request with a new schema can take longer than later ones, because the service processes the schema.

A schema guarantees shape, not truth. A perfectly valid object can hold the wrong date, an invented name or an unsafe value. The next lesson shows how to check meaning.

Tips for schema design

A schema is also a prompt. The model reads your field names and descriptions, so make them say what you mean. A field called delivery_date, with the description "date the customer asks for, as YYYY-MM-DD, or null if not stated", is much clearer than a field called date.

Prefer an enum to free text whenever the possible values are known. It removes spelling variants such as "High," "high priority" and "urgent." Include a catch-all value, such as other or unclear, so unusual input is not forced into the wrong box.

For a list, make it a property of the top-level object, because the root must be an object. For example, use an object with a tasks array rather than a bare array. Remember that an empty list is a valid answer, and say in the instructions when it is expected.

Avoid very deep nesting. Flat structures are easier to read, validate and store. If one request needs a very large schema, consider splitting the work into two simpler requests and testing both.

Finally, keep the schema and the code that consumes it together. A test that builds the schema and runs your strict-mode check can catch a mistake before any paid request is made.

Common mistakes

  • Making every field a required string with no way to say unknown, which invites invented values.
  • Parsing the output before checking for an incomplete status or a refusal.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does a JSON Schema go in a Responses API request?

    The format object has type json_schema, a name, the schema and the strict flag.
  2. 2. How do you express an optional value in strict mode?

    Strict mode requires every property to be listed, so absence is expressed with null.
  3. 3. What does JSON mode guarantee compared with Structured Outputs?

    Only Structured Outputs with a schema enforces the fields.
  4. 4. Which two cases should your code handle besides a normal result?

    A refusal or a cut-off reply will not give you a complete object.

Summary

  • Structured Outputs makes model output follow your JSON Schema.
  • Strict mode needs closed objects with every property required; use null for optional values.
  • responses.parse with a Pydantic model returns typed data.
  • Give the model honest ways to say "unknown."
  • Handle refusals and incomplete output, and remember that valid shape is not correct content.

Next: Validating Structured Results

Progres Anda disimpan di browser ini. Tidak perlu akun.