Chat Bot


How Chatbot work?




Azure Bot Channel regisration:


1. Create resource group

2. Create Microsoft id and Password for Bot manualy and update in appsetting.json.

3. Rezgister the bot channel and set https url.







Passing Custom parameter Jquery to chat bot framework:


Jquery Code:

<html>

<head>  

    <title>GeniEbix</title> 

    <script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>

    <style>

        html, body {

            height: 100%
        }

        body {
            margin: 0
        }

        #webchat {
            height: 95%;
            width: 100%;
        }
    </style>
</head>
<body>
    <div style="width: 100%;height:30px;background-color:deepskyblue;" id="divHeader">
        <span style="float: left; font-family:Calibri;font-size:16px; ">
            <img src="Images/Test.jpg" align="left" style="height:30px;width:30px;" />
            &nbsp;&nbsp;&nbsp; 
        </span>
        <button id="btnClose" type="button" class="close1" data-dismiss="alert" aria-label="Close" style="float: right;cursor: pointer;">
            <span aria-hidden="true">×</span>
        </button>
    </div>

    <div id="bot" role="main"></div>
    <script>

        const styleOptions = {
            botAvatarImage: 'Images/Test.jpg',
            //'https://docs.microsoft.com/en-us/azure/bot-service/v4sdk/media/logo_bot.svg?view=azure-bot-service-4.0',
            userAvatarImage: 'Images/user_img.png'
            //'https://github.com/compulim.png?size=64',
            // bubbleBackground: 'rgba(0, 0, 255, .1)',
            //bubbleFromUserBackground: 'rgba(0, 255, 0, .1)'
        };                

        var botConnection = new window.WebChat.createDirectLine({
            token: 'Secret Value'           
        });
      
        var userinfo = { id: 'Guru', userparam: 'Guru' };

        window.WebChat.renderWebChat({
            directLine: botConnection,
            user: userinfo,
            styleOptions,
            locale: 'en-US',
         

        }, document.getElementById('bot'));

        document.querySelector('#bot > div > div:last-child  [data-id]').setAttribute('placeholder', 'Ask your test');

        botConnection.postActivity({
            type: 'event',
            from: userinfo,
        }).subscribe(function (id) { console.log('you send an event activity'); });
      
    </script>
</body>
</html>


C# Code




            if (turnContext.Activity.Type == ActivityTypes.Event)

                {

                try

                {

                    var uparam = turnContext.Activity.From.Properties["userparam"].ToString();

                    await turnContext.SendActivityAsync($"Parameter that you sent is '{uparam}'");
                }
                catch (Exception ex)
                {
                    strText = strText + "Parameter Event" + ex.Message;
                }
             
                   
                }     



Dynamic Form flow- add dynamic prompt, description


https://www.c-sharpcorner.com/article/formflow-in-microsoft-bot-framework-part-two/



Suggestions 



Fetch entity from Luis


How to host chatbot on azure?

chat bot test with url:


1. open the bot emulator (3.5)
2. configure the ngrok
3. connect

What is ngrok?
Ngrok is a multiplatform tunnelling, reverse proxy software that establishes secure tunnels from a public endpoint such as internet to a locally running network service while capturing all traffic for detailed inspection and replay
NLP?
Natural Language Processing (NLP) is a branch of AI that helps computers to understand, interpret and manipulate human language.


NLP is a way of computers to analyze, understand and derive meaning from a human languages such as English, Spanish, Hindi, etc

What is Language Understanding (LUIS)?:


Chat Bot Demo -https://niki.ai/
https://thirdeyedata.io/language-understanding-luis-in-azure/
Reference:https://www.expertsystem.com/chatbot/

Luis configuration
//https://www.brightdevelopers.com/how-to-work-with-luis-in-bot-framework-v4-part-4/

// Brief Introduction
Reference: http://www.insightsbot.com/blog/1xRE1M/microsoft-chatbot-sdk-v4-introduction-with-c

Reference :https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-v4-state?view=azure-bot-service-4.0&tabs=csharp


Chat Bot Folder Structure:

Form Flow:

ChatBot Hosting :

http://aihelpwebsite.com/Blog/EntryId/1030/Creating-a-Hello-World-Bot-MS-Bot-Framework-V4-Preview-Edition
https://www.skeintech.com/chatbot-development/
Chatbots conversational interfaces are developed for better communication between humans and computers through natural language. Chatbot has distinct characteristics that can be programmed according to the nature and need of your industry. Its quick learning ability from users and innovative design makes Chatbot a better personal assistant.
Chatbots can interact with the user not only through text and voice. They can also engage the audience by providing visual recognition. Our Chatbot experts develop ai bots with innovative UI/UX and comprehensive language integration capable of answering customer requests, promoting unique products and providing an instant quotation and data gathering.




