Exemple #1
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var qnaMaker = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = KBID,
                EndpointKey     = ENDPOINT_KEY,
                Host            = HOST
            },
                                        null,
                                        new System.Net.Http.HttpClient());

            var conversationStateAccessors = _conversationState.CreateProperty <ConversationService>(nameof(ConversationService));
            var conversationService        = await conversationStateAccessors.GetAsync(turnContext, () => new ConversationService());

            var input = turnContext.Activity.Text;

            if (String.IsNullOrEmpty(conversationService.currentService) && (input.Equals("FAQ") || input.Equals("dy365")))
            {
                conversationService.currentService = input;
                await turnContext.SendActivityAsync(MessageFactory.Text("using " + input + " service , pls enter your " + input + " question"), cancellationToken);
            }
            else if (String.IsNullOrEmpty(conversationService.currentService))
            {
                await turnContext.SendActivityAsync(MessageFactory.Text("select a service from hero card first"), cancellationToken);
            }
            else if (conversationService.currentService.Equals("FAQ"))
            {
                var result = qnaMaker.GetAnswersAsync(turnContext).GetAwaiter().GetResult();

                if (result.Length == 0)
                {
                    await turnContext.SendActivityAsync(MessageFactory.Text("Sorry , I can't find any answer for it"), cancellationToken);
                }
                else
                {
                    await turnContext.SendActivityAsync(MessageFactory.Text(result[0].Answer), cancellationToken);
                }
            }
            else if (conversationService.currentService.Equals("dy365"))
            {
                //call your dy 365 service here
                await turnContext.SendActivityAsync(MessageFactory.Text("dy365 response"), cancellationToken);
            }
            else
            {
                await turnContext.SendActivityAsync(MessageFactory.Text("error"), cancellationToken);
            };
        }
Exemple #2
0
        public BotServices(BotSettings settings, IBotTelemetryClient client)
        {
            foreach (var pair in settings.CognitiveModels)
            {
                var set      = new CognitiveModelSet();
                var language = pair.Key;
                var config   = pair.Value;

                var telemetryClient = client;
                var luisOptions     = new LuisPredictionOptions()
                {
                    TelemetryClient        = telemetryClient,
                    LogPersonalInformation = true,
                };

                if (config.DispatchModel != null)
                {
                    var dispatchApp = new LuisApplication(config.DispatchModel.AppId, config.DispatchModel.SubscriptionKey, config.DispatchModel.GetEndpoint());
                    set.DispatchService = new LuisRecognizer(dispatchApp, luisOptions);
                }

                if (config.LanguageModels != null)
                {
                    foreach (var model in config.LanguageModels)
                    {
                        var luisApp = new LuisApplication(model.AppId, model.SubscriptionKey, model.GetEndpoint());
                        set.LuisServices.Add(model.Id, new LuisRecognizer(luisApp, luisOptions));
                    }
                }

                if (config.Knowledgebases != null)
                {
                    foreach (var kb in config.Knowledgebases)
                    {
                        var qnaEndpoint = new QnAMakerEndpoint()
                        {
                            KnowledgeBaseId = kb.KbId,
                            EndpointKey     = kb.EndpointKey,
                            Host            = kb.Hostname,
                        };
                        var qnaMaker = new QnAMaker(qnaEndpoint);
                        set.QnAServices.Add(kb.Id, qnaMaker);
                    }
                }

                CognitiveModelSets.Add(language, set);
            }
        }
        public BotServices(IConfiguration configuration)
        {
            QnAMakerService = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = configuration["QnAKnowledgebaseId"],
                EndpointKey     = configuration["QnAAuthKey"],
                Host            = GetHostname(configuration["QnAEndpointHostName"])
            });

            DocDbEndPoint           = configuration["DocDbEndPoint"];
            DocDbMasterKey          = configuration["DocDbMasterKey"];
            DocDbContainer          = configuration["DocDbContainer"];
            DocDbDatabase           = configuration["DocDbDatabase"];
            DefaultNoAnswer         = configuration["DefaultNoAnswer"];
            TableDbConnectionString = configuration["TableDbConnectionString"];
        }
