Azure 聊天完成模型与您自己的数据(预览版)

2023 年 9 月 11 日
在 Github 中打开

此示例展示了如何将 Azure OpenAI 服务模型与您自己的数据一起使用。此功能目前为预览版。

Azure OpenAI on your data 使您能够在您自己的数据上运行受支持的聊天模型,例如 GPT-3.5-Turbo 和 GPT-4,而无需训练或微调模型。在您的数据上运行模型使您能够以更高的准确性和速度在您的数据之上进行聊天和分析。Azure OpenAI on your data 的主要优势之一是其能够定制对话式 AI 的内容。由于该模型可以访问并引用特定来源以支持其响应,因此答案不仅基于其预训练的知识,还基于指定数据源中可用的最新信息。这种基础数据还有助于模型避免生成基于过时或不正确信息的响应。

Azure OpenAI on your own data 与 Azure AI 搜索(以前称为 Azure 认知搜索)一起使用,为知识检索提供了一个可自定义的、预构建的解决方案,可以从中构建对话式 AI 应用程序。要查看知识检索和语义搜索的替代方法,请查看有关向量数据库的 cookbook 示例。

工作原理

Azure OpenAI on your own data 将模型与您的数据连接,使其能够检索和利用数据,从而增强模型的输出。结合 Azure AI 搜索,根据用户输入和提供的对话历史记录,从指定的数据源检索数据。然后,数据被扩充并作为提示重新提交给模型,为模型提供可用于生成响应的上下文信息。

有关更多信息,请参阅 Azure OpenAI 服务的数据、隐私和安全性

先决条件

要开始使用,我们将介绍一些先决条件。

为了正确访问 Azure OpenAI 服务,我们需要在 Azure 门户中创建适当的资源(您可以在 Microsoft Docs 中查看有关如何执行此操作的详细指南)

