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.
1 chunk could not be placed in the source:
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.
Installation
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:
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:
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
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
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
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
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)
# 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
| Input | Fields used | Placement |
|---|---|---|
| Plain strings and dicts | text, start/end, doc_id, metadata | Exact with offsets, otherwise located by search |
| LangChain | page_content, metadata["start_index"], metadata["source"] | Exact with add_start_index=True |
| LlamaIndex | text, start_char_idx / end_char_idx, ref_doc_id | Exact |
| Haystack 2.x | content, meta["split_idx_start"], meta["source_id"] | Exact |
| Chonkie | text, start_index / end_index, token_count | Exact |
| Docling (experimental) | text, meta.headings, page numbers, file name | Located by search |
| Unstructured (experimental) | text, metadata (page_number, filename) | Located by search |
| chunkscope.Chunk or any object with .text | text, start / end, id, doc_id, metadata, score | Exact with offsets, otherwise located by search |
| (chunk, score) pairs | any of the above + a score (LangChain similarity_search_with_score) | As the chunk |
| LlamaIndex NodeWithScore | the node + its score | As the node |
| A list of lists | one list of chunks per document, paired with sources by position | As 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:
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_idorsource(dicts),metadata["source"](LangChain),ref_doc_id(LlamaIndex) ormeta["source_id"](Haystack). - A list of lists is read as one list of chunks per document, paired with
sourcesby 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.
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 by | Shows | Use it to |
|---|---|---|
| Chunk | Alternating colours, a #n marker where each chunk starts | See the boundaries |
| Size | Small to large (one blue scale); over max_tokens in red | Find chunks that are too big or too small |
| Issues | The worst issue of each chunk: info, ▲ warning, ✕ error | Jump to problems |
| Retrieval score | Low to high score (one orange scale); unscored chunks dimmed | See what a query retrieves, in context |
| Metadata: key | One colour per value of a field (section, page, heading…), with a legend | Check 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.
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.
# 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.
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")
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:
#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 |
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:
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 see | It means | |
|---|---|---|
Coloured text with a #n marker | Chunk n starts here and covers the coloured text. With “Colour by: Chunk”, neighbouring chunks alternate colours. | |
| Text in two colours, in a dashed box | An 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 text | A 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 underline | A 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 text | Chunks 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,unmatchedorno 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.
Links to any view
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:
| Address | Opens | Demo |
|---|---|---|
#overview | The overview page | open |
#d4 | Document 4 (counted from 0, in navigation order), on its first tab | open |
#d4:chunks, #d4:issues, #d4:compare | A specific tab of document 4 | open |
#d4:c2 | Chunk 2 of document 4, selected and highlighted in the source | open |
#d4:chunks:c2 | The card of chunk 2 in the Chunks tab | open |
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.
- 1Read the overview: errors, chunks over the limit, the shape of the histogram, the lowest coverage.
- 2Open the worst document from the Documents table.
- 3Set Colour by to Issues and click the red and amber text to read what is wrong.
- 4Fix the chunker, run again and refresh the page: the numbers should move the right way.
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:
- Exact. The chunk carries character offsets that match the source.
- 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
partialwith the share of text that was found. - 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:
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
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.
| Method | Kind | Use it to |
|---|---|---|
chunkscope.report() | function | Analyze chunks and write the HTML report in one call. |
chunkscope.analyze() | function | Analyze chunks without writing anything. The core of every other call. |
chunkscope.compare() | function | Analyze several chunkings of the same documents in one report. |
chunkscope.save() | function | Write a Report to one self-contained HTML file. |
chunkscope.render_html() | function | Get the report page as a string, to serve or store it yourself. |
Report | class | The result of analyze() and compare(). Use it in code, tests and CI. |
Chunk | class | The generic chunk contract every input is converted to. You can also pass Chunk objects directly. |
chunkscope.tokenizers | module | Size counters, so limits match your embedding model. |
chunkscope.adapters | module | Advanced: how inputs are read. Useful to debug how an object is understood. |
chunkscope report / compare | command line | The command line, for chunks saved as JSON Lines or JSON. |
chunkscope.report()
functionAnalyze chunks and write the HTML report in one call.
chunkscope.report(
chunks, source=None, *,
output="chunkscope-report.html", open_browser=False,
**options, # every keyword argument of analyze()
) -> Report
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
chunks | iterable | required | The chunks, in any accepted format (strings, dicts, framework objects, (chunk, score) pairs, a list of lists). |
source | str | document | None | The text every chunk comes from (one document). |
output | str | Path | "chunkscope-report.html" | Where to write the report. Missing folders are created. |
open_browser | bool | False | Open the report in the default browser after writing it. |
**options | sources, 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.
TypeError, ValueError: Same as analyze()OSError: The file cannot be written
Usages (4)
import chunkscope
chunks = my_chunker(text)
chunkscope.report(chunks, source=text) # writes chunkscope-report.html
chunkscope.analyze()
functionAnalyze chunks without writing anything. The core of every other call.
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
| Name | Type | Default | Description |
|---|---|---|---|
chunks | iterable | required | The chunks, in any accepted format. A list of lists means one list of chunks per document, paired with sources by position. |
source | str | document | None | The text of a single document. Every chunk is placed in it. |
sources | mapping | list | None | Several 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. |
framework | str | None | Skip auto-detection: "text", "dict", "langchain", "llamaindex", "haystack", "chonkie", "docling", "unstructured" or "generic". |
token_counter | callable | tokenizer | None | How sizes are measured: any callable(str) -> int, or a tokenizer with encode() (tiktoken, Hugging Face, sentence-transformers model). Default: characters. |
size_unit | str | "tokens" / "chars" | The unit shown in the report. "tokens" when a counter is given, otherwise "chars". |
max_tokens | int | None | Chunks larger than this are flagged as over_limit errors. |
min_tokens | int | None | Chunks smaller than this are flagged as under_limit warnings. |
title | str | "Chunking report" | Report title. |
scores | list | mapping | None | Retrieval scores: a list aligned with the chunks (input order), or {position: score} / {chunk id: score} for a subset. None means "not scored". |
query | str | None | The query the scores belong to, shown in the report. |
color_by | str | "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_metadata | str | list | automatic | Metadata keys offered as colourings (up to four). Picked automatically when omitted. |
theme | str | "auto" | "auto" (follow the system), "light" or "dark". |
Returns: A Report: documents, chunks, issues and summary(). Nothing is written to disk.
TypeError: chunks is a single string or dict; a chunk has an unsupported type; token_counter does not return an intValueError: 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)
# Located in the text by search
result = chunkscope.analyze(["First chunk ...", "Second chunk ..."], source=text)
chunkscope.compare()
functionAnalyze several chunkings of the same documents in one report.
chunkscope.compare(
runs, source=None, *,
sources=None, title="Chunking comparison",
**options, # analyze() options; scores is per run
) -> Report
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
runs | mapping | required | {label: chunks}, one entry per run. Labels are shown in the report. |
source / sources | None | As in analyze(), shared by every run. | |
title | str | "Chunking comparison" | Report title. |
scores | mapping | None | {run label: scores}: retrieval scores for some runs, in any form analyze() accepts. |
**options | Every 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.
ValueError: runs is empty or not a mapping; scores is not keyed by run labels; otherwise as analyze()
Usages (3)
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()
functionWrite a Report to one self-contained HTML file.
chunkscope.save(result, output="chunkscope-report.html", open_browser=False) -> Path
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
result | Report | required | From analyze() or compare(). |
output | str | Path | "chunkscope-report.html" | File to write; ~ is expanded and missing folders are created. |
open_browser | bool | False | Open the file in the default browser. |
Returns: The path of the written file.
Usages (2)
result = chunkscope.analyze(chunks, source=text)
path = chunkscope.save(result, "reports/chunks.html")
chunkscope.render_html()
functionGet the report page as a string, to serve or store it yourself.
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)
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
classThe result of analyze() and compare(). Use it in code, tests and CI.
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
| Name | Type | Description |
|---|---|---|
documents | list[DocumentResult] | One per document (per run for compare()): id, title, text, chunks, issues, all_issues, gaps, overlaps, coverage, run. |
chunks | list[ChunkResult] | Every chunk: index, chunk, size, chars, status (exact, normalized, partial, unmatched, no_source), start, end, match_ratio, issues, score, rank, located. |
issues | list[Issue] | Every issue: code, severity (error, warning, info), message, chunk (index in its document, or None). |
summary() | dict | documents, 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_size | The unit and the limits used for the checks. | |
frameworks, query, runs | Detected chunk formats, the retrieval query, the run labels of compare(). | |
color_by, color_metadata, theme | Display settings; can be changed before save(). |
Usages (3)
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
classThe generic chunk contract every input is converted to. You can also pass Chunk objects directly.
Chunk(text, start=None, end=None, id=None, parent_id=None,
doc_id=None, metadata={}, score=None)
Fields
| Name | Type | Default | Description |
|---|---|---|---|
text | str | required | The chunk text. The only required field. |
start, end | int | None | None | Character offsets in the source (end exclusive). Exact placement when they match. |
id | str | None | None | Your chunk id; usable as a key in scores. |
parent_id | str | None | None | For hierarchical chunkers. |
doc_id | str | None | None | Which source document the chunk comes from. |
metadata | dict | {} | Anything; shown on the chunk card and usable as a colouring. |
score | float | None | None | Retrieval score. |
Usages (2)
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
moduleSize counters, so limits match your embedding model.
from chunkscope.tokenizers import (
characters, words,
tiktoken_counter, huggingface_counter,
as_counter, from_spec,
)
Functions
| Name | Returns | Description |
|---|---|---|
characters(text) | int | Length in characters. The default. |
words(text) | int | Whitespace-separated words. |
tiktoken_counter(encoding="cl100k_base") | counter | A tiktoken encoding or model name. Needs pip install "chunkscope[tiktoken]". |
huggingface_counter(name, add_special_tokens=False) | counter | A Hugging Face tokenizer by model name (tokenizers or transformers). Needs pip install "chunkscope[hf]"; downloads the tokenizer files on first use. |
as_counter(obj) | counter | Turns 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)
from chunkscope.tokenizers import tiktoken_counter
chunkscope.report(chunks, source=text, token_counter=tiktoken_counter("cl100k_base"), max_tokens=8191)
chunkscope.adapters
moduleAdvanced: how inputs are read. Useful to debug how an object is understood.
from chunkscope.adapters import detect, to_chunk, to_sources
Functions
| Name | Returns | Description |
|---|---|---|
detect(obj) | str | The 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
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 lineThe command line, for chunks saved as JSON Lines or JSON.
chunkscope report CHUNKS [options] # one chunking
chunkscope compare CHUNKS CHUNKS... [options] # each file name is a run label
chunkscope --version
Options
| Name | Type | Default | Description |
|---|---|---|---|
CHUNKS | file | required | JSON Lines (one chunk per line) or a JSON list, with the same fields as dict chunks, including score. |
-s, --source FILE | required | A source document; repeat for several. A single source takes every chunk without a document id. | |
--source-dir DIR | required | Read the sources named by the chunks' doc_id / source, inside DIR only. | |
-o, --output FILE | chunkscope-report.html | Report path. | |
--tokenizer SPEC | chars | chars, words, tiktoken:<encoding>, hf:<model>. | |
--max-tokens N, --min-tokens N | required | Size limits. | |
--color-by MODE | required | chunk, size, issues, score or meta:<key>. | |
--theme | auto | auto, light or dark. | |
--query TEXT | required | The query behind the chunks' score values. | |
--title TEXT, --open | required | Report title; open the report in the browser. | |
--fail-on error|warning | required | Exit with status 3 when issues of that severity or worse exist. Exit codes: 0 written, 1 error, 2 usage, 3 threshold reached. |
Usages (4)
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
| Check | Severity | Meaning |
|---|---|---|
over_limit | error | The chunk is larger than max_tokens. Embedding models silently truncate the rest. |
empty | error | The chunk has no text. |
under_limit | warning | The chunk is smaller than min_tokens and carries little meaning. |
gaps | warning | Source text that is in no chunk, so it can never be retrieved. |
split_code_block | warning | A ``` code fence is opened or closed in another chunk. |
starts_in_table | warning | Table rows are separated from their header. |
ends_in_table | warning | The table continues in the next chunk. |
starts_mid_word / ends_mid_word | warning | The boundary cuts a word in half. |
heading_only | warning | The chunk is only a heading; its content is elsewhere. |
unmatched | warning | The chunk text cannot be found in the source. |
offset_mismatch | warning | The chunk's own offsets point to different text. |
ends_mid_sentence | info | The boundary falls inside a sentence. |
partial | info | The chunker transformed the text (added headers or context); only part of it was found. |
duplicate | info | Same text as an earlier chunk: it is embedded and retrieved twice. |
no_chunks | warning | Document level: a document produced no chunks, so none of it is retrievable. |
no_source | info | Document 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.