November 05, 2020 by Anuraj Estimated read time : 6 mins
This blog post is about adding natural language understanding to your bot. Language Understanding (LUIS) is a cloud-based API service that helps you to recognize the intent of user input and better direct the conversation flow. In the previous post I configured LUIS and in this post I will explain how we can use the LUIS service in a Bot Application.
I am using Visual Studio 2019, and I have created an Bot from the EchoBot template. Next we need to integrate LUIS app to the Bot. To do that first we need to add the reference of Microsoft.Bot.Builder.Ai.LUIS package. Once it is added, we need to implement IRecognizer interface, which helps you to interact with the LUIS application.
Here is the code for IRecognizer implementation.
Next you need to inject this to the controllers and bots using the ASP.NET Core dependency injection service. To do this I am modifying the Startup.cs class and adding following code.
If you notice the NotesRecognizer implementation, there is RecognizeAsync generic implementation which accepts type of IRecognizerConvert - this implementation will help us to get the intents and entities from the user input. There is a tool called LUISGen - LUISGen is a tool for generating a strongly typed C# class or typescript interface to make consuming LUIS output easier. So first we need to install the LUISGen - it is a dotnet tool - dotnet tool install -g LUISGen. Once the tool is installed, open the LUIS Portal, select the app from the dashboard and choose Export menu, and choose Export as JSON
It will open the JSON data in a new tab. Save it to your local folder - I created a folder called CognitiveModels in the Bot project and I saved it there. Next open powershell or command line window. And run the following command - luisgen .\notes.json -cs NotesBot.NotesRecognizerConvert - this command will converts the JSON to C# class.
Next you need to add the following entries in the appsettings.json file - LuisAppId, LuisAPIKey and LuisAPIHostName. You can get these values from LUIS portal.
Finally we need to modify the code in the Bot Application. I added a Constructor so that I can access the NotesRecognizer service. And in the OnMessageActivityAsync method, I am checking whether it is configured or not. And if configured, get the result from the NotesRecognizer. And from the result I am selecting the top intent and executing it. Here is my implementation.
To get the entities you can access the luisResult.Entities object. From which you can access properties like Note_Text and Note_Title etc.
In this post we explored how to integrate LUIS application to Bot application. Also we explored how to generate C# or Typescript code using LUISGen tool.