← Projectschunkscope

See how your RAG chunking splits your documents.

chunkscope is a Python package for developers building retrieval-augmented generation (RAG) systems. Add one line to your pipeline and get an offline HTML report that shows every chunk in its place in the source, where chunks overlap, which text ended up in no chunk, how big your chunks really are, and the boundary bugs that quietly hurt retrieval.

Version 0.2.0 · Python 3.10+ · MIT licence · no dependencies · PyPI ↗

Different use cases

One line, any pipeline

Next: LangChain
pipeline.py
import chunkscope

text = open("guide.md").read()
chunks = my_chunker(text)

chunkscope.report(chunks, source=text)

Any chunker: strings or dicts are enough

  • Chunks highlighted in place
  • Offline, single-file report
  • No dependencies

Each chunk in its own colour, in the source text

What you get

One HTML page that shows every chunk where it lives in your document: what each chunk covers, where chunks overlap, which text fell between them, and which boundaries are broken. This is a small, working example of it.

Try it: switch Colour by, click the text, a #n marker or a bar in the chunk map. Look for the two-colour overlap, the red gaps and the chunk over the limit.

guide.md · live example
Colour by
alternating colours tell neighbouring chunks apart

1 chunk could not be placed in the source:

Fresh beans matter more than expensive equipment. Buy whole beans roasted within the last four weeks and grind them just before brewing. Light roasts taste brighter and more acidic; dark roasts taste heavier. ## Grind Size | Method | Grind | Brew time | |---|---|---| | Espresso | Fine | 25-30 s | | Pour-over | Medium-fine | 3 min | | French press | Coarse | 4 min | ## Water Use filtered water heated to 92-96 °C. Water that is too hot extracts bitter compounds; water that is too cold leaves the cup thin and sour.

Why chunkscope

Chunking decides what your retriever can find. A table split from its header, a code block cut in half or a paragraph that silently fell between two chunks will never be retrieved correctly, and no metric tells you why. Reading chunks as a list of strings does not show these problems. Seeing them in place does.

Any chunker

Fixed-size, recursive, sentence, Markdown, semantic, LLM-based, hierarchical, or your own code. chunkscope only needs the chunk text.

Any framework

LangChain, LlamaIndex, Haystack, Chonkie, Docling, Unstructured, or plain strings and dicts. Detected automatically, never imported.

Any file type

It shows the text your chunker received from PDF, DOCX, HTML, Markdown or code, so extraction bugs become visible too.

Private by design

One self-contained HTML file that cannot make network requests. Safe for confidential documents.

Live demo

The example above is a miniature. This is the real thing, exactly as chunkscope writes it: seven documents of technical documentation for Quillstore, a fictional key-value store, chunked three ways and compared in one report: a heading-aware chunker, fixed-size chunks with overlap, and one chunk per blank-line block. The heading-aware run is scored against the query “How do I recover a node after a disk failure?” with a small BM25 retriever. A few mistakes were added on purpose, so every check appears.

  • Overview: the size histogram, the retrieval ranking, and a table comparing the three runs.
  • A document: try Colour by (chunk, size, issues, retrieval score, section, document type), click the chunk map or the text, and open the Compare runs tab.
  • Things to find: overlaps and words cut in half (fixed-size), dropped headings as gaps and repeated table headers as partial matches (heading-aware), heading-only and tiny chunks (blocks), a generated summary that is not in the source, an off-by-seven offset bug, and a document that produced no chunks.

The text is synthetic and sizes are counted in words, with a limit of 120 and a minimum of 8.

Open the demo full screen ↗

Installation

shell
pip install chunkscope                 # core: standard library only
pip install "chunkscope[tiktoken]"     # + count sizes with tiktoken
pip install "chunkscope[hf]"           # + count sizes with a Hugging Face tokenizer

chunkscope supports Python 3.10 and newer and has no required dependencies. The frameworks it reads (LangChain, LlamaIndex, …) are never installed or imported by chunkscope: it recognises their objects by their attributes.

Quick start

Pass your chunks and the text they came from:

python
import chunkscope

text = open("guide.md", encoding="utf-8").read()
chunks = my_chunker(text)              # strings, dicts or framework objects

chunkscope.report(chunks, source=text, max_tokens=512, open_browser=True)

This writes chunkscope-report.html next to your script and opens it. Change the path with output=. In a Jupyter notebook, chunkscope.analyze(chunks, source=text) displays the report inline.

A chunk can be as simple as a string. Offsets make placement exact and are recommended when your chunker knows them:

python
chunks = [
    {"text": "First chunk ...", "start": 0, "end": 512, "metadata": {"section": "Intro"}},
    {"text": "Second chunk ...", "start": 448, "end": 960},
]
chunkscope.report(chunks, source=text)

Frameworks

Hand chunkscope the objects your framework returns. Pass the documents you split as sources so every chunk is matched to its document.

LangChain

python
from langchain_text_splitters import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50, add_start_index=True)
chunks = splitter.split_documents(docs)        # docs: your loaded Documents
chunkscope.report(chunks, sources=docs)

add_start_index=True gives exact offsets. Without it, chunkscope finds the chunks by searching the text.

LlamaIndex

python
from llama_index.core.node_parser import SentenceSplitter

nodes = SentenceSplitter(chunk_size=256, chunk_overlap=20).get_nodes_from_documents(documents)
chunkscope.report(nodes, sources=documents)

Haystack

python
from haystack.components.preprocessors import DocumentSplitter

splitter = DocumentSplitter(split_by="word", split_length=150, split_overlap=20)
splitter.warm_up()
chunks = splitter.run(documents=docs)["documents"]
chunkscope.report(chunks, sources=docs)

Chonkie

python
from chonkie import RecursiveChunker

chunker = RecursiveChunker(chunk_size=512)
chunkscope.report(chunker(text), source=text)

# Several texts: one list of chunks per text, paired by position
chunkscope.report(chunker.chunk_batch(texts), sources=texts)

Docling and Unstructured (experimental)

python
# Docling: compare the chunks with the Markdown export of the converted document
doc = DocumentConverter().convert("report.pdf").document
chunks = list(HybridChunker().chunk(dl_doc=doc))
chunkscope.report(chunks, source=doc.export_to_markdown())

# Unstructured: compare the chunks with the text of the partitioned elements
elements = partition(filename="report.pdf")
chunks = chunk_by_title(elements)
chunkscope.report(chunks, source="\n\n".join(el.text for el in elements))

These two do not expose character offsets, so chunks are located by search. Some may show as partial matches when the chunk text is formatted differently from the source. Page numbers, headings and file names appear in each chunk's metadata.

What chunkscope reads from each format

InputFields usedPlacement
Plain strings and dictstext, start/end, doc_id, metadataExact with offsets, otherwise located by search
LangChainpage_content, metadata["start_index"], metadata["source"]Exact with add_start_index=True
LlamaIndextext, start_char_idx / end_char_idx, ref_doc_idExact
Haystack 2.xcontent, meta["split_idx_start"], meta["source_id"]Exact
Chonkietext, start_index / end_index, token_countExact
Docling (experimental)text, meta.headings, page numbers, file nameLocated by search
Unstructured (experimental)text, metadata (page_number, filename)Located by search
chunkscope.Chunk or any object with .texttext, start / end, id, doc_id, metadata, scoreExact with offsets, otherwise located by search
(chunk, score) pairsany of the above + a score (LangChain similarity_search_with_score)As the chunk
LlamaIndex NodeWithScorethe node + its scoreAs the node
A list of listsone list of chunks per document, paired with sources by positionAs the chunks

Detection is automatic. To skip it, pass framework="langchain" (or llamaindex, haystack, chonkie, docling, unstructured, dict, text).

Several documents

One report can cover a whole corpus. Give the sources as a mapping or as a list, and chunkscope groups the chunks by document:

python
sources = {"guide.md": guide_text, "faq.md": faq_text}
chunks = [
    {"text": "...", "doc_id": "guide.md"},
    {"text": "...", "doc_id": "docs/faq.md"},   # also matches "faq.md" by file name
]
chunkscope.report(chunks, sources=sources)
  • Chunks find their document through doc_id or source (dicts), metadata["source"] (LangChain), ref_doc_id (LlamaIndex) or meta["source_id"] (Haystack).
  • A list of lists is read as one list of chunks per document, paired with sources by position.
  • Chunks that match no document are kept in a separate group, never dropped. A document that produced no chunks is reported as a warning.
  • Without any source, chunks are still listed, measured and checked, but cannot be shown in context.

Counting tokens

Chunk limits only mean something in the tokens of your embedding model. Pass a counter that matches it. Without one, sizes are counted in characters and the report says so.

python
from chunkscope.tokenizers import huggingface_counter, tiktoken_counter

chunkscope.report(chunks, source=text, token_counter=huggingface_counter("BAAI/bge-small-en-v1.5"), max_tokens=512)
chunkscope.report(chunks, source=text, token_counter=tiktoken_counter("cl100k_base"), max_tokens=8191)
chunkscope.report(chunks, source=text, token_counter=model)          # a sentence-transformers model
chunkscope.report(chunks, source=text, token_counter=lambda t: len(t.split()), size_unit="words")

Any function from a string to an integer works, and so does any tokenizer object with an encode() method.

Visualization options

Every report has a Colour by menu above the source text. Switching is instant and works offline.

Colour byShowsUse it to
ChunkAlternating colours, a #n marker where each chunk startsSee the boundaries
SizeSmall to large (one blue scale); over max_tokens in redFind chunks that are too big or too small
IssuesThe worst issue of each chunk: info, ▲ warning, ✕ errorJump to problems
Retrieval scoreLow to high score (one orange scale); unscored chunks dimmedSee what a query retrieves, in context
Metadata: keyOne colour per value of a field (section, page, heading…), with a legendCheck that structure survived chunking
  • Chunk map: a strip above the text shows the whole document, one bar per chunk, overlapping chunks on extra rows and gaps in red. Click a bar to open its chunk.
  • Overlaps are drawn in both chunks' colours (earlier chunk on top, next chunk below) inside a dashed box, in every colouring.
  • Theme: a button switches automatic, light and dark.
python
chunkscope.report(chunks, source=text, color_by="size", max_tokens=512)
chunkscope.report(chunks, source=text, color_by="meta:section", color_metadata=["section", "page"])
chunkscope.report(chunks, source=text, theme="dark")

Metadata fields are offered automatically when they are present on most chunks, vary within a document and are not unique ids. color_metadata= chooses them yourself.

See what a query retrieves

Give chunkscope the scores of a query and the report opens coloured by score, with a ranked table of the best chunks and a “retrieval rank” order for the chunk cards. You see what was retrieved and what sits right next to it.

python
# LangChain: (Document, score) pairs work as chunks
hits = vectorstore.similarity_search_with_score(query, k=50)
chunkscope.report(hits, sources=docs, query=query)

# LlamaIndex: NodeWithScore works as a chunk
chunkscope.report(retriever.retrieve(query), sources=documents, query=query)

# Any retriever: one score per chunk, or {position or id: score} for a subset
chunkscope.report(chunks, source=text, scores=scores, query=query)

Scoring every chunk, not only the top results, shows near misses: the chunk that should have been retrieved and how far it ranked.

Compare chunkings

chunkscope.compare() puts several chunkings of the same documents in one report: a table comparing the runs, documents grouped by run, and a Compare runs tab that stacks the chunk map of every run on the same scale.

python
runs = {f"{size} / {overlap}": split(size, overlap) for size, overlap in [(500, 50), (1000, 100)]}
result = chunkscope.compare(runs, sources=docs, max_tokens=512)
chunkscope.save(result, "compare.html")
shell
chunkscope compare small.jsonl large.jsonl --source guide.md

The report

Every call to report(), save() or the command line produces the same thing: one HTML page that shows your chunks in their documents. This section explains what is on it and how to work with it. Every example links to the live demo report, so you can follow along.

One file, offline

Self-contained

Styles, scripts and data are inside one .html file. Nothing to install, no server: double-click it, or use open_browser=True / --open.

Offline by design

A Content-Security-Policy blocks every network request, so the page works without internet and cannot send your text anywhere.

Share it carefully

It contains your documents and chunks. Share it like the documents themselves: a CI artifact or a pull request in a private repository, never a public one.

Size

About the size of your documents, times the number of runs in a comparison. Thousands of chunks are fine; for huge corpora, report per folder or on a sample.

Anatomy of the page

Every document page has the same layout:

Report titleTheme: autoOverviewDocumentsguide.md ▲ 3api.mdfaq.md ▲ 1
guide.md
SourceChunksIssuesCompare runs
Colour by ▾

#0Fresh beans matter more than expensive equipment. Buy whole beans

roasted within four weeks and grind them just before brewing.

## Grind size

#2| Method | Grind | Brew time |

#1 exact 212 tokens

Hover or click a number to see where it is. Click again to release.

The overview page

The report opens on the overview (demo), which answers “is my chunking healthy?” at a glance:

Chunking report
7documents282chunks32median30over 12093%coverage
Query: “recover a node after a disk failure?”1 12.5 runbook #22 11.5 runbook #33 11.2 replication #8
Runsheading-aware · 69 · 0 errorsfixed-size · 42 · 27 errorsblocks · 171 · 4 errors
Documentsoverview.md · 12 · 94%install.md · 11 · 95%runbook.md · 12 · 95%
Issues by type✕ over_limit · 31▲ gaps · 21▲ split_code_block · 15

Hover or click a number to see where it is. Click again to release.

A document page

Click a document in the navigation or in the Documents table. Its page has up to four tabs.

Source shows the document as the chunker received it, exactly like the example at the top of this page. Each mark means something; Show me takes you to it in the example.

You seeIt means
Coloured text with a #n markerChunk n starts here and covers the coloured text. With “Colour by: Chunk”, neighbouring chunks alternate colours.
Text in two colours, in a dashed boxAn overlap: the text belongs to two or more chunks. Top half: the earlier chunk; bottom half: the next one. Click again to switch between them.
Red textA gap: no chunk contains this text, so it can never be retrieved. Expected for headings kept as metadata; a problem for real content.
A dashed underlineA partial match: the chunker changed the text (here, it repeated the table header), so only part of the chunk is in the source.
A note above the textChunks that could not be placed (unmatched), with a link to their card.

Chunks (demo) lists one card per chunk:

  • Header: #n; the placement status (exact, normalized, partial, unmatched or no source; hover it for an explanation); the size, red when over the limit, with a bar against the limit; the character range; the retrieval rank and score; and show in source.
  • Issues of the chunk, each with its severity and a plain-language explanation.
  • Metadata (collapsed): your metadata, plus the id, parent id, document id and the offsets the chunker gave.
  • Text: the full chunk, exactly as it will be embedded.

Use Show only chunks with errors or warnings to triage, and, when the chunks have scores, Order: retrieval rank to read them in the order the retriever ranked them.

Issues (demo) lists every finding for the document, worst first, each linked to its chunk. Compare runs (demo) appears in comparisons: the chunk map of every run for this document, on the same scale, with each run's numbers; click a bar to open that run's chunk.

Every view has its own address, so you can bookmark it or send it with the file (“open the report at #d3:c12”):

demo-report.html#d4:c2Open ↗

Opens “05 · Operations Runbook” (heading-aware), chunk #2 selected in the source.

The address formats:

AddressOpensDemo
#overviewThe overview pageopen
#d4Document 4 (counted from 0, in navigation order), on its first tabopen
#d4:chunks, #d4:issues, #d4:compareA specific tab of document 4open
#d4:c2Chunk 2 of document 4, selected and highlighted in the sourceopen
#d4:chunks:c2The card of chunk 2 in the Chunks tabopen

Clicking text updates the address, so the link you copy from the address bar always points to the chunk you are looking at.

How to use it

Change one setting, regenerate, refresh.

  1. 1Read the overview: errors, chunks over the limit, the shape of the histogram, the lowest coverage.
  2. 2Open the worst document from the Documents table.
  3. 3Set Colour by to Issues and click the red and amber text to read what is wrong.
  4. 4Fix the chunker, run again and refresh the page: the numbers should move the right way.
Try it in the demo: A fixed-size run with overlaps ↗

How chunks are placed

Chunkers differ in what they return, so chunkscope works at three levels of fidelity, and every chunker reaches at least the last one:

  1. Exact. The chunk carries character offsets that match the source.
  2. Located. Text only, or offsets that do not match. chunkscope searches the source for an exact match, then for a match that ignores whitespace, then piece by piece for chunks the chunker transformed. Such chunks are marked partial with the share of text that was found.
  3. Listed. The text cannot be found, or no source was given. The chunk is still measured and checked.

The search follows document order, starting after the previous chunk, so overlapping chunks and repeated passages land on the right occurrence.

Tests and CI

Every report is also data. Use it to stop chunking regressions before they reach your index:

python
def test_chunking_quality():
    result = chunkscope.analyze(chunk(doc), source=doc, max_tokens=512)
    summary = result.summary()
    assert summary["errors"] == 0
    assert summary["coverage"] > 0.99
shell
chunkscope report chunks.jsonl --source-dir docs --max-tokens 512 --fail-on error   # exit code 3 on errors

Privacy

  • Everything runs locally. chunkscope sends nothing anywhere and has no telemetry.
  • The report is a single file with inline styles and scripts. A Content-Security-Policy stops the page from loading or sending anything over the network, even if the file is opened on another computer.
  • All text is HTML-escaped, so chunk content cannot inject markup.
  • The report contains your document text. Treat it like the documents themselves and do not commit it to a public repository.

FAQ and limits

Why is my coverage below 100%?

Open the source view and look at the red text. Headings removed by a Markdown splitter are a common, harmless cause. Missing paragraphs are not.

Why are some chunks "partial"?

Your chunker changed the text: it added a title or context line, repeated a table header or cleaned up markup. Only part of the chunk exists in the source, and that part is highlighted.

Can I see chunks on the original PDF page?

Not yet. chunkscope shows the extracted text the chunker received. A page view with bounding boxes is planned.

What is next?

A live view that re-runs your chunker on every refresh, a page view that draws chunks on the original PDF, and a hierarchy view for parent and child chunks. Comparing chunkings and the retrieval overlay are already available: see Comparing chunkings and Retrieval.

Reference

API reference

Every public method, with its parameters, what it returns, the errors it raises, and its different usages. The same reference is in docs/API.md in the package.

MethodKindUse it to
chunkscope.report()functionAnalyze chunks and write the HTML report in one call.
chunkscope.analyze()functionAnalyze chunks without writing anything. The core of every other call.
chunkscope.compare()functionAnalyze several chunkings of the same documents in one report.
chunkscope.save()functionWrite a Report to one self-contained HTML file.
chunkscope.render_html()functionGet the report page as a string, to serve or store it yourself.
ReportclassThe result of analyze() and compare(). Use it in code, tests and CI.
ChunkclassThe generic chunk contract every input is converted to. You can also pass Chunk objects directly.
chunkscope.tokenizersmoduleSize counters, so limits match your embedding model.
chunkscope.adaptersmoduleAdvanced: how inputs are read. Useful to debug how an object is understood.
chunkscope report / comparecommand lineThe command line, for chunks saved as JSON Lines or JSON.

chunkscope.report()

function

Analyze chunks and write the HTML report in one call.

signature
chunkscope.report(
    chunks, source=None, *,
    output="chunkscope-report.html", open_browser=False,
    **options,            # every keyword argument of analyze()
) -> Report

Parameters

NameTypeDefaultDescription
chunksiterablerequiredThe chunks, in any accepted format (strings, dicts, framework objects, (chunk, score) pairs, a list of lists).
sourcestr | documentNoneThe text every chunk comes from (one document).
outputstr | Path"chunkscope-report.html"Where to write the report. Missing folders are created.
open_browserboolFalseOpen the report in the default browser after writing it.
**optionssources, framework, token_counter, size_unit, max_tokens, min_tokens, title, scores, query, color_by, color_metadata, theme: see analyze().

Returns: The Report, so you can use summary() or issues right away.

Raises:
  • TypeError, ValueError: Same as analyze()
  • OSError: The file cannot be written

Usages (4)

python
import chunkscope

chunks = my_chunker(text)
chunkscope.report(chunks, source=text)          # writes chunkscope-report.html

chunkscope.analyze()

function

Analyze chunks without writing anything. The core of every other call.

signature
chunkscope.analyze(
    chunks, source=None, *,
    sources=None, framework=None,
    token_counter=None, size_unit=None, max_tokens=None, min_tokens=None,
    title="Chunking report",
    scores=None, query=None,
    color_by=None, color_metadata=None, theme="auto",
) -> Report

Parameters

NameTypeDefaultDescription
chunksiterablerequiredThe chunks, in any accepted format. A list of lists means one list of chunks per document, paired with sources by position.
sourcestr | documentNoneThe text of a single document. Every chunk is placed in it.
sourcesmapping | listNoneSeveral documents: {id: text}, or a list of strings, dicts {"id", "text", "title"} or LangChain / LlamaIndex / Haystack documents. Chunks are matched to them by document id, then by file name. Cannot be combined with source.
frameworkstrNoneSkip auto-detection: "text", "dict", "langchain", "llamaindex", "haystack", "chonkie", "docling", "unstructured" or "generic".
token_countercallable | tokenizerNoneHow sizes are measured: any callable(str) -> int, or a tokenizer with encode() (tiktoken, Hugging Face, sentence-transformers model). Default: characters.
size_unitstr"tokens" / "chars"The unit shown in the report. "tokens" when a counter is given, otherwise "chars".
max_tokensintNoneChunks larger than this are flagged as over_limit errors.
min_tokensintNoneChunks smaller than this are flagged as under_limit warnings.
titlestr"Chunking report"Report title.
scoreslist | mappingNoneRetrieval scores: a list aligned with the chunks (input order), or {position: score} / {chunk id: score} for a subset. None means "not scored".
querystrNoneThe query the scores belong to, shown in the report.
color_bystr"score" or "chunk"The colouring the report opens with: "chunk", "size", "issues", "score" or "meta:<key>". "score" by default when any chunk is scored.
color_metadatastr | listautomaticMetadata keys offered as colourings (up to four). Picked automatically when omitted.
themestr"auto""auto" (follow the system), "light" or "dark".

Returns: A Report: documents, chunks, issues and summary(). Nothing is written to disk.

Raises:
  • TypeError: chunks is a single string or dict; a chunk has an unsupported type; token_counter does not return an int
  • ValueError: source and sources both given; a dict chunk has no text; unknown framework, theme or color_by; scores of the wrong length or naming a missing id; a list of lists with a different number of sources

Usages (8)

python
# Located in the text by search
result = chunkscope.analyze(["First chunk ...", "Second chunk ..."], source=text)

chunkscope.compare()

function

Analyze several chunkings of the same documents in one report.

signature
chunkscope.compare(
    runs, source=None, *,
    sources=None, title="Chunking comparison",
    **options,            # analyze() options; scores is per run
) -> Report

Parameters

NameTypeDefaultDescription
runsmappingrequired{label: chunks}, one entry per run. Labels are shown in the report.
source / sourcesNoneAs in analyze(), shared by every run.
titlestr"Chunking comparison"Report title.
scoresmappingNone{run label: scores}: retrieval scores for some runs, in any form analyze() accepts.
**optionsEvery other analyze() keyword argument, applied to every run.

Returns: A Report whose runs lists the labels. The overview compares the runs, and every document gets a Compare runs tab with each run's chunk map on the same scale.

Raises:
  • ValueError: runs is empty or not a mapping; scores is not keyed by run labels; otherwise as analyze()

Usages (3)

python
from langchain_text_splitters import RecursiveCharacterTextSplitter

def split(size, overlap):
    return RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap,
                                          add_start_index=True).split_documents(docs)

result = chunkscope.compare({"500 / 50": split(500, 50), "1000 / 100": split(1000, 100)},
                            sources=docs, max_tokens=512)
chunkscope.save(result, "compare.html")

chunkscope.save()

function

Write a Report to one self-contained HTML file.

signature
chunkscope.save(result, output="chunkscope-report.html", open_browser=False) -> Path

Parameters

NameTypeDefaultDescription
resultReportrequiredFrom analyze() or compare().
outputstr | Path"chunkscope-report.html"File to write; ~ is expanded and missing folders are created.
open_browserboolFalseOpen the file in the default browser.

Returns: The path of the written file.

Usages (2)

python
result = chunkscope.analyze(chunks, source=text)
path = chunkscope.save(result, "reports/chunks.html")

chunkscope.render_html()

function

Get the report page as a string, to serve or store it yourself.

signature
chunkscope.render_html(result) -> str

Returns: The complete HTML page, with its Content-Security-Policy that blocks all network requests.

In Jupyter you do not need it: a Report displays itself inline when it is the last line of a cell.

Usages (3)

python
from fastapi.responses import HTMLResponse

@app.get("/debug/chunks", response_class=HTMLResponse)
def chunks_page():
    result = chunkscope.analyze(load_chunks(), sources=load_docs())
    return chunkscope.render_html(result)

