コード例 #1
0
        private void RegisterLuisRecognizers(IServiceCollection services)
        {
            var luisIsConfigured = !string.IsNullOrEmpty(Configuration["LuisAppId"]) && !string.IsNullOrEmpty(Configuration["LuisAPIKey"]) && !string.IsNullOrEmpty(Configuration["LuisAPIHostName"]);

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

                var recognizer = new LuisRecognizer(luisApplication);
                services.AddSingleton <IRecognizer>(recognizer);
            }
        }
コード例 #2
0
        public static async Task <BookingDetails> ExecuteLuisQuery(IConfiguration configuration, ILogger logger, ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var bookingDetails = new BookingDetails();

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

                var recognizer = new LuisRecognizer(luisApplication);

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

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

                    if (bookingDetails.Destination == null)
                    {
                        bookingDetails.Destination = recognizerResult.GetEntity <string>("To");
                    }

                    bookingDetails.Origin = recognizerResult.Entities["From"]?.FirstOrDefault()?["Airport"]?.FirstOrDefault()?.FirstOrDefault()?.ToString();

                    if (bookingDetails.Origin == null)
                    {
                        bookingDetails.Origin = recognizerResult.GetEntity <string>("From");
                    }

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

            return(bookingDetails);
        }
コード例 #3
0
        public static async Task <BookingDetails> ExecuteLuisQuery(IBotTelemetryClient telemetryClient, IConfiguration configuration, ILogger logger, ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var bookingDetails = new BookingDetails();

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


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

                var recognizer = new LuisRecognizer(recognizerOptions);

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

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

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

            return(bookingDetails);
        }
コード例 #4
0
        public BotServices(IConfiguration configuration)
        {
            // Read the setting for cognitive services (LUIS, QnA) from the appsettings.json
            Dispatch = new LuisRecognizer(new LuisApplication(
                                              configuration["LuisAppId"],
                                              configuration["LuisAPIKey"],
                                              $"https://{configuration["LuisAPIHostName"]}.api.cognitive.microsoft.com"),
                                          new LuisPredictionOptions {
                IncludeAllIntents = true, IncludeInstanceData = true
            },
                                          true);

            SampleQnA = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = configuration["QnAKnowledgebaseId"],
                EndpointKey     = configuration["QnAAuthKey"],
                Host            = configuration["QnAEndpointHostName"]
            });
        }
コード例 #5
0
        public FlightBookingRecognizer(IConfiguration configuration)
        {
            var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId1"]) && !string.IsNullOrEmpty(configuration["LuisAPIKey1"]) && !string.IsNullOrEmpty(configuration["LuisAPIHostName1"]);

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

                _recognizer = new LuisRecognizer(recognizerOptions);
            }
        }
コード例 #6
0
        public BotServices(IConfiguration configuration)
        {
            // Read the setting for cognitive services (LUIS, QnA) from the appsettings.json
            // If includeApiResults is set to true, the full response from the LUIS api (LuisResult)
            // will be made available in the properties collection of the RecognizerResult
            Dispatch = new LuisRecognizer(new LuisApplication(
                                              configuration["LuisAppId"],
                                              configuration["LuisAPIKey"],
                                              $"https://{configuration["LuisAPIHostName"]}.api.cognitive.microsoft.com"),
                                          new LuisPredictionOptions {
                IncludeAllIntents = true, IncludeInstanceData = true
            },
                                          includeApiResults: true);

            SampleQnA = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = configuration["QnAKnowledgebaseId"],
                EndpointKey     = configuration["QnAEndpointKey"],
                Host            = configuration["QnAEndpointHostName"]
            });
        }
コード例 #7
0
 private LuisRecognizer ReadLuisRecognizer(IConfiguration configuration)
 {
     try
     {
         var services    = configuration.GetSection("BotServices");
         var application = new LuisApplication(services.GetValue <string>("LuisAppId"),
                                               services.GetValue <string>("LuisAuthoringKey"),
                                               "https://" + services.GetValue <string>("LuisHostName"));
         var predictions = new LuisPredictionOptions
         {
             IncludeAllIntents   = true,
             IncludeInstanceData = true
         };
         var recognizer = new LuisRecognizer(application, predictions, true);
         return(recognizer);
     }
     catch (Exception)
     {
         return(null);
     }
 }
        public FlightBookingRecognizer(IConfiguration configuration, IBotTelemetryClient telemetryClient)
        {
            var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId"]) && !string.IsNullOrEmpty(configuration["LuisAPIKey"]) && !string.IsNullOrEmpty(configuration["LuisAPIHostName"]);

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

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

                _recognizer = new LuisRecognizer(recognizerOptions);
            }
        }
コード例 #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="luisServices">A dictionary of named <see cref="LuisRecognizer"/> instances for usage within the bot.</param>
        public BotServices(BotConfiguration botConfiguration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.Luis:
                {
                    var luis = (LuisService)service;
                    if (luis == null)
                    {
                        throw new InvalidOperationException("The LUIS service is not configured correctly in your '.bot' file.");
                    }

                    var endpoint   = (luis.Region?.StartsWith("https://") ?? false) ? luis.Region : luis.GetEndpoint();
                    var app        = new LuisApplication(luis.AppId, luis.AuthoringKey, endpoint);
                    var recognizer = new LuisRecognizer(app);
                    this.LuisServices.Add(luis.Name, recognizer);
                    break;
                }

                case ServiceTypes.QnA:
                {
                    // Create a QnA Maker that is initialized and suitable for passing
                    // into the IBot-derived class (QnABot).
                    var qna         = service as QnAMakerService;
                    var qnaEndpoint = new QnAMakerEndpoint()
                    {
                        KnowledgeBaseId = qna.KbId,
                        EndpointKey     = qna.EndpointKey,
                        Host            = qna.Hostname,
                    };

                    var qnaMaker = new QnAMaker(qnaEndpoint);
                    this.QnAServices.Add(qna.Name, qnaMaker);
                    break;
                }
                }
            }
        }
コード例 #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="luisServices">A dictionary of named <see cref="LuisRecognizer"/> instances for usage within the bot.</param>
        public BotServices(BotConfiguration botConfiguration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.Luis:
                {
                    var luis = (LuisService)service;
                    if (luis == null)
                    {
                        throw new InvalidOperationException("The LUIS service is not configured correctly in your '.bot' file.");
                    }

                    var app        = new LuisApplication(luis.AppId, luis.AuthoringKey, luis.GetEndpoint());
                    var recognizer = new LuisRecognizer(app);
                    LuisServices.Add(luis.Name, recognizer);
                    break;
                }
                }
            }
        }
コード例 #11
0
        public BotServices(IConfiguration configuration, IBotTelemetryClient telemetryClient)
        {
            // Read the setting for cognitive services (LUIS, QnA) from the appsettings.json
            // If includeApiResults is set to true, the full response from the LUIS api (LuisResult)
            // will be made available in the properties collection of the RecognizerResult

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

            // 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 LuisRecognizerOptionsV2(luisApplication)
            {
                IncludeAPIResults = true,
                PredictionOptions = new LuisPredictionOptions()
                {
                    IncludeAllIntents   = true,
                    IncludeInstanceData = true
                }
            };

            Dispatch = new LuisRecognizer(recognizerOptions);

            DocumentationQnA = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = configuration["DocumentationQnAKnowledgebaseId"],
                EndpointKey     = configuration["DocumentationQnAEndpointKey"],
                Host            = configuration["DocumentationQnAEndpointHostName"]
            }, null, null, telemetryClient);

            KustoQnA = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = configuration["KustoQnAKnowledgebaseId"],
                EndpointKey     = configuration["KustoQnAEndpointKey"],
                Host            = configuration["KustoQnAEndpointHostName"]
            }, null, null, telemetryClient);
        }
