Chat bot implementation with LUIS AI

First we need to install Bot Framework Emulator 
  Install :::>   https://github.com/Microsoft/BotFramework-Emulator/releases/download/v3.5.37/botframework-emulator-3.5.37-windows-setup.exe

2. Configure LUIS app  https://luis.ai/
      Create an Application in Luis 
       Create Intents
       Each intent inside at least, we need to create one Phrase
       Create Entities and train Your bot application in LUIS. 
 upload Luis sample json

{ "query": "Upcomming movie", "topScoringIntent": { "intent": "Hero",
"score": 0.921233 }, "entities": [ { "entity": "ReleaseDate",
"type": "Date", "startIndex": 10, "endIndex": 13, "score": 0.7615982 } ] }


Or use this link to configure

https://docs.microsoft.com/en-us/azure/cognitive-services/luis/luis-get-started-create-app


Next Step: for all Applications :
============================================
in WebapiConfig.cs
------------------------
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Web.Http;

namespace Sample
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Json settings
            config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting = Newtonsoft.Json.Formatting.Indented,
                NullValueHandling = NullValueHandling.Ignore,
            };

            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Create New Controller :

using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using SD = System.Diagnostics;
namespace Sample
{
[BotAuthentication]
public class SampleController : ApiController
{
/// POST: api/Messages

public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
SD.Trace.TraceInformation("MessagesController::Post");
if (activity.Type == ActivityTypes.Message)
{
await Conversation.SendAsync(activity, () => new Dialogs.AppRootDialog());
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
private Activity HandleSystemMessage(Activity message)
{
if (message.Type == ActivityTypes.DeleteUserData)
{
// Implement user deletion here
// If we handle user deletion, return a real message
}
else if (message.Type == ActivityTypes.ConversationUpdate)
{
// 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
}
else if (message.Type == ActivityTypes.ContactRelationUpdate)
{
// Handle add/remove from contact lists
// Activity.From + Activity.Action represent what happened
}
else if (message.Type == ActivityTypes.Typing)
{
// Handle knowing tha the user is typing
}
else if (message.Type == ActivityTypes.Ping)
{
}
return null;
}
}
}

Create New Folder name Like Dialog: after that create a new class file name like:RootDialog
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Luis.Models;
using Microsoft.Bot.Connector;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Sample.Dialogs
{
// Model Id == App Id that you'll find in LUIS Portal
// Find at: https://www.luis.ai/home/keys
// Subscription Key is one of the two keys from your Cognitive Services App.
// Find at: https://portal.azure.com in the Resource Group where you've created
// your Cognitive Services resource on the Keys blade.
[LuisModel("", "")]
[Serializable]
public class RootDialog : LuisDialog<object>
{
[LuisIntent("Hero")]
public async Task Help(IDialogContext context, LuisResult result)
{
await context.PostAsync("Hi! Try asking me to 'Book a Cabana'.");
context.Wait(this.MessageReceived);
}
[LuisIntent("")]
[LuisIntent("None")]
public async Task None(IDialogContext context, LuisResult result)
{
string message = $"Sorry, I did not understand '{result.Query}'. Type 'help' if you need assistance.";
await context.PostAsync(message);
context.Wait(this.MessageReceived);
}
}
}
In Web.config file:
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
  <appSettings>
    <!-- update these with your BotId, Microsoft App Id and your Microsoft App Password-->
    <add key="BotId" value="YourBotId" />
    <!-- see Web.Release.Config for the following two items. -->
    <!--<add key="MicrosoftAppId" value="" />
    <add key="MicrosoftAppPassword" value="" />-->
    <!-- Bot App Registration for AADv2 -->
    <add key="aad:ClientId" value="" />
    <add key="aad:ClientSecret" value="" />
    <add key="aad:Callback" value="http://localhost:3979/Callback" />
    <add key="StorageConnectionString" value="UseDevelopmentStorage=true" />
  </appSettings>
  <!--
    For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.

    The following attributes can be set on the <httpRuntime> tag.
      <system.Web>
        <httpRuntime targetFramework="4.6" />
      </system.Web>
  -->
  <system.web>
    <customErrors mode="Off" /> 
    <compilation debug="true" targetFramework="4.6" />
    <httpRuntime targetFramework="4.6" />
  </system.web>
  <system.webServer>
    <defaultDocument>
      <files>
        <clear />
        <add value="default.htm" />
      </files>
    </defaultDocument>
    
