共用方式為


快速入門:開始在 Azure OpenAI 服務上使用 GPT-35-Turbo 和 GPT-4

使用本文開始使用 Azure OpenAI。

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶

  • 在所需的 Azure 訂用帳戶中授與 Azure OpenAI 的存取權。

    目前只有應用程式會授予此服務的存取權。 您可以填妥 https://aka.ms/oai/access 的表單,以申請 Azure OpenAI 的存取權。 如有問題,請在此存放庫中提出問題來與我們連絡。

  • 已部署 gpt-35-turbogpt-4 模型的 Azure OpenAI 服務資源。 如需模型部署的詳細資訊,請參閱資源部署指南

提示

請嘗試新整合的 Azure AI Studio (預覽),此工具將多個 Azure AI 服務的功能整合在一起。

移至 Azure OpenAI Studio

https://oai.azure.com/ 瀏覽至 Azure OpenAI Studio,並使用可存取 OpenAI 資源的認證登入。 在登入工作流程期間 (或之後),選取適當的目錄、Azure 訂用帳戶和 Azure OpenAI 資源。

從 Azure OpenAI Studio 登陸頁面,選取 [聊天遊樂場]

此螢幕擷取畫面顯示 Azure OpenAI Studio 登陸頁面,其中醒目提示聊天遊樂場。

遊樂場

透過 Azure OpenAI Studio 聊天遊樂場開始探索無程式碼方法的 OpenAI 功能。 您可以透過此頁面,快速逐一查看並實驗各種功能。

聊天遊樂場頁面的螢幕擷取畫面。

助理設定

您可以使用 [助理設定] 下拉式清單選取一些預先載入的 [系統訊息] 範例,以開始使用。

[系統訊息] 能為模型提供其行為的相關指示,以及其在產生回應時應該參考的任何內容。 您可以描述助理的特質、告訴其應該和不應該回答的內容,以及告訴其設定回應的格式。

[新增少樣本範例] 可讓您提供模型用於情境中學習 (部分機器翻譯) 的對話範例。

使用聊天遊樂場時,您可以隨時選取 [檢視程式碼],以查看根據您目前的聊天工作階段和設定選取項目所預先填入的 Python、curl 和 json 程式碼範例。 然後,您可以取得此程式碼並撰寫應用程式,以完成您目前正在使用遊樂場執行的相同工作。

聊天工作階段

選取 [傳送] 按鈕會將輸入的文字傳送至完成 API,並將結果傳回文字輸入框。

選取 [清除聊天] 按鈕,以刪除目前的交談歷程記錄。

設定

名稱 說明
部署 與特定模型相關聯的部署名稱。
溫度 控制隨機性。 降低溫度表示模型會產生更多重複的確定性回應。 提升溫度會產生更多非預期或令人意外的回應。 您可試著調整溫度或 Top P,但不可同時調整兩者。
最大長度 (語彙基元) 設定每個模型回應的權杖數目限制。 API 支援在提示 (包括系統訊息、範例、訊息歷程記錄,以及使用者查詢) 和模型的回應之間共用最多 4096 個語彙基元。 每個語彙基元大約是一般英文文字的四個字元。
最高機率 類似於溫度,此設定能控制隨機性,但會使用不同的方法。 降低 Top P 會將模型的語彙基元選取範圍縮小至可能性較高的內容。 增加 Top P 會讓模型從所有可能性的語彙基元中進行挑選。 您可試著調整溫度或 Top P,但不可同時調整兩者。
多回合交談 選取要包括在每個新 API 要求中的舊訊息數目。 這有助於為模型提供新使用者查詢的內容。 若將此數目設定為 10,便會產生五個使用者查詢和五個系統回應。
停止序列 停止序列會使模型在所需的時間點結束其回應。 模型回應會在指定的序列之前結束,因此不會包含停止序列文字。 針對 GPT-35-Turbo,使用 <|im_end|> 可確保模型回應不會產生後續的使用者查詢。 您可以包括多達四個停止序列。

顯示面板

根據預設,有三個面板:助理設定、聊天工作階段和設定。 [顯示面板] 可讓您新增、移除和重新排列面板。 如果您關閉面板後需要將其還原,請使用 [顯示面板] 來還原遺失的面板。

開始聊天工作階段

  1. 從 [助理設定] 下拉式清單中,選取 [Xbox 客戶支援專員]

  2. 系統會提示您,詢問是否要更新系統訊息,請選取 [繼續]

  3. 在聊天工作階段窗格中,輸入下列問題:「我想要購買新的 Xbox」,然後選取 [傳送]

  4. 您會收到類似下面的回應:

    此螢幕擷取畫面顯示遊樂場中的第一個問題與答案。

  5. 輸入類似下面的後續問題:「哪個型號支援 4K?」

    此螢幕擷取畫面顯示遊樂場中的後續問題與答案。

  6. 在您擁有基本交談之後,請選取 [助理設定] 底下的 [檢視程式碼],您便能看見目前整個交談幕後之程式碼的重新執行:

#Note: The openai-python library support for Azure OpenAI is in preview.
import os
import openai
openai.api_type = "azure"
openai.api_base = "https://docs-test-001.openai.azure.com/"
openai.api_version = "2024-02-01"
openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.ChatCompletion.create(
  engine="gpt-35-turbo", # replace this value with the deployment name you chose when you deployed the associated model.
  messages = [{"role":"system","content":"You are an Xbox customer support agent whose primary goal is to help users with issues they are experiencing with their Xbox devices. You are friendly and concise. You only provide factual answers to queries, and do not provide answers that are not related to Xbox."},{"role":"user","content":"How much is a PS5?"},{"role":"assistant","content":"I apologize, but I do not have information about the prices of other gaming devices such as the PS5. My primary focus is to assist with issues regarding Xbox devices. Is there a specific issue you are having with your Xbox device that I may be able to help with?"},{"role":"user","content":"I am interested in buying an Xbox?"},{"role":"assistant","content":"Great! There are several Xbox models available in the market, including the Xbox Series X, Xbox Series S, and Xbox One. The Xbox Series X is the latest and most powerful console, while the Xbox Series S is a more affordable option that still offers great performance. The Xbox One is the previous generation console, but it still has a large library of games available to play.\n\nBefore purchasing an Xbox, you may want to consider factors such as your budget, the types of games you want to play, and whether you want to play games in 4K resolution. Once you have decided on a console, you can purchase it from a retailer or directly from the Xbox website. Let me know if you have any other questions or concerns!"},{"role":"user","content":"Which models are 4K?"},{"role":"assistant","content":"Both the Xbox Series X and Xbox One X support 4K resolution gaming. The Xbox Series S, on the other hand, supports up to 1440p resolution gaming, but it can upscale games to 4K. It's worth noting that in order to take advantage of 4K gaming, you'll need a 4K TV or monitor that supports HDR (High Dynamic Range) and HDMI 2.0 or higher."}],
  temperature=0,
  max_tokens=350,
  top_p=0.95,
  frequency_penalty=0,
  presence_penalty=0,
  stop=None)

了解提示結構

如果您從 [檢視程式碼] 檢查範例,您會發現一些不屬於一般 GPT 完成呼叫的唯一語彙基元。 GPT-35-Turbo 已定型為使用特殊語彙基元來區分提示的不同部分。 會在 <|im_start|><|im_end|> 語彙基元之間將內容提供給模型。 提示的開頭為系統訊息,其可透過包括模型的內容或指示用來準備模型。 之後,提示會包含使用者與助理之間的一系列訊息。

助理對提示的回應會接著在 <|im_start|>assistant 語彙基元下方傳回,並以 <|im_end|> 表示助理已完成其回應來作為結尾。 您也可以使用 [顯示原始語法] 切換按鈕,在聊天工作階段面板中顯示這些語彙基元。

GPT-35-Turbo 與 GPT-4 操作指南提供新提示結構的深入介紹,以及如何有效地使用 gpt-35-turbo 模型。

部署模型

當您對 Azure OpenAI Studio 中的體驗感到滿意之後,您可以選取 [部署至] 按鈕,直接從 Studio 部署 Web 應用程式。

顯示 Azure OpenAI Studio 中模型部署按鈕的螢幕擷取畫面。

這可讓您選擇將模型部署至獨立的 Web 應用程式,或部署為 Copilot Studio (預覽) 中的一個副手 (若您在模型上使用自己的資料)。

例如,如果您選擇部署 Web 應用程式:

第一次部署 Web 應用程式時,您應該選取 [建立新的 Web 應用程式]。 選擇應用程式的名稱,其會成為應用程式 URL 的一部分。 例如: https://<appname>.azurewebsites.net

選取已發佈應用程式的訂用帳戶、資源群組、位置和定價方案。 若要更新現有的應用程式,請選取 [發佈到現有的 Web 應用程式],然後從下拉式功能表中選擇先前應用程式的名稱。

如果您選擇部署 Web 應用程式,請參閱使用方式的重要考量

清除資源

測試聊天遊樂場之後,如果您想要清除並移除 Azure OpenAI 資源,可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。

下一步

原始程式碼 | 套件 (NuGet) | 範例| 擷取擴增生成 (RAG) 企業聊天範本 |

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • 在所需的 Azure 訂用帳戶中授與 Azure OpenAI 服務的存取權。 目前只有應用程式會授予此服務的存取權。 您可以填妥 https://aka.ms/oai/access (英文) 的表單,以申請 Azure OpenAI 服務的存取權。
  • .NET 7 SDK
  • 已部署 gpt-35-turbogpt-4 模型的 Azure OpenAI 服務資源。 如需模型部署的詳細資訊,請參閱資源部署指南

設定

建立新的 .NET Core 應用程式

在主控台視窗中 (例如 cmd、PowerShell 或 Bash),使用 dotnet new 命令建立名為 azure-openai-quickstart 的新主控台應用程式。 此命令會建立簡單的 "Hello World" 專案,內含單一 C# 來源檔案:Program.cs

dotnet new console -n azure-openai-quickstart

將目錄變更為新建立的應用程式資料夾。 您可以使用下列命令來建置應用程式:

dotnet build

建置輸出應該不會有警告或錯誤。

...
Build succeeded.
 0 Warning(s)
 0 Error(s)
...

使用下列項目安裝 OpenAI .NET 用戶端程式庫:

dotnet add package Azure.AI.OpenAI --prerelease

擷取金鑰和端點

若要成功對 Azure OpenAI 進行呼叫,您需要端點金鑰

變數名稱
ENDPOINT 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 或者,您可以在 [Azure OpenAI Studio]>[遊樂場]>[程式碼檢視] 中找到該值。 範例端點為:https://docs-test-001.openai.azure.com/
API-KEY 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 KEY1KEY2

移至您在 Azure 入口網站中的資源。 您可以在 [資源管理] 區段中找到 [金鑰和端點] 區段。 複製您的端點和存取金鑰,因為您需要這兩者才能驗證 API 呼叫。 您可以使用 KEY1KEY2。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。

Azure 入口網站中某個 Azure OpenAI 資源,以紅色圓圈強調端點和存取金鑰位置的概觀使用者介面螢幕擷取畫面。

環境變數

為您的金鑰和端點建立及指派永續性環境變數。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

建立應用程式範例

從專案目錄中開啟 program.cs 檔案,並取代為下列程式碼:

沒有回應串流

using Azure;
using Azure.AI.OpenAI;
using static System.Environment;

string endpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
string key = GetEnvironmentVariable("AZURE_OPENAI_API_KEY");

OpenAIClient client = new(new Uri(endpoint), new AzureKeyCredential(key));

var chatCompletionsOptions = new ChatCompletionsOptions()
{
    DeploymentName = "gpt-35-turbo", //This must match the custom deployment name you chose for your model
    Messages =
    {
        new ChatRequestSystemMessage("You are a helpful assistant."),
        new ChatRequestUserMessage("Does Azure OpenAI support customer managed keys?"),
        new ChatRequestAssistantMessage("Yes, customer managed keys are supported by Azure OpenAI."),
        new ChatRequestUserMessage("Do other Azure AI services support this too?"),
    },
    MaxTokens = 100
};

Response<ChatCompletions> response = client.GetChatCompletions(chatCompletionsOptions);

Console.WriteLine(response.Value.Choices[0].Message.Content);

Console.WriteLine();

重要

在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需有關認證安全性的詳細資訊,請參閱 Azure AI 服務安全性一文。

dotnet run program.cs

輸出

Yes, many of the Azure AI services support customer managed keys. Some examples include Text Analytics, Speech Services, and Translator. However, it's important to note that not all services support customer managed keys, so it's best to check the documentation for each individual service to see if it is supported.

這會等到模型產生整個回應,才會列印結果。 或者,如果您想要以非同步方式串流回應並列印結果,您可以將 program.cs 的內容取代為下一個範例中的程式碼。

使用串流進行非同步處理

using Azure;
using Azure.AI.OpenAI;
using static System.Environment;

string endpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
string key = GetEnvironmentVariable("AZURE_OPENAI_API_KEY");

