コード例 #1
0
        public override async Task <RecognizerResult> RecognizeAsync(DialogContext dialogContext, string text, string locale, CancellationToken cancellationToken = default)
        {
            var client     = GetMockedClient(text);
            var recognizer = new LuisRecognizer(_options, client);
            var result     = await recognizer.RecognizeAsync(dialogContext, text, locale, cancellationToken);

            if (client == null)
            {
                // Save response
                var outPath = ResponsePath(text);
                File.WriteAllText(outPath, JsonConvert.SerializeObject(result.Properties["luisResult"]));
            }

            return(result);
        }
コード例 #2
0
        public void NullEndpoint()
        {
            // Arrange
            GetEnvironmentVars();
            var fieldInfo = typeof(LuisRecognizer).GetField("_luisRecognizerOptions", BindingFlags.NonPublic | BindingFlags.Instance);

            // Act
            var myappNull      = new LuisApplication(AppId, Key, null);
            var recognizerNull = new LuisRecognizer(new LuisRecognizerOptionsV3(myappNull), null);

            // Assert
            var app = (LuisRecognizerOptions)fieldInfo.GetValue(recognizerNull);

            Assert.Equal("https://westus.api.cognitive.microsoft.com", app.Application.Endpoint);
        }
コード例 #3
0
        public void EmptyEndpoint()
        {
            // Arrange
            GetEnvironmentVars();
            var fieldInfo = typeof(LuisRecognizer).GetField("_application", BindingFlags.NonPublic | BindingFlags.Instance);

            // Act
            var myappEmpty      = new LuisApplication(AppId, Key, string.Empty);
            var recognizerEmpty = new LuisRecognizer(myappEmpty, null);

            // Assert
            var app = (LuisApplication)fieldInfo.GetValue(recognizerEmpty);

            Assert.AreEqual("https://westus.api.cognitive.microsoft.com", app.Endpoint);
        }
コード例 #4
0
        public ControlAzureResourceRecognizer(IConfiguration configuration)
        {
            var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId"]) && !string.IsNullOrEmpty(configuration["LuisAPIKey"]) && !string.IsNullOrEmpty(configuration["LuisAPIHostName"]);

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

                LuisRecognizerOptions options = new LuisRecognizerOptionsV3(luisApplication);
                _recognizer = new LuisRecognizer(options);
            }
        }
コード例 #5
0
ファイル: LuisConnectivity.cs プロジェクト: limajim/JimBot
        private static async Task <RecognizerResult> GetResults(string question, IConfiguration configuration)
        {
            var luisSettings    = configuration.GetSection("LUISSettings");
            var modelId         = luisSettings["ModelId"];
            var subscriptionKey = luisSettings["SubscriptionKey"];
            var url             = luisSettings["Url"];
            var luisModel       = new LuisModel(modelId, subscriptionKey, new System.Uri(url));

            LuisRecognizer luisRecognizer1;

            luisRecognizer1 = new LuisRecognizer(luisModel);
            var recognizerResult = await luisRecognizer1.Recognize(question, System.Threading.CancellationToken.None);

            return(recognizerResult);
        }
コード例 #6
0
        private DialogSet ComposeRootDialog()
        {
            var dialogs = new DialogSet();

            dialogs.Add(nameof(MainBot), new WaterfallStep[]
            {
                async(dc, args, next) =>
                {
                    var utterance = dc.Context.Activity.Text?.Trim().ToLowerInvariant();

                    if (!string.IsNullOrEmpty(utterance))
                    {
                        // Decide which dialog to start based on top scoring Luis intent
                        var luisResult = await LuisRecognizer.Recognize <BankoLuisModel>(utterance, new CancellationToken());

                        // Decide which dialog to start.
                        switch (luisResult.TopIntent().intent)
                        {
                        case BankoLuisModel.Intent.Balance:
                            await dc.Begin(nameof(BalanceDialogContainer));
                            break;

                        case BankoLuisModel.Intent.Transfer:
                            var dialogArgs = new Dictionary <string, object>();
                            dialogArgs.Add(Keys.LuisArgs, luisResult.Entities);
                            await dc.Begin(nameof(TransferDialogContainer), dialogArgs);
                            break;

                        case BankoLuisModel.Intent.None:
                        default:
                            await dc.Context.SendActivity($"I dont know what you want to do. Type `make a transfer` or `get a balance`.");
                            await next();
                            break;
                        }
                    }
                    else
                    {
                        await dc.End();
                    }
                }
            });

            // Add our child dialogs.
            dialogs.Add(nameof(BalanceDialogContainer), BalanceDialogContainer.Instance);
            dialogs.Add(nameof(TransferDialogContainer), TransferDialogContainer.Instance);

            return(dialogs);
        }
