Example #1
0
 public async Task CallTrainAsync(FeedbackRecords feedbackRecords)
 {
     if (_activeQnAMaker != null)
     {
         await _activeQnAMaker.CallTrainAsync(feedbackRecords);
     }
 }
Example #2
0
        /// <summary>
        /// Train knowledge base.
        /// </summary>
        /// <returns>If Error return null</returns>
        public async Task <Result> TrainKnowledgeBase(FeedbackRecords feedbackRecords)
        {
            if (string.IsNullOrWhiteSpace(SubscriptionKey))
            {
                return(ResultHelper.GetGenericError("SubscriptionKey is empty"));
            }

            if (string.IsNullOrWhiteSpace(KnowledgeId))
            {
                return(ResultHelper.GetGenericError("KnowledgeId is empty"));
            }

            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", SubscriptionKey);

            var uri = EndPoint + KnowledgeId + "/train";

            using (var request = new HttpRequestMessage(new HttpMethod("PATCH"), uri))
            {
                request.Content = new StringContent(JsonConvert.SerializeObject(feedbackRecords),
                                                    Encoding.UTF8, "application/json");

                var response = await client.SendAsync(request);

                if (response.IsSuccessStatusCode)
                {
                    return(ResultHelper.GetSucess("Train completed successfully"));
                }

                var jsonResponse = await response.Content.ReadAsStringAsync();

                return(ResultHelper.GetError(JsonConvert.DeserializeObject <Result>(jsonResponse)));
            }
        }
        private async Task <DialogTurnResult> CallTrain(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var trainResponses = stepContext.Values[QnAData] as List <QueryResult>;
            var currentQuery   = stepContext.Values[CurrentQuery] as string;

            var reply = stepContext.Context.Activity.Text;

            var dialogOptions            = GetDialogOptionsValue(stepContext);
            var qnaDialogResponseOptions = dialogOptions[QnADialogResponseOptions] as QnADialogResponseOptions;

            if (trainResponses.Count > 1)
            {
                var qnaResult = trainResponses.FirstOrDefault(kvp => kvp.Questions[0] == reply);

                if (qnaResult != null)
                {
                    stepContext.Values[QnAData] = new List <QueryResult>()
                    {
                        qnaResult
                    };

                    var records = new FeedbackRecord[]
                    {
                        new FeedbackRecord
                        {
                            UserId       = stepContext.Context.Activity.Id,
                            UserQuestion = currentQuery,
                            QnaId        = qnaResult.Id,
                        }
                    };

                    var feedbackRecords = new FeedbackRecords {
                        Records = records
                    };

                    // Call Active Learning Train API
                    await _services.QnAMakerService.CallTrainAsync(feedbackRecords).ConfigureAwait(false);

                    return(await stepContext.NextAsync(new List <QueryResult>() { qnaResult }, cancellationToken).ConfigureAwait(false));
                }
                else if (reply.Equals(qnaDialogResponseOptions.CardNoMatchText, StringComparison.OrdinalIgnoreCase))
                {
                    await stepContext.Context.SendActivityAsync(qnaDialogResponseOptions.CardNoMatchResponse, cancellationToken : cancellationToken).ConfigureAwait(false);

                    return(await stepContext.EndDialogAsync().ConfigureAwait(false));
                }
                else
                {
                    return(await stepContext.ReplaceDialogAsync(QnAMakerDialogName, stepContext.ActiveDialog.State["options"], cancellationToken).ConfigureAwait(false));
                }
            }

            return(await stepContext.NextAsync(stepContext.Result, cancellationToken).ConfigureAwait(false));
        }
Example #4
0
        private async Task UpdateActiveLearningFeedbackRecordsAsync(FeedbackRecords feedbackRecords)
        {
            var requestUrl = $"{_endpoint.Host}/language/query-knowledgebases/projects/{_endpoint.KnowledgeBaseId}/feedback?{ApiVersionQueryParam}";

            var feedbackRecordsRequest = new FeedbackRecordsRequest();

            feedbackRecordsRequest.Records.AddRange(feedbackRecords.Records.ToList());

            var jsonRequest = JsonConvert.SerializeObject(feedbackRecordsRequest);

            var httpRequestHelper = new HttpRequestUtils(_httpClient);
            await httpRequestHelper.ExecuteHttpRequestAsync(requestUrl, jsonRequest, _endpoint).ConfigureAwait(false);
        }
Example #5
0
        private async Task <DialogTurnResult> CallTrain(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var trainResponses = stepContext.Values[QnAData] as List <QueryResult>;
            var currentQuery   = stepContext.Values[CurrentQuery] as string;

            var reply = stepContext.Context.Activity.Text;

            if (trainResponses.Count() > 1)
            {
                var qnaResult = trainResponses.Where(kvp => kvp.Questions[0] == reply).FirstOrDefault();

                if (qnaResult != null)
                {
                    stepContext.Values[QnAData] = new List <QueryResult>()
                    {
                        qnaResult
                    };

                    var records = new FeedbackRecord[]
                    {
                        new FeedbackRecord
                        {
                            UserId       = stepContext.Context.Activity.Id,
                            UserQuestion = currentQuery,
                            QnaId        = qnaResult.Id,
                        }
                    };

                    var feedbackRecords = new FeedbackRecords {
                        Records = records
                    };

                    // Call Active Learning Train API
                    await _services.QnAMakerService.CallTrainAsync(feedbackRecords);

                    return(await stepContext.NextAsync(new List <QueryResult>(){ qnaResult }, cancellationToken));
                }
                else if (reply.Equals(cardNoMatchText))
                {
                    await stepContext.Context.SendActivityAsync(cardNoMatchResponse, cancellationToken : cancellationToken);

                    return(await stepContext.EndDialogAsync());
                }
                else
                {
                    return(await stepContext.ReplaceDialogAsync(ActiveLearningDialogName, stepContext.ActiveDialog.State["options"], cancellationToken));
                }
            }

            return(await stepContext.NextAsync(stepContext.Result, cancellationToken));
        }
