Output strutturati

Gli output strutturati fanno in modo che un modello segua una definizione di schema JSON specificata come parte della chiamata API di inferenza. Sia l'API Completamento chat che l'API Risposte supportano output strutturati. Per Chat Completions, definisci lo schema in response_format. Per le risposte, definire lo schema in text.format. Questo approccio si contrappone alla vecchia funzionalità JSON mode, che garantiva JSON valido ma non poteva assicurare una stretta aderenza allo schema fornito. Usare output strutturati per chiamare funzioni, estrarre dati strutturati e creare flussi di lavoro complessi in più passaggi.

Per iniziare

È possibile usare Pydantic per definire gli schemi degli oggetti in Python. A seconda della versione delle Pydantic in esecuzione, potrebbe essere necessario eseguire l'aggiornamento a una versione più recente. Questi esempi sono stati testati su openai 1.42.0 e pydantic 2.8.2.

pip install openai pydantic azure-identity --upgrade

Se sei nuovo nell'utilizzo di Microsoft Entra ID per l'autenticazione, consulta Come configurare Azure OpenAI nei modelli Microsoft Foundry con autenticazione Microsoft Entra ID.

from pydantic import BaseModel
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider

token_provider = get_bearer_token_provider(
    DefaultAzureCredential(), "https://ai.azure.com/.default"
)

client = OpenAI(  
  base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",  
  api_key=token_provider,
)

class CalendarEvent(BaseModel):
    name: str
    date: str
    participants: list[str]

completion = client.beta.chat.completions.parse(
    model="MODEL_DEPLOYMENT_NAME", # replace with the model deployment name of your gpt-4o 2024-08-06 deployment
    messages=[
        {"role": "system", "content": "Extract the event information."},
        {"role": "user", "content": "Alice and Bob are going to a science fair on Friday."},
    ],
    response_format=CalendarEvent,
)

event = completion.choices[0].message.parsed

print(event)
print(completion.model_dump_json(indent=2))

Output

name='Science Fair' date='Friday' participants=['Alice', 'Bob']
{
  "id": "chatcmpl-A1EUP2fAmL4SeB1lVMinwM7I2vcqG",
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "{\n  \"name\": \"Science Fair\",\n  \"date\": \"Friday\",\n  \"participants\": [\"Alice\", \"Bob\"]\n}",
        "refusal": null,
        "role": "assistant",
        "function_call": null,
        "tool_calls": [],
        "parsed": {
          "name": "Science Fair",
          "date": "Friday",
          "participants": [
            "Alice",
            "Bob"
          ]
        }
      }
    }
  ],
  "created": 1724857389,
  "model": "gpt-4o-2024-08-06",
  "object": "chat.completion",
  "service_tier": null,
  "system_fingerprint": "fp_1c2eaec9fe",
  "usage": {
    "completion_tokens": 27,
    "prompt_tokens": 32,
    "total_tokens": 59
  }
}

Usare output strutturati con l'API Risposte

Per l'API Risposte, usare OpenAI Python 2.x e passare un modello Pydantic a responses.parse usando il text_format parametro . L'SDK converte il modello in uno schema JSON in text.format e restituisce il valore analizzato in output_parsed.

from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import OpenAI
from pydantic import BaseModel

# Configure access.
endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
token_provider = get_bearer_token_provider(
    DefaultAzureCredential(), "https://ai.azure.com/.default"
)
openai = OpenAI(base_url=endpoint, api_key=token_provider)

# Define the structured response.
class CalendarEvent(BaseModel):
    name: str
    date: str
    participants: list[str]

# Parse the response directly into the Pydantic model.
response = openai.responses.parse(
    model="gpt-5-mini",
  input="Extract the event information from: Alice and Bob are going to a science fair on Friday.",
    text_format=CalendarEvent,
)

print(response.output_parsed)

Output:

name='Science Fair' date='Friday' participants=['Alice', 'Bob']