OpenAIClient client = new(new Uri(endpoint), new AzureKeyCredential(key));

var chatCompletionsOptions = new ChatCompletionsOptions()
{
    DeploymentName= "gpt-35-turbo", //This must match the custom deployment name you chose for your model
    Messages =
    {
        new ChatRequestSystemMessage("You are a helpful assistant."),
        new ChatRequestUserMessage("Does Azure OpenAI support customer managed keys?"),
        new ChatRequestAssistantMessage("Yes, customer managed keys are supported by Azure OpenAI."),
        new ChatRequestUserMessage("Do other Azure AI services support this too?"),
    },
    MaxTokens = 100
};

await foreach (StreamingChatCompletionsUpdate chatUpdate in client.GetChatCompletionsStreaming(chatCompletionsOptions))
{
    if (chatUpdate.Role.HasValue)
    {
        Console.Write($"{chatUpdate.Role.Value.ToString().ToUpperInvariant()}: ");
    }
    if (!string.IsNullOrEmpty(chatUpdate.ContentUpdate))
    {
        Console.Write(chatUpdate.ContentUpdate);
    }
}

清除資源

如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。

下一步

原始程式碼 | 套件 (Go)| 範例

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • 在所需的 Azure 訂用帳戶中授與 Azure OpenAI 服務的存取權。 目前只有應用程式會授予此服務的存取權。 您可以填妥 https://aka.ms/oai/access (英文) 的表單,以申請 Azure OpenAI 服務的存取權。
  • 已在本機安裝 Go 1.21.0 或更高版本。
  • 已部署 gpt-35-turbo 模型的 Azure OpenAI 服務資源。 如需模型部署的詳細資訊,請參閱資源部署指南

設定

擷取金鑰和端點

若要成功對 Azure OpenAI 進行呼叫,您需要端點金鑰

變數名稱
ENDPOINT 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 或者,您可以在 [Azure OpenAI Studio]>[遊樂場]>[程式碼檢視] 中找到該值。 範例端點為:https://docs-test-001.openai.azure.com/
API-KEY 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 KEY1KEY2

移至您在 Azure 入口網站中的資源。 您可以在 [資源管理] 區段中找到 [金鑰和端點] 區段。 複製您的端點和存取金鑰,因為您需要這兩者才能驗證 API 呼叫。 您可以使用 KEY1KEY2。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。

Azure 入口網站中某個 Azure OpenAI 資源,以紅色圓圈強調端點和存取金鑰位置的概觀使用者介面螢幕擷取畫面。

環境變數

為您的金鑰和端點建立及指派永續性環境變數。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

建立應用程式範例

建立名為 chat_completions.go 的新檔案。 將下列程式碼複製到 chat_completions.go 檔案。

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
)

