快速入门:在 Azure AI Foundry 模型中开始使用 Azure OpenAI 的聊天补全功能

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

先决条件

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

转到 Azure AI Foundry

导航到 Azure AI Foundry 门户,然后使用有权访问 Azure OpenAI 资源的凭据登录。 在登录工作流之中和之后,选择适当的目录、Azure 订阅和 Azure OpenAI 资源。

在 Azure AI Foundry 中,选择“聊天操场”。

操场

通过 Azure AI Foundry Chat 体验区,以无代码方法开始探索 Azure OpenAI 功能。 在此页中,可以快速循环访问和试验这些功能。

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

设置

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

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

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

聊天会话

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

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

关键设置

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

查看代码

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

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

了解提示结构

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

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

部署模型

对体验感到满意后,可以通过选择“部署到”按钮直接从门户部署 Web 应用。

显示门户中的模型部署按钮的屏幕截图。

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

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

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

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

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

清理资源

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

后续步骤

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

先决条件

Microsoft Entra ID 先决条件

若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,你需要:

  • 安装使用 Microsoft Entra ID 进行无密钥身份验证所需的 Azure CLI
  • Cognitive Services User 角色分配给用户帐户。 可以在 Azure 门户中的“访问控制 (IAM)”“添加角色分配”下分配角色。>

设置

  1. 创建新文件夹 chat-quickstart,并使用以下命令转到快速入门文件夹:

    mkdir chat-quickstart && cd chat-quickstart
    
  2. 使用以下命令创建新的控制台应用程序:

    dotnet new console
    
  3. 使用 dotnet add package 命令安装 OpenAI .NET 客户端库

    dotnet add package Azure.AI.OpenAI --prerelease
    
  4. 若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,请使用以下命令安装 Azure.Identity 包:

    dotnet add package Azure.Identity
    
  5. 若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,请使用以下命令登录到 Azure:

    az login
    

检索资源信息

需要检索以下信息才能使用 Azure OpenAI 资源对应用程序进行身份验证:

变量名称
AZURE_OPENAI_ENDPOINT 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值将对应于在部署模型时为部署选择的自定义名称。 Azure 门户中的“资源管理”“模型部署”下提供了此值。>
OPENAI_API_VERSION 详细了解 API 版本

可以在代码中更改版本或使用环境变量。

详细了解无密钥身份验证,以及如何设置环境变量

运行快速入门

本快速入门中的示例代码使用 Microsoft Entra ID 进行推荐的无密钥身份验证。 如果希望使用 API 密钥,可以将 DefaultAzureCredential 对象替换为 AzureKeyCredential 对象。

AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential()); 

可以使用流式处理或非流式处理来获取聊天补全。 下面的代码示例演示如何使用这两种方法。 第一个示例演示如何使用非流式处理方法,第二个示例演示如何使用流式处理方法。

没有响应流式处理

若要运行快速入门,请执行以下步骤:

  1. Program.cs 的内容替换为以下代码,并将占位符值更新为你自己的值。

    using Azure;
    using Azure.Identity;
    using OpenAI.Assistants;
    using Azure.AI.OpenAI;
    using OpenAI.Chat;
    using static System.Environment;
    
    string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? "https://<your-resource-name>.openai.azure.com/";
    string key = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY") ?? "<your-key>";
    
    // Use the recommended keyless credential instead of the AzureKeyCredential credential.
    AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential()); 
    //AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key));
    
    // This must match the custom deployment name you chose for your model
    ChatClient chatClient = openAIClient.GetChatClient("gpt-4o");
    
    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 services support this too?")
        ]);
    
    Console.WriteLine($"{completion.Role}: {completion.Content[0].Text}");
    
  2. 使用以下命令运行应用程序:

    dotnet run
    

输出

Assistant: Arrr, ye be askin’ a fine question, matey! Aye, several Azure services support customer-managed keys (CMK)! This lets ye take the wheel and secure yer data with encryption keys stored in Azure Key Vault. Services such as Azure Machine Learning, Azure Cognitive Search, and others also offer CMK fer data protection. Always check the specific service's documentation fer the latest updates, as features tend to shift swifter than the tides, aye!

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

使用流式处理进行异步

若要运行快速入门,请执行以下步骤:

  1. Program.cs 的内容替换为以下代码,并将占位符值更新为你自己的值。

    using Azure;
    using Azure.Identity;
    using OpenAI.Assistants;
    using Azure.AI.OpenAI;
    using OpenAI.Chat;
    using static System.Environment;
    
    string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? "https://<your-resource-name>.openai.azure.com/";
    string key = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY") ?? "<your-key>";
    
    // Use the recommended keyless credential instead of the AzureKeyCredential credential.
    AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential()); 
    //AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key));
    
    // This must match the custom deployment name you chose for your model
    ChatClient chatClient = openAIClient.GetChatClient("gpt-4o");
    
    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 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);
        }
    }
    
  2. 使用以下命令运行应用程序:

    dotnet run
    

输出

Assistant: Arrr, ye be askin’ a fine question, matey! Aye, many Azure services support customer-managed keys (CMK)! This lets ye take the wheel and secure yer data with encryption keys stored in Azure Key Vault. Services such as Azure Machine Learning, Azure Cognitive Search, and others also offer CMK fer data protection. Always check the specific service's documentation fer the latest updates, as features tend to shift swifter than the tides, aye!

清理资源

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

后续步骤

源代码 | 包 (Go)| 示例

先决条件

  • Azure 订阅 - 免费创建订阅
  • 已在本地安装 Go 1.21.0 或更高版本。
  • 一个 Azure AI Foundry 中的 Azure OpenAI 模型,其中已部署 gpt-4 模型。 有关模型部署的详细信息,请参阅资源部署指南