Chiamata di funzioni con output strutturati

Gli output strutturati per le chiamate di funzione possono essere abilitati con un singolo parametro, specificando strict: true.

Nota

Gli output strutturati non sono supportati con chiamate di funzione parallele. Quando si usano output strutturati, impostare parallel_tool_calls su false.

import openai
from pydantic import BaseModel
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider

token_provider = get_bearer_token_provider(
    DefaultAzureCredential(), "https://ai.azure.com/.default"
)

client = OpenAI(  
  base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",  
  api_key=token_provider,
)

class GetDeliveryDate(BaseModel):
    order_id: str

tools = [openai.pydantic_function_tool(GetDeliveryDate)]

messages = []
messages.append({"role": "system", "content": "You are a helpful customer support assistant. Use the supplied tools to assist the user."})
messages.append({"role": "user", "content": "Hi, can you tell me the delivery date for my order #12345?"}) 

response = client.chat.completions.create(
    model="MODEL_DEPLOYMENT_NAME", # replace with the model deployment name of your gpt-4o 2024-08-06 deployment
    messages=messages,
    tools=tools
)

print(response.choices[0].message.tool_calls[0].function)
print(response.model_dump_json(indent=2))

Per iniziare

Aggiungere i pacchetti seguenti al progetto:

  • OpenAI: libreria .NET OpenAI standard.
  • Azure. Identity: fornisce supporto per l'autenticazione dei token di Microsoft Entra ID nelle librerie Azure SDK.
dotnet add package OpenAI
dotnet add package Azure.Identity

Se non si ha familiarità con l'uso di Microsoft Entra ID per l'autenticazione, vedere Come configurare Azure OpenAI nei modelli Microsoft Foundry con autenticazione Microsoft Entra ID.

using Azure.Identity;
using OpenAI;
using OpenAI.Chat;
using System.ClientModel.Primitives;
using System.Text.Json;

#pragma warning disable OPENAI001

BearerTokenPolicy tokenPolicy = new(
    new DefaultAzureCredential(),
    "https://ai.azure.com/.default");

ChatClient client = new(
    model: "gpt-4.1",
    authenticationPolicy: tokenPolicy,
    options: new OpenAIClientOptions()
    {
        Endpoint = new Uri("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1")
    }
);

ChatCompletionOptions options = new()
{
    ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat(
        jsonSchemaFormatName: "math_reasoning",
        jsonSchema: BinaryData.FromBytes("""
            {
                "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
            }
            """u8.ToArray()),
        jsonSchemaIsStrict: true)
};

// Create a list of ChatMessage objects
ChatCompletion completion = client.CompleteChat(
    [
        new UserChatMessage("How can I solve 8x + 7 = -23?")
    ],
    options);

using JsonDocument structuredJson = JsonDocument.Parse(completion.Content[0].Text);

Console.WriteLine($"Final answer: {structuredJson.RootElement.GetProperty("final_answer")}");
Console.WriteLine("Reasoning steps:");

foreach (JsonElement stepElement in structuredJson.RootElement.GetProperty("steps").EnumerateArray())
{
    Console.WriteLine($"  - Explanation: {stepElement.GetProperty("explanation")}");
    Console.WriteLine($"    Output: {stepElement.GetProperty("output")}");
}

Usare output strutturati con l'API Risposte

L'API risposte .NET supporta la configurazione della richiesta dello schema JSON. Restituisce il risultato strutturato come testo JSON anziché deserializzarlo automaticamente in un tipo di .NET.

Creare un file denominato calendar-event-schema.json con lo schema:

{
    "type": "object",
    "properties": {
        "name": { "type": "string" },
        "date": { "type": "string" },
        "participants": {
            "type": "array",
            "items": { "type": "string" }
        }
    },
    "required": ["name", "date", "participants"],
    "additionalProperties": false
}

