Пример #1
0
        public async Task StartAsync(IDialogContext context)
        {
            luis = new LuisService(
                new LuisModelAttribute(
                    Settings.Instance.LuisAppId,
                    Settings.Instance.LuisSubscriptionKey,
                    LuisApiVersion.V2,
                    domain: Settings.Instance.LuisAPIHostName
                    ));

            context.Wait(MessageReceivedAsync);
        }
Пример #2
0
        public void NullOrEmptyIntents_DefaultsTo_TopScoringIntent()
        {
            var intent = new IntentRecommendation();
            var result = new LuisResult()
            {
                TopScoringIntent = intent
            };

            LuisService.Fix(result);

            Assert.AreEqual(1, result.Intents.Count);
            Assert.AreEqual(intent, result.Intents[0]);
        }
Пример #3
0
        /// <summary>
        /// Query Luis API (Async).
        /// </summary>
        /// <param name="query">Luis Query.</param>
        /// <returns></returns>
        internal static async Task <dynamic> RunQuery(string query)
        {
            // Process message

            LuisService luisService = new LuisService(new LuisModelAttribute(ConfigurationManager.AppSettings["LuisConfiguration:AppId"], ConfigurationManager.AppSettings["LuisConfiguration:AppSecret"]));

            LuisResult luisResult = await luisService.QueryAsync(query, CancellationToken.None);

            IList <EntityRecommendation> luisEntities = luisResult.Entities;
            IList <IntentRecommendation> luisIntents  = luisResult.Intents;

            return(luisResult);
        }
        /// <summary>
        /// Converts a Luis service definition into a Luis service.
        /// </summary>
        /// <returns>The Luis service.</returns>
        public LuisService GetLuisService()
        {
            LuisService ls = new LuisService
            {
                AppId           = AppId,
                AuthoringKey    = AuthoringKey,
                SubscriptionKey = SubscriptionKey,
                Version         = Version,
                Region          = Region
            };

            return(ls);
        }
