將自然語言理解新增至您的 BotAdd natural language understanding to your bot

適用于: SDK v4APPLIES TO: SDK v4

讓您的 Bot 能透過對話和上下文了解使用者的意思,並不是簡單的工作,但這樣的功能可讓您的 Bot 使用起來更有自然對話的感覺。The ability to understand what your user means conversationally and contextually can be a difficult task, but can provide your bot a more natural conversation feel. Language Understanding (LUIS) 是雲端式 API 服務,能讓您這麼做,使您的 Bot 可以辨識使用者訊息的意圖,這樣使用者就能使用更自然的語言,且更順利地引導交談流程。Language Understanding (LUIS) is a cloud-based API service that enables you to do just that so that your bot can recognize the intent of user messages, allow for more natural language from your user, and better direct the conversation flow.

本主題會逐步引導您將 LUIS 新增至航班預訂應用程式,以辨識使用者輸入內含的不同意圖和實體。This topic walks you through adding LUIS to a flight booking application to recognize different intents and entities contained within user input.

必要條件Prerequisites

關於此範例About this sample

此核心 Bot 範例顯示機場航班預訂應用程式的範例。This core bot sample shows an example of an airport flight booking application. 其會使用 LUIS 服務來辨識使用者輸入,並傳回最常辨識的 LUIS 意圖。It uses a LUIS service to recognize the user input and return the top recognized LUIS intent.

語言模型包含三個意圖:Book FlightCancelNoneThe language model contains three intents: Book Flight, Cancel, and None. LUIS 將使用這些意圖,了解使用者將訊息傳送給 Bot 時的用意。LUIS will use these intents to understand what the user meant when they send a message to the bot. 語言模型也會定義 LUIS 可以從使用者的輸入 (例如來源或目的地機場) 擷取的實體。The language model also defines entities that LUIS can extract from the user's input, such as the origin or destination airport.

在每此處理使用者輸入之後,DialogBot 會儲存 UserStateConversationState 的目前狀態。After each processing of user input, DialogBot saves the current state of both UserState and ConversationState. 蒐集所有必要的資訊後,程式碼範例會建立示範航班預訂保留。Once all the required information has been gathered the coding sample creates a demo flight booking reservation. 這本文中,我們將探討這的範例的 LUIS 層面。In this article we'll be covering the LUIS aspects of this sample. 不過,此範例的一般流程如下所示:However, the general flow of the sample is shown below:

  • 當新的使用者連線並顯示歡迎卡片時,就會呼叫 OnMembersAddedAsyncOnMembersAddedAsync is called when a new user is connected and displays a welcome card.
  • 系統會針對每個收到的使用者輸入呼叫 OnMessageActivityAsyncOnMessageActivityAsync is called for each user input received.

LUIS 範例的邏輯流程

OnMessageActivityAsync 模組會透過 Run 對話擴充方法執行適當的對話。The OnMessageActivityAsync module runs the appropriate dialog through the Run dialog extension method. 然後,該主要對話方塊會呼叫 LUIS 協助程式,以尋找評分最高的使用者意圖。Then the main dialog calls the LUIS helper to find the the top scoring user intent. 如果使用者輸入的最高意圖傳回 "BookFlight",則協助程式會填寫 LUIS 傳回的使用者資訊。If the top intent for the user input returns "BookFlight", the helper fills out information from the user that LUIS returned. 之後,主要對話會啟動 BookingDialog,其會視需要向使用者取得其他資訊,例如:After that, the main dialog starts the BookingDialog, which acquires additional information as needed from the user such as:

  • Origin 原始城市Origin the originating city
  • TravelDate 要預訂航班的日期TravelDate the date to book the flight
  • Destination 目的地城市Destination the destination city

本文涵蓋如何將 LUIS 新增至 Bot。This article covers how to add LUIS to a bot. 如需使用對話或狀態的詳細資訊,請分別參閱如何使用對話提示蒐集使用者輸入儲存使用者和交談資料For information about using dialogs or state, see how to gather user input using a dialog prompt or save user and conversation data, respectively.

在 LUIS 入口網站中建立 LUIS 應用程式Create a LUIS app in the LUIS portal

  1. 登入 LUIS 入口網站Sign in to the LUIS portal.

    • 如果您還沒有帳戶,請建立帳戶。If you don't already have an account, create one.
    • 如果您還沒有撰寫資源,請建立撰寫資源。If you don't already have an authoring resource, create one.
    • 如需詳細資訊,請參閱 LUIS 文件以了解如何登入 LUIS 入口網站For more information, see the LUIS documentation on how to sign in to the LUIS portal.
  2. 在 [我的應用程式] 頁面中,按一下 [新增對話應用程式],然後按一下 [匯入為 JSON]。On the My Apps page, click New app for conversation and select Import as JSON.

  3. 在 [匯入新的應用程式] 對話方塊中:In the Import new app dialog:

    1. 在範例的 CognitiveModels 資料夾中,選擇 FlightBooking.json 檔案。Choose the FlightBooking.json file in the CognitiveModels folder of the sample.
    2. 輸入 FlightBooking 作為應用程式的選擇性名稱,然後按一下 [完成]。Enter FlightBooking as the optional name of the app, and click Done.
  4. 系統可能會提示您升級複合實體。You may be prompted to upgrade your composite entities. 您可以忽略此內容,並按一下 [在 稍後提醒我]:You can ignore this and click Remind me later:

    忽略複合-實體

  5. 訓練和發佈您的應用程式。Train and publish your app. 如需詳細資訊,請參閱 LUIS 文件以了解如何訓練應用程式以及將其發佈至實際執行環境。For more information, see the LUIS documentation on how to train and publish an app to the production environment.

為何使用實體Why use entities

LUIS 實體可讓 Bot 以智慧方式了解與標準意圖不同的特定事項或事件。LUIS entities allow your bot to intelligently understand certain things or events that are different than the standard intents. 這可讓您向使用者收集額外資訊,進而讓 Bot 更聰明地回應,或可能略過要求使用者提供該資訊的某些問題。This enables you to gather extra information from the user, which lets your bot respond more intelligently or possibly skip certain questions where it asks the user for that information. 除了三個 LUIS 意圖 [預訂航班]、[取消] 和 [無] 的定義,FlightBooking.json 檔案還包含一組實體,例如 'From.Airport' 和 'To.Airport'。Along with definitions for the three LUIS intents 'Book Flight', 'Cancel', and 'None' the FlightBooking.json file also contains a set of entities such as 'From.Airport' and 'To.Airport'. 這些實體可讓 LUIS 偵測使用者原始輸入內含的其他資訊,並且在使用者要求新的旅行預約時傳回這些資訊。These entities allow LUIS to detect and return additional information contained within the user's original input when they request a new travel booking.

取得值以連線到您的 LUIS 應用程式Obtain values to connect to your LUIS app

在您的 LUIS 應用程式發佈之後,您即可從 Bot 進行存取。Once your LUIS app is published, you can access it from your bot. 您必須記錄數個值,以從 Bot 存取您的 LUIS 應用程式。You will need to record several values to access your LUIS app from within your bot. 您可以使用 LUIS 入口網站擷取該資訊。You can retrieve that information using the LUIS portal.

從 LUIS.ai 入口網站擷取應用程式資訊Retrieve application information from the LUIS.ai portal

settings 檔案 (appsettings.json.envconfig.py) 檔案可作為將所有服務參考匯合在一起的位置。The settings file (appsettings.json, .env or config.py) acts as the place to bring all service references together in one place. 您所擷取的資訊會新增至下一節中的這個檔案。The information you retrieve will be added to this file in the next section.

  1. luis.ai 中選取已發佈的 LUIS 應用程式。Select your published LUIS app from luis.ai.
  2. 開啟已發佈的 LUIS 應用程式後,選取 [管理] 索引標籤。With your published LUIS app open, select the MANAGE tab.
  3. 選取左側的 [ 設定 ] 索引標籤,並將 [ 應用程式識別碼 ] 所顯示的值記錄為 <YOUR_APP_ID> 。Select the Settings tab on the left side and record the value shown for Application ID as <YOUR_APP_ID>.

    管理 LUIS 應用程式 - 應用程式資訊Manage LUIS app - Application Information

  4. 選取左側的 [Azure 資源] 索引標籤,然後選取 [撰寫資源] 群組。Select the Azure Resources tab on the left side and select the Authoring Resource group. 位置 顯示的值記錄為 <YOUR_REGION>,將 主索引鍵 顯示的值記錄為 <YOUR_AUTHORING_KEY>。Record the value shown for Location as <YOUR_REGION> and Primary Key as <YOUR_AUTHORING_KEY>.

    管理 LUIS 應用程式撰寫資訊Manage LUIS app - Authoring Information

更新 settings 檔案Update the settings file

將存取 LUIS 應用程式所需的資訊 (包括應用程式識別碼、撰寫金鑰和區域) 新增至 appsettings.json 檔案中。Add the information required to access your LUIS app including application id, authoring key, and region into the appsettings.json file. 這些是您先前從已發佈的 LUIS 應用程式儲存的值。These are the values you saved previously from your published LUIS app. 請注意,API 主機名稱應該採用 <your region>.api.cognitive.microsoft.com 格式。Note that the API host name should be in the format <your region>.api.cognitive.microsoft.com.

appsetting.jsonappsetting.json

{
  "MicrosoftAppId": "",
  "MicrosoftAppPassword": "",
  "LuisAppId": "",
  "LuisAPIKey": "",
  "LuisAPIHostName": ""
}

設定 Bot 來使用 LUIS 應用程式Configure your bot to use your LUIS app

請確定您已為專案安裝 Microsoft.Bot.Builder.AI.Luis NuGet 套件。Be sure that the Microsoft.Bot.Builder.AI.Luis NuGet package is installed for your project.

若要連線到 LUIS 服務,Bot 會從 appsetting.json 檔案提取您前面新增的資訊。To connect to the LUIS service, the bot pulls the information you added above from the appsetting.json file. FlightBookingRecognizer 類別包含的程式碼有來自 appsetting.json 檔案的設定,並且會藉由呼叫 RecognizeAsync 方法來查詢 LUIS 服務。The FlightBookingRecognizer class contains code with your settings from the appsetting.json file and queries the LUIS service by calling RecognizeAsync method.

