Example #1
0
        async def receive():
            text = get_text()  #grab message from user
            with open('users.json') as f:
                userdata = json.load(f)
            sender_id = userdata['user']['papaya']
            output = CollectingOutputChannel(
            )  #sets the output channel to just collect the messages from Core
            on_new_message(
                UserMessage(text, output, sender_id)
            )  #this will tell Rasa Core to handle this user message
            responses = [
                m["text"] for m in out.messages
            ]  #out.messages = list of dictionaries with id & response message
            #grab response for bot:
            message = ' '.join(
                responses
            )  #if dispatcher sends multiple messages these are all put in 'message'
            r = {
                "Username": sender_id,
                "Convo": {
                    "UserInput": text,
                    "BotOutput": message
                }
            }

            return response.json(r)
Example #2
0
        async def receive(request: Request):
            print("Inside receive")
            sender_id = await self._extract_sender(request)
            text = self._extract_message(request)
            print("sender_id is ::-", sender_id)
            print("text is ::-", text)
            should_use_stream = rasa.utils.endpoints.bool_arg(request,
                                                              "stream",
                                                              default=False)

            if should_use_stream:
                return response.stream(
                    self.stream_response(on_new_message, text, sender_id),
                    content_type="text/event-stream",
                )
            else:
                collector = CollectingOutputChannel()
                on_new_message(UserMessage(text, collector, sender_id))
                print("collector MSG::", collector)
                # noinspection PyBroadException
                try:
                    await on_new_message(
                        UserMessage(text,
                                    collector,
                                    sender_id,
                                    input_channel=self.name()))
                except CancelledError:
                    logger.error("Message handling timed out for "
                                 "user message '{}'.".format(text))
                except Exception:
                    logger.exception("An exception occured while handling "
                                     "user message '{}'.".format(text))
                return response.json(collector.messages)
Example #3
0
        async def receive(request: Request) -> HTTPResponse:
            sender_id = await self._extract_sender(request)
            text = self._extract_message(request)
            should_use_stream = rasa.utils.endpoints.bool_arg(request,
                                                              "stream",
                                                              default=False)
            input_channel = self._extract_input_channel(request)
            metadata = self.get_metadata(request)

            if should_use_stream:
                return response.stream(
                    self.stream_response(on_new_message, text, sender_id,
                                         input_channel, metadata),
                    content_type="text/event-stream",
                )
            else:
                collector = CollectingOutputChannel()
                # noinspection PyBroadException
                try:
                    await on_new_message(
                        UserMessage(
                            text,
                            collector,
                            sender_id,
                            input_channel=input_channel,
                            metadata=metadata,
                        ))
                except CancelledError:
                    logger.error(f"Message handling timed out for "
                                 f"user message '{text}'.")
                except Exception:
                    logger.exception(f"An exception occured while handling "
                                     f"user message '{text}'.")
                return response.json(collector.messages)
Example #4
0
 def receive():
     payload = json.loads(request.data)
     sender_id = payload['user']['userId']
     intent = payload['inputs'][0]['intent']
     text = payload['inputs'][0]['rawInputs'][0]['query']
     if intent == 'actions.intent.MAIN':
         message = "<speak>Hello! <break time=\"1\"/> Welcome to the Rasa-powered Google Assistant skill. You can start by saying hi."
     else:
         out = CollectingOutputChannel()
         on_new_message(UserMessage(text, out, sender_id))
         responses = [m["text"] for m in out.messages]
         message = responses[0]
     r = json.dumps({
         "conversationToken":
         "{\"state\":null,\"data\":{}}",
         "expectUserResponse":
         'true',
         "expectedInputs": [{
             "inputPrompt": {
                 "initialPrompts": [{
                     "ssml": message
                 }]
             },
             "possibleIntents": [{
                 "intent": "actions.intent.TEXT"
             }]
         }]
     })
     return r
Example #5
0
    async def execute_action(request: Request, conversation_id: Text):
        request_params = request.json

        action_to_execute = request_params.get("name", None)

        if not action_to_execute:
            raise ErrorResponse(
                400,
                "BadRequest",
                "Name of the action not provided in request body.",
                {"parameter": "name", "in": "body"},
            )

        policy = request_params.get("policy", None)
        confidence = request_params.get("confidence", None)

        verbosity = event_verbosity_parameter(request, EventVerbosity.AFTER_RESTART)

        try:
            out = CollectingOutputChannel()
            await app.agent.execute_action(
                conversation_id, action_to_execute, out, policy, confidence
            )
        except Exception as e:
            logger.debug(traceback.format_exc())
            raise ErrorResponse(
                500,
                "ConversationError",
                "An unexpected error occurred. Error: {}".format(e),
            )

        tracker = obtain_tracker_store(app.agent, conversation_id)
        state = tracker.current_state(verbosity)
        return response.json({"tracker": state, "messages": out.messages})