Passare lo schema a ResponseTextFormat.CreateJsonSchemaFormate leggere il codice JSON da GetOutputText:

#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;

// Create a client that uses Microsoft Entra ID.
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
ResponsesClient openAIClient = new(
    authenticationPolicy: new BearerTokenPolicy(
        new DefaultAzureCredential(), "https://ai.azure.com/.default"),
    options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });

// Configure and send the structured-output request.
BinaryData calendarEventSchema = BinaryData.FromString(
    File.ReadAllText("calendar-event-schema.json"));
CreateResponseOptions options = new()
{
    Model = "gpt-5-mini",
    InputItems = { ResponseItem.CreateUserMessageItem(
        "Extract event information from: Alice and Bob are going to a science fair on Friday.") },
    TextOptions = new ResponseTextOptions
    {
        TextFormat = ResponseTextFormat.CreateJsonSchemaFormat(
            "CalendarEventResponse", calendarEventSchema,
            jsonSchemaIsStrict: true)
    }
};

ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());

Output:

{"name":"Science Fair","date":"Friday","participants":["Alice","Bob"]}

Prerequisiti

  • Una sottoscrizione di Azure.
  • Una risorsa Azure OpenAI con una distribuzione di un modello gpt-5-mini. Per creare una risorsa e distribuire un modello, vedere Creare una risorsa e distribuire un modello con Azure OpenAI.
  • Il tuo endpoint Azure OpenAI v1, ad esempio https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/.
  • Per l'autenticazione Microsoft Entra ID, un'identità con ruolo Cognitive Services OpenAI User assegnato alla risorsa Azure OpenAI. Installare il interfaccia della riga di comando di Azure e quindi eseguire az login.
  • Per l'autenticazione tramite chiave API, una chiave della risorsa Azure OpenAI archiviata nella variabile di ambiente AZURE_OPENAI_API_KEY.

Configurazione

Gli esempi richiedono Node.js 22 o versione successiva. Creare un progetto, configurare i moduli ECMAScript e installare i pacchetti OpenAI, Zod e Azure Identity:

npm init --yes
npm pkg set type=module
npm install openai zod @azure/identity
npm install --save-dev typescript tsx @types/node

Per TypeScript, salvare ogni esempio come structured-outputs.tse quindi eseguirlo:

npx tsx structured-outputs.ts

Per JavaScript, salvare ogni esempio come structured-outputs.mjse quindi eseguirlo:

node structured-outputs.mjs

Usa output strutturati con Chat Completions

Definire la struttura di output con Zod. L'helper zodResponseFormat converte l'oggetto Zod in uno schema JSON rigoroso e convalida la risposta del modello. Tutte le proprietà in un oggetto Zod sono obbligatorie, a meno che non si definisca un'unione nullable.

import {
  DefaultAzureCredential,
  getBearerTokenProvider,
} from "@azure/identity";
import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod/v4";

const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
const tokenProvider = getBearerTokenProvider(
  new DefaultAzureCredential(),
  "https://ai.azure.com/.default",
);
const openai = new OpenAI({ baseURL: endpoint, apiKey: tokenProvider });
const CalendarEvent = z.object({
  name: z.string(),
  date: z.string(),
  participants: z.array(z.string()),
});

const completion = await openai.chat.completions.parse({
  model: "gpt-5-mini",
  messages: [
    { role: "system", content: "Extract the event information." },
    {
      role: "user",
      content: "Alice and Bob are going to a science fair on Friday.",
    },
  ],
  response_format: zodResponseFormat(CalendarEvent, "calendar_event"),
});
const message = completion.choices[0]?.message;
if (message?.refusal) throw new Error(`Request refused: ${message.refusal}`);
if (!message?.parsed) throw new Error("The response wasn't parsed.");
console.log(message.parsed);

L'output è simile al seguente:

{
  name: 'Science Fair',
  date: 'Friday',
  participants: [ 'Alice', 'Bob' ]
}

