Extracting an Entity from LUIS in Bot Framework

Recent changes to the supporting LUIS libraries in the Bot Framework have puzzled me. I find that whilst getting the Top Intent from the RecognizerResult recognizerResult?.GetTopScoringIntent(); is easy, getting hold of an Entity seems very strange. I’m not sure if it’s my SDK, LUIS models or what, but this is the code I’m currently having to use…and I confess I still find it all very odd [Edit 20-Nov-2018] Code changed to better cope with arrays coming and going :s;

public static T GetEntity<T>(this RecognizerResult luisResult, string entityKey, string valuePropertyName = "text")
{
    if (luisResult != null)
    {
        //// var value = (luisResult.Entities["$instance"][entityKey][0]["text"] as JValue).Value;
        var data = luisResult.Entities as IDictionary<string, JToken>;

        if (data.TryGetValue("$instance", out JToken value))
        {
            var entities = value as IDictionary<string, JToken>;
            if (entities.TryGetValue(entityKey, out JToken targetEntity))
            {
                var entityArray = targetEntity as JArray;
                if (entityArray.Count > 0)
                {
                    var values = entityArray[0] as IDictionary<string, JToken>;
                    if (values.TryGetValue(valuePropertyName, out JToken textValue))
                    {
                        var text = textValue as JValue;
                        if (text != null)
                        {
                            return (T)text.Value;
                        }
                    }
                }
            }
        }
    }

    return default(T);
}

Hope it helps

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s