コード例 #12
0
ファイル: BotServices.cs プロジェクト: ppsinghgit/MyBot
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="luisServices">A dictionary of named <see cref="LuisRecognizer"/> instances for usage within the bot.</param>
        public BotServices(BotConfiguration botConfiguration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.Luis:
                {
                    var luis = (LuisService)service;
                    if (luis == null)
                    {
                        throw new InvalidOperationException("The LUIS service is not configured correctly in your '.bot' file.");
                    }

                    var endpoint   = (luis.Region?.StartsWith("https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/469ed5e3-0f34-4878-b6cf-a3ae7f535c83?subscription-key=d08cab2fd9f2440d8c17b5361bd47b9a&timezoneOffset=-360&q=") ?? true) ? luis.Region : luis.GetEndpoint();
                    var app        = new LuisApplication(luis.AppId, luis.AuthoringKey, endpoint);
                    var recognizer = new LuisRecognizer(app);
                    this.LuisServices.Add(luis.Name, recognizer);
                    break;
                }
                }
            }
        }
コード例 #13
0
        public FlightBookingRecognizer(IConfiguration configuration)
        {
            var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId"]) && !string.IsNullOrEmpty(configuration["LuisAPIKey"]) && !string.IsNullOrEmpty(configuration["LuisAPIHostName"]);

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

                _recognizer = new LuisRecognizer(recognizerOptions);
            }
        }
コード例 #14
0
        private async Task <DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var Details = await _TokenAccessor.GetAsync(innerDc.Context, () => new StoredDetails(), cancellationToken);

            var p = Details.TokenResponse;



            if (innerDc.Context.Activity.Type == ActivityTypes.Message)
            {
                //var text = innerDc.Context.Activity.Text.ToLowerInvariant();

                var luisApplication = new LuisApplication(
                    "bdc48cb4-0945-40e8-8e89-99fec5924d03",
                    "76e8996cfd994ef3a4b79b938c0c2b04",
                    $"https://westus.api.cognitive.microsoft.com");

                var recognizer = new LuisRecognizer(luisApplication);
                // The actual call to LUIS
                var recognizerResult = await recognizer.RecognizeAsync(innerDc.Context, cancellationToken);

                var topIntent = recognizerResult.GetTopScoringIntent();

                if (topIntent.intent == "Exit")
                {
                    Details.TokenResponse = null;
                    var botAdapter = (BotFrameworkAdapter)innerDc.Context.Adapter;
                    await botAdapter.SignOutUserAsync(innerDc.Context, ConnectionName, null, cancellationToken);

                    await innerDc.Context.SendActivityAsync(MessageFactory.Text("You have been signed out."), cancellationToken);

                    return(await innerDc.CancelAllDialogsAsync(cancellationToken));
                }
            }

            return(null);
        }
コード例 #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">A dictionary of named <see cref="BotConfiguration"/> instances for usage within the bot.</param>
        public BotServices(BotConfiguration botConfiguration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.Luis:
                {
                    var luis = (LuisService)service;
                    if (luis == null)
                    {
                        throw new InvalidOperationException("The LUIS service is not configured correctly in your '.bot' file.");
                    }

                    // CAUTION: Authoring key is used in this example as it is appropriate for prototyping.
                    // When implimenting for deployment/production, assign and use a subscription key instead of an authoring key.
                    var app        = new LuisApplication(luis.AppId, luis.AuthoringKey, luis.GetEndpoint());
                    var recognizer = new LuisRecognizer(app);
                    this.LuisServices.Add(luis.Name, recognizer);
                    break;
                }
                }
            }
        }
コード例 #16
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>();

            // Create instance for Bing Spell Check
            LuisPredictionOptions lpo = new LuisPredictionOptions
            {
                BingSpellCheckSubscriptionKey = bingSpellCheckKey,
                SpellCheck = true,
            };

            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 anaysis.
                    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 " + luis.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.Split("_").LastOrDefault(), 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 anaysis.
                    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.");
                    }

                    if (string.IsNullOrWhiteSpace(bingSpellCheckKey))
                    {
                        throw new InvalidOperationException("The BingSpellCheckKey ('bingSpellCheckKey') 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, lpo);
                    luisServices.Add(dispatch.Name.Split("_").Last(), 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,
                    };

                    // Using QnAMakerOptions class allows you to return the top 3, 4, 5, etc. results
                    var qnaMaker = new QnAMaker(qnaEndpoint, options: new QnAMakerOptions {
                            Top = 3, ScoreThreshold = .6f
                        });
                    // You only want the top answer for Chitchat, otherwise the responses are confusing
                    var qnaMaker_chitchat = new QnAMaker(qnaEndpoint, options: new QnAMakerOptions {
                            Top = 1, ScoreThreshold = .6f
                        });

                    if (qna.Name == "Chitchat-Shell")
                    {
                        qnaServices.Add(qna.Name, qnaMaker_chitchat);
                    }
                    else
                    {
                        qnaServices.Add(qna.Name, qnaMaker);
                    }

                    break;
                }
                }
            }

            return(new BotServices(qnaServices, luisServices));
        }
コード例 #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">A dictionary of named <see cref="LuisRecognizer"/> instances for usage within the bot.</param>
        public BotServices(BotConfiguration botConfiguration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.Luis:
                {
                    var luis = (LuisService)service;
                    if (luis == null)
                    {
                        throw new InvalidOperationException("The LUIS service is not configured correctly in your '.bot' file.");
                    }

                    // CAUTION: Authoring key is used in this example as it is appropriate for prototyping.
                    // When implimenting for deployment/production, assign and use a subscription key instead of an authoring key.
                    var app        = new LuisApplication(luis.AppId, luis.AuthoringKey, luis.GetEndpoint());
                    var recognizer = new LuisRecognizer(app);
                    LuisServices.Add(luis.Name, recognizer);
                    break;
                }

                case ServiceTypes.QnA:
                {
                    // Create a QnA Maker that is initialized and suitable for passing
                    // into the IBot-derived class (QnABot).
                    var qna = (QnAMakerService)service;
                    if (qna == null)
                    {
                        throw new InvalidOperationException("The QnA service is not configured correctly in your '.bot' file.");
                    }

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

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

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

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

                    var qnaMaker = new QnAMaker(qnaEndpoint);
                    QnaServices.Add(qna.Name, qnaMaker);

                    break;
                }
                }
            }
        }
コード例 #18
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));
        }
コード例 #19
0
        //   public static object RecognizerResult { get; private set; }

        public static async Task <IncidentDetails> ExecuteLuisQuery(IConfiguration configuration, ILogger logger, ITurnContext turnContext, /*RecognizerResult luisresult,*/ CancellationToken cancellationToken)
        {
            var incidentDetails = new IncidentDetails();


            //  RecognizerResult = luisresult;

            try
            {
                // Create the LUIS settings from configuration.
                var luisApplication = new LuisApplication(
                    configuration["LuisAppIdForSnow"],
                    configuration["LuisAPIKey"],
                    configuration["LuisAPIHostNameforiter"]
                    // $"https://{configuration["LuisAPIHostName"]}.api.cognitive.microsoft.com"))
                    );



                var recognizer = new LuisRecognizer(luisApplication);

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


                //  var intent = luisresult.GetTopScoringIntent();

                //  var (intent, score) = luisresult.GetTopScoringIntent();

                var(intent, score) = recognizerResult.GetTopScoringIntent();
                if (intent == "SAP")
                {
                    incidentDetails.SAP = "true";
                }
                else
                {
                    incidentDetails.SAP = "false";
                }

                if (intent == "create_incident")
                {
                    incidentDetails.Create_incident = "true";

                    // We need to get the result from the LUIS JSON which at every level returns an array.
                    //    incidentDetails.Destination = recognizerResult.Entities["To"]?.FirstOrDefault()?["Airport"]?.FirstOrDefault()?.FirstOrDefault()?.ToString();
                    //  incidentDetails.Origin = recognizerResult.Entities["From"]?.FirstOrDefault()?["Airport"]?.FirstOrDefault()?.FirstOrDefault()?.ToString();

                    // This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part.
                    // TIMEX is a format that represents DateTime expressions that include some ambiguity. e.g. missing a Year.
                    //incidentDetails.TravelDate = recognizerResult.Entities["datetime"]?.FirstOrDefault()?["timex"]?.FirstOrDefault()?.ToString().Split('T')[0];


                    //  BeginDialogAsync(nameof(IncidentDialog), incidentDetails, cancellationToken);
                }
                else
                {
                    incidentDetails.Create_incident = "false";
                }



                if (intent == "create_catlog")
                {
                    incidentDetails.Create_catalog = "true";

                    // We need to get the result from the LUIS JSON which at every level returns an array.
                    //    incidentDetails.Destination = recognizerResult.Entities["To"]?.FirstOrDefault()?["Airport"]?.FirstOrDefault()?.FirstOrDefault()?.ToString();
                    //  incidentDetails.Origin = recognizerResult.Entities["From"]?.FirstOrDefault()?["Airport"]?.FirstOrDefault()?.FirstOrDefault()?.ToString();

                    // This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part.
                    // TIMEX is a format that represents DateTime expressions that include some ambiguity. e.g. missing a Year.
                    //incidentDetails.TravelDate = recognizerResult.Entities["datetime"]?.FirstOrDefault()?["timex"]?.FirstOrDefault()?.ToString().Split('T')[0];


                    //  BeginDialogAsync(nameof(IncidentDialog), incidentDetails, cancellationToken);
                }
                else
                {
                    incidentDetails.Create_catalog = "false";
                }



                if (intent == "None")
                {
                    incidentDetails.None = "true";
                }
                else
                {
                    incidentDetails.None = "false";
                }

                if (intent == "incident_status")
                {
                    incidentDetails.Incident_status = "true";

                    incidentDetails.Incident_No = recognizerResult.Entities["incident_no"]?.FirstOrDefault().ToString();
                }
                else
                {
                    incidentDetails.Incident_status = "false";
                }
            }
            catch (Exception e)
            {
                logger.LogWarning($"LUIS Exception: {e.Message} Check your LUIS configuration.");
            }

            return(incidentDetails);
        }
