示例#1
0
        /// <summary>
        /// Call the QnA Maker endpoint and get a response
        /// </summary>
        /// <param name="query">User question</param>
        /// <returns></returns>
        public async Task <QnAAnswer> GetAnswer(string query)
        {
            var qnaResponse = new QnAResponse();

            using (HttpClient client = new HttpClient())
            {
                string requestUri = String.Format("{0}{1}{2}{3}",
                                                  _qnaServiceHostName,
                                                  @"knowledgebases/",
                                                  _knowledgeBaseId,
                                                  @"/generateAnswer");

                var httpContent = new StringContent("{\"question\": \"" + query + "\"}}", Encoding.UTF8, "application/json");

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("EndpointKey", _endpointKey);

                var msg = await client.PostAsync(requestUri, httpContent);

                if (msg.IsSuccessStatusCode)
                {
                    var jsonDataResponse = await msg.Content.ReadAsStringAsync();

                    qnaResponse = JsonConvert.DeserializeObject <QnAResponse>(jsonDataResponse);
                }
            }

            if (qnaResponse != null && qnaResponse.Answers != null && qnaResponse.Answers.Count > 0)
            {
                return(qnaResponse.Answers.FirstOrDefault());
            }
            else
            {
                return(null);
            }
        }
示例#2
0
        public async Task <QnAResponse> GetAnswerAsync(string question)
        {
            string responseString = string.Empty;


            //Build the URI
            Uri qnamakerUriBase = new Uri("https://westus.api.cognitive.microsoft.com/qnamaker/v1.0");
            var builder         = new UriBuilder($"{qnamakerUriBase}/knowledgebases/{knowledgebaseId}/generateAnswer");

            //Add the question as part of the body
            var postBody = $"{{\"question\": \"{question}\"}}";

            //Send the POST request
            using (WebClient client = new WebClient())
            {
                //Add the subscription key header
                client.Headers.Add("Ocp-Apim-Subscription-Key", qnamakerSubscriptionKey);
                client.Headers.Add("Content-Type", "application/json");
                responseString = await client.UploadStringTaskAsync(builder.Uri, postBody);
            }

            QnAResponse response = await JSONHelper.DeSerializeJSON <QnAResponse>(responseString);

            return(response);
        }
示例#3
0
        public async Task QnA(IDialogContext context, LuisResult result)
        {
            QnAService  qNa     = new QnAService();
            QnAResponse reponse = await qNa.GetAnswerAsync(result.Query);

            await context.PostAsync(reponse.Answer);

            context.Wait(this.MessageReceived);
        }
示例#4
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;

            // Typing
            var typingActivity = ((Activity)context.Activity).CreateReply();

            typingActivity.Type = ActivityTypes.Typing;
            await context.PostAsync(typingActivity);

            string      searchText = activity.Text;
            QnAResponse response   = await Utils.ServiceProxies.GetQnAResponse(searchText);

            if (response.answers != null && response.answers.Length > 0 && response.answers[0].score >= 50)
            {
                searchText = response.answers[0].answer;
            }

            // Now do Azure Search
            string searchResult = Utils.ServiceProxies.SearchMarkdown(searchText);
            string resultText   = "I unfortunately didn't find anything for you!";
            string resultSpeech = "I unfortunately didn't find anything for you!";

            if (!String.IsNullOrEmpty(searchResult))
            {
                JObject jsonResult = JObject.Parse(searchResult);
                if (jsonResult["value"][0] != null)
                {
                    resultText   = jsonResult["value"][0]["content"].Value <string>();
                    resultSpeech = jsonResult["value"][0]["textcontent"].Value <string>();
                }
            }

            Activity reply = activity.CreateReply(resultText);

            reply.Speak = resultSpeech;

            await context.PostAsync(reply);

            context.Wait(MessageReceivedAsync);
        }
示例#5
0
        public async Task <QnAAnswer> AskWineChatbotFaqAsync(string question)
        {
            const string BaseUrl         = "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0";
            string       knowledgeBaseID = ConfigurationManager.AppSettings["QnAKnowledgeBaseID"];
            string       url             = $"{BaseUrl}//knowledgebases/{knowledgeBaseID}/generateAnswer";

            var    client    = new HttpClient();
            string accessKey = ConfigurationManager.AppSettings["QnASubscriptionKey"];

            client.DefaultRequestHeaders.Add(AccessKey, accessKey);

            var content = new StringContent(
                $"{{ \"question\": \"{question}\" }}", Encoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PostAsync(url, content);

            string jsonResult = await response.Content.ReadAsStringAsync();

            QnAResponse qnaResponse = JsonConvert.DeserializeObject <QnAResponse>(jsonResult);

            return(qnaResponse.Answers.FirstOrDefault());
        }
示例#6
0
        public static async Task <QnAResponse> GetQnAResponse(string Question)
        {
            QnARequest request = new QnARequest();

            request.question = Question;

            QnAResponse data = new QnAResponse();

            using (WebClient client = new WebClient())
            {
                client.Headers.Add("Content-Type", "application/json");
                client.Headers.Add("Ocp-Apim-Subscription-Key", ConfigurationManager.AppSettings["QnAKey"]);
                client.Encoding = System.Text.Encoding.UTF8;

                string requestUri = ConfigurationManager.AppSettings["QnAEndpoint"];

                string responseString = client.UploadString(requestUri, JsonConvert.SerializeObject(request));
                string decodedString  = System.Net.WebUtility.HtmlDecode(responseString).Replace("\"", "'").Replace("„", "'");
                data = JsonConvert.DeserializeObject <QnAResponse>(decodedString);
            }

            return(data);
        }
示例#7
0
        public static async Task <QnAResponse> GetQnAResponse(string Question)
        {
            QnARequest request = new QnARequest();

            request.question = Question;

            QnAResponse data = new QnAResponse();

            using (WebClient client = new WebClient())
            {
                client.Headers.Add("Content-Type", "application/json");
                client.Headers.Add("Ocp-Apim-Subscription-Key", "6a50acd8314e456191ecf4cbf40164c9");
                client.Encoding = System.Text.Encoding.UTF8;

                string requestUri = "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/efe61b54-60d9-4630-a773-2c9ae7288fed/generateAnswer";

                string responseString = client.UploadString(requestUri, JsonConvert.SerializeObject(request));
                string decodedString  = System.Net.WebUtility.HtmlDecode(responseString).Replace("\"", "'").Replace("„", "'");
                data = JsonConvert.DeserializeObject <QnAResponse>(decodedString);
            }

            return(data);
        }
示例#8
0
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var message = await argument;
            // First send typing
            var typingActivity = ((Activity)message).CreateReply();

            typingActivity.Type = ActivityTypes.Typing;
            await context.PostAsync(typingActivity);

            LuisResponse luisInfo = await ServiceProxies.GetEntityFromLUIS(message.Text);

            if (luisInfo.intents != null && luisInfo.intents.Length > 0 && luisInfo.intents[0].score > 0.8 && luisInfo.intents[0].intent == "Kreditablösen")
            {
                // Kredit
                await context.PostAsync("Wollen Sie die Kreditablösesumme jetzt anfordern?");

                context.Wait(this.StartKreditAblöseDialog);
            }
            //else if (luisInfo.intents != null && luisInfo.intents.Length > 0 && luisInfo.intents[0].score > 0.8 && luisInfo.intents[0].intent == "Wikipedia")
            //{
            //    // Wikipedia
            //    string answer = "Das weiß ich nicht, ich lerne noch..";
            //    string wikiResult = await ServiceProxies.SearchWikipedia(luisInfo.entities[0].entity);

            //    Newtonsoft.Json.Linq.JArray jsonResult = JArray.Parse(wikiResult);
            //    JArray titleArray = (JArray)jsonResult[1];
            //    JArray descriptionArray = (JArray)jsonResult[2];
            //    JArray linkArray = (JArray)jsonResult[3];

            //    if (titleArray.Count > 0)
            //    {
            //        answer = "Ich kenne mich nicht so aus, aber hier sind Infos von Wikipedia: " + titleArray[0].ToString() + ". " + descriptionArray[0].ToString();
            //    }

            //    await context.PostAsync(answer);
            //    context.Wait(MessageReceivedAsync);
            //}
            else
            {
                // Fall back on QnAMaker
                QnAResponse response = await ServiceProxies.GetQnAResponse(message.Text);

                string answer = "Das weiß ich nicht, ich lerne noch..";

                if (response.answers.Length > 0 && response.answers[0].score > 0.7)
                {
                    if (smalltalkData[response.answers[0].answer] != null)
                    {
                        // Get random answer from array
                        int index = randomGen.Next(0, ((JArray)smalltalkData[response.answers[0].answer]).Count - 1);
                        answer = smalltalkData[response.answers[0].answer][index].ToString();
                    }
                    else if (!response.answers[0].answer.Contains(".agent."))
                    {
                        answer = response.answers[0].answer;
                    }
                    else
                    {
                        System.Diagnostics.Trace.TraceError("MISSING-ANSWER: " + message.Text);
                    }
                }
                else
                {
                    System.Diagnostics.Trace.TraceError("MISSING-ANSWER: " + message.Text);
                }

                await context.PostAsync(answer);

                context.Wait(MessageReceivedAsync);
            }
        }