private async Task <RecognizerResult> RecognizeInternalAsync(ITurnContext turnContext, Dictionary <string, string> telemetryProperties, Dictionary <string, double> telemetryMetrics, CancellationToken cancellationToken)
        {
            BotAssert.ContextNotNull(turnContext);

            if (turnContext.Activity.Type != ActivityTypes.Message)
            {
                return(null);
            }

            var utterance = turnContext.Activity?.AsMessageActivity()?.Text;

            if (string.IsNullOrWhiteSpace(utterance))
            {
                throw new ArgumentNullException(nameof(utterance));
            }

            var luisResult = await _runtime.Prediction.ResolveAsync(
                _application.ApplicationId,
                utterance,
                timezoneOffset : _options.TimezoneOffset,
                verbose : _options.IncludeAllIntents,
                staging : _options.Staging,
                spellCheck : _options.SpellCheck,
                bingSpellCheckSubscriptionKey : _options.BingSpellCheckSubscriptionKey,
                log : _options.Log ?? true,
                cancellationToken : cancellationToken).ConfigureAwait(false);

            var recognizerResult = new RecognizerResult
            {
                Text        = utterance,
                AlteredText = luisResult.AlteredQuery,
                Intents     = LuisUtil.GetIntents(luisResult),
                Entities    = LuisUtil.ExtractEntitiesAndMetadata(luisResult.Entities, luisResult.CompositeEntities, _options.IncludeInstanceData ?? true),
            };

            LuisUtil.AddProperties(luisResult, recognizerResult);
            if (_includeApiResults)
            {
                recognizerResult.Properties.Add("luisResult", luisResult);
            }

            // Log telemetry
            await OnRecognizerResultAsync(recognizerResult, turnContext, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false);

            var traceInfo = JObject.FromObject(
                new
            {
                recognizerResult,
                luisModel = new
                {
                    ModelID = _application.ApplicationId,
                },
                luisOptions = _options,
                luisResult,
            });

            await turnContext.TraceActivityAsync("LuisRecognizer", traceInfo, LuisTraceType, LuisTraceLabel, cancellationToken).ConfigureAwait(false);

            return(recognizerResult);
        }
Beispiel #2
0
        private RecognizerResult BuildRecognizerResultFromLuisResult(LuisResult luisResult, string utterance)
        {
            var recognizerResult = new RecognizerResult
            {
                Text        = utterance,
                AlteredText = luisResult.AlteredQuery,
                Intents     = LuisUtil.GetIntents(luisResult),
                Entities    = LuisUtil.ExtractEntitiesAndMetadata(luisResult.Entities, luisResult.CompositeEntities, PredictionOptions.IncludeInstanceData ?? true, utterance),
            };

            LuisUtil.AddProperties(luisResult, recognizerResult);
            if (IncludeAPIResults)
            {
                recognizerResult.Properties.Add("luisResult", luisResult);
            }

            return(recognizerResult);
        }
