API Reference

notebookllm.models

Core data models for notebookllm — universal notebook representation.

Defines a format-agnostic intermediate representation (CIR) for notebooks. Every format loader and dumper converts to/from these models, providing a single, type-safe API across all supported notebook formats.

Key classes:
  • NotebookDocument: Top-level notebook container.

  • Cell: A single cell (code, markdown, or raw).

  • CellOutput: Execution output from a code cell.

  • CellType: Enum distinguishing code / markdown / raw cells.

  • OutputMode: AI Agent text verbosity levels.

class notebookllm.models.CellType(*values)[source]

Bases: Enum

Type of a notebook cell.

Each cell in a notebook is one of these three types:

  • CODE: Executable code cell (Python, R, Julia, SQL, etc.)

  • MARKDOWN: Formatted text / documentation cell.

  • RAW: Unformatted text (passthrough, not executed).

Usage:

>>> CellType.CODE
<CellType.CODE: 'code'>
>>> CellType("markdown")
<CellType.MARKDOWN: 'markdown'>
CODE = 'code'
MARKDOWN = 'markdown'
RAW = 'raw'
class notebookllm.models.OutputMode(*values)[source]

Bases: Enum

AI Agent output verbosity mode for NotebookDocument.to_text().

Controls how much detail is included in the Agent-optimized plain-text representation of a notebook.

Levels (increasing verbosity):

MINIMAL

