Example #1
0
    def handle_channels(
        self,
        channels: List[InputChannel],
        http_port: int = constants.DEFAULT_SERVER_PORT,
        route: Text = "/webhooks/",
        cors=None,
    ) -> Sanic:
        """Start a webserver attaching the input channels and handling msgs."""

        from rasa.core import run

        logger.warning(
            "DEPRECATION warning: Using `handle_channels` is deprecated. "
            "Please use `rasa.run(...)` or see "
            "`rasa.core.run.configure_app(...)` if you want to implement "
            "this on a more detailed level.")

        app = run.configure_app(channels,
                                cors,
                                None,
                                enable_api=False,
                                route=route)

        app.agent = self

        update_sanic_log_level()

        app.run(host="0.0.0.0", port=http_port)

        # this might seem unnecessary (as run does not return until the server
        # is killed) - but we use it for tests where we mock `.run` to directly
        # return and need the app to inspect if we created a properly
        # configured server
        return app
Example #2
0
    def handle_channels(
        self,
        channels: List[InputChannel],
        http_port: int = constants.DEFAULT_SERVER_PORT,
        route: Text = "/webhooks/",
        cors=None,
    ) -> Sanic:
        """Start a webserver attaching the input channels and handling msgs."""

        from rasa.core import run

        app = run.configure_app(channels,
                                cors,
                                None,
                                enable_api=False,
                                route=route)

        app.agent = self

        update_sanic_log_level()

        app.run(host="0.0.0.0", port=http_port)

        # this might seem unnecessary (as run does not return until the server
        # is killed) - but we use it for tests where we mock `.run` to directly
        # return and need the app to inspect if we created a properly
        # configured server
        return app
Example #3
0
    def handle_channels(self, channels: List[InputChannel],
                        http_port: int = constants.DEFAULT_SERVER_PORT,
                        route: Text = "/webhooks/",
                        cors=None) -> 'Sanic':
        """Start a webserver attaching the input channels and handling msgs.

        If ``serve_forever`` is set to ``True``, this call will be blocking.
        Otherwise the webserver will be started, and the method will
        return afterwards."""
        from rasa.core import run

        app = run.configure_app(channels, cors, None,
                                enable_api=False,
                                route=route)

        app.agent = self

        app.run(host='0.0.0.0', port=http_port,
                access_log=logger.isEnabledFor(logging.DEBUG))

        # this might seem unnecessary (as run does not return until the server
        # is killed) - but we use it for tests where we mock `.run` to directly
        # return and need the app to inspect if we created a properly
        # configured server
        return app
Example #4
0
async def serve_application(core_model: Text = None,
                            nlu_model: Optional[Text] = None,
                            tracker_dump: Optional[Text] = None,
                            port=constants.DEFAULT_SERVER_PORT,
                            enable_api=True,
                            endpoints=None
                            ):
    input_channels = run.create_http_input_channels("cmdline", None)

    app = run.configure_app(input_channels, enable_api=enable_api, port=port)

    logger.info("Starting Rasa Core server on "
                "{}".format(constants.DEFAULT_SERVER_FORMAT.format(port)))

    # noinspection PyShadowingNames
    async def load_agent_and_tracker(app, loop):
        agent = await run.load_agent_on_start(core_model, endpoints,
                                              nlu_model, app, loop)

        tracker = load_tracker_from_json(tracker_dump,
                                         agent.domain)
        await replay_events(tracker, agent)

    app.register_listener(load_agent_and_tracker, 'before_server_start')
    app.run(host='0.0.0.0', port=port,
            access_log=logger.isEnabledFor(logging.DEBUG))
Example #5
0
def run_interactive_learning(stories: Text = None,
                             finetune: bool = False,
                             skip_visualization: bool = False,
                             server_args: Dict[Text, Any] = None,
                             additional_arguments: Dict[Text, Any] = None):
    """Start the interactive learning with the model of the agent."""

    server_args = server_args or {}

    if not skip_visualization:
        p = Process(target=start_visualization, args=("story_graph.dot", ))
        p.deamon = True
        p.start()
    else:
        p = None

    app = run.configure_app(enable_api=True)
    endpoints = AvailableEndpoints.read_endpoints(server_args.get("endpoints"))

    # before_server_start handlers make sure the agent is loaded before the
    # interactive learning IO starts
    if server_args.get("core"):
        app.register_listener(
            partial(run.load_agent_on_start, server_args.get("core"),
                    endpoints, server_args.get("nlu")), 'before_server_start')
    else:
        app.register_listener(
            partial(train_agent_on_start, server_args, endpoints,
                    additional_arguments), 'before_server_start')

    _serve_application(app, stories, finetune, skip_visualization)

    if not skip_visualization:
        p.terminate()
        p.join()
