快速入門:自訂問題解答
注意
Azure OpenAI on your Data 會利用大型語言模型 (LLM) 來產生與自訂問題解答類似的結果。 如果您想要將現有的自訂問題解答專案連線至 Azure OpenAI On Your Data,請參閱我們的指南。
注意
您要從 QnA Maker 移轉工作負載嗎? 如需功能比較和移轉步驟的相關資訊,請參閱我們的移轉指南。
開始使用自訂問題解答用戶端程式庫。 請遵循下列步驟來安裝套件,並試用基本工作的程式碼範例。
您可以從自己的內容 (例如常見問題集或產品手冊) 建立自訂問題解答專案。 本文包含相關範例,說明如何從產品手冊建立自訂問題解答專案以回答問題。
必要條件
建立您的第一個自訂問題解答專案
使用您的 Azure 認證登入 Language Studio。
向下捲動至 [回答問題] 區段,然後選取 [開啟自訂問題解答]。
如果您的資源尚未連線至 Azure 搜尋服務,請選取 [連線至 Azure 搜尋服務]。 這會開啟新的瀏覽器索引標籤,顯示您的資源在 Azure 入口網站中的 [功能] 窗格。
選取 [啟用自訂問題解答],選擇要連結到的 Azure 搜尋服務資源,然後選取 [套用]。
返回 [Language Studio] 索引標籤。您可能需要重新整理此頁面,才能將變更註冊至您的資源。 選取 [建立新專案]。
選擇 [我要為在此資源中建立的所有專案設定語言] 選項> 選取 [英文]> 選取 [下一步]。
輸入範例專案的專案名稱、第一個問題解答專案的描述,並保留預設答案的設定找不到答案。
檢閱您的選擇,然後選取 [建立專案]
在 [管理來源] 頁面中,選取 [新增來源]>[URL]。
選取 [新增 URL],輸入下列值,然後選取 [全部新增]:
URL 名稱 URL 值 Surface Book 使用者指南 https://download.microsoft.com/download/7/B/1/7B10C82E-F520-4080-8516-5CF0D803EEE0/surface-book-user-guide-EN.pdf 擷取程序需要一點時間來讀取文件並找出問題和回答。
成功新增來源之後,您即可編輯來源內容,以新增更多自訂回應集。
測試您的專案
選取來源的連結,這會開啟 [編輯專案] 頁面。
從功能表列中選取 [測試] > 輸入問題如何設定我的 Surface Book?。 系統會根據從您的來源 URL 自動識別和擷取的問答配對產生答案:
如果您勾選 [包含簡短的回答回應] 的方塊,則在您提出問題時,除了測試窗格中的答案段落以外,您也將看到精確的答案 (如果有的話)。
選取 [檢查],更詳細地檢查回應。 測試視窗可讓您在部署專案前測試您對專案所做的變更。
您可以從 [檢查] 介面查看此回應回答問題的信賴等級,並可直接編輯指定的問答回應配對。
部署您的專案
選擇 [部署專案] 圖示進入 [部署專案] 選單。
當您部署專案時,專案的內容會從
test
索引移至 Azure 搜尋服務中的prod
索引。選取 [部署] > 在出現提示時,再次選取 [部署]。
您的專案現已成功部署。 您可以使用端點,在您自己的自訂應用程式中或 Bot 中回答問題。
必要條件
- 最新版的 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
取代為您資源的端點。
重要
如果您使用 API 金鑰,請將其安全地儲存在別處,例如 Azure Key Vault。 請勿在程式碼中直接包含 API 金鑰,且切勿公開將其張貼。
如需 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.api.cognitive.microsoft.com/ |
API-Key |
從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 Key1 或 Key2。 隨時都有兩個有效金鑰有助於進行安全的金鑰輪替,而不需要停機。 或者,您可以在 [Language Studio]>[問題解答]>[部署專案]>[取得預測 URL] 中找到此值。 金鑰值是範例要求的一部分。 |
Project |
自訂問題解答專案的名稱。 |
Deployment |
有兩個可能的值:test 和 production 。 production 取決於您如何從 Language Studio>問題解答>部署專案部署您的專案。 |
cURL 命令是從 BASH 殼層執行。 使用您自己的資源名稱、資源金鑰,以及 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": {}
}
]
}
不使用專案來查詢文字
您也可以在沒有專案的情況下使用自訂問題解答:使用透過 query-text
來呼叫的預建自訂問題解答 REST API。 在此情況下,必須對問題解答提供問題,以及在傳送要求時您要從中搜尋答案的相關文字記錄。
在此範例中,您只需修改 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.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 要求。 在生產環境中,請運用安全的方式來儲存和存取您的登入資訊。 在此範例中,您會在執行應用程式的本機電腦上將認證寫入環境變數。
若要設定語言資源金鑰的環境變數,請開啟主控台視窗,並遵循作業系統和開發環境的指示進行。
- 若要設定
LANGUAGE_KEY
環境變數,請將your-key
取代為您資源的其中一個金鑰。 - 若要設定
LANGUAGE_ENDPOINT
環境變數,請將your-endpoint
取代為您資源的端點。
重要
如果您使用 API 金鑰,請將其安全地儲存在別處,例如 Azure Key Vault。 請勿在程式碼中直接包含 API 金鑰,且切勿公開將其張貼。
如需 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.api.cognitive.microsoft.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 Key Vault 可提供安全的金鑰儲存。
在使用上述程式碼更新 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
使用自訂問題解答。 在此情況下,必須對自訂問題解答提供問題,以及在傳送要求時您要從中搜尋答案的相關文字記錄。
在此範例中,您只需修改 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}.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
取代為上述指令碼區塊的內容,並修改 endpoint
和 credential
變數,以對應至您為了符合必要條件而建立的語言資源。
在此情況下,我們會逐一查看所有回應,且只會傳回最高信賴分數大於 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/實驗室中的儲存格。
您需要更新下列程式碼,並為下列變數提供您自己的值。
變數名稱 | 值 |
---|---|
endpoint |
從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 或者,您可以在 [Language Studio]>[問題解答]>[部署專案]>[取得預測 URL] 中找到此值。 範例端點為:https://southcentralus.api.cognitive.microsoft.com/ |
credential |
從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 Key1 或 Key2。 隨時都有兩個有效金鑰有助於進行安全的金鑰輪替,而不需要停機。 或者,您可以在 [Language Studio]>[問題解答]>[部署專案]>[取得預測 URL] 中找到此值。 金鑰值是範例要求的一部分。 |
knowledge_base_project |
問題解答專案的名稱。 |
deployment |
有兩個可能的值:test 和 production 。 production 取決於您如何從 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 Key Vault 可提供安全的金鑰儲存。
執行上述程式碼時,如果您使用必要條件中的資料來源,則會得到如下的答案:
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 使用自訂問題解答。 在此情況下,必須對自訂問題解答提供問題,以及在傳送要求時您要從中搜尋答案的相關文字記錄。
在此範例中,您只需修改 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}.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/實驗室中的新儲存格。 此範例會傳回下列結果:
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 來使用撰寫功能: