コード例 #1
0
def test_last_executed_has_not_name():
    events = [
        ActionExecuted("one"),
        user_uttered("two", 1),
        ActionExecuted(ACTION_LISTEN_NAME),
    ]

    tracker = get_tracker(events)

    assert tracker.last_executed_action_has("another") is False
コード例 #2
0
def test_get_last_event_for_with_skip():
    events = [
        ActionExecuted("one"),
        user_uttered("two", 1),
        ActionExecuted("three")
    ]

    tracker = get_tracker(events)

    assert tracker.get_last_event_for("action", skip=1).get("name") == "one"
コード例 #3
0
def test_applied_events_after_restart():
    events = [
        ActionExecuted("one"),
        user_uttered("two", 1),
        Restarted(),
        ActionExecuted("three"),
    ]

    tracker = get_tracker(events)

    assert tracker.applied_events() == [ActionExecuted("three")]
コード例 #4
0
    def test_provide_feedback_not_given(self):
        tracker = self.create_tracker(
            slots={
                REQUESTED_SLOT: FEEDBACK_SLOT,
                QUESTION_SLOT: QUESTION,
                ANSWERS_SLOT: ANSWERS,
                STATUS_SLOT: QuestionAnsweringStatus.SUCCESS,
            },
            text="some text with",
            intent="another_intent",
            entities=[{
                "and": "entities"
            }],
        )

        self.run_form(tracker, DOMAIN)

        self.assert_events([
            SlotSet(FEEDBACK_SLOT, FEEDBACK_NOT_GIVEN),
            SlotSet(QUESTION_SLOT, None),
            SlotSet(FEEDBACK_SLOT, None),
            SlotSet(
                ASKED_QUESTION_SLOT,
                {
                    **FULL_RESULT_SUCCESS, FEEDBACK_KEY: FEEDBACK_NOT_GIVEN
                },
            ),
            Form(None),
            SlotSet(REQUESTED_SLOT, None),
            ActionExecuted("utter_ask_another_question"),
            ActionExecuted("action_listen"),
            UserUttered(
                "some text with",
                parse_data={
                    "text": "some text with",
                    "intent": {
                        "name": "another_intent"
                    },
                    "intent_ranking": [],
                    "entities": [{
                        "and": "entities"
                    }],
                },
            ),
            Form(None),
            SlotSet(REQUESTED_SLOT, None),
        ])

        self.assert_templates([])
コード例 #5
0
def _carry_user_utterance(tracker: Tracker) -> List[EventType]:
    return [
        ActionExecuted("utter_ask_another_question"),
        BotUttered(metadata={"template_name": "utter_ask_another_question"}),
        ActionExecuted(ACTION_LISTEN_NAME),
        UserUttered(
            tracker.latest_message.get("text", ""),
            parse_data={
                "text": tracker.latest_message.get("text", ""),
                "intent": tracker.latest_message.get("intent", {}),
                "intent_ranking": tracker.latest_message.get("intent_ranking", []),
                "entities": tracker.latest_message.get("entities", []),
            },
        ),
    ]
コード例 #6
0
def latest_events(template_name):
    return [
        BotUttered(text="Heigh ho, heigh ho",
                   metadata={"template_name": template_name}),
        ActionExecuted(ACTION_LISTEN_NAME),
        UserUttered(USER_TEXT),
    ]
コード例 #7
0
ファイル: actions.py プロジェクト: Albert-91/BARF-o-bot
    def inject_user_utterance_event(self, user_event):
        """Returns events that injects given user utterance event (with all appropriate data) into tracker state to
           allow handling them on stories same way as comes from user input. Use this method in other actions
           in theirs return statement.
           [More details here ](https://forum.rasa.com/t/trigger-a-story-or-intent-from-a-custom-action/13784/9)"""

        return [ActionExecuted('action_listen', confidence=1.0), user_event]
    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[EventType]:

        # the session should begin with a `session_started` event
        events = [SessionStarted()]

        events.extend(self._slot_set_events_from_tracker(tracker))

        # create mock profile
        user_profile = create_mock_profile()

        # initialize slots from mock profile
        for key, value in user_profile.items():
            if value is not None:
                events.append(SlotSet(key=key, value=value))

        # an `action_listen` should be added at the end
        events.append(ActionExecuted("action_listen"))

        # evt = {'event': 'followup', 'name': 'action_greet_user'}
        # events.append(evt)
        # events.append(ActionExecuted("action_greet_user"))
        # logger.debug(f"These are the events: {events[-1]}")
        # return [events, FollowupAction("action_listen")]
        return events
