Azure botframework SDKV4 can be used with LUIS models and QnA Maker knowledge bases. It helps to determine which LUIS model or QnA Maker knowledge base best matches the user input.
In this tutorial, you will learn the following.
- Build SDKV4 Bot Framework Project
- Build Luis App
- Build QnA Maker
- Build and test your bot with Emulator.
Let's understand the information flow.
Azure Bot framework (SDKV4) interacts with waterfall dialog model. Waterfall dialog model has three basic parameters; i.e.:
- Intro Step Async -> Used to initalize the luis configuration.
- Act Step Async -> Used to gather all potiential information and process the request based on defined intent.
- Final StepAsync -> Used to restart or call the mail dialog again.
On Memebr Added Async is called as and when a member is added and is used to greet the members.
OnMessageActivityAsync is called for each user input received. This module finds the top scoring user intent and is used to process the request based on defined intent or QnA Maker.
Step 1 - Create a VS Project using BotFramework V4 (Echo Bot)
Select echo bot and click next to select the location and finsh.
Step 2 - Visual Studio Project Strucutre
VS project strucutre looks like this,
Installing packages
Prior to running this app for the first time ensure that several NuGet packages are installed,
- Microsoft.Bot.Builder
- Microsoft.Bot.Builder.AI.Luis
- Microsoft.Bot.Builder.AI.QnA
Step 3 - Create Luis Recognizer Class
Luis recognizer class implements IRecognizer interface. This method will help to recognize the intent and entity.
In LusRecognizer.cs, the information contained within configuration file appsettings.json is used to connect your bot to the Luis. The constructors use the values you provided to connect to these services.
- private readonly LuisRecognizer _recognizer;
- public LusRecognizer(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"]);
- var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
- {
- PredictionOptions = new Microsoft.Bot.Builder.AI.LuisV3.LuisPredictionOptions
- {
- IncludeInstanceData = true,
- }
- };
- _recognizer = new LuisRecognizer(recognizerOptions);
- }
- }
Step 4 - Create Main Dialog class
Main Dialog class implements the ComponentDialog. This class method will be responsible to define the waterfall model and is based on defined intent which helps to process the query.
Initalize the constructor
- private readonly LusRecognizer _luisRecognizer;
- public QnAMaker qnAMakerObject { get; private set; }
- // Dependency injection uses this constructor to instantiate MainDialog
- public MainDialog(LusRecognizer luisRecognizer, QnAMakerEndpoint endpoint)
- : base(nameof(MainDialog))
- {
- _luisRecognizer = luisRecognizer;
- qnAMakerObject = new QnAMaker(endpoint);
- AddDialog(new TextPrompt(nameof(TextPrompt)));
- AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
- {
- IntroStepAsync,
- ActStepAsync,
- FinalStepAsync,
- }));
- // The initial child Dialog to run.
- InitialDialogId = nameof(WaterfallDialog);
- }
Initilaize the Intro Step Asyc Method -> It will help to intialize or create the Luis Object,
- private async Task<DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
- {
- if (!_luisRecognizer.IsConfigured)
- {
- //await stepContext.Context.SendActivityAsync( MessageFactory.Text("NOTE: LUIS is not configured. To enable all capabilities, add 'LuisAppId', 'LuisAPIKey' and 'LuisAPIHostName' to the appsettings.json file.", inputHint: InputHints.IgnoringInput), cancellationToken);
- return await stepContext.NextAsync(null, cancellationToken);
- }
- return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { }, cancellationToken);
- }
Initilaize the Act Step Asyc Method -> It will help to gather all potienial information to process the request based on defined intent.
When the model produces a result, it indicates which service can most appropriately process the utterance. The code in this bot routes the request to the corresponding service, and then summarizes the response from the called service. Depending on the intent returned, this code uses the returned intent to route to the correct LUIS model or QnA service.
- private async Task<DialogTurnResult> ActStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
- {
- // Call LUIS and gather any potential booking details. (Note the TurnContext has the response to the prompt.)
- var luisResult = await _luisRecognizer.RecognizeAsync<CognitiveModel>(stepContext.Context, cancellationToken);
- switch (luisResult.TopIntent().intent)
- {
- case CognitiveModel.Intent.LeaveRequest:
- //Do processing.
- await stepContext.Context.SendActivityAsync(MessageFactory.Text("Luis Intent Called i.e. Leave Request"), cancellationToken);
- break;
- default:
- var results = await qnAMakerObject.GetAnswersAsync(stepContext.Context);
- if (results.Length > 0)
- {
- var answer = results.First().Answer;
- await stepContext.Context.SendActivityAsync(MessageFactory.Text(answer), cancellationToken);
- }
- else
- {
- Activity reply = ((Activity)stepContext.Context.Activity).CreateReply();
- reply.Text = $"😢 **Sorry!!! I found nothing** \n\n Please try to rephrase your query.";
- await stepContext.Context.SendActivityAsync(reply);
- }
- break;
- }
- return await stepContext.NextAsync(null, cancellationToken);
- }
Initilaize the Final Step Asyc Method -> It will help to re-initiate the dialog,
- private async Task<DialogTurnResult> FinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
- {
- return await stepContext.ReplaceDialogAsync(InitialDialogId, null, cancellationToken);
- }
Step 5 - Manually update your appsettings.json file
Once all of your service apps are created, the information for each needs to be added into your 'appsettings.json' file.
For each of the entities shown below, add the values you recorded earlier in these instructions,
appsettings.json
- "MicrosoftAppId": "",
- "MicrosoftAppPassword": "",
- "QnAKnowledgebaseId": "<knowledge-base-id>",
- "QnAEndpointKey": "<qna-maker-resource-key>",
- "QnAEndpointHostName": "<your-hostname>",
- "LuisAppId": "<app-id->",
- "LuisAPIKey": "<your-luis-endpoint-key>",
- "LuisAPIHostName": "<your--app-region>",
Step 6 - Create Luis App
Log into the Luis web portal "https://www.luis.ai" Under the My apps section, select the create new app. The following Dialog Box will appear:
Step 7 - Define Luis Model
- Select the build button to define intent and entity
- Select Intent
- Enter phrases; i.e., "apply 2 days sick leave"
- Select Entities
- Add Pre-defined entitiy i.e. number , Date & time and custom entity i.e. Leave Type.
- Train the Model
- Publish the Model
Choose the 'production' environment and then select the Publish button.
Once your new LUIS app has been published, select the MANAGE Tab. From the 'Application Information' page, record the values Application ID as "app-id-for-app" and Display name as "name-of-app". From the 'Key and Endpoints' page, record the values Authoring Key as "your-luis-authoring-key" and Region as "your-region". These values will later be used within your 'appsetting.json' file.
Step 8 - Create QnA Maker knowledge base
The first step to setting up a QnA Maker knowledge base is to set up a QnA Maker service in Azure. To do that, follow the step-by-step instructions found here.
Once your QnA Maker Service has been created in Azure, you need to record the Cognitive Services Key 1 provided for your QnA Maker service. This will be used as <azure-qna-service-key1> when adding the QnA Maker app to your dispatch application.
Now sign in to the QnAMaker web portal. https://qnamaker.ai
- Your Azure AD account.
- Your Azure subscription name.
- The name you created for your QnA Maker service. (If your Azure QnA service does not initially appear in this pull down list, try refreshing the page.)
- Create QnA
- Provide a name for your QnA Maker knowledge base. For this example use the name 'sample-qna'.
- Select the option + Add File, navigate to the CognitiveModel folder of your sample code, and select the file 'QnAMaker.tsv'. There is an additional selection to add a Chit-chat personality to your knowledge base but our example does not include this option.
- Create QnA
- Select Create your knowledge base.
- Once the knowledge base is created from your uploaded file, select Save and train and when finished, select the PUBLISH Tab and publish your app.
- Once your QnA Maker app is published, select the SETTINGS Tab, and scroll down to 'Deployment details'. Record the following values from the Postman Sample HTTP request.
Step9 - Add Luis & QnaMaker Keys, ID and Endpoint to VS solution
Service authoring keys
The authoring key is only used for creating and editing the models. You need an ID and key for each of the two LUIS apps and the QnA Maker app.
App | Location of information |
LUIS App ID | In the LUIS portal, for each LUIS app, in the Manage section, select Keys and Endpoint settings to find the keys associated with each app. If you are following this tutorial, the endpoint key is the same key as the <your-luis-authoring-key>. The authoring key allows for 1000 endpoint hits then expires. |
QnA Maker App ID | In the QnA Maker portal, for the knowledge base, in the Manage settings, use the key value shows in the Postman settings for the Authorization header, without the text of EndpointKey. |
Update these values into Appsetting.json file.
Step 10 - Test your bot
- Using your development environment, start the sample code. Note the localhost address shown in the address bar of the browser window opened by your App: "https://localhost:<Port_Number>".
- Open your Bot Framework Emulator, then select Create a new bot configuration. A .bot file enables you to use the Inspector in the bot emulator to see the JSON returned from LUIS and QnA Maker.
- In the New bot configuration dialog box, enter your bot name, and your endpoint URL, such as http://localhost:3978/api/messages. Save the file at the root of your bot sample code project.
- Select the bot name in the My Bots list to access your running bot
Output
First, the bot prompts with a greeting message.
Second, the user asks a query, the system defines the intent -> it goes to Luis and responds.
Third, the user asks a non-intent question -> it goes to qna maker and responds.
I hope you have enjoyed and learned something new in this article. Thanks for reading and stay tuned for the next article.