Exemple #4
0
        public async Task QnaMaker_Test_Top_OutOfRange()
        {
            if (!EnvironmentVariablesDefined())
            {
                Assert.Inconclusive("Missing QnaMaker Environment variables - Skipping test");
                return;
            }

            var qna = new QnAMaker(new QnAMakerOptions()
            {
                KnowledgeBaseId = knowlegeBaseId,
                SubscriptionKey = subscriptionKey,
                Top             = -1,
                ScoreThreshold  = 0.5F
            }, new HttpClient());
        }
Exemple #5
0
        private static BotServices InitBotServices(BotConfiguration config)
        {
            var qnaServices  = new Dictionary <string, QnAMaker>();
            var luisServices = new Dictionary <string, LuisRecognizer>();

            foreach (var service in config.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.Luis:
                {
                    var luis       = (LuisService)service;
                    var app        = new LuisApplication(luis.AppId, luis.AuthoringKey, luis.GetEndpoint());
                    var recognizer = new LuisRecognizer(app);
                    luisServices.Add(luis.Name, recognizer);
                    break;
                }

                case ServiceTypes.Dispatch:
                    var dispatch    = (DispatchService)service;
                    var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.AuthoringKey, dispatch.GetEndpoint());

                    // Since the Dispatch tool generates a LUIS model, we use the LuisRecognizer to resolve the
                    // dispatching of the incoming utterance.
                    var dispatchARecognizer = new LuisRecognizer(dispatchApp);
                    luisServices.Add(dispatch.Name, dispatchARecognizer);
                    break;

                case ServiceTypes.QnA:
                {
                    var qna         = (QnAMakerService)service;
                    var qnaEndpoint = new QnAMakerEndpoint()
                    {
                        KnowledgeBaseId = qna.KbId,
                        EndpointKey     = qna.EndpointKey,
                        Host            = qna.Hostname,
                    };

                    var qnaMaker = new QnAMaker(qnaEndpoint);
                    qnaServices.Add(qna.Name, qnaMaker);
                    break;
                }
                }
            }

            return(new BotServices(qnaServices, luisServices));
        }
        protected override async Task <DialogTurnResult> OnBeginDialogAsync(DialogContext innerDc, object options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            bool   isResponded = false;
            string response    = string.Empty;

            // QnA Service
            _configuration.CheckKeyVault(_configuration["QnA:EndpointKey"]);
            var qnaEndpoint = new QnAMakerEndpoint()
            {
                KnowledgeBaseId = _configuration["QnA:KbId"],
                EndpointKey     = _configuration[_configuration["QnA:EndpointKey"]],
                Host            = _configuration["QnA:Hostname"],
            };
            QnAMakerOptions qnaOptions = float.TryParse(_configuration["QnA:Threshold"], out float scoreThreshold)
                ? new QnAMakerOptions {
                ScoreThreshold = scoreThreshold, Top = 1,
            }
                : null;

            var qnaMaker = new QnAMaker(qnaEndpoint, qnaOptions, null);

            QueryResult[] answer = await qnaMaker.GetAnswersAsync(innerDc.Context);

            if (answer != null && answer.Length > 0)
            {
                response = Regex.Replace(answer.FirstOrDefault().Answer, Utilities.GetResourceMessage(Constants.FirstNamePlaceHolder), innerDc.Context.Activity.From.Name, RegexOptions.IgnoreCase);
                await innerDc.Context.SendActivityAsync(response.Trim());

                await innerDc.Context.AskUserFeedbackAsync(_prevActivityAccessor);

                isResponded = true;
            }
            TaskResult taskResult = new TaskResult()
            {
                Category     = CategoryType.QnA,
                ModelName    = _configuration["QnA:Name"],
                Intent       = string.Empty,
                Entity       = string.Empty,
                Response     = response,
                ResponseType = BotResponseType.ValidResponse,
                Score        = (answer == null || answer.Length == 0) ? 0 : answer.FirstOrDefault().Score,
                Source       = string.IsNullOrEmpty(response) ? CategoryType.QnA : CategoryType.BotResponse
            };
            await _sqlLoggerRepository.InsertBotLogAsync(innerDc.Context.Activity, taskResult);

            return(await innerDc.EndDialogAsync(result : isResponded));
        }
