private async void MandarMensaje_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            mensajes.Add(new Mensaje(false, ChatTextBox.Text));
            Mensaje mensajeBot = new Mensaje(true, "Pensando...");

            mensajes.Add(mensajeBot);

            string respuesta = "";

            try
            {
                var cliente = new QnAMakerRuntimeClient(new EndpointKeyServiceClientCredentials(Properties.Settings.Default.EndPointKey))
                {
                    RuntimeEndpoint = Properties.Settings.Default.EndPoint
                };
                QnASearchResultList response = await cliente.Runtime.GenerateAnswerAsync(Properties.Settings.Default.KnowledgeBaseId, new QueryDTO { Question = ChatTextBox.Text });

                respuesta = response.Answers[0].Answer;
            }
            catch (IOException)
            {
                respuesta = "Estoy muy cansado para hablar";
            }

            mensajeBot.Texto = respuesta;
            ChatTextBox.Text = "";
            ChatScrollViewer.ScrollToVerticalOffset(ChatScrollViewer.ExtentHeight);
        }
        /// <summary>
        /// Get the reply to a question asked by end user.
        /// </summary>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="message">Text message.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        public async Task GetReplyToQnAAsync(
            ITurnContext<IMessageActivity> turnContext,
            IMessageActivity message)
        {
            string text = message.Text?.ToLower()?.Trim() ?? string.Empty;

            try
            {
                var queryResult = new QnASearchResultList();

                ResponseCardPayload payload = new ResponseCardPayload();

                if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null))
                {
                    payload = ((JObject)message.Value).ToObject<ResponseCardPayload>();
                }

                queryResult = await this.qnaServiceProvider.GenerateAnswerAsync(question: text, isTestKnowledgeBase: false, payload.PreviousQuestions?.Last().Id.ToString(), payload.PreviousQuestions?.Last().Questions.First()).ConfigureAwait(false);
                bool answerFound = false;

                foreach (QnASearchResult answerData in queryResult.Answers)
                {
                    bool isContextOnly = answerData.Context?.IsContextOnly ?? false;
                    if (answerData.Id != -1 &&
                        ((!isContextOnly && payload.PreviousQuestions == null) ||
                            (isContextOnly && payload.PreviousQuestions != null)))
                    {
                        // This is the expected answer
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(answerData, text, this.appBaseUri, payload))).ConfigureAwait(false);
                        answerFound = true;
                        break;
                    }
                }

                if (!answerFound)
                {
                    await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                // Check if knowledge base is empty and has not published yet when end user is asking a question to bot.
                if (((ErrorResponseException)ex).Response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                {
                    var knowledgeBaseId = await this.configurationProvider.GetSavedEntityDetailAsync(Constants.KnowledgeBaseEntityId).ConfigureAwait(false);
                    var hasPublished = await this.qnaServiceProvider.GetInitialPublishedStatusAsync(knowledgeBaseId).ConfigureAwait(false);

                    // Check if knowledge base has not published yet.
                    if (!hasPublished)
                    {
                        this.logger.LogError(ex, "Error while fetching the qna pair: knowledge base may be empty or it has not published yet.");
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false);
                        return;
                    }
                }

                // Throw the error at calling place, if there is any generic exception which is not caught.
                throw;
            }
        }
示例#3
0
        private async void CommandBinding_Executed_CheckConnection(object sender, ExecutedRoutedEventArgs e)
        {
            string EndPoint = Properties.Settings.Default.EndPoint;
            string Key      = Properties.Settings.Default.Key;
            string Id       = Properties.Settings.Default.Id;

            QnAMakerRuntimeClient client = new QnAMakerRuntimeClient(new EndpointKeyServiceClientCredentials(Key))
            {
                RuntimeEndpoint = EndPoint
            };

            try
            {
                string pregunta = "hola";
                QnASearchResultList response = await client.Runtime.GenerateAnswerAsync(Id, new QueryDTO { Question = pregunta });

                string respuesta = response.Answers[0].Answer;

                MessageBox.Show("Conexion realizada con exito", "Comprobar conexion", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception)
            {
                MessageBox.Show("No se ha podido completar la conexion...", "Comprobar conexion", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
示例#4
0
        private async void ComprobarConexion_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                string EndPoint               = Properties.Settings.Default.EndPoint;
                string EndPointKey            = Properties.Settings.Default.EndPointKey;
                string KnowledgeBaseId        = Properties.Settings.Default.KnowledgeBaseId;
                QnAMakerRuntimeClient cliente = new QnAMakerRuntimeClient(new EndpointKeyServiceClientCredentials(EndPointKey))
                {
                    RuntimeEndpoint = EndPoint
                };

                //Realizamos la pregunta a la API
                QnASearchResultList response = await(cliente.Runtime.GenerateAnswerAsync(KnowledgeBaseId, new QueryDTO {
                    Question = "Hola"
                }));
                _ = response.Answers[0].Answer;

                string           messageBoxText = "Conexión correcta con el servidor del Bot";
                string           caption        = "Comprobar conexión";
                MessageBoxButton button         = MessageBoxButton.OK;
                MessageBoxImage  icon           = MessageBoxImage.Information;
                MessageBox.Show(messageBoxText, caption, button, icon);
            }
            catch (Exception)
            {
                string           caption = "Error Bot";
                MessageBoxButton button  = MessageBoxButton.OK;
                MessageBoxImage  icon    = MessageBoxImage.Error;
                MessageBox.Show("No se ha podido establecer la conexión con el servidor del bot", caption, button, icon);
            }
        }
示例#5
0
        private async Task ObtenRespuestaBotAsync(string pregunta, int indice)
        {
            try
            {
                string EndPoint               = Properties.Settings.Default.EndPoint;
                string EndPointKey            = Properties.Settings.Default.EndPointKey;
                string KnowledgeBaseId        = Properties.Settings.Default.KnowledgeBaseId;
                QnAMakerRuntimeClient cliente = new QnAMakerRuntimeClient(new EndpointKeyServiceClientCredentials(EndPointKey))
                {
                    RuntimeEndpoint = EndPoint
                };

                //Realizamos la pregunta a la API
                QnASearchResultList response = await(cliente.Runtime.GenerateAnswerAsync(KnowledgeBaseId, new QueryDTO {
                    Question = pregunta
                }));
                string respuesta = response.Answers[0].Answer;
                mensajes[indice].Mensaje = respuesta;
            }
            catch (Exception ex)
            {
                string           messageBoxText = ex.Message;
                string           caption        = "Error Bot";
                MessageBoxButton button         = MessageBoxButton.OK;
                MessageBoxImage  icon           = MessageBoxImage.Error;
                MessageBox.Show(messageBoxText, caption, button, icon);
                mensajes[indice].Mensaje = "No he podifo obtener una respuesta.";
            }
        }
示例#6
0
        public async Task <string> MensajeRobot(string pregunta)
        {
            //Para usar la API QnA añadir el paquete NuGet
            //Microsoft.Azure.CognitiveServices.Knowledge.QnAMaker

            //Creamos el cliente de QnA
            string EndPoint        = Properties.Settings.Default.EndPoint;
            string EndPointKey     = Properties.Settings.Default.EndPointKey;
            string KnowledgeBaseId = Properties.Settings.Default.KnowledgeBaseId;
            var    cliente         = new QnAMakerRuntimeClient(new EndpointKeyServiceClientCredentials(EndPointKey))
            {
                RuntimeEndpoint = EndPoint
            };

            hayConexion = true;
            //Realizamos la pregunta a la API
            try
            {
                QnASearchResultList response = await cliente.Runtime.GenerateAnswerAsync(KnowledgeBaseId, new QueryDTO { Question = pregunta });

                return(response.Answers[0].Answer);
            }
            catch (Exception)
            {
                hayConexion = false;
                return(null);
            }
        }
        /// <summary>
        /// Get answer from knowledgebase for a given question.
        /// </summary>
        /// <param name="question">Question text.</param>
        /// <param name="isTestKnowledgeBase">Prod or test.</param>
        /// <param name="previousQnAId">Id of previous question.</param>
        /// <param name="previousUserQuery">Previous question information.</param>
        /// <returns>QnaSearchResultList result as response.</returns>
        public async Task<QnASearchResultList> GenerateAnswerAsync(string question, bool isTestKnowledgeBase, string previousQnAId = null, string previousUserQuery = null, IList<QueryTag> tags = null)
        {
            var knowledgeBaseId = await this.configurationProvider.GetSavedEntityDetailAsync(ConfigurationEntityTypes.KnowledgeBaseId).ConfigureAwait(false);

            QueryDTO queryDTO = new QueryDTO()
            {
                IsTest = isTestKnowledgeBase,
                Question = question?.Trim(),
                ScoreThreshold = Convert.ToDouble(this.options.ScoreThreshold, CultureInfo.InvariantCulture),
            };

            // if metadata tags are provided, add those to the query
            if (tags != null)
            {
                queryDTO.StrictFilters = tags.Select(x => new MetadataDTO(x.Name, x.Value)).ToList();
                queryDTO.StrictFiltersCompoundOperationType = StrictFiltersCompoundOperationType.AND;
            }

            if (previousQnAId != null && previousUserQuery != null)
            {
                queryDTO.Context = new QueryDTOContext
                {
                    PreviousQnaId = Convert.ToInt32(previousQnAId),
                    PreviousUserQuery = previousUserQuery,
                };
            }

            QnASearchResultList qnASearchResultList = await this.qnaMakerClient.Knowledgebase.GenerateAnswerAsync(knowledgeBaseId, queryDTO).ConfigureAwait(false);
            return qnASearchResultList;
        }
        private async Task CognitiveServices_QnA_MigrationGuide_Runtime()
        {
            #region Snippet:CognitiveServices_QnA_Maker_Snippets_MigrationGuide_CreateRuntimeClient
            EndpointKeyServiceClientCredentials credential = new EndpointKeyServiceClientCredentials("{ApiKey}");

            QnAMakerRuntimeClient client = new QnAMakerRuntimeClient(credential)
            {
                RuntimeEndpoint = "{QnaMakerEndpoint}"
            };
            #endregion Snippet:CognitiveServices_QnA_Maker_Snippets_MigrationGuide_CreateRuntimeClient

            #region Snippet:CognitiveServices_QnA_Maker_Snippets_MigrationGuide_QueryKnowledgeBase
            QueryDTO queryDTO = new QueryDTO();
            queryDTO.Question = "{Question}";

            QnASearchResultList response = await client.Runtime.GenerateAnswerAsync("{knowledgebase-id}", queryDTO);

            #endregion Snippet:CognitiveServices_QnA_Maker_Snippets_MigrationGuide_QueryKnowledgeBase

            #region Snippet:CognitiveServices_QnA_Maker_Snippets_MigrationGuide_Chat
            QueryDTO queryDTOFollowUp = new QueryDTO();
            queryDTOFollowUp.Context = new QueryDTOContext(previousQnaId: 1);

            QnASearchResultList responseFollowUp = await client.Runtime.GenerateAnswerAsync("{knowledgebase-id}", queryDTO);

            #endregion Snippet:CognitiveServices_QnA_Maker_Snippets_MigrationGuide_Chat
        }
示例#9
0
        public async Task MakeQuestion(string question, ObservableCollection <Message> messages)
        {
            IsNotProcessing = false;
            QnASearchResultList response = await cliente.Runtime.GenerateAnswerAsync(Properties.Settings.Default.AzureBotId, new QueryDTO { Question = question });

            string responseString = response.Answers[0].Answer;

            messages.Add(new Message(Message.SenderType.Bot, responseString == DEFAULT_NOT_FOUND_ANSWER ? DEFAULT_NOT_FOUND_ANSWER_TO_CLIENT : responseString));
        }
示例#10
0
        public async Task SendQuestion(string question, ObservableCollection <Message> messages)
        {
            string id = "68c6efd8-5210-45dd-b60c-722c64c4f9fc";
            QnASearchResultList response = await server.Runtime.GenerateAnswerAsync(id, new QueryDTO { Question = question });

            string responseString = response.Answers[0].Answer;

            messages.Add(new Message(Message.SenderMessage.Bot, response.Answers[0].Answer));
        }
        /// <summary>
        /// Get answer from knowledgebase for a given question.
        /// </summary>
        /// <param name="question">Question text.</param>
        /// <param name="isTestKnowledgeBase">Prod or test.</param>
        /// <returns>QnaSearchResult result as response.</returns>
        public async Task <QnASearchResultList> GenerateAnswerAsync(string question, bool isTestKnowledgeBase)
        {
            var knowledgeBaseId = await this.configurationProvider.GetSavedEntityDetailAsync(ConfigurationEntityTypes.KnowledgeBaseId).ConfigureAwait(false);

            QnASearchResultList qnaSearchResult = await this.qnaMakerRuntimeClient.Runtime.GenerateAnswerAsync(knowledgeBaseId, new QueryDTO()
            {
                IsTest         = isTestKnowledgeBase,
                Question       = question?.Trim(),
                ScoreThreshold = Convert.ToDouble(this.options.ScoreThreshold, CultureInfo.InvariantCulture),
            }).ConfigureAwait(false);

            return(qnaSearchResult);
        }
示例#12
0
        public async Task <bool> ComprobarConexion()
        {
            string id = "68c6efd8-5210-45dd-b60c-722c64c4f9fc";

            try
            {
                QnASearchResultList response = await server.Runtime.GenerateAnswerAsync(id, new QueryDTO { Question = "Comprobación" });
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
示例#13
0
        //Conexión ------------------------------------------------------------------------------------------------------------------------------------------

        private async void Conexion()
        {
            string EndPoint = "https://botsergio.azurewebsites.net";
            string Key      = "164b4f7b-d067-439f-9ef9-20d58c3d5ec8";
            string Id       = "69e93d1d-6ccd-493d-8314-19e007646cf2";
            var    cliente  = new QnAMakerRuntimeClient(new EndpointKeyServiceClientCredentials(Key))
            {
                RuntimeEndpoint = EndPoint
            };

            //Realizamos la pregunta a la API
            string pregunta = "Your question";
            QnASearchResultList response = await cliente.Runtime.GenerateAnswerAsync(Id, new QueryDTO { Question = pregunta });

            string respuesta = response.Answers[0].Answer;
        }
示例#14
0
        private async void Send_MessageAsync(object sender, RoutedEventArgs e)
        {
            string pregunta = MessageTextBox.Text;

            Mensaje mensajeEnviado = new Mensaje(pregunta, false);

            listaMensajes.Add(mensajeEnviado);

            QnASearchResultList response = await cliente.Runtime.GenerateAnswerAsync(Id, new QueryDTO { Question = pregunta });

            string respuesta = response.Answers[0].Answer;

            Mensaje mensajeBot = new Mensaje(respuesta, true);

            listaMensajes.Add(mensajeBot);
        }
示例#15
0
        /// <summary>
        /// Get answer from knowledge base for a given question.
        /// </summary>
        /// <param name="question">Question text.</param>
        /// <returns>QnA search result as response.</returns>
        public async Task <QnASearchResultList> GenerateAnswerAsync(string question)
        {
            var knowledgeBaseEntity = await this.appConfigRepository.GetAsync(AppConfigTableName.SettingsPartition, AppConfigTableName.KnowledgeBaseIdRowKey);

            if (knowledgeBaseEntity == null)
            {
                return(null);
            }

            QnASearchResultList qnaSearchResult = await this.qnaMakerRuntimeClient.Runtime.GenerateAnswerAsync(knowledgeBaseEntity.Value, new QueryDTO()
            {
                Question       = question.Trim(),
                ScoreThreshold = Convert.ToDouble(this.options.ScoreThreshold),
            });

            return(qnaSearchResult);
        }
示例#16
0
        public void GetHelpResults_Execute()
        {
            if (string.IsNullOrEmpty(QuestionText))
            {
                return;
            }

            //Call service to get results
            Cursor oldCursor = Mouse.OverrideCursor;

            try
            {
                SearchResults.Clear();

                Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;

                IQnAGateway qnag = new QnAGateway(_config);


                Task <QnASearchResultList> searchTask = Task.Run(() => qnag.AnswerQuestion(QuestionText, "user1", 5));
                QnASearchResultList        results    = searchTask.Result;

                var answerResults = new List <HelpResultItem>();
                foreach (var answer in results.Answers)
                {
                    var theResult = new HelpResultItem()
                    {
                        MatchedText       = answer.Answer,
                        RelevancyScore    = answer.Score.GetValueOrDefault(),
                        SourceDocumentURL = answer.Source,
                    };
                    answerResults.Add(theResult);
                }

                SearchResults = new ObservableCollection <HelpResultItem>(answerResults);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
            finally
            {
                Mouse.OverrideCursor = oldCursor;
            }
        }
        /// <summary>
        /// get answer from kb for a given question.
        /// </summary>
        /// <param name="isTest">prod or test.</param>
        /// <param name="question">question text.</param>
        /// <param name="teamId">team id.</param>
        /// <returns>qnaSearchResult response.</returns>
        public async Task <QnASearchResultList> GenerateAnswerAsync(bool isTest, string question, string teamId)
        {
            var kb = await this.configurationStorageProvider.GetKbConfigAsync();

            QnASearchResultList qnaSearchResult = await this.qnaMakerRuntimeClient.Runtime.GenerateAnswerAsync(kb?.KbId, new QueryDTO()
            {
                IsTest         = isTest,
                Question       = question,
                ScoreThreshold = this.scoreThreshold,
                StrictFilters  = new List <MetadataDTO> {
                    new MetadataDTO()
                    {
                        Name = Constants.MetadataTeamId, Value = HttpUtility.UrlEncode(teamId)
                    }
                },
            });

            return(qnaSearchResult);
        }
示例#18
0
        private async void CommandBinding_Executed_SendMessage(object sender, ExecutedRoutedEventArgs e)
        {
            Mensaje m = new Mensaje("Persona", MensajeTextBox.Text);

            mensajes.Add(m);
            MensajeTextBox.Text = "";

            string EndPoint = Properties.Settings.Default.EndPoint;
            string Key      = Properties.Settings.Default.Key;
            string Id       = Properties.Settings.Default.Id;

            QnAMakerRuntimeClient cliente = new QnAMakerRuntimeClient(new EndpointKeyServiceClientCredentials(Key))
            {
                RuntimeEndpoint = EndPoint
            };

            Mensaje mensajeRobot = new Mensaje("Robot", "Pensando...");

            mensajes.Add(mensajeRobot);
            disponible = false;
            string respuesta = "";

            try
            {
                string pregunta = m.Contenido;
                QnASearchResultList response = await cliente.Runtime.GenerateAnswerAsync(Id, new QueryDTO { Question = pregunta });

                respuesta = response.Answers[0].Answer;
            }
            catch (Exception)
            {
                respuesta = "Estoy ocupado ahora mismo";
            }

            mensajes.Remove(mensajeRobot);
            mensajeRobot.Contenido = respuesta;
            mensajes.Add(mensajeRobot);
            disponible = true;
            ScrollViewer.ScrollToEnd();
        }
        /// <summary>
        /// get answer from kb for a given question.
        /// </summary>
        /// <param name="isTest">prod or test.</param>
        /// <param name="question">question text.</param>
        /// <param name="teamId">team id.</param>
        /// <returns>qnaSearchResult response.</returns>
        public async Task <QnASearchResultList> GenerateAnswerAsync(bool isTest, string question, string teamId)
        {
            var kb = await this.GetKbMappingAsync(teamId);

            this.qnaMakerRuntimeClient = new QnAMakerRuntimeClient(new EndpointKeyServiceClientCredentials(kb.EndpointKey))
            {
                RuntimeEndpoint = this.configuration["QnAMakerHostUrl"]
            };

            QnASearchResultList qnaSearchResult = await this.qnaMakerRuntimeClient.Runtime.GenerateAnswerAsync(kb?.KbId, new QueryDTO()
            {
                IsTest         = isTest,
                Question       = question,
                ScoreThreshold = double.Parse(this.configuration["ScoreThreshold"]),
                StrictFilters  = new List <MetadataDTO> {
                    new MetadataDTO()
                    {
                        Name = Constants.MetadataTeamId, Value = HttpUtility.UrlEncode(teamId)
                    }
                },
            });

            return(qnaSearchResult);
        }
        public async System.Threading.Tasks.Task <string> RespuestaRobotAsync(string pregunta)
        {
            string respuesta;

            try
            {
                string EndPoint        = Properties.Settings.Default.EndPoint;
                string EndPointKey     = Properties.Settings.Default.EndPointKey;
                string KnowledgeBaseId = Properties.Settings.Default.KnowledgeBaseId;
                cliente = new QnAMakerRuntimeClient(new EndpointKeyServiceClientCredentials(EndPointKey))
                {
                    RuntimeEndpoint = EndPoint
                };

                QnASearchResultList response = await cliente.Runtime.GenerateAnswerAsync(KnowledgeBaseId, new QueryDTO { Question = pregunta });

                respuesta = response.Answers[0].Answer;
            }
            catch (Exception)
            {
                respuesta = falloRobot;
            }
            return(respuesta);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string        requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            SearchRequest data        = JsonConvert.DeserializeObject <SearchRequest>(requestBody);

            string kbId;
            string qnaRuntimeKey;
            QnASearchResultList qnaResponse = null;

            if (data.getAnswer)
            {
                try
                {
                    kbId = await GetKbId(log);

                    qnaRuntimeKey = await GetRuntimeKey(log);

                    runtimeClient = new QnAMakerRuntimeClient(new EndpointKeyServiceClientCredentials(qnaRuntimeKey))
                    {
                        RuntimeEndpoint = qnaMakerEndpoint
                    };

                    var qnaOptions = new QueryDTO
                    {
                        Question       = data.q,
                        Top            = 1,
                        ScoreThreshold = 30
                    };
                    qnaResponse = await runtimeClient.Runtime.GenerateAnswerAsync(kbId, qnaOptions);
                }
                catch (Exception e)
                {
                    log.LogInformation(e.Message);
                }
            }


            SearchOptions options = new SearchOptions()
            {
                Size = data.top,
                Skip = data.skip,
                IncludeTotalCount = true,
                Filter            = CreateFilterExpression(data.filters)
            };

            options.Facets.Add("keyPhrases");
            options.Facets.Add("fileType");
            options.HighlightFields.Add("content");
            options.Select.Add("metadata_storage_name");
            options.Select.Add("metadata_storage_path");
            options.Select.Add("id");

            var response = await searchClient.SearchAsync <SearchDocument>(RemoveStopwords(data.q), options);

            Dictionary <string, IList <FacetValue> > facets = new Dictionary <string, IList <FacetValue> >();

            foreach (KeyValuePair <string, IList <FacetResult> > facet in response.Value.Facets)
            {
                //KeyValuePair<string, IList<FacetValue>> f = new KeyValuePair<string, IList<FacetValue>>(facet.Key, new List<FacetValue>());

                var values = new List <FacetValue>();
                foreach (FacetResult result in facet.Value)
                {
                    FacetValue value = new FacetValue()
                    {
                        count = result.Count, value = result.Value.ToString()
                    };
                    values.Add(value);
                }

                facets[facet.Key] = values;
            }

            SearchOutput output = new SearchOutput();

            output.count   = response.Value.TotalCount;
            output.results = response.Value.GetResults().ToList();
            output.facets  = facets;

            if (qnaResponse != null)
            {
                output.answers        = new QnAResult();
                output.answers.answer = qnaResponse.Answers.First();
                var source = output.answers.answer.Source;
                output.answers.document = await GetDocument(source, output.results, log);
            }

            return(new OkObjectResult(output));
        }
        /// <summary>
        /// Get the reply to a question asked by end user.
        /// </summary>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="message">Text message.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        private async Task GetQuestionAnswerReplyAsync(
            ITurnContext turnContext,
            IMessageActivity message)
        {
            string text = message.Text?.ToLower()?.Trim() ?? string.Empty;

            try
            {
                var queryResult = new QnASearchResultList();

                ResponseCardPayload payload = new ResponseCardPayload();

                if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null))
                {
                    payload = ((JObject)message.Value).ToObject <ResponseCardPayload>();
                }

                queryResult = await _qnaServiceProvider.GenerateAnswerAsync(question : text, isTestKnowledgeBase : false, payload.PreviousQuestions?.First().Id.ToString(), payload.PreviousQuestions?.First().Questions.First()).ConfigureAwait(false);

                if (queryResult.Answers.First().Id != -1)
                {
                    var answerData = queryResult.Answers.First();
                    payload.QnaPairId = answerData.Id ?? -1;

                    AnswerModel answerModel = new AnswerModel();

                    if (Validators.IsValidJSON(answerData.Answer))
                    {
                        answerModel = JsonConvert.DeserializeObject <AnswerModel>(answerData.Answer);
                    }

                    if (!string.IsNullOrEmpty(answerModel?.Title) || !string.IsNullOrEmpty(answerModel?.Subtitle) || !string.IsNullOrEmpty(answerModel?.ImageUrl) || !string.IsNullOrEmpty(answerModel?.RedirectionUrl))
                    {
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(MessagingExtensionQnaCard.GetEndUserRichCard(text, answerData, payload.QnaPairId))).ConfigureAwait(false);
                    }
                    else
                    {
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(answerData, text, _appBaseUri, payload))).ConfigureAwait(false);
                    }

                    _telemetryClient.TrackEvent(
                        FaqPlusPlusBot.EVENT_ANSWERED_QUESTION_SINGLE,
                        new Dictionary <string, string>
                    {
                        { "QuestionId", payload.QnaPairId.ToString() },
                        { "QuestionAnswered", queryResult.Answers[0].Questions[0] },
                        { "QuestionAsked", text },
                        { "UserName", turnContext.Activity.From.Name },
                        { "UserAadId", turnContext.Activity.From?.AadObjectId ?? "" },
                        { "Product", _options.ProductName },
                    });
                }
                else
                {
                    await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                // Check if knowledge base is empty and has not published yet when end user is asking a question to bot.
                if (((Azure.CognitiveServices.Knowledge.QnAMaker.Models.ErrorResponseException)ex).Response.StatusCode == HttpStatusCode.BadRequest)
                {
                    var knowledgeBaseId = await _configurationProvider.GetSavedEntityDetailAsync(Constants.KnowledgeBaseEntityId).ConfigureAwait(false);

                    var hasPublished = await _qnaServiceProvider.GetInitialPublishedStatusAsync(knowledgeBaseId).ConfigureAwait(false);

                    // Check if knowledge base has not published yet.
                    if (!hasPublished)
                    {
                        this._telemetryClient.TrackException(ex, new Dictionary <string, string> {
                            {
                                "message", "Error while fetching the qna pair: knowledge base may be empty or it has not published yet."
                            },
                        });
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false);

                        return;
                    }
                }

                // Throw the error at calling place, if there is any generic exception which is not caught.
                throw;
            }
        }