Machine Learning :
Definition: Machine Learning is a concept which allows the machine to learn from examples and experience, and that too without being explicitly programmed. So instead of you writing the code, what you do is you feed data to the generic algorithm, and the algorithm/machine builds the logic based on the given data. 


Artificial Intelligence:

Artificial Intelligence is the broader concept of machines being able to carry out tasks in a smarter way. It covers anything which enables the computers to behave like humans. 

Chatbot:

A chatbot is an artificial intelligence (AI) software that can simulate a conversation (or a chat) with a user in natural language through messaging applications, websites, mobile apps or through the telephone. A chatbot is often described as one of the most advanced and promising expressions of interaction between humans and machines. However, from a technological point of view, a chatbot only represents the natural evolution of a Question Answering system leveraging Natural Language Processing (NLP). Formulating responses to questions in natural language is one of the most typical Examples of Natural Language Processing applied in various enterprises’ end-use applications.

Reference:https://tutorials.botsfloor.com/the-chatbot-dictionary-8aea8478faf1s onversational inteomer requests, promoting unique products and providing an instant quotation and data gathering.

Chatbot Terminology:


























Chatbots

A conversational interface, voice or text, that enables people to interact
 with computer programs (possibly human or Al aided) to get something done.
Artificial Intelligence
A machine’s ability to make decisions and perform task that simulate human intelligence and behaviour.
Machine Learning
A machine, ability to learn without being programmed and adapt itself to new data with the help of algorithms.
Natural Language Understanding
A branch of machine learning that uses algorithms to understand natural human inputs made in the form of sentences in a text or speech format.
Entity Extraction
Extracting valuable information from textual data or input to complete a task. Also known as Named Entity Recognition(NER)
Supervised Learning
ML algorithms in which labelled data sets train the machine to learn a mapping between inputs and outputs. i.e. classifying data based on labels.
Unsupervised Learning
ML algorithms that draw inferences from data sets consisting of
 input data without labelled responses. i.e. cluttering.
Deep Learning
A machine’s ability to learn on its own from data representations as opposed to task specific algorithms or commands.
Neural Networks
A variety of deep learning algorithms that are patterned after the 
operation of neurons in the human brain.

How a chatbot works:




Why chatbots are important

Chatbot applications streamline interactions between people and services, enhancing customer experience. At the same time, they offer companies new opportunities to improve the customers engagement process and operational efficiency by reducing the typical cost of customer service.
To be successful, a chatbot solution should be able to effectively perform both of these tasks. Human support plays a key role here: Regardless of the kind of approach and the platform, human intervention is crucial in configuring, training and optimizing the chatbot system.
Reference:
ChatBot  basic resources :
1. Framework  : 
   

Microsoft Bot Framework

Microsoft’s framework to help develop conversational interfaces aka Bots is called the Microsoft Bot Framework. Microsoft provides you with a free open source SDK hosed on github called the Bot Builder SDK. This project provides you with everything you need to build your own chatbots in multiple languages such as C#, Node js Python and others.   

 C#

Prerequisites

  • Visual Studio 2017
  • Bot Framework SDK v4 template for C#
  • Bot Framework Emulator
  • Knowledge of ASP.Net Core and asynchronous programming in C#
JavaScript

Prerequisites

2. Natural Language understanding, processing and learning
An effective bot is one that is able to understand the user’s language and the context of conversation throughout the chat. While comprehending the language of user requires text and linguistic analysis i.e
 parts of speech tagging, phrase analysis etc. analyzing the context of conversation involves modelling the entities, intents, and actions of the user.
  3.Cognitive Service Abstraction – This component provides an abstraction layer to industry       standard AI & cognitive services across text, speech, vision (image) and custom machine learning algorithms. You will have the flexibility to choose and integrate the best Ai services as they mature. The abstraction layer ensures that the rest of your bot implementation will not be affected.

