Exemple #1
0
        public object Load(JToken obj, JsonSerializer serializer, Type type)
        {
            // If the luis service info is inlined with the recognizer, load it here for
            // simpler json format
            if (obj["applicationId"]?.Type == JTokenType.String)
            {
                var luisApplication = obj.ToObject <LuisApplication>();
                var name            = luisApplication.ApplicationId;
                if (name.StartsWith("{") && name.EndsWith("}"))
                {
                    var start = name.LastIndexOf('.') + 1;
                    var end   = name.LastIndexOf('}');
                    name = name.Substring(start, end - start);
                }

                luisApplication.ApplicationId = configuration.LoadSetting(luisApplication.ApplicationId);
                luisApplication.Endpoint      = configuration.LoadSetting(luisApplication.Endpoint);
                luisApplication.EndpointKey   = configuration.LoadSetting(luisApplication.EndpointKey);

                var options = new LuisRecognizerOptionsV3(luisApplication);
                if (obj["predictionOptions"] != null)
                {
                    options.PredictionOptions = obj["predictionOptions"].ToObject <AI.LuisV3.LuisPredictionOptions>();
                }

                return(new MockLuisRecognizer(options, configuration.GetValue <string>("luis:resources"), name));
            }

            // Else, just assume it is the verbose structure with LuisService as inner object
            return(obj.ToObject <MockLuisRecognizer>(serializer));
        }
        public LanguageRecognitionService(IOptions <Luis> configuration)
        {
            var luisIsConfigured = !string.IsNullOrEmpty(configuration.Value.LuisAppId) &&
                                   !string.IsNullOrEmpty(configuration.Value.LuisAPIKey) &&
                                   !string.IsNullOrEmpty(configuration.Value.LuisAPIHostName);

            if (luisIsConfigured)
            {
                throw new InvalidOperationException("Missing LUIS configuration values");
            }

            var luisApplication = new LuisApplication(
                configuration.Value.LuisAppId,
                configuration.Value.LuisAPIKey,
                "https://" + configuration.Value.LuisAPIHostName);

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

            _recognizer = new LuisRecognizer(recognizerOptions);
        }
        public async Task Telemetry_ConvertParms()
        {
            // Arrange
            // Note this is NOT a real LUIS application ID nor a real LUIS subscription-key
            // theses are GUIDs edited to look right to the parsing and validation code.
            var endpoint        = "https://westus.api.cognitive.microsoft.com/luis/v3.0-preview/apps/b31aeaf3-3511-495b-a07f-571fc873214b/slots/production/predict?verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=";
            var clientHandler   = new EmptyLuisResponseClientHandlerV3();
            var luisApp         = new LuisApplication(endpoint);
            var telemetryClient = new Mock <IBotTelemetryClient>();
            var adapter         = new NullAdapter();
            var activity        = new Activity
            {
                Type         = ActivityTypes.Message,
                Text         = "please book from May 5 to June 6",
                Recipient    = new ChannelAccount(),        // to no where
                From         = new ChannelAccount(),        // from no one
                Conversation = new ConversationAccount(),   // on no conversation
            };

            var turnContext = new TurnContext(adapter, activity);

            var options = new LuisRecognizerOptionsV3(luisApp)
            {
                TelemetryClient        = telemetryClient.Object,
                LogPersonalInformation = false,
            };
            var recognizer = new LuisRecognizer(options, clientHandler);

            // Act
            var additionalProperties = new Dictionary <string, string>
            {
                { "test", "testvalue" },
                { "foo", "foovalue" },
            };
            var additionalMetrics = new Dictionary <string, double>
            {
                { "moo", 3.14159 },
                { "luis", 1.0001 },
            };

            var result = await recognizer.RecognizeAsync(turnContext, additionalProperties, additionalMetrics, CancellationToken.None).ConfigureAwait(false);

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(telemetryClient.Invocations.Count, 1);
            Assert.AreEqual(telemetryClient.Invocations[0].Arguments[0].ToString(), "LuisResult");
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("test"));
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1])["test"] == "testvalue");
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("foo"));
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1])["foo"] == "foovalue");
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("applicationId"));
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("intent"));
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("intentScore"));
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("fromId"));
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("entities"));
            Assert.IsTrue(((Dictionary <string, double>)telemetryClient.Invocations[0].Arguments[2]).ContainsKey("moo"));
            Assert.AreEqual(((Dictionary <string, double>)telemetryClient.Invocations[0].Arguments[2])["moo"], 3.14159);
            Assert.IsTrue(((Dictionary <string, double>)telemetryClient.Invocations[0].Arguments[2]).ContainsKey("luis"));
            Assert.AreEqual(((Dictionary <string, double>)telemetryClient.Invocations[0].Arguments[2])["luis"], 1.0001);
        }
        //private static object services;

        public static async Task <string> ExecuteLuisQuery(IConfiguration configuration, ILogger logger, ITurnContext turnContext, CancellationToken cancellationToken)
        {
            try
            {
                // Create the LUIS settings from configuration.
                var luisApplication = new LuisApplication(
                    configuration["LuisAppId"],
                    configuration["LuisAPIKey"],
                    "https://" + configuration["LuisAPIHostName"]
                    );

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

                var recognizer = new LuisRecognizer(recognizerOptions);

                // The actual call to LUIS
                var recognizerResult = await recognizer.RecognizeAsync(turnContext, cancellationToken);

                var(intent, score)  = recognizerResult.GetTopScoringIntent();
                AzureDetails.Intent = intent;
            }
            catch (Exception e)
            {
                logger.LogWarning($"LUIS Exception: {e.Message} Check your LUIS configuration.");
            }

            return(AzureDetails.Intent);
        }
        public ConnectionRecognizer(IConfiguration configuration)
        {
            var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId"]) && !string.IsNullOrEmpty(configuration["LuisAPIKey"]) && !string.IsNullOrEmpty(configuration["LuisAPIHostName"]);

            if (luisIsConfigured)
            {
                var luisApplication = new LuisApplication(
                    configuration["LuisAppId"],
                    configuration["LuisAPIKey"],
                    "https://" + configuration["LuisAPIHostName"]);

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

                _recognizer = new LuisRecognizer(recognizerOptions);
            }


            SampleQnA = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = QnAKnowledgebaseId,
                EndpointKey     = QnAEndpointKey,
                Host            = QnAEndpointHostName
            });
        }
        public FlightBookingRecognizer(IConfiguration configuration)
        {
            var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId"]) &&
                                   !string.IsNullOrEmpty(configuration["LuisAPIKey"]) &&
                                   !string.IsNullOrEmpty(configuration["LuisAPIHostName"]);

            if (luisIsConfigured)
            {
                var luisApplication = new LuisApplication(
                    configuration["LuisAppId"],
                    configuration["LuisAPIKey"],
                    "https://" + configuration["LuisAPIHostName"]);

                // Set the recognizer options depending on which endpoint version you want to use.
                // More details can be found in https://docs.microsoft.com/en-gb/azure/cognitive-services/luis/luis-migration-api-v3
                var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
                {
                    PredictionOptions = new LuisPredictionOptions
                    {
                        IncludeInstanceData = true
                    }
                };

                _recognizer = new LuisRecognizer(recognizerOptions);
            }
        }
        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;

                LuisRecognizerOptionsV3 luisOptions;

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

                if (config.LanguageModels != null)
                {
                    foreach (var model in config.LanguageModels)
                    {
                        var luisApp = new LuisApplication(model.AppId, model.SubscriptionKey, model.GetEndpoint());
                        luisOptions = new LuisRecognizerOptionsV3(luisApp)
                        {
                            TelemetryClient        = telemetryClient,
                            LogPersonalInformation = true,
                            PredictionOptions      = new Microsoft.Bot.Builder.AI.LuisV3.LuisPredictionOptions()
                            {
                                IncludeInstanceData = true
                            }
                        };
                        set.LuisServices.Add(model.Id, new LuisRecognizer(luisOptions));
                    }
                }

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

                        set.QnAConfiguration.Add(kb.Id, qnaEndpoint);
                    }
                }

                CognitiveModelSets.Add(language, set);
            }
        }
Exemple #8
0
        public BeerBotIntentRecognizer(IOptions <RecognizerOptions> options)
        {
            var luisApplication   = new LuisApplication(options.Value.AppId, options.Value.ApiKey, options.Value.Endpoint);
            var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
            {
                PredictionOptions = new Microsoft.Bot.Builder.AI.LuisV3.LuisPredictionOptions
                {
                    IncludeInstanceData = true
                }
            };

            _recognizer = new LuisRecognizer(recognizerOptions);
        }
        private IRecognizer GetLuisRecognizer(MockedHttpClientHandler httpClientHandler, LuisV3.LuisPredictionOptions options = null)
        {
            var luisApp = new LuisApplication(AppId, Key, Endpoint);
            var luisRecognizerOptions = new LuisRecognizerOptionsV3(luisApp)
            {
                PredictionOptions = options,
                IncludeAPIResults = options == null ? false : true,
            };

            return(new LuisRecognizer(luisRecognizerOptions, httpClientHandler));

            // return new LuisRecognizer(luisApp, new LuisRecognizerOptions { HttpClient = httpClientHandler }, options);
        }
Exemple #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Check that all configuration values have been specified
            IConfiguration chatbotConfig       = Configuration.GetSection("PersonalizerChatbot");
            var            missingConfigValues = chatbotConfig.GetChildren().Where(c => string.IsNullOrEmpty(c.Value));

            if (missingConfigValues.Count() > 0)
            {
                throw new Exception($"Missing config values in appsettings. Please check the README to ensure you have filled in all the necessary Personalizer and LUIS config values. {string.Join(",", missingConfigValues.Select(cv => cv.Key).ToArray())}");
            }

            services.AddControllers().AddNewtonsoftJson();

            // Create the Bot Framework Adapter with error handling enabled.
            services.AddSingleton <IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();

            // Create the reinforcement learning feature manager
            services.AddSingleton <RLContextManager>();

            // Register LUIS recognizer
            services.AddSingleton(recognizer =>
            {
                var luisApplication = new LuisApplication(
                    chatbotConfig["LuisAppId"],
                    chatbotConfig["LuisAPIKey"],
                    chatbotConfig["LuisServiceEndpoint"]);
                // Set the recognizer options depending on which endpoint version you want to use.
                // More details can be found in https://docs.microsoft.com/en-gb/azure/cognitive-services/luis/luis-migration-api-v3
                var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
                {
                    PredictionOptions = new Microsoft.Bot.Builder.AI.LuisV3.LuisPredictionOptions
                    {
                        IncludeInstanceData = true,
                    }
                };

                return(new LuisRecognizer(recognizerOptions));
            });

            // Register Personalizer client
            services.AddSingleton(client =>
            {
                return(new PersonalizerClient(new ApiKeyServiceClientCredentials(chatbotConfig["PersonalizerAPIKey"]))
                {
                    Endpoint = chatbotConfig["PersonalizerServiceEndpoint"],
                });
            });

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            services.AddTransient <IBot, Bots.PersonalizerChatbot>();
        }
        public BotServices(IConfiguration _configuration)
        {
            configuration = _configuration;
            // 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

            var luisApplication = new LuisApplication(
                configuration["LuisAppId"],
                configuration["LuisAPIKey"],
                $"https://{configuration["LuisAPIHostName"]}.api.cognitive.microsoft.com");

            var luisApplicationDetails = new LuisApplication(
                configuration["LuisAppIdDetails"],
                configuration["LuisAPIKeyDetails"],
                $"https://{configuration["LuisAPIHostName"]}.api.cognitive.microsoft.com");

            // Set the recognizer options depending on which endpoint version you want to use.

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

            Dispatch = new LuisRecognizer(recognizerOptions);

            DispatchDetailsModels = new LuisRecognizer(recognizerOptions);

            QnAMakerService = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = configuration["QnAKnowledgebaseId"],
                EndpointKey     = configuration["QnAEndpointKey"],
                Host            = GetHostname()
            });
        }
Exemple #12
0
        public static IServiceCollection AddLuisService(this IServiceCollection services, LuisApplication luisApplication)
        {
            luisApplication.Validate();

            var luisRecognizerOptions = new LuisRecognizerOptionsV3(luisApplication);

            luisRecognizerOptions.PredictionOptions.IncludeAllIntents = false;

            var luisRecognizer = new LuisRecognizer(luisRecognizerOptions);

            services.AddSingleton <LuisRecognizer>(luisRecognizer);

            return(services);
        }
        public void LuisRecognizer_Timeout()
        {
            var endpoint        = "https://westus.api.cognitive.microsoft.com/luis/v3.0-preview/apps/b31aeaf3-3511-495b-a07f-571fc873214b/slots/production/predict?verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=";
            var expectedTimeout = 300;

            var options = new LuisRecognizerOptionsV3(new LuisApplication(endpoint))
            {
                Timeout = expectedTimeout
            };
            var recognizerWithTimeout = new LuisRecognizer(options);

            Assert.IsNotNull(recognizerWithTimeout);
            Assert.AreEqual(expectedTimeout, LuisRecognizer.DefaultHttpClient.Timeout.Milliseconds);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MockLuisRecognizer"/> class.
 /// </summary>
 /// <param name="resourceDir">Where the settings file generated by lubuild is found.</param>
 /// <param name="name">Name of the LUIS model.</param>
 /// <param name="options">LUIS options.</param>
 public MockLuisRecognizer(
     LuisRecognizerOptionsV3 options,
     string resourceDir,
     string name)
 {
     _responseDir = Path.Combine(resourceDir, "cachedResponses", name);
     _name        = name;
     _options     = options;
     _options.IncludeAPIResults = true;
     if (!Directory.Exists(_responseDir))
     {
         Directory.CreateDirectory(_responseDir);
     }
 }
Exemple #15
0
        public async Task Telemetry_OverrideOnDeriveAsync()
        {
            // Arrange
            // Note this is NOT a real LUIS application ID nor a real LUIS subscription-key
            // theses are GUIDs edited to look right to the parsing and validation code.
            var endpoint        = "https://westus.api.cognitive.microsoft.com/luis/prediction/v3.0/apps/b31aeaf3-3511-495b-a07f-571fc873214b/slots/production/predict?verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=";
            var clientHandler   = new EmptyLuisResponseClientHandlerV3();
            var luisApp         = new LuisApplication(endpoint);
            var telemetryClient = new Mock <IBotTelemetryClient>();
            var adapter         = new NullAdapter();
            var activity        = new Activity
            {
                Type         = ActivityTypes.Message,
                Text         = "please book from May 5 to June 6",
                Recipient    = new ChannelAccount(),        // to no where
                From         = new ChannelAccount(),        // from no one
                Conversation = new ConversationAccount(),   // on no conversation
            };

            var turnContext = new TurnContext(adapter, activity);

            var options = new LuisRecognizerOptionsV3(luisApp)
            {
                TelemetryClient        = telemetryClient.Object,
                LogPersonalInformation = false,
            };
            var recognizer = new TelemetryOverrideRecognizer(options, clientHandler);

            var additionalProperties = new Dictionary <string, string>
            {
                { "test", "testvalue" },
                { "foo", "foovalue" },
            };
            var result = await recognizer.RecognizeAsync(turnContext, additionalProperties).ConfigureAwait(false);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(3, telemetryClient.Invocations.Count);
            Assert.Equal("LuisResult", telemetryClient.Invocations[0].Arguments[0].ToString());
            Assert.True(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("MyImportantProperty"));
            Assert.Equal("myImportantValue", ((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1])["MyImportantProperty"]);
            Assert.True(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("test"));
            Assert.Equal("testvalue", ((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1])["test"]);
            Assert.True(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("foo"));
            Assert.Equal("foovalue", ((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1])["foo"]);
            Assert.Equal("MySecondEvent", telemetryClient.Invocations[1].Arguments[0].ToString());
            Assert.True(((Dictionary <string, string>)telemetryClient.Invocations[1].Arguments[1]).ContainsKey("MyImportantProperty2"));
            Assert.Equal("myImportantValue2", ((Dictionary <string, string>)telemetryClient.Invocations[1].Arguments[1])["MyImportantProperty2"]);
        }
        public ControlAzureResourceRecognizer(IConfiguration configuration)
        {
            var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId"]) && !string.IsNullOrEmpty(configuration["LuisAPIKey"]) && !string.IsNullOrEmpty(configuration["LuisAPIHostName"]);

            if (luisIsConfigured)
            {
                var luisApplication = new LuisApplication(
                    configuration["LuisAppId"],
                    configuration["LuisAPIKey"],
                    "https://" + configuration["LuisAPIHostName"]);

                LuisRecognizerOptions options = new LuisRecognizerOptionsV3(luisApplication);
                _recognizer = new LuisRecognizer(options);
            }
        }
Exemple #17
0
        public LuisService(IConfiguration configuration)
        {
            var luisApplication = new LuisApplication(
                configuration["LuisAppId"],
                configuration["LuisApiKey"],
                configuration["LuisHostName"]
                );
            var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
            {
                PredictionOptions = new Microsoft.Bot.Builder.AI.LuisV3.LuisPredictionOptions()
                {
                    IncludeInstanceData = true
                }
            };

            _luisRecognizer = new LuisRecognizer(recognizerOptions);
        }
Exemple #18
0
        public static async Task <BookingDetails> ExecuteLuisQuery(IBotTelemetryClient telemetryClient, IConfiguration configuration, ILogger logger, ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var bookingDetails = new BookingDetails();

            try
            {
                // Create the LUIS settings from configuration.
                var luisApplication = new LuisApplication(
                    configuration["LuisAppId"],
                    configuration["LuisAPIKey"],
                    "https://" + configuration["LuisAPIHostName"]
                    );


                // Set the recognizer options depending on which endpoint version you want to use.
                // More details can be found in https://docs.microsoft.com/en-gb/azure/cognitive-services/luis/luis-migration-api-v3
                var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
                {
                    TelemetryClient = telemetryClient,
                };

                var recognizer = new LuisRecognizer(recognizerOptions);

                // The actual call to LUIS
                var recognizerResult = await recognizer.RecognizeAsync(turnContext, cancellationToken);

                var(intent, score) = recognizerResult.GetTopScoringIntent();
                if (intent == "Book_flight")
                {
                    // We need to get the result from the LUIS JSON which at every level returns an array.
                    bookingDetails.Destination = recognizerResult.Entities["To"]?.FirstOrDefault()?["Airport"]?.FirstOrDefault()?.FirstOrDefault()?.ToString();
                    bookingDetails.Origin      = recognizerResult.Entities["From"]?.FirstOrDefault()?["Airport"]?.FirstOrDefault()?.FirstOrDefault()?.ToString();

                    // This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part.
                    // TIMEX is a format that represents DateTime expressions that include some ambiguity. e.g. missing a Year.
                    bookingDetails.TravelDate = recognizerResult.Entities["datetime"]?.FirstOrDefault()?["timex"]?.FirstOrDefault()?.ToString().Split('T')[0];
                }
            }
            catch (Exception e)
            {
                logger.LogWarning($"LUIS Exception: {e.Message} Check your LUIS configuration.");
            }

            return(bookingDetails);
        }
Exemple #19
0
        public BotServices(IConfiguration configuration)
        {  //Read the setting for cognitive services (LUIS, QnA) from the appseting, json
            var luisApplication = new LuisApplication(
                configuration["LuisAppId"],
                configuration["LuisAPIkey"],
                $"https://{configuration["LuisAPIHostName"]}.api.cognitive.microsoft.com");

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

            Dispatch = new LuisRecognizer(recognizerOptions);
        }
Exemple #20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var luisApplication = new LuisApplication(
                configuration["LuisAppId"],
                configuration["LuisAPIKey"],
                configuration["LuisAPIHostName"]);
            var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
            {
                PredictionOptions = new Microsoft.Bot.Builder.AI.LuisV3.LuisPredictionOptions
                {
                    IncludeInstanceData = true,
                }
            };

            var recognizer = new LuisRecognizer(recognizerOptions);

            services.AddSingleton(recognizer);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Create the Bot Framework Adapter with error handling enabled.
            services.AddSingleton <IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();

            // Create the storage we'll be using for User and Conversation state. (Memory is great for testing purposes.)
            services.AddSingleton <IStorage, MemoryStorage>();

            // Create the User state. (Used in this bot's Dialog implementation.)
            services.AddSingleton <UserState>();

            // Create the Conversation state. (Used by the Dialog system itself.)
            services.AddSingleton <ConversationState>();

            // Register LUIS recognizer
            services.AddSingleton <FlightBookingRecognizer>();

            // Register the BookingDialog.
            services.AddSingleton <BookingDialog>();

            // The MainDialog that will be run by the bot.
            services.AddSingleton <MainDialog>();

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            services.AddTransient <IBot, MainBot <MainDialog> >();
        }