Usare output strutturati con l'API Risposte

Per l'API Risposte, passare il risultato di zodTextFormat in text.format. Il valore ottenuto dall’analisi è disponibile tramite output_parsed dopo il completamento della risposta.

import {
  DefaultAzureCredential,
  getBearerTokenProvider,
} from "@azure/identity";
import OpenAI from "openai";
import { zodTextFormat } from "openai/helpers/zod";
import { z } from "zod/v4";

const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
const tokenProvider = getBearerTokenProvider(
  new DefaultAzureCredential(),
  "https://ai.azure.com/.default",
);
const openai = new OpenAI({ baseURL: endpoint, apiKey: tokenProvider });
const CalendarEvent = z.object({
  name: z.string(),
  date: z.string(),
  participants: z.array(z.string()),
});

const response = await openai.responses.parse({
  model: "gpt-5-mini",
  input:
    "Extract the event information: Alice and Bob are going to a science " +
    "fair on Friday.",
  text: { format: zodTextFormat(CalendarEvent, "calendar_event") },
});
if (response.status !== "completed") {
  const details = response.error ?? response.incomplete_details;
  throw new Error(JSON.stringify(details));
}
const refusal = response.output
  .flatMap((item) => item.type === "message" ? item.content : [])
  .find((content) => content.type === "refusal");
if (refusal) throw new Error(`Request refused: ${refusal.refusal}`);
if (!response.output_parsed) throw new Error("The response wasn't parsed.");
console.log(response.output_parsed);

L'output è simile al seguente:

{
  name: 'Science Fair',
  date: 'Friday',
  participants: [ 'Alice', 'Bob' ]
}

Usare output strutturati per la chiamata di funzioni

Utilizzare zodFunction per creare uno strumento di funzione rigoroso e analizzarne gli argomenti. Azure OpenAI non supporta le chiamate di funzione parallele con output strutturati, quindi imposta parallel_tool_calls su false.

import {
  DefaultAzureCredential,
  getBearerTokenProvider,
} from "@azure/identity";
import OpenAI from "openai";
import { zodFunction } from "openai/helpers/zod";
import { z } from "zod/v4";

const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
const tokenProvider = getBearerTokenProvider(
  new DefaultAzureCredential(),
  "https://ai.azure.com/.default",
);
const openai = new OpenAI({ baseURL: endpoint, apiKey: tokenProvider });
const DeliveryRequest = z.object({ order_id: z.string() });

const completion = await openai.chat.completions.parse({
  model: "gpt-5-mini",
  messages: [
    { role: "system", content: "Use the supplied tool to help the user." },
    { role: "user", content: "When will order 12345 be delivered?" },
  ],
  tools: [zodFunction({
    name: "get_delivery_date",
    description: "Get the delivery date for an order.",
    parameters: DeliveryRequest,
  })],
  parallel_tool_calls: false,
});
const toolCall = completion.choices[0]?.message.tool_calls?.[0];
if (toolCall?.type !== "function") {
  throw new Error("No function call returned.");
}
console.log(toolCall.function.parsed_arguments);

L'output è simile al seguente:

{ order_id: '12345' }

Per le forme di richiesta sottostanti senza Zod, usare gli esempi di schema JSON nell'opzione del linguaggio REST.

Per iniziare

response_format è impostato su json_schema con strict: true impostato.

curl -X POST  https://YOUR_RESOURCE_NAME.openai.azure.com/openai/v1/chat/completions \
  -H "api-key: $AZURE_OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
    -d '{
        "model": "YOUR_MODEL_DEPLOYMENT_NAME",
        "messages": [
                {"role": "system", "content": "Extract the event information."},
                {"role": "user", "content": "Alice and Bob are going to a science fair on Friday."}
            ],
            "response_format": {
                "type": "json_schema",
                "json_schema": {
                    "name": "CalendarEventResponse",
                    "strict": true,
                    "schema": {
                        "type": "object",
                        "properties": {
                            "name": {
                              "type": "string"
                            },
                            "date": {
                                "type": "string"
                            },
                            "participants": {
                                "type": "array",
                                "items": {
                                    "type": "string"
                                }
                            }
                        },
                        "required": [
                            "name",
                            "date",
                            "participants"
                        ],
                        "additionalProperties": false
                    }
                }
          }
  }'

