Forms

Forms

Note
There is an in-depth tutorial here about how to use Rasa Forms for slot filling.

One of the most common conversation patterns is to collect a few pieces of information from a user in order to do something (book a restaurant, call an API, search a database, etc.). This is also called slot filling.

If you need to collect multiple pieces of information in a row, we recommended that you create a FormAction. This is a single action which contains the logic to loop over the required slots and ask the user for this information. There is a full example using forms in the examples/formbot directory of Rasa Core.

When you define a form, you need to add it to your domain file. If your form’s name is restaurant_form, your domain would look like this:

forms:
  - restaurant_form
actions:
  ...

To use forms, you also need to include the FormPolicy in your policy configuration file. For example:

policies:
  - name: "FormPolicy"

Using a FormAction, you can describe all of the happy paths with a single story. By “happy path”, we mean that whenever you ask a user for some information, they respond with the information you asked for.

If we take the example of the restaurant bot, this single story describes all of the happy paths.

## happy path
* request_restaurant
    - restaurant_form
    - form{"name": "restaurant_form"}
    - form{"name": null}

In this story, the user intent is request_restaurant, which is followed by the form action restaurant_form. With form{"name": "restaurant_form"} the form is activated and with form{"name": null} the form is deactivated again. The bot can execute any kind of actions outside the form while the form is still active.

The FormAction will only request slots which haven’t already been set. If a user starts the conversation with I’d like a vegetarian Chinese restaurant for 8 people, then they won’t be asked about the cuisine and num_people slots.

Note that for this story to work, your slots should be unfeaturized. If any of these slots are featurized, your story needs to include slot{} events to show these slots being set.

Here is an example of what the FormAction looks like. You need to define three methods:

def name(self) -> Text:
    return "restaurant_form"
@staticmethod
def required_slots(tracker: Tracker) -> List[Text]:
    return ["cuisine", "num_people", "outdoor_seating", "preferences", "feedback"]
def submit(
    self,
    dispatcher: CollectingDispatcher,
    tracker: Tracker,
    domain: Dict[Text, Any],
) -> List[Dict]:
    dispatcher.utter_message(template="utter_submit")
    return []

Once the form action gets called for the first time, the form gets activated and the FormPolicy jumps in. The FormPolicy is extremely simple and just always predicts the form action.

Every time the form action gets called, it will ask the user for the next slot in required_slots which is not already set. It does this by looking for a response called utter_ask_{slot_name}, so you need to define these in your domain file for each required slot.

Once all the slots are filled, the submit() method is called, where you can use the information you’ve collected to do something for the user, for example querying a restaurant API. If you don’t want your form to do anything at the end, just use return [] as your submit method.

Custom slot mappings
If you do not define slot mappings, slots will be only filled by entities with the same name as the slot that are picked up from the user input. Some slots, like cuisine, can be picked up using a single entity, but a FormAction can also support yes/no questions and free-text input. The slot_mappings method defines how to extract slot values from user responses.

Here’s an example for the restaurant bot:

def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]:
    return {
        "cuisine": self.from_entity(entity="cuisine", not_intent="chitchat"),
        "num_people": [
            self.from_entity(entity="num_people", intent=["inform", "request_restaurant"]),
            self.from_entity(entity="number"),
        ],
        "outdoor_seating": [
            self.from_entity(entity="seating"),
            self.from_intent(intent="affirm", value=True),
            self.from_intent(intent="deny", value=False),
        ],
        "preferences": [
            self.from_intent(intent="deny", value="no additional preferences"),
            self.from_text(not_intent="affirm"),
        ],
        "feedback": [self.from_entity(entity="feedback"), self.from_text()],
    }

The predefined functions work as follows:

Validating user input

After extracting a slot value from user input, the form will try to validate the value of the slot. Note that by default, validation only happens if the form action is executed immediately after user input.

Here is an example, validate_cuisine(), which checks if the extracted cuisine slot belongs to a list of supported cuisines.

    def validate_cuisine(  
        self,  
        value: Text,  
        dispatcher: CollectingDispatcher,  
        tracker: Tracker,  
        domain: Dict[Text, Any],  
    ) -> Dict[Text, Any]:  
        if value.lower() in self.cuisine_db():
            return {"cuisine": value}
        else:
            dispatcher.utter_message(template="utter_wrong_cuisine")
            return {"cuisine": None}

The helper validation functions return dictionaries of slot names and values to set. If you want to allow a combination of these, provide them as a list as in the example above.

Handling unhappy paths

Of course your users will not always respond with the information you ask of them. Typically, users will ask questions, make chitchat, or otherwise stray from the happy path.

You can handle such situations gracefully using a default action action_deactivate_form which will deactivate the form and reset the requested slot. An example story of such conversation could look as follows:

## chitchat
* request_restaurant
    - restaurant_form
    - form{"name": "restaurant_form"}
* stop
    - utter_ask_continue
* deny
    - action_deactivate_form
    - form{"name": null}

The slot requested_slot is automatically added to the domain as an unfeaturized slot. You might want to make it featurized if you want to handle your unhappy paths differently depending on what slot is currently being asked from the user.

Handling conditional slot logic

You can achieve this by writing some logic into the required_slots() method.

@staticmethod
def required_slots(tracker) -> List[Text]:
    if tracker.get_slot('cuisine') == 'greek':
     return ["cuisine", "num_people", "outdoor_seating", "preferences", "feedback"]
    else:
     return ["cuisine", "num_people", "preferences", "feedback"]

Debugging

Run your bot with the debug flag to see details. One of the guiding principles behind Rasa Core is:

Learning from real conversations is more important than designing hypothetical ones.

👋 I can help you get started with Rasa and answer your technical questions.