Structured Outputs constrains completed, non-refusal model output to the JSON Schema you supply, so required fields and enum values follow the schema instead of the model best guess. It is the evolution of JSON mode: both ensure valid JSON is produced, but only Structured Outputs ensures schema adherence. Your application still needs to handle refusals, incomplete responses and API errors, and to validate any business rules the schema does not express.
What you need
- An API client for a model that supports Structured Outputs, starting with GPT-4o
- A JSON Schema for the reply you need
- A parser for the response in your language
Step 1: Write the schema first
Define the object with its properties, types, required fields and any enum values before you write the prompt. A schema written after the prompt usually misses a field the code needs.
Step 2: Pass the schema as the response format
Send the schema as a json_schema response format with strict mode on, so the model is constrained to produce exactly the schema you defined. In the Responses API this is the text.format setting.
Step 3: Parse the typed result and handle the rest
Read the parsed output from the response object. If the response carries a refusal instead, handle it in the UI or in code; a refusal does not follow the schema.
Worked example: synthetic calendar event extraction
The table below is a synthetic example. It shows the expected result of a structured extraction; no API call was made.
| Field | Schema requires | Returned |
|---|---|---|
| name | string, required | Science fair |
| date | string, required | Friday |
| participants | list of strings, required | Alice, Bob |
| Extra fields | None allowed | None |
Expected result (UNTESTED). the reply parses as a calendar event with all three required fields and no extra fields. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- Schema adherence is not truth: a well-formed reply can still hallucinate facts, so verify the values.
- Structured Outputs with a json_schema response format is only supported with gpt-4o-mini, gpt-4o-mini-2024-07-18 and gpt-4o-2024-08-06 snapshots and later; older models may use JSON mode instead.
- Your application still needs to handle refusals, incomplete responses and API errors.
- Keep the schema shallow where you can; deep nesting is harder for the model to fill correctly.