コード例 #20
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            Logger.LogInformation("Running dialog with Message Activity.");
            var Details = await _TokenAccessor.GetAsync(turnContext, () => new StoredDetails(), cancellationToken);

            var p = Details.TokenResponse;

            // Run the Dialog with the new message Activity.
            if ((p != null) && (turnContext.Activity.Text != "logout"))
            {
                if (turnContext.Activity.Type == ActivityTypes.Message)
                {
                    if (string.IsNullOrEmpty(turnContext.Activity.Text))
                    {
                        dynamic value = turnContext.Activity.Value;
                        string  tex   = value["id"];// The property will be named after your text input's ID
                        if (value != null)
                        {
                            if (tex == "submit_others")
                            {
                                string data = value["data_others"];
                                if (data == "")
                                {
                                    await turnContext.SendActivityAsync(MessageFactory.Text($"Please fill all fields above."), cancellationToken);
                                }
                                else
                                {
                                    await turnContext.SendActivityAsync(MessageFactory.Text($"Your Complaint is Registered with us successfully.\nPlease note down Reference Number :HG1278 for further Reference."), cancellationToken);
                                    await SendSuggestedActionsAsync(turnContext, cancellationToken);
                                }
                            }
                            else if (tex == "submit_others_cancel")
                            {
                                await SendSuggestedActionsAsync(turnContext, cancellationToken);
                            }
                            else if (tex == "submit_forgotpassword")
                            {
                                string dataInput1 = value["FP_userid"];
                                string dataInput2 = value["FP_mobilenumber"];
                                string dataInput3 = value["FP_emailid"];
                                string dataInput4 = value["FP_choiceset"];
                                if ((dataInput1 == "") || (dataInput2 == "") || (dataInput3 == "") || (dataInput4 == ""))
                                {
                                    await turnContext.SendActivityAsync(MessageFactory.Text($"Please fill all fields above."), cancellationToken);
                                }
                                else
                                {
                                    await turnContext.SendActivityAsync(MessageFactory.Text($"Request for Physical Password has been registered successfully.\nIt will reach your registered Address within 8 working days."), cancellationToken);
                                    await SendSuggestedActionsAsync(turnContext, cancellationToken);
                                }
                            }
                            else if (tex == "submit_forgotpassword_cancel")
                            {
                                await SendSuggestedActionsAsync(turnContext, cancellationToken);
                            }
                            else if (tex == "submit_otp")
                            {
                                string data = value["otp_data"];
                                if (data == "")
                                {
                                    await turnContext.SendActivityAsync(MessageFactory.Text($"Please fill all fields above."), cancellationToken);
                                }
                                else
                                {
                                    await turnContext.SendActivityAsync(MessageFactory.Text($"Your Mobile Number for OTP is registered successfully.Please note down Reference Number :HG1278 for further Reference."), cancellationToken);
                                    await SendSuggestedActionsAsync(turnContext, cancellationToken);
                                }
                            }
                            else if (tex == "submit_otp_cancel")
                            {
                                await SendSuggestedActionsAsync(turnContext, cancellationToken);
                            }
                            else if (tex == "submit_checkbook")
                            {
                                string data = value["data_checkbook"];
                                if (data == "")
                                {
                                    await turnContext.SendActivityAsync(MessageFactory.Text($"Please fill all fields above."), cancellationToken);
                                }
                                else
                                {
                                    await turnContext.SendActivityAsync(MessageFactory.Text($"Your Request has been successfully Registered.Please note down Reference Number :HG1278 for further Reference.\nCheck Book will be delivered to Registered Address within 8 working days."), cancellationToken);
                                    await SendSuggestedActionsAsync(turnContext, cancellationToken);
                                }
                            }
                            else if (tex == "submit_checkbook_cancel")
                            {
                                await SendSuggestedActionsAsync(turnContext, cancellationToken);
                            }
                            else if (tex == "submit_updatemobileno")
                            {
                                string data = value["data_updatemobileno"];
                                if (data == "")
                                {
                                    await turnContext.SendActivityAsync(MessageFactory.Text($"Please fill all fields above."), cancellationToken);
                                }
                                else
                                {
                                    await turnContext.SendActivityAsync(MessageFactory.Text($"Your Mobile Number has been updated successfully.Please note down Reference Number :HG1278 for further Reference."), cancellationToken);
                                    await SendSuggestedActionsAsync(turnContext, cancellationToken);
                                }
                            }
                            else if (tex == "submit_updatemobileno_cancel")
                            {
                                await SendSuggestedActionsAsync(turnContext, cancellationToken);
                            }
                        }
                    }
                    else
                    {
                        var luisApplication = new LuisApplication(
                            "bdc48cb4-0945-40e8-8e89-99fec5924d03",
                            "76e8996cfd994ef3a4b79b938c0c2b04",
                            $"https://westus.api.cognitive.microsoft.com");

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

                        var topIntent = recognizerResult.GetTopScoringIntent();
                        // Next, we call the dispatcher with the top intent.
                        await DispatchToTopIntentAsync(turnContext, topIntent.intent, recognizerResult, cancellationToken);

                        //await turnContext.SendActivityAsync(MessageFactory.Text($"Echo: {turnContext.Activity.Text}"), cancellationToken);
                    }
                }


                //await turnContext.SendActivityAsync(MessageFactory.Text($"I am in on message"), cancellationToken);
            }
            else
            {
                await Dialog.Run(turnContext, ConversationState.CreateProperty <DialogState>(nameof(DialogState)), cancellationToken);
            }
        }