Microsoft Entra ID 先决条件

若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,你需要:

  • 安装使用 Microsoft Entra ID 进行无密钥身份验证所需的 Azure CLI
  • Cognitive Services User 角色分配给用户帐户。 可以在 Azure 门户中的“访问控制 (IAM)”“添加角色分配”下分配角色。>

设置

  1. 创建新文件夹 chat-quickstart,并使用以下命令转到快速入门文件夹:

    mkdir chat-quickstart && cd chat-quickstart
    
  2. 若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,请使用以下命令登录到 Azure:

    az login
    

检索资源信息

需要检索以下信息才能使用 Azure OpenAI 资源对应用程序进行身份验证:

变量名称
AZURE_OPENAI_ENDPOINT 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值将对应于在部署模型时为部署选择的自定义名称。 Azure 门户中的“资源管理”“模型部署”下提供了此值。>
OPENAI_API_VERSION 详细了解 API 版本

可以在代码中更改版本或使用环境变量。

详细了解无密钥身份验证,以及如何设置环境变量

运行快速入门

本快速入门中的示例代码使用 Microsoft Entra ID 进行推荐的无密钥身份验证。 如果希望使用 API 密钥,可以将 NewDefaultAzureCredential 实现替换为 NewKeyCredential

azureOpenAIEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT")
credential, err := azidentity.NewDefaultAzureCredential(nil)
client, err := azopenai.NewClient(azureOpenAIEndpoint, credential, nil)

若要运行该示例:

  1. 创建名为 chat_completions_keyless.go 的新文件。 将以下代码复制到 chat_completions_keyless.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/azidentity"
    )
    
    func main() {
    	azureOpenAIEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT")
    	modelDeploymentID := "gpt-4o"
        maxTokens:= int32(400)
    
    	credential, err := azidentity.NewDefaultAzureCredential(nil)
    	if err != nil {
    		log.Printf("ERROR: %s", err)
    		return
    	}
    
    	client, err := azopenai.NewClient(
    		azureOpenAIEndpoint, credential, nil)
    	if err != nil {
    		log.Printf("ERROR: %s", err)
    		return
    	}
    
    	// This is a conversation in progress.
    	// All messages, regardless of role, count against token usage for this API.
    	messages := []azopenai.ChatRequestMessageClassification{
    		// System message sets the tone and rules of the conversation.
    		&azopenai.ChatRequestSystemMessage{
    			Content: azopenai.NewChatRequestSystemMessageContent(
    				"You are a helpful assistant."),
    		},
    
    		// The user asks a question
    		&azopenai.ChatRequestUserMessage{
    			Content: azopenai.NewChatRequestUserMessageContent(
    				"Can I use honey as a substitute for sugar?"),
    		},
    
    		// The reply would come back from the model. You
    		// add it to the conversation so we can maintain context.
    		&azopenai.ChatRequestAssistantMessage{
    			Content: azopenai.NewChatRequestAssistantMessageContent(
    				"Yes, you can use use honey as a substitute for sugar."),
    		},
    
    		// The user answers the question based on the latest reply.
    		&azopenai.ChatRequestUserMessage{
    			Content: azopenai.NewChatRequestUserMessageContent(
    				"What other ingredients can I use as a substitute for sugar?"),
    		},
    
    		// From here you can keep iterating, sending responses back from the chat model.
    	}
    
    	gotReply := false
    
    	resp, err := client.GetChatCompletions(context.TODO(), azopenai.ChatCompletionsOptions{
    		// This is a conversation in progress.
    		// All messages count against token usage for this API.
    		Messages: messages,
    		DeploymentName: &modelDeploymentID,
    		MaxTokens: &maxTokens,
    	}, nil)
    
    	if err != nil {
    		// Implement 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 {
    			// The conversation for this choice 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")
    	}
    
    }
    
  2. 运行以下命令来创建新的 Go 模块:

     go mod init chat_completions_keyless.go
    
  3. 运行 go mod tidy 来安装必需的依赖项:

    go mod tidy
    
  4. 运行以下命令来运行示例:

     go run chat_completions_keyless.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]: There are many alternatives to sugar that you can use, depending on the type of recipe you’re making and your dietary needs or taste preferences. Here are some popular sugar substitutes:

---

### **Natural Sweeteners**  
1. **Honey**
   - Sweeter than sugar and adds moisture, with a distinct flavor.
   - Substitution: Use ¾ cup honey for 1 cup sugar, and reduce the liquid in your recipe by 2 tablespoons. Lower the baking temperature by 25°F to prevent over-browning.

2. **Maple Syrup**
   - Adds a rich, earthy sweetness with a hint of maple flavor.
   - Substitution: Use ¾ cup syrup for 1 cup sugar. Reduce liquids by 3 tablespoons.

3. **Agave Nectar**
   - Sweeter and milder than honey, it dissolves well in cold liquids.
   - Substitution: Use ⅔ cup agave for 1 cup sugar. Reduce liquids in the recipe slightly.

4. **Molasses**
   - A byproduct of sugar production with a robust, slightly bitter flavor.
   - Substitution: Use 1 cup of molasses for 1 cup sugar. Reduce liquid by ¼ cup and consider combining it with other sweeteners due to its strong flavor.

5. **Coconut Sugar**
   - Made from the sap of coconut palms, it has a rich, caramel-like flavor.
   - Substitution: Use it in a 1:1 ratio for sugar.

6. **Date Sugar** (or Medjool Dates)
   - Made from ground, dried dates, or blended into a puree, offering a rich, caramel taste.
   - Substitution: Use 1:1 for sugar. Adjust liquid in recipes if needed.

---

### **Calorie-Free or Reduced-Calorie Sweeteners**
1. **Stevia**
   - A natural sweetener derived from stevia leaves, hundreds of