func main() {
	azureOpenAIKey := os.Getenv("AZURE_OPENAI_API_KEY")
	modelDeploymentID := os.Getenv("YOUR_MODEL_DEPLOYMENT_NAME")
    maxTokens:= int32(400)


	// Ex: "https://<your-azure-openai-host>.openai.azure.com"
	azureOpenAIEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT")

	if azureOpenAIKey == "" || modelDeploymentID == "" || azureOpenAIEndpoint == "" {
		fmt.Fprintf(os.Stderr, "Skipping example, environment variables missing\n")
		return
	}

	keyCredential := azcore.NewKeyCredential(azureOpenAIKey)

	// In Azure OpenAI you must deploy a model before you can use it in your client. For more information
	// see here: https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource
	client, err := azopenai.NewClientWithKeyCredential(azureOpenAIEndpoint, keyCredential, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	// This is a conversation in progress.
	// NOTE: all messages, regardless of role, count against token usage for this API.
	messages := []azopenai.ChatRequestMessageClassification{
		// You set the tone and rules of the conversation with a prompt as the system role.
		&azopenai.ChatRequestSystemMessage{Content: to.Ptr("You are a helpful assistant.")},

		// The user asks a question
		&azopenai.ChatRequestUserMessage{Content: azopenai.NewChatRequestUserMessageContent("Does Azure OpenAI support customer managed keys?")},

		// The reply would come back from the model. You'd add it to the conversation so we can maintain context.
		&azopenai.ChatRequestAssistantMessage{Content: to.Ptr("Yes, customer managed keys are supported by Azure OpenAI")},

		// The user answers the question based on the latest reply.
		&azopenai.ChatRequestUserMessage{Content: azopenai.NewChatRequestUserMessageContent("What other Azure Services support customer managed keys?")},

		// from here you'd keep iterating, sending responses back from ChatGPT
	}

	gotReply := false

	resp, err := client.GetChatCompletions(context.TODO(), azopenai.ChatCompletionsOptions{
		// This is a conversation in progress.
		// NOTE: all messages count against token usage for this API.
		Messages:       messages,
		DeploymentName: &modelDeploymentID,
		MaxTokens: &maxTokens,
	}, nil)

	if err != nil {
		// TODO: Update the following line with your application specific error handling logic
		log.Printf("ERROR: %s", err)
		return
	}

	for _, choice := range resp.Choices {
		gotReply = true

		if choice.ContentFilterResults != nil {
			fmt.Fprintf(os.Stderr, "Content filter results\n")

			if choice.ContentFilterResults.Error != nil {
				fmt.Fprintf(os.Stderr, "  Error:%v\n", choice.ContentFilterResults.Error)
			}

			fmt.Fprintf(os.Stderr, "  Hate: sev: %v, filtered: %v\n", *choice.ContentFilterResults.Hate.Severity, *choice.ContentFilterResults.Hate.Filtered)
			fmt.Fprintf(os.Stderr, "  SelfHarm: sev: %v, filtered: %v\n", *choice.ContentFilterResults.SelfHarm.Severity, *choice.ContentFilterResults.SelfHarm.Filtered)
			fmt.Fprintf(os.Stderr, "  Sexual: sev: %v, filtered: %v\n", *choice.ContentFilterResults.Sexual.Severity, *choice.ContentFilterResults.Sexual.Filtered)
			fmt.Fprintf(os.Stderr, "  Violence: sev: %v, filtered: %v\n", *choice.ContentFilterResults.Violence.Severity, *choice.ContentFilterResults.Violence.Filtered)
		}

		if choice.Message != nil && choice.Message.Content != nil {
			fmt.Fprintf(os.Stderr, "Content[%d]: %s\n", *choice.Index, *choice.Message.Content)
		}

		if choice.FinishReason != nil {
			// this choice's conversation is complete.
			fmt.Fprintf(os.Stderr, "Finish reason[%d]: %s\n", *choice.Index, *choice.FinishReason)
		}
	}

	if gotReply {
		fmt.Fprintf(os.Stderr, "Received chat completions reply\n")
	}

}

重要

在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需有關認證安全性的詳細資訊,請參閱 Azure AI 服務安全性一文。

現在開啟命令提示字元,然後執行:

go mod init chat_completions.go

接下來執行:

go mod tidy
go run chat_completions.go

輸出

Content filter results
  Hate: sev: safe, filtered: false
  SelfHarm: sev: safe, filtered: false
  Sexual: sev: safe, filtered: false
  Violence: sev: safe, filtered: false
Content[0]: As of my last update in early 2023, in Azure, several AI services support the use of customer-managed keys (CMKs) through Azure Key Vault. This allows customers to have control over the encryption keys used to secure their data at rest. The services that support this feature typically fall under Azure's range of cognitive services and might include:

1. Azure Cognitive Search: It supports using customer-managed keys to encrypt the index data.
2. Azure Form Recognizer: For data at rest, you can use customer-managed keys for added security.
3. Azure Text Analytics: CMKs can be used for encrypting your data at rest.
4. Azure Blob Storage: While not exclusively an AI service, it's often used in conjunction with AI services to store data, and it supports customer-managed keys for encrypting blob data.

Note that the support for CMKs can vary by service and sometimes even by the specific feature within the service. Additionally, the landscape of cloud services is fast evolving, and new features, including security capabilities, are frequently added. Therefore, it's recommended to check the latest Azure documentation or contact Azure support for the most current information about CMK support for any specific Azure AI service.
Finish reason[0]: stop
Received chat completions reply

清除資源

如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。

下一步

如需更多範例,請參閱 Azure OpenAI 範例 GitHub 存放庫

原始程式碼 | 成品 (Maven) | 範例 | 擷取擴增生成 (RAG) 企業聊天範本 | IntelliJ IDEA

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • 在所需的 Azure 訂用帳戶中授與 Azure OpenAI 服務的存取權。 目前只有應用程式會授予此服務的存取權。 您可以填妥 https://aka.ms/oai/access (英文) 的表單,以申請 Azure OpenAI 服務的存取權。
  • Gradle 建置工具,或其他相依性管理員。
  • 已部署 gpt-35-turbogpt-4 模型的 Azure OpenAI 服務資源。 如需模型部署的詳細資訊,請參閱資源部署指南

設定

擷取金鑰和端點

若要成功對 Azure OpenAI 進行呼叫,您需要端點金鑰

變數名稱
ENDPOINT 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 或者,您可以在 [Azure OpenAI Studio]>[遊樂場]>[程式碼檢視] 中找到該值。 範例端點為:https://docs-test-001.openai.azure.com/
API-KEY 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 KEY1KEY2

移至您在 Azure 入口網站中的資源。 您可以在 [資源管理] 區段中找到 [金鑰和端點] 區段。 複製您的端點和存取金鑰,因為您需要這兩者才能驗證 API 呼叫。 您可以使用 KEY1KEY2。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。

Azure 入口網站中某個 Azure OpenAI 資源,以紅色圓圈強調端點和存取金鑰位置的概觀使用者介面螢幕擷取畫面。

環境變數

為您的金鑰和端點建立及指派永續性環境變數。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

建立新的 Java 應用程式

建立新的 Gradle 專案。

在主控台視窗 (例如 cmd、PowerShell 或 Bash) 中,為您的應用程式建立新的目錄,並瀏覽至該目錄。

mkdir myapp && cd myapp

從您的工作目錄執行 gradle init 命令。 此命令會建立 Gradle 的基本組建檔案,包括 build.gradle.kts,此檔案將在執行階段用來建立及設定您的應用程式。

gradle init --type basic

出現選擇 DSL 的提示時,請選取 [Kotlin]

安裝 Java SDK

本快速入門會使用 Gradle 相依性管理員。 您可以在 Maven 中央存放庫中找到用戶端程式庫和其他相依性管理員的資訊。

找出 build.gradle.kts,並使用您慣用的 IDE 或文字編輯器加以開啟。 然後,在其中複製下列組建組態。 此設定會將專案定義為一個 JAVA 應用程式,其進入點為 OpenAIQuickstart。 它會匯入 Azure AI 視覺程式庫。

plugins {
    java
    application
}
application { 
    mainClass.set("OpenAIQuickstart")
}
repositories {
    mavenCentral()
}
dependencies {
    implementation(group = "com.azure", name = "azure-ai-openai", version = "1.0.0-beta.10")
    implementation("org.slf4j:slf4j-simple:1.7.9")
}

建立應用程式範例

  1. 建立 Java 檔案。

    在您的工作目錄中執行下列命令,以建立專案來源資料夾:

    mkdir -p src/main/java
    

    瀏覽至新的資料夾,並建立名為 OpenAIQuickstart.java 的檔案。

  2. 在慣用的編輯器或 IDE 中開啟 OpenAIQuickstart.java,並貼上下列程式碼。

    package com.azure.ai.openai.usage;
    
    import com.azure.ai.openai.OpenAIClient;
    import com.azure.ai.openai.OpenAIClientBuilder;
    import com.azure.ai.openai.models.ChatChoice;
    import com.azure.ai.openai.models.ChatCompletions;
    import com.azure.ai.openai.models.ChatCompletionsOptions;
    import com.azure.ai.openai.models.ChatRequestAssistantMessage;
    import com.azure.ai.openai.models.ChatRequestMessage;
    import com.azure.ai.openai.models.ChatRequestSystemMessage;
    import com.azure.ai.openai.models.ChatRequestUserMessage;
    import com.azure.ai.openai.models.ChatResponseMessage;
    import com.azure.ai.openai.models.CompletionsUsage;
    import com.azure.core.credential.AzureKeyCredential;
    import com.azure.core.util.Configuration;
    
    import java.util.ArrayList;
    import java.util.List;
    
    
    public class OpenAIQuickstart {
    
        public static void main(String[] args) {
            String azureOpenaiKey = Configuration.getGlobalConfiguration().get("AZURE_OPENAI_API_KEY");
            String endpoint = Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT");
            String deploymentOrModelId = "{azure-open-ai-deployment-model-id}";
    
            OpenAIClient client = new OpenAIClientBuilder()
                .endpoint(endpoint)
                .credential(new AzureKeyCredential(azureOpenaiKey))
                .buildClient();
    
            List<ChatRequestMessage> chatMessages = new ArrayList<>();
            chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant."));
            chatMessages.add(new ChatRequestUserMessage("Does Azure OpenAI support customer managed keys?"));
            chatMessages.add(new ChatRequestAssistantMessage("Yes, customer managed keys are supported by Azure OpenAI?"));
            chatMessages.add(new ChatRequestUserMessage("Do other Azure AI services support this too?"));    
    
            ChatCompletions chatCompletions = client.getChatCompletions(deploymentOrModelId, new ChatCompletionsOptions(chatMessages));
    
            System.out.printf("Model ID=%s is created at %s.%n", chatCompletions.getId(), chatCompletions.getCreatedAt());
            for (ChatChoice choice : chatCompletions.getChoices()) {
                ChatResponseMessage message = choice.getMessage();
                System.out.printf("Index: %d, Chat Role: %s.%n", choice.getIndex(), message.getRole());
                System.out.println("Message:");
                System.out.println(message.getContent());
            }
    
            System.out.println();
            CompletionsUsage usage = chatCompletions.getUsage();
            System.out.printf("Usage: number of prompt token is %d, "
                    + "number of completion token is %d, and number of total tokens in request and response is %d.%n",
                usage.getPromptTokens(), usage.getCompletionTokens(), usage.getTotalTokens());
        }
    }
    

    重要

    在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需有關認證安全性的詳細資訊,請參閱 Azure AI 服務安全性一文。

  3. 瀏覽回專案根資料夾,並使用下列項目建置應用程式:

    gradle build
    

    然後,使用 gradle run 命令加以執行:

    gradle run
    

輸出

Model ID=chatcmpl-7JYnyE4zpd5gaIfTRH7hNpeVsvAw4 is created at 1684896378.
Index: 0, Chat Role: assistant.
Message:
Yes, most of the Azure AI services support customer managed keys. However, there may be some exceptions, so it is best to check the documentation of each specific service to confirm.

Usage: number of prompt token is 59, number of completion token is 36, and number of total tokens in request and response is 95.

清除資源

如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。

下一步

原始程式碼 | 成品 (Maven) | 範例

必要條件

設定

擷取金鑰和端點

若要成功對 Azure OpenAI 進行呼叫,您需要端點金鑰

變數名稱
ENDPOINT 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 或者,您可以在 [Azure OpenAI Studio]>[遊樂場]>[程式碼檢視] 中找到該值。 範例端點為:https://docs-test-001.openai.azure.com/
API-KEY 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 KEY1KEY2

移至您在 Azure 入口網站中的資源。 您可以在 [資源管理] 區段中找到 [金鑰和端點] 區段。 複製您的端點和存取金鑰,因為您需要這兩者才能驗證 API 呼叫。 您可以使用 KEY1KEY2。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。

Azure 入口網站中某個 Azure OpenAI 資源,以紅色圓圈強調端點和存取金鑰位置的概觀使用者介面螢幕擷取畫面。

環境變數

為您的金鑰和端點建立及指派永續性環境變數。

注意

Spring AI 會將模型名稱預設為 gpt-35-turbo。 只有在您使用了不同名稱部署模型時,才需要提供 SPRING_AI_AZURE_OPENAI_MODEL 值。

export SPRING_AI_AZURE_OPENAI_API_KEY="REPLACE_WITH_YOUR_KEY_VALUE_HERE"
export SPRING_AI_AZURE_OPENAI_ENDPOINT="REPLACE_WITH_YOUR_ENDPOINT_HERE"
export SPRING_AI_AZURE_OPENAI_MODEL="REPLACE_WITH_YOUR_MODEL_NAME_HERE"

建立新的 Spring 應用程式

建立新的 Spring 專案。

在 Bash 視窗中,為您的應用程式建立新目錄,並瀏覽至其中。

mkdir ai-chat-demo && cd ai-chat-demo

從您的工作目錄執行 spring init 命令。 此命令會為您的 Spring 專案建立標準目錄結構 (包括主要 JAVA 類別來源檔案),以及用於管理 Maven 型專案的 pom.xml 檔案。

spring init -a ai-chat-demo -n AIChat --force --build maven -x

產生的檔案與資料夾類似下列結構:

ai-chat-demo/
|-- pom.xml
|-- mvn
|-- mvn.cmd
|-- HELP.md
|-- src/
    |-- main/
    |   |-- resources/
    |   |   |-- application.properties
    |   |-- java/
    |       |-- com/
    |           |-- example/
    |               |-- aichatdemo/
    |                   |-- AiChatApplication.java
    |-- test/
        |-- java/
            |-- com/
                |-- example/
                    |-- aichatdemo/
                        |-- AiChatApplicationTests.java

編輯 Spring 應用程式

  1. 編輯 pom.xml 檔案。

    使用慣用的編輯器或 IDE,從專案目錄的根目錄開啟 pom.xml 檔案,並以下列內容覆寫檔案:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>3.2.0</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.example</groupId>
        <artifactId>ai-chat-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>AIChat</name>
        <description>Demo project for Spring Boot</description>
        <properties>
            <java.version>17</java.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.experimental.ai</groupId>
                <artifactId>spring-ai-azure-openai-spring-boot-starter</artifactId>
                <version>0.7.0-SNAPSHOT</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
        <repositories>
            <repository>
                <id>spring-snapshots</id>
                <name>Spring Snapshots</name>
                <url>https://repo.spring.io/snapshot</url>
                <releases>
                    <enabled>false</enabled>
                </releases>
            </repository>
        </repositories>
    </project>
    
  2. 使用慣用的編輯器或 IDE,從 src/main/java/com/example/aichatdemo 資料夾開啟 AiChatApplication.java,並貼上下列程式碼:

    package com.example.aichatdemo;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.springframework.ai.client.AiClient;
    import org.springframework.ai.prompt.Prompt;
    import org.springframework.ai.prompt.messages.ChatMessage;
    import org.springframework.ai.prompt.messages.Message;
    import org.springframework.ai.prompt.messages.MessageType;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class AiChatApplication implements CommandLineRunner
    {
        private static final String ROLE_INFO_KEY = "role";
    
        @Autowired
        private AiClient aiClient;
    
        public static void main(String[] args) {
            SpringApplication.run(AiChatApplication.class, args);
        }
    
        @Override
        public void run(String... args) throws Exception
        {
            System.out.println(String.format("Sending chat prompts to AI service. One moment please...\r\n"));
    
            final List<Message> msgs = new ArrayList<>();
    
            msgs.add(new ChatMessage(MessageType.SYSTEM, "You are a helpful assistant"));
            msgs.add(new ChatMessage(MessageType.USER, "Does Azure OpenAI support customer managed keys?"));
            msgs.add(new ChatMessage(MessageType.ASSISTANT, "Yes, customer managed keys are supported by Azure OpenAI?"));
            msgs.add(new ChatMessage(MessageType.USER, "Do other Azure AI services support this too?"));
    
            final var resps = aiClient.generate(new Prompt(msgs));
    
            System.out.println(String.format("Prompt created %d generated response(s).", resps.getGenerations().size()));
    
            resps.getGenerations().stream()
              .forEach(gen -> {
                  final var role = gen.getInfo().getOrDefault(ROLE_INFO_KEY, MessageType.ASSISTANT.getValue());
    
                  System.out.println(String.format("Generated respose from \"%s\": %s", role, gen.getText()));
              });
        }
    
    }
    

    重要

    在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需有關認證安全性的詳細資訊,請參閱 Azure AI 服務安全性一文。

  3. 瀏覽回專案根資料夾,並使用下列命令執行應用程式:

    ./mvnw spring-boot:run
    

輸出

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.1.5)