Example #6
0
def test_facebook_channel():
    from rasa.core.channels.facebook import FacebookInput

    input_channel = FacebookInput(
        fb_verify="YOUR_FB_VERIFY",
        # you need tell facebook this token, to confirm your URL
        fb_secret="YOUR_FB_SECRET",  # your app secret
        fb_access_token="YOUR_FB_PAGE_ACCESS_TOKEN"
        # token for the page you subscribed to
    )

    s = run.configure_app([input_channel], port=5004)
    routes_list = utils.list_routes(s)

    assert routes_list["fb_webhook.health"].startswith("/webhooks/facebook")
    assert routes_list["fb_webhook.webhook"].startswith("/webhooks/facebook/webhook")
Example #7
0
    def handle_channels(
        self,
        channels: List[InputChannel],
        http_port: int = constants.DEFAULT_SERVER_PORT,
        route: Text = "/webhooks/",
        cors: Union[Text, List[Text], None] = None,
    ) -> Sanic:
        """Start a webserver attaching the input channels and handling msgs."""

        from rasa.core import run

        raise_warning(
            "Using `handle_channels` is deprecated. "
            "Please use `rasa.run(...)` or see "
            "`rasa.core.run.configure_app(...)` if you want to implement "
            "this on a more detailed level.",
            DeprecationWarning,
        )

        app = run.configure_app(channels,
                                cors,
                                None,
                                enable_api=False,
                                route=route)

        app.agent = self

        update_sanic_log_level()

        app.run(
            host="0.0.0.0",
            port=http_port,
            backlog=int(os.environ.get(ENV_SANIC_BACKLOG, "100")),
            workers=rasa.core.utils.number_of_sanic_workers(self.lock_store),
        )

        # this might seem unnecessary (as run does not return until the server
        # is killed) - but we use it for tests where we mock `.run` to directly
        # return and need the app to inspect if we created a properly
        # configured server
        return app
Example #8
0
def serve_application(
    model_path: Optional[Text] = None,
    channel: Optional[Text] = None,
    port: int = constants.DEFAULT_SERVER_PORT,
    credentials: Optional[Text] = None,
    cors: Optional[Union[Text, List[Text]]] = None,
    auth_token: Optional[Text] = None,
    enable_api: bool = True,
    response_timeout: int = constants.DEFAULT_RESPONSE_TIMEOUT,
    jwt_secret: Optional[Text] = None,
    jwt_method: Optional[Text] = None,
    endpoints: Optional[AvailableEndpoints] = None,
    remote_storage: Optional[Text] = None,
    log_file: Optional[Text] = None,
    ssl_certificate: Optional[Text] = None,
    ssl_keyfile: Optional[Text] = None,
    ssl_ca_file: Optional[Text] = None,
    ssl_password: Optional[Text] = None,
    conversation_id: Optional[Text] = uuid.uuid4().hex,
):
    """Run the API entrypoint."""
    from rasa import server

    if not channel and not credentials:
        channel = "cmdline"

    input_channels = create_http_input_channels(channel, credentials)

    app = configure_app(
        input_channels,
        cors,
        auth_token,
        enable_api,
        response_timeout,
        jwt_secret,
        jwt_method,
        port=port,
        endpoints=endpoints,
        log_file=log_file,
        conversation_id=conversation_id,
    )

    ssl_context = server.create_ssl_context(ssl_certificate, ssl_keyfile,
                                            ssl_ca_file, ssl_password)
    protocol = "https" if ssl_context else "http"

    logger.info("Starting Rasa server on "
                "{}".format(
                    constants.DEFAULT_SERVER_FORMAT.format(protocol, port)))

    app.register_listener(
        partial(load_agent_on_start, model_path, endpoints, remote_storage),
        "before_server_start",
    )

    # noinspection PyUnresolvedReferences
    async def clear_model_files(_app: Sanic, _loop: Text) -> None:
        if app.agent.model_directory:
            shutil.rmtree(_app.agent.model_directory)

    app.register_listener(clear_model_files, "after_server_stop")

    rasa.utils.common.update_sanic_log_level(log_file)

    # 注册自己的蓝图
    app.register_blueprint(api)

    app.run(
        host="0.0.0.0",
        port=port,
        ssl=ssl_context,
        backlog=int(os.environ.get(ENV_SANIC_BACKLOG, "100")),
        workers=rasa.core.utils.number_of_sanic_workers(
            endpoints.lock_store if endpoints else None),
    )