  <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers></system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.29.0" newVersion="4.2.29.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.7.1.0" newVersion="4.7.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Bot.Builder" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.15.0.0" newVersion="3.15.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Bot.Connector" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.15.0.0" newVersion="3.15.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Bot.Builder.Autofac" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.15.0.0" newVersion="3.15.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.IdentityModel.Tokens.Jwt" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.1.0" newVersion="5.2.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Tokens" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.1.0" newVersion="5.2.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Protocols" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.1.0" newVersion="5.2.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Protocols.OpenIdConnect" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.1.0" newVersion="5.2.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

In global.asax.cs

using Autofac;
using Autofac.Integration.WebApi;
using Microsoft.Bot.Builder.Azure;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Dialogs.Internals;
using Microsoft.Bot.Connector;
using Microsoft.WindowsAzure.Storage;
using System.Configuration;
using System.Reflection;
using System.Web.Http;
namespace CommerceBot
{
public class WebApiApplication : System.Web.HttpApplication
{
private const string BotStateTableName = "HeroBot";
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];
var config = GlobalConfiguration.Configuration;
Conversation.UpdateContainer(
builder =>
{
builder.RegisterModule(new AzureModule(Assembly.GetExecutingAssembly()));
//var store = new TableBotDataStore(connectionString, BotStateTableName);
//builder.Register(c => store)
// .Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore)
// .AsSelf()
// .SingleInstance();
var store = new InMemoryDataStore();
// Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterWebApiFilterProvider(config);
});
config.DependencyResolver = new AutofacWebApiDependencyResolver(Conversation.Container);
}
}
}

In Package.config:

<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Autofac" version="4.7.1" targetFramework="net46" />
<package id="Autofac.WebApi2" version="4.1.0" targetFramework="net46" />
<package id="BotAuth" version="3.11.0-alpha" targetFramework="net46" />
<package id="BotAuth.AADv2" version="3.11.0-alpha" targetFramework="net46" />
<package id="Chronic.Signed" version="0.3.2" targetFramework="net46" />
<package id="EntityFramework" version="6.2.0" targetFramework="net46" />
<package id="Microsoft.AspNet.WebApi" version="5.2.4" targetFramework="net46" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.4" targetFramework="net46" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.4" targetFramework="net46" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.4" targetFramework="net46" />
<package id="Microsoft.Azure.DocumentDB" version="1.21.1" targetFramework="net46" />
<package id="Microsoft.Azure.KeyVault.Core" version="2.0.4" targetFramework="net46" />
<package id="Microsoft.Bot.Builder" version="3.15.0" targetFramework="net46" />
<package id="Microsoft.Bot.Builder.Azure" version="3.2.5" targetFramework="net46" />
<package id="Microsoft.Bot.Builder.History" version="3.15.0" targetFramework="net46" />
<package id="Microsoft.Bot.Connector" version="3.15.0" targetFramework="net46" />
<package id="Microsoft.Data.Edm" version="5.8.3" targetFramework="net46" />
<package id="Microsoft.Data.OData" version="5.8.3" targetFramework="net46" />
<package id="Microsoft.Data.Services.Client" version="5.8.3" targetFramework="net46" />
<package id="Microsoft.Identity.Client" version="1.1.0-preview" targetFramework="net46" />
<package id="Microsoft.IdentityModel.Logging" version="5.2.1" targetFramework="net46" />
<package id="Microsoft.IdentityModel.Protocol.Extensions" version="1.0.4.403061554" targetFramework="net46" />
<package id="Microsoft.IdentityModel.Protocols" version="5.2.1" targetFramework="net46" />
<package id="Microsoft.IdentityModel.Protocols.OpenIdConnect" version="5.2.1" targetFramework="net46" />
<package id="Microsoft.IdentityModel.Tokens" version="5.2.1" targetFramework="net46" />
<package id="Microsoft.Rest.ClientRuntime" version="2.3.11" targetFramework="net46" />
<package id="Microsoft.WindowsAzure.ConfigurationManager" version="3.2.3" targetFramework="net46" />
<package id="Newtonsoft.Json" version="11.0.2" targetFramework="net46" />
<package id="System.IdentityModel.Tokens.Jwt" version="5.2.1" targetFramework="net46" />
<package id="System.Spatial" version="5.8.3" targetFramework="net46" />
<package id="WindowsAzure.Storage" version="9.1.1" targetFramework="net46" />
</packages>
In default.html file:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body style="font-family:'Segoe UI'">
<h1>CommerceBot</h1>
<p>Describe your bot here and your terms of use etc.</p>
<p>Visit <a href="https://www.botframework.com/">Bot Framework</a> to register your bot. When you register it, remember to set your bot's endpoint to <pre>https://<i>your_bots_hostname</i>/api/messages</pre></p>
</body>
</html>
The below microsoft official artical has publish. if you dont understand above , try the below link https://github.com/Microsoft/AzureBotServices-scenarios/tree/master/CSharp/Commerce/src

Comments

  1. https://github.com/Microsoft/AzureBotServices-scenarios/tree/master/CSharp/Commerce/src

    ReplyDelete
  2. https://mycodin.blogspot.com/2018/12/chat-bot-implementation-with-luis-ai.html?showComment=1544374383577#c953040358624368938

    ReplyDelete

Post a Comment

Popular posts from this blog

Reverse Sentence using c#

How to write Pure java script Program?