示例#23
0
        /// <summary>
        /// Delete qna pair.
        /// </summary>
        /// <param name="turnContext">Turn context.</param>
        /// <param name="qnaServiceProvider">Qna Service provider.</param>
        /// <param name="activityStorageProvider">Activity Storage Provider.</param>
        /// <param name="logger">Logger.</param>
        /// <param name="cancellationToken">Cancellation Token.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        public static async Task DeleteQnaPair(
            ITurnContext <IMessageActivity> turnContext,
            IQnaServiceProvider qnaServiceProvider,
            IActivityStorageProvider activityStorageProvider,
            ILogger logger,
            CancellationToken cancellationToken)
        {
            QnASearchResult searchResult;
            Attachment      attachment;

            var activity      = (Activity)turnContext.Activity;
            var activityValue = ((JObject)activity.Value).ToObject <AdaptiveSubmitActionData>();
            QnASearchResultList qnaAnswerResponse = await qnaServiceProvider.GenerateAnswerAsync(activityValue?.OriginalQuestion, isTestKnowledgeBase : false).ConfigureAwait(false);

            bool isSameQuestion = false;

            searchResult = qnaAnswerResponse.Answers.First();

            // Check if question exist in the knowledgebase.
            if (searchResult != null && searchResult.Questions.Count > 0)
            {
                // Check if the deleted question & result returned from the knowledgebase are same.
                isSameQuestion = searchResult.Questions.First().ToUpperInvariant() == activityValue?.OriginalQuestion.ToUpperInvariant().Trim();
            }

            // Delete the QnA pair if question exist in the knowledgebase & exactly the same question user wants to delete.
            if (searchResult.Id != -1 && isSameQuestion)
            {
                await qnaServiceProvider.DeleteQnaAsync(searchResult.Id.Value).ConfigureAwait(false);

                logger.LogInformation($"Question deleted by: {activity.Conversation.AadObjectId}");
                attachment = MessagingExtensionQnaCard.DeletedEntry(activityValue?.OriginalQuestion, searchResult.Answer, activity.From.Name, activityValue?.UpdateHistoryData);
                ActivityEntity activityEntity = new ActivityEntity {
                    ActivityReferenceId = searchResult.Metadata.FirstOrDefault(x => x.Name == Constants.MetadataActivityReferenceId)?.Value
                };

                bool operationStatus = await activityStorageProvider.DeleteActivityEntityAsync(activityEntity).ConfigureAwait(false);

                if (!operationStatus)
                {
                    logger.LogInformation($"Unable to delete the activity data from table storage.");
                }

                var updateCardActivity = new Activity(ActivityTypes.Message)
                {
                    Id           = turnContext.Activity.ReplyToId,
                    Conversation = turnContext.Activity.Conversation,
                    Attachments  = new List <Attachment> {
                        attachment
                    },
                };

                // Send deleted question and answer card as response.
                await turnContext.UpdateActivityAsync(updateCardActivity, cancellationToken).ConfigureAwait(false);
            }
            else
            {
                // check if question and answer is present in unpublished version.
                qnaAnswerResponse = await qnaServiceProvider.GenerateAnswerAsync(activityValue?.OriginalQuestion, isTestKnowledgeBase : true).ConfigureAwait(false);

                if (qnaAnswerResponse?.Answers?.First().Id != -1)
                {
                    await turnContext.SendActivityAsync(MessageFactory.Text(string.Format(CultureInfo.InvariantCulture, Strings.WaitMessage, activityValue?.OriginalQuestion))).ConfigureAwait(false);
                }
            }

            return;
        }
