Example #1
0
        def webhook():
            sender_id = self._extract_sender(request)
            text = self._extract_message(request)

            collector = CallbackOutput(self.callback_endpoint)
            on_new_message(UserMessage(text, collector, sender_id))
            return "success"
Example #2
0
def test_int_message_id_in_user_message():
    from rasa_core.channels import UserMessage

    # noinspection PyTypeChecker
    message = UserMessage("B text", message_id=987654321)

    assert message.message_id == "987654321"
Example #3
0
        async def message(request: Request):
            sender = request.form.get("From", None)
            text = request.form.get("Body", None)

            out_channel = TwilioOutput(
                self.account_sid, self.auth_token, self.twilio_number
            )

            if sender is not None and message is not None:
                try:
                    # @ signs get corrupted in SMSes by some carriers
                    text = text.replace("¡", "@")
                    # await on_new_message(
                    #     UserMessage(
                    #         text, out_channel, sender, input_channel=self.name()
                    #     )
                    # )
                    user_msg = UserMessage(text, out_channel, sender)
                    on_new_message(user_msg)
                except Exception as e:
                    logger.error(
                        "Exception when trying to handle message.{0}".format(e)
                    )
                    logger.debug(e, exc_info=True)
                    if self.debug_mode:
                        raise
                    pass
            else:
                logger.debug("Invalid message")

            return response.text("success")
Example #4
0
def test_remote_client(http_app, default_agent, tmpdir):
    model_path = tmpdir.join("persisted_model").strpath

    default_agent.persist(model_path)

    remote_agent = RemoteAgent.load(model_path, EndpointConfig(http_app))

    message = UserMessage("""/greet{"name":"Rasa"}""",
                          output_channel=CollectingOutputChannel())

    remote_agent.process_message(message)

    tracker = remote_agent.core_client.tracker_json("default")

    assert len(tracker.get("events")) == 6

    # listen
    assert tracker["events"][0]["name"] == "action_listen"
    # this should be the utterance
    assert tracker["events"][1]["text"] == """/greet{"name":"Rasa"}"""
    # set slot event
    assert tracker["events"][2]["value"] == "Rasa"
    # utter action
    assert tracker["events"][3]["name"] == "utter_greet"
    # this should be the bot utterance
    assert tracker["events"][4]["text"] == "hey there Rasa!"
    # listen
    assert tracker["events"][5]["name"] == "action_listen"
Example #5
0
def test_message_processor(default_processor):
    out = CollectingOutputChannel()
    default_processor.handle_message(UserMessage('/greet{"name":"Core"}', out))
    assert {
        'recipient_id': 'default',
        'text': 'hey there Core!'
    } == out.latest_output()
Example #6
0
    def handle_message(
        self,
        text_message,  # type: Text
        message_preprocessor=None,  # type: Optional[Callable[[Text], Text]]
        output_channel=None,  # type: Optional[OutputChannel]
        sender_id=UserMessage.DEFAULT_SENDER_ID  # type: Optional[Text]
    ):
        # type: (...) -> Optional[List[Text]]
        """Handle a single message.

        If a message preprocessor is passed, the message will be passed to that
        function first and the return value is then used as the
        input for the dialogue engine.

        The return value of this function depends on the `output_channel`. If
        the output channel is not set, set to `None`, or set
        to `CollectingOutputChannel` this function will return the messages
        the bot wants to respond.

        :Example:

            >>> from rasa_core.agent import Agent
            >>> agent = Agent.load("examples/restaurantbot/models/dialogue",
            ... interpreter="examples/restaurantbot/models/nlu/current")
            >>> agent.handle_message("hello")
            [u'how can I help you?']

        """
        # Creates a new processor for the agent and handles
        # the single message
        processor = self._create_processor(message_preprocessor)
        return processor.handle_message(
            UserMessage(text_message, output_channel, sender_id))
