Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private async Task HandleMessage(IDialogContext context, string queryText)
- {
- var response = await GetQnAMakerResponse(queryText, knowledgeBaseId, subscriptionKey);
- if (HandlerByMaximumScore == null)
- {
- HandlerByMaximumScore =
- new Dictionary<QnAMakerResponseHandlerAttribute, QnAMakerResponseHandler>(GetHandlersByMaximumScore());
- }
- if (response.Score == 0)
- {
- await NoMatchHandler(context, queryText);
- }
- else
- {
- var applicableHandlers = HandlerByMaximumScore.OrderBy(h => h.Key.MaximumScore).Where(h => h.Key.MaximumScore > response.Score);
- var handler = applicableHandlers.Any() ? applicableHandlers.First().Value : null;
- if (handler != null)
- {
- await handler.Invoke(context, queryText, response);
- }
- else
- {
- await DefaultMatchHandler(context, queryText, response);
- }
- }
- }
- private async Task<QnAMakerResult> GetQnAMakerResponse(string query, string knowledgeBaseId, string subscriptionKey)
- {
- string responseString = string.Empty;
- var knowledgebaseId = knowledgeBaseId; // Use knowledge base id created.
- var qnamakerSubscriptionKey = subscriptionKey; //Use subscription key assigned to you.
- //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\": \"{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", qnamakerSubscriptionKey);
- client.Headers.Add("Content-Type", "application/json");
- responseString = client.UploadString(builder.Uri, postBody);
- }
- //De-serialize the response
- QnAMakerResult response;
- try
- {
- response = JsonConvert.DeserializeObject<QnAMakerResult>(responseString);
- return response;
- }
- catch
- {
- throw new Exception("Unable to deserialize QnA Maker response string.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement