開始使用 Azure OpenAI 和回應 API

本文將教你如何使用 Azure OpenAI Starter Kit來部署一個Azure OpenAI 資源,並運行一個小型的 Hello World 應用程式。 此應用程式使用 Microsoft Entra ID 驗證和 OpenAI SDK 來呼叫 Azure OpenAI Responses API。

到本文結束時,你將:

  • 使用 Azure 開發者 CLI 部署 Azure OpenAI 與 GPT-5-mini。
  • 執行一個本地應用程式,用 Microsoft Entra ID 來驗證,而不是 API 金鑰。
  • 發送一個請求到 Responses API,然後列印模型輸出。

Note

本文以 Azure OpenAI 入門套件作為範例的基礎。 入門套件包含基礎設施即程式碼、Azure 開發者 CLI 設定,以及多種程式語言的用戶端範例。

Cost

本文中建立的 Azure 資源所產生的費用會計入您的 Azure 訂用帳戶。 為了避免持續收費,完成文章後請整理資源。

先決條件

要完成這篇文章,你需要:

  • Python 3.8 或更新版本。
  • .NET SDK 10 或更新版本。 入門套件使用基於檔案的 C# 應用程式,並執行套件指令。
  • Node.js 18 或更新版本。
  • 改用 1.25.1 或更新版本。
  • Java 21 或更新版本。
  • Maven 3.9 或更新版本。

取得程式碼

複製 Azure OpenAI 入門套件庫並開啟專案資料夾。

git clone https://github.com/Azure-Samples/azure-openai-starter.git
cd azure-openai-starter

登入 Azure

請同時使用 Azure CLI 和 Azure Developer CLI 登入。

az login
azd auth login

如果你的帳號有多個租戶的存取權,請確認該活躍租戶就是你想要部署資源的租戶。

az account show --query tenantId -o tsv

Deploy Azure OpenAI

從倉庫根執行以下 Azure Developer CLI 指令:

azd up

請依照以下指引回答題目:

提示 Answer
環境名稱 使用簡短的小寫名稱,例如 aoai-hello。 這個值用於 Azure 資源名稱中。
訂閱 選擇你想建立資源的訂閱。
地點 選取您附近的區域。
Azure OpenAI 模型位置 選擇有 GPT-5-mini 可用區域。

部署通常需時數分鐘。 指令完成後,入門套件已配置 Azure OpenAI 並部署 GPT-5-mini 模型。

設定您的本機環境

hello world 應用程式會用你的 Azure 登入來取得 Microsoft Entra 存取權杖。 設定 OpenAI 用戶端使用的端點。

export AZURE_OPENAI_ENDPOINT=$(azd env get-value AZURE_OPENAI_ENDPOINT)
export AZURE_OPENAI_DEPLOYMENT=$(azd env get-value AZURE_OPENAI_GPT_DEPLOYMENT_NAME)
export AZURE_TENANT_ID=$(az account show --query tenantId -o tsv)

Tip

Azure OpenAI 在 API 呼叫中使用部署名稱。 入門套件會將 GPT-5-mini 的部署名稱輸出為 AZURE_OPENAI_GPT_DEPLOYMENT_NAME。 本文將這個值映射到 AZURE_OPENAI_DEPLOYMENT ,使程式碼在不同語言間保持一致。

建立並執行 Hello World 應用程式

在 hello_world_entra.py 資料夾中,建立名為 src/python 的檔案。

import os

from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import OpenAI

endpoint = os.environ["AZURE_OPENAI_ENDPOINT"].rstrip("/")
deployment = os.getenv("AZURE_OPENAI_DEPLOYMENT", "gpt-5-mini")

token_provider = get_bearer_token_provider(
    DefaultAzureCredential(),
    "https://cognitiveservices.azure.com/.default",
)

client = OpenAI(
    base_url=f"{endpoint}/openai/v1/",
    api_key=token_provider,
)

response = client.responses.create(
    model=deployment,
    input="Say hello from Azure OpenAI in one sentence.",
    max_output_tokens=300,
)

print(response.output_text)

安裝 Python 相依套件並執行應用程式。

cd src/python
python -m pip install -r requirements.txt
python hello_world_entra.py

在 hello_world_entra.cs 資料夾中,建立名為 src/dotnet 的檔案。

#!/usr/bin/dotnet run
#:package OpenAI@2.9.1
#:package Azure.Identity@1.*

using System;
using System.ClientModel.Primitives;
using Azure.Identity;
using OpenAI;
using OpenAI.Responses;

#pragma warning disable OPENAI001

string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
    ?? throw new InvalidOperationException("Set AZURE_OPENAI_ENDPOINT.");
string deployment = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT")
    ?? "gpt-5-mini";

BearerTokenPolicy tokenPolicy = new(
    new DefaultAzureCredential(),
    "https://cognitiveservices.azure.com/.default");

OpenAIClientOptions options = new()
{
    Endpoint = new Uri($"{endpoint.TrimEnd('/')}/openai/v1/")
};

ResponsesClient client = new(tokenPolicy, options);

ResponseResult response = await client.CreateResponseAsync(
    deployment,
    "Say hello from Azure OpenAI in one sentence.",
    null);

Console.WriteLine(response.GetOutputText());

執行應用程式。

cd src/dotnet
dotnet run hello_world_entra.cs

在 hello_world_entra.ts 資料夾中,建立名為 src/typescript 的檔案。

import OpenAI from "openai";
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";

const endpoint = process.env.AZURE_OPENAI_ENDPOINT;

if (!endpoint) {
  throw new Error("Set AZURE_OPENAI_ENDPOINT.");
}

const deployment = process.env.AZURE_OPENAI_DEPLOYMENT ?? "gpt-5-mini";
const tokenProvider = getBearerTokenProvider(
  new DefaultAzureCredential(),
  "https://cognitiveservices.azure.com/.default"
);

const client = new OpenAI({
  baseURL: `${endpoint.replace(/\/+$/, "")}/openai/v1/`,
  apiKey: tokenProvider as any,
});

const response = await client.responses.create({
  model: deployment,
  input: "Say hello from Azure OpenAI in one sentence.",
  max_output_tokens: 300,
});

console.log(response.output_text);

安裝 TypeScript 相依套件並執行應用程式。

cd src/typescript
npm install
npx tsx hello_world_entra.ts

在 hello_world_entra.go 資料夾中,建立名為 src/go/responses_example_entra 的檔案。

package main

import (
  "context"
  "fmt"
  "log"
  "net/http"
  "os"
  "strings"

  "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
  "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
  "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
  "github.com/openai/openai-go/v3"
  "github.com/openai/openai-go/v3/option"
  "github.com/openai/openai-go/v3/responses"
)

type policyAdapter option.MiddlewareNext

func (adapter policyAdapter) Do(req *policy.Request) (*http.Response, error) {
  return (option.MiddlewareNext)(adapter)(req.Raw())
}

func newClient(endpoint string) openai.Client {
  const scope = "https://cognitiveservices.azure.com/.default"

  credential, err := azidentity.NewDefaultAzureCredential(nil)
  if err != nil {
    log.Fatalf("Failed to create DefaultAzureCredential: %s", err)
  }

  bearerTokenPolicy := runtime.NewBearerTokenPolicy(
    credential,
    []string{scope},
    nil,
  )

  return openai.NewClient(
    option.WithBaseURL(strings.TrimRight(endpoint, "/")+"/openai/v1/"),
    option.WithMiddleware(func(req *http.Request, next option.MiddlewareNext) (*http.Response, error) {
      pipeline := runtime.NewPipeline(
        "aoai-hello-world",
        "",
        runtime.PipelineOptions{},
        &policy.ClientOptions{
          PerRetryPolicies: []policy.Policy{
            bearerTokenPolicy,
            policyAdapter(next),
          },
        },
      )

      pipelineRequest, err := runtime.NewRequestFromRequest(req)
      if err != nil {
        return nil, err
      }

      return pipeline.Do(pipelineRequest)
    }),
  )
}