コード例 #9
0
ファイル: action_fallback.py プロジェクト: fparga/covidflow
    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        bind_logger(tracker)

        last_user_event = tracker.get_last_event_for("user")
        last_user_event = copy.deepcopy(last_user_event)
        text = last_user_event["text"]

        fallback_user_event = UserUttered(
            text,
            parse_data={
                "text": text,
                "intent": {"name": "fallback", "confidence": 1.0},
                "intent_ranking": [{"name": "fallback", "confidence": 1.0}],
                "entities": [],
            },
        )

        return [
            UserUtteranceReverted(),
            ActionExecuted("action_listen"),
            fallback_user_event,
        ]
コード例 #10
0
 async def run(self,dispatcher, tracker, domain):
     events = [SessionStarted()]
     events.extend(self._slot_set_events_from_tracker(tracker))
     username = tracker.get_slot('name') if tracker.get_slot("name") else tracker.current_state()["sender_id"]    
     dispatcher.utter_message(text=f"Hello {username}")
     events.append(ActionExecuted("action_listen"))
     return events
コード例 #11
0
    def run(self, dispatcher, tracker, domain) -> List[EventType]:
        if tracker.get_slot("step"):
            step = int(tracker.get_slot("step")) + 1

            if step in [2, 3, 4]:
                dispatcher.utter_message(template=f"utter_continue_step{step}")
            else:
                dispatcher.utter_message(template="utter_no_more_steps")

            return []

        else:
            # trigger get_started_step1 intent
            return [
                ActionExecuted("action_listen"),
                UserUttered(
                    "/get_started_step1",
                    {
                        "intent": {
                            "name": "get_started_step1",
                            "confidence": 1.0
                        },
                        "entities": {},
                    },
                ),
            ]
コード例 #12
0
    async def run(self, dispatcher, tracker: Tracker,
                  domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        # the session should begin with a `session_started` event
        events = [SessionStarted()]
        try:
            r = requests.get(
                'https://1ntj0abfh0.execute-api.us-east-1.amazonaws.com/PROD/customer?contactId='
                + tracker.sender_id)
            print(r.status_code)
            if r.status_code > 300:

                raise Exception("No Data supplied")
            data = r.json()
            for key in data:
                events.append(SlotSet(key, data[key]))
        except:
            data = {
                "name": "DemoMan",
                "payment_amount": "500 pesos",
                "payment_date": "22 de Enero"
            }

            for key in data:
                events.append(SlotSet(key, data[key]))

        # an `action_listen` should be added at the end as a user message follows
        events.append(ActionExecuted("action_listen"))
        return events
コード例 #13
0
    async def test_other_intent(self):
        tracker = self.create_tracker(
            intent="unrelated", events=latest_events("utter_dwarfs_song"))

        await self.run_action(tracker)

        self.assert_events([
            UserUtteranceReverted(),
            ActionExecuted(ACTION_LISTEN_NAME),
            UserUttered(
                USER_TEXT,
                parse_data={
                    "text":
                    USER_TEXT,
                    "intent": {
                        "name": FALLBACK_INTENT,
                        "confidence": 1.0
                    },
                    "intent_ranking": [{
                        "name": FALLBACK_INTENT,
                        "confidence": 1.0
                    }],
                    "entities": [],
                },
            ),
        ])

        self.assert_templates([])
コード例 #14
0
    async def test_assessment_type_with_previous_tested_positive(self):
        tracker = self.create_tracker(events=[
            UserUttered(
                "tested positive",
                parse_data={
                    "text": "tested positive",
                    "intent": {
                        "name": "tested_positive",
                        "confidence": 1.0
                    },
                    "entities": [],
                },
            ),
            UserUttered(
                "yes",
                parse_data={
                    "text": "yes",
                    "intent": {
                        "name": "affirm",
                        "confidence": 1.0
                    },
                    "entities": [],
                },
            ),
            ActionExecuted(self.form_name),
            SlotSet(ASSESSMENT_TYPE_SLOT, AssessmentType.GENERIC),
        ])

        await self.run_action(tracker)

        self.assert_events(
            [SlotSet(ASSESSMENT_TYPE_SLOT, AssessmentType.TESTED_POSITIVE)])

        self.assert_templates([])
コード例 #15
0
def test_latest_input_channel():
    tracker = get_tracker([
        UserUttered("my message text", input_channel="superchat"),
        ActionExecuted("action_listen"),
    ])

    assert tracker.get_latest_input_channel() == "superchat"
コード例 #16
0
    async def run(
            self,
            dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any],
    ) -> List[EventType]:
        # the session should begin with a `session_started` event
        message_metadata = []
        events = tracker.current_state()['events']
        for e in events:
            if e['event'] == 'user' or e['event'] == 'session_started':
                message_metadata.append(e)
        meta = message_metadata[-1]["metadata"]["metadata"]
        meta_dict = ast.literal_eval(meta)
        per_id = meta_dict["id"]
        fname = meta_dict["first_name"]
        lname = meta_dict["last_name"]
        events = [SessionStarted()]
        dispatcher.utter_message(template="utter_iamabot")
        dispatcher.utter_message("Pleased to meet you, {}!".format(fname))
        dispatcher.utter_message("How're you doing today?")
        # any slots that should be carried over should come after the
        # `session_started` event
        events.extend(self.fetch_slots(dispatcher, tracker))

        # an `action_listen` should be added at the end as a user message follows
        events.append(ActionExecuted("action_listen"))

        return events