Finish reason[0]: length
Received chat completions reply

清理资源

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

后续步骤

有关更多示例,请查看 Azure OpenAI 示例 GitHub 存储库

源代码 | 生成工件 (Maven) | 示例 | 检索增强生成 (RAG) 企业版聊天模板 | IntelliJ IDEA

先决条件

  • Gradle 生成工具,或其他依赖项管理器。
  • 一个 Azure AI Foundry 中的 Azure OpenAI 模型,其中已部署 gpt-4 模型。 有关模型部署的详细信息,请参阅资源部署指南

Microsoft Entra ID 先决条件

若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,你需要:

  • 安装使用 Microsoft Entra ID 进行无密钥身份验证所需的 Azure CLI
  • Cognitive Services User 角色分配给用户帐户。 可以在 Azure 门户中的“访问控制 (IAM)”“添加角色分配”下分配角色。>

设置

  1. 创建新文件夹 chat-quickstart,并使用以下命令转到快速入门文件夹:

    mkdir chat-quickstart && cd chat-quickstart
    
  2. 安装 Apache Maven。 然后运行 mvn -v 以确认安装成功。

  3. 在项目的根目录中创建一个新的 pom.xml 文件,并将以下代码复制到该文件中:

    <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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
         <modelVersion>4.0.0</modelVersion>
         <groupId>com.azure.samples</groupId>
         <artifactId>quickstart-dall-e</artifactId>
         <version>1.0.0-SNAPSHOT</version>
         <build>
             <sourceDirectory>src</sourceDirectory>
             <plugins>
             <plugin>
                 <artifactId>maven-compiler-plugin</artifactId>
                 <version>3.7.0</version>
                 <configuration>
                 <source>1.8</source>
                 <target>1.8</target>
                 </configuration>
             </plugin>
             </plugins>
         </build>
         <dependencies>    
             <dependency>
                 <groupId>com.azure</groupId>
                 <artifactId>azure-ai-openai</artifactId>
                 <version>1.0.0-beta.10</version>
             </dependency>
             <dependency>
                 <groupId>com.azure</groupId>
                 <artifactId>azure-core</artifactId>
                 <version>1.53.0</version>
             </dependency>
             <dependency>
                 <groupId>com.azure</groupId>
                 <artifactId>azure-identity</artifactId>
                 <version>1.15.1</version>
             </dependency>
             <dependency>
                 <groupId>org.slf4j</groupId>
                 <artifactId>slf4j-simple</artifactId>
                 <version>1.7.9</version>
             </dependency>
         </dependencies>
     </project>
    
  4. 安装 Azure OpenAI SDK 和依赖项。

    mvn clean dependency:copy-dependencies
    
  5. 若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,请使用以下命令登录到 Azure:

    az login
    

检索资源信息

需要检索以下信息才能使用 Azure OpenAI 资源对应用程序进行身份验证:

变量名称
AZURE_OPENAI_ENDPOINT 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值将对应于在部署模型时为部署选择的自定义名称。 Azure 门户中的“资源管理”“模型部署”下提供了此值。>
OPENAI_API_VERSION 详细了解 API 版本

可以在代码中更改版本或使用环境变量。

详细了解无密钥身份验证,以及如何设置环境变量

运行应用

本快速入门中的示例代码使用 Microsoft Entra ID 进行推荐的无密钥身份验证。 如果希望使用 API 密钥,可以将 DefaultAzureCredential 对象替换为 AzureKeyCredential 对象。

OpenAIClient client = new OpenAIClientBuilder()
    .endpoint(endpoint)
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildAsyncClient();

按照以下步骤创建用于语音识别的控制台应用程序。

  1. 在同一项目根目录中创建一个名为 Quickstart.java 的新文件。

  2. 将以下代码复制到 Quickstart.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.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.identity.DefaultAzureCredentialBuilder;
    import com.azure.core.util.Configuration;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class QuickstartEntra {
    
        public static void main(String[] args) {
    
            String endpoint = Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT");
            String deploymentOrModelId = "gpt-4o";
    
            // Use the recommended keyless credential instead of the AzureKeyCredential credential.
    
            OpenAIClient client = new OpenAIClientBuilder()
                .endpoint(endpoint)
                .credential(new DefaultAzureCredentialBuilder().build())
                .buildClient();
    
            List<ChatRequestMessage> chatMessages = new ArrayList<>();
            chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant."));
            chatMessages.add(new ChatRequestUserMessage("Can I use honey as a substitute for sugar?"));
            chatMessages.add(new ChatRequestAssistantMessage("Yes, you can use use honey as a substitute for sugar."));
            chatMessages.add(new ChatRequestUserMessage("What other ingredients can I use as a substitute for sugar?"));    
    
            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());
        }
    }
    
  3. 运行新的控制台应用程序以生成映像:

    javac Quickstart.java -cp ".;target\dependency\*"
    java -cp ".;target\dependency\*" Quickstart
    

输出

Model ID=chatcmpl-BDgC0Yr8YNhZFhLABQYfx6QfERsVO is created at 2025-03-21T23:35:52Z.
Index: 0, Chat Role: assistant.
Message:
If you're looking to replace sugar in cooking, baking, or beverages, there are several alternatives you can use depending on your tastes, dietary needs, and the recipe. Here's a list of common sugar substitutes:

### **Natural Sweeteners**
1. **Honey**
   - Sweeter than sugar, so you may need less.
   - Adds moisture to recipes.
   - Adjust liquids and cooking temperature when baking to avoid over-browning.

2. **Maple Syrup**
   - Provides a rich, complex flavor.
   - Can be used in baking, beverages, and sauces.
   - Reduce the liquid content slightly in recipes.

3. **Agave Syrup**
   - Sweeter than sugar and has a mild flavor.
   - Works well in drinks, smoothies, and desserts.
   - Contains fructose, so use sparingly.

4. **Date Sugar or Date Paste**
   - Made from dates, it's a whole-food sweetener with fiber and nutrients.
   - Great for baked goods and smoothies.
   - May darken recipes due to its color.

5. **Coconut Sugar**
   - Similar in taste and texture to brown sugar.
   - Less refined than white sugar.
   - Slightly lower glycemic index, but still contains calories.

6. **Molasses**
   - Dark, syrupy byproduct of sugar refining.
   - Strong flavor; best for specific recipes like gingerbread or BBQ sauce.

### **Artificial Sweeteners**
1. **Stevia**
   - Extracted from the leaves of the stevia plant.
   - Virtually calorie-free and much sweeter than sugar.
   - Available as liquid, powder, or granulated.

2. **Erythritol**
   - A sugar alcohol with few calories and a clean, sweet taste.
   - Doesn?t caramelize like sugar.
   - Often blended with other sweeteners.

3. **Xylitol**
   - A sugar alcohol similar to erythritol.
   - Commonly used in baking and beverages.
   - Toxic to pets (especially dogs), so handle carefully.

### **Whole Fruits**
1. **Mashed Bananas**
   - Natural sweetness works well in baking.
   - Adds moisture to recipes.
   - Can replace sugar partially or fully depending on the dish.

2. **Applesauce (Unsweetened)**
   - Adds sweetness and moisture to baked goods.
   - Reduce other liquids in the recipe accordingly.

3. **Pureed Dates, Figs, or Prunes**
   - Dense sweetness with added fiber and nutrients.
   - Ideal for energy bars, smoothies, and baking.

### **Other Options**
1. **Brown Rice Syrup**
   - Less sweet than sugar, with a mild flavor.
   - Good for granola bars and baked goods.

2. **Yacon Syrup**
   - Extracted from the root of the yacon plant.
   - Sweet and rich in prebiotics.
   - Best for raw recipes.

3. **Monk Fruit Sweetener**
   - Natural sweetener derived from monk fruit.
   - Often mixed with erythritol for easier use.
   - Provides sweetness without calories.

### **Tips for Substitution**
- Sweeteners vary in sweetness, texture, and liquid content, so adjust recipes accordingly.
- When baking, reducing liquids or fats slightly may be necessary.
- Taste test when possible to ensure the sweetness level matches your preference.

Whether you're seeking healthier options, low-calorie substitutes, or simply alternatives for flavor, these sugar substitutes can work for a wide range of recipes!

Usage: number of prompt token is 60, number of completion token is 740, and number of total tokens in request and response is 800.

清理资源

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

后续步骤

源代码 | 项目 (Maven) | 示例

先决条件

设置

检索密钥和终结点

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

变量名称
ENDPOINT 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到服务终结点。 或者,也可以通过 Azure AI Foundry 门户中的“部署”页找到该终结点。 示例终结点为:https://docs-test-001.openai.azure.com/
API-KEY 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 可以使用 KEY1KEY2

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

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

环境变量

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

重要说明

请谨慎使用 API 密钥。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。 如果使用 API 密钥,请将其安全地存储在 Azure Key Vault 中。 若要详细了解如何在应用中安全地使用 API 密钥,请参阅 API 密钥与 Azure Key Vault

有关 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.3.4</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>
          <spring-ai.version>1.0.0-M5</spring-ai.version>
       </properties>
       <dependencies>
          <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter</artifactId>
          </dependency>
          <dependency>
             <groupId>org.springframework.ai</groupId>
             <artifactId>spring-ai-azure-openai-spring-boot-starter</artifactId>
          </dependency>
          <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
          </dependency>
       </dependencies>
       <dependencyManagement>
          <dependencies>
             <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>${spring-ai.version}</version>
                <type>pom</type>
                <scope>import</scope>
             </dependency>
          </dependencies>
       </dependencyManagement>
       <build>
          <plugins>
             <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
             </plugin>
          </plugins>
       </build>
       <repositories>
          <repository>
             <id>spring-milestones</id>
             <name>Spring Milestones</name>
             <url>https://repo.spring.io/milestone</url>
             <snapshots>
                <enabled>false</enabled>
             </snapshots>
          </repository>
       </repositories>
    
    </project>
    
  2. 在“src/main/java/com/example/aichatdemo”文件夹中,使用首选编辑器或 IDE 打开“AiChatApplication.java”,并粘贴以下代码:

    package com.example.aichatdemo;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.ai.chat.client.ChatClient;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Bean;
    
    @SpringBootApplication
    public class AiChatApplication {
    
       private static final Logger log = LoggerFactory.getLogger(AiChatApplication.class);
    
       public static void main(String[] args) {
          SpringApplication.run(AiChatApplication.class, args);
       }
    
       @Bean
       CommandLineRunner commandLineRunner(ChatClient.Builder builder) {
          return args -> {
             var chatClient = builder.build();
             log.info("Sending chat prompts to AI service. One moment please...");
             String response = chatClient.prompt()
                   .user("What was Microsoft's original internal codename for the project that eventually became Azure?")
                   .call()
                   .content();
    
             log.info("Response: {}", response);
          };
       }
    }
    

    重要说明

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

  3. 导航回项目根文件夹,然后使用以下命令运行应用:

    ./mvnw spring-boot:run
    

输出

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.3.4)