func main() {
  endpoint := os.Getenv("AZURE_OPENAI_ENDPOINT")
  if endpoint == "" {
    log.Fatal("Set AZURE_OPENAI_ENDPOINT.")
  }

  deployment := os.Getenv("AZURE_OPENAI_DEPLOYMENT")
  if deployment == "" {
    deployment = "gpt-5-mini"
  }

  client := newClient(endpoint)

  response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
    Model: deployment,
    Input: responses.ResponseNewParamsInputUnion{
      OfString: openai.String("Say hello from Azure OpenAI in one sentence."),
    },
    MaxOutputTokens: openai.Int(300),
  })
  if err != nil {
    log.Fatalf("Failed to create response: %s", err)
  }

  fmt.Println(response.OutputText())
}

執行應用程式。

cd src/go/responses_example_entra
go run hello_world_entra.go

在 HelloWorldEntra.java 資料夾中,建立名為 src/java/src/main/java/com/azure/openai/starter 的檔案。

package com.azure.openai.starter;

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.Response;
import com.openai.models.responses.ResponseCreateParams;

import java.util.function.Supplier;

public class HelloWorldEntra {

    public static void main(String[] args) {
        String endpoint = System.getenv("AZURE_OPENAI_ENDPOINT");
        if (endpoint == null || endpoint.isBlank()) {
            throw new IllegalStateException("Set AZURE_OPENAI_ENDPOINT.");
        }

        String deployment = System.getenv().getOrDefault(
                "AZURE_OPENAI_DEPLOYMENT",
                "gpt-5-mini");

        Supplier<String> bearerTokenSupplier = AuthenticationUtil.getBearerTokenSupplier(
                new DefaultAzureCredentialBuilder().build(),
                "https://cognitiveservices.azure.com/.default");

        OpenAIClient client = OpenAIOkHttpClient.builder()
                .baseUrl(endpoint.replaceAll("/+$", "") + "/openai/v1/")
                .credential(BearerTokenCredential.create(bearerTokenSupplier))
                .build();

        Response response = client.responses().create(
                ResponseCreateParams.builder()
                        .model(deployment)
                        .input(ResponseCreateParams.Input.ofText(
                                "Say hello from Azure OpenAI in one sentence."))
                        .maxOutputTokens(300)
                        .build());

        System.out.println(response.output());
    }
}

執行應用程式。

cd src/java
mvn compile exec:java -Dexec.mainClass="com.azure.openai.starter.HelloWorldEntra"

具體的輸出格式會依 SDK 而異。 你應該會看到已部署的 Azure OpenAI 模型輸出,其中包含簡短的問候語。

Hello from Azure OpenAI! I'm running on your Azure OpenAI deployment and ready to help.

了解程式碼

Hello World 應用程式包含三個重要部分:

  • DefaultAzureCredential 會從你當地的 Azure 登入獲得一個 Microsoft Entra 代幣。
  • OpenAI 用戶端指向你Azure的 OpenAI v1 端點:/openai/v1/。
  • model 值是 Azure OpenAI 部署名稱。 在這個入門套件中,部署名稱為 gpt-5-mini。

Python 應用程式使用 openai 套件搭配 azure-identity。 get_bearer_token_provider 輔助程式會建立權杖提供者,供 OpenAI 用戶端將其用作認證憑證。

C# 應用程式使用 OpenAI 套件,並搭配 Azure.Identity。 BearerTokenPolicy 會為 ResponsesClient 所發送的請求增加 Microsoft Entra 個標記。

