你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:开始通过 Azure OpenAI 服务使用 GPT-35-Turbo and 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

导航到 Azure OpenAI Studio (https://oai.azure.com/),然后使用有权访问 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 即表示 5 个用户查询和 5 个系统回复。
停止序列 停止序列使模型在所需时间点结束响应。 模型响应会在指定序列之前结束,因此它不包含停止序列文本。 对于 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 工作室中的体验感到满意后,可以通过选择“部署到”按钮直接从工作室部署 Web 应用。

屏幕截图显示 Azure OpenAI Studio 中的模型部署按钮。

如果你在模型上使用自己的数据,这样就可以选择部署到独立的 Web 应用程序或 Copilot Studio(预览版)中的 Copilot。

例如,如果选择部署 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 的新控制台应用。 此命令将创建包含单个 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。 始终准备好两个密钥可以安全地轮换和重新生成密钥,而不会导致服务中断。

Azure 门户中 Azure OpenAI 资源概述 UI 的屏幕截图,其中终结点和访问密钥的位置用红圈标示。

环境变量

为密钥和终结点创建和分配持久环境变量。

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 资源概述 UI 的屏幕截图,其中终结点和访问密钥的位置用红圈标示。

环境变量

为密钥和终结点创建和分配持久环境变量。

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 Key Vault。 有关凭据安全性的详细信息,请参阅 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-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 资源概述 UI 的屏幕截图,其中终结点和访问密钥的位置用红圈标示。

环境变量

为密钥和终结点创建和分配持久环境变量。

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 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 资源概述 UI 的屏幕截图,其中终结点和访问密钥的位置用红圈标示。

环境变量

为密钥和终结点创建和分配持久环境变量。

注意

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 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) | 示例 | 检索增强生成 (RAG) 企业版聊天模板|

先决条件

  • 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 资源概述 UI 的屏幕截图,其中终结点和访问密钥的位置用红圈标示。

环境变量

为密钥和终结点创建和分配持久环境变量。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

创建 Node 应用程序

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建一个新目录并导航到该目录。 然后运行 npm init 命令以使用 package.json 文件创建一个 node 应用程序。

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 Key Vault。 有关凭据安全性的详细信息,请参阅 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) 企业版聊天模板 |

先决条件

  • 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 维护,目前为预览版。 参考发行历史记录version.py 提交历史记录跟踪库的最新更新。

检索密钥和终结点

若要成功对 Azure OpenAI 发出调用,需要一个终结点和一个密钥。

变量名称
ENDPOINT 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 或者,可以在“Azure OpenAI Studio”>“操场”>“代码视图”中找到该值。 示例终结点为:https://docs-test-001.openai.azure.com/
API-KEY 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 可以使用 KEY1KEY2

在 Azure 门户中转到你的资源。 可在“资源管理”部分中找到“密钥和终结点”部分。 复制终结点和访问密钥,因为在对 API 调用进行身份验证时需要这两项。 可以使用 KEY1KEY2。 始终准备好两个密钥可以安全地轮换和重新生成密钥,而不会导致服务中断。

Azure 门户中 Azure OpenAI 资源概述 UI 的屏幕截图,其中终结点和访问密钥的位置用红圈标示。

环境变量

为密钥和终结点创建和分配持久环境变量。

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 的内容替换为以下代码。

需要将变量 model 设置为部署 GPT-3.5-Turbo 或 GPT-4 模型时选择的部署名称。 输入模型名称将导致错误,除非选择的部署名称与基础模型名称相同。

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 资源概述 UI 的屏幕截图,其中终结点和访问密钥的位置用红圈标示。

环境变量

为密钥和终结点创建和分配持久环境变量。

setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE" 
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE" 

REST API

在 bash shell 中运行以下命令: 需要将 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 资源概述 UI 的屏幕截图,其中终结点和访问密钥的位置用红圈标示。

为密钥和终结点创建和分配持久环境变量。

环境变量

$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 = '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 Secret Management。 有关凭据安全性的详细信息,请参阅 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 资源,可以删除该资源。 在删除资源之前,必须先删除所有已部署的模型。

后续步骤