예제 #1
0
    def continue_predicting(sender_id):
        """Continue a prediction started with parse.

        Caller should have executed the action returned from the parse
        endpoint. The events returned from that executed action are
        passed to continue which will trigger the next action prediction.

        If continue predicts action listen, the caller should wait for the
        next user message."""

        request_params = request.get_json(force=True)
        encoded_events = request_params.get("events", [])
        executed_action = request_params.get("executed_action", None)
        evts = events.deserialise_events(encoded_events)
        try:
            response = agent().continue_message_handling(sender_id,
                                                         executed_action,
                                                         evts)
        except ValueError as e:
            return Response(jsonify(error=e.message),
                            status=400,
                            content_type="application/json")
        except Exception as e:
            logger.exception(e)
            return Response(jsonify(error="Server failure. Error: {}"
                                          "".format(e)),
                            status=500,
                            content_type="application/json")
        return jsonify(response)
예제 #2
0
파일: server.py 프로젝트: zyt9749/rasa_core
    def continue_predicting(sender_id):
        """Continue a prediction started with parse.

        Caller should have executed the action returned from the parse
        endpoint. The events returned from that executed action are
        passed to continue which will trigger the next action prediction.

        If continue predicts action listen, the caller should wait for the
        next user message."""

        request_params = request.get_json(force=True)
        encoded_events = request_params.get("events", [])
        executed_action = request_params.get("executed_action", None)
        evts = events.deserialise_events(encoded_events)
        try:
            response = agent().continue_message_handling(
                sender_id, executed_action, evts)
        except ValueError as e:
            return Response(jsonify(error=e.message),
                            status=400,
                            content_type="application/json")
        except Exception as e:
            logger.exception(e)
            return Response(jsonify(error="Server failure. Error: {}"
                                    "".format(e)),
                            status=500,
                            content_type="application/json")
        return jsonify(response)
예제 #3
0
 def from_dict(cls, sender_id, dump_as_dict, domain):
     evts = events.deserialise_events(dump_as_dict, domain)
     tracker = cls(sender_id, domain.slots, domain.topics,
                   domain.default_topic)
     for e in evts:
         tracker.update(e)
     return tracker
예제 #4
0
    def continue_predicting(self, request, sender_id):
        """Continue a prediction started with parse.

        Caller should have executed the action returned from the parse
        endpoint. The events returned from that executed action are
        passed to continue which will trigger the next action prediction.

        If continue predicts action listen, the caller should wait for the
        next user message."""

        request.setHeader('Content-Type', 'application/json')
        request_params = json.loads(
                request.content.read().decode('utf-8', 'strict'))
        encoded_events = request_params.get("events", [])
        executed_action = request_params.get("executed_action", None)
        evts = events.deserialise_events(encoded_events)
        try:
            response = self.agent.continue_message_handling(sender_id,
                                                            executed_action,
                                                            evts)
        except ValueError as e:
            request.setResponseCode(400)
            return json.dumps({"error": e.message})
        except Exception as e:
            request.setResponseCode(500)
            logger.exception(e)
            return json.dumps({"error": "Server failure. Error: {}".format(e)})
        return json.dumps(response)
