Make your Chatbot ready (Microsoft Bot Framework).to work with LUIS

Prerequisities :

  1. LUIS Service :
    http://www.muhammetatalay.com/2019/02/luis-language-understanding-intelligent.html
  2. Bot Project creation :
    http://www.muhammetatalay.com/2019/02/create-chatbot-application-with.html
  3. Installation and Configuration of Microsoft Bot Framework Emulator :
    http://www.muhammetatalay.com/2019/02/step-by-step-installation-and.html
  4. Configure LUIS service for bot :
    http://www.muhammetatalay.com/2019/02/how-to-configure-luis-service-for.html


1.1                            Connecting to the services from your bot

if you go over prerequisities, you will have a visual studio project so in order to connect to the LUIS service, your bot should be configured properly through the .bot file.

In Startup.cs, ConfigureServices read connection string or other necessary information from .bot to  integrate with external services and InitBotServices uses that information to initialize the services accordingly.

sample of  ".bot " file:


{
  "name": "CRMBot",
  "services": [
    {
      "type": "endpoint",
      "name": "development",
      "endpoint": "http://localhost:3978/api/messages",
      "appId": "",
      "appPassword": "",
      "id": "1"
    },
    {
      "type": "endpoint",
      "name": "production",
      "endpoint": "<YOUR ENDPOINT>",
      "appId": "<YOUR APPID>",
      "appPassword": "<YOUR PASSWORD>",
      "id": "2"
    },
    {
      "type": "luis",
      "name": "LuisBot",
      "appId": "3c4dd5df-e45c-405e-8d48-2faa95918dcc",
      "version": "0.1",
      "authoringKey": "e38f05d2f3894d9ba38c6158c7ae46c1",
      "subscriptionKey": "e38f05d2f3894d9ba38c6158c7ae46c1",
      "region": "westus",
      "id": "158"
    }
  ],
  "padlock": "",
  "version": "2.0"
}

BotServices class initializes the neceserray objects to build robust communication with external channel

 public BotServices(BotConfiguration botConfiguration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                    case ServiceTypes.Luis:
                        {
                            var luis = (LuisService)service;
                            if (luis == null)
                            {
                                throw new InvalidOperationException("The LUIS service is not configured correctly in your '.bot' file.");
                            }

                            var app = new LuisApplication(luis.AppId, luis.AuthoringKey, luis.GetEndpoint());
                            var recognizer = new LuisRecognizer(app);
                            this.LuisServices.Add(luis.Name, recognizer);
                            break;
                        }
                }
            }
        }

BotConfiguration is a class that engages with configuration and objects to be used by bot under Microsoft.Bot.Configuration namespace.


1.2                            Calling Services from your bot

In the <project name>Bot.cs file, the bot's constructor gets the BotServices object that we registered at startup.

In the bot's OnTurnAsync method, we check incoming messages from the user :

 public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Handle Message activity type, which is the main activity type for shown within a conversational interface
            // Message activities may contain text, speech, interactive cards, and binary or unknown attachments.
            // see https://aka.ms/about-bot-activity-message to learn more about the message and other activity types
            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                // Check LUIS model
                var recognizerResult = await _services.LuisServices[LuisKey].RecognizeAsync(turnContext, cancellationToken);
                var topIntent = recognizerResult?.GetTopScoringIntent();
                if (topIntent != null && topIntent.HasValue && topIntent.Value.intent != "None")
                {
                    await turnContext.SendActivityAsync($"==>LUIS Top Scoring Intent: {topIntent.Value.intent}, Score: {topIntent.Value.score}\n");
                    await DispatchToTopIntentAsync(turnContext, topIntent, cancellationToken);
                }
                else
                {
                    var msg = @"No LUIS intents were found.
                        This sample is about identifying four user intents:
                        'Calendar.Add'
                        'Calendar.Find'
                        'Subscriptions'
                        'Customer'
                        'None'
                        Try typing 'Add Event' or 'Show me tomorrow'.";
                    await turnContext.SendActivityAsync(msg);
                }
            }
            else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
            {
                // Send a welcome message to the user and tell them what actions they may perform to use this bot
                await SendWelcomeMessageAsync(turnContext, cancellationToken);
            }
            else
            {
                await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected", cancellationToken: cancellationToken);
            }
        }



