Workshop at ilionx's DevDays
In this lab you'll get to work with LUIS to implement language understanding for your bot.
The finished solutions can be found here and are available for you to compare your work, or to take a look when you're having difficulties executing the assignments.
- Visual Studio 2017 or newer
- The Microsoft Bot Framework SDK v4 template is installed
- The Microsoft Bot Framework Emulator is installed
- A finished solution of the previous lab. If you didn't complete the first lab yet you can get a finished solution here.
1.1 Creating the LUIS application)
- Navigate to LUIS eu portal
If you don't have an Azure account yet you can use LUIS using a 3 month free trial, select
Continue using your trial key
to use this free trial.
- Click on
Create new app
- Choose any name you like, in this workshop we'll use
DevDaysBot
- Select the culture (languague) you want to use, in this workshop we'll use english
- Choose any name you like, in this workshop we'll use
Starting on 6/8/2020 LUIS will require an Azure resource. During this workshop we will not create this to reduce complexity. Learn more.
1.2 Adding intents)
- Navigate to the
Build
tab, here you can see the list of intents.
- Create a new intent with the name
Greeting
- Enter a few different utterances for this intent, using these differenct utterances we can train our LUIS application.
- Add a
Goodbye
intent, add utterances like "see you later". - Add a
GetLeaveBalance
intent, add utterances like "How many days do I still have off?". - Add a
CallInSickToday
intent, add utterances like "I'm sick so I can't come to work.". - In the
None
intent, add a couple of random utterances that don't have to do anything with our bot.
1.3 Training and publishing)
Now that we have some intents set up we can train our LUIS application to try to assign incoming utterances to its known intents. When this finished, you can test the model by pressing Test
.
-
Click
Train
to train your LUIS model -
Publish your LUIS model by pressing
Publish
and selectingproduction
. -
Navigate to the
Manage
tab, underAzure Resources
, copy the following values:- Primary key (in blue)
- AppID (in orange)
2.1 Creating Middleware)
In this assignment we will use the LUIS application we created from within our bot. This will allow it to better understand the user's intentions, therefore improving the user experience. We want to know what the user means with the message they send before we continue with our logic. To achieve this we will create custom middleware.
First of all, we'll need to install a NuGet package which will allow us to easily access our LUIS application.
- Install the
Microsoft.Bot.Builder.AI.Luis
NuGet package to your solution.
- Navigate to
appsettings.json
in your solution in Visual Studio - Add the following in this file:
LuisAppId
with its corresponding valueLuisAPIKey
with its corresponding valueLuisAPIHostName
with the value ofhttps://westeurope.api.cognitive.microsoft.com
Note: We created our LUIS application through the european portal (eu.luis.ai), if you created it in a different region, the value of the hostname will be different.
-
Create a new folder called
Middleware
. In this folder, create a new class file calledIntentRecognizerMiddleware.cs
. This class should implement theIMiddleware
interface of theMicrosoft.Bot.Builder
namespace. Import the required namespaces. -
Add a private readonly LuisRecognizer property and a constructor. The values we use to create the LuisApplication are retrieved from the
appsettings.json
. Import the required namespaces.private readonly LuisRecognizer luisRecognizer; public IntentRecognizerMiddleware(IConfiguration configuration) { var luisApplication = new LuisApplication( configuration["LuisAppId"], configuration["LuisAPIKey"], configuration["LuisAPIHostName"]); luisRecognizer = new LuisRecognizer(luisApplication); }
-
Next, lets implement the
OnTurnAsync
function. This will use the LuisRecognizer to access our LUIS application and pass the message of the user. The highest scoring intent is retrieved from the response and is added to theTurnState
. This will allow us to retrieve this value in ourDevDaysBot.cs
file. Import the required namespaces.public async Task OnTurnAsync(ITurnContext turnContext, NextDelegate next, CancellationToken cancellationToken = default) { if (!string.IsNullOrEmpty(turnContext.Activity.Text)) { var recognizerResult = await luisRecognizer.RecognizeAsync(turnContext, cancellationToken); var (intent, score) = recognizerResult.GetTopScoringIntent(); turnContext.TurnState.Add("Intent", intent); } await next(cancellationToken); }
2.2 Using our custom middleware)
We've created our custom middleware, nice work! Lets now start using it. First we need to tell our bot to run the code we've written in our custom middleware.
Middleware is added via adapters. The project template created an adapter for us, we can simply use that one.
- In the
AdapterWithErrorHandler.cs
file, import the namespace the IntentRecognizerMiddleware resides in. - In the same file, add the following line before the
OnTurnError
in the constructor:// Our custom middleware Use(new IntentRecognizerMiddleware(configuration));
-
In the
DevDaysBot.cs
file, add the following line above the start of the switch statement:string intent = turnContext.TurnState.Get<string>("Intent");
-
Alter the switch to use this intent as the expression, and match the cases to the different intents you created in your LUIS application.
-
Run the bot again and verify that the bot understands the
Greeting
andGoodbye
'command'. -
Add a case for
GetLeaveBalance
, enter the following code there:Random random = new Random(); // In a real application we would want to fetch the remaining leave hours from an actual source. // For the purpose of this workshop a random number is generated. await turnContext.SendActivityAsync($"Currently, your available leave balance is {random.Next(1, 200)} hours this year."); break;
-
Add a case for
CallInSickToday
, enter the following code there:// For the purpose of this workshop we only send a confirmation message. await turnContext.SendActivityAsync($"Alright, I've notified your manager, get better soon!"); break;
In this lab you created a LUIS application including some intents, you wrote your own custom middleware and implemented it within the logic of the bot.
You can check your solution with the finished solution.
In the next lab we'll integrate a another cognitive service called QnA Maker, and make this work alongside LUIS using the dispatch tool to further improve our bot.
Unbelievable! If you want you can take a look at entities within LUIS and implement a simple entity in your application, see how here. Try to use this from within your bot.