コード例 #21
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.
            services.AddSingleton <IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();

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

            //init bot
            services.AddBot <PictureBot>(options =>
            {
                //read appsettings.json
                var secretKey   = Configuration.GetSection("MicrosoftAppId")?.Value;
                var botFilePath = Configuration.GetSection("MicrosoftAppPassword")?.Value;

                options.CredentialProvider = new SimpleCredentialProvider(secretKey, botFilePath);
            });


            services.AddSingleton <PictureBotAccessors>(sp =>
            {
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the state accessors");
                }

                //read Cosmos DB settings from appsettings.json
                CosmosDbStorage _myStorage = new CosmosDbStorage(new CosmosDbStorageOptions
                {
                    AuthKey          = Configuration.GetSection("CosmosDB").GetValue <string>("Key"),
                    CollectionId     = Configuration.GetSection("CosmosDB").GetValue <string>("CollectionName"),
                    CosmosDBEndpoint = new Uri(Configuration.GetSection("CosmosDB").GetValue <string>("EndpointURI")),
                    DatabaseId       = Configuration.GetSection("CosmosDB").GetValue <string>("DatabaseName"),
                });

                var conversationState = new ConversationState(_myStorage);
                var userState         = new UserState(_myStorage);

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

                return(accessors);
            });


            // Create and register a LUIS recognizer.
            services.AddSingleton(sp =>
            {
                // Get LUIS information
                var luisApp = new LuisApplication(
                    "XXX",
                    "XXX",
                    "https://XXXX.api.cognitive.microsoft.com/");

                // Specify LUIS options. These may vary for your bot.
                var luisPredictionOptions = new LuisPredictionOptions
                {
                    IncludeAllIntents = true,
                };

                // Create the recognizer
                var recognizer = new LuisRecognizer(luisApp, luisPredictionOptions, true, null);
                return(recognizer);
            });
        }
コード例 #22
0
        public static async Task <EntitiDetails> ExecuteLuisQuery(IConfiguration configuration, ILogger logger, ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var entitiDetails = new EntitiDetails();

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

                var recognizer = new LuisRecognizer(luisApplication);

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

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

                entitiDetails.Intent = intent;
                entitiDetails.Score  = score;
                //if(score<0.3)
                //    return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("which Acronyn details would you like to have") }, cancellationToken)
                if (intent == "Trigger_Service" || intent == "Build_Deployment")
                {
                    // We need to get the result from the LUIS JSON which at every level returns an array.
                    //entitiDetails.Project = recognizerResult.Entities["service"]?.FirstOrDefault()?["Tag"]?.FirstOrDefault()?.FirstOrDefault()?.ToString();
                    if (recognizerResult.Entities["service"] != null)
                    {
                        entitiDetails.Project = recognizerResult.Entities["service"].First().ToString().Replace("[\r\n  \"", string.Empty).Replace("\"\r\n]", string.Empty);
                    }
                    if (recognizerResult.Entities["Tag"] != null)
                    {
                        entitiDetails.Tag = recognizerResult.Entities["Tag"].First().ToString().Replace("[\r\n  \"", string.Empty).Replace("\"\r\n]", string.Empty);
                    }
                    if (recognizerResult.Entities["Var"] != null)
                    {
                        entitiDetails.Buildwar = recognizerResult.Entities["Var"].First().ToString().Replace("[\r\n  \"", string.Empty).Replace("\"\r\n]", string.Empty);
                    }
                    if (recognizerResult.Entities["Portfolio"] != null)
                    {
                        entitiDetails.Portfolio = recognizerResult.Entities["Portfolio"].First().ToString().Replace("[\r\n  \"", string.Empty).Replace("\"\r\n]", string.Empty);
                    }
                    if (recognizerResult.Entities["Environment"] != null)
                    {
                        entitiDetails.Environment = recognizerResult.Entities["Environment"].First().ToString().Replace("[\r\n  \"", string.Empty).Replace("\"\r\n]", string.Empty);
                    }
                    //entitiDetails.TravelDate = recognizerResult.Entities["datetime"]?.FirstOrDefault()?["timex"]?.FirstOrDefault()?.ToString().Split('T')[0];
                }
                else if (intent == "Acronym")
                {
                    entitiDetails.Acronym = recognizerResult.Entities["Word"].First().ToString().Replace("[\r\n  \"", string.Empty).Replace("\"\r\n]", string.Empty);
                }
            }
            catch (Exception e)
            {
                logger.LogWarning($"LUIS Exception: {e.Message} Check your LUIS configuration.");
            }

            return(entitiDetails);
        }