你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
本快速入门将指导你完成在 Azure AI Foundry 中创建、测试和部署自定义问答 (CQA) 项目所需的基本步骤。 无论你是从 Language Studio 迁移过来,还是从零开始,本快速入门都适合你。 本快速入门提供清晰可行的说明,助力实现快速且成功的 CQA 项目部署。
注意
- 如果已有 Azure AI 语言或多服务资源(无论是单独使用还是通过 Language Studio 使用),则可以在 Azure AI Foundry 门户中继续使用这些现有语言资源。 有关详细信息,请参阅 如何在 Azure AI Foundry 门户中使用 Azure AI 服务。
- 强烈建议在 AI Foundry 中使用 Azure AI Foundry 资源;但是,也可以使用语言资源按照这些说明进行操作。
先决条件
在开始之前,需要以下资源和权限:
- 有效的 Azure 订阅。 如果没有,请免费创建一个。
- 必备权限。 确保在订阅级别将负责建立帐户和项目的人员分配为 Azure AI 帐户拥有者角色。 若在订阅范围内具有 参与者 或 认知服务参与者 角色,也可以满足此要求。 有关详细信息,请参阅基于角色的访问控制(RBAC)。
- Azure AI Foundry 资源或 Azure AI 语言资源。
- Azure AI 搜索资源(访问 CQA 时需要)。 有关如何连接 Azure AI 搜索资源的详细信息,请参阅在 AI Foundry 中配置连接
- 在 Azure AI Foundry 中创建的 Foundry 项目。 有关详细信息, 请参阅创建 AI Foundry 项目。
开始
导航到 Azure AI Foundry。
如果尚未登录,门户会提示你使用 Azure 凭据执行此作。
登录后,可以在 Azure AI Foundry 中创建或访问现有项目。
如果尚未开始执行此任务的项目,请选择它。
创建 CQA 微调任务
在 Azure AI Foundry 中,微调任务充当 CQA 解决方案的工作区。 以前,微调任务被称为 CQA 项目。 在较早的 CQA 文档中,这两个术语可能会被交替使用。
选择要用于本快速入门的 Azure AI Foundry 项目后,请从左侧导航菜单中选择“微调”。
在主窗口中,选择“AI 服务微调”选项卡,然后选择“+ 微调”按钮。
在“创建服务微调”窗口中,选择“自定义问答”选项卡,然后选择“下一步”。
在“创建 CQA 微调任务”窗口中选择“连接的 Azure AI 搜索资源”。 有关详细信息,请参阅配置 Azure 资源连接。
接下来,填写“名称”和“语言”字段。 对于这个项目,可以保留“未返回答案时的默认答案”字段(未找到答案)。
选择“创建”按钮。
添加 CQA 知识库源
CQA 知识库是一组结构化的问答对,针对对话式 AI 进行了优化。 知识库基于自然语言处理技术,能够理解用户查询,并从指定数据集中提供上下文相关的准确回答。
在“入门”菜单中,选择“管理源”。
在主窗口中,选择“+ 添加源”下拉菜单。
在下拉菜单中,可以选择“添加闲聊”、“添加 URL”或“添加文件”。
对于此项目,请选择“添加闲聊”。
在“添加新源”窗口中,选择“友好”。
最后,选择“ 添加”。 创建源可能需要几分钟时间。
创建后,源将列在“管理源”窗口中。
测试知识库
从“入门”菜单中选择“测试知识库”。
在“键入问题”字段中键入以下内容,然后选择“运行”。
Hello! How are you doing today?在检查界面中,可以查看响应置信度,并选择最合适的答案。
部署知识库
部署 CQA 知识库意味着将整理过的问答内容发布为一个可实时访问并可搜索的终结点。 此过程将项目从测试阶段移动到生产环境,使客户端应用程序能够将其用于各种项目和解决方案,包括聊天机器人。
检查完成后,从“入门”菜单中选择“部署知识库”部分。
首先从“部署知识库”主窗口中选择“部署”按钮,然后从“部署此项目”弹出窗口选择部署按钮。 这一过程需要花费几分钟时间。
部署完成后,部署的项目将列在“部署知识库”窗口中。
就是这样! 自定义问答 (CQA) 知识库为数据提供自然语言界面,允许用户以对话方式与信息交互。 通过部署此解决方案,可以创建高级聊天机器人和交互式代理,以理解用户问题、提供精确答案并适应不断变化的信息需求。
先决条件
- 最新版本的 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 请求。 在生产环境中,请使用安全的方式进行访问凭据的存储和管理。 在此示例中,你将凭据写入运行应用程序的本地计算机上的环境变量。
若要为语言资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。
- 若要设置
LANGUAGE_KEY环境变量,请将your-key替换为资源的其中一个密钥。 - 若要设置
LANGUAGE_ENDPOINT环境变量,请将your-endpoint替换为资源的终结点。
重要
我们建议使用 Azure 资源的托管标识进行 Microsoft Entra ID 身份验证,以避免将凭据随云中运行的应用程序一起存储。
请谨慎使用 API 密钥。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。 如果使用 API 密钥,请将其安全地存储在 Azure Key Vault 中,定期轮换密钥,并使用基于角色的访问控制和网络访问限制来限制对 Azure Key Vault 的访问。 若要详细了解如何在应用中安全地使用 API 密钥,请参阅 API 密钥与 Azure Key Vault。
有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证。
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.cognitiveservices.azure.com/ |
API-Key |
从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 可以使用 Key1 或 Key2。 应始终具有两个有效密钥,以实现安全密钥轮换而无需停机。 也可以在“Language Studio”>“问题解答”>“部署项目”>“获取预测 URL”中查找该值。 此密钥值是示例请求的一部分。 |
Project |
自定义问题解答项目的名称。 |
Deployment |
有两个可能的值:test 和 production。
production 取决于是否已在“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.cognitiveservices.azure.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.cognitiveservices.azure.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 KEY 和 ENDPOINT 变量。
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.cognitiveservices.azure.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 的自定义问题解答客户端库,可使用本快速入门来实现以下目的:
- 从项目获取答案。
- 从与问题一起发送的文本正文中获取答案。
- 获取问题答案的置信度分数。
先决条件
- 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 请求。 在生产环境中,请使用安全的方式进行访问凭据的存储和管理。 在此示例中,你将凭据写入运行应用程序的本地计算机上的环境变量。
若要为语言资源密钥设置环境变量,请打开控制台窗口,并按照操作系统和开发环境的说明进行操作。
- 若要设置
LANGUAGE_KEY环境变量,请将your-key替换为资源的其中一个密钥。 - 若要设置
LANGUAGE_ENDPOINT环境变量,请将your-endpoint替换为资源的终结点。
重要
我们建议使用 Azure 资源的托管标识进行 Microsoft Entra ID 身份验证,以避免将凭据随云中运行的应用程序一起存储。
请谨慎使用 API 密钥。 请不要直接在代码中包含 API 密钥,并且切勿公开发布该密钥。 如果使用 API 密钥,请将其安全地存储在 Azure Key Vault 中,定期轮换密钥,并使用基于角色的访问控制和网络访问限制来限制对 Azure Key Vault 的访问。 若要详细了解如何在应用中安全地使用 API 密钥,请参阅 API 密钥与 Azure Key Vault。
有关 Azure AI 服务安全性的详细信息,请参阅对 Azure AI 服务的请求进行身份验证。
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.cognitiveservices.azure.com/ |
credential |
从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 可以使用 Key1 或 Key2。 应始终具有两个有效密钥,以实现安全密钥轮换而无需停机。 也可以在“Language Studio”>“问题解答”>“部署项目”>“获取预测 URL”中查找该值。 此密钥值是示例请求的一部分。 |
projectName |
自定义问题解答项目的名称。 |
deploymentName |
有两个可能的值:test 和 production。
production 取决于是否已在“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)
将置信度分数乘以 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 在没有项目的情况下使用自定义问题解答。 在这种情况下,你可以提供自定义问题解答,其中既包含问题,也包含发送请求时你要从中搜索答案的相关文本记录。
对于此示例,只需修改 endpoint 和 credential 变量。
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}.cognitiveservices.azure.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 替换为脚本块的内容,并修改 endpoint 和 credential 变量,使其与已作为先决条件的一部分创建的语言资源相对应。
在这种情况下,我们将循环访问所有的响应,并仅返回具有大于 0.9 的最高置信度分数的响应。 详细了解可与 GetAnswersFromText 一起使用的选项。
对于适用于 Python 的自定义问题解答客户端库,可使用本快速入门来实现以下目的:
- 从项目获取答案。
- 从与问题一起发送的文本正文中获取答案。
- 获取问题答案的置信度分数。
先决条件
- 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.cognitiveservices.azure.com/ |
credential |
从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。 可以使用 Key1 或 Key2。 应始终具有两个有效密钥,以实现安全密钥轮换而无需停机。 也可以在“Language Studio”>“问题解答”>“部署项目”>“获取预测 URL”中查找该值。 此密钥值是示例请求的一部分。 |
knowledge_base_project |
问答项目的名称。 |
deployment |
有两个可能的值:test 和 production。
production。 |
重要
完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering import QuestionAnsweringClient
endpoint = "https://{YOUR-ENDPOINT}.cognitiveservices.azure.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("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
将置信度分数乘以 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 在没有项目的情况下使用自定义问题解答。 在这种情况下,你可以提供自定义问题解答,其中既包含问题,也包含发送请求时你要从中搜索答案的相关文本记录。
对于此示例,只需修改 endpoint 和 credential 变量。
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}.cognitiveservices.azure.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 资源,可以删除单个资源或整个资源组。 如果删除资源组,也会删除包含的所有资源。