Web App Bot using the LUIS template for C#

Using C#, build a chat bot integrated with language understanding (LUIS). This chat bot uses the prebuilt HomeAutomation domain to quickly implement a bot solution.

Prerequisite

LUIS HomeAutomation Intents

Intent Example utterance Bot functionality
HomeAutomation.TurnOn Turn on the lights. When the LUIS intent HomeAutomation.TurnOn is detected, the bot invokes the OnIntent dialog handler. This dialog is where you'd call an IoT service to turn on a device and tell the user that the device has been turned on.
HomeAutomation.TurnOff Turn off the bedroom lights. When the LUIS intent HomeAutomation.TurnOff is detected, the bot invokes the OffIntent dialog handler. This dialog is where you'd call an IoT service to turn off a device and tell the user that the device has been turned off.

Create a Language Understanding bot with Bot Service

  1. In the Azure portal, select Create new resource in the top left menu.

    Create new resource

  2. In the search box, search for Web App Bot.

    Create new resource

  3. In the Web App Bot window, click Create.

  4. In Bot Service, provide the required information, and click Create. This creates and deploys the bot service and LUIS app to Azure. If you want to use speech priming, review region requirements before creating your bot.

    • Set App name to your bot’s name. The name is used as the subdomain when your bot is deployed to the cloud (for example, mynotesbot.azurewebsites.net).
    • Select the subscription, resource group, App service plan, and location.
    • Select the Language understanding (C#) template for the Bot template field.
    • Select the LUIS App Location. This is the authoring region the app is created in.
    • Select the confirmation checkbox for the legal notice. The terms of the legal notice are below the checkbox.

      Bot Service

  5. Confirm that the bot service has been deployed.

    • Click Notifications (the bell icon that is located along the top edge of the Azure portal). The notification changes from Deployment started to Deployment succeeded.
    • After the notification changes to Deployment succeeded, click Go to resource on that notification.

Note

This web app bot creation process also created a new LUIS app for you. It has been trained and published for you.

Try the default bot

Confirm that the bot has been deployed by selecting the Notifications checkbox. The notifications changes from Deployment in progress... to Deployment succeeded. Click Go to resource button to open the bot's resources.

Once the bot is deployed, click Test in Web Chat to open the Web Chat pane. Type "hello" in Web Chat.

Test the bot in Web Chat

The bot responds by saying "You have reached Greeting. You said: hello". This response confirms that the bot has received your message and passed it to a default LUIS app that it created. This default LUIS app detected a Greeting intent. In the next step, you'll connect the bot to the LUIS app you previously created instead of the default LUIS app.

Connect your LUIS app to the bot

Open Application Settings and edit the LuisAppId field to contain the application ID of your LUIS app. If you created your HomeAutomation LUIS app in a region other than West US, you need to change the LuisAPIHostName as well. The LuisAPIKey is currently set to your authoring key. You change this to your endpoint key when your traffic exceeds the free tier quota.

Update the LUIS app ID in Azure

Note

If you don't have the LUIS app ID of the Home Automation app, log in to the LUIS website using the same account you use to log in to Azure.

  1. Click on My apps.
  2. Find the LUIS app you previously created, that contains the intents and entities from the HomeAutomation domain.
  3. In the Settings page for the LUIS app, find and copy the app ID. Make sure it is trained and published.

Warning

If you delete your app ID or LUIS key, the bot will stop working.

Modify the bot code

  1. Click Build and then click Open online code editor.

    Open online code editor

  2. Right click build.cmd and choose Run from Console to build the app. There are several build steps the service completes automatically for you. The build is complete when it finished with "Finished successfully."

  3. In the code editor, open /Dialogs/BasicLuisDialog.cs. It contains the following code:

    using System;
    using System.Configuration;
    using System.Threading.Tasks;
    
    using Microsoft.Bot.Builder.Dialogs;
    using Microsoft.Bot.Builder.Luis;
    using Microsoft.Bot.Builder.Luis.Models;
    
    namespace Microsoft.Bot.Sample.LuisBot
    {
        // For more information about this template visit http://aka.ms/azurebots-csharp-luis
        [Serializable]
        public class BasicLuisDialog : LuisDialog<object>
        {
            public BasicLuisDialog() : base(new LuisService(new LuisModelAttribute(
                ConfigurationManager.AppSettings["LuisAppId"], 
                ConfigurationManager.AppSettings["LuisAPIKey"], 
                domain: ConfigurationManager.AppSettings["LuisAPIHostName"])))
            {
            }
    
            [LuisIntent("None")]
            public async Task NoneIntent(IDialogContext context, LuisResult result)
            {
                await this.ShowLuisResult(context, result);
            }
    
            // Go to https://luis.ai and create a new intent, then train/publish your luis app.
            // Finally replace "Gretting" with the name of your newly created intent in the following handler
            [LuisIntent("Greeting")]
            public async Task GreetingIntent(IDialogContext context, LuisResult result)
            {
                await this.ShowLuisResult(context, result);
            }
    
            [LuisIntent("Cancel")]
            public async Task CancelIntent(IDialogContext context, LuisResult result)
            {
                await this.ShowLuisResult(context, result);
            }
    
            [LuisIntent("Help")]
            public async Task HelpIntent(IDialogContext context, LuisResult result)
            {
                await this.ShowLuisResult(context, result);
            }
    
            private async Task ShowLuisResult(IDialogContext context, LuisResult result) 
            {
                await context.PostAsync($"You have reached {result.Intents[0].Intent}. You said: {result.Query}");
                context.Wait(MessageReceived);
            }
        }
    }
    

Change code to HomeAutomation intents

  1. Remove the three intent attributes and methods for Greeting, Cancel, and Help. These intents are not used in the HomeAutomation prebuilt domain. Make sure to keep the None intent attribute and method.

  2. Add dependencies to the top of the file, with the other dependencies:

    using System.Collections.Generic;
    using System.Text;
    
  3. Add constants to manage strings at the top of the BasicLuisDialog class:

    // CONSTANTS        
    // Entity
    public const string Entity_Device = "HomeAutomation.Device";
    public const string Entity_Room = "HomeAutomation.Room";
    public const string Entity_Operation = "HomeAutomation.Operation";
    
    // Intents
    public const string Intent_TurnOn = "HomeAutomation.TurnOn";
    public const string Intent_TurnOff = "HomeAutomation.TurnOff";
    public const string Intent_None = "None";
    
  4. Add the code for the new intents of HomeAutomation.TurnOn and HomeAutomation.TurnOff inside the BasicLuisDialog class:

    [LuisIntent(Intent_TurnOn)]
    public async Task OnIntent(IDialogContext context, LuisResult result)
    {
        await this.ShowLuisResult(context, result);
    }
    
    [LuisIntent(Intent_TurnOff)]
    public async Task OffIntent(IDialogContext context, LuisResult result)
    {
        await this.ShowLuisResult(context, result);
    }    
    
  5. Add the code to get any entities found by LUIS inside the BasicLuisDialog class:

    // Entities found in result
    public string BotEntityRecognition(LuisResult result)
    {
        StringBuilder entityResults = new StringBuilder();
    
        if(result.Entities.Count>0)
        {
            foreach (EntityRecommendation item in result.Entities)
            {
                // Query: Turn on the [light]
                // item.Type = "HomeAutomation.Device"
                // item.Entity = "light"
                entityResults.Append(item.Type + "=" + item.Entity + ",");
            }
            // remove last comma
            entityResults.Remove(entityResults.Length - 1, 1);
        }
    
        return entityResults.ToString();
    }
    
  6. Change ShowLuisResult method in the BasicLuisDialog class to round the score, collect the entities, and display the response message in the chatbot:

    private async Task ShowLuisResult(IDialogContext context, LuisResult result) 
    {
        // get recognized entities
        string entities = this.BotEntityRecognition(result);
        
        // round number
        string roundedScore =  result.Intents[0].Score != null ? (Math.Round(result.Intents[0].Score.Value, 2).ToString()) : "0";
        
        await context.PostAsync($"**Query**: {result.Query}, **Intent**: {result.Intents[0].Intent}, **Score**: {roundedScore}. **Entities**: {entities}");
        context.Wait(MessageReceived);
    }
    

Build the bot

In the code editor, right-click on build.cmd and select Run from Console.

Build Web bot

The code view is replaced with a terminal window showing the progress and results of the build.

Build Web bot success

Tip

An alternative method to build the bot is to select the bot name in the top blue bar, and select Open Kudu Console. The console opens to D:\home.

Change the directory to D:\home\site\wwwroot by typing: cd site\wwwroot

Run the build script by typing: build.cmd

Test the bot

In the Azure portal, click on Test in Web Chat to test the bot. Type messages like "Turn on the lights", and "turn off my heater" to invoke the intents that you added to it.

Test HomeAutomation bot in Web Chat

Tip

You can retrain your LUIS app without any modification to your bot's code. See Add example utterances and train and test your LUIS app.

Download the bot to debug

If your bot isn't working, download the project to your local machine and continue debugging.

Learn more about Bot Framework

Learn more about Bot Framework and the 3.x and 4.x SDKs.

Next steps

Add the LUIS intents and Bot service dialogs for handling Help, Cancel, and Greeting intents. Remember to train, publish and to build the web app bot. Both LUIS and the bot should have the same intents.