The Microsoft Bot Framework is an increbible tool from Microsoft. It makes building chatbots easier and more accessible than ever. That means you can build awesome conversational chatbots for a range of platforms, including Facebook and Slack. In this tutorial, you'll learn how to build an FAQ chatbot using Microsoft Bot Framework and ASP.NET Core.
This tutorial has been taken from .NET Core 2.0 By Example.
Let's get started. You're chatbot that can respond to simple queries such as:
This should provide a good foundation for you to go further and build more complex chatbots with the Microsoft Bot Framework, The more you train the Bot and the more questions you put in its knowledge base, the better it will be. If you're a UK based public sector organisation then ICS AI offer conversational AI solutions built to your needs. Their Microsoft based infrastructure runs chatbots augmented with AI to better serve general public enquiries.
First of all, we need to create a page that can be accessed anonymously, as this is frequently asked questions (FAQ ), and hence the user should not be required to be logged in to the system to access this page.
To do so, let's create a new controller called FaqController in our LetsChat.csproj. It will be a very simple class with just one action called Index, which will display the FAQ page. The code is as follows:
[AllowAnonymous] public class FaqController : Controller { // GET: Faq public ActionResult Index() { return this.View(); } }
Notice that we have used the [AllowAnonymous] attribute, so that this controller can be accessed even if the user is not logged in. The corresponding .cshtml is also very simple. In the solution explorer, right-click on the Views folder under the LetsChat project and create a folder named Faq and then add an Index.cshtml file in that folder. The markup of the Index.cshtml would look like this:
@{ ViewData["Title"] = "Let's Chat"; ViewData["UserName"] = "Guest"; if(User.Identity.IsAuthenticated) { ViewData["UserName"] = User.Identity.Name; } } <h1> Hello @ViewData["UserName"]! Welcome to FAQ page of Let's Chat </h1> <br />
Nothing much here apart from the welcome message. The message displays the username if the user is authenticated, else it displays Guest.
Now, we need to integrate the Chatbot stuff on this page. To do so, let's browse http://qnamaker.ai. This is Microsoft's QnA (as in questions and answers) maker site which a free, easy-to-use, REST API and web-based service that trains artificial intelligence (AI) to respond to user questions in a more natural, conversational way. Compatible across development platforms, hosting services, and channels, QnA Maker is the only question and answer service with a graphical user interface—meaning you don’t need to be a developer to train, manage, and use it for a wide range of solutions. And that is what makes it incredibly easy to use. You would need to log in to this site with your Microsoft account (@microsoft/@live/@outlook).
If you don't have one, you should create one and log in. On the very first login, the site would display a dialog seeking permission to access your email address and profile information. Click Yes and grant permission:
You would then be presented with the service terms. Accept that as well. Then navigate to the Create New Service tab. A form will appear as shown here:
The form is easy to fill in and provides the option to extract the question/answer pairs from a site or .tsv, .docx, .pdf, and .xlsx files. We don't have questions handy and so we will type them; so do not bother about these fields.
Just enter the service name and click the Create button. The service should be created successfully and the knowledge base screen should be displayed. We will enter probable questions and answers in this knowledge base. If the user types a question that resembles the question in the knowledge base, it will respond with the answer in the knowledge base. Hence, the more questions and answers we type, the better it will perform.
So, enter all the questions and answers that you wish to enter, test it in the local Chatbot setup, and, once you are happy with it, click on Publish. This would publish the knowledge bank and share the sample URL to make the HTTP request. Note it down in a notepad. It contains the knowledge base identifier guide, hostname, and subscription key. With this, our questions and answers are ready and deployed.
We need to display a chat interface, pass the user-entered text to this service, and display the response from this service to the user in the chat user interface. To do so, we will make use of the Microsoft Bot Builder SDK for .NET and follow these steps:
We have a working bot in place which just returns the text along with its length.
We need to modify this bot, to pass the user input to our QnA Maker service and display the response returned from our service. To do so, we will need to check the code of MessagesController in the Controllers folder. We notice that it has just one method called Post, which checks the activity type, does specific processing for the activity type, creates a response, and returns it. The calculation happens in the Dialogs.RootDialog class, which is where we need to make the modification to wire up our QnA service. The modified code is shown here:
private static string knowledgeBaseId = ConfigurationManager.AppSettings["KnowledgeBaseId"]; //// Knowledge base id of QnA Service.
private static string qnamakerSubscriptionKey =
ConfigurationManager.AppSettings["SubscriptionKey"]; ////Subscription
key.
private static string hostUrl =
ConfigurationManager.AppSettings["HostUrl"];
private async Task MessageReceivedAsync(IDialogContext context,
IAwaitable<object> result)
{
var activity = await result as Activity;
// return our reply to the user
await
context.PostAsync(this.GetAnswerFromService(activity.Text));
context.Wait(MessageReceivedAsync);
}
private string GetAnswerFromService(string inputText)
{
//// Build the QnA Service URI
Uri qnamakerUriBase = new Uri(hostUrl);
var builder = new UriBuilder($"{qnamakerUriBase}/knowledgebases
/{knowledgeBaseId}/generateAnswer");
var postBody = $"{{"question": "{inputText}"}}";
//Add the subscription key header
using (WebClient client = new WebClient())
{
client.Headers.Add("Ocp-Apim-Subscription-Key",
qnamakerSubscriptionKey);
client.Headers.Add("Content-Type", "application/json");
try
{
var response = client.UploadString(builder.Uri,
postBody);
var json = JsonConvert.DeserializeObject<QnAResult>
(response);
return json?.answers?.FirstOrDefault().answer;
}
catch (Exception ex)
{
return ex.Message;
}
}
}
The code is pretty straightforward. First, we add the QnA Maker service subscription key, host URL, and knowledge base ID in the appSettings section of Web.config. Next, we read these app settings into static variables so that they are available always. Next, we modify the MessageReceivedAsync method of the dialog to pass the user input to the QnA service and return the response of the service back to the user. The QnAResult class can be seen from the source code.
Our simple FAQ bot using the Microsoft Bot Framework and ASP.NET Core 2.0 is now ready!