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

快速入门:开始通过 Azure OpenAI 服务使用 GPT-35-Turbo and GPT-4

使用本文来帮助你开始使用 Azure OpenAI。

先决条件

  • Azure 订阅 - 免费创建订阅
  • 部署了 gpt-4ogpt-4o-mini 模型的 Azure OpenAI 服务资源。 建议使用标准或全局标准模型部署类型进行初始探索。 有关模型部署的详细信息,请参阅资源部署指南

登录到 Azure OpenAI Studio

导航到 https://oai.azure.com/ 处的 Azure OpenAI Studio,然后使用有权访问 Azure OpenAI 资源的凭据登录。 在登录过程中或登录之后,选择适当的目录、Azure 订阅和 Azure OpenAI 资源。

在 Azure OpenAI Studio 登陆页面中,选择“聊天操场”

Azure OpenAI Studio 登陆页面的屏幕截图,其中突出显示了“聊天操场”。

操场

通过 Azure OpenAI Studio“聊天操场”,以无代码方式开始探索 OpenAI 功能。 在此页中,可以快速循环访问和试验这些功能。

“聊天操场”页面的屏幕截图。

安装

可以使用“提示示例”下拉列表选择一些预加载的系统消息示例以开始使用。

系统消息为模型提供有关它应该如何行为以及生成回复时应引用什么上下文的说明。 你可以描述助手的个性,告诉它应该回答什么和不应该回答什么,并告诉它如何设置回复的格式。

使用“聊天操场”时,可以随时选择“查看代码”以查看基于当前聊天会话和设置选择所预先填充的 Python、curl 和 json 代码示例。 然后,可以采用此代码并编写应用程序,以完成当前使用操场执行的相同任务。

聊天会话

选择 Enter 按钮或选择向右箭图标会将输入的文本发送到聊天补全 API,结果将返回到文本框。

选择“清除聊天”按钮可删除当前对话历史记录。

关键设置

Name 说明
部署 与特定模型关联的部署名称。
添加数据
参数 更改模型响应的自定义参数。 当你开始的时候,我们建议对大多数参数使用默认值
温度 控制随机性。 降低温度意味着模型会产生更多重复性和确定性的回复。 提高温度会导致更多意外或创造性的回复。 请尝试调整温度或 Top P 值,但不要同时调整两者。
最大响应(令牌) 对每个模型回复的标记数设置限制。 最新模型上的 API 支持最多 128,000 个标记,包括提示(包括系统消息、示例、消息历史记录以及用户查询)和模型的回复。 对于典型的英文文本,一个标记大约是四个字符。
Top p 与温度类似,它控制着随机性,但使用不同的方法。 降低 Top P 值会将模型的标记选择范围缩小到可能性更高的标记。 增加 Top P 值会使模型既选择可能高的标记又选择可能性低的标记。 请尝试调整温度或 Top P 值,但不要同时调整两者。
停止序列 停止序列使模型在所需时间点结束响应。 模型响应会在指定序列之前结束,因此它不包含停止序列文本。 对于 GPT-35-Turbo,使用 <|im_end|> 可确保模型响应不会生成后续用户查询。 可以包含多达四个停止序列。

查看代码

尝试与模型聊天后,请选择“</> 查看代码”按钮。 这样,就可以重播整个对话背后的代码:

查看代码体验的屏幕截图。

了解提示结构

如果你从“查看代码”处检查示例,你会注意到对话分为三个不同的角色, systemuserassistant。 每次向模型发送消息时,整个对话历史记录都会重新发送到该点。 使用聊天补全 API 时,模型无法真正记住你过去发送给它的内容,因此需要提供对话历史记录作为上下文,以便模型做出正确响应。

聊天补全操作指南提供了对新提示结构的深入介绍,以及如何有效地使用聊天补全模型。

部署模型

对 Azure OpenAI 工作室中的体验感到满意后,可以通过选择“部署到”按钮直接从工作室部署 Web 应用。

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

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

例如,如果选择部署 Web 应用:

首次部署 Web 应用时,应选择“创建新的 Web 应用”。 为应用选择一个名称,该名称将成为应用 URL 的一部分。 例如,https://<appname>.azurewebsites.net