Beispiel #3
0
        internal override async Task <RecognizerResult> RecognizeInternalAsync(ITurnContext turnContext, HttpClient httpClient, CancellationToken cancellationToken)
        {
            BotAssert.ContextNotNull(turnContext);

            if (turnContext.Activity == null || turnContext.Activity.Type != ActivityTypes.Message)
            {
                return(null);
            }

            var utterance = turnContext.Activity?.AsMessageActivity()?.Text;
            RecognizerResult recognizerResult;
            LuisResult       luisResult = null;

            if (string.IsNullOrWhiteSpace(utterance))
            {
                recognizerResult = new RecognizerResult
                {
                    Text = utterance
                };
            }
            else
            {
                var credentials = new ApiKeyServiceClientCredentials(Application.EndpointKey);
                var runtime     = new LUISRuntimeClient(credentials, httpClient, false)
                {
                    Endpoint = Application.Endpoint,
                };
                luisResult = await runtime.Prediction.ResolveAsync(
                    Application.ApplicationId,
                    utterance,
                    timezoneOffset : PredictionOptions.TimezoneOffset,
                    verbose : PredictionOptions.IncludeAllIntents,
                    staging : PredictionOptions.Staging,
                    spellCheck : PredictionOptions.SpellCheck,
                    bingSpellCheckSubscriptionKey : PredictionOptions.BingSpellCheckSubscriptionKey,
                    log : PredictionOptions.Log ?? true,
                    cancellationToken : cancellationToken).ConfigureAwait(false);

                recognizerResult = new RecognizerResult
                {
                    Text        = utterance,
                    AlteredText = luisResult.AlteredQuery,
                    Intents     = LuisUtil.GetIntents(luisResult),
                    Entities    = LuisUtil.ExtractEntitiesAndMetadata(luisResult.Entities, luisResult.CompositeEntities, PredictionOptions.IncludeInstanceData ?? true, utterance),
                };
                LuisUtil.AddProperties(luisResult, recognizerResult);
                if (IncludeAPIResults)
                {
                    recognizerResult.Properties.Add("luisResult", luisResult);
                }
            }

            var traceInfo = JObject.FromObject(
                new
            {
                recognizerResult,
                luisModel = new
                {
                    ModelID = Application.ApplicationId,
                },
                luisOptions = PredictionOptions,
                luisResult,
            });

            await turnContext.TraceActivityAsync("LuisRecognizer", traceInfo, LuisTraceType, LuisTraceLabel, cancellationToken).ConfigureAwait(false);

            return(recognizerResult);
        }
