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

快速入门:自定义问题解答

注意

Azure Open AI On Your Data 利用大型语言模型 (LLM) 生成与自定义问题解答类似的结果。 如果要将现有的自定义问题解答项目连接到 Azure Open AI On Your Data,请查看我们的指南

注意

是否希望从 QnA Maker 迁移工作负载? 有关功能比较和迁移步骤的信息,请参阅迁移指南

开始使用自定义问答客户端库。 请按照以下步骤安装程序包并试用基本任务的示例代码。

你可以从自己的内容(例如 FAQ 或产品手册)创建自定义问题解答项目。 本文包含的一个示例演示了如何从产品手册创建自定义问题解答项目来回答问题。

先决条件

  • 如果没有 Azure 订阅,请在开始之前创建一个免费帐户
  • 启用了自定义问答功能的语言资源。 请记住你在创建资源时选择的 Microsoft Entra ID、订阅、语言资源名称。

创建你的第一个自定义问题解答项目

  1. 使用你的 Azure 凭据登录到 Language Studio

  2. 向下滚动到“回答问题”部分,然后选择“打开自定义问答”。

    打开自定义问题解答

  3. 如果资源尚未连接到 Azure 搜索,请选择连接到 Azure 搜索。 这会打开新的浏览器选项卡,显示 Azure 门户中资源的“功能”窗格。

    连接到 Azure 搜索

  4. 选择“启用自定义问答”,选择要链接到的 Azure 搜索资源,然后选择“应用”。

    启用自定义问题解答

  5. 返回到“Language Studio”选项卡。可能需要刷新此页面,才能将更改注册到资源。 选择“创建新项目”。

  6. 选择“我想为在此资源中创建的所有项目设置语言”选项,选择“英语”,然后选择“下一步”。>>

  7. 输入项目名称“示例项目”、说明“我的第一个问答项目”,并保留默认答案及“未找到答案”的设置。

  8. 查看你的选择,然后选择“创建项目”

  9. 在“管理源”页面中,选择“添加” >“源 URL”。

  10. 选择“添加 URL”并输入以下值,然后选择“添加全部”:

    URL 名称 URL 值
    Surface Book 用户指南 https://download.microsoft.com/download/7/B/1/7B10C82E-F520-4080-8516-5CF0D803EEE0/surface-book-user-guide-EN.pdf

    提取过程需要一些时间来读取文档并确定问题和解答。

    成功添加源后,可以编辑源内容以添加更多自定义问题答案集。

测试项目

  1. 选择源的链接,这将打开“编辑项目”页面。

  2. 从菜单栏中选择“测试”,输入问题“如何设置我的 Surface Book?”。 将基于从你的源 URL 自动识别和提取的问题答案对生成答案:

    测试问题聊天界面

    如果选中“包含简短问题响应”框,则当你提出问题时,还会在测试窗格中看到准确答案(如果可用)和答案段落。

  3. 选择“检查”,更详细地检查响应。 使用测试窗口,在部署项目前测试你对项目的更改。

    查看置信区间

    从“检查”界面,可以查看此响应解答问题的置信度,并直接编辑给定的问题和答案响应对。

部署项目

  1. 选择“部署项目”图标以进入部署项目菜单。

    部署项目

    部署项目时,项目的内容会从 Azure 搜索中的 test 索引移动到 prod 索引。

  2. 选择“部署”,然后在出现提示时再次选择“部署”。

    成功部署

    你的项目现已成功部署。 你可以使用终结点,在你自己的自定义解答应用程序中或机器人中回答问题。

先决条件

  • 最新版本的 cURL。 快速入门中使用了 cURL 文档中所述的多个命令行开关。
  • Azure 订阅 - 免费创建订阅
  • 自定义问题解答需要启用了自定义问题解答功能的语言资源来生成 API 密钥和终结点。
    • 部署语言资源后,选择“转到资源”。 你需要从创建的资源获取密钥和终结点,以便连接到 API。 稍后在快速入门中将密钥和终结点粘贴到下方的代码中。
  • 要使用 Azure CLI 创建语言资源,请提供以下额外属性:--api-properties qnaAzureSearchEndpointId=/subscriptions/<azure-subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Search/searchServices/<azure-search-service-name> qnaAzureSearchEndpointKey=<azure-search-service-auth-key>
  • 要查询的现有项目。 如果尚未设置项目,可以按照 Language Studio 快速入门 中的说明进行操作。 或者添加将此 Surface 用户指南 URL 用作数据源的项目。

设置

创建环境变量

应用程序必须经过身份验证才能发送 API 请求。 对于生产,请使用安全的方式存储和访问凭据。 在此示例中,你将凭据写入运行应用程序的本地计算机上的环境变量。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性一文。

若要为语言资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  1. 若要设置 LANGUAGE_KEY 环境变量,请将 your-key 替换为资源的其中一个密钥。
  2. 若要设置 LANGUAGE_ENDPOINT 环境变量,请将 your-endpoint 替换为资源的终结点。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

注意

如果只需要访问当前正在运行的控制台中的环境变量,则可以使用 set(而不是 setx)设置环境变量。

添加环境变量后,可能需要重启任何正在运行的、需要读取环境变量的程序(包括控制台窗口)。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

查询项目

从项目生成答案

要使用 REST API 和 cURL 查询自定义问题解答项目,需要以下信息:

变量名称
Endpoint 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 也可以在“Language Studio”>“问题解答”>“部署项目”>“获取预测 URL”中查找该值。 示例终结点为:https://southcentralus.api.cognitive.microsoft.com/
API-Key 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 可以使用 Key1 或 Key2。 应始终具有两个有效密钥,以实现安全密钥轮换而无需停机。 也可以在“Language Studio”>“问题解答”>“部署项目”>“获取预测 URL”中查找该值。 此密钥值是示例请求的一部分。
Project 自定义问题解答项目的名称。
Deployment 有两个可能的值:testproductionproduction 依赖于你已从“Language Studio”>“问题解答”>“部署项目”部署项目。

cURL 命令将从 BASH shell 执行。 请使用自己的资源名称、资源密钥、JSON 值和 JSON 大小编辑此命令。

curl -X POST -H "Ocp-Apim-Subscription-Key: $LANGUAGE_KEY" -H "Content-Type: application/json" -d '{
  "question": "How much battery life do I have left?"
  }'  '$LANGUAGE_ENDPOINT.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName={YOUR_PROJECT_NAME}&api-version=2021-10-01&deploymentName={DEPLOYMENT_NAME}'

运行上述代码时,如果使用的是先决条件数据源,将会获得如下所示的答案:

{
"answers": [
    {
      "questions": [
        "Check battery level"
      ],
      "answer": "If you want to see how much battery you have left, go to **Start  **> **Settings  **> **Devices  **> **Bluetooth & other devices  **, then find your pen. The current battery level will appear under the battery icon.",
      "confidenceScore": 0.9185,
      "id": 101,
      "source": "https://support.microsoft.com/en-us/surface/how-to-use-your-surface-pen-8a403519-cd1f-15b2-c9df-faa5aa924e98",
      "metadata": {},
      "dialog": {
        "isContextOnly": false,
        "prompts": []
      }
    }
  ]
}

confidenceScore 返回的值介于 0 到 1 之间。 可以将此值视为百分比并乘以 100,因此置信度为 0.9185 表示,根据项目,自定义问题解答对这是问题的正确答案有 91.85% 的信心。

如果要排除置信度分数低于特定阈值的答案,可添加 confidenceScoreThreshold 参数。

curl -X POST -H "Ocp-Apim-Subscription-Key: $LANGUAGE_KEY" -H "Content-Type: application/json" -d '{
  "question": "How much battery life do I have left?",
  "confidenceScoreThreshold": "0.95",
  }'  '$LANGUAGE_ENDPOINT.api.cognitive.microsoft.com//language/:query-knowledgebases?projectName=Sample-project&api-version=2021-10-01&deploymentName={DEPLOYMENT_NAME}'