2023-11-07T13:31:10.884-06:00  INFO 6248 --- [           main] c.example.aichatdemo.AiChatApplication   : No active profile set, falling back to 1 default profile: "default"
2023-11-07T13:31:11.595-06:00  INFO 6248 --- [           main] c.example.aichatdemo.AiChatApplication   : Started AiChatApplication in 0.994 seconds (process running for 1.28)
Sending chat prompts to AI service. One moment please...

Prompt created 1 generated response(s).
Generated respose from "assistant": Yes, other Azure AI services also support customer managed keys. Azure AI Services, Azure Machine Learning, and other AI services in Azure provide options for customers to manage and control their encryption keys. This allows customers to have greater control over their data and security.

清除資源

如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。

下一步

如需更多範例,請參閱 Azure OpenAI 範例 GitHub 存放庫

原始程式碼 | 套件 (npm)

注意

本文已更新為使用最新的 OpenAI npm 套件,此套件現在完全支援 Azure OpenAI。 如果您要尋找舊版 Azure OpenAI JavaScript SDK 的程式碼範例,目前仍可在此存放庫中取得

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • 在所需的 Azure 訂用帳戶中授與 Azure OpenAI 服務的存取權。 目前只有應用程式會授予此服務的存取權。 您可以填妥 https://aka.ms/oai/access (英文) 的表單,以申請 Azure OpenAI 服務的存取權。
  • LTS 版本的 Node.js
  • 已部署 gpt-35-turbogpt-4 系列模型的 Azure OpenAI 服務資源。 如需模型部署的詳細資訊,請參閱資源部署指南