コード例 #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EchoWithCounterBot"/> class.
        /// </summary>
        /// <param name="accessors">A class containing <see cref="IStatePropertyAccessor{T}"/> used to manage state.</param>
        /// <param name="loggerFactory">A <see cref="ILoggerFactory"/> that is hooked to the Azure App Service provider.</param>
        /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.1#windows-eventlog-provider"/>
        public EchoWithCounterBot(EchoBotAccessors accessors, LuisRecognizer luis)
        {
            _accessors = accessors ?? throw new System.ArgumentNullException("accessor can't be null");

            // DialogState accessor
            _dialogs = new DialogSet(accessors.ConversationDialogState);

            // This array defines how the Waterfall will execute.
            var standard_waterfallSteps = new WaterfallStep[]
            {
                GetAgreementAsync,
                AskFeelingAsync,
                SuicidalThinkingAsync,
                RelationshipAsync,
                FrequencyofFeelingAsync,
                PlanSuicideAsync,
                TrySuicideAsync,
                BeforeResultAsync,
                ResultAsync,
            };

            var feelingAgain_waterfallSteps = new WaterfallStep[]
            {
                ConfirmationAsync,
                SuicidalThinkingAsync,
                RelationshipAsync,
                FrequencyofFeelingAsync,
                TrySuicideAsync,
                PlanSuicideAsync,
                BeforeResultAsync,
                ResultAsync,
            };

            // Add named dialogs to the DialogSet. These names are saved in the dialog state.
            _dialogs.Add(new WaterfallDialog("details", standard_waterfallSteps));
            _dialogs.Add(new WaterfallDialog(Dialogs.ConfirmationAsync, feelingAgain_waterfallSteps));
            _dialogs.Add(new TextPrompt("name"));
            _dialogs.Add(new TextPrompt("feeling"));
            _dialogs.Add(new TextPrompt("confirmation"));
            _dialogs.Add(new TextPrompt("suicidalthinking"));
            _dialogs.Add(new TextPrompt("frequency"));
            _dialogs.Add(new TextPrompt("trysuicide"));
            _dialogs.Add(new TextPrompt("plansuicide"));
            _dialogs.Add(new TextPrompt("beforeresult"));

            // The incoming luis variable is the LUIS Recognizer we added above.
            this.Recognizer = luis ?? throw new System.ArgumentNullException(nameof(luis));
        }
コード例 #8
0
        /// <summary>
        /// Initialize the bot's references to external services.
        /// For example, Luis services created here.  External services are configured
        /// using the <see cref="BotConfiguration"/> class (based on the contents of your .bot file).
        /// </summary>
        /// <param name="config">Configuration object based on your .bot file.</param>
        /// <returns>A <see cref="BotConfiguration"/> representing client objects to access external services the bot uses.</returns>
        /// <seealso cref="BotConfiguration"/>
        /// <seealso cref="LuisRecognizer"/>
        /// <seealso cref="TelemetryClient"/>
        private static BotServices InitBotServices(BotConfiguration config)
        {
            var luisServices = new Dictionary <string, LuisRecognizer>();

            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.Region);
                    var recognizer = new LuisRecognizer(app);
                    luisServices.Add(LuisBot.LuisKey, recognizer);
                    break;
                }
                }
            }

            var connectedServices = new BotServices(luisServices);

            return(connectedServices);
        }
コード例 #9
0
        public FabrikamServiceBot(FabrikamServiceBotAccessors accessors)
        {
            _accessors = accessors ?? throw new System.ArgumentNullException(nameof(accessors));

            //get the luis app id & key
            var MicrosoftLuisAppId = ConfigurationManager.AppSettings["MicrosoftLuisAppId"];
            var MicrosoftLuisKey   = ConfigurationManager.AppSettings["MicrosoftLuisKey"];

            var LuisApp     = new LuisApplication(ConfigurationManager.AppSettings["MicrosoftLuisAppId"], ConfigurationManager.AppSettings["MicrosoftLuisKey"], ConfigurationManager.AppSettings["MicrosoftLuisEndPoint"]);
            var LuisOptions = new LuisPredictionOptions
            {
                IncludeAllIntents = true,
            };

            luisRecognizer = new LuisRecognizer(LuisApp, LuisOptions, true);
        }