Example #6
0
def _get_output_channel(
        request: Request,
        tracker: Optional[DialogueStateTracker]) -> OutputChannel:
    """Returns the `OutputChannel` which should be used for the bot's responses.

    Args:
        request: HTTP request whose query parameters can specify which `OutputChannel`
                 should be used.
        tracker: Tracker for the conversation. Used to get the latest input channel.

    Returns:
        `OutputChannel` which should be used to return the bot's responses to.
    """
    requested_output_channel = request.args.get(OUTPUT_CHANNEL_QUERY_KEY)

    if (requested_output_channel == USE_LATEST_INPUT_CHANNEL_AS_OUTPUT_CHANNEL
            and tracker):
        requested_output_channel = tracker.get_latest_input_channel()

    # Interactive training does not set `input_channels`, hence we have to be cautious
    registered_input_channels = getattr(request.app, "input_channels",
                                        None) or []
    matching_channels = [
        channel for channel in registered_input_channels
        if channel.name() == requested_output_channel
    ]

    # Check if matching channels can provide a valid output channel,
    # otherwise use `CollectingOutputChannel`
    return reduce(
        lambda output_channel_created_so_far, input_channel:
        (input_channel.get_output_channel() or output_channel_created_so_far),
        matching_channels,
        CollectingOutputChannel(),
    )
Example #7
0
        async def receive(request):
            # get the json request sent by Alexa
            payload = request.json
            # check to see if the user is trying to launch the skill
            intenttype = payload["request"]["type"]

            # if the user is starting the skill, let them know it worked & what to do next
            if intenttype == "LaunchRequest":
                message = "Hello! Welcome to this Rasa-powered Alexa skill. You can start by saying 'hi'."
                session = "false"
            else:
                # get the Alexa-detected intent
                intent = payload["request"]["intent"]["name"]

                # makes sure the user isn't trying to end the skill
                if intent == "AMAZON.StopIntent":
                    session = "true"
                    message = "Talk to you later"
                else:
                    # get the user-provided text from the slot named "text"
                    text = payload["request"]["intent"]["slots"]["text"][
                        "value"]

                    # initialize output channel
                    out = CollectingOutputChannel()

                    # send the user message to Rasa & wait for the
                    # response to be sent back
                    await on_new_message(UserMessage(text, out))
                    # extract the text from Rasa's response
                    responses = [m["text"] for m in out.messages]
                    message = responses[0]
                    session = "false"
            # Send the response generated by Rasa back to Alexa to
            # pass on to the user. For more information, refer to the
            # Alexa Skills Kit Request and Response JSON Reference:
            # https://developer.amazon.com/en-US/docs/alexa/custom-skills/request-and-response-json-reference.html
            r = {
                "version": "1.0",
                "sessionAttributes": {
                    "status": "test"
                },
                "response": {
                    "outputSpeech": {
                        "type": "PlainText",
                        "text": message,
                        "playBehavior": "REPLACE_ENQUEUED",
                    },
                    "reprompt": {
                        "outputSpeech": {
                            "type": "PlainText",
                            "text": message,
                            "playBehavior": "REPLACE_ENQUEUED",
                        }
                    },
                    "shouldEndSession": session,
                },
            }

            return response.json(r)
        async def action(request):
            print("/action called - form: " + str(request.form))
            result = request.form.get("SpeechResult")
            call_sid = request.form.get("CallSid", None)

            print("Result: " + str(result))

            if result:
                out = CollectingOutputChannel()

                # sends message to Rasa, wait for the response
                await on_new_message(
                    UserMessage(
                        result, out, call_sid, input_channel="twilio_voice"
                    )
                )

                # extract the text from Rasa's response
                last_response = py_.nth(out.messages, -1)

                # Some times on restarts, the server is in a weird state and their may be no session for an action
                if last_response:
                    print("last message: " + last_response["text"])
                    return self.prompt(last_response["text"])
                else:
                    return self.prompt('How can I help you today?')
            else:
                # If we did not get a user response, just reprompt
                return self.prompt("sorry, I did not get that - please repeat")
Example #9
0
async def test_update_tracker_session_with_metadata(
    default_processor: MessageProcessor, monkeypatch: MonkeyPatch,
):
    sender_id = uuid.uuid4().hex
    metadata = {"metadataTestKey": "metadataTestValue"}
    message = UserMessage(
        text="hi",
        output_channel=CollectingOutputChannel(),
        sender_id=sender_id,
        metadata=metadata,
    )
    await default_processor.handle_message(message)

    tracker = default_processor.tracker_store.retrieve(sender_id)
    events = list(tracker.events)

    assert events[0] == SlotSet(SESSION_START_METADATA_SLOT, metadata)
    assert tracker.slots[SESSION_START_METADATA_SLOT].value == metadata

    assert events[1] == ActionExecuted(ACTION_SESSION_START_NAME)
    assert events[2] == SessionStarted()
    assert events[2].metadata == metadata
    assert events[3] == SlotSet(SESSION_START_METADATA_SLOT, metadata)
    assert events[4] == ActionExecuted(ACTION_LISTEN_NAME)
    assert isinstance(events[5], UserUttered)
Example #10
0
        async def receive(request):
            payload = request.json
            intent = payload['inputs'][0]['intent']
            text = payload['inputs'][0]['rawInputs'][0]['query']

            if intent == 'actions.intent.MAIN':
                message = 'Hello, I\'m Charlotte. Your digital assistant!'
            else:
                out = CollectingOutputChannel()
                await on_new_message(UserMessage(text, out))
                responses = [reply['text'] for reply in out.messages]
                message = responses[0]
            response = {
                "expectUserResponse":
                'true',
                "expectedInputs": [{
                    "possibleIntents": [{
                        "intent": "actions.intent.TEXT"
                    }],
                    "inputPrompt": {
                        "richInitialPrompt": {
                            "items": [{
                                "simpleResponse": {
                                    "textToSpeech": message,
                                    "displayText": message
                                }
                            }]
                        }
                    }
                }]
            }

            return json(response)
Example #11
0
async def test_custom_action_session_start_with_metadata(
    default_processor: MessageProcessor,
):
    domain = Domain.from_dict({KEY_ACTIONS: [ACTION_SESSION_START_NAME]})
    default_processor.domain = domain
    action_server_url = "http://some-url"
    default_processor.action_endpoint = EndpointConfig(action_server_url)

    sender_id = uuid.uuid4().hex
    metadata = {"metadataTestKey": "metadataTestValue"}
    message = UserMessage(
        text="hi",
        output_channel=CollectingOutputChannel(),
        sender_id=sender_id,
        metadata=metadata,
    )

    with aioresponses() as mocked:
        mocked.post(action_server_url, payload={"events": []})
        await default_processor.handle_message(message)

    last_request = tests.utilities.latest_request(mocked, "post", action_server_url)
    tracker_for_custom_action = tests.utilities.json_of_latest_request(last_request)[
        "tracker"
    ]

    assert tracker_for_custom_action["events"] == [
        {
            "event": "slot",
            "timestamp": 1580515200.0,
            "name": SESSION_START_METADATA_SLOT,
            "value": metadata,
        }
    ]
Example #12
0
        async def receive(request):
            payload = request.json
            intent = payload['inputs'][0]['intent']
            text = payload['inputs'][0]['rawInputs'][0]['query']

            if intent == 'actions.intent.MAIN':
                message = "Hello! Welcome to the Rasa-powered Google Assistant skill. You can start by saying hi."
            else:
                out = CollectingOutputChannel()
                await on_new_message(UserMessage(text, out))
                print(out)
                print(out.messages)
                responses = [m["text"] for m in out.messages]
                message = responses[0]
            r = {
                "expectUserResponse":
                'true',
                "expectedInputs": [{
                    "possibleIntents": [{
                        "intent": "actions.intent.TEXT"
                    }],
                    "inputPrompt": {
                        "richInitialPrompt": {
                            "items": [{
                                "simpleResponse": {
                                    "textToSpeech": message,
                                    "displayText": message
                                }
                            }]
                        }
                    }
                }]
            }
            return response.json(r)
Example #13
0
async def test_action_unlikely_intent_metadata(
        default_processor: MessageProcessor):
    tracker = DialogueStateTracker.from_events(
        "some-sender",
        evts=[
            ActionExecuted(ACTION_LISTEN_NAME),
        ],
    )
    domain = Domain.empty()
    metadata = {"key1": 1, "key2": "2"}

    await default_processor._run_action(
        ActionUnlikelyIntent(),
        tracker,
        CollectingOutputChannel(),
        TemplatedNaturalLanguageGenerator(domain.responses),
        PolicyPrediction([], "some policy", action_metadata=metadata),
    )

    applied_events = tracker.applied_events()
    assert applied_events == [
        ActionExecuted(ACTION_LISTEN_NAME),
        ActionExecuted(ACTION_UNLIKELY_INTENT_NAME, metadata=metadata),
    ]
    assert applied_events[1].metadata == metadata
        async def auth_token(request: Request):
            if not request.json:
                return response.json({"error":"Missing sender"}, 400)
            # sender_id = await self._extract_sender(request)

            sender_id = request.json.get("sender_id") # method to get sender_id 
            text = request.json.get("text") # method to fetch text
            headers = request.headers
            try:
                auth_key = headers['authorization']
                if auth_key != "thisismysecret":
                    return response.json({"status":"not_authorized","message":"Sorry. You are not an authorized user"})
            except:
                return response.json({"status":"not_authorized","message":"Sorry. You are not an authorized user"})
            input_channel = self.name()
            collector = CollectingOutputChannel()
            await on_new_message(
                UserMessage(
                    text,
                    collector,
                    sender_id,
                    input_channel=input_channel,
                )
            )            
            # return response.json({"bot_token":decoded_token}, 200)
            return response.json({"reply":collector.messages}, 200)
Example #15
0
async def test_restart_triggers_session_start(
    default_channel: CollectingOutputChannel,
    default_processor: MessageProcessor,
    monkeypatch: MonkeyPatch,
):
    # The rule policy is trained and used so as to allow the default action ActionRestart to be predicted
    rule_policy = RulePolicy()
    rule_policy.train([], default_processor.domain, RegexInterpreter())
    monkeypatch.setattr(
        default_processor.policy_ensemble,
        "policies",
        [rule_policy, *default_processor.policy_ensemble.policies],
    )

    sender_id = uuid.uuid4().hex

    entity = "name"
    slot_1 = {entity: "name1"}
    await default_processor.handle_message(
        UserMessage(f"/greet{json.dumps(slot_1)}", default_channel, sender_id)
    )

    assert default_channel.latest_output() == {
        "recipient_id": sender_id,
        "text": "hey there name1!",
    }

    # This restarts the chat
    await default_processor.handle_message(
        UserMessage("/restart", default_channel, sender_id)
    )

    tracker = default_processor.tracker_store.get_or_create_tracker(sender_id)

    expected = [
        ActionExecuted(ACTION_SESSION_START_NAME),
        SessionStarted(),
        ActionExecuted(ACTION_LISTEN_NAME),
        UserUttered(
            f"/greet{json.dumps(slot_1)}",
            {INTENT_NAME_KEY: "greet", "confidence": 1.0},
            [{"entity": entity, "start": 6, "end": 23, "value": "name1"}],
        ),
        SlotSet(entity, slot_1[entity]),
        DefinePrevUserUtteredFeaturization(use_text_for_featurization=False),
        ActionExecuted("utter_greet"),
        BotUttered("hey there name1!", metadata={"template_name": "utter_greet"}),
        ActionExecuted(ACTION_LISTEN_NAME),
        UserUttered("/restart", {INTENT_NAME_KEY: "restart", "confidence": 1.0}),
        DefinePrevUserUtteredFeaturization(use_text_for_featurization=False),
        ActionExecuted(ACTION_RESTART_NAME),
        Restarted(),
        ActionExecuted(ACTION_SESSION_START_NAME),
        SessionStarted(),
        # No previous slot is set due to restart.
        ActionExecuted(ACTION_LISTEN_NAME),
    ]
    for actual, expected in zip(tracker.events, expected):
        assert actual == expected
