No project description provided
Project description
🪐 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.
pip install jupyter_nbmodel_client
We ask you to take additional actions to overcome limitations and bugs of the pycrdt library.
# Ensure you create a new shell after running the following commands.
pip uninstall -y pycrdt datalayer_pycrdt
pip install datalayer_pycrdt
Usage with Jupyter
- Ensure you have the needed packages in your environment to run the example here after.
pip install jupyterlab jupyter-collaboration matplotlib
- Start a JupyterLab server, setting a
portand atokento be reused by the agent, and create a notebooktest.ipynb.
# make jupyterlab
jupyter lab --port 8888 --ServerApp.port_retries 0 --IdentityProvider.token MY_TOKEN --ServerApp.root_dir ./dev
- Open a IPython (needed for async functions) REPL in a terminal with
ipython(orjupyter console). Execute the following snippet to add a cell in thetest.ipynbnotebook.
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.ipynbin JupyterLab, you should see a cell with contentprint('hello world')appended to the notebook.
- 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.
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.ipynbin JupyterLab. You should see an additional cell with contentprint('hello world')appended to the notebook, but this time the cell is executed, so the output should showhello world.
You can go further and create a plot with eg matplotlib.
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.ipynbin JupyterLab for the cell with the matplotlib.
[!NOTE]
Instead of using the nbmodel clients as context manager, you can call the
start()andstop()methods.
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, you can use the helper function get_datalayer_notebook_websocket_url:
- The
serverishttps://prod1.datalayer.runfor the Datalayer production SaaS. - The
room_idis the id of your notebook shown in the URL browser bar. - The
tokenis the assigned token for the notebook.
All those details can be retrieved from a Notebook sidebar on the Datalayer SaaS.
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.
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 extension installed.
{
"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
# 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:
pip install -e ".[test]"
To run the python tests, use:
pytest
Development uninstall
pip uninstall jupyter_nbmodel_client
Packaging the library
See RELEASE
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file jupyter_nbmodel_client-0.14.1-py3-none-any.whl.
File metadata
- Download URL: jupyter_nbmodel_client-0.14.1-py3-none-any.whl
- Upload date:
- Size: 27.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b1b74dce616d56b77c453cdbf731f478808aac6afabaf4bec2377a2d006230a0
|
|
| MD5 |
e93b57b6ecd28638566af4f713ecd120
|
|
| BLAKE2b-256 |
b1993bd3754ece51f8aa7223d64b11458dc678480d01bc9f6e25e7c8d16905a3
|