コード例 #10
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var luisApplication = new LuisApplication(
                _configuration["LuisApplicationID"],
                _configuration["LuisEndPointKey"],
                _configuration["LuisEndPoint"]);

            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);
        }
コード例 #11
0
        public void LuisRecognizer_Timeout()
        {
            var endpoint = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=";

            var expectedTimeout = 300;

            var opts = new LuisRecognizerOptionsV2(new LuisApplication(endpoint))
            {
                Timeout = 300,
            };

            var recognizerWithTimeout = new LuisRecognizer(opts);

            Assert.IsNotNull(recognizerWithTimeout);
            Assert.AreEqual(expectedTimeout, LuisRecognizer.DefaultHttpClient.Timeout.Milliseconds);
        }
コード例 #12
0
        public TeamsActionRecognizer(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"]);

                _recognizer = new LuisRecognizer(luisApplication);
            }
        }
コード例 #13
0
        public EchoBot(EchoBotAccessors accessors, IOptions <MySettings> config, LuisRecognizer luisRecognizer, QnAMaker qna)
        {
            _accessors = accessors ?? throw new System.ArgumentNullException(nameof(accessors));
            QnA        = qna ?? throw new ArgumentNullException(nameof(qna));

            // Initialize the dialogs
            _dialogs = new DialogSet(_accessors.ConversationDialogState);

            // Initialize the TTSS

            // Initialize the LUIS recognizer
            _luis = luisRecognizer;

            // Register the dialog
            _dialogs.Add(new ReservationDialog(_accessors.ReservationState, null));
        }
コード例 #14
0
        public EchoBot(EchoBotAccessors accessors, LuisRecognizer luisRecognizer, IConfiguration configuration, IBotTelemetryClient telemetry)
        {
            _accessors = accessors ?? throw new System.ArgumentNullException(nameof(accessors));

            _dialogs = new DialogSet(_accessors.ConversationDialogState);

            _luis = luisRecognizer;

            Configuration = configuration;

            _telemetry = telemetry;

            dh = new DialogHelper();

            _ttsService = new TextToSpeechService();

            var waterfallSteps = new WaterfallStep[]
            {
                ZeroStepAsync,
                FirstStepAsync,
                SecondStepAsync,
                ThirdStepAsync,
                FourthStepAsync,
            };

            var waterfallSteps2 = new WaterfallStep[]
            {
                Assessment_ZeroStep,
                Assessment_FirstStep,
            };

            var waterfallSteps3 = new WaterfallStep[]
            {
                Count_ZeroStep,
                Count_FirstStep,
            };

            _dialogs.Add(new WaterfallDialog("booking", waterfallSteps));
            _dialogs.Add(new WaterfallDialog("navigation", waterfallSteps2));
            _dialogs.Add(new WaterfallDialog("YesNo", waterfallSteps3));
            _dialogs.Add(new TextPrompt("B1"));
            _dialogs.Add(new TextPrompt("B2"));
            _dialogs.Add(new TextPrompt("B3"));
            _dialogs.Add(new TextPrompt("B4"));
            _dialogs.Add(new TextPrompt("YN1"));
            _dialogs.Add(new TextPrompt("N1"));
        }
コード例 #15
0
ファイル: WeatherBotBot.cs プロジェクト: nomada2/WeatherBot
        private DialogSet ComposeRootDialog()
        {
            var dialogs = new DialogSet();

            try
            {
                dialogs.Add(nameof(WeatherBot), new WaterfallStep[]
                {
                    async(dc, args, next) =>
                    {
                        try
                        {
                            var utterance = dc.Context.Activity.Text?.Trim().ToLowerInvariant();

                            if (!string.IsNullOrEmpty(utterance))
                            {
                                // Decide which dialog to start based on top scoring Luis intent
                                var luisResult = await LuisRecognizer.Recognize <WeatherLuisModel>(utterance, new CancellationToken());

                                // Decide which dialog to start.
                                switch (luisResult.TopIntent().intent)
                                {
                                case WeatherLuisModel.Intent.Get_Weather_Condition:
                                    var dialogArgs = new Dictionary <string, object>();
                                    dialogArgs.Add(Constantes.LuisArgs, luisResult.Entities);
                                    await dc.Begin(nameof(WeatherDialogContainer), dialogArgs);
                                    break;
                                }
                            }
                            else
                            {
                                await dc.End();
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                });
            }
            catch (Exception ex)
            {
            }
            // Add our child dialogs.
            dialogs.Add(nameof(WeatherDialogContainer), WeatherDialogContainer.Instance);
            return(dialogs);
        }
コード例 #16
0
        private static BotServices InitBotServices(BotConfiguration config)
        {
            var qnaServices  = new Dictionary <string, QnAMaker>();
            var luisServices = new Dictionary <string, LuisRecognizer>();

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

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

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

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

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

            return(new BotServices(qnaServices, luisServices));
        }
コード例 #17
0
        private Dictionary <string, LuisRecognizer> BuildDictionary(IBotTelemetryClient botTelemetryClient = null)
        {
            Dictionary <string, LuisRecognizer> result = new Dictionary <string, LuisRecognizer>();

            foreach (LuisApp app in config.LuisApplications)
            {
                var luis = new LuisApplication(app.AppId, app.AuthoringKey, app.Endpoint);

                LuisPredictionOptions luisPredictionOptions = null;
                LuisRecognizer        recognizer            = null;

                bool needsPredictionOptions = false;
                if ((!string.IsNullOrEmpty(config.BingSpellCheckSubscriptionKey)) || (config.EnableLuisTelemetry))
                {
                    needsPredictionOptions = true;
                }

                if (needsPredictionOptions)
                {
                    luisPredictionOptions = new LuisPredictionOptions();

                    if (config.EnableLuisTelemetry)
                    {
                        luisPredictionOptions.TelemetryClient        = botTelemetryClient;
                        luisPredictionOptions.Log                    = true;
                        luisPredictionOptions.LogPersonalInformation = true;
                    }

                    if (!string.IsNullOrEmpty(config.BingSpellCheckSubscriptionKey))
                    {
                        luisPredictionOptions.BingSpellCheckSubscriptionKey = config.BingSpellCheckSubscriptionKey;
                        luisPredictionOptions.SpellCheck        = true;
                        luisPredictionOptions.IncludeAllIntents = true;
                    }

                    recognizer = new LuisRecognizer(luis, luisPredictionOptions);
                }
                else
                {
                    recognizer = new LuisRecognizer(luis);
                }

                result.Add(app.Name, recognizer);
            }

            return(result);
        }
コード例 #18
0
        public ThirdThursdayBot(IConfiguration configuration)
        {
            //_service = new FirebaseService(configuration.GetSection("DatabaseEndpoint")?.Value);
            _service     = new FirebaseServiceMock(configuration.GetSection("DatabaseEndpoint")?.Value);
            _yelpService = new YelpService(
                configuration.GetSection("YelpClientId")?.Value,
                configuration.GetSection("YelpClientSecret")?.Value,
                configuration.GetSection("YelpPreferredLocation")?.Value
                );

            var luidModelId         = configuration.GetSection($"Luis-ModelId-Lunch")?.Value;
            var luisSubscriptionKey = configuration.GetSection("Luis-SubscriptionKey")?.Value;
            var luisUri             = configuration.GetSection("Luis-Url")?.Value;

            this.luisLunchModel = new LuisApplication(luidModelId, luisSubscriptionKey, luisUri);
            this.luisRecognizer = new LuisRecognizer(luisLunchModel);
        }
コード例 #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CarWashBot"/> class.
        /// </summary>
        /// <param name="accessors">The state accessors for managing bot state.</param>
        /// <param name="botConfig">The parsed .bot config file.</param>
        /// <param name="services">External services.</param>
        /// <param name="loggerFactory">Logger.</param>
        /// <param name="telemetryClient">Telemetry client.</param>
        public CarWashBot(StateAccessors accessors, BotConfiguration botConfig, BotServices services, ILoggerFactory loggerFactory, TelemetryClient telemetryClient)
        {
            _accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));
            if (botConfig == null)
            {
                throw new ArgumentNullException(nameof(botConfig));
            }
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            _telemetryClient = telemetryClient;

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

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

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

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

            // Dialogs.Add(FormDialog.FromForm(NewReservationForm.BuildForm));
        }
コード例 #20
0
 public BotServices(BotConfiguration botConfiguration)
 {
     foreach (var service in botConfiguration.Services)
     {
         switch (service.Type)
         {
         case ServiceTypes.Luis:
         {
             var luis       = (LuisService)service;
             var app        = new LuisApplication(luis.AppId, luis.AuthoringKey, luis.GetEndpoint());
             var recognizer = new LuisRecognizer(app);
             LuisServices.Add(luis.Name, recognizer);
             break;
         }
         }
     }
 }
コード例 #21
0
        public ChatBoxBot(ConversationState conversationState, UserState userState, IChannelClient client,
                          QnAMaker qna, LuisRecognizer luis, ILoggerFactory loggerFactory)
        {
            _userState        = userState;
            _converationState = conversationState;
            QnA        = qna;
            Recognizer = luis;
            ConversationDialogState = _converationState.CreateProperty <DialogState>($"{nameof(ChatBox)}.ConversationDialogState");
            UserSelectionsState     = _userState.CreateProperty <UserSelections>($"{nameof(ChatBox)}.UserSelectionsState");

            _logger  = loggerFactory.CreateLogger <ChatBoxBot>();
            _dialogs = new DialogSet(ConversationDialogState);
            _dialogs.Add(new WhenNextDialog(Constants.WhenNextIntent, UserSelectionsState, client));
            _dialogs.Add(new SetTimezoneDialog(Constants.SetTimezoneIntent, UserSelectionsState));
            _dialogs.Add(new LiveNowDialog(Constants.LiveNow, client));
            _dialogs.Add(new DiscoveryDialog(Constants.DiscoverIntent, client));
        }
コード例 #22
0
        public LuisService(IConfiguration configuration)
        {
            var luisApplication = new LuisApplication(
                configuration["LuisAppId"],
                configuration["LuisApiKey"],
                configuration["LuisHostName"]
                );
            var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
            {
                PredictionOptions = new Microsoft.Bot.Builder.AI.LuisV3.LuisPredictionOptions()
                {
                    IncludeInstanceData = true
                }
            };

            _luisRecognizer = new LuisRecognizer(recognizerOptions);
        }
コード例 #23
0
        //ToDo: Revisit this once we have more channels
        //private List<IConversationalHubChannel> _channels;

        public ConversationalHub(
            ITranscriptRepository transcriptRepository
            , IHubRepository hubRepository
            , ISpeechService speechRepository
            , LuisRecognizer dispatch
            , List <BotIntent> botIntents
            )
        {
            //ToDo: Revisit this once we have more channels
            //_channels = new List<IConversationalHubChannel>();

            _transcriptRepo = transcriptRepository;
            _hubRepo        = hubRepository;
            _speechRepo     = speechRepository;
            _dispatch       = dispatch;
            _botIntents     = botIntents;
        }
コード例 #24
0
        public AddressRecognizer(IConfiguration configuration)
        {
            var luisKeyKey      = "LuisAPIKey" + configuration["region"];
            var luisHostNameKey = "LuisAPIHostName" + configuration["region"];

            var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId"]) && !string.IsNullOrEmpty(configuration[luisKeyKey]) && !string.IsNullOrEmpty(configuration[luisHostNameKey]);

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

                _recognizer = new LuisRecognizer(luisApplication);
            }
        }