Exemple #7
0
        private async Task <DialogTurnResult> WhatToHelpAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if (!_recognizer.IsConfigured)
            {
                await stepContext.Context.SendActivityAsync(
                    MessageFactory.Text("NOTE: LUIS is not configured. To enable all capabilities, add 'LuisAppId', 'LuisAPIKey' and 'LuisAPIHostName' to the appsettings.json file.", inputHint: InputHints.IgnoringInput), cancellationToken);

                return(await stepContext.NextAsync(null, cancellationToken));
            }
            var luisResult = await _recognizer.RecognizeAsync <LuisIntents>(stepContext.Context, cancellationToken);

            if (luisResult.TopIntent().intent == LuisIntents.Intent.Exit)
            {
                return(await stepContext.BeginDialogAsync(nameof(GoodbyeDialog), null, cancellationToken));
            }
            if (luisResult.TopIntent().intent == LuisIntents.Intent.ServiceToShareWithFamily)
            {
                return(await stepContext.BeginDialogAsync(nameof(GiveOptionsNotClientDialog), null, cancellationToken));
            }

            //Setting up Qna
            var httpClient = _httpClientFactory.CreateClient();
            var qnaMaker   = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
                EndpointKey     = _configuration["QnAEndpointKey"],
                Host            = _configuration["QnAEndpointHostName"]
            },
                                          null,
                                          httpClient);

            // The actual call to the QnA Maker service.
            var qnaOptions = new QnAMakerOptions();

            qnaOptions.ScoreThreshold = 0.4F;

            var response = await qnaMaker.GetAnswersAsync(stepContext.Context, qnaOptions);

            if (response != null && response.Length > 0)
            {
                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text($"{response[0].Answer}. To continue, say 'YES'.") }, cancellationToken));
            }
            else
            {
                return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Sorry, I didn’t understand you. Can you please repeat what you said?") }, cancellationToken));
            }
        }
Exemple #8
0
        public void QnaMaker_Test_ScoreThresholdTooSmall_OutOfRange()
        {
            var endpoint = new QnAMakerEndpoint
            {
                KnowledgeBaseId = _knowlegeBaseId,
                EndpointKey     = _endpointKey,
                Host            = _hostname
            };

            var tooSmallThreshold = new QnAMakerOptions
            {
                ScoreThreshold = -9000.0F,
                Top            = 1
            };

            var qnaWithSmallThreshold = new QnAMaker(endpoint, tooSmallThreshold);
        }
Exemple #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CarWashBot"/> class.
        /// </summary>
        /// <param name="accessors">The state accessors for managing bot state.</param>
        /// <param name="botConfig">The parsed .bot config file.</param>
        /// <param name="services">External services.</param>
        /// <param name="loggerFactory">Logger.</param>
        /// <param name="telemetryClient">Telemetry client.</param>
        public CarWashBot(StateAccessors accessors, BotConfiguration botConfig, BotServices services, ILoggerFactory loggerFactory, TelemetryClient telemetryClient)
        {
            _accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));
            if (botConfig == null)
            {
                throw new ArgumentNullException(nameof(botConfig));
            }
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            _telemetryClient = telemetryClient;

            // Verify LUIS configuration.
            if (!services.LuisServices.ContainsKey(LuisConfiguration))
            {
                throw new InvalidOperationException($"Invalid configuration. Please check your '.bot' file for a LUIS service named '{LuisConfiguration}'.");
            }
            _luis = services.LuisServices[LuisConfiguration];

            // Verify QnAMaker configuration.
            if (!services.QnAServices.ContainsKey(QnAMakerConfiguration))
            {
                throw new ArgumentException($"Invalid configuration. Please check your '.bot' file for a QnA service named '{QnAMakerConfiguration}'.");
            }
            _qna = services.QnAServices[QnAMakerConfiguration];

            // Verify Storage configuration.
            if (!services.StorageServices.ContainsKey(StorageConfiguration))
            {
                throw new ArgumentException($"Invalid configuration. Please check your '.bot' file for a Storage service named '{StorageConfiguration}'.");
            }
            _storage = services.StorageServices[StorageConfiguration];

            Dialogs = new DialogSet(_accessors.DialogStateAccessor);
            Dialogs.Add(new NewReservationDialog(_accessors.NewReservationStateAccessor, telemetryClient));
            Dialogs.Add(new ConfirmDropoffDialog(_accessors.ConfirmDropoffStateAccessor, telemetryClient));
            Dialogs.Add(new CancelReservationDialog(_accessors.CancelReservationStateAccessor, telemetryClient));
            Dialogs.Add(new FindReservationDialog(telemetryClient));
            Dialogs.Add(new NextFreeSlotDialog(telemetryClient));
            Dialogs.Add(new AuthDialog(accessors.UserProfileAccessor, _storage, telemetryClient));
            Dialogs.Add(AuthDialog.LoginPromptDialog());

            // Dialogs.Add(FormDialog.FromForm(NewReservationForm.BuildForm));
        }
        //string messageText = "What can I help you with today?";
        // Dependency injection uses this constructor to instantiate MainDialog
        public MainDialogs(SearchLuisRecognizer luisRecognizer, QnAMakerEndpoint endpoint)
            : base(nameof(MainDialogs))
        {
            _luisRecognizer = luisRecognizer;
            SearchBotQnA    = new QnAMaker(endpoint);

            AddDialog(new TextPrompt(nameof(TextPrompt)));
            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
            {
                IntroStepAsync,
                ActStepAsync,
                FinalStepAsync,
            }));

            // The initial child Dialog to run.
            InitialDialogId = nameof(WaterfallDialog);
        }
        public BotServices(IConfiguration configuration, OrchestratorRecognizer dispatcher)
        {
            // Read the setting for cognitive services (LUIS, QnA) from the appsettings.json
            // If includeApiResults is set to true, the full response from the LUIS api (LuisResult)
            // will be made available in the properties collection of the RecognizerResult
            LuisHomeAutomationRecognizer = CreateLuisRecognizer(configuration, "LuisHomeAutomationAppId");
            LuisWeatherRecognizer        = CreateLuisRecognizer(configuration, "LuisWeatherAppId");

            Dispatch = dispatcher;

            SampleQnA = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = configuration["QnAKnowledgebaseId"],
                EndpointKey     = configuration["QnAEndpointKey"],
                Host            = configuration["QnAEndpointHostName"]
            });
        }
Exemple #12
0
        static async Task UpdateKnowledgebaseDeletebySource(QnAMaker client)
        {
            var kbUpdate = new KnowledgebaseUpdate
            {
                delete = new Delete
                {
                    sources = new List <string>()
                    {
                        "KB"
                    }
                }
            };

            var retorno = await client.UpdateKnowledgebase(kbUpdate);

            System.Console.WriteLine(retorno.operationId);
        }
        public QuestionDialog(UserState userState, QnAMakerEndpoint endpoint) : base(nameof(QuestionDialog))
        {
            _userProfileAccessor = userState.CreateProperty <UserProfile>("UserProfile");
            _kennisAvondBotQnA   = new QnAMaker(endpoint);

            var waterfallSteps = new WaterfallStep[]
            {
                AskForQuestionStepAsync,
                AnswerQuestionStepAsync,
            };

            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));

            AddDialog(new TextPrompt("QuestionPrompt"));

            InitialDialogId = nameof(WaterfallDialog);
        }