Example #6
0
        /// <summary>
        /// Call to Update Active Learning Feedback.
        /// </summary>
        /// <param name="feedbackRecords">An object containing an array of <see cref="FeedbackRecord"/>.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task UpdateActiveLearningFeedbackAsync(FeedbackRecords feedbackRecords)
        {
            if (feedbackRecords == null)
            {
                throw new ArgumentNullException(nameof(feedbackRecords), "Feedback records cannot be null.");
            }

            if (feedbackRecords.Records == null || feedbackRecords.Records.Length == 0)
            {
                return;
            }

            // Call update active learning feedback
            await UpdateActiveLearningFeedbackRecordsAsync(feedbackRecords).ConfigureAwait(false);
        }
        /// <summary>
        /// Method to call REST-based QnAMaker Train API for Active Learning
        /// </summary>
        /// <param name="endpoint">Endpoint URI of the runtime</param>
        /// <param name="FeedbackRecords">Feedback records train API</param>
        /// <param name="kbId">Knowledgebase Id</param>
        /// <param name="key">Endpoint key</param>
        /// <param name="cancellationToken"> Cancellation token</param>
        public async static void CallTrain(string endpoint, FeedbackRecords feedbackRecords, string kbId, string key, CancellationToken cancellationToken)
        {
            var uri = endpoint + "/knowledgebases/" + kbId + "/train/";

            using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage())
                {
                    request.Method     = HttpMethod.Post;
                    request.RequestUri = new Uri(uri);
                    request.Content    = new StringContent(JsonConvert.SerializeObject(feedbackRecords), Encoding.UTF8, "application/json");
                    request.Headers.Add("Authorization", "EndpointKey " + key);

                    var response = await client.SendAsync(request, cancellationToken);

                    await response.Content.ReadAsStringAsync();
                }
            }
        }
        private async Task <DialogTurnResult> CallTrainAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var dialogOptions  = ObjectPath.GetPathValue <QnAMakerDialogOptions>(stepContext.ActiveDialog.State, Options);
            var trainResponses = stepContext.Values[ValueProperty.QnAData] as List <QueryResult>;
            var currentQuery   = stepContext.Values[ValueProperty.CurrentQuery] as string;

            var reply = stepContext.Context.Activity.Text;

            if (trainResponses.Count > 1)
            {
                var qnaResult = trainResponses.FirstOrDefault(kvp => kvp.Questions[0] == reply);

                if (qnaResult != null)
                {
                    stepContext.Values[ValueProperty.QnAData] = new List <QueryResult>()
                    {
                        qnaResult
                    };

                    var records = new FeedbackRecord[]
                    {
                        new FeedbackRecord
                        {
                            UserId       = stepContext.Context.Activity.Id,
                            UserQuestion = currentQuery,
                            QnaId        = qnaResult.Id,
                        }
                    };

                    var feedbackRecords = new FeedbackRecords {
                        Records = records
                    };

                    // Call Active Learning Train API
                    var qnaClient = await GetQnAMakerClientAsync(stepContext).ConfigureAwait(false);

                    await qnaClient.CallTrainAsync(feedbackRecords).ConfigureAwait(false);

                    return(await stepContext.NextAsync(new List <QueryResult>() { qnaResult }, cancellationToken).ConfigureAwait(false));
                }
                else if (reply.Equals(dialogOptions.ResponseOptions.CardNoMatchText, StringComparison.OrdinalIgnoreCase))
                {
                    var activity = dialogOptions.ResponseOptions.CardNoMatchResponse;
                    if (activity == null)
                    {
                        await stepContext.Context.SendActivityAsync(DefaultCardNoMatchResponse, cancellationToken : cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        await stepContext.Context.SendActivityAsync(activity, cancellationToken : cancellationToken).ConfigureAwait(false);
                    }

                    return(await stepContext.EndDialogAsync().ConfigureAwait(false));
                }
                else
                {
                    // restart the waterfall to step 0
                    return(await RunStepAsync(stepContext, index : 0, reason : DialogReason.BeginCalled, result : null, cancellationToken : cancellationToken).ConfigureAwait(false));
                }
            }

            return(await stepContext.NextAsync(stepContext.Result, cancellationToken).ConfigureAwait(false));
        }
Example #9
0
 public async Task TrainQnAServiceAsync(FeedbackRecords feedbackRecords)
 {
     QnAMaker trainer = new QnAMaker(_endpoint);
     await trainer.CallTrainAsync(feedbackRecords);
 }