由于根据上次的代码执行结果,我们已知道置信度分数是:.9185,因此将阈值设置为 .95 将导致返回默认答案

{
  "answers": [
    {
      "questions": [],
      "answer": "No good match found in KB",
      "confidenceScore": 0.0,
      "id": -1,
      "metadata": {}
    }
  ]
}

在没有项目的情况下查询文本

还可以通过预生成的自定义问题解答 REST API(通过 query-text 调用)在没有项目的情况下使用自定义问题解答。 在这种情况下,需要为问答功能提供问题和要在发送请求时用于搜索答案的相关文本记录。

对于此示例,只需修改 API KEYENDPOINT 变量。

curl -X POST -H "Ocp-Apim-Subscription-Key: $LANGUAGE_KEY" -H "Content-Type: application/json" -d '{
"question":"How long does it takes to charge a surface?",
"records":[
{"id":"doc1","text":"Power and charging.It takes two to four hours to charge the Surface Pro 4 battery fully from an empty state. It can take longer if you\u0027re using your Surface for power-intensive activities like gaming or video streaming while you\u0027re charging it"},
{"id":"doc2","text":"You can use the USB port on your Surface Pro 4 power supply to charge other devices, like a phone, while your Surface charges. The USB port on the power supply is only for charging, not for data transfer. If you want to use a USB device, plug it into the USB port on your Surface."}],
"language":"en",
"stringIndexType":"Utf16CodeUnit"
}'  '$LANGUAGE_ENDPOINT.api.cognitive.microsoft.com/language/:query-text?&api-version=2021-10-01'

此示例将返回以下结果:

{  
"answers": [
    {
      "answer": "Power and charging.It takes two to four hours to charge the Surface Pro 4 battery fully from an empty state. It can take longer if you're using your Surface for power-intensive activities like gaming or video streaming while you're charging it",
      "confidenceScore": 0.9118788838386536,
      "id": "doc1",
      "answerSpan": {
        "text": "two to four hours",
        "confidenceScore": 0.9850527,
        "offset": 27,
        "length": 18
      },
      "offset": 0,
      "length": 243
    },
    {
      "answer": "It can take longer if you're using your Surface for power-intensive activities like gaming or video streaming while you're charging it",
      "confidenceScore": 0.052793052047491074,
      "id": "doc1",
      "answerSpan": {
        "text": "longer",
        "confidenceScore": 0.6694634,
        "offset": 11,
        "length": 7
      },
      "offset": 109,
      "length": 134
    },
    {
      "answer": "You can use the USB port on your Surface Pro 4 power supply to charge other devices, like a phone, while your Surface charges. The USB port on the power supply is only for charging, not for data transfer. If you want to use a USB device, plug it into the USB port on your Surface.",
      "confidenceScore": 0.017600709572434425,
      "id": "doc2",
      "answerSpan": {
        "text": "USB port on your Surface Pro 4 power supply to charge other devices, like a phone, while your Surface charges. The USB port on the power supply is only for charging",
        "confidenceScore": 0.1544854,
        "offset": 15,
        "length": 165
      },
      "offset": 0,
      "length": 280
    }
  ]
}

使用这一有关适用于 .NET 的自定义问题解答客户端库的快速入门,可以:

  • 从项目获取答案。
  • 从与问题一起发送的文本正文中获取答案。
  • 获取问题答案的置信度分数。

参考文档 | 包 (NuGet) | 其他示例 | 库源代码

先决条件

  • Azure 订阅 - 免费创建订阅
  • Visual Studio IDE 或最新版本的 .NET Core
  • 自定义问题解答需要启用了自定义问题解答功能的语言资源来生成 API 密钥和终结点。
    • 部署语言资源后,选择“转到资源”。 你需要从创建的资源获取密钥和终结点,以便连接到 API。 稍后在快速入门中将密钥和终结点粘贴到下方的代码中。
  • 要使用 Azure CLI 创建语言资源,请提供以下额外属性:--api-properties qnaAzureSearchEndpointId=/subscriptions/<azure-subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Search/searchServices/<azure-search-service-name> qnaAzureSearchEndpointKey=<azure-search-service-auth-key>
  • 要查询的现有项目。 如果尚未设置项目,可以按照 Language Studio 快速入门 中的说明进行操作。 或者添加将此 Surface 用户指南 URL 用作数据源的项目。