Exemple #14
0
        static async Task UpdateKnowledgebaseDeleteById(QnAMaker client, Guid kbId)
        {
            var kbUpdate = new KnowledgebaseUpdate
            {
                delete = new Delete
                {
                    ids = new List <int>()
                    {
                        142
                    }
                }
            };

            var retorno = await client.UpdateKnowledgebase(kbUpdate);

            System.Console.WriteLine(retorno.operationId);
        }
        public ChatBoxBot(ConversationState conversationState, UserState userState, IChannelClient client,
                          QnAMaker qna, LuisRecognizer luis, ILoggerFactory loggerFactory)
        {
            _userState        = userState;
            _converationState = conversationState;
            QnA        = qna;
            Recognizer = luis;
            ConversationDialogState = _converationState.CreateProperty <DialogState>($"{nameof(ChatBox)}.ConversationDialogState");
            UserSelectionsState     = _userState.CreateProperty <UserSelections>($"{nameof(ChatBox)}.UserSelectionsState");

            _logger  = loggerFactory.CreateLogger <ChatBoxBot>();
            _dialogs = new DialogSet(ConversationDialogState);
            _dialogs.Add(new WhenNextDialog(Constants.WhenNextIntent, UserSelectionsState, client));
            _dialogs.Add(new SetTimezoneDialog(Constants.SetTimezoneIntent, UserSelectionsState));
            _dialogs.Add(new LiveNowDialog(Constants.LiveNow, client));
            _dialogs.Add(new DiscoveryDialog(Constants.DiscoverIntent, client));
        }
Exemple #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">A dictionary of named <see cref="BotConfiguration"/> instances for usage within the bot.</param>
        public BotServices(BotConfiguration botConfiguration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.QnA:
                {
                    // Create a QnA Maker that is initialized and suitable for passing
                    // into the IBot-derived class (QnABot).
                    var qna = service as QnAMakerService;
                    if (qna == null)
                    {
                        throw new InvalidOperationException("The QnA service is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(qna.KbId))
                    {
                        throw new InvalidOperationException("The QnA KnowledgeBaseId ('kbId') is required to run this sample. Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(qna.EndpointKey))
                    {
                        throw new InvalidOperationException("The QnA EndpointKey ('endpointKey') is required to run this sample. Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(qna.Hostname))
                    {
                        throw new InvalidOperationException("The QnA Host ('hostname') is required to run this sample. Please update your '.bot' file.");
                    }

                    var qnaEndpoint = new QnAMakerEndpoint()
                    {
                        KnowledgeBaseId = qna.KbId,
                        EndpointKey     = qna.EndpointKey,
                        Host            = qna.Hostname,
                    };

                    var qnaMaker = new QnAMaker(qnaEndpoint);
                    QnAServices.Add(qna.Name, qnaMaker);
                    break;
                }
                }
            }
        }
Exemple #17
0
        public ADSBotServices(IConfiguration configuration, ConversationState conversationState,
                              UserState userState, CRMService crmService, DataService dataService)
        {
            ConversationState = conversationState;
            Configuration     = configuration;
            DataService       = dataService;
            UserState         = userState;
            CRM = crmService;

            UserProfileAccessor = UserState.CreateProperty <UserProfile>(nameof(UserProfile));
            DialogStateAccessor = ConversationState.CreateProperty <DialogState>(nameof(DialogState));
            //Used by micrsoft dialog classes
            GenericUserProfileAccessor = UserState.CreateProperty <Dictionary <string, object> >(nameof(UserProfile));

            QnAOptions = new QnAMakerOptions();

            LeadQualQnA = new QnAMaker(
                new QnAMakerEndpoint
            {
                KnowledgeBaseId = configuration["qna:QnAKnowledgebaseId"],
                EndpointKey     = configuration["qna:QnAEndpointKey"],
                Host            = configuration["qna:QnAEndpointHostName"]
            }, QnAOptions);

            //Apparently the constructor overrides the properties with defaults?
            QnAOptions.ScoreThreshold = 0;

            var luisApplication = new LuisApplication(
                configuration["luis:id"],
                configuration["luis:endpointKey"],
                configuration["luis:endpoint"]);

            var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
            {
                IncludeAPIResults = true,
                PredictionOptions = new Microsoft.Bot.Builder.AI.LuisV3.LuisPredictionOptions()
                {
                    IncludeAllIntents   = true,
                    IncludeInstanceData = true
                }
            };

            LuisRecognizer = new LuisRecognizer(recognizerOptions);
        }
        public DispatcherService(IHttpClientFactory httpClientFactory, IConfiguration configuration)
        {
            var httpClient = httpClientFactory.CreateClient();


            Dispatch = new LuisRecognizer(new LuisRecognizerOptionsV2(new LuisApplication(
                                                                          configuration["Dispatcher:LuisAppId"],
                                                                          configuration["Dispatcher:LuisAPIKey"],
                                                                          configuration["Dispatcher:LuisAPIHostName"])
                                                                      )
            {
                IncludeAPIResults = true,
                PredictionOptions = new LuisPredictionOptions()
                {
                    IncludeAllIntents   = true,
                    IncludeInstanceData = true
                }
            });


            QnA = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = configuration["QnAMaker:KnowledgebaseId"],
                EndpointKey     = configuration["QnAMaker:EndpointKey"],
                Host            = configuration["QnAMaker:Host"]
            },
                               null,
                               httpClient);

            Luis = new LuisRecognizer(new LuisRecognizerOptionsV2(new LuisApplication(
                                                                      configuration["LUIS:LuisAppId"],
                                                                      configuration["LUIS:LuisAPIKey"],
                                                                      configuration["LUIS:LuisAPIHostName"])
                                                                  )
            {
                IncludeAPIResults = true,
                PredictionOptions = new LuisPredictionOptions()
                {
                    IncludeAllIntents   = true,
                    IncludeInstanceData = true
                }
            });
        }
        public BotServices(IConfiguration configuration)
        {
            // Read the setting for cognitive services (LUIS, QnA) from the appsettings.json
            Dispatch = new LuisRecognizer(new LuisApplication(
                                              configuration["LuisAppId"],
                                              configuration["LuisAPIKey"],
                                              $"https://{configuration["LuisAPIHostName"]}.api.cognitive.microsoft.com"),
                                          new LuisPredictionOptions {
                IncludeAllIntents = true, IncludeInstanceData = true
            },
                                          true);

            SampleQnA = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = configuration["QnAKnowledgebaseId"],
                EndpointKey     = configuration["QnAAuthKey"],
                Host            = configuration["QnAEndpointHostName"]
            });
        }