設定

擷取金鑰和端點

若要成功對 Azure OpenAI 進行呼叫,您需要端點金鑰

變數名稱
ENDPOINT 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 或者,您可以在 [Azure OpenAI Studio]>[遊樂場]>[程式碼檢視] 中找到該值。 範例端點為:https://docs-test-001.openai.azure.com/
API-KEY 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 KEY1KEY2

移至您在 Azure 入口網站中的資源。 您可以在 [資源管理] 區段中找到 [金鑰和端點] 區段。 複製您的端點和存取金鑰,因為您需要這兩者才能驗證 API 呼叫。 您可以使用 KEY1KEY2。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。

Azure 入口網站中某個 Azure OpenAI 資源,以紅色圓圈強調端點和存取金鑰位置的概觀使用者介面螢幕擷取畫面。

環境變數

為您的金鑰和端點建立及指派永續性環境變數。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

建立節點應用程式

在主控台視窗 (例如 cmd、PowerShell 或 Bash) 中,為您的應用程式建立新的目錄,並瀏覽至該目錄。

安裝用戶端程式庫

從新目錄的內容中安裝具有 npm 的 JavaScript 必要套件:

npm install openai dotenv @azure/identity

應用程式的 package.json 檔案將會隨著相依項目更新。

建立應用程式範例

開啟命令提示字元並移至您要新增專案的位置,然後建立名為 ChatCompletion.js 的新檔案。 將以下程式碼複製到 ChatCompletion.js 檔案。

const { AzureOpenAI } = require("openai");

// Load the .env file if it exists
const dotenv = require("dotenv");
dotenv.config();

// You will need to set these environment variables or edit the following values
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
const apiKey = process.env["AZURE_OPENAI_API_KEY"] || "<api key>";
const apiVersion = "2024-05-01-preview";
const deployment = "gpt-4o"; //This must match your deployment name.
require("dotenv/config");