要将您自己的数据与 Azure OpenAI 模型一起使用,您将需要

  1. Azure OpenAI 访问权限以及部署了聊天模型的资源(例如,GPT-3 或 GPT-4)
  2. Azure AI 搜索(以前称为 Azure 认知搜索)资源
  3. Azure Blob 存储资源
  4. 您的文档用作数据(请参阅数据源选项

有关如何将文档上传到 Blob 存储并使用 Azure AI Studio 创建索引的完整演练,请参阅此快速入门

设置

首先,我们安装必要的依赖项。

! pip install "openai>=1.0.0,<2.0.0"
! pip install python-dotenv

在本示例中,我们将使用 dotenv 加载我们的环境变量。要连接 Azure OpenAI 和搜索索引,应将以下变量以 KEY=VALUE 格式添加到 .env 文件中

  • AZURE_OPENAI_ENDPOINT - Azure OpenAI 端点。可以在 Azure 门户中 Azure OpenAI 资源的“密钥和终结点”下找到。
  • AZURE_OPENAI_API_KEY - Azure OpenAI API 密钥。可以在 Azure 门户中 Azure OpenAI 资源的“密钥和终结点”下找到。如果使用 Azure Active Directory 身份验证,则省略(请参阅下面的使用 Microsoft Active Directory 进行身份验证
  • SEARCH_ENDPOINT - AI 搜索端点。此 URL 可以在 Azure 门户中搜索资源的“概述”中找到。
  • SEARCH_KEY - AI 搜索 API 密钥。在 Azure 门户中搜索资源的“密钥”下找到。
  • SEARCH_INDEX_NAME - 您使用自己的数据创建的索引的名称。
import os
import openai
import dotenv

dotenv.load_dotenv()

身份验证

Azure OpenAI 服务支持多种身份验证机制,包括 API 密钥和 Azure Active Directory 令牌凭据。

use_azure_active_directory = False  # Set this flag to True if you are using Azure Active Directory

使用 API 密钥进行身份验证

要设置 OpenAI SDK 以使用Azure API 密钥,我们需要将 api_key 设置为与您的终结点关联的密钥(您可以在 Azure 门户“资源管理”下的“密钥和终结点”中找到此密钥)。您还可以在此处找到资源的终结点。

if not use_azure_active_directory:
    endpoint = os.environ["AZURE_OPENAI_ENDPOINT"]
    api_key = os.environ["AZURE_OPENAI_API_KEY"]
    # set the deployment name for the model we want to use
    deployment = "<deployment-id-of-the-model-to-use>"

    client = openai.AzureOpenAI(
        base_url=f"{endpoint}/openai/deployments/{deployment}/extensions",
        api_key=api_key,
        api_version="2023-09-01-preview"
    )

使用 Azure Active Directory 进行身份验证

现在让我们看看如何通过 Azure Active Directory 进行身份验证。我们将首先安装 azure-identity 库。此库将提供我们需要进行身份验证的令牌凭据,并通过 get_bearer_token_provider 帮助程序函数帮助我们构建令牌凭据提供程序。建议使用 get_bearer_token_provider 而不是向 AzureOpenAI 提供静态令牌,因为此 API 将自动为您缓存和刷新令牌。

有关如何使用 Azure OpenAI 设置 Azure Active Directory 身份验证的更多信息,请参阅文档

! pip install "azure-identity>=1.15.0"
from azure.identity import DefaultAzureCredential, get_bearer_token_provider

if use_azure_active_directory:
    endpoint = os.environ["AZURE_OPENAI_ENDPOINT"]
    api_key = os.environ["AZURE_OPENAI_API_KEY"]
    # set the deployment name for the model we want to use
    deployment = "<deployment-id-of-the-model-to-use>"

    client = openai.AzureOpenAI(
        base_url=f"{endpoint}/openai/deployments/{deployment}/extensions",
        azure_ad_token_provider=get_bearer_token_provider(DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"),
        api_version="2023-09-01-preview"
    )

注意:如果未提供 AzureOpenAI,则会从其对应的环境变量中推断出以下参数

  • 来自 AZURE_OPENAI_API_KEYapi_key
  • 来自 AZURE_OPENAI_AD_TOKENazure_ad_token
  • 来自 OPENAI_API_VERSIONapi_version
  • 来自 AZURE_OPENAI_ENDPOINTazure_endpoint

在本示例中,我们希望我们的模型基于 Azure AI 服务文档数据做出响应。按照之前共享的快速入门,我们已将markdown 文件添加到我们的搜索索引,该文件用于 Azure AI 服务和机器学习 文档页面。该模型现在已准备好回答有关 Azure AI 服务和机器学习的问题。

现在我们可以将 Azure on your own data 与聊天完成一起使用。在 dataSources 中提供我们的搜索端点、密钥和索引名称,现在向模型提出的任何问题都将以我们自己的数据为基础。响应中将提供一个额外的属性 context,以显示模型引用来回答问题的数据。

completion = client.chat.completions.create(
    messages=[{"role": "user", "content": "What are the differences between Azure Machine Learning and Azure AI services?"}],
    model=deployment,
    extra_body={
        "dataSources": [
            {
                "type": "AzureCognitiveSearch",
                "parameters": {
                    "endpoint": os.environ["SEARCH_ENDPOINT"],
                    "key": os.environ["SEARCH_KEY"],
                    "indexName": os.environ["SEARCH_INDEX_NAME"],
                }
            }
        ]
    }
)
print(f"{completion.choices[0].message.role}: {completion.choices[0].message.content}")

# `context` is in the model_extra for Azure
print(f"\nContext: {completion.choices[0].message.model_extra['context']['messages'][0]['content']}")

如果您希望从模型流式传输响应,您可以传递 stream=True 关键字参数

response = client.chat.completions.create(
    messages=[{"role": "user", "content": "What are the differences between Azure Machine Learning and Azure AI services?"}],
    model=deployment,
    extra_body={
        "dataSources": [
            {
                "type": "AzureCognitiveSearch",
                "parameters": {
                    "endpoint": os.environ["SEARCH_ENDPOINT"],
                    "key": os.environ["SEARCH_KEY"],
                    "indexName": os.environ["SEARCH_INDEX_NAME"],
                }
            }
        ]
    },
    stream=True,
)

for chunk in response:
    delta = chunk.choices[0].delta

    if delta.role:
        print("\n"+ delta.role + ": ", end="", flush=True)
    if delta.content:
        print(delta.content, end="", flush=True)
    if delta.model_extra.get("context"):
        print(f"Context: {delta.model_extra['context']}", end="", flush=True)