// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Retrieve configuration from sections
            Settings.MicrosoftAppId       = Configuration.GetSection("MicrosoftAppId")?.Value;
            Settings.MicrosoftAppPassword = Configuration.GetSection("MicrosoftAppPassword")?.Value;
            Settings.TranslatorTextAPIKey = Configuration.GetSection("TranslatorTextAPIKey")?.Value;
            Settings.BotVersion           = Configuration.GetSection("BotVersion")?.Value;
            Settings.LuisAppId01          = Configuration.GetSection("LuisAppId01")?.Value;
            Settings.LuisName01           = Configuration.GetSection("LuisName01")?.Value;
            Settings.LuisAuthoringKey01   = Configuration.GetSection("LuisAuthoringKey01")?.Value;
            Settings.LuisEndpoint01       = Configuration.GetSection("LuisEndpoint01")?.Value;

            IStorage storage = new MemoryStorage();

            services.AddBot <Bot>(options =>
            {
                options.State.Add(new UserState(storage));
                options.State.Add(new ConversationState(storage));

                options.CredentialProvider = new SimpleCredentialProvider(Settings.MicrosoftAppId, Settings.MicrosoftAppPassword);

                // The BotStateSet middleware forces state storage to auto-save when the bot is complete processing the message.
                // Note: Developers may choose not to add all the state providers to this middleware if save is not required.
                options.Middleware.Add(new AutoSaveStateMiddleware(options.State.ToArray()));
                options.Middleware.Add(new ShowTypingMiddleware());
            });

            services.AddSingleton(sp =>
            {
                // We need to grab the conversationState we added on the options in the previous step
                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.");
                }

                var userState = options.State.OfType <UserState>().FirstOrDefault();
                if (userState == null)
                {
                    throw new InvalidOperationException("UserState must be defined and added before adding user-scoped state accessors.");
                }

                var luisServices = new Dictionary <string, LuisRecognizer>();
                var app          = new LuisApplication(Settings.LuisAppId01, Settings.LuisAuthoringKey01, Settings.LuisEndpoint01);
                var recognizer   = new LuisRecognizer(app);
                luisServices.Add(Settings.LuisName01, recognizer);

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new BotAccessors(conversationState, userState, luisServices)
                {
                    ConversationDialogState  = conversationState.CreateProperty <DialogState>("DialogState"),
                    LanguagePreference       = userState.CreateProperty <string>("LanguagePreference"),
                    IsReadyForLUISPreference = userState.CreateProperty <bool>("IsReadyForLUISPreference")
                };

                return(accessors);
            });
        }
Exemple #2
0
 public LuisHelper(IConfiguration configuration)
 {
     luisApplication = new LuisApplication(configuration["LuisAppId"], configuration["LuisAPIKey"], configuration["LuisAPIHostName"]);
 }