예제 #5
0
파일: action.py 프로젝트: punitcs81/chatbot
    def run(self, dispatcher, tracker, domain):
        json = self._action_call_format(tracker, domain)

        if not self.action_endpoint:
            raise Exception("The model predicted the custom action '{}' "
                            "but you didn't configure an endpoint to "
                            "run this custom action. Please take a look at "
                            "the docs and set an endpoint configuration. "
                            "{}/customactions/"
                            "".format(self.name(), DOCS_BASE_URL))

        try:
            logger.debug("Calling action endpoint to run action '{}'."
                         "".format(self.name()))
            response = self.action_endpoint.request(
                json=json, method="post", timeout=DEFAULT_REQUEST_TIMEOUT)

            if response.status_code == 400:
                response_data = response.json()
                exception = ActionExecutionRejection(
                    response_data["action_name"],
                    response_data.get("error")
                )
                logger.debug(exception.message)
                raise exception

            response.raise_for_status()
            response_data = response.json()
            self._validate_action_result(response_data)
        except requests.exceptions.ConnectionError as e:

            logger.error("Failed to run custom action '{}'. Couldn't connect "
                         "to the server at '{}'. Is the server running? "
                         "Error: {}".format(self.name(),
                                            self.action_endpoint.url,
                                            e))
            raise Exception("Failed to execute custom action.")
        except requests.exceptions.HTTPError as e:

            logger.error("Failed to run custom action '{}'. Action server "
                         "responded with a non 200 status code of {}. "
                         "Make sure your action server properly runs actions "
                         "and returns a 200 once the action is executed. "
                         "Error: {}".format(self.name(),
                                            e.response.status_code,
                                            e))
            raise Exception("Failed to execute custom action.")

        events_json = response_data.get("events", [])
        responses = response_data.get("responses", [])

        self._utter_responses(responses, dispatcher, tracker)

        evts = events.deserialise_events(events_json)

        return evts
예제 #6
0
    def append_events(sender_id):
        """Append a list of events to the state of a conversation"""

        request_params = request.get_json(force=True)
        evts = events.deserialise_events(request_params)
        tracker = agent().tracker_store.get_or_create_tracker(sender_id)
        for e in evts:
            tracker.update(e)
        agent().tracker_store.save(tracker)
        return jsonify(tracker.current_state())
예제 #7
0
파일: server.py 프로젝트: zyt9749/rasa_core
    def append_events(sender_id):
        """Append a list of events to the state of a conversation"""

        request_params = request.get_json(force=True)
        evts = events.deserialise_events(request_params)
        tracker = agent().tracker_store.get_or_create_tracker(sender_id)
        for e in evts:
            tracker.update(e)
        agent().tracker_store.save(tracker)
        return jsonify(tracker.current_state())
예제 #8
0
def _write_stories_to_file(export_story_path, evts):
    # type: (Text, List[Dict[Text, Any]]) -> None
    """Write the conversation of the sender_id to the file paths."""

    sub_conversations = _split_conversation_at_restarts(evts)

    with io.open(export_story_path, 'a', encoding="utf-8") as f:
        for conversation in sub_conversations:
            parsed_events = events.deserialise_events(conversation)
            s = Story.from_events(parsed_events)
            f.write(s.as_story_string(flat=True) + "\n")
예제 #9
0
    async def run(self, dispatcher, tracker, domain):
        json_body = self._action_call_format(tracker, domain)

        if not self.action_endpoint:
            raise Exception("The model predicted the custom action '{}' "
                            "but you didn't configure an endpoint to "
                            "run this custom action. Please take a look at "
                            "the docs and set an endpoint configuration. "
                            "{}/customactions/"
                            "".format(self.name(), DOCS_BASE_URL))

        try:
            logger.debug("Calling action endpoint to run action '{}'."
                         "".format(self.name()))
            response = await self.action_endpoint.request(
                json=json_body, method="post", timeout=DEFAULT_REQUEST_TIMEOUT)
            self._validate_action_result(response)

            events_json = response.get("events", [])
            responses = response.get("responses", [])
            await self._utter_responses(responses, dispatcher, tracker)

            evts = events.deserialise_events(events_json)
            return evts

        except ClientResponseError as e:
            if e.status == 400:
                response_data = json.loads(e.text)
                exception = ActionExecutionRejection(
                    response_data["action_name"], response_data.get("error"))
                logger.debug(exception.message)
                raise exception
            else:
                raise Exception("Failed to execute custom action.") from e

        except aiohttp.ClientConnectionError as e:
            logger.error("Failed to run custom action '{}'. Couldn't connect "
                         "to the server at '{}'. Is the server running? "
                         "Error: {}".format(self.name(),
                                            self.action_endpoint.url, e))
            raise Exception("Failed to execute custom action.")

        except aiohttp.ClientError as e:
            # not all errors have a status attribute, but
            # helpful to log if they got it

            # noinspection PyUnresolvedReferences
            status = getattr(e, 'status', None)
            logger.error("Failed to run custom action '{}'. Action server "
                         "responded with a non 200 status code of {}. "
                         "Make sure your action server properly runs actions "
                         "and returns a 200 once the action is executed. "
                         "Error: {}".format(self.name(), status, e))
            raise Exception("Failed to execute custom action.")
예제 #10
0
def test_remote_append_events(http_app, event):
    client = RasaCoreClient(EndpointConfig(http_app))

    cid = str(uuid.uuid1())

    client.append_event_to_tracker(cid, event)

    tracker = client.tracker_json(cid)

    evts = tracker.get("events")
    expected = [ActionExecuted(ACTION_LISTEN_NAME), event]
    assert events.deserialise_events(evts) == expected
예제 #11
0
    def append_events(self, request, sender_id):
        """Append a list of events to the state of a conversation"""

        request.setHeader('Content-Type', 'application/json')
        request_params = json.loads(
                request.content.read().decode('utf-8', 'strict'))
        evts = events.deserialise_events(request_params)
        tracker = self.agent.tracker_store.get_or_create_tracker(sender_id)
        for e in evts:
            tracker.update(e)
        self.agent.tracker_store.save(tracker)
        return json.dumps(tracker.current_state())
예제 #12
0
파일: test_server.py 프로젝트: mann2107/NLP
def test_remote_append_events(http_app):
    client = RasaCoreClient(EndpointConfig(http_app))

    cid = str(uuid.uuid1())

    client.append_events_to_tracker(cid, test_events[:2])

    tracker = client.tracker_json(cid)

    evts = tracker.get("events")
    expected = [ActionExecuted(ACTION_LISTEN_NAME)] + test_events[:2]
    assert events.deserialise_events(evts) == expected
예제 #13
0
    def from_dict(cls, sender_id, dump_as_dict, domain):
        # type: (Text, List[Dict[Text, Any]]) -> DialogueStateTracker
        """Create a tracker from dump.

        The dump should be an array of dumped events. When restoring
        the tracker, these events will be replayed to recreate the state."""

        evts = events.deserialise_events(dump_as_dict)
        tracker = cls(sender_id, domain.slots)
        for e in evts:
            tracker.update(e)
        return tracker
예제 #14
0
def run_action(input_action, sender_id):
    next_action = input_action
    if next_action['next_action'] == 'bot.action.name_to_photo':
        status = name_to_photo()
        next_action = agent.continue_message_handling(
            executed_action=next_action['next_action'],
            sender_id=sender_id,
            events=[])
        next_action = agent.start_message_handling(status)
        return next_action
    elif (next_action['next_action'] == 'action_slot_reset'):
        evts = events.deserialise_events([{"event": "reset_slots"}])
        next_action = agent.continue_message_handling(
            executed_action=next_action['next_action'],
            sender_id=sender_id,
            events=evts)
        return next_action
    elif (next_action['next_action'] == "bot.utter.herb_name"):
        herb_name = "มะนาว"
        evts = events.deserialise_events([{
            "event": "slot",
            "name": "herb",
            "value": herb_name
        }])
        next_action = agent.continue_message_handling(
            executed_action=next_action['next_action'],
            sender_id=sender_id,
            events=evts)
        return next_action

    else:
        next_action = agent.continue_message_handling(
            executed_action=next_action['next_action'],
            sender_id=sender_id,
            events=[])
        next_action = agent.continue_message_handling(
            executed_action="bot.ask.name_to_benefit.herb_name",
            sender_id=sender_id,
            events=[])
        return next_action
예제 #15
0
    def from_dict(
            cls,
            sender_id: Text,
            events_as_dict: List[Dict[Text, Any]],
            slots: List[Slot],
            max_event_history: Optional[int] = None) -> 'DialogueStateTracker':
        """Create a tracker from dump.

        The dump should be an array of dumped events. When restoring
        the tracker, these events will be replayed to recreate the state."""

        evts = events.deserialise_events(events_as_dict)
        return cls.from_events(sender_id, evts, slots, max_event_history)
