In this lab, you will set up and run your first functional bot. It takes you beyond the basics by connecting your chat bot with a knowledge base deployed in Azure. Upon completion, developers should have:
- Installed the prerequisites to build a bot
- Learned the basics of a bot project
- Tested the bot using the Bot Framework Emulator
- Set up a knowledge base in Azure using the QnA Maker
- Tested the knowledge base on the QnA Maker website
- Exported and imported a knowledge base
- Integrated a bot application with the QnA Maker API
This module will walk you through the process of setting up the tools required to build and test your bot.
Navigate to https://visualstudio.microsoft.com/downloads/
Choose an edition of Visual Studio. For this lab, any edition will work.
The download installs the installer (not Visual Studio itself). When the installer starts, select “ASP.NET and web development”, “Azure development”, and “.NET Core cross-platform development”. Click “Install”
Wait
When it’s done, you’ll be asked to sign in. You can sign in or choose to do so later. Go ahead in sign in, because if you don’t do so now, you’ll have to do so in a few seconds.
Close Visual Studio and the Visual Studio Installer
Navigate to https://github.com/Microsoft/BotFramework-Emulator/releases and install the latest version
Navigate to https://botbuilder.myget.org/gallery/aitemplates and choose the latest version of “Bot Builder SDK Template for Visual Studio”
Download and install
Start Visual Studio (you should not need to restart Windows)
In this module, you will create and run a bot using the predefined templates provided to Visual Studio.
Create a new project
Create a new "Bot Builder Echo Bot V4" project
Start the project
Start the Bot Framework Emulator
Click "Open Bot"
Select the BotConfiguration.bot file in the project you just created
Type anything in the chat window. The EchoBot will respond by echoing back your message.
Work with a partner to identify where the turn is being processed. Modify the code to respond “Polo” when “Marco” is typed.
Look at how EchoBotAccessors.cs works. Modify it to save the user’s name if they type “My name is [name]”
Modify the bot to respond “Hello, it’s nice to meet you” when the user types “hello”, but only the first time the user types “hello”. Double bonus if you have it include the user's name if provided in the previous bonus exercise.
In this module, you will learn how to create and configure a knowledge base using the Microsoft QnA Maker. You will also create a bot from a blank project and connect it to the QnA Maker API to provide interactive knowledge base functionality.
Navigate to https://www.qnamaker.ai
If you have not signed in, do so now.
Click "Create a knowledge base"
Create a QnA service in Azure
Navigate to www.qnamaker.ai, and refresh the page. You should now be able to select the QnA service
Name your KB. For this exercise, any name will do
Skip "STEP 4". Click "Create your KB" in "STEP 5"
Click "Add QnA pair"
When inspecting the answer to “Do you have a name?” Have HAL9000 answer “Yes, I have a name. My friends call me HAL. You may call me HAL9000.”
Brainstorm with a partner to add alternative phrasings to the name question
Explore the Settings section of your KB. Export the knowledge base file and inspect it.
In this module, we create a new QnA service and import a pre-configured file. We then will create a new bot project and connect it to the QnA service.
In QnA Maker (www.qnamaker.ai), click “Create a new knowledge base”
Select the options for "STEP 2"
Name the KB "HAL Bot 9000"
In "STEP 4", you can connect to a URL or upload a file during setup. We'll skip this step and connect after the KB is set up.
In "STEP 5", create the KB
Go to "Settings"
Add KB file by URL or file
By File:
Click "Add File" under "File Name"
If you pulled the lab content from GitHub, you can find the file in \labs\lab1\module4\models\HAL9000_QnA.tsv
Click "Save and train"
By URL
In the “URL” text box, paste the following URL: https://raw.githubusercontent.com/BlueMetal/BackMeUpBIAD/master/labs/lab1/module4/models/HAL9000_QnA.tsv
Click "Save and train"
Return to "EDIT" to see the questions and answers populated.
Click on "PUBLISH", then on the "Publish" button
Create a new "Bot Builder Echo Bot V4" project
Change the "Target Framework" to ".Net Core 2.1" in the project properties
The current version of the libraries require .NET Core 2.1, so we must update this setting before updating libraries.
Click “Managed NuGet Packages” in the “Dependencies” context menu for the project. This is because you won’t be able to update the packages (next step) until you do so.
You’ll need to update your packages before importing the QnA package
Navigate to “Browse”, and add “Microsoft.Bot.Builder.AI.QnA”
Change the name of EchoWithCounterBot to HalBot
Locate “BotConfiguration.bot”. Paste the following configuration at the end of the “services” collection.
{
"type": "qna",
"name": "hal-bot-9000",
"kbId": "",
"endpointKey": "",
"hostname": "",
"id": "2"
}In the KB you just created on https://www.qnamaker.ai, navigate to “SETTINGS” to get “kbID”, “endpointKey”, and “hostname”
.Net Core uses dependency injection to provide services to its middleware. We register dependencies using the IServicesCollection interface provided to the ConfigureServices method of Startup.cs.
Delete the file EchoBotAccessors.cs
Delete the file CounterState.cs
Remove the EchoBotAccessors references from HalBot.cs
- Remove from constructor signature
- Remove from constructor body
- Remove from fields
Open Startup.cs
Add a method to configure the bot
private void ConfigureBot(BotFrameworkOptions options, ICredentialProvider credentialProvider)
{
// Set the CredentialProvider for the bot. It uses this to authenticate with the QnA service in Azure
options.CredentialProvider = credentialProvider
?? throw new InvalidOperationException("Missing endpoint information from bot configuraiton file.");
// Creates a logger for the application to use.
ILogger logger = _loggerFactory.CreateLogger<HalBot>();
// Catches any errors that occur during a conversation turn and logs them.
options.OnTurnError = async (context, exception) =>
{
logger.LogError($"Exception caught : {exception}");
await context.SendActivityAsync("Sorry, it looks like something went wrong.");
};
// The Memory Storage used here is for local bot debugging only. When the bot
// is restarted, everything stored in memory will be gone.
IStorage dataStore = new MemoryStorage();
// Create Conversation State object.
// The Conversation State object is where we persist anything at the conversation-scope.
var conversationState = new ConversationState(dataStore);
options.State.Add(conversationState);
}Replace the contents of the ConfigureServices method with the following:
var secretKey = Configuration.GetSection("botFileSecret")?.Value;
var botFilePath = Configuration.GetSection("botFilePath")?.Value;
// Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection.
var botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", secretKey);
services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded. ({botConfig})"));
// Retrieve current endpoint.
var environment = _isProduction ? "production" : "development";
ICredentialProvider credentialProvider = null;
foreach (var service in botConfig.Services)
{
switch (service.Type)
{
case ServiceTypes.Endpoint:
if (service is EndpointService endpointService)
{
credentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);
}
break;
case ServiceTypes.QnA:
if (service is QnAMakerService qnaMakerService)
{
var qnaEndpoint = new QnAMakerEndpoint
{
Host = qnaMakerService.Hostname,
EndpointKey = qnaMakerService.EndpointKey,
KnowledgeBaseId = qnaMakerService.KbId,
};
services.AddSingleton(new QnAMaker(qnaEndpoint));
}
break;
}
}
services.AddBot<HalBot>(options => ConfigureBot(options, credentialProvider));Add QnAMaker to the constructor and state of the HalBot class
- Add to fields
- Add to constructor signature
- Add to constructor body
Replace the contents of the OnTurnAsync method with the following:
if (turnContext.Activity.Type == ActivityTypes.Message)
{
if (string.IsNullOrWhiteSpace(turnContext.Activity.Text))
{
await turnContext.SendActivityAsync(MessageFactory.Text("This doesn't work unless you say something first."), cancellationToken);
return;
}
var results = await _qnaMaker.GetAnswersAsync(turnContext).ConfigureAwait(false);
if (results.Any())
{
var topResult = results.First();
await turnContext.SendActivityAsync(MessageFactory.Text(topResult.Answer), cancellationToken);
}
else
{
await turnContext.SendActivityAsync(MessageFactory.Text("I'm sorry Dave, I don't understand you."), cancellationToken);
}
}
else
{
await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected");
}Run the code and test the bot using the Bot Framework Emulator.
Check out the GitHub Project https://github.com/Microsoft/BotBuilder-PersonalityChat/tree/master/CSharp/Datasets. Add a chitchat dataset to your service.
Explore the documentation for chit chat (https://docs.microsoft.com/en-us/azure/cognitive-services/qnamaker/how-to/chit-chat-knowledge-base) and augment the chit chat you added in the previous exercise with new QnA









































