快速入門:自定義問題解答

注意

Azure Open AI On Your Data 利用大型語言模型 (LLM) 來產生與自定義問題解答類似的結果。 如果您想要將現有的自定義問題解答項目連線至 Azure Open AI On Your Data,請參閱我們的 指南

注意

您要從 QnA Maker 移轉工作負載嗎? 如需功能比較和移轉步驟的相關資訊,請參閱我們的移轉指南

開始使用自定義問題解答客戶端連結庫。 請遵循下列步驟來安裝套件,並試用基本工作的範例程序代碼。

您可以從自己的內容建立自定義問題解答專案,例如常見問題或產品手冊。 本文包含從產品手冊建立自定義問答專案的範例,以回答問題。

必要條件

  • 如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶
  • 已啟用自訂問題解答功能的語言資源。 請記住您在建立資源時選取的 Microsoft Entra ID、訂用帳戶、語言資源名稱。

建立您的第一個自定義問題解答專案

  1. 使用您的 Azure 認證登入 Language Studio

  2. 向下捲動至 [回答問題] 區段,然後選取 [開啟自訂問題解答]

    開啟自定義問題解答

  3. 如果您的資源尚未連線到 Azure 搜尋服務,請選取 [連線 至 Azure 搜尋服務]。 這會開啟新的瀏覽器索引標籤至資源 Azure 入口網站 中的 [功能] 窗格。

    連線 至 Azure 搜尋服務

  4. 選取 [ 啟用自定義問題解答],選擇要連結的 Azure 搜尋服務資源,然後選取 [ 套用]。

    啟用自定義問題解答

  5. 返回 [語言 Studio] 索引標籤。您可能需要重新整理此頁面,以註冊資源的變更。 選取 [建立新專案]

  6. 選擇 [我想為此資源中建立的所有項目設定語言] 選項,選取 [英文>選取下一步]。>

  7. 輸入 Sample-project 的項目名稱、我的第一個問題解答專案的描述,並將預設答案保留為 [找不到答案] 設定

  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 書籍的問題。 系統會根據自動識別並從來源 URL 擷取的問題答案組產生答案:

    測試問題聊天介面

    如果您核取包含簡短答案回應的方塊,您也會看到精確的答案,如果有的話,以及當您提出問題時,測試窗格中的答案段落。

  3. 選取 [ 檢查 ] 以更詳細地檢查回應。 測試視窗可用來在部署專案之前測試您對項目的變更。

    查看信賴區間

    從 [檢查] 介面中,您可以看到此回應會回答問題的信賴等級,並直接編輯指定的問答回應組。

部署您的專案

  1. 選擇 [部署專案] 圖示進入 [部署專案] 選單。

    部署專案

    當您部署專案時,專案的內容會從 test 索引 prod 移至 Azure 搜尋服務中的索引。

  2. 選取 [ 部署> ],然後在出現提示時再次選取 [部署 ]。

    部署成功

    您的項目現在已成功部署。 您可以使用端點來回答您自己的自定義應用程式中的問題,以在 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 要求。 針對生產環境,請使用安全的方式來儲存和存取您的認證。 在此範例中,您會將認證寫入執行應用程式的本機計算機上環境變數。

提示

請勿將金鑰直接包含在您的程式代碼中,且絕不會公開發佈。 如需更多驗證選項 (例如 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 有兩個可能的值: test、 和 productionproduction 取決於您如何從 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": {}
    }
  ]
}

不使用專案來查詢文字

您也可以 搭配預先建置的自定義問題解答 REST API 使用自定義問題解答,而不需要專案 即可使用自定義問題解答,而 REST API 是透過 query-text呼叫的。 在此情況下,您會提供問題解答,以及您想要在傳送要求時搜尋答案的相關文字記錄。

在此範例中,您只需要修改 和ENDPOINTAPI KEY變數。

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 有兩個可能的值: test、 和 productionproduction 取決於您如何從 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的情況下使用自定義問題解答。 在此情況下,您會提供自定義問題解答,其中包含問題,以及您想要在傳送要求時搜尋答案的相關文字記錄。

在此範例中,您只需要修改 和credentialendpoint變數。

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 有兩個可能的值: test、 和 productionproduction 取決於您如何從 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的項目的情況下使用自定義問題解答。 在此情況下,您會提供自定義問題解答,其中包含問題,以及您想要在傳送要求時搜尋答案的相關文字記錄。

在此範例中,您只需要修改 和credentialendpoint變數。

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 使用:

下一步