refactor forms RasaHQ/roadmap#263
@@ -6,7 +6,7 @@ from __future__ import unicode_literals
import logging
import typing
-from typing import Dict, Text, Any, List
+from typing import Dict, Text, Any, List, Union
from rasa_core_sdk import Action, ActionExecutionError
from rasa_core_sdk.events import SlotSet, Form
@@ -37,23 +37,32 @@ class FormAction(Action):
raise NotImplementedError("A form must implement required slots "
"that it has to fill")
+ def slot_mapping(self):
+ # type: () -> Dict[Text: Union[Text, List[Text]]]
+ """A dictionary to map required slots to extracted entities"""
+
+ return dict(zip(self.required_slots(), self.required_slots()))
+
# noinspection PyUnusedLocal
def validate(self, dispatcher, tracker, domain):
# type: (CollectingDispatcher, Tracker, Dict[Text, Any]) -> List[Dict]
""""Validate the user input else return an error"""
+ slot_to_fill = tracker.slots[REQUESTED_SLOT]
+
+ # map requested_slot to entity
+ required_entities = self.slot_mapping().get(slot_to_fill)
+
+ if required_entities:
+ if isinstance(required_entities, str):
+ required_entities = [required_entities]
- events = []
for e in tracker.latest_message["entities"]:
- if e.get("entity") == tracker.slots[REQUESTED_SLOT]:
- events.append(SlotSet(e['entity'], e['value']))
+ if e.get("entity") in required_entities:
+ return [SlotSet(slot_to_fill, e['value'])]
- if events:
- return events
- else:
raise ActionExecutionError("Failed to validate slot {0} "
"with action {1}"
- "".format(tracker.slots[REQUESTED_SLOT],
- self.name()),
+ "".format(slot_to_fill, self.name()),
self.name())
def submit(self, dispatcher, tracker, domain):
