Gebruik de Azure OpenAI-antwoorden-api om stateful, meerdere beurten antwoorden te genereren. Het combineert mogelijkheden van chatvoltooiingen en de Assistants-API in één uniforme ervaring. De Response-API ondersteunt ook het computer-use-preview model dat computergebruik mogelijk maakt.
Voorwaarden
- Een geïmplementeerd Azure OpenAI-model.
- Een verificatiemethode:
- API-sleutel (bijvoorbeeld
AZURE_OPENAI_API_KEY), of
- Microsoft Entra ID (aanbevolen).
- Installeer de clientbibliotheek voor uw taal:
-
Python:
pip install openai azure-identity
-
.NET:
dotnet add package OpenAI en dotnet add package Azure.Identity
-
JavaScript/TypeScript:
npm install openai @azure/identity
-
Java: voeg
com.openai:openai-java en com.azure:azure-identity toe aan uw project.
- Voor REST-voorbeelden stelt u
AZURE_OPENAI_API_KEY (API-sleutelstroom) of AZURE_OPENAI_AUTH_TOKEN (Microsoft Entra ID stroom) in.
Ondersteunde regio’s
Voordat u de voorbeelden in dit artikel uitvoert, moet u controleren of uw resourceregio ondersteuning biedt voor de Response-API. De v1-API is vereist voor toegang tot de nieuwste functies. Zie de levenscyclus van de API-versie voor meer informatie. De Antwoorden-API is momenteel beschikbaar in de volgende regio's:
- australië-oost
- brazilsouth
- canadacentral
- canadaeast
- eastus
- eastus2
- francecentral
- germanywestcentral
- Noord-Italië
- japaneast
- koreacentral
- northcentralus
- noorwegenoost
- Polencentral
- southafricanorth
- southcentralus
- southeastasia
- Zuid-India
- spaincentral
- swedencentral
- zwitserlandnoord
- uaenorth
- uksouth
- westus
- westus3
Ondersteunde modellen
De Antwoorden-API ondersteunt de volgende modellen:
-
gpt-chat-latest (Versie: 2026-05-05)
-
gpt-5.5 (Versie: 2026-04-24)
-
gpt-5.4-nano (Versie: 2026-03-17)
-
gpt-5.4-mini (Versie: 2026-03-17)
-
gpt-5.4-pro (Versie:2026-03-05)
-
gpt-5.4 (Versie:2026-03-05)
-
gpt-5.3-chat (Versie: 2026-03-03)
-
gpt-5.3-codex (Versie: 2026-02-24)
-
gpt-5.2-codex (Versie: 2026-01-14)
-
gpt-5.2 (Versie: 2025-12-11)
-
gpt-5.2-chat (Versie: 2025-12-11)
-
gpt-5.2-chat (Versie: 2026-02-10)
-
gpt-5.1-codex-max (Versie: 2025-12-04)
-
gpt-5.1 (Versie: 2025-11-13)
-
gpt-5.1-chat (Versie: 2025-11-13)
-
gpt-5.1-codex (Versie: 2025-11-13)
-
gpt-5.1-codex-mini (Versie: 2025-11-13)
-
gpt-5-pro (Versie: 2025-10-06)
-
gpt-5-codex (Versie: 2025-09-11)
-
gpt-5 (Versie: 2025-08-07)
-
gpt-5-mini (Versie: 2025-08-07)
-
gpt-5-nano (Versie: 2025-08-07)
-
gpt-5-chat (Versie: 2025-08-07)
-
gpt-5-chat (Versie: 2025-10-03)
-
gpt-5-codex (Versie: 2025-09-15)
-
gpt-4o (Versies: 2024-11-20, 2024-08-06, 2024-05-13)
-
gpt-4o-mini (Versie: 2024-07-18)
computer-use-preview
-
gpt-4.1 (Versie: 2025-04-14)
-
gpt-4.1-nano (Versie: 2025-04-14)
-
gpt-4.1-mini (Versie: 2025-04-14)
-
gpt-image-1 (Versie: 2025-04-15)
-
gpt-image-1-mini (Versie: 2025-10-06)
-
gpt-image-1.5 (Versie: 2025-12-16)
-
o1 (Versie: 2024-12-17)
-
o3-mini (Versie: 2025-01-31)
-
o3 (Versie: 2025-04-16)
-
o4-mini (Versie: 2025-04-16)
Niet elk model is beschikbaar in elke ondersteunde regio. Controleer de pagina modellen op beschikbaarheid van modelregio's. Zie de referentiedocumentatie voor de antwoorden-API voor de volledige set aanvraag- en antwoordparameters.
Opmerking
Momenteel niet ondersteund:
- Het genereren van afbeeldingen met meerdere iteraties van bewerkingen via streaming.
- Afbeeldingen kunnen niet worden geüpload als een bestand en vervolgens worden verwezen als invoer.
Er is een bekend probleem met het volgende:
- PDF als invoerbestand wordt nu ondersteund, maar het instellen van het uploaddoel
user_data voor bestanden wordt momenteel niet ondersteund.
- Prestatieproblemen wanneer de achtergrondmodus wordt gebruikt met streaming. Microsoft werkt aan het oplossen van dit probleem.
Een tekstantwoord genereren
Genereer een eenvoudig tekstantwoord met behulp van de Antwoorden-API. Vervang YOUR-RESOURCE-NAME en MODEL_NAME door uw implementatiewaarden.
import os
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
# API key authentication
client = OpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
)
response = client.responses.create(
model="MODEL_NAME",
input="This is a test."
)
print(response.model_dump_json(indent=2))
# Microsoft Entra ID authentication (recommended)
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(),
)
response = client.responses.create(
model="MODEL_NAME",
input="This is a test."
)
print(response.model_dump_json(indent=2))
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems = { ResponseItem.CreateUserMessageItem("This is a test.") }
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
import { OpenAI } from "openai";
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
// API key authentication
const openai = new OpenAI({
baseURL: endpoint,
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await openai.responses.create({
model: "MODEL_NAME",
input: "This is a test."
});
console.log(response.output_text);
// Microsoft Entra ID authentication (recommended)
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
"https://ai.azure.com/.default"
);
const openaiEntra = new OpenAI({
baseURL: endpoint,
apiKey: await tokenProvider(),
});
const responseEntra = await openaiEntra.responses.create({
model: "MODEL_NAME",
input: "This is a test."
});
console.log(responseEntra.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
// Microsoft Entra ID authentication (recommended)
OpenAIClient openAIClientEntra = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(BearerTokenCredential.create(
AuthenticationUtil.getBearerTokenSupplier(
new DefaultAzureCredentialBuilder().build(),
"https://ai.azure.com/.default")))
.build();
ResponseCreateParams params = ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("This is a test.")
.build();
Response response = openAIClient.responses().create(params);
System.out.println(response.outputText());
Microsoft Entra ID
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN" \
-d '{
"model": "MODEL_NAME",
"input": "This is a test."
}'
API-sleutel
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": "This is a test."
}'
Voorbeeld van een antwoord
{
"id": "resp_67cb32528d6881909eb2859a55e18a85",
"created_at": 1741369938.0,
"output_text": "Great! How can I help you today?",
...
}
Een antwoord ophalen
Haal een antwoord op met de bijbehorende id van een eerdere antwoord-API-aanroep.
import os
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
# API key authentication
client = OpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
)
response = client.responses.retrieve("<response_id>")
print(response.model_dump_json(indent=2))
# Microsoft Entra ID authentication
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,
)
response = client.responses.retrieve("<response_id>")
print(response.model_dump_json(indent=2))
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
string responseId = "<response_id>";
ResponseResult response = await openAIClient.GetResponseAsync(responseId);
Console.WriteLine(response.GetOutputText());
import { OpenAI } from "openai";
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
// API key authentication
const openai = new OpenAI({
baseURL: endpoint,
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await openai.responses.retrieve("<response_id>");
console.log(response.output_text);
// Microsoft Entra ID authentication
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
"https://ai.azure.com/.default"
);
const openaiEntra = new OpenAI({
baseURL: endpoint,
apiKey: await tokenProvider(),
});
const responseEntra = await openaiEntra.responses.retrieve("<response_id>");
console.log(responseEntra.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
// Microsoft Entra ID authentication
OpenAIClient openAIClientEntra = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(BearerTokenCredential.create(
AuthenticationUtil.getBearerTokenSupplier(
new DefaultAzureCredentialBuilder().build(),
"https://ai.azure.com/.default")))
.build();
Response response = openAIClient.responses().retrieve("<response_id>");
System.out.println(response.outputText());
Microsoft Entra ID
curl -X GET https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses/<response_id> \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN"
API-sleutel
curl -X GET https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses/<response_id> \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY"
Voorbeeld van een antwoord
{
"id": "resp_67cb61fa3a448190bcf2c42d96f0d1a8",
"output_text": "Hello! How can I assist you today?",
...
}
Een antwoord verwijderen
Antwoordgegevens worden standaard 30 dagen bewaard. Verwijder een opgeslagen antwoord op id.
import os
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
# API key authentication
client = OpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
)
response = client.responses.delete("<response_id>")
print(response)
# Microsoft Entra ID authentication
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,
)
response = client.responses.delete("<response_id>")
print(response)
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
string responseId = "<response_id>";
var result = await openAIClient.DeleteResponseAsync(responseId);
Console.WriteLine(result); // result.Deleted == true if successful
import { OpenAI } from "openai";
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
// API key authentication
const openai = new OpenAI({
baseURL: endpoint,
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const result = await openai.responses.delete("<response_id>");
console.log(result);
// Microsoft Entra ID authentication
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
"https://ai.azure.com/.default"
);
const openaiEntra = new OpenAI({
baseURL: endpoint,
apiKey: await tokenProvider(),
});
const resultEntra = await openaiEntra.responses.delete("<response_id>");
console.log(resultEntra);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
// Microsoft Entra ID authentication
OpenAIClient openAIClientEntra = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(BearerTokenCredential.create(
AuthenticationUtil.getBearerTokenSupplier(
new DefaultAzureCredentialBuilder().build(),
"https://ai.azure.com/.default")))
.build();
Response result = openAIClient.responses().delete("<response_id>");
System.out.println(result);
Microsoft Entra ID
curl -X DELETE https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses/<response_id> \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN"
API-sleutel
curl -X DELETE https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses/<response_id> \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY"
Antwoorden aan elkaar koppelen
Keten draait door de vorige antwoord-id door te geven aan previous_response_id.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
first_response = client.responses.create(
model="MODEL_NAME",
input="Define catastrophic forgetting."
)
second_response = client.responses.create(
model="MODEL_NAME",
previous_response_id=first_response.id,
input="Explain it for a college freshman."
)
print(second_response.output_text)
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
CreateResponseOptions firstOptions = new()
{
Model = "MODEL_NAME",
InputItems = { ResponseItem.CreateUserMessageItem("Define and explain the concept of catastrophic forgetting?") }
};
ResponseResult firstResponse = await openAIClient.CreateResponseAsync(firstOptions);
Console.WriteLine(firstResponse.GetOutputText());
CreateResponseOptions secondOptions = new()
{
Model = "MODEL_NAME",
PreviousResponseId = firstResponse.Id,
InputItems = { ResponseItem.CreateUserMessageItem("Explain this at a level that could be understood by a college freshman") }
};
ResponseResult secondResponse = await openAIClient.CreateResponseAsync(secondOptions);
Console.WriteLine(secondResponse.GetOutputText());
import { OpenAI } from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const firstResponse = await client.responses.create({
model: "MODEL_NAME",
input: "Define catastrophic forgetting."
});
const secondResponse = await client.responses.create({
model: "MODEL_NAME",
previous_response_id: firstResponse.id,
input: "Explain it for a college freshman."
});
console.log(secondResponse.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
Response first = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("Define and explain the concept of catastrophic forgetting?")
.build());
Response second = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.previousResponseId(first.id())
.input("Explain this at a level that could be understood by a college freshman.")
.build());
second.output().stream()
.flatMap(item -> item.message().stream())
.flatMap(m -> m.content().stream())
.flatMap(c -> c.outputText().stream())
.forEach(t -> System.out.println(t.text()));
# First turn
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": "Define catastrophic forgetting."
}'
# Follow-up turn using previous_response_id from the first call
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"previous_response_id": "<response_id>",
"input": "Explain it for a college freshman."
}'
Reacties handmatig koppelen
U kunt ook uitvoeritems handmatig doorsturen in de volgende aanvraag.
import os
from openai import OpenAI
client = OpenAI(
base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
inputs = [{"type": "message", "role": "user", "content": "Define and explain the concept of catastrophic forgetting?"}]
response = client.responses.create(
model="gpt-4o", # replace with your model deployment name
input=inputs
)
inputs += response.output
inputs.append({"role": "user", "type": "message", "content": "Explain this at a level that could be understood by a college freshman"})
second_response = client.responses.create(
model="MODEL_NAME",
input=inputs
)
print(second_response.model_dump_json(indent=2))
Een antwoord comprimeren
Compactie vermindert de inputcontext, terwijl de essentiële toestand behouden blijft voor volgende interacties.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
compacted = client.responses.compact(
model="MODEL_NAME",
input=[
{"role": "user", "content": "Create a simple landing page for a dog cafe."},
{
"id": "msg_001",
"type": "message",
"status": "completed",
"role": "assistant",
"content": [{"type": "output_text", "text": "..."}],
},
]
)
follow_up = client.responses.create(
model="MODEL_NAME",
input=[*compacted.output, {"role": "user", "content": "Add a booking form."}]
)
print(follow_up.output_text)
Opmerking
De .NET SDK biedt nog geen sterk getypt oppervlak voor antwoordcompressie. Zie het REST-tabblad voor de indeling van de aanroep, of roep de protocolmethode direct aan met BinaryContent JSON.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const compacted = await client.responses.compact({
model: "MODEL_NAME",
input: [
{ role: "user", content: "Create a simple landing page for a dog cafe." },
{
id: "msg_001",
type: "message",
status: "completed",
role: "assistant",
content: [{ type: "output_text", text: "..." }],
},
],
});
const followUp = await client.responses.create({
model: "MODEL_NAME",
input: [...compacted.output, { role: "user", content: "Add a booking form." }],
});
console.log(followUp.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.CompactedResponse;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCompactParams;
import com.openai.models.responses.ResponseCreateParams;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
Response initial = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("Create a simple landing page for a dog cafe.")
.build());
CompactedResponse compacted = openAIClient.responses().compact(
ResponseCompactParams.builder()
.model("MODEL_NAME")
.previousResponseId(initial.id())
.build());
Response followUp = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.previousResponseId(compacted.id())
.input("Add a booking form.")
.build());
System.out.println(followUp.outputText());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses/compact \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": [
{"role": "user", "content": "Create a simple landing page for a dog cafe."},
{
"id": "msg_001",
"type": "message",
"status": "completed",
"role": "assistant",
"content": [{"type": "output_text", "text": "..."}]
}
]
}'
Comprimeren met behulp van geretourneerde items
U kunt alle items comprimeren die zijn geretourneerd uit eerdere aanvragen, zoals redenering, bericht, functieoproep, enzovoort.
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses/compact \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN" \
-d '{
"model": "MODEL_NAME",
"input": [
{
"role" : "user",
"content": "Create a simple landing page for a dog petting café."
},
{
"id": "msg_001",
"type": "message",
"status": "completed",
"content": [
{
"type": "output_text",
"annotations": [],
"logprobs": [],
"text": "Below is a single file, ready-to-use landing page for a dog petting café:..."
}
],
"role": "assistant"
}
]
}'
# Use the compacted output as input for the next turn.
next_response = client.responses.create(
model="MODEL_NAME",
input=[*compacted.output, {"role": "user", "content": "Add opening hours."}],
)
print(next_response.output_text)
Comprimeren met behulp van vorige antwoord-id
U kunt ook comprimeren met behulp van een vorige antwoord-id.
initial_response = client.responses.create(
model="MODEL_NAME",
input="What is the size of France?"
)
compacted_response = client.responses.compact(
model="MODEL_NAME",
previous_response_id=initial_response.id
)
follow_up_response = client.responses.create(
model="MODEL_NAME",
input=[
*compacted_response.output,
{"role": "user", "content": "What is the capital?"}
]
)
print(follow_up_response.output_text)
Compressie aan serverzijde
U kunt server-side compactie ook direct in Responses (POST /responses of client.responses.create) gebruiken door context_management in te stellen met een compact_threshold.
- Wanneer het aantal uitvoertoken de geconfigureerde drempelwaarde overschrijdt, wordt de api voor antwoorden automatisch gecomprimeerd.
- In deze modus hoeft u niet afzonderlijk aan te roepen
/responses/compact .
- Het antwoord bevat een versleuteld compressie-item.
- Compressie aan de serverzijde werkt wanneer u store=false instelt bij aanvragen voor het genereren van antwoorden.
Het compactie-item draagt de essentiële voorafgaande status en redenering over naar de volgende beurt met minder tokens. Het is ondoorzichtig en is niet bedoeld om leesbaar te zijn voor mensen.
Als u staatloze invoermatrixketens gebruikt, voegt u uitvoeritems zoals gebruikelijk toe. Als u gebruikmaakt van previous_response_id, geeft u bij elke beurt alleen het nieuwe gebruikersbericht door. In beide patronen bevat het compressie-item de context die nodig is voor het volgende venster.
Tip
Nadat u uitvoeritems hebt toegevoegd aan de vorige invoeritems, kunt u items verwijderen die vóór het meest recente compressie-item zijn geleverd om aanvragen kleiner te houden en de latentie van de lange staart te verminderen. Het meest recente compactie-item bevat de benodigde context om het gesprek voort te zetten. Als u kettingen gebruikt previous_response_id , moet u niet handmatig snoeien.
Stroom
- Bel
responses zoals gebruikelijk. Voeg context_management samen met compact_threshold toe om compressie aan de serverzijde in te schakelen.
- Als de uitvoer de drempelwaarde overschrijdt, activeert de service compactie, stuurt een compactie-item in de uitvoerstroom en verwijdert de context voordat inferentie wordt voortgezet.
- Ga door met het gesprek met behulp van een van deze patronen:
- Staatloze invoermatrixkoppeling: uitvoeritems, inclusief compressie-items, toevoegen aan de volgende invoermatrix.
-
previous_response_id koppelen: geef alleen het nieuwe gebruikersbericht op elke keer door en draag de meest recente antwoord-id door.
Voorbeeld
conversation = [
{
"type": "message",
"role": "user",
"content": "Let's begin a long coding task.",
}
]
while keep_going:
response = client.responses.create(
model="MODEL_NAME",
input=conversation,
store=False,
context_management=[{"type": "compaction", "compact_threshold": 200000}],
)
conversation.append(
{
"type": "message",
"role": "user",
"content": get_next_user_input(),
}
)
Streamen
Stream het antwoord terwijl het wordt gegenereerd door stream=true in te stellen. De service verzendt incrementele gebeurtenissen die u kunt gebruiken om uitvoertoken per token weer te geven.
Opmerking
Tijdens het streamen kan de Antwoorden-API een fout gebeurtenis ( 500, 429en soortgelijke fouten) retourneren als de service een fout tegenkomt, zoals tokenlimieten of parseringsproblemen. Toepassingen moeten deze gebeurtenis detecteren en streaming probleemloos stoppen of opnieuw starten. Er worden geen kosten in rekening gebracht voor tokens die worden gegenereerd tijdens mislukte streamingantwoorden.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
stream = client.responses.create(
model="MODEL_NAME",
input="Summarize Azure OpenAI Responses API in one sentence.",
stream=True,
)
for event in stream:
if event.type == "response.output_text.delta":
print(event.delta, end="")
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems = { ResponseItem.CreateUserMessageItem("Summarize Azure OpenAI Responses API in one sentence.") },
StreamingEnabled = true
};
await foreach (StreamingResponseUpdate update in openAIClient.CreateResponseStreamingAsync(options))
{
if (update is StreamingResponseOutputTextDeltaUpdate textDelta)
{
Console.Write(textDelta.Delta);
}
else if (update is StreamingResponseCompletedUpdate completed)
{
Console.WriteLine();
Console.WriteLine($"[done] response id: {completed.Response.Id}");
}
}
import { OpenAI } from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const stream = await client.responses.create({
model: "MODEL_NAME",
input: "Summarize Azure OpenAI Responses API in one sentence.",
stream: true,
});
for await (const event of stream) {
if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
}
}
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseStreamEvent;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
ResponseCreateParams params = ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("This is a test")
.build();
try (StreamResponse<ResponseStreamEvent> stream = openAIClient.responses().createStreaming(params)) {
stream.stream()
.flatMap(event -> event.outputTextDelta().stream())
.forEach(delta -> System.out.print(delta.delta()));
}
curl -N -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": "Summarize Azure OpenAI Responses API in one sentence.",
"stream": true
}'
Functie aanroepen
De Response-API biedt ondersteuning voor functie-aanroepen.
import os
import json
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
response = client.responses.create(
model="MODEL_NAME",
tools=[
{
"type": "function",
"name": "get_weather",
"description": "Get weather for a location",
"parameters": {
"type": "object",
"properties": {"location": {"type": "string"}},
"required": ["location"],
},
}
],
input="What is the weather in San Francisco?",
)
tool_outputs = []
for item in response.output:
if item.type == "function_call" and item.name == "get_weather":
args = json.loads(item.arguments)
weather = {"location": args["location"], "temperature": "70 F"}
tool_outputs.append(
{
"type": "function_call_output",
"call_id": item.call_id,
"output": json.dumps(weather),
}
)
final_response = client.responses.create(
model="MODEL_NAME",
previous_response_id=response.id,
input=tool_outputs,
)
print(final_response.output_text)
#pragma warning disable OPENAI001
using System.Text.Json;
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
FunctionTool getWeatherTool = ResponseTool.CreateFunctionTool(
functionName: "get_weather",
functionParameters: BinaryData.FromBytes("""
{
"type": "object",
"properties": {
"location": { "type": "string", "description": "The city, e.g. Boston, MA" }
},
"required": ["location"]
}
"""u8.ToArray()),
strictModeEnabled: false,
functionDescription: "Get the current weather for a location.");
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems = { ResponseItem.CreateUserMessageItem("What is the weather in San Francisco?") },
Tools = { getWeatherTool }
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
foreach (ResponseItem item in response.OutputItems)
{
if (item is FunctionCallResponseItem call && call.FunctionName == "get_weather")
{
using JsonDocument args = JsonDocument.Parse(call.FunctionArguments);
string location = args.RootElement.GetProperty("location").GetString();
string toolOutput = $"{{ \"location\": \"{location}\", \"temperature\": \"70 F\" }}";
CreateResponseOptions followUp = new()
{
Model = "MODEL_NAME",
PreviousResponseId = response.Id,
InputItems = { ResponseItem.CreateFunctionCallOutputItem(call.CallId, toolOutput) },
Tools = { getWeatherTool }
};
ResponseResult finalResponse = await openAIClient.CreateResponseAsync(followUp);
Console.WriteLine(finalResponse.GetOutputText());
}
}
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await client.responses.create({
model: "MODEL_NAME",
tools: [
{
type: "function",
name: "get_weather",
description: "Get weather for a location",
parameters: {
type: "object",
properties: { location: { type: "string" } },
required: ["location"],
},
},
],
input: "What is the weather in San Francisco?",
});
const toolOutputs = [];
for (const item of response.output ?? []) {
if (item.type === "function_call" && item.name === "get_weather") {
const args = JSON.parse(item.arguments);
toolOutputs.push({
type: "function_call_output",
call_id: item.call_id,
output: JSON.stringify({ location: args.location, temperature: "70 F" }),
});
}
}
const finalResponse = await client.responses.create({
model: "MODEL_NAME",
previous_response_id: response.id,
input: toolOutputs,
});
console.log(finalResponse.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseFunctionToolCall;
import com.openai.models.responses.ResponseInputItem;
import java.util.ArrayList;
import java.util.List;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
// Strongly-typed function parameter class.
class GetWeather {
@JsonPropertyDescription("City and country, for example, Paris, France")
public String location;
}
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("What is the weather like in Paris today?")
.addTool(GetWeather.class)
.build());
List<ResponseInputItem> followUp = new ArrayList<>();
response.output().forEach(item -> {
if (item.isFunctionCall()) {
ResponseFunctionToolCall call = item.asFunctionCall();
// Execute the tool with call.arguments() and capture the result.
String result = "{\"temperature\":\"22 C\",\"conditions\":\"Sunny\"}";
followUp.add(ResponseInputItem.ofFunctionCallOutput(
ResponseInputItem.FunctionCallOutput.builder()
.callId(call.callId())
.output(result)
.build()));
}
});
Response finalResponse = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.previousResponseId(response.id())
.inputOfResponse(followUp)
.addTool(GetWeather.class)
.build());
System.out.println(finalResponse.outputText());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"tools": [
{
"type": "function",
"name": "get_weather",
"description": "Get weather for a location",
"parameters": {
"type": "object",
"properties": {"location": {"type": "string"}},
"required": ["location"]
}
}
],
"input": "What is the weather in San Francisco?"
}'
Code-interpreter
Met het hulpprogramma Code Interpreter kunnen modellen Python code schrijven en uitvoeren in een beveiligde, sandbox-omgeving. Het ondersteunt een reeks geavanceerde taken, waaronder:
- Bestanden verwerken met verschillende gegevensindelingen en structuren
- Bestanden genereren die gegevens en visualisaties bevatten (bijvoorbeeld grafieken)
- Iteratief code schrijven en uitvoeren om problemen op te lossen: modellen kunnen fouten opsporen en code opnieuw proberen totdat het lukt
- Visuele redenering in ondersteunde modellen verbeteren (bijvoorbeeld o3, o4-mini) door afbeeldingstransformaties in te schakelen, zoals bijsnijden, zoomen en draaien
- Dit hulpprogramma is vooral handig voor scenario's met betrekking tot gegevensanalyse, wiskundige berekening en het genereren van code.
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"tools": [
{ "type": "code_interpreter", "container": {"type": "auto"} }
],
"instructions": "You are a personal math tutor. When asked a math question, write and run code using the python tool to answer the question.",
"input": "I need to solve the equation 3x + 11 = 14. Can you help me?"
}'
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
response = client.responses.create(
model="MODEL_NAME",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
instructions="You are a math tutor. Write and run Python code to solve math problems.",
input="Solve 3x + 11 = 14."
)
print(response.output_text)
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Containers;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
CodeInterpreterToolContainer container = new(
CodeInterpreterToolContainerConfiguration.CreateAutomaticContainerConfiguration());
CodeInterpreterTool codeInterpreterTool = new(container);
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems =
{
ResponseItem.CreateUserMessageItem("Solve 3x + 11 = 14.")
},
Tools = { codeInterpreterTool }
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await client.responses.create({
model: "MODEL_NAME",
tools: [{ type: "code_interpreter", container: { type: "auto" } }],
instructions: "You are a math tutor. Write and run Python code to solve math problems.",
input: "Solve 3x + 11 = 14.",
});
console.log(response.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.Tool;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
Tool codeInterpreter = Tool.ofCodeInterpreter(
Tool.CodeInterpreter.builder()
.container(Tool.CodeInterpreter.Container.ofCodeInterpreterToolAuto(
Tool.CodeInterpreter.Container.CodeInterpreterToolAuto.builder().build()))
.build());
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("Solve 3x + 11 = 14.")
.addTool(codeInterpreter)
.build());
System.out.println(response.outputText());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"tools": [{"type": "code_interpreter", "container": {"type": "auto"}}],
"instructions": "You are a math tutor. Write and run Python code to solve math problems.",
"input": "Solve 3x + 11 = 14."
}'
Containers
Belangrijk
Code-interpreter heeft aanvoeglijke kosten buiten de tokenkosten voor Azure OpenAI-gebruik. Als de Response-API code-interpreter tegelijkertijd aanroept in twee verschillende threads, worden er twee code-interpretersessies gemaakt. Elke sessie is standaard gedurende 1 uur actief met een time-out voor inactiviteit van 20 minuten.
Het hulpprogramma Code Interpreter vereist een container: een volledig in de sandbox geplaatste virtuele machine waar het model Python code kan uitvoeren. Containers kunnen geüploade bestanden of bestanden bevatten die tijdens de uitvoering zijn gegenereerd.
Als u een container wilt maken, geeft u "container": { "type": "auto", "file_ids": ["file-1", "file-2"] } op in de configuratie van het hulpprogramma bij het maken van een nieuw antwoordobject. Hiermee wordt automatisch een nieuwe container gemaakt of wordt een actieve container opnieuw gebruikt op basis van een eerdere code_interpreter_call in de context van het model. De code_interpreter_call in de uitvoer van de API zal de container_id bevatten dat gegenereerd was. Deze container verloopt als deze gedurende 20 minuten niet wordt gebruikt.
Bij het uitvoeren van code-interpreter kan het model zijn eigen bestanden maken. Als u bijvoorbeeld vraagt om een plot te maken of een CSV te maken, worden deze afbeeldingen rechtstreeks in uw container gemaakt. Deze bestanden worden in de aantekeningen van het volgende bericht weergegeven.
Bestanden in de modelinvoer worden automatisch geüpload naar de container. U hoeft deze niet expliciet te uploaden naar de container.
Ondersteunde bestanden
| Bestandsindeling |
MIME-type |
.c |
tekst/x-c |
.cs |
text/x-csharp |
.cpp |
text/x-c++ |
.csv |
text/csv |
.doc |
application/msword |
.docx |
application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.html |
text/html |
.java |
text/x-java |
.json |
application/json |
.md |
text/markdown |
.pdf |
application/pdf |
.php |
text/x-php |
.pptx |
application/vnd.openxmlformats-officedocument.presentationml.presentation |
.py |
text/x-python |
.py |
text/x-script.python |
.rb |
text/x-ruby |
.tex |
tekst/x-tex |
.txt |
platte tekst |
.css |
text/css |
.js |
text/JavaScript |
.sh |
application/x-sh |
.ts |
toepassing/TypeScript |
.csv |
application/csv |
.jpeg |
afbeelding/jpeg |
.jpg |
afbeelding/jpeg |
.gif |
image/gif |
.pkl |
application/octet-stream |
.png |
image/png |
.tar |
application/x-tar |
.xlsx |
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.xml |
application/xml of "text/xml" |
.zip |
toepassing/zip |
Haal de invoeritems op die naar een antwoord zijn verzonden. Dit is handig voor het inspecteren van de volledige gesprekscontext, inclusief alle items die door het model worden toegevoegd (bijvoorbeeld functie-aanroepen of compressie-items).
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
items = client.responses.input_items.list("<response_id>")
print(items.model_dump_json(indent=2))
Opmerking
De .NET SDK maakt dit eindpunt alleen beschikbaar als protocolmethode. Zie het REST-tabblad voor de aanroepindeling, of gebruik de protocolmethode rechtstreeks.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const items = await client.responses.inputItems.list("<response_id>");
console.log(JSON.stringify(items, null, 2));
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.inputitems.ResponseInputItemListPage;
import com.openai.models.responses.inputitems.ResponseInputItemListParams;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
ResponseInputItemListPage page = openAIClient.responses().inputItems().list(
ResponseInputItemListParams.builder()
.responseId("<response_id>")
.build());
page.autoPager().stream().forEach(item -> System.out.println(item));
curl -X GET https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses/<response_id>/input_items \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY"
Voorbeeld van een antwoord
{
"object": "list",
"data": [
{
"id": "msg_...",
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "This is a test."}]
}
]
}
Voor modellen met vision zijn ondersteunde afbeeldingsindelingen PNG, JPEG en WebP.
Afbeeldings-URL
Verwijs naar een image die wordt gehost op een openbare URL. Het model haalt de afbeelding op en bevat deze als onderdeel van de invoerinhoud.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
response = client.responses.create(
model="MODEL_NAME",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": "What is in this image?"},
{"type": "input_image", "image_url": "<image_url>"}
]
}
]
)
print(response.output_text)
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems =
{
ResponseItem.CreateUserMessageItem(
[
ResponseContentPart.CreateInputTextPart("What is in this image?"),
ResponseContentPart.CreateInputImagePart(new Uri("<image_url>"))
])
}
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await client.responses.create({
model: "MODEL_NAME",
input: [
{
role: "user",
content: [
{ type: "input_text", text: "What is in this image?" },
{ type: "input_image", image_url: "<image_url>" }
],
},
],
});
console.log(response.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputImage;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
ResponseInputImage image = ResponseInputImage.builder()
.detail(ResponseInputImage.Detail.AUTO)
.imageUrl("<image_url>")
.build();
ResponseInputItem userMsg = ResponseInputItem.ofMessage(
ResponseInputItem.Message.builder()
.role(ResponseInputItem.Message.Role.USER)
.addInputTextContent("What is in this image?")
.addContent(image)
.build());
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.inputOfResponse(List.of(userMsg))
.build());
System.out.println(response.outputText());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": [
{
"role": "user",
"content": [
{"type": "input_text", "text": "What is in this image?"},
{"type": "input_image", "image_url": "<image_url>"}
]
}
]
}'
Base64-gecodeerde afbeelding
Verstuur een afbeelding inline door de bytes ervan te coderen als een base64-data-URI. Gebruik dit patroon wanneer de afbeelding niet op een openbare URL wordt gehost of wanneer u een extra netwerkaanvraag wilt vermijden.
import base64
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
with open("path_to_your_image.jpg", "rb") as image_file:
base64_image = base64.b64encode(image_file.read()).decode("utf-8")
response = client.responses.create(
model="MODEL_NAME",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": "What is in this image?"},
{"type": "input_image", "image_url": f"data:image/jpeg;base64,{base64_image}"}
]
}
]
)
print(response.output_text)
#pragma warning disable OPENAI001
using System.IO;
using System.Threading.Tasks;
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
byte[] imageBytes = await File.ReadAllBytesAsync("path_to_your_image.jpg");
BinaryData imageData = BinaryData.FromBytes(imageBytes);
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems =
{
ResponseItem.CreateUserMessageItem(
[
ResponseContentPart.CreateInputTextPart("What is in this image?"),
ResponseContentPart.CreateInputImagePart(imageData, "image/jpeg")
])
}
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
import { readFileSync } from "node:fs";
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const base64Image = readFileSync("path_to_your_image.jpg").toString("base64");
const response = await client.responses.create({
model: "MODEL_NAME",
input: [
{
role: "user",
content: [
{ type: "input_text", text: "What is in this image?" },
{ type: "input_image", image_url: `data:image/jpeg;base64,${base64Image}` }
],
},
],
});
console.log(response.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputImage;
import com.openai.models.responses.ResponseInputItem;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
byte[] bytes = Files.readAllBytes(Paths.get("cat.jpg"));
String dataUrl = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(bytes);
ResponseInputImage image = ResponseInputImage.builder()
.detail(ResponseInputImage.Detail.AUTO)
.imageUrl(dataUrl)
.build();
ResponseInputItem userMsg = ResponseInputItem.ofMessage(
ResponseInputItem.Message.builder()
.role(ResponseInputItem.Message.Role.USER)
.addInputTextContent("What is in this image?")
.addContent(image)
.build());
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.inputOfResponse(List.of(userMsg))
.build());
System.out.println(response.outputText());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": [
{
"role": "user",
"content": [
{"type": "input_text", "text": "What is in this image?"},
{"type": "input_image", "image_url": "data:image/jpeg;base64,<BASE64_IMAGE>"}
]
}
]
}'
Modellen met vision-mogelijkheden ondersteunen PDF-invoer. PDF-bestanden kunnen worden geleverd als met Base64 gecodeerde gegevens of als bestands-id's. Om modellen te helpen PDF-inhoud te interpreteren, worden zowel de geëxtraheerde tekst als een afbeelding van elke pagina opgenomen in de context van het model. Dit is handig wanneer belangrijke informatie wordt overgebracht via diagrammen of niet-tekstuele inhoud.
Opmerking
- Alle geëxtraheerde tekst en afbeeldingen worden in de context van het model geplaatst. Zorg ervoor dat u de gevolgen van het gebruik van prijzen en tokens begrijpt voor het gebruik van PDF-bestanden als invoer.
- In één API-aanvraag moet de grootte van inhoud die is geüpload over meerdere invoer (bestanden) binnen de contextlengte van het model vallen.
- Alleen modellen die zowel tekst- als afbeeldingsinvoer ondersteunen, kunnen PDF-bestanden als invoer accepteren.
- Een
purpose van user_data wordt momenteel niet ondersteund. Als tijdelijke oplossing moet u het doel instellen op assistants.
PDF converteren naar Base64 en analyseren
Verzend een PDF inline door de bytes te coderen naar een base64-data-URI. Het model ontvangt zowel de geëxtraheerde tekst als een gerenderde afbeelding van elke pagina.
import base64
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
with open("PDF-FILE-NAME.pdf", "rb") as f:
base64_string = base64.b64encode(f.read()).decode("utf-8")
response = client.responses.create(
model="MODEL_NAME",
input=[
{
"role": "user",
"content": [
{
"type": "input_file",
"filename": "PDF-FILE-NAME.pdf",
"file_data": f"data:application/pdf;base64,{base64_string}",
},
{"type": "input_text", "text": "Summarize this PDF."},
],
},
]
)
print(response.output_text)
#pragma warning disable OPENAI001
using System.IO;
using System.Threading.Tasks;
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
byte[] pdfBytes = await File.ReadAllBytesAsync("PDF-FILE-NAME.pdf");
BinaryData pdfData = BinaryData.FromBytes(pdfBytes);
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems =
{
ResponseItem.CreateUserMessageItem(
[
ResponseContentPart.CreateInputFilePart(pdfData, "application/pdf", "PDF-FILE-NAME.pdf"),
ResponseContentPart.CreateInputTextPart("Summarize this PDF.")
])
}
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
import { readFileSync } from "node:fs";
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const base64Pdf = readFileSync("PDF-FILE-NAME.pdf").toString("base64");
const response = await client.responses.create({
model: "MODEL_NAME",
input: [
{
role: "user",
content: [
{
type: "input_file",
filename: "PDF-FILE-NAME.pdf",
file_data: `data:application/pdf;base64,${base64Pdf}`,
},
{ type: "input_text", text: "Summarize this PDF." },
],
},
],
});
console.log(response.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputFile;
import com.openai.models.responses.ResponseInputItem;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
byte[] pdfBytes = Files.readAllBytes(Paths.get("document.pdf"));
String dataUrl = "data:application/pdf;base64," + Base64.getEncoder().encodeToString(pdfBytes);
ResponseInputFile file = ResponseInputFile.builder()
.filename("document.pdf")
.fileData(dataUrl)
.build();
ResponseInputItem userMsg = ResponseInputItem.ofMessage(
ResponseInputItem.Message.builder()
.role(ResponseInputItem.Message.Role.USER)
.addInputTextContent("Summarize this PDF.")
.addContent(file)
.build());
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.inputOfResponse(List.of(userMsg))
.build());
System.out.println(response.outputText());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": [
{
"role": "user",
"content": [
{"type": "input_file", "filename": "PDF-FILE-NAME.pdf", "file_data": "data:application/pdf;base64,<BASE64_PDF>"},
{"type": "input_text", "text": "Summarize this PDF."}
]
}
]
}'
PDF uploaden en analyseren
Upload het PDF-bestand met purpose="assistants". Een purpose van user_data wordt momenteel niet ondersteund.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
file = client.files.create(
file=open("nucleus_sampling.pdf", "rb"),
purpose="assistants"
)
response = client.responses.create(
model="MODEL_NAME",
input=[
{
"role": "user",
"content": [
{"type": "input_file", "file_id": file.id},
{"type": "input_text", "text": "Summarize this PDF."},
],
},
]
)
print(response.output_text)
#pragma warning disable OPENAI001
using System.IO;
using System.Threading.Tasks;
using Azure.Identity;
using OpenAI;
using OpenAI.Files;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
OpenAIFileClient fileClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new OpenAIClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
byte[] pdfBytes = await File.ReadAllBytesAsync("nucleus_sampling.pdf");
OpenAIFile uploadedFile = await fileClient.UploadFileAsync(
BinaryData.FromBytes(pdfBytes),
"nucleus_sampling.pdf",
FileUploadPurpose.UserData);
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems =
{
ResponseItem.CreateUserMessageItem(
[
ResponseContentPart.CreateInputFilePart(uploadedFile.Id),
ResponseContentPart.CreateInputTextPart("Summarize this PDF.")
])
}
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
import fs from "node:fs";
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const file = await client.files.create({
file: fs.createReadStream("nucleus_sampling.pdf"),
purpose: "assistants",
});
const response = await client.responses.create({
model: "MODEL_NAME",
input: [
{
role: "user",
content: [
{ type: "input_file", file_id: file.id },
{ type: "input_text", text: "Summarize this PDF." },
],
},
],
});
console.log(response.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.FileCreateParams;
import com.openai.models.FileObject;
import com.openai.models.FilePurpose;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputFile;
import com.openai.models.responses.ResponseInputItem;
import java.nio.file.Paths;
import java.util.List;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
FileObject uploaded = openAIClient.files().create(
FileCreateParams.builder()
.file(Paths.get("document.pdf"))
.purpose(FilePurpose.USER_DATA)
.build());
ResponseInputFile file = ResponseInputFile.builder()
.fileId(uploaded.id())
.build();
ResponseInputItem userMsg = ResponseInputItem.ofMessage(
ResponseInputItem.Message.builder()
.role(ResponseInputItem.Message.Role.USER)
.addInputTextContent("Summarize this PDF.")
.addContent(file)
.build());
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.inputOfResponse(List.of(userMsg))
.build());
System.out.println(response.outputText());
# Upload the PDF
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/files \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-F purpose="assistants" \
-F file="@your_file.pdf"
# Use the returned file ID with Responses
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": [
{
"role": "user",
"content": [
{"type": "input_file", "file_id": "<file_id>"},
{"type": "input_text", "text": "Summarize this PDF."}
]
}
]
}'
Externe MCP-servers gebruiken
U kunt de mogelijkheden van uw model uitbreiden door het te verbinden met hulpprogramma's die worden gehost op MCP-servers (Remote Model Context Protocol). Deze servers worden onderhouden door ontwikkelaars en organisaties en maken hulpprogramma's beschikbaar die toegankelijk zijn voor MCP-compatibele clients, zoals de Antwoorden-API.
Model Context Protocol (MCP) is een open standaard die definieert hoe toepassingen hulpprogramma's en contextuele gegevens bieden aan grote taalmodellen (LLM's). Het maakt consistente, schaalbare integratie van externe hulpprogramma's mogelijk in modelwerkstromen.
In het volgende voorbeeld ziet u hoe u een externe MCP-server gebruikt om informatie op te vragen over een Azure REST API-opslagplaats. Het model haalt repository-inhoud in realtime op en redeneert erover.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
response = client.responses.create(
model="MODEL_NAME",
tools=[
{
"type": "mcp",
"server_label": "github",
"server_url": "https://contoso.com/Azure/azure-rest-api-specs",
"require_approval": "never"
}
],
input="What transport protocols are supported in the 2025-03-26 version of the MCP spec?"
)
print(response.output_text)
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems = { ResponseItem.CreateUserMessageItem("What transport protocols are supported in the 2025-03-26 version of the MCP spec?") },
Tools =
{
new McpTool(serverLabel: "github", serverUri: new Uri("https://contoso.com/Azure/azure-rest-api-specs"))
{
ToolCallApprovalPolicy = GlobalMcpToolCallApprovalPolicy.NeverRequireApproval
}
}
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await client.responses.create({
model: "MODEL_NAME",
tools: [
{
type: "mcp",
server_label: "github",
server_url: "https://contoso.com/Azure/azure-rest-api-specs",
require_approval: "never",
},
],
input: "What is this repo in 100 words?",
});
console.log(response.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.Tool;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
Tool mcpTool = Tool.ofMcp(
Tool.Mcp.builder()
.serverLabel("github")
.serverUrl("https://contoso.com/Azure/azure-rest-api-specs")
.requireApproval(Tool.Mcp.RequireApproval.ofMcpToolApprovalSetting(
Tool.Mcp.RequireApproval.McpToolApprovalSetting.NEVER))
.build());
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("What is this repo in 100 words?")
.addTool(mcpTool)
.build());
System.out.println(response.outputText());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"tools": [
{
"type": "mcp",
"server_label": "github",
"server_url": "https://contoso.com/Azure/azure-rest-api-specs",
"require_approval": "never"
}
],
"input": "What is this repo in 100 words?"
}'
Het MCP-hulpprogramma werkt alleen in de Antwoorden-API en is beschikbaar voor alle nieuwere modellen (gpt-4o, gpt-4.1 en onze redeneringsmodellen). Wanneer u het MCP-hulpprogramma gebruikt, betaalt u alleen voor tokens die worden gebruikt bij het importeren van hulpprogrammadefinities of het maken van hulpprogramma-aanroepen. Er zijn geen extra kosten verbonden.
Goedkeuringen
De Antwoorden-API vereist standaard expliciete goedkeuring voordat gegevens worden gedeeld met een externe MCP-server. Deze goedkeuringsstap zorgt voor transparantie en geeft u controle over welke informatie extern wordt verzonden.
We raden u aan alle gegevens te controleren die worden gedeeld met externe MCP-servers en deze eventueel te registreren voor controledoeleinden.
Wanneer een goedkeuring is vereist, retourneert het model een mcp_approval_request item in de antwoorduitvoer. Dit object bevat de details van de aanvraag die in behandeling is en stelt u in staat om de gegevens te inspecteren of te wijzigen voordat u doorgaat.
{
"id": "mcpr_682bd9cd428c8198b170dc6b549d66fc016e86a03f4cc828",
"type": "mcp_approval_request",
"arguments": {},
"name": "fetch_azure_rest_api_docs",
"server_label": "github"
}
Als u wilt doorgaan met de externe MCP-aanroep, moet u reageren op de goedkeuringsaanvraag door een nieuw antwoordobject te maken dat een mcp_approval_response item bevat. Dit object bevestigt uw intentie zodat het model de opgegeven gegevens naar de externe MCP-server kan verzenden.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
response = client.responses.create(
model="MODEL_NAME",
tools=[
{
"type": "mcp",
"server_label": "github",
"server_url": "https://contoso.com/Azure/azure-rest-api-specs",
"require_approval": "never"
}
],
previous_response_id="<previous_response_id>",
input=[
{
"type": "mcp_approval_response",
"approve": True,
"approval_request_id": "<approval_request_id>"
}
]
)
print(response.output_text)
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
McpTool mcpTool = new(serverLabel: "github", serverUri: new Uri("https://contoso.com/Azure/azure-rest-api-specs"));
ResponseResult priorResponse = await openAIClient.GetResponseAsync("<previous_response_id>");
foreach (ResponseItem item in priorResponse.OutputItems)
{
if (item is McpToolCallApprovalRequestItem approvalRequest)
{
CreateResponseOptions followUp = new()
{
Model = "MODEL_NAME",
PreviousResponseId = priorResponse.Id,
InputItems = { new McpToolCallApprovalResponseItem(approvalRequest.Id, approved: true) },
Tools = { mcpTool }
};
ResponseResult finalResponse = await openAIClient.CreateResponseAsync(followUp);
Console.WriteLine(finalResponse.GetOutputText());
}
}
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await client.responses.create({
model: "MODEL_NAME",
tools: [
{
type: "mcp",
server_label: "github",
server_url: "https://contoso.com/Azure/azure-rest-api-specs",
require_approval: "never",
},
],
previous_response_id: "<previous_response_id>",
input: [
{
type: "mcp_approval_response",
approve: true,
approval_request_id: "<approval_request_id>",
},
],
});
console.log(response.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.previousResponseId("<previous_response_id>")
.inputOfResponse(List.of(
ResponseInputItem.ofMcpApprovalResponse(
ResponseInputItem.McpApprovalResponse.builder()
.approvalRequestId("<approval_request_id>")
.approve(true)
.build())))
.build());
System.out.println(response.outputText());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"tools": [
{
"type": "mcp",
"server_label": "github",
"server_url": "https://contoso.com/Azure/azure-rest-api-specs",
"require_approval": "never"
}
],
"previous_response_id": "<previous_response_id>",
"input": [
{
"type": "mcp_approval_response",
"approve": true,
"approval_request_id": "<approval_request_id>"
}
]
}'
Verificatie
Belangrijk
- Voor de MCP-client in de antwoorden-API is TLS 1.2 of hoger vereist.
- Wederzijdse TLS (mTLS) wordt momenteel niet ondersteund.
-
Azure servicetags worden momenteel niet ondersteund voor MCP-clientverkeer.
In tegenstelling tot de GitHub MCP-server vereisen de meeste externe MCP-servers verificatie. Het MCP-hulpprogramma in de antwoorden-API ondersteunt aangepaste headers, zodat u veilig verbinding kunt maken met deze servers met behulp van het verificatieschema dat ze nodig hebben.
U kunt headers opgeven, zoals API-sleutels, OAuth-toegangstokens of andere referenties, rechtstreeks in uw aanvraag. De meest gebruikte header is de Authorization header.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
response = client.responses.create(
model="MODEL_NAME",
input="What is this repo in 100 words?",
tools=[
{
"type": "mcp",
"server_label": "github",
"server_url": "https://contoso.com/Azure/azure-rest-api-specs",
"headers": {"Authorization": "Bearer $YOUR_MCP_TOKEN"}
}
]
)
print(response.output_text)
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems = { ResponseItem.CreateUserMessageItem("What is this repo in 100 words?") },
Tools =
{
new McpTool(serverLabel: "github", serverUri: new Uri("https://contoso.com/Azure/azure-rest-api-specs"))
{
AuthorizationToken = Environment.GetEnvironmentVariable("YOUR_MCP_TOKEN"),
ToolCallApprovalPolicy = GlobalMcpToolCallApprovalPolicy.NeverRequireApproval
}
}
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await client.responses.create({
model: "MODEL_NAME",
input: "What is this repo in 100 words?",
tools: [
{
type: "mcp",
server_label: "github",
server_url: "https://contoso.com/Azure/azure-rest-api-specs",
headers: { Authorization: "Bearer $YOUR_MCP_TOKEN" },
},
],
});
console.log(response.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.Tool;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
Tool mcpTool = Tool.ofMcp(
Tool.Mcp.builder()
.serverLabel("github")
.serverUrl("https://contoso.com/Azure/azure-rest-api-specs")
.headers(Tool.Mcp.Headers.builder()
.putAdditionalProperty("Authorization", JsonValue.from("Bearer $YOUR_MCP_TOKEN"))
.build())
.requireApproval(Tool.Mcp.RequireApproval.ofMcpToolApprovalSetting(
Tool.Mcp.RequireApproval.McpToolApprovalSetting.NEVER))
.build());
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("What is this repo in 100 words?")
.addTool(mcpTool)
.build());
System.out.println(response.outputText());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": "What is this repo in 100 words?",
"tools": [
{
"type": "mcp",
"server_label": "github",
"server_url": "https://contoso.com/Azure/azure-rest-api-specs",
"headers": {"Authorization": "Bearer $YOUR_MCP_TOKEN"}
}
]
}'
Achtergrondtaken
Met de achtergrondmodus kunt u langlopende taken asynchroon uitvoeren met redeneringsmodellen zoals o3 en o1-pro. Het is handig voor complexe taken die enkele minuten kunnen duren (bijvoorbeeld Codex- of Deep Research-agents). Wanneer een verzoek met "background": true wordt verzonden, wordt de taak asynchroon verwerkt en vraagt u de status ervan op.
Een achtergrondtaak starten
Stel background=true in voor het verzoek, zodat de taak in de wachtrij wordt geplaatst. De service wordt onmiddellijk geretourneerd met een antwoord-id en een queued status. Gebruik deze id om de taak te peilen, te streamen of te annuleren.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
response = client.responses.create(
model="MODEL_NAME",
input="Write me a very long story.",
background=True
)
print(response.status)
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems = { ResponseItem.CreateUserMessageItem("Write me a very long story.") },
BackgroundModeEnabled = true
};
ResponseResult queued = await openAIClient.CreateResponseAsync(options);
Console.WriteLine($"Response id: {queued.Id}");
Console.WriteLine($"Status: {queued.Status}");
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await client.responses.create({
model: "MODEL_NAME",
input: "Write me a very long story.",
background: true,
});
console.log(response.status);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("Write a 1000-word essay on the history of computing.")
.background(true)
.build());
System.out.println(response.status());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": "Write me a very long story.",
"background": true
}'
Peiling voor voltooiing
Blijf polling uitvoeren zolang de status queued of in_progress is. Zodra het antwoord de terminalstatus heeft bereikt, is het beschikbaar voor het ophalen.
from time import sleep
while response.status in {"queued", "in_progress"}:
print(f"Current status: {response.status}")
sleep(2)
response = client.responses.retrieve(response.id)
print(f"Final status: {response.status}\nOutput:\n{response.output_text}")
#pragma warning disable OPENAI001
using System.Threading.Tasks;
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
ResponseResult current = await openAIClient.GetResponseAsync("<response_id>");
while (current.Status == ResponseStatus.Queued || current.Status == ResponseStatus.InProgress)
{
Console.WriteLine($"Current status: {current.Status}");
await Task.Delay(TimeSpan.FromSeconds(2));
current = await openAIClient.GetResponseAsync(current.Id);
}
Console.WriteLine($"Final status: {current.Status}");
if (current.Status == ResponseStatus.Completed)
{
Console.WriteLine(current.GetOutputText());
}
let current = response;
while (current.status === "queued" || current.status === "in_progress") {
console.log(`Current status: ${current.status}`);
await new Promise((r) => setTimeout(r, 2000));
current = await client.responses.retrieve(current.id);
}
console.log(`Final status: ${current.status}\nOutput:\n${current.output_text}`);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
Response current = openAIClient.responses().retrieve("<response_id>");
while (current.status().filter(s ->
s.equals(Response.Status.QUEUED) || s.equals(Response.Status.IN_PROGRESS)).isPresent()) {
System.out.println("Current status: " + current.status());
Thread.sleep(2000);
current = openAIClient.responses().retrieve(current.id());
}
System.out.println("Final status: " + current.status());
System.out.println("Output:\n" + current.outputText());
curl -X GET https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses/<response_id> \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY"
Een achtergrondtaak annuleren
Annuleer een lopende achtergrondtaak via het cancel-eindpunt. Annuleren is idempotent. Volgende aanroepen retourneren het uiteindelijke antwoordobject.
response = client.responses.cancel("<response_id>")
print(response.status)
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
ResponseResult cancelled = await openAIClient.CancelResponseAsync("<response_id>");
Console.WriteLine($"Status: {cancelled.Status}");
const cancelled = await client.responses.cancel("<response_id>");
console.log(cancelled.status);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
Response cancelled = openAIClient.responses().cancel("<response_id>");
System.out.println(cancelled.status());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses/<response_id>/cancel \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY"
Als u een achtergrondantwoord wilt streamen, stelt u zowel background als stream in op true. Met dit patroon kunt u streaming hervatten als de verbinding afneemt. Houd uw positie bij met de sequence_number uit elke gebeurtenis.
stream = client.responses.create(
model="MODEL_NAME",
input="Write me a very long story.",
background=True,
stream=True,
)
cursor = None
for event in stream:
print(event)
cursor = event["sequence_number"]
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
CreateResponseOptions createOptions = new()
{
Model = "MODEL_NAME",
InputItems = { ResponseItem.CreateUserMessageItem("Write me a very long story.") },
BackgroundModeEnabled = true,
StreamingEnabled = true
};
string queuedResponseId = null;
int lastSequenceNumber = 0;
await foreach (StreamingResponseUpdate update in openAIClient.CreateResponseStreamingAsync(createOptions))
{
if (update is StreamingResponseQueuedUpdate queuedUpdate)
{
queuedResponseId = queuedUpdate.Response.Id;
lastSequenceNumber = queuedUpdate.SequenceNumber;
Console.WriteLine($"Queued response: {queuedResponseId}, sequence {lastSequenceNumber}");
break;
}
}
// Resume streaming from where we disconnected.
GetResponseOptions resumeOptions = new(queuedResponseId)
{
StartingAfter = lastSequenceNumber,
StreamingEnabled = true
};
await foreach (StreamingResponseUpdate update in openAIClient.GetResponseStreamingAsync(resumeOptions))
{
Console.WriteLine(update.GetType().Name);
if (update is StreamingResponseCompletedUpdate completed)
{
Console.WriteLine($"[done] final id: {completed.Response.Id}");
}
}
const stream = await client.responses.create({
model: "MODEL_NAME",
input: "Write me a very long story.",
background: true,
stream: true,
});
let cursor = null;
for await (const event of stream) {
console.log(event);
cursor = event.sequence_number;
}
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.ResponseRetrieveParams;
import com.openai.models.responses.ResponseStreamEvent;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
long cursor = 0L;
try (StreamResponse<ResponseStreamEvent> stream = openAIClient.responses().retrieveStreaming(
"<response_id>",
ResponseRetrieveParams.builder().startingAfter(cursor).build())) {
stream.stream().forEach(event -> System.out.println(event));
}
curl -N -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": "Write me a very long story.",
"background": true,
"stream": true
}'
Achtergrondantwoorden hebben momenteel een hogere tijd-tot-eerste-token latentie dan synchrone antwoorden. Er worden verbeteringen doorgevoerd om deze kloof te verminderen.
Beperkingen
- Voor de achtergrondmodus is vereist
store=true. Staatloze aanvragen worden niet ondersteund.
- U kunt streaming alleen hervatten als het oorspronkelijke verzoek
stream=true bevat.
- Als u een synchrone reactie wilt annuleren, beëindigt u de verbinding rechtstreeks.
Streaming hervatten vanaf een specifiek punt
Als een streamingverbinding wegvalt, kunt u vanaf een bekende gebeurtenis hervatten door stream=true samen met starting_after=<sequence_number> mee te geven met het GET-antwoord. De service speelt gebeurtenissen die na dat sequentienummer zijn gegenereerd opnieuw af.
curl -N -X GET "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses/<response_id>?stream=true&starting_after=42" \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY"
Versleutelde redeneringsgereedschappen
Wanneer u de Responses API in staatloze modus (store=false) gebruikt, moet u de redeneercontext over meerdere gespreksbeurten heen behouden. Neem hiervoor versleutelde redeneringsitems op in uw aanvragen.
Als u redeneringsitems tussen beurten wilt behouden, voegt u reasoning.encrypted_content toe aan de parameter include. Het antwoord bevat vervolgens een versleutelde versie van de redeneringstracering, die u kunt doorgeven aan toekomstige aanvragen.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
response = client.responses.create(
model="MODEL_NAME",
reasoning={"effort": "medium"},
input="What is the weather like today?",
tools=[
# Replace with your function or tool definitions.
],
include=["reasoning.encrypted_content"],
store=False,
)
print(response.output_text)
#pragma warning disable OPENAI001
using System.Collections.Generic;
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
List<ResponseItem> inputItems =
[
ResponseItem.CreateUserMessageItem("<your_prompt>")
];
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
StoredOutputEnabled = false,
IncludedProperties = { IncludedResponseProperty.ReasoningEncryptedContent }
};
foreach (ResponseItem item in inputItems)
{
options.InputItems.Add(item);
}
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
// To carry encrypted reasoning into a follow-up turn, append response.OutputItems to inputItems
// and resend with StoredOutputEnabled = false. Don't use PreviousResponseId when not stored.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await client.responses.create({
model: "MODEL_NAME",
reasoning: { effort: "medium" },
input: "What is the weather like today?",
tools: [
// Replace with your function or tool definitions.
],
include: ["reasoning.encrypted_content"],
store: false,
});
console.log(response.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Reasoning;
import com.openai.models.responses.ReasoningEffort;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseIncludable;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("Explain quantum entanglement.")
.reasoning(Reasoning.builder().effort(ReasoningEffort.MEDIUM).build())
.addInclude(ResponseIncludable.REASONING_ENCRYPTED_CONTENT)
.store(false)
.build());
System.out.println(response.outputText());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"reasoning": {"effort": "medium"},
"input": "What is the weather like today?",
"tools": [],
"include": ["reasoning.encrypted_content"],
"store": false
}'
De Response-API maakt het genereren van afbeeldingen mogelijk als onderdeel van gesprekken en werkstromen met meerdere stappen. Het ondersteunt invoer en uitvoer van afbeeldingen binnen context en bevat ingebouwde hulpprogramma's voor het genereren en bewerken van afbeeldingen.
Vergeleken met de zelfstandige image-API biedt de Response-API twee voordelen:
-
Streaming: Deeluitvoer van afbeeldingen weergeven tijdens het genereren om de ervaren latentie te verbeteren.
-
Flexibele invoer: Accepteer afbeeldingsbestand-id's als invoer naast onbewerkte afbeeldingsbytes.
Opmerking
Het hulpprogramma voor het genereren van afbeeldingen in de Antwoorden-API wordt ondersteund door gpt-image-1-seriemodellen en u kunt het aanroepen vanuit een set compatibele chat- en redeneringsmodellen. Raadpleeg verderop in dit artikel de sectie Ondersteunde modellen voor de huidige lijst met ondersteunde orkestratiemodellen.
Het hulpprogramma voor het genereren van afbeeldingen biedt momenteel geen ondersteuning voor de streamingmodus. Als u gedeeltelijke afbeeldingen wilt streamen, roept u de API voor het genereren van afbeeldingen rechtstreeks aan buiten de Responses API.
Gebruik de Responses API om conversationele beeldervaringen te bouwen met GPT Image-modellen.
import base64
import os
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,
default_headers={
"x-ms-oai-image-generation-deployment": os.getenv("IMAGE_MODEL_NAME"),
"api_version": "preview",
},
)
response = client.responses.create(
model="MODEL_NAME",
input="Generate an image of a gray tabby cat hugging an otter with an orange scarf.",
tools=[{"type": "image_generation"}],
)
image_data = [
output.result
for output in response.output
if output.type == "image_generation_call"
]
if image_data:
with open("otter.png", "wb") as f:
f.write(base64.b64decode(image_data[0]))
#pragma warning disable OPENAI001
using System.IO;
using System.Threading.Tasks;
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
ImageGenerationTool imageTool = ResponseTool.CreateImageGenerationTool(model: "gpt-image-1");
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems =
{
ResponseItem.CreateUserMessageItem("Generate an image of an otter swimming in a pond.")
},
Tools = { imageTool }
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
foreach (ResponseItem item in response.OutputItems)
{
if (item is ImageGenerationCallResponseItem imageCall && imageCall.ImageResultBytes is not null)
{
await File.WriteAllBytesAsync("otter.png", imageCall.ImageResultBytes.ToArray());
Console.WriteLine($"Saved image. Revised prompt: {imageCall.RevisedPrompt}");
}
}
import fs from "fs";
import OpenAI from "openai";
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
"https://ai.azure.com/.default"
);
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: await tokenProvider(),
defaultHeaders: {
"x-ms-oai-image-generation-deployment": process.env.IMAGE_MODEL_NAME,
api_version: "preview",
},
});
const response = await client.responses.create({
model: "MODEL_NAME",
input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",
tools: [{ type: "image_generation" }],
});
const imageBase64 = response.output
.filter((o) => o.type === "image_generation_call")
.map((o) => o.result)[0];
if (imageBase64) {
fs.writeFileSync("otter.png", Buffer.from(imageBase64, "base64"));
}
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseOutputItem;
import com.openai.models.responses.Tool;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
Tool imageGen = Tool.ofImageGeneration(Tool.ImageGeneration.builder().build());
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")
.addTool(imageGen)
.build());
response.output().stream()
.filter(ResponseOutputItem::isImageGenerationCall)
.map(ResponseOutputItem::asImageGenerationCall)
.findFirst()
.flatMap(call -> call.result())
.ifPresent(b64 -> {
try {
Files.write(Paths.get("otter.png"), Base64.getDecoder().decode(b64));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-H "x-ms-oai-image-generation-deployment: $IMAGE_MODEL_NAME" \
-d '{
"model": "MODEL_NAME",
"input": "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",
"tools": [{ "type": "image_generation" }]
}'
Redeneringsmodellen
Zie de handleiding met redeneringsmodellen voor voorbeelden van het gebruik van redeneringsmodellen met de api voor antwoorden.
Computergebruik
Computergebruik met Playwright is verplaatst naar de speciale handleiding voor computergebruik.
Probleemoplossing
-
401/403: Als u Microsoft Entra ID gebruikt, controleert u of het token is afgestemd op
https://ai.azure.com/.default. Als u een API-sleutel gebruikt, controleert u of u de juiste sleutel voor de resource gebruikt.
-
404: Bevestig
model dat deze overeenkomt met uw implementatienaam.
Verwante inhoud