设置

创建环境变量

应用程序必须经过身份验证才能发送 API 请求。 对于生产,请使用安全的方式存储和访问凭据。 在此示例中,你将凭据写入运行应用程序的本地计算机上的环境变量。

提示

请不要直接在代码中包含密钥,并且绝不公开发布密钥。 有关 Azure Key Vault 等更多身份验证选项,请参阅 Azure AI 服务安全性一文。

若要为语言资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。

  1. 若要设置 LANGUAGE_KEY 环境变量,请将 your-key 替换为资源的其中一个密钥。
  2. 若要设置 LANGUAGE_ENDPOINT 环境变量,请将 your-endpoint 替换为资源的终结点。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

注意

如果只需要访问当前正在运行的控制台中的环境变量,则可以使用 set(而不是 setx)设置环境变量。

添加环境变量后,可能需要重启任何正在运行的、需要读取环境变量的程序(包括控制台窗口)。 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。

CLI

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,使用 dotnet new 命令创建名为 question-answering-quickstart 的新控制台应用。 此命令将创建包含单个源文件的简单“Hello World”C# 项目:program.cs

dotnet new console -n question-answering-quickstart

将目录更改为新创建的应用文件夹。 可使用以下代码生成应用程序:

dotnet build

生成输出不应包含警告或错误。

...
Build succeeded.
 0 Warning(s)
 0 Error(s)
...

在应用程序目录中,使用以下命令安装适用于 .NET 的自定义问答客户端库:

dotnet add package Azure.AI.Language.QuestionAnswering

查询项目

从项目生成答案

以下示例允许使用 GetAnswers 查询项目,从而获得问题的答案。

需要更新以下代码,并为以下变量提供你自己的值。

变量名称
endpoint 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 也可以在“Language Studio”>“问题解答”>“部署项目”>“获取预测 URL”中查找该值。 示例终结点为:https://southcentralus.api.cognitive.microsoft.com/
credential 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 可以使用 Key1 或 Key2。 应始终具有两个有效密钥,以实现安全密钥轮换而无需停机。 也可以在“Language Studio”>“问题解答”>“部署项目”>“获取预测 URL”中查找该值。 此密钥值是示例请求的一部分。
projectName 自定义问题解答项目的名称。
deploymentName 有两个可能的值:testproductionproduction 依赖于你已从“Language Studio”>“问题解答”>“部署项目”部署项目。

重要

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。

从项目目录中,打开 Program.cs 文件,并将其内容替换为以下代码:

using Azure;
using Azure.AI.Language.QuestionAnswering;
using System;

namespace question_answering
{
    class Program
    {
        static void Main(string[] args)
        {

            // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
            Uri endpoint = new Uri("LANGUAGE_ENDPOINT");
            AzureKeyCredential credential = new AzureKeyCredential("LANGUAGE_KEY");
            string projectName = "{YOUR-PROJECT-NAME}";
            string deploymentName = "production";

            string question = "How long should my Surface battery last?";

            QuestionAnsweringClient client = new QuestionAnsweringClient(endpoint, credential);
            QuestionAnsweringProject project = new QuestionAnsweringProject(projectName, deploymentName);

            Response<AnswersResult> response = client.GetAnswers(question, project);

            foreach (KnowledgeBaseAnswer answer in response.Value.Answers)
            {
                Console.WriteLine($"Q:{question}");
                Console.WriteLine($"A:{answer.Answer}");
            }
        }
    }
}

虽然我们对示例中的变量进行了硬编码,但是, 对于生产环境,请考虑使用安全的方法来存储和访问凭据。 例如,Azure 密钥保管库可提供安全的密钥存储。

使用上面的代码更新 Program.cs 并将其中的变量值替换为正确的变量值后, 从应用程序目录使用 dotnet run 命令运行应用程序。

dotnet run

响应将如下所示:

Q: How much battery life do I have left?
A: If you want to see how much battery you have left, go to **Start  **> **Settings  **> **Devices  **> **Bluetooth & other devices  **, then find your pen. The current battery level will appear under the battery icon.

若要了解自定义问题解答功能对“这是正确的回答”有多大的信心,请在现有 print 语句下添加其他 print语句:

Console.WriteLine($"Q:{question}");
Console.WriteLine($"A:{answer.Answer}");
Console.WriteLine($"({answer.Confidence})"); // add this line

如果再次执行 dotnet run,将会收到带有置信度分数的结果:

Q:How much battery life do I have left?
A:If you want to see how much battery you have left, go to **Start  **> **Settings  **> **Devices  **> **Bluetooth & other devices  **, then find your pen. The current battery level will appear under the battery icon.
(0.9185)

置信度分数返回介于 0 和 1 之间的值。 可以将此值视为百分比并乘以 100,因此置信度为 0.9185 表示,根据项目,自定义问题解答对这是问题的正确答案有 91.85% 的信心。

如果要排除置信度分数低于特定阈值的答案,可使用 AnswerOptions 添加 ConfidenceScoreThreshold 属性。

QuestionAnsweringClient client = new QuestionAnsweringClient(endpoint, credential);
QuestionAnsweringProject project = new QuestionAnsweringProject(projectName, deploymentName);
AnswersOptions options = new AnswersOptions(); //Add this line
options.ConfidenceThreshold = 0.95; //Add this line

Response<AnswersResult> response = client.GetAnswers(question, project, options); //Add the additional options parameter

由于根据上次的代码执行结果,我们已知道置信度分数是:.9185,因此将阈值设置为 .95 将导致返回默认答案

Q:How much battery life do I have left?
A:No good match found in KB
(0)

在没有项目的情况下查询文本

还可以通过 GetAnswersFromText 在没有项目的情况下使用自定义问题解答。 在这种情况下,需要为自定义问题解答功能提供问题和要在发送请求时用于搜索答案的相关文本记录。

对于此示例,只需修改 endpointcredential 变量。

using Azure;
using Azure.AI.Language.QuestionAnswering;
using System;
using System.Collections.Generic;


namespace questionansweringcsharp
{
    class Program
    {
        static void Main(string[] args)
        {

            Uri endpoint = new Uri("https://{YOUR-ENDPOINT}.api.cognitive.microsoft.com/");
            AzureKeyCredential credential = new AzureKeyCredential("YOUR-LANGUAGE-RESOURCE-KEY");
            QuestionAnsweringClient client = new QuestionAnsweringClient(endpoint, credential);

            IEnumerable<TextDocument> records = new[]
            {
                new TextDocument("doc1", "Power and charging.It takes two to four hours to charge the Surface Pro 4 battery fully from an empty state. " +
                         "It can take longer if you're using your Surface for power-intensive activities like gaming or video streaming while you're charging it"),
                new TextDocument("doc2", "You can use the USB port on your Surface Pro 4 power supply to charge other devices, like a phone, while your Surface charges. " +
                         "The USB port on the power supply is only for charging, not for data transfer. If you want to use a USB device, plug it into the USB port on your Surface."),
            };

            AnswersFromTextOptions options = new AnswersFromTextOptions("How long does it takes to charge a surface?", records);
            Response<AnswersFromTextResult> response = client.GetAnswersFromText(options);

           foreach (TextAnswer answer in response.Value.Answers)
            {
                if (answer.Confidence > .9)
                {
                    string BestAnswer = response.Value.Answers[0].Answer;

                    Console.WriteLine($"Q:{options.Question}");
                    Console.WriteLine($"A:{BestAnswer}");
                    Console.WriteLine($"Confidence Score: ({response.Value.Answers[0].Confidence:P2})"); //:P2 converts the result to a percentage with 2 decimals of accuracy. 
                    break;
                }
                else
                {
                    Console.WriteLine($"Q:{options.Question}");
                    Console.WriteLine("No answers met the requested confidence score.");
                    break;
                }
            }

        }
    }
}

若要运行上面的代码,请将 Program.cs 替换为上述脚本块的内容,并修改 endpointcredential 变量,使其与已作为先决条件的一部分创建的语言资源相对应。

在这种情况下,我们将循环访问所有的响应,并仅返回具有大于 0.9 的最高置信度分数的响应。 了解有关 GetAnswersFromText 的可用选项的详细信息。

使用这一有关适用于 Python 的自定义问题解答客户端库的快速入门,可以:

  • 从项目获取答案。
  • 从与问题一起发送的文本正文中获取答案。
  • 获取问题答案的置信度分数。

参考文档 | 包 (PyPI) | 其他示例 | 库源代码

先决条件

  • Azure 订阅 - 免费创建订阅
  • Python 3.x
  • 自定义问题解答需要启用了自定义问题解答功能的语言资源来生成 API 密钥和终结点。
    • 部署语言资源后,选择“转到资源”。 需要从创建的资源获取密钥和终结点,以便连接到 API。 稍后在快速入门中将密钥和终结点粘贴到下方的代码中。
  • 要使用 Azure CLI 创建语言资源,请提供以下其他属性:--api-properties qnaAzureSearchEndpointId=/subscriptions/<azure-subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Search/searchServices/<azure-search-service-name> qnaAzureSearchEndpointKey=<azure-search-service-auth-key>
  • 要查询的现有项目。 如果尚未设置项目,可以按照 Language Studio 快速入门 中的说明进行操作。 或者添加将此 Surface 用户指南 URL 用作数据源的项目。

设置

安装客户端库

在安装 Python 后,可以通过以下命令安装客户端库:

pip install azure-ai-language-questionanswering

查询项目

从项目生成答案

以下示例允许使用 get_answers 查询项目,从而获得问题的答案。 可以将此代码复制到专用 .py 文件中,或者复制到 Jupyter Notebook/Lab 中的单元格。

需要更新以下代码,并为以下变量提供你自己的值。

变量名称
endpoint 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 也可以在“Language Studio”>“问题解答”>“部署项目”>“获取预测 URL”中查找该值。 示例终结点为:https://southcentralus.api.cognitive.microsoft.com/
credential 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 可以使用 Key1 或 Key2。 应始终具有两个有效密钥,以实现安全密钥轮换而无需停机。 也可以在“Language Studio”>“问题解答”>“部署项目”>“获取预测 URL”中查找该值。 此密钥值是示例请求的一部分。
knowledge_base_project 问答项目的名称。
deployment 有两个可能的值:testproductionproduction 依赖于你已从“Language Studio”>“问题解答”>“部署项目”部署项目。

重要

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文

from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering import QuestionAnsweringClient

endpoint = "https://{YOUR-ENDPOINT}.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("{YOUR-LANGUAGE-RESOURCE-KEY}")
knowledge_base_project = "{YOUR-PROJECT-NAME}"
deployment = "production"

def main():
    client = QuestionAnsweringClient(endpoint, credential)
    with client:
        question="How much battery life do I have left?"
        output = client.get_answers(
            question = question,
            project_name=knowledge_base_project,
            deployment_name=deployment
        )
    print("Q: {}".format(question))
    print("A: {}".format(output.answers[0].answer))

if __name__ == '__main__':
    main()

不过,我们对示例中的变量进行了硬编码。 对于生产环境,请考虑使用安全的方法来存储和访问凭据。 例如,Azure 密钥保管库可提供安全的密钥存储。

运行上述代码时,如果使用的是先决条件中的数据源,你会获得如下所示的答案:

Q: How much battery life do I have left?
A: If you want to see how much battery you have left, go to **Start  **> **Settings  **> **Devices  **> **Bluetooth & other devices  **, then find your pen. The current battery level will appear under the battery icon.