예제 #16
0
def test_put_tracker(app):
    data = json.dumps([event.as_dict() for event in test_events])
    response = app.put("http://dummy/conversations/pushtracker/tracker/events",
                       data=data, content_type='application/json')
    content = response.get_json()
    assert response.status_code == 200
    assert len(content["events"]) == len(test_events)
    assert content["sender_id"] == "pushtracker"

    tracker_response = app.get("http://dummy/conversations/pushtracker/tracker")
    tracker = tracker_response.get_json()
    assert tracker is not None
    evts = tracker.get("events")
    assert events.deserialise_events(evts) == test_events
예제 #17
0
def _write_stories_to_file(export_file_path, sender_id, endpoint):
    # type: (Text, Text, EndpointConfig) -> None
    """Write the conversation of the sender_id to the file path."""

    tracker = retrieve_tracker(endpoint, sender_id)
    evts = tracker.get("events", [])

    sub_conversations = _split_conversation_at_restarts(evts)

    with io.open(export_file_path, 'a') as f:
        for conversation in sub_conversations:
            parsed_events = events.deserialise_events(conversation)
            s = Story.from_events(parsed_events)
            f.write(s.as_story_string(flat=True) + "\n")
예제 #18
0
def test_put_tracker(app):
    data = json.dumps([event.as_dict() for event in test_events])
    response = app.put("http://dummy/conversations/pushtracker/tracker",
                       data=data, content_type='application/json')
    content = response.get_json()
    assert response.status_code == 200
    assert len(content["events"]) == len(test_events)
    assert content["sender_id"] == "pushtracker"

    tracker_response = app.get("http://dummy/conversations/pushtracker/tracker")
    tracker = tracker_response.get_json()
    assert tracker is not None
    evts = tracker.get("events")
    assert events.deserialise_events(evts) == test_events
예제 #19
0
    def run(self, dispatcher, tracker, domain):
        try:
            method = self.executor.actions[self.name()]
            response_data = method(dispatcher, tracker, domain)
            # self._validate_action_result(response_data)
        except Exception as e:
            raise Exception("Failed to execute custom action.")

        # events_json = response_data.get("events", [])
        events_json = []
        responses = []
        # responses = response_data.get("responses", [])

        self._utter_responses(responses, dispatcher, tracker)
        evts = events.deserialise_events(events_json)
        return evts
예제 #20
0
def _fetch_events(sender_ids: List[Union[Text, List[Event]]],
                  endpoint: EndpointConfig) -> List[List[Event]]:
    """Retrieve all event trackers from the endpoint for all sender ids."""

    event_sequences = []
    for sender_id in sender_ids:
        if isinstance(sender_id, str):
            tracker = retrieve_tracker(endpoint, sender_id)
            evts = tracker.get("events", [])

            for conversation in _split_conversation_at_restarts(evts):
                parsed_events = events.deserialise_events(conversation)
                event_sequences.append(parsed_events)
        else:
            event_sequences.append(sender_id)
    return event_sequences
예제 #21
0
def test_put_tracker(app):
    data = json.dumps([event.as_dict() for event in test_events])
    _, response = app.put(
        "/conversations/pushtracker/tracker/events",
        data=data, headers={"Content-Type": "application/json"})
    content = response.json
    assert response.status == 200
    assert len(content["events"]) == len(test_events)
    assert content["sender_id"] == "pushtracker"

    _, tracker_response = app.get(
        "/conversations/pushtracker/tracker")
    tracker = tracker_response.json
    assert tracker is not None
    evts = tracker.get("events")
    assert events.deserialise_events(evts) == test_events