Exemple #20
0
        public BotServices(IConfiguration configuration)
        {
            // Read the setting for cognitive services (LUIS, QnA) from the appsettings.json
            luisRecognizer = new LuisRecognizer(new LuisApplication(
                                                    configuration["LuisAppId"],
                                                    configuration["LuisAPIKey"],
                                                    configuration["LuisAPIHostName"]),
                                                new LuisPredictionOptions {
                IncludeAllIntents = true, IncludeInstanceData = true
            },
                                                true);

            qnaMaker = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = configuration["QnAKnowledgebaseId"],
                EndpointKey     = configuration["QnAEndpointKey"],
                Host            = configuration["QnAEndpointHostName"]
            });
        }
Exemple #21
0
        void EnsureQnAMakerService()
        {
            if (_qnaMakerService != null)
            {
                return;
            }

            //Iterate through all services in the .bot file and get the first one with 'qna' as the type
            var service = _botConfiguration.Services.FirstOrDefault(s => s.Type == ServiceTypes.QnA) as QnAMakerService;

            var qnaEndpoint = new QnAMakerEndpoint()
            {
                KnowledgeBaseId = service.KbId,
                EndpointKey     = service.EndpointKey,
                Host            = service.Hostname,
            };

            _qnaMakerService = new QnAMaker(qnaEndpoint);
        }
Exemple #22
0
        public BotServices(IConfiguration configuration)
        {
            //Read the settings for cognitive services (LUIS, QnA) from the appsettings.json
            //If includeApiResults is set to true, the full response from the LUIS api (LuisResult)
            //will be made available in the properties collection of the RecognizerResult
            LuisService = new LuisRecognizer(
                new LuisApplication(configuration["LuisAppId"], configuration["LuisAPIKey"],
                                    $"https://{configuration["LuisAPIHostName"]}.api.cognitive.microsoft.com"),
                new LuisPredictionOptions {
                IncludeAllIntents = true, IncludeInstanceData = true
            },
                includeApiResults: true);

            QnAMakerService = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = configuration["QnAKnowledgebaseId"],
                EndpointKey     = configuration["QnAEndpointKey"],
                Host            = configuration["QnAEndpointHostName"]
            });
        }
