Skip to main content

No project description provided

Project description

Datalayer

Become a Sponsor

Jupyter NbModel Client

Github Actions Status PyPI - Version

Client to interact with a Jupyter Notebook model.

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

  1. Ensure you have the needed packages in your environment to run the example here after.
pip install jupyterlab jupyter-collaboration ipykernel matplotlib
  1. Start a JupyterLab server, setting a port and a token to be reused by the agent, and create a notebook test.ipynb.
jupyter lab --port 8888 --IdentityProvider.token MY_TOKEN
  1. Open a Python REPL and execute the following snippet to add a cell.
from jupyter_nbmodel_client import NbModelClient, get_jupyter_notebook_websocket_url

with NbModelClient(
    get_jupyter_notebook_websocket_url(
        server_url="http://localhost:8888",
        token="MY_TOKEN",
        path="test.ipynb"
    )
) as notebook:
    notebook.add_code_cell("print('hello world')")

Check test.ipynb in JupyterLab.

  1. The previous example does not involve kernels. Put that now in the picture, adding a cell and executing 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:
    async with NbModelClient(
        get_jupyter_notebook_websocket_url(
            server_url="http://localhost:8888",
            token="MY_TOKEN",
            path="test.ipynb"
        )
    ) as notebook:
        cell_index = notebook.add_code_cell("print('hello world')")
        results = notebook.execute_cell(cell_index, kernel)

        assert results["status"] == "ok"
        assert len(results["outputs"]) > 0

Check test.ipynb in JupyterLab.

You can go further and create a plot with 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:
    async with NbModelClient(
        get_jupyter_notebook_websocket_url(
            server_url="http://localhost:8888",
            token="MY_TOKEN",
            path="test.ipynb"
        )
    ) as notebook:
        cell_index = notebook.add_code_cell(CODE)
        results = notebook.execute_cell(cell_index, kernel)

        assert results["status"] == "ok"
        assert len(results["outputs"]) > 0

Check test.ipynb in JupyterLab.

[!NOTE]

Instead of using the clients as context manager, you can call the start() and stop() 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:
    notebook = NbModelClient(
        get_jupyter_notebook_websocket_url(
            server_url="http://localhost:8888",
            token="MY_TOKEN",
            path="test.ipynb"
        )
    )
    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()

[!NOTE] To connect to Datalayer collaborative room, you can use the helper function get_datalayer_websocket_url:

from jupyter_nbmodel_client import NbModelClient, get_datalayer_websocket_url

async with NbModelClient(
    get_datalayer_websocket_url(
        server_url=server,
        room_id=room_id,
        token=token
    )
) as notebook:
    notebook.add_code_cell(CODE)

Uninstall

To remove the library, run the following.

pip uninstall jupyter_nbmodel_client

Contributing

Data models

The following json schema describe the data model used in cells and notebook metadata to communicate between user clients and the ai agent.

{
  "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"]
            }
          }
        }
      }
    }
  }
}

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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jupyter_nbmodel_client-0.11.3.tar.gz (25.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

jupyter_nbmodel_client-0.11.3-py3-none-any.whl (26.1 kB view details)

Uploaded Python 3

File details

Details for the file jupyter_nbmodel_client-0.11.3.tar.gz.

File metadata

  • Download URL: jupyter_nbmodel_client-0.11.3.tar.gz
  • Upload date:
  • Size: 25.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.12

File hashes

Hashes for jupyter_nbmodel_client-0.11.3.tar.gz
Algorithm Hash digest
SHA256 04bb91c3841e35eafb718ee2775a3328d8783ad84212503f76dd8f3780c03cc0
MD5 679045b6b152714cc0bab20f14f623b4
BLAKE2b-256 f0f17ed94fb32aac4a92ac884dd59d2ab2905af13be4d13fe3f22d83a3c80dc5

See more details on using hashes here.

File details

Details for the file jupyter_nbmodel_client-0.11.3-py3-none-any.whl.

File metadata

File hashes

Hashes for jupyter_nbmodel_client-0.11.3-py3-none-any.whl
Algorithm Hash digest
SHA256 9d17fe8db6b7f458e1e5a7b2c25f62c6b3f3d15195194f371f66a49b8428253d
MD5 c7c2ebe74a774b23f1c0e5e898b852bf
BLAKE2b-256 43d9cb3fd242e21f558cdb4b9fd485aea3a0879491c2bb2e9f22aece261a6316

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page