Structured Outputs
Structured Outputs constrains completed, non-refusal model output to your supplied JSON Schema.
Definition · At a glance · How it works
Definition
Structured Outputs constrains completed, non-refusal model output to the JSON Schema you supply. Structured Outputs is the evolution of JSON mode. The documentation lists schema adherence as a benefit: required fields and enum values follow the supported JSON Schema you supply.
It also lists explicit refusals as a benefit: safety-based model refusals are now programmatically detectable. Structured Outputs supports a subset of the JSON Schema language. Structured Outputs is available in the latest large language models, starting with GPT-4o.
At a glance
Both JSON mode and Structured Outputs ensure valid JSON is produced, but JSON mode has some edge cases that you should detect and handle appropriately. Only Structured Outputs ensure schema adherence.
- Structured Outputs: completed, non-refusal model output is constrained to the supplied JSON Schema.
- JSON mode: output is ensured to be valid JSON except in some edge cases that you should detect and handle appropriately. It will not guarantee a match to any specific schema, only that the output is valid and parses without errors.
- Refusal: a refusal does not necessarily follow the schema you supplied in
response_format, so the API response includes a new field calledrefusalto indicate that the model refused the request. - Incomplete response: the model might not generate a valid response that matches the provided JSON schema, for example when a max tokens limit is reached and the response is incomplete.
The source does not state the order of these points, so they are listed without arrows.
How it works
Structured Outputs is available in two forms in the OpenAI API. Function calling is useful when you are building an application that bridges the models and functionality of your application. Conversely, Structured Outputs via response_format are more suitable when you want to indicate a structured schema for use when the model responds to the user, rather than when the model calls a tool.
Structured Outputs only supports generating specified keys and values, so developers are required to set additionalProperties to false to opt into Structured Outputs. Although all fields must be required and the model returns a value for each parameter, an optional parameter can be emulated by using a union type with null. If you turn on Structured Outputs by supplying strict as true and call the API with an unsupported JSON Schema, you will receive an error.
The root level object of a schema must be an object and must not use anyOf. A schema may have up to 5000 object properties in total, with up to 10 levels of nesting. On supported GPT-6 and later models in standard, single-agent mode, you can switch schemas between responses by appending a configuration_update item to input before the next user message.
Keep the original top-level text.format on each request so the earlier prompt prefix stays eligible for prompt caching. The documentation supposes that the previous turn described a shipment with 17 red crates and 26 blue crates in plain text. The expected answer is a total_crates value of 43.
The response object’s text.format still reports the original request-level format. After checking for refusals and incomplete responses, the answer is parsed with the schema from the latest format update. Each format update replaces the whole format.
Example
One documented use is asking the model to output an answer in a structured, step-by-step way, to guide the user through the solution. In addition to supporting JSON Schema in the REST API, the OpenAI libraries for Python and JavaScript also let you define object schemas using pydantic.BaseModel and z.object respectively. First you must define an object or data structure to represent the JSON Schema that the model should be constrained to follow.
You can use the parse method to automatically parse the JSON response into the object you defined. Under the hood, the SDK takes care of supplying the JSON schema corresponding to your data structure, and then parsing the response as an object. In some cases, the model might not generate a valid response that matches the provided JSON schema.
This can happen in the case of a refusal, if the model refuses to answer for safety reasons, or if for example you reach a max tokens limit and the response is incomplete. When the refusal property appears in your output object, you might present the refusal in your UI, or include conditional logic in code that consumes the response to handle the case of a refused request. Your application still needs to handle refusals, incomplete responses, and API errors, and validate business rules that the schema does not express.
from pydantic import BaseModel
from openai import OpenAI
client = OpenAI()
class Step(BaseModel):
explanation: str
output: str
class MathReasoning(BaseModel):
steps: list[Step]
final_answer: str
completion = client.chat.completions.parse(
model="gpt-6.2-astra",
messages=[
{
"role": "system",
"content": "You are a helpful math tutor. Guide the user through the solution step by step.",
},
{"role": "user", "content": "how can I solve 8x + 7 = -23"},
],
response_format=MathReasoning,
)
math_reasoning = completion.choices[0].message.parsed{
"steps": [
{
"explanation": "Start with the equation 8x + 7 = -23.",
"output": "8x + 7 = -23"
},
{
"explanation": "Subtract 7 from both sides to isolate the term with the variable.",
"output": "8x = -23 - 7"
},
{
"explanation": "Simplify the right side of the equation.",
"output": "8x = -30"
},
{
"explanation": "Divide both sides by 8 to solve for x.",
"output": "x = -30 / 8"
},
{
"explanation": "Simplify the fraction.",
"output": "x = -15 / 4"
}
],
"final_answer": "x = -15 / 4"
}try:
response = client.chat.completions.create(
model="gpt-6.2-astra",
messages=[
{
"role": "system",
"content": "You are a helpful math tutor. Guide the user through the solution step by step.",
},
{"role": "user", "content": "how can I solve 8x + 7 = -23"},
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "math_response",
"strict": True,
"schema": {
"type": "object",
"properties": {
"steps": {
"type": "array",
"items": {
"type": "object",
"properties": {
"explanation": {"type": "string"},
"output": {"type": "string"},
},
"required": ["explanation", "output"],
"additionalProperties": False,
},
},
"final_answer": {"type": "string"},
},
"required": ["steps", "final_answer"],
"additionalProperties": False,
},
},
},
max_completion_tokens=1024,
)
if response.choices[0].finish_reason == "length":
raise Exception("Incomplete response")
math_response = response.choices[0].message
if math_response.refusal:
print(math_response.refusal)
elif math_response.content:
print(math_response.content)
else:
raise Exception("No response content")
except Exception as e:
# handle errors like finish_reason, refusal, content_filter, etc.
print(e)Sources
This page is written from the official sources below. Open them to check the original text.
- Official documentationhttps://developers.openai.com/api/docs/guides/structured-outputsFetched
Verified ·
This page is written by AI from the official sources above and checked automatically. This site has not tested it. Found a mistake? Tell us.