public static void LogToApplicationInsights(IConfiguration configuration, ITurnContext turnContext, RecognizerResult result) { // Create Application Insights object TelemetryClient telemetry = new TelemetryClient(); // Set Application Insights Instrumentation Key from App Settings telemetry.InstrumentationKey = configuration["BotDevAppInsightsKey"]; // Collect information to send to Application Insights Dictionary <string, string> logProperties = new Dictionary <string, string>(); logProperties.Add("BotConversation", turnContext.Activity.Conversation.Name); logProperties.Add("Bot_userId", turnContext.Activity.Conversation.Id); logProperties.Add("LUIS_query", result.Text); logProperties.Add("LUIS_topScoringIntent_Name", result.GetTopScoringIntent().intent); logProperties.Add("LUIS_topScoringIntentScore", result.GetTopScoringIntent().score.ToString()); // Add entities to collected information int i = 1; if (result.Entities.Count > 0) { foreach (var item in result.Entities) { logProperties.Add("LUIS_entities_" + i++ + "_" + item.Key, item.Value.ToString()); } } // Send to Application Insights telemetry.TrackTrace("LUIS", ApplicationInsights.DataContracts.SeverityLevel.Information, logProperties); }
private async Task ManageIntentions(ITurnContext <IMessageActivity> turnContext, RecognizerResult recognizeResult, CancellationToken cancellationToken) { var topIntent = recognizeResult.GetTopScoringIntent(); switch (topIntent.intent) { case "Saludar": await IntentSaludar(turnContext, recognizeResult, cancellationToken); break; case "Agradecer": await IntentAgradecer(turnContext, recognizeResult, cancellationToken); break; case "PrestarDinero": await IntentPrestarDinero(turnContext, recognizeResult, cancellationToken); break; case "None": await IntentNone(turnContext, recognizeResult, cancellationToken); break; default: break; } }
#pragma warning restore CA2227 // Collection properties should be read only public override async Task <RecognizerResult> RecognizeAsync(DialogContext dialogContext, Activity activity, CancellationToken cancellationToken = default, Dictionary <string, string> telemetryProperties = null, Dictionary <string, double> telemetryMetrics = null) { if (dialogContext == null) { throw new ArgumentNullException(nameof(dialogContext)); } if (activity == null) { throw new ArgumentNullException(nameof(activity)); } RecognizerResult result = null; // Get recognizer result one after another foreach (var r in Recognizers) { result = await r.RecognizeAsync(dialogContext, activity, cancellationToken, telemetryProperties, telemetryMetrics).ConfigureAwait(false); if (result != null) { var(intent, score) = result.GetTopScoringIntent(); if (!intent.Equals("None")) { break; } } } this.TrackRecognizerResult(dialogContext, "RecognizerSetWithPriority", this.FillRecognizerResultTelemetryProperties(result, telemetryProperties), telemetryMetrics); return(result); }
/// <summary> /// Every Conversation turn for our EchoBot will call this method. In here /// the bot checks the Activty type to verify it's a message, bumps the /// turn conversation 'Turn' count, and then echoes the users typing /// back to them. /// </summary> /// <param name="context">Turn scoped context containing all the data needed /// for processing this conversation turn. </param> public async Task OnTurn(ITurnContext context) { // This bot is only handling Messages if (context.Activity.Type == ActivityTypes.Message) { RecognizerResult resultado = context.Services.Get <RecognizerResult>(LuisRecognizerMiddleware.LuisRecognizerResultKey); var intencaoMaisPontuada = resultado?.GetTopScoringIntent(); switch ((intencaoMaisPontuada != null) ? intencaoMaisPontuada.Value.intent : null) { case "None": await context.SendActivity("Não entendi."); break; case "PedirPizza": await context.SendActivity("Você quer pedir uma pizza."); break; case "PrevisaoTempo": await context.SendActivity("Você quer saber a previsão do tempo."); break; case "MarcarConsulta": await context.SendActivity("Você quer marcar uma consulta."); break; } } }
public static OnTurnProperty FromLuisResults(RecognizerResult luisResults) { var(intent, score) = luisResults.GetTopScoringIntent(); var onTurnProperties = new OnTurnProperty { Intent = intent, Score = score, Type = Luis }; // Gather entity values if available. Uses a const list of LUIS entity names. foreach (var entity in luisEntities) { var value = luisResults.Entities.SelectTokens(entity).FirstOrDefault(); if (value == null) { continue; } onTurnProperties.Entities.Add(new EntityProperty(entity, value)); } return(onTurnProperties); }
private async Task Intention(ITurnContext <IMessageActivity> turnContext, RecognizerResult luisResul, CancellationToken cancellationToken) { var topIntent = luisResul.GetTopScoringIntent(); switch (topIntent.intent) { case "Greet": await IntenGreet(turnContext, luisResul, cancellationToken); break; case "Dismiss": await IntenDismiss(turnContext, luisResul, cancellationToken); break; case "Thank": await IntenThank(turnContext, luisResul, cancellationToken); break; case "BuyMovie": await IntenBuyMovie(turnContext, luisResul, cancellationToken); break; case "None": await IntenNone(turnContext, luisResul, cancellationToken); break; default: break; } }
private async Task <DialogTurnResult> IntroStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(Configuration["LuisAppId"]) || string.IsNullOrEmpty(Configuration["LuisAPIKey"]) || string.IsNullOrEmpty(Configuration["LuisAPIHostName"])) { await stepContext.Context.SendActivityAsync( MessageFactory.Text("NOTE: LUIS is not configured. To enable all capabilities, add 'LuisAppId', 'LuisAPIKey' and 'LuisAPIHostName' to the appsettings.json file."), cancellationToken); return(await stepContext.NextAsync(null, cancellationToken)); } else { RecognizerResult recognizerResult = null; recognizerResult = await _botServices.Dispatch.RecognizeAsync(stepContext.Context, cancellationToken); //var result = stepContext.Context.Activity as Activity; //string data = result.ChannelData.ToString(); //await stepContext.Context.SendActivityAsync(MessageFactory.Text(data), cancellationToken); string msg = JsonConvert.SerializeObject(recognizerResult.Intents); await stepContext.Context.SendActivityAsync(MessageFactory.Text(msg), cancellationToken); // Top intent tell us which cognitive service to use. var topIntent = recognizerResult.GetTopScoringIntent(); // Next, we call the dispatcher with the top intent. await DispatchToTopIntentAsync(stepContext, topIntent.intent, recognizerResult, cancellationToken); return(await stepContext.NextAsync(null, cancellationToken)); } }
public static async Task <DialogTurnResult> LuisValueRedirection <T>(this DialogContext context, T instanceReference, RecognizerResult result) where T : class { var dialogName = result.GetTopScoringIntent().intent; if (!string.IsNullOrEmpty(dialogName)) { var comparisonAttribute = new DialogNameAtribute(dialogName); var methods = instanceReference.GetType() .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) .Where(m => m.GetCustomAttributes() .OfType <DialogNameAtribute>() .Any(n => n.Equals(comparisonAttribute))); if (methods.Count() > 1) { throw new Exception("Multiple methods found"); } var method = methods.FirstOrDefault(); var handler = (LuisCommandHandler)Delegate.CreateDelegate(typeof(LuisCommandHandler), instanceReference, method, throwOnBindFailure: false); if (handler == null) { throw new Exception("No method Found"); } if (handler != null) { return(await handler(context, result)); } } throw new Exception("Intent handler Not Found"); }
private Dictionary <string, object> ParseEntities(RecognizerResult recognizerResult) { Dictionary <string, object> parsedEntites = new Dictionary <string, object>(); string intentName = recognizerResult.GetTopScoringIntent().intent; var intent = this.Intents.FirstOrDefault(i => i.Id == intentName); if (intent != null) { foreach (var property in intent.Properties) { var value = recognizerResult.Entities[property.EntityType]; if (value == null) { continue; } int index = intent.Properties.Where(p => p.EntityType == property.EntityType).ToList().IndexOf(property); var result = value[index].ToString(); parsedEntites.Add(property.Name, result); } } return(parsedEntites); }
private async Task <DialogTurnResult> Intenciones(WaterfallStepContext stepContext, RecognizerResult luisResult, CancellationToken cancellationToken) { var topIntent = luisResult.GetTopScoringIntent(); switch (topIntent.intent) { case "Saludar": await IntencionSaludar(stepContext, cancellationToken); break; case "Despedir": await IntencionDespedir(stepContext, cancellationToken); break; case "Agradecer": await IntencionAgradecer(stepContext, cancellationToken); break; case "None": await IntencionNone(stepContext, cancellationToken); break; case "ComprarPelicula": return(await IntencionComprarPelicula(stepContext, cancellationToken)); } return(await stepContext.NextAsync(cancellationToken : cancellationToken)); }
public static OnTurnProperty FromLuisResults(RecognizerResult luisResults) { var onTurnProperties = new OnTurnProperty(); onTurnProperties.Intent = luisResults.GetTopScoringIntent().intent; // Gather entity values if available. Uses a const list of LUIS entity names. foreach (var entity in luisEntities) { dynamic value = luisResults.Entities[entity]; string strVal = null; if (value is JArray) { // ConfirmList is nested arrays. value = (from val in (JArray)value select val).FirstOrDefault(); } strVal = (string)value; if (strVal == null) { // Don't add empty entities. continue; } onTurnProperties.Entities.Add(new EntityProperty(entity, strVal)); } return(onTurnProperties); }
public static string GetLuisIntent(RecognizerResult luisResult, BotUserState userState) { var(intent, score) = luisResult.GetTopScoringIntent(); var intentResult = score >= LUIS_INTENT_THRESHOLD ? intent : "None"; return(intentResult); }
private async Task <bool> Recognize(ITurnContext turnContext, CancellationToken cancellationToken) { var dialogContext = await Dialogs.CreateContextAsync(turnContext, cancellationToken); RecognizerResult result = turnContext.Get <RecognizerResult>(); if (result != null) { var topIntent = result?.GetTopScoringIntent(); string memberKey = _members.Select(kp => kp.Key).FirstOrDefault((kp) => kp.Equals(topIntent.Value.intent, StringComparison.InvariantCultureIgnoreCase)); if (memberKey is null) { return(false); } Task task = (Task)_members[memberKey].Invoke(this, new object[] { dialogContext, result, cancellationToken }); await task; result = null; return(true); } else { return(false); } }
/// <summary> /// Gets the top intent returned by an intent recognizer. /// </summary> /// <param name="results">Intent recognizer results.</param> /// <returns>Intent name.</returns> public static string GetTopIntent(this RecognizerResult results) { var scoringIntent = results?.GetTopScoringIntent(); return scoringIntent.HasValue && scoringIntent.Value.score >= MinScore ? scoringIntent.Value.intent : null; }
public static async Task <(string intent, double score)?> GetTopIntent(string question, IConfiguration configuration) { RecognizerResult recognizerResult = await GetResults(question, configuration); var topIntent = recognizerResult?.GetTopScoringIntent(); return(topIntent); }
public async Task OnTurn(ITurnContext context) { Dictionary <string, object> state = ConversationState <Dictionary <string, object> > .Get(context); DialogContext dc = dialogos.CreateContext(context, state); await dc.Continue(); if (context.Activity.Type == ActivityTypes.Message) { RecognizerResult resultado = context.Services.Get <RecognizerResult>(LuisRecognizerMiddleware.LuisRecognizerResultKey); var intencaoMaisPontuada = resultado?.GetTopScoringIntent(); if (!context.Responded) { IDictionary <string, object> argumentos = new Dictionary <string, object>(); if (this.ObterEntidade <string>(resultado, "Cidade") != null) { argumentos.Add("Cidade", this.ObterEntidade <string>(resultado, "Cidade")); } if (this.ObterEntidade <string>(resultado, "Tamanho") != null) { argumentos.Add("Tamanho", this.ObterEntidade <string>(resultado, "Tamanho")); } if (this.ObterEntidade <string>(resultado, "Sabor") != null) { argumentos.Add("Sabor", this.ObterEntidade <string>(resultado, "Sabor")); } switch ((intencaoMaisPontuada != null) ? intencaoMaisPontuada.Value.intent : null) { case "None": await context.SendActivity("Não entendi."); break; case "PedirPizza": await dc.Begin("pedirPizza", argumentos); break; case "PrevisaoTempo": await dc.Begin("previsaoTempo", argumentos); break; case "MarcarConsulta": await dc.Begin("marcarConsulta"); break; } } } }
private async Task ProcessLuisIntent(ITurnContext turnContext, RecognizerResult result, string response) { // Match top LUIS intent to appropriate action switch (result.GetTopScoringIntent().intent) { // AMTS: Intent to give patient an address to remember later on - extracts address entity from sentence and stores for later retrieval case "AMTSRememberAddress": { if (result.Entities.Count > 1) { response += "\"text\":\"Okay Doctor, " + result.Entities.GetValue("AMTSAddress")[0] + ", I'll remember it.\", \"type\":\"AMTSRememberAddress\"}"; // Save the address into state and recall later _userHistoryState.patientAMTSAddress = result.Entities.GetValue("AMTSAddress")[0].ToString(); await _userStateAccessor.SetAsync(turnContext, _userHistoryState); } else { response += "\"text\":\"Sure Doctor, what's the address?\", \"type\":\"AMTSRememberAddress\"}"; // Prompt user for address } await turnContext.SendActivityAsync(response); break; } // AMTS: Intent to recall an address that was specified earlier by the user case "AMTSRecallAddress": { if (_userHistoryState.patientAMTSAddress != null) { response += "\"text\":\"I think it was " + _userHistoryState.patientAMTSAddress + ".\", \"type\":\"AMTSRecallAddress\"}"; } else { response += "\"text\":\"I don't think you told me an address Doctor.\", \"type\":\"AMTSRememberAddress\"}"; } await turnContext.SendActivityAsync(response); break; } // If intent isn't matched for some reason, dispatch to QnAMaker default: { await ProcessQnAMakerResponse(turnContext, response); break; } } }
public void GIVENAnyResult_WHENRecognizerResultAdapterIsInvoked_THENActivityIsMapped(RecognizerResult recognizerResult) { // Arrange var adapter = new RecognizerResultAdapter(recognizerResult); var topScoringIntent = recognizerResult.GetTopScoringIntent(); // Act var recognizedIntentResult = adapter.IntentResult; // Assert Assert.Equal(recognizedIntentResult.Intent, topScoringIntent.intent); Assert.Equal(recognizedIntentResult.Score, topScoringIntent.score.ToString(CultureInfo.InvariantCulture)); Assert.Equal(recognizedIntentResult.Entities, recognizerResult.Entities.ToString(Formatting.None)); }
/// <summary> /// Fills the event properties for LuisResult event for telemetry. /// These properties are logged when the recognizer is called. /// </summary> /// <param name="recognizerResult">Last activity sent from user.</param> /// <param name="turnContext">Context object containing information for a single turn of conversation with a user.</param> /// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// additionalProperties /// <returns>A dictionary that is sent as "Properties" to IBotTelemetryClient.TrackEvent method for the BotMessageSend event.</returns> protected Task <Dictionary <string, string> > FillLuisEventPropertiesAsync(RecognizerResult recognizerResult, ITurnContext turnContext, Dictionary <string, string> telemetryProperties = null, CancellationToken cancellationToken = default(CancellationToken)) { var topLuisIntent = recognizerResult.GetTopScoringIntent(); var intentScore = topLuisIntent.score.ToString("N2"); var topTwoIntents = (recognizerResult.Intents.Count > 0) ? recognizerResult.Intents.OrderByDescending(x => x.Value.Score).Take(2).ToArray() : null; // Add the intent score and conversation id properties var properties = new Dictionary <string, string>() { { LuisTelemetryConstants.ApplicationIdProperty, _application.ApplicationId }, { LuisTelemetryConstants.IntentProperty, topTwoIntents?[0].Key ?? string.Empty }, { LuisTelemetryConstants.IntentScoreProperty, topTwoIntents?[0].Value.Score?.ToString("N2") ?? "0.00" }, { LuisTelemetryConstants.Intent2Property, (topTwoIntents?.Count() > 1) ? topTwoIntents?[1].Key ?? string.Empty : string.Empty }, { LuisTelemetryConstants.IntentScore2Property, (topTwoIntents?.Count() > 1) ? topTwoIntents?[1].Value.Score?.ToString("N2") ?? "0.00" : "0.00" }, { LuisTelemetryConstants.FromIdProperty, turnContext.Activity.From.Id }, }; if (recognizerResult.Properties.TryGetValue("sentiment", out var sentiment) && sentiment is JObject) { if (((JObject)sentiment).TryGetValue("label", out var label)) { properties.Add(LuisTelemetryConstants.SentimentLabelProperty, label.Value <string>()); } if (((JObject)sentiment).TryGetValue("score", out var score)) { properties.Add(LuisTelemetryConstants.SentimentScoreProperty, score.Value <string>()); } } var entities = recognizerResult.Entities?.ToString(); properties.Add(LuisTelemetryConstants.EntitiesProperty, entities); // Use the LogPersonalInformation flag to toggle logging PII data, text is a common example if (LogPersonalInformation && !string.IsNullOrEmpty(turnContext.Activity.Text)) { properties.Add(LuisTelemetryConstants.QuestionProperty, turnContext.Activity.Text); } // Additional Properties can override "stock" properties. if (telemetryProperties != null) { return(Task.FromResult(telemetryProperties.Concat(properties) .GroupBy(kv => kv.Key) .ToDictionary(g => g.Key, g => g.First().Value))); } return(Task.FromResult(properties)); }
public virtual Task <RecognizerResult> LuisIntentChange(DialogContext outerDc, RecognizerResult result, object options = null, CancellationToken cancellationToken = default) { //Kvoli volaniu NONE intentu kedže NONE intent nie je dialog if (result.GetTopScoringIntent().intent.ToLower() == "none") { result.Intents.Clear(); IntentScore score = new IntentScore { Score = 1 }; result.Intents.Add(nameof(RootDialog), score); } return(Task.FromResult(result)); }
private async Task ProcessAlarmAsync(ITurnContext <IMessageActivity> turnContext, RecognizerResult result, CancellationToken cancellationToken) { _logger.LogInformation("ProcessLAlarmAsync"); var client = _clientFactory.CreateClient("visionBackend"); var topIntent = result.GetTopScoringIntent().intent; TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; switch (topIntent) { case "LastEntry": var entry = JsonConvert.DeserializeObject <Entry>(await client.GetStringAsync("LastEntry")); await DisplayEntry(turnContext, entry.ImageName, "Last Entry", "Last entrants were: " + textInfo.ToTitleCase(String.Join(", ", entry.Entrants.ToArray())), entry.Timestamp, cancellationToken); break; case "LastIdentifiedPersonEntered": var entry2 = JsonConvert.DeserializeObject <Entry>(await client.GetStringAsync("LastKnownEntrant")); await DisplayEntry(turnContext, entry2.ImageName, "Last know entrant(s)", "Last known entrants were: " + textInfo.ToTitleCase(String.Join(", ", entry2.Entrants.ToArray())), entry2.Timestamp, cancellationToken); break; case "PersonArrived": var name = result.Entities["Person"][0].ToString(); var entry3 = JsonConvert.DeserializeObject <Entry>(await client.GetStringAsync("GetLastEntryForName/" + name)); await DisplayEntry(turnContext, entry3.ImageName, textInfo.ToTitleCase(name) + " entered at", " ", entry3.Timestamp, cancellationToken); break; case "ShowMeTodaysEntrants": var todaysEntrants = JsonConvert.DeserializeObject <string[]>(await client.GetStringAsync("EntrantsOnDay/" + DateTime.Now.Date.ToString("s"))); string namesList = ""; foreach (var n in todaysEntrants) { namesList += " " + n; } await turnContext.SendActivityAsync("People who entered today:" + textInfo.ToTitleCase(namesList)); break; default: await turnContext.SendActivityAsync("Sorry your intent was not recognized"); break; } }
public ClassifierResult GetResult(bool cleanup = true) { if (_resultWithoutCorrection == null) { return(null); } var(_, score) = _resultWithoutCorrection.GetTopScoringIntent(); if (_resultWithCorrection != null) { var(_, scoreWithCorrection) = _resultWithCorrection.GetTopScoringIntent(); if (score < scoreWithCorrection) { return(ToResult(_resultWithCorrection, cleanup)); } } return(ToResult(_resultWithoutCorrection, cleanup)); }
private async Task <DialogTurnResult> ManageIntentions(WaterfallStepContext stepContext, RecognizerResult luisResult, CancellationToken cancellationToken) { var topIntent = luisResult.GetTopScoringIntent(); if (topIntent.score > 0.5) { switch (topIntent.intent) { case "Saludar": await IntentSaludar(stepContext, luisResult, cancellationToken); break; case "Despedirse": await IntentAgradecer(stepContext, luisResult, cancellationToken); break; case "Calificar": return(await IntentCalificar(stepContext, luisResult, cancellationToken)); case "VerCursos": return(await IntentVerCursos(stepContext, luisResult, cancellationToken)); case "AtencionPersonal": return(await IntentAgente(stepContext, luisResult, cancellationToken)); case "Pagos": return(await IntentPagos(stepContext, luisResult, cancellationToken)); case "None": await IntentNone(stepContext, luisResult, cancellationToken); break; default: break; } } else { await IntentNone(stepContext, luisResult, cancellationToken); } return(await stepContext.NextAsync(cancellationToken : cancellationToken)); }
public void TrackIntent( IActivity activity, RecognizerResult recognizerResult) { var(intent, score) = recognizerResult.GetTopScoringIntent(); var properties = new Dictionary <string, string> { { TelemetryEventProperties.IntentProperty, intent }, { TelemetryEventProperties.ScoreProperty, score.ToString("N2") }, { TelemetryEventProperties.EntitiesProperty, JsonConvert.SerializeObject(recognizerResult.Entities) }, }; var et = BuildEventTelemetry(activity, properties); et.Name = TelemetryEventTypes.Intent; telemetryClient.TrackEvent(et); // TODO: Track sentiment if included in intent data. }
public void TrackIntent(IActivity activity, RecognizerResult result) { BotAssert.ActivityNotNull(activity); if (result == null) { throw new ArgumentNullException(nameof(result)); } var topScoringIntent = result.GetTopScoringIntent(); var properties = new Dictionary <string, string> { { IntentConstants.Intent, topScoringIntent.intent }, { IntentConstants.Score, topScoringIntent.score.ToString(CultureInfo.InvariantCulture) }, { IntentConstants.Entities, result.Entities.ToString(Formatting.None) } }; this.TrackIntent(activity, properties); }
public static OnTurnProperty FromLuisResults(RecognizerResult luisResults) { var onTurnProperties = new OnTurnProperty(); onTurnProperties.Intent = luisResults.GetTopScoringIntent().intent; // Gather entity values if available. Uses a const list of LUIS entity names. foreach (var entity in luisEntities) { var value = luisResults.Entities.SelectTokens(entity).FirstOrDefault(); if (value == null) { continue; } object property = null; var val = value.First(); if (val.Type == JTokenType.Array) { var arr = (JArray)val; property = arr[0].ToString(); // Store first value } else if (val.Type == JTokenType.Object) { var obj = (JObject)val; if (obj["type"].ToString() == "datetime") { property = val; // Store the JToken from LUIS (includes Timex) } } else if (val.Type == JTokenType.Integer) { var num = (JValue)val; property = val.ToString(); // Store string for number of guests } onTurnProperties.Entities.Add(new EntityProperty(entity, property)); } return(onTurnProperties); }
public void GivenAnyActivity_WhenTrackIntentIsInvoked_ThenEventTelemetryIsBeingSent( IMessageActivity activity, RecognizerResult luisResult, InstrumentationSettings settings) { // Arrange var instrumentation = new IntentInstrumentation(this.telemetryClient, settings); var topScoringIntent = luisResult.GetTopScoringIntent(); // Act instrumentation.TrackIntent(activity, luisResult); // Assert this.mockTelemetryChannel.Verify( tc => tc.Send(It.Is <EventTelemetry>(t => t.Name == EventTypes.Intent && t.Properties[IntentConstants.Intent] == topScoringIntent.intent && t.Properties[IntentConstants.Score] == topScoringIntent.score.ToString(CultureInfo.InvariantCulture) && t.Properties[IntentConstants.Entities] == luisResult.Entities.ToString(Formatting.None))), Times.Once); }
private async Task ProcessAIConBotAsync(ITurnContext <IMessageActivity> turnContext, RecognizerResult recognizerResult, CancellationToken cancellationToken) { _logger.LogInformation("ProcessAIConBotAsync"); // Retrieve LUIS results for Weather. // var result = luisResult.ConnectedServiceResult; var topIntent = recognizerResult.GetTopScoringIntent(); //await turnContext.SendActivityAsync(MessageFactory.Text($"SNOW"), cancellationToken); //await turnContext.SendActivityAsync(MessageFactory.Text($"ProcessAIConBot Intents detected::\n\n{string.Join("\n\n", luisResult.Intents.Select(i => i.Intent))}"), cancellationToken); if (topIntent.intent.Length > 0) { // await turnContext.SendActivityAsync(MessageFactory.Text($"ProcessWeather entities were found in the message:\n\n{string.Join("\n\n", result.Entities.Select(i => i.Entity))}"), cancellationToken); // Run the Dialog with the new message Activity. await Dialog.Run(turnContext, ConversationState.CreateProperty <DialogState>("DialogState"), /*recognizerResult*/ cancellationToken); } else { await turnContext.SendActivityAsync(MessageFactory.Text("Sorry, I didn't get you."), cancellationToken); } }
/// <summary> /// Every conversation turn for our NLP Dispatch Bot will call this method. /// There are no dialogs used, since it's "single turn" processing, meaning a single /// request and response, with no stateful conversation. /// </summary> /// <param name="turnContext">A <see cref="ITurnContext"/> containing all the data needed /// for processing this conversation turn. </param> /// <param name="cancellationToken">(Optional) A <see cref="CancellationToken"/> that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns> public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { if (turnContext.Activity.Type == ActivityTypes.Message && !turnContext.Responded) { // Get the intent recognition result RecognizerResult recognizerResult = null; try { recognizerResult = await _services.LuisServices[DispatchKey].RecognizeAsync(turnContext, cancellationToken); } catch (System.Exception ex) { throw; } var topIntent = recognizerResult?.GetTopScoringIntent(); if (topIntent == null) { await turnContext.SendActivityAsync("Unable to get the top intent."); } else { await DispatchToTopIntentAsync(turnContext, topIntent, cancellationToken); } } else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate) { // Send a welcome message to the user and tell them what actions they may perform to use this bot if (turnContext.Activity.MembersAdded != null) { await SendWelcomeMessageAsync(turnContext, cancellationToken); } } else { await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected", cancellationToken : cancellationToken); } }
protected Intent GetTopIntent(RecognizerResult luisResult) { if (luisResult == null) { return(_botIntents.DefaultIntent); } var topScoringIntent = luisResult.GetTopScoringIntent(); if (topScoringIntent.score >= _botIntents.IntentTriggerThreshold) { var topIntent = topScoringIntent.intent; if (_botIntents.Intents.ContainsKey(topIntent)) { return(_botIntents.Intents[topIntent]); } else { _logger.LogError($"Fail to find intent {topIntent} in bot definition."); } } return(_botIntents.DefaultIntent); }