1.3                            Working with the recognition results

When the model produces a result, it indicates which service can most appropriately process the utterance. The code in this bot routes the request to the corresponding service, and then summarizes the response from the called service in the <project name>Bot.cs file.

Following method is called by LUIS with the meaning of what customer texted with similarity score of the customer text with our utterences.

                   /// <summary>
        /// Depending on the intent from Dispatch, routes to the right LUIS model .
        /// </summary>
        private async Task DispatchToTopIntentAsync(ITurnContext context, (string intent, double score)? topIntent, CancellationToken cancellationToken = default(CancellationToken))
        {            // Utterances that are defined in LUIS -> prereuisities #1
            const string subscriptions = "Subscriptions";
            const string customers = "Customer";
            const string calendarfind = "Calendar-Find";
            const string none = "None";
            const string calendaradd = "Calendar-Add";

            switch (topIntent.Value.intent)
            {
                case subscriptions:
                    await DispatchToLuisModelAsync(context, LuisBotLuisKey);

                    // Here, you can add code for calling the hypothetical home automation service, passing in any entity information that you need
                    break;

                case customers:
                    await DispatchToLuisModelAsync(context, LuisBotLuisKey);

                    // Here, you can add code for calling the hypothetical home automation service, passing in any entity information that you need
                    break;

                case calendarfind:
                    await DispatchToLuisModelAsync(context, LuisBotLuisKey);
                    // Here, you can add code for calling the hypothetical weather service,
                    // passing in any entity information that you need
                    break;
                case none:
                // You can provide logic here to handle the known None intent (none of the above).
                // In this example we fall through to the QnA intent.
                case calendaradd:
                    await DispatchToLuisModelAsync(context, LuisBotLuisKey);
                    break;

                default:
                    // The intent didn't match any case, so just display the recognition results.
                    await context.SendActivityAsync($"Dispatch intent: {topIntent.Value.intent} ({topIntent.Value.score}).");
                    break;
            }

        }

we can define our operations based on LUIS results under Bot:

private async Task DispatchToLuisModelAsync(ITurnContext context, string appName, CancellationToken cancellationToken = default(CancellationToken))
        {
            await context.SendActivityAsync($"Sending your request to the {appName} system ...");
            var result = await _services.LuisServices[appName].RecognizeAsync(context, cancellationToken);

            await context.SendActivityAsync($"Intents detected by the {appName} app:\n\n{string.Join("\n\n", result.Intents)}");

            if (result.Entities.Count > 0)
            {
                await context.SendActivityAsync($"The following entities were found in the message:\n\n{string.Join("\n\n", result.Entities)}");
                Case crmCase = new Case();
               

                foreach (JToken jToken in result.Entities.SelectTokens("$..['type']"))
                {
                    await context.SendActivityAsync($"Entity Element {jToken.ToString()}");

// I teach LUIS for case related communication for customer in order to create case in Dynamics CRM
                    switch (jToken.ToString())
                    {
                        case "Case - Dispute":
                            break;
                        case "Case - Problem":
                            break;
                        case "Case - Question":
                            break;
                        case "Case - Request":                     
                            break;
                        default:
                            await context.SendActivityAsync($"CRM Map for Entity Element {jToken.ToString()} was not found");
                            break;
                    }

                    await context.SendActivityAsync($"Case has been created in CRM");
                }

2.                             Execution Bot via Emulator

·        Click F5 in order to run project which is created above in Visual Studio

·      Visual Studio will open Internet Explorer through IISExpress  then Bot will be ready to register any channel .



·      Type Emulator in windows start menu (search) (look at #3 in prerequisities)

·        Click “Bot Framework Emulator (V4)”
·        Emulator will open

·        Click Open Bot and set Project with your project.
“<project name>.bot” file
·        Type your Message for any conversations !




Comments

Popular posts from this blog

Assembly Microsoft.Dynamics.Service.Plugins.dll can not be loaded. Dynamics CRM 365 Engine version 9 - CRM User creation error

Exception caught instantiating TERADATA report server extension SQL Reporting Services

Could not load file or assembly 'System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified at Configuration class initiation in CrmServiceHelper.cv