Tutorial: Use QnA Maker in your bot to answer questions

APPLIES TO: SDK v4

You can use the QnA Maker service to create a knowledge base to add question-and-answer support to your bot. When you create your knowledge base, you seed it with questions and answers.

In this tutorial, you learn how to:

  • Create a QnA Maker service and knowledge base
  • Add knowledge base information to your configuration file
  • Update your bot to query the knowledge base
  • Republish your bot

If you don't have an Azure subscription, create a free account before you begin.

Prerequisites

  • The bot created in the previous tutorial. You'll add a question-and-answer feature to the bot.
  • Some familiarity with QnA Maker is helpful. You'll use the QnA Maker portal to create, train, and publish the knowledge base to use with the bot.
  • Familiarity with QnA bot creation using Azure Bot Service.
  • Installed Maven, for Java only.

You should also already have the prerequisites for the previous tutorial.

Create a QnA Maker service and knowledge base

You'll import an existing knowledge base definition from the QnA Maker sample in the BotBuilder-Samples repo.

  1. Clone or copy the samples repo to your computer.
  2. Sign into to the QnA Maker portal with your Azure credentials.
  3. Select Create a knowledge base in the QnA Maker portal.
    1. If necessary, create a QnA service. (You can use an existing QnA Maker service or create a new one for this tutorial.) For more detailed QnA Maker instructions, see Create a QnA Maker service and Create, train, and publish your QnA Maker knowledge base.
    2. Connect your QnA Maker service to your knowledge base.
    3. Name your knowledge base.
    4. To populate your knowledge base, use the smartLightFAQ.tsv file from the samples repo. If you've downloaded the samples, upload the file smartLightFAQ.tsv from your computer.
    5. Select Create your kb to create the knowledge base.
  4. Select Save and train.
  5. Select PUBLISH to publish your knowledge base.

Once your QnA Maker app is published, select SETTINGS, and scroll down to Deployment details. Copy the following values from the Postman HTTP example request.

POST /knowledgebases/<knowledge-base-id>/generateAnswer
Host: <your-hostname>  // NOTE - this is a URL ending in /qnamaker.
Authorization: EndpointKey <qna-maker-resource-key>

The full URL string for your hostname will look like "https://<knowledge-base-name>.azure.net/qnamaker".

These values will be used within your bot configuration file in the next step.

The knowledge base is now ready for your bot to use.

Add knowledge base information to your bot

Use the following instructions connect your C#, JavaScript, Java, or Python bot to your knowledge base.

Add the following values to your appsetting.json file:

{
  "MicrosoftAppId": "",
  "MicrosoftAppPassword": "",
  "ScmType": "None",

  "QnAKnowledgebaseId": "knowledge-base-id",
  "QnAAuthKey": "qna-maker-resource-key",
  "QnAEndpointHostName": "your-hostname" // This is a URL ending in /qnamaker
}
Field Value
QnAKnowledgebaseId The knowledge base ID that the QnA Maker portal generated for you.
QnAAuthKey (QnAEndpointKey in Python) The endpoint key that the QnA Maker portal generated for you.
QnAEndpointHostName The host URL that the QnA Maker portal generated. Use the complete URL, starting with https:// and ending with /qnamaker. The full URL string will look like "https://<knowledge-base-name>.azure.net/qnamaker".

Now save your edits.

Update your bot to query the knowledge base

