示例#1
0
        private async Task <RecognizerResult> find(string utterance)
        {
            var luisModel      = new LuisModel(ModelId, SubscriptionKey, new System.Uri(StreamUrl));
            var luisRecognizer = new LuisRecognizer(luisModel);

            return(await luisRecognizer.Recognize(utterance, CancellationToken.None));
        }
        /// <summary>
        /// A helper method that retrieves intents for an input from QnA maker
        /// </summary>
        /// <param name="luisModel">The LUIS model to be used for intent recognition</param>
        /// <param name="text">The text to find out the intent for</param>
        /// <returns></returns>
        private static async Task <(IEnumerable <string> intents, IEnumerable <string> entities)> RecognizeAsync(LuisModel luisModel, string text)
        {
            var luisRecognizer   = new LuisRecognizer(luisModel);
            var recognizerResult = await luisRecognizer.Recognize(text, System.Threading.CancellationToken.None);

            // list the intents
            var intents = new List <string>();

            foreach (var intent in recognizerResult.Intents)
            {
                intents.Add(intent.Key);
            }

            // list the entities
            var entities = new List <string>();

            foreach (var entity in recognizerResult.Entities)
            {
                if (!entity.Key.ToString().Equals("$instance"))
                {
                    entities.Add($"{entity.Key}: {entity.Value.First}");
                }
            }

            return(intents, entities);
        }
示例#3
0
        private async Task <RecognizerResult> playLuis(IBotContext botContext, string utterance)
        {
            await botContext.SendActivity("Start LUIS");


            // finder
            var luisModel = new LuisModel("", "", new System.Uri(""));
            // feedback
            //var luisModel = new LuisModel("", "", new System.Uri(""));

            var luisRecognizer = new LuisRecognizer(luisModel);

            return(await luisRecognizer.Recognize(utterance, CancellationToken.None));
        }
示例#4
0
        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);
        }
示例#5
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);
        }
示例#6
0
        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);
        }
        public async Task OnTurn(ITurnContext context)
        {
            if (context.Activity.Type is ActivityTypes.Message)
            {
                var dispatchResult = context.Services.Get<RecognizerResult>(LuisRecognizerMiddleware.LuisRecognizerResultKey) as RecognizerResult;
                var topIntent = dispatchResult?.GetTopScoringIntent();

                if (topIntent == null)
                {
                    await context.SendActivity("Unable to get the top intent.");
                }
                else
                {
                    // we can use the model name to index into our array of qna/luis models
                    var modelName = topIntent.Value.intent;

                    var targetModel = this.models[modelName];

                    if (targetModel is QnAMakerEndpoint qnaModel)
                    {
                        await context.SendActivity($"Dispatching to QnAMaker model {modelName}");
                        var qnaMaker = new QnAMaker(qnaModel);
                        var qnaResponse = await qnaMaker.GetAnswers(context.Activity.Text);
                        await context.SendActivity($"Result from QnAMaker: {qnaResponse.FirstOrDefault().Answer}");
                    }
                    else if (targetModel is LuisModel luisModel)
                    {
                        await context.SendActivity($"Dispatching to luis model {modelName}");

                        var luisRecognizer = new LuisRecognizer(luisModel);
                        var recognizerResult = await luisRecognizer.Recognize(context.Activity.Text, System.Threading.CancellationToken.None);
                        await context.SendActivity($"Result from luis: {recognizerResult.GetTopScoringIntent().intent}");
                    }
                }
            }
        }
        public async Task OnTurn(ITurnContext context)
        {
            if (context.Activity.Type is ActivityTypes.Message)
            {
                var message = context.Activity.AsMessageActivity();
                // Get the intent recognition result from the context object.
                var              dispatchResult = context.Services.Get <RecognizerResult>(LuisRecognizerMiddleware.LuisRecognizerResultKey) as RecognizerResult;
                var              topIntent = dispatchResult?.GetTopScoringIntent();
                LuisRecognizer   luisRecognizer1, luisRecognizer2;
                RecognizerResult recognizerResult;

                var intentsList = new List <string>();
                var entitiesList = new List <string>();

                if (topIntent == null)
                {
                    await context.SendActivity("Unable to get the top intent.");
                }
                else
                {
                    if (topIntent.Value.score < 0.3)
                    {
                        await context.SendActivity("I'm not very sure what you want but will try to send your request.");
                    }
                    switch (topIntent.Value.intent.ToLowerInvariant())
                    {
                    case "l_homeautomation":
                        await context.SendActivity("Sending your request to the home automation system ...");

                        luisRecognizer1  = new LuisRecognizer(this.luisModelHomeAutomation);
                        recognizerResult = await luisRecognizer1.Recognize(message.Text, System.Threading.CancellationToken.None);

                        // list the intents
                        foreach (var intent in recognizerResult.Intents)
                        {
                            intentsList.Add($"'{intent.Key}', score {intent.Value}");
                        }
                        await context.SendActivity($"Intents detected by the home automation app:\n\n{string.Join("\n\n", intentsList)}");

                        // list the entities
                        entitiesList = new List <string>();
                        foreach (var entity in recognizerResult.Entities)
                        {
                            if (!entity.Key.ToString().Equals("$instance"))
                            {
                                entitiesList.Add($"{entity.Key}: {entity.Value.First}");
                            }
                        }

                        if (entitiesList.Count > 0)
                        {
                            await context.SendActivity($"The following entities were found in the message:\n\n{string.Join("\n\n", entitiesList)}");
                        }

                        // Here, you can add code for calling the hypothetical home automation service, passing in any entity information that you need

                        break;

                    case "l_weather":
                        await context.SendActivity("Sending your request to the weather system ...");

                        luisRecognizer2  = new LuisRecognizer(this.luisModelWeather);
                        recognizerResult = await luisRecognizer2.Recognize(message.Text, System.Threading.CancellationToken.None);

                        // list the intents
                        var intentsResult2 = new List <string>();
                        foreach (var intent in recognizerResult.Intents)
                        {
                            intentsResult2.Add($"'{intent.Key}', score {intent.Value}");
                        }
                        await context.SendActivity($"Intents detected by the weather app: \n\n{string.Join("\n\n", intentsResult2)}");

                        // list the entities
                        entitiesList = new List <string>();
                        foreach (var entity in recognizerResult.Entities)
                        {
                            if (!entity.Key.ToString().Equals("$instance"))
                            {
                                entitiesList.Add($"{entity.Key}: {entity.Value.First}");
                            }
                        }

                        if (entitiesList.Count > 0)
                        {
                            await context.SendActivity($"The following entities were found in the message:\n\n{string.Join("\n\n", entitiesList)}");
                        }

                        // Here, you can add code for calling the hypothetical weather service, passing in any entity information that you need

                        break;

                    case "none":
                    // You can provide logic here to handle the known None intent (none of the above).
                    // In this example we fall through to the QnA intent.
                    case "q_faq":
                        QnAMaker qnaMaker        = new QnAMaker(this.qnaOptions);
                        var      messageActivity = context.Activity.AsMessageActivity();
                        if (!string.IsNullOrEmpty(messageActivity.Text))
                        {
                            var results = await qnaMaker.GetAnswers(messageActivity.Text.Trim()).ConfigureAwait(false);

                            if (results.Any())
                            {
                                await context.SendActivity(results.First().Answer);
                            }
                            else
                            {
                                await context.SendActivity("Couldn't find an answer in the FAQ.");
                            }
                        }
                        break;

                    default:
                        // The intent didn't match any case, so just display the recognition results.
                        await context.SendActivity($"Dispatch intent: {topIntent.Value.intent} ({topIntent.Value.score}).");

                        break;
                    }
                }
            }
            else if (context.Activity.Type is ActivityTypes.ConversationUpdate)
            {
                foreach (var newMember in context.Activity.MembersAdded)
                {
                    if (newMember.Id != context.Activity.Recipient.Id)
                    {
                        await context.SendActivity("Hello and welcome to the LUIS Dispatch sample bot. This bot dispatches messages to LUIS apps and QnA, using a LUIS model generated by the Dispatch tool in hierarchical mode.");
                    }
                }
            }
        }
