Użyj API odpowiedzi Azure OpenAI, aby generować odpowiedzi stanowe, wielotaktowe. Łączy ona funkcje uzupełniania czatów oraz interfejsu API Asystentów w jedno spójne doświadczenie. Użyj orkiestracji wielu agentów, aby delegować niezależne zadania do równoległych podagentów, albo użyj wyszukiwania narzędzi, aby ładować definicje narzędzi tylko wtedy, gdy model ich potrzebuje. Interfejs API odpowiedzi obsługuje również model napędzający computer-use-previewużycie komputera.
Aby uzyskać pełne opisy parametrów żądań i odpowiedzi, zobacz dokumentację parametrów interfejsu API odpowiedzi.
Wymagania wstępne
- Wdrożony model Azure OpenAI.
- Metoda uwierzytelniania:
- Klucz interfejsu API (na przykład
AZURE_OPENAI_API_KEY), lub
- Microsoft Entra ID (zalecane).
- Zainstaluj bibliotekę klienta dla swojego języka:
-
Python:
pip install openai azure-identity
-
.NET:
dotnet add package OpenAI i dotnet add package Azure.Identity
-
JavaScript/TypeScript:
npm install openai @azure/identity
-
Java: Dodaj
com.openai:openai-java i com.azure:azure-identity do projektu.
- W przykładach REST ustaw
AZURE_OPENAI_API_KEY (przepływ klucza API) lub AZURE_OPENAI_AUTH_TOKEN (przepływ Microsoft Entra ID).
Obsługiwane regiony
Przed uruchomieniem przykładów w tym artykule upewnij się, że region zasobu obsługuje interfejs API Responses. Interfejs API w wersji 1 jest wymagany do uzyskiwania dostępu do najnowszych funkcji. Aby uzyskać szczegółowe informacje, zobacz cykl życia wersji interfejsu API. Aby uzyskać pomoc regionalną dla usługi Agent Foundry, zobacz regionalną tabelę dostępności. Interfejs API Responses jest obecnie dostępny w następujących regionach:
- australiaeast
- brazilsouth
- canadacentral
- canadaeast
- centralny
- eastus
- eastus2
- francecentral
- germanywestcentral
- italynorth
- japaneast
- japanwest
- koreacentral
- northcentralus
- norwayeast
- polandcentral
- southafricanorth
- southcentralus
- południowo-wschodnia Azja
- Południowe Indie
- hiszpaniacentral
- swedencentral
- Szwajcaria Północ
- switzerlandwest
- uaenorth
- uksouth
- ukwest
- westcentralus
- Europa Zachodnia
- westus
- westus2
- westus3
Obsługiwane modele
Interfejs API odpowiedzi obsługuje następujące modele:
-
gpt-6.1-terra (Wersja: 2026-10-26)
-
gpt-6.1-sol (Wersja: 2026-09-29)
-
gpt-6-luna (Wersja: 2026-09-22)
-
gpt-6-sol (Wersja: 2026-09-22)
-
gpt-6-astra (Wersja: 2026-09-03)
-
gpt-5.6-sol (Wersja: 2026-07-09)
-
gpt-5.6-terra (Wersja: 2026-07-09)
-
gpt-5.6-luna (Wersja: 2026-07-09)
-
gpt-chat-latest (Wersje: 2026-10-07, 2026-08-06, 2026-06-24, 2026-05-28, 2026-05-05)
-
gpt-5.5 (Wersja: 2026-04-24)
-
gpt-5.4-nano (Wersja: 2026-03-17)
-
gpt-5.4-mini (Wersja: 2026-03-17)
-
gpt-5.4-pro (Wersja:2026-03-05)
-
gpt-5.4 (Wersja:2026-03-05)
-
gpt-5.3-chat (Wersja: 2026-03-03)
-
gpt-5.3-codex (Wersja: 2026-02-24)
-
gpt-5.2-codex (Wersja: 2026-01-14)
-
gpt-5.2 (Wersja: 2025-12-11)
-
gpt-5.2-chat (Wersja: 2025-12-11)
-
gpt-5.2-chat (Wersja: 2026-02-10)
-
gpt-5.1-codex-max (Wersja: 2025-12-04)
-
gpt-5.1 (Wersja: 2025-11-13)
-
gpt-5.1-chat (Wersja: 2025-11-13)
-
gpt-5.1-codex (Wersja: 2025-11-13)
-
gpt-5.1-codex-mini (Wersja: 2025-11-13)
-
gpt-5-pro (Wersja: 2025-10-06)
-
gpt-5-codex (Wersja: 2025-09-11)
-
gpt-5 (Wersja: 2025-08-07)
-
gpt-5-mini (Wersja: 2025-08-07)
-
gpt-5-nano (Wersja: 2025-08-07)
-
gpt-5-chat (Wersja: 2025-08-07)
-
gpt-5-chat (Wersja: 2025-10-03)
-
gpt-5-codex (Wersja: 2025-09-15)
-
gpt-4o(Wersje: 2024-11-20, , 2024-08-062024-05-13)
-
gpt-4o-mini (Wersja: 2024-07-18)
computer-use-preview
-
gpt-4.1 (Wersja: 2025-04-14)
-
gpt-4.1-nano (Wersja: 2025-04-14)
-
gpt-4.1-mini (Wersja: 2025-04-14)
-
gpt-image-1 (Wersja: 2025-04-15)
-
gpt-image-1-mini (Wersja: 2025-10-06)
-
gpt-image-1.5 (Wersja: 2025-12-16)
-
gpt-image-2.5-flare (Wersja: 2026-09-09)
-
gpt-image-2.5-sunburst (Wersja: 2026-09-09)
-
o1 (Wersja: 2024-12-17)
-
o3-mini (Wersja: 2025-01-31)
-
o3 (Wersja: 2025-04-16)
-
o4-mini (Wersja: 2025-04-16)
Nie każdy model jest dostępny w każdym obsługiwanym regionie. Sprawdź stronę modeli pod kątem dostępności regionu modelu.
Uwaga
Obecnie niewspierane:
- Generowanie obrazów za pomocą edycji wieloetapowej i przesyłania strumieniowego.
Istnieje znany problem z następującymi elementami:
- Plik PDF jako plik wejściowy jest teraz obsługiwany, ale ustawienie przeznaczenia przekazywania plików na
user_data nie jest obecnie obsługiwane.
- Problemy z wydajnością, gdy tryb w tle jest używany z przesyłaniem strumieniowym. Microsoft pracuje nad rozwiązaniem tego problemu.
Generowanie odpowiedzi tekstowej
Wygeneruj prostą odpowiedź tekstową przy użyciu interfejsu API odpowiedzi. Zastąp YOUR-RESOURCE-NAME i MODEL_NAME wartościami wdrożenia.
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."
}'
Klucz interfejsu API
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."
}'
Przykładowa odpowiedź
{
"id": "resp_67cb32528d6881909eb2859a55e18a85",
"created_at": 1741369938.0,
"output_text": "Great! How can I help you today?",
...
}
Pobieranie odpowiedzi
Pobierz odpowiedź na podstawie jej identyfikatora z poprzedniego wywołania Responses API.
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"
Klucz interfejsu API
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"
Przykładowa odpowiedź
{
"id": "resp_67cb61fa3a448190bcf2c42d96f0d1a8",
"output_text": "Hello! How can I assist you today?",
...
}
Usuwanie odpowiedzi
Domyślnie dane odpowiedzi są przechowywane przez 30 dni. Usuń przechowywaną odpowiedź na podstawie identyfikatora.
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"
Klucz interfejsu API
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"
Szyfrowanie przechowywanych danych odpowiedzi
Gdy interfejs API odpowiedzi utrwala historię komunikatów i powiązaną zawartość, usługa szyfruje te dane w spoczynku. Aby uzyskać wyjaśnienie dotyczące szyfrowania magazynu, zobacz Dane, prywatność i zabezpieczenia modeli sprzedawanych przez Azure w usłudze Microsoft Foundry. Aby uzyskać informacje na temat zakresu obsługi CMK i wymagań wstępnych, zobacz Szyfrowanie przy użyciu klucza zarządzanego przez klienta w usłudze Microsoft Foundry.
To szyfrowanie jest oddzielone od zaszyfrowanych elementów rozumowania zwracanych do aplikacji podczas zarządzania stanem konwersacji przy użyciu store=false.
Łączenie łańcuchów odpowiedzi
Łańcuch zmienia się przez przekazanie poprzedniego identyfikatora odpowiedzi do 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."
}'
Ręczne łączenie odpowiedzi
Alternatywnie możesz ręcznie przenieść elementy wyjściowe do przodu w następnym żądaniu.
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))
Kompaktowanie odpowiedzi
Kompaktowanie zmniejsza kontekst wejściowy przy zachowaniu podstawowego stanu dla późniejszych zmian.
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)
Uwaga
SDK platformy .NET nie zapewnia jeszcze silnie typizowanego interfejsu do kompaktowania odpowiedzi. Zobacz kartę REST, aby sprawdzić strukturę wywołania, lub wywołaj metodę protokołu bezpośrednio za pomocą BinaryContent formatu 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": "..."}]
}
]
}'
Kompaktowanie przy użyciu zwracanych elementów
Można skompaktować wszystkie elementy zwracane z poprzednich żądań, takich jak rozumowanie, komunikat, wywołanie funkcji itp.
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)
Kompaktowanie przy użyciu poprzedniego identyfikatora odpowiedzi
Można również skompresować, używając poprzedniego identyfikatora odpowiedzi.
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)
Kompaktowanie po stronie serwera
Można także użyć kompaktowania po stronie serwera bezpośrednio w odpowiedziach (POST /responses lub client.responses.create) poprzez ustawienie context_management, używając compact_threshold.
- Gdy liczba tokenów wyjściowych przekroczy skonfigurowany próg, interfejs API odpowiedzi automatycznie uruchamia kompaktowanie.
- W tym trybie nie trzeba wywoływać
/responses/compact oddzielnie.
- Odpowiedź zawiera zaszyfrowany element kompaktowania.
- Kompaktowanie po stronie serwera będzie działać po ustawieniu store=false w żądaniach utworzenia odpowiedzi.
Element kompaktowania przenosi dalej niezbędny poprzedni stan i rozumowanie w kolejnym etapie, używając mniej tokenów. Jest nieprzezroczyste i nie ma być czytelne dla człowieka.
Jeśli używasz bezstanowego łańcucha tablic wejściowych, dołącz elementy wyjściowe jak zwykle. Jeśli używasz previous_response_id, przekaż tylko nowy komunikat użytkownika przy każdej iteracji. W obu wzorcach element kompaktowania przenosi kontekst wymagany do następnego okna.
Wskazówka
Po dołączeniu elementów wyjściowych do poprzednich elementów wejściowych można usunąć elementy, które pojawiły się przed najnowszym elementem kompaktowania, aby zachować mniejsze żądania i zmniejszyć opóźnienie długiego ogona. Ostatni element kompresji niesie ze sobą niezbędny kontekst do kontynuowania rozmowy. Jeśli używasz previous_response_id łączenia, nie należy przycinać ręcznie.
Flow
- Zadzwoń
responses jak zwykle. Dodaj context_management z compact_threshold aby włączyć kompaktowanie po stronie serwera.
- Jeśli dane wyjściowe przekroczą próg, usługa wyzwala kompaktowanie, emituje element kompaktowania w strumieniu wyjściowym i czyści kontekst przed kontynuowaniem wnioskowania.
- Kontynuuj konwersację przy użyciu jednego z następujących wzorców:
- Bezstanowe tworzenie łańcuchów tablic wejściowych: dołączanie elementów wyjściowych, w tym elementów kompaktowania, do następnej tablicy wejściowej.
-
previous_response_id chaining: przekaż tylko nowy komunikat użytkownika na każdym etapie i przekazuj najnowszy identyfikator odpowiedzi na kolejny etap.
Przykład
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(),
}
)
Transmisja strumieniowa
Przesyłaj strumieniowo odpowiedź w miarę jego generowania, ustawiając wartość stream=true. Usługa emituje zdarzenia przyrostowe, które można wykorzystać do wyświetlania wyniku token po tokenie.
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
}'
Podczas strumieniowania, jeśli w jego trakcie wystąpi błąd, system podejmuje wewnętrzne próby ponowienia, aby go usunąć. Jeśli żądanie nadal kończy się niepowodzeniem, usługa napotka nieodwracalny błąd. W takich przypadkach kod odpowiedzi HTTP wynosi 200 (sukces), ale zdarzenie błędu w strumieniu zawiera szczegółowe informacje o błędach występujących w trakcie strumieniowania.
Serwer zwraca następujące typy błędów:
| Typ błędu |
Można przetłumaczyć jako |
server_error |
Kod zwrotny 500 |
too_many_requests |
Kod zwrotny 429 |
forbidden |
Kod zwrotny 403 |
user_error |
Kod zwrotny 400 |
Przykładowe zdarzenie błędu:
{
"type": "error",
"error": {
"type": "too_many_requests",
"code": "no_capacity",
"headers": {
"skip-error-remapping": "true"
},
"message": "The system is currently experiencing high demand and cannot process your request. Your request exceeds the maximum usage size allowed during peak load. For improved capacity reliability, consider switching to Provisioned Throughput.",
"param": null
}
}
Aplikacje powinny wykrywać te błędy i bezpiecznie zatrzymywać lub ponownie uruchamiać przesyłanie strumieniowe. Nie są naliczane opłaty za tokeny generowane podczas nieudanych odpowiedzi przesyłania strumieniowego.
Dane wyjściowe ze strukturą
Użyj ustrukturyzowanych danych wyjściowych, aby wykonać odpowiedź zgodnie ze schematem JSON. W żądaniu do Responses API zdefiniuj schemat w text.format. Chat Completions używa zamiast tego response_format. Przykłady SDK i interfejsu REST, obsługiwane ograniczenia schematu oraz ograniczenia znajdziesz w sekcji Ustrukturyzowane dane wyjściowe.
Wywoływanie funkcji
API Responses obsługuje wywołania funkcji.
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?"
}'
Obsługa barier zabezpieczających i filtrowania zawartości
Zastosuj zabezpieczenia (filtry zawartości) na poziomie wdrożenia. Każdy skonfigurowany mechanizm kontroli ocenia obsługiwaną zawartość i punkty interwencji: filtry podstawowych zagrożeń oceniają dane wejściowe i wyjściowe, wykrywanie ataków na prompt użytkownika ocenia dane wejściowe użytkownika, a wykrywanie ataków na dokument ocenia zawartość dokumentu po włączeniu. Skonfiguruj zabezpieczenia oddzielnie. Aby uzyskać więcej informacji, zobacz Konfigurowanie poręczy i kontrolek. W tej sekcji pokazano, jak wykrywać i obsługiwać wyniki działania mechanizmu guardrails podczas wywoływania interfejsu API Responses.
Interfejs API Responses prezentuje wyniki mechanizmów zabezpieczających inaczej niż Chat Completions. Zamiast pól prompt_filter_results i content_filter_results, które zwracają uzupełnienia czatu, obiekt odpowiedzi zawiera tablicę content_filters na najwyższym poziomie. Każdy wpis opisuje jeden wynik filtru.
| Pole |
Opis |
blocked |
Czy zawartość została zablokowana. |
source_type |
Czy wynik dotyczy prompt (danych wejściowych) czy completion (danych wyjściowych). |
content_filter_results |
Wyniki kategorii, takie jak hate, sexual, violence i self_harm, z poziomami ważności, oraz opcjonalne kategorie, takie jak jailbreak, indirect_attack, protected_material_text i protected_material_code. |
content_filter_offsets |
Przesunięcia znaków, do których odnosi się wynik. |
Uwaga
Tablica content_filters jest rozszerzeniem Microsoft Foundry, które nie jest częścią podstawowego schematu odpowiedzi OpenAI, więc zestawy SDK nie uwidaczniają dla niej właściwości wpisanej. Odczytaj je jako nieprzetworzone lub dodatkowe pole, jak pokazano w poniższych przykładach.
Gdy zabezpieczenia blokują dane wejściowe, interfejs API zwraca błąd HTTP 400 z kodem content_filter. Przechwyć ten błąd, aby we właściwy sposób obsłużyć zablokowane polecenia.
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
)
# A blocked prompt raises BadRequestError with the code "content_filter"
try:
response = client.responses.create(
model="MODEL_NAME",
input="This is a test."
)
print(response.output_text)
except BadRequestError as error:
if error.code == "content_filter":
print("The prompt was blocked by a guardrail.")
else:
raise
#pragma warning disable OPENAI001
using OpenAI.Responses;
using System.ClientModel;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems = { ResponseItem.CreateUserMessageItem("This is a test.") }
};
// A blocked prompt throws ClientResultException with HTTP 400
try
{
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
}
catch (ClientResultException error) when (error.Status == 400)
{
Console.WriteLine("The prompt was blocked by a guardrail.");
}
import { OpenAI, APIError } from "openai";
const openai = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
// A blocked prompt throws APIError with the code "content_filter"
try {
const response = await openai.responses.create({
model: "MODEL_NAME",
input: "This is a test."
});
console.log(response.output_text);
} catch (error) {
if (error instanceof APIError && error.code === "content_filter") {
console.log("The prompt was blocked by a guardrail.");
} else {
throw error;
}
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.AzureApiKeyCredential;
import com.openai.errors.BadRequestException;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1")
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
ResponseCreateParams params = ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("This is a test.")
.build();
// A blocked prompt throws BadRequestException (HTTP 400)
try {
Response response = openAIClient.responses().create(params);
System.out.println(response.outputText());
} catch (BadRequestException error) {
System.out.println("The prompt was blocked by a guardrail.");
}
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."
}'
Gdy zabezpieczenia blokują dane wejściowe, interfejs API zwraca kod HTTP 400 z kodem content_filter:
{
"error": {
"code": "content_filter",
"message": "The response was filtered due to the prompt triggering content management policy."
}
}
Odczytywanie adnotacji zabezpieczających
Gdy żądanie zakończy się pomyślnie, odczytaj z odpowiedzi tablicę content_filters, aby sprawdzić wyniki zabezpieczeń dla danych wejściowych i wyjściowych.
W trybie adnotacji skonfigurowane kontrolki mogą zgłaszać poziom ważności lub wyniki wykrywania bez ich wymuszania. Odpowiadające wartości blocked i filtered pozostają false. Tryb adnotacji dla czterech kategorii podstawowych szkód wymaga zatwierdzenia zmodyfikowanych Guardrails.
import os
from openai import OpenAI
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."
)
# content_filters is an Azure extension, so read it from model_extra
content_filters = response.model_extra.get("content_filters", [])
for result in content_filters:
print(f"Source: {result['source_type']}, Blocked: {result['blocked']}")
#pragma warning disable OPENAI001
using OpenAI.Responses;
using System.ClientModel;
using System.ClientModel.Primitives;
using System.Text.Json;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems = { ResponseItem.CreateUserMessageItem("This is a test.") }
};
// content_filters has no typed property, so parse it from the raw response
ClientResult<ResponseResult> result = await openAIClient.CreateResponseAsync(options);
using JsonDocument doc = JsonDocument.Parse(result.GetRawResponse().Content);
if (doc.RootElement.TryGetProperty("content_filters", out JsonElement filters))
{
foreach (JsonElement filter in filters.EnumerateArray())
{
string source = filter.GetProperty("source_type").GetString()!;
bool blocked = filter.GetProperty("blocked").GetBoolean();
Console.WriteLine($"Source: {source}, Blocked: {blocked}");
}
}
import { OpenAI } from "openai";
const openai = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await openai.responses.create({
model: "MODEL_NAME",
input: "This is a test."
});
// content_filters is an Azure extension not in the typed response
const contentFilters = response.content_filters ?? [];
for (const result of contentFilters) {
console.log(`Source: ${result.source_type}, Blocked: ${result.blocked}`);
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.AzureApiKeyCredential;
import com.openai.core.JsonValue;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1")
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
ResponseCreateParams params = ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("This is a test.")
.build();
Response response = openAIClient.responses().create(params);
// content_filters has no typed accessor, so read it from additional properties
JsonValue contentFilters = response._additionalProperties().get("content_filters");
System.out.println(contentFilters);
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."
}'
Tablica content_filters pojawia się w obiekcie odpowiedzi:
{
"id": "resp_<id>",
"content_filters": [
{
"source_type": "prompt",
"blocked": false,
"content_filter_results": {
"hate": { "filtered": false, "severity": "safe" },
"self_harm": { "filtered": false, "severity": "safe" },
"sexual": { "filtered": false, "severity": "safe" },
"violence": { "filtered": false, "severity": "safe" }
}
}
]
}
Aby dowiedzieć się więcej o kategoriach zabezpieczeń i poziomach ważności, zobacz Omówienie zabezpieczeń oraz Praca z adnotacjami.
Interpreter kodu
Narzędzie interpretera kodu umożliwia modelom pisanie i wykonywanie kodu Python w bezpiecznym środowisku piaskownicy (sandbox). Obsługuje szereg zaawansowanych zadań, w tym:
- Przetwarzanie plików o różnych formatach danych i strukturach
- Generowanie plików zawierających dane i wizualizacje (na przykład grafy)
- Iteracyjne pisanie i uruchamianie kodu w celu rozwiązania problemów — modele mogą debugować i ponawiać próbę kodu do momentu pomyślnego
- Ulepszanie rozumowania wizualnego w obsługiwanych modelach (na przykład o3, o4-mini) przez włączenie przekształceń obrazów, takich jak przycinanie, powiększanie i obracanie
- To narzędzie jest szczególnie przydatne w scenariuszach obejmujących analizę danych, obliczenia matematyczne i generowanie kodu.
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
Ważne
Interpreter kodu ma dodatkowe opłaty wykraczające poza opłaty oparte na tokenach dla użycia usługi Azure OpenAI. Jeśli interfejs API odpowiedzi wywołuje interpreter kodu jednocześnie w dwóch różnych wątkach, tworzone są dwie sesje interpretera kodu. Każda sesja wiąże się z opłatami za minutę, a minimalna opłata wynosi pięć minut. Sesja pozostaje aktywna, o ile uzyskujesz dostęp do kontenera w ciągu 20-minutowego limitu czasu bezczynności.
Narzędzie Interpreter kodu wymaga kontenera — w pełni odizolowanej maszyny wirtualnej, na której model może wykonywać kod w Pythonie. Kontenery mogą zawierać przekazane pliki lub pliki wygenerowane podczas wykonywania.
Aby utworzyć kontener, określ "container": { "type": "auto", "file_ids": ["file-1", "file-2"] } w konfiguracji narzędzia podczas tworzenia nowego obiektu Response. Spowoduje to automatyczne utworzenie nowego kontenera lub ponowne użycie aktywnego kontenera z wcześniejszego wywołania `code_interpreter_call` w kontekście modelu. Element code_interpreter_call w danych wyjściowych interfejsu API będzie zawierać wygenerowane container_id. Ten kontener wygasa, jeśli nie jest używany przez 20 minut.
Obowiązują następujące limity plików:
- Żądanie może zawierać maksymalnie 50 identyfikatorów plików.
- Kontener może przechowywać łącznie do 1000 plików, w tym pliki wejściowe i pliki generowane przez interpreter kodu.
Podczas uruchamiania interpretera kodu model może utworzyć własne pliki. Jeśli na przykład zostanie poproszony o utworzenie wykresu lub pliku CSV, utworzy te elementy bezpośrednio w twoim kontenerze. Przytacza te pliki w adnotacjach kolejnej wiadomości.
Wszystkie pliki w danych wejściowych modelu są automatycznie przekazywane do kontenera. Nie trzeba ręcznie przekazywać go do kontenera.
Obsługiwane pliki
| Format pliku |
typ MIME |
.c |
tekst/x-c |
.cs |
text/x-csharp |
.cpp |
text/x-c++ |
.csv |
tekst/csv |
.doc |
application/msword |
.docx |
application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.html |
tekst/html |
.java |
text/x-java |
.json |
application/json |
.md |
tekst/markdown |
.pdf |
aplikacja/plik PDF |
.php |
text/x-php |
.pptx |
application/vnd.openxmlformats-officedocument.presentationml.presentation |
.py |
text/x-python |
.py |
text/x-script.python |
.rb |
tekst/x-ruby |
.tex |
text/x-tex |
.txt |
tekst/zwykły |
.css |
tekst/css |
.js |
text/JavaScript |
.sh |
application/x-sh |
.ts |
application/TypeScript |
.csv |
aplikacja/csv |
.jpeg |
image/jpeg |
.jpg |
image/jpeg |
.gif |
obraz/gif |
.pkl |
application/octet-stream |
.png |
image/png |
.tar |
aplikacja/x-tar |
.xlsx |
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.xml |
application/xml lub "text/xml" |
.zip |
aplikacja/zip |
Pobierz elementy wejściowe, które zostały przesłane w odpowiedzi. Jest to przydatne do sprawdzania pełnego kontekstu konwersacji, w tym wszystkich elementów dodanych przez model (na przykład wywołań funkcji lub elementów kompaktowania).
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))
Uwaga
Zestaw SDK .NET uwidacznia ten punkt końcowy tylko jako metodę protokołu. Zobacz na karcie REST postać wywołania lub bezpośrednio wywołaj metodę protokołu.
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"
Przykładowa odpowiedź
{
"object": "list",
"data": [
{
"id": "msg_...",
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "This is a test."}]
}
]
}
Modele obsługujące analizę obrazu mogą interpretować obrazy razem z tekstem. Mogą rozpoznawać obiekty, kształty, kolory i tekstury oraz odczytywać tekst zawarty na obrazie, z zastrzeżeniem ograniczeń wymienionych w dalszej części tego artykułu.
Obraz można podać jako dane wejściowe żądania w dowolny z następujących sposobów:
- W pełni kwalifikowany adres URL do pliku obrazu
- URI danych zakodowany w Base64
- Identyfikator pliku utworzony za pomocą interfejsu API plików
Adres URL obrazu
Odwołuj się do obrazu hostowanego pod publicznym adresem URL. Model pobiera obraz i dołącza go jako część zawartości wejściowej.
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>"}
]
}
]
}'
Obraz zakodowany w formacie Base64
Wyślij obraz bezpośrednio, kodując jego bajty jako URI danych base64. Użyj tego wzorca, gdy obraz nie jest hostowany pod publicznym adresem URL lub gdy chcesz uniknąć dodatkowego pobierania sieci.
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>"}
]
}
]
}'
Identyfikator pliku
Przekaż obraz za pomocą interfejsu API plików przy użyciu polecenia purpose="assistants", a następnie odwołaj się do zwróconego identyfikatora pliku w żądaniu. Takie podejście jest przydatne, gdy chcesz ponownie użyć tego samego obrazu w wielu żądaniach bez ponownego wysłania bajtów.
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")
)
def create_file(file_path):
with open(file_path, "rb") as file_content:
result = client.files.create(
file=file_content,
purpose="assistants",
)
return result.id
file_id = create_file("path_to_your_image.jpg")
response = client.responses.create(
model="MODEL_NAME",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": "What is in this image?"},
{"type": "input_image", "file_id": file_id},
],
}
],
)
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;
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[] imageBytes = await File.ReadAllBytesAsync("path_to_your_image.jpg");
OpenAIFile uploadedFile = await fileClient.UploadFileAsync(
BinaryData.FromBytes(imageBytes),
"path_to_your_image.jpg",
FileUploadPurpose.Assistants);
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems =
{
ResponseItem.CreateUserMessageItem(
[
ResponseContentPart.CreateInputTextPart("What is in this image?"),
ResponseContentPart.CreateInputImagePart(uploadedFile.Id)
])
}
};
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("path_to_your_image.jpg"),
purpose: "assistants",
});
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", file_id: file.id },
],
},
],
});
console.log(response.output_text);
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.AzureApiKeyCredential;
import com.openai.models.files.FileCreateParams;
import com.openai.models.files.FileObject;
import com.openai.models.files.FilePurpose;
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.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("path_to_your_image.jpg"))
.purpose(FilePurpose.ASSISTANTS)
.build());
ResponseInputImage image = ResponseInputImage.builder()
.detail(ResponseInputImage.Detail.AUTO)
.fileId(uploaded.id())
.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());
# Upload the image
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/files \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-F purpose="assistants" \
-F file="@path_to_your_image.jpg"
# 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_text", "text": "What is in this image?"},
{"type": "input_image", "file_id": "<file_id>"}
]
}
]
}'
W poniższej tabeli wymieniono obsługiwane typy plików dla danych wejściowych obrazu.
| Typ pliku |
typ MIME |
| PNG |
image/png |
| JPEG |
image/jpeg |
| WebP |
image/webp |
| Nieanimowany GIF |
image/gif |
W jednym żądaniu można uwzględnić maksymalnie 50 obrazów. Każdy pojedynczy plik obrazu musi mieć rozmiar poniżej 512 MB, a łączny rozmiar monitu, w tym wszystkie obrazy w żądaniu, również musi wynosić poniżej 512 MB.
Obrazy muszą spełniać następujące dodatkowe wymagania:
- Obraz musi być odpowiedni dla monitu; model nie jest przeznaczony dla niepowiązanej zawartości wizualnej.
- Obrazy nie powinny zawierać szkodliwej ani poufnej zawartości naruszającej zasady zawartości.
- Pliki obrazów nie mogą być uszkodzone ani nieczytelne. Jeśli model nie może przetworzyć obrazu, żądanie zakończy się niepowodzeniem.
Wybieranie poziomu szczegółów obrazu
Użyj właściwości detail we fragmencie zawartości input_image, aby określić, jak model przetwarza obraz. Niższy poziom szczegółowości zużywa mniej tokenów i działa szybciej, natomiast wyższy poziom szczegółowości zużywa więcej tokenów, ale pozwala modelowi wychwytywać drobniejsze cechy.
{
"type": "input_image",
"image_url": "<image_url>",
"detail": "high"
}
W poniższej tabeli opisano każdy poziom szczegółów.
| Poziom podsumowania |
Opis |
low |
Model używa wersji obrazu o niższej rozdzielczości. Ta opcja używa najmniejszych tokenów i generuje najszybszą odpowiedź, ale model może przegapić szczegółowe informacje. |
high |
Model używa wersji obrazu o wyższej rozdzielczości. Ta opcja przechwytuje bardziej szczegółowe informacje, ale używa większej liczby tokenów i trwa dłużej. |
auto |
Domyślnie. Model wybiera odpowiedni poziom szczegółów na podstawie obrazu i monitu. |
Modele z obsługą przetwarzania obrazów mają następujące ograniczenia:
-
Obrazy medyczne: Model nie jest odpowiedni do interpretacji wyspecjalizowanych obrazów medycznych, takich jak skany CT i nie powinien być używany do porad medycznych.
-
Tekst inny niż angielski: model może nie działać optymalnie podczas obsługi obrazów zawierających tekst w alfabetach innych niż łacińskich, takich jak japoński lub koreański.
-
Mały tekst: powiększanie tekstu na obrazie w celu zwiększenia czytelności, ale unikaj przycinania ważnych szczegółów.
-
Rotacja: model może źle interpretować obracany lub do góry nogami tekst i obrazy.
-
Elementy wizualne: model może zmagać się z grafami lub tekstami, w których kolory lub style — takie jak stałe, kreskowane lub kropkowane — różnią się.
-
Rozumowanie przestrzenne: model ma trudności z zadaniami wymagającymi dokładnej lokalizacji przestrzennej, takich jak identyfikowanie pozycji szachowych.
-
Dokładność: w niektórych przypadkach model może generować niepoprawne opisy lub podpisy.
-
Kształt obrazu: Ten model ma trudności z obrazów panoramicznych i z efektem rybiego oka.
-
Metadane i zmiana rozmiaru: model nie przetwarza oryginalnych nazw plików ani metadanych, a obrazy są zmieniane przed analizą, co wpływa na ich oryginalne wymiary.
-
Liczenie: model może dać przybliżone liczby obiektów na obrazach.
-
CAPTCHAs: Ze względów bezpieczeństwa system jest przeznaczony do blokowania przesyłania capTCHAs.
Modele z możliwościami przetwarzania obrazów obsługują dane wejściowe w formacie PDF. Plik PDF można udostępnić na dowolny z następujących sposobów:
- Dane zakodowane w Base64
- Identyfikator pliku utworzony za pomocą interfejsu API plików
- Adres URL pliku zewnętrznego (
file_url)
Aby ułatwić modelom interpretowanie zawartości PDF, kontekst modelu zawiera zarówno wyodrębniony tekst, jak i obraz każdej strony. Ta funkcja jest przydatna, gdy kluczowe informacje są przekazywane za pośrednictwem diagramów lub zawartości nietekstowej.
Uwaga
- Cały wyodrębniony tekst i obrazy są umieszczane w kontekście modelu. Upewnij się, że rozumiesz wpływ cen i użycia tokenów na używanie plików PDF jako danych wejściowych.
- W jednym żądaniu interfejsu API można dołączyć więcej niż jeden plik, ale każdy plik musi mieć wartość poniżej 50 MB. Łączny limit dla wszystkich plików w żądaniu wynosi 50 MB.
- Tylko modele, które obsługują zarówno dane wejściowe tekstu, jak i obrazów, mogą akceptować pliki PDF jako dane wejściowe.
- Obsługa
purposeuser_data nie jest obecnie dostępna. Jako tymczasowe obejście należy ustawić cel na assistants.
Konwertowanie formatu PDF na format Base64 i analizowanie
Wyślij plik PDF bezpośrednio, kodując jego bajty jako URI danych w formacie base64. Model odbiera wyodrębniony tekst i renderowany obraz każdej strony.
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."}
]
}
]
}'
Przekazywanie plików PDF i analizowanie
Przekaż plik PDF za pomocą polecenia purpose="assistants".
purpose z user_data nie jest obecnie obsługiwany.
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;
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.Assistants);
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.files.FileCreateParams;
import com.openai.models.files.FileObject;
import com.openai.models.files.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.ASSISTANTS)
.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/v1/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."}
]
}
]
}'
Analizowanie pliku PDF z zewnętrznego adresu URL pliku
Odwołuj się do pliku PDF hostowanego pod publicznie dostępnym adresem URL przy użyciu file_url właściwości input_file elementu zawartości. Nie musisz najpierw pobierać, kodować ani przesyłać pliku.
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": "Analyze the letter and provide a summary of the key points.",
},
{
"type": "input_file",
"file_url": "https://www.berkshirehathaway.com/letters/2024ltr.pdf",
},
],
},
]
)
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("Analyze the letter and provide a summary of the key points."),
ResponseContentPart.CreateInputFilePart(new Uri("https://www.berkshirehathaway.com/letters/2024ltr.pdf"))
])
}
};
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: "Analyze the letter and provide a summary of the key points.",
},
{
type: "input_file",
file_url: "https://www.berkshirehathaway.com/letters/2024ltr.pdf",
},
],
},
],
});
console.log(response.output_text);
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
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.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();
ResponseInputFile file = ResponseInputFile.builder()
.fileUrl("https://www.berkshirehathaway.com/letters/2024ltr.pdf")
.build();
ResponseInputItem userMsg = ResponseInputItem.ofMessage(
ResponseInputItem.Message.builder()
.role(ResponseInputItem.Message.Role.USER)
.addInputTextContent("Analyze the letter and provide a summary of the key points.")
.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_text",
"text": "Analyze the letter and provide a summary of the key points."
},
{
"type": "input_file",
"file_url": "https://www.berkshirehathaway.com/letters/2024ltr.pdf"
}
]
}
]
}'
Używanie zdalnych serwerów MCP
Możliwości modelu można rozszerzyć, łącząc go z narzędziami hostowanymi na zdalnych serwerach protokołu KONTEKSTU modelu (MCP). Te serwery są obsługiwane przez deweloperów i organizacje i udostępniają narzędzia, które są dostępne dla klientów kompatybilnych z MCP, takich jak API odpowiedzi.
Model Context Protocol (MCP) to otwarty standard, który definiuje sposób, w jaki aplikacje udostępniają narzędzia i dane kontekstowe dużym modelom językowym (LLMs). Umożliwia spójną, skalowalną integrację narzędzi zewnętrznych z przepływami pracy modelu.
W poniższym przykładzie pokazano, jak używać zdalnego serwera MCP do wykonywania zapytań dotyczących informacji o repozytorium interfejsu API REST Azure. Model pobiera i analizuje zawartość repozytorium w czasie rzeczywistym.
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?"
}'
Narzędzie MCP działa tylko w interfejsie API odpowiedzi i jest dostępne we wszystkich nowszych modelach (gpt-4o, gpt-4.1 i naszych modelach rozumowania). W przypadku korzystania z narzędzia MCP płacisz tylko za tokeny używane podczas importowania definicji narzędzi lub wykonywania wywołań narzędzi — nie są naliczane żadne dodatkowe opłaty.
Zatwierdzenia
Domyślnie interfejs API odpowiedzi wymaga jawnego zatwierdzenia przed udostępnieniem jakichkolwiek danych zdalnemu serwerowi MCP. Ten krok zatwierdzania pomaga zapewnić przejrzystość i zapewnia kontrolę nad tym, jakie informacje są wysyłane zewnętrznie.
Zalecamy przejrzenie wszystkich danych udostępnianych zdalnym serwerom MCP i opcjonalne rejestrowanie ich na potrzeby inspekcji.
Gdy wymagane jest zatwierdzenie, model zwraca mcp_approval_request element w danych wyjściowych odpowiedzi. Ten obiekt zawiera szczegóły oczekującego żądania i umożliwia inspekcję lub modyfikowanie danych przed kontynuowaniem.
{
"id": "mcpr_682bd9cd428c8198b170dc6b549d66fc016e86a03f4cc828",
"type": "mcp_approval_request",
"arguments": {},
"name": "fetch_azure_rest_api_docs",
"server_label": "github"
}
Aby kontynuować zdalne wywołanie MCP, należy odpowiedzieć na żądanie zatwierdzenia, tworząc nowy obiekt odpowiedzi zawierający element mcp_approval_response. Ten obiekt potwierdza zamiar umożliwienia modelowi wysyłania określonych danych do zdalnego serwera MCP.
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>"
}
]
}'
Uwierzytelniania
Ważne
- Klient MCP w interfejsie API odpowiedzi wymaga protokołu TLS 1.2 lub nowszego.
- Mutual TLS (mTLS) nie jest obecnie obsługiwany.
-
Tagi usług Azure nie są obecnie obsługiwane dla ruchu klienta MCP.
W przeciwieństwie do serwera GitHub MCP większość zdalnych serwerów MCP wymaga uwierzytelniania. Narzędzie MCP w interfejsie API odpowiedzi obsługuje nagłówki niestandardowe, co umożliwia bezpieczne łączenie się z tymi serwerami przy użyciu wymaganego schematu uwierzytelniania.
Możesz określić nagłówki, takie jak klucze interfejsu API, tokeny dostępu OAuth lub inne poświadczenia bezpośrednio w swoim żądaniu. Najczęściej używany nagłówek to nagłówek Authorization.
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"}
}
]
}'
Zadania w tle
Tryb w tle umożliwia asynchroniczne wykonywanie długotrwałych zadań przy użyciu modeli rozumowania, takich jak o3 i o1-pro. Jest to przydatne w przypadku złożonych zadań, które mogą potrwać kilka minut (na przykład agentów w stylu Codex lub Deep Research). Po wysłaniu żądania z użyciem "background": true zadanie jest przetwarzane asynchronicznie, a następnie sprawdzasz jego stan.
Uruchamianie zadania w tle
Ustaw background=true w żądaniu, aby dodać zadanie do kolejki. Usługa zwraca natychmiast identyfikator odpowiedzi i queued stan — użyj tego identyfikatora, aby sondować, przesyłać strumieniowo lub anulować zadanie.
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
}'
Sonduj pod kątem ukończenia
Kontynuuj sondowanie, gdy stan to queued lub in_progress. Gdy odpowiedź osiągnie stan terminalu, jest ona dostępna do pobierania.
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"
Anulowanie zadania w tle
Anuluj trwające zadanie w tle za pomocą punktu końcowego cancel. Anulowanie jest idempotentne — kolejne wywołania zwracają końcowy obiekt odpowiedzi.
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"
Aby strumieniować odpowiedź w tle, ustaw zarówno background, jak i stream na true. Ten wzorzec umożliwia wznowienie przesyłania strumieniowego, jeśli połączenie spadnie. Śledź swoją pozycję za pomocą sequence_number z każdego zdarzenia.
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
}'
Odpowiedzi w tle mają obecnie większe opóźnienie od pierwszego tokenu niż odpowiedzi synchroniczne. W toku wprowadzono ulepszenia w celu zmniejszenia tej luki.
Ograniczenia
- Tryb tła wymaga
store=true. Żądania bezstanowe nie są obsługiwane.
- Przesyłanie strumieniowe można wznowić tylko wtedy, gdy oryginalne żądanie zawierało element
stream=true.
- Aby anulować synchroniczną odpowiedź, zakończ połączenie bezpośrednio.
Wznawianie przesyłania strumieniowego z określonego punktu
Jeśli połączenie strumieniowe zostanie przerwane, możesz wznowić od znanego zdarzenia, przekazując stream=true wraz z starting_after=<sequence_number> w odpowiedzi GET. Usługa odtwarza zdarzenia emitowane po tym numerze sekwencji.
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"
Szyfrowane rozumowanie
Jeśli używasz modelu rozumowania z interfejsem Responses API w trybie bezstanowym (store=false), aplikacja dostarcza kontekst dla każdego kolejnego żądania. Wcześniejsze wiadomości zawierają historię konwersacji, ale nie zawierają wewnętrznego rozumowania modelu. Zaszyfrowany element zawierający tok rozumowania umożliwia przenoszenie zgodnego kontekstu rozumowania do późniejszego żądania bez uwidaczniania tego rozumowania jako czytelnego tekstu w aplikacji.
Dlaczego warto używać szyfrowanego wnioskowania?
Użyj szyfrowanego rozumowania, gdy aplikacja zarządza stanem konwersacji i musi kontynuować wieloetapowy przepływ pracy rozumowania. Na przykład użytkownik może zadać pytanie uzupełniające lub model może wywołać narzędzie, a następnie kontynuować po otrzymaniu wyniku.
Przekazywanie wcześniejszych komunikatów nie przekazuje samego kontekstu rozumowania modelu z poprzedniej tury. Zaszyfrowany element rozumowania przenosi ten kontekst do przodu, zachowując zawartość nieczytelną dla aplikacji.
Korzystanie
- Ustaw wartość
store=false. Aby jawnie zażądać zaszyfrowanego rozumowania, dodaj reasoning.encrypted_content do parametru include , jak pokazano w poniższych przykładach.
- Zachowaj wszystkie zwrócone elementy wyjściowe w ich oryginalnej kolejności, w tym elementy rozumowania z właściwością
encrypted_content .
- W następnym wywołaniu uwzględnij te elementy z innymi odpowiednimi elementami rozmowy w elemencie
input i nadal ustawiaj store=false. Nie należy używać previous_response_id w przypadku niezapisanej odpowiedzi.
Odpowiedzi bezstanowe domyślnie zwracają zaszyfrowaną zawartość; include parametr pozostaje obsługiwany pod kątem zgodności. Powtórzenie elementu sprawia, że jest dostępne zgodne rozumowanie, ale rozumowanie używane przez model zależy od obsługiwanego trybu kontekstu rozumowania. Aby uzyskać szczegółowe informacje, zobacz Zachowywanie rozumowania między wywołaniami.
W trybie bezstanowym zaszyfrowany element reasoning jest zwracany do aplikacji. Aplikacja jest odpowiedzialna za bezpieczne przechowywanie jej i przekazywanie jej z powrotem przy kolejnym żądaniu. Wybierz lokalizację magazynu po stronie aplikacji, która spełnia wymagania dotyczące zabezpieczeń i cyklu życia.
W poniższych próbkach użyto uwierzytelniania za pomocą klucza interfejsu API. Przykłady w Pythonie korzystają z biblioteki klienckiej OpenAI. Inne przykłady bezpośrednio wywołują punkt końcowy REST Responses i zachowują pełne elementy wyjściowe jako dane JSON.
Zainstaluj zależności dla danego języka:
-
Python: zainstaluj klienta poleceniem
pip install --upgrade openai.
-
C#: Użyj aplikacji konsolowej .NET 8 lub nowszej. Nie są wymagane żadne dodatkowe pakiety.
-
JavaScript: użyj Node.js 18 lub nowszy i zapisz każdy przykład jako plik
.mjs. Nie są wymagane żadne dodatkowe pakiety.
-
Java: użyj zestawu JDK 17 lub nowszego i dodaj zależność Maven
com.fasterxml.jackson.core:jackson-databind:2.22.4. Zapisz każdą próbkę pod nazwą pliku wyświetlaną na jego karcie.
-
REST: Uruchom przykłady programu PowerShell przy użyciu programu PowerShell 7 lub nowszego.
Ustaw następujące zmienne środowiskowe dla każdego języka:
-
AZURE_OPENAI_ENDPOINT: Punkt końcowy zasobu, taki jak https://YOUR-RESOURCE-NAME.openai.azure.com.
-
AZURE_OPENAI_API_KEY: Twój klucz API.
-
AZURE_OPENAI_DEPLOYMENT: nazwa obsługiwanego wdrożenia modelu rozumowania.
Oba przykłady sprawdzają zaszyfrowany element rozumowania i zgłaszają błąd, jeśli żaden nie zostanie zwrócony. Użyj konfiguracji wdrażania i rozumowania, która generuje elementy rozumowania dla przykładowych żądań.
Kontynuuj rozmowę bez zachowywania stanu
Ten przykład zachowuje zwrócone elementy na liście zarządzanej przez aplikację i przekazuje je do kolejnego żądania.
import os
from openai import BadRequestError, OpenAI
client = OpenAI(
api_key=os.environ["AZURE_OPENAI_API_KEY"],
base_url=f"{os.environ['AZURE_OPENAI_ENDPOINT'].rstrip('/')}/openai/v1/",
)
deployment = os.environ["AZURE_OPENAI_DEPLOYMENT"]
# Application-managed state. This example keeps it in memory.
conversation = [
{"role": "user", "content": "Explain the trade-offs of this design."}
]
def add_response_items(response):
items = [item.model_dump(exclude_none=True) for item in response.output]
if not any(
item.get("type") == "reasoning" and item.get("encrypted_content")
for item in items
):
raise RuntimeError(
"No encrypted reasoning item was returned. Check the deployment "
"and the request's include parameter."
)
# Preserve the returned items, including encrypted reasoning.
conversation.extend(items)
try:
first = client.responses.create(
model=deployment,
input=conversation,
store=False,
include=["reasoning.encrypted_content"],
)
add_response_items(first)
print("First answer:", first.output_text)
conversation.append({
"role": "user",
"content": "Which trade-off matters most for reliability?",
})
second = client.responses.create(
model=deployment,
input=conversation,
store=False,
include=["reasoning.encrypted_content"],
)
add_response_items(second)
print("Follow-up answer:", second.output_text)
except BadRequestError as exc:
# Inspect the service error before deciding whether to restart.
print(f"Request rejected: {exc}")
raise
using System;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
string endpoint = RequiredEnvironment("AZURE_OPENAI_ENDPOINT").TrimEnd('/');
string deployment = RequiredEnvironment("AZURE_OPENAI_DEPLOYMENT");
using HttpClient openAIClient = new();
openAIClient.DefaultRequestHeaders.Add(
"api-key", RequiredEnvironment("AZURE_OPENAI_API_KEY"));
// Application-managed state. Preserve each complete output item.
JsonArray conversation = new()
{
new JsonObject
{
["role"] = "user",
["content"] = "Explain the trade-offs of this design."
}
};
JsonObject first = await CreateResponseAsync();
AddResponseItems(first);
Console.WriteLine($"First answer: {GetOutputText(first)}");
conversation.Add(new JsonObject
{
["role"] = "user",
["content"] = "Which trade-off matters most for reliability?"
});
JsonObject second = await CreateResponseAsync();
AddResponseItems(second);
Console.WriteLine($"Follow-up answer: {GetOutputText(second)}");
async Task<JsonObject> CreateResponseAsync()
{
JsonObject request = new()
{
["model"] = deployment,
["input"] = conversation.DeepClone(),
["store"] = false,
["include"] = new JsonArray("reasoning.encrypted_content")
};
using StringContent content = new(
request.ToJsonString(), Encoding.UTF8, "application/json");
using HttpResponseMessage response = await openAIClient.PostAsync(
$"{endpoint}/openai/v1/responses", content);
string body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException(
$"Request rejected ({(int)response.StatusCode}): {body}");
}
return JsonNode.Parse(body)?.AsObject()
?? throw new InvalidOperationException("No response body was returned.");
}
void AddResponseItems(JsonObject response)
{
JsonArray items = response["output"]?.AsArray()
?? throw new InvalidOperationException("No output items were returned.");
if (!items.OfType<JsonObject>().Any(item =>
item["type"]?.GetValue<string>() == "reasoning" &&
!string.IsNullOrEmpty(item["encrypted_content"]?.GetValue<string>())))
{
throw new InvalidOperationException(
"No encrypted reasoning item was returned.");
}
foreach (JsonNode? item in items)
{
conversation.Add(item?.DeepClone()
?? throw new InvalidOperationException("An output item was null."));
}
}
static string GetOutputText(JsonObject response) => string.Concat(
response["output"]!.AsArray().OfType<JsonObject>()
.Where(item => item["type"]?.GetValue<string>() == "message")
.SelectMany(item => item["content"]!.AsArray().OfType<JsonObject>())
.Where(part => part["type"]?.GetValue<string>() == "output_text")
.Select(part => part["text"]!.GetValue<string>()));
static string RequiredEnvironment(string name)
{
string? value = Environment.GetEnvironmentVariable(name);
return !string.IsNullOrEmpty(value) ? value
: throw new InvalidOperationException($"Set {name} before running.");
}
const requiredEnvironment = (name) => {
const value = process.env[name];
if (!value) throw new Error(`Set ${name} before running.`);
return value;
};
const endpoint = requiredEnvironment("AZURE_OPENAI_ENDPOINT").replace(/\/+$/, "");
const deployment = requiredEnvironment("AZURE_OPENAI_DEPLOYMENT");
const apiKey = requiredEnvironment("AZURE_OPENAI_API_KEY");
// Application-managed state. Preserve each complete output item.
const conversation = [
{ role: "user", content: "Explain the trade-offs of this design." },
];
async function createResponse() {
const response = await fetch(`${endpoint}/openai/v1/responses`, {
method: "POST",
headers: { "Content-Type": "application/json", "api-key": apiKey },
body: JSON.stringify({
model: deployment,
input: conversation,
store: false,
include: ["reasoning.encrypted_content"],
}),
});
if (!response.ok) {
throw new Error(
`Request rejected (${response.status}): ${await response.text()}`,
);
}
return response.json();
}
function addResponseItems(response) {
if (!Array.isArray(response.output)) {
throw new Error("No output items were returned.");
}
if (!response.output.some(
(item) => item.type === "reasoning" && item.encrypted_content,
)) {
throw new Error("No encrypted reasoning item was returned.");
}
conversation.push(...response.output);
}
function getOutputText(response) {
return response.output
.filter((item) => item.type === "message")
.flatMap((item) => item.content)
.filter((part) => part.type === "output_text")
.map((part) => part.text)
.join("");
}
const first = await createResponse();
addResponseItems(first);
console.log("First answer:", getOutputText(first));
conversation.push({
role: "user",
content: "Which trade-off matters most for reliability?",
});
const second = await createResponse();
addResponseItems(second);
console.log("Follow-up answer:", getOutputText(second));
Zapisz ten przykład jako StatelessConversation.java.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class StatelessConversation {
private static final ObjectMapper JSON = new ObjectMapper();
public static void main(String[] args) throws Exception {
String endpoint = requiredEnvironment("AZURE_OPENAI_ENDPOINT")
.replaceAll("/+$", "");
String deployment = requiredEnvironment("AZURE_OPENAI_DEPLOYMENT");
String apiKey = requiredEnvironment("AZURE_OPENAI_API_KEY");
HttpClient openAIClient = HttpClient.newHttpClient();
// Application-managed state. Preserve each complete output item.
ArrayNode conversation = JSON.createArrayNode();
conversation.add(JSON.createObjectNode()
.put("role", "user")
.put("content", "Explain the trade-offs of this design."));
JsonNode first = createResponse(
openAIClient, endpoint, apiKey, deployment, conversation);
addResponseItems(conversation, first);
System.out.println("First answer: " + getOutputText(first));
conversation.add(JSON.createObjectNode()
.put("role", "user")
.put("content", "Which trade-off matters most for reliability?"));
JsonNode second = createResponse(
openAIClient, endpoint, apiKey, deployment, conversation);
addResponseItems(conversation, second);
System.out.println("Follow-up answer: " + getOutputText(second));
}
private static JsonNode createResponse(
HttpClient openAIClient, String endpoint, String apiKey,
String deployment, ArrayNode conversation) throws Exception {
ObjectNode payload = JSON.createObjectNode();
payload.put("model", deployment);
payload.set("input", conversation);
payload.put("store", false);
payload.set("include", JSON.createArrayNode()
.add("reasoning.encrypted_content"));
HttpRequest request = HttpRequest.newBuilder(
URI.create(endpoint + "/openai/v1/responses"))
.header("Content-Type", "application/json")
.header("api-key", apiKey)
.POST(HttpRequest.BodyPublishers.ofString(
JSON.writeValueAsString(payload)))
.build();
HttpResponse<String> response = openAIClient.send(
request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new IllegalStateException(
"Request rejected (" + response.statusCode() + "): "
+ response.body());
}
return JSON.readTree(response.body());
}
private static void addResponseItems(
ArrayNode conversation, JsonNode response) {
JsonNode items = response.get("output");
if (items == null || !items.isArray()) {
throw new IllegalStateException("No output items were returned.");
}
boolean hasEncryptedReasoning = false;
for (JsonNode item : items) {
JsonNode encrypted = item.get("encrypted_content");
if ("reasoning".equals(item.path("type").asText())
&& encrypted != null && encrypted.isTextual()
&& !encrypted.asText().isEmpty()) {
hasEncryptedReasoning = true;
}
}
if (!hasEncryptedReasoning) {
throw new IllegalStateException(
"No encrypted reasoning item was returned.");
}
for (JsonNode item : items) {
conversation.add(item);
}
}
private static String getOutputText(JsonNode response) {
StringBuilder text = new StringBuilder();
for (JsonNode item : response.get("output")) {
if ("message".equals(item.path("type").asText())) {
for (JsonNode part : item.get("content")) {
if ("output_text".equals(part.path("type").asText())) {
text.append(part.get("text").asText());
}
}
}
}
return text.toString();
}
private static String requiredEnvironment(String name) {
String value = System.getenv(name);
if (value == null || value.isEmpty()) {
throw new IllegalStateException("Set " + name + " before running.");
}
return value;
}
}
Ten przykład programu PowerShell wysyła żądania JSON bezpośrednio do punktu końcowego REST.
$ErrorActionPreference = "Stop"
foreach ($name in "AZURE_OPENAI_ENDPOINT", "AZURE_OPENAI_API_KEY",
"AZURE_OPENAI_DEPLOYMENT") {
if (-not [Environment]::GetEnvironmentVariable($name)) {
throw "Set $name before running."
}
}
$endpoint = $env:AZURE_OPENAI_ENDPOINT.TrimEnd("/")
$deployment = $env:AZURE_OPENAI_DEPLOYMENT
$headers = @{ "api-key" = $env:AZURE_OPENAI_API_KEY }
# Application-managed state. Preserve each complete output item.
$conversation = [System.Collections.Generic.List[object]]::new()
$conversation.Add(@{
role = "user"
content = "Explain the trade-offs of this design."
})
function New-Response {
$body = @{
model = $deployment
input = $conversation.ToArray()
store = $false
include = @("reasoning.encrypted_content")
} | ConvertTo-Json -Depth 100
Invoke-RestMethod -Method Post -Uri "$endpoint/openai/v1/responses" `
-Headers $headers -ContentType "application/json" -Body $body
}
function Add-ResponseItems($response) {
$items = @($response.output)
if (-not ($items | Where-Object {
$_.type -eq "reasoning" -and $_.encrypted_content
})) {
throw "No encrypted reasoning item was returned."
}
foreach ($item in $items) {
$conversation.Add($item)
}
}
function Get-OutputText($response) {
$parts = foreach ($item in $response.output) {
if ($item.type -eq "message") {
foreach ($part in $item.content) {
if ($part.type -eq "output_text") { $part.text }
}
}
}
$parts -join ""
}
$first = New-Response
Add-ResponseItems $first
Write-Output "First answer: $(Get-OutputText $first)"
$conversation.Add(@{
role = "user"
content = "Which trade-off matters most for reliability?"
})
$second = New-Response
Add-ResponseItems $second
Write-Output "Follow-up answer: $(Get-OutputText $second)"
Przykład wyświetla pierwszą odpowiedź i odpowiedź uzupełniającą. Zachowuje wszystkie elementy wyjściowe, w tym zaszyfrowane rozumowanie, a nie tylko czytelną odpowiedź.
Lista conversation to miejsce, w którym aplikacja tego przykładu przechowuje elementy. Jest on przechowywany w pamięci i nie przetrwa ponownego uruchomienia procesu. Aplikacja, która musi zostać wznowiona później, musi wybrać i zabezpieczyć własne miejsce do przechowywania.
Ten przykład zachowuje elementy rozumowania i wywołania funkcji, wykonuje przykładową funkcję i wysyła wynik z powrotem przy użyciu zgodnego call_idelementu .
import json
import os
from openai import BadRequestError, OpenAI
client = OpenAI(
api_key=os.environ["AZURE_OPENAI_API_KEY"],
base_url=f"{os.environ['AZURE_OPENAI_ENDPOINT'].rstrip('/')}/openai/v1/",
)
deployment = os.environ["AZURE_OPENAI_DEPLOYMENT"]
tools = [{
"type": "function",
"name": "get_order_status",
"description": "Look up the status of an example order.",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string"}
},
"required": ["order_id"],
"additionalProperties": False,
},
}]
def get_order_status(order_id):
# Replace this example with your own trusted data source.
if order_id == "A123":
return {"order_id": order_id, "status": "Shipped"}
return {"order_id": order_id, "status": "Not found"}
conversation = [{
"role": "user",
"content": "What is the status of order A123?",
}]
def create_response():
return client.responses.create(
model=deployment,
input=conversation,
tools=tools,
store=False,
include=["reasoning.encrypted_content"],
)
try:
# Bound the number of tool rounds.
for _ in range(3):
response = create_response()
items = [item.model_dump(exclude_none=True) for item in response.output]
if not any(
item.get("type") == "reasoning" and item.get("encrypted_content")
for item in items
):
raise RuntimeError("No encrypted reasoning item was returned.")
# Preserve returned items in order, including reasoning and tool calls.
conversation.extend(items)
calls = [
item for item in response.output
if item.type == "function_call"
]
if not calls:
print(response.output_text)
break
for call in calls:
if call.name != "get_order_status":
raise ValueError(f"Unexpected tool: {call.name}")
arguments = json.loads(call.arguments)
result = get_order_status(arguments["order_id"])
conversation.append({
"type": "function_call_output",
"call_id": call.call_id,
"output": json.dumps(result),
})
else:
raise RuntimeError("The tool-call limit was reached.")
except BadRequestError as exc:
print(f"Request rejected: {exc}")
raise
using System;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
string endpoint = RequiredEnvironment("AZURE_OPENAI_ENDPOINT").TrimEnd('/');
string deployment = RequiredEnvironment("AZURE_OPENAI_DEPLOYMENT");
using HttpClient openAIClient = new();
openAIClient.DefaultRequestHeaders.Add(
"api-key", RequiredEnvironment("AZURE_OPENAI_API_KEY"));
JsonArray tools = JsonNode.Parse("""
[
{
"type": "function",
"name": "get_order_status",
"description": "Look up the status of an example order.",
"parameters": {
"type": "object",
"properties": { "order_id": { "type": "string" } },
"required": ["order_id"],
"additionalProperties": false
}
}
]
""")!.AsArray();
JsonArray conversation = new()
{
new JsonObject
{
["role"] = "user",
["content"] = "What is the status of order A123?"
}
};
// Preserve reasoning and tool calls before appending each tool result.
for (int round = 0; round < 3; round++)
{
JsonObject response = await CreateResponseAsync();
JsonArray items = response["output"]?.AsArray()
?? throw new InvalidOperationException("No output items were returned.");
if (!items.OfType<JsonObject>().Any(item =>
item["type"]?.GetValue<string>() == "reasoning" &&
!string.IsNullOrEmpty(item["encrypted_content"]?.GetValue<string>())))
{
throw new InvalidOperationException(
"No encrypted reasoning item was returned.");
}
foreach (JsonNode? item in items)
{
conversation.Add(item?.DeepClone()
?? throw new InvalidOperationException("An output item was null."));
}
JsonObject[] calls = items.OfType<JsonObject>()
.Where(item => item["type"]?.GetValue<string>() == "function_call")
.ToArray();
if (calls.Length == 0)
{
Console.WriteLine(GetOutputText(response));
return;
}
foreach (JsonObject call in calls)
{
if (call["name"]?.GetValue<string>() != "get_order_status")
{
throw new InvalidOperationException($"Unexpected tool: {call["name"]}");
}
JsonObject arguments = JsonNode.Parse(
call["arguments"]!.GetValue<string>())?.AsObject()
?? throw new InvalidOperationException("Invalid tool arguments.");
if (arguments["order_id"] is not JsonValue orderIdNode ||
!orderIdNode.TryGetValue<string>(out string? orderId) ||
orderId is null)
{
throw new InvalidOperationException("Missing or invalid order_id.");
}
// Replace this example data with your own trusted data source.
JsonObject result = new()
{
["order_id"] = orderId,
["status"] = orderId == "A123" ? "Shipped" : "Not found"
};
conversation.Add(new JsonObject
{
["type"] = "function_call_output",
["call_id"] = call["call_id"]!.GetValue<string>(),
["output"] = result.ToJsonString()
});
}
}
throw new InvalidOperationException("The tool-call limit was reached.");
async Task<JsonObject> CreateResponseAsync()
{
JsonObject request = new()
{
["model"] = deployment,
["input"] = conversation.DeepClone(),
["tools"] = tools.DeepClone(),
["store"] = false,
["include"] = new JsonArray("reasoning.encrypted_content")
};
using StringContent content = new(
request.ToJsonString(), Encoding.UTF8, "application/json");
using HttpResponseMessage response = await openAIClient.PostAsync(
$"{endpoint}/openai/v1/responses", content);
string body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException(
$"Request rejected ({(int)response.StatusCode}): {body}");
}
return JsonNode.Parse(body)?.AsObject()
?? throw new InvalidOperationException("No response body was returned.");
}
static string GetOutputText(JsonObject response) => string.Concat(
response["output"]!.AsArray().OfType<JsonObject>()
.Where(item => item["type"]?.GetValue<string>() == "message")
.SelectMany(item => item["content"]!.AsArray().OfType<JsonObject>())
.Where(part => part["type"]?.GetValue<string>() == "output_text")
.Select(part => part["text"]!.GetValue<string>()));
static string RequiredEnvironment(string name)
{
string? value = Environment.GetEnvironmentVariable(name);
return !string.IsNullOrEmpty(value) ? value
: throw new InvalidOperationException($"Set {name} before running.");
}
const requiredEnvironment = (name) => {
const value = process.env[name];
if (!value) throw new Error(`Set ${name} before running.`);
return value;
};
const endpoint = requiredEnvironment("AZURE_OPENAI_ENDPOINT").replace(/\/+$/, "");
const deployment = requiredEnvironment("AZURE_OPENAI_DEPLOYMENT");
const apiKey = requiredEnvironment("AZURE_OPENAI_API_KEY");
const tools = [{
type: "function",
name: "get_order_status",
description: "Look up the status of an example order.",
parameters: {
type: "object",
properties: { order_id: { type: "string" } },
required: ["order_id"],
additionalProperties: false,
},
}];
const conversation = [{
role: "user",
content: "What is the status of order A123?",
}];
async function createResponse() {
const response = await fetch(`${endpoint}/openai/v1/responses`, {
method: "POST",
headers: { "Content-Type": "application/json", "api-key": apiKey },
body: JSON.stringify({
model: deployment,
input: conversation,
tools,
store: false,
include: ["reasoning.encrypted_content"],
}),
});
if (!response.ok) {
throw new Error(
`Request rejected (${response.status}): ${await response.text()}`,
);
}
return response.json();
}
function getOutputText(response) {
return response.output
.filter((item) => item.type === "message")
.flatMap((item) => item.content)
.filter((part) => part.type === "output_text")
.map((part) => part.text)
.join("");
}
// Preserve reasoning and tool calls before appending each tool result.
let completed = false;
for (let round = 0; round < 3; round++) {
const response = await createResponse();
if (!Array.isArray(response.output)) {
throw new Error("No output items were returned.");
}
if (!response.output.some(
(item) => item.type === "reasoning" && item.encrypted_content,
)) {
throw new Error("No encrypted reasoning item was returned.");
}
conversation.push(...response.output);
const calls = response.output.filter((item) => item.type === "function_call");
if (calls.length === 0) {
console.log(getOutputText(response));
completed = true;
break;
}
for (const call of calls) {
if (call.name !== "get_order_status") {
throw new Error(`Unexpected tool: ${call.name}`);
}
const argumentsObject = JSON.parse(call.arguments);
if (typeof argumentsObject.order_id !== "string") {
throw new Error("Missing or invalid order_id.");
}
// Replace this example data with your own trusted data source.
const result = {
order_id: argumentsObject.order_id,
status: argumentsObject.order_id === "A123" ? "Shipped" : "Not found",
};
conversation.push({
type: "function_call_output",
call_id: call.call_id,
output: JSON.stringify(result),
});
}
}
if (!completed) throw new Error("The tool-call limit was reached.");
Zapisz ten przykład jako StatelessToolCalling.java.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
public class StatelessToolCalling {
private static final ObjectMapper JSON = new ObjectMapper();
public static void main(String[] args) throws Exception {
String endpoint = requiredEnvironment("AZURE_OPENAI_ENDPOINT")
.replaceAll("/+$", "");
String deployment = requiredEnvironment("AZURE_OPENAI_DEPLOYMENT");
String apiKey = requiredEnvironment("AZURE_OPENAI_API_KEY");
HttpClient openAIClient = HttpClient.newHttpClient();
JsonNode tools = JSON.readTree("""
[{
"type": "function",
"name": "get_order_status",
"description": "Look up the status of an example order.",
"parameters": {
"type": "object",
"properties": { "order_id": { "type": "string" } },
"required": ["order_id"],
"additionalProperties": false
}
}]
""");
ArrayNode conversation = JSON.createArrayNode();
conversation.add(JSON.createObjectNode()
.put("role", "user")
.put("content", "What is the status of order A123?"));
// Preserve reasoning and tool calls before appending each tool result.
for (int round = 0; round < 3; round++) {
JsonNode response = createResponse(openAIClient, endpoint, apiKey,
deployment, conversation, tools);
JsonNode items = response.get("output");
if (items == null || !items.isArray()) {
throw new IllegalStateException("No output items were returned.");
}
boolean hasEncryptedReasoning = false;
List<JsonNode> calls = new ArrayList<>();
for (JsonNode item : items) {
JsonNode encrypted = item.get("encrypted_content");
if ("reasoning".equals(item.path("type").asText())
&& encrypted != null && encrypted.isTextual()
&& !encrypted.asText().isEmpty()) {
hasEncryptedReasoning = true;
}
if ("function_call".equals(item.path("type").asText())) {
calls.add(item);
}
}
if (!hasEncryptedReasoning) {
throw new IllegalStateException(
"No encrypted reasoning item was returned.");
}
for (JsonNode item : items) {
conversation.add(item);
}
if (calls.isEmpty()) {
System.out.println(getOutputText(response));
return;
}
for (JsonNode call : calls) {
if (!"get_order_status".equals(call.path("name").asText())) {
throw new IllegalArgumentException(
"Unexpected tool: " + call.path("name").asText());
}
JsonNode arguments = JSON.readTree(
call.get("arguments").asText());
JsonNode orderIdNode = arguments.get("order_id");
if (orderIdNode == null || !orderIdNode.isTextual()) {
throw new IllegalArgumentException(
"Missing or invalid order_id.");
}
String orderId = orderIdNode.asText();
// Replace this example data with your trusted data source.
ObjectNode result = JSON.createObjectNode()
.put("order_id", orderId)
.put("status", "A123".equals(orderId)
? "Shipped" : "Not found");
conversation.add(JSON.createObjectNode()
.put("type", "function_call_output")
.put("call_id", call.get("call_id").asText())
.put("output", JSON.writeValueAsString(result)));
}
}
throw new IllegalStateException("The tool-call limit was reached.");
}
private static JsonNode createResponse(
HttpClient openAIClient, String endpoint, String apiKey,
String deployment, ArrayNode conversation,
JsonNode tools) throws Exception {
ObjectNode payload = JSON.createObjectNode();
payload.put("model", deployment);
payload.set("input", conversation);
payload.set("tools", tools);
payload.put("store", false);
payload.set("include", JSON.createArrayNode()
.add("reasoning.encrypted_content"));
HttpRequest request = HttpRequest.newBuilder(
URI.create(endpoint + "/openai/v1/responses"))
.header("Content-Type", "application/json")
.header("api-key", apiKey)
.POST(HttpRequest.BodyPublishers.ofString(
JSON.writeValueAsString(payload)))
.build();
HttpResponse<String> response = openAIClient.send(
request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new IllegalStateException(
"Request rejected (" + response.statusCode() + "): "
+ response.body());
}
return JSON.readTree(response.body());
}
private static String getOutputText(JsonNode response) {
StringBuilder text = new StringBuilder();
for (JsonNode item : response.get("output")) {
if ("message".equals(item.path("type").asText())) {
for (JsonNode part : item.get("content")) {
if ("output_text".equals(part.path("type").asText())) {
text.append(part.get("text").asText());
}
}
}
}
return text.toString();
}
private static String requiredEnvironment(String name) {
String value = System.getenv(name);
if (value == null || value.isEmpty()) {
throw new IllegalStateException("Set " + name + " before running.");
}
return value;
}
}
Ten przykład programu PowerShell wysyła żądania JSON bezpośrednio do punktu końcowego REST.
$ErrorActionPreference = "Stop"
foreach ($name in "AZURE_OPENAI_ENDPOINT", "AZURE_OPENAI_API_KEY",
"AZURE_OPENAI_DEPLOYMENT") {
if (-not [Environment]::GetEnvironmentVariable($name)) {
throw "Set $name before running."
}
}
$endpoint = $env:AZURE_OPENAI_ENDPOINT.TrimEnd("/")
$deployment = $env:AZURE_OPENAI_DEPLOYMENT
$headers = @{ "api-key" = $env:AZURE_OPENAI_API_KEY }
$tools = @(@{
type = "function"
name = "get_order_status"
description = "Look up the status of an example order."
parameters = @{
type = "object"
properties = @{ order_id = @{ type = "string" } }
required = @("order_id")
additionalProperties = $false
}
})
$conversation = [System.Collections.Generic.List[object]]::new()
$conversation.Add(@{
role = "user"
content = "What is the status of order A123?"
})
function New-Response {
$body = @{
model = $deployment
input = $conversation.ToArray()
tools = $tools
store = $false
include = @("reasoning.encrypted_content")
} | ConvertTo-Json -Depth 100
Invoke-RestMethod -Method Post -Uri "$endpoint/openai/v1/responses" `
-Headers $headers -ContentType "application/json" -Body $body
}
function Get-OutputText($response) {
$parts = foreach ($item in $response.output) {
if ($item.type -eq "message") {
foreach ($part in $item.content) {
if ($part.type -eq "output_text") { $part.text }
}
}
}
$parts -join ""
}
# Preserve reasoning and tool calls before appending each tool result.
$completed = $false
for ($round = 0; $round -lt 3; $round++) {
$response = New-Response
$items = @($response.output)
if (-not ($items | Where-Object {
$_.type -eq "reasoning" -and $_.encrypted_content
})) {
throw "No encrypted reasoning item was returned."
}
foreach ($item in $items) {
$conversation.Add($item)
}
$calls = @($items | Where-Object { $_.type -eq "function_call" })
if ($calls.Count -eq 0) {
Write-Output (Get-OutputText $response)
$completed = $true
break
}
foreach ($call in $calls) {
if ($call.name -cne "get_order_status") {
throw "Unexpected tool: $($call.name)"
}
$arguments = $call.arguments | ConvertFrom-Json
if ($arguments.order_id -isnot [string]) {
throw "Missing or invalid order_id."
}
# Replace this example data with your own trusted data source.
$status = if ($arguments.order_id -ceq "A123") {
"Shipped"
} else {
"Not found"
}
$result = @{
order_id = $arguments.order_id
status = $status
} | ConvertTo-Json -Compress
$conversation.Add(@{
type = "function_call_output"
call_id = $call.call_id
output = $result
})
}
}
if (-not $completed) { throw "The tool-call limit was reached." }
Przykład wyświetla ostateczną odpowiedź modelu po przetworzeniu przykładowego statusu zamówienia. Funkcja używa przykładowych danych, a nie systemu zamówień na żywo. Pętla ogranicza liczbę żądań odpowiedzi od modelu do trzech i zgłasza błąd, jeśli model nadal prosi o narzędzia.
Zachowaj zaszyfrowane elementy wnioskowania bez zmian; nie próbuj odczytywać ani modyfikować ich zaszyfrowanej zawartości. Aby zapoznać się z definicjami funkcji i formatami wyników narzędzia, zobacz Wywoływanie funkcji.
Zagadnienia dotyczące trasowania
W przypadku kierowania przez Azure API Management zweryfikuj zaszyfrowane odtwarzanie rozumowania w skonfigurowanych zapleczach przed jego użyciem. Jeśli usługa zwróci invalid_encrypted_content, sprawdź błąd i routing zasobów przed podjęciem decyzji, czy ponownie uruchomić konwersację.
Zagadnienia dotyczące ochrony danych
Zaszyfrowane elementy rozumowania przenoszą nieprzezroczysty kontekst rozumowania między żądaniami. Nie opisują one sposobu szyfrowania przechowywanych danych przez usługę, które klucze chronią przechowywane prompty lub stan konwersacji lub gdzie aplikacja musi przechowywać zwrócone elementy.
Ustawienie store=false nie jest całkowitą gwarancją zerowego przechowywania w każdym procesie usługi. Aby uzyskać szczegółowe informacje o przechowywaniu po stronie usługi i monitorowaniu nadużyć, zobacz Dane, prywatność i zabezpieczenia dla Azure OpenAI.
Generowanie obrazu
Interfejs API odpowiedzi umożliwia generowanie obrazów w ramach konwersacji i wieloetapowych przepływów pracy. Obsługuje obrazy jako dane wejściowe i wyjściowe w ramach kontekstu oraz zawiera wbudowane narzędzia do generowania i edytowania obrazów.
W porównaniu z samodzielnym interfejsem API obrazów, interfejs Responses API oferuje dwie zalety:
-
Przesyłanie strumieniowe: wyświetlanie częściowych danych wyjściowych obrazu w trakcie generowania w celu zwiększenia widocznego opóźnienia.
-
Elastyczne dane wejściowe: akceptuj identyfikatory plików obrazów jako dane wejściowe oprócz nieprzetworzonych bajtów obrazu.
Uwaga
Narzędzie do generowania obrazów w Responses API jest obsługiwane przez modele z serii gpt-image-1, a wywoływać je można za pomocą wybranych zgodnych modeli czatu i wnioskowania. Aby zapoznać się z bieżącą listą obsługiwanych modeli aranżacji, zobacz sekcję Obsługiwane modele w dalszej części tego artykułu.
Narzędzie do generowania obrazów nie obsługuje obecnie trybu przesyłania strumieniowego. Aby strumieniować obrazy częściowe, wywołaj bezpośrednio interfejs API generowania obrazów, z pominięciem interfejsu Responses API.
Użyj interfejsu Responses API, aby tworzyć konwersacyjne środowiska pracy z obrazami za pomocą modeli GPT Image.
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" }]
}'
Modele rozumowania
Aby zapoznać się z przykładami używania modeli rozumowania z interfejsem API odpowiedzi, zobacz przewodnik po modelach rozumowania.
Korzystanie z komputera
Funkcja korzystania z komputera w Playwright została przeniesiona do dedykowanego przewodnika po modelu korzystania z komputera.
Rozwiązywanie problemów
Dlaczego moja sesja interfejsu API została zakończona jako środek ostrożności?
W przypadku korzystania z modeli Astra, aby upewnić się, że agenci interpretują i postępują zgodnie z instrukcjami prawidłowo, mamy system, który zatrzymuje sesje w interfejsie API odpowiedzi, jeśli wykryje, że agent może nie interpretować instrukcji poprawnie w takich przypadkach, jak przesyłanie poufnych danych, uzyskiwanie dostępu do poufnych danych lub wprowadzanie destrukcyjnych zmian. Jeśli sesja została zakończona, nie musi to koniecznie oznaczać, że agent popełnił błąd, a jedynie, że warto przejrzeć jego działania, aby upewnić się, że prawidłowo zinterpretował i wykonał Twoje instrukcje.
Które żądania interfejsu API są monitorowane przez ten system?
Ten sam system opisany powyżej asynchronicznie monitoruje żądania kierowane do Astry w interfejsie Responses API. Interfejs API Chat Completions nie jest objęty skanowaniem przez ten konkretny system monitorujący. Zalecamy korzystanie z Responses API, aby zapewnić najwyższą wydajność i bezpieczeństwo w zastosowaniach agentowych.
Jak wykryć, że konwersacja została zakończona w interfejsie API przez ten system?
Gdy system bezpieczeństwa wykryje, że agent mógł w istotny sposób błędnie zinterpretować instrukcje, interfejs API zwraca kod adnotacji bezpieczeństwa misalignment-enforcement. W takim przypadku dana sesja nie może zostać wznowiona.
Co powinna zrobić moja aplikacja, jeśli taki przypadek zostanie wykryty?
Możesz rozważyć skonfigurowanie systemu, aby umożliwić komuś przejrzenie akcji, które agent podjął w takich konwersacjach, na przykład poprzez udostępnienie interfejsu użytkownika użytkownikowi końcowemu do przejrzenia. Po zatrzymaniu konwersacji z tego powodu w interfejsie API nie można go wznowić.
Rozwiązywanie typowych błędów interfejsu API
Skorzystaj z poniższych wskazówek, aby rozwiązać typowe błędy interfejsu API:
-
401/403: Jeśli używasz Microsoft Entra ID, sprawdź, czy token ma określony zakres dla
https://ai.azure.com/.default. Jeśli używasz klucza interfejsu API, upewnij się, że używasz poprawnego klucza dla zasobu.
-
404: Potwierdź, że
model jest zgodna z nazwą wdrożenia.
Powiązana zawartość