Update your initialization code to load the service information for your knowledge base.

  1. Add the Microsoft.Bot.Builder.AI.QnA NuGet package to your project.

    You can do this via the NuGet package manager or the command line:

    dotnet add package Microsoft.Bot.Builder.AI.QnA
    

    For more information on NuGet, see the NuGet documentation.

  2. In your Startup.cs file, add the following namespace reference.

    Startup.cs

    using Microsoft.Bot.Builder.AI.QnA;
    
  3. Modify the ConfigureServices method in Startup.cs to create a QnAMakerEndpoint object that connects to the knowledge base defined in the appsettings.json file.

    Startup.cs

    // Create QnA Maker endpoint as a singleton
    services.AddSingleton(new QnAMakerEndpoint
    {
        KnowledgeBaseId = Configuration.GetValue<string>("QnAKnowledgebaseId"),
        EndpointKey = Configuration.GetValue<string>("QnAAuthKey"),
        Host = Configuration.GetValue<string>("QnAEndpointHostName")
    });
    
  4. In your EchoBot.cs file, add the following namespace references.

    Bots\EchoBot.cs

    using System.Linq;
    using Microsoft.Bot.Builder.AI.QnA;
    
  5. Add an EchoBotQnA property and add a constructor to initialize it.

    EchoBot.cs

    public QnAMaker EchoBotQnA { get; private set; }
    
    public EchoBot(QnAMakerEndpoint endpoint)
    {
       // connects to QnA Maker endpoint for each turn
       EchoBotQnA = new QnAMaker(endpoint);
    }
    
  6. Add an AccessQnAMaker method:

    EchoBot.cs

    private async Task AccessQnAMaker(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
    {
       var results = await EchoBotQnA.GetAnswersAsync(turnContext);
       if (results.Any())
       {
          await turnContext.SendActivityAsync(MessageFactory.Text("QnA Maker Returned: " + results.First().Answer), cancellationToken);
       }
       else
       {
          await turnContext.SendActivityAsync(MessageFactory.Text("Sorry, could not find an answer in the knowledge base."), cancellationToken);
       }
    }
    
  7. Update the OnMessageActivityAsync method to call the new AccessQnAMaker method.

    EchoBot.cs

    protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
    {
        var replyText = $"Echo: {turnContext.Activity.Text}";
        await turnContext.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken);
    
        await AccessQnAMaker(turnContext, cancellationToken);
    }
    

Test your bot locally

At this point, your bot should be able to answer some questions. Run the bot locally and open it in the Emulator.

Sample interaction with the bot and QnA Maker.

Republish your bot

Now you can republish your bot back to Azure. Zip your project folder and then run the command to redeploy your bot.

Prepare your project files

Prepare your project files before you deploy your bot.

  1. Switch to your project's root folder. For C#, the root is the folder that contains the .csproj file.

  2. Do a clean rebuild in release mode.

  3. If you haven't done so before, run az bot prepare-deploy to add required files to the root of your local source code directory. This command generates a .deployment file in your bot project folder.

    az bot prepare-deploy --lang Csharp --code-dir "." --proj-file-path "<my-cs-proj>"
    
    Option Description
    lang The language or runtime of the bot. Use Csharp.
    code-dir The directory to place the generated deployment files in. Use your project's root folder. Default is the current directory.
    proj-file-path The path to the .csproj file for your bot, relative to the code-dir option.
  4. Within your project's root folder, create a zip file that contains all files and subfolders.

Republish your bot

Tip

If your session token expired, run az login again. If you aren't using your default subscription, also reset your subscription.

At this point, we are ready to deploy the code to the Azure Web App.

Run the following command from the command line to perform deployment using the Kudu zip push deployment for a web app.

az webapp deployment source config-zip --resource-group "<resource-group-name>" --name "<name-of-web-app>" --src "<project-zip-path>"
Option Description
resource-group The name of the Azure resource group that contains your bot.
name Name of the Web App you used earlier.
src The path to the zipped project file you created.

Note

This step can take a few minutes to complete. Also it can take a few more minutes between when the deployment finishes and when your bot is available to test.

Clean up resources

If you aren't going to use this application again, delete the associated resources with the following steps:

  1. In the Azure portal, open the resource group for your bot.
    1. Select Delete resource group to delete the group and all the resources it contains.
    2. Enter the resource group name in the confirmation pane, then select Delete.
  2. If you created a single-tenant or multi-tenant app:
    1. Go to the Azure Active Directory blade.
    2. Locate the app registration you used for your bot, and delete it.

Next steps

For information on how to add features to your bot, see the Send and receive text message article and the other articles in the how-to develop section.