Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2017
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. private async Task HandleMessage(IDialogContext context, string queryText)
  2. {
  3. var response = await GetQnAMakerResponse(queryText, knowledgeBaseId, subscriptionKey);
  4.  
  5. if (HandlerByMaximumScore == null)
  6. {
  7. HandlerByMaximumScore =
  8. new Dictionary<QnAMakerResponseHandlerAttribute, QnAMakerResponseHandler>(GetHandlersByMaximumScore());
  9. }
  10.  
  11. if (response.Score == 0)
  12. {
  13. await NoMatchHandler(context, queryText);
  14. }
  15. else
  16. {
  17. var applicableHandlers = HandlerByMaximumScore.OrderBy(h => h.Key.MaximumScore).Where(h => h.Key.MaximumScore > response.Score);
  18. var handler = applicableHandlers.Any() ? applicableHandlers.First().Value : null;
  19.  
  20. if (handler != null)
  21. {
  22. await handler.Invoke(context, queryText, response);
  23. }
  24. else
  25. {
  26. await DefaultMatchHandler(context, queryText, response);
  27. }
  28. }
  29. }
  30.  
  31. private async Task<QnAMakerResult> GetQnAMakerResponse(string query, string knowledgeBaseId, string subscriptionKey)
  32. {
  33. string responseString = string.Empty;
  34.  
  35. var knowledgebaseId = knowledgeBaseId; // Use knowledge base id created.
  36. var qnamakerSubscriptionKey = subscriptionKey; //Use subscription key assigned to you.
  37.  
  38. //Build the URI
  39. Uri qnamakerUriBase = new Uri("https://westus.api.cognitive.microsoft.com/qnamaker/v1.0");
  40. var builder = new UriBuilder($"{qnamakerUriBase}/knowledgebases/{knowledgebaseId}/generateAnswer");
  41.  
  42. //Add the question as part of the body
  43. var postBody = $"{{\"question\": \"{query}\"}}";
  44.  
  45. //Send the POST request
  46. using (WebClient client = new WebClient())
  47. {
  48. //Set the encoding to UTF8
  49. client.Encoding = System.Text.Encoding.UTF8;
  50.  
  51. //Add the subscription key header
  52. client.Headers.Add("Ocp-Apim-Subscription-Key", qnamakerSubscriptionKey);
  53. client.Headers.Add("Content-Type", "application/json");
  54. responseString = client.UploadString(builder.Uri, postBody);
  55. }
  56.  
  57. //De-serialize the response
  58. QnAMakerResult response;
  59. try
  60. {
  61. response = JsonConvert.DeserializeObject<QnAMakerResult>(responseString);
  62. return response;
  63. }
  64. catch
  65. {
  66. throw new Exception("Unable to deserialize QnA Maker response string.");
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement