/// <summary> /// Initializes a new instance of the <see cref="TelemetryLuisRecognizer"/> class. /// </summary> /// <param name="application">The LUIS application to use to recognize text.</param> /// <param name="predictionOptions">The LUIS prediction options to use.</param> /// <param name="includeApiResults">TRUE to include raw LUIS API response.</param> /// <param name="logOriginalMessage">TRUE to include original user message.</param> /// <param name="logUserName">TRUE to include user name.</param> public TelemetryLuisRecognizer(LuisApplication application, LuisPredictionOptions predictionOptions = null, bool includeApiResults = false, bool logOriginalMessage = false, bool logUserName = false) : base(application, predictionOptions, includeApiResults) { _luisApplication = application; LogOriginalMessage = logOriginalMessage; LogUsername = logUserName; }
public async Task ShouldOverridePredictionOptionsIfProvided(bool?includeAllIntents, double?timezoneOffset, bool?spellCheck, string bingSpellCheckSubscriptionKey, bool?log, bool?staging) { // Arrange // Initialize options with non default values so we can assert they have been overriden. var constructorOptions = new LuisPredictionOptions() { IncludeAllIntents = true, TimezoneOffset = 42, SpellCheck = true, BingSpellCheckSubscriptionKey = "Fake2806-EC0A-472D-95B7-A7132D159E03", Log = false, Staging = true, }; // Create overriden options for call var overridenOptions = new LuisPredictionOptions() { IncludeAllIntents = includeAllIntents, TimezoneOffset = timezoneOffset, SpellCheck = spellCheck, BingSpellCheckSubscriptionKey = bingSpellCheckSubscriptionKey, Log = log, Staging = staging, }; // Create combined options for assertion taking the test case value if not null or the constructor value if not null. var expectedOptions = new LuisPredictionOptions() { IncludeAllIntents = includeAllIntents ?? constructorOptions.IncludeAllIntents, TimezoneOffset = timezoneOffset ?? constructorOptions.TimezoneOffset, SpellCheck = spellCheck ?? constructorOptions.SpellCheck, BingSpellCheckSubscriptionKey = bingSpellCheckSubscriptionKey ?? constructorOptions.BingSpellCheckSubscriptionKey, Log = log ?? constructorOptions.Log, Staging = staging ?? constructorOptions.Staging, LogPersonalInformation = constructorOptions.LogPersonalInformation, }; var sut = new LuisRecognizer(_luisApp, constructorOptions, clientHandler: _mockHttpClientHandler); // Act/Assert RecognizeAsync override await sut.RecognizeAsync(BuildTurnContextForUtterance("hi"), overridenOptions, CancellationToken.None); AssertLuisRequest(_mockHttpClientHandler.RequestMessage, expectedOptions); // these values can't be overriden and should stay unchanged. Assert.Equal(constructorOptions.TelemetryClient, sut.TelemetryClient); Assert.Equal(constructorOptions.LogPersonalInformation, sut.LogPersonalInformation); // Act/Assert RecognizeAsync<T> override await sut.RecognizeAsync <Contoso_App>(BuildTurnContextForUtterance("hi"), overridenOptions, CancellationToken.None); AssertLuisRequest(_mockHttpClientHandler.RequestMessage, expectedOptions); // these values can't be overriden and should stay unchanged. Assert.Equal(constructorOptions.TelemetryClient, sut.TelemetryClient); Assert.Equal(constructorOptions.LogPersonalInformation, sut.LogPersonalInformation); }
public async Task Telemetry_OverrideOnLogAsync() { // 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/v2.0/apps/b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q="; var clientHandler = new EmptyLuisResponseClientHandler(); var luisApp = new LuisApplication(endpoint); var telemetryClient = new Mock <IBotTelemetryClient>(); var adapter = new NullAdapter(); var options = new LuisPredictionOptions { TelemetryClient = telemetryClient.Object, LogPersonalInformation = false, }; 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 opts = new LuisRecognizerOptionsV2(luisApp) { TelemetryClient = telemetryClient.Object, LogPersonalInformation = false, }; var turnContext = new TurnContext(adapter, activity); var recognizer = new LuisRecognizer(opts, clientHandler); // Act var additionalProperties = new Dictionary <string, string> { { "test", "testvalue" }, { "foo", "foovalue" }, }; var result = await recognizer.RecognizeAsync(turnContext, additionalProperties).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")); }
private static void AssertLuisRequest(HttpRequestMessage httpRequestForLuis, LuisPredictionOptions expectedOptions) { var queryStringParameters = HttpUtility.ParseQueryString(httpRequestForLuis.RequestUri.Query); Assert.Equal(expectedOptions.BingSpellCheckSubscriptionKey?.ToString(CultureInfo.InvariantCulture), queryStringParameters["bing-spell-check-subscription-key"]); Assert.Equal(expectedOptions.SpellCheck?.ToString(CultureInfo.InvariantCulture).ToLower(), queryStringParameters["spellCheck"]); Assert.Equal(expectedOptions.IncludeAllIntents?.ToString(CultureInfo.InvariantCulture).ToLower(), queryStringParameters["verbose"]); Assert.Equal(expectedOptions.Staging?.ToString(CultureInfo.InvariantCulture).ToLower(), queryStringParameters["staging"]); Assert.Equal(expectedOptions.Log?.ToString(CultureInfo.InvariantCulture).ToLower(), queryStringParameters["log"]); }
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, SpellCheck = string.IsNullOrEmpty(settings.BingSpellCheckSubscriptionKey) ? false : true, BingSpellCheckSubscriptionKey = settings.BingSpellCheckSubscriptionKey }; 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 void LuisRecognizer_Timeout() { var endpoint = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q="; var optionsWithTimeout = new LuisPredictionOptions() { Timeout = 300, }; var expectedTimeout = 300; var recognizerWithTimeout = new LuisRecognizer(endpoint, optionsWithTimeout); Assert.IsNotNull(recognizerWithTimeout); Assert.AreEqual(expectedTimeout, LuisRecognizer.DefaultHttpClient.Timeout.Milliseconds); }
public FabrikamServiceBot(FabrikamServiceBotAccessors accessors) { _accessors = accessors ?? throw new System.ArgumentNullException(nameof(accessors)); //get the luis app id & key var MicrosoftLuisAppId = ConfigurationManager.AppSettings["MicrosoftLuisAppId"]; var MicrosoftLuisKey = ConfigurationManager.AppSettings["MicrosoftLuisKey"]; var LuisApp = new LuisApplication(ConfigurationManager.AppSettings["MicrosoftLuisAppId"], ConfigurationManager.AppSettings["MicrosoftLuisKey"], ConfigurationManager.AppSettings["MicrosoftLuisEndPoint"]); var LuisOptions = new LuisPredictionOptions { IncludeAllIntents = true, }; luisRecognizer = new LuisRecognizer(LuisApp, LuisOptions, true); }
private Dictionary <string, LuisRecognizer> BuildDictionary(IBotTelemetryClient botTelemetryClient = null) { Dictionary <string, LuisRecognizer> result = new Dictionary <string, LuisRecognizer>(); foreach (LuisApp app in config.LuisApplications) { var luis = new LuisApplication(app.AppId, app.AuthoringKey, app.Endpoint); LuisPredictionOptions luisPredictionOptions = null; LuisRecognizer recognizer = null; bool needsPredictionOptions = false; if ((!string.IsNullOrEmpty(config.BingSpellCheckSubscriptionKey)) || (config.EnableLuisTelemetry)) { needsPredictionOptions = true; } if (needsPredictionOptions) { luisPredictionOptions = new LuisPredictionOptions(); if (config.EnableLuisTelemetry) { luisPredictionOptions.TelemetryClient = botTelemetryClient; luisPredictionOptions.Log = true; luisPredictionOptions.LogPersonalInformation = true; } if (!string.IsNullOrEmpty(config.BingSpellCheckSubscriptionKey)) { luisPredictionOptions.BingSpellCheckSubscriptionKey = config.BingSpellCheckSubscriptionKey; luisPredictionOptions.SpellCheck = true; luisPredictionOptions.IncludeAllIntents = true; } recognizer = new LuisRecognizer(luis, luisPredictionOptions); } else { recognizer = new LuisRecognizer(luis); } result.Add(app.Name, recognizer); } return(result); }
public BotServices(BotSettings settings) { foreach (var pair in settings.CognitiveModels) { var set = new CognitiveModelSet(); var language = pair.Key; var config = pair.Value; var telemetryClient = new BotTelemetryClient(new TelemetryClient(settings.AppInsights)); var luisOptions = new LuisPredictionOptions() { TelemetryClient = telemetryClient, LogPersonalInformation = true, }; 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)); } } foreach (var kb in config.Knowledgebases) { var qnaEndpoint = new QnAMakerEndpoint() { KnowledgeBaseId = kb.KbId, EndpointKey = kb.EndpointKey, Host = kb.Hostname, }; var qnaMaker = new QnAMaker(qnaEndpoint, null, null, telemetryClient: telemetryClient, logPersonalInformation: true); set.QnAServices.Add(kb.Id, qnaMaker); } CognitiveModelSets.Add(language, set); } }
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"] ); var luisPredictionOptions = new LuisPredictionOptions() { TelemetryClient = telemetryClient, }; var recognizer = new LuisRecognizer(luisApplication, luisPredictionOptions); // 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); }
/// <summary> /// Generate the prediction options. /// </summary> /// <returns>The prediction options.</returns> public LuisPredictionOptions GetPredictOpts() { if (string.IsNullOrWhiteSpace(SpellCheckerKey)) { return new LuisPredictionOptions() { IncludeAllIntents = true } } ; LuisPredictionOptions lo = new LuisPredictionOptions { SpellCheck = true, BingSpellCheckSubscriptionKey = SpellCheckerKey, IncludeAllIntents = true }; return(lo); } }
public async Task LuisPredictionOptionsAreUsedInTheRequest(bool?includeAllIntents, double?timezoneOffset, bool?spellCheck, string bingSpellCheckSubscriptionKey, bool?log, bool?staging) { // Arrange var expectedOptions = new LuisPredictionOptions() { IncludeAllIntents = includeAllIntents, TimezoneOffset = timezoneOffset, SpellCheck = spellCheck, BingSpellCheckSubscriptionKey = bingSpellCheckSubscriptionKey, Log = log ?? true, Staging = staging, }; var sut = new LuisRecognizer(_luisApp, expectedOptions, clientHandler: _mockHttpClientHandler); // Act await sut.RecognizeAsync(BuildTurnContextForUtterance("hi"), CancellationToken.None); // Assert AssertLuisRequest(_mockHttpClientHandler.RequestMessage, expectedOptions); }
private LuisRecognizer ReadLuisRecognizer(IConfiguration configuration) { try { var services = configuration.GetSection("BotServices"); var application = new LuisApplication(services.GetValue <string>("LuisAppId"), services.GetValue <string>("LuisAuthoringKey"), "https://" + services.GetValue <string>("LuisHostName")); var predictions = new LuisPredictionOptions { IncludeAllIntents = true, IncludeInstanceData = true }; var recognizer = new LuisRecognizer(application, predictions, true); return(recognizer); } catch (Exception) { return(null); } }
private IRecognizer GetLuisRecognizer(bool verbose = false, LuisPredictionOptions options = null) { var luisAppId = "ab48996d-abe2-4785-8eff-f18d15fc3560"; // Any value, it won't be used. var subscriptionKey = "cc7bbcc0-3715-44f0-b7c9-d8fee333dce1"; // Any value, it won't be used. var endpoint = "https://westus.api.cognitive.microsoft.com"; var requestUrl = $"{endpoint}/luis/v2.0/apps/{luisAppId}"; var messageHandler = new MockHttpMessageHandler(); messageHandler.When(requestUrl).WithPartialContent("hello") .Respond("application/json", GetResponse("HiIntent.json")); messageHandler.When(requestUrl).WithPartialContent("bye") .Respond("application/json", GetResponse("ByeIntent.json")); messageHandler.When(requestUrl).WithPartialContent("cancel") .Respond("application/json", GetResponse("CancelIntent.json")); messageHandler.When(requestUrl).WithPartialContent("help") .Respond("application/json", GetResponse("HelpIntent.json")); var luisApp = new LuisApplication(luisAppId, subscriptionKey, endpoint); return(new LuisRecognizer(luisApp, options, verbose, new MockedHttpClientHandler(messageHandler.ToHttpClient()))); }
public void ConfigureServices(IServiceCollection services) { // Set up the service configuration var builder = new ConfigurationBuilder() .SetBasePath(ContentRootPath) .AddJsonFile("appsettings.json") .AddEnvironmentVariables(); var configuration = builder.Build(); services.AddSingleton(configuration); services.AddSingleton(sp => { // get these values from luis.ai // i've left the endpoint in so you have an example of an url that works // because all luis client libs seem to vary var luisApp = new LuisApplication( applicationId: "", endpointKey: "", endpoint: "https://westus.api.cognitive.microsoft.com"); var luisPredictionOptions = new LuisPredictionOptions { IncludeAllIntents = true, }; return(new LuisRecognizer( application: luisApp, predictionOptions: luisPredictionOptions, includeApiResults: true)); }); // Add your SimpleBot to your application services.AddBot <SimpleBot>(options => { options.CredentialProvider = new ConfigurationCredentialProvider(configuration); }); }
private IRecognizer GetLuisRecognizer(MockedHttpClientHandler httpClientHandler, LuisPredictionOptions options = null) { var luisApp = new LuisApplication(AppId, Key, Endpoint); return(new LuisRecognizer(luisApp, new LuisRecognizerOptions { HttpClient = httpClientHandler }, options)); }
public TelemetryOverrideRecognizer(IBotTelemetryClient telemetryClient, LuisApplication application, LuisPredictionOptions predictionOptions = null, bool includeApiResults = false, bool logPersonalInformation = false, HttpClientHandler clientHandler = null) : base(application, predictionOptions, includeApiResults, clientHandler) { LogPersonalInformation = logPersonalInformation; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Create the Bot Framework Adapter. services.AddSingleton <IBotFrameworkHttpAdapter, AdapterWithErrorHandler>(); // Create the bot as a transient. In this case the ASP Controller is expecting an IBot. services.AddTransient <IBot, PictureBot>(); //init bot services.AddBot <PictureBot>(options => { //read appsettings.json var secretKey = Configuration.GetSection("MicrosoftAppId")?.Value; var botFilePath = Configuration.GetSection("MicrosoftAppPassword")?.Value; options.CredentialProvider = new SimpleCredentialProvider(secretKey, botFilePath); }); services.AddSingleton <PictureBotAccessors>(sp => { var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value; if (options == null) { throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the state accessors"); } //read Cosmos DB settings from appsettings.json CosmosDbStorage _myStorage = new CosmosDbStorage(new CosmosDbStorageOptions { AuthKey = Configuration.GetSection("CosmosDB").GetValue <string>("Key"), CollectionId = Configuration.GetSection("CosmosDB").GetValue <string>("CollectionName"), CosmosDBEndpoint = new Uri(Configuration.GetSection("CosmosDB").GetValue <string>("EndpointURI")), DatabaseId = Configuration.GetSection("CosmosDB").GetValue <string>("DatabaseName"), }); var conversationState = new ConversationState(_myStorage); var userState = new UserState(_myStorage); // Create the custom state accessor. // State accessors enable other components to read and write individual properties of state. var accessors = new PictureBotAccessors(conversationState, userState) { PictureState = conversationState.CreateProperty <PictureState>(PictureBotAccessors.PictureStateName), DialogStateAccessor = conversationState.CreateProperty <DialogState>("DialogState"), }; return(accessors); }); // Create and register a LUIS recognizer. services.AddSingleton(sp => { // Get LUIS information var luisApp = new LuisApplication( "XXX", "XXX", "https://XXXX.api.cognitive.microsoft.com/"); // Specify LUIS options. These may vary for your bot. var luisPredictionOptions = new LuisPredictionOptions { IncludeAllIntents = true, }; // Create the recognizer var recognizer = new LuisRecognizer(luisApp, luisPredictionOptions, true, null); return(recognizer); }); }
private IRecognizer GetLuisRecognizer(bool verbose = false, LuisPredictionOptions luisOptions = null) { var app = new LuisApplication(appId, subscriptionKey, region); return new LuisRecognizer(app, luisOptions, verbose); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> specifies the contract for a collection of service descriptors.</param> /// <seealso cref="IStatePropertyAccessor{T}"/> /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection"/> /// <seealso cref="https://docs.microsoft.com/en-us/azure/bot-service/bot-service-manage-channels?view=azure-bot-service-4.0"/> public void ConfigureServices(IServiceCollection services) { var secretKey = Configuration.GetSection("botFileSecret")?.Value; var botFilePath = Configuration.GetSection("botFilePath")?.Value; if (!File.Exists(botFilePath)) { throw new FileNotFoundException($"The .bot configuration file was not found. botFilePath: {botFilePath}"); } // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection. BotConfiguration botConfig = null; try { botConfig = BotConfiguration.Load(botFilePath, secretKey); } catch { var msg = @"Error reading bot file. Please ensure you have valid botFilePath and botFileSecret set for your environment. - You can find the botFilePath and botFileSecret in the Azure App Service application settings. - If you are running this bot locally, consider adding a appsettings.json file with botFilePath and botFileSecret. - See https://aka.ms/about-bot-file to learn more about .bot file its use and bot configuration. "; throw new InvalidOperationException(msg); } services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot configuration file could not be loaded. botFilePath: {botFilePath}")); // Retrieve current endpoint. var environment = _isProduction ? "production" : "development"; var service = botConfig.Services.FirstOrDefault(s => s.Type == "endpoint" && s.Name == environment); if (service == null && _isProduction) { // Attempt to load development environment service = botConfig.Services.Where(s => s.Type == "endpoint" && s.Name == "development").FirstOrDefault(); } if (!(service is EndpointService endpointService)) { throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); } // Memory Storage is for local bot debugging only. When the bot // is restarted, everything stored in memory will be gone. IStorage dataStore = new MemoryStorage(); // For production bots use the Azure Blob or // Azure CosmosDB storage providers. For the Azure // based storage providers, add the Microsoft.Bot.Builder.Azure // Nuget package to your solution. That package is found at: // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/ // Un-comment the following lines to use Azure Blob Storage // // Storage configuration name or ID from the .bot file. // const string StorageConfigurationId = "<STORAGE-NAME-OR-ID-FROM-BOT-FILE>"; // var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId); // if (!(blobConfig is BlobStorageService blobStorageConfig)) // { // throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'."); // } // // Default container name. // const string DefaultBotContainer = "<DEFAULT-CONTAINER>"; // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container; // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer); // Create and add conversation state. var conversationState = new ConversationState(dataStore); services.AddSingleton(conversationState); services.AddBot <EchoBotBot>(options => { options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); // Catches any errors that occur during a conversation turn and logs them to currently // configured ILogger. ILogger logger = _loggerFactory.CreateLogger <EchoBotBot>(); options.OnTurnError = async(context, exception) => { logger.LogError($"Exception caught : {exception}"); await context.SendActivityAsync($"please provide precise input"); }; }); services.AddSingleton(sp => { // Set up Luis var luisApp = new LuisApplication( applicationId: "591a9762-a049-408e-af99-d3eaf653977b", endpointKey: "f598e3e4481646029781ebdfd9a7bb4f", endpoint: "https://westus.api.cognitive.microsoft.com/"); // Specify LUIS options. These may vary for your bot. var luisPredictionOptions = new LuisPredictionOptions { IncludeAllIntents = true, }; return(new LuisRecognizer( application: luisApp, predictionOptions: luisPredictionOptions, includeApiResults: true)); }); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> specifies the contract for a collection of service descriptors.</param> /// <seealso cref="IStatePropertyAccessor{T}"/> /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection"/> /// <seealso cref="https://docs.microsoft.com/en-us/azure/bot-service/bot-service-manage-channels?view=azure-bot-service-4.0"/> public void ConfigureServices(IServiceCollection services) { services.AddBot <PictureBot>(options => { var secretKey = Configuration.GetSection("botFileSecret")?.Value; var botFilePath = Configuration.GetSection("botFilePath")?.Value; // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection. var botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", secretKey); services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded. ({botConfig})")); // Retrieve current endpoint. var environment = _isProduction ? "production" : "development"; var service = botConfig.Services.Where(s => s.Type == "endpoint" && s.Name == environment).FirstOrDefault(); if (!(service is EndpointService endpointService)) { throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); } options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); // Creates a logger for the application to use. ILogger logger = _loggerFactory.CreateLogger <PictureBot>(); // Catches any errors that occur during a conversation turn and logs them. options.OnTurnError = async(context, exception) => { logger.LogError($"Exception caught : {exception}"); await context.SendActivityAsync("Sorry, it looks like something went wrong."); }; // The Memory Storage used here is for local bot debugging only. When the bot // is restarted, everything stored in memory will be gone. IStorage dataStore = new MemoryStorage(); // For production bots use the Azure Blob or // Azure CosmosDB storage providers. For the Azure // based storage providers, add the Microsoft.Bot.Builder.Azure // Nuget package to your solution. That package is found at: // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/ // Uncomment the following lines to use Azure Blob Storage // //Storage configuration name or ID from the .bot file. // const string StorageConfigurationId = "<STORAGE-NAME-OR-ID-FROM-BOT-FILE>"; // var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId); // if (!(blobConfig is BlobStorageService blobStorageConfig)) // { // throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'."); // } // // Default container name. // const string DefaultBotContainer = "botstate"; // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container; // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer); // Create Conversation State object. // The Conversation State object is where we persist anything at the conversation-scope. var conversationState = new ConversationState(dataStore); options.State.Add(conversationState); var middleware = options.Middleware; // Add middleware below with "middleware.Add(...." // Add Regex below middleware.Add(new RegExpRecognizerMiddleware() .AddIntent("search", new Regex("search picture(?:s)*(.*)|search pic(?:s)*(.*)", RegexOptions.IgnoreCase)) .AddIntent("share", new Regex("share picture(?:s)*(.*)|share pic(?:s)*(.*)", RegexOptions.IgnoreCase)) .AddIntent("order", new Regex("order picture(?:s)*(.*)|order print(?:s)*(.*)|order pic(?:s)*(.*)", RegexOptions.IgnoreCase)) .AddIntent("help", new Regex("help(.*)", RegexOptions.IgnoreCase))); }); // Create and register state accesssors. // Acessors created here are passed into the IBot-derived class on every turn. services.AddSingleton <PictureBotAccessors>(sp => { var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value; if (options == null) { throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the state accessors"); } var conversationState = options.State.OfType <ConversationState>().FirstOrDefault(); if (conversationState == null) { throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors."); } // Create the custom state accessor. // State accessors enable other components to read and write individual properties of state. var accessors = new PictureBotAccessors(conversationState) { PictureState = conversationState.CreateProperty <PictureState>(PictureBotAccessors.PictureStateName), DialogStateAccessor = conversationState.CreateProperty <DialogState>("DialogState"), }; return(accessors); }); // Create and register a LUIS recognizer. services.AddSingleton(sp => { // Get LUIS information var luisApp = new LuisApplication("LuisAppId", "LuisSubscriptionKey", "LuisEndpoint"); // Specify LUIS options. These may vary for your bot. var luisPredictionOptions = new LuisPredictionOptions { IncludeAllIntents = true, }; // Create the recognizer var recognizer = new LuisRecognizer(luisApp, luisPredictionOptions, true, null); return(recognizer); }); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> specifies the contract for a collection of service descriptors.</param> /// <seealso cref="IStatePropertyAccessor{T}"/> /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection"/> /// <seealso cref="https://docs.microsoft.com/en-us/azure/bot-service/bot-service-manage-channels?view=azure-bot-service-4.0"/> public void ConfigureServices(IServiceCollection services) { //The original example couples much of bot init into a single anonymous method, //but here it is split up for readability and to resolve race conditions //Retrieve the secretKey and botFilePath from the app configuration var secretKey = Configuration.GetSection("botFileSecret")?.Value; var botFilePath = Configuration.GetSection("botFilePath")?.Value; //Use BotConfiguration.Load to create an instance of BotConfiguration //based on the file path. Use as a default. //(Optional) - Throw an Exception if this is null //(Optional) - Add this to the services container as a singleton var botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", secretKey) ?? throw new InvalidOperationException("Error reading bot file. Please ensure you have valid botFilePath and botFileSecret set for your environment."); services.AddSingleton(botConfig); //Use the AddBot<T> extension to IServiceCollection to inject both //your bot and BotFrameworkOptions into the services collection services.AddBot <PictureBot>(options => { //Retrieve the endpoint for the given environment //You can use "FindServiceByNameOrId" and cast to EndpointService //(optional) - Throw an exception if it cannot be found var environment = _isProduction ? "production" : "development"; var endpointService = botConfig.FindServiceByNameOrId(environment) as EndpointService ?? throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); //Add a SimpleCredentialProvider to the options. //This is important for setting up the route that intercepts bot traffic options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); //Set up the datastore to hold conversation state data. //We will use a MemoryStorage for this example, but production apps //should always leverage Azure Blob or CosmosDB storage providers. //(Or roll your own!) IStorage dataStore = new MemoryStorage(); //Create the conversation state based on the datastore //and add it to the options. var conversationState = new ConversationState(dataStore); options.State.Add(conversationState); //Add the RegExpRecognizer as middleware. //Note that this is not included in the Microsoft.Bot.Builder libraries; //instead, it is part of this source distribution! var middleware = options.Middleware; middleware.Add(new RegExpRecognizerMiddleware() .AddIntent("SearchPics", new Regex("search picture(?:s)*(.*)|search pic(?:s)*(.*)", RegexOptions.IgnoreCase)) .AddIntent("Share", new Regex("share picture(?:s)*(.*)|share pic(?:s)*(.*)", RegexOptions.IgnoreCase)) .AddIntent("Order", new Regex("order picture(?:s)*(.*)|order print(?:s)*(.*)|order pic(?:s)*(.*)", RegexOptions.IgnoreCase)) .AddIntent("Help", new Regex("help(.*)", RegexOptions.IgnoreCase))); //Since we have external dependencies, something is bound to go wrong! //Setup a callback for OnTurnError to log errors and/or send data to the user options.OnTurnError = async(context, exception) => { _loggerFactory.CreateLogger <PictureBot>().LogError(exception, $"Uncaught exception in bot!"); await context.SendActivityAsync($"Sorry, it looks like something went wrong. Exception: {exception.Message}"); }; }); // Create and register state accesssors. // Acessors created here are passed into the IBot-derived class on every turn. services.AddSingleton <PictureBotAccessors>(sp => { //Retrieve the IOptions<BotFrameworkOptions> from the IServiceProvider //(It's added via AddBot!) var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value; if (options == null) { throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the state accessors"); } //Retrieve the ConversationState.It is the first state "OfType<ConversationState>()" var conversationState = options.State.OfType <ConversationState>().FirstOrDefault(); if (conversationState == null) { throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors."); } //return a new instance of PictureBotAccessors based on this conversationState. //You will have to also add additional properties for PictureState and DialogState //DialogState is provided by BotBuilder; PictureState is from this code base var accessors = new PictureBotAccessors(conversationState) { PictureState = conversationState.CreateProperty <PictureState>(PictureBotAccessors.PictureStateName), DialogStateAccessor = conversationState.CreateProperty <DialogState>(PictureBotAccessors.DialogStateName) }; return(accessors); }); //Add LUIS to the services collection //so we can access it at any point in our bot services.AddSingleton(sp => { var appId = Configuration.GetSection("LuisAppId").Value; var key = Configuration.GetSection("LuisKey").Value; var endpoint = Configuration.GetSection("LuisEndpoint").Value; //Create a new LuisApplication based on these credentials var luisApp = new LuisApplication(appId, key, endpoint); //Optionally you can also create LuisPredictionOptions which may vary from bot to bot var luisPredictionOptions = new LuisPredictionOptions { IncludeAllIntents = true, }; // Create and inject the recognizer var recognizer = new LuisRecognizer(luisApp, luisPredictionOptions, true, null); return(recognizer); }); }
private IRecognizer GetLuisRecognizer(MockHttpMessageHandler messageHandler, bool verbose = false, LuisPredictionOptions options = null) { var luisApp = new LuisApplication(_luisAppId, _subscriptionKey, _endpoint); return(new LuisRecognizer(luisApp, options, verbose, _mock ? new MockedHttpClientHandler(messageHandler.ToHttpClient()) : null)); }
public async Task <IActionResult> Post([FromBody] LUISDiscoveryRequest model) { // non-forced-to-disposal LUISDiscoveryResponse result = new LUISDiscoveryResponse { IsSucceded = true, ResultId = (int)LUISDiscoveryResponseEnum.Success }; // forced-to-disposal try { if (string.IsNullOrEmpty(model.Text)) { throw new BusinessException((int)LUISDiscoveryResponseEnum.FailedEmptyText); } // building service list Settings.LuisServices = new Dictionary <string, LuisRecognizer>(); foreach (LuisAppRegistration app in Settings.LuisAppRegistrations) { var luis = new LuisApplication(app.LuisAppId, app.LuisAuthoringKey, app.LuisEndpoint); LuisPredictionOptions luisPredictionOptions = null; LuisRecognizer recognizer = null; bool needsPredictionOptions = false; if ((!string.IsNullOrEmpty(model.BingSpellCheckSubscriptionKey)) || (model.EnableLuisTelemetry)) { needsPredictionOptions = true; } if (needsPredictionOptions) { luisPredictionOptions = new LuisPredictionOptions(); if (model.EnableLuisTelemetry) { luisPredictionOptions.TelemetryClient = telemetry; luisPredictionOptions.Log = true; luisPredictionOptions.LogPersonalInformation = true; } if (!string.IsNullOrEmpty(model.BingSpellCheckSubscriptionKey)) { luisPredictionOptions.BingSpellCheckSubscriptionKey = model.BingSpellCheckSubscriptionKey; luisPredictionOptions.SpellCheck = true; luisPredictionOptions.IncludeAllIntents = true; } recognizer = new LuisRecognizer(luis, luisPredictionOptions); } else { recognizer = new LuisRecognizer(luis); } Settings.LuisServices.Add(app.LuisName, recognizer); } foreach (LuisAppRegistration app in Settings.LuisAppRegistrations) { var storage = new MemoryStorage(); var conversationState = new ConversationState(storage); var adapter = new TestAdapter().Use(new AutoSaveStateMiddleware(conversationState)); IMessageActivity msg = Activity.CreateMessageActivity(); msg.Id = Guid.NewGuid().ToString(); msg.From = new ChannelAccount("sip: [email protected]", "bot"); msg.Recipient = new ChannelAccount("sip: [email protected]", "agent"); msg.Text = model.Text; msg.Locale = "en-us"; msg.ServiceUrl = "url"; msg.ChannelId = Guid.NewGuid().ToString(); msg.Conversation = new ConversationAccount(); msg.Type = ActivityTypes.Message; msg.Timestamp = DateTime.UtcNow; var context = new TurnContext(adapter, (Activity)msg); var recognizerResult = await Settings.LuisServices[app.LuisName].RecognizeAsync(context, new CancellationToken()); var topIntent = recognizerResult?.GetTopScoringIntent(); if (topIntent != null && topIntent.HasValue && topIntent.Value.score >= .90 && topIntent.Value.intent != "None") { result.LuisAppDetails.Add(new LuisAppDetail() { Name = app.LuisName, Intent = topIntent.Value.intent, Score = topIntent.Value.score }); } } } catch (Exception ex) { result.IsSucceded = false; if (ex is BusinessException) { result.ResultId = ((BusinessException)ex).ResultId; } else { result.ResultId = (int)LUISDiscoveryResponseEnum.Failed; this.logger.LogError($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}"); if (ex.InnerException != null) { this.logger.LogError($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}"); } } } finally { // clean forced-to-disposal GC.Collect(); } string message = EnumDescription.GetEnumDescription((LUISDiscoveryResponseEnum)result.ResultId); this.logger.LogInformation($">> Message information: {message}"); return((result.IsSucceded) ? (ActionResult) new OkObjectResult(new { result = result }) : (ActionResult) new BadRequestObjectResult(new { message = message })); }
private IRecognizer GetLuisRecognizer(MockedHttpClientHandler httpClientHandler, bool verbose = false, LuisPredictionOptions options = null) { var luisApp = new LuisApplication(AppId, Key, Endpoint); return(new LuisRecognizer(luisApp, options, verbose, httpClientHandler)); }
/// <summary> /// Initializes a new instance of the <see cref="BotServices"/> class. /// </summary> /// <param name="botConfiguration">A dictionary of named <see cref="LuisRecognizer"/> instances for usage within the bot.</param> public BotServices(BotConfiguration botConfiguration) { foreach (var service in botConfiguration.Services) { switch (service.Type) { case ServiceTypes.Luis: { var luis = (LuisService)service; if (luis == null) { throw new InvalidOperationException("The LUIS service is not configured correctly in your '.bot' file."); } var app = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint()); // Specify LUIS options. These may vary for your bot. var luisPredictionOptions = new LuisPredictionOptions { IncludeAllIntents = true, }; var recognizer = new LuisRecognizer(app, luisPredictionOptions, true); LuisServices.Add(luis.Name, recognizer); break; } //case ServiceTypes.QnA: // { // // Create a QnA Maker that is initialized and suitable for passing // // into the IBot-derived class (QnABot). // var qna = (QnAMakerService)service; // 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; // } } } }
/// <summary> /// Initializes a new instance of the <see cref="LuisRecognizerMiddleware"/> class. /// </summary> /// <param name="luisModel">The LUIS model to use to recognize text.</param> /// <param name="luisRecognizerOptions">The LUIS recognizer options to use.</param> /// <param name="luisOptions">The LUIS request options to use.</param> public LuisRecognizerMiddleware(LuisApplication luisModel, LuisPredictionOptions luisRecognizerOptions = null) { this.luisModel = luisModel ?? throw new ArgumentNullException(nameof(luisModel)); this.luisRecognizer = new LuisRecognizer(luisModel, luisRecognizerOptions, true); }
private IRecognizer GetLuisRecognizer(MockHttpMessageHandler messageHandler, bool verbose = false, LuisPredictionOptions options = null) { if (!_mock && _endpointKey == null) { Assert.Inconclusive("Cannot run live tests without an endpoint key."); } var luisApp = new LuisApplication(_appId, _endpointKey, _endpoint); return(new LuisRecognizer(luisApp, options, verbose, _mock ? new MockedHttpClientHandler(messageHandler.ToHttpClient()) : null)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Create the Bot Framework Adapter with error handling enabled. services.AddSingleton <IBotFrameworkHttpAdapter, AdapterWithErrorHandler>(); services.AddBot <PictureBot.Bots.PictureBot>(options => { var appId = Configuration.GetSection("MicrosoftAppId")?.Value; var appSecret = Configuration.GetSection("MicrosoftAppPassword")?.Value; options.CredentialProvider = new SimpleCredentialProvider(appId, appSecret); // Creates a logger for the application to use. ILogger logger = _loggerFactory.CreateLogger <PictureBot.Bots.PictureBot>(); // Catches any errors that occur during a conversation turn and logs them. options.OnTurnError = async(context, exception) => { logger.LogError($"Exception caught : {exception}"); await context.SendActivityAsync("Sorry, it looks like something went wrong."); }; // The Memory Storage used here is for local bot debugging only. When the bot // is restarted, everything stored in memory will be gone. //IStorage dataStore = new MemoryStorage(); var blobConnectionString = Configuration.GetSection("BlobStorageConnectionString")?.Value; var blobContainer = Configuration.GetSection("BlobStorageContainer")?.Value; IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobConnectionString, blobContainer); services.AddSingleton <IStorage>(dataStore); // For production bots use the Azure Blob or // Azure CosmosDB storage providers. For the Azure // based storage providers, add the Microsoft.Bot.Builder.Azure // Nuget package to your solution. That package is found at: // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/ // Uncomment the following lines to use Azure Blob Storage // //Storage configuration name or ID from the .bot file. // const string StorageConfigurationId = "<STORAGE-NAME-OR-ID-FROM-BOT-FILE>"; // var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId); // if (!(blobConfig is BlobStorageService blobStorageConfig)) // { // throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'."); // } // // Default container name. // const string DefaultBotContainer = "botstate"; // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container; // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer); var userState = new UserState(dataStore); var conversationState = new ConversationState(dataStore); // Create the User state. services.AddSingleton <UserState>(userState); // Create the Conversation state. services.AddSingleton <ConversationState>(conversationState); var middleware = options.Middleware; // Add Regex below middleware.Add(new RegExpRecognizerMiddleware() .AddIntent("search", new Regex("search picture(?:s)*(.*)|search pic(?:s)*(.*)", RegexOptions.IgnoreCase)) .AddIntent("share", new Regex("share picture(?:s)*(.*)|share pic(?:s)*(.*)", RegexOptions.IgnoreCase)) .AddIntent("order", new Regex("order picture(?:s)*(.*)|order print(?:s)*(.*)|order pic(?:s)*(.*)", RegexOptions.IgnoreCase)) .AddIntent("help", new Regex("help(.*)", RegexOptions.IgnoreCase))); }); // Create and register state accesssors. // Acessors created here are passed into the IBot-derived class on every turn. services.AddSingleton <PictureBotAccessors>(sp => { var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value; if (options == null) { throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the state accessors"); } var conversationState = services.BuildServiceProvider().GetService <ConversationState>(); if (conversationState == null) { throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors."); } // Create the custom state accessor. // State accessors enable other components to read and write individual properties of state. var accessors = new PictureBotAccessors(conversationState) { PictureState = conversationState.CreateProperty <PictureState>(PictureBotAccessors.PictureStateName), DialogStateAccessor = conversationState.CreateProperty <DialogState>("DialogState"), }; return(accessors); }); // Create and register a LUIS recognizer. services.AddSingleton(sp => { var luisAppId = Configuration.GetSection("luisAppId")?.Value; var luisAppKey = Configuration.GetSection("luisAppKey")?.Value; var luisEndPoint = Configuration.GetSection("luisEndPoint")?.Value; // Get LUIS information var luisApp = new LuisApplication(luisAppId, luisAppKey, luisEndPoint); // Specify LUIS options. These may vary for your bot. var luisPredictionOptions = new LuisPredictionOptions { IncludeAllIntents = true, }; // Create the recognizer var recognizer = new LuisRecognizer(luisApp, luisPredictionOptions, true, null); return(recognizer); }); services.AddSingleton(sp => { string cogsBaseUrl = Configuration.GetSection("cogsBaseUrl")?.Value; string cogsKey = Configuration.GetSection("cogsKey")?.Value; var credentials = new ApiKeyServiceClientCredentials(cogsKey); TextAnalyticsClient client = new TextAnalyticsClient(credentials) { Endpoint = cogsBaseUrl }; return(client); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Create the credential provider to be used with the Bot Framework Adapter. services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>(); // Create the Bot Framework Adapter. services.AddSingleton <IBotFrameworkHttpAdapter, AdapterWithErrorHandler>(); // Un-comment the following lines to use Azure Blob Storage // // Storage configuration name or ID from the .bot file. // const string StorageConfigurationId = "<STORAGE-NAME-OR-ID-FROM-BOT-FILE>"; // var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId); // if (!(blobConfig is BlobStorageService blobStorageConfig)) // { // throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'."); // } // // Default container name. // const string DefaultBotContainer = "botstate"; // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container; // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer); // 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>(); // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection. BotConfiguration botConfig = null; try { botConfig = BotConfiguration.Load(@".\SharePointBot.bot", "PsORifD1iMKAL92f/1ucFVQVLU2fSV1h4Pc+ZarSjZk="); } catch { var msg = @"Error reading bot file."; throw new InvalidOperationException(msg); } services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded. ({botConfig})")); // Add BotServices singleton. // Create the connected services from .bot file. services.AddSingleton(sp => new BotServices(botConfig)); // Retrieve current endpoint. var environment = _isProduction ? "production" : "development"; var service = botConfig.Services.Where(s => s.Type == "endpoint" && s.Name == environment).FirstOrDefault(); if (!(service is EndpointService endpointService)) { throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); } var luisService = botConfig.Services.Where(s => s.Type == "luis" && s.Name == "CRM Helper").FirstOrDefault(); if (luisService == null || !(luisService is LuisService)) { throw new InvalidOperationException($"The .bot file does not contain an Luis Service with name 'CRM Helper'."); } // Create and register a LUIS recognizer. services.AddSingleton(sp => { var luisSvc = (LuisService)luisService; // Get LUIS information //var luisApp = new LuisApplication(Constants.CRM_HELPER_APP, "6587e88502964c1e9dca1af530ba4ffa", luisSvc.GetEndpoint()); var luisApp = new LuisApplication(Constants.CRM_HELPER_APP, "c7516642105b4b1093c5fb9212b34653", luisSvc.GetEndpoint()); // Specify LUIS options. These may vary for your bot. var luisPredictionOptions = new LuisPredictionOptions { IncludeAllIntents = true, IncludeInstanceData = true, }; // Create the recognizer var recognizer = new LuisRecognizer(luisApp, luisPredictionOptions, true, null); return(recognizer); }); // Create the bot as a transient. In this case the ASP Controller is expecting an IBot. //services.AddTransient<IBot, EchoBot>(); // The Dialog that will be run by the bot. services.AddSingleton <MainDialog>(); services.AddSingleton <CalDialog>(); // Create the bot as a transient. In this case the ASP Controller is expecting an IBot. //services.AddTransient<IBot, AuthBot<MainDialog>>(); //services.AddTransient<IBot, AuthBot<CalDialog>>(); services.AddTransient <AuthBot <MainDialog> >(); services.AddTransient <AuthBot <CalDialog> >(); services.AddTransient <Func <string, IBot> >(serviceProvider => key => { switch (key) { case "main": return(serviceProvider.GetService <AuthBot <MainDialog> >()); case "graph": return(serviceProvider.GetService <AuthBot <CalDialog> >()); default: throw new KeyNotFoundException(); // or maybe return null, up to you } }); }