async function main() {

  const client = new AzureOpenAI({ endpoint, apiKey, apiVersion, deployment });
  const result = await client.chat.completions.create({
    messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Does Azure OpenAI support customer managed keys?" },
    { role: "assistant", content: "Yes, customer managed keys are supported by Azure OpenAI?" },
    { role: "user", content: "Do other Azure AI services support this too?" },
    ],
    model: "",
  });

  for (const choice of result.choices) {
    console.log(choice.message);
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

module.exports = { main };

使用下列命令來執行指令碼:

node.exe ChatCompletion.js

輸出

== Chat Completions Sample ==
{
  content: 'Yes, several other Azure AI services also support customer managed keys for enhanced security and control over encryption keys.',
  role: 'assistant'
}

Microsoft Entra ID

重要

在上一個範例中,我們示範了金鑰型驗證。 一旦成功測試了金鑰型驗證,就會建議您使用更安全的 Microsoft Entra ID 進行驗證,這會在下一個程式碼範例中示範。 開始使用 [Microsoft Entra ID] 將需要一些額外的必要條件

const { AzureOpenAI } = require("openai");
const { DefaultAzureCredential, getBearerTokenProvider } = require("@azure/identity");

// Set AZURE_OPENAI_ENDPOINT to the endpoint of your
// OpenAI resource. You can find this in the Azure portal.
// Load the .env file if it exists
require("dotenv/config");

async function main() {
  console.log("== Chat Completions Sample ==");

  const scope = "https://cognitiveservices.azure.com/.default";
  const azureADTokenProvider = getBearerTokenProvider(new DefaultAzureCredential(), scope);
  const deployment = "gpt-35-turbo";
  const apiVersion = "2024-04-01-preview";
  const client = new AzureOpenAI({ azureADTokenProvider, deployment, apiVersion });
  const result = await client.chat.completions.create({
    messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Does Azure OpenAI support customer managed keys?" },
    { role: "assistant", content: "Yes, customer managed keys are supported by Azure OpenAI?" },
    { role: "user", content: "Do other Azure AI services support this too?" },
    ],
    model: "",
  });

  for (const choice of result.choices) {
    console.log(choice.message);
  }
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

module.exports = { main };

注意

如果您收到錯誤:發生錯誤:OpenAIError:apiKeyazureADTokenProvider 引數互斥;一次只能傳遞一個。您可能需要從系統中移除 API 金鑰預先存在的環境變數。 即使 Microsoft Entra ID 程式碼範例未明確參考該 API 金鑰環境變數,但如果執行此範例的系統有此情況,仍會產生此錯誤。

清除資源

如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。

下一步

程式庫原始程式碼 | 套件 (PyPi) | 擷取擴增生成 (RAG) 企業聊天範本 |

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • 在所需的 Azure 訂用帳戶中授與 Azure OpenAI 服務的存取權。 目前只有應用程式會授予此服務的存取權。 您可以填妥 https://aka.ms/oai/access (英文) 的表單,以申請 Azure OpenAI 服務的存取權。
  • Python 3.8 或更新版本
  • 下列 Python 程式庫:os。
  • 已部署 gpt-35-turbogpt-4 模型的 Azure OpenAI 服務資源。 如需模型部署的詳細資訊,請參閱資源部署指南

設定

使用下列項目安裝 OpenAI Python 用戶端程式庫:

pip install openai

注意

程式庫是由 OpenAI 進行維護。 參照版本歷程記錄來追蹤程式庫的最新更新。

擷取金鑰和端點

若要成功對 Azure OpenAI 進行呼叫,您需要端點金鑰

變數名稱
ENDPOINT 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 或者,您可以在 [Azure OpenAI Studio]>[遊樂場]>[程式碼檢視] 中找到該值。 範例端點為:https://docs-test-001.openai.azure.com/
API-KEY 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 KEY1KEY2

移至您在 Azure 入口網站中的資源。 您可以在 [資源管理] 區段中找到 [金鑰和端點] 區段。 複製您的端點和存取金鑰,因為您需要這兩者才能驗證 API 呼叫。 您可以使用 KEY1KEY2。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。

Azure 入口網站中某個 Azure OpenAI 資源,以紅色圓圈強調端點和存取金鑰位置的概觀使用者介面螢幕擷取畫面。

環境變數

為您的金鑰和端點建立及指派永續性環境變數。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

建立新的 Python 應用程式

  1. 建立命名為 quickstart.py 的新 Python 檔案。 然後,以您慣用的編輯器或 IDE 加以開啟。

  2. 將 quickstart.py 的內容取代為下列程式碼。

當您部署 GPT-3.5-Turbo 或 GPT-4 模型時,您需要將 model 變數設定為您選擇的部署名稱。 除非您選擇與基礎模型名稱相同的部署名稱,否則輸入模型名稱會導致錯誤。

import os
from openai import AzureOpenAI

client = AzureOpenAI(
  azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"), 
  api_key=os.getenv("AZURE_OPENAI_API_KEY"),  
  api_version="2024-02-01"
)

response = client.chat.completions.create(
    model="gpt-35-turbo", # model = "deployment_name".
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Does Azure OpenAI support customer managed keys?"},
        {"role": "assistant", "content": "Yes, customer managed keys are supported by Azure OpenAI."},
        {"role": "user", "content": "Do other Azure AI services support this too?"}
    ]
)

print(response.choices[0].message.content)

重要

在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需有關認證安全性的詳細資訊,請參閱 Azure AI 服務安全性一文。

  1. 使用快速入門檔案上的 python 命令執行應用程式:

    python quickstart.py
    

輸出

{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "Yes, most of the Azure AI services support customer managed keys. However, not all services support it. You can check the documentation of each service to confirm if customer managed keys are supported.",
        "role": "assistant"
      }
    }
  ],
  "created": 1679001781,
  "id": "chatcmpl-6upLpNYYOx2AhoOYxl9UgJvF4aPpR",
  "model": "gpt-3.5-turbo-0301",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 39,
    "prompt_tokens": 58,
    "total_tokens": 97
  }
}
Yes, most of the Azure AI services support customer managed keys. However, not all services support it. You can check the documentation of each service to confirm if customer managed keys are supported.

了解訊息結構

GPT-35-Turbo 和 GPT-4 模型已針對與格式化為交談的輸入搭配使用進行最佳化。 messages 變數會在系統、使用者和助理所描述的交談中傳遞具有不同角色的字典陣列。 系統訊息可透過包括模型應如何回應的內容或指示以用來準備模型。

GPT-35-Turbo 和 GPT-4 操作指南提供這些新模型通訊選項的深入說明。

清除資源

如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。

下一步

REST API 規格 | (英文)

必要條件

  • Azure 訂用帳戶 - 建立免費帳戶
  • 在所需的 Azure 訂用帳戶中授與 Azure OpenAI 服務的存取權。 目前只有應用程式會授予此服務的存取權。 您可以填妥 https://aka.ms/oai/access (英文) 的表單,以申請 Azure OpenAI 服務的存取權。
  • 已部署 gpt-35-turbogpt-4 模型的 Azure OpenAI 服務資源。 如需模型部署的詳細資訊,請參閱資源部署指南

設定

擷取金鑰和端點

若要成功對 Azure OpenAI 進行呼叫,您需要端點金鑰

變數名稱
ENDPOINT 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 或者,您可以在 [Azure OpenAI Studio]>[遊樂場]>[程式碼檢視] 中找到該值。 範例端點為:https://docs-test-001.openai.azure.com/
API-KEY 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 KEY1KEY2

移至您在 Azure 入口網站中的資源。 您可以在 [資源管理] 區段中找到 [金鑰和端點] 區段。 複製您的端點和存取金鑰,因為您需要這兩者才能驗證 API 呼叫。 您可以使用 KEY1KEY2。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。

Azure 入口網站中某個 Azure OpenAI 資源,以紅色圓圈強調端點和存取金鑰位置的概觀使用者介面螢幕擷取畫面。

環境變數

為您的金鑰和端點建立及指派永續性環境變數。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

REST API

在 bash 殼層中,執行下列命令。 您必須將 gpt-35-turbo 取代為您在部署 GPT-35-Turbo 或 GPT-4 模型時所選擇的部署名稱。 除非您選擇與底層模型名稱相同的部署名稱,否則輸入模型名稱將會產生錯誤。

curl $AZURE_OPENAI_ENDPOINT/openai/deployments/gpt-35-turbo/chat/completions?api-version=2024-02-01 \
  -H "Content-Type: application/json" \
  -H "api-key: $AZURE_OPENAI_API_KEY" \
  -d '{"messages":[{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Does Azure OpenAI support customer managed keys?"},{"role": "assistant", "content": "Yes, customer managed keys are supported by Azure OpenAI."},{"role": "user", "content": "Do other Azure AI services support this too?"}]}'