예제 #22
0
def _export_stories(tracker):
    # export current stories and quit
    file_prompt = ("File to export to (if file exists, this "
                   "will append the stories) "
                   "[{}]: ").format(DEFAULT_FILE_EXPORT_PATH)
    export_file_path = utils.request_input(prompt=file_prompt)

    if not export_file_path:
        export_file_path = DEFAULT_FILE_EXPORT_PATH

    parsed_events = events.deserialise_events(tracker.get("events", []))

    s = Story.from_events(parsed_events)

    with io.open(export_file_path, 'a') as f:
        f.write(s.as_story_string(flat=True) + "\n")
예제 #23
0
    def run(self, dispatcher, tracker, domain):
        json = self._action_call_format(tracker, domain)

        if not self.action_endpoint:
            raise Exception("The model predicted the custom action '{}' "
                            "but you didn't configure an endpoint to "
                            "run this custom action. Please take a look at "
                            "the docs and set an endpoint configuration. "
                            "{}/customactions/"
                            "".format(self.name(), DOCS_BASE_URL))

        try:
            logger.debug("Calling action endpoint to run action '{}'."
                         "".format(self.name()))
            response = self.action_endpoint.request(
                    json=json, method="post", timeout=DEFAULT_REQUEST_TIMEOUT)
            response.raise_for_status()
            response_data = response.json()

            self._validate_action_result(response_data)
        except requests.exceptions.ConnectionError as e:

            logger.error("Failed to run custom action '{}'. Couldn't connect "
                         "to the server at '{}'. Is the server running? "
                         "Error: {}".format(self.name(),
                                            self.action_endpoint.url,
                                            e))
            raise Exception("Failed to execute custom action.")
        except requests.exceptions.HTTPError as e:

            logger.error("Failed to run custom action '{}'. Action server "
                         "responded with a non 200 status code of {}. "
                         "Make sure your action server properly runs actions "
                         "and returns a 200 once the action is executed. "
                         "Error: {}".format(self.name(),
                                            e.response.status_code,
                                            e))
            raise Exception("Failed to execute custom action.")

        events_json = response_data.get("events", [])
        responses = response_data.get("responses", [])

        self._utter_responses(responses, dispatcher, tracker)

        evts = events.deserialise_events(events_json)

        return evts
예제 #24
0
    def from_dict(cls,
                  sender_id,  # type: Text
                  events_as_dict,  # type: List[Dict[Text, Any]]
                  slots,  # type: List[Slot]
                  max_event_history=None  # type: Optional[int]
                  ):
        # type: (...) -> DialogueStateTracker
        """Create a tracker from dump.

        The dump should be an array of dumped events. When restoring
        the tracker, these events will be replayed to recreate the state."""

        evts = events.deserialise_events(events_as_dict)
        tracker = cls(sender_id, slots, max_event_history)
        for e in evts:
            tracker.update(e)
        return tracker
예제 #25
0
    def from_dict(cls,
                  sender_id,  # type: Text
                  events_as_dict,  # type: List[Dict[Text, Any]]
                  slots,  # type: List[Slot]
                  max_event_history=None  # type: Optional[int]
                  ):
        # type: (...) -> DialogueStateTracker
        """Create a tracker from dump.

        The dump should be an array of dumped events. When restoring
        the tracker, these events will be replayed to recreate the state."""

        evts = events.deserialise_events(events_as_dict)
        tracker = cls(sender_id, slots, max_event_history)
        for e in evts:
            tracker.update(e)
        return tracker
예제 #26
0
    def on_post(self, req, resp):
        encoded_events = req.media.get('events', [])
        executed_action = req.media.get("executed_action", None)
        print('executed action')
        print(executed_action)
        evts = events.deserialise_events(encoded_events, self.agent.domain)
        sender_id = req.media['sender_id']
        try:
            result = self.agent.continue_message_handling(
                sender_id, executed_action, evts)
            status_code = '200 OK'
        except ValueError as e:
            status_code = '400 Bad Request'
            result = {"error": e.message}
        except Exception as e:
            status_code = '500 Internal Server Error'
            result = {"error": "Server failure. Error: {}".format(e)}

        resp.status = status_code
        resp.media = result
        resp.context_type = falcon.MEDIA_JSON