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

使用本文開始使用 Azure OpenAI。

必要條件

  • Azure 訂用帳戶 - 免費建立一個訂用帳戶。

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

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

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

提示

試用新的統一 Azure AI Studio (預覽版), 將來自多個 Azure AI 服務的功能整合在一起。

移至 Azure OpenAI Studio

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

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

Screenshot of the Azure OpenAI Studio landing page with Chat playground highlighted.

操場

透過 Azure OpenAI Studio Chat 遊樂場,開始使用無程式代碼方法探索 OpenAI 功能。 您可以從此頁面快速反覆運算並實驗功能。

Screenshot of the Chat playground page.

小幫手設定

您可以使用 [ 小幫手設定 ] 下拉式列表,選取一些預先載入 的系統訊息 範例來開始使用。

系統訊息 會提供模型指示,說明其運作方式,以及產生回應時應參考的任何內容。 您可以描述助理的個性、告知其應該和不應該回答的內容,以及如何格式化回應。

新增幾槍範例 可讓您提供模型用於 內容內學習的對話式範例。

使用聊天遊樂場時,您可以隨時選取 [檢視程序代碼 ] 來查看根據您目前的聊天會話和設定選取專案預先填入的 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. 您會收到類似以下的回應:

    Screenshot of a first question and answer in playground.

  5. 輸入後續問題,例如:「哪些模型支援 4K?

    Screenshot of follow-up question and answer in playground.

  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 = "2023-05-15"
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 應用程式。

A screenshot showing the model deployment button in Azure OpenAI Studio.

這可讓您選擇部署至獨立 Web 應用程式,或在 Copilot Studio 中部署 copilot Studio (預覽版),如果您是 在模型上使用自己的數據

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

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

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

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

清除資源

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

下一步

原始程式碼套件 (NuGet) | 範例| 擷取增強世代 (RAG) 企業聊天範本 | |

必要條件

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

設定

建立新的 .NET Core 應用程式

在主控台視窗中 (例如 cmd、PowerShell 或 Bash),使用 dotnet new 命令建立名為 azure-openai-quickstart 的新主控台應用程式。 此命令會建立具有單一 C# 原始程式檔的簡單 「Hello World」 專案: 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。 一律有兩個金鑰可讓您安全地輪替和重新產生密鑰,而不會造成服務中斷。

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境變數

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

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 金鑰保存庫。 如需有關認證安全性的詳細資訊,請參閱 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 OpenAI 進行呼叫,您需要 端點密鑰

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

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

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境變數

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

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/to"
)

func main() {
	azureOpenAIKey := os.Getenv("AZURE_OPENAI_API_KEY")
    //modelDeploymentID = deployment name, if model name and deployment name do not match change this value to name chosen when you deployed the model.
	modelDeploymentID := "gpt-35-turbo" 

	// 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, err := azopenai.NewKeyCredential(azureOpenAIKey)

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

	client, err := azopenai.NewClientWithKeyCredential(azureOpenAIEndpoint, keyCredential, nil)

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

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

		// The user asks a question
		{Role: to.Ptr(azopenai.ChatRoleUser), Content: to.Ptr("Does Azure OpenAI support customer managed keys?")},

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

		// The user answers the question based on the latest reply.
		{Role: to.Ptr(azopenai.ChatRoleUser), Content: to.Ptr("Do other Azure AI services support this too?")},

		// from here you'd keep iterating, sending responses back from the chat completions API
	}

	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,
		Deployment: modelDeploymentID,
	}, nil)

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

	for _, choice := range resp.Choices {
		fmt.Fprintf(os.Stderr, "Content[%d]: %s\n", *choice.Index, *choice.Message.Content)
	}

}

重要

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

現在開啟命令提示字元並執行:

go mod init chat_completions.go

下一次執行:

go mod tidy
go run chat_completions.go

輸出

Content[0]: Yes, many Azure AI services also support customer managed keys. These services enable you to bring your own encryption keys for data at rest, which provides you with more control over the security of your data.

清除資源

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

下一步

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

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

必要條件

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

設定

擷取金鑰和端點

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

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

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

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境變數

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

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.3")
    implementation("org.slf4j:slf4j-simple:1.7.9")
}

