使用 OpenAI SDK 搭配 Azure OpenAI v1 端點,建立 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 認證,一個有執行推論權限的身份。 關於角色選項,請參見「配置 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 套件同時也支援 .NET Standard 2.0 及後續 .NET 版本。
安裝套件
安裝 OpenAI 與 Azure Identity 套件:
dotnet add package OpenAI
dotnet add package Azure.Identity
指令會把兩個套件的參考都加入你的專案。
用 Microsoft Entra ID 建立回應
使用 DefaultAzureCredential 和 BearerTokenPolicy 進行驗證,且不儲存 API 金鑰。
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。 當你需要訊息介面或維護現有應用程式時,請使用 Chat Completions。
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 的回應。 當你需要不同的行為時,透過客戶端選項設定重試政策。 Catch ClientResultException 可檢查 HTTP 狀態及錯誤細節,尋找失敗請求。
診斷時,保留操作回傳的 並 ClientResult<T> 檢查其原始回應標頭。 失敗操作會透過 揭露狀態資訊 ClientResultException。
參考資料: 錯誤處理與客戶結果細節
更多 SDK 範例
原始碼 | 包裝 | REST API 參考 | Go API 參考
這些範例需要 Go 1.25 或更新版本。 它們曾以 3.44.0 和 github.com/openai/openai-go/v3 1.14.0 版本進行測試azidentity。
安裝模組
安裝 OpenAI 與 Azure Identity 模組:
go get github.com/openai/openai-go/v3
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
/v3這個後綴是因為它標示了當前 Go 模組的主要版本。
用 Microsoft Entra ID 建立回應
使用 DefaultAzureCredential 和 Azure 認證選項,可以在不儲存 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"
"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。 當你需要訊息介面或維護現有應用程式時,請使用 Chat Completions。
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,並在模型產生的文字 delta 事件時處理它們:
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 回應兩次。 用來 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 或更新版本。 它們曾以 4.43.0 和 openai-java 1.18.4 進行測試azure-identity。
安裝套件
Maven
將 OpenAI 和 Azure Identity 相依關係加入你的 Maven 專案:
<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 建立回應
使用 DefaultAzureCredential 和 BearerTokenCredential 進行驗證,且不儲存 API 金鑰。
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。 當你需要訊息介面或維護現有應用程式時,請使用 Chat Completions。
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,並在模型產生的文字 delta 事件時處理它們:
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 回應兩次。 Catch OpenAIServiceException 用來檢查服務回應的 HTTP 狀態和錯誤細節,以及 OpenAIException 其他 SDK 失敗的 catch。
打電話maxRetriesOpenAIOkHttpClient.builder()去更改預設值。 保留服務例外,讓你的應用程式能記錄狀態並請求元資料。
更多 SDK 範例
原始碼 | 包裝 | REST API 參考 | Azure OpenAI v1 guidance
這些例子需要 Node.js 20年或更晚。 它們曾以 6.46.0 和 openai 4.13.1 進行測試@azure/identity。 當你傳遞 Microsoft Entra 令牌提供者時openai,請使用 apiKey 5.18.0 或更新版本。
安裝套件
安裝 OpenAI 與 Azure Identity 套件:
npm install openai @azure/identity
這個指令會把兩個套件都加入你的專案。
用 Microsoft Entra ID 建立回應
使用 DefaultAzureCredential 和 getBearerTokenProvider 進行驗證,且不儲存 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 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。 當你需要訊息介面或維護現有應用程式時,請使用 Chat Completions。
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,並在模型產生文字 delta 事件時處理它們:
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 回應兩次。 設定maxRetriesOpenAI客戶端來改變這種行為。 Catch APIError 可檢查 HTTP 狀態、請求 ID 及失敗請求的錯誤細節。
以下範例設定四次重試,並記錄成功與失敗請求的請求 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 範例
這些範例需要 Python 3.9 或更新版本。 它們曾以 2.46.0 和 openai 1.25.3 進行測試azure-identity。 當你傳遞 Microsoft Entra 令牌提供者時openai,請使用 api_key 1.106.0 或更新版本。
安裝套件
安裝 OpenAI 與 Azure Identity 套件:
pip install openai azure-identity
此指令會將兩個套件安裝在活躍的 Python 環境中。
用 Microsoft Entra ID 建立回應
使用 DefaultAzureCredential 和 get_bearer_token_provider 進行驗證,且不儲存 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)
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。 當你需要訊息介面或維護現有應用程式時,請使用 Chat Completions。
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,並在模型產生文字 delta 事件時處理它們:
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 回應兩次。 設定max_retriesOpenAI客戶端來改變這種行為。 Catch openai.APIStatusError 用來檢查 HTTP 狀態、請求 ID 以及失敗請求的回應。
以下範例設定四次重試,並記錄成功與失敗請求的請求 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 範例
故障排除
- 對於 a
401或403回應,請確認預期的身份或 API 金鑰是否能存取 Azure OpenAI 資源。 - 回覆
404時,請確認基礎網址以 in/openai/v1/結尾且model包含有效的部署名稱。 - 遇到套件或類型錯誤時,更新 SDK 並比較已安裝版本與本頁測試版本。
- 若出現模型參數錯誤,請檢查已部署的模型是否支援該參數。 參數支援在不同模型族之間可能有所不同。