FlightBookingRecognizer.csFlightBookingRecognizer.cs

public class FlightBookingRecognizer : IRecognizer
{
    private readonly LuisRecognizer _recognizer;

    public FlightBookingRecognizer(IConfiguration configuration)
    {
        var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId"]) && !string.IsNullOrEmpty(configuration["LuisAPIKey"]) && !string.IsNullOrEmpty(configuration["LuisAPIHostName"]);
        if (luisIsConfigured)
        {
            var luisApplication = new LuisApplication(
                configuration["LuisAppId"],
                configuration["LuisAPIKey"],
                "https://" + configuration["LuisAPIHostName"]);
            // Set the recognizer options depending on which endpoint version you want to use.
            // More details can be found in https://docs.microsoft.com/en-gb/azure/cognitive-services/luis/luis-migration-api-v3
            var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
            {
                PredictionOptions = new Bot.Builder.AI.LuisV3.LuisPredictionOptions
                {
                    IncludeInstanceData = true,
                }
            };

            _recognizer = new LuisRecognizer(recognizerOptions);
        }
    }

    // Returns true if luis is configured in the appsettings.json and initialized.
    public virtual bool IsConfigured => _recognizer != null;

    public virtual async Task<RecognizerResult> RecognizeAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        => await _recognizer.RecognizeAsync(turnContext, cancellationToken);

    public virtual async Task<T> RecognizeAsync<T>(ITurnContext turnContext, CancellationToken cancellationToken)
        where T : IRecognizerConvert, new()
        => await _recognizer.RecognizeAsync<T>(turnContext, cancellationToken);
}

FlightBookingEx.cs 的邏輯會擷取 FromToTravelDate;其會延伸在從 MainDialog.cs 呼叫 FlightBookingRecognizer.RecognizeAsync<FlightBooking> 時用來儲存 LUIS 結果的部分類別 FlightBooking.csThe FlightBookingEx.cs contains the logic to extract From, To and TravelDate; it extends the partial class FlightBooking.cs used to store LUIS results when calling FlightBookingRecognizer.RecognizeAsync<FlightBooking> from the MainDialog.cs.

CognitiveModels\FlightBookingEx.csCognitiveModels\FlightBookingEx.cs

// Extends the partial FlightBooking class with methods and properties that simplify accessing entities in the luis results
public partial class FlightBooking
{
    public (string From, string Airport) FromEntities
    {
        get
        {
            var fromValue = Entities?._instance?.From?.FirstOrDefault()?.Text;
            var fromAirportValue = Entities?.From?.FirstOrDefault()?.Airport?.FirstOrDefault()?.FirstOrDefault();
            return (fromValue, fromAirportValue);
        }
    }

    public (string To, string Airport) ToEntities
    {
        get
        {
            var toValue = Entities?._instance?.To?.FirstOrDefault()?.Text;
            var toAirportValue = Entities?.To?.FirstOrDefault()?.Airport?.FirstOrDefault()?.FirstOrDefault();
            return (toValue, toAirportValue);
        }
    }

    // This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part.
    // TIMEX is a format that represents DateTime expressions that include some ambiguity. e.g. missing a Year.
    public string TravelDate
        => Entities.datetime?.FirstOrDefault()?.Expressions.FirstOrDefault()?.Split('T')[0];
}

現在已針對您的 Bot 設定和連線 LUIS。LUIS is now configured and connected for your bot.

測試 BotTest the bot

下載並安裝最新版 Bot Framework EmulatorDownload and install the latest Bot Framework Emulator

  1. 在您的電腦本機執行範例。Run the sample locally on your machine. 如需相關指示,請參閱 C# 範例JS 範例Python 範例的讀我檔案。If you need instructions, refer to the readme file for the C# Sample, JS Sample or Python Sample.

  2. 在模擬器中,輸入訊息,例如「旅遊至巴黎」或「從巴黎到柏林」。In the Emulator, type a message such as "travel to paris" or "going from paris to berlin". 使用在 FlightBooking.json 檔案中找到的任何語句來訓練「預訂航班」意圖。Use any utterance found in the file FlightBooking.json for training the intent "Book flight".

LUIS 預訂輸入

如果 LUIS 傳回的最高意圖解析為「預訂航班」,您的 Bot 會詢問其他問題,直到儲存足夠的資訊來建立旅行預訂為止。If the top intent returned from LUIS resolves to "Book flight" your bot will ask additional questions until it has enough information stored to create a travel booking. 屆時,會將此預訂資訊傳回給您的使用者。At that point it will return this booking information back to your user.

LUIS 預訂結果

此時,程式碼 Bot 邏輯會重設,而您可以繼續建立其他預訂。At this point the code bot logic will reset and you can continue to create additional bookings.

其他資訊Additional information

如需 LUIS 的詳細資訊,請參閱 LUIS 文件:For more about LUIS, see the LUIS documentation:

後續步驟Next steps