Azure OpenAI v1 エンドポイントと共に OpenAI SDK を使用して、Python、C#、JavaScript、Java、または Go でモデル推論アプリケーションを構築します。 この例では、新しいアプリケーションに Responses API を使用し、メッセージ ベースのインターフェイスを引き続き使用するアプリケーションのチャットの完了を示します。
前提 条件
- Azure サブスクリプション。 お持ちでない場合は、無料で作成してください。
-
gpt-5-miniモデルデプロイを使用するAzure OpenAI リソース。 - Azure OpenAI リソース エンドポイント (
https://YOUR-RESOURCE-NAME.openai.azure.comなど)。 - Microsoft Entra ID認証の場合、推論を実行するアクセス許可を持つ ID。 ロール オプションについては、「Microsoft Entra ID認証の構成」を参照してください。
- API キー認証の場合、Azure OpenAI リソース キー。 運用環境のアプリケーションには、Microsoft Entra IDをお勧めします。
- 選択した言語でサポートされている言語ランタイムとパッケージ マネージャー。
すべての要求のmodel値は、Azure モデルのデプロイ名です。 例では、 gpt-5-miniを使用します。デプロイの名前が異なる場合は置き換えます。
例は、OpenAI 2.12.0、Azure.Identity 1.21.0、.NET 8 でテストされました。 OpenAI パッケージは、Standard 2.0 以降の.NET バージョン.NETも対象としています。
パッケージをインストールする
OpenAI と Azure ID パッケージをインストールします。
dotnet add package OpenAI
dotnet add package Azure.Identity
このコマンドは、両方のパッケージ参照をプロジェクトに追加します。
Microsoft Entra IDを使用して応答を作成する
API キーを格納せずに認証するには、 DefaultAzureCredential と BearerTokenPolicy を使用します。
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
#pragma warning disable OPENAI001
var endpoint = new Uri(
"https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/");
var tokenPolicy = new BearerTokenPolicy(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
var openAIClient = new ResponsesClient(
tokenPolicy,
new ResponsesClientOptions { Endpoint = endpoint });
var response = await openAIClient.CreateResponseAsync(
"gpt-5-mini",
"Explain the purpose of an API in one sentence.");
Console.WriteLine(response.Value.GetOutputText());
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
ResponsesClient を参照してください。
API キーを使用して応答を作成する
API キーは、運用環境での使用には推奨されません。 キーをソース コードに配置するのではなく、 AZURE_OPENAI_API_KEY 環境変数に格納します。
export AZURE_OPENAI_API_KEY="<your-api-key>"
次に、クライアントを作成して要求します。
using OpenAI.Responses;
using System.ClientModel;
#pragma warning disable OPENAI001
var endpoint = new Uri(
"https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/");
var apiKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")
?? throw new InvalidOperationException("AZURE_OPENAI_API_KEY is required.");
var openAIClient = new ResponsesClient(
new ApiKeyCredential(apiKey),
new ResponsesClientOptions { Endpoint = endpoint });
var response = await openAIClient.CreateResponseAsync(
"gpt-5-mini",
"Explain the purpose of an API in one sentence.");
Console.WriteLine(response.Value.GetOutputText());
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
CreateResponseAsync を参照してください。
チャットの完了を使用する
新しいアプリケーションの場合は、Responses API を使用します。 メッセージ ベースのインターフェイスが必要な場合、または既存のアプリケーションを維持している場合は、チャットの完了を使用します。
using Azure.Identity;
using OpenAI;
using OpenAI.Chat;
using System.ClientModel.Primitives;
#pragma warning disable OPENAI001
var endpoint = new Uri(
"https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/");
var tokenPolicy = new BearerTokenPolicy(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
var openAIClient = new ChatClient(
model: "gpt-5-mini",
authenticationPolicy: tokenPolicy,
options: new OpenAIClientOptions { Endpoint = endpoint });
var completion = await openAIClient.CompleteChatAsync([
new SystemChatMessage("You are a helpful assistant."),
new UserChatMessage("Explain the purpose of an API.")
]);
Console.WriteLine(completion.Value.Content[0].Text);
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
ChatClient を参照してください。
応答をストリーム配信する
CreateResponseStreamingAsyncを呼び出し、モデルによって生成されるテキスト差分更新を処理します。
using OpenAI.Responses;
using System.ClientModel;
#pragma warning disable OPENAI001
var endpoint = new Uri(
"https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/");
var apiKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")
?? throw new InvalidOperationException("AZURE_OPENAI_API_KEY is required.");
var openAIClient = new ResponsesClient(
new ApiKeyCredential(apiKey),
new ResponsesClientOptions { Endpoint = endpoint });
// Stream text as the model generates it.
var updates = openAIClient.CreateResponseStreamingAsync(
"gpt-5-mini",
"Explain the purpose of an API in one sentence.");
await foreach (var update in updates)
{
if (update is StreamingResponseOutputTextDeltaUpdate delta)
{
Console.Write(delta.Delta);
}
}
次のストリーミング出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
CreateResponseStreamingAsync を参照してください。
エラーと再試行を処理する
クライアントは、指数バックオフを使用して HTTP 408、429、500、502、503、および 504 応答を自動的に再試行します。 異なる動作が必要な場合は、クライアント オプションを使用して再試行ポリシーを構成します。
ClientResultExceptionをキャッチして、失敗した要求の HTTP 状態とエラーの詳細を調べます。
診断の場合は、操作によって返された ClientResult<T> を保持し、その生の応答ヘッダーを調べます。 失敗した操作では、 ClientResultExceptionを介して状態情報が公開されます。
リファレンス: エラー処理とクライアント結果の詳細
その他の SDK の例
ソース コード | パッケージ | REST API リファレンス | Go API リファレンス
例では Go 1.25 以降が必要です。 これらは、 github.com/openai/openai-go/v3 3.44.0 と azidentity 1.14.0 でテストされました。
モジュールをインストールする
OpenAI モジュールと Azure Identity モジュールをインストールします。
go get github.com/openai/openai-go/v3
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
go モジュールの現在のメジャー バージョンを識別するため、 /v3 サフィックスが必要です。
Microsoft Entra IDを使用して応答を作成する
API キーを格納せずに認証するには、DefaultAzureCredentialとAzure認証オプションを使用します。
package main
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/azure"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)
func main() {
credential, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil { panic(err) }
endpoint := "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openaiClient := openai.NewClient(
option.WithBaseURL(endpoint),
azure.WithTokenCredential(credential, azure.WithTokenCredentialScopes(
[]string{"https://ai.azure.com/.default"})))
response, err := openaiClient.Responses.New(context.Background(), responses.ResponseNewParams{
Model: openai.ChatModel("gpt-5-mini"),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(
"Explain the purpose of an API in one sentence.")},
})
if err != nil { panic(err) }
fmt.Println(response.OutputText())
}
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
リファレンス: ResponseService.New と WithTokenCredentialScopes
API キーを使用して応答を作成する
API キーは、運用環境での使用には推奨されません。 キーをソース コードに配置するのではなく、 AZURE_OPENAI_API_KEY 環境変数に格納します。
export AZURE_OPENAI_API_KEY="<your-api-key>"
次に、クライアントを作成して要求します。
package main
import (
"context"
"fmt"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)
func main() {
apiKey := os.Getenv("AZURE_OPENAI_API_KEY")
if apiKey == "" { panic("AZURE_OPENAI_API_KEY is required") }
endpoint := "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openaiClient := openai.NewClient(
option.WithBaseURL(endpoint),
option.WithAPIKey(apiKey))
response, err := openaiClient.Responses.New(context.Background(), responses.ResponseNewParams{
Model: openai.ChatModel("gpt-5-mini"),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(
"Explain the purpose of an API in one sentence.")},
})
if err != nil { panic(err) }
fmt.Println(response.OutputText())
}
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
Responses.New を参照してください。
チャットの完了を使用する
新しいアプリケーションの場合は、Responses API を使用します。 メッセージ ベースのインターフェイスが必要な場合、または既存のアプリケーションを維持している場合は、チャットの完了を使用します。
package main
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/azure"
"github.com/openai/openai-go/v3/option"
)
func main() {
credential, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil { panic(err) }
endpoint := "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openaiClient := openai.NewClient(
option.WithBaseURL(endpoint),
azure.WithTokenCredential(credential, azure.WithTokenCredentialScopes(
[]string{"https://ai.azure.com/.default"})))
completion, err := openaiClient.Chat.Completions.New(context.Background(),
openai.ChatCompletionNewParams{
Model: openai.ChatModel("gpt-5-mini"),
Messages: []openai.ChatCompletionMessageParamUnion{
openai.DeveloperMessage("You are a helpful assistant."),
openai.UserMessage("Explain the purpose of an API.")}})
if err != nil { panic(err) }
fmt.Println(completion.Choices[0].Message.Content)
}
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
Chat.Completions.New を参照してください。
応答をストリーム配信する
Responses.NewStreamingを呼び出し、モデルによって生成されるテキスト デルタ イベントを処理します。
package main
import (
"context"
"fmt"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)
func main() {
endpoint := "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openaiClient := openai.NewClient(option.WithBaseURL(endpoint),
option.WithAPIKey(os.Getenv("AZURE_OPENAI_API_KEY")))
// Stream text as the model generates it.
stream := openaiClient.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{
Model: openai.ChatModel("gpt-5-mini"),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(
"Explain the purpose of an API in one sentence.")},
})
for stream.Next() { fmt.Print(stream.Current().Delta) }
if err := stream.Err(); err != nil { panic(err) }
}
次のストリーミング出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
Responses.NewStreaming を参照してください。
エラーと再試行を処理する
SDK は、接続エラーと HTTP 408、409、429、および 5xx 応答を指数バックオフで 2 回再試行します。
option.WithMaxRetriesを使用して既定値を変更します。 応答を読み取る前に返された error を確認し、 errors.As を使用して openai.Errorを検査します。
package main
import (
"context"
"errors"
"fmt"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)
func main() {
endpoint := "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openaiClient := openai.NewClient(option.WithBaseURL(endpoint),
option.WithAPIKey(os.Getenv("AZURE_OPENAI_API_KEY")), option.WithMaxRetries(4))
// Send the request and inspect structured service errors.
result, err := openaiClient.Responses.New(context.Background(), responses.ResponseNewParams{
Model: openai.ChatModel("gpt-5-mini"),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Explain an API.")},
})
if err != nil {
var apiError *openai.Error
if errors.As(err, &apiError) { fmt.Printf("Status: %d; Request ID: %s\n",
apiError.StatusCode, apiError.Response.Header.Get("x-request-id")) }
panic(err)
}
fmt.Println(result.OutputText())
}
要求が成功した場合、次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
リファレンス: エラーと再試行
その他の SDK の例
ソース コード | パッケージ | REST API リファレンス | Java API リファレンス
例では、Java 8 以降が必要です。 これらは、 openai-java 4.43.0 と azure-identity 1.18.4 でテストされました。
パッケージをインストールする
Maven
Maven プロジェクトに OpenAI と Azure ID の依存関係を追加します。
<dependencies>
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.43.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.18.4</version>
</dependency>
</dependencies>
Maven は、プロジェクトのビルド時にパッケージとその推移的な依存関係を解決します。
Gradle
Gradle ビルド ファイルの dependencies ブロックに同じパッケージを追加します。
dependencies {
implementation("com.openai:openai-java:4.43.0")
implementation("com.azure:azure-identity:1.18.4")
}
Gradle は、プロジェクトのビルド時にパッケージを解決します。
Microsoft Entra IDを使用して応答を作成する
API キーを格納せずに認証するには、 DefaultAzureCredential と BearerTokenCredential を使用します。
import com.azure.identity.AuthenticationUtil;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.ResponseCreateParams;
public class ResponsesExample {
public static void main(String[] args) {
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(BearerTokenCredential.create(
AuthenticationUtil.getBearerTokenSupplier(
new DefaultAzureCredentialBuilder().build(),
"https://ai.azure.com/.default")))
.build();
ResponseCreateParams params = ResponseCreateParams.builder()
.model("gpt-5-mini")
.input("Explain the purpose of an API in one sentence.")
.build();
openAIClient.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(output -> System.out.println(output.text()));
}
}
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
リファレンス: AzureEntraIdExample と ResponsesExample
API キーを使用して応答を作成する
運用環境では API キーを使用しないでください。 キーをソース コードに配置するのではなく、 AZURE_OPENAI_API_KEY 環境変数に格納します。
export AZURE_OPENAI_API_KEY="<your-api-key>"
次に、クライアントを作成して要求します。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
public class ApiKeyResponsesExample {
public static void main(String[] args) {
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
String apiKey = System.getenv("AZURE_OPENAI_API_KEY");
if (apiKey == null) throw new IllegalStateException(
"AZURE_OPENAI_API_KEY is required.");
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint).apiKey(apiKey).build();
ResponseCreateParams params = ResponseCreateParams.builder()
.model("gpt-5-mini")
.input("Explain the purpose of an API in one sentence.")
.build();
openAIClient.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(output -> System.out.println(output.text()));
}
}
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
OpenAIOkHttpClient を参照してください。
チャットの完了を使用する
新しいアプリケーションの場合は、Responses API を使用します。 メッセージ ベースのインターフェイスが必要な場合、または既存のアプリケーションを維持している場合は、チャットの完了を使用します。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
public class ChatExample {
public static void main(String[] args) {
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
String apiKey = System.getenv("AZURE_OPENAI_API_KEY");
if (apiKey == null) throw new IllegalStateException(
"AZURE_OPENAI_API_KEY is required.");
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint).apiKey(apiKey).build();
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("gpt-5-mini")
.addDeveloperMessage("You are a helpful assistant.")
.addUserMessage("Explain the purpose of an API.")
.build();
openAIClient.chat().completions().create(params).choices().stream()
.flatMap(choice -> choice.message().content().stream())
.forEach(System.out::println);
}
}
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
ChatCompletionCreateParams を参照してください。
応答をストリーム配信する
createStreamingを呼び出し、モデルによって生成されるテキスト デルタ イベントを処理します。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseStreamEvent;
public class StreamingExample {
public static void main(String[] args) {
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
String apiKey = System.getenv("AZURE_OPENAI_API_KEY");
if (apiKey == null) throw new IllegalStateException(
"AZURE_OPENAI_API_KEY is required.");
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint).apiKey(apiKey).build();
// Stream text as the model generates it.
ResponseCreateParams params = ResponseCreateParams.builder()
.model("gpt-5-mini")
.input("Explain the purpose of an API in one sentence.")
.build();
try (StreamResponse<ResponseStreamEvent> stream =
openAIClient.responses().createStreaming(params)) {
stream.stream().flatMap(event -> event.outputTextDelta().stream())
.forEach(delta -> System.out.print(delta.delta()));
}
}
}
次のストリーミング出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
responses.createStreaming を参照してください。
エラーと再試行を処理する
SDK は、接続エラーと HTTP 408、409、429、および 5xx 応答を指数バックオフで 2 回再試行します。
OpenAIServiceExceptionをキャッチして、サービス応答の HTTP 状態とエラーの詳細を調べ、他の SDK エラーのOpenAIExceptionをキャッチします。
maxRetriesのOpenAIOkHttpClient.builder()を呼び出して、既定値を変更します。 アプリケーションが状態をログに記録し、メタデータを要求できるように、サービス例外を保持します。
その他の SDK の例
ソース コード | パッケージ | REST API リファレンス | Azure OpenAI v1 ガイダンス
例では、Node.js 20 以降が必要です。 これらは、 openai 6.46.0 と @azure/identity 4.13.1 でテストされました。
openaiとしてMicrosoft Entra トークン プロバイダーを渡す場合は、apiKey 5.18.0 以降を使用します。
パッケージをインストールする
OpenAI と Azure ID パッケージをインストールします。
npm install openai @azure/identity
このコマンドは、両方のパッケージをプロジェクトに追加します。
Microsoft Entra IDを使用して応答を作成する
API キーを格納せずに認証するには、 DefaultAzureCredential と getBearerTokenProvider を使用します。 トークン プロバイダーは、必要に応じアクセス トークンを更新します。
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
import OpenAI from "openai";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
"https://ai.azure.com/.default",
);
const openai = new OpenAI({ baseURL: endpoint, apiKey: tokenProvider });
async function main() {
const response = await openai.responses.create({
model: "gpt-5-mini",
input: "Explain the purpose of an API in one sentence.",
});
console.log(response.output_text);
}
main().catch(console.error);
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
リファレンス: OpenAI クライアントと Azure OpenAI v1 認証
API キーを使用して応答を作成する
API キーは、運用環境での使用には推奨されません。 キーをソース コードに配置するのではなく、 AZURE_OPENAI_API_KEY 環境変数に格納します。
export AZURE_OPENAI_API_KEY="<your-api-key>"
次に、クライアントを作成して要求します。
import OpenAI from "openai";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
const apiKey = process.env["AZURE_OPENAI_API_KEY"];
if (!apiKey) throw new Error("AZURE_OPENAI_API_KEY is required.");
const openai = new OpenAI({ baseURL: endpoint, apiKey });
async function main() {
const response = await openai.responses.create({
model: "gpt-5-mini",
input: "Explain the purpose of an API in one sentence.",
});
console.log(response.output_text);
}
main().catch(console.error);
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
responses.create を参照してください。
チャットの完了を使用する
新しいアプリケーションの場合は、Responses API を使用します。 メッセージ ベースのインターフェイスが必要な場合、または既存のアプリケーションを維持している場合は、チャットの完了を使用します。
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
import OpenAI from "openai";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
"https://ai.azure.com/.default",
);
const openai = new OpenAI({ baseURL: endpoint, apiKey: tokenProvider });
async function main() {
const completion = await openai.chat.completions.create({
model: "gpt-5-mini",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Explain the purpose of an API." },
],
});
console.log(completion.choices[0]?.message.content ?? "No response returned.");
}
main().catch(console.error);
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
要求内で messages を維持すると、 role 値に必要なコンテキスト型指定が提供されます。 配列を個別に定義する場合は、 OpenAI.Chat.ChatCompletionMessageParam[]として宣言します。
chat.completions.create を参照してください。
応答をストリーム配信する
streamをtrueに設定し、モデルによって生成されるテキスト デルタ イベントを処理します。
import OpenAI from "openai";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
const apiKey = process.env["AZURE_OPENAI_API_KEY"];
if (!apiKey) throw new Error("AZURE_OPENAI_API_KEY is required.");
const openai = new OpenAI({ baseURL: endpoint, apiKey });
async function main() {
// Stream text as the model generates it.
const stream = await openai.responses.create({
model: "gpt-5-mini",
input: "Explain the purpose of an API in one sentence.",
stream: true,
});
for await (const event of stream) {
if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
}
}
}
main().catch(console.error);
次のストリーミング出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
リファレンス: responses.create ストリーミング
エラーと再試行を処理する
SDK は、接続エラー、タイムアウト、HTTP 408、409、429、および 5xx 応答を指数バックオフで 2 回自動的に再試行します。 この動作を変更するには、maxRetries クライアントでOpenAIを設定します。 失敗した要求の HTTP 状態、要求 ID、エラーの詳細を調べるには、 APIError をキャッチします。
次の例では、4 回の再試行を設定し、成功した要求と失敗した要求の要求 ID を記録します。
import OpenAI from "openai";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
const apiKey = process.env["AZURE_OPENAI_API_KEY"];
if (!apiKey) throw new Error("AZURE_OPENAI_API_KEY is required.");
const openai = new OpenAI({ baseURL: endpoint, apiKey, maxRetries: 4 });
async function main() {
try {
// Send the request and record its request ID.
const response = await openai.responses.create({
model: "gpt-5-mini",
input: "Explain the purpose of an API in one sentence.",
});
console.log(response.output_text);
console.log(`Request ID: ${response._request_id}`);
} catch (error) {
if (error instanceof OpenAI.APIError) {
console.error(`Status: ${error.status}; Request ID: ${error.requestID}`);
}
throw error;
}
}
main().catch(console.error);
要求が成功した場合、次の出力が代表的です。 応答テキストと要求 ID は異なります。
An API allows software applications to communicate and exchange data through a defined set of rules.
Request ID: <request-id>
リファレンス: 要求 ID、エラー、再試行
その他の SDK の例
ソース コード | パッケージ | API リファレンス
例では、Python 3.9 以降が必要です。 これらは、 openai 2.46.0 と azure-identity 1.25.3 でテストされました。 Microsoft Entra トークン プロバイダーをopenaiとして渡すときは、api_key 1.106.0 以降を使用します。
パッケージをインストールする
OpenAI と Azure ID パッケージをインストールします。
pip install openai azure-identity
このコマンドは、両方のパッケージをアクティブなPython環境にインストールします。
Microsoft Entra IDを使用して応答を作成する
API キーを格納せずに認証するには、 DefaultAzureCredential と get_bearer_token_provider を使用します。 トークン プロバイダーは、必要に応じアクセス トークンを更新します。
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import OpenAI
endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://ai.azure.com/.default"
)
openai = OpenAI(base_url=endpoint, api_key=token_provider)
response = openai.responses.create(
model="gpt-5-mini",
input="Explain the purpose of an API in one sentence.",
)
print(response.output_text)
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
リファレンス: OpenAI クライアント と get_bearer_token_provider
API キーを使用して応答を作成する
API キーは、運用環境での使用には推奨されません。 キーをソース コードに配置するのではなく、 AZURE_OPENAI_API_KEY 環境変数に格納します。
export AZURE_OPENAI_API_KEY="<your-api-key>"
次に、クライアントを作成して要求します。
import os
from openai import OpenAI
endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
api_key = os.environ["AZURE_OPENAI_API_KEY"]
openai = OpenAI(base_url=endpoint, api_key=api_key)
response = openai.responses.create(
model="gpt-5-mini",
input="Explain the purpose of an API in one sentence.",
)
print(response.output_text)
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
responses.create を参照してください。
チャットの完了を使用する
新しいアプリケーションの場合は、Responses API を使用します。 メッセージ ベースのインターフェイスが必要な場合、または既存のアプリケーションを維持している場合は、チャットの完了を使用します。
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import OpenAI
endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://ai.azure.com/.default"
)
openai = OpenAI(base_url=endpoint, api_key=token_provider)
completion = openai.chat.completions.create(
model="gpt-5-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain the purpose of an API."},
],
)
print(completion.choices[0].message.content)
次の出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
chat.completions.create を参照してください。
応答をストリーム配信する
streamをTrueに設定し、モデルによって生成されるテキスト デルタ イベントを処理します。
import os
from openai import OpenAI
endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openai = OpenAI(
base_url=endpoint,
api_key=os.environ["AZURE_OPENAI_API_KEY"],
)
# Stream text as the model generates it.
stream = openai.responses.create(
model="gpt-5-mini",
input="Explain the purpose of an API in one sentence.",
stream=True,
)
for event in stream:
if event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
次のストリーミング出力が代表的です。 正確な文言は異なる場合があります。
An API allows software applications to communicate and exchange data through a defined set of rules.
リファレンス: responses.create ストリーミング
エラーと再試行を処理する
SDK は、接続エラー、タイムアウト、HTTP 408、409、429、および 5xx 応答を指数バックオフで 2 回自動的に再試行します。 この動作を変更するには、max_retries クライアントでOpenAIを設定します。 失敗した要求の HTTP 状態、要求 ID、応答を調べるには、 openai.APIStatusError をキャッチします。
次の例では、4 回の再試行を設定し、成功した要求と失敗した要求の要求 ID を記録します。
import os
import openai as openai_sdk
from openai import OpenAI
endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openai = OpenAI(
base_url=endpoint,
api_key=os.environ["AZURE_OPENAI_API_KEY"],
max_retries=4,
)
try:
# Send the request and record its request ID.
response = openai.responses.create(
model="gpt-5-mini",
input="Explain the purpose of an API in one sentence.",
)
print(response.output_text)
print(f"Request ID: {response._request_id}")
except openai_sdk.APIStatusError as error:
print(f"Status: {error.status_code}; Request ID: {error.request_id}")
raise
要求が成功した場合、次の出力が代表的です。 応答テキストと要求 ID は異なります。
An API allows software applications to communicate and exchange data through a defined set of rules.
Request ID: <request-id>
リファレンス: 要求 ID、エラー、再試行
その他の SDK の例
トラブルシューティング
-
401または403応答の場合は、目的の ID または API キーが Azure OpenAI リソースにアクセスできることを確認します。 -
404応答の場合は、ベース URL が/openai/v1/で終わり、modelに有効なデプロイ名が含まれていることを確認します。 - パッケージまたは型エラーの場合は、SDK を更新し、インストールされているバージョンとこのページでテストされたバージョンを比較します。
- モデル パラメーター エラーの場合は、デプロイされたモデルがパラメーターをサポートしているかどうかを確認します。 パラメーターのサポートは、モデル ファミリによって異なる場合があります。