2025-03-14T13:35:30.145-04:00  INFO 93252 --- [AIChat] [           main] c.example.aichatdemo.AiChatApplication   : Starting AiChatApplication using Java 23.0.2 with PID 93252 (/Users/vega/dev/msft/spring-ai-samples/ai-chat-demo/target/classes started by vega in /Users/vega/dev/msft/spring-ai-samples/ai-chat-demo)
2025-03-14T13:35:30.146-04:00  INFO 93252 --- [AIChat] [           main] c.example.aichatdemo.AiChatApplication   : No active profile set, falling back to 1 default profile: "default"
2025-03-14T13:35:30.500-04:00  INFO 93252 --- [AIChat] [           main] c.example.aichatdemo.AiChatApplication   : Started AiChatApplication in 0.445 seconds (process running for 0.633)
2025-03-14T13:35:30.501-04:00  INFO 93252 --- [AIChat] [           main] c.example.aichatdemo.AiChatApplication   : Sending chat prompts to AI service. One moment please...
2025-03-14T13:35:31.950-04:00  INFO 93252 --- [AIChat] [           main] c.example.aichatdemo.AiChatApplication   : Response: Microsoft's original internal codename for the project that eventually became Azure was "Project Red Dog." This initiative ultimately led to the development and launch of the Microsoft Azure cloud computing platform.

清理资源

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

后续步骤

有关更多示例,请查看 Azure OpenAI 示例 GitHub 存储库

源代码 | 包 (npm) | 示例

注意

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

先决条件

  • Azure 订阅 - 免费创建订阅
  • LTS 版本的 Node.js
  • Azure CLI用于本地开发环境中的无密码身份验证,请使用 Azure CLI 登录以创建必要的上下文。
  • 一个 Azure AI Foundry 中的 Azure OpenAI 模型,其中已部署 gpt-4 系列模型。 有关模型部署的详细信息,请参阅资源部署指南

Microsoft Entra ID 先决条件

若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,你需要:

  • 安装使用 Microsoft Entra ID 进行无密钥身份验证所需的 Azure CLI
  • Cognitive Services User 角色分配给用户帐户。 可以在 Azure 门户中的“访问控制 (IAM)”“添加角色分配”下分配角色。>

设置

  1. 创建新文件夹 chat-quickstart,并使用以下命令转到快速入门文件夹:

    mkdir chat-quickstart && cd chat-quickstart
    
  2. 使用以下命令创建 package.json

    npm init -y
    
  3. 使用以下命令安装适用于 JavaScript 的 OpenAI 客户端库:

    npm install openai
    
  4. 对于推荐的无密码身份验证:

    npm install @azure/identity
    

检索资源信息

需要检索以下信息才能使用 Azure OpenAI 资源对应用程序进行身份验证:

变量名称
AZURE_OPENAI_ENDPOINT 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值将对应于在部署模型时为部署选择的自定义名称。 Azure 门户中的“资源管理”“模型部署”下提供了此值。>
OPENAI_API_VERSION 详细了解 API 版本

可以在代码中更改版本或使用环境变量。

详细了解无密钥身份验证,以及如何设置环境变量

警告

若要对 SDK 使用推荐的无密钥身份验证,请确保未设置 AZURE_OPENAI_API_KEY 环境变量。

创建一个示例应用程序

  1. 使用以下代码创建 index.js 文件:

    const { AzureOpenAI } = require("openai");
    const { 
      DefaultAzureCredential, 
      getBearerTokenProvider 
    } = require("@azure/identity");
    
    // You will need to set these environment variables or edit the following values
    const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "Your endpoint";
    const apiVersion = process.env.OPENAI_API_VERSION || "2024-05-01-preview";
    const deployment = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "gpt-4o"; //This must match your deployment name.
    
    // keyless authentication    
    const credential = new DefaultAzureCredential();
    const scope = "https://cognitiveservices.azure.com/.default";
    const azureADTokenProvider = getBearerTokenProvider(credential, scope);
    
    async function main() {
    
      const client = new AzureOpenAI({ endpoint, apiKey, azureADTokenProvider, deployment });
      const result = await client.chat.completions.create({
        messages: [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: "Does Azure OpenAI support customer managed keys?" },
        { role: "assistant", content: "Yes, customer managed keys are supported by Azure OpenAI?" },
        { role: "user", content: "Do other Azure services support this too?" },
        ],
        model: "",
      });
    
      for (const choice of result.choices) {
        console.log(choice.message);
      }
    }
    
    main().catch((err) => {
      console.error("The sample encountered an error:", err);
    });
    
    module.exports = { main };
    
  2. 使用以下命令登录到 Azure:

    az login
    
  3. 运行 JavaScript 文件。

    node index.js
    

输出

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

注意

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

清理资源

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

后续步骤

源代码 | 包 (npm) | 示例

注意

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

先决条件

Microsoft Entra ID 先决条件

若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,你需要:

  • 安装使用 Microsoft Entra ID 进行无密钥身份验证所需的 Azure CLI
  • Cognitive Services User 角色分配给用户帐户。 可以在 Azure 门户中的“访问控制 (IAM)”“添加角色分配”下分配角色。>

设置

  1. 创建新文件夹 chat-quickstart,并使用以下命令转到快速入门文件夹:

    mkdir chat-quickstart && cd chat-quickstart
    
  2. 使用以下命令创建 package.json

    npm init -y
    
  3. 使用以下命令将 package.json 更新为 ECMAScript:

    npm pkg set type=module
    
  4. 使用以下命令安装适用于 JavaScript 的 OpenAI 客户端库:

    npm install openai
    
  5. 对于推荐的无密码身份验证:

    npm install @azure/identity
    

检索资源信息

需要检索以下信息才能使用 Azure OpenAI 资源对应用程序进行身份验证:

变量名称
AZURE_OPENAI_ENDPOINT 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值将对应于在部署模型时为部署选择的自定义名称。 Azure 门户中的“资源管理”“模型部署”下提供了此值。>
OPENAI_API_VERSION 详细了解 API 版本

可以在代码中更改版本或使用环境变量。

详细了解无密钥身份验证,以及如何设置环境变量

警告