TypeScript 應用程式使用 openai 帶有 @azure/identity的套件。 getBearerTokenProvider 輔助程式會建立權杖提供者,供 OpenAI 用戶端將其用作認證憑證。

Go 應用程式使用 azidentity.NewDefaultAzureCredential,並採用 Azure Core 持有人令牌政策。 此原則會以中介軟體的形式新增至 OpenAI 用戶端,讓要求使用 Microsoft Entra ID 權杖。

Java 應用程式使用 DefaultAzureCredentialBuilder 搭配 AuthenticationUtil.getBearerTokenSupplier。 權杖提供者會使用 BearerTokenCredential 傳遞給 OpenAI 用戶端。

在 Azure 託管應用程式中使用無金鑰驗證

這個攻略是使用您的開發人員身分在本地執行應用程式;它不會把應用程式部署到 Azure。 當你在 Azure 中架設應用程式時,請設定主機服務和 Azure Identity 認證,讓它使用受控識別。 對於使用者指派的受控識別,請明確設定認證以選取該識別。 關於憑證指引及語言特定參考,請參見 Azure 服務的無密碼連線。

在 Azure OpenAI 資源範圍內,賦予託管應用程式的身份適當的 Azure OpenAI 角色,例如認知服務 OpenAI 使用者。 你的開發者帳號角色分配不會自動授予該託管應用程式的存取權限。 關於指派步驟,請參閱 使用 Azure 入口網站指派 Azure 角色。

執行入門套件範例

入門套件還包含每種語言的更大回應 API 範例。

python responses_example_entra.py
dotnet run responses_example_entra.cs
npx tsx responses_example_entra.ts
go run main.go
mvn compile exec:java -Dexec.mainClass="com.azure.openai.starter.ResponsesExampleEntra"

Troubleshooting

Issue 試試這個
azd up 失敗是因為 GPT-5-mini 在所選區域無法取得。 當提示時選擇不同的 Azure OpenAI 模型位置,或將另一個區域設為 azd env set AZURE_LOCATION eastus2,並重新執行 azd up。
azd up 因角色指派或授權錯誤而失敗。 確保你的帳號能建立資源和角色分配。 此範本通常需要 Owner 或 User Access Administrator 權限。
應用程式會回傳 401 或 PermissionDenied。 確認你已登入到 azd up 所使用的相同租用戶和訂用帳戶。 執行 az login、azd auth login,並將 AZURE_TENANT_ID 設定為來自 az account show 的租戶 ID。 角色分配的傳播也可能只需幾分鐘。
DefaultAzureCredential failed to retrieve a token。 確認Azure CLI已安裝並用 az account show 認證。 如果你使用多個租用戶,請使用 az login --tenant <tenant-id> 登入正確的租用戶。
應用程式會回傳 model not found 或 deployment not found。 確認 AZURE_OPENAI_DEPLOYMENT 是否與 Azure OpenAI 部署名稱相符。 入門套組的預設是 gpt-5-mini。
.NET 應用程式無法辨識套件指令。 安裝入門套件所需的 .NET SDK 版本。 基於檔案的 C# 應用程式若有 #:package,則需要更新的 .NET SDK。
Go 應用程式找不到模組或依賴。 從 src/go/responses_example_entra 執行 Go 指令。 確認 Go 1.25.1 或更新版本已安裝。
Java 應用程式會因來源版本或目標版本錯誤而失敗。 確認你的終端機是否安裝並選擇了 Java 21 或更新版本。
你需要詳細的部署日誌。 執行 azd up --debug。

你可以用以下工具檢查目前 Azure Developer CLI 環境的值:

azd env get-values

清理資源

當你不再需要資源時,從 starter kit 儲存庫的根目錄執行以下指令:

azd down --purge

這個指令會刪除 starter kit 建立的 Azure 資源,並幫助停止持續的收費。

尋求幫助

如果你需要入門套件的幫助,請利用以下資源:

下一步