Example #7
0
    def handle_reminder(self, reminder_event, dispatcher):
        # type: (ReminderScheduled, Dispatcher) -> None
        """Handle a reminder that is triggered asynchronously."""

        tracker = self._get_tracker(dispatcher.sender_id)

        if not tracker:
            logger.warning("Failed to retrieve or create tracker for sender "
                           "'{}'.".format(dispatcher.sender_id))
            return None

        if (reminder_event.kill_on_user_message
                and self._has_message_after_reminder(tracker, reminder_event)
                or not self._is_reminder_still_valid(tracker, reminder_event)):
            logger.debug("Canceled reminder because it is outdated. "
                         "(event: {} id: {})".format(
                             reminder_event.action_name, reminder_event.name))
        else:
            # necessary for proper featurization, otherwise the previous
            # unrelated message would influence featurization
            tracker.update(UserUttered.empty())
            action = self._get_action(reminder_event.action_name)
            should_continue = self._run_action(action, tracker, dispatcher)
            if should_continue:
                user_msg = UserMessage(None, dispatcher.output_channel,
                                       dispatcher.sender_id)
                self._predict_and_execute_next_action(user_msg, tracker)
            # save tracker state to continue conversation from this state
            self._save_tracker(tracker)
Example #8
0
    def handle_reminder(self, reminder_event, dispatcher):
        # type: (ReminderScheduled, Dispatcher) -> None
        """Handle a reminder that is triggered asynchronously."""
        def has_message_after_reminder(tracker):
            """If the user sent a message after the reminder got scheduled -
            it might be better to cancel it."""

            for e in reversed(tracker.events):
                if isinstance(e,
                              ReminderScheduled) and e.name == \
                        reminder_event.name:
                    return False
                elif isinstance(e, UserUttered):
                    return True
            return True  # tracker has probably been restarted

        tracker = self._get_tracker(dispatcher.sender_id)

        if (reminder_event.kill_on_user_message
                and has_message_after_reminder(tracker)):
            logger.debug("Canceled reminder because it is outdated. "
                         "(event: {} id: {})".format(
                             reminder_event.action_name, reminder_event.name))
        else:
            # necessary for proper featurization, otherwise the previous
            # unrelated message would influence featurization
            tracker.update(UserUttered.empty())
            action = self.domain.action_for_name(reminder_event.action_name)
            should_continue = self._run_action(action, tracker, dispatcher)
            if should_continue:
                user_msg = UserMessage(None, dispatcher.output_channel,
                                       dispatcher.sender_id)
                self._predict_and_execute_next_action(user_msg, tracker)
            # save tracker state to continue conversation from this state
            self._save_tracker(tracker)
    def log_message(sender_id):
        request_params = request.get_json(force=True)
        try:
            message = request_params["message"]
        except KeyError:
            message = request_params.get("text")

        sender = request_params.get("sender")
        parse_data = request_params.get("parse_data")
        verbosity = event_verbosity_parameter(EventVerbosity.AFTER_RESTART)

        # TODO: implement properly for agent / bot
        if sender != "user":
            return error(
                500, "NotSupported",
                "Currently, only user messages can be passed "
                "to this endpoint. Messages of sender '{}' "
                "can not be handled. ".format(sender), {
                    "parameter": "sender",
                    "in": "body"
                })

        try:
            usermsg = UserMessage(message, None, sender_id, parse_data)
            tracker = agent.log_message(usermsg)
            return jsonify(tracker.current_state(verbosity))

        except Exception as e:
            logger.exception("Caught an exception while logging message.")
            return error(500, "MessageException",
                         "Server failure. Error: {}".format(e))
Example #10
0
    def log_message(sender_id):
        request_params = request.get_json(force=True)
        message = request_params.get("text")
        sender = request_params.get("sender")
        parse_data = request_params.get("parse_data")

        # TODO: implement properly for agent / bot
        if sender != "user":
            return Response(jsonify(error="Currently, only user messages can "
                                    "be passed to this endpoint. "
                                    "Messages of sender '{}' can not be "
                                    "handled. ".format(sender)),
                            status=500,
                            content_type="application/json")

        try:

            usermsg = UserMessage(message, None, sender_id, parse_data)
            tracker_state = agent.log_message(usermsg)
            return jsonify(tracker_state)

        except Exception as e:
            logger.exception("Caught an exception while logging message.")
            return Response(jsonify(error="Server failure. Error: {}"
                                    "".format(e)),
                            status=500,
                            content_type="application/json")
Example #11
0
 def handle_message(sid, data):
     output_channel = SocketOutputChatBot(sio, self.bot_message_evt)
     message = UserMessage(data['message'],
                           output_channel,
                           sid,
                           input_channel=self.name())
     on_new_message(message)
