Chatbots are becoming more popular nowadays with the release of ChatGPT, Google Bard, etc. ChatGPT is an etc. AI chatbot developed by Open AI that can write articles, give answers to questions, compose essays, etc. A Microsoft Bot Framework Chatbot Development is an application program that simulates human conversation and replies to users based on the data and rules on which the chatbot is trained. Chatbots are integrated into mobile application, websites, Facebook Messenger, etc. Chatbots utilize natural language processing (NLP) to understand the user’s intent and respond using AI-based decision-making.
In this guide, I’ll show you to develop a chatbot for a real-world scenario. We will develop a chatbot to take details from users to register them for a conference.
In this guide, we will learn:
This article was published as a part of the Data Science Blogathon.
A bot is an application program that simulates human conversation and replies to users based on the data and rules on which the bot is trained. Users communicate with a bot using adaptive cards, forms, text, audio, images, etc. Bots can be used to perform tasks such as gathering information from users for booking a flight ticket, paying electricity bills, resolving user queries based on a FAQ document, etc. Bots recognize the intent of the user questions using NLP and respond to them using AI-based decision-making.
Design the bot by keeping in mind the phrase, syntax, and other things used in human conversation. A great bot doesn’t require users to repeat themselves many times, has a good flow while gathering information, and gives a satisfactory response to questions when asked in a twisted way. Based on the configuration, the bot can respond to user messages using video, images, documents, etc. Bots are designed to intelligently respond to user queries, provide customer services to the users, or help the user to perform tasks like ticket booking, paying bills, etc.
Users can interact with bots through a channel such as Slack, mobile applications, websites, Facebook Messenger, etc. Depending on the user’s response to a question, the bot can ask the additional relevant information from the user or access the services on the user’s behalf. Then from the bot’s response, users can understand what the bot has done and make the required corrections based on the prompts provided by the bot.
Microsoft Bot Framework Chatbot Development is a collection of functions, libraries, tools, and services that helps developers easily develop, debug, test, and deploy bots. Using Microsoft Bot Framework, developers can create bots having advanced capabilities such as NLP, getting more trained and increasingly valuable from user inputs, etc. Design the bot by keeping in mind the phrase, syntax, and other things used in human conversation. Users can interact with bots through a channel such as Slack, mobile applications, websites, Facebook Messenger, etc.
We can develop bots in C#, Python, Java, or JavaScript programming language using Bot Framework SDK. Bots developed using Microsoft Bot Framework Chatbot Development can easily use other Azure Services such as Azure SQL, Azure Blob Storage, or Azure Cosmos DB for storage purposes. We can use Azure Cognitive Services such as Custom Question Answering, Azure LUIS, etc. in the bot to add NLP capabilities.
Follow the below steps to build a bot using Microsoft Bot Framework:
Below are some important Development Concepts in Microsoft Bot Framework:
All the interactions between users and bots are known as activities. The interaction may happen in the form of images, audio, video, text, etc. In normal human conversation, people speak one at a time to express their opinion. Similarly, in bot conversation, the bot responds to the user when the bot turn came. Generally, at the start of a bot conversation, the bot greets the user. Based on the user’s query or action, the bot responds to the user using the data.
The bot does event-driven conversations with the help of an activity handler. Based on the activity or sub-activity type, the bot decodes which activity handler will handle that activity. For example, whenever you add a new member to the bot conversation OnMembersAddedAsync() gets called to handle the user-welcoming logic.
Microsoft Bot Framework SDK provides state management functionality and a storage layer to manage the data storage and states efficiently. Maintaining state helps in having better conversation flow as we can save the provided by users in the previous turns which is very beneficial in a multi-turn conversation. Depending on the type of data, budget, and requirement, we can use different data storage services such as Memory Storage, SharePoint Online, Azure SQL, Cosmos DB, Azure Blob storage, etc. for storing data.
Microsoft Bot Framework provides several templates for developing bots in C# and Python. An empty bot template provides a basic code structure for the bot and greets the user. The echo bot template provides the functionality of echoing the text entered by the user. The core bot template provides LUIS, Custom Question Answering capabilities, component dialog, and child dialog to effectively manage user conversations.
Intent is a task that the user wants to perform. Entities are important information or keywords in a text. Utterances are the inputs given by the user. For example, in a flight booking scenario when a user provides input to a bot as “Book a flight from Mumbai to Pune for
24th May 2023”. Here, booking a flight is intent, Mumbai and Pune are entities, and Booking a flight from Mumbai to Pune for 24th May 2023 is utterance.
Dialogs provide ways to manage conversations with users. We can pass arguments or parameters to dialogs. A dialog can be started, paused, resumed, or stopped.
Dialogs are very useful in implementing multi-turn conversations. For example, if we want to develop a bot that suggests weekend activities and highly rated restaurants based on the user’s input like their hobbies and favorite food, we can use dialogs. Bot Framework provides various types of dialogs such as waterfall dialog, prompt dialog, adaptive dialog, QnA Maker dialog, etc. to efficiently manage the conversation with users. For example, use a Prompt dialog to take input from the user and validate input.
Keep the below principles in mind while designing a bot:
Now, we have a good understanding of the principles of bot design and Microsoft Bot Framework Chatbot Development key concepts. Let’s now develop a bot for taking user details for registering them for Analytics Vidhya Conference using the Core bot template, Prompts, and Dialogs in the Microsoft bot framework. Follow the below steps:
1. Open Visual Studio-> Create New Project-> Search for Empty Bot template and select it.
2. Click Next. Provide ConferenceBot as the Project name and click Create.
3. Install the NuGet packages: AdaptiveCards and Microsoft.Bot.Builder.Dialogs.Declarative
4. Create a new file ConferenceBot.cs inside the new folder Bots in the project. Paste the below code snippet in the file:
namespace ConferenceBot.Bots
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AdaptiveCards;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
public class ConferenceBot<T> : ActivityHandler where T : Dialog
{
protected readonly Dialog Dialog;
protected readonly BotState ConversationState;
protected readonly BotState UserState;
protected readonly ILogger Logger;
public ConferenceBot(
ConversationState conversationState, UserState userState,
T dialog, ILogger<ConferenceBot<T>> logger)
{
ConversationState = conversationState;
UserState = userState;
Dialog = dialog;
Logger = logger;
}
public override async Task OnTurnAsync(
ITurnContext tc, CancellationToken ct = default)
{
await base.OnTurnAsync(tc, ct);
await ConversationState.SaveChangesAsync(tc, false, ct);
await UserState.SaveChangesAsync(tc, false, ct);
}
protected override async Task OnMessageActivityAsync(
ITurnContext<IMessageActivity> tc,
CancellationToken ct)
{
Logger.LogInformation("Running dialog with Message Activity.");
await Dialog.RunAsync(tc,
ConversationState.CreateProperty<DialogState>
(nameof(DialogState)), ct);
}
Here, the OnTurnAsync method is used to process the action waiting on the queue. The OnMessageActivityAsync method is called for processing the message activities. The Dialog conversation gets created and the dialog state is maintained to save data in memory.
protected override async Task OnMembersAddedAsync(
IList<ChannelAccount> ca, ITurnContext<IConversationUpdateActivity> tc,
CancellationToken ct)
{
var welcomeCard = CreateAdaptiveCardAttachment();
var welcomeResponse = MessageFactory.Attachment
(welcomeCard, ssml: "Welcome to Conference Registration!");
foreach (var member in ca)
{
if (member.Id != tc.Activity.Recipient.Id)
{
await tc.SendActivityAsync(welcomeResponse, ct);
}
}
}
/// <summary>
/// Adaptive Card for welcoming user
/// </summary>
/// <returns></returns>
private static Attachment CreateAdaptiveCardAttachment()
{
AdaptiveCard weclomeCard = new AdaptiveCard();
weclomeCard.Body.Add(new AdaptiveTextBlock()
{
Text = "Conference Registration",
Size = AdaptiveTextSize.Large,
Wrap = true
});
weclomeCard.Body.Add(new AdaptiveTextBlock()
{
Text = "30th April 2023, Pune",
Size = AdaptiveTextSize.Medium
});
weclomeCard.Body.Add(new AdaptiveImage()
{
Url = new Uri("image URI"),
HorizontalAlignment = AdaptiveHorizontalAlignment.Center
});
weclomeCard.Body.Add(new AdaptiveTextBlock()
{
Text = " Hi, data enthusiast.",
Size = AdaptiveTextSize.Small,
Wrap = true,
Weight = AdaptiveTextWeight.Bolder
});
Attachment attachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = weclomeCard
};
return attachment;
}
}
}
Here, OnMembersAddedAsync() gets called when a new user joins the conversation. CreateAdaptiveCardAttachment() returns adaptive card attachment. OnMessageActivityAsync() gets the requests from the user and handles them using Dialog.
5. Create a new file ConferenceDetailsDialog.cs inside the new folder Dialog in the project with the help of the below code snippets:
var waterfallSteps = new WaterfallStep[]
{
FetchUserNameAsync,
FetchUserEmailAsync,
TransportStepAsync,
OptionalAgeStepAsync,
FetchUserAgeAsync,
UploadProfileImageAsync,
DataProcessConfirmationStepAsync,
DataProcessingStepAsync,
};
AddDialog(new WaterfallDialog(
nameof(WaterfallDialog),
waterfallSteps));
AddDialog(new TextPrompt(
nameof(TextPrompt),
ValidateNameAsync));
AddDialog(new TextPrompt(
nameof(TextPrompt)));
AddDialog(new ChoicePrompt(
nameof(ChoicePrompt)));
AddDialog(new NumberPrompt<int>(
nameof(NumberPrompt<int>),
ValidateAgeAsync));
AddDialog(new ConfirmPrompt(
nameof(ConfirmPrompt)));
AddDialog(new AttachmentPrompt(
nameof(AttachmentPrompt),
ValidateProfileImageAsync));
The above code snippet creates waterfall steps for taking data from the user.
private static async Task<DialogTurnResult> FetchUserNameAsync(
WaterfallStepContext sc, CancellationToken ct)
{
return await sc.PromptAsync(nameof(TextPrompt),
new PromptOptions
{
Prompt = MessageFactory.Text(
"Please enter your name (must contain at least 3 characters
and at most 200 characters)."),
RetryPrompt = MessageFactory.Text("Invalid username"),
}
, ct);
}
The above code snippet creates Text Prompt which takes the username. The FetchUserEmailAsync, TransportStepAsync, and FetchUserAgeAsync methods stores name, email, and age and process the provided data.
private async Task<DialogTurnResult> FetchUserEmailAsync(
WaterfallStepContext sc, CancellationToken ct)
{
sc.Values["name"] = (string)sc.Result;
//logic
}
private async Task<DialogTurnResult> TransportStepAsync(
WaterfallStepContext sc
, CancellationToken ct)
{
sc.Values["email"] = (string)sc.Result;
//logic
}
private async Task<DialogTurnResult> FetchUserAgeAsync(
WaterfallStepContext sc,
CancellationToken ct)
{
if ((bool)sc.Result)
{
var promptOptions = new PromptOptions
{
Prompt = MessageFactory.Text("Provide age:"),
RetryPrompt = MessageFactory.Text("Invalid age."),
};
return await sc.
PromptAsync(nameof(NumberPrompt<int>),
promptOptions, ct);
}
else
{
return await sc.
NextAsync(-1, ct);
}
}
private static Task<bool> ValidateAgeAsync(
PromptValidatorContext<int> pc, CancellationToken ct)
{
return Task.FromResult(pc.Recognized.Succeeded &&
pc.Recognized.Value > 0 && pc.Recognized.Value < 80);
}
private static Task<bool> ValidateNameAsync(
PromptValidatorContext<string> pc,
CancellationToken ct)
{
return Task.FromResult(pc.Recognized.Succeeded
&& pc.Recognized.Value.Length > 3
&& pc.Recognized.Value.Length < 200);
}
The above code snippets validate the age and name entered by the user. The age should be between 0 and 80. The length of the name should be between 3 and 200.
6. Click IISExpress and run the project.
Now, open Bot Framework Emulator to test the bot locally.
7. Open Bot Framework Emulator. Click Connect.
In this article, we have seen how to develop a chatbot to take details from users to register them for a conference using Microsoft Bot Framework Chatbot Development. An application program called a bot simulates human conversation and provides responses to users based on its training data and rules. Developers design bots to intelligently respond to user queries, offer customer services, and assist users with tasks such as ticket booking or bill payments. We have seen how to use prompts to take data from users. We also understand how to store gathered data temporarily into in-memory. Below are the major takeaways from the above guide:
The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.
A. Microsoft Bot Framework is a platform that enables developers to build, deploy, and manage intelligent chatbots and conversational agents. It provides tools, SDKs, and services for creating bots to interact with users across various channels like websites, messaging apps, and voice assistants.
A. Yes, the Microsoft Bot Framework offers a free tier that allows developers to build and deploy bots without incurring additional costs. However, certain premium features and services may have associated costs, depending on the usage and requirements of your bot.
A. To learn Microsoft Bot Framework, you can start by visiting the official documentation and exploring the various tutorials and guides Microsoft provides. Additionally, online courses, community forums, and code samples are available to help you get started and gain proficiency in building bots using the framework.
A. The Microsoft Bot Framework offers several benefits, including cross-platform compatibility, a rich bot development ecosystem, Natural Language Processing (NLP) integration, and scalability and reliability.