4.Conversational User Experience Design:Conversational User Experience (CUX) Design is an important element of any good chatbot design. A well crafted conversational UX helps users achieve their goal in the shortest time with maximum end-user experience.The design should make it easy for users to easily understand the functioning of bot and have an intelligent and helpful conversation with the bot.
5.Dialog development
The user engagement directly depends on how well the bot converses with the user. An effective bot should send natural language responses based on the inputs. 
6. Host channel
Host channel is the channel through which you host the conversation with a user. By providing suitable API support for bots, a channel can prove to be an excellent host for publishing custom bots. A few of the most notable chat applications like Slack, Skype, Skype for Business, Telegram etc. have started providing support for bots.
7. Analytics & Administration
Once the bot is deployed for end users, it’s important to keep a check on its performance and continue to refine its natural language understanding through further training.
8. Security & User Permissions 
The bot should be aware if a user is authorized and properly authenticated to chat with it. This ensures that the bot is able to provide the right set of relevant services for a particular user. The entire communication series between the bot and user should be encrypted using SSL based encryption.The bot needs to accept conversations from valid user IDs which are authorized to chat with the bot. These IDs can be configured into the bot post deployment by an administrator.
Bot Application without Azure:
Certificate Requirement For your Bot API:
If you decided for any reason, that you don’t want to host your Bot on Azure, then first of all as mentioned earlier you need to make sure it is accessible through internet, and second is the Certificate.The following is the Certificate requirement, if you want to host your API outside of Azure:
The Bot Framework requires that the x.509v3 certificate exposed by your endpoint be current and valid. Most of the checks for “current and valid” are standard checks for server certs: the CN must match the hostname, it must not be expired, it must not be listed in a CRL, it must have the correct set of EKUs, etc.Most importantly, your cert must chain to a root certificate authority trusted by Microsoft. 
Bot Framework  4
Step To Add application

1. Installed required tools and extensions

2. Configure - Start.cs

3. update the latest Microsoft bot builder and other references from nuget

4. Install -Microsoft.Bot.Builder.Dialogs

5. Install -Bot.Builder.Community.Dialogs.FormFlow



Chat bot Adaptive Card

      private static AdaptiveColumn SetAdaptiveColumn(string text, AdaptiveHorizontalAlignment alignment)
        {
            AdaptiveColumn adaptiveColumn = new AdaptiveColumn();
            adaptiveColumn.Width = AdaptiveColumnWidth.Stretch;
            adaptiveColumn.Type = "TextBlock";
            adaptiveColumn.Items.Add(new AdaptiveTextBlock()
            {
                Text = text,
                Size = AdaptiveTextSize.Medium,
                HorizontalAlignment = alignment,
                Spacing = AdaptiveSpacing.Padding,

            });
            return adaptiveColumn;
        }




private static AdaptiveColumnSet SetAdaptiveColumnRowSet(string labelText, string value)
        {
            AdaptiveColumnSet adaptiveColumnSet = new AdaptiveColumnSet();
            AdaptiveColumn col1 = SetAdaptiveColumn(labelText, AdaptiveHorizontalAlignment.Left);
            adaptiveColumnSet.Columns.Add(col1);

            AdaptiveColumn col2 = SetAdaptiveColumn(value, AdaptiveHorizontalAlignment.Right);
            adaptiveColumnSet.Columns.Add(col2);
            return adaptiveColumnSet;
        }


 private static AdaptiveCard Test(TestP tp)
        {


            AdaptiveCard card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0));
            AdaptiveColumnSet Title = new AdaptiveColumnSet();
            AdaptiveColumn titletext = new AdaptiveColumn();
            titletext.Width = AdaptiveColumnWidth.Auto;

            titletext.Items.Add(new AdaptiveTextBlock()
            {
                Weight = AdaptiveTextWeight.Bolder,
                Wrap = true,
                Text = "TestDetails",
                Size = AdaptiveTextSize.Medium,

            });
            Title.Columns.Add(titletext);
            card.Body.Add(Title);

            AdaptiveColumnSet columnSet1 = SetAdaptiveColumnRowSet("Number:", customerProfile.ClientNumber);
            card.Body.Add(columnSet1);

            AdaptiveColumnSet columnSet2 = SetAdaptiveColumnRowSet("Name:", customerProfile.ClientName);
            card.Body.Add(columnSet2);

            AdaptiveColumnSet columnSet3 = SetAdaptiveColumnRowSet("Company:", customerProfile.Company);
            card.Body.Add(columnSet3);

   

            card.Actions.Add(new AdaptiveOpenUrlAction()
            {
                Url = new Uri(test.URL),
                Title = "Click Details"
            });

            return card;
        }