Пример #5
0
        /// <summary>
        /// Demande à luis la comprehension
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public async Task <JsonResult> GetReponse(string result)
        {
            var actions = GetJsonModels();
            //UserConnect.GetContext(HttpContext);
            LuisService luisService = new LuisService();
            var         resultLuis  = await luisService.SendRequest(result);

            var resultRequest = actions.Where(a => a.Intent == resultLuis.TopScoringIntent.Intent).FirstOrDefault();

            return(new JsonResult()
            {
                Data = "Test", JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
        public async Task <T> GetResultDate(string text)
        {
            Result = default(T);
            //invoke LUIS
            if (string.IsNullOrEmpty(text))
            {
                return(default(T));
            }
            if ((EqualityComparer <T> .Default.Equals(Result, default(T))))
            {
                LuisService luis = new LuisService(new LuisModelAttribute(
                                                       modelID: ConfigurationManager.AppSettings["LuisModel"],
                                                       subscriptionKey: ConfigurationManager.AppSettings["LuisKey"],
                                                       apiVersion: LuisApiVersion.V2
                                                       ));
                bool hasResult = true;
                var  result    = Task.Run(() => luis.QueryAsync(new LuisRequest(text), System.Threading.CancellationToken.None)).Result;
                EntityRecommendation datetime = null;
                if (!result.TryFindEntity("builtin.datetimeV2.datetime", out datetime) &&
                    !result.TryFindEntity("builtin.datetimeV2.date", out datetime) &&
                    !result.TryFindEntity("builtin.datetimeV2.time", out datetime) &&
                    !result.TryFindEntity("builtin.datetimeV2.duration", out datetime))
                {
                    hasResult = false;
                }

                if (!hasResult)
                {
                    Result = default(T);
                }
                else
                {
                    //Result = datetime.ToDateTime();
                    if (Result.GetType() == typeof(DateTimeOffset))
                    {
                        Result = (T)Convert.ChangeType(datetime.ToDateTime(), typeof(DateTimeOffset));
                    }
                    else if (Result.GetType() == typeof(TimeSpan))
                    {
                        Result = (T)Convert.ChangeType(datetime.ToTimeSpan(), typeof(TimeSpan));
                    }
                    else if ((Result.GetType() == typeof(Int64)))
                    {
                        Result = (T)Convert.ChangeType(datetime.ToInt64(), typeof(Int64));
                    }
                }
            }
            return(Result);
        }
Пример #7
0
        public static async Task <LuisResult> GetIntentAndEntitiesFromLUIS(string query)
        {
            LuisService luisService = new LuisService(
                new LuisModelAttribute(
                    ConfigurationManager.AppSettings["LuisAppId"],
                    ConfigurationManager.AppSettings["LuisAPIKey"],
                    LuisApiVersion.V2,
                    ConfigurationManager.AppSettings["LuisAPIHostName"],
                    double.Parse(ConfigurationManager.AppSettings["LuisAPIThreshold"], System.Globalization.CultureInfo.InvariantCulture)
                    )
                );
            LuisResult luisData = await luisService.QueryAsync(query, CancellationToken.None);

            return(luisData);
        }
Пример #8
0
        public async Task Query_ReturnsModelWithIntents_WhenCommandQuered()
        {
            var settingsMock = new Mock <ISettings>();

            settingsMock.Setup(x => x.LuisAppUri)
            .Returns($"{Config["LuisApp:Uri"]}?subscription-key={Config["LuisApp:Key"]}&verbose=true&timezoneOffset=0");

            var luisService = new LuisService(settingsMock.Object);

            var result = await luisService.Query("Who let the dog out??");

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Intents);
            Assert.AreNotEqual(result.Intents.Count, 0);
        }
Пример #9
0
        public void LuisApplication_Configuration()
        {
            var service = new LuisService
            {
                AppId           = Guid.NewGuid().ToString(),
                SubscriptionKey = Guid.NewGuid().ToString(),
                Region          = "westus"
            };

            var model = new LuisApplication(service);

            Assert.AreEqual(service.AppId, model.ApplicationId);
            Assert.AreEqual(service.SubscriptionKey, model.EndpointKey);
            Assert.AreEqual(service.GetEndpoint(), model.Endpoint);
        }
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            switch (activity.GetActivityType())
            {
            // all messages pass through one dialog for now
            case ActivityTypes.Message:
                LuisModelAttribute attr    = new LuisModelAttribute(ConfigurationManager.AppSettings[Constants.LuisModelIdKey], ConfigurationManager.AppSettings[Constants.LuisSubscriptionKey]);
                LuisService        luisSvc = new LuisService(attr);
                await Conversation.SendAsync(activity, () => new GitHubLuisDialog(luisSvc));

                break;

            // send a "hello" to someone who just joined the conversation (not all channels support this)
            case ActivityTypes.ConversationUpdate:
                IConversationUpdateActivity update = activity;
                using (ILifetimeScope scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
                {
                    IConnectorClient client = scope.Resolve <IConnectorClient>();
                    if (update.MembersAdded.Any())
                    {
                        Activity reply = activity.CreateReply();
                        IEnumerable <ChannelAccount> newMembers = update.MembersAdded?.Where(t => t.Id != activity.Recipient.Id);
                        foreach (var newMember in newMembers)
                        {
                            reply.Text = Constants.DemoText + $"Welcome {newMember.Name}! I can help you with getting information about your GitHub repos.";

                            IBotData data = scope.Resolve <IBotData>();
                            await data.LoadAsync(CancellationToken.None);

                            if (data.UserData.ContainsKey(Constants.AuthTokenKey))
                            {
                                reply.Text += " It looks like you're already logged in, so what can I help you with?";
                            }
                            else
                            {
                                reply.Text += " To get started, type **login** to authorize me to talk to GitHub on your behalf, or type **help** to get more information.";
                            }

                            await client.Conversations.ReplyToActivityAsync(reply);
                        }
                    }
                }
                break;
            }

            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }
Пример #11
0
        public static void Validate(this LuisService luisService)
        {
            if (string.IsNullOrWhiteSpace(luisService.AppId))
            {
                throw new InvalidOperationException("The LUIS AppId ('appId') is required to run this sample.");
            }

            if (string.IsNullOrWhiteSpace(luisService.AuthoringKey))
            {
                throw new InvalidOperationException("The LUIS AuthoringKey ('authoringKey') is required to run this sample.");
            }

            if (string.IsNullOrWhiteSpace(luisService.SubscriptionKey))
            {
                throw new InvalidOperationException("The LUIS SubscriptionKey ('subscriptionKey') is required to run this sample.");
            }
        }
Пример #12
0
        private static Func <IDialog <object> > MakeRootDialog()
        {
            //get the luis app id & key
            var MicrosoftLuisAppId = ConfigurationManager.AppSettings["MicrosoftLuisAppId"];
            var MicrosoftLuisKey   = ConfigurationManager.AppSettings["MicrosoftLuisKey"];

            Func <IDialog <object> > luisDialog = null;

            //instantiate the root luis dialog and encapsulate it in a delegate
            luisDialog = () =>
            {
                var luisService = new LuisService(new LuisModelAttribute(MicrosoftLuisAppId, MicrosoftLuisKey));
                return(new Dialogs.RootLuisDialog(luisService));
            };

            return(luisDialog);
        }
Пример #13
0
        public async Task <ActionResult> Index(QueryViewModel model)
        {
            if (!model.HasIntent)
            {
                var luisService = new LuisService(new LuisModelAttribute(ConfigurationManager.AppSettings["LUIS_ModelId"], ConfigurationManager.AppSettings["LUIS_SubscriptionKey"]));
                var luisResult  = await luisService.QueryAsync(model.Query, CancellationToken.None);

                var resolver = new LuisActionResolver(typeof(GetTimeInPlaceAction).Assembly);
                var action   = resolver.ResolveActionFromLuisIntent(luisResult);

                // Triggering Contextual Action from scratch is not supported on this Web Sample
                if (action != null && !LuisActionResolver.IsContextualAction(action))
                {
                    model.LuisAction = action;

                    // TODO: this is dangerous. This should be stored somewhere else, not in the client, or at least encrypted
                    model.LuisActionType = action.GetType().AssemblyQualifiedName;
                }
                else
                {
                    // no action recnogized
                    return(this.View(new QueryViewModel()));
                }
            }

            ModelState.Clear();
            var isValid = TryValidateModel(model.LuisAction);

            if (isValid)
            {
                // fulfill
                var actionResult = await model.LuisAction.FulfillAsync();

                if (actionResult == null)
                {
                    actionResult = "Cannot resolve your query";
                }

                return(this.View("ActionFulfill", actionResult));
            }
            else
            {
                // not valid, continue to present form with missing/invalid parameters
                return(this.View(model));
            }
        }
Пример #14
0
        public async void GetConfigurationTest()
        {
            // arrage
            var storage           = new MemoryStorage();
            var userState         = new UserState(storage);
            var conversationState = new ConversationState(storage);
            var adapter           = new TestAdapter().Use(new AutoSaveStateMiddleware(conversationState));
            var dialogState       = conversationState.CreateProperty <DialogState>("dialogState");
            var dialogs           = new DialogSet(dialogState);
            var steps             = new WaterfallStep[]
            {
                async(step, cancellationToken) =>
                {
                    await step.Context.SendActivityAsync("response");

                    // act
                    ILuisService luisService = new LuisService(EnvironmentName, ContentRootPath, null, null);
                    LuisConfig   config      = luisService.GetConfiguration();

                    // assert
                    Assert.Equal(configuration.BingSpellCheckSubscriptionKey, config.BingSpellCheckSubscriptionKey);
                    Assert.Collection <LuisApp>(configuration.LuisApplications, x => Xunit.Assert.Contains("name", x.Name));
                    Assert.Equal(configuration.LuisRouterUrl, config.LuisRouterUrl);

                    return(Dialog.EndOfTurn);
                }
            };

            dialogs.Add(new WaterfallDialog(
                            "test",
                            steps));

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);
                await dc.ContinueDialogAsync(cancellationToken);
                if (!turnContext.Responded)
                {
                    await dc.BeginDialogAsync("test", null, cancellationToken);
                }
            })
            .Send("ask")
            .AssertReply("response")
            .StartTestAsync();
        }
Пример #15
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                var attributes = new LuisModelAttribute(
                    ConfigurationManager.AppSettings["LUISModelID"],
                    ConfigurationManager.AppSettings["LUISSubscriptionKey"]);
                var service = new LuisService(attributes);
                await Conversation.SendAsync(activity, () => new MyFirstLuisDialog(service));
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Пример #16
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.Register <RootDialog>(c =>
            {
                var settings = c.Resolve <LuisModelSettings>();
                var service  = new LuisService(new LuisModelAttribute(settings.ModelId, settings.SubscriptionKey));

                return(new RootDialog(service));
            });

            builder.RegisterType <OpenOrders>().AsSelf();
            builder.RegisterType <OrderStatus>().AsSelf();
            builder.RegisterType <Representative>().AsSelf();

            builder.RegisterType <DialogFactory>().AsSelf();

            base.Load(builder);
        }
Пример #17
0
        private async Task <DialogTurnResult> FinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken = default)
        {
            var accessor = _userState.CreateProperty <string>("Solicitacao");
            await accessor.SetAsync(stepContext.Context, (string)stepContext.Result, cancellationToken);

            var luisResult = await LuisService.ExecuteLuisQuery(_configuration, stepContext.Context, cancellationToken);

            if (luisResult.intent.Equals("None"))
            {
                return(await stepContext.BeginDialogAsync(nameof(LearningDialog), null, cancellationToken));
            }
            else
            {
                await stepContext.Context.SendActivityAsync(Conversation.Answer(luisResult.intent), cancellationToken : cancellationToken);
            }

            return(await stepContext.ReplaceDialogAsync(nameof(LoopDialog), cancellationToken : cancellationToken));
        }
Пример #18
0
        public JArrayString ProcessMessage(RbAppMasterCache rbappmc, RbAppRouterCache rbapprc, RbHeader rbh, string rbBodyString)
        {
            var appInfo = JsonConvert.DeserializeObject <JObject>(rbappmc.AppInfo);

            appInfo["DeviceId"] = rbh.SourceDeviceId;
            var          appParams = JsonConvert.DeserializeObject <JObject>(rbBodyString);
            JArrayString message   = null;

            if (rbh.MessageId == "Speech")
            {
                var speechAppBody = new SpeechAppBody();
                var personId      = (appParams["PersonId"] ?? "").ToString();
                var talk          = (appParams["talk"] ?? "").ToString();
                var luisService   = new LuisService(rbh.SourceDeviceId, appInfo);
                speechAppBody.Behavior = luisService.CreateRobotBehavior(talk);
                speechAppBody.Behavior.NaturalTalkText = TextOverflow(speechAppBody.Behavior.NaturalTalkText);
                if (personId != "")
                {
                    var actionClient = new HwsRobotBehaviorApi.Person.Action.Client(appInfo["SqlConnectionString"].ToString());
                    foreach (var entity in speechAppBody.Behavior.LuisEntities)
                    {
                        actionClient.CreateTalkLog(rbh.SourceDeviceId, personId, speechAppBody.Behavior.NaturalTalkText, talk, entity);
                    }
                }

                message = new JArrayString(MakeProcessMessages(rbh, speechAppBody));
            }
            else if (rbh.MessageId == "RobotSpeech")
            {
                var speechAppBody = new SpeechAppBody();
                var talk          = (appParams["talk"] ?? "").ToString();
                var luisService   = new LuisService(rbh.SourceDeviceId, appInfo);
                speechAppBody.Behavior = luisService.CreateRobotBehaviorDirectSpeech(talk);
                speechAppBody.Behavior.NaturalTalkText = TextOverflow(speechAppBody.Behavior.NaturalTalkText);
                message = new JArrayString(MakeProcessMessages(rbh, speechAppBody));
            }
            else if (rbh.MessageId == "GetRobotAction")
            {
                var speechAppBody = RobotAction(rbh, appInfo, appParams);
                message = new JArrayString(MakeProcessMessages(rbh, speechAppBody));
            }

            return(message);
        }
Пример #19
0
        public void Uri_Building()
        {
            const string Model        = "model";
            const string Subscription = "subscription";
            const string Domain       = "domain";
            const string Text         = "text";

            // TODO: xunit theory
            var tests = new[]
            {
#pragma warning disable CS0612
                new { m    = new LuisModelAttribute(Model, Subscription, LuisApiVersion.V1, null)
                      {
                      }, u = new Uri("https://api.projectoxford.ai/luis/v1/application?subscription-key=subscription&q=text&id=model&log=True") },
                new { m = new LuisModelAttribute(Model, Subscription, LuisApiVersion.V1, null)
                      {
                          Log = false, SpellCheck = false, Staging = false, TimezoneOffset = 1, Verbose = false
                      }, u = new Uri("https://api.projectoxford.ai/luis/v1/application?subscription-key=subscription&q=text&id=model&log=False&spellCheck=False&staging=False&timezoneOffset=1&verbose=False") },
                new { m = new LuisModelAttribute(Model, Subscription, LuisApiVersion.V1, Domain)
                      {
                          Log = true, SpellCheck = true, Staging = true, TimezoneOffset = 2, Verbose = true
                      }, u = new Uri("https://api.projectoxford.ai/luis/v1/application?subscription-key=subscription&q=text&id=model&log=True&spellCheck=True&staging=True&timezoneOffset=2&verbose=True") },
#pragma warning restore CS0612
                new { m    = new LuisModelAttribute(Model, Subscription, LuisApiVersion.V2, null)
                      {
                      }, u = new Uri("https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/model?subscription-key=subscription&q=text&log=True") },
                new { m = new LuisModelAttribute(Model, Subscription, LuisApiVersion.V2, null)
                      {
                          Log = false, SpellCheck = false, Staging = false, TimezoneOffset = 1, Verbose = false
                      }, u = new Uri("https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/model?subscription-key=subscription&q=text&log=False&spellCheck=False&staging=False&timezoneOffset=1&verbose=False") },
                new { m = new LuisModelAttribute(Model, Subscription, LuisApiVersion.V2, Domain)
                      {
                          Log = true, SpellCheck = true, Staging = true, TimezoneOffset = 2, Verbose = true
                      }, u = new Uri("https://domain/luis/v2.0/apps/model?subscription-key=subscription&q=text&log=True&spellCheck=True&staging=True&timezoneOffset=2&verbose=True") },
            };

            foreach (var test in tests)
            {
                ILuisService service = new LuisService(test.m);
                var          actual  = service.BuildUri(Text);
                Assert.AreEqual(test.u, actual);
            }
        }
Пример #20
0
        public static async System.Threading.Tasks.Task <string> MessageHandler(string inputStr)
        {
            string response = String.Empty;

            // Convert input string to FaqLuis Model
            LuisObject faqLuis = await LuisService.ParseFaqInput(inputStr);

            if (faqLuis.topScoringIntent != null)
            {
                switch (faqLuis.topScoringIntent.intent)
                {
                case "FaqQuery":
                    response = await FaqService.FaqQueryProcessor(faqLuis.topScoringIntent);

                    break;

                case "Assistance":
                    response = ResponseSet.GetRandomResponse(ResponseSet.Assistance);
                    break;

                case "DirectAddress":

                    response = await DirectAddressHandler(inputStr);

                    break;

                case "Farewell":
                    response = ResponseSet.GetRandomResponse(ResponseSet.Farewells);
                    break;

                case "Politeness":
                    response = ResponseSet.GetRandomResponse(ResponseSet.Emojis);
                    break;

                //- Could not place request
                default:
                    response = ResponseSet.GetRandomResponse(ResponseSet.Nones);
                    break;
                }
            }
            return(response);
        }
Пример #21
0
        private async Task <DialogTurnResult> FinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken = default)
        {
            var accessor    = _userState.CreateProperty <string>("Solicitacao");
            var solicitacao = await accessor.GetAsync(stepContext.Context, cancellationToken : cancellationToken);

            var intencaoSolicitacao = ((FoundChoice)stepContext.Result).Value;

            var intentName = "None";

            switch (intencaoSolicitacao)
            {
            case "Nenhuma":
                intentName = "None";
                break;

            case "Estou apenas te cumprimentando :)":
                intentName = "Saudacao";
                break;

            case "Fazer uma reserva":
                intentName = "Reserva";
                break;

            case "Solicitar o serviço de quarto":
                intentName = "ServicoQuarto";
                break;

            case "Solicitar o serviço de despertador":
                intentName = "Despertador";
                break;

            case "Sair":
                return(await stepContext.ReplaceDialogAsync(nameof(RootDialog), cancellationToken : cancellationToken));
            }
            Task.Run(() => LuisService.Learn(_configuration, solicitacao, intentName));

            var message = Conversation.Answer(intentName);

            await stepContext.Context.SendActivityAsync(message, cancellationToken : cancellationToken);

            return(await stepContext.ReplaceDialogAsync(nameof(LoopDialog), cancellationToken : cancellationToken));
        }
Пример #22
0
        private async Task <DialogTurnResult> VerifyLuisIntentionStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var response = stepContext.Context.Activity.CreateReply();

            if (Log)
            {
                UltimaMensagem = stepContext.Context.Activity.Text;
                var intencao = LuisService.ObterIntencao(UltimaMensagem);
                switch (intencao)
                {
                case "BancoDeHorasQuery":
                    response.Attachments = new List <Attachment>()
                    {
                        ObterCardAttachment("HorasCard.json")
                    };
                    await stepContext.Context.SendActivityAsync(response);

                    UltimaMensagem = stepContext.Context.Activity.Text;
                    return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));

                case "ProximasFeriasQuery":
                    response.Attachments = new List <Attachment>()
                    {
                        ObterCardAttachment("FeriasCard.json")
                    };
                    await stepContext.Context.SendActivityAsync(response);

                    UltimaMensagem = stepContext.Context.Activity.Text;
                    return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));

                default:
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text("Não entendi sua pergunta..."));

                    UltimaMensagem = stepContext.Context.Activity.Text;
                    return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken));
                }
            }
            else
            {
                return(await stepContext.NextAsync("", cancellationToken));
            }
        }
Пример #23
0
        private async Task MessageReceiveAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            var         userInput   = await result;
            LuisService luisService = new LuisService();
            string      intent      = await luisService.GetTopIntent(userInput.Text);

            switch (intent)
            {
            case "AskNewinfo":
                await context.PostAsync($"最新情報が知りたいのですね。[このリンク](https://blogs.technet.microsoft.com/office365-tech-japan/)を確認してみてください。");

                break;

            case "AskHowto":
                await context.PostAsync($"How toが知りたいのですね。[このリンク](https://blogs.msdn.microsoft.com/lync_support_team_blog_japan/)を確認してみてください。");

                break;
            }
            context.Done <object>(null);
        }
Пример #24
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="AppSettings"/> class (based on the contents of your "appsettings.json" file).
        /// </summary>
        /// <param name="appSettings"><see cref="AppSettings"/> object based on your "appsettings.json" file.</param>
        /// <returns>A <see cref="BotServices"/> representing client objects to access external services the bot uses.</returns>
        /// <seealso cref="AppSettings"/>
        /// <seealso cref="QnAMaker"/>
        /// <seealso cref="LuisService"/>
        public static BotServices InitBotServices(AppSettings appSettings)
        {
            var            luisIntents           = appSettings.luisIntents;
            var            qnaServices           = new Dictionary <string, QnAMaker>();
            LuisRecognizer luisRecignizerService = null;
            List <string>  IntentsList           = appSettings.luisIntents;
            //Prepare Luis service
            LuisService luisService = new LuisService()
            {
                AppId           = appSettings.luisApp.appId,
                AuthoringKey    = appSettings.luisApp.authoringKey,
                Id              = appSettings.luisApp.id,
                Name            = appSettings.luisApp.name,
                Region          = appSettings.luisApp.region,
                SubscriptionKey = appSettings.luisApp.subscriptionKey,
                Type            = appSettings.luisApp.type,
                Version         = appSettings.luisApp.version
            };
            var luisApp = new LuisApplication(luisService.AppId, luisService.AuthoringKey, luisService.GetEndpoint());

            luisRecignizerService = new LuisRecognizer(luisApp);
            //Prepare QnA service
            foreach (var qna in appSettings.qnaServices)
            {
                var qnaEndpoint = new QnAMakerEndpoint()
                {
                    KnowledgeBaseId = qna.kbId,
                    EndpointKey     = qna.endpointKey,
                    Host            = qna.hostname,
                };
                var qnaMaker = new QnAMaker(qnaEndpoint);
                qnaServices.Add(qna.name, qnaMaker);
            }
            //return new BotServices(luisRecignizerService, qnaServices, Intents);
            return(new BotServices()
            {
                Intents = IntentsList,
                LuisRecognizerService = luisRecignizerService,
                QnAServices = qnaServices,
            });
        }
