Using Azure QnA Maker (MS Bot Framework V4 Edition)

Oct 4

Written by:
10/4/2018 7:33 PM  RssIcon

image

The Microsoft Bot Framework V4 allows you to create intelligent bots that interact naturally wherever your users are (text/SMS to Skype, Slack, Office 365 mail and other popular services). The Bot Builder V4 SDK offers new features and is extensible with a pluggable middleware model.

In this article we will build on the example started in the following article: Using LUIS -Language Understanding Intelligent Service (MS Bot Framework V4 Edition). In this article we will cover integrating the QnA Maker service into your Bot. Using the QnA Maker in your Bot allows you to create chat bots that are able to understand and respond to queries by simply looking at a list of questions and answers that you provide.

Tutorial Series

Other articles in this series:

Requirements

 

What Is QnA Maker?

According to the Microsoft QnA Maker website, the QnA Maker allows you to: “Build, train and publish a simple question and answer bot based on FAQ URLs, structured documents, product manuals or editorial content in minutes”. This really speeds your Bot development because it leverages the abilities of LUIS (Language Understanding Intelligent Service) to understand human conversation, and combines it with a service that allows you to provide a list of questions and answers, or simply upload a product manual or provide a link to a website, and the questions and answers will be parsed for you automatically.

The end result is an incredible amount of functionality that you can add to your Bot easily.

 

Create The QnA Maker Service

image

To get started, go to: https://www.qnamaker.ai/, and sign in with your Azure account.

image

Select Create a knowledge base.

image

Select Create a QnA service.

Note: This will open a new web browser window.

image

Fill in the details to create the service and click the Create button.

image

Return to the https://www.qnamaker.ai/ site (the site should still be open on it’s original web browser tab/window).

Scroll down the page to the STEP 2 section.

Click the refresh this page link.

image

The page will query Azure to detect any newly added services.

image

You will now be able to select the service you just created.

image

Scroll down the page to the STEP 3 section.

Give the QnA database a name

image

Scroll down the page to the STEP 4 section.

Add a URL to a web page that contains FAQs (Frequently Asked Questions).

(or upload a file with question and answer pairs).

image

Scroll down the page to the STEP 5 section.

Click the Create your KB button.

image

The knowledgebase will be created.

image

The questions and answers detected on the page will be loaded.

You can update and edit them at this point.

For now, just click the Save and train button.

image

The knowledgebase will be updated.

image

Select PUBLISH.

image

Click the Publish button.

image

The knowledgebase will be published.

image

The connection settings will display.

Save them, you will need them later.

Note: You can always get back to these settings by selecting My knowledge bases from the main menu, then View Code for the service.

 

Update The Bot Code

image

Open the project created in the article: Using LUIS -Language Understanding Intelligent Service (MS Bot Framework V4 Edition) in Visual Studio 2017 (or higher).

Right-click on the project node and select Manage NuGet Packages.

image

Search for Microsoft.Bot.Builder.Ai.QnA.

Click on Microsoft.Bot.Builder.Ai.QnA, then click the Install button.

(accept any other screens that appear and fully install the package)

image

Open the Startup.cs file.

Add the following using statement to the top of the file:

 

using Microsoft.Bot.Builder.AI.QnA;

 

Add the following code at the end of ConfigureServices method (but still inside the method):

 

        // Create and register a QnA service and knowledgebase
        services.AddSingleton(sp =>
        {
            var hostPath = "** Your Host **";
            var endpointKey = "** Your EndpointKey **";
            var knowledgebaseId = "** Your KnowledgeBaseId **";
            var qnaOptions = float.TryParse("0.4F", out float scoreThreshold)
                ? new QnAMakerOptions {
                    ScoreThreshold = scoreThreshold, Top = 1 } : null;
            return new QnAMaker(
                new QnAMakerEndpoint
                {
                    EndpointKey = endpointKey,
                    Host = hostPath,
                    KnowledgeBaseId = knowledgebaseId,
                },
                qnaOptions);
        });

 

Note:

  • Enter the Host you saved earlier where it indicates ** Your Host ** (it must be between the quotes)
  • Enter the EndpointKey you saved earlier where it indicates ** Your EndpointKey ** (it must be between the quotes)
  • Enter the KnowledgeBaseId you saved earlier where it indicates ** Your KnowledgeBaseId ** (it must be between the quotes)

Also, if you downloaded the code from the Download page on this site, ensure that you have LUIS keys for the LUIS sections in the code (See: Using LUIS -Language Understanding Intelligent Service (MS Bot Framework V4  Edition)).

This code returns a QnAMaker that will them be injected into the main code (in the EchoBot.cs file) using dependency injection.

image

Open the EchoBot.cs file.

Add the following using statements to the top of the file:

 

using Microsoft.Bot.Builder.AI.QnA;
using System.Linq;

 

Add the following global property to the class:

 

private QnAMaker QnA { get; } = null;

 

Alter the constructor for the class to the following to pass in the QnAMaker (using dependency injection):

 

public EchoWithCounterBot(EchoBotAccessors accessors, LuisRecognizer luis, QnAMaker qna)

 

Inside the constructor ad the following code to set the value of the global variable:

 

            // The incoming QnA variable is the QnAMaker we added above.
            this.QnA = qna ?? throw new System.ArgumentNullException(nameof(qna));

 

Change the following code:

 

        // Echo back to the user whatever they typed.
        var responseMessage =
            $"Turn {state.TurnCount}: {user.Name} you said '{turnContext.Activity.Text}'\n";
        await turnContext.SendActivityAsync(responseMessage);
 

To (this adds code to call the QnA Service):

 

        // Give QnA Maker a chance to answer
        var answers = await this.QnA.GetAnswersAsync(turnContext);
        if (answers.Any())
        {
            // If the service produced one or more answers, send the first one.
            await turnContext.SendActivityAsync(answers[0].Answer);
        }
        else
        {
            // Echo back to the user whatever they typed.
            var responseMessage =
                $"Turn {state.TurnCount}: {user.Name} you said '{turnContext.Activity.Text}'\n";
            await turnContext.SendActivityAsync(responseMessage);
        }

 

Run The Updated Code

image

We can now run the application and connect to it with the Bot Framework Emulator (V4) (see: Creating a Hello World! Bot (MS Bot Framework V4 Edition) for information on how to do that).

image

The Bot will behave as before, however, when asked a question that can be answered by the QnA service, it will provide the answer.

However, if the QnA service cannot provide an answer, it wont, and the normal code will run.

 

Links

Azure Bot Service Documentation for the v4 SDK

www.qnamaker.ai

What is QnA Maker?

Create a QnA Bot with Azure Bot Service

QnA Maker Documentation

Integrate QnA Maker and LUIS to distribute your knowledge base

Choosing capacity for your QnA Maker deployment

 

Download

You can download the code from the Download page