Report

class

The result of analyze() and compare(). Use it in code, tests and CI.

signature
result.documents      # list[DocumentResult]
result.chunks         # list[ChunkResult], every chunk of every document
result.issues         # list[Issue], document- and chunk-level
result.summary()      # dict of headline numbers

Attributes

NameTypeDescription
documentslist[DocumentResult]One per document (per run for compare()): id, title, text, chunks, issues, all_issues, gaps, overlaps, coverage, run.
chunkslist[ChunkResult]Every chunk: index, chunk, size, chars, status (exact, normalized, partial, unmatched, no_source), start, end, match_ratio, issues, score, rank, located.
issueslist[Issue]Every issue: code, severity (error, warning, info), message, chunk (index in its document, or None).
summary()dictdocuments, chunks, size_unit, min_size, median_size, max_size, over_limit, errors, warnings, infos, coverage (lowest document coverage, or None).
size_unit, max_size, min_sizeThe unit and the limits used for the checks.
frameworks, query, runsDetected chunk formats, the retrieval query, the run labels of compare().
color_by, color_metadata, themeDisplay settings; can be changed before save().

Usages (3)

python
def test_chunking_quality():
    summary = chunkscope.analyze(chunk(doc), source=doc, max_tokens=512).summary()
    assert summary["errors"] == 0
    assert summary["coverage"] > 0.99

Chunk

class

The generic chunk contract every input is converted to. You can also pass Chunk objects directly.

signature
Chunk(text, start=None, end=None, id=None, parent_id=None,
      doc_id=None, metadata={}, score=None)

Fields

NameTypeDefaultDescription
textstrrequiredThe chunk text. The only required field.
start, endint | NoneNoneCharacter offsets in the source (end exclusive). Exact placement when they match.
idstr | NoneNoneYour chunk id; usable as a key in scores.
parent_idstr | NoneNoneFor hierarchical chunkers.
doc_idstr | NoneNoneWhich source document the chunk comes from.
metadatadict{}Anything; shown on the chunk card and usable as a colouring.
scorefloat | NoneNoneRetrieval score.

Usages (2)

python
from chunkscope import Chunk

chunks = [Chunk(text[s:e], start=s, end=e, metadata={"page": p}) for s, e, p in spans]
chunkscope.report(chunks, source=text)

chunkscope.tokenizers

module

Size counters, so limits match your embedding model.

signature
from chunkscope.tokenizers import (
    characters, words,
    tiktoken_counter, huggingface_counter,
    as_counter, from_spec,
)

Functions