Example #16
0
        async def receive(request: Request) -> HTTPResponse:
            """
            Transform Zipwhip request into Rasa expected format

            :param request: Zipwhip message receive request
            {
                "body": "Hello from mobile device",
                "bodySize": 24,
                "address": "ptn:/+12063996756",
                "finalSource": "+12063996756",
                "finalDestination": "+12068163958",
                "fingerprint": "1514465037",
                "id": 1195453017123205120,
                "contactId": 14543967707,
                "deviceId": 377265507,
                "messageType": "MO",
                "cc": null,
                "bcc": null,
                "visible": true,
                "read": false,
                "scheduledDate": null,
                "dateDeleted": null,
                "messageTransport": 5,
                "dateDelivered": null,
                "hasAttachment": false,
                "dateCreated": "2019-11-15T21:26:24+00:00",
                "deleted": false,
                "dateRead": null,
                "statusCode": 4
            }
            :return: HTTP response to return to Zipwhip
            """
            sender_id = await self._extract_sender(request)
            text = self._extract_message(request)
            print(text)

            input_channel = self._extract_input_channel(request)
            metadata = self.get_metadata(request)

            collector = CollectingOutputChannel()
            # noinspection PyBroadException
            try:
                await on_new_message(
                    UserMessage(
                        text,
                        collector,
                        sender_id,
                        input_channel=input_channel,
                        metadata=metadata,
                    ))
            except CancelledError:
                logger.error("Message handling timed out for "
                             "user message '{}'.".format(text))
            except Exception:
                logger.exception("An exception occured while handling "
                                 "user message '{}'.".format(text))

            self.send_all(sender_id, collector.messages)
            return response.json("Success.")
Example #17
0
async def test_message_processor(default_channel: CollectingOutputChannel,
                                 default_processor: MessageProcessor):
    await default_processor.handle_message(
        UserMessage('/greet{"name":"Core"}', default_channel))
    assert default_channel.latest_output() == {
        "recipient_id": "default",
        "text": "hey there Core!",
    }
Example #18
0
        async def receive(request: Request):
            sender_id = await self._extract_sender(request)
            sender_id = sender_id['userId']
            intent = self._extract_message(request)[0]['intent']
            text = self._extract_message(request)[0]['rawInputs'][0]['query']
            should_use_stream = rasa.utils.endpoints.bool_arg(request,
                                                              "stream",
                                                              default=False)

            if should_use_stream:
                return response.stream(
                    self.stream_response(on_new_message, text, sender_id),
                    content_type="text/event-stream",
                )
            else:
                if intent == 'actions.intent.MAIN':
                    message = "<speak>Welcome back <break time=\"1\"/> This is the Oticon-powered Google Assistant skill. You can talk to the OPN chatbot.</speak>"
#                    message = "Hello!"
                else:
                    collector = CollectingOutputChannel()
                    # noinspection PyBroadException
                    try:
                        await on_new_message(
                            UserMessage(text,
                                        collector,
                                        sender_id,
                                        input_channel=self.name()))
                        responses = [m["text"] for m in collector.messages]
                        message = responses[0]

                    except CancelledError:
                        logger.error("Message handling timed out for "
                                     "user message '{}'.".format(text))
                        message = "sorry..."
                    except Exception:
                        logger.exception("An exception occured while handling "
                                         "user message '{}'.".format(text))
                        message = "sorry..."

                r = response.json({
                    "conversationToken":
                    "{\"state\":null,\"data\":{}}",
                    "expectUserResponse":
                    'true',
                    "expectedInputs": [{
                        "inputPrompt": {
                            "initialPrompts": [{
                                "ssml": message
                            }]
                        },
                        "possibleIntents": [{
                            "intent": "actions.intent.TEXT"
                        }]
                    }]
                })
                return r
        async def message(request):
            print(request.form)  # The payload is form-encoded body
            call_sid = request.form.get("CallSid", None)
            out = CollectingOutputChannel()
            await on_new_message(
                UserMessage(
                    "Hello there", out, call_sid, input_channel="twilio_voice"
                )
            )

            return self.prompt(out.messages[0]["text"])
        async def receive(request: Request) -> HTTPResponse:
            #todo
            # 1 参数转换 done
            # 2 请求转发 done
            # 注: 前端加上senderId

            log.debug(json.dumps(request.json))

            sender_id = await self._extract_sender(request)
            text = self._extract_message(request)

            should_use_stream = rasa.utils.endpoints.bool_arg(request,
                                                              "stream",
                                                              default=False)
            input_channel = self._extract_input_channel(request)
            metadata = self.get_metadata(request)

            answer_id = self._extract_answer_id(request)
            problem_id = self._extract_answer_id(request)
            if answer_id is not None or problem_id is not None:
                log.debug('query by id')
                json_result = query_by_id(request.json)
                log.debug(json.dumps(json_result))
                return response.json(json_result)

            # rasa 处理
            log.debug('query by rasa')
            if should_use_stream:
                return response.stream(
                    self.stream_response(on_new_message, text, sender_id,
                                         input_channel, metadata),
                    content_type="text/event-stream",
                )
            else:
                collector = CollectingOutputChannel()
                # noinspection PyBroadException
                try:
                    await on_new_message(
                        UserMessage(
                            text,
                            collector,
                            sender_id,
                            input_channel=input_channel,
                            metadata=metadata,
                        ))
                except CancelledError:
                    log.error("Message handling timed out for "
                              "user message '{}'.".format(text))
                except Exception:
                    log.exception("An exception occured while handling "
                                  "user message '{}'.".format(text))
                return response.json(collector.messages)