Exemple #21
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);
        }
        private HttpClientHandler GetMockedClient(string utterance, LuisRecognizerOptionsV3 recognizer)
        {
            HttpClientHandler client = null;

            if (utterance != null)
            {
                var response = ResponsePath(utterance, recognizer);
                if (File.Exists(response))
                {
                    var handler = new MockHttpMessageHandler();
                    handler
                    .When(recognizer.Application.Endpoint + "*")
                    .WithPartialContent(utterance)
                    .Respond("application/json", File.OpenRead(response));
                    client = new MockedHttpClientHandler(handler.ToHttpClient());
                }
            }

            return(client);
        }
Exemple #23
0
        public FlightBookingRecognizer(IConfiguration configuration)
        {
            var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId1"]) && !string.IsNullOrEmpty(configuration["LuisAPIKey1"]) && !string.IsNullOrEmpty(configuration["LuisAPIHostName1"]);

            if (luisIsConfigured)
            {
                var luisApplication = new LuisApplication(
                    configuration["LuisAppId1"],
                    configuration["LuisAPIKey1"],
                    "https://" + configuration["LuisAPIHostName1"]);
                var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
                {
                    PredictionOptions = new Bot.Builder.AI.LuisV3.LuisPredictionOptions
                    {
                        IncludeInstanceData = true,
                    }
                };

                _recognizer = new LuisRecognizer(recognizerOptions);
            }
        }
