這份快速入門指南將引導你完成在 Microsoft Foundry 中建立、測試及部署自訂問答(CQA)專案所需的重要步驟。 無論您是從 Language Studio 轉換還是從頭開始,本快速入門都很適合您。 其提供了清晰且可操作的指示,以實現快速、成功的 CQA 專案部署。
附註
- 如果你已經在 Foundry 工具中使用 Azure 語言或多服務資源——無論是單獨使用或透過 Language Studio 使用——你仍可在 Foundry 入口網站中使用現有的語言資源。 欲了解更多資訊,請參閱 Foundry 入口網站中的「如何使用 Foundry 工具」。
- 我們強烈建議您在 Foundry 中使用 Foundry 資源;不過,您也可以使用語言資源來按照這些指示進行操作。
先決條件
開始之前,您需要下列資源和權限:
- 作用中的 Azure 訂用帳戶。 如果您沒有帳戶,請免費建立一個。
- 必要的權限。 請確定建立帳戶和項目的人員已獲指派為訂用帳戶層級的 Azure AI 帳戶擁有者角色。 或者,在訂用帳戶範圍擁有 [參與者] 或 [認知服務參與者] 角色也符合這項需求。 如需詳細資訊,請參閱角色型訪問控制(RBAC)。
- Foundry 資源或語言資源。
- Azure AI 搜尋服務資源 (存取 CQA 所需)。 欲了解更多如何連接 Azure AI Search 資源的資訊,請參閱「在 Foundry 中配置連線」
- 在 Foundry 平台上創建的 Foundry 專案。 欲了解更多資訊, 請參閱「建立鑄造廠專案」。
開始
瀏覽到 Foundry。
如果您尚未登入,入口網站會提示您使用您的 Azure 認證來執行此動作。
登入後,你可以在 Foundry 內建立或存取現有專案。
如果您尚未進入這項工作中的專案,請選取它。
建立您的 CQA 微調工作
在 Foundry 中,微調工作會作為 CQA 解決方案的工作區。 微調工作以前稱為 CQA 專案。 在較舊的 CQA 文件中,您可能會遇到這兩個術語交替使用的情況。
選取要用於本快速入門的 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 金鑰的詳細資訊,請參閱透過 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.cognitiveservices.azure.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.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": {}
}
]
}
不使用專案來查詢文字
您也可以在沒有專案的情況下使用自訂問題解答:使用透過 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.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 的自訂問題解答用戶端程式庫快速入門來:
- 從專案取得答案。
- 從與您的問題一起傳送的文字本文取得答案。
- 取得問題解答的信賴分數。
參考文件 | 套件 (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取代為您資源的端點。
重要事項
我們建議使用適用於 Azure 資源的受控識別搭配 Microsoft Entra ID 驗證,以避免使用在雲端執行的應用程式儲存認證。
請謹慎使用 API 金鑰。 請勿在程式碼中直接包含 API 金鑰,且切勿公開張貼金鑰。 如果使用 API 金鑰,請將這些金鑰安全地儲存在 Azure Key Vault 中、定期輪替金鑰,並使用角色型存取控制和網路存取限制來限制對 Azure Key Vault 的存取。 如需在應用程式中安全地使用 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.cognitiveservices.azure.com/ |
credential |
從 Azure 入口網站查看您的資源時,可以在 [金鑰與端點] 區段中找到此值。 您可以使用 Key1 或 Key2。 隨時都有兩個有效金鑰有助於進行安全的金鑰輪替,而不需要停機。 或者,您可以在 [Language Studio]>[問題解答]>[部署專案]>[取得預測 URL] 中找到此值。 金鑰值是範例要求的一部分。 |
projectName |
自訂問題解答專案的名稱。 |
deploymentName |
有兩個可能的值:test 和 production。
production 取決於您是否從 [Language Studio]>[問題解答]>[部署專案] 部署了您的專案。 |
重要事項
完成時,請記得從程式碼中移除金鑰,且不要公開張貼金鑰。 在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 欲了解更多資訊,請參閱 Foundry Tools 安全性。
從專案目錄中開啟 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)
將信賴度分數乘以 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/實驗室中的儲存格。
您需要更新程式碼,並為下列變數提供您自己的值。
| 變數名稱 | 值 |
|---|---|
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。 欲了解更多資訊,請參閱 Foundry Tools 安全文章。
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 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("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/實驗室中的新儲存格。 此範例會傳回下列結果:
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 資源,您可以刪除個別資源或整個資源群組。 如果您刪除資源群組,則也會刪除其中包含的所有資源。