Hinweis
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, sich anzumelden oder das Verzeichnis zu wechseln.
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, das Verzeichnis zu wechseln.
Strukturierte Ausgaben veranlassen ein Modell, einer JSON-Schema-Definition zu folgen, die Sie als Teil Ihres Inferenz-API-Aufrufs bereitstellen. Sowohl die Api für Chatabschlusse als auch die Antwort-API unterstützen strukturierte Ausgaben. Definieren Sie für Chatabschlusse das Schema in response_format. Definieren Sie für Antworten das Schema in text.format. Dieser Ansatz steht im Gegensatz zu dem älteren JSON-Modus-Feature , das gültige JSON garantiert, aber keine strikte Einhaltung des bereitgestellten Schemas gewährleisten konnte. Verwenden Sie strukturierte Ausgaben für Funktionsaufrufe, Extrahieren strukturierter Daten und Erstellen komplexer mehrstufiger Workflows.
Erste Schritte
Sie können Pydantic verwenden, um Objektschemas in Python zu definieren. Je nachdem, welche Version von OpenAI und Pydantic Bibliotheken Sie ausführen, müssen Sie möglicherweise ein Upgrade auf eine neuere Version durchführen. Diese Beispiele wurden gegen openai 1.42.0 und pydantic 2.8.2 getestet.
pip install openai pydantic azure-identity --upgrade
Wenn Sie noch keine Microsoft Entra ID für die Authentifizierung verwenden, lesen Sie Wie sie Azure OpenAI in Microsoft Foundry Models mit Microsoft Entra ID Authentifizierung konfigurieren.
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))
Ausgabe
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
}
}
Verwenden Sie strukturierte Ausgaben mit der Responses API
Verwenden Sie für die Responses API OpenAI Python 2.x und übergeben Sie ein Pydantic-Modell mithilfe des Parameters text_format an responses.parse. Das SDK konvertiert das Modell in ein JSON-Schema unter text.format und gibt den analysierten Wert 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)
Ausgabe:
name='Science Fair' date='Friday' participants=['Alice', 'Bob']
Funktionsaufrufe mit strukturierten Ausgaben
Strukturierte Ausgaben für Funktionsaufrufe können mit einem einzelnen Parameter aktiviert werden, indem strict: true bereitgestellt wird.
Hinweis
Strukturierte Ausgaben werden bei parallelen Funktionsaufrufen nicht unterstützt. Bei Verwendung von strukturierten Ausgaben setzen Sie parallel_tool_calls auf 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))
Erste Schritte
Fügen Sie ihrem Projekt die folgenden Pakete hinzu:
- OpenAI: Standard OpenAI .NET Library.
- Azure. Identity: Stellt Microsoft Entra ID Unterstützung für die Tokenauthentifizierung in den Azure SDK-Bibliotheken bereit.
dotnet add package OpenAI
dotnet add package Azure.Identity
Wenn Sie noch nicht Microsoft Entra ID für die Authentifizierung verwenden, lesen Sie Wie sie Azure OpenAI in Microsoft Foundry Models mit Microsoft Entra ID Authentifizierung konfigurieren.
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")}");
}
Verwenden Sie strukturierte Ausgaben mit der Responses API
Die .NET Antwort-API unterstützt die JSON-Schemaanforderungskonfiguration. Es gibt das strukturierte Ergebnis als JSON-Text zurück, anstatt es automatisch in einen .NET Typ zu deserialisieren.
Erstellen Sie eine Mit dem Schema benannte calendar-event-schema.json Datei:
{
"type": "object",
"properties": {
"name": { "type": "string" },
"date": { "type": "string" },
"participants": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["name", "date", "participants"],
"additionalProperties": false
}
Übergeben Sie das Schema an ResponseTextFormat.CreateJsonSchemaFormat, und lesen Sie den JSON-Code aus 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());
Ausgabe:
{"name":"Science Fair","date":"Friday","participants":["Alice","Bob"]}
Voraussetzungen
- Ein Azure-Abonnement.
- Eine Azure OpenAI-Ressource mit einer
gpt-5-mini-Modellbereitstellung. Informationen zum Erstellen einer Ressource und Bereitstellen eines Modells finden Sie unter Erstellen einer Ressource und Bereitstellen eines Modells mit Azure OpenAI. - Ihr Azure OpenAI v1-Endpunkt, wie
https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/. - Für die Microsoft Entra ID-Authentifizierung, eine Identität, der für die Azure OpenAI-Ressource die Rolle
Cognitive Services OpenAI Userzugewiesen ist. Installieren Sie die Azure CLI und führen Sie anschließendaz loginaus. - Bei der API-Schlüsselauthentifizierung wird ein in der Umgebungsvariablen
AZURE_OPENAI_API_KEYgespeicherter Azure OpenAI-Ressourcenschlüssel gespeichert.
Einrichten
Die Beispiele erfordern Node.js 22 oder höher. Erstellen Sie ein Projekt, konfigurieren Sie ECMAScript-Module, und installieren Sie die Pakete OpenAI, Zod und Azure Identity:
npm init --yes
npm pkg set type=module
npm install openai zod @azure/identity
npm install --save-dev typescript tsx @types/node
Speichern Sie für TypeScript jedes Beispiel als structured-outputs.ts, und führen Sie es dann aus:
npx tsx structured-outputs.ts
Speichern Sie für JavaScript jedes Beispiel als structured-outputs.mjs, und führen Sie es dann aus:
node structured-outputs.mjs
Verwenden Sie strukturierte Ausgaben mit Chat Completions
Definieren Sie die Ausgabestruktur mit Zod. Die zodResponseFormat Hilfsfunktion wandelt das Zod-Objekt in ein strenges JSON-Schema um und validiert die Modellantwort. Alle Eigenschaften im Zod-Objekt sind erforderlich, es sei denn, Sie definieren eine nullfähige Union.
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);
Die Ausgabe sieht in etwa wie folgt aus:
{
name: 'Science Fair',
date: 'Friday',
participants: [ 'Alice', 'Bob' ]
}
Verwenden Sie strukturierte Ausgaben mit der Responses API
Übergeben Sie für die Responses API das Ergebnis von zodTextFormat unter text.format. Der geparste Wert ist nach Abschluss der Antwort über output_parsed verfügbar.
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);
Die Ausgabe sieht in etwa wie folgt aus:
{
name: 'Science Fair',
date: 'Friday',
participants: [ 'Alice', 'Bob' ]
}
Verwenden Sie strukturierte Ausgaben für Funktionsaufrufe
Verwenden Sie zodFunction, um ein striktes Funktions-Tool zu erstellen und seine Argumente zu parsen. Azure OpenAI unterstützt keine parallelen Funktionsaufrufe mit strukturierten Ausgaben, setzen Sie also parallel_tool_calls auf 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);
Die Ausgabe sieht in etwa wie folgt aus:
{ order_id: '12345' }
Verwenden Sie für die zugrunde liegenden Anforderungs-Shapes ohne Zod die JSON-Schemabeispiele in der REST-Sprachoption.
Erste Schritte
response_format ist auf json_schema mit strict: true festgelegt.
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
}
}
}
}'
Ausgabe:
{
"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"
}
Verwenden Sie strukturierte Ausgaben mit der Responses API
Definieren Sie für die Antwort-API das JSON-Schema unter text.format. Festlegen type, , name, schema, und strict als gleichgeordnete Eigenschaften von format. Bevor Sie die Anfrage ausführen, legen Sie für AZURE_OPENAI_AUTH_TOKEN ein Microsoft Entra ID-Zugriffstoken fest.
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
}
}
}'
Der output_text Inhalt enthält:
{
"name": "Science Fair",
"date": "Friday",
"participants": ["Alice", "Bob"]
}
Funktionsaufrufe mit strukturierten Ausgaben
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
}
}
}
]
}'
JSON-Schemaunterstützung und -einschränkungen
Azure strukturierte OpenAI-Ausgaben unterstützen eine Teilmenge des JSON-Schemas. Die folgenden Azure spezifischen Grenzwerte und nicht unterstützten Schlüsselwörter gelten sowohl für die API für Chatabschlusse als auch für die Antwort-API.
Unterstützte Typen
- Schnur
- Nummer
- Boolean
- Ganzzahl
- Objekt
- Array
- Enum
- anyOf
Hinweis
Stammobjekte können nicht der anyOf Typ sein.
Alle Felder müssen ausgefüllt werden.
Schließen Sie alle Felder oder Funktionsparameter nach Bedarf ein. Im folgenden Beispiel werden beide location und unit unter "required": ["location", "unit"]angezeigt.
{
"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"]
}
}
Bei Bedarf können Sie einen optionalen Parameter mithilfe eines Union-Typs mit nullemulieren. In diesem Beispiel wird dieser Ansatz durch die Zeile "type": ["string", "null"],dargestellt.
{
"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"
]
}
}
Schachtelungstiefe
Ein Schema kann bis zu 100 Objekteigenschaften insgesamt mit bis zu fünf Schachtelungsebenen aufweisen.
Immer additionalProperties: false in Objekten setzen
Diese Eigenschaft steuert, ob ein Objekt andere Schlüsselwertpaare aufweisen kann, die im JSON-Schema nicht definiert wurden. Wenn Sie strukturierte Ausgaben verwenden möchten, legen Sie diesen Wert auf "false" fest.
Schlüsselreihenfolge
Strukturierte Ausgaben folgen der gleichen Reihenfolge wie das angegebene Schema. Um die Ausgabereihenfolge zu ändern, ändern Sie die Reihenfolge des Schemas, das Sie als Teil Ihrer Rückschlussanforderung senden.
Nicht unterstützte typspezifische Schlüsselwörter
| Typ | Nicht unterstütztes Schlüsselwort |
|---|---|
| Schnur | Mindestlänge MaximaleLänge Muster Format |
| Nummer | Minimum Maximum multipleOf |
| Objekte | patternProperties nicht ausgewertete Eigenschaften propertyNames minProperties maxProperties |
| Arrays | nicht ausgewerteteItems Enthält minContains maxContains minItems maxItems uniqueItems |
Geschachtelte Schemas mit anyOf müssen der gesamten JSON-Schemauntermenge entsprechen.
Beispiel für unterstütztes anyOf Schema:
{
"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"
]
}
Definitionen werden unterstützt.
Unterstütztes Beispiel:
{
"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
}
Rekursive Schemas werden unterstützt.
Beispiel für die Rekursion an der Wurzel mit #:
{
"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
}
}
Beispiel für explizite Rekursion:
{
"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"
]
}
Hinweis
Derzeit werden strukturierte Ausgaben bei folgenden Punkten nicht unterstützt:
- Bringen Sie Ihre eigenen Datenszenarien mit.
- Assistent oderGießerei-Agents-Dienst.
- Version von
gpt-4o-audio-previewundgpt-4o-mini-audio-preview:2024-12-17.
Unterstützte Modelle
-
gpt-5.1-codexVersion:2025-11-13 -
gpt-5.1-codex miniVersion:2025-11-13 -
gpt-5.1Version:2025-11-13 -
gpt-5.1-chatVersion:2025-11-13 -
gpt-5-proVersion2025-10-06 -
gpt-5-codexVersion2025-09-11 -
gpt-5Version2025-08-07 -
gpt-5-miniVersion2025-08-07 -
gpt-5-nanoVersion2025-08-07 -
codex-miniVersion2025-05-16 -
o3-proVersion2025-06-10 -
o3-miniVersion2025-01-31 -
o1Version:2024-12-17 -
gpt-4o-miniVersion:2024-07-18 -
gpt-4oVersion:2024-08-06 -
gpt-4oVersion:2024-11-20 -
gpt-4.1Version2025-04-14 -
gpt-4.1-nanoVersion2025-04-14 -
gpt-4.1-miniVersion:2025-04-14 -
o4-miniVersion:2025-04-16 -
o3Version:2025-04-16
API-Unterstützung
DIE API-Version 2024-08-01-preview ist die erste Version, die strukturierte Ausgaben unterstützt. Die neuesten Vorschau-APIs und die neueste GA-API v1unterstützen auch strukturierte Ausgaben.