为已发布的应用选择订阅、资源组、位置和定价计划。 要更新现有应用,请选择“发布到现有 Web 应用”,然后从下拉菜单中选择上一个应用的名称。

如果选择部署 Web 应用,请参阅使用它的重要注意事项

清理资源

完成聊天操场测试后,如果要清理并移除某个 Azure OpenAI 资源,可以删除该资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。

后续步骤

源代码 | 包 (NuGet) | 示例| 检索增强生成 (RAG) 企业版聊天模板 |

先决条件

设置

创建新的 .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 的屏幕截图,其中终结点和访问密钥的位置用红圈标示。

环境变量

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

重要

如果使用 API 密钥,请将其安全地存储在某个其他位置,例如 Azure Key Vault 中。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。

有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证

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");

AzureOpenAIClient azureClient = new(
    new Uri(endpoint),
    new AzureKeyCredential(key));

// This must match the custom deployment name you chose for your model
ChatClient chatClient = azureClient.GetChatClient("gpt-35-turbo");

ChatCompletion completion = chatClient.CompleteChat(
    [
        new SystemChatMessage("You are a helpful assistant that talks like a pirate."),
        new UserChatMessage("Does Azure OpenAI support customer managed keys?"),
        new AssistantChatMessage("Yes, customer managed keys are supported by Azure OpenAI"),
        new UserChatMessage("Do other Azure AI services support this too?")
    ]);

Console.WriteLine($"{completion.Role}: {completion.Content[0].Text}");

重要

对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关凭据安全性的详细信息,请参阅 Azure AI 服务安全性一文。

dotnet run program.cs

输出

Assistant : Yes, many other Azure AI services also support customer managed keys, including Azure Cognitive Services, Azure Machine Learning, and Azure Databricks. By using customer managed keys, you can retain complete control over your encryption keys and provide an additional layer of security for your AI assets.

这将等到模型生成其整个响应后再打印结果。 或者,如果要异步流式处理响应并打印结果,则可以将 program.cs 的内容替换为下一个示例中的代码。

使用流式处理进行异步

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

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

AzureOpenAIClient azureClient = new(
    new Uri(endpoint),
    new AzureKeyCredential(key));

// This must match the custom deployment name you chose for your model
ChatClient chatClient = azureClient.GetChatClient("gpt-35-turbo");

var chatUpdates = chatClient.CompleteChatStreamingAsync(
    [
        new SystemChatMessage("You are a helpful assistant that talks like a pirate."),
        new UserChatMessage("Does Azure OpenAI support customer managed keys?"),
        new AssistantChatMessage("Yes, customer managed keys are supported by Azure OpenAI"),
        new UserChatMessage("Do other Azure AI services support this too?")
    ]);

await foreach(var chatUpdate in chatUpdates)
{
    if (chatUpdate.Role.HasValue)
    {
        Console.Write($"{chatUpdate.Role} : ");
    }
    
    foreach(var contentPart in chatUpdate.ContentUpdate)
    {
        Console.Write(contentPart.Text);
    }
}

清理资源

如果你想要清理和移除 Azure OpenAI 资源,可以删除该资源。 在删除资源之前,必须先删除所有已部署的模型。

后续步骤

源代码 | 包 (Go)| 示例

先决条件

设置

检索密钥和终结点

若要成功对 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 的屏幕截图,其中终结点和访问密钥的位置用红圈标示。

环境变量

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

重要

如果使用 API 密钥,请将其安全地存储在某个其他位置,例如 Azure Key Vault 中。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。

有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证

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

先决条件

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

环境变量

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

重要

如果使用 API 密钥,请将其安全地存储在某个其他位置,例如 Azure Key Vault 中。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。

有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证

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

环境变量

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

重要

如果使用 API 密钥,请将其安全地存储在某个其他位置,例如 Azure Key Vault 中。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。

有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证

注意

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) | 示例

注意

本文已更新为使用最新的 OpenAI npm 包,该包现已完全支持 Azure OpenAI。 如果要查找旧版 Azure OpenAI JavaScript SDK 的代码示例,目前仍可以此存储库中找到它们

先决条件

设置

检索密钥和终结点

若要成功对 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 的屏幕截图,其中终结点和访问密钥的位置用红圈标示。