Exemple #23
0
        public BotServices(BotSettings settings)
        {
            foreach (var pair in settings.CognitiveModels)
            {
                var set      = new CognitiveModelSet();
                var language = pair.Key;
                var config   = pair.Value;

                if (config.DispatchModel != null)
                {
                    var dispatchApp = new LuisApplication(config.DispatchModel.AppId, config.DispatchModel.SubscriptionKey, config.DispatchModel.GetEndpoint());
                    set.DispatchService = new LuisRecognizer(dispatchApp);
                }

                if (config.LanguageModels != null)
                {
                    foreach (var model in config.LanguageModels)
                    {
                        var luisApp = new LuisApplication(model.AppId, model.SubscriptionKey, model.GetEndpoint());
                        set.LuisServices.Add(model.Id, new LuisRecognizer(luisApp));
                    }
                }

                if (config.Knowledgebases != null)
                {
                    foreach (var kb in config.Knowledgebases)
                    {
                        var qnaEndpoint = new QnAMakerEndpoint()
                        {
                            KnowledgeBaseId = kb.KbId,
                            EndpointKey     = kb.EndpointKey,
                            Host            = kb.Hostname,
                        };
                        var qnaMaker = new QnAMaker(qnaEndpoint);
                        set.QnAServices.Add(kb.Id, qnaMaker);
                    }
                }

                CognitiveModelSets.Add(language, set);
            }
        }
Exemple #24
0
        /// <summary>
        /// Initialize the bot's references to external services.
        ///
        /// For example, QnaMaker services are created here.
        /// These external services are configured
        /// using the <see cref="AppSettings"/> class (based on the contents of your "appsettings.json" file).
        /// </summary>
        /// <param name="appSettings"><see cref="AppSettings"/> object based on your "appsettings.json" file.</param>
        /// <returns>A <see cref="BotServices"/> representing client objects to access external services the bot uses.</returns>
        /// <seealso cref="AppSettings"/>
        /// <seealso cref="QnAMaker"/>
        /// <seealso cref="LuisService"/>
        public static BotServices InitBotServices(AppSettings appSettings)
        {
            var            luisIntents           = appSettings.luisIntents;
            var            qnaServices           = new Dictionary <string, QnAMaker>();
            LuisRecognizer luisRecignizerService = null;
            List <string>  IntentsList           = appSettings.luisIntents;
            //Prepare Luis service
            LuisService luisService = new LuisService()
            {
                AppId           = appSettings.luisApp.appId,
                AuthoringKey    = appSettings.luisApp.authoringKey,
                Id              = appSettings.luisApp.id,
                Name            = appSettings.luisApp.name,
                Region          = appSettings.luisApp.region,
                SubscriptionKey = appSettings.luisApp.subscriptionKey,
                Type            = appSettings.luisApp.type,
                Version         = appSettings.luisApp.version
            };
            var luisApp = new LuisApplication(luisService.AppId, luisService.AuthoringKey, luisService.GetEndpoint());

            luisRecignizerService = new LuisRecognizer(luisApp);
            //Prepare QnA service
            foreach (var qna in appSettings.qnaServices)
            {
                var qnaEndpoint = new QnAMakerEndpoint()
                {
                    KnowledgeBaseId = qna.kbId,
                    EndpointKey     = qna.endpointKey,
                    Host            = qna.hostname,
                };
                var qnaMaker = new QnAMaker(qnaEndpoint);
                qnaServices.Add(qna.name, qnaMaker);
            }
            //return new BotServices(luisRecignizerService, qnaServices, Intents);
            return(new BotServices()
            {
                Intents = IntentsList,
                LuisRecognizerService = luisRecignizerService,
                QnAServices = qnaServices,
            });
        }
        public void QnaMaker_Test_ScoreThreshold_OutOfRange()
        {
            if (!EnvironmentVariablesDefined())
            {
                Assert.Inconclusive("Missing QnaMaker Environment variables - Skipping test");
                return;
            }

            var qna = new QnAMaker(
                new QnAMakerEndpoint
            {
                KnowledgeBaseId = knowlegeBaseId,
                EndpointKey     = endpointKey,
                Host            = hostname
            },
                new QnAMakerOptions
            {
                Top            = 1,
                ScoreThreshold = 1.1F
            });
        }