示例#24
0
        public async Task <string> GenerarRespuesta(string pregunta)
        {
            QnASearchResultList response = await cliente.Runtime.GenerateAnswerAsync(Id, new QueryDTO { Question = pregunta });

            return(response.Answers[0].Answer);
        }
        static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                var exeName = "batchtesting.exe";
                Console.WriteLine("For Qna Maker GA");
                Console.WriteLine($"Usage: {exeName} <tsv-inputfile> <runtime-hostname> <runtime-endpointkey> <tsv-outputfile>");
                Console.WriteLine($"{exeName} input.tsv https://myhostname.azurewebsites.net 5397A838-2B74-4E55-8111-D60ED1D7CF7F output.tsv");
                Console.WriteLine("For QnA Maker managed (preview)");
                Console.WriteLine($"Usage: {exeName} <tsv-inputfile> <cs-hostname> <cs-endpointkey> <tsv-outputfile>");
                Console.WriteLine($"{exeName} input.tsv https://myhostname.cognitiveservices.azure.com b0863a25azsxdcf0b6855e9e988805ed output.tsv");
                Console.WriteLine();

                return;
            }

            var i           = 0;
            var inputFile   = args[i++];
            var runtimeHost = args[i++];
            var endpointKey = args[i++];
            var outputFile  = args[i++];

            var isQnAMakerV2 = CheckForQnAMakerV2(runtimeHost);

            var inputQueries   = File.ReadAllLines(inputFile);
            var inputQueryData = inputQueries.Select(x => GetTsvData(x)).ToList();

            IQnAMakerClient       qnaMakerClient        = null;
            QnAMakerRuntimeClient qnaMakerRuntimeClient = null;

            if (isQnAMakerV2)
            {
                qnaMakerClient = GetQnAMakerClient(endpointKey, runtimeHost);
            }
            else
            {
                qnaMakerRuntimeClient = new QnAMakerRuntimeClient(new EndpointKeyServiceClientCredentials(endpointKey))
                {
                    RuntimeEndpoint = runtimeHost
                };
            }

            var lineNumber       = 0;
            var answerSpanHeader = isQnAMakerV2 ? "\tAnswerSpanText\tAnswerSpanScore" : string.Empty;

            File.WriteAllText(outputFile, $"Line\tKbId\tQuery\tAnswer\tScore{answerSpanHeader}\tMetadata\tAnswerId\tExpectedAnswerId\tLabel{Environment.NewLine}");
            var watch = new Stopwatch();

            watch.Start();
            var maxLines = inputQueryData.Count;

            foreach (var queryData in inputQueryData)
            {
                try
                {
                    lineNumber++;
                    var(queryDto, kbId, expectedAnswerId) = GetQueryDTO(queryData, isQnAMakerV2);

                    QnASearchResultList response = null;

                    if (isQnAMakerV2)
                    {
                        response = qnaMakerClient.Knowledgebase.GenerateAnswerAsync(kbId, queryDto).Result;
                    }
                    else
                    {
                        response = qnaMakerRuntimeClient.Runtime.GenerateAnswerAsync(kbId, queryDto).Result;
                    }

                    var resultLine = new List <string>();
                    resultLine.Add(lineNumber.ToString());
                    resultLine.Add(kbId);
                    resultLine.Add(queryDto.Question);

                    // Add the first answer and its score
                    var firstResult = response.Answers.FirstOrDefault();
                    var answer      = firstResult?.Answer?.Replace("\n", "\\n");

                    resultLine.Add(answer);
                    resultLine.Add(firstResult?.Score?.ToString());

                    if (isQnAMakerV2 && firstResult?.AnswerSpan?.Text != null)
                    {
                        resultLine.Add(firstResult?.AnswerSpan?.Text);
                        resultLine.Add(firstResult?.AnswerSpan?.Score?.ToString());
                    }

                    // Add Metadata
                    var metaDataList = firstResult?.Metadata?.Select(x => $"{x.Name}:{x.Value}")?.ToList();
                    resultLine.Add(metaDataList == null ? string.Empty : string.Join("|", metaDataList));

                    // Add the QnaId
                    var firstQnaId = firstResult?.Id?.ToString();
                    resultLine.Add(firstQnaId);

                    // Add expected answer and label
                    if (!string.IsNullOrWhiteSpace(expectedAnswerId))
                    {
                        resultLine.Add(expectedAnswerId);
                        resultLine.Add(firstQnaId == expectedAnswerId ? "Correct" : "Incorrect");
                    }

                    var result = string.Join('\t', resultLine);
                    File.AppendAllText(outputFile, $"{result}{Environment.NewLine}");
                    PrintProgress(watch, lineNumber, maxLines);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error processing line : {lineNumber}, {ex}");
                }
            }
        }
