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:
EnumType 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:
EnumAI 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):
MINIMALCell markers (
# %% [type]) + source code only. Cleanest for Agent input — ideal for high-level analysis.STANDARDAdds execution count and cell metadata tags — useful for understanding notebook execution history.
FULLAdds 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:
objectRepresents 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_datait may be a MIME-bundle dict (e.g.{"text/plain": "...", "image/png": "..."}).- name: Stream name —
"stdout"or"stderr". Only set when output_type == "stream".
- output_type: The kind of output (
- 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:
objectUniversal 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 producesCellinstances 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 (
Noneif never run). outputs: List ofCellOutputobjects (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: DeepnoteblockGroupUUID 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:
- outputs: list[CellOutput]
- class notebookllm.models.NotebookDocument(cells=<factory>, metadata=<factory>, kernel_name=None, language='python', source_format=None)[source]
Bases:
objectUniversal notebook representation — format-agnostic.
The central data structure of notebookllm. Every format loader produces a
NotebookDocumentand every dumper consumes one.NotebookDocumentprovides the public API for reading, editing, searching, converting, and token-analyzing notebooks.- Attributes:
cells: Ordered list of
Cellobjects. 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:
- to_json()[source]
Serialize the notebook to a JSON string.
The output includes a
_cir_versionfield for forward-compatible deserialization.- Returns:
Indented JSON string.
- Return type:
- 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:
- 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:
- Return type:
- to_file(filepath, fmt=None)[source]
Save the notebook to a file.
Auto-detects the output format from the file extension unless
fmtis explicitly provided.- Args:
filepath: Destination file path. fmt: Output format override (e.g.
"ipynb"). IfNone, inferred from extension.
- 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 themodeparameter.- 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:
mode (OutputMode)
max_tokens (int | None)
- Return type:
- classmethod from_text(text, source_format=None)[source]
Parse plain text into a NotebookDocument.
When
source_formatisNone, the format is auto-detected by content sniffing (seenotebookllm.utils.detect.detect_text_format()).- Args:
text: The plain text content to parse. source_format: Explicit format hint or
Nonefor auto-detect.- Returns:
A new NotebookDocument.
- Parameters:
- Return type:
- 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
Cellobjects.
- get_cell(index)[source]
Get a cell by its index.
- Args:
index: Zero-based cell index.
- Returns:
The
Cellat that index.- Raises:
IndexError: If
indexis out of range.
- add_cell(cell, position=None)[source]
Add a cell to the notebook.
- Args:
cell: The
Cellto add. position: Insertion index. IfNone, the cell is appended at the end.- Raises:
IndexError: If
positionis out of range.
- 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
indexis out of range.
- delete_cell(index)[source]
Delete a cell by index.
- Args:
index: Index of the cell to remove.
- Raises:
IndexError: If
indexis 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_indexis out of range.
- 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.
- 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
- Returns:
A
NotebookTokenReportwith per-cell and total token counts.
- Parameters:
mode (OutputMode)
- Return type:
- class notebookllm.models.CellType(*values)[source]
Bases:
EnumType 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:
EnumAI 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):
MINIMALCell markers (
# %% [type]) + source code only. Cleanest for Agent input — ideal for high-level analysis.STANDARDAdds execution count and cell metadata tags — useful for understanding notebook execution history.
FULLAdds 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:
objectRepresents 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_datait may be a MIME-bundle dict (e.g.{"text/plain": "...", "image/png": "..."}).- name: Stream name —
"stdout"or"stderr". Only set when output_type == "stream".
- output_type: The kind of output (
- output_type: str
- 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:
objectUniversal 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 producesCellinstances 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 (
Noneif never run). outputs: List ofCellOutputobjects (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: DeepnoteblockGroupUUID 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
- outputs: list[CellOutput]
- metadata: dict
- class notebookllm.models.NotebookDocument(cells=<factory>, metadata=<factory>, kernel_name=None, language='python', source_format=None)[source]
Bases:
objectUniversal notebook representation — format-agnostic.
The central data structure of notebookllm. Every format loader produces a
NotebookDocumentand every dumper consumes one.NotebookDocumentprovides the public API for reading, editing, searching, converting, and token-analyzing notebooks.- Attributes:
cells: Ordered list of
Cellobjects. 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:
- metadata: dict
- language: str = 'python'
- to_json()[source]
Serialize the notebook to a JSON string.
The output includes a
_cir_versionfield for forward-compatible deserialization.- Returns:
Indented JSON string.
- Return type:
- 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:
- 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:
- Return type:
- to_file(filepath, fmt=None)[source]
Save the notebook to a file.
Auto-detects the output format from the file extension unless
fmtis explicitly provided.- Args:
filepath: Destination file path. fmt: Output format override (e.g.
"ipynb"). IfNone, inferred from extension.
- 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 themodeparameter.- 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:
mode (OutputMode)
max_tokens (int | None)
- Return type:
- classmethod from_text(text, source_format=None)[source]
Parse plain text into a NotebookDocument.
When
source_formatisNone, the format is auto-detected by content sniffing (seenotebookllm.utils.detect.detect_text_format()).- Args:
text: The plain text content to parse. source_format: Explicit format hint or
Nonefor auto-detect.- Returns:
A new NotebookDocument.
- Parameters:
- Return type:
- 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
Cellobjects.
- get_cell(index)[source]
Get a cell by its index.
- Args:
index: Zero-based cell index.
- Returns:
The
Cellat that index.- Raises:
IndexError: If
indexis out of range.
- add_cell(cell, position=None)[source]
Add a cell to the notebook.
- Args:
cell: The
Cellto add. position: Insertion index. IfNone, the cell is appended at the end.- Raises:
IndexError: If
positionis out of range.
- 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
indexis out of range.
- delete_cell(index)[source]
Delete a cell by index.
- Args:
index: Index of the cell to remove.
- Raises:
IndexError: If
indexis 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_indexis out of range.
- 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.
- 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
- Returns:
A
NotebookTokenReportwith per-cell and total token counts.
- Parameters:
mode (OutputMode)
- Return type:
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:
- Raises:
ValueError: If the format cannot be detected from the extension.
- Parameters:
- Return type:
- 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:
doc (NotebookDocument)
fmt (str | None)
- 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:
- Raises:
ValueError: If the format is not supported or cannot be detected.
- Parameters:
- Return type:
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:
BaseLoaderLoad percent-format
.pyfiles 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
.pyfile.- Returns:
- Parameters:
- Return type:
- class notebookllm.loaders.percent.PercentDumper[source]
Bases:
BaseDumperDump
NotebookDocumentto 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:
doc (NotebookDocument)
filepath (Path | None)
- Return type:
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:
BaseLoaderLoad
.ipynbfiles intoNotebookDocument.For files smaller than
streaming_threshold, usesnbformat(fast, full in-memory parsing). For larger files, usesijsonto stream-parse cells one at a time, keeping memory usage low.Falls back to
nbformatifijsonis not installed.- load(source)[source]
Load a
.ipynbfile from disk.- Args:
source: Path to the
.ipynbfile.- Returns:
- Parameters:
- Return type:
- class notebookllm.loaders.ipynb.IpynbDumper[source]
Bases:
BaseDumperDump
NotebookDocumentto.ipynbformat.Produces standard Jupyter notebook JSON, compatible with JupyterLab, VS Code, and nbformat v4.
- dump(doc, filepath=None)[source]
Serialize a notebook to
.ipynbJSON.- Args:
doc: The notebook to serialize. filepath: If provided, write the output to this file.
- Returns:
The
.ipynbJSON string.
- Parameters:
doc (NotebookDocument)
filepath (Path | None)
- Return type:
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:
BaseLoaderLoad marimo-format
.pyfiles using AST parsing.Parses the Python AST to find functions decorated with
@app.cell, extracts their source code, and detectsmo.md()calls to identify markdown cells. Also extracts the__generated_withversion from module-level assignments.- load(source)[source]
Load a marimo notebook from a file path.
- Args:
source: Path to the marimo
.pyfile.- Returns:
- Parameters:
- Return type:
- class notebookllm.loaders.marimo.MarimoDumper[source]
Bases:
BaseDumperDump
NotebookDocumentto marimo format.Produces a valid marimo
.pyfile with@app.celldecorators. Markdown cells are wrapped inmo.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:
doc (NotebookDocument)
filepath (Path | None)
- Return type:
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:
BaseLoaderLoad Quarto
.qmdfiles.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
.qmdfile.- Returns:
- Parameters:
- Return type:
- class notebookllm.loaders.quarto.QuartoDumper[source]
Bases:
BaseDumperDump
NotebookDocumentto Quarto.qmdformat.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
.qmdcontent as a string.
- Parameters:
doc (NotebookDocument)
filepath (Path | None)
- Return type:
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:
BaseLoaderLoad Markdown files with embedded fenced code blocks.
Code blocks with known languages (python, r, julia, javascript, etc.) are treated as
CODEcells. Other language blocks becomeRAWcells.- load(source)[source]
Load a Markdown notebook from a file.
- Args:
source: Path to the
.mdfile.- Returns:
- Parameters:
- Return type:
- class notebookllm.loaders.markdown.MarkdownDumper[source]
Bases:
BaseDumperDump
NotebookDocumentto 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:
doc (NotebookDocument)
filepath (Path | None)
- Return type:
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:
BaseLoaderLoad R Markdown files with embedded R and Python code blocks.
R code blocks (
```{r}`) are stored withlanguage="r". Python and other languages are recognized similarly. Unknown languages becomeRAWcells.- load(source)[source]
Load an R Markdown file from disk.
- Args:
source: Path to the
.Rmdfile.- Returns:
- Parameters:
- Return type:
- class notebookllm.loaders.rmarkdown.RMarkdownDumper[source]
Bases:
BaseDumperDump
NotebookDocumentto R Markdown format.Produces
.Rmdoutput 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
.Rmdcontent as a string.
- Parameters:
doc (NotebookDocument)
filepath (Path | None)
- Return type:
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:
BaseDumperDump
NotebookDocumentto flat.pyformat.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:
doc (NotebookDocument)
filepath (Path | None)
- Return type:
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:
BaseLoaderLoad
.deepnoteYAML 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
.deepnotefile.- Returns:
- Parameters:
- Return type:
- class notebookllm.loaders.deepnote.DeepnoteDumper[source]
Bases:
BaseDumperDump
NotebookDocumentto Deepnote YAML format.Groups cells by
notebook_namemetadata, sorts blocks bysorting_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:
doc (NotebookDocument)
filepath (Path | None)
- Return type:
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
NotebookDocumentand 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:
ABCAbstract base class for notebook format loaders.
Subclasses must implement:
- abstractmethod load(source)[source]
Load a notebook from a file path.
- Args:
source: Path to the notebook file.
- Returns:
A
NotebookDocumentinstance.
- Parameters:
- Return type:
- abstractmethod loads(content)[source]
Load a notebook from a string.
- Args:
content: The raw text content of the notebook.
- Returns:
A
NotebookDocumentinstance.
- Parameters:
content (str)
- Return type:
- class notebookllm.loaders.base.BaseDumper[source]
Bases:
ABCAbstract 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:
doc (NotebookDocument)
filepath (Path | None)
- Return type:
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:
objectConverts
NotebookDocumentto 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):
Markdown cells (explanatory — most valuable for Agent understanding)
Code cells with outputs (executed, have results)
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) // 4heuristic.
- 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:
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-mcppackage.- Args:
- session_manager: An optional session manager instance. If not
provided, a new one is created.
- Returns:
A configured
FastMCPapp.
- 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:
objectA 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)
kernel_manager (Any)
kernel_client (Any)
- doc: NotebookDocument
- class notebookllm.mcp.session.SessionManager(db_path=None)[source]
Bases:
objectManages 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:
session_id (str)
doc (NotebookDocument)
filepath (str | None)
- 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:
- get_session(session_id)[source]
Get the full
Sessionobject.Falls back to loading from SQLite if the session is not in the in-memory cache.
- Args:
session_id: Session identifier.
- Returns:
The
Sessionobject.- Raises:
KeyError: If the session does not exist.
- get_filepath(session_id)[source]
Get the filepath associated with a session.
- Args:
session_id: Session identifier.
- Returns:
The filepath string, or
Noneif not set.
- class notebookllm.mcp.session.Session(doc, filepath=None, kernel_manager=None, kernel_client=None)[source]
Bases:
objectA 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)
kernel_manager (Any)
kernel_client (Any)
- doc: NotebookDocument
- kernel_manager: Any = None
- kernel_client: Any = None
- class notebookllm.mcp.session.SessionManager(db_path=None)[source]
Bases:
objectManages 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:
session_id (str)
doc (NotebookDocument)
filepath (str | None)
- 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:
- get_session(session_id)[source]
Get the full
Sessionobject.Falls back to loading from SQLite if the session is not in the in-memory cache.
- Args:
session_id: Session identifier.
- Returns:
The
Sessionobject.- Raises:
KeyError: If the session does not exist.
- get_filepath(session_id)[source]
Get the filepath associated with a session.
- Args:
session_id: Session identifier.
- Returns:
The filepath string, or
Noneif not set.
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:
objectRepresents 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:
- class notebookllm.mcp.engine.KernelPool(max_workers=4)[source]
Bases:
objectManages kernel lifecycle and cell execution for MCP sessions.
Thread-safe — all
_kernelsand_jobsaccess is guarded byself._lock. Uses aThreadPoolExecutorto 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_clientis not installed.
- 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.
- 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.
- async interrupt(session_id)[source]
Interrupt the running kernel for a session.
- Args:
session_id: Session to interrupt.
- Returns:
A status message.
- 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
- class notebookllm.mcp.engine.ExecutionJob(job_id, session_id, cell_index, status='pending', output='', error=None)[source]
Bases:
objectRepresents 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'] = 'pending'
- output: str = ''
- class notebookllm.mcp.engine.KernelPool(max_workers=4)[source]
Bases:
objectManages kernel lifecycle and cell execution for MCP sessions.
Thread-safe — all
_kernelsand_jobsaccess is guarded byself._lock. Uses aThreadPoolExecutorto 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_clientis not installed.
- 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.
- 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.
- async interrupt(session_id)[source]
Interrupt the running kernel for a session.
- Args:
session_id: Session to interrupt.
- Returns:
A status message.
- 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:
Trueif a kernel exists for the session.
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 withproject.notebookskeys.
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.
- notebookllm.utils.detect.detect_text_format(content)[source]
Detect notebook format from text content alone (content sniffing).
Detection order:
"percent"— if any line starts with# %%"marimo"— if containsimport marimoor@app.cell"rmarkdown"— if contains```{r}`"quarto"— if contains```{python}`"markdown"— if contains```python`"ipynb"— if content is JSON withcellsandnbformatkeys"deepnote"— if content is YAML withproject.notebooks"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".
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:
count_tokens(): Token count for a single string.tokenize_notebook(): Full token analysis of a notebook with per-cell breakdown.
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.
- class notebookllm.utils.tokenizer.CellTokenInfo(cell_index, cell_type, tokens, preview)[source]
Bases:
objectToken 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).
- class notebookllm.utils.tokenizer.NotebookTokenReport(total_tokens, cell_tokens=<factory>, mode='minimal', num_cells=0)[source]
Bases:
objectToken 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)
num_cells (int)
- cell_tokens: list[CellTokenInfo]
- 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:
doc (NotebookDocument)
mode (str)
encoding_name (str)
- Return type:
- class notebookllm.utils.tokenizer.CellTokenInfo(cell_index, cell_type, tokens, preview)[source]
Bases:
objectToken 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).
- 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:
objectToken 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)
num_cells (int)
- 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.
- 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:
doc (NotebookDocument)
mode (str)
encoding_name (str)
- Return type:
Input/output validation and atomic write utilities.
Provides notebook integrity checks and crash-safe file writing:
ValidationReport— comprehensive validation with error/warning trackingvalidate_notebook()— run all checks on aNotebookDocumentatomic_write()— crash-safe file writes via temp-file + renameLegacy 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:
objectA 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.
- class notebookllm.utils.validation.ValidationReport(errors=<factory>, warnings=<factory>)[source]
Bases:
objectReport from a notebook validation run.
- Attributes:
errors: List of blocking issues. warnings: List of non-blocking issues.
- Parameters:
errors (list[ValidationError])
warnings (list[ValidationError])
- errors: list[ValidationError]
- warnings: list[ValidationError]
- 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.
- 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
ValidationErrorfor cells with invalid types.
- Parameters:
doc (NotebookDocument)
- Return type:
- 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
ValidationErrorwarnings for non-code cells that have outputs attached.
- Parameters:
doc (NotebookDocument)
- Return type:
- 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
ValidationErrorwarnings for empty cells.
- Parameters:
doc (NotebookDocument)
- Return type:
- notebookllm.utils.validation.validate_notebook(doc)[source]
Run all validation checks on a
NotebookDocument.Runs the following checks:
validate_cell_types()— errors for invalid cell types.validate_no_orphan_outputs()— warnings for non-code cells with outputs.validate_no_empty_cells()— warnings for empty cells.
- Args:
doc: The notebook to validate.
- Returns:
A
ValidationReportwith all errors and warnings.
- Parameters:
doc (NotebookDocument)
- Return type:
- 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.
- 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.
- 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.
- notebookllm.utils.validation.validate_cell_type(cell_type)[source]
Validate and convert a cell type string to a
CellTypeenum.- 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.
- class notebookllm.utils.validation.ValidationError(field, message, severity='error', cell_index=None)[source]
Bases:
objectA 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.
- field: str
- message: str
- severity: str = 'error'
- class notebookllm.utils.validation.ValidationReport(errors=<factory>, warnings=<factory>)[source]
Bases:
objectReport from a notebook validation run.
- Attributes:
errors: List of blocking issues. warnings: List of non-blocking issues.
- Parameters:
errors (list[ValidationError])
warnings (list[ValidationError])
- errors: list[ValidationError]
- warnings: list[ValidationError]
- property is_valid: bool
Trueif 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.
- 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.
- notebookllm.utils.validation.validate_notebook(doc)[source]
Run all validation checks on a
NotebookDocument.Runs the following checks:
validate_cell_types()— errors for invalid cell types.validate_no_orphan_outputs()— warnings for non-code cells with outputs.validate_no_empty_cells()— warnings for empty cells.
- Args:
doc: The notebook to validate.
- Returns:
A
ValidationReportwith all errors and warnings.
- Parameters:
doc (NotebookDocument)
- Return type:
- 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.
- 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.
- 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.