jupyter-ai-router


Namejupyter-ai-router JSON
Version 0.0.2 PyPI version JSON
download
home_pageNone
SummaryCore routing layer of Jupyter AI
upload_time2025-10-30 16:52:12
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseBSD 3-Clause License Copyright (c) 2025, Project Jupyter All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
keywords jupyter jupyterlab jupyterlab-extension
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # jupyter_ai_router

[![Github Actions Status](https://github.com/jupyter-ai-contrib/jupyter-ai-router/workflows/Build/badge.svg)](https://github.com/jupyter-ai-contrib/jupyter-ai-router/actions/workflows/build.yml)

Core message routing layer for Jupyter AI

This extension provides the foundational message routing functionality for Jupyter AI. It automatically detects new chat sessions and routes messages to registered callbacks based on message type (slash commands vs regular messages). Extensions can register callbacks to handle specific chat events without needing to manage chat lifecycle directly.

## Usage

### Basic MessageRouter Setup

```python
# The router is available in other extensions via settings
router = self.serverapp.web_app.settings.get("jupyter-ai", {}).get("router")

# Register callbacks for different event types
def on_new_chat(room_id: str, ychat: YChat):
    print(f"New chat connected: {room_id}")

def on_slash_command(room_id: str, command: str, message: Message):
    print(f"Slash command '{command}' in {room_id}: {message.body}")

def on_regular_message(room_id: str, message: Message):
    print(f"Regular message in {room_id}: {message.body}")

# Register the callbacks
router.observe_chat_init(on_new_chat)
router.observe_slash_cmd_msg("room-id", "help", on_slash_command)  # Only /help commands
router.observe_chat_msg("room-id", on_regular_message)
```

### Message Flow

1. **Router detects new chats** - Automatically listens for chat room initialization events
2. **Router connects chats** - Establishes observers on YChat message streams
3. **Router routes messages** - Calls appropriate callbacks based on message type (slash vs regular)
4. **Extensions respond** - Your callbacks receive room_id and message data

### Available Methods

- `observe_chat_init(callback)` - Called when new chat sessions are initialized with `(room_id, ychat)`
- `observe_slash_cmd_msg(room_id, command_pattern, callback)` - Called for specific slash commands matching the pattern in a specific room
- `observe_chat_msg(room_id, callback)` - Called for regular (non-slash) messages in a specific room

### Command Pattern Matching

The `observe_slash_cmd_msg` method supports regex pattern matching:

```python
# Exact match: Only matches "/help"
router.observe_slash_cmd_msg("room-id", "help", callback)

# Regex pattern: Matches "/ai-generate", "/ai-review", etc.
router.observe_slash_cmd_msg("room-id", "ai-.*", callback)

# Regex with groups: Matches "/export-json", "/export-csv", "/export-xml"
router.observe_slash_cmd_msg("room-id", r"export-(json|csv|xml)", callback)
```

**Callback signature**: `callback(room_id: str, command: str, message: Message)`

- `room_id`: The chat room identifier
- `command`: The matched command without the leading slash (e.g., "help", "ai-generate")
- `message`: Message object with the command removed from the body (only arguments remain)

## Install

To install the extension, execute:

```bash
pip install jupyter_ai_router
```

## Uninstall

To remove the extension, execute:

```bash
pip uninstall jupyter_ai_router
```

## Troubleshoot

If you are seeing the frontend extension, but it is not working, check
that the server extension is enabled:

```bash
jupyter server extension list
```

If the server extension is installed and enabled, but you are not seeing
the frontend extension, check the frontend extension is installed:

```bash
jupyter labextension list
```

## Contributing

### Development install

Note: You will need NodeJS to build the extension package.

The `jlpm` command is JupyterLab's pinned version of
[yarn](https://yarnpkg.com/) that is installed with JupyterLab. You may use
`yarn` or `npm` in lieu of `jlpm` below.

```bash
# Clone the repo to your local environment
# Change directory to the jupyter_ai_router directory
# Install package in development mode
pip install -e ".[test]"
# Link your development version of the extension with JupyterLab
jupyter labextension develop . --overwrite
# Server extension must be manually installed in develop mode
jupyter server extension enable jupyter_ai_router
# Rebuild extension Typescript source after making changes
jlpm build
```

You can watch the source directory and run JupyterLab at the same time in different terminals to watch for changes in the extension's source and automatically rebuild the extension.

```bash
# Watch the source directory in one terminal, automatically rebuilding when needed
jlpm watch
# Run JupyterLab in another terminal
jupyter lab
```

With the watch command running, every saved change will immediately be built locally and available in your running JupyterLab. Refresh JupyterLab to load the change in your browser (you may need to wait several seconds for the extension to be rebuilt).

By default, the `jlpm build` command generates the source maps for this extension to make it easier to debug using the browser dev tools. To also generate source maps for the JupyterLab core extensions, you can run the following command:

```bash
jupyter lab build --minimize=False
```

### Development uninstall

```bash
# Server extension must be manually disabled in develop mode
jupyter server extension disable jupyter_ai_router
pip uninstall jupyter_ai_router
```

In development mode, you will also need to remove the symlink created by `jupyter labextension develop`
command. To find its location, you can run `jupyter labextension list` to figure out where the `labextensions`
folder is located. Then you can remove the symlink named `@jupyter-ai/router` within that folder.

### Testing the extension

#### Server tests

This extension is using [Pytest](https://docs.pytest.org/) for Python code testing.

Install test dependencies (needed only once):

```sh
pip install -e ".[test]"
# Each time you install the Python package, you need to restore the front-end extension link
jupyter labextension develop . --overwrite
```

To execute them, run:

```sh
pytest -vv -r ap --cov jupyter_ai_router
```

#### Frontend tests

This extension is using [Jest](https://jestjs.io/) for JavaScript code testing.

To execute them, execute:

```sh
jlpm
jlpm test
```

#### Integration tests

This extension uses [Playwright](https://playwright.dev/docs/intro) for the integration tests (aka user level tests).
More precisely, the JupyterLab helper [Galata](https://github.com/jupyterlab/jupyterlab/tree/master/galata) is used to handle testing the extension in JupyterLab.

More information are provided within the [ui-tests](./ui-tests/README.md) README.

### Packaging the extension

See [RELEASE](RELEASE.md)

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "jupyter-ai-router",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "jupyter, jupyterlab, jupyterlab-extension",
    "author": null,
    "author_email": "Project Jupyter <jupyter@googlegroups.com>",
    "download_url": "https://files.pythonhosted.org/packages/c2/69/49d02cde0ce2b9dd3b9141903b329614e1062e2bdcbeef657d5dd6e990b2/jupyter_ai_router-0.0.2.tar.gz",
    "platform": null,
    "description": "# jupyter_ai_router\n\n[![Github Actions Status](https://github.com/jupyter-ai-contrib/jupyter-ai-router/workflows/Build/badge.svg)](https://github.com/jupyter-ai-contrib/jupyter-ai-router/actions/workflows/build.yml)\n\nCore message routing layer for Jupyter AI\n\nThis extension provides the foundational message routing functionality for Jupyter AI. It automatically detects new chat sessions and routes messages to registered callbacks based on message type (slash commands vs regular messages). Extensions can register callbacks to handle specific chat events without needing to manage chat lifecycle directly.\n\n## Usage\n\n### Basic MessageRouter Setup\n\n```python\n# The router is available in other extensions via settings\nrouter = self.serverapp.web_app.settings.get(\"jupyter-ai\", {}).get(\"router\")\n\n# Register callbacks for different event types\ndef on_new_chat(room_id: str, ychat: YChat):\n    print(f\"New chat connected: {room_id}\")\n\ndef on_slash_command(room_id: str, command: str, message: Message):\n    print(f\"Slash command '{command}' in {room_id}: {message.body}\")\n\ndef on_regular_message(room_id: str, message: Message):\n    print(f\"Regular message in {room_id}: {message.body}\")\n\n# Register the callbacks\nrouter.observe_chat_init(on_new_chat)\nrouter.observe_slash_cmd_msg(\"room-id\", \"help\", on_slash_command)  # Only /help commands\nrouter.observe_chat_msg(\"room-id\", on_regular_message)\n```\n\n### Message Flow\n\n1. **Router detects new chats** - Automatically listens for chat room initialization events\n2. **Router connects chats** - Establishes observers on YChat message streams\n3. **Router routes messages** - Calls appropriate callbacks based on message type (slash vs regular)\n4. **Extensions respond** - Your callbacks receive room_id and message data\n\n### Available Methods\n\n- `observe_chat_init(callback)` - Called when new chat sessions are initialized with `(room_id, ychat)`\n- `observe_slash_cmd_msg(room_id, command_pattern, callback)` - Called for specific slash commands matching the pattern in a specific room\n- `observe_chat_msg(room_id, callback)` - Called for regular (non-slash) messages in a specific room\n\n### Command Pattern Matching\n\nThe `observe_slash_cmd_msg` method supports regex pattern matching:\n\n```python\n# Exact match: Only matches \"/help\"\nrouter.observe_slash_cmd_msg(\"room-id\", \"help\", callback)\n\n# Regex pattern: Matches \"/ai-generate\", \"/ai-review\", etc.\nrouter.observe_slash_cmd_msg(\"room-id\", \"ai-.*\", callback)\n\n# Regex with groups: Matches \"/export-json\", \"/export-csv\", \"/export-xml\"\nrouter.observe_slash_cmd_msg(\"room-id\", r\"export-(json|csv|xml)\", callback)\n```\n\n**Callback signature**: `callback(room_id: str, command: str, message: Message)`\n\n- `room_id`: The chat room identifier\n- `command`: The matched command without the leading slash (e.g., \"help\", \"ai-generate\")\n- `message`: Message object with the command removed from the body (only arguments remain)\n\n## Install\n\nTo install the extension, execute:\n\n```bash\npip install jupyter_ai_router\n```\n\n## Uninstall\n\nTo remove the extension, execute:\n\n```bash\npip uninstall jupyter_ai_router\n```\n\n## Troubleshoot\n\nIf you are seeing the frontend extension, but it is not working, check\nthat the server extension is enabled:\n\n```bash\njupyter server extension list\n```\n\nIf the server extension is installed and enabled, but you are not seeing\nthe frontend extension, check the frontend extension is installed:\n\n```bash\njupyter labextension list\n```\n\n## Contributing\n\n### Development install\n\nNote: You will need NodeJS to build the extension package.\n\nThe `jlpm` command is JupyterLab's pinned version of\n[yarn](https://yarnpkg.com/) that is installed with JupyterLab. You may use\n`yarn` or `npm` in lieu of `jlpm` below.\n\n```bash\n# Clone the repo to your local environment\n# Change directory to the jupyter_ai_router directory\n# Install package in development mode\npip install -e \".[test]\"\n# Link your development version of the extension with JupyterLab\njupyter labextension develop . --overwrite\n# Server extension must be manually installed in develop mode\njupyter server extension enable jupyter_ai_router\n# Rebuild extension Typescript source after making changes\njlpm build\n```\n\nYou can watch the source directory and run JupyterLab at the same time in different terminals to watch for changes in the extension's source and automatically rebuild the extension.\n\n```bash\n# Watch the source directory in one terminal, automatically rebuilding when needed\njlpm watch\n# Run JupyterLab in another terminal\njupyter lab\n```\n\nWith the watch command running, every saved change will immediately be built locally and available in your running JupyterLab. Refresh JupyterLab to load the change in your browser (you may need to wait several seconds for the extension to be rebuilt).\n\nBy default, the `jlpm build` command generates the source maps for this extension to make it easier to debug using the browser dev tools. To also generate source maps for the JupyterLab core extensions, you can run the following command:\n\n```bash\njupyter lab build --minimize=False\n```\n\n### Development uninstall\n\n```bash\n# Server extension must be manually disabled in develop mode\njupyter server extension disable jupyter_ai_router\npip uninstall jupyter_ai_router\n```\n\nIn development mode, you will also need to remove the symlink created by `jupyter labextension develop`\ncommand. To find its location, you can run `jupyter labextension list` to figure out where the `labextensions`\nfolder is located. Then you can remove the symlink named `@jupyter-ai/router` within that folder.\n\n### Testing the extension\n\n#### Server tests\n\nThis extension is using [Pytest](https://docs.pytest.org/) for Python code testing.\n\nInstall test dependencies (needed only once):\n\n```sh\npip install -e \".[test]\"\n# Each time you install the Python package, you need to restore the front-end extension link\njupyter labextension develop . --overwrite\n```\n\nTo execute them, run:\n\n```sh\npytest -vv -r ap --cov jupyter_ai_router\n```\n\n#### Frontend tests\n\nThis extension is using [Jest](https://jestjs.io/) for JavaScript code testing.\n\nTo execute them, execute:\n\n```sh\njlpm\njlpm test\n```\n\n#### Integration tests\n\nThis extension uses [Playwright](https://playwright.dev/docs/intro) for the integration tests (aka user level tests).\nMore precisely, the JupyterLab helper [Galata](https://github.com/jupyterlab/jupyterlab/tree/master/galata) is used to handle testing the extension in JupyterLab.\n\nMore information are provided within the [ui-tests](./ui-tests/README.md) README.\n\n### Packaging the extension\n\nSee [RELEASE](RELEASE.md)\n",
    "bugtrack_url": null,
    "license": "BSD 3-Clause License\n        \n        Copyright (c) 2025, Project Jupyter\n        All rights reserved.\n        \n        Redistribution and use in source and binary forms, with or without\n        modification, are permitted provided that the following conditions are met:\n        \n        1. Redistributions of source code must retain the above copyright notice, this\n           list of conditions and the following disclaimer.\n        \n        2. Redistributions in binary form must reproduce the above copyright notice,\n           this list of conditions and the following disclaimer in the documentation\n           and/or other materials provided with the distribution.\n        \n        3. Neither the name of the copyright holder nor the names of its\n           contributors may be used to endorse or promote products derived from\n           this software without specific prior written permission.\n        \n        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n        AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n        IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n        DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n        FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n        DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n        SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n        CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n        OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n        OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
    "summary": "Core routing layer of Jupyter AI",
    "version": "0.0.2",
    "project_urls": {
        "Bug Tracker": "https://github.com/jupyter-ai-contrib/jupyter-ai-router/issues",
        "Homepage": "https://github.com/jupyter-ai-contrib/jupyter-ai-router",
        "Repository": "https://github.com/jupyter-ai-contrib/jupyter-ai-router.git"
    },
    "split_keywords": [
        "jupyter",
        " jupyterlab",
        " jupyterlab-extension"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "8a7bce626e9b322521940aacfad14bb7175af55edaf8e928e60e51dc1ebd68bf",
                "md5": "30d620ed4bb3d66d8fa7e03e74b7c943",
                "sha256": "a79c01cd5a1e974f5dad91463c0180d1e16bcb4262e20bc15147e7ea868ee391"
            },
            "downloads": -1,
            "filename": "jupyter_ai_router-0.0.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "30d620ed4bb3d66d8fa7e03e74b7c943",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 26987,
            "upload_time": "2025-10-30T16:52:10",
            "upload_time_iso_8601": "2025-10-30T16:52:10.992278Z",
            "url": "https://files.pythonhosted.org/packages/8a/7b/ce626e9b322521940aacfad14bb7175af55edaf8e928e60e51dc1ebd68bf/jupyter_ai_router-0.0.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "c26949d02cde0ce2b9dd3b9141903b329614e1062e2bdcbeef657d5dd6e990b2",
                "md5": "968ede3dd4407158c62e0b4b3db29351",
                "sha256": "4a152a10ebf25dc335a2877c2572d597f5f7bc11410beb1e12465b62cd74d977"
            },
            "downloads": -1,
            "filename": "jupyter_ai_router-0.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "968ede3dd4407158c62e0b4b3db29351",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 140782,
            "upload_time": "2025-10-30T16:52:12",
            "upload_time_iso_8601": "2025-10-30T16:52:12.456893Z",
            "url": "https://files.pythonhosted.org/packages/c2/69/49d02cde0ce2b9dd3b9141903b329614e1062e2bdcbeef657d5dd6e990b2/jupyter_ai_router-0.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-30 16:52:12",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "jupyter-ai-contrib",
    "github_project": "jupyter-ai-router",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "jupyter-ai-router"
}
        
Elapsed time: 2.13171s