示例#26
0
        /// <summary>
        /// Get the reply to a question asked by end user.
        /// </summary>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="message">Text message.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        private async Task GetQuestionAnswerReplyAsync(
            ITurnContext <IMessageActivity> turnContext,
            IMessageActivity message)
        {
            string text = message.Text?.ToLower()?.Trim() ?? string.Empty;

            try
            {
                var queryResult = new QnASearchResultList();

                ResponseCardPayload payload = new ResponseCardPayload();

                if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null))
                {
                    payload = ((JObject)message.Value).ToObject <ResponseCardPayload>();
                }

                queryResult = await this.qnaServiceProvider.GenerateAnswerAsync(question : text, isTestKnowledgeBase : false, payload.PreviousQuestions?.First().Id.ToString(), payload.PreviousQuestions?.First().Questions.First()).ConfigureAwait(false);

                if (queryResult.Answers.First().Id != -1)
                {
                    var         answerData  = queryResult.Answers.First();
                    AnswerModel answerModel = new AnswerModel();

                    if (Validators.IsValidJSON(answerData.Answer))
                    {
                        answerModel = JsonConvert.DeserializeObject <AnswerModel>(answerData.Answer);
                    }

                    if (!string.IsNullOrEmpty(answerModel?.Title) || !string.IsNullOrEmpty(answerModel?.Subtitle) || !string.IsNullOrEmpty(answerModel?.ImageUrl) || !string.IsNullOrEmpty(answerModel?.RedirectionUrl))
                    {
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(MessagingExtensionQnaCard.GetEndUserRichCard(text, answerData))).ConfigureAwait(false);
                    }
                    else
                    {
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(answerData, text, this.appBaseUri, payload))).ConfigureAwait(false);
                    }
                }
                else
                {
                    await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                // Check if knowledge base is empty and has not published yet when end user is asking a question to bot.
                if (((ErrorResponseException)ex).Response.StatusCode == HttpStatusCode.BadRequest)
                {
                    var knowledgeBaseId = await this.configurationProvider.GetSavedEntityDetailAsync(Constants.KnowledgeBaseEntityId).ConfigureAwait(false);

                    var hasPublished = await this.qnaServiceProvider.GetInitialPublishedStatusAsync(knowledgeBaseId).ConfigureAwait(false);

                    // Check if knowledge base has not published yet.
                    if (!hasPublished)
                    {
                        this.logger.LogError(ex, "Error while fetching the qna pair: knowledge base may be empty or it has not published yet.");
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false);

                        return;
                    }
                }

                // Throw the error at calling place, if there is any generic exception which is not caught.
                throw;
            }
        }