Exemple #3
0
        public SkillConfiguration(BotConfiguration botConfiguration, string[] supportedProviders, string[] parameters, Dictionary <string, object> configuration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.AppInsights:
                {
                    var appInsights     = service as AppInsightsService;
                    var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey);
                    TelemetryClient = new TelemetryClient(telemetryConfig);
                    break;
                }

                case ServiceTypes.Luis:
                {
                    var luis    = service as LuisService;
                    var luisApp = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                    LuisServices.Add(service.Id, new LuisRecognizer(luisApp));
                    break;
                }

                case ServiceTypes.Generic:
                {
                    if (service.Name == "Authentication")
                    {
                        var auth = service as GenericService;

                        foreach (var provider in supportedProviders)
                        {
                            auth.Configuration.TryGetValue(provider, out var connectionName);

                            if (connectionName != null)
                            {
                                AuthenticationConnections.Add(provider, connectionName);
                            }
                        }
                    }

                    break;
                }
                }
            }

            if (parameters != null)
            {
                // add the parameters the skill needs
                foreach (var parameter in parameters)
                {
                    // Initialize each parameter to null. Needs to be set later by the bot.
                    Properties.Add(parameter, null);
                }
            }

            if (configuration != null)
            {
                // add the additional keys the skill needs
                foreach (var set in configuration)
                {
                    Properties.Add(set.Key, set.Value);
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">The <see cref="BotConfiguration"/> instance for the bot.</param>
        public BotServices(BotConfiguration botConfiguration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.Dispatch:
                {
                    var dispatch = service as DispatchService;
                    if (dispatch == null)
                    {
                        throw new InvalidOperationException("The Dispatch service is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(dispatch.AppId))
                    {
                        throw new InvalidOperationException("The Dispatch Luis Model Application Id ('appId') is required to run this sample.  Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(dispatch.SubscriptionKey))
                    {
                        throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.SubscriptionKey, dispatch.GetEndpoint());
                    DispatchRecognizer = new TelemetryLuisRecognizer(dispatchApp);
                    break;
                }

                case ServiceTypes.Luis:
                {
                    var luis = service as LuisService;
                    if (luis == null)
                    {
                        throw new InvalidOperationException("The Luis service is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.AppId))
                    {
                        throw new InvalidOperationException("The Luis Model Application Id ('appId') is required to run this sample.  Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.AuthoringKey))
                    {
                        throw new InvalidOperationException("The Luis Authoring Key ('authoringKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.SubscriptionKey))
                    {
                        throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.Region))
                    {
                        throw new InvalidOperationException("The Region ('region') is required to run this sample.  Please update your '.bot' file.");
                    }

                    var luisApp    = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                    var recognizer = new TelemetryLuisRecognizer(luisApp);
                    LuisServices.Add(service.Id, recognizer);
                    break;
                }

                case ServiceTypes.QnA:
                {
                    var qna         = service as QnAMakerService;
                    var qnaEndpoint = new QnAMakerEndpoint()
                    {
                        KnowledgeBaseId = qna.KbId,
                        EndpointKey     = qna.EndpointKey,
                        Host            = qna.Hostname,
                    };
                    var qnaMaker = new TelemetryQnAMaker(qnaEndpoint);
                    QnAServices.Add(qna.Id, qnaMaker);
                    break;
                }
                }
            }
        }
        // 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(
                    "...",
                    "...",
                    "https://westus.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);
            });
        }
        LuisRecognizer LuisRec(string applicationId, string endpointKey, string endpoint)
        {
            LuisApplication LA = new LuisApplication(applicationId, endpointKey, endpoint);

            return(new LuisRecognizer(LA));
        }
        /// <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);
        }
Exemple #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">Parsed .bot configuration file.</param>
        public BotServices(BotConfiguration botConfiguration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.Endpoint:
                {
                    var endpoint = (EndpointService)service;
                    EndpointServices.Add(endpoint.Name, endpoint);

                    break;
                }

                case ServiceTypes.BlobStorage:
                {
                    // Create a Storage client.
                    var storage = (BlobStorageService)service;

                    if (string.IsNullOrWhiteSpace(storage.ConnectionString))
                    {
                        throw new InvalidOperationException("The Storage ConnectionString ('connectionString') is required. Please update your '.bot' file.");
                    }

                    var storageAccount = CloudStorageAccount.Parse(storage.ConnectionString);
                    StorageServices.Add(storage.Name, storageAccount);

                    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 (string.IsNullOrWhiteSpace(qna.KbId))
                    {
                        throw new InvalidOperationException("The QnA KnowledgeBaseId ('kbId') is required. Please update your '.bot' file.");
                    }

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

                    if (string.IsNullOrWhiteSpace(qna.Hostname))
                    {
                        throw new InvalidOperationException("The QnA Host ('hostname') is required. 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;
                }

                case ServiceTypes.Luis:
                {
                    var luis = (LuisService)service;

                    if (string.IsNullOrWhiteSpace(luis.AppId))
                    {
                        throw new InvalidOperationException("The LUIS AppId ('appId') is required. Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.AuthoringKey))
                    {
                        throw new InvalidOperationException("The LUIS AuthoringKey ('authoringKey') is required. Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.Region))
                    {
                        throw new InvalidOperationException("The LUIS Region ('region') is required. Please update your '.bot' file.");
                    }

                    var app        = new LuisApplication(luis.AppId, luis.AuthoringKey, luis.GetEndpoint());
                    var recognizer = new LuisRecognizer(app);
                    LuisServices.Add(luis.Name, recognizer);

                    break;
                }

                case ServiceTypes.Generic:
                {
                    var genericService = (GenericService)service;
                    if (genericService.Name == "carwashuservicebus")
                    {
                        if (string.IsNullOrWhiteSpace(genericService.Configuration["connectionString"]))
                        {
                            throw new InvalidOperationException("The ServiceBus ConnectionString ('connectionString') is required. Please update your '.bot' file.");
                        }

                        var serviceBusConnection = new ServiceBusConnection(genericService.Configuration["connectionString"]);
                        ServiceBusServices.Add(genericService.Name, serviceBusConnection);
                    }

                    break;
                }
                }
            }
        }
Exemple #9
0
        public override async Task <RecognizerResult> RecognizeAsync(DialogContext dialogContext, Activity activity, CancellationToken cancellationToken = default, Dictionary <string, string> telemetryProperties = null, Dictionary <string, double> telemetryMetrics = null)
        {
            var utterance = activity.Text;

            RecognizerResult recognizerResult = null;
            JObject          luisResponse     = null;

            var dcState     = dialogContext.GetState();
            var endPoint    = Endpoint.GetValue(dcState);
            var id          = ApplicationId.GetValue(dcState);
            var application = new LuisApplication
            {
                ApplicationId = id,
                Endpoint      = endPoint,
            };

            if (string.IsNullOrWhiteSpace(utterance))
            {
                recognizerResult = new RecognizerResult
                {
                    Text    = utterance,
                    Intents = new Dictionary <string, IntentScore>()
                    {
                        { string.Empty, new IntentScore()
                          {
                              Score = 1.0
                          } }
                    },
                    Entities = new JObject(),
                };
            }
            else
            {
                var httpClient = new HttpClient();

                var uri      = BuildUri(application);
                var content  = BuildRequestBody(utterance);
                var response = await httpClient.PostAsync(uri.Uri, new StringContent(content.ToString(), System.Text.Encoding.UTF8, "application/json")).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();
                luisResponse     = (JObject)JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
                recognizerResult = new RecognizerResult();

                recognizerResult.Text     = utterance;
                recognizerResult.Intents  = GetIntents(luisResponse);
                recognizerResult.Entities = ExtractEntitiesAndMetadata(luisResponse);
            }

            var traceInfo = JObject.FromObject(
                new
            {
                recognizerResult,
                spacyModel = new
                {
                    ModelID = application.ApplicationId,
                },
                spacyResult = luisResponse,
            });

            await dialogContext.Context.TraceActivityAsync(TraceName, traceInfo, TraceType, TraceLabel, cancellationToken).ConfigureAwait(false);

            return(recognizerResult);
        }
        private object UpdateLuisApplicationAsync(OperationRunner context)
        {
            AzureClient client = new AzureClient(WizardContext.TokenProvider);

            client.SetLogger(context.Logger);

            LuisApplication luisApp = client.GetLuisAppByNameAsync(
                DataModel.InstallationConfiguration.Azure.Luis.AuthoringKey,
                DataModel.InstallationConfiguration.Azure.Luis.AppName,
                DataModel.InstallationConfiguration.Azure.Luis.AuthoringRegion).Result;

            if (luisApp != null)
            {
                LuisGeneralResponse response = client.DeleteLuisAppAsync(
                    DataModel.InstallationConfiguration.Azure.Luis.AuthoringKey,
                    luisApp.Id,
                    DataModel.InstallationConfiguration.Azure.Luis.AuthoringRegion).Result;

                if (response == null)
                {
                    throw new Exception("Failed to delete existing LUIS application.");
                }
            }

            string luisAppId = client.ImportLuisAppAsync(
                DataModel.InstallationConfiguration.Azure.Luis.AuthoringKey,
                DataModel.InstallationConfiguration.Azure.Luis.AppName,
                DataModel.InstallationConfiguration.Azure.Luis.AppFilePath,
                DataModel.InstallationConfiguration.Azure.Luis.AuthoringRegion).Result;

            if (string.IsNullOrWhiteSpace(luisAppId))
            {
                throw new Exception("Failed to import LUIS application.");
            }

            DataModel.InstallationConfiguration.Azure.Luis.ApplicationId = luisAppId;

            LuisGeneralResponse associatedApp = client.AssociateAzureResourceWithLuisAppAsync(
                luisAppId,
                DataModel.InstallationConfiguration.Azure.Luis.AuthoringRegion,
                DataModel.InstallationConfiguration.Azure.Luis.AuthoringKey,
                new LuisAssociatedAzureResourceRequest()
            {
                AzureSubscriptionId = DataModel.InstallationConfiguration.Azure.SelectedSubscription.Id,
                ResourceGroup       = DataModel.InstallationConfiguration.Azure.ResourceGroupName,
                AccountName         = DataModel.InstallationConfiguration.Azure.Luis.ResourceName,
            }).Result;

            if (associatedApp == null ||
                string.Compare(associatedApp.Code, "Success", true) != 0)
            {
                throw new Exception("Failed to associated LUIS application with Azure LUIS Cognitive Services resource!");
            }

            LuisModelTrainingStatus[] trainedApp = client.TrainLuisApp(
                DataModel.InstallationConfiguration.Azure.Luis.ApplicationId,
                DataModel.InstallationConfiguration.Azure.Luis.AppVersion,
                DataModel.InstallationConfiguration.Azure.Luis.AuthoringRegion,
                DataModel.InstallationConfiguration.Azure.Luis.AuthoringKey);

            if (trainedApp
                .Where(x => x.Details.StatusId != 0 &&
                       x.Details.StatusId != 2).Count() > 0)
            {
                throw new Exception("Failed to train LUIS application!");
            }

            LuisPublishResponse publishedApp = client.PublishLuisAppAsync(
                DataModel.InstallationConfiguration.Azure.Luis.ApplicationId,
                DataModel.InstallationConfiguration.Azure.Luis.AppVersion,
                DataModel.InstallationConfiguration.Azure.Luis.AuthoringRegion,
                DataModel.InstallationConfiguration.Azure.Luis.AuthoringKey).Result;

            if (publishedApp == null)
            {
                throw new Exception("Failed to publish LUIS application!");
            }

            DataModel.InstallationConfiguration.Azure.Luis.EndpointUri = publishedApp.EndpointUrl.Replace(DataModel.InstallationConfiguration.Azure.Luis.AuthoringRegion, DataModel.InstallationConfiguration.Azure.Luis.ResourceRegion);

            // Update settings
            AppServiceAppSettings appSettings = client.GetAppServiceAppSettingsAsync(
                DataModel.InstallationConfiguration.Azure.SelectedSubscription.Id,
                DataModel.InstallationConfiguration.Azure.ResourceGroupName,
                DataModel.InstallationConfiguration.Azure.FunctionApp.AppName).Result;

            if (appSettings == null)
            {
                throw new Exception("Failed to get app settings for app service!");
            }

            appSettings.Properties["luisEndpoint"] = DataModel.InstallationConfiguration.Azure.Luis.EndpointUri;

            AppServiceAppSettings updatedAppSettings = client.UpdateAppServiceAppSettingsAsync(
                DataModel.InstallationConfiguration.Azure.SelectedSubscription.Id,
                DataModel.InstallationConfiguration.Azure.ResourceGroupName,
                DataModel.InstallationConfiguration.Azure.FunctionApp.AppName,
                appSettings).Result;

            if (appSettings == null)
            {
                throw new Exception("Failed to update app settings for app service!");
            }

            return(true);
        }
Exemple #11
0
        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 EmptyLuisResponseClientHandler();
            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 LuisRecognizerOptions
            {
                TelemetryClient        = telemetryClient.Object,
                LogPersonalInformation = false,
                HttpClient             = clientHandler,
            };
            var recognizer = new LuisRecognizer(luisApp, options);

            // 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.NotNull(result);
            Assert.Single(telemetryClient.Invocations);
            Assert.Equal("LuisResult", telemetryClient.Invocations[0].Arguments[0].ToString());
            Assert.True(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("test"));
            Assert.True(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1])["test"] == "testvalue");
            Assert.True(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("foo"));
            Assert.True(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1])["foo"] == "foovalue");
            Assert.True(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("applicationId"));
            Assert.True(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("intent"));
            Assert.True(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("intentScore"));
            Assert.True(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("fromId"));
            Assert.True(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("entities"));
            Assert.True(((Dictionary <string, double>)telemetryClient.Invocations[0].Arguments[2]).ContainsKey("moo"));
            Assert.Equal(3.14159, ((Dictionary <string, double>)telemetryClient.Invocations[0].Arguments[2])["moo"]);
            Assert.True(((Dictionary <string, double>)telemetryClient.Invocations[0].Arguments[2]).ContainsKey("luis"));
            Assert.Equal(1.0001, ((Dictionary <string, double>)telemetryClient.Invocations[0].Arguments[2])["luis"]);
        }
Exemple #12
0
 public LuisRecognizerTests()
 {
     _luisApp = new LuisApplication(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "https://someluisendpoint");
     _mockHttpClientHandler = new EmptyLuisResponseClientHandler();
 }
Exemple #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TelemetryLuisRecognizer"/> class.
 /// </summary>
 /// <param name="application">The <see cref="LuisApplication"/> to use to recognize text.</param>
 /// <param name="predictionOptions">(Optional) The <see cref="LuisPredictionOptions"/> to use.</param>
 /// <param name="includeApiResults">(Optional) TRUE to include raw LUIS API response.</param>
 public TelemetryLuisRecognizer(LuisApplication application, LuisPredictionOptions predictionOptions = null, bool includeApiResults = false)
 {
     recognizer = new LuisRecognizer(application, predictionOptions, includeApiResults);
 }
Exemple #14
0
        public override async Task  OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            var luisApp = new LuisApplication(
                applicationId: "3485b012-bb8e-4239-a3d5-7529253fc5fe",
                endpointKey: "203efc898c8c4c7eb7562c6d0d72c73a",
                endpoint: "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/3485b012-bb8e-4239-a3d5-7529253fc5fe?verbose=true&timezoneOffset=-360&subscription-key=203efc898c8c4c7eb7562c6d0d72c73a&q=");


            if (!turnContext.Responded && turnContext.Activity.Type == ActivityTypes.Message)
            {
                var state = await CapitaAccessor.CapitaStateStateAccessor.GetAsync(turnContext, () => new State(), cancellationToken);

                turnContext.TurnState.Add("CapitaAccessors", CapitaAccessor);
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var dialogResult = await dc.ContinueDialogAsync(cancellationToken);

                if (!dc.Context.Responded)
                {
                    var recognizer       = new LuisRecognizer(luisApp);
                    var recognizerResult = await recognizer.RecognizeAsync(turnContext, cancellationToken);

                    var(intent, score) = recognizerResult.GetTopScoringIntent();

                    switch (intent)
                    {
                    case "None":
                        await turnContext.SendActivityAsync("Sorry, I don't understand.");

                        break;

                    case "hello":
                        await turnContext.SendActivityAsync("Hello! How can I help you?");

                        break;

                    case "ServiceRequest":
                        await dc.BeginDialogAsync(MainDialog.Id, cancellationToken);

                        break;

                    default:

                        await dc.CancelAllDialogsAsync(cancellationToken);

                        break;
                    }
                }
            }



            else
            {
                string text           = "👋 Hi, I'm your virtual assistant!";
                string message        = "Please ask your question";
                var    cardAttachment = Card.CreateAdaptiveCardAttachment(text, message);
                await turnContext.SendActivityAsync(MessageFactory.Attachment(cardAttachment), cancellationToken);
            }
            await CapitaAccessor.ConversationState.SaveChangesAsync(turnContext, false, cancellationToken);
        }
        public SkillConfiguration(BotConfiguration botConfiguration, Dictionary <string, Dictionary <string, string> > languageModels, string[] supportedProviders = null, string[] parameters = null, Dictionary <string, object> configuration = null)
        {
            if (supportedProviders != null && supportedProviders.Count() > 0)
            {
                IsAuthenticatedSkill = true;
            }

            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.Generic:
                {
                    if (service.Name == "Authentication")
                    {
                        var auth = service as GenericService;

                        foreach (var provider in supportedProviders)
                        {
                            var matches = auth.Configuration.Where(x => x.Value == provider);

                            foreach (var match in matches)
                            {
                                AuthenticationConnections.Add(match.Key, match.Value);
                            }
                        }
                    }

                    break;
                }
                }
            }

            foreach (var language in languageModels)
            {
                var localeConfig = new LocaleConfiguration
                {
                    Locale = language.Key
                };

                var path   = language.Value["botFilePath"];
                var secret = language.Value["botFileSecret"];
                var config = BotConfiguration.Load(path, !string.IsNullOrEmpty(secret) ? secret : null);

                foreach (var service in config.Services)
                {
                    switch (service.Type)
                    {
                    case ServiceTypes.Dispatch:
                    {
                        var dispatch    = service as DispatchService;
                        var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.SubscriptionKey, dispatch.GetEndpoint());
                        localeConfig.DispatchRecognizer = new TelemetryLuisRecognizer(dispatchApp);
                        break;
                    }

                    case ServiceTypes.Luis:
                    {
                        var luis    = service as LuisService;
                        var luisApp = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                        localeConfig.LuisServices.Add(service.Id, new TelemetryLuisRecognizer(luisApp));
                        break;
                    }

                    case ServiceTypes.QnA:
                    {
                        var qna         = service as QnAMakerService;
                        var qnaEndpoint = new QnAMakerEndpoint()
                        {
                            KnowledgeBaseId = qna.KbId,
                            EndpointKey     = qna.EndpointKey,
                            Host            = qna.Hostname,
                        };
                        var qnaMaker = new TelemetryQnAMaker(qnaEndpoint);
                        localeConfig.QnAServices.Add(qna.Id, qnaMaker);
                        break;
                    }
                    }
                }

                LocaleConfigurations.Add(language.Key, localeConfig);
            }

            if (parameters != null)
            {
                // add the parameters the skill needs
                foreach (var parameter in parameters)
                {
                    // Initialize each parameter to null. Needs to be set later by the bot.
                    Properties.Add(parameter, null);
                }
            }

            if (configuration != null)
            {
                // add the additional keys the skill needs
                foreach (var set in configuration)
                {
                    Properties.Add(set.Key, set.Value);
                }
            }
        }
Exemple #16
0
        // 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>();

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            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.
                var blobConnectionString = Configuration.GetSection("BlobStorageConnectionString")?.Value;
                var blobContainer        = Configuration.GetSection("BlobStorageContainer")?.Value;
                IStorage dataStore       = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobConnectionString, blobContainer);

                // 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 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 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)));
            });

            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);
            });

            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);
            });
        }
Exemple #17
0
        /// <summary>
        /// Initialize the bot's references to external services.
        ///
        /// For example, QnaMaker services are created here.
        /// These external services are configured
        /// using the <see cref="BotConfiguration"/> class (based on the contents of your ".bot" file).
        /// </summary>
        /// <param name="config"><see cref="BotConfiguration"/> object based on your ".bot" file.</param>
        /// <returns>A <see cref="BotServices"/> representing client objects to access external services the bot uses.</returns>
        /// <seealso cref="BotConfiguration"/>
        /// <seealso cref="QnAMaker"/>
        /// <seealso cref="TelemetryClient"/>
        private static BotServices InitBotServices(BotConfiguration config)
        {
            var qnaServices  = new Dictionary <string, QnAMaker>();
            var luisServices = new Dictionary <string, LuisRecognizer>();

            foreach (var service in config.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.Luis:
                {
                    // Create a Luis Recognizer that is initialized and suitable for passing
                    // into the IBot-derived class (NlpDispatchBot).
                    // In this case, we're creating a custom class (wrapping the original
                    // Luis Recognizer client) that logs the results of Luis Recognizer results
                    // into Application Insights for future analysis.
                    if (!(service is LuisService luis))
                    {
                        throw new InvalidOperationException("The LUIS service is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.AppId))
                    {
                        throw new InvalidOperationException("The LUIS Model Application Id ('appId') is required to run this sample. Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.AuthoringKey))
                    {
                        throw new InvalidOperationException("The Luis Authoring Key ('authoringKey') is required to run this sample. Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.SubscriptionKey))
                    {
                        throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample. Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.Region))
                    {
                        throw new InvalidOperationException("The Region ('region') is required to run this sample. Please update your '.bot' file.");
                    }

                    var app        = new LuisApplication(luis.AppId, luis.AuthoringKey, luis.GetEndpoint());
                    var recognizer = new LuisRecognizer(app);
                    luisServices.Add(luis.Name, recognizer);
                    break;
                }

                case ServiceTypes.Dispatch:
                    // Create a Dispatch Recognizer that is initialized and suitable for passing
                    // into the IBot-derived class (NlpDispatchBot).
                    // In this case, we're creating a custom class (wrapping the original
                    // Luis Recognizer client) that logs the results of Luis Recognizer results
                    // into Application Insights for future analysis.
                    if (!(service is DispatchService dispatch))
                    {
                        throw new InvalidOperationException("The Dispatch service is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(dispatch.AppId))
                    {
                        throw new InvalidOperationException("The LUIS Model Application Id ('appId') is required to run this sample. Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(dispatch.AuthoringKey))
                    {
                        throw new InvalidOperationException("The LUIS Authoring Key ('authoringKey') is required to run this sample. Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(dispatch.SubscriptionKey))
                    {
                        throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample. Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(dispatch.Region))
                    {
                        throw new InvalidOperationException("The Region ('region') is required to run this sample. Please update your '.bot' file.");
                    }

                    var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.AuthoringKey, dispatch.GetEndpoint());

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

                case ServiceTypes.QnA:
                {
                    // Create a QnA Maker that is initialized and suitable for passing
                    // into the IBot-derived class (NlpDispatchBot).
                    // In this case, we're creating a custom class (wrapping the original
                    // QnAMaker client) that logs the results of QnA Maker into Application
                    // Insights for future analysis.
                    if (!(service is QnAMakerService qna))
                    {
                        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;
                }
                }
            }

            return(new BotServices(qnaServices, luisServices));
        }
        /// <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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // add options
            services.AddSingleton <BotConfigOptions>(new BotConfigOptions {
                MicrosoftAppId       = Configuration["MicrosoftAppId"],
                MicrosoftAppPassword = Configuration["MicrosoftAppPassword"],
            });

            // create luis recognizer

            var luisApplication = new LuisApplication(
                Configuration["LuisAppId"],
                Configuration["LuisAPIKey"],
                "https://" + Configuration["LuisAPIHostName"]);

            services.AddSingleton(new LuisRecognizer(luisApplication));

            // Create the credential provider to be used with the Bot Framework Adapter.
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();

            // 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>();

            // The Dialogs that will be run by the bot.

            // Memory Storage is for local bot debugging only. When the bot
            // is restarted, everything stored in memory will be gone.
            IStorage dataStore = new MemoryStorage();

            // Create and add conversation state.
            var conversationState = new ConversationState(dataStore);

            services.AddSingleton(conversationState);

            var userState = new UserState(dataStore);

            services.AddSingleton(userState);

            services.AddBot <SmartRetailBot>(options =>
            {
            });

            // Create and register state accessors.
            // Accessors created here are passed into the IBot-derived class on every turn.
            services.AddSingleton(sp =>
            {
                // We need to grab the conversationState we added on the options in the previous step
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors");
                }

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new BotAccessors(conversationState, userState)
                {
                    ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"),
                    UserData = userState.CreateProperty <UserData>("UserData"),
                };

                return(accessors);
            });
        }
Exemple #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">The <see cref="BotConfiguration"/> instance for the bot.</param>
        public BotServices(BotConfiguration botConfiguration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.AppInsights:
                {
                    var appInsights = (AppInsightsService)service;
                    if (appInsights == null)
                    {
                        throw new InvalidOperationException("The Application Insights is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(appInsights.InstrumentationKey))
                    {
                        throw new InvalidOperationException("The Application Insights Instrumentation Key ('instrumentationKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey);
                    TelemetryClient = new TelemetryClient(telemetryConfig)
                    {
                        InstrumentationKey = appInsights.InstrumentationKey,
                    };

                    break;
                }

                case ServiceTypes.Dispatch:
                {
                    var dispatch = service as DispatchService;
                    if (dispatch == null)
                    {
                        throw new InvalidOperationException("The Dispatch service is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(dispatch.AppId))
                    {
                        throw new InvalidOperationException("The Dispatch Luis Model Application Id ('appId') is required to run this sample.  Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(dispatch.SubscriptionKey))
                    {
                        throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.SubscriptionKey, dispatch.GetEndpoint());
                    DispatchRecognizer = new TelemetryLuisRecognizer(dispatchApp);
                    break;
                }

                case ServiceTypes.Luis:
                {
                    var luis = service as LuisService;
                    if (luis == null)
                    {
                        throw new InvalidOperationException("The Luis service is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.AppId))
                    {
                        throw new InvalidOperationException("The Luis Model Application Id ('appId') is required to run this sample.  Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.AuthoringKey))
                    {
                        throw new InvalidOperationException("The Luis Authoring Key ('authoringKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.SubscriptionKey))
                    {
                        throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.Region))
                    {
                        throw new InvalidOperationException("The Region ('region') is required to run this sample.  Please update your '.bot' file.");
                    }

                    var luisApp    = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                    var recognizer = new TelemetryLuisRecognizer(luisApp);
                    LuisServices.Add(service.Id, recognizer);
                    break;
                }

                case ServiceTypes.QnA:
                {
                    var qna         = service as QnAMakerService;
                    var qnaEndpoint = new QnAMakerEndpoint()
                    {
                        KnowledgeBaseId = qna.KbId,
                        EndpointKey     = qna.EndpointKey,
                        Host            = qna.Hostname,
                    };
                    var qnaMaker = new TelemetryQnAMaker(qnaEndpoint);
                    QnAServices.Add(qna.Id, qnaMaker);
                    break;
                }

                case ServiceTypes.Generic:
                {
                    if (service.Name == "Authentication")
                    {
                        var authentication = service as GenericService;

                        if (!string.IsNullOrEmpty(authentication.Configuration["Azure Active Directory v2"]))
                        {
                            AuthConnectionName = authentication.Configuration["Azure Active Directory v2"];
                        }
                    }

                    break;
                }
                }
            }
        }
Exemple #20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson();

            // Create the Bot Framework Adapter with error handling enabled.
            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 = sp.GetRequiredService <ConversationState>();
                //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.
                return(new PictureBotAccessors(conversationState)
                {
                    PictureState = conversationState.CreateProperty <PictureState>(PictureBotAccessors.PictureStateName),
                    DialogStateAccessor = conversationState.CreateProperty <DialogState>("DialogState"),
                });
            });

            services.AddSingleton(sp =>
            {
                var luisApplication = new LuisApplication(
                    Configuration.GetSection("luisAppId")?.Value,
                    Configuration.GetSection("luisAppKey")?.Value,
                    Configuration.GetSection("luisEndPoint")?.Value);
                // 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
                    {
                        IncludeAllIntents = true,
                    }
                };
                return(new LuisRecognizer(recognizerOptions));
            });
            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            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.");
                };


                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 the User state.
            services.AddSingleton <UserState>(sp => {
                var dataStore = sp.GetRequiredService <IStorage>();
                return(new UserState(dataStore));
            });

            // Create the Conversation state.
            services.AddSingleton <ConversationState>(sp =>
            {
                var dataStore = sp.GetRequiredService <IStorage>();
                return(new ConversationState(dataStore));
            });

            // Create the IStorage.
            services.AddSingleton <IStorage, BlobsStorage>(sp =>
            {
                var blobConnectionString = Configuration.GetSection("BlobStorageConnectionString")?.Value;
                var blobContainer        = Configuration.GetSection("BlobStorageContainer")?.Value;
                BlobsStorage dataStore   = new BlobsStorage(blobConnectionString, blobContainer);
                return(dataStore);
            });
            services.AddSingleton(sp =>
            {
                CosmosClientBuilder clientBuilder = new CosmosClientBuilder(
                    Configuration.GetSection("cosmosEndpointURI")?.Value,
                    Configuration.GetSection("cosmosKey")?.Value
                    );

                CosmosClient client = clientBuilder
                                      .WithConnectionModeDirect()
                                      .Build();

                Container container = client.GetContainer(
                    Configuration.GetSection("cosmosDatabaseName")?.Value,
                    Configuration.GetSection("cosmosCollectionName")?.Value
                    );

                return(container);
            });
            services.AddSingleton <TextAnalyticsClient>(sp =>
            {
                Uri cogsBaseUrl = new Uri(Configuration.GetSection("cogsBaseUrl")?.Value);
                string cogsKey  = Configuration.GetSection("cogsKey")?.Value;

                var credentials = new AzureKeyCredential(cogsKey);
                return(new TextAnalyticsClient(cogsBaseUrl, credentials));
            });
        }
Exemple #21
0
        /// <summary>
        /// Initialize the bot's references to external services.
        ///
        /// For example, Application Insights and LUIS services
        /// are created here. These external services are configured
        /// using the <see cref="BotConfiguration"/> class (based on the contents of your ".bot" file).
        /// </summary>
        /// <param name="config">The <see cref="BotConfiguration"/> object based on your ".bot" file.</param>
        /// <returns>A <see cref="BotServices"/> representing client objects to access external services the bot uses.</returns>
        /// <seealso cref="BotConfiguration"/>
        /// <seealso cref="LuisRecognizer"/>
        private static BotServices InitBotServices(BotConfiguration config)
        {
            var luisServices = new Dictionary <string, TelemetryLuisRecognizer>();

            foreach (var service in config.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.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.AppId))
                    {
                        throw new InvalidOperationException("The Luis Model Application Id ('appId') is required to run this sample.  Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.AuthoringKey))
                    {
                        throw new InvalidOperationException("The Luis Authoring Key ('authoringKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.SubscriptionKey))
                    {
                        throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(luis.Region))
                    {
                        throw new InvalidOperationException("The Region ('region') is required to run this sample.  Please update your '.bot' file.");
                    }

                    var app        = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                    var recognizer = new TelemetryLuisRecognizer(app);
                    luisServices.Add(LuisBot.LuisKey, recognizer);
                    break;
                }

                case ServiceTypes.AppInsights:
                {
                    var appInsights = (AppInsightsService)service;
                    if (appInsights == null)
                    {
                        throw new InvalidOperationException("The Application Insights is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(appInsights.InstrumentationKey))
                    {
                        throw new InvalidOperationException("The Application Insights Instrumentation Key ('instrumentationKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    break;
                }
                }
            }

            var connectedServices = new BotServices(luisServices);

            return(connectedServices);
        }
 public OverrideFillRecognizer(LuisApplication application, LuisPredictionOptions predictionOptions = null, bool includeApiResults = false, bool logPersonalInformation = false, HttpClientHandler clientHandler = null)
     : base(application, predictionOptions, includeApiResults, clientHandler)
 {
     LogPersonalInformation = logPersonalInformation;
 }
Exemple #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">The <see cref="BotConfiguration"/> instance for the bot.</param>
        public BotServices(BotConfiguration botConfiguration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.AppInsights:
                {
                    var appInsights     = service as AppInsightsService;
                    var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey);
                    TelemetryClient = new TelemetryClient(telemetryConfig);
                    break;
                }

                case ServiceTypes.Dispatch:
                {
                    var dispatch    = service as DispatchService;
                    var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.SubscriptionKey, dispatch.GetEndpoint());
                    DispatchRecognizer = new TelemetryLuisRecognizer(dispatchApp);
                    break;
                }

                case ServiceTypes.Luis:
                {
                    var luis    = service as LuisService;
                    var luisApp = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                    LuisServices.Add(service.Id, new TelemetryLuisRecognizer(luisApp));
                    break;
                }

                case ServiceTypes.QnA:
                {
                    var qna         = service as QnAMakerService;
                    var qnaEndpoint = new QnAMakerEndpoint()
                    {
                        KnowledgeBaseId = qna.KbId,
                        EndpointKey     = qna.EndpointKey,
                        Host            = qna.Hostname,
                    };
                    var qnaMaker = new TelemetryQnAMaker(qnaEndpoint);
                    QnAServices.Add(qna.Id, qnaMaker);
                    break;
                }

                case ServiceTypes.Generic:
                {
                    if (service.Name == "Authentication")
                    {
                        var authentication = service as GenericService;

                        if (!string.IsNullOrEmpty(authentication.Configuration["Azure Active Directory v2"]))
                        {
                            AuthConnectionName = authentication.Configuration["Azure Active Directory v2"];
                        }
                    }

                    break;
                }
                }
            }
        }
Exemple #24
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">Specifies the contract for a <see cref="IServiceCollection"/> of service descriptors.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // add options
            services.Configure <BotOptions>(Configuration.GetSection("Bot"));

            // create luis recognizer
            var luisApplication = new LuisApplication(
                Configuration["LuisAppId"],
                Configuration["LuisAPIKey"],
                "https://" + Configuration["LuisAPIHostName"]
                );

            services.AddSingleton(new LuisRecognizer(luisApplication));


            // Create the credential provider to be used with the Bot Framework Adapter.
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();

            // 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>();

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

            // Memory Storage is for local bot debugging only. When the bot
            // is restarted, everything stored in memory will be gone.
            IStorage dataStore = new MemoryStorage();

            // Create and add conversation state.
            var conversationState = new ConversationState(dataStore);

            services.AddSingleton(conversationState);

            var userState = new UserState(dataStore);

            services.AddSingleton(userState);

            // Add translation middleware here
            var languangeProperty = conversationState.CreateProperty <string>("Language");

            services.AddSingleton(new TranslationMiddleware(languangeProperty));

            // Add Hero Cards translation middleware here
            services.AddSingleton(new HeroCardsTranslationMiddleware(languangeProperty));


            services.AddTransient <IBot, InsuranceBot>();

            // Create and register state accessors.
            // Accessors created here are passed into the IBot-derived class on every turn.
            services.AddSingleton(sp =>
            {
                // We need to grab the conversationState we added on the options in the previous step
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors");
                }

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new InsuranceBotAccessors(conversationState, userState)
                {
                    ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"),
                    GetInsuranceState       = userState.CreateProperty <InsuranceState>("GetInsuranceState"),
                };

                return(accessors);
            });

            // Add QnA Maker here
            // Create and register a QnA service and knowledgebase
            services.AddSingleton(sp =>
            {
                return(new QnAMaker(
                           new QnAMakerEndpoint
                {
                    EndpointKey = "88f57255-703b-4cc8-85a8-847c580643e9",
                    Host = "https://minilitware-qna-em.azurewebsites.net/qnamaker",
                    KnowledgeBaseId = "e51dc78e-5cdd-4c77-94b3-ec84c391f7b4",
                },
                           new QnAMakerOptions
                {
                    ScoreThreshold = 0.9f,
                    Top = 1,
                }));
            });
        }
Exemple #25
0
        /// <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 <EchoWithCounterBot>(options =>
            {
                var secretKey   = Configuration.GetSection("botFileSecret")?.Value;
                var botFilePath = Configuration.GetSection("botFilePath")?.Value;
                if (!File.Exists(botFilePath))
                {
                    throw new FileNotFoundException($"The .botconfiguration file was not found. botFilePath: {botFilePath}");
                }

                // 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 <EchoWithCounterBot>();

                // 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 = "<DEFAULT-CONTAINER>";
                // 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);

                // Create and add user state.
                var userState = new UserState(dataStore);
                options.State.Add(userState);
            });

            // Create and register state accesssors.
            // Acessors created here are passed into the IBot-derived class on every turn.
            services.AddSingleton <EchoBotAccessors>(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 userState = options.State.OfType <UserState>().FirstOrDefault();
                if (userState == null)
                {
                    throw new InvalidOperationException(
                        "UserState must be defined and added before adding user-scoped 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 EchoBotAccessors(conversationState, userState)
                {
                    CounterState            = conversationState.CreateProperty <CounterState>(EchoBotAccessors.CounterStateName),
                    ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"),
                    UserProfile             = userState.CreateProperty <UserProfile>("UserProfile"),
                };

                return(accessors);
            });

            // Create and register a LUIS recognizer.
            services.AddSingleton(sp =>
            {
                // Set up Luis
                var luisApp = new LuisApplication(
                    applicationId: "0dbe4190-91aa-4a1c-805d-830b8bde8858",
                    endpointKey: "5e37061632e7468e85b0023fd323d679",
                    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));
            });
        }
Exemple #26
0
        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));
        }
Exemple #27
0
 /// <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)
 {
     LogOriginalMessage = logOriginalMessage;
     LogUsername        = logUserName;
 }
Exemple #28
0
 public OverrideFillRecognizer(LuisApplication application, LuisRecognizerOptions recognizerOptions = null)
     : base(application, recognizerOptions)
 {
 }
Exemple #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">The <see cref="BotConfiguration"/> instance for the bot.</param>
        /// <param name="skills">List of <see cref="SkillDefinition"/> for loading skill configurations.</param>
        /// <param name="languageModels">The locale specifc language model configs for each supported language.</param>
        /// <param name="skillEventsConfig">The configuration for skill events.</param>
        public BotServices(BotConfiguration botConfiguration, Dictionary <string, Dictionary <string, string> > languageModels, List <SkillDefinition> skills, List <SkillEvent> skillEventsConfig)
        {
            // Create service clients for each service in the .bot file.
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.AppInsights:
                {
                    var appInsights = (AppInsightsService)service;
                    if (appInsights == null)
                    {
                        throw new InvalidOperationException("The Application Insights is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(appInsights.InstrumentationKey))
                    {
                        throw new InvalidOperationException("The Application Insights Instrumentation Key ('instrumentationKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey);
                    TelemetryClient = new TelemetryClient(telemetryConfig)
                    {
                        InstrumentationKey = appInsights.InstrumentationKey,
                    };

                    break;
                }

                case ServiceTypes.CosmosDB:
                {
                    var cosmos = service as CosmosDbService;

                    CosmosDbOptions = new CosmosDbStorageOptions
                    {
                        AuthKey          = cosmos.Key,
                        CollectionId     = cosmos.Collection,
                        DatabaseId       = cosmos.Database,
                        CosmosDBEndpoint = new Uri(cosmos.Endpoint),
                    };

                    break;
                }

                case ServiceTypes.Generic:
                {
                    if (service.Name == "Authentication")
                    {
                        var authentication = service as GenericService;
                        AuthenticationConnections = authentication.Configuration;
                    }

                    break;
                }
                }
            }

            // Create locale configuration object for each language config in appsettings.json
            foreach (var language in languageModels)
            {
                if (language.Value.TryGetValue("botFilePath", out var botFilePath) && File.Exists(botFilePath))
                {
                    var botFileSecret = language.Value["botFileSecret"];
                    var config        = BotConfiguration.Load(botFilePath, !string.IsNullOrEmpty(botFileSecret) ? botFileSecret : null);

                    var localeConfig = new LocaleConfiguration
                    {
                        Locale = language.Key
                    };

                    foreach (var service in config.Services)
                    {
                        switch (service.Type)
                        {
                        case ServiceTypes.Dispatch:
                        {
                            var dispatch = service as DispatchService;
                            if (dispatch == null)
                            {
                                throw new InvalidOperationException("The Dispatch service is not configured correctly in your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(dispatch.AppId))
                            {
                                throw new InvalidOperationException("The Dispatch Luis Model Application Id ('appId') is required to run this sample.  Please update your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(dispatch.SubscriptionKey))
                            {
                                throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample.  Please update your '.bot' file.");
                            }

                            var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.SubscriptionKey, dispatch.GetEndpoint());
                            localeConfig.DispatchRecognizer = new TelemetryLuisRecognizer(dispatchApp);
                            break;
                        }

                        case ServiceTypes.Luis:
                        {
                            var luis = service as LuisService;
                            if (luis == null)
                            {
                                throw new InvalidOperationException("The Luis service is not configured correctly in your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(luis.AppId))
                            {
                                throw new InvalidOperationException("The Luis Model Application Id ('appId') is required to run this sample.  Please update your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(luis.AuthoringKey))
                            {
                                throw new InvalidOperationException("The Luis Authoring Key ('authoringKey') is required to run this sample.  Please update your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(luis.SubscriptionKey))
                            {
                                throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample.  Please update your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(luis.Region))
                            {
                                throw new InvalidOperationException("The Region ('region') is required to run this sample.  Please update your '.bot' file.");
                            }

                            var luisApp    = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                            var recognizer = new TelemetryLuisRecognizer(luisApp);
                            localeConfig.LuisServices.Add(service.Id, recognizer);
                            break;
                        }

                        case ServiceTypes.QnA:
                        {
                            var qna         = service as QnAMakerService;
                            var qnaEndpoint = new QnAMakerEndpoint()
                            {
                                KnowledgeBaseId = qna.KbId,
                                EndpointKey     = qna.EndpointKey,
                                Host            = qna.Hostname,
                            };
                            var qnaMaker = new TelemetryQnAMaker(qnaEndpoint);
                            localeConfig.QnAServices.Add(qna.Id, qnaMaker);
                            break;
                        }
                        }
                    }

                    LocaleConfigurations.Add(language.Key, localeConfig);
                }
            }

            // Create a skill configurations for each skill in appsettings.json
            foreach (var skill in skills)
            {
                var skillConfig = new SkillConfiguration()
                {
                    CosmosDbOptions = CosmosDbOptions
                };

                foreach (var localeConfig in LocaleConfigurations)
                {
                    skillConfig.LocaleConfigurations.Add(localeConfig.Key, new LocaleConfiguration
                    {
                        LuisServices = localeConfig.Value.LuisServices.Where(l => skill.LuisServiceIds.Contains(l.Key) == true).ToDictionary(l => l.Key, l => l.Value)
                    });
                }

                if (skill.SupportedProviders != null)
                {
                    foreach (var provider in skill.SupportedProviders)
                    {
                        var matches = AuthenticationConnections.Where(x => x.Value == provider);

                        foreach (var match in matches)
                        {
                            skillConfig.AuthenticationConnections.Add(match.Key, match.Value);
                        }
                    }
                }

                foreach (var set in skill.Configuration)
                {
                    skillConfig.Properties.Add(set.Key, set.Value);
                }

                SkillDefinitions.Add(skill);
                SkillConfigurations.Add(skill.Id, skillConfig);
                SkillEvents = skillEventsConfig != null?skillEventsConfig.ToDictionary(i => i.Event) : null;
            }
        }
Exemple #30
0
        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>();

            // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
            services.AddTransient <IBot, EchoBot>();


            // Create and register a LUIS recognizer.
            services.AddSingleton(sp =>
            {
                // Set up Luis
                var luisApp = new LuisApplication(
                    applicationId: "",
                    endpointKey: "",
                    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));
            });



            services.AddBot <EchoBot>(options =>
            {
                // 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 = "<DEFAULT-CONTAINER>";
                // 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);

                // Create and add user state.
                var userState = new UserState(dataStore);
                options.State.Add(userState);
            });

            // Create and register state accesssors.
            // Acessors created here are passed into the IBot-derived class on every turn.
            services.AddSingleton <EchoBotAccessors>(sp =>
            {
                var options = sp.GetRequiredService <Microsoft.Extensions.Options.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.");
                }

                var userState = options.State.OfType <UserState>().FirstOrDefault();
                if (userState == null)
                {
                    throw new InvalidOperationException("UserState must be defined and added before adding user-scoped state accessors.");
                }

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new EchoBotAccessors(conversationState, userState)
                {
                    CounterState            = conversationState.CreateProperty <CounterState>(EchoBotAccessors.CounterStateName),
                    ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"),
                    UserProfile             = userState.CreateProperty <WeatherProfile>("WeatherProfile"),
                };

                return(accessors);
            });
        }