NameReturnsDescription
characters(text)intLength in characters. The default.
words(text)intWhitespace-separated words.
tiktoken_counter(encoding="cl100k_base")counterA tiktoken encoding or model name. Needs pip install "chunkscope[tiktoken]".
huggingface_counter(name, add_special_tokens=False)counterA Hugging Face tokenizer by model name (tokenizers or transformers). Needs pip install "chunkscope[hf]"; downloads the tokenizer files on first use.
as_counter(obj)counterTurns a callable or any tokenizer with encode() into a counter. This is what token_counter= uses.
from_spec(spec)(counter, unit)Parses the CLI form: chars, words, tiktoken:<encoding>, hf:<model>.

Usages (4)

python
from chunkscope.tokenizers import tiktoken_counter
chunkscope.report(chunks, source=text, token_counter=tiktoken_counter("cl100k_base"), max_tokens=8191)

chunkscope.adapters

module

Advanced: how inputs are read. Useful to debug how an object is understood.

signature
from chunkscope.adapters import detect, to_chunk, to_sources

Functions

NameReturnsDescription
detect(obj)strThe detected format name; TypeError if unsupported.
to_chunk(obj, framework=None)(Chunk, str)One input converted to a Chunk, with the format used.
to_sources(sources)list[SourceDocument]The sources= argument normalized to id, text, title.

Usage

python
from chunkscope.adapters import detect, to_chunk

detect(chunks[0])                  # 'langchain'
chunk, name = to_chunk(chunks[0])
print(chunk.start, chunk.doc_id, chunk.metadata)

chunkscope report / compare

command line

The command line, for chunks saved as JSON Lines or JSON.

usage
chunkscope report  CHUNKS            [options]    # one chunking
chunkscope compare CHUNKS CHUNKS...  [options]    # each file name is a run label
chunkscope --version

Options

NameTypeDefaultDescription
CHUNKSfilerequiredJSON Lines (one chunk per line) or a JSON list, with the same fields as dict chunks, including score.
-s, --source FILErequiredA source document; repeat for several. A single source takes every chunk without a document id.
--source-dir DIRrequiredRead the sources named by the chunks' doc_id / source, inside DIR only.
-o, --output FILEchunkscope-report.htmlReport path.
--tokenizer SPECcharschars, words, tiktoken:<encoding>, hf:<model>.
--max-tokens N, --min-tokens NrequiredSize limits.
--color-by MODErequiredchunk, size, issues, score or meta:<key>.
--themeautoauto, light or dark.
--query TEXTrequiredThe query behind the chunks' score values.
--title TEXT, --openrequiredReport title; open the report in the browser.
--fail-on error|warningrequiredExit with status 3 when issues of that severity or worse exist. Exit codes: 0 written, 1 error, 2 usage, 3 threshold reached.

Usages (4)

shell
chunkscope report chunks.jsonl --source guide.md --open
chunkscope report chunks.jsonl --source-dir docs/ --tokenizer hf:BAAI/bge-small-en-v1.5 --max-tokens 512

Checks

CheckSeverityMeaning
over_limiterrorThe chunk is larger than max_tokens. Embedding models silently truncate the rest.
emptyerrorThe chunk has no text.
under_limitwarningThe chunk is smaller than min_tokens and carries little meaning.
gapswarningSource text that is in no chunk, so it can never be retrieved.
split_code_blockwarningA ``` code fence is opened or closed in another chunk.
starts_in_tablewarningTable rows are separated from their header.
ends_in_tablewarningThe table continues in the next chunk.
starts_mid_word / ends_mid_wordwarningThe boundary cuts a word in half.
heading_onlywarningThe chunk is only a heading; its content is elsewhere.
unmatchedwarningThe chunk text cannot be found in the source.
offset_mismatchwarningThe chunk's own offsets point to different text.
ends_mid_sentenceinfoThe boundary falls inside a sentence.
partialinfoThe chunker transformed the text (added headers or context); only part of it was found.
duplicateinfoSame text as an earlier chunk: it is embedded and retrieved twice.
no_chunkswarningDocument level: a document produced no chunks, so none of it is retrievable.
no_sourceinfoDocument level: no source text was given or matched, so the chunks are listed but not placed.

Checks that depend on boundaries (word, sentence and table cuts) only run on chunks placed exactly, so transformed chunks do not cause false alarms.