Beispiel #4
0
        private async Task <RecognizerResult> RecognizeInternalAsync(ITurnContext turnContext, LuisPredictionOptions predictionOptions, Dictionary <string, string> telemetryProperties, Dictionary <string, double> telemetryMetrics, CancellationToken cancellationToken)
        {
            var luisPredictionOptions = predictionOptions == null ? _options : MergeDefaultOptionsWithProvidedOptions(_options, predictionOptions);

            BotAssert.ContextNotNull(turnContext);

            if (turnContext.Activity.Type != ActivityTypes.Message)
            {
                return(null);
            }

            var utterance = turnContext.Activity?.AsMessageActivity()?.Text;
            RecognizerResult recognizerResult;
            LuisResult       luisResult = null;

            if (string.IsNullOrWhiteSpace(utterance))
            {
                recognizerResult = new RecognizerResult
                {
                    Text    = utterance,
                    Intents = new Dictionary <string, IntentScore>()
                    {
                        { string.Empty, new IntentScore()
                          {
                              Score = 1.0
                          } }
                    },
                    Entities = new JObject(),
                };
            }
            else
            {
                luisResult = await _runtime.Prediction.ResolveAsync(
                    _application.ApplicationId,
                    utterance,
                    timezoneOffset: luisPredictionOptions.TimezoneOffset,
                    verbose: luisPredictionOptions.IncludeAllIntents,
                    staging: luisPredictionOptions.Staging,
                    spellCheck: luisPredictionOptions.SpellCheck,
                    bingSpellCheckSubscriptionKey : luisPredictionOptions.BingSpellCheckSubscriptionKey,
                    log : luisPredictionOptions.Log ?? true,
                    cancellationToken : cancellationToken).ConfigureAwait(false);

                recognizerResult = new RecognizerResult
                {
                    Text        = utterance,
                    AlteredText = luisResult.AlteredQuery,
                    Intents     = LuisUtil.GetIntents(luisResult),
                    Entities    = LuisUtil.ExtractEntitiesAndMetadata(luisResult.Entities, luisResult.CompositeEntities, luisPredictionOptions.IncludeInstanceData ?? true, utterance),
                };
                LuisUtil.AddProperties(luisResult, recognizerResult);
                if (_includeApiResults)
                {
                    recognizerResult.Properties.Add("luisResult", luisResult);
                }
            }

            // Log telemetry
            await OnRecognizerResultAsync(recognizerResult, turnContext, telemetryProperties, telemetryMetrics, cancellationToken).ConfigureAwait(false);

            var traceInfo = JObject.FromObject(
                new
            {
                recognizerResult,
                luisModel = new
                {
                    ModelID = _application.ApplicationId,
                },
                luisOptions = luisPredictionOptions,
                luisResult,
            });

            await turnContext.TraceActivityAsync("LuisRecognizer", traceInfo, LuisTraceType, LuisTraceLabel, cancellationToken).ConfigureAwait(false);

            return(recognizerResult);
        }
        private async Task <RecognizerResult> RecognizeInternalAsync(ITurnContext turnContext, LuisPredictionOptions predictionOptions, Dictionary <string, string> telemetryProperties, Dictionary <string, double> telemetryMetrics, CancellationToken cancellationToken)
        {
            BotAssert.ContextNotNull(turnContext);
            if (turnContext.Activity.Type != ActivityTypes.Message)
            {
                return(null);
            }

            var options   = predictionOptions ?? _predictionOptions;
            var utterance = turnContext.Activity?.AsMessageActivity()?.Text;
            RecognizerResult recognizerResult;
            JObject          luisResponse = null;

            if (string.IsNullOrWhiteSpace(utterance))
            {
                recognizerResult = new RecognizerResult
                {
                    Text    = utterance,
                    Intents = new Dictionary <string, IntentScore>()
                    {
                        { string.Empty, new IntentScore()
                          {
                              Score = 1.0
                          } }
                    },
                    Entities = new JObject(),
                };
            }
            else
            {
                var uri = new UriBuilder(_application.Endpoint);

                // TODO: When the endpoint GAs, we will need to change this.  I could make it an option, but other code is likely to need to change.
                uri.Path += $"luis/v3.0-preview/apps/{_application.ApplicationId}";

                var query = AddParam(null, "verbose", options.IncludeInstanceData);
                query     = AddParam(query, "log", options.Log);
                query     = AddParam(query, "show-all-intents", options.IncludeAllIntents);
                uri.Query = query;

                var content = new JObject
                {
                    { "query", utterance },
                };
                var queryOptions = new JObject
                {
                    { "overridePredictions", options.PreferExternalEntities },
                };
                content.Add("options", queryOptions);

                var settings = new JsonSerializerSettings {
                    NullValueHandling = NullValueHandling.Ignore
                };
                if (options.DynamicLists != null)
                {
                    foreach (var list in options.DynamicLists)
                    {
                        list.Validate();
                    }

                    content.Add("dynamicLists", (JArray)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(options.DynamicLists, settings)));
                }

                if (options.ExternalEntities != null)
                {
                    foreach (var entity in options.ExternalEntities)
                    {
                        entity.Validate();
                    }

                    content.Add("externalEntities", (JArray)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(options.ExternalEntities, settings)));
                }

                if (options.Version == null)
                {
                    uri.Path += $"/slots/{options.Slot}/predict";
                }
                else
                {
                    uri.Path += $"/versions/{options.Version}/predict";
                }

                var response = await DefaultHttpClient.PostAsync(uri.Uri, new StringContent(content.ToString(), System.Text.Encoding.UTF8, "application/json")).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();
                luisResponse = (JObject)JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
                var prediction = (JObject)luisResponse["prediction"];
                recognizerResult = new RecognizerResult
                {
                    Text        = utterance,
                    AlteredText = prediction["alteredQuery"]?.Value <string>(),
                    Intents     = LuisUtil.GetIntents(prediction),
                    Entities    = LuisUtil.ExtractEntitiesAndMetadata(prediction),
                };
                LuisUtil.AddProperties(prediction, recognizerResult);
                if (options.IncludeAPIResults)
                {
                    recognizerResult.Properties.Add("luisResult", luisResponse);
                }
            }

            // Log telemetry
            OnRecognizerResult(recognizerResult, turnContext, telemetryProperties, telemetryMetrics);

            var traceInfo = JObject.FromObject(
                new
            {
                recognizerResult,
                luisModel = new
                {
                    ModelID = _application.ApplicationId,
                },
                luisOptions = options,
                luisResult  = luisResponse,
            });

            await turnContext.TraceActivityAsync("LuisRecognizer", traceInfo, LuisTraceType, LuisTraceLabel, cancellationToken).ConfigureAwait(false);

            return(recognizerResult);
        }