Structured output

Program sends the schema

Field names, types and allowed values

Model outputs as expected

JSON object that matches the schema

Program processes the object

JSON response is known in advance

Introduction

Many applications need to process the generated output by large language models (LLMs) according to their application scenarios. The default output format of LLMs is plain text, which is challenging for applications to process.

Structural outputs address this problem. It constrains the LLMs' output to a predefined JSON schema by developers. The LLMs will follow the schema to produce outputs at their best efforts. It is still the developers' responsibility to validate the outputs to assure the robustness of programs.

To learn more about structural outputs, please visit https://developers.openai.com/api/docs/guides/structured-outputs for more details.

Interaction model

Scaffold code

A schema specifying the field expecting from LLMs with detailed requirements.

structured_output_scaffold.py
python
SCHEMA = {
    "type": "object",
    "properties": {
        "required_field": {
            "type": "string",
            "description": "The model must provide this.",
        },
        "optional_field": {
            "type": ["string", "null"],
            "description": "The model sends null when it has nothing to put here.",
        },
    },
    "required": ["required_field", "optional_field"],
    "additionalProperties": False,
}

response_format = {
    "type": "json_schema",
    "json_schema": {
        "name": "result_name",
        "strict": True,
        "schema": SCHEMA,
    },
}

client.chat.completions.create(
    model="gpt-4.1-mini",
    messages=[{"role": "user", "content": message}],
    response_format=response_format
)

name is the label for this schema. strict requires the model to follow it. required is a field list that the model must provide. properties specifies the fields in detail.

On chat completions API, you set response_format to json_schema and turn on strict. The answer arrives as message.content, a JSON string. json.loads turns it into a dict.

Note that on response API, the usage is a bit different. Please refer to the official documentation for how to use.

Code example

Type a prompt in natural language and then inspect the internal process.

structured_output.py
python
"""Read a conversion request into a fixed JSON shape."""

import json
from openai import OpenAI

client = OpenAI()

SCHEMA = {
    "type": "object",
    "properties": {
        "kind": {
            "type": "string",
            "enum": ["temperature", "distance"],
            "description": "Which conversion the user asked for.",
        },
        "value": {
            "type": "number",
            "description": "The number to convert.",
        },
        "to": {
            "type": "string",
            "enum": ["celsius", "fahrenheit", "km", "miles"],
            "description": "The unit to convert into.",
        },
    },
    "required": ["kind", "value", "to"],
    "additionalProperties": False,
}

def convert(data: dict) -> str:
    value = data["value"]
    to = data["to"]
    if data["kind"] == "temperature":
        result = value * 9 / 5 + 32 if to == "fahrenheit" else (value - 32) * 5 / 9
        return f"{result:.1f}"
    result = value * 1.609344 if to == "km" else value / 1.609344
    return f"{result:.2f}"

def read_request(question: str) -> dict:
    response = client.chat.completions.create(
        model="gpt-4.1-mini",
        messages=[{"role": "user", "content": question}],
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "conversion",
                "strict": True,
                "schema": SCHEMA,
            },
        },
    )
    return json.loads(response.choices[0].message.content)

if __name__ == "__main__":
    data = read_request("Convert 100F to C")
    print(data)
    print(convert(data))
Prompt in the program
Program
Convert 100F to C
How many km is a 10 mile run?
What is 0 degrees Celsius in Fahrenheit?
Program sends the schema
Program
The model generates the JSON object
Model
Program processes the fields
Program
The answer computed from JSON object
Program