コード例 #1
0
        public static QnaEntity QNAConnection(string question)
        {
            var lst = new QnaEntity();

            try
            {
                ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; //---> Remove later

                var client  = new RestClient(QNAMakerSettings.host);
                var request = new RestRequest($"/knowledgebases/{QNAMakerSettings.kbid}/generateAnswer", Method.POST);

                request.RequestFormat = DataFormat.Json;
                request.AddHeader("Authorization", $"EndpointKey {QNAMakerSettings.authkey}");
                request.AddBody(new
                {
                    question = question,
                    top      = 5
                });
                lst = client.Execute <QnaEntity>(request).Data;
            }
            catch (Exception ex)
            {
                //throw?
            }
            return(lst);
        }
コード例 #2
0
ファイル: CarouselDialog.cs プロジェクト: jonnunez/C-Chatbot
        public static async Task Carousel(Activity msg, RecognizerResult recognizerResult, BotAccessors accessors, WaterfallStepContext step, CancellationToken cancellationToken = default(CancellationToken))
        {
            List <HeroCard> herocardlst = new List <HeroCard>();
            var             questions   = new QnaEntity();

            questions.answers = new List <Answer>();

            TextInfo textInfo             = new CultureInfo("en-US", false).TextInfo;
            int      TotalNextBestAnswers = Convert.ToInt32(Settings.TotalBestNextAnswers);
            await accessors.UserState.SaveChangesAsync(step.Context, true, cancellationToken);

            int counter = 0;
            var intents = recognizerResult.Intents.OrderByDescending(i => i.Value.Score);

            foreach (var item in intents)
            {
                var luisscore = item.Value.Score * 100;
                step.Context.Activity.Text = item.Key;

                if (/*(luisscore <= MedConfidenceThresholdValue1 && luisscore >= MedConfidenceThresholdValue2)*/ counter <= Counter)
                {
                    var qnaResponse = await accessors.QnAServices[Settings.QnAName01].GetAnswersAsync(step.Context);
                    counter++;
                    if (qnaResponse != null && qnaResponse.Length > 0)
                    {
                        Answer answer = new Answer
                        {
                            answer    = qnaResponse[0].Answer,
                            metadata  = qnaResponse[0].Metadata.ToList(),
                            questions = qnaResponse[0].Questions.ToList() //added this so that I can map the question to the variable
                        };
                        questions.answers.Add(answer);
                    }
                }
            }

            if (questions != null && questions.answers != null && questions.answers.Any() && questions.answers[0].answer != "No good match found in KB.")
            {
                foreach (var item in questions.answers.Where(i => i.metadata != null && i.metadata.Count > 0 && i.answer != "No good match found in KB."))
                {
                    var        title    = (from b in item.metadata where b.Name == CarouselSettings.carouseltitle select b.Value).FirstOrDefault();
                    var        question = item.questions?.FirstOrDefault();
                    CardButton cButton  = new CardButton();
                    cButton.value = question;// question;
                    herocardlst.Add(new HeroCard
                    {
                        Title    = textInfo.ToTitleCase(title),
                        Subtitle = FirstCharToUpper((from b in item.metadata
                                                     where b.Name == CarouselSettings.carouselsummary
                                                     select b.Value).FirstOrDefault()),

                        Buttons = new List <CardAction>()
                        {
                            new CardAction(ActionTypes.PostBack, QNABotSettings.seedetails, value: JsonConvert.SerializeObject(cButton))
                        },                                                                                                                                                 //qnaResponse.questions[0] JsonConvert.SerializeObject(cButton) changed instead of title, takes
                    });
                }

                msg.SuggestedActions = new SuggestedActions
                {
                    Actions = CardActionDialog.GetNoneoftheAbove()
                };
                msg.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                herocardlst.ForEach(i => msg.Attachments.Add(i.ToAttachment()));
                await step.Context.SendActivityAsync(msg);
            }
            else
            {
                var defaultMessage = step.Context.Activity.CreateReply(QNABotSettings.sorrynextrelease);
                defaultMessage.SuggestedActions = new SuggestedActions {
                    Actions = CardActionDialog.GetContactInfoCard()
                };
                await step.Context.SendActivityAsync(defaultMessage);
            }
        }