示例#9
0
        public async Task OnTurn(ITurnContext context)
        {
            //TODO: is this the right way to handle cards?
            string  utterance = context.Activity.Text;
            JObject cardData  = (JObject)context.Activity.Value;

            if (cardData != null && cardData.Property("intent") != null)
            {
                utterance = cardData["utterance"].ToString();
            }
            System.Threading.CancellationToken ct;

            CafeBotUserState userState         = context.GetUserState <CafeBotUserState>();
            CafeBotConvState conversationState = context.GetConversationState <CafeBotConvState>();

            switch (context.Activity.Type)
            {
            case ActivityTypes.ConversationUpdate:
                var newUserName = context.Activity.MembersAdded[0].Name;
                if (!string.IsNullOrWhiteSpace(newUserName) && newUserName != "Bot")
                {
                    await context.SendActivity($"Hello {newUserName}! I'm the Cafe bot!");

                    // remember the user's name
                    userState.name = newUserName;

                    userState.sendCards = true;

                    await context.SendActivity("I can help you find contoso cafe locations, book a table and answer questions about Contoso cafe!");

                    // send a welcome card
                    if (userState.sendCards)
                    {
                        await context.SendActivity(CreateCardResponse(context.Activity, createWelcomeCardAttachment()));
                    }
                }
                break;

            case ActivityTypes.Message:
                // create dialogContext
                DialogContext dc = _dialogs.CreateContext(context, conversationState);


                if (utterance == "start over")
                {
                    //restart the conversation
                    await context.SendActivity("Sure.. Let's start over");

                    dc.EndAll();
                }
                else
                {
                    // continue with any active dialogs
                    await dc.Continue();
                }

                if (!context.Responded)
                {
                    // call LUIS and get results
                    LuisRecognizer lRecognizer = createLUISRecognizer();
                    cafeLUISModel  lResult     = await lRecognizer.Recognize <cafeLUISModel>(utterance, ct);

                    Dictionary <string, object> lD = new Dictionary <string, object>();
                    if (lResult != null)
                    {
                        lD.Add("luisResult", lResult);
                    }

                    // top level dispatch
                    switch (lResult.TopIntent().intent)
                    {
                    case cafeLUISModel.Intent.Greeting:
                        await context.SendActivity("Hello, I'm the contoso cafe bot. How can I help you?");

                        if (userState.sendCards)
                        {
                            await context.SendActivity(CreateCardResponse(context.Activity, createWelcomeCardAttachment()));
                        }
                        break;

                    case cafeLUISModel.Intent.Book_Table:
                        await dc.Begin("BookTable", lD);

                        break;

                    case cafeLUISModel.Intent.Who_are_you_intent:
                        await dc.Begin("WhoAreYou");

                        break;

                    case cafeLUISModel.Intent.None:
                    default:
                        await getQnAResult(context);

                        break;
                    }
                }
                break;
            }
        }