若要了解自定义问题解答功能对“这是正确的回答”有多大的信心,请在现有 print 语句下再添加一个 print 语句:

print("Q: {}".format(question))
print("A: {}".format(output.answers[0].answer))
print("Confidence Score: {}".format(output.answers[0].confidence)) # add this line 

现在,你将获得一个具有置信度分数的结果:

Q: How much battery life do I have left?
A: If you want to see how much battery you have left, go to **Start  **> **Settings  **> **Devices  **> **Bluetooth & other devices  **, then find your pen. The current battery level will appear under the battery icon.
Confidence Score: 0.9185

置信度分数返回介于 0 和 1 之间的值。 可以将此值视为百分比并乘以 100,因此置信度为 0.9185 表示,根据项目,自定义问题解答对这是问题的正确答案有 91.85% 的信心。

如果要排除置信度分数低于特定阈值的答案,可修改 AnswerOptions 以添加 confidence_threshold 参数。

        output = client.get_answers(
            confidence_threshold = 0.95, #add this line
            question = question,
            project_name=knowledge_base_project,
            deployment_name=deployment
        )

由于根据上次的代码执行结果,我们已知道置信度分数是 .9185,因此将阈值设置为 .95 将导致返回默认答案

Q: How much battery life do I have left?
A: No good match found in KB
Confidence Score: 0.0

在没有项目的情况下查询文本

还可以通过 get_answers_from_text 在没有项目的情况下使用自定义问题解答。 在这种情况下,需要为自定义问题解答功能提供问题和要在发送请求时用于搜索答案的相关文本记录。

对于此示例,只需修改 endpointcredential 变量。

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering import QuestionAnsweringClient
from azure.ai.language.questionanswering import models as qna

endpoint = "https://{YOUR-ENDPOINT}.api.cognitive.microsoft.com/"
credential = AzureKeyCredential("YOUR-LANGUAGE-RESOURCE-KEY")

def main():
    client = QuestionAnsweringClient(endpoint, credential)
    with client:
        question="How long does it takes to charge a surface?"
        input = qna.AnswersFromTextOptions(
            question=question,
            text_documents=[
                "Power and charging. It takes two to four hours to charge the Surface Pro 4 battery fully from an empty state. " +
                "It can take longer if you're using your Surface for power-intensive activities like gaming or video streaming while you're charging it.",
                "You can use the USB port on your Surface Pro 4 power supply to charge other devices, like a phone, while your Surface charges. " +
                "The USB port on the power supply is only for charging, not for data transfer. If you want to use a USB device, plug it into the USB port on your Surface.",
            ]
        )


        output = client.get_answers_from_text(input)

    best_answer = [a for a in output.answers if a.confidence > 0.9][0]
    print(u"Q: {}".format(input.question))
    print(u"A: {}".format(best_answer.answer))
    print("Confidence Score: {}".format(output.answers[0].confidence))

if __name__ == '__main__':
    main()

可以将此代码复制到专用 .py 文件中,或者复制到 Jupyter Notebook/Lab 中的新单元格。 此示例返回以下结果:

Q: How long does it takes to charge surface?
A: Power and charging. It takes two to four hours to charge the Surface Pro 4 battery fully from an empty state. It can take longer if you're using your Surface for power-intensive activities like gaming or video streaming while you're charging it.
Confidence Score: 0.9254655838012695

在这种情况下,我们将循环访问所有的响应,并仅返回具有大于 0.9 的最高置信度分数的响应。 若要详细了解 get_answers_from_text 的可用选项,请查看 AnswersFromTextOptions 参数

清理资源

如果想要清理并移除 Azure AI 服务订阅,可以删除资源或资源组。 删除资源组同时也会删除与之相关联的任何其他资源。

探索 REST API

若要了解如何自动执行自定义问题解答管道,请参阅 REST API 文档。 目前只能通过 REST API 获取创作功能:

后续步骤