使用範例端點之命令的第一行格式會顯示如下:curl https://docs-test-001.openai.azure.com/openai/deployments/{YOUR-DEPLOYMENT_NAME_HERE}/chat/completions?api-version=2024-02-01 \ 如果您遇到錯誤重複檢查,請檢查您在端點與 /openai/deployments 之間的分隔沒有重複輸入 /

如果您想要在一般 Windows 命令提示字元中執行此命令,您必須改變文字以移除 \ 和分行符號。

重要

在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需有關認證安全性的詳細資訊,請參閱 Azure AI 服務安全性一文。

輸出

{"id":"chatcmpl-6v7mkQj980V1yBec6ETrKPRqFjNw9",
"object":"chat.completion","created":1679072642,
"model":"gpt-35-turbo",
"usage":{"prompt_tokens":58,
"completion_tokens":68,
"total_tokens":126},
"choices":[{"message":{"role":"assistant",
"content":"Yes, other Azure AI services also support customer managed keys. Azure AI services offer multiple options for customers to manage keys, such as using Azure Key Vault, customer-managed keys in Azure Key Vault or customer-managed keys through Azure Storage service. This helps customers ensure that their data is secure and access to their services is controlled."},"finish_reason":"stop","index":0}]}

輸出格式已加以調整以方便您閱讀,但實際的輸出是沒有分行符號的單一文字區塊。

了解訊息結構

GPT-35-Turbo 和 GPT-4 模型已針對與格式化為交談的輸入搭配使用進行最佳化。 messages 變數會在系統、使用者和助理所描述的交談中傳遞具有不同角色的字典陣列。 系統訊息可透過包括模型應如何回應的內容或指示以用來準備模型。

GPT-35-Turbo 和 GPT-4 操作指南提供這些新模型通訊選項的深入說明。

清除資源

如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。

下一步

必要條件

擷取金鑰和端點

若要成功對 Azure OpenAI 發出呼叫,您將需要 端點金鑰

變數名稱
ENDPOINT 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 或者,您可以在 [Azure OpenAI Studio]>[遊樂場]>[程式碼檢視] 中找到該值。 範例端點為:https://docs-test-001.openai.azure.com/
API-KEY 從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 KEY1KEY2

移至您在 Azure 入口網站中的資源。 您可以在 [資源管理] 區段中找到 [端點和金鑰]。 複製您的端點和存取金鑰,因為您需要這兩者才能驗證 API 呼叫。 您可以使用 KEY1KEY2。 隨時持有兩個金鑰可讓您安全地輪替和重新產生金鑰,而不會造成服務中斷。

此螢幕擷取畫面顯示 Azure 入口網站中某個 Azure OpenAI 資源的概觀使用者介面,其中以紅色圓圈顯示端點和存取金鑰位置。

為您的金鑰和端點建立及指派永續性環境變數。

環境變數

$Env:AZURE_OPENAI_API_KEY = 'YOUR_KEY_VALUE'
$Env:AZURE_OPENAI_ENDPOINT = 'YOUR_ENDPOINT'

建立新的 PowerShell 指令碼

  1. 建立稱為 quickstart.ps1 的新 PowerShell 檔案。 然後,以您慣用的編輯器或 IDE 加以開啟。

  2. 將 quickstart.ps1 的內容取代為下列程式碼。 您必須針對您在部署 GPT-35-Turbo 或 GPT-4 模型時所選擇的部署名稱設定 engine 變數。 除非您選擇與底層模型名稱相同的部署名稱,否則輸入模型名稱將會產生錯誤。

    # Azure OpenAI metadata variables
    $openai = @{
       api_key     = $Env:AZURE_OPENAI_API_KEY
       api_base    = $Env:AZURE_OPENAI_ENDPOINT # your endpoint should look like the following https://YOUR_RESOURCE_NAME.openai.azure.com/
       api_version = '2024-02-01' # this may change in the future
       name        = 'YOUR-DEPLOYMENT-NAME-HERE' #This will correspond to the custom name you chose for your deployment when you deployed a model.
    }
    
    # Completion text
    $messages = @()
    $messages += @{
      role = 'system'
      content = 'You are a helpful assistant.'
    }
    $messages += @{
      role = 'user'
      content = 'Does Azure OpenAI support customer managed keys?'
    }
    $messages += @{
      role = 'assistant'
      content = 'Yes, customer managed keys are supported by Azure OpenAI.'
    }
    $messages += @{
      role = 'user'
      content = 'Do other Azure AI services support this too?'
    }
    
    # Header for authentication
    $headers = [ordered]@{
       'api-key' = $openai.api_key
    }
    
    # Adjust these values to fine-tune completions
    $body = [ordered]@{
       messages = $messages
    } | ConvertTo-Json
    
    # Send a request to generate an answer
    $url = "$($openai.api_base)/openai/deployments/$($openai.name)/chat/completions?api-version=$($openai.api_version)"
    
    $response = Invoke-RestMethod -Uri $url -Headers $headers -Body $body -Method Post -ContentType 'application/json'
    return $response
    

    重要

    針對生產環境,請使用儲存和存取認證的安全方式,例如搭配 Azure Key Vault 的 PowerShell 祕密管理。 如需有關認證安全性的詳細資訊,請參閱 Azure AI 服務安全性一文。

  3. 使用 PowerShell 執行指令碼:

    ./quickstart.ps1
    

輸出

# the output of the script will be a .NET object containing the response
id      : chatcmpl-7sdJJRC6fDNGnfHMdfHXvPkYFbaVc
object  : chat.completion
created : 1693255177
model   : gpt-35-turbo
choices : {@{index=0; finish_reason=stop; message=}}
usage   : @{completion_tokens=67; prompt_tokens=55; total_tokens=122}

# convert the output to JSON
./quickstart.ps1 | ConvertTo-Json -Depth 3

# or to view the text returned, select the specific object property
$reponse = ./quickstart.ps1
$response.choices.message.content

了解訊息結構

GPT-35-Turbo 和 GPT-4 模型已針對與格式化為交談的輸入搭配使用進行最佳化。 messages 變數會在系統、使用者和助理所描述的交談中傳遞具有不同角色的字典陣列。 系統訊息可透過包括模型應如何回應的內容或指示以用來準備模型。

GPT-35-Turbo 和 GPT-4 操作指南提供這些新模型通訊選項的深入說明。

清除資源

如果您想要清除和移除 Azure OpenAI 資源,可以刪除資源。 刪除資源之前,您必須先刪除任何已部署的模型。

下一步