コード例 #17
0
   def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[EventType]:

       dispatcher.utter_message("Hi, I am Woody. How may I help you")
       events=[SessionStarted()]
       events.append(ActionExecuted("action_listen"))

       return events
コード例 #18
0
 def run(
     self,
     dispatcher: CollectingDispatcher,
     tracker: Tracker,
     domain: Dict[Text, Any],
 ) -> List[Dict[Text, Any]]:
     actions = self.get_carry_over_slots(tracker)
     actions.append(ActionExecuted("action_listen"))
     return actions
コード例 #19
0
ファイル: test_tracker.py プロジェクト: nbeuchat/rasa-sdk
def test_get_extracted_slots_with_no_active_loop():
    events = [
        ActionExecuted("my_form"),
        SlotSet("my_slot", "some_value"),
        SlotSet("some_other", "some_value2"),
    ]
    tracker = get_tracker(events)

    assert tracker.form_slots_to_validate() == {}
コード例 #20
0
    async def test_action_not_in_list(self):
        tracker = self.create_tracker(
            intent=FORBIDDEN_INTENT,
            events=[
                ActionExecuted("action_another"),
                ActionExecuted(ACTION_LISTEN_NAME),
                UserUttered(text="text",
                            parse_data={"intent": FORBIDDEN_INTENT}),
            ],
        )

        await self.run_action(tracker)

        self.assert_events(
            [ActionReverted(),
             FollowupAction(FALLBACK_ACTION_NAME)])

        self.assert_templates([])
コード例 #21
0
def _carry_user_utterance(tracker: Tracker) -> List[EventType]:
    return [
        Form(
            None
        ),  # Ending it manually to have events in correct order to fit stories
        SlotSet(REQUESTED_SLOT, None),
        ActionExecuted("utter_ask_another_question"),
        ActionExecuted("action_listen"),
        UserUttered(
            tracker.latest_message.get("text", ""),
            parse_data={
                "text": tracker.latest_message.get("text", ""),
                "intent": tracker.latest_message.get("intent", {}),
                "intent_ranking":
                tracker.latest_message.get("intent_ranking", []),
                "entities": tracker.latest_message.get("entities", []),
            },
        ),
    ]
コード例 #22
0
async def test_run_action_session_start(dispatcher, domain):
    tracker = EMPTY_TRACKER
    action = actions.ActionSessionStart()
    events = await action.run(dispatcher, tracker, domain)
    expected_events = [
        SessionStarted(),
        SlotSet("currency", "INR"),
        ActionExecuted("action_listen"),
    ]
    assert events == expected_events
コード例 #23
0
 def test_carry_over_slots(self):
     """
     Should set all the carry over slots, and then add a listen at the end
     """
     dispatcher = CollectingDispatcher()
     tracker = Tracker("", {}, None, [], False, None, None, None)
     actions = ActionSessionStart().run(dispatcher, tracker, {})
     assert actions[0] == SessionStarted()
     assert actions[-1] == ActionExecuted("action_listen")
     assert len(actions) > 2
コード例 #24
0
ファイル: actions.py プロジェクト: ChaosDestiny/Project-II
 def start_story_events(story_intent):
     # type: (Text) -> List[Dict]
     return [ActionExecuted("action_listen")] + [
         UserUttered(
             "/" + story_intent, {
                 "intent": {
                     "name": story_intent,
                     "confidence": 1.0
                 },
                 "entities": {}
             })
     ]