Пример #25
0
        private static async Task RunQuery(string query)
        {
            // Process message
            var luisService = new LuisService(new LuisModelAttribute(ConfigurationManager.AppSettings["LUIS_ModelId"], ConfigurationManager.AppSettings["LUIS_SubscriptionKey"]));
            var luisResult  = await luisService.QueryAsync(query, CancellationToken.None);

            // Try to resolve intent to action
            var intentName     = default(string);
            var intentEntities = default(IList <EntityRecommendation>);
            var intentAction   = new LuisActionResolver(typeof(GetTimeInPlaceAction).Assembly)
                                 .ResolveActionFromLuisIntent(luisResult, out intentName, out intentEntities);

            if (intentAction != null)
            {
                var executionContextChain = new List <ActionExecutionContext> {
                    new ActionExecutionContext(intentName, intentAction)
                };
                while (LuisActionResolver.IsContextualAction(intentAction))
                {
                    var luisActionDefinition = default(LuisActionBindingAttribute);
                    if (!LuisActionResolver.CanStartWithNoContextAction(intentAction, out luisActionDefinition))
                    {
                        Console.WriteLine($"Cannot start contextual action '{luisActionDefinition.FriendlyName}' without a valid context.");

                        return;
                    }

                    intentAction = LuisActionResolver.BuildContextForContextualAction(intentAction, out intentName);
                    if (intentAction != null)
                    {
                        executionContextChain.Insert(0, new ActionExecutionContext(intentName, intentAction));
                    }
                }

                await RunActions(luisService, executionContextChain);
            }
            else
            {
                Console.WriteLine("Could not understand the input.");
            }
        }
Пример #26
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            var connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            var attributes = new LuisModelAttribute(
                ConfigurationManager.AppSettings["LuisId"],
                ConfigurationManager.AppSettings["LuisSubscriptionKey"]);
            var service = new LuisService(attributes);

            if (activity.Type == ActivityTypes.Message)
            {
                await Conversation.SendAsync(activity, () => new ImageDescriptor(service));
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Пример #27
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            var connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            var luisAttributes = new LuisModelAttribute(
                ConfigurationManager.AppSettings["LuisID"],
                ConfigurationManager.AppSettings["LuisSubscriptionKey"]);
            var luisService = new LuisService(luisAttributes);

            switch (activity.Type)
            {
            case ActivityTypes.Message:
                // If receive a start command from Telegram...
                if (activity.Text == "/start")
                {
                    var telegram = activity.CreateReply();
                    telegram.Text = "Olá, que bom ver você por aqui no Telegram!";

                    await connector.Conversations.ReplyToActivityAsync(telegram);

                    break;
                }
                // Send to Luis consideration...
                await Conversation.SendAsync(activity, () => new RootDialog(luisService));

                break;

            case ActivityTypes.ConversationUpdate:
                if (activity.MembersAdded.Any(o => o.Id == activity.Recipient.Id))
                {
                    var reply = activity.CreateReply();
                    reply.Text = "Olá, que bom ver você por aqui!";

                    await connector.Conversations.ReplyToActivityAsync(reply);
                }
                break;
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Пример #28
0
        public LuisTaskRecognizer()
        {
            var service = new LuisService()
            {
                AppId           = "5e7068ca-eaa8-42f8-b6b0-f603b070c5ee",
                SubscriptionKey = "2760aa3227d8414f9e948ac5eb1849fb",
                Region          = "westus",
                Version         = "2.0",
            };
            var app        = new LuisApplication(service);
            var regOptions = new LuisRecognizerOptionsV2(app)
            {
                IncludeAPIResults = true,
                PredictionOptions = new LuisPredictionOptions()
                {
                    IncludeAllIntents   = true,
                    IncludeInstanceData = true
                }
            };

            _luisRecognizer = new Microsoft.Bot.Builder.AI.Luis.LuisRecognizer(regOptions);
        }
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                //await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());

                //para LUIS Bot
                var luisAttributes = new LuisModelAttribute(
                    ConfigurationManager.AppSettings["LuisId"],
                    ConfigurationManager.AppSettings["LuisSubscriptionKey"]
                    );
                var luisService = new LuisService(luisAttributes);
                await Conversation.SendAsync(activity, () => new Dialogs.PrevisaoTempoDialog(luisService));
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);

            return(response);
        }
Пример #30
0
        public LuisHelper()
        {
            var service = new LuisService()
            {
                AppId           = "a4fe9ae0-be39-4837-b2d9-ed3ca0b33af2",
                SubscriptionKey = "127183aa64af4de893cc822599f2a4ec",
                Region          = "eastus",
                Version         = "0.1"
            };

            var app        = new LuisApplication(service);
            var regOptions = new LuisRecognizerOptionsV2(app)
            {
                IncludeAPIResults = true,
                PredictionOptions = new LuisPredictionOptions()
                {
                    IncludeAllIntents   = true,
                    IncludeInstanceData = true
                }
            };

            _luisRecognizer = new LuisRecognizer(regOptions);
        }