Exemple #26
0
        public async Task QnaMaker_TestThreshold()
        {
            if (!EnvironmentVariablesDefined())
            {
                Assert.Inconclusive("Missing QnaMaker Environment variables - Skipping test");
                return;
            }

            var qna = new QnAMaker(new QnAMakerOptions()
            {
                KnowledgeBaseId = knowlegeBaseId,
                SubscriptionKey = subscriptionKey,
                Top             = 1,
                ScoreThreshold  = 0.99F
            }, new HttpClient());

            var results = await qna.GetAnswers("how do I clean the stove?");

            Assert.IsNotNull(results);
            Assert.AreEqual(results.Length, 0, "should get zero result because threshold");
        }
Exemple #27
0
        public async Task QnaMaker_ReturnsAnswer()
        {
            if (!EnvironmentVariablesDefined())
            {
                Assert.Inconclusive("Missing QnaMaker Environment variables - Skipping test");
                return;
            }

            var qna = new QnAMaker(new QnAMakerOptions()
            {
                KnowledgeBaseId = knowlegeBaseId,
                SubscriptionKey = subscriptionKey,
                Top             = 1
            }, new HttpClient());

            var results = await qna.GetAnswers("how do I clean the stove?");

            Assert.IsNotNull(results);
            Assert.AreEqual(results.Length, 1, "should get one result");
            Assert.IsTrue(results[0].Answer.StartsWith("BaseCamp: You can use a damp rag to clean around the Power Pack"));
        }
Exemple #28
0
        static async Task ReplaceKnowledgebase(QnAMaker client)
        {
            var kbreplace = new KnowledgebaseReplace
            {
                qnaList = (await client.DownloadKnowledgeBase()).qnaDocuments
            };

            foreach (var item in kbreplace.qnaList)
            {
                item.metadata = new List <Metadata>()
                {
                    new Metadata()
                    {
                        name  = "origem",
                        value = "xpto"
                    }
                };
            }

            await client.ReplaceKnowledgebase(kbreplace);
        }
Exemple #29
0
        public async Task <QueryResult[]> SearchQnaMaker(string message)
        {
            var options = new QnAMakerOptions()
            {
                KnowledgeBaseId = "",
                SubscriptionKey = "",
                ScoreThreshold  = 0.7f
            };

            qnAMaker = new QnAMaker(options);
            var results = await qnAMaker.GetAnswers(message);

            if (results.Count() > 0)
            {
                return(results);
            }
            else
            {
                return(null);
            }
        }
Exemple #30
0
        static async Task MakeAQuestion(QnAMaker client)
        {
            var q = new Question()
            {
                question = "como carregar um celular",
                //top = 3,
                //strictFilters = new List<Metadata>()
                //{
                //    new Metadata()
                //    {
                //        name = "parametro02",
                //        value = "000002"
                //    }
                //},
                //Score = 9.5f,
                userId = "xpto"
            };

            var xxx = await client.MakeAQuestion("como carregar um celular");

            foreach (var answerItem in xxx.answers)
            {
                System.Console.WriteLine($"Id - {answerItem.id}");
                System.Console.WriteLine($"Answer - {answerItem.answer}");
                System.Console.WriteLine($"Score - {answerItem.score}");
                System.Console.WriteLine($"Source - {answerItem.source}");

                foreach (var metadata in answerItem.metadata)
                {
                    System.Console.WriteLine($"Metadata : {metadata.name} - {metadata.value}");
                }

                foreach (var question in answerItem.questions)
                {
                    System.Console.WriteLine($"Question : {question}");
                }

                System.Console.WriteLine("-------------------");
            }
        }