示例#10
0
        public async Task OnTurn(ITurnContext context)
        {
            //TODO: is this the right way to handle cards?
            string  utterance = context.Activity.Text;
            JObject cardData  = (JObject)context.Activity.Value;

            if (cardData != null && cardData.Property("intent") != null)
            {
                utterance = cardData["utterance"].ToString();
            }

            var userState         = context.GetUserState <CafeBotUserState>();
            var conversationState = context.GetConversationState <CafeBotConvState>();

            switch (context.Activity.Type)
            {
            case ActivityTypes.ConversationUpdate:
                var newUserName = context.Activity.MembersAdded[0].Name;
                if (!string.IsNullOrWhiteSpace(newUserName) && newUserName != "Bot" && string.IsNullOrEmpty(userState.name))
                {
                    await context.SendActivity($"Hello {newUserName}! I'm the Cafe bot!");

                    // remember the user's name
                    userState.name = newUserName;

                    //userState.sendCards = true;

                    await context.SendActivity("I can help you find contoso cafe locations, book a table and answer questions about Contoso cafe!");

                    // send a welcome card
                    if (userState.sendCards)
                    {
                        await context.SendActivity(CreateCardResponse(context.Activity, createWelcomeCardAttachment()));
                    }
                }
                break;

            case ActivityTypes.Message:

                // create dialogContext
                var dc = _dialogs.CreateContext(context, conversationState);
                // continue with any active dialogs
                await dc.Continue();

                if (!context.Responded)
                {
                    // call LUIS and get results
                    LuisRecognizerOptions lOptions = new LuisRecognizerOptions()
                    {
                        Verbose = true
                    };
                    LuisModel lModel = new LuisModel(
                        "edaadd9b-b632-4733-a25c-5b67271035dd",
                        "be30825b782843dcbbe520ac5338f567",
                        new System.Uri("https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/"), Microsoft.Cognitive.LUIS.LuisApiVersion.V2);
                    LuisRecognizer lRecognizer = new LuisRecognizer(lModel, lOptions);
                    System.Threading.CancellationToken ct;
                    cafeLUISModel lResult = await lRecognizer.Recognize <cafeLUISModel>(context.Activity.Text, ct);

                    // top level dispatch

                    switch (lResult.TopIntent().intent)
                    {
                    case cafeLUISModel.Intent.Greeting:
                        //case "hi":
                        await context.SendActivity("Hello, I'm the contoso cafe bot. How can I help you?");

                        if (userState.sendCards)
                        {
                            await context.SendActivity(CreateCardResponse(context.Activity, createWelcomeCardAttachment()));
                        }
                        break;

                    case cafeLUISModel.Intent.Book_Table:
                        // case "book table":
                        await dc.Begin("BookTable");

                        break;

                    case cafeLUISModel.Intent.Who_are_you_intent:
                        // case "who are you?":
                        await dc.Begin("WhoAreYou");

                        break;

                    case cafeLUISModel.Intent.None:
                    default:
                        var qEndpoint = new QnAMakerEndpoint()
                        {
                            Host            = "https://contosocafeqnamaker.azurewebsites.net/qnamaker",
                            EndpointKey     = "09e2d55b-a44c-41b6-a08a-76a7df9ddffe",
                            KnowledgeBaseId = "b5534d70-bded-45e1-998a-5945174d4ff3"
                        };
                        var qOptions = new QnAMakerOptions()
                        {
                            ScoreThreshold = 0.4F,
                            Top            = 1
                        };
                        var           qnamaker = new QnAMaker(qEndpoint, qOptions);
                        QueryResult[] qResult  = await qnamaker.GetAnswers(context.Activity.Text);

                        if (qResult.Length == 0)
                        {
                            await context.SendActivity("Sorry, I do not understand.");

                            await context.SendActivity("You can say hi or book table or find locations");
                        }
                        else
                        {
                            await context.SendActivity(qResult[0].Answer);
                        }

                        //await context.SendActivity("Sorry, I do not understand.");
                        //await context.SendActivity("You can say hi or book table or find locations");
                        break;
                    }
                }
                break;
            }
        }