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 have 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 you 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

You can now republish your bot back to Azure. Zip your project folder and then run the command to deploy your bot to Azure. For details, see how to Deploy your bot.

Zip your project folder

When using the non-configured zip deploy API to deploy your bot's code, Web App/Kudu's behavior is as follows:

Kudu assumes by default that deployments from .zip files are ready to run and don't require extra build steps during deployment, such as npm install or dotnet restore/dotnet publish.

It's important to include your built code with all necessary dependencies in the zip file being deployed, otherwise your bot will not work as intended. For more information, see the Azure documentation on how to Deploy files to App Service.

Important

Before zipping your project files, make sure that you are in the bot's project folder.

  • For C# bots, it's the folder that has the .csproj file.
  • For JavaScript bots, it's the folder that has the app.js or index.js file.
  • For TypeScript bots, it's the folder that includes the src folder (where the bot.ts and index.ts files are).
  • For Python bots, it's the folder that has the app.py file.

Within the project folder, make sure you select all the files and folders before running the command to create the zip file. This will create a single zip file within the project folder. If your root folder location is incorrect, the bot will fail to run in the Azure portal.

Deploy your code to Azure

Tip

If your session token expired, run az login again. If you are not 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.

If you're not going to continue to use this application, delete the associated resources with the following steps:

  1. In the Azure portal, open the resource group for your bot.
  2. Select Delete resource group to delete the group and all the resources it contains.
  3. Enter the resource group name in the confirmation pane, then select Delete.

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.