环境变量

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

重要

如果使用 API 密钥,请将其安全地存储在某个其他位置,例如 Azure Key Vault 中。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。

有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证

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 安装 JavaScript 所需的包:

npm install openai dotenv @azure/identity

你的应用的 package.json 文件将随依赖项进行更新。

创建一个简单的应用程序

在需要新项目的位置打开命令提示符,并创建一个名为 ChatCompletion.js 的新文件。 将以下代码复制到 ChatCompletion.js 文件中。

import "dotenv/config";
import { AzureOpenAI } from "openai";
import type {
  ChatCompletion,
  ChatCompletionCreateParamsNonStreaming,
} from "openai/resources/index";

// 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>";

// Required Azure OpenAI deployment name and API version
const apiVersion = "2024-08-01-preview";
const deploymentName = "gpt-4o-mini"; //This must match your deployment name.

function getClient(): AzureOpenAI {
  return new AzureOpenAI({
    endpoint,
    apiKey,
    apiVersion,
    deployment: deploymentName,
  });
}

function createMessages(): ChatCompletionCreateParamsNonStreaming {
  return {
    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: "",
  };
}
async function printChoices(completion: ChatCompletion): Promise<void> {
  for (const choice of completion.choices) {
    console.log(choice.message);
  }
}
export async function main() {
  const client = getClient();
  const messages = createMessages();
  const result = await client.chat.completions.create(messages);
  await printChoices(result);
}

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

使用以下命令构建脚本:

tsc

使用以下命令运行该脚本:

node.exe Completion.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] 需要一些额外的先决条件

import {
  DefaultAzureCredential,
  getBearerTokenProvider,
} from "@azure/identity";
import "dotenv/config";
import { AzureOpenAI } from "openai";
import type {
  ChatCompletion,
  ChatCompletionCreateParamsNonStreaming,
} from "openai/resources/index";

// You will need to set these environment variables or edit the following values
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";

// Required Azure OpenAI deployment name and API version
const apiVersion = "2024-08-01-preview";
const deploymentName = "gpt-4o-mini"; //This must match your deployment name.

function getClient(): AzureOpenAI {
  const scope = "https://cognitiveservices.azure.com/.default";
  const azureADTokenProvider = getBearerTokenProvider(
    new DefaultAzureCredential(),
    scope
  );
  return new AzureOpenAI({
    endpoint,
    azureADTokenProvider,
    deployment: deploymentName,
    apiVersion,
  });
}

function createMessages(): ChatCompletionCreateParamsNonStreaming {
  return {
    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: "",
  };
}
async function printChoices(completion: ChatCompletion): Promise<void> {
  for (const choice of completion.choices) {
    console.log(choice.message);
  }
}
export async function main() {
  const client = getClient();
  const messages = createMessages();
  const result = await client.chat.completions.create(messages);
  await printChoices(result);
}

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

注意

如果收到错误消息:“发生错误: OpenAIError: apiKeyazureADTokenProvider 参数互斥;一次只能传递一个”。可能需要从系统中移除 API 密钥的预先存在的环境变量。 即使 Microsoft Entra ID 代码示例未显式引用 API 密钥环境变量,但如果执行此示例的系统中存在该环境变量,仍会生成此错误。

清理资源

如果你想要清理和移除 Azure OpenAI 资源,可以删除该资源。 在删除资源之前,必须先删除所有已部署的模型。

后续步骤

库源代码 | 包 (PyPi) | 检索增强生成 (RAG) 企业版聊天模板 |

先决条件

设置

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

环境变量

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

重要

如果使用 API 密钥,请将其安全地存储在某个其他位置,例如 Azure Key Vault 中。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。

有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证

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 OpenAI 发出调用,需要一个终结点和一个密钥。

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

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

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

环境变量

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

重要

如果使用 API 密钥,请将其安全地存储在某个其他位置,例如 Azure Key Vault 中。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。

有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证

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

环境变量

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

重要

如果使用 API 密钥,请将其安全地存储在某个其他位置,例如 Azure Key Vault 中。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。

有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证

$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 资源,可以删除该资源。 在删除资源之前,必须先删除所有已部署的模型。

后续步骤