Chat Bot Validation:


  AddDialog(new TextPrompt("apiText", ApiValidation));



  private Task<bool>  ApiValidation(PromptValidatorContext<string> promptcontext, CancellationToken cancellationtoken)
        {
            if (!promptcontext.Recognized.Succeeded)
            {
            //    promptcontext.Options.RetryPrompt = MessageFactory.Text(" input is not valid");
                return Task.FromResult(false);
            }
     
            if (!ValidateAPI(requestParam))
            {
                promptcontext.Options.RetryPrompt = MessageFactory.Text("Api validation.");
                return Task.FromResult(false);
            }

            return Task.FromResult(true);

        }


Session Management in chatBot

How store user info from jquery to bot framework?

   protected readonly BotState UserState;

   public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
       
            var userStateAccessors = UserState.CreateProperty<UserInfo>(nameof(UserInfo));
            var userProfile = await userStateAccessors.GetAsync(turnContext, () => new UserInfo());
         
            if (turnContext.Activity.Type == ActivityTypes.Event)
            {
                try
                {

                    //Fetch the value form Jquery and write into bot memory
                    await userStateAccessors.DeleteAsync(turnContext, cancellationToken);
                    var userId = turnContext.Activity.From.Properties["UserParam"].ToString();
                 
                    userProfile.UserId = userId;
                    await _myStorage.DeleteAsync(new[] { "UserLog" }, cancellationToken).ConfigureAwait(false);

                    // If no stored messages were found, create and store a new entry.

                    // add the current userId to a new object.
                        userLog = new UserLog();
                        userLog.UserList.Add(userId);
                        // set initial turn counter to 1.
                        userLog.TurnNumber++;
                          // Create Dictionary object to hold received user messages.
                        var changes = new Dictionary<string, object>();
                        {
                            changes.Add("UserLog", userLog);
                        }
                        try
                        {
                            // Save the user message to your Storage.
                            await _myStorage.WriteAsync(changes, cancellationToken);

                       }
                        catch
                        {
                            // Inform the user an error occured.
                            await turnContext.SendActivityAsync("Sorry, something went wrong storing your message!");
                        }
                 
                }
                catch (Exception ex)
                {

                }

            }


            //Bot initialization
            if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
            {

                // see if there are previous messages saved in storage.
                try
                {
                    string[] UserList = { "UserLog" };
                    userLog = _myStorage.ReadAsync<UserLog>(UserList).Result?.FirstOrDefault().Value;
                }
                catch
                {
                    // Inform the user an error occured.
                    await turnContext.SendActivityAsync("Sorry, something went wrong reading your stored messages!");
                }
                if (userLog != null)
                {                 
                    var user = string.Join(", ", userLog.UserList);
                    userProfile.UserId = user;
                }
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
                IConversationUpdateActivity iConversationUpdated = turnContext.Activity as IConversationUpdateActivity;
                if (iConversationUpdated != null)
                {
                    //  ConnectorClient connector = new ConnectorClient(new System.Uri(turnContext.Activity.ServiceUrl));

                    foreach (var member in iConversationUpdated.MembersAdded ?? System.Array.Empty<ChannelAccount>())
                    {
                        // if the bot is added, then                   

                        if (member.Id == iConversationUpdated.Recipient.Id)
                        {

                            var welComeHeroCard = new HeroCard
                            {
                              Text="Hello"

                            };

                            var replyWelcome = turnContext.Activity.CreateReply();
                            replyWelcome.Attachments.Add(welComeHeroCard.ToAttachment());
                            await turnContext.SendActivityAsync(replyWelcome);
                            //var response = MessageFactory.Text("");
                            //await turnContext.SendActivityAsync(response, cancellationToken);
                            await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>("DialogState"), cancellationToken);
                        }
                    }
                }
            }

            await base.OnTurnAsync(turnContext, cancellationToken);

            // Save any state changes that might have occured during the turn.
            await ConversationState.SaveChangesAsync(turnContext, false, cancellationToken);
            await UserState.SaveChangesAsync(turnContext,true, cancellationToken);
        }



 // Class for storing a log of userIds (text of messages) as a list.
    public class UserLog : IStoreItem
    {
        // A list of things that users have said to the bot
        public List<string> UserList { get; } = new List<string>();

        // The number of conversational turns that have occurred     
        public int TurnNumber { get; set; } = 0;

        // Create concurrency control where this is used.
        public string ETag { get; set; } = "*";
    }



//fetch in Request dialog
var userStateAccessors = UserState.CreateProperty<UserInfo>(nameof(UserInfo));
            var userProfile = await userStateAccessors.GetAsync(stepContext.Context, () => new UserInfo());




Comments

Post a Comment

Popular posts from this blog

Microsoft Enterprise Library-Data Access Application Block for for .Net Core & .Net Standard

Entity Framework