public async Task Help(IDialogContext context, IAwaitable <IMessageActivity> activity, LuisResult result) { var qnaMakerResult = new QnAMakerResult(); string returnMessage = string.Empty; var message = await activity; contentType = message.Locale; await context.PostAsync($"Translate to English: {message.Text}"); qnaMakerResult = qnAmakerService.GetMessageFromQnAMaker(message.Text); message.Text = qnaMakerResult.answers.Count > 0 ? qnaMakerResult.answers[0].answer : string.Empty; // debug await context.PostAsync($"Get message from QnA maker: {message.Text}"); if (!string.IsNullOrEmpty(message.Text)) { returnMessage = await translatorService.TranslatorExecute("en", contentType, message.Text); } else { returnMessage = await translatorService.TranslatorExecute("en", contentType, $"system error"); } await context.PostAsync(returnMessage); context.Wait(MessageReceived); }
private IEnumerable <Restaurant> GetRestaurantsAsync(RestaurantsQuery searchQuery) { var hotels = new List <Restaurant>(); var qnaMakerResult = new QnAMakerResult(); var randomCount = new Random(); var count = randomCount.Next(1, 5); // Filling the hotels results manually just for demo purposes for (int i = 1; i <= count; i++) { var random = new Random(i); qnaMakerResult = qnAmakerService.GetMessageFromQnAMaker("Restaurant " + random.Next(1, 5).ToString()); Restaurant restaurant = new Restaurant() { Name = $"{searchQuery.PlaceName ?? searchQuery.Address} Restaurant {i}", Location = searchQuery.PlaceName ?? searchQuery.Address, Rating = random.Next(1, 5), NumberOfReviews = random.Next(0, 5000), PriceStarting = random.Next(80, 450), Image = qnaMakerResult.answers.Count > 0 ? qnaMakerResult.answers[0].answer : string.Empty }; hotels.Add(restaurant); } //hotels.Sort((h1, h2) => h1.PriceStarting.CompareTo(h2.PriceStarting)); return(hotels); }
public static QnAMakerResult Get(string knowledgebaseId, string qnamakerSubscriptionKey, string Query) { string responseString = string.Empty; QnAMakerResult response; try { //Build the URI Uri qnamakerUriBase = new Uri(QnAMakerURL); var builder = new UriBuilder($"{qnamakerUriBase}/knowledgebases/{knowledgebaseId}/generateAnswer"); QQ q = new QQ(); q.question = Query; var postBody = JsonConvert.SerializeObject(q); //var postBody = $"{{\"question\": \"{Query}\"}}"; //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"); client.Encoding = System.Text.Encoding.UTF8; responseString = client.UploadString(builder.Uri, postBody); } //De-serialize the response response = JsonConvert.DeserializeObject <QnAMakerResult>(responseString); } catch (Exception EQ) { response = new QnAMakerResult(); response.Score = 50; response.Answer = "Error:" + EQ.Message; } return(response); }
/// <summary> /// Processes the confident QnA Maker answer and get results /// </summary> /// <param name="context">The database context</param> /// <param name="answers">The answers</param> /// <returns></returns> public String ProcessConfidentAnswerAndGetResult(DbContext context, QnAMakerResult answer) { var parsedAnswers = ParseAnswers(answer); var result = SelectAnswer(parsedAnswers); return(SubstitutePlaceholders(context, result)); }
private string GetAnswer(string query) { string responseString = string.Empty; try { var knowledgebaseId = Convert.ToString("bdadde1b-deee-4321-9a08-df7b8c801b82", CultureInfo.InvariantCulture); //Build the URI var builder = new UriBuilder(string.Format(Convert.ToString($"https://botqnamakerdemo.azurewebsites.net/qnamaker/knowledgebases/{knowledgebaseId}/generateAnswer", CultureInfo.InvariantCulture), knowledgebaseId)); //Add the question as part of the body var postBody = string.Format("{{\"question\": \"{0}\"}}", query); //Send the POST request using (WebClient client = new WebClient()) { //Set the encoding to UTF8 client.Encoding = System.Text.Encoding.UTF8; //Add the subscription key header var qnamakerSubscriptionKey = Convert.ToString("63a32ec5-7201-4ac3-8fb6-823bf795302f", CultureInfo.InvariantCulture); client.Headers.Add("Authorization", $"EndpointKey {qnamakerSubscriptionKey}"); client.Headers.Add("Content-Type", "application/json"); responseString = client.UploadString(builder.Uri, postBody); } QnAMakerResult result = JsonConvert.DeserializeObject <QnAMakerResult>(responseString); return(result.Answers[0].Answer); } catch (Exception exception) { } return(string.Empty); }
private static Attachment CreateCard(QnAMakerResult qnaMakerResult) { return(new HeroCard { Subtitle = qnaMakerResult.Questions.First(), Text = qnaMakerResult.Answer }.ToAttachment()); }
//This method is called automatically when there is a result for the question public override async Task DefaultMatchHandler(IDialogContext context, string originalQueryText, QnAMakerResult result) { if (originalQueryText.ToUpper() == "EXIT") { context.Done(""); return; } await context.PostAsync(result.Answers.First().Answer); context.Wait(MessageReceived); }
[QnAMakerResponseHandler(0.5)] //1: 100%, 0.5: 50% //This method is called when there is a low-order result. public async Task LowScoreHandler(IDialogContext context, string originalQueryText, QnAMakerResult result) { var messageActivity = ProcessResultAndCreateMessageActivity(context, ref result); messageActivity.Text = $"I found an answer that might help..." + $"{result.Answers.First().Answer}."; await context.PostAsync(messageActivity); context.Wait(MessageReceived); }
private async Task MakeQnAMakerCall(IDialogContext context, string QueryString) { string KnowledgeBaseId = KeysAndRessourceStrings.KnowledgeBaseIdQuestions; string SubscriptionKey = KeysAndRessourceStrings.SubscriptionKeyQnAMaker; IQnAMakerRequests QnAMakerAPI = new QnAMakerRequests(); IQnAMakerMatchHandler QnAMakerMatchHandler = new QnAMakerMatchHandler(); QnAMakerResult QnAMakerResultObject = await QnAMakerAPI.GetQnAMakerResponse(QueryString, KnowledgeBaseId, SubscriptionKey); await QnAMakerMatchHandler.QnAMakerResultProcessing(context, QueryString, QnAMakerResultObject); }
private async void FilterIntentScore(IDialogContext context, LuisResult result) { if (result.TopScoringIntent.Score < INTENT_SCORE_THRESHOLD) { // Chamar QnA Maker QnAMakerResult qnaResult = await QnADialog.MakeRequest(result.Query); if (qnaResult != null && result.TopScoringIntent.Score >= INTENT_SCORE_THRESHOLD && qnaResult.Score >= INTENT_SCORE_THRESHOLD) { await context.PostAsync(qnaResult.Answer); } } }
private async Task <bool> LuisQnADecision(QnAMakerResult QnAMakerResultObject, JObject LuisResult) { double QnAScore = QnAMakerResultObject.Answers[0].Score; double LuisScore = LuisResult.Value <JObject>("topScoringIntent").Value <double>("score"); if (QnAScore > LuisScore * 100) { return(false); } else { return(true); } }
public async Task Reviews(IDialogContext context, IAwaitable <IMessageActivity> activity, LuisResult result) { EntityRecommendation restaurantEntityRecommendation; var qnaMakerResult = new QnAMakerResult(); var qnaMakerResultTitle = new QnAMakerResult(); var qnaMakerResultText = new QnAMakerResult(); var message = await activity; contentType = message.Locale; // debug await context.PostAsync($"Translate to English: {message.Text}"); if (result.TryFindEntity(EntityRestaurantName, out restaurantEntityRecommendation)) { await context.PostAsync(await translatorService.TranslatorExecute("en", contentType, $"Looking for reviews of '{restaurantEntityRecommendation.Entity}'...")); var resultMessage = context.MakeMessage(); resultMessage.AttachmentLayout = AttachmentLayoutTypes.Carousel; resultMessage.Attachments = new List <Attachment>(); var randomCount = new Random(); int count = randomCount.Next(1, 3); for (int i = 0; i < count; i++) { var random = new Random(i); qnaMakerResult = qnAmakerService.GetMessageFromQnAMaker("Review " + random.Next(6, 10).ToString()); qnaMakerResultTitle = qnAmakerService.GetMessageFromQnAMaker("Comments " + random.Next(1, 5).ToString()); qnaMakerResultText = qnAmakerService.GetMessageFromQnAMaker("Comments " + random.Next(6, 10).ToString()); ThumbnailCard thumbnailCard = new ThumbnailCard() { Title = await translatorService.TranslatorExecute("en", contentType, qnaMakerResultTitle.answers.Count > 0?qnaMakerResultTitle.answers[0].answer : titleOptions[random.Next(0, titleOptions.Count - 1)]), Text = await translatorService.TranslatorExecute("en", contentType, qnaMakerResultText.answers.Count > 0?qnaMakerResultText.answers[0].answer : titleOptions[random.Next(0, titleOptions.Count - 1)]), Images = new List <CardImage>() { new CardImage() { Url = qnaMakerResult.answers.Count > 0? qnaMakerResult.answers[0].answer : "https://upload.wikimedia.org/wikipedia/en/e/ee/Unknown-person.gif" } }, }; resultMessage.Attachments.Add(thumbnailCard.ToAttachment()); } await context.PostAsync(resultMessage); } context.Wait(MessageReceived); }
private async Task <TransferObjectQnA> MakeQnAMakerCallforConversion(IDialogContext context, string QueryString) { string KnowledgeBaseId = KeysAndRessourceStrings.KnowledgeBaseIdConvert; string SubscriptionKey = KeysAndRessourceStrings.SubscriptionKeyQnAMaker; IQnAMakerRequests QnAMakerObject = new QnAMakerRequests(); IQnAMakerMatchHandler qnAMakerMatchHandler = new QnAMakerMatchHandler(); // Name to number magic QnAMakerResult QnAMakerResultObject = await QnAMakerObject.GetQnAMakerResponse(QueryString, KnowledgeBaseId, SubscriptionKey); TransferObjectQnA querystring = await qnAMakerMatchHandler.QnAMakerResultProcessingWithReturn(context, QueryString, QnAMakerResultObject); return(querystring); }
private IEnumerable <QnAMakerAnswerModel> ParseAnswers(QnAMakerResult answer) { return(answer.Answer.FromJsonSafe <String[]>() ?.Select(y => new QnAMakerAnswerModel { Answer = y, Score = answer.Score }) ?? new QnAMakerAnswerModel[] { //TODO: parse CSV here new QnAMakerAnswerModel { Answer = answer.Answer, Score = answer.Score } }); }
private Attachment BuildResponseCard(QnAMakerResult answer) { var json = answer.Answer; var response = JsonConvert.DeserializeObject <RichQnaResponse>(json); return(new HeroCard { Text = response.Title, Subtitle = response.Text, Images = new CardImage[] { new CardImage { Url = response.Image } } } .ToAttachment()); }
private static QnAMakerResult Recognize(QnAMakerApp app, string utterance) { var responseString = String.Empty; QnAMakerResult QnAresponse = null; // Send question to API QnA bot if (utterance.Length > 0) { var knowledgebaseId = app.KnowledgeBaseId; var qnamakerSubscriptionKey = app.SubscriptionKey; //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\": \"{utterance}\"}}"; //Send the POST request using (WebClient client = new WebClient()) { //Set headers and encoding client.Encoding = System.Text.Encoding.UTF8; client.Headers.Add("Ocp-Apim-Subscription-Key", qnamakerSubscriptionKey); client.Headers.Add("Content-Type", "application/json"); responseString = client.UploadString(builder.Uri, postBody); } try { QnAresponse = JsonConvert.DeserializeObject <QnAMakerResult>(responseString); } catch { throw new Exception("Unable to deserialize QnA Maker response string."); } } return(QnAresponse); }
public static QnAMakerResult GetFirstQnaAnswer(string inputText) { var query = inputText; // QnA connection string responseString = string.Empty; string returnResult = string.Empty; var builder = new UriBuilder($"{Credentials.QNA_MAKER_URI_BASE}/knowledgebases/{Credentials.QNA_KNOWLEDGE_BASE_ID}/generateAnswer"); //Add the question as part of the body var postBody = $"{{\"question\": \"{query}\"}}"; //Send the POST request using (WebClient client = new WebClient()) { //Set the encoding to UTF8 client.Encoding = System.Text.Encoding.UTF8; //Add the subscription key header client.Headers.Add("Ocp-Apim-Subscription-Key", Credentials.QNA_SUBSCRIPTION_KEY); client.Headers.Add("Content-Type", "application/json"); responseString = client.UploadString(builder.Uri, postBody); } //De-serialize the response QnAMakerResult qnaResponse = null; try { qnaResponse = JsonConvert.DeserializeObject <QnAMakerResult>(responseString); } catch (Exception e) { // Implement exception handling } return(qnaResponse); }
private async Task <List <TransferObjectQnA> > MakeNameQnAMakerCall(IDialogContext context, TransferObjectLuis QueryString) { IQnAMakerRequests QnAMaker = new QnAMakerRequests(); IQnAMakerMatchHandler qnAMakerMatchHandler = new QnAMakerMatchHandler(); List <TransferObjectQnA> TransferList = new List <TransferObjectQnA>(); string KnowledgeBaseId = KeysAndRessourceStrings.KnowledgeBaseIdConvert; string SubscriptionKey = KeysAndRessourceStrings.SubscriptionKeyQnAMaker; QnAMakerResult QnAMakerResultObject = await QnAMaker.GetQnAMakerResponse(QueryString.Name_0, KnowledgeBaseId, SubscriptionKey); TransferList.Add(await qnAMakerMatchHandler.QnAMakerResultProcessingWithReturn(context, QueryString.Name_0, QnAMakerResultObject)); QnAMakerResult QnAMakerResultObject2 = await QnAMaker.GetQnAMakerResponse(QueryString.Name_1, KnowledgeBaseId, SubscriptionKey); TransferList.Add(await qnAMakerMatchHandler.QnAMakerResultProcessingWithReturn(context, QueryString.Name_1, QnAMakerResultObject)); return(TransferList); }
private string GetAnswer(string query) { string responseString = string.Empty; var knowledgebaseId = Convert.ToString(ConfigurationManager.AppSettings["KNOWLEDGE_BASE_ID"], CultureInfo.InvariantCulture); //Build the URI var builder = new UriBuilder(string.Format(Convert.ToString(ConfigurationManager.AppSettings["QNA_SERVICE_URL"], CultureInfo.InvariantCulture), knowledgebaseId)); //Add the question as part of the body var postBody = string.Format("{{\"question\": \"{0}\"}}", query); //Send the POST request using (WebClient client = new WebClient()) { //Set the encoding to UTF8 client.Encoding = System.Text.Encoding.UTF8; //Add the subscription key header var qnamakerSubscriptionKey = Convert.ToString(ConfigurationManager.AppSettings["SUBSCRIPTION_KEY"], CultureInfo.InvariantCulture); // client.Headers.Add("Ocp-Apim-Subscription-Key", qnamakerSubscriptionKey); client.Headers.Add("Authorization", $"EndpointKey {qnamakerSubscriptionKey}"); client.Headers.Add("Content-Type", "application/json"); responseString = client.UploadString(builder.Uri, postBody); } QnAMakerResult result = JsonConvert.DeserializeObject <QnAMakerResult>(responseString); if (result.Answers[0].Answer.Contains("No good match found in KB")) { return(CANT_FIND_TEXT); } if (result.Answers[0].Score < 50) { return(LOW_SCORE_TEXT); } return(result.Answers[0].Answer); }
/// <summary> /// Iterate through all registered QnA Maker apps until reaching a high confidence index /// </summary> /// <param name="utterance"></param> /// <returns></returns> public static QnAMakerResult Recognize(string utterance, string userCulture) { IList <QnAMakerApp> _apps = new List <QnAMakerApp>(); int count = System.Configuration.ConfigurationManager.AppSettings.AllKeys .Where(x => x.StartsWith("QnAMakerAppId") && x.EndsWith(userCulture)) .Count(); //Instantiate a QnAMakerApp for each id and key pair for this user culture for (int i = 1; i <= count; i++) { string id = System.Configuration.ConfigurationManager.AppSettings.GetValues($"QnAMakerAppId_{i}_{userCulture}").First(); string key = System.Configuration.ConfigurationManager.AppSettings.GetValues($"QnAMakerAppKey_{i}_{userCulture}").First(); _apps.Add(new QnAMakerApp() { KnowledgeBaseId = id, SubscriptionKey = key }); } //Iterate through each app until finding a high cofidence response foreach (QnAMakerApp app in _apps) { QnAMakerResult result = Recognize(app, utterance); // Get pre-defined confidence threshold float.TryParse(System.Configuration.ConfigurationManager.AppSettings.GetValues("QnaMakerConfidenceThreshold").First(), out float confidenceThreshold); if (result.Score >= confidenceThreshold) { return(result); } } // No result was better than the pre-defined confidence threshould, ignore this QnA App return(null); }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result) { var activity = await result as Activity; ILuisRequest LuisAPI = new LuisRequest(); IQnAMakerRequests QnAMakerAPI = new QnAMakerRequests(); string KnowledgeBaseId = KeysAndRessourceStrings.KnowledgeBaseIdQuestions; string SubscriptionKey = KeysAndRessourceStrings.SubscriptionKeyQnAMaker; QnAMakerResult QnAMakerResultObject = await QnAMakerAPI.GetQnAMakerResponse(activity.Text, KnowledgeBaseId, SubscriptionKey); JObject LuisResult = await MakeLuisCall(context, activity.Text, LuisAPI); if (await LuisQnADecision(QnAMakerResultObject, LuisResult)) { await LuisCallProcess(context, result, LuisResult); } else { await QnACallProcess(context, result, activity.Text, QnAMakerResultObject); } }
public override async Task DefaultMatchHandler(IDialogContext context, string originalQueryText, QnAMakerResult result) { if (result.Answer.StartsWith("http")) { var activity = context.Activity as Activity; if (activity == null) { return; } var reply = activity.CreateReply(""); reply.Attachments = new List <Attachment> { new Attachment { ContentUrl = result.Answer, ContentType = "image/png", Name = "Bender_Rodriguez.png" } }; await new ConnectorClient(new Uri(activity.ServiceUrl)).Conversations.ReplyToActivityAsync(reply); } else { await base.DefaultMatchHandler(context, originalQueryText, result); } }
public async Task LowScoreHandler(IDialogContext context, string originalQueryText, QnAMakerResult result) { var messageActivity = ProcessResultAndCreateMessageActivity(context, ref result); messageActivity.From.Name = Resources.ChatBot.BotName; messageActivity.Attachments = new List <Attachment>(); AdaptiveCard card = new AdaptiveCard(); // Add text to the card. card.Body.Add(new TextBlock() { Text = "I found an answer that might help...", Size = TextSize.Large, Weight = TextWeight.Normal, Wrap = true }); card.Body.Add(new TextBlock() { Text = result.Answer, Wrap = true }); card.Body.Add(new TextBlock() { Text = "If you are looking for something else, you can always navigate to the following link:", Size = TextSize.Large, Weight = TextWeight.Normal, Wrap = true }); // Add buttons to the card. card.Actions.Add(new OpenUrlAction() { Url = "http://tst2.purinamills.com/", Title = "Purina FAQ", }); Attachment attachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = card }; messageActivity.Attachments.Add(attachment); await context.PostAsync(messageActivity); context.Wait(MessageReceived); }
public override async Task DefaultMatchHandler(IDialogContext context, string originalQueryText, QnAMakerResult result) { if (result.Answers.FirstOrDefault().Score > 80) { await context.PostAsync($"I found {result.Answers.Length} answer(s) that might help...{result.Answers.First().Answer}."); } else { await context.PostAsync($"Sorry, I couldn't find an answer for '{originalQueryText}'."); } context.Done(true); }
/// <summary> /// This is the default handler used if no specific applicable score handlers are found /// </summary> public override async Task DefaultMatchHandler(IDialogContext context, string originalQueryText, QnAMakerResult result) { // ProcessResultAndCreateMessageActivity will remove any attachment markup from the results answer // and add any attachments to a new message activity with the message activity text set by default // to the answer property from the result var messageActivity = ProcessResultAndCreateMessageActivity(context, ref result); messageActivity.Text = $"I found an answer that might help...{result.Answer}."; //User = new Guest(); User.Context = context; User.Message = originalQueryText; Bot = new QnABot(context); await Bot.AnswerAsync(User); //await ProcessResult(context, result.Answer); context.Wait(MessageReceived); }
public override async Task DefaultMatchHandler(IDialogContext context, string originalQueryText, QnAMakerResult result) { var messageActivity = ProcessResultAndCreateMessageActivity(context, ref result); messageActivity.From.Name = Resources.ChatBot.BotName; messageActivity.Attachments = new List <Attachment>(); AdaptiveCard card = new AdaptiveCard(); card.Body.Add(new TextBlock() { Text = result.Answer, Wrap = true }); card.Body.Add(new TextBlock() { Text = "You can always find more information at below link...", Size = TextSize.Medium, Weight = TextWeight.Normal, Wrap = true }); // Add buttons to the card. card.Actions.Add(new OpenUrlAction() { Url = "http://tst2.purinamills.com/animal-nutrition-information", Title = "Purina FAQ", }); Attachment attachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = card }; messageActivity.Attachments.Add(attachment); await context.PostAsync(messageActivity); context.Wait(MessageReceived); }
public override async Task DefaultMatchHandler(IDialogContext context, string originalQueryText, QnAMakerResult result) { await context.PostAsync(result.Answer); context.Done(true); }
/// <summary> /// The DefaultMatchHandler is called whenver any match is found in QnAMaker, no matter how high the score /// </summary> /// <param name="context">The current chat context</param> /// <param name="originalQueryText">The text the user sent to the bot</param> /// <param name="result">The result returned from the QnAMaker service</param> /// <returns></returns> public override Task DefaultMatchHandler(IDialogContext context, string originalQueryText, QnAMakerResult result) { var message = context.MakeMessage(); // create a new message to retun message.Summary = NOT_FOUND; // init as NOT_FOUND message.Text = originalQueryText; // keep the original user's text in the text in case the calling dialog wants to use it float bestMatch = result.Answers.Max(a => a.Score); // find the best score of the matches if (bestMatch >= _tolerance) // if the best matching score is greater than our tolerance, use it { message.Summary = ""; // send back the answer from QnA as the messages text message.Text = result.Answers.Where(a => a.Score == bestMatch).FirstOrDefault().Answer; } // finish the dialog and return the message to the calling dialog context.Done(message); return(Task.CompletedTask); }
public async Task LowScoreHandler(IDialogContext context, string originalQueryText, QnAMakerResult result) { await context.PostAsync($"I found an answer that might help...{result.Answer}."); context.Wait(MessageReceived); }
public async Task PrettyHighScoreHandler(IDialogContext context, string originalQueryText, QnAMakerResult result) { _foundResult = result.Answer; if (_interactivMode) { await context.PostAsync($"This seems to be what you are after: {result.Answer}."); } }