コード例 #25
0
        /// <summary>
        /// Creates the analyzer.
        /// </summary>
        /// <param name="config">The configuration of the bot</param>
        /// <param name="lang">Defines the language.</param>
        /// <param name="threshold">The default threshold for Luis classification.</param>
        /// <exception cref="ArgumentException">unsupported language.</exception>
        public LUISQuestionAnalyzer(IConfiguration config, Language lang, double threshold)
        {
            if (!Configs.ContainsKey(lang))
            {
                throw new ArgumentException("Your Language is not supported.");
            }
            var map = config.GetSection("QuestionAnalyzer").GetSection(Configs[lang]).Get <Dictionary <string, object> >();
            LuisServiceDefinition lsd = JsonConvert.DeserializeObject <LuisServiceDefinition>(JsonConvert.SerializeObject(map));

            _classifier = new LuisRecognizer(
                new LuisRecognizerOptionsV2(new LuisApplication(lsd.GetLuisService()))
            {
                PredictionOptions = lsd.GetPredictOpts()
            }
                );
            _threshold = threshold;
        }
コード例 #26
0
        public MainBot(IConfiguration configuration)
        {
            // Create DialogSet
            _dialogs = ComposeRootDialog();

            // Create the LUIS recognizer for our model.
            var luisRecognizerOptions = new LuisRecognizerOptions {
                Verbose = true
            };
            var luisModel = new LuisModel(
                configuration[Keys.LuisModel],
                configuration[Keys.LuisSubscriptionKey],
                new Uri(configuration[Keys.LuisUriBase]),
                LuisApiVersion.V2);

            LuisRecognizer = new LuisRecognizer(luisModel, luisRecognizerOptions, null);
        }
