Azure OpenAI Responses API を使用して、ステートフルな複数ターン応答を生成します。 チャットの完了と Assistants API の機能を 1 つの統合されたエクスペリエンスにまとめます。 Responses API は、computer-use-previewを支援する モデルもサポートしています。
前提 条件
- デプロイされた Azure OpenAI モデル。
- 認証方法:
- API キー (たとえば、
AZURE_OPENAI_API_KEY)、または
- Microsoft Entra ID (推奨)。
- 言語のクライアント ライブラリをインストールします。
-
Python:
pip install openai azure-identity
-
.NET:
dotnet add package OpenAI と dotnet add package Azure.Identity
-
JavaScript/TypeScript:
npm install openai @azure/identity
-
Java:
com.openai:openai-java と com.azure:azure-identity をプロジェクトに追加します。
- REST の例では、
AZURE_OPENAI_API_KEY (API キー フロー) または AZURE_OPENAI_AUTH_TOKEN (Microsoft Entra ID フロー) を設定します。
サポートされているリージョン
この記事の例を実行する前に、リソース リージョンで Responses API がサポートされていることを確認してください。 v1 API は、最新の機能にアクセスするために必要です。詳細については、 API バージョンのライフサイクルを参照してください。 現在、Responses API は次のリージョンで使用できます。
- australiaeast
- brazilsouth
- canadacentral
- canadaeast
- eastus
- eastus2
- francecentral
- ドイツ西中央
- italynorth
- japaneast
- koreacentral
- northcentralus
- norwayeast
- polandcentral
- southafricanorth
- southcentralus
- southeastasia
- インド南部
- spaincentral
- swedencentral
- switzerlandnorth
- uaenorth
- uksouth
- westus
- westus3
サポートされているモデル
Responses API では、次のモデルがサポートされています。
-
gpt-chat-latest (バージョン: 2026-05-28、 2026-05-05)
-
gpt-5.5 (バージョン: 2026-04-24)
-
gpt-5.4-nano (バージョン: 2026-03-17)
-
gpt-5.4-mini (バージョン: 2026-03-17)
-
gpt-5.4-pro (バージョン:2026-03-05)
-
gpt-5.4 (バージョン:2026-03-05)
-
gpt-5.3-chat (バージョン: 2026-03-03)
-
gpt-5.3-codex (バージョン: 2026-02-24)
-
gpt-5.2-codex (バージョン: 2026-01-14)
-
gpt-5.2 (バージョン: 2025-12-11)
-
gpt-5.2-chat (バージョン: 2025-12-11)
-
gpt-5.2-chat (バージョン: 2026-02-10)
-
gpt-5.1-codex-max (バージョン: 2025-12-04)
-
gpt-5.1 (バージョン: 2025-11-13)
-
gpt-5.1-chat (バージョン: 2025-11-13)
-
gpt-5.1-codex (バージョン: 2025-11-13)
-
gpt-5.1-codex-mini (バージョン: 2025-11-13)
-
gpt-5-pro (バージョン: 2025-10-06)
-
gpt-5-codex (バージョン: 2025-09-11)
-
gpt-5 (バージョン: 2025-08-07)
-
gpt-5-mini (バージョン: 2025-08-07)
-
gpt-5-nano (バージョン: 2025-08-07)
-
gpt-5-chat (バージョン: 2025-08-07)
-
gpt-5-chat (バージョン: 2025-10-03)
-
gpt-5-codex (バージョン: 2025-09-15)
-
gpt-4o (バージョン: 2024-11-20、 2024-08-06、 2024-05-13)
-
gpt-4o-mini (バージョン: 2024-07-18)
computer-use-preview
-
gpt-4.1 (バージョン: 2025-04-14)
-
gpt-4.1-nano (バージョン: 2025-04-14)
-
gpt-4.1-mini (バージョン: 2025-04-14)
-
gpt-image-1 (バージョン: 2025-04-15)
-
gpt-image-1-mini (バージョン: 2025-10-06)
-
gpt-image-1.5 (バージョン: 2025-12-16)
-
o1 (バージョン: 2024-12-17)
-
o3-mini (バージョン: 2025-01-31)
-
o3 (バージョン: 2025-04-16)
-
o4-mini (バージョン: 2025-04-16)
サポートされているすべてのリージョンですべてのモデルを使用できるわけではありません。
モデルページでモデル地域の可用性を確認してください。 要求パラメーターと応答パラメーターの完全なセットについては、 Responses API リファレンス ドキュメントを参照してください。
メモ
現在サポートされていません。
- 複数ターンの編集とストリーミングを使用した画像の生成。
- 画像をファイルとしてアップロードし、入力として参照することはできません。
次の既知の問題があります。
- 入力ファイルとしての PDF がサポートされるようになりましたが、ファイルのアップロードの目的を
user_data に設定することは現在サポートされていません。
- バックグラウンド モードがストリーミングで使用される場合のパフォーマンスの問題。 Microsoftはこの問題の解決に取り組んでいます。
テキスト応答を生成する
Responses API を使用して単純なテキスト応答を生成します。
YOUR-RESOURCE-NAMEとMODEL_NAMEをデプロイの値に置き換えます。
import os
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
# API key authentication
client = OpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
)
response = client.responses.create(
model="MODEL_NAME",
input="This is a test."
)
print(response.model_dump_json(indent=2))
# Microsoft Entra ID authentication (recommended)
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://ai.azure.com/.default"
)
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=token_provider(),
)
response = client.responses.create(
model="MODEL_NAME",
input="This is a test."
)
print(response.model_dump_json(indent=2))
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems = { ResponseItem.CreateUserMessageItem("This is a test.") }
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
import { OpenAI } from "openai";
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
// API key authentication
const openai = new OpenAI({
baseURL: endpoint,
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await openai.responses.create({
model: "MODEL_NAME",
input: "This is a test."
});
console.log(response.output_text);
// Microsoft Entra ID authentication (recommended)
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
"https://ai.azure.com/.default"
);
const openaiEntra = new OpenAI({
baseURL: endpoint,
apiKey: await tokenProvider(),
});
const responseEntra = await openaiEntra.responses.create({
model: "MODEL_NAME",
input: "This is a test."
});
console.log(responseEntra.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
// Microsoft Entra ID authentication (recommended)
OpenAIClient openAIClientEntra = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(BearerTokenCredential.create(
AuthenticationUtil.getBearerTokenSupplier(
new DefaultAzureCredentialBuilder().build(),
"https://ai.azure.com/.default")))
.build();
ResponseCreateParams params = ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("This is a test.")
.build();
Response response = openAIClient.responses().create(params);
System.out.println(response.outputText());
Microsoft Entra ID
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN" \
-d '{
"model": "MODEL_NAME",
"input": "This is a test."
}'
API キー
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."
}'
応答の例
{
"id": "resp_67cb32528d6881909eb2859a55e18a85",
"created_at": 1741369938.0,
"output_text": "Great! How can I help you today?",
...
}
応答を取得する
前の Responses API 呼び出しから ID で応答を取得します。
import os
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
# API key authentication
client = OpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
)
response = client.responses.retrieve("<response_id>")
print(response.model_dump_json(indent=2))
# Microsoft Entra ID authentication
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://ai.azure.com/.default"
)
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=token_provider,
)
response = client.responses.retrieve("<response_id>")
print(response.model_dump_json(indent=2))
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
string responseId = "<response_id>";
ResponseResult response = await openAIClient.GetResponseAsync(responseId);
Console.WriteLine(response.GetOutputText());
import { OpenAI } from "openai";
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
// API key authentication
const openai = new OpenAI({
baseURL: endpoint,
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await openai.responses.retrieve("<response_id>");
console.log(response.output_text);
// Microsoft Entra ID authentication
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
"https://ai.azure.com/.default"
);
const openaiEntra = new OpenAI({
baseURL: endpoint,
apiKey: await tokenProvider(),
});
const responseEntra = await openaiEntra.responses.retrieve("<response_id>");
console.log(responseEntra.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
// Microsoft Entra ID authentication
OpenAIClient openAIClientEntra = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(BearerTokenCredential.create(
AuthenticationUtil.getBearerTokenSupplier(
new DefaultAzureCredentialBuilder().build(),
"https://ai.azure.com/.default")))
.build();
Response response = openAIClient.responses().retrieve("<response_id>");
System.out.println(response.outputText());
Microsoft Entra ID
curl -X GET https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses/<response_id> \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN"
API キー
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"
応答の例
{
"id": "resp_67cb61fa3a448190bcf2c42d96f0d1a8",
"output_text": "Hello! How can I assist you today?",
...
}
応答を削除する
既定では、応答データは 30 日間保持されます。 保存されている応答を ID で削除します。
import os
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
# API key authentication
client = OpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
)
response = client.responses.delete("<response_id>")
print(response)
# Microsoft Entra ID authentication
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://ai.azure.com/.default"
)
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=token_provider,
)
response = client.responses.delete("<response_id>")
print(response)
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
string responseId = "<response_id>";
var result = await openAIClient.DeleteResponseAsync(responseId);
Console.WriteLine(result); // result.Deleted == true if successful
import { OpenAI } from "openai";
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
// API key authentication
const openai = new OpenAI({
baseURL: endpoint,
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const result = await openai.responses.delete("<response_id>");
console.log(result);
// Microsoft Entra ID authentication
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
"https://ai.azure.com/.default"
);
const openaiEntra = new OpenAI({
baseURL: endpoint,
apiKey: await tokenProvider(),
});
const resultEntra = await openaiEntra.responses.delete("<response_id>");
console.log(resultEntra);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
// Microsoft Entra ID authentication
OpenAIClient openAIClientEntra = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(BearerTokenCredential.create(
AuthenticationUtil.getBearerTokenSupplier(
new DefaultAzureCredentialBuilder().build(),
"https://ai.azure.com/.default")))
.build();
Response result = openAIClient.responses().delete("<response_id>");
System.out.println(result);
Microsoft Entra ID
curl -X DELETE https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses/<response_id> \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AZURE_OPENAI_AUTH_TOKEN"
API キー
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"
応答を連結する
チェーンは、前の応答 ID を 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."
}'
応答を手動で連結する
または、次の要求で出力項目を手動で繰り越すことができます。
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))
応答を圧縮する
圧縮により、後のターンで重要な状態を維持しながら、入力コンテキストが減少します。
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)
メモ
.NET SDK では、応答圧縮用に厳密に型指定されたサーフェスはまだ提供されていません。 呼び出し図形の REST タブを参照するか、JSON を使用してプロトコル メソッド BinaryContent 直接呼び出します。
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": "..."}]
}
]
}'
返された項目を使用してコンパクト化する
推論、メッセージ、関数呼び出しなど、以前の要求から返されたすべての項目を圧縮できます。
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)
以前の応答 ID を使用してコンパクト化する
以前の応答 ID を使用して圧縮することもできます。
initial_response = client.responses.create(
model="MODEL_NAME",
input="What is the size of France?"
)
compacted_response = client.responses.compact(
model="MODEL_NAME",
previous_response_id=initial_response.id
)
follow_up_response = client.responses.create(
model="MODEL_NAME",
input=[
*compacted_response.output,
{"role": "user", "content": "What is the capital?"}
]
)
print(follow_up_response.output_text)
サーバー側の圧縮
POST /responsesでclient.responses.createを設定することで、応答 (context_managementまたはcompact_threshold) でサーバー側の圧縮を直接使用することもできます。
- 出力トークン数が構成されたしきい値を超えると、Responses API によって圧縮が自動的に実行されます。
- このモードでは、
/responses/compact を個別に呼び出す必要はありません。
- 応答には、暗号化された圧縮項目が含まれます。
- 応答の作成要求で store=false を設定すると、サーバー側の圧縮が機能します。
圧縮項目は、より少ないトークンを使用して、本質的な前の状態と推論を次のターンに進めます。 不透明であり、人間が判読できるものではありません。
ステートレス入力配列チェーンを使用している場合は、通常どおり出力項目を追加します。
previous_response_idを使用している場合は、各ターンで新しいユーザー メッセージのみを渡します。 どちらのパターンでも、圧縮項目には次のウィンドウに必要なコンテキストが含まれます。
ヒント
前の入力項目に出力項目を追加した後、最新の圧縮項目の前に来た項目を削除して、要求を小さくし、長い末尾の待機時間を短縮できます。 最新の圧縮項目には、会話を続行するために必要なコンテキストが含まれています。
previous_response_idチェーンを使用する場合は、手動で剪定しないでください。
Flow
- 通常どおり
responses を呼び出します。
context_managementを使用してcompact_thresholdを追加して、サーバー側の圧縮を有効にします。
- 出力がしきい値を超えた場合、サービスは圧縮をトリガーし、出力ストリームに圧縮項目を出力し、推論を続行する前にコンテキストを排除します。
- 次のいずれかのパターンを使用して会話を続行します。
- ステートレス入力配列チェーン: 圧縮項目を含む出力項目を次の入力配列に追加します。
-
previous_response_id チェーン: 各ターンで新しいユーザー メッセージのみを渡し、最新の応答 ID を転送します。
例
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(),
}
)
ストリーミング
stream=trueを設定して、生成された応答をストリーム配信します。 サービスは、出力トークンをトークンごとにレンダリングするために使用できる増分イベントを出力します。
メモ
ストリーミング中に、サービスでトークンの制限や解析の問題などのエラーが発生した場合、Responses API はエラー イベント ( 500、 429、および同様のエラー) を返す可能性があります。 アプリケーションはこのイベントを検出し、ストリーミングを正常に停止または再開する必要があります。 失敗したストリーミング応答中に生成されたトークンには課金されません。
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
}'
関数呼び出し
Responses API では、関数呼び出しがサポートされています。
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?"
}'
ガードレールとコンテンツフィルタリングを処理する
Guardrail (コンテンツ フィルター) はデプロイ レベルで適用され、すべての Responses API 呼び出しで自動的に実行されるため、送信する入力とモデルによって生成される出力の両方が保護されます。 ガードレールは個別に構成します。 詳細については、「 ガードレールとコントロールの構成」を参照してください。 このセクションでは、Responses API を呼び出すときにガードレールの結果を検出して処理する方法を示します。
Responses API は、チャットの完了とは異なる方法でガードレールの結果を表示します。 chat completions が返す prompt_filter_results フィールドと content_filter_results フィールドの代わりに、レスポンス オブジェクトにはトップレベルの content_filters 配列が含まれます。 各エントリは、1 つのフィルター結果を記述します。
| フィールド |
Description |
blocked |
コンテンツがブロックされたかどうか。 |
source_type |
結果が prompt (入力) に適用されるか、 completion (出力) に適用されるか。 |
content_filter_results |
重大度レベルの hate、 sexual、 violence、 self_harm などのカテゴリの結果に加えて、 jailbreak、 indirect_attack、 protected_material_text、 protected_material_codeなどのオプションのカテゴリが表示されます。 |
content_filter_offsets |
結果の適用対象となる文字オフセット。 |
メモ
content_filters配列は、基本 OpenAI 応答スキーマの一部ではない Microsoft Foundry 拡張機能であるため、SDK は型指定されたプロパティを公開しません。 次の例に示すように、生または追加のフィールドとして読み取ります。
ガードレールによって入力がブロックされると、API はコード content_filterで HTTP 400 エラーを返します。 ブロックされたプロンプトを適切に処理するには、このエラーをキャッチします。
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."
}'
ガードレールが入力をブロックすると、API はコード content_filterで HTTP 400 を返します。
{
"error": {
"code": "content_filter",
"message": "The response was filtered due to the prompt triggering content management policy."
}
}
ガードレールのアノテーションを読み取る
要求が成功したら、応答から content_filters 配列を読み取り、入力と出力のガードレールの結果を調べます。
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."
}'
content_filters配列が応答オブジェクトに表示されます。
{
"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" }
}
}
]
}
ガードレールのカテゴリと重大度レベルの詳細については、「 ガードレールの概要 」および 「注釈の操作」を参照してください。
コード インタープリター
コード インタープリター ツールを使用すると、セキュリティで保護されたサンドボックス環境でPythonコードを記述して実行できます。 次のようなさまざまな高度なタスクがサポートされています。
- さまざまなデータ形式と構造を持つファイルの処理
- データと視覚化を含むファイルの生成 (グラフなど)
- 問題を解決するためのコードを繰り返し記述して実行します。モデルは、成功するまでコードをデバッグして再試行できます
- トリミング、ズーム、回転などの画像変換を有効にして、サポートされているモデル (o3、o4-mini など) の視覚的推論を強化する
- このツールは、データ分析、数学計算、およびコード生成を含むシナリオに特に役立ちます。
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
重要
コード インタープリターには、Azure OpenAI の使用に対するトークン ベースの料金を超える追加料金があります。 Responses API が 2 つの異なるスレッドでコード インタープリターを同時に呼び出すと、2 つのコード インタープリター セッションが作成されます。 各セッションは既定で 1 時間アクティブで、アイドル タイムアウトは 20 分です。
コード インタープリター ツールにはコンテナーが必要です。コンテナーは、モデルがコードPython実行できる完全にサンドボックス化された仮想マシンです。 コンテナーには、アップロードされたファイルまたは実行中に生成されたファイルを含めることができます。
コンテナーを作成するには、新しい Response オブジェクトを作成するときにツール構成で "container": { "type": "auto", "file_ids": ["file-1", "file-2"] } を指定します。 これにより、新しいコンテナーが自動的に作成されるか、モデルのコンテキストで以前のcode_interpreter_callのアクティブなコンテナーが再利用されます。 APIwill の出力の code_interpreter_call には、生成された container_id が含まれます。 このコンテナーは、20 分間使用しないと有効期限が切れます。
コード インタープリターを実行する場合、モデルは独自のファイルを作成できます。 たとえば、プロットの作成や CSV の作成を依頼した場合、コンテナーにこれらのイメージが直接作成されます。 次のメッセージの注釈でこれらのファイルを引用します。
モデル入力内のすべてのファイルがコンテナーに自動的にアップロードされます。 コンテナーに明示的にアップロードする必要はありません。
サポートされているファイル
| ファイル形式 |
MIME の種類 |
.c |
text/x-c |
.cs |
text/x-csharp |
.cpp |
text/x-c++ |
.csv |
text/csv |
.doc |
application/msword |
.docx |
application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.html |
text/html |
.java |
text/x-java |
.json |
application/json |
.md |
text/markdown |
.pdf |
application/pdf |
.php |
text/x-php |
.pptx |
application/vnd.openxmlformats-officedocument.presentationml.presentation |
.py |
text/x-python |
.py |
text/x-script.python |
.rb |
text/x-ruby |
.tex |
text/x-tex |
.txt |
text/plain |
.css |
text/css |
.js |
text/JavaScript |
.sh |
application/x-sh |
.ts |
application/TypeScript |
.csv |
application/csv |
.jpeg |
image/jpeg |
.jpg |
image/jpeg |
.gif |
image/gif |
.pkl |
application/octet-stream |
.png |
image/png |
.tar |
application/x-tar |
.xlsx |
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.xml |
application/xml または "text/xml" |
.zip |
application/zip |
応答に送信された入力項目を取得します。 これは、モデルによって追加された項目 (関数呼び出しや圧縮項目など) を含む、完全な会話コンテキストを検査する場合に便利です。
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))
メモ
.NET SDK は、このエンドポイントをプロトコル メソッドとしてのみ公開します。 呼び出し図形の REST タブを参照するか、プロトコル メソッドを直接呼び出します。
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"
応答の例
{
"object": "list",
"data": [
{
"id": "msg_...",
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "This is a test."}]
}
]
}
視覚対応モデルでは、画像をテキストと共に解釈できます。 この記事で後述する制限に従って、オブジェクト、図形、色、テクスチャを認識し、画像に含まれるテキストを読み取ることができます。
次のいずれかの方法で、要求への入力として画像を提供できます。
- 画像ファイルへの完全な URL
- Base64 でエンコードされたデータ URI
-
Files API で作成されたファイル ID
イメージの URL
パブリック URL でホストされているイメージを参照します。 モデルは画像を取得し、入力コンテンツの一部として含めます。
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
response = client.responses.create(
model="MODEL_NAME",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": "What is in this image?"},
{"type": "input_image", "image_url": "<image_url>"}
]
}
]
)
print(response.output_text)
#pragma warning disable OPENAI001
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems =
{
ResponseItem.CreateUserMessageItem(
[
ResponseContentPart.CreateInputTextPart("What is in this image?"),
ResponseContentPart.CreateInputImagePart(new Uri("<image_url>"))
])
}
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await client.responses.create({
model: "MODEL_NAME",
input: [
{
role: "user",
content: [
{ type: "input_text", text: "What is in this image?" },
{ type: "input_image", image_url: "<image_url>" }
],
},
],
});
console.log(response.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputImage;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
ResponseInputImage image = ResponseInputImage.builder()
.detail(ResponseInputImage.Detail.AUTO)
.imageUrl("<image_url>")
.build();
ResponseInputItem userMsg = ResponseInputItem.ofMessage(
ResponseInputItem.Message.builder()
.role(ResponseInputItem.Message.Role.USER)
.addInputTextContent("What is in this image?")
.addContent(image)
.build());
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.inputOfResponse(List.of(userMsg))
.build());
System.out.println(response.outputText());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": [
{
"role": "user",
"content": [
{"type": "input_text", "text": "What is in this image?"},
{"type": "input_image", "image_url": "<image_url>"}
]
}
]
}'
Base64 でエンコードされたイメージ
バイトを base64 データ URI としてエンコードして、イメージをインラインで送信します。 このパターンは、イメージがパブリック URL でホストされていない場合、または余分なネットワーク フェッチを回避する場合に使用します。
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>"}
]
}
]
}'
ファイルID
purpose="vision"を使用して Files API を使用してイメージをアップロードし、要求で返されたファイル 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")
)
def create_file(file_path):
with open(file_path, "rb") as file_content:
result = client.files.create(
file=file_content,
purpose="vision",
)
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.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.Vision);
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: "vision",
});
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.FileCreateParams;
import com.openai.models.FileObject;
import com.openai.models.FilePurpose;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.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.VISION)
.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/files \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-F purpose="vision" \
-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>"}
]
}
]
}'
次の表に、イメージ入力でサポートされているファイルの種類を示します。
| ファイルの種類 |
MIME の種類 |
| PNG |
image/png |
| JPEG |
image/jpeg |
| WebP |
image/webp |
| アニメーション以外の GIF |
image/gif |
1 つの要求に、最大 100 個の画像を含めることができます。 個々のイメージ ファイルは 50 MB 未満である必要があり、要求内のすべてのイメージの合計サイズも 50 MB 未満である必要があります。
イメージは、次の追加要件を満たしている必要があります。
- イメージはプロンプトに関連している必要があります。モデルは、関連のないビジュアル コンテンツ用に設計されていません。
- 画像には、コンテンツ ポリシーに違反する有害または機密性の高いコンテンツを含めることはできません。
- 画像ファイルは破損していたり、読み取れなかったりすることはできません。 モデルがイメージを処理できない場合、要求は失敗します。
画像の詳細レベルを選択する
detail コンテンツ パーツの input_image プロパティを使用して、モデルがイメージを処理する方法を制御します。 詳細が小さいほど使用されるトークンが少なく、高速になりますが、より詳細な場合は、より多くのトークンが使用されますが、モデルはより細かい機能をキャプチャできます。
{
"type": "input_image",
"image_url": "<image_url>",
"detail": "high"
}
次の表では、各詳細レベルについて説明します。
| 詳細レベル |
Description |
low |
このモデルでは、画像の解像度の低いバージョンが使用されます。 このオプションでは、最も少ないトークンが使用され、最速の応答が生成されますが、モデルでは細かい詳細が見逃される可能性があります。 |
high |
このモデルでは、画像の解像度が高いバージョンが使用されます。 このオプションは、より詳細な情報をキャプチャしますが、より多くのトークンを使用し、応答に時間がかかります。 |
auto |
これが既定値です。 モデルは、画像とプロンプトに基づいて適切な詳細レベルを選択します。 |
ビジョン対応モデルには、次の制限があります。
-
医療画像: このモデルは、CT スキャンなどの特殊な医療画像を解釈するのに適していません。また、医療アドバイスには使用しないでください。
-
英語以外のテキスト: 日本語や韓国語など、ラテン以外のアルファベットのテキストを含む画像を処理する場合、モデルが最適に動作しない可能性があります。
-
小さいテキスト: 画像内のテキストを拡大して読みやすくしますが、重要な詳細をトリミングしないようにします。
-
回転: モデルは、回転した、または上下逆さまのテキストや画像を誤って解釈する可能性があります。
-
ビジュアル要素: モデルは、色やスタイル (実線、破線、点線など) が異なるグラフやテキストに苦労する可能性があります。
-
空間推論: このモデルは、チェスの位置の識別など、正確な空間ローカライズを必要とするタスクでは困難です。
-
精度: モデルでは、場合によっては不適切な説明やキャプションが生成される場合があります。
-
画像の形状:モデルはパノラマ画像と魚眼画像では困難です。
-
メタデータとサイズ変更: モデルは元のファイル名やメタデータを処理せず、画像は分析前にサイズ変更され、元のディメンションに影響します。
-
カウント: モデルは、画像内のオブジェクトの概数を示す場合があります。
-
CAPTCHA: 安全上の理由から、CAPTCHA の送信をブロックするシステムが整っています。
ビジョン機能を備えたモデルでは、PDF 入力がサポートされます。 PDF ファイルは、Base64 でエンコードされたデータまたはファイル ID として提供できます。 モデルが PDF コンテンツを解釈できるように、抽出されたテキストと各ページの画像の両方がモデルのコンテキストに含まれます。 これは、重要な情報が図やテキスト以外のコンテンツを介して伝達される場合に便利です。
メモ
- 抽出されたすべてのテキストと画像は、モデルのコンテキストに配置されます。 PDF を入力として使用した場合の価格とトークンの使用への影響を理解していることを確認してください。
- 1 つの API 要求では、複数のファイルを含めることができますが、各ファイルは 50 MB 未満である必要があります。 要求内のすべてのファイルの合計制限は 50 MB です。
- PDF ファイルを入力として受け入れることができるのは、テキスト入力と画像入力の両方をサポートするモデルのみです。
-
purposeのuser_dataは現在サポートされていません。 一時的な回避策として、目的をassistantsに設定する必要があります。
PDF を Base64 に変換して分析する
バイトを base64 データ URI としてエンコードして、PDF をインラインで送信します。 モデルは、抽出されたテキストと各ページのレンダリングされた画像の両方を受け取ります。
import base64
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
with open("PDF-FILE-NAME.pdf", "rb") as f:
base64_string = base64.b64encode(f.read()).decode("utf-8")
response = client.responses.create(
model="MODEL_NAME",
input=[
{
"role": "user",
"content": [
{
"type": "input_file",
"filename": "PDF-FILE-NAME.pdf",
"file_data": f"data:application/pdf;base64,{base64_string}",
},
{"type": "input_text", "text": "Summarize this PDF."},
],
},
]
)
print(response.output_text)
#pragma warning disable OPENAI001
using System.IO;
using System.Threading.Tasks;
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
byte[] pdfBytes = await File.ReadAllBytesAsync("PDF-FILE-NAME.pdf");
BinaryData pdfData = BinaryData.FromBytes(pdfBytes);
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems =
{
ResponseItem.CreateUserMessageItem(
[
ResponseContentPart.CreateInputFilePart(pdfData, "application/pdf", "PDF-FILE-NAME.pdf"),
ResponseContentPart.CreateInputTextPart("Summarize this PDF.")
])
}
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
import { readFileSync } from "node:fs";
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const base64Pdf = readFileSync("PDF-FILE-NAME.pdf").toString("base64");
const response = await client.responses.create({
model: "MODEL_NAME",
input: [
{
role: "user",
content: [
{
type: "input_file",
filename: "PDF-FILE-NAME.pdf",
file_data: `data:application/pdf;base64,${base64Pdf}`,
},
{ type: "input_text", text: "Summarize this PDF." },
],
},
],
});
console.log(response.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputFile;
import com.openai.models.responses.ResponseInputItem;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
byte[] pdfBytes = Files.readAllBytes(Paths.get("document.pdf"));
String dataUrl = "data:application/pdf;base64," + Base64.getEncoder().encodeToString(pdfBytes);
ResponseInputFile file = ResponseInputFile.builder()
.filename("document.pdf")
.fileData(dataUrl)
.build();
ResponseInputItem userMsg = ResponseInputItem.ofMessage(
ResponseInputItem.Message.builder()
.role(ResponseInputItem.Message.Role.USER)
.addInputTextContent("Summarize this PDF.")
.addContent(file)
.build());
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.inputOfResponse(List.of(userMsg))
.build());
System.out.println(response.outputText());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": [
{
"role": "user",
"content": [
{"type": "input_file", "filename": "PDF-FILE-NAME.pdf", "file_data": "data:application/pdf;base64,<BASE64_PDF>"},
{"type": "input_text", "text": "Summarize this PDF."}
]
}
]
}'
PDF をアップロードして分析する
purpose="assistants"を使用して PDF ファイルをアップロードします。
purposeのuser_dataは現在サポートされていません。
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
file = client.files.create(
file=open("nucleus_sampling.pdf", "rb"),
purpose="assistants"
)
response = client.responses.create(
model="MODEL_NAME",
input=[
{
"role": "user",
"content": [
{"type": "input_file", "file_id": file.id},
{"type": "input_text", "text": "Summarize this PDF."},
],
},
]
)
print(response.output_text)
#pragma warning disable OPENAI001
using System.IO;
using System.Threading.Tasks;
using Azure.Identity;
using OpenAI;
using OpenAI.Files;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
OpenAIFileClient fileClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new OpenAIClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
byte[] pdfBytes = await File.ReadAllBytesAsync("nucleus_sampling.pdf");
OpenAIFile uploadedFile = await fileClient.UploadFileAsync(
BinaryData.FromBytes(pdfBytes),
"nucleus_sampling.pdf",
FileUploadPurpose.UserData);
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
InputItems =
{
ResponseItem.CreateUserMessageItem(
[
ResponseContentPart.CreateInputFilePart(uploadedFile.Id),
ResponseContentPart.CreateInputTextPart("Summarize this PDF.")
])
}
};
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
import fs from "node:fs";
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const file = await client.files.create({
file: fs.createReadStream("nucleus_sampling.pdf"),
purpose: "assistants",
});
const response = await client.responses.create({
model: "MODEL_NAME",
input: [
{
role: "user",
content: [
{ type: "input_file", file_id: file.id },
{ type: "input_text", text: "Summarize this PDF." },
],
},
],
});
console.log(response.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.FileCreateParams;
import com.openai.models.FileObject;
import com.openai.models.FilePurpose;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputFile;
import com.openai.models.responses.ResponseInputItem;
import java.nio.file.Paths;
import java.util.List;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
FileObject uploaded = openAIClient.files().create(
FileCreateParams.builder()
.file(Paths.get("document.pdf"))
.purpose(FilePurpose.USER_DATA)
.build());
ResponseInputFile file = ResponseInputFile.builder()
.fileId(uploaded.id())
.build();
ResponseInputItem userMsg = ResponseInputItem.ofMessage(
ResponseInputItem.Message.builder()
.role(ResponseInputItem.Message.Role.USER)
.addInputTextContent("Summarize this PDF.")
.addContent(file)
.build());
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.inputOfResponse(List.of(userMsg))
.build());
System.out.println(response.outputText());
# Upload the PDF
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/files \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-F purpose="assistants" \
-F file="@your_file.pdf"
# Use the returned file ID with Responses
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"input": [
{
"role": "user",
"content": [
{"type": "input_file", "file_id": "<file_id>"},
{"type": "input_text", "text": "Summarize this PDF."}
]
}
]
}'
リモート MCP サーバーの使用
モデルの機能を拡張するには、リモート モデル コンテキスト プロトコル (MCP) サーバーでホストされているツールに接続します。 これらのサーバーは開発者や組織によって管理され、応答 API など、MCP と互換性のあるクライアントがアクセスできるツールを公開します。
モデル コンテキスト プロトコル (MCP) は、アプリケーションが大規模言語モデル (LLM) にツールとコンテキスト データを提供する方法を定義するオープン標準です。 これにより、外部ツールをモデル ワークフローに一貫性のあるスケーラブルに統合できます。
次の例は、リモート MCP サーバーを使用して、Azure REST API リポジトリに関する情報を照会する方法を示しています。 このモデルは、リポジトリのコンテンツに対する理由をリアルタイムで取得します。
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?"
}'
MCP ツールは Responses API でのみ機能し、すべての新しいモデル (gpt-4o、gpt-4.1、および推論モデル) で使用できます。 MCP ツールを使用している場合は、ツール定義のインポートまたはツール呼び出し時に使用されるトークンに対してのみ支払います。追加料金はかかりません。
承認
既定では、Responses API は、リモート MCP サーバーとデータを共有する前に明示的な承認を必要とします。 この承認手順は、透明性を確保するのに役立ち、外部に送信される情報を制御できます。
リモート MCP サーバーと共有されているすべてのデータを確認し、必要に応じて監査目的でログに記録することをお勧めします。
承認が必要な場合、モデルは応答出力で mcp_approval_request 項目を返します。 このオブジェクトには、保留中の要求の詳細が含まれており、続行する前にデータを検査または変更できます。
{
"id": "mcpr_682bd9cd428c8198b170dc6b549d66fc016e86a03f4cc828",
"type": "mcp_approval_request",
"arguments": {},
"name": "fetch_azure_rest_api_docs",
"server_label": "github"
}
リモート MCP 呼び出しを続行するには、mcp_approval_response項目を含む新しい応答オブジェクトを作成して、承認要求に応答する必要があります。 このオブジェクトは、モデルが指定されたデータをリモート 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>"
}
]
}'
認証
重要
- Responses API 内の MCP クライアントには、TLS 1.2 以上が必要です。
- 現在、相互 TLS (mTLS) はサポートされていません。
-
Azure サービス タグ は現在、MCP クライアント トラフィックではサポートされていません。
GitHub MCP サーバーとは異なり、ほとんどのリモート MCP サーバーでは認証が必要です。 Responses API の MCP ツールはカスタム ヘッダーをサポートしているため、必要な認証スキームを使用してこれらのサーバーに安全に接続できます。
API キー、OAuth アクセス トークン、その他の資格情報などのヘッダーは、要求で直接指定できます。 最も一般的に使用されるヘッダーは、 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"}
}
]
}'
バックグラウンド タスク
バックグラウンド モードでは、 o3 や o1-proなどの推論モデルを使用して、実行時間の長いタスクを非同期的に実行できます。 これは、完了までに数分かかる複雑なタスク (Codex や Deep Research スタイルのエージェントなど) に役立ちます。
"background": trueで要求が送信されると、タスクは非同期的に処理され、その状態をポーリングします。
バックグラウンド タスクを開始する
タスクをキューに入れるには、要求で background=true を設定します。 サービスは、応答 ID と queued 状態で直ちに返されます。その 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")
)
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
}'
完了に関するアンケート
ステータスが queued または in_progress の間、ポーリングを続行します。 応答が終了状態になると、取得できます。
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"
バックグラウンド タスクを取り消す
cancel エンドポイントで進行中のバックグラウンド タスクを取り消します。 キャンセル操作は冪等であり、以降の呼び出しでは最終的な応答オブジェクトが返されます。
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"
バックグラウンド応答をストリーミングするには、 background と stream の両方を trueに設定します。 このパターンでは、接続が切断された場合にストリーミングを再開できます。 各イベントの sequence_number で自分の位置を追跡します。
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
}'
バックグラウンド応答では、現在、同期応答よりも、最初のトークンまでの待機時間が長くなっています。 このギャップを減らすために、改善が進行中です。
制限
- バックグラウンド モードでは、
store=trueが必要です。 ステートレス要求はサポートされていません。
- 元の要求が
stream=true含まれている場合にのみ、ストリーミングを再開できます。
- 同期応答を取り消すには、接続を直接終了します。
特定のポイントからのストリーミングを再開する
ストリーミング接続が切断された場合は、stream=trueのstarting_after=<sequence_number>と共にGETを応答に渡すことで、既知のイベントから再開できます。 サービスは、そのシーケンス番号の後に出力されたイベントを再生します。
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"
暗号化された推論項目
ステートレス モード (store=false) で Responses API を使用する場合でも、会話のターン間で推論コンテキストを保持する必要があります。 これを行うには、暗号化された推論項目を要求に含めます。
複数のターンにわたって推論項目を保持するには、 reasoning.encrypted_content を include パラメーターに追加します。 その後、応答には暗号化されたバージョンの推論トレースが含まれています。これは、今後の要求に渡すことができます。
import os
from openai import OpenAI
client = OpenAI(
base_url="https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=os.getenv("AZURE_OPENAI_API_KEY")
)
response = client.responses.create(
model="MODEL_NAME",
reasoning={"effort": "medium"},
input="What is the weather like today?",
tools=[
# Replace with your function or tool definitions.
],
include=["reasoning.encrypted_content"],
store=False,
)
print(response.output_text)
#pragma warning disable OPENAI001
using System.Collections.Generic;
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
string endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
// API key authentication
ResponsesClient openAIClient = new(
credential: new ApiKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!),
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
// Microsoft Entra ID authentication (recommended)
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
ResponsesClient openAIClientEntra = new(
authenticationPolicy: tokenPolicy,
options: new ResponsesClientOptions { Endpoint = new Uri(endpoint) });
List<ResponseItem> inputItems =
[
ResponseItem.CreateUserMessageItem("<your_prompt>")
];
CreateResponseOptions options = new()
{
Model = "MODEL_NAME",
StoredOutputEnabled = false,
IncludedProperties = { IncludedResponseProperty.ReasoningEncryptedContent }
};
foreach (ResponseItem item in inputItems)
{
options.InputItems.Add(item);
}
ResponseResult response = await openAIClient.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
// To carry encrypted reasoning into a follow-up turn, append response.OutputItems to inputItems
// and resend with StoredOutputEnabled = false. Don't use PreviousResponseId when not stored.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: process.env.AZURE_OPENAI_API_KEY,
});
const response = await client.responses.create({
model: "MODEL_NAME",
reasoning: { effort: "medium" },
input: "What is the weather like today?",
tools: [
// Replace with your function or tool definitions.
],
include: ["reasoning.encrypted_content"],
store: false,
});
console.log(response.output_text);
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.AuthenticationUtil;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.Reasoning;
import com.openai.models.responses.ReasoningEffort;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseIncludable;
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(AzureApiKeyCredential.create(System.getenv("AZURE_OPENAI_API_KEY")))
.build();
Response response = openAIClient.responses().create(
ResponseCreateParams.builder()
.model("MODEL_NAME")
.input("Explain quantum entanglement.")
.reasoning(Reasoning.builder().effort(ReasoningEffort.MEDIUM).build())
.addInclude(ResponseIncludable.REASONING_ENCRYPTED_CONTENT)
.store(false)
.build());
System.out.println(response.outputText());
curl -X POST https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/responses \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d '{
"model": "MODEL_NAME",
"reasoning": {"effort": "medium"},
"input": "What is the weather like today?",
"tools": [],
"include": ["reasoning.encrypted_content"],
"store": false
}'
Responses API を使用すると、会話とマルチステップ ワークフローの一部として画像を生成できます。 コンテキスト内の画像の入力と出力をサポートし、画像を生成および編集するための組み込みのツールが含まれています。
スタンドアロンの Image API と比較すると、Responses API には次の 2 つの利点があります。
-
ストリーミング: 生成中に部分的な画像出力を表示して、認識される待機時間を改善します。
-
柔軟な入力: 生の画像バイトに加えて、画像ファイル ID を入力として受け入れます。
メモ
Responses API の画像生成ツールは、 gpt-image-1シリーズ モデルでサポートされており、互換性のあるチャットと推論モデルのセットから呼び出すことができます。 サポートされているオーケストレーション モデルの現在の一覧については、この記事で後述する 「サポートされているモデル 」セクションを参照してください。
イメージ生成ツールは現在、ストリーミング モードをサポートしていません。 部分的なイメージをストリーミングするには、Responses API の外部から直接 イメージ生成 API を呼び出します。
Responses API を使用して、GPT イメージ モデルを使用して会話型イメージ エクスペリエンスを構築します。
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" }]
}'
推論モデル
応答 API で推論モデルを使用する方法の例については、 推論モデルガイドを参照してください。
コンピューターの使用
Playwright でのコンピューターの使用は、 専用のコンピューター使用モデル ガイドに移行しました。
トラブルシューティング
-
401/403: Microsoft Entra IDを使用する場合は、トークンのスコープが
https://ai.azure.com/.default であることを確認します。 API キーを使用する場合は、リソースに正しいキーを使用していることを確認します。
-
404:
model がデプロイ名と一致するかどうかを確認します。
関連コンテンツ