Exemple #24
0
        public object Load(JToken obj, JsonSerializer serializer, Type type)
        {
            // If the luis service info is inlined with the recognizer, load it here for
            // simpler json format
            if (obj["applicationId"]?.Type == JTokenType.String)
            {
                var luisApplication = obj.ToObject <LuisApplication>();
                luisApplication.ApplicationId = configuration.LoadSetting(luisApplication.ApplicationId);
                luisApplication.Endpoint      = configuration.LoadSetting(luisApplication.Endpoint);
                luisApplication.EndpointKey   = configuration.LoadSetting(luisApplication.EndpointKey);
                var options = new LuisRecognizerOptionsV3(luisApplication);
                if (obj["predictionOptions"] != null)
                {
                    options.PredictionOptions = obj["predictionOptions"].ToObject <AI.LuisV3.LuisPredictionOptions>();
                }

                return(new LuisRecognizer(options));
            }

            // Else, just assume it is the verbose structure with LuisService as inner object
            return(obj.ToObject <LuisRecognizer>(serializer));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="LuisHelper"/> class.
        /// </summary>
        /// <param name="configuration">configuration.</param>
        public LuisHelper(IConfiguration configuration)
        {
            var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId"]) && !string.IsNullOrEmpty(configuration["LuisAPIKey"]) && !string.IsNullOrEmpty(configuration["LuisAPIHostName"]);

            if (luisIsConfigured)
            {
                var luisApplication = new LuisApplication(
                    configuration["LuisAppId"],
                    configuration["LuisAPIKey"],
                    "https://" + configuration["LuisAPIHostName"]);

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

                this.recognizer = new LuisRecognizer(recognizerOptions);
            }
        }
Exemple #26
0
        public QuestionRecognizer(IConfiguration configuration)
        {
            var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId"]) && !string.IsNullOrEmpty(configuration["LuisEndpointKey"]) && !string.IsNullOrEmpty(configuration["LuisEndpointKey"]);

            if (luisIsConfigured)
            {
                var luisApplication = new LuisApplication(
                    configuration["LuisAppId"],
                    configuration["LuisEndpointKey"],
                    configuration["LuisEndpoint"]);

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

                _recognizer = new LuisRecognizer(recognizerOptions);
            }
        }
        public HotelRecognizer(IOptions<LuisSettings> settings)
        {
            var configuration = settings.Value;
            
            var luisIsConfigured = !string.IsNullOrEmpty(configuration.LuisAppId) && !string.IsNullOrEmpty(configuration.LuisAPIKey) && !string.IsNullOrEmpty(configuration.LuisAPIHostName);

            if (!luisIsConfigured) return;
            
            var luisApplication = new LuisApplication(
                configuration.LuisAppId,
                configuration.LuisAPIKey,
                configuration.LuisAPIHostName);

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

            _recognizer = new LuisRecognizer(recognizerOptions);
        }
        public FlightBookingRecognizer(IConfiguration configuration)
        {
            var luisIsConfigured = !string.IsNullOrEmpty(configuration["5a26bc7d-62d6-4be9-8380-607e0bbb42df"]) && !string.IsNullOrEmpty(configuration["c82bd94d-9bb6-493e-aff0-1555bb579295"]) && !string.IsNullOrEmpty(configuration["chatbotupdate"]);

            if (luisIsConfigured)
            {
                var luisApplication = new LuisApplication(
                    configuration["LuisAppId"],
                    configuration["LuisAPIKey"],
                    "https://" + configuration["LuisAPIHostName"]);
                // Set the recognizer options depending on which endpoint version you want to use.
                // More details can be found in https://docs.microsoft.com/en-gb/azure/cognitive-services/luis/luis-migration-api-v3
                var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
                {
                    PredictionOptions = new Microsoft.Bot.Builder.AI.LuisV3.LuisPredictionOptions
                    {
                        IncludeInstanceData = true,
                    }
                };

                _recognizer = new LuisRecognizer(recognizerOptions);
            }
        }
Exemple #29
0
        private HttpClientHandler GetMockedClient(string utterance, LuisRecognizerOptionsV3 recognizer)
        {
            HttpClientHandler client = null;

            if (utterance != null)
            {
                var response = ResponsePath(utterance, recognizer);
                if (File.Exists(response))
                {
#pragma warning disable CA2000 // Dispose objects before losing scope (ownership of handler is passed to MockedHttpClientHandler, that object should dispose it)
                    var handler = new MockHttpMessageHandler();
#pragma warning restore CA2000 // Dispose objects before losing scope
                    handler
                    .When(recognizer.Application.Endpoint + "*")
                    .WithPartialContent(utterance)
#pragma warning disable CA2000 // Dispose objects before losing scope (ownership of the File.OpenRead() stream is passed to MockedHttpClientHandler, that object should dispose it)
                    .Respond("application/json", File.OpenRead(response));
#pragma warning restore CA2000 // Dispose objects before losing scope
                    client = new MockedHttpClientHandler(handler.ToHttpClient());
                }
            }

            return(client);
        }
        private string ResponsePath(string utterance, LuisRecognizerOptionsV3 recognizer)
        {
            var hash = utterance.StableHash();

            if (recognizer.ExternalEntityRecognizer != null)
            {
                hash ^= "external".StableHash();
            }

            if (recognizer.IncludeAPIResults)
            {
                hash ^= "api".StableHash();
            }

            if (recognizer.LogPersonalInformation)
            {
                hash ^= "personal".StableHash();
            }

            var options = recognizer.PredictionOptions;

            if (options.DynamicLists != null)
            {
                foreach (var dynamicList in options.DynamicLists)
                {
                    hash ^= dynamicList.Entity.StableHash();
                    foreach (var choices in dynamicList.List)
                    {
                        hash ^= choices.CanonicalForm.StableHash();
                        foreach (var synonym in choices.Synonyms)
                        {
                            hash ^= synonym.StableHash();
                        }
                    }
                }
            }

            if (options.ExternalEntities != null)
            {
                foreach (var external in options.ExternalEntities)
                {
                    hash ^= external.Entity.StableHash();
                    hash ^= external.Start.ToString(CultureInfo.InvariantCulture).StableHash();
                    hash ^= external.Length.ToString(CultureInfo.InvariantCulture).StableHash();
                }
            }

            if (options.IncludeAllIntents)
            {
                hash ^= "all".StableHash();
            }

            if (options.IncludeInstanceData)
            {
                hash ^= "instance".StableHash();
            }

            if (options.Log ?? false)
            {
                hash ^= "log".StableHash();
            }

            if (options.PreferExternalEntities)
            {
                hash ^= "prefer".StableHash();
            }

            if (options.Slot != null)
            {
                hash ^= options.Slot.StableHash();
            }

            if (options.Version != null)
            {
                hash ^= options.Version.StableHash();
            }

            return(Path.Combine(_responseDir, $"{hash}.json"));
        }