コード例 #27
0
        public static async Task <LUISResponse> ExecuteLuisQuery(IConfiguration configuration, ILogger logger, ITurnContext turnContext, CancellationToken cancellationToken)
        {
            LUISResponse response = new LUISResponse();

            try
            {
                // Cria as configurações do LUIS a partir da configuração.
                var luisApplication = new LuisApplication(
                    configuration["LuisAppId"],
                    configuration["LuisAPIKey"],
                    "https://" + configuration["LuisAPIHostName"]
                    );

                var recognizer = new LuisRecognizer(luisApplication);

                // Chama o LUIS
                var recognizerResult = await recognizer.RecognizeAsync(turnContext, cancellationToken);

                var(intent, score) = recognizerResult.GetTopScoringIntent();
                Enum.TryParse(intent, out Intencao intencao);
                response.Intencao = intencao;

                switch (intencao)
                {
                case Intencao.conversa_saudacao:
                    break;

                case Intencao.conversa_sobre:
                    break;

                case Intencao.moeda_cotacao:
                    response.Entidade = recognizerResult.Entities["Moeda"]?.FirstOrDefault().ToString();
                    break;

                case Intencao.moeda_listagem:
                    break;
                }
            }
            catch (Exception e)
            {
                logger.LogWarning($"Exceção LUIS: {e.Message} Verifique sua configuração LUIS.");
            }

            return(response);
        }
コード例 #28
0
        public async Task Telemetry_NoPiiLoggedAsync()
        {
            // 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 result = await recognizer.RecognizeAsync(turnContext).ConfigureAwait(false);

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(telemetryClient.Invocations.Count, 1);
            Assert.AreEqual(telemetryClient.Invocations[0].Arguments[0].ToString(), "LuisResult");
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).Count == 7);
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("applicationId"));
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("intent"));
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("intentScore"));
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("intent2"));
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("intentScore2"));
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("fromId"));
            Assert.IsTrue(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("entities"));
            Assert.IsFalse(((Dictionary <string, string>)telemetryClient.Invocations[0].Arguments[1]).ContainsKey("question"));
        }
コード例 #29
0
        public static async Task <BookingHotelDetail> ExecuteLuisQuery(IConfiguration configuration, ILogger logger, ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var bookingDetails = new BookingDetail();

            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 == "订酒店")
                {
                    // We need to get the result from the LUIS JSON which at every level returns an array.
                    if (recognizerResult.Entities["location"] == null || recognizerResult.Entities["datetimeV2"] == null)
                    {
                        Console.WriteLine("Error :");
                        Console.WriteLine("LUIS setting Error");
                        Console.WriteLine("LUIS model training uncertain,There are some entites missing.");
                        // bookingDetails.Location = "北京市";
                        // bookingDetails.StartDate = "2019-07-20";
                    }

                    // bookingDetails.Location = recognizerResult.Entities["location"]?.ToString();
                    // bookingDetails.StartDate = recognizerResult.Entities["datetimeV2"]?.ToString();
                }
                // logger.LogWarning($"Predidct by luis.ai result that your intent is {intent} with score {score}");
                Console.WriteLine(intent);
                Console.WriteLine(score);
            }
            catch (Exception e)
            {
                logger.LogWarning($"LUIS Exception: {e.Message} Check your LUIS configuration.");
            }

            return(bookingDetails);
        }
コード例 #30
0
        public void Telemetry_Construction()
        {
            // 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 fieldInfo = typeof(LuisRecognizer).GetField("_application", BindingFlags.NonPublic | BindingFlags.Instance);

            // Act
            var recognizer = new LuisRecognizer(new LuisApplication(endpoint));

            // Assert
            var app = (LuisApplication)fieldInfo.GetValue(recognizer);

            Assert.AreEqual("b31aeaf3-3511-495b-a07f-571fc873214b", app.ApplicationId);
            Assert.AreEqual("048ec46dc58e495482b0c447cfdbd291", app.EndpointKey);
            Assert.AreEqual("https://westus.api.cognitive.microsoft.com", app.Endpoint);
        }