Example #21
0
        async def receive(request: Request) -> HTTPResponse:
            sender_id = await self._extract_sender(request)
            text = self._extract_message(request)
            should_use_stream = rasa.utils.endpoints.bool_arg(
                request, "stream", default=False
            )
            input_channel = self._extract_input_channel(request)
            metadata = self.get_metadata(request)

            if should_use_stream:
                return response.stream(
                    self.stream_response(
                        on_new_message, text, sender_id, input_channel, metadata
                    ),
                    content_type="text/event-stream",
                )
            else:
                collector = CollectingOutputChannel()
                # noinspection PyBroadException
                try:

                    # Synthesize bot voice with desired pretrained NVIDIA Tacotron2 spanish fine-tuned voice model
                    botutterance = text
                    logger.debug(f"BotUttered message '{botutterance}'.")
                    voice, sr = synthesize(botutterance, self.speaker, self.sigma, self.denoiser)

                    #Stream bot voice through HTTP server

                    audio_file = "0_{}_synthesis.wav".format(sender_id)
                    audio_path = os.path.join(
                        "./rasadjango/dadbot/audios/", audio_file)
                    write(audio_path, sr, voice)
                    #url = "http://192.168.1.103:8000/audios/{}_".format(i) + "{}".format(sender_id)
                    #url = "http://dadbot-web:8000/audios/{}_".format(i) + "{}".format(sender_id)
                    url = "https://27875340f6fc.eu.ngrok.io/audios/0_{}".format(sender_id)
                    with open(audio_path, 'rb') as f:
                        files = {"files": (audio_path, f, 'application/octet-stream')}
                        requests.post(url, files = files)
                        f.close()

                except CancelledError:
                    logger.error(
                        f"Message handling timed out for " f"user message '{text}'."
                    )
                except Exception:
                    logger.exception(
                        f"An exception occured while handling "
                        f"user message '{text}'."
                    )

                #return response.json(collector.messages)
                return response.json([{"text": botutterance}])
Example #22
0
        async def receive(request: Request) -> HTTPResponse:
            sender_id = await self._extract_sender(request)
            text = self._extract_message(request)
            should_use_stream = rasa.utils.endpoints.bool_arg(
                request, "stream", default=False
            )
            #----------------------------------------------------
            # Manipula Metadata para Json de Saída
            input_channel = self._extract_input_channel(request)
            metadata = self._extract_metadata(request)
            metadata = "{\"metadata\": \"" + str(metadata) + "\"}"
            metadata = json.loads(metadata)
            #-----------------------------------------------------

            if should_use_stream:
                return response.stream(
                    self.stream_response(
                        on_new_message, text, sender_id, input_channel, metadata
                    ),
                    content_type="text/event-stream",
                )
            else:
                collector = CollectingOutputChannel()
                # noinspection PyBroadException
                try:
                    await on_new_message(
                        UserMessage(
                            text,
                            collector,
                            sender_id,
                            input_channel=input_channel,
                            #--------------------------------------------------------------
                            metadata=metadata, # Acrescenta campo metadata no json de saída
                            #--------------------------------------------------------------
                        )
                    )
                except CancelledError:
                    logger.error(
                        "Message handling timed out for "
                        "user message '{}'.".format(text)
                    )
                except Exception:
                    logger.exception(
                        "An exception occured while handling "
                        "user message '{}'.".format(text)
                    )
                return response.json(collector.messages)