Example #12
0
        def message():
            sender = request.values.get('From', None)
            text = request.values.get('Body', None)

            out_channel = TwilioOutput(self.account_sid, self.auth_token,
                                       self.twilio_number)

            if sender is not None and message is not None:
                try:
                    # @ signs get corrupted in SMSes by some carriers
                    text = text.replace('¡', '@')
                    on_new_message(
                        UserMessage(text,
                                    out_channel,
                                    sender,
                                    input_channel=self.name()))
                except Exception as e:
                    logger.error("Exception when trying to handle "
                                 "message.{0}".format(e))
                    logger.error(e, exc_info=True)
                    if self.debug_mode:
                        raise
                    pass
            else:
                logger.debug("Invalid message")

            return "success"
Example #13
0
def test_int_sender_id_in_user_message():
    from rasa_core.channels import UserMessage

    # noinspection PyTypeChecker
    message = UserMessage("A text", sender_id=1234567890)

    assert message.sender_id == "1234567890"
Example #14
0
    def start_message_handling(self,
                               text_message,
                               sender=None):
        # type: (Text, Optional[Text]) -> Dict[Text, Any]

        processor = self._create_processor()
        return processor.start_message_handling(
                UserMessage(text_message, None, sender))
Example #15
0
    def start_message_handling(self,
                               text_message,
                               sender_id=UserMessage.DEFAULT_SENDER_ID):
        # type: (Text, Optional[Text]) -> Dict[Text, Any]

        processor = self._create_processor()
        return processor.start_message_handling(
            UserMessage(text_message, None, sender_id))
Example #16
0
    def _record_messages(self, on_message, max_message_limit=None):
        logger.info("Bot loaded. Fake user will automatically respond!")
        num_messages = 0

        while max_message_limit is None or num_messages < max_message_limit:
            tracker = self.tracker_store.retrieve('nlu')
            text = self.customer.respond_to_action(tracker)
            on_message(UserMessage(text, ConsoleOutputChannel()))
            num_messages += 1
Example #17
0
 def handle_unfollow(self, event):
     logger.info("Line Unfollow from %s", event["source"]["userId"])
     user_msg = UserMessage(
         "/unfollow_event",
         None,
         event["source"]["userId"],
         input_channel=self.name()
     )
     self.on_new_message(user_msg)
Example #18
0
    def start_message_handling(self,
                               text_message,
                               sender_id=UserMessage.DEFAULT_SENDER_ID):
        # type: (Text, Optional[Text]) -> Dict[Text, Any]
        """Start to process a messages, returning the next action to take. """

        processor = self._create_processor()
        return processor.start_message_handling(
                UserMessage(text_message, None, sender_id))
Example #19
0
def test_message_id_logging(default_processor):
    from rasa_core.trackers import DialogueStateTracker

    message = UserMessage("If Meg was an egg would she still have a leg?")
    tracker = DialogueStateTracker('1', [])
    default_processor._handle_message_with_tracker(message, tracker)
    logged_event = tracker.events[-1]

    assert logged_event.message_id == message.message_id
    assert logged_event.message_id is not None
Example #20
0
        async def webhook(request):
            sender_id = self._extract_sender(request)
            text = self._extract_message(request)

            collector = CallbackOutput(self.callback_endpoint)
            await on_new_message(
                UserMessage(text,
                            collector,
                            sender_id,
                            input_channel=self.name()))
            return response.text("success")
Example #21
0
 def handle_follow(self, event):
     logger.info("Line Follow from %s", event["source"]["userId"])
     out_channel = LineOutput(self.line_api, event["replyToken"])
     user_msg = UserMessage(
         "/follow_event",
         out_channel,
         event["source"]["userId"],
         input_channel=self.name()
     )
     self.on_new_message(user_msg)
     out_channel.send_reply()
Example #22
0
 def handle_things_unlink(self, event):
     logger.info("Line Things Unlink from %s", event["source"]["userId"])
     out_channel = LineOutput(self.line_api, event["replyToken"])
     user_msg = UserMessage(
         "/things_unlink{\"things_deviceId\": \"%s\"}" % event["things"]["deviceId"],
         out_channel,
         event["source"]["userId"],
         input_channel=self.name()
     )
     self.on_new_message(user_msg)
     out_channel.send_reply()
Example #23
0
 def handle_postback(self, event):
     logger.info("Line Postback: %s from %s",
                 event["postback"]["data"], event["source"]["userId"])
     out_channel = LineOutput(self.line_api, event["replyToken"])
     user_msg = UserMessage(
         event["postback"]["data"],
         out_channel,
         event["source"]["userId"],
         input_channel=self.name()
     )
     self.on_new_message(user_msg)
     out_channel.send_reply()
