Skip to main content

A tool that writes a NotebookNode object to a file in JSON format, preserving the notebook structure.

Project description

Swarmauri Logo

PyPI - Downloads Hits PyPI - Python Version PyPI - License PyPI - swarmauri_tool_jupyterwritenotebook


Swarmauri Tool · Jupyter Write Notebook

A Swarmauri automation tool that serializes Jupyter NotebookNode objects (or compatible dictionaries) to disk using the nbformat JSON schema. It encapsulates validation, encoding, and integrity checks so pipelines can persist generated notebooks with confidence.

  • Writes notebooks with pretty-printed JSON (indent=2) and ensure_ascii=False for readable diffs and Unicode safety.
  • Performs a read-back verification step to guarantee the file contains valid JSON data.
  • Slots directly into agent workflows via the standard Swarmauri tool registration system.

Requirements

  • Python 3.10 – 3.13.
  • nbformat for working with notebook structures.
  • Dependencies (swarmauri_base, swarmauri_standard, pydantic). These install automatically with the package.

Installation

Choose the installer that matches your workflow—each command pulls transitive dependencies.

pip

pip install swarmauri_tool_jupyterwritenotebook

Poetry

poetry add swarmauri_tool_jupyterwritenotebook

uv

# Add to the active project and update uv.lock
uv add swarmauri_tool_jupyterwritenotebook

# or install into the current environment without modifying pyproject.toml
uv pip install swarmauri_tool_jupyterwritenotebook

Tip: When using uv in this repository, run commands from the repo root so uv can resolve the shared pyproject.toml.

Quick Start

Generate a notebook programmatically and persist it with the tool. The response dictionary includes either a success message and file path or an error string.

from nbformat.v4 import new_notebook, new_markdown_cell, new_code_cell
from swarmauri_tool_jupyterwritenotebook import JupyterWriteNotebookTool

nb = new_notebook(
    cells=[
        new_markdown_cell("# Metrics Report"),
        new_code_cell("print('accuracy:', 0.91)")
    ],
    metadata={
        "kernelspec": {
            "display_name": "Python 3",
            "language": "python",
            "name": "python3"
        }
    }
)

write_notebook = JupyterWriteNotebookTool()
result = write_notebook(notebook_data=nb, output_file="reports/metrics.ipynb")

print(result)
# {'message': 'Notebook written successfully', 'file_path': 'reports/metrics.ipynb'}

Usage Scenarios

Persist Notebook Output From an Agent

from swarmauri_core.agent.Agent import Agent
from swarmauri_standard.tools.registry import ToolRegistry
from swarmauri_tool_jupyterwritenotebook import JupyterWriteNotebookTool

registry = ToolRegistry()
registry.register(JupyterWriteNotebookTool())
agent = Agent(tool_registry=registry)

# Agent actions produce notebook JSON (truncated for brevity)
notebook_payload = {
    "cells": [
        {"cell_type": "code", "source": "print('done')", "metadata": {}, "outputs": []}
    ],
    "metadata": {"kernelspec": {"name": "python3"}},
    "nbformat": 4,
    "nbformat_minor": 5
}

response = agent.tools["JupyterWriteNotebookTool"](
    notebook_data=notebook_payload,
    output_file="runs/output.ipynb"
)
print(response)

Register the tool alongside other Swarmauri components so agents can emit notebooks as part of a conversation or workflow.

Convert Executed Notebooks to Artifacts

import nbformat
from nbformat import NotebookNode
from swarmauri_tool_jupyterwritenotebook import JupyterWriteNotebookTool

# Assume executed_notebook is a NotebookNode returned by nbconvert or papermill
executed_notebook: NotebookNode = nbformat.read("executed.ipynb", as_version=4)
executed_notebook.metadata.setdefault("tags", []).append("validated")

writer = JupyterWriteNotebookTool()
artifact = writer(notebook_data=executed_notebook, output_file="artifacts/executed.ipynb")
print(artifact)

This pattern is useful for CI systems that run notebooks and archive the executed results for review.

Chain With Validation Before Publishing

import nbformat
from swarmauri_tool_jupytervalidatenotebook import JupyterValidateNotebookTool
from swarmauri_tool_jupyterwritenotebook import JupyterWriteNotebookTool

nb = nbformat.read("draft.ipynb", as_version=4)
validate = JupyterValidateNotebookTool()
write = JupyterWriteNotebookTool()

validation = validate(nb)
if validation["valid"] != "True":
    raise RuntimeError(validation["report"])

result = write(notebook_data=nb, output_file="dist/published.ipynb")
print(result)

Validate the notebook schema first, then persist the approved version for distribution.

Troubleshooting

  • An error occurred during notebook write operation – The tool surfaces file-system exceptions verbatim. Check write permissions and ensure the target directory exists.
  • Empty file after execution – Read-back verification triggers when the file cannot be parsed as JSON. Confirm the notebook structure is JSON serializable (e.g., use nbformat helper constructors).
  • Unexpected characters – The tool writes with ensure_ascii=False so non-ASCII text remains intact. If your environment cannot handle UTF-8, pass a different encoding argument.

License

swarmauri_tool_jupyterwritenotebook is released under the Apache 2.0 License. See LICENSE for the full text.

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 Distribution

Built Distribution

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

File details

Details for the file swarmauri_tool_jupyterwritenotebook-0.8.3.dev10.tar.gz.

File metadata

  • Download URL: swarmauri_tool_jupyterwritenotebook-0.8.3.dev10.tar.gz
  • Upload date:
  • Size: 9.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.8 {"installer":{"name":"uv","version":"0.10.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for swarmauri_tool_jupyterwritenotebook-0.8.3.dev10.tar.gz
Algorithm Hash digest
SHA256 e3fe0e2fda98aedd25bc5cf0e6aefeda0452bf9d6a4c1624788c18b581b0aae7
MD5 69b5a0868e2870d68da5b084669a0702
BLAKE2b-256 8f32aea7665357c5301dbcb358e508a70f9561b5d159c88679dcc3ac40ea81c2

See more details on using hashes here.

File details

Details for the file swarmauri_tool_jupyterwritenotebook-0.8.3.dev10-py3-none-any.whl.

File metadata

  • Download URL: swarmauri_tool_jupyterwritenotebook-0.8.3.dev10-py3-none-any.whl
  • Upload date:
  • Size: 10.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.8 {"installer":{"name":"uv","version":"0.10.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for swarmauri_tool_jupyterwritenotebook-0.8.3.dev10-py3-none-any.whl
Algorithm Hash digest
SHA256 6cd32269c6590613d0d621849c596acdc0ae0b0ba2eea6c2a8ec7926c1a896ed
MD5 0a6a686e07434a14a8a78477eec3db7d
BLAKE2b-256 5adfdc4013b2922f382295dce3f3e50b24a3fd5fa7001e51dec0c2197af1c7c9

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