Output:

{
  "id": "chatcmpl-A1HKsHAe2hH9MEooYslRn9UmEwsag",
  "object": "chat.completion",
  "created": 1724868330,
  "model": "gpt-4o-2024-08-06",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "{\n  \"name\": \"Science Fair\",\n  \"date\": \"Friday\",\n  \"participants\": [\"Alice\", \"Bob\"]\n}"
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 33,
    "completion_tokens": 27,
    "total_tokens": 60
  },
  "system_fingerprint": "fp_1c2eaec9fe"
}

Usare output strutturati con l'API Risposte

Per l'API Responses, definire lo schema JSON sotto text.format. Impostare type, nameschema, e strict come proprietà di pari livello di format. Prima di eseguire la richiesta, impostare AZURE_OPENAI_AUTH_TOKEN su un token di accesso di Microsoft Entra ID.

curl -X POST https://YOUR_RESOURCE_NAME.openai.azure.com/openai/v1/responses \
  -H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5-mini",
    "input": "Extract the event information from: Alice and Bob are going to a science fair on Friday.",
    "text": {
      "format": {
        "type": "json_schema",
        "name": "CalendarEventResponse",
        "schema": {
          "type": "object",
          "properties": {
            "name": {"type": "string"},
            "date": {"type": "string"},
            "participants": {
              "type": "array",
              "items": {"type": "string"}
            }
          },
          "required": ["name", "date", "participants"],
          "additionalProperties": false
        },
        "strict": true
      }
    }
  }'

Il output_text contenuto contiene:

{
  "name": "Science Fair",
  "date": "Friday",
  "participants": ["Alice", "Bob"]
}

Chiamata di funzioni con output strutturati

curl -X POST  https://YOUR_RESOURCE_NAME.openai.azure.com/openai/v1/chat/completions \
  -H "api-key: $AZURE_OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "YOUR_MODEL_DEPLOYMENT_NAME",
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful assistant. The current date is August 6, 2024. You help users query for the data they are looking for by calling the query function."
    },
    {
      "role": "user",
      "content": "look up all my orders in may of last year that were fulfilled but not delivered on time"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "query",
        "description": "Execute a query.",
        "strict": true,
        "parameters": {
          "type": "object",
          "properties": {
            "table_name": {
              "type": "string",
              "enum": ["orders"]
            },
            "columns": {
              "type": "array",
              "items": {
                "type": "string",
                "enum": [
                  "id",
                  "status",
                  "expected_delivery_date",
                  "delivered_at",
                  "shipped_at",
                  "ordered_at",
                  "canceled_at"
                ]
              }
            },
            "conditions": {
              "type": "array",
              "items": {
                "type": "object",
                "properties": {
                  "column": {
                    "type": "string"
                  },
                  "operator": {
                    "type": "string",
                    "enum": ["=", ">", "<", ">=", "<=", "!="]
                  },
                  "value": {
                    "anyOf": [
                      {
                        "type": "string"
                      },
                      {
                        "type": "number"
                      },
                      {
                        "type": "object",
                        "properties": {
                          "column_name": {
                            "type": "string"
                          }
                        },
                        "required": ["column_name"],
                        "additionalProperties": false
                      }
                    ]
                  }
                },
                "required": ["column", "operator", "value"],
                "additionalProperties": false
              }
            },
            "order_by": {
              "type": "string",
              "enum": ["asc", "desc"]
            }
          },
          "required": ["table_name", "columns", "conditions", "order_by"],
          "additionalProperties": false
        }
      }
    }
  ]
}'