建立範例應用程式

  1. 建立 Java 檔案。

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

    mkdir -p src/main/java
    

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

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

    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.ChatMessage;
    import com.azure.ai.openai.models.ChatRole;
    import com.azure.ai.openai.models.CompletionsUsage;
    import com.azure.core.credential.AzureKeyCredential;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class GetChatCompletionsSample {
    
        public static void main(String[] args) {
            String azureOpenaiKey = System.getenv("AZURE_OPENAI_API_KEY");;
            String endpoint = System.getenv("AZURE_OPENAI_ENDPOINT");;
            String deploymentOrModelId = "gpt-35-turbo";
    
          OpenAIClient client = new OpenAIClientBuilder()
                .endpoint(endpoint)
                .credential(new AzureKeyCredential(azureOpenaiKey))
                .buildClient();
    
            List<ChatMessage> chatMessages = new ArrayList<>();
            chatMessages.add(new ChatMessage(ChatRole.SYSTEM, "You are a helpful assistant"));
            chatMessages.add(new ChatMessage(ChatRole.USER, "Does Azure OpenAI support customer managed keys?"));
            chatMessages.add(new ChatMessage(ChatRole.ASSISTANT, "Yes, customer managed keys are supported by Azure OpenAI?"));
            chatMessages.add(new ChatMessage(ChatRole.USER, "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()) {
                ChatMessage 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 金鑰保存庫。 如需有關認證安全性的詳細資訊,請參閱 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。 一律有兩個金鑰可讓您安全地輪替和重新產生密鑰,而不會造成服務中斷。

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境變數

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

注意

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. 從 src/main/java/com/example/aichatdemo 資料夾,開啟您慣用編輯器或 IDE 中的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 金鑰保存庫。 如需有關認證安全性的詳細資訊,請參閱 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) | 範例 | 擷取增強世代 (RAG) 企業聊天範本 | |

必要條件

設定

擷取金鑰和端點

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

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

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

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境變數

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

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

建立節點應用程式

在主控台視窗中(例如 cmd、PowerShell 或 Bash),為您的應用程式建立新的目錄,然後流覽至它。 然後執行 npm init 命令,以使用 package.json 檔案建立節點應用程式。

npm init

安裝客戶端連結庫

使用 npm 安裝適用於 JavaScript 的 Azure OpenAI 用戶端連結庫:

npm install @azure/openai

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

建立範例應用程式

開啟您想要新專案的命令提示字元,然後建立名為 ChatCompletion.js 的新檔案。 將下列程式代碼複製到ChatCompletion.js檔案中。

const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] ;
const azureApiKey = process.env["AZURE_OPENAI_API_KEY"] ;

const 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" },
];

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

  const client = new OpenAIClient(endpoint, new AzureKeyCredential(azureApiKey));
  const deploymentId = "gpt-35-turbo";
  const result = await client.getChatCompletions(deploymentId, messages);

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

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

module.exports = { main };

重要

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

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

node.exe ChatCompletion.js

輸出

== Chat Completions Sample ==
{
  role: 'assistant',
  content: 'Yes, most Azure AI services support customer managed keys. It is always best to check the specific service documentation to confirm this.'
}

清除資源

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

下一步

連結庫原始程式碼 | 套件 (PyPi) | 擷取增強世代 (RAG) 企業聊天範本 |

必要條件

設定

使用下列項目安裝 OpenAI Python 用戶端連結庫:

pip install openai==0.28.1

注意

此程式庫是由 OpenAI 維護,目前為預覽版本。 參閱版本歷程記錄version.py 認可歷程記錄來追蹤程式庫的最新更新。

擷取金鑰和端點

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

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

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

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境變數

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

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 的內容取代為下列程式碼。

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

import os
import openai
openai.api_type = "azure"
openai.api_base = os.getenv("AZURE_OPENAI_ENDPOINT") 
openai.api_key = os.getenv("AZURE_OPENAI_API_KEY")
openai.api_version = "2023-05-15"

response = openai.ChatCompletion.create(
    engine="gpt-35-turbo", # engine = "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)
print(response['choices'][0]['message']['content'])

重要

針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 Azure 金鑰保存庫。 如需有關認證安全性的詳細資訊,請參閱 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 操作指南提供與這些新模型通訊選項的深入介紹。

清除資源

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

下一步

REST API 規格 |

必要條件

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

設定

擷取金鑰和端點

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

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

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

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint and access keys location circled in red.

環境變數

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

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-4 模型時,您必須將 取代 gpt-35-turbo 為您所選擇的部署名稱。 除非您選擇與基礎模型名稱相同的部署名稱,否則輸入模型名稱會導致錯誤。

curl $AZURE_OPENAI_ENDPOINT/openai/deployments/gpt-35-turbo/chat/completions?api-version=2023-05-15 \
  -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=2023-05-15 \:如果您遇到錯誤雙重檢查,請確定您在端點與 /openai/deployments之間的分隔處沒有兩倍/的 。

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

重要

針對生產環境,請使用安全的方式來儲存和存取您的認證,例如 Azure 金鑰保存庫。 如需有關認證安全性的詳細資訊,請參閱 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 操作指南提供與這些新模型通訊選項的深入介紹。

清除資源

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

下一步

必要條件

擷取金鑰和端點

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

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

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

Screenshot of the overview UI for an OpenAI Resource in the Azure portal with the endpoint & access keys location circled in red.

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

環境變數

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

建立新的 PowerShell 腳本

  1. 建立名為 quickstart.ps1 的新 PowerShell 檔案。 然後在您慣用的編輯器或 IDE 中開啟它。

  2. 以下列程序代碼取代 quickstart.ps1 的內容。 您必須將 engine 變數設定為部署 GPT-35-Turbo 或 GPT-4 模型時所選擇的部署名稱。 除非您選擇與基礎模型名稱相同的部署名稱,否則輸入模型名稱會導致錯誤。

    # 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 = '2023-05-15' # 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
    

    重要

    針對生產環境,請使用安全的方式來儲存和存取您的認證,例如PowerShell秘密管理與 Azure 金鑰保存庫。 如需有關認證安全性的詳細資訊,請參閱 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 操作指南提供與這些新模型通訊選項的深入介紹。

清除資源

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

下一步