Example #23
0
 async def receive(request):
     payload = request.json	
     intenttype = payload['request']['type']
     if intenttype == 'LaunchRequest':	
         message = "Hello! Welcome to the Rasa-powered Alexa skill. You can start by saying hi."
         session = 'false'
     elif intenttype == 'SessionEndedRequest':
         message = "Talk to you later."
         session = 'true'			 
     else:                
         intent = payload['request']['intent']['name']
         print(intent)
         if intent == 'AMAZON.StopIntent':
             session = 'true'
             message = 'Talk to you later'
         else:
             text = payload['request']['intent']['slots']['text']['value']
             print(text)
             out = CollectingOutputChannel()			
             await on_new_message(UserMessage(text, out))
             responses = [m["text"] for m in out.messages]
             message = responses[0]                  
             session = 'false'
     r = {
         "version": "0.1",
         "sessionAttributes": {
             "status": "test"
         },
         "response": {
             "outputSpeech": {
                 "type": "PlainText",
                 "text": message,
                 "playBehavior": "REPLACE_ENQUEUED"
             },
             "reprompt": {
                 "outputSpeech": {
                     "type": "PlainText",
                     "text": message,
                     "playBehavior": "REPLACE_ENQUEUED"
                 }
             },
             "shouldEndSession": session
         }
     }
     return response.json(r)				  		
Example #24
0
async def replay_events(tracker: DialogueStateTracker, agent: "Agent") -> None:
    """Take a tracker and replay the logged user utterances against an agent.

    During replaying of the user utterances, the executed actions and events
    created by the agent are compared to the logged ones of the tracker that
    is getting replayed. If they differ, a warning is logged.

    At the end, the tracker stored in the agent's tracker store for the
    same sender id will have quite the same state as the one
    that got replayed."""

    actions_between_utterances = []
    last_prediction = [ACTION_LISTEN_NAME]

    for i, event in enumerate(tracker.events_after_latest_restart()):
        if isinstance(event, UserUttered):
            _check_prediction_aligns_with_story(last_prediction,
                                                actions_between_utterances)

            actions_between_utterances = []
            cliutils.print_success(event.text)
            out = CollectingOutputChannel()
            await agent.handle_text(event.text,
                                    sender_id=tracker.sender_id,
                                    output_channel=out)
            for m in out.messages:
                buttons = m.pop("buttons", None)  # for non-terminal stdin
                console.print_bot_output(m)

                if buttons is not None:
                    color = rasa.cli.utils.bcolors.OKBLUE
                    rasa.cli.utils.print_color("Buttons:", color=color)
                    for idx, button in enumerate(buttons):
                        rasa.cli.utils.print_color(console.button_to_string(
                            button, idx),
                                                   color=color)

            tracker = agent.tracker_store.retrieve(tracker.sender_id)
            last_prediction = actions_since_last_utterance(tracker)

        elif isinstance(event, ActionExecuted):
            actions_between_utterances.append(event.action_name)

    _check_prediction_aligns_with_story(last_prediction,
                                        actions_between_utterances)
Example #25
0
        async def receive(request):
            payload = request.json
            intent = payload['inputs'][0]['intent']
            text = payload['inputs'][0]['rawInputs'][0]['query']

            if intent == 'actions.intent.MAIN':
                message = "Hello! Let's play a game. You can start by saying hi."
            else:
                out = CollectingOutputChannel()
                await on_new_message(UserMessage(text, out))
                print(out)
                print(out.messages)

                responses = [m["text"] for m in out.messages]
                if len(responses) == 0:
                    message = "No response"
                else:
                    if len(responses) == 1:
                        message = responses[0]
                    else:
                        message_tmp = ""
                        for resp in responses:
                            message_tmp += resp
                        message = message_tmp
            r = {
                "expectUserResponse":
                'true',
                "expectedInputs": [{
                    "possibleIntents": [{
                        "intent": "actions.intent.TEXT"
                    }],
                    "inputPrompt": {
                        "richInitialPrompt": {
                            "items": [{
                                "simpleResponse": {
                                    "textToSpeech": message,
                                    "displayText": message
                                }
                            }]
                        }
                    }
                }]
            }
            return response.json(r)
Example #26
0
        async def receive(request: Request):
            # jwt_data = await self._extract_header(request)
            # jwt_data = jwt_decode(jwt_data)
            message = await self._extract_message(request)
            sender = await self._extract_sender(request)
            metadata = await self._extract_metadata(request)
            # should_use_stream = rasa.utils.endpoints.bool_arg(
            #     request, "stream", default=False
            # )

            # if(jwt_data):
            # sender_id = await self._extract_sender(jwt_data)
            # if should_use_stream:
            #     return response.stream(
            #         self.stream_response(on_new_message, message, sender, metadata),
            #         content_type="text/event-stream",

            #     )
            # else:
            collector = CollectingOutputChannel()
            try:
                if metadata:
                    await on_new_message(
                        UserMessage(text=message,
                                    output_channel=collector,
                                    sender_id=sender,
                                    input_channel=self.name(),
                                    metadata=metadata))
                else:
                    await on_new_message(
                        UserMessage(text=message,
                                    output_channel=collector,
                                    sender_id=sender,
                                    input_channel=self.name()))

            except CancelledError:
                logger.error("Message handling timed out for "
                             "user message '{}'.".format(message))
            except Exception:
                logger.exception("An exception occured while handling "
                                 "user message '{}'.".format(message))
            return response.json(collector.messages)
        async def receive(request: Request) -> HTTPResponse:
            sender_id = request.json.get("sender")  # method to get sender_id
            text = request.json.get("message")  # method to fetch text
            input_channel = self.name()  # method to fetch input channel
            metadata = self.get_metadata(request)  # method to get metadata

            collector = CollectingOutputChannel()

            # include exception handling

            await on_new_message(
                UserMessage(
                    text,
                    collector,
                    sender_id,
                    input_channel=input_channel,
                    metadata=metadata,
                ))

            return response.json(collector.messages)