コード例 #25
0
    async def test_submit_feedback_not_given(self):
        tracker = self.create_tracker(
            slots={
                QUESTION_SLOT: QUESTION,
                FEEDBACK_SLOT: FEEDBACK_NOT_GIVEN,
                ANSWERS_SLOT: ANSWERS,
                STATUS_SLOT: QuestionAnsweringStatus.SUCCESS,
            },
            text="some text with",
            intent="another_intent",
            entities=[{"and": "entities"}],
        )

        await self.run_action(tracker)

        self.assert_events(
            [
                SlotSet(QUESTION_SLOT, None),
                SlotSet(FEEDBACK_SLOT, None),
                SlotSet(
                    ASKED_QUESTION_SLOT,
                    {**FULL_RESULT_SUCCESS, FEEDBACK_KEY: FEEDBACK_NOT_GIVEN},
                ),
                ActionExecuted("utter_ask_another_question"),
                BotUttered(metadata={"template_name": "utter_ask_another_question"}),
                ActionExecuted(ACTION_LISTEN_NAME),
                UserUttered(
                    "some text with",
                    parse_data={
                        "text": "some text with",
                        "intent": {"name": "another_intent"},
                        "intent_ranking": [],
                        "entities": [{"and": "entities"}],
                    },
                ),
            ]
        )

        self.assert_templates([])
コード例 #26
0
ファイル: actions.py プロジェクト: ChikkaUdayaSai/cora
    async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], **kwargs) -> List[
        EventType]:

        # the session should begin with a `session_started` event
        events = [SessionStarted()]

        # any slots that should be carried over should come after the
        # `session_started` event
        events.extend(self.fetch_slots(tracker))

        # an `action_listen` should be added at the end as a user message follows
        events.append(ActionExecuted("action_listen"))

        return events
コード例 #27
0
ファイル: actions.py プロジェクト: ChaosDestiny/Project-II
 def run(self, dispatcher, tracker, domain):
     
     song = tracker.get_slot('song')
     if (song != None):
         query = urllib.parse.quote(song)
         url = "https://www.youtube.com/results?search_query=" + query
         response = urllib.request.urlopen(url)
         results = re.findall(re.compile("\"/watch\?v=(.{11})"), response.read().decode())
         vid = "http://www.youtube.com/watch?v=" + results[0]
         webbrowser.open_new_tab(vid)
         return dispatcher.utter_message(text="Của bạn đây: " + vid)
     else:
         dispatcher.utter_message(text="Bạn muốn nghe bài gì?")
         return [ActionExecuted("action_listen")]
コード例 #28
0
    async def check_activation(
        self,
        events: List[EventType] = None,
        previous_slots: dict = None,
        templates: List[str] = None,
    ) -> None:
        tracker = self.create_tracker(
            events=[ActionExecuted(self.form_name)],
            slots=previous_slots or {},
        )

        await self.run_action(tracker, self.domain)

        self.assert_events(events or [])

        self.assert_templates((templates or []))
コード例 #29
0
ファイル: actions.py プロジェクト: Albert-91/BARF-o-bot
    def inject_intent(self, intent):
        """Returns events that injects given intent into tracker state to allow handling them on stories same way
           as comes from user input. Use this method in other actions in theirs return statement.
           [More details here ](https://forum.rasa.com/t/trigger-a-story-or-intent-from-a-custom-action/13784/9)"""

        return [
            ActionExecuted('action_listen', confidence=1.0),
            UserUttered(text='/' + intent,
                        parse_data={
                            'intent': {
                                'name': intent,
                                'confidence': 1.0
                            },
                            'entities': []
                        })
        ]
コード例 #30
0
ファイル: actions.py プロジェクト: ChikkaUdayaSai/cora
    async def run(self, dispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        events = []

        try:
            for symptom in get_symptoms_by_severity(tracker.sender_id):
                if tracker.get_slot(symptom.name) is not None:
                    if symptom.severity is not None:
                        dispatcher.utter_message(self.templates["ask_severity"].format(symptom=symptom.name,
                                                                                       severity=symptom.severity))
                    else:
                        dispatcher.utter_message(self.templates["ask_severity_no_value"].format(symptom=symptom.name))
                    return [ActionExecuted('action_ask_' + symptom.name)]

        except AttributeError:
            return []