利用Azure OpenAI和Azure Cognitive Search打造定制聊天应用的教程

在数字化时代,人工智能(AI)已经成为许多企业和开发者的不可或缺的一部分。聊天机器人和对话式AI已经在各个领域中发挥着关键作用,从客户支持到虚拟助手,再到智能搜索引擎。如果您希望构建自己的聊天应用程序,同时希望这些应用程序能够根据您自己的数据提供更准确和迅速的回答,那么Azure OpenAI和Azure Cognitive Search的结合将为您提供强大的工具。

故事开端

假设您是一家企业的创始人,您希望为您的网站或应用程序添加一个智能聊天机器人,以提供更好的客户支持和信息检索体验。您希望这个聊天机器人不仅能够回答常见问题,还能够根据您自己的业务数据提供个性化的建议和信息。在寻找解决方案时,您发现了Azure OpenAI和Azure Cognitive Search的结合,这为您提供了一个强大的工具,可以实现这一目标。

教程内容

步骤1:准备工作

要开始使用Azure OpenAI和Azure Cognitive Search,您需要一些必要的前提条件:

  1. Azure OpenAI资源: 您需要在Azure门户中创建Azure OpenAI资源,并部署一个支持的聊天模型,例如GPT-3.5-Turbo或GPT-4。

  2. Azure Cognitive Search资源: 您需要创建Azure Cognitive Search资源,以便将您的数据与聊天模型连接起来。

  3. Azure Blob Storage资源: 您需要一个Azure Blob Storage资源来存储您的数据文件。

  4. 您的数据: 您需要将要用作数据的文档上传到Blob Storage,并使用Azure AI Studio创建一个索引。这将成为聊天模型的数据源。

步骤2:设置

首先,您需要安装必要的Python依赖项,以便与Azure OpenAI和Azure Cognitive Search进行交互。使用以下命令安装所需的依赖项:

! pip install "openai>=0.27.6"
! pip install python-dotenv

在这个示例中,我们使用dotenv库来加载环境变量。您需要在一个名为.env的文件中添加以下变量:

  • OPENAI_API_BASE - Azure OpenAI的终结点,可以在Azure门户中的“Keys and Endpoints”下找到。
  • OPENAI_API_KEY - Azure OpenAI的API密钥,可以在Azure门户中的“Keys and Endpoints”下找到。
  • SEARCH_ENDPOINT - Cognitive Search的终结点,可以在Azure门户中的Search资源的“Overview”中找到。
  • SEARCH_KEY - Cognitive Search的API密钥,可以在Azure门户中的Search资源的“Keys”下找到。
  • SEARCH_INDEX_NAME - 您使用自己的数据创建的索引的名称。

接下来,您可以使用以下代码来配置Azure OpenAI SDK,以便连接到Azure OpenAI服务:

import os
import openai
import dotenv

dotenv.load_dotenv()

openai.api_base = os.environ["OPENAI_API_BASE"]
openai.api_version = "2023-08-01-preview"

步骤3:身份验证

Azure OpenAI服务支持多种身份验证机制,包括API密钥和Azure凭据。根据您的身份验证选择,您可以使用以下代码中的其中一种方式进行身份验证。

使用API密钥进行身份验证

如果选择使用API密钥进行身份验证,请设置use_azure_active_directory标志为False,然后使用以下代码设置OpenAI SDK以使用Azure API密钥:

if not use_azure_active_directory:
    openai.api_type = 'azure'
    openai.api_key = os.environ["OPENAI_API_KEY"]

使用Microsoft Active Directory进行身份验证

如果选择使用Microsoft Active Directory进行身份验证,请使用以下代码安装azure-identity库,并设置use_azure_active_directory标志为True,然后使用以下代码设置OpenAI SDK以使用Azure Active Directory令牌:

! pip install azure-identity

from azure.identity import DefaultAzureCredential

if use_azure_active_directory:
    default_credential = DefaultAzureCredential()
    token = default_credential.get_token("https://cognitiveservices.azure.com/.default")

    openai.api_type = "azure_ad"
    openai.api_key = token.token

步骤4:定制聊天应用程序

现在,您已经完成了设置和身份验证,可以开始创建定制的聊天应用程序,该应用程序可以根据您自己的数据提供回答。

首先,您需要使用以下代码来设置Azure OpenAI SDK,以便使用自己的数据进行聊天:

import requests

def setup_byod(deployment_id: str) -> None:
    """Sets up the OpenAI Python SDK to use your own data for the chat endpoint.

    :param deployment_id: The deployment ID for the model to use with your own data.

    To remove this configuration, simply set openai.requestssession to None.
    """

    class BringYourOwnDataAdapter(requests.adapters.HTTPAdapter):

        def send(self, request, **kwargs):
            request.url = f"{openai.api_base}/openai/deployments/{deployment_id}/extensions/chat/completions?api-version={openai.api_version}"
            return super().send(request, **kwargs)

    session = requests.Session()

    # Mount a custom adapter which will use the extensions endpoint for any call using the given `deployment_id`
    session.mount(
        prefix=f"{openai.api_base}/openai/deployments/{deployment_id}",
        adapter=BringYourOwnDataAdapter()
    )

    if use_azure_active_directory:
        session.auth

 = None
    else:
        session.auth = (openai.api_key, '')

    openai.requests_session = session

# 使用您的部署ID来设置自己的数据
setup_byod("YOUR_DEPLOYMENT_ID")

接下来,您可以使用以下代码来与聊天模型进行交互,并提供自己的数据:

import openai

def chat_with_model(messages):
    response = openai.ChatCompletion.create(
        model="YOUR_MODEL_NAME",  # 使用您的模型名称,如"gpt-3.5-turbo"或"gpt-4"
        messages=messages
    )
    return response.choices[0].message["content"]

# 与聊天模型交互
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Tell me about our products."},
]

response = chat_with_model(messages)
print(response)

步骤5:与Azure Cognitive Search集成

最后,您可以使用Azure Cognitive Search来提供对自己的数据的强大搜索功能。您可以使用Azure Cognitive Search SDK或 REST API来查询您的索引,并将搜索结果与聊天模型集成到您的应用程序中。

以下是一个使用Azure Cognitive Search SDK进行搜索的示例代码:

from azure.search.documents.indexes import SearchIndexClient
from azure.core.credentials import AzureKeyCredential

search_endpoint = os.environ["SEARCH_ENDPOINT"]
search_api_key = os.environ["SEARCH_KEY"]
search_index_name = os.environ["SEARCH_INDEX_NAME"]

# 创建Search Index客户端
index_client = SearchIndexClient(endpoint=search_endpoint, index_name=search_index_name, credential=AzureKeyCredential(search_api_key))

# 构建搜索查询
search_query = "Your search query here"

# 执行搜索查询
results = index_client.search(search_text=search_query)

# 处理搜索结果
for result in results:
    print(result)

将搜索结果与聊天模型的回答合并,以创建一个功能强大的聊天应用程序,可以提供个性化的建议和信息检索功能。

总结

通过结合Azure OpenAI和Azure Cognitive Search,您可以构建自己的定制聊天应用程序,该应用程序可以根据您自己的数据提供回答,并具有强大的搜索功能。这将帮助您提供更好的客户支持和信息检索体验,同时提高用户满意度和效率。

请注意,本教程只是一个示例,您可以根据自己的需求和业务逻辑进行自定义。祝您成功构建您的聊天应用程序!

声明:本站所有文章,如无特殊说明或标注,均为本站(王大神)原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
教程

网络里面的对称加密协议:保护信息安全的关键

2023-11-1 0:45:32

教程

OpenAPI规范, GPT调用API, 智能API调用, 教程, Azure OpenAI

2023-11-1 10:32:58

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索