コード例 #3
0
ファイル: QNADialog.cs プロジェクト: jonnunez/C-Chatbot
        protected override async Task RespondFromQnAMakerResultAsync(IDialogContext context, IMessageActivity message, QnAMakerResults result)
        {
            var telemetry = new TelemetryClient();

            try
            {
                var      qnaAnswer    = result?.Answers?.First()?.Answer;//store qnamaker result text and store it in qnaAnswer variable
                var      qnaQuestions = result?.Answers?.First()?.Questions;
                var      questions    = new QnaEntity();
                var      userinput    = new QnaHelper();
                var      myquestion   = result;
                Activity reply        = ((Activity)context.Activity).CreateReply();

                if (qnaAnswer != null & qnaQuestions != null && qnaQuestions.Any())
                {
                    if (message.Text.ToString().ToLower().Contains("help") || message.Text.ToString().ToLower().Contains("ayuda"))
                    {
                        await context.PostAsync(QNABotSettings.prompt1);

                        Task.Delay(2000);
                        await context.PostAsync(QNABotSettings.prompt2);

                        return;
                    }

                    if (qnaQuestions.Any())
                    {
                        questions = QnaHelper.QNAConnection(qnaQuestions?.FirstOrDefault());
                        context.UserData.SetValue("questions", questions);
                    }
                    else
                    {
                        context.UserData.RemoveValue("questions");
                    }

                    var score = result.Answers.OrderByDescending(i => i.Score).FirstOrDefault()?.Score;

                    if (score != null)
                    {
                        score = score * 100;

                        //Threshold 1 Path! 100% - 80%
                        if (score <= (Convert.ToInt32(QNABotSettings.threshold1[0]) + 0.99) && score >= Convert.ToInt32(QNABotSettings.threshold1[1]))
                        {
                            f.Flags1++;
                            if (qnaAnswer.Contains("||"))
                            {
                                var msg     = context.MakeMessage();
                                var answers = qnaAnswer.Split("||".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
                                msg.Attachments.Add(await GetCardsAttachments(answers));
                                await context.PostAsync(msg);

                                if (qnaAnswer.Contains(ConfigurationManager.AppSettings["HRHeroTitle"]))
                                {
                                    showHRHeroCardFlag = false;
                                }
                                else
                                {
                                    showHRHeroCardFlag = true;
                                }
                            }
                            else
                            {
                                await context.PostAsync(qnaAnswer);
                            }
                        }

                        //Threshold 2 Path!79 % -40 %
                        else if (score <= (Convert.ToInt32(QNABotSettings.threshold2[0]) + 0.99) && score >= Convert.ToInt32(QNABotSettings.threshold2[1]))//79-40
                        {
                            f.Flags2++;
                            context.UserData.SetValue("firstCheck", "true");
                            showHRHeroCardFlag = true;
                            var msg         = ((Activity)context.Activity).CreateReply(QNABotSettings.accurateanswer); //for carousel
                            var herocardlst = new List <HeroCard>();
                            if (questions != null && questions.answers != null && questions.answers.Any())
                            {
                                foreach (var item in questions.answers.Where(i => i.metadata != null))
                                {
                                    //string TitleCase = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase();
                                    //System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase() //this is causing issues with Spanish language
                                    herocardlst.Add(new HeroCard
                                    {
                                        Title = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase((from b in item.metadata
                                                                                                                      where b.name == CarouselSettings.carouseltitle
                                                                                                                      select b.value).FirstOrDefault()),

                                        Subtitle = (from b in item.metadata
                                                    where b.name == CarouselSettings.carouselsummary
                                                    select b.value).FirstOrDefault(),
                                        Buttons = new List <CardAction>()
                                        {
                                            new CardAction(ActionTypes.PostBack, QNABotSettings.seedetails, value: item.questions?.FirstOrDefault())
                                        },
                                    });
                                }
                            }
                            msg.SuggestedActions = new SuggestedActions
                            {
                                Actions = CardActionDialogue.GetNoneoftheAbove()
                            };

                            msg.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                            herocardlst.ForEach(i => msg.Attachments.Add(i.ToAttachment()));
                            msg.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                            await context.PostAsync(msg);

                            context.Wait(Noneoftheabovedialog);
                        }

                        //Threshold 3 Path!39 % -0 %
                        else if (score < (Convert.ToInt32(QNABotSettings.threshold3[0]) + 0.99) && score >= Convert.ToInt32(QNABotSettings.threshold3[1])) //39-0
                        {
                            var defaultMessage = ((Activity)context.Activity).CreateReply(QNABotSettings.sorrynextrelease);                                //Created a new Activity object which will prompt the user with a question – “Did you find what you need?” when the dialog starts

                            defaultMessage.SuggestedActions = new SuggestedActions {
                                Actions = CardActionDialogue.GetContactInfoCard()
                            };

                            await context.PostAsync(defaultMessage);

                            context.Wait(ChoiceMenuLogic);
                        }
                    }
                }
                else
                {
                    var defaultMessage = ((Activity)context.Activity).CreateReply(QNABotSettings.sorrynextrelease);//Created a new Activity object which will prompt the user with a question – “Did you find what you need?” when the dialog starts

                    defaultMessage.SuggestedActions = new SuggestedActions {
                        Actions = CardActionDialogue.GetContactInfoCard()
                    };
                    context.UserData.SetValue("firstCheck", "false");
                    await context.PostAsync(defaultMessage);

                    context.Wait(ChoiceMenuLogic);
                }
            }
            catch (Exception)
            {
                throw;
                //telemetry.TrackEvent("QnA Dialog RespondFromQnAMakerResultAsync Exception", new Dictionary<string, string> { { "Exception", SimpleJson.SimpleJson.SerializeObject(ex) } });
            }
        }