Supporto e limitazioni dello schema JSON

Gli output strutturati di Azure OpenAI supportano un sottoinsieme di JSON Schema. I seguenti limiti specifici di Azure e le parole chiave non supportate si applicano sia all'API Chat Completions sia all'API Responses.

Tipi supportati

  • Stringa
  • Numero
  • Boolean
  • Intero
  • Oggetto
  • Array
  • Enum
  • anyOf

Nota

Gli oggetti radice non possono essere il anyOf tipo.

Tutti i campi devono essere obbligatori

Includere tutti i campi o i parametri di funzione in base alle esigenze. Nell'esempio seguente, entrambi location e unit vengono visualizzati in "required": ["location", "unit"].

{
    "name": "get_weather",
    "description": "Fetches the weather in the given location",
    "strict": true,
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The location to get the weather for"
            },
            "unit": {
                "type": "string",
                "description": "The unit to return the temperature in",
                "enum": ["F", "C"]
            }
        },
        "additionalProperties": false,
        "required": ["location", "unit"]
    }
}

Se necessario, è possibile emulare un parametro facoltativo usando un tipo di unione con null. In questo esempio questo approccio è rappresentato dalla riga "type": ["string", "null"],.

{
    "name": "get_weather",
    "description": "Fetches the weather in the given location",
    "strict": true,
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The location to get the weather for"
            },
            "unit": {
                "type": ["string", "null"],
                "description": "The unit to return the temperature in",
                "enum": ["F", "C"]
            }
        },
        "additionalProperties": false,
        "required": [
            "location", "unit"
        ]
    }
}

Profondità di annidamento

Uno schema può avere fino a 100 proprietà oggetto totali, con un massimo di cinque livelli di annidamento.

Impostare sempre additionalProperties: false negli oggetti

Questa proprietà controlla se un oggetto può avere altre coppie chiave-valore non definite nello schema JSON. Per usare output strutturati, impostare questo valore su false.

Ordinamento delle chiavi

Gli output strutturati seguono lo stesso ordine dello schema fornito. Per modificare l'ordine di output, modificare l'ordine dello schema inviato come parte della richiesta di inferenza.

Parole chiave specifiche del tipo non supportate

Digitare Parola chiave non supportata
Stringa minlength
maxLength
Schema
Formato
Numero Minimo
Massimo
multipleOf
Oggetti patternProperties
proprietà non valutate
propertyNames
minProperties
maxProperties
Matrici elementi non valutati
Contiene
minContains
maxContains
minItems
maxItems
elementi unici

Gli schemi annidati che usano anyOf devono rispettare il subset complessivo dello schema JSON

Schema di esempio supportato anyOf

{
    "type": "object",
    "properties": {
        "item": {
            "anyOf": [
                {
                    "type": "object",
                    "description": "The user object to insert into the database",
                    "properties": {
                        "name": {
                            "type": "string",
                            "description": "The name of the user"
                        },
                        "age": {
                            "type": "number",
                            "description": "The age of the user"
                        }
                    },
                    "additionalProperties": false,
                    "required": [
                        "name",
                        "age"
                    ]
                },
                {
                    "type": "object",
                    "description": "The address object to insert into the database",
                    "properties": {
                        "number": {
                            "type": "string",
                            "description": "The number of the address. Eg. for 123 main st, this would be 123"
                        },
                        "street": {
                            "type": "string",
                            "description": "The street name. Eg. for 123 main st, this would be main st"
                        },
                        "city": {
                            "type": "string",
                            "description": "The city of the address"
                        }
                    },
                    "additionalProperties": false,
                    "required": [
                        "number",
                        "street",
                        "city"
                    ]
                }
            ]
        }
    },
    "additionalProperties": false,
    "required": [
        "item"
    ]
}