若要对 SDK 使用推荐的无密钥身份验证,请确保未设置 AZURE_OPENAI_API_KEY 环境变量。

创建一个示例应用程序

  1. 使用以下代码创建 index.ts 文件:

    import { AzureOpenAI } from "openai";
    import { 
      DefaultAzureCredential, 
      getBearerTokenProvider 
    } from "@azure/identity";
    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 || "Your endpoint";
    
    // Required Azure OpenAI deployment name and API version
    const apiVersion = process.env.OPENAI_API_VERSION || "2024-08-01-preview";
    const deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "gpt-4o-mini"; //This must match your deployment name.
    
    // keyless authentication    
    const credential = new DefaultAzureCredential();
    const scope = "https://cognitiveservices.azure.com/.default";
    const azureADTokenProvider = getBearerTokenProvider(credential, scope);
    
    function getClient(): AzureOpenAI {
      return new AzureOpenAI({
        endpoint,
        azureADTokenProvider,
        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 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);
    });
    
  2. 创建 tsconfig.json 文件以转译 TypeScript 代码,然后复制以下 ECMAScript 代码。

    {
        "compilerOptions": {
          "module": "NodeNext",
          "target": "ES2022", // Supports top-level await
          "moduleResolution": "NodeNext",
          "skipLibCheck": true, // Avoid type errors from node_modules
          "strict": true // Enable strict type-checking options
        },
        "include": ["*.ts"]
    }
    
  3. 从 TypeScript 转译到 JavaScript。

    tsc
    
  4. 使用以下命令运行代码:

    node index.js
    

输出

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

注意

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

清理资源

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

后续步骤

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

先决条件

设置

使用以下项安装 OpenAI Python 客户端库:

pip install openai

注意

此库由 OpenAI 维护。 请参阅发布历史记录,以跟踪库的最新更新。

检索密钥和终结点

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

变量名称
ENDPOINT 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到服务终结点。 或者,也可以通过 Azure AI Foundry 门户中的“部署”页找到该终结点。 示例终结点为:https://docs-test-001.openai.azure.com/
API-KEY 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 可以使用 KEY1KEY2

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

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

环境变量

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

重要说明

我们建议使用 Azure 资源托管标识进行 Microsoft Entra ID 身份验证,以避免将凭据存储在云端运行的应用程序中。

请谨慎使用 API 密钥。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。 如果使用 API 密钥,请将其安全地存储在 Azure Key Vault 中,定期轮换密钥,并使用基于角色的访问控制和网络访问限制来限制对 Azure Key Vault 的访问。 若要详细了解如何在应用中安全地使用 API 密钥,请参阅 API 密钥与 Azure Key Vault

有关 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 services support this too?"}
    ]
)

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

重要说明

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

  1. 使用快速入门文件中的 python 命令运行应用程序:

    python quickstart.py
    

输出

