Name | jupyter-nbmodel-client JSON |
Version |
0.13.5
JSON |
| download |
home_page | None |
Summary | None |
upload_time | 2025-07-08 10:20:22 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.9 |
license | BSD 3-Clause License
Copyright (c) 2024, Datalayer
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
|
VCS |
 |
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
<!--
~ Copyright (c) 2023-2024 Datalayer, Inc.
~
~ BSD 3-Clause License
-->
[](https://datalayer.io)
[](https://github.com/sponsors/datalayer)
# 🪐 Jupyter NbModel Client
[](https://github.com/datalayer/jupyter-nbmodel-client/actions/workflows/build.yml)
[](https://pypi.org/project/jupyter-nbmodel-client)
`Jupyter NbModel Client` is a python library to interact with a live Jupyter Notebooks.
To install the library, run the following command.
```bash
pip install jupyter_nbmodel_client
```
We ask you to take additional actions to overcome limitations and bugs of the pycrdt library.
```bash
# Ensure you create a new shell after running the following commands.
pip uninstall -y pycrdt datalayer_pycrdt
pip install datalayer_pycrdt
```
## Usage with Jupyter
1. Ensure you have the needed packages in your environment to run the example here after.
```sh
pip install jupyterlab jupyter-collaboration matplotlib
```
2. Start a JupyterLab server, setting a `port` and a `token` to be reused by the agent, and create a notebook `test.ipynb`.
```sh
# make jupyterlab
jupyter lab --port 8888 --ServerApp.port_retries 0 --IdentityProvider.token MY_TOKEN --ServerApp.root_dir ./dev
```
3. Open a IPython (needed for async functions) REPL in a terminal with `ipython` (or `jupyter console`). Execute the following snippet to add a cell in the `test.ipynb` notebook.
```py
from jupyter_nbmodel_client import NbModelClient, get_jupyter_notebook_websocket_url
ws_url = get_jupyter_notebook_websocket_url(
server_url="http://localhost:8888",
token="MY_TOKEN",
path="test.ipynb"
)
async with NbModelClient(ws_url) as nbmodel:
nbmodel.add_code_cell("print('hello world')")
```
> Check `test.ipynb` in JupyterLab, you should see a cell with content `print('hello world')` appended to the notebook.
5. The previous example does not involve kernels. Put that now in the picture, adding a cell and executing the cell code within a kernel process.
```py
from jupyter_kernel_client import KernelClient
from jupyter_nbmodel_client import NbModelClient, get_jupyter_notebook_websocket_url
with KernelClient(server_url="http://localhost:8888", token="MY_TOKEN") as kernel:
ws_url = get_jupyter_notebook_websocket_url(
server_url="http://localhost:8888",
token="MY_TOKEN",
path="test.ipynb"
)
async with NbModelClient(ws_url) as notebook:
cell_index = notebook.add_code_cell("print('hello world')")
results = notebook.execute_cell(cell_index, kernel)
print(results)
assert results["status"] == "ok"
assert len(results["outputs"]) > 0
```
> Check `test.ipynb` in JupyterLab. You should see an additional cell with content `print('hello world')` appended to the notebook, but this time the cell is executed, so the output should show `hello world`.
You can go further and create a plot with eg matplotlib.
```py
from jupyter_kernel_client import KernelClient
from jupyter_nbmodel_client import NbModelClient, get_jupyter_notebook_websocket_url
CODE = """import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']
ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')
plt.show()
"""
with KernelClient(server_url="http://localhost:8888", token="MY_TOKEN") as kernel:
ws_url = get_jupyter_notebook_websocket_url(
server_url="http://localhost:8888",
token="MY_TOKEN",
path="test.ipynb"
)
async with NbModelClient(ws_url) as notebook:
cell_index = notebook.add_code_cell(CODE)
results = notebook.execute_cell(cell_index, kernel)
print(results)
assert results["status"] == "ok"
assert len(results["outputs"]) > 0
```
> Check `test.ipynb` in JupyterLab for the cell with the matplotlib.
> [!NOTE]
>
> Instead of using the nbmodel clients as context manager, you can call the `start()` and `stop()` methods.
```py
from jupyter_nbmodel_client import NbModelClient, get_jupyter_notebook_websocket_url
kernel = KernelClient(server_url="http://localhost:8888", token="MY_TOKEN")
kernel.start()
try:
ws_url = get_jupyter_notebook_websocket_url(
server_url="http://localhost:8888",
token="MY_TOKEN",
path="test.ipynb"
)
notebook = NbModelClient(ws_url)
await notebook.start()
try:
cell_index = notebook.add_code_cell("print('hello world')")
results = notebook.execute_cell(cell_index, kernel)
finally:
await notebook.stop()
finally:
kernel.stop()
```
## Usage with Datalayer
To connect to a [Datalayer collaborative room](https://docs.datalayer.app/platform#notebook-editor), you can use the helper function `get_datalayer_notebook_websocket_url`:
- The `server` is `https://prod1.datalayer.run` for the Datalayer production SaaS.
- The `room_id` is the id of your notebook shown in the URL browser bar.
- The `token` is the assigned token for the notebook.
All those details can be retrieved from a Notebook sidebar on the Datalayer SaaS.
```py
from jupyter_nbmodel_client import NbModelClient, get_datalayer_notebook_websocket_url
ws_url = get_datalayer_notebook_websocket_url(
server_url=server,
room_id=room_id,
token=token
)
async with NbModelClient(ws_url) as notebook:
notebook.add_code_cell("1+1")
```
## Uninstall
To remove the library, run the following.
```bash
pip uninstall jupyter_nbmodel_client
```
## Data Models
The following json schema describes the data model used in cells and notebook metadata to communicate between user clients and an Jupyter AI Agent.
For that, you will need the [Jupyter AI Agents](https://github.com/datalayer/jupyter-ai-agents) extension installed.
```json
{
"datalayer": {
"type": "object",
"properties": {
"ai": {
"type": "object",
"properties": {
"prompts": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"title": "Prompt unique identifier",
"type": "string"
},
"prompt": {
"title": "User prompt",
"type": "string"
},
"username": {
"title": "Unique identifier of the user making the prompt.",
"type": "string"
},
"timestamp": {
"title": "Number of milliseconds elapsed since the epoch; i.e. January 1st, 1970 at midnight UTC.",
"type": "integer"
}
},
"required": ["id", "prompt"]
}
},
"messages": {
"type": "array",
"items": {
"type": "object",
"properties": {
"parent_id": {
"title": "Prompt unique identifier",
"type": "string"
},
"message": {
"title": "AI reply",
"type": "string"
},
"type": {
"title": "Type message",
"enum": [0, 1, 2]
},
"timestamp": {
"title": "Number of milliseconds elapsed since the epoch; i.e. January 1st, 1970 at midnight UTC.",
"type": "integer"
}
},
"required": ["id", "prompt"]
}
}
}
}
}
}
}
```
## Contributing
### Development install
```bash
# Clone the repo to your local environment
# Change directory to the jupyter_nbmodel_client directory
# Install package in development mode - will automatically enable
# The server extension.
pip install -e ".[test,lint,typing]"
```
### Running Tests
Install dependencies:
```bash
pip install -e ".[test]"
```
To run the python tests, use:
```bash
pytest
```
### Development uninstall
```bash
pip uninstall jupyter_nbmodel_client
```
### Packaging the library
See [RELEASE](RELEASE.md)
Raw data
{
"_id": null,
"home_page": null,
"name": "jupyter-nbmodel-client",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": null,
"keywords": "Jupyter",
"author": null,
"author_email": "Datalayer <info@datalayer.io>",
"download_url": null,
"platform": null,
"description": "<!--\n ~ Copyright (c) 2023-2024 Datalayer, Inc.\n ~\n ~ BSD 3-Clause License\n-->\n\n[](https://datalayer.io)\n\n[](https://github.com/sponsors/datalayer)\n\n# \ud83e\ude90 Jupyter NbModel Client\n\n[](https://github.com/datalayer/jupyter-nbmodel-client/actions/workflows/build.yml)\n[](https://pypi.org/project/jupyter-nbmodel-client)\n\n`Jupyter NbModel Client` is a python library to interact with a live Jupyter Notebooks.\n\nTo install the library, run the following command.\n\n```bash\npip install jupyter_nbmodel_client\n```\n\nWe ask you to take additional actions to overcome limitations and bugs of the pycrdt library.\n\n```bash\n# Ensure you create a new shell after running the following commands.\npip uninstall -y pycrdt datalayer_pycrdt\npip install datalayer_pycrdt\n```\n\n## Usage with Jupyter\n\n1. Ensure you have the needed packages in your environment to run the example here after.\n\n```sh\npip install jupyterlab jupyter-collaboration matplotlib\n```\n\n2. Start a JupyterLab server, setting a `port` and a `token` to be reused by the agent, and create a notebook `test.ipynb`.\n\n```sh\n# make jupyterlab\njupyter lab --port 8888 --ServerApp.port_retries 0 --IdentityProvider.token MY_TOKEN --ServerApp.root_dir ./dev\n```\n\n3. Open a IPython (needed for async functions) REPL in a terminal with `ipython` (or `jupyter console`). Execute the following snippet to add a cell in the `test.ipynb` notebook.\n\n```py\nfrom jupyter_nbmodel_client import NbModelClient, get_jupyter_notebook_websocket_url\n\nws_url = get_jupyter_notebook_websocket_url(\n server_url=\"http://localhost:8888\",\n token=\"MY_TOKEN\",\n path=\"test.ipynb\"\n)\n\nasync with NbModelClient(ws_url) as nbmodel:\n nbmodel.add_code_cell(\"print('hello world')\")\n```\n\n> Check `test.ipynb` in JupyterLab, you should see a cell with content `print('hello world')` appended to the notebook.\n\n5. The previous example does not involve kernels. Put that now in the picture, adding a cell and executing the cell code within a kernel process.\n\n```py\nfrom jupyter_kernel_client import KernelClient\nfrom jupyter_nbmodel_client import NbModelClient, get_jupyter_notebook_websocket_url\n\nwith KernelClient(server_url=\"http://localhost:8888\", token=\"MY_TOKEN\") as kernel:\n ws_url = get_jupyter_notebook_websocket_url(\n server_url=\"http://localhost:8888\",\n token=\"MY_TOKEN\",\n path=\"test.ipynb\"\n )\n async with NbModelClient(ws_url) as notebook:\n cell_index = notebook.add_code_cell(\"print('hello world')\")\n results = notebook.execute_cell(cell_index, kernel)\n print(results)\n assert results[\"status\"] == \"ok\"\n assert len(results[\"outputs\"]) > 0\n```\n\n> Check `test.ipynb` in JupyterLab. You should see an additional cell with content `print('hello world')` appended to the notebook, but this time the cell is executed, so the output should show `hello world`.\n\nYou can go further and create a plot with eg matplotlib.\n\n```py\nfrom jupyter_kernel_client import KernelClient\nfrom jupyter_nbmodel_client import NbModelClient, get_jupyter_notebook_websocket_url\n\nCODE = \"\"\"import matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\n\nfruits = ['apple', 'blueberry', 'cherry', 'orange']\ncounts = [40, 100, 30, 55]\nbar_labels = ['red', 'blue', '_red', 'orange']\nbar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']\n\nax.bar(fruits, counts, label=bar_labels, color=bar_colors)\n\nax.set_ylabel('fruit supply')\nax.set_title('Fruit supply by kind and color')\nax.legend(title='Fruit color')\n\nplt.show()\n\"\"\"\n\nwith KernelClient(server_url=\"http://localhost:8888\", token=\"MY_TOKEN\") as kernel:\n ws_url = get_jupyter_notebook_websocket_url(\n server_url=\"http://localhost:8888\",\n token=\"MY_TOKEN\",\n path=\"test.ipynb\"\n )\n async with NbModelClient(ws_url) as notebook:\n cell_index = notebook.add_code_cell(CODE)\n results = notebook.execute_cell(cell_index, kernel)\n print(results)\n assert results[\"status\"] == \"ok\"\n assert len(results[\"outputs\"]) > 0\n```\n\n> Check `test.ipynb` in JupyterLab for the cell with the matplotlib.\n\n> [!NOTE]\n>\n> Instead of using the nbmodel clients as context manager, you can call the `start()` and `stop()` methods.\n\n```py\nfrom jupyter_nbmodel_client import NbModelClient, get_jupyter_notebook_websocket_url\n\nkernel = KernelClient(server_url=\"http://localhost:8888\", token=\"MY_TOKEN\")\nkernel.start()\n\ntry:\n ws_url = get_jupyter_notebook_websocket_url(\n server_url=\"http://localhost:8888\",\n token=\"MY_TOKEN\",\n path=\"test.ipynb\"\n )\n notebook = NbModelClient(ws_url)\n await notebook.start()\n try:\n cell_index = notebook.add_code_cell(\"print('hello world')\")\n results = notebook.execute_cell(cell_index, kernel)\n finally:\n await notebook.stop()\nfinally:\n kernel.stop()\n```\n\n## Usage with Datalayer\n\nTo connect to a [Datalayer collaborative room](https://docs.datalayer.app/platform#notebook-editor), you can use the helper function `get_datalayer_notebook_websocket_url`:\n\n- The `server` is `https://prod1.datalayer.run` for the Datalayer production SaaS.\n- The `room_id` is the id of your notebook shown in the URL browser bar.\n- The `token` is the assigned token for the notebook.\n\nAll those details can be retrieved from a Notebook sidebar on the Datalayer SaaS.\n\n```py\nfrom jupyter_nbmodel_client import NbModelClient, get_datalayer_notebook_websocket_url\n\nws_url = get_datalayer_notebook_websocket_url(\n server_url=server,\n room_id=room_id,\n token=token\n)\n\nasync with NbModelClient(ws_url) as notebook:\n notebook.add_code_cell(\"1+1\")\n```\n\n## Uninstall\n\nTo remove the library, run the following.\n\n```bash\npip uninstall jupyter_nbmodel_client\n```\n\n## Data Models\n\nThe following json schema describes the data model used in cells and notebook metadata to communicate between user clients and an Jupyter AI Agent.\n\nFor that, you will need the [Jupyter AI Agents](https://github.com/datalayer/jupyter-ai-agents) extension installed.\n\n```json\n{\n \"datalayer\": {\n \"type\": \"object\",\n \"properties\": {\n \"ai\": {\n \"type\": \"object\",\n \"properties\": {\n \"prompts\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"title\": \"Prompt unique identifier\",\n \"type\": \"string\"\n },\n \"prompt\": {\n \"title\": \"User prompt\",\n \"type\": \"string\"\n },\n \"username\": {\n \"title\": \"Unique identifier of the user making the prompt.\",\n \"type\": \"string\"\n },\n \"timestamp\": {\n \"title\": \"Number of milliseconds elapsed since the epoch; i.e. January 1st, 1970 at midnight UTC.\",\n \"type\": \"integer\"\n }\n },\n \"required\": [\"id\", \"prompt\"]\n }\n },\n \"messages\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"parent_id\": {\n \"title\": \"Prompt unique identifier\",\n \"type\": \"string\"\n },\n \"message\": {\n \"title\": \"AI reply\",\n \"type\": \"string\"\n },\n \"type\": {\n \"title\": \"Type message\",\n \"enum\": [0, 1, 2]\n },\n \"timestamp\": {\n \"title\": \"Number of milliseconds elapsed since the epoch; i.e. January 1st, 1970 at midnight UTC.\",\n \"type\": \"integer\"\n }\n },\n \"required\": [\"id\", \"prompt\"]\n }\n }\n }\n }\n }\n }\n}\n```\n\n## Contributing\n\n### Development install\n\n```bash\n# Clone the repo to your local environment\n# Change directory to the jupyter_nbmodel_client directory\n# Install package in development mode - will automatically enable\n# The server extension.\npip install -e \".[test,lint,typing]\"\n```\n\n### Running Tests\n\nInstall dependencies:\n\n```bash\npip install -e \".[test]\"\n```\n\nTo run the python tests, use:\n\n```bash\npytest\n```\n\n### Development uninstall\n\n```bash\npip uninstall jupyter_nbmodel_client\n```\n\n### Packaging the library\n\nSee [RELEASE](RELEASE.md)\n",
"bugtrack_url": null,
"license": "BSD 3-Clause License\n \n Copyright (c) 2024, Datalayer\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": null,
"version": "0.13.5",
"project_urls": {
"Home": "https://github.com/datalayer/jupyter-nbmodel-client"
},
"split_keywords": [
"jupyter"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "bfae9ab14d22b0b35aed0b64437fa61fc462b0c040bbdd31caacad93b3fbb95f",
"md5": "f6eea4758ef14f94d11f8448264dcd62",
"sha256": "e5a40db2d962f233d2c61e098926272e5f37c80d43d9ded1016d49d7c713e44c"
},
"downloads": -1,
"filename": "jupyter_nbmodel_client-0.13.5-py3-none-any.whl",
"has_sig": false,
"md5_digest": "f6eea4758ef14f94d11f8448264dcd62",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 26897,
"upload_time": "2025-07-08T10:20:22",
"upload_time_iso_8601": "2025-07-08T10:20:22.672932Z",
"url": "https://files.pythonhosted.org/packages/bf/ae/9ab14d22b0b35aed0b64437fa61fc462b0c040bbdd31caacad93b3fbb95f/jupyter_nbmodel_client-0.13.5-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-07-08 10:20:22",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "datalayer",
"github_project": "jupyter-nbmodel-client",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "jupyter-nbmodel-client"
}