pythonnlpwit.ai

How to work with multiple entities in one message in Wit.ai?


I followed this tutorial to write a simple script using Wit.ai.

So, there is a code snippet which retrieves the entity from the first message:

def first_entity_value(entities, entity):
    if entity not in entities:
        return None
    val = entities[entity][0]['value']
    if not val:
        return None
    return val['value'] if isinstance(val, dict) else val

I have two questions:

  1. How can I get entities from the other messages? So, when user type something (not as a first message)?
  2. I have multiple entities in the message (e.g: I'm gonna visit London this weekend), how can I get, for example, the second entity (weekend)? Now I tried to write something like the following but got an error:

    def first_entity_value(entities, entity):
        if entity not in entities:
            return None
        val = entities[entity][0][1]['value'] # to get the second entity
        if not val:
            return None
        return val['value'] if isinstance(val, dict) else val
    

Solution

  • "London" is a location and "weekend" is a datetime. They are not the same entity.

    To retrieve both entities, just adapt the entity argument:

    city = first_entity_value(entities, 'location')
    date = first_entity_value(entities, 'datetime')
    

    If you want to retrieve two values of the same entity (e.g: I love Paris and London), then you should use the method you tried:

    def get_entity_value(entities, entity, pos):
        if entity not in entities:
            return None
        val = entities[entity][pos]['value'] # to get the entity at "pos"
        if not val:
            return None
        return val['value'] if isinstance(val, dict) else val
    

    I don't really get your first question. The selected action(s) (from Wit converse) is/are run every time you receive a message from the user.