Cell markers (# %% [type]) + source code only. Cleanest for Agent input — ideal for high-level analysis.

STANDARD

Adds execution count and cell metadata tags — useful for understanding notebook execution history.

FULL

Adds cell execution outputs (stdout, stderr, rich display data, error tracebacks) — complete picture of notebook state.

MINIMAL = 'minimal'
STANDARD = 'standard'
FULL = 'full'
class notebookllm.models.CellOutput(output_type, content, name=None)[source]

Bases: object

Represents output from a single code-cell execution.

Stores one piece of output — a stream chunk, a rich display result, or an error traceback.

Attributes:
output_type: The kind of output ("stream", "execute_result",

"display_data", or "error").

content: The output content. For stream output this is plain text.

For execute_result / display_data it may be a MIME-bundle dict (e.g. {"text/plain": "...", "image/png": "..."}).

name: Stream name — "stdout" or "stderr". Only set when

output_type == "stream".

Parameters:
output_type: str
content: str | dict
name: str | None = None
class notebookllm.models.Cell(cell_type, source, execution_count=None, outputs=<factory>, metadata=<factory>, cell_id=None, language=None, block_type=None, block_group=None, content_hash=None, sorting_key=None)[source]

Bases: object

Universal cell representation — format-agnostic.

A single notebook cell, storing its type, source code, execution metadata, and optional format-specific fields (e.g. Deepnote block metadata, language tag).

This is the building block of NotebookDocument. Every format loader produces Cell instances and every dumper consumes them.

Attributes:

cell_type: Whether this is code, markdown, or raw. source: The cell’s text content (code or markdown). execution_count: Execution counter (None if never run). outputs: List of CellOutput objects (code cells only). metadata: Arbitrary key-value metadata (tags, cell-level options). cell_id: Unique cell identifier (UUID string), auto-generated when needed. language: Programming language (e.g. "python", "r", "sql", "julia"). block_type: Format-specific block type (Deepnote: sql, visualization, input, etc.). block_group: Deepnote blockGroup UUID for grouped blocks. content_hash: Deepnote SHA-256 content hash (first 16 hex chars). sorting_key: Deepnote base-36 sorting key for block ordering.

Parameters:
  • cell_type (CellType)

  • source (str)

  • execution_count (int | None)

  • outputs (list[CellOutput])

  • metadata (dict)

  • cell_id (str | None)

  • language (str | None)

  • block_type (str | None)

  • block_group (str | None)

  • content_hash (str | None)

  • sorting_key (str | None)

cell_type: CellType
source: str
execution_count: int | None = None
outputs: list[CellOutput]
metadata: dict
cell_id: str | None = None
language: str | None = None
block_type: str | None = None
block_group: str | None = None
content_hash: str | None = None
sorting_key: str | None = None
class notebookllm.models.NotebookDocument(cells=<factory>, metadata=<factory>, kernel_name=None, language='python', source_format=None)[source]

Bases: object

Universal notebook representation — format-agnostic.

The central data structure of notebookllm. Every format loader produces a NotebookDocument and every dumper consumes one.

NotebookDocument provides the public API for reading, editing, searching, converting, and token-analyzing notebooks.

Attributes:

cells: Ordered list of Cell objects. metadata: Notebook-level metadata (kernel spec, language info, Deepnote settings, etc.). kernel_name: Name of the Jupyter kernel (e.g. "python3"). language: Primary language ("python", "r"). Defaults to "python". source_format: Format loaded from or dumped to ("ipynb", "quarto", "marimo").

Parameters:
cells: list[Cell]
metadata: dict
kernel_name: str | None = None
language: str = 'python'
source_format: str | None = None
to_json()[source]

Serialize the notebook to a JSON string.

The output includes a _cir_version field for forward-compatible deserialization.

Returns:

Indented JSON string.

Return type:

str

classmethod from_json(json_str)[source]

Deserialize a JSON string back into a NotebookDocument.

Version-tolerant — unknown keys are silently ignored so newer serialized documents can be read by older code.

Args:

json_str: A JSON string produced by to_json().

Returns:

A new NotebookDocument instance.

Parameters:

json_str (str)

Return type:

NotebookDocument

classmethod from_file(filepath)[source]

Load a notebook from a file. Auto-detects format.

This is a convenience wrapper around notebookllm.load_file().

Args:

filepath: Path to the notebook file.

Returns:

A NotebookDocument with the loaded content.

Raises:
ValueError: If the format cannot be detected from the file

extension or content.

Parameters:

filepath (str | Path)

Return type:

NotebookDocument

to_file(filepath, fmt=None)[source]

Save the notebook to a file.

Auto-detects the output format from the file extension unless fmt is explicitly provided.

Args:

filepath: Destination file path. fmt: Output format override (e.g. "ipynb"). If None, inferred from extension.

Parameters:
Return type:

None

to_text(mode=OutputMode.MINIMAL, *, max_tokens=None)[source]

Convert the notebook to Agent-optimized plain text.

The output format uses # %% [type] markers for cell boundaries. The verbosity is controlled by the mode parameter.

Args:

mode: Output verbosity. Defaults to OutputMode.MINIMAL. max_tokens: Token budget for token-budget mode (drops lowest-priority cells).

Returns:

Plain text representation of the notebook.

Parameters:
Return type:

str

classmethod from_text(text, source_format=None)[source]

Parse plain text into a NotebookDocument.

When source_format is None, the format is auto-detected by content sniffing (see notebookllm.utils.detect.detect_text_format()).

Args:

text: The plain text content to parse. source_format: Explicit format hint or None for auto-detect.

Returns:

A new NotebookDocument.

Parameters:
  • text (str)

  • source_format (str | None)

Return type:

NotebookDocument

filter_cells(cell_type=None, query=None)[source]

Filter cells by type and/or content query.

Args:

cell_type: If set, only return cells of this type. query: If set, only return cells whose source contains this string (case-insensitive).

Returns:

Filtered list of Cell objects.

Parameters:
Return type:

list[Cell]

get_cell(index)[source]

Get a cell by its index.

Args:

index: Zero-based cell index.

Returns:

The Cell at that index.

Raises:

IndexError: If index is out of range.

Parameters:

index (int)

Return type:

Cell

add_cell(cell, position=None)[source]

Add a cell to the notebook.

Args:

cell: The Cell to add. position: Insertion index. If None, the cell is appended at the end.

Raises:

IndexError: If position is out of range.

Parameters:
  • cell (Cell)

  • position (int | None)

Return type:

None

edit_cell(index, source, cell_type=None)[source]

Edit a cell’s source and optionally change its type.

Args:

index: Index of the cell to edit. source: New source text. cell_type: If set, change the cell’s type.

Raises:

IndexError: If index is out of range.

Parameters:
Return type:

None

delete_cell(index)[source]

Delete a cell by index.

Args:

index: Index of the cell to remove.

Raises:

IndexError: If index is out of range.

Parameters:

index (int)

Return type:

None

move_cell(from_index, to_index)[source]

Move a cell from one position to another.

Args:

from_index: Current index of the cell. to_index: Target index. If beyond the end, the cell is placed at the end.

Raises:

IndexError: If from_index is out of range.

Parameters:
  • from_index (int)

  • to_index (int)

Return type:

None

search(query, cell_type=None)[source]

Search cells by content (case-insensitive substring match).

Args:

query: The search string. cell_type: If set, only search cells of this type.

Returns:

List of (index, cell) tuples for cells whose source contains the query string.

Parameters:
Return type:

list[tuple[int, Cell]]

token_breakdown(mode=OutputMode.MINIMAL)[source]

Get a token usage breakdown for this notebook.

Analyzes every cell in the notebook and returns per-cell and total token counts for the given output mode.

Args:
mode: Output verbosity mode to use for counting. Defaults to

OutputMode.MINIMAL.

Returns:

A NotebookTokenReport with per-cell and total token counts.

Parameters:

mode (OutputMode)

Return type:

NotebookTokenReport

class notebookllm.models.CellType(*values)[source]

Bases: Enum

Type of a notebook cell.

Each cell in a notebook is one of these three types:

  • CODE: Executable code cell (Python, R, Julia, SQL, etc.)

  • MARKDOWN: Formatted text / documentation cell.

  • RAW: Unformatted text (passthrough, not executed).

Usage:

>>> CellType.CODE
<CellType.CODE: 'code'>
>>> CellType("markdown")
<CellType.MARKDOWN: 'markdown'>
CODE = 'code'
MARKDOWN = 'markdown'
RAW = 'raw'
class notebookllm.models.OutputMode(*values)[source]

Bases: Enum

AI Agent output verbosity mode for NotebookDocument.to_text().

Controls how much detail is included in the Agent-optimized plain-text representation of a notebook.

Levels (increasing verbosity):

MINIMAL

Cell markers (# %% [type]) + source code only. Cleanest for Agent input — ideal for high-level analysis.

STANDARD

Adds execution count and cell metadata tags — useful for understanding notebook execution history.

FULL

Adds cell execution outputs (stdout, stderr, rich display data, error tracebacks) — complete picture of notebook state.

MINIMAL = 'minimal'
STANDARD = 'standard'
FULL = 'full'
class notebookllm.models.CellOutput(output_type, content, name=None)[source]

Bases: object

Represents output from a single code-cell execution.

Stores one piece of output — a stream chunk, a rich display result, or an error traceback.

Attributes:
output_type: The kind of output ("stream", "execute_result",

"display_data", or "error").

content: The output content. For stream output this is plain text.

For execute_result / display_data it may be a MIME-bundle dict (e.g. {"text/plain": "...", "image/png": "..."}).

name: Stream name — "stdout" or "stderr". Only set when

output_type == "stream".

Parameters:
output_type: str
content: str | dict
name: str | None = None
class notebookllm.models.Cell(cell_type, source, execution_count=None, outputs=<factory>, metadata=<factory>, cell_id=None, language=None, block_type=None, block_group=None, content_hash=None, sorting_key=None)[source]

Bases: object

Universal cell representation — format-agnostic.

A single notebook cell, storing its type, source code, execution metadata, and optional format-specific fields (e.g. Deepnote block metadata, language tag).

This is the building block of NotebookDocument. Every format loader produces Cell instances and every dumper consumes them.

Attributes:

cell_type: Whether this is code, markdown, or raw. source: The cell’s text content (code or markdown). execution_count: Execution counter (None if never run). outputs: List of CellOutput objects (code cells only). metadata: Arbitrary key-value metadata (tags, cell-level options). cell_id: Unique cell identifier (UUID string), auto-generated when needed. language: Programming language (e.g. "python", "r", "sql", "julia"). block_type: Format-specific block type (Deepnote: sql, visualization, input, etc.). block_group: Deepnote blockGroup UUID for grouped blocks. content_hash: Deepnote SHA-256 content hash (first 16 hex chars). sorting_key: Deepnote base-36 sorting key for block ordering.

Parameters:
  • cell_type (CellType)

  • source (str)

  • execution_count (int | None)

  • outputs (list[CellOutput])

  • metadata (dict)

  • cell_id (str | None)

  • language (str | None)

  • block_type (str | None)

  • block_group (str | None)

  • content_hash (str | None)

  • sorting_key (str | None)

cell_type: CellType
source: str
execution_count: int | None = None
outputs: list[CellOutput]
metadata: dict
cell_id: str | None = None
language: str | None = None
block_type: str | None = None
block_group: str | None = None
content_hash: str | None = None
sorting_key: str | None = None
class notebookllm.models.NotebookDocument(cells=<factory>, metadata=<factory>, kernel_name=None, language='python', source_format=None)[source]

Bases: object

Universal notebook representation — format-agnostic.

The central data structure of notebookllm. Every format loader produces a NotebookDocument and every dumper consumes one.

NotebookDocument provides the public API for reading, editing, searching, converting, and token-analyzing notebooks.

Attributes:

cells: Ordered list of Cell objects. metadata: Notebook-level metadata (kernel spec, language info, Deepnote settings, etc.). kernel_name: Name of the Jupyter kernel (e.g. "python3"). language: Primary language ("python", "r"). Defaults to "python". source_format: Format loaded from or dumped to ("ipynb", "quarto", "marimo").

Parameters:
cells: list[Cell]
metadata: dict
kernel_name: str | None = None
language: str = 'python'
source_format: str | None = None
to_json()[source]

Serialize the notebook to a JSON string.

The output includes a _cir_version field for forward-compatible deserialization.

Returns:

Indented JSON string.

Return type:

str

classmethod from_json(json_str)[source]

Deserialize a JSON string back into a NotebookDocument.

Version-tolerant — unknown keys are silently ignored so newer serialized documents can be read by older code.

Args:

json_str: A JSON string produced by to_json().

Returns:

A new NotebookDocument instance.

Parameters:

json_str (str)

Return type:

NotebookDocument

classmethod from_file(filepath)[source]

Load a notebook from a file. Auto-detects format.

This is a convenience wrapper around notebookllm.load_file().

Args:

filepath: Path to the notebook file.

Returns:

A NotebookDocument with the loaded content.

Raises:
ValueError: If the format cannot be detected from the file

extension or content.

Parameters:

filepath (str | Path)

Return type:

NotebookDocument

to_file(filepath, fmt=None)[source]

Save the notebook to a file.

Auto-detects the output format from the file extension unless fmt is explicitly provided.

Args:

filepath: Destination file path. fmt: Output format override (e.g. "ipynb"). If None, inferred from extension.

Parameters:
Return type:

None

to_text(mode=OutputMode.MINIMAL, *, max_tokens=None)[source]

Convert the notebook to Agent-optimized plain text.

The output format uses # %% [type] markers for cell boundaries. The verbosity is controlled by the mode parameter.

Args:

mode: Output verbosity. Defaults to OutputMode.MINIMAL. max_tokens: Token budget for token-budget mode (drops lowest-priority cells).

Returns:

Plain text representation of the notebook.

Parameters:
Return type:

str

classmethod from_text(text, source_format=None)[source]

Parse plain text into a NotebookDocument.

When source_format is None, the format is auto-detected by content sniffing (see notebookllm.utils.detect.detect_text_format()).

Args:

text: The plain text content to parse. source_format: Explicit format hint or None for auto-detect.

Returns:

A new NotebookDocument.

Parameters:
  • text (str)

  • source_format (str | None)

Return type:

NotebookDocument

filter_cells(cell_type=None, query=None)[source]

Filter cells by type and/or content query.

Args:

cell_type: If set, only return cells of this type. query: If set, only return cells whose source contains this string (case-insensitive).

Returns:

Filtered list of Cell objects.

Parameters:
Return type:

list[Cell]

get_cell(index)[source]

Get a cell by its index.

Args:

index: Zero-based cell index.

Returns:

The Cell at that index.

Raises:

IndexError: If index is out of range.

Parameters:

index (int)

Return type:

Cell

add_cell(cell, position=None)[source]

Add a cell to the notebook.

Args:

cell: The Cell to add. position: Insertion index. If None, the cell is appended at the end.

Raises:

IndexError: If position is out of range.

Parameters:
  • cell (Cell)

  • position (int | None)

Return type:

None

edit_cell(index, source, cell_type=None)[source]

Edit a cell’s source and optionally change its type.

Args:

index: Index of the cell to edit. source: New source text. cell_type: If set, change the cell’s type.

Raises:

IndexError: If index is out of range.

Parameters:
Return type:

None

delete_cell(index)[source]

Delete a cell by index.

Args:

index: Index of the cell to remove.

Raises:

IndexError: If index is out of range.

Parameters:

index (int)

Return type:

None

move_cell(from_index, to_index)[source]

Move a cell from one position to another.

Args:

from_index: Current index of the cell. to_index: Target index. If beyond the end, the cell is placed at the end.

Raises:

IndexError: If from_index is out of range.

Parameters:
  • from_index (int)

  • to_index (int)

Return type:

None

search(query, cell_type=None)[source]

Search cells by content (case-insensitive substring match).

Args:

query: The search string. cell_type: If set, only search cells of this type.

Returns:

List of (index, cell) tuples for cells whose source contains the query string.

Parameters:
Return type:

list[tuple[int, Cell]]

token_breakdown(mode=OutputMode.MINIMAL)[source]

Get a token usage breakdown for this notebook.

Analyzes every cell in the notebook and returns per-cell and total token counts for the given output mode.

Args:
mode: Output verbosity mode to use for counting. Defaults to

OutputMode.MINIMAL.

Returns:

A NotebookTokenReport with per-cell and total token counts.

Parameters:

mode (OutputMode)

Return type:

NotebookTokenReport

notebookllm.loaders

Format auto-detection and dispatch — entry points for loading and dumping notebooks.

This module provides the public functions for reading and writing notebooks:

  • load_file(): Load a notebook from a file path (auto-detects format).

  • dump_file(): Save a notebook to a file (auto-detects format from extension).

  • loads_text(): Parse a string into a notebook (auto-detects format from content).

Each function dispatches to the appropriate format-specific loader or dumper based on the detected format.

notebookllm.loaders.load_file(filepath)[source]

Load a notebook from a file. Auto-detects format from the file extension.

Supported formats (auto-detected by extension):

  • .ipynb — Jupyter Notebook

  • .py — Percent script (# %%) or Marimo (@app.cell)

  • .qmd — Quarto document

  • .md — Markdown with fenced code blocks

  • .rmd — R Markdown

  • .deepnote — Deepnote YAML project

Args:

filepath: Path to the notebook file.

Returns:

A NotebookDocument.

Raises:

ValueError: If the format cannot be detected from the extension.

Parameters:

filepath (str | Path)

Return type:

NotebookDocument

notebookllm.loaders.dump_file(doc, filepath, fmt=None)[source]

Dump a notebook to a file. Auto-detects format from extension or uses fmt.

Args:

doc: The notebook to serialize. filepath: Destination file path. fmt: Output format override. If None, inferred from the file extension.

Raises:

ValueError: If the format is not supported.

Parameters:
Return type:

None

notebookllm.loaders.loads_text(text, source_format=None)[source]

Load a notebook from a string. Auto-detects format if not specified.

Args:

text: The raw text content to parse. source_format: Explicit format hint. If None, auto-detected by content sniffing.

Returns:

A NotebookDocument.

Raises:

ValueError: If the format is not supported or cannot be detected.

Parameters:
  • text (str)

  • source_format (str | None)

Return type:

NotebookDocument

Percent format loader/dumper — .py files with # %% cell markers.

Percent-format scripts (also called “cell mode” or “VS Code interactive”) use # %% comments as cell delimiters. This is the native format for VS Code’s Python Interactive window, Spyder, and PyCharm Scientific Mode.

Markdown cells are encoded as #-prefixed comment lines.

Example:

# %% [markdown]
# This is a markdown cell.
# It explains what follows.

# %% [code]
import pandas as pd
print("hello")

The loader correctly handles triple-quoted strings (""" and ''') by ignoring # %% markers that appear inside docstrings.

class notebookllm.loaders.percent.PercentLoader[source]

Bases: BaseLoader

Load percent-format .py files with # %% cell markers.

Detects cell boundaries by # %% markers. Markdown cells are identified by the [markdown] tag in the marker line. Supports triple-quoted strings ('"""' and ''') — markers inside docstrings are ignored.

load(source)[source]

Load a percent-format notebook from a file path.

Args:

source: Path to the .py file.

Returns:

A NotebookDocument.

Parameters:

source (str | Path)

Return type:

NotebookDocument

loads(content)[source]

Load a percent-format notebook from a string.

Args:

content: Raw percent-format source code.

Returns:

A NotebookDocument.

Parameters:

content (str)

Return type:

NotebookDocument

class notebookllm.loaders.percent.PercentDumper[source]

Bases: BaseDumper

Dump NotebookDocument to percent format.

Code cells are output with # %% [code] markers. Markdown cells use # %% [markdown] markers with content encoded as #-prefixed comment lines.

dump(doc, filepath=None)[source]

Serialize a notebook to percent-format .py.

Args:

doc: The notebook to serialize. filepath: If provided, write the output to this file.

Returns:

Percent-format source code as a string.

Parameters:
Return type:

str

ipynb loader/dumper — Jupyter notebook format (.ipynb).

Uses nbformat for files under 10 MB and ijson streaming for larger files to avoid loading the entire JSON into memory. Falls back to nbformat if ijson is not installed.

Handles all standard Jupyter cell types (code, markdown, raw), preserves cell IDs, execution counts, metadata, and all output types (stream, execute_result, display_data, error with rich MIME bundles).

class notebookllm.loaders.ipynb.IpynbLoader[source]

Bases: BaseLoader

Load .ipynb files into NotebookDocument.

For files smaller than streaming_threshold, uses nbformat (fast, full in-memory parsing). For larger files, uses ijson to stream-parse cells one at a time, keeping memory usage low.

Falls back to nbformat if ijson is not installed.

streaming_threshold: int = 10485760
load(source)[source]

Load a .ipynb file from disk.

Args:

source: Path to the .ipynb file.

Returns:

A NotebookDocument.

Parameters:

source (str | Path)

Return type:

NotebookDocument

loads(content)[source]

Load a .ipynb notebook from a JSON string.

Args:

content: The raw JSON content of a .ipynb file.

Returns:

A NotebookDocument.

Parameters:

content (str)

Return type:

NotebookDocument

class notebookllm.loaders.ipynb.IpynbDumper[source]

Bases: BaseDumper

Dump NotebookDocument to .ipynb format.

Produces standard Jupyter notebook JSON, compatible with JupyterLab, VS Code, and nbformat v4.

dump(doc, filepath=None)[source]

Serialize a notebook to .ipynb JSON.

Args:

doc: The notebook to serialize. filepath: If provided, write the output to this file.

Returns:

The .ipynb JSON string.

Parameters:
Return type:

str

Marimo format loader/dumper — .py files with @app.cell decorators.

Marimo (https://marimo.io) is a reactive Python notebook that stores notebooks as standard Python files. Cells are defined as functions decorated with @app.cell. Markdown cells are represented as mo.md("...") calls inside code cells.

The loader uses AST parsing to extract cell bodies, detects mo.md() calls to identify markdown cells, and reads the __generated_with version from module-level assignments.

class notebookllm.loaders.marimo.MarimoLoader[source]

Bases: BaseLoader

Load marimo-format .py files using AST parsing.

Parses the Python AST to find functions decorated with @app.cell, extracts their source code, and detects mo.md() calls to identify markdown cells. Also extracts the __generated_with version from module-level assignments.

load(source)[source]

Load a marimo notebook from a file path.

Args:

source: Path to the marimo .py file.

Returns:

A NotebookDocument.

Parameters:

source (str | Path)

Return type:

NotebookDocument

loads(content)[source]

Load a marimo notebook from a string.

Args:

content: Raw marimo source code.

Returns:

A NotebookDocument.

Parameters:

content (str)

Return type:

NotebookDocument

class notebookllm.loaders.marimo.MarimoDumper[source]

Bases: BaseDumper

Dump NotebookDocument to marimo format.

Produces a valid marimo .py file with @app.cell decorators. Markdown cells are wrapped in mo.md() calls.

dump(doc, filepath=None)[source]

Serialize a notebook to marimo format.

Args:

doc: The notebook to serialize. filepath: If provided, write the output to this file.

Returns:

The marimo-format source code as a string.

Parameters:
Return type:

str

Quarto format loader/dumper — .qmd files with YAML frontmatter and fenced code blocks.

Quarto (https://quarto.org) is an open-source scientific and technical publishing system. Notebooks use .qmd files with:

  • Optional --- YAML frontmatter for document metadata.

  • Markdown text cells between code blocks.

  • ```{python}`` / ```{r}` fenced code blocks with optional #| cell options (e.g., #| echo: false, #| fig-width: 8).

The loader preserves cell-level options in cell metadata under the quarto_options key.

class notebookllm.loaders.quarto.QuartoLoader[source]

Bases: BaseLoader

Load Quarto .qmd files.

Parses YAML frontmatter, markdown text between code blocks, and fenced code blocks with their language tags and #| cell options.

load(source)[source]

Load a Quarto file from disk.

Args:

source: Path to the .qmd file.

Returns:

A NotebookDocument.

Parameters:

source (str | Path)

Return type:

NotebookDocument

loads(content)[source]

Load a Quarto notebook from a string.

Args:

content: Raw .qmd content.

Returns:

A NotebookDocument.

Parameters:

content (str)

Return type:

NotebookDocument

class notebookllm.loaders.quarto.QuartoDumper[source]

Bases: BaseDumper

Dump NotebookDocument to Quarto .qmd format.

Preserves YAML frontmatter, cell language tags, and #| cell options.

dump(doc, filepath=None)[source]

Serialize a notebook to Quarto format.

Args:

doc: The notebook to serialize. filepath: If provided, write the output to this file.

Returns:

The .qmd content as a string.

Parameters:
Return type:

str

Markdown format loader/dumper — .md files with fenced code blocks.

Loads and saves notebooks as standard Markdown files. Code cells are stored as fenced code blocks with language tags (e.g., ```python`, ```r```). Markdown cells are stored as plain markdown text.

Supports optional YAML frontmatter. Code blocks with known languages (python, r, julia, javascript, typescript) become CODE cells; others become RAW.

class notebookllm.loaders.markdown.MarkdownLoader[source]

Bases: BaseLoader

Load Markdown files with embedded fenced code blocks.

Code blocks with known languages (python, r, julia, javascript, etc.) are treated as CODE cells. Other language blocks become RAW cells.

load(source)[source]

Load a Markdown notebook from a file.

Args:

source: Path to the .md file.

Returns:

A NotebookDocument.

Parameters:

source (str | Path)

Return type:

NotebookDocument

loads(content)[source]

Load a Markdown notebook from a string.

Args:

content: Raw markdown content.

Returns:

A NotebookDocument.

Parameters:

content (str)

Return type:

NotebookDocument

class notebookllm.loaders.markdown.MarkdownDumper[source]

Bases: BaseDumper

Dump NotebookDocument to Markdown format.

Code cells are written as fenced code blocks with language tags. Markdown cells are written as plain text.

dump(doc, filepath=None)[source]

Serialize a notebook to Markdown format.

Args:

doc: The notebook to serialize. filepath: If provided, write the output to this file.

Returns:

The markdown content as a string.

Parameters:
Return type:

str

R Markdown format loader/dumper — .Rmd files with R and Python code blocks.

R Markdown is a variant of Markdown used by RStudio and the rmarkdown package. Code blocks use the ```{language}` syntax (same as Quarto) and support R, Python, Julia, and other languages.

See: https://rmarkdown.rstudio.com

The loader distinguishes between R and Python code cells by setting the language field in cell metadata, enabling bidirectional conversion between R Markdown and other notebook formats.

class notebookllm.loaders.rmarkdown.RMarkdownLoader[source]

Bases: BaseLoader

Load R Markdown files with embedded R and Python code blocks.

R code blocks (```{r}`) are stored with language="r". Python and other languages are recognized similarly. Unknown languages become RAW cells.

load(source)[source]

Load an R Markdown file from disk.

Args:

source: Path to the .Rmd file.

Returns:

A NotebookDocument.

Parameters:

source (str | Path)

Return type:

NotebookDocument

loads(content)[source]

Load an R Markdown notebook from a string.

Args:

content: Raw .Rmd content.

Returns:

A NotebookDocument.

Parameters:

content (str)

Return type:

NotebookDocument

class notebookllm.loaders.rmarkdown.RMarkdownDumper[source]

Bases: BaseDumper

Dump NotebookDocument to R Markdown format.

Produces .Rmd output with ```{language}` fenced code blocks.

dump(doc, filepath=None)[source]

Serialize a notebook to R Markdown format.

Args:

doc: The notebook to serialize. filepath: If provided, write the output to this file.

Returns:

The .Rmd content as a string.

Parameters:
Return type:

str

Script format dumper — flat .py without cell markers.

Converts notebooks to standalone Python scripts: code cells become code, markdown/raw cells become #-prefixed comments. This is a one-way export format (no loader) — cell boundaries cannot be reconstructed from a flat script.

Use this format when you need a plain Python file that can be run directly without any notebook-aware tooling.

Example output:

# %% original cell
# This was a markdown cell
x = 1
print(x)
class notebookllm.loaders.script.ScriptDumper[source]

Bases: BaseDumper

Dump NotebookDocument to flat .py format.

Code cells become Python code. Markdown and raw cells become #-prefixed comments. All cell boundaries are lost — this format cannot be loaded back.

dump(doc, filepath=None)[source]

Serialize a notebook to a flat script.

Args:

doc: The notebook to serialize. filepath: If provided, write the output to this file.

Returns:

The flat script content as a string.

Parameters:
Return type:

str

Deepnote YAML loader/dumper — .deepnote project format.

Deepnote (https://deepnote.com) is a collaborative data science platform. Projects are stored as YAML files with a rich block-based structure that includes code, markdown, SQL, charts, visualizations, and more.

Maps Deepnote blocks onto the universal Cell model, preserving Deepnote-specific fields like block_type, block_group, content_hash, and sorting_key.

Supports custom block types: sql, chart, input, visualization, big_number, data_frame_viewer, divider, rich_text — all mapped to the appropriate CellType.

class notebookllm.loaders.deepnote.DeepnoteLoader[source]

Bases: BaseLoader

Load .deepnote YAML project files.

Reads the Deepnote YAML structure, iterates over notebooks and their blocks, and converts each block to a Cell. Preserves Deepnote-specific metadata (block groups, content hashes, sorting keys) on the Cell objects.

load(source)[source]

Load a Deepnote YAML file from disk.

Args:

source: Path to the .deepnote file.

Returns:

A NotebookDocument.

Parameters:

source (str | Path)

Return type:

NotebookDocument

loads(content)[source]

Load a Deepnote project from a YAML string.

Args:

content: The raw YAML content.

Returns:

A NotebookDocument.

Parameters:

content (str)

Return type:

NotebookDocument

class notebookllm.loaders.deepnote.DeepnoteDumper[source]

Bases: BaseDumper

Dump NotebookDocument to Deepnote YAML format.

Groups cells by notebook_name metadata, sorts blocks by sorting_key, and produces a valid Deepnote project YAML file.

dump(doc, filepath=None)[source]

Serialize a notebook to Deepnote YAML format.

Args:

doc: The notebook to serialize. filepath: If provided, write the output to this file.

Returns:

The Deepnote YAML content as a string.

Parameters:
Return type:

str

Abstract base classes for format loaders and dumpers.

Every supported notebook format provides a pair of classes:

  • Loader: Reads a file (or string) in that format and produces a NotebookDocument.

  • Dumper: Takes a NotebookDocument and serializes it to the format’s text representation, optionally writing to a file.

New format support is added by subclassing BaseLoader and BaseDumper and registering the loader/dumper in notebookllm.loaders.

class notebookllm.loaders.base.BaseLoader[source]

Bases: ABC

Abstract base class for notebook format loaders.

Subclasses must implement:

  • load() — load from a file path.

  • loads() — load from a string.

abstractmethod load(source)[source]

Load a notebook from a file path.

Args:

source: Path to the notebook file.

Returns:

A NotebookDocument instance.

Parameters:

source (str | Path)

Return type:

NotebookDocument

abstractmethod loads(content)[source]

Load a notebook from a string.

Args:

content: The raw text content of the notebook.

Returns:

A NotebookDocument instance.

Parameters:

content (str)

Return type:

NotebookDocument

class notebookllm.loaders.base.BaseDumper[source]

Bases: ABC

Abstract base class for notebook format dumpers.

Subclasses must implement dump().

abstractmethod dump(doc, filepath=None)[source]

Serialize a notebook to the target format.

Args:

doc: The notebook to serialize. filepath: If provided, serialized content is written to this file.

Returns:

The serialized notebook as a string.

Parameters:
Return type:

str

notebookllm.converters

AI Agent Optimizer — converts NotebookDocument to Agent-optimized plain text.

Produces clean, token-efficient text representations of notebooks designed for AI Agent consumption. Supports four output modes (minimal, standard, full) with different verbosity levels and an optional token budget that automatically drops low-priority cells to fit within context limits.

class notebookllm.converters.llm_optimizer.LLMOptimizer(mode=OutputMode.MINIMAL, include_cell_markers=True, max_line_length=None, summarize_outputs=False, max_tokens=None)[source]

Bases: object

Converts NotebookDocument to Agent-optimized text.

Produces a clean, structured text format with # %% [type] cell markers, optionally including metadata and execution outputs. When a token budget is set, intelligently drops lowest-value cells first to stay within the limit.

Drop priority (highest-value cells kept longest):

  1. Markdown cells (explanatory — most valuable for Agent understanding)

  2. Code cells with outputs (executed, have results)

  3. Code cells without outputs (scaffolding — dropped first)

Parameters:
  • mode (OutputMode) – Output verbosity mode. Defaults to MINIMAL.

  • include_cell_markers (bool) – Whether to include # %% [type] markers between cells.

  • max_line_length (int | None) – If set, truncate source lines to this length.

  • summarize_outputs (bool) – Replace long and rich outputs (DataFrames, images, tracebacks) with compressed one-line summaries.

  • max_tokens (int | None) – If set, trim the result to fit within this many tokens by dropping lowest-priority cells first. Token counting uses a simple len(text) // 4 heuristic.

optimize(doc)[source]

Produce optimized text, optionally constrained by token budget.

Args:

doc: The notebook to optimize.

Returns:

The optimized plain text representation.

Parameters:

doc (NotebookDocument)

Return type:

str

notebookllm.cli.commands

Command-Line Interface commands are documented on the dedicated CLI Reference page.

notebookllm.mcp

MCP server for notebookllm — exposes notebook operations via the Model Context Protocol.

Provides a FastMCP-based server that allows AI Agent clients (Claude Desktop, VS Code, Zed, Cursor, Claude Code, etc.) to load, create, edit, search, execute, and convert notebooks programmatically.

The server manages sessions via SessionManager (SQLite-persisted, thread-safe) and kernel lifecycle via KernelPool (async, thread-pooled).

Features: - 20+ MCP tools with aliases for backward compatibility - 3 URI resource templates for notebook/cell access - 3 prompt templates (summarize, review, explain) - Automatic session eviction at 100 concurrent sessions - Optional SSE transport for remote connections

notebookllm.mcp.server.create_app(session_manager=None)[source]

Create and configure the FastMCP server app.

Registers all MCP tools, resources, and prompts on the app instance. Also registers backward-compatible aliases for tools that had different names in the old notebookllm-mcp package.

Args:
session_manager: An optional session manager instance. If not

provided, a new one is created.

Returns:

A configured FastMCP app.

Parameters:

session_manager (SessionManager | None)

notebookllm.mcp.server.main(transport='stdio')[source]

Run the MCP server.

Args:

transport: Transport type — "stdio" (default) or "sse".

Parameters:

transport (str)

Return type:

None

Session manager for MCP server — SQLite-backed persistent notebook sessions.

Provides SessionManager, which stores NotebookDocument instances in both an in-memory cache and a local SQLite database. Sessions survive server restarts and are auto-evicted (oldest first) when the maximum count of 100 is exceeded.

The database is stored at ~/.local/share/notebookllm/sessions.db (or the XDG_DATA_HOME equivalent) and uses WAL mode for concurrent access safety.

Thread safety is ensured via a threading.Lock on all mutations.

class notebookllm.mcp.session.Session(doc, filepath=None, kernel_manager=None, kernel_client=None)[source]

Bases: object

A single user session holding a notebook document.

Attributes:

doc: The notebook document for this session. filepath: Optional filepath (loaded from or saved to). kernel_manager: Jupyter kernel manager (set when kernel is started). kernel_client: Jupyter kernel client (set when kernel is started).

Parameters:
doc: NotebookDocument
filepath: str | None = None
kernel_manager: Any = None
kernel_client: Any = None
class notebookllm.mcp.session.SessionManager(db_path=None)[source]

Bases: object

Manages notebook sessions for MCP connections.

Sessions are persisted in SQLite (documents serialized via NotebookDocument.to_json() / NotebookDocument.from_json()) and cached in memory for fast access. In-memory state (kernel_client, filepath) is NOT persisted to SQLite — only the NotebookDocument is.

Args:
db_path: Path to the SQLite database. Defaults to the XDG data

directory (see _get_db_path()).

Parameters:

db_path (str | Path | None)

store(session_id, doc, filepath=None)[source]

Store or replace a notebook session (persisted to SQLite).

Args:

session_id: Unique session identifier. doc: The notebook document to store. filepath: Optional filepath associated with the session.

Parameters:
Return type:

None

get(session_id)[source]

Get the notebook document for a session.

Args:

session_id: Session identifier.

Returns:

The NotebookDocument.

Raises:

KeyError: If the session does not exist.

Parameters:

session_id (str)

Return type:

NotebookDocument

get_session(session_id)[source]

Get the full Session object.

Falls back to loading from SQLite if the session is not in the in-memory cache.

Args:

session_id: Session identifier.

Returns:

The Session object.

Raises:

KeyError: If the session does not exist.

Parameters:

session_id (str)

Return type:

Session

get_filepath(session_id)[source]

Get the filepath associated with a session.

Args:

session_id: Session identifier.

Returns:

The filepath string, or None if not set.

Parameters:

session_id (str)

Return type:

str | None

delete(session_id)[source]

Delete a session from memory and SQLite.

Shuts down any associated kernel first.

Args:

session_id: Session identifier to delete.

Raises:

KeyError: If the session does not exist.

Parameters:

session_id (str)

Return type:

None

list_sessions()[source]

List all active session IDs.

Returns:

A list of session ID strings.

Return type:

list[str]

class notebookllm.mcp.session.Session(doc, filepath=None, kernel_manager=None, kernel_client=None)[source]

Bases: object

A single user session holding a notebook document.

Attributes:

doc: The notebook document for this session. filepath: Optional filepath (loaded from or saved to). kernel_manager: Jupyter kernel manager (set when kernel is started). kernel_client: Jupyter kernel client (set when kernel is started).

Parameters:
doc: NotebookDocument
filepath: str | None = None
kernel_manager: Any = None
kernel_client: Any = None
class notebookllm.mcp.session.SessionManager(db_path=None)[source]

Bases: object

Manages notebook sessions for MCP connections.

Sessions are persisted in SQLite (documents serialized via NotebookDocument.to_json() / NotebookDocument.from_json()) and cached in memory for fast access. In-memory state (kernel_client, filepath) is NOT persisted to SQLite — only the NotebookDocument is.

Args:
db_path: Path to the SQLite database. Defaults to the XDG data

directory (see _get_db_path()).

Parameters:

db_path (str | Path | None)

store(session_id, doc, filepath=None)[source]

Store or replace a notebook session (persisted to SQLite).

Args:

session_id: Unique session identifier. doc: The notebook document to store. filepath: Optional filepath associated with the session.

Parameters:
Return type:

None

get(session_id)[source]

Get the notebook document for a session.

Args:

session_id: Session identifier.

Returns:

The NotebookDocument.

Raises:

KeyError: If the session does not exist.

Parameters:

session_id (str)

Return type:

NotebookDocument

get_session(session_id)[source]

Get the full Session object.

Falls back to loading from SQLite if the session is not in the in-memory cache.

Args:

session_id: Session identifier.

Returns:

The Session object.

Raises:

KeyError: If the session does not exist.

Parameters:

session_id (str)

Return type:

Session

get_filepath(session_id)[source]

Get the filepath associated with a session.

Args:

session_id: Session identifier.

Returns:

The filepath string, or None if not set.

Parameters:

session_id (str)

Return type:

str | None

delete(session_id)[source]

Delete a session from memory and SQLite.

Shuts down any associated kernel first.

Args:

session_id: Session identifier to delete.

Raises:

KeyError: If the session does not exist.

Parameters:

session_id (str)

Return type:

None

list_sessions()[source]

List all active session IDs.

Returns:

A list of session ID strings.

Return type:

list[str]

Kernel execution engine for MCP server — manages Jupyter kernel lifecycle.

Provides a thread-safe KernelPool that manages multiple Jupyter kernels (one per session) and executes code cells asynchronously. Blocking kernel client API calls are offloaded to a ThreadPoolExecutor so the asyncio event loop remains responsive.

Requires jupyter_client (included via notebookllm[all] or pip install jupyter_client).

class notebookllm.mcp.engine.ExecutionJob(job_id, session_id, cell_index, status='pending', output='', error=None)[source]

Bases: object

Represents an active or completed cell execution.

Attributes:

job_id: Unique job identifier. session_id: Session this job belongs to. cell_index: Index of the cell being executed. status: Current execution status. output: Captured stdout/stderr output. error: Error message if execution failed.

Parameters:
  • job_id (str)

  • session_id (str)

  • cell_index (int)

  • status (Literal['pending', 'running', 'completed', 'failed', 'interrupted'])

  • output (str)

  • error (str | None)

job_id: str
session_id: str
cell_index: int
status: Literal['pending', 'running', 'completed', 'failed', 'interrupted'] = 'pending'
output: str = ''
error: str | None = None
class notebookllm.mcp.engine.KernelPool(max_workers=4)[source]

Bases: object

Manages kernel lifecycle and cell execution for MCP sessions.

Thread-safe — all _kernels and _jobs access is guarded by self._lock. Uses a ThreadPoolExecutor to run blocking Jupyter client calls without blocking the asyncio event loop.

Args:

max_workers: Maximum number of concurrent kernel executions.

Parameters:

max_workers (int)

async start_kernel(session_id, kernel_name='python3')[source]

Start a Jupyter kernel for a session.

Args:

session_id: Session identifier. kernel_name: Kernel spec name. Defaults to "python3".

Returns:

The kernel name that was started.

Raises:

ImportError: If jupyter_client is not installed.

Parameters:
  • session_id (str)

  • kernel_name (str)

Return type:

str

async execute_cell(session_id, cell_index, cell_source, timeout=60)[source]

Execute a code cell via the session’s kernel.

Runs the blocking Jupyter client API in a thread pool so the event loop remains responsive.

Args:

session_id: Session identifier. cell_index: Index of the cell (for reporting). cell_source: Source code to execute. timeout: Maximum execution time in seconds.

Returns:

The cell output as a string, or an error message.

Parameters:
  • session_id (str)

  • cell_index (int)

  • cell_source (str)

  • timeout (int)

Return type:

str

async execute_all_cells(session_id, cells, timeout=60)[source]

Execute all code cells in a notebook sequentially.

Skips non-code cells and stops on the first execution error.

Args:

session_id: Session identifier. cells: List of cells to execute. timeout: Maximum execution time per cell in seconds.

Returns:

Combined output from all cells as a string.

Parameters:
Return type:

str

async interrupt(session_id)[source]

Interrupt the running kernel for a session.

Args:

session_id: Session to interrupt.

Returns:

A status message.

Parameters:

session_id (str)

Return type:

str

async shutdown_kernel(session_id)[source]

Shutdown and cleanup a session’s kernel.

Args:

session_id: Session to shut down.

Parameters:

session_id (str)

Return type:

None

has_kernel(session_id)[source]

Check if a session has an active kernel.

Args:

session_id: Session to check.

Returns:

True if a kernel exists for the session.

Parameters:

session_id (str)

Return type:

bool

list_kernels()[source]

List available Jupyter kernels from jupyter kernelspec.

Returns:

A list of dicts with name and display_name keys. Returns an empty list if jupyter_client is not installed.

Return type:

list[dict]

class notebookllm.mcp.engine.ExecutionJob(job_id, session_id, cell_index, status='pending', output='', error=None)[source]

Bases: object

Represents an active or completed cell execution.

Attributes:

job_id: Unique job identifier. session_id: Session this job belongs to. cell_index: Index of the cell being executed. status: Current execution status. output: Captured stdout/stderr output. error: Error message if execution failed.

Parameters:
  • job_id (str)

  • session_id (str)

  • cell_index (int)

  • status (Literal['pending', 'running', 'completed', 'failed', 'interrupted'])

  • output (str)

  • error (str | None)

job_id: str
session_id: str
cell_index: int
status: Literal['pending', 'running', 'completed', 'failed', 'interrupted'] = 'pending'
output: str = ''
error: str | None = None
class notebookllm.mcp.engine.KernelPool(max_workers=4)[source]

Bases: object

Manages kernel lifecycle and cell execution for MCP sessions.

Thread-safe — all _kernels and _jobs access is guarded by self._lock. Uses a ThreadPoolExecutor to run blocking Jupyter client calls without blocking the asyncio event loop.

Args:

max_workers: Maximum number of concurrent kernel executions.

Parameters:

max_workers (int)

async start_kernel(session_id, kernel_name='python3')[source]

Start a Jupyter kernel for a session.

Args:

session_id: Session identifier. kernel_name: Kernel spec name. Defaults to "python3".

Returns:

The kernel name that was started.

Raises:

ImportError: If jupyter_client is not installed.

Parameters:
  • session_id (str)

  • kernel_name (str)

Return type:

str

async execute_cell(session_id, cell_index, cell_source, timeout=60)[source]

Execute a code cell via the session’s kernel.

Runs the blocking Jupyter client API in a thread pool so the event loop remains responsive.

Args:

session_id: Session identifier. cell_index: Index of the cell (for reporting). cell_source: Source code to execute. timeout: Maximum execution time in seconds.

Returns:

The cell output as a string, or an error message.

Parameters:
  • session_id (str)

  • cell_index (int)

  • cell_source (str)

  • timeout (int)

Return type:

str

async execute_all_cells(session_id, cells, timeout=60)[source]

Execute all code cells in a notebook sequentially.

Skips non-code cells and stops on the first execution error.

Args:

session_id: Session identifier. cells: List of cells to execute. timeout: Maximum execution time per cell in seconds.

Returns:

Combined output from all cells as a string.

Parameters:
Return type:

str

async interrupt(session_id)[source]

Interrupt the running kernel for a session.

Args:

session_id: Session to interrupt.

Returns:

A status message.

Parameters:

session_id (str)

Return type:

str

async shutdown_kernel(session_id)[source]

Shutdown and cleanup a session’s kernel.

Args:

session_id: Session to shut down.

Parameters:

session_id (str)

Return type:

None

has_kernel(session_id)[source]

Check if a session has an active kernel.

Args:

session_id: Session to check.

Returns:

True if a kernel exists for the session.

Parameters:

session_id (str)

Return type:

bool

list_kernels()[source]

List available Jupyter kernels from jupyter kernelspec.

Returns:

A list of dicts with name and display_name keys. Returns an empty list if jupyter_client is not installed.

Return type:

list[dict]

notebookllm.utils

Format detection for notebooks — file-extension mapping and content sniffing.

Determines which notebook format a file or string is in by checking:

  • File extension (for detect_format()): .ipynb, .qmd, .rmd, .deepnote, .md, .py — maps directly to format name.

  • Content patterns (for detect_text_format()): # %% markers, import marimo, ```{r}`/```{python}` blocks, JSON structure, YAML structure with project.notebooks keys.

Supports automatic detection for all 8+ notebook formats.

notebookllm.utils.detect.detect_format(filepath, content=None)[source]

Detect notebook format from a file path, optionally checking content.

Detection priority:

  • .ipynb -> "ipynb"

  • .qmd -> "quarto"

  • .rmd -> "rmarkdown"

  • .deepnote -> "deepnote"

  • .md -> "markdown"

  • .py -> marimo (if contains @app.cell) or percent

Args:

filepath: Path to the notebook file. content: Optional file content for content-based disambiguation.

Returns:

A format string: "ipynb", "quarto", "rmarkdown", "deepnote", "markdown", "marimo", or "percent".

Raises:

ValueError: If the file extension is not recognized.

Parameters:
  • filepath (Path)

  • content (str | None)

Return type:

str

notebookllm.utils.detect.detect_text_format(content)[source]

Detect notebook format from text content alone (content sniffing).

Detection order:

  1. "percent" — if any line starts with # %%

  2. "marimo" — if contains import marimo or @app.cell

  3. "rmarkdown" — if contains ```{r}`

  4. "quarto" — if contains ```{python}`

  5. "markdown" — if contains ```python`

  6. "ipynb" — if content is JSON with cells and nbformat keys

  7. "deepnote" — if content is YAML with project.notebooks

  8. "percent" — fallback for unrecognized text

Args:

content: The raw text content to sniff.

Returns:

A format string: "percent", "marimo", "rmarkdown", "quarto", "markdown", "ipynb", or "deepnote".

Parameters:

content (str)

Return type:

str

Token counting utilities — estimate AI Agent token usage for notebooks.

Provides accurate token counting via tiktoken (GPT-4 cl100k_base encoding) and a fast character-based fallback (len(text) / 4) when tiktoken is not available.

Key functions:

Install notebookllm[token] for accurate GPT-4 token counting, or use the built-in heuristic for instant approximate counts (±20%).

notebookllm.utils.tokenizer.count_tokens(text, encoding_name='cl100k_base')[source]

Count tokens in a text string.

Uses tiktoken if available, falls back to character-length heuristic.

Args:

text: The text to count tokens for. encoding_name: Name of the tiktoken encoding (default: cl100k_base).

Returns:

Number of tokens. Returns 0 for empty strings.

Parameters:
  • text (str)

  • encoding_name (str)

Return type:

int

class notebookllm.utils.tokenizer.CellTokenInfo(cell_index, cell_type, tokens, preview)[source]

Bases: object

Token usage breakdown for a single cell.

Attributes:

cell_index: Zero-based index of the cell in the notebook. cell_type: Type of the cell ("code", "markdown", or "raw"). tokens: Number of tokens in the cell’s source text. preview: First 50 characters of the cell source (whitespace collapsed).

Parameters:
  • cell_index (int)

  • cell_type (str)

  • tokens (int)

  • preview (str)

cell_index: int
cell_type: str
tokens: int
preview: str
class notebookllm.utils.tokenizer.NotebookTokenReport(total_tokens, cell_tokens=<factory>, mode='minimal', num_cells=0)[source]

Bases: object

Token usage report for an entire notebook.

Produced by tokenize_notebook().

Attributes:

total_tokens: Total tokens across all cells. cell_tokens: Per-cell token breakdown as a list of CellTokenInfo. mode: Output mode used for counting ("minimal", "standard", or "full"). num_cells: Number of cells in the notebook.

Parameters:
total_tokens: int
cell_tokens: list[CellTokenInfo]
mode: str = 'minimal'
num_cells: int = 0
property token_summary: str

Human-readable summary of token usage.

Returns:

A string like "Total: 420 tokens across 8 cells (minimal mode)".

notebookllm.utils.tokenizer.tokenize_notebook(doc, mode='minimal', encoding_name='cl100k_base')[source]

Analyze a notebook and return per-cell and total token counts.

Args:

doc: The notebook document to analyze. mode: Output verbosity (minimal, standard, or full). encoding_name: Name of the tiktoken encoding (default: cl100k_base).

Returns:

A NotebookTokenReport with per-cell and total token counts.

Parameters:
Return type:

NotebookTokenReport

class notebookllm.utils.tokenizer.CellTokenInfo(cell_index, cell_type, tokens, preview)[source]

Bases: object

Token usage breakdown for a single cell.

Attributes:

cell_index: Zero-based index of the cell in the notebook. cell_type: Type of the cell ("code", "markdown", or "raw"). tokens: Number of tokens in the cell’s source text. preview: First 50 characters of the cell source (whitespace collapsed).

Parameters:
  • cell_index (int)

  • cell_type (str)

  • tokens (int)

  • preview (str)

cell_index: int
cell_type: str
tokens: int
preview: str
class notebookllm.utils.tokenizer.NotebookTokenReport(total_tokens, cell_tokens=<factory>, mode='minimal', num_cells=0)[source]

Bases: object

Token usage report for an entire notebook.

Produced by tokenize_notebook().

Attributes:

total_tokens: Total tokens across all cells. cell_tokens: Per-cell token breakdown as a list of CellTokenInfo. mode: Output mode used for counting ("minimal", "standard", or "full"). num_cells: Number of cells in the notebook.

Parameters:
total_tokens: int
cell_tokens: list[CellTokenInfo]
mode: str = 'minimal'
num_cells: int = 0
property token_summary: str

Human-readable summary of token usage.

Returns:

A string like "Total: 420 tokens across 8 cells (minimal mode)".

notebookllm.utils.tokenizer.count_tokens(text, encoding_name='cl100k_base')[source]

Count tokens in a text string.

Uses tiktoken if available, falls back to character-length heuristic.

Args:

text: The text to count tokens for. encoding_name: Name of the tiktoken encoding (default: cl100k_base).

Returns:

Number of tokens. Returns 0 for empty strings.

Parameters:
  • text (str)

  • encoding_name (str)

Return type:

int

notebookllm.utils.tokenizer.tokenize_notebook(doc, mode='minimal', encoding_name='cl100k_base')[source]

Analyze a notebook and return per-cell and total token counts.

Args:

doc: The notebook document to analyze. mode: Output verbosity (minimal, standard, or full). encoding_name: Name of the tiktoken encoding (default: cl100k_base).

Returns:

A NotebookTokenReport with per-cell and total token counts.

Parameters:
Return type:

NotebookTokenReport

Input/output validation and atomic write utilities.

Provides notebook integrity checks and crash-safe file writing:

  • ValidationReport — comprehensive validation with error/warning tracking

  • validate_notebook() — run all checks on a NotebookDocument

  • atomic_write() — crash-safe file writes via temp-file + rename

  • Legacy helpers: validate_filepath, validate_output_format, validate_cell_index, validate_cell_type

class notebookllm.utils.validation.ValidationError(field, message, severity='error', cell_index=None)[source]

Bases: object

A single validation issue found in a notebook.

Attributes:

field: The field that failed validation (e.g. cell_type). message: A human-readable description of the issue. severity: Either error (blocks usage) or warning (informational). cell_index: Index of the offending cell, or None for notebook-level.

Parameters:
  • field (str)

  • message (str)

  • severity (str)

  • cell_index (int | None)

field: str
message: str
severity: str = 'error'
cell_index: int | None = None
class notebookllm.utils.validation.ValidationReport(errors=<factory>, warnings=<factory>)[source]

Bases: object

Report from a notebook validation run.

Attributes:

errors: List of blocking issues. warnings: List of non-blocking issues.

Parameters:
errors: list[ValidationError]
warnings: list[ValidationError]
property is_valid: bool

True if there are no errors (warnings are allowed).

property summary: str

A one-line summary of the validation results.

Returns:

"Validation passed." if clean, or a count of errors/warnings.

format_text()[source]

Format the report as human-readable text.

Returns:

Multi-line string with ERROR and WARNING lines.

Return type:

str

notebookllm.utils.validation.atomic_write(filepath, content)[source]

Write content to a file atomically using a temp file + rename.

Writes to a temporary file in the same directory (same filesystem), then renames — which is atomic on POSIX and most local filesystems.

Args:

filepath: Destination file path. content: Content to write.

Parameters:
Return type:

None

notebookllm.utils.validation.validate_cell_types(doc)[source]

Check that all cells have a valid CellType.

Args:

doc: The notebook to validate.

Returns:

List of ValidationError for cells with invalid types.

Parameters:

doc (NotebookDocument)

Return type:

list[ValidationError]

notebookllm.utils.validation.validate_no_orphan_outputs(doc)[source]

Check that non-code cells have no outputs (a common corruption signal).

Args:

doc: The notebook to validate.

Returns:

List of ValidationError warnings for non-code cells that have outputs attached.

Parameters:

doc (NotebookDocument)

Return type:

list[ValidationError]

notebookllm.utils.validation.validate_no_empty_cells(doc)[source]

Warn on empty cells (zero-length source text).

Args:

doc: The notebook to validate.

Returns:

List of ValidationError warnings for empty cells.

Parameters:

doc (NotebookDocument)

Return type:

list[ValidationError]

notebookllm.utils.validation.validate_notebook(doc)[source]

Run all validation checks on a NotebookDocument.

Runs the following checks:

Args:

doc: The notebook to validate.

Returns:

A ValidationReport with all errors and warnings.

Parameters:

doc (NotebookDocument)

Return type:

ValidationReport

notebookllm.utils.validation.validate_filepath(filepath)[source]

Validate that a filepath exists and is a file (not a directory).

Args:

filepath: Path to validate.

Returns:

The resolved Path.

Raises:

IsADirectoryError: If filepath is a directory. FileNotFoundError: If filepath does not exist.

Parameters:

filepath (str | Path)

Return type:

Path

notebookllm.utils.validation.validate_output_format(fmt)[source]

Validate that a format string is one of the supported output formats.

Args:

fmt: Format string to validate.

Returns:

The validated format string.

Raises:

ValueError: If fmt is not a supported format.

Parameters:

fmt (str)

Return type:

str

notebookllm.utils.validation.validate_cell_index(index, total)[source]

Validate that a cell index is within the valid range.

Args:

index: Zero-based cell index. total: Total number of cells.

Returns:

The validated index.

Raises:

IndexError: If index is out of range.

Parameters:
Return type:

int

notebookllm.utils.validation.validate_cell_type(cell_type)[source]

Validate and convert a cell type string to a CellType enum.

Args:

cell_type: String like "code", "markdown", or "raw".

Returns:

The corresponding CellType.

Raises:

ValueError: If cell_type is not one of the valid values.

Parameters:

cell_type (str)

Return type:

CellType

class notebookllm.utils.validation.ValidationError(field, message, severity='error', cell_index=None)[source]

Bases: object

A single validation issue found in a notebook.

Attributes:

field: The field that failed validation (e.g. cell_type). message: A human-readable description of the issue. severity: Either error (blocks usage) or warning (informational). cell_index: Index of the offending cell, or None for notebook-level.

Parameters:
  • field (str)

  • message (str)

  • severity (str)

  • cell_index (int | None)

field: str
message: str
severity: str = 'error'
cell_index: int | None = None
class notebookllm.utils.validation.ValidationReport(errors=<factory>, warnings=<factory>)[source]

Bases: object

Report from a notebook validation run.

Attributes:

errors: List of blocking issues. warnings: List of non-blocking issues.

Parameters:
errors: list[ValidationError]
warnings: list[ValidationError]
property is_valid: bool

True if there are no errors (warnings are allowed).

property summary: str

A one-line summary of the validation results.

Returns:

"Validation passed." if clean, or a count of errors/warnings.

format_text()[source]

Format the report as human-readable text.

Returns:

Multi-line string with ERROR and WARNING lines.

Return type:

str

notebookllm.utils.validation.atomic_write(filepath, content)[source]

Write content to a file atomically using a temp file + rename.

Writes to a temporary file in the same directory (same filesystem), then renames — which is atomic on POSIX and most local filesystems.

Args:

filepath: Destination file path. content: Content to write.

Parameters:
Return type:

None

notebookllm.utils.validation.validate_notebook(doc)[source]

Run all validation checks on a NotebookDocument.

Runs the following checks:

Args:

doc: The notebook to validate.

Returns:

A ValidationReport with all errors and warnings.

Parameters:

doc (NotebookDocument)

Return type:

ValidationReport

notebookllm.utils.validation.validate_filepath(filepath)[source]

Validate that a filepath exists and is a file (not a directory).

Args:

filepath: Path to validate.

Returns:

The resolved Path.

Raises:

IsADirectoryError: If filepath is a directory. FileNotFoundError: If filepath does not exist.

Parameters:

filepath (str | Path)

Return type:

Path

notebookllm.utils.validation.validate_output_format(fmt)[source]

Validate that a format string is one of the supported output formats.

Args:

fmt: Format string to validate.

Returns:

The validated format string.

Raises:

ValueError: If fmt is not a supported format.

Parameters:

fmt (str)

Return type:

str

notebookllm.utils.validation.validate_cell_index(index, total)[source]

Validate that a cell index is within the valid range.

Args:

index: Zero-based cell index. total: Total number of cells.

Returns:

The validated index.

Raises:

IndexError: If index is out of range.

Parameters:
Return type:

int

notebookllm.utils.validation.validate_cell_type(cell_type)[source]

Validate and convert a cell type string to a CellType enum.

Args:

cell_type: String like "code", "markdown", or "raw".

Returns:

The corresponding CellType.

Raises:

ValueError: If cell_type is not one of the valid values.

Parameters:

cell_type (str)

Return type:

CellType