Example #28
0
        async def webhook(request: Request):
            payload = request.json
            # print(payload)
            # sender_id = payload['user']['userId']
            sender_id = "default"
            intent = payload['inputs'][0]['intent']
            text = payload['inputs'][0]['rawInputs'][0]['query']
            # print(intent)
            if intent == 'actions.intent.MAIN':
                message = "<speak>Hello! <break time=\"1\"/> Welcome to the Rasa-powered Google Assistant skill. You can start by saying hi.</speak>"
            else:
                out = CollectingOutputChannel(
                )  # collect the bot responses Core creates while the bot is processing your messages
                on_new_message(
                    UserMessage(text,
                                out,
                                sender_id,
                                input_channel=self.name()))
                responses = [m["text"] for m in out.messages]
                message = responses[0]

            r = json.dumps({
                "conversationToken":
                "{\"state\":null,\"data\":{}}",
                "expectUserResponse":
                'true',
                "expectedInputs": [{
                    "inputPrompt": {
                        "initialPrompts": [{
                            "ssml": message
                        }]
                    },
                    "possibleIntents": [{
                        "intent": "actions.intent.TEXT"
                    }]
                }]
            })
            print(message)
            print(r)
            return r
Example #29
0
        async def receive(request: Request) -> HTTPResponse:
            sender_id = await self._extract_sender(request)
            text = self._extract_message(request)
            message_type = self._extract_type(request)
            should_use_stream = rasa.utils.endpoints.bool_arg(request,
                                                              'stream',
                                                              default=False)
            input_channel = self._extract_input_channel(request)
            metadata = self.get_metadata(request)

            if should_use_stream:
                return response.stream(
                    self.stream_response(on_new_message, text, sender_id,
                                         input_channel, metadata),
                    content_type='text/event-stream',
                )
            else:
                collector = CollectingOutputChannel()
                # noinspection PyBroadException
                try:
                    await on_new_message(
                        UserMessage(
                            text,
                            collector,
                            sender_id,
                            input_channel=input_channel,
                            metadata=metadata,
                        ))
                except CancelledError:
                    logger.error(f'Message handling timed out for '
                                 f"user message '{text}'.")
                except Exception:
                    logger.exception(f'An exception occurred while handling '
                                     f"user message '{text}'.")
                messages = collector.messages
                for message_rasa in messages:
                    if message_type == 'audio':
                        audio = synthesize_text(message_rasa['text'])
                        message_rasa['audio'] = audio
                return response.json(messages)
Example #30
0
        async def receive(request: Request):
            print(f"dumping request: {request}")
            print(request.json)
            sender_id = await self._extract_sender(request)
            # sender_id = request.json.get("session")["user"]["userId"]
            print("sender_id: "+sender_id)
            req = request.json.get("request")
            should_use_stream = rasa.utils.endpoints.bool_arg(
                request, "stream", default=False
            )

            if should_use_stream:
                return response.stream(
                    self.stream_response(on_new_message, req, sender_id),
                    content_type="text/event-stream",
                )
            else:
                collector = CollectingOutputChannel()
                # noinspection PyBroadException
                try:
                    await on_new_message(
                        UserMessage(
                            json.dumps(req), collector, sender_id,
                            input_channel=self.name()
                        )
                    )
                except CancelledError:
                    logger.error(
                        "Message handling timed out for "
                        "user message '{}'.".format(req)
                    )
                except Exception:
                    logger.exception(
                        "An exception occured while handling "
                        "user message '{}'.".format(req)
                    )
                # return response.json(collector.messages)
                return response.json(mapp2Echo(collector.messages))