Le definizioni sono supportate

Esempio supportato:

{
    "type": "object",
    "properties": {
        "steps": {
            "type": "array",
            "items": {
                "$ref": "#/$defs/step"
            }
        },
        "final_answer": {
            "type": "string"
        }
    },
    "$defs": {
        "step": {
            "type": "object",
            "properties": {
                "explanation": {
                    "type": "string"
                },
                "output": {
                    "type": "string"
                }
            },
            "required": [
                "explanation",
                "output"
            ],
            "additionalProperties": false
        }
    },
    "required": [
        "steps",
        "final_answer"
    ],
    "additionalProperties": false
}

Gli schemi ricorsivi sono supportati

Esempio di utilizzo # per la ricorsione radice:

{
        "name": "ui",
        "description": "Dynamically generated UI",
        "strict": true,
        "schema": {
            "type": "object",
            "properties": {
                "type": {
                    "type": "string",
                    "description": "The type of the UI component",
                    "enum": ["div", "button", "header", "section", "field", "form"]
                },
                "label": {
                    "type": "string",
                    "description": "The label of the UI component, used for buttons or form fields"
                },
                "children": {
                    "type": "array",
                    "description": "Nested UI components",
                    "items": {
                        "$ref": "#"
                    }
                },
                "attributes": {
                    "type": "array",
                    "description": "Arbitrary attributes for the UI component, suitable for any element",
                    "items": {
                        "type": "object",
                        "properties": {
                            "name": {
                                "type": "string",
                                "description": "The name of the attribute, for example onClick or className"
                            },
                            "value": {
                                "type": "string",
                                "description": "The value of the attribute"
                            }
                        },
                      "additionalProperties": false,
                      "required": ["name", "value"]
                    }
                }
            },
            "required": ["type", "label", "children", "attributes"],
            "additionalProperties": false
        }
    }

Esempio di ricorsione esplicita:

{
    "type": "object",
    "properties": {
        "linked_list": {
            "$ref": "#/$defs/linked_list_node"
        }
    },
    "$defs": {
        "linked_list_node": {
            "type": "object",
            "properties": {
                "value": {
                    "type": "number"
                },
                "next": {
                    "anyOf": [
                        {
                            "$ref": "#/$defs/linked_list_node"
                        },
                        {
                            "type": "null"
                        }
                    ]
                }
            },
            "additionalProperties": false,
            "required": [
                "next",
                "value"
            ]
        }
    },
    "additionalProperties": false,
    "required": [
        "linked_list"
    ]
}

Nota

Attualmente, gli output strutturati non sono supportati con:

Modelli supportati

  • gpt-5.1-codex Versione: 2025-11-13
  • gpt-5.1-codex mini Versione: 2025-11-13
  • gpt-5.1 Versione: 2025-11-13
  • gpt-5.1-chat Versione: 2025-11-13
  • gpt-5-pro Versione 2025-10-06
  • gpt-5-codex Versione 2025-09-11
  • gpt-5 Versione 2025-08-07
  • gpt-5-mini Versione 2025-08-07
  • gpt-5-nano Versione 2025-08-07
  • codex-mini Versione 2025-05-16
  • o3-pro Versione 2025-06-10
  • o3-mini Versione 2025-01-31
  • o1 Versione: 2024-12-17
  • gpt-4o-mini Versione: 2024-07-18
  • gpt-4o Versione: 2024-08-06
  • gpt-4o Versione: 2024-11-20
  • gpt-4.1 Versione 2025-04-14
  • gpt-4.1-nano Versione 2025-04-14
  • gpt-4.1-mini Versione: 2025-04-14
  • o4-mini Versione: 2025-04-16
  • o3 Versione: 2025-04-16

Supporto API

La versione 2024-08-01-preview dell'API è la prima versione che supporta output strutturati. Le API di anteprima più recenti e l'API GA più recente, v1, supportano anche output strutturati.