Example #24
0
    def start_message_handling(
        self,
        text_message,  # type: Text
        sender_id=UserMessage.DEFAULT_SENDER_ID  # type: Optional[Text]
    ):
        # type: (...) -> Dict[Text, Any]
        """Start to process a messages, returning the next action to take. """

        # Creates a new processor for the agent and starts the
        # message handling
        processor = self._create_processor()
        return processor.start_message_handling(
            UserMessage(text_message, None, sender_id))
def run_fake_user(input_channel, max_training_samples=10, serve_forever=True):
    logger.info("Starting to train policy")
    agent = Agent(RASA_CORE_DOMAIN_PATH,
                  policies=[MemoizationPolicy(), KerasPolicy()],
                  interpreter=RegexInterpreter())

    agent.train_online(RASA_CORE_TRAINING_DATA_PATH,
                       input_channel=input_channel,
                       epochs=RASA_CORE_EPOCHS,
                       max_training_samples=max_training_samples)

    while serve_forever:
        agent.handle_message(UserMessage(back, ConsoleOutputChannel()))

    return agent
Example #26
0
def test_message_processor(default_domain, capsys):
    story_filename = "data/dsl_stories/stories_defaultdomain.md"
    ensemble = SimplePolicyEnsemble([ScoringPolicy()])
    interpreter = RegexInterpreter()

    PolicyTrainer(ensemble, default_domain,
                  BinaryFeaturizer()).train(story_filename, max_history=3)

    tracker_store = InMemoryTrackerStore(default_domain)
    processor = MessageProcessor(interpreter, ensemble, default_domain,
                                 tracker_store)

    processor.handle_message(UserMessage("_greet", ConsoleOutputChannel()))
    out, _ = capsys.readouterr()
    assert "hey there!" in out
Example #27
0
def test_message_processor(default_domain, capsys):
    story_filename = "data/dsl_stories/stories_defaultdomain.md"
    ensemble = SimplePolicyEnsemble([ScoringPolicy()])
    interpreter = RegexInterpreter()

    PolicyTrainer(ensemble, default_domain,
                  BinaryFeaturizer()).train(story_filename, max_history=3)

    tracker_store = InMemoryTrackerStore(default_domain)
    processor = MessageProcessor(interpreter, ensemble, default_domain,
                                 tracker_store)

    out = CollectingOutputChannel()
    processor.handle_message(UserMessage("_greet[name=Core]", out))
    assert ("default", "hey there Core!") == out.latest_output()
Example #28
0
def test_http_parsing():
    message = UserMessage('lunch?')
    httpretty.register_uri(httpretty.GET, 'https://interpreter.com/parse')

    endpoint = EndpointConfig('https://interpreter.com')
    httpretty.enable()
    inter = RasaNLUHttpInterpreter(endpoint=endpoint)
    try:
        MessageProcessor(inter, None, None, None, None)._parse_message(message)
    except KeyError:
        pass  # logger looks for intent and entities, so we except

    query = httpretty.last_request.querystring
    httpretty.disable()

    assert query['message_id'][0] == message.message_id
Example #29
0
    def log_message(self,
                    message: UserMessage) -> Optional[DialogueStateTracker]:

        # preprocess message if necessary
        if self.message_preprocessor is not None:
            message.text = self.message_preprocessor(message.text)
        # we have a Tracker instance for each user
        # which maintains conversation state
        tracker = self._get_tracker(message.sender_id)
        if tracker:
            self._handle_message_with_tracker(message, tracker)
            # save tracker state to continue conversation from this state
            self._save_tracker(tracker)
        else:
            logger.warning("Failed to retrieve or create tracker for sender "
                           "'{}'.".format(message.sender_id))
        return tracker
async def test_http_parsing():
    message = UserMessage('lunch?')

    endpoint = EndpointConfig('https://interpreter.com')
    with aioresponses() as mocked:
        mocked.post('https://interpreter.com/parse', repeat=True, status=200)

        inter = RasaNLUHttpInterpreter(endpoint=endpoint)
        try:
            await MessageProcessor(inter, None, None, None,
                                   None)._parse_message(message)
        except KeyError:
            pass  # logger looks for intent and entities, so we except

        r = latest_request(mocked, 'POST', "https://interpreter.com/parse")

        assert r
        assert json_of_latest_request(r)['message_id'] == message.message_id