{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "Yes, most of the Azure 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 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 AI Foundry 中的 Azure OpenAI 模型,其中已部署 gpt-35-turbogpt-4 模型。 有关模型部署的详细信息,请参阅资源部署指南

设置

检索密钥和终结点

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

变量名称
ENDPOINT 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到服务终结点。 或者,也可以通过 Azure AI Foundry 门户中的“部署”页找到该终结点。 示例终结点为:https://docs-test-001.openai.azure.com/
API-KEY 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 可以使用 KEY1KEY2

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

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

环境变量

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

重要说明

我们建议使用 Azure 资源托管标识进行 Microsoft Entra ID 身份验证,以避免将凭据存储在云端运行的应用程序中。

请谨慎使用 API 密钥。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。 如果使用 API 密钥,请将其安全地存储在 Azure Key Vault 中,定期轮换密钥,并使用基于角色的访问控制和网络访问限制来限制对 Azure Key Vault 的访问。 若要详细了解如何在应用中安全地使用 API 密钥,请参阅 API 密钥与 Azure Key Vault

有关 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 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。 有关凭据安全性的详细信息,请参阅此 安全 文章。

输出

{"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, many other Azure services also support customer managed keys. Azure OpenAI offers 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 资源,可以删除该资源。 在删除资源之前,必须先删除所有已部署的模型。

后续步骤

先决条件

Microsoft Entra ID 先决条件

若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,你需要:

  • 安装使用 Microsoft Entra ID 进行无密钥身份验证所需的 Azure CLI
  • Cognitive Services User 角色分配给用户帐户。 可以在 Azure 门户中的“访问控制 (IAM)”“添加角色分配”下分配角色。>

检索资源信息

需要检索以下信息才能使用 Azure OpenAI 资源对应用程序进行身份验证:

变量名称
AZURE_OPENAI_ENDPOINT 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值将对应于在部署模型时为部署选择的自定义名称。 Azure 门户中的“资源管理”“模型部署”下提供了此值。>
OPENAI_API_VERSION 详细了解 API 版本

可以在代码中更改版本或使用环境变量。

详细了解无密钥身份验证,以及如何设置环境变量

创建新的 PowerShell 脚本

  1. 若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,请使用以下命令登录到 Azure:

    az login
    
  2. 创建一个名为 quickstart.ps1 的新 PowerShell 文件。 然后在你偏好的编辑器或 IDE 中打开该文件。

  3. 将 quickstart.ps1 的内容替换为以下代码。 需要将变量 engine 设置为部署 GPT-4o 模型时选择的部署名称。 输入模型名称将会导致错误,除非所选部署名称与基础模型名称相同。

    # Azure OpenAI metadata variables
    $openai = @{
       api_base    = $Env:AZURE_OPENAI_ENDPOINT
       api_version = '2024-10-21' # This can change in the future.
       name        = 'gpt-4o' # The name you chose for your model deployment.
    }
    
    # Use the recommended keyless authentication via bearer token.
    $headers = [ordered]@{
        #'api-key' = $Env:AZURE_OPENAI_API_KEY
        'Authorization' = "Bearer $($Env:DEFAULT_AZURE_CREDENTIAL_TOKEN)"
    }
    
    # Completion text
    $messages = @()
    $messages += @{
      role = 'system'
      content = 'You are a helpful assistant.'
    }
    $messages += @{
      role = 'user'
      content = 'Can I use honey as a substitute for sugar?'
    }
    $messages += @{
      role = 'assistant'
      content = 'Yes, you can use honey as a substitute for sugar.'
    }
    $messages += @{
      role = 'user'
      content = 'What other ingredients can I use as a substitute for sugar?'
    }
    
    # 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 机密管理。 有关凭据安全性的详细信息,请参阅此 安全 文章。

  4. 使用 PowerShell 运行脚本。 在此示例中,我们使用 -Depth 参数来确保输出不会被截断。

    ./quickstart.ps1 | ConvertTo-Json -Depth 4
    

输出

脚本的输出是一个 JSON 对象,其中包含来自 Azure OpenAI 的响应。 输出如下所示:

{
  "choices": [
    {
      "content_filter_results": {
        "custom_blocklists": {
          "filtered": false
        },
        "hate": {
          "filtered": false,
          "severity": "safe"
        },
        "protected_material_code": {
          "filtered": false,
          "detected": false
        },
        "protected_material_text": {
          "filtered": false,
          "detected": false
        },
        "self_harm": {
          "filtered": false,
          "severity": "safe"
        },
        "sexual": {
          "filtered": false,
          "severity": "safe"
        },
        "violence": {
          "filtered": false,
          "severity": "safe"
        }
      },
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "There are many alternatives to sugar that can be used in cooking and baking, depending on your dietary needs, taste preferences, and the type of recipe you're making. Here are some popular sugar substitutes:\n\n---\n\n### 1. **Natural Sweeteners**\n   - **Maple Syrup**: A natural sweetener with a rich, distinct flavor. Use about ¾ cup of maple syrup for every cup of sugar, and reduce the liquid in the recipe slightly.\n   - **Agave Nectar**: A liquid sweetener that’s sweeter than sugar. Use about ⅔ cup of agave nectar for each cup of sugar, and reduce the liquid in the recipe.\n   - **Coconut Sugar**: Made from the sap of the coconut palm, it has a mild caramel flavor. Substitute in a 1:1 ratio for sugar.\n   - **Molasses**: A by-product of sugar production, molasses is rich in flavor and best for recipes like gingerbread or barbecue sauce. Adjust quantities based on the recipe.\n   - **Stevia (Natural)**: Derived from the stevia plant, it's intensely sweet and available in liquid or powder form. Use sparingly, as a little goes a long way.\n\n---\n\n### 2. **Fruit-Based Sweeteners**\n   - **Ripe Bananas**: Mashed bananas work well for baking recipes like muffins or pancakes. Use about ½ cup of mashed banana for every cup of sugar and reduce the liquid slightly.\n   - **Applesauce**: Unsweetened applesauce adds sweetness and moisture to baked goods. Replace sugar in a 1:1 ratio, but reduce the liquid by ¼ cup.\n   - **Dates/Date Paste**: Blend dates with water to make a paste, which works well in recipes like energy bars, cakes, or smoothies. Use in a 1:1 ratio for sugar.\n   - **Fruit Juices (e.g., orange juice)**: Can be used to impart natural sweetness but is best suited for specific recipes like marinades or desserts.\n\n---\n\n### 3. **Artificial and Low-Calorie Sweeteners**\n   - **Erythritol**: A sugar alcohol with no calories. Substitute in equal amounts, but be careful as it may cause a cooling sensation in some recipes.\n   - **Xylitol**: Another sugar alcohol, often used in gum and candies. It’s a 1:1 sugar substitute but may affect digestion if consumed in large quantities.\n   - **Monk Fruit Sweetener**: A natural, calorie-free sweetener that’s significantly sweeter than sugar. Follow the product packaging for exact substitution measurements.\n   - **Aspartame, Sucralose, or Saccharin** (Artificial Sweeteners): Often used for calorie reduction in beverages or desserts. Follow package instructions for substitution.\n\n---\n\n### 4. **Other Natural Alternatives**\n   - **Brown Rice Syrup**: A sticky, malt-flavored syrup used in granolas or desserts. Substitute 1 ¼ cups of brown rice syrup for every cup of sugar.\n   - **Barley Malt Syrup**: A thick, dark syrup with a distinct flavor. It can replace sugar but might require recipe adjustments due to its strong taste.\n   - **Yacon Syrup**: Made from the root of the yacon plant, it’s similar in texture to molasses and has a mild sweetness.\n\n---\n\n### General Tips for Substituting Sugar:\n- **Adjust Liquids:** Many liquid sweeteners (like honey or maple syrup) require reducing the liquid in the recipe to maintain texture.\n- **Baking Powder Adjustment:** If replacing sugar with an acidic sweetener (e.g., honey or molasses), you might need to add a little baking soda to neutralize acidity.\n- **Flavor Changes:** Some substitutes, like molasses or coconut sugar, have distinct flavors that can influence the taste of your recipe.\n- **Browning:** Sugar contributes to caramelization and browning in baked goods. Some alternatives may yield lighter-colored results.\n\nBy trying out different substitutes, you can find what works best for your recipes!",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1742602230,
  "id": "chatcmpl-BDgjWjEboQ0z6r58pvSBgH842JbB2",
  "model": "gpt-4o-2024-11-20",
  "object": "chat.completion",
  "prompt_filter_results": [
    {
      "prompt_index": 0,
      "content_filter_results": {
        "custom_blocklists": {
          "filtered": false
        },
        "hate": {
          "filtered": false,
          "severity": "safe"
        },
        "jailbreak": {
          "filtered": false,
          "detected": false
        },
        "self_harm": {
          "filtered": false,
          "severity": "safe"
        },
        "sexual": {
          "filtered": false,
          "severity": "safe"
        },
        "violence": {
          "filtered": false,
          "severity": "safe"
        }
      }
    }
  ],
  "system_fingerprint": "fp_a42ed5ff0c",
  "usage": {
    "completion_tokens": 836,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 60,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 896
  }
}

注解

如果要查看原始输出,可以跳过 ConvertTo-Json 步骤。

./quickstart.ps1

输出如下所示:

choices               : {@{content_filter_results=; finish_reason=stop; index=0; logprobs=; message=}}
created               : 1742602727
id                    : chatcmpl-BDgrX0BF38mZuszFeyU1NKZSiRpSX
model                 : gpt-4o-2024-11-20
object                : chat.completion
prompt_filter_results : {@{prompt_index=0; content_filter_results=}}
system_fingerprint    : fp_b705f0c291
usage                 : @{completion_tokens=944; completion_tokens_details=; prompt_tokens=60; prompt_tokens_details=; total_tokens=1004}

可以编辑 powershell.ps1 脚本的内容以返回整个对象或特定属性。 例如,若要返回所返回的文本,可以将脚本的最后一行 (return $response) 替换为以下内容:

return $response.choices.message.content

然后再次运行脚本。

./quickstart.ps1

输出如下所示:

There are several ingredients that can be used as substitutes for sugar, depending on the recipe and your dietary preferences. Here are some popular options:

---

### **Natural Sweeteners**
1. **Maple Syrup**
   - Flavor: Rich and slightly caramel-like.
   - Use: Works well in baking, sauces, oatmeal, and beverages.
   - Substitution: Replace sugar in a 1:1 ratio but reduce the liquid in your recipe by about 3 tablespoons per cup of maple syrup.

2. **Agave Nectar**
   - Flavor: Mildly sweet, less pronounced than honey.
   - Use: Good for beverages, desserts, and dressings.
   - Substitution: Use about 2/3 cup of agave nectar for every 1 cup of sugar, and reduce other liquids slightly.

3. **Molasses**
   - Flavor: Strong, earthy, and slightly bitter.
   - Use: Perfect for gingerbread, cookies, and marinades.
   - Substitution: Replace sugar in equal amounts, but adjust for the strong flavor.

4. **Date Paste**
   - Flavor: Naturally sweet with hints of caramel.
   - Use: Works well in energy bars, smoothies, or baking recipes.
   - Substitution: Blend pitted dates with water to create paste (about 1:1 ratio). Use equal amounts in recipes.

5. **Coconut Sugar**
   - Flavor: Similar to brown sugar, mildly caramel-like.
   - Use: Excellent for baking.
   - Substitution: Replace sugar in a 1:1 ratio.

---

### **Low-Calorie Sweeteners**
1. **Stevia**
   - Flavor: Very sweet but can have a slightly bitter aftertaste.
   - Use: Works in beverages, desserts, and some baked goods.
   - Substitution: Use less—around 1 teaspoon of liquid stevia or 1/2 teaspoon stevia powder for 1 cup of sugar. Check the package for exact conversion.

2. **Erythritol**
   - Flavor: Similar to sugar but less sweet.
   - Use: Perfect for baked goods and beverages.
   - Substitution: Replace sugar using a 1:1 ratio, though you may need to adjust for less sweetness.

3. **Xylitol**
   - Flavor: Similar to sugar.
   - Use: Great for baking or cooking but avoid using it for recipes requiring caramelization.
   - Substitution: Use a 1:1 ratio.

---

### **Fruit-Based Sweeteners**
1. **Mashed Bananas**
   - Flavor: Sweet with a fruity note.
   - Use: Great for muffins, cakes, and pancakes.
   - Substitution: Use 1 cup mashed banana for 1 cup sugar, but reduce liquid slightly in the recipe.

2. **Applesauce**
   - Flavor: Mildly sweet.
   - Use: Excellent for baked goods like muffins or cookies.
   - Substitution: Replace sugar 1:1, but reduce other liquids slightly.

3. **Fruit Juice Concentrates**
   - Flavor: Sweet with fruity undertones.
   - Use: Works well in marinades, sauces, and desserts.
   - Substitution: Use equal amounts, but adjust liquid content.

---

### **Minimal-Processing Sugars**
1. **Raw Honey**
   - Flavor: Sweet with floral undertones.
   - Use: Good for baked goods and beverages.
   - Substitution: Replace sugar in a 1:1 ratio, but reduce other liquids slightly.

2. **Brown Rice Syrup**
   - Flavor: Mildly sweet with a hint of nuttiness.
   - Use: Suitable for baked goods and granola bars.
   - Substitution: Use 1-1/4 cups of syrup for 1 cup of sugar, and decrease liquid in the recipe.

---

### Tips for Substitution:
- Adjust for sweetness: Some substitutes are sweeter or less sweet than sugar, so amounts may need tweaking.
- Baking considerations: Sugar affects texture, browning, and moisture. If you replace it, you may need to experiment to get the desired result.
- Liquid adjustments: Many natural sweeteners are liquid, so you’ll often need to reduce the amount of liquid in your recipe.

Would you like help deciding the best substitute for a specific recipe?

了解消息结构

GPT-4 模型经过优化,可以处理格式化为对话的输入。 变量 messages 传递一组字典,这些字典在由系统、用户和助手划定的对话中具有不同角色。 系统消息可用于通过包含有关模型应如何响应的上下文或说明来启动模型。

GPT-4 操作指南深入介绍了与这些模型通信的选项。

清理资源

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

后续步骤