Ejemplo n.º 1
0
        public static VmIntentResponse FromIntentResponse(IntentResponse intentResponse)
        {
            var response = new VmIntentResponse
            {
                Action = intentResponse.Action
            };

            response.AffectedContexts = intentResponse.Contexts.Select(ctx => ctx.ToObject <VmIntentResponseContext>()).ToList();

            response.Parameters = intentResponse.Parameters.Select(p => VmIntentResponseParameter.FromIntentResponseParameter(p)).ToList();

            response.Messages = intentResponse.Messages.Select(msg => {
                if (msg.Speech == null)
                {
                    return(new VmIntentResponseMessage());
                }

                return(new VmIntentResponseMessage
                {
                    Payload = msg.Payload,
                    Type = msg.Type,
                    Speeches = JsonConvert.DeserializeObject <List <String> >(msg.Speech)
                });
            }).ToList();

            return(response);
        }
Ejemplo n.º 2
0
        public IntentResponse CreateIntent(string workspaceId, CreateIntent body)
        {
            if (string.IsNullOrEmpty(workspaceId))
            {
                throw new ArgumentNullException(nameof(workspaceId));
            }
            if (body == null)
            {
                throw new ArgumentNullException(nameof(body));
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
            }

            IntentResponse result = null;

            try
            {
                result = this.Client.WithAuthentication(this.UserName, this.Password)
                         .PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/intents")
                         .WithArgument("version", VersionDate)
                         .WithBody <CreateIntent>(body)
                         .As <IntentResponse>()
                         .Result;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Ejemplo n.º 3
0
        public static Type GetIntentType(this IntentResponse intent)
        {
            switch (intent.Intent)
            {
            case "PlaySong":
                return(typeof(WidgetDeezer));

            case "TurnOnTv":
            case "FullScreenTv":
            case "ReduceScreenTv":
                return(typeof(WidgetTv));

            case "TurnOnRadio":
                return(typeof(WidgetRadio));

            case "BlancheNeige":
            //Vm.SpeakCommand.Execute("Si je m'en tiens aux personnes que je connais, je peux affirmer que tu es le plus beau.");
            case "Tweet":
            case "HideAll":
            case "StartScreen":
            case "DisplayWidget":
            case "DisplayMail":
            case "AddReminder":
            case "TakePhoto":
            case "TurnOff":
            default:
                return(null);
            }
        }
Ejemplo n.º 4
0
        private void Client_OnMessageReceived(object sender, TwitchLib.Client.Events.OnMessageReceivedArgs e)
        {
            string botCommandResponse = _chatMessageService.HandleBotCommands(e.ChatMessage.Message.Trim());

            if (string.IsNullOrEmpty(botCommandResponse))  // do something with luis
            {
                // Run async method in this sync method  (read https://cpratt.co/async-tips-tricks/)
                IntentResponse intentResponse = AsyncHelper.RunSync(() => _luisService.GetIntentAsync(e.ChatMessage.Message.Trim()));

                decimal certaintyThreshold;

                if (!decimal.TryParse(_luisConfiguration.LuisChatCertaintyThreshold, out certaintyThreshold))
                {
                    throw new ArgumentException(nameof(_luisConfiguration.LuisChatCertaintyThreshold));
                }


                if (intentResponse.Certainty > certaintyThreshold)
                {
                    string luisMappedResponse = _chatMessageService.MapLuisIntentToResponse(intentResponse);
                    _twitchClient.SendMessage(_twitchConfiguration.ChannelName, luisMappedResponse);
                }

                AddTwitchUserChatRecordToDb(e, intentResponse);
            }
            else // do something with explicit bot commands
            {
                _twitchClient.SendMessage(_twitchConfiguration.ChannelName, botCommandResponse);
            }
        }
Ejemplo n.º 5
0
        public IntentResponse UpdateIntent(string workspaceId, string intent, UpdateIntent request)
        {
            IntentResponse result = null;

            if (string.IsNullOrEmpty(workspaceId))
            {
                throw new ArgumentNullException("parameter: workspaceId");
            }
            if (string.IsNullOrEmpty(intent))
            {
                throw new ArgumentNullException("parameter: intent");
            }
            if (request == null)
            {
                throw new ArgumentNullException("parameter: request");
            }

            try
            {
                result =
                    this.Client.WithAuthentication(this.UserName, this.Password)
                    .PostAsync($"{this.Endpoint}{PATH_CONVERSATION}/{workspaceId}")
                    .WithArgument("version", VERSION_DATE_2017_05_26)
                    .WithHeader("accept", HttpMediaType.TEXT_HTML)
                    .WithBody <UpdateIntent>(request, MediaTypeHeaderValue.Parse(HttpMediaType.APPLICATION_JSON))
                    .As <IntentResponse>()
                    .Result;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        private void Client_OnMessageReceived(object sender, TwitchLib.Client.Events.OnMessageReceivedArgs e)
        {
            string botMessageResponse = _chatMessageService.HandleBotCommands(e);

            IntentResponse intentResponse = new IntentResponse {
                Certainty = null, EmbeddedUrl = null, Intent = null
            };                                             // create with an empty default, for bot-command messages (those that are not fed through LUIS)

            if (string.IsNullOrEmpty(botMessageResponse))  // nothing from bot-commands, so try doing something with LUIS
            {
                // Run async method in this sync method  (read https://cpratt.co/async-tips-tricks/)
                intentResponse = AsyncHelper.RunSync(() => _luisService.GetIntentAsync(e.ChatMessage.Message.Trim()));

                decimal certaintyThreshold;

                if (!decimal.TryParse(_luisConfiguration.LuisChatCertaintyThreshold, out certaintyThreshold))
                {
                    throw new ArgumentException(nameof(_luisConfiguration.LuisChatCertaintyThreshold));
                }


                if (intentResponse.Certainty > certaintyThreshold)
                {
                    botMessageResponse = _chatMessageService.MapLuisIntentToResponse(intentResponse);
                }
            }

            AddTwitchUserChatRecordToDb(e, intentResponse);
            _twitchClient.SendMessage(_twitchConfiguration.ChannelName, botMessageResponse);
        }
Ejemplo n.º 7
0
        public static void HandleContext(Database dc, AIConfiguration AiConfig, IntentResponse intentResponse, AIResponse aiResponse)
        {
            if (intentResponse == null)
            {
                return;
            }

            // Merge context lifespan
            // override if exists, otherwise add, delete if lifespan is zero
            dc.DbTran(() =>
            {
                var sessionContexts = dc.Table <ConversationContext>().Where(x => x.ConversationId == AiConfig.SessionId).ToList();

                // minus 1 round
                sessionContexts.Where(x => !intentResponse.Contexts.Select(ctx => ctx.Name).Contains(x.Context))
                .ToList()
                .ForEach(ctx => ctx.Lifespan = ctx.Lifespan - 1);

                intentResponse.Contexts.ForEach(ctx =>
                {
                    var session1 = sessionContexts.FirstOrDefault(x => x.Context == ctx.Name);

                    if (session1 != null)
                    {
                        if (ctx.Lifespan == 0)
                        {
                            dc.Table <ConversationContext>().Remove(session1);
                        }
                        else
                        {
                            session1.Lifespan = ctx.Lifespan;
                        }
                    }
                    else
                    {
                        dc.Table <ConversationContext>().Add(new ConversationContext
                        {
                            ConversationId = AiConfig.SessionId,
                            Context        = ctx.Name,
                            Lifespan       = ctx.Lifespan
                        });
                    }
                });
            });

            aiResponse.Result.Contexts = dc.Table <ConversationContext>()
                                         .Where(x => x.Lifespan > 0 && x.ConversationId == AiConfig.SessionId)
                                         .Select(x => new AIContext {
                Name = x.Context.ToLower(), Lifespan = x.Lifespan
            })
                                         .ToArray();
        }
Ejemplo n.º 8
0
        public string MapLuisIntentToResponse(IntentResponse intentResponse)
        {
            string intent = intentResponse.Intent.ToLower();

            switch (intent)
            {
            case "compliment":
                return(_luisChatResponses.Compliment);

            case "greeting":
                return(_luisChatResponses.Greeting);

            case "hostile":
                return(_luisChatResponses.Hostile);

            case "howdoesbotwork":
                return(_luisChatResponses.Howdoesbotwork);

            case "howlongprogramming":
                return(_luisChatResponses.Howlongprogramming);

            case "lowlongstream":
                return(_luisChatResponses.Howlongstream);

            case "innapropriate":
                return(_luisChatResponses.Innapropriate);

            case "provideurllink":
                return(_luisChatResponses.Provideurllink);

            case "whatareyoudoing":
                return(_luisChatResponses.Whatareyoudoing);

            case "whatlanguage":
                return(_luisChatResponses.Whatlanguage);

            case "whendoyoustream":
                return(_luisChatResponses.Whendoyoustream);

            case "whichide":
                return(_luisChatResponses.WhichIDE);

            case "whoareyou":
                return(_luisChatResponses.Whoareyou);

            default:
                return(string.Empty);
            }
        }
Ejemplo n.º 9
0
        public IntentResponse ToIntentResponse(IntentResponse intentResponse = null)
        {
            if (intentResponse == null)
            {
                intentResponse = new IntentResponse
                {
                    Id            = Guid.NewGuid().ToString(),
                    ResetContexts = ResetContexts,
                    Contexts      = AffectedContexts.Select(x => x.ToObject <IntentResponseContext>()).ToList(),
                    Parameters    = Parameters.Select(x => x.ToObject <IntentResponseParameter>()).ToList(),
                    Messages      = Messages.Select(x => x.ToIntentResponseMessage()).ToList()
                };
            }

            return(intentResponse);
        }
Ejemplo n.º 10
0
        private List <AIContext> HandleContexts(string sessionId, IntentResponse response)
        {
            var newContexts = response.Contexts.Select(x => new AIContext
            {
                Name       = x.Name,
                Lifespan   = x.Lifespan,
                Parameters = response.Parameters.Select(p => new KeyValuePair <string, object>(p.Name, p.Value)).ToDictionary(d => d.Key, d => d.Value == null ? String.Empty : d.Value)
            }).ToList();

            // persist
            var ctxStore = contextStorageFactory.Get();

            ctxStore.Persist(sessionId, newContexts.ToArray());

            return(newContexts);
        }
Ejemplo n.º 11
0
        private void AddTwitchUserChatRecordToDb(OnMessageReceivedArgs e, IntentResponse intentResponse)
        {
            // create new chat record
            TwitchUserChat twitchUserChat = new TwitchUserChat
            {
                TwitchUserId          = e.ChatMessage.UserId.ToString(),
                TwitchUserType        = e.ChatMessage.UserType.ToString(),
                TwitchUserDisplayName = e.ChatMessage.DisplayName.ToString(),
                ChatMessage           = e.ChatMessage.Message,
                ExtractedUrl          = intentResponse.EmbeddedUrl,
                LuisIntent            = intentResponse.Intent,
                LuisCertainty         = intentResponse.Certainty
            };

            // add chat record to DB
            AsyncHelper.RunSync(() => _twitchUserChatRepository.CreateAsync(twitchUserChat));
        }
Ejemplo n.º 12
0
        public static void HandleMessage(IntentResponse intentResponse)
        {
            if (intentResponse == null)
            {
                return;
            }

            var missingRequiredParameter = intentResponse.Parameters.FirstOrDefault(x => x.Required && String.IsNullOrEmpty(x.Value));

            if (missingRequiredParameter != null)
            {
                intentResponse.Messages = new List <IntentResponseMessage> {
                    new IntentResponseMessage {
                        Type             = AIResponseMessageType.Text,
                        Speech           = ArrayHelper.GetRandom(missingRequiredParameter.Prompts).Prompt,
                        IntentResponseId = intentResponse.Id,
                        UpdatedTime      = DateTime.UtcNow
                    }
                };
            }
            else
            {
                intentResponse.Messages = intentResponse.Messages.OrderBy(x => x.UpdatedTime).ToList();
            }

            intentResponse.Messages.ToList()
            .ForEach(msg =>
            {
                if (msg.Type == AIResponseMessageType.Custom)
                {
                }
                else
                {
                    if (msg.Speech != "[]")
                    {
                        msg.Speech = msg.Speech.StartsWith("[") ?
                                     ArrayHelper.GetRandom(msg.Speech.Substring(2, msg.Speech.Length - 4).Split("\",\"").ToList()) :
                                     msg.Speech;

                        msg.Speech = ReplaceParameters4Response(intentResponse.Parameters, msg.Speech);
                    }
                }
            });
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="agent"></param>
        /// <param name="intentResponse"></param>
        /// <param name="response"></param>
        /// <param name="request"></param>
        /// <returns>Required field is missed</returns>
        public static void HandleParameter(AgentModel agent, IntentResponse intentResponse, RasaResponse response, AiRequest aiRequest)
        {
            if (intentResponse == null)
            {
                return;
            }

            intentResponse.Parameters.ForEach(p => {
                string query = aiRequest.Text;
                var entity   = response.Entities.FirstOrDefault(x => x.Entity == p.Name || x.Entity.Split(':').Contains(p.Name));
                if (entity != null)
                {
                    p.Value = query.Substring(entity.Start, entity.End - entity.Start);
                }

                // convert to Standard entity value

                /*if (!String.IsNullOrEmpty(p.Value) && !p.DataType.StartsWith("sys."))
                 * {
                 *  p.Value = agent.Entities
                 *      .FirstOrDefault(x => x.Entity == p.DataType)
                 *      .Entries
                 *      .FirstOrDefault((entry) =>
                 *      {
                 *          return entry.Value.ToLower() == p.Value.ToLower() ||
                 *              entry.Synonyms.Select(synonym => synonym.Synonym.ToLower()).Contains(p.Value.ToLower());
                 *      })?.Value;
                 * }*/

                // fixed entity per request

                /*if (aiRequest.Entities != null)
                 * {
                 *  var fixedEntity = request.Entities.FirstOrDefault(x => x.Name == p.Name);
                 *  if (fixedEntity != null)
                 *  {
                 *      if (query.ToLower().Contains(fixedEntity.Entries.First().Value.ToLower()))
                 *      {
                 *          p.Value = fixedEntity.Entries.First().Value;
                 *      }
                 *  }
                 * }*/
            });
        }
Ejemplo n.º 14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="agent"></param>
        /// <param name="intentResponse"></param>
        /// <param name="response"></param>
        /// <param name="request"></param>
        /// <returns>Required field is missed</returns>
        public static void HandleParameter(Agent agent, IntentResponse intentResponse, RasaResponse response, AIRequest request)
        {
            if (intentResponse == null)
            {
                return;
            }

            intentResponse.Parameters.ForEach(p => {
                string query = request.Query.First();
                var entity   = response.Entities.FirstOrDefault(x => x.Entity == p.Name || x.Entity.Split(":").Contains(p.Name));
                if (entity != null)
                {
                    p.Value = query.Substring(entity.Start, entity.End - entity.Start);
                }

                // convert to Standard entity value
                if (!String.IsNullOrEmpty(p.Value) && !p.DataType.StartsWith("sys."))
                {
                    p.Value = agent.Entities
                              .FirstOrDefault(x => x.Name == p.DataType)
                              .Entries
                              .FirstOrDefault((entry) =>
                    {
                        return(entry.Value.ToLower() == p.Value.ToLower() ||
                               entry.Synonyms.Select(synonym => synonym.Synonym.ToLower()).Contains(p.Value.ToLower()));
                    })?.Value;
                }

                // fixed entity per request
                if (request.Entities != null)
                {
                    var fixedEntity = request.Entities.FirstOrDefault(x => x.Name == p.Name);
                    if (fixedEntity != null)
                    {
                        if (query.ToLower().Contains(fixedEntity.Entries.First().Value.ToLower()))
                        {
                            p.Value = fixedEntity.Entries.First().Value;
                        }
                    }
                }
            });
        }
Ejemplo n.º 15
0
        private static IntentResponse CreateResponse(AvailabilityMessageModel messages)
        {
            var cardMessage       = messages.CardMessages.First();
            var assistantResponse = messages.SimpleResponses.First();
            var response          = new IntentResponse
            {
                FulfillmentText     = messages.FulFillmentMessage,
                FulfillmentMessages = new List <Models.Response.Fulfillmentmessage>
                {
                    new Models.Response.Fulfillmentmessage
                    {
                        Card = new Card
                        {
                            Title    = cardMessage.Title,
                            Subtitle = cardMessage.SubTitle
                        }
                    }
                },
                Payload = new Models.Response.Payload
                {
                    Google = new Models.Response.Google
                    {
                        ExpectUserResponse = false,
                        RichResponse       = new Richresponse
                        {
                            Items = new List <Item>
                            {
                                new Item
                                {
                                    SimpleResponse = assistantResponse
                                }
                            }
                        }
                    }
                }
            };

            return(response);
        }
Ejemplo n.º 16
0
        public async Task <IntentResponse> GetIntentAsync(string phrase)
        {
            var luisApiIntentUri = new Uri(this.LuisApiUri, $"?subscription-key={this.LuisInstanceKey}&verbose=true&timezoneOffset=0&q={phrase}");
            var luisResponse     = await this.GetLuisIntent(luisApiIntentUri);

            var intentResponse = new IntentResponse();

            intentResponse.Intent = luisResponse.TopScoringIntent.Intent;
            foreach (var entity in luisResponse.Entities)
            {
                intentResponse.Entities.Add(
                    new Entity
                {
                    Name       = entity.Entity,
                    Score      = entity.Score,
                    StartIndex = entity.StartIndex,
                    EndIndex   = entity.EndIndex,
                    Type       = entity.Type
                });
            }

            return(intentResponse);
        }
Ejemplo n.º 17
0
 public ActionMessage(IntentResponse intent)
 {
     Intent = intent;
 }