chunklabel
A Python library for splitting text into categorized chunks using an LLM.
Overview
chunklabel segments text into semantically coherent spans, assigning a free-form category to each. Categories are named by the LLM without a predefined schema. Each chunk's quote is a verbatim excerpt from the source text, aligned back to the original after LLM output.
from chunklabel import ChunkLabeler
labeler = ChunkLabeler()
chunks = labeler.split(
"The project kicked off in January with a small team. "
"Budget constraints forced a scope reduction in March. "
"Despite the setbacks, the product launched successfully in June."
)
# [
# Chunk(category="initiation", quote="The project kicked off in January with a small team", start=0, end=51),
# Chunk(category="obstacle", quote="Budget constraints forced a scope reduction in March", start=53, end=104),
# Chunk(category="outcome", quote="the product launched successfully in June", start=120, end=160),
# ]
Installation
pip install chunklabel
For in-process inference with llama.cpp:
pip install "chunklabel[llamacpp]"
Data structures
The LLM returns raw chunks without span information. Alignment is performed as a separate step, producing the final Chunk with character-level positions.
# Intermediate: LLM output
@dataclass
class RawChunk:
category: str # Free-form category name assigned by the LLM
quote: str # Verbatim excerpt (may contain minor transcription noise)
# Final: after alignment
@dataclass
class Chunk:
category: str # Same as RawChunk
quote: str # Excerpt aligned to source text
start: int # Start index in source text
end: int # End index in source text
Pipeline
Input text
│
▼
LLM → [{category, quote}, ...] (RawChunk list)
│
▼
rapidfuzz alignment → (start, end) resolved per chunk
│
▼
Span post-processing (lenient mode)
│ gap-filling / overlap resolution
▼
Chunk list
Alignment
Each quote (with surrounding whitespace stripped) is located in the source text:
- Exact match, searching forward from the previous quote.
- Exact match anywhere, for a verbatim quote the LLM emitted out of order.
- Fuzzy match: the best-matching substring (
rapidfuzz.fuzz.partial_ratio_alignment), accepted if its score is at leastfuzzy_threshold. Quotes shorter than 16 characters must match exactly, since short phrases produce spurious fuzzy matches.
Lenient mode
- Gaps: the prompt asks the LLM to cover the whole text. Any part it skips, or whose quote fails to align, is filled automatically as
category="uncategorized". Check how often this happens withsplit_with_report(gap_coverage). - Overlaps: the earlier chunk takes priority; the later chunk's start is pushed forward
Category normalization (offline)
After processing multiple texts, category names can drift across runs. A dedicated normalization step lets the LLM consolidate them in batch.
from chunklabel import Normalizer
normalizer = Normalizer()
normalizer.build_mapping(all_chunks)
# {"kick-off": "initiation", "project start": "initiation", "blocker": "obstacle", ...}
normalized_chunks = normalizer.apply(all_chunks)
The mapping is stored internally after build_mapping, so it can be passed to apply implicitly. To reuse the mapping across runs without calling the LLM again:
# Save after building
normalizer.save("mapping.json")
# Restore later
normalizer = Normalizer.load("mapping.json")
normalized_chunks = normalizer.apply(all_chunks)
Normalization runs offline over the full category inventory, so the LLM can make globally consistent decisions rather than local ones.
Segmenter estimator (experimental)
ZeroShotPromptSegmenter is a scikit-learn style estimator that follows KMeans. Prompts contain no examples (zero-shot). Each segmentation is a list of (start, end, label) triples that cover the text without overlapping; text[start:end] is the segment's text.
Inducing a label set. fit(X) splits every text with free labels, as ChunkLabeler does, then merges the label names over all of X with Normalizer. fit processes every text it gets, so pass it a sample of the size you want.
from chunklabel import ZeroShotPromptSegmenter
segmenter = ZeroShotPromptSegmenter(client="gpt-4o")
segmentations = segmenter.fit_predict(texts) # list[list[tuple[int, int, str]]]
segmenter.labels_ # the label set found in texts
segmenter.mapping_ # free label -> label in labels_
new_segmentations = segmenter.predict(new_texts) # only labels from labels_
fit_predict makes one LLM pass over texts. predict prompts again with the label set, so calling it on the training texts can give different boundaries than fit_predict.
A given label set. Pass labels to use your own labels (or labels_ after editing it by hand). predict then works without fit.
segmenter = ZeroShotPromptSegmenter(
labels=["background", "methods", "results", "conclusions"], # or {label: description}
)
segmentations = segmenter.predict(texts)
- Where the backend supports it (OpenAI structured outputs, llama.cpp), the JSON schema restricts labels to the label set. Any other label is mapped to the closest allowed one (
on_unknown_label="closest"), or dropped / rejected ("drop"/"raise"). - Text that no aligned quote covers joins the preceding segment, so every label comes from the label set. Check how much text that was with
predict_with_report(see "Checking fidelity" below). get_params/set_paramsfollow scikit-learn conventions, sosklearn.base.cloneworks.ChunkLabeleris unchanged.- Calling
predictbeforefit, with nolabels, raiseschunklabel.NotFittedError(aValueErrorandAttributeError, like scikit-learn's).
Learning from examples. FewShotPromptSegmenter takes labeled texts. y holds one segmentation per text, or None for an unlabeled text (accepted, not used yet). fit makes no LLM call: it keeps the labeled texts as an example pool. predict shows n_examples of them to the LLM, as earlier turns of the conversation, and allows only the labels that occur in y.
from chunklabel import FewShotPromptSegmenter
segmenter = FewShotPromptSegmenter(n_examples=3, example_selection="similar")
segmenter.fit(train_texts, train_segmentations) # [[(start, end, label), ...], ...]
segmentations = segmenter.predict(texts)
example_selection="random"(default) uses the same examples, drawn withrandom_state, for every text."similar"picks, per text, the most similar pool texts; the most similar comes last. Similarity is TF-IDF over character 3-grams by default, which needs no extra dependency and works for text without spaces. Passembedding=(a function from a list of texts to a list of vectors, such as a sentence-transformers model'sencode) to use an embedding model instead.- A pool text identical to the input is never used as its example.
- Each example costs about twice its length in prompt tokens (its text plus the expected answer), so lower
n_examplesfor long texts. Nothing is truncated automatically.
Configuration
labeler = ChunkLabeler(
client="gpt-4o", # model name string, or a BaseLLMClient instance
fuzzy_threshold=85, # match threshold for rapidfuzz alignment (0–100)
)
Checking fidelity on your model and data
How faithfully the LLM quotes the source depends on the model and the text. Before
relying on a setup, run split_with_report on a few representative texts:
from chunklabel import ChunkLabeler
labeler = ChunkLabeler(client=my_client)
for text in sample_texts:
chunks, report = labeler.split_with_report(text)
print(
f"verbatim {report.exact_rate:.0%} fuzzy {report.fuzzy_rate:.0%} "
f"unaligned {report.unaligned_rate:.0%} not quoted {report.gap_coverage:.0%}"
)
| field | meaning |
|---|---|
exact_rate |
quotes found verbatim in the source |
fuzzy_rate |
quotes that differ from the source but matched at or above fuzzy_threshold |
unaligned_rate |
quotes that could not be matched (dropped; their text becomes uncategorized) |
gap_coverage |
share of the source's non-whitespace characters not covered by any quote |
fuzzy_scores |
match score of every non-verbatim quote, to judge fuzzy_threshold |
split_with_report returns the same chunks as split, but never raises on alignment
errors: unaligned quotes are counted in the report instead. For a single text you can
also call chunklabel.eval.fidelity(raw_chunks, text) directly.
The segmenter estimators have predict_with_report, which returns the same report per
text. This matters even more there: they join unquoted text to the preceding segment, so
a segmentation always looks complete, and only gap_coverage shows how much the LLM
skipped. ZeroShotPromptSegmenter.fit also keeps the reports of its own pass over the
training texts in fit_reports_.
segmentations, reports = segmenter.predict_with_report(texts)
skipped = [i for i, r in enumerate(reports) if r.gap_coverage > 0.2]
As a reference point, on 40 PubMed abstracts Gemma 4 E4B quoted 100% verbatim with
almost no gaps. Qwen2.5-7B quoted 99% verbatim but left 5–7% of the text unquoted
(benchmarks/fidelity).
Using local LLMs
llama.cpp (in-process)
from llama_cpp import Llama
from chunklabel import ChunkLabeler
from chunklabel.llm import LlamaCppClient
client = LlamaCppClient(Llama(model_path="path/to/model.gguf", n_ctx=4096))
labeler = ChunkLabeler(client=client)
OpenAI-compatible server (e.g. llama.cpp server, Ollama)
Set OPENAI_BASE_URL before constructing the client:
OPENAI_BASE_URL=http://localhost:8080/v1 python your_script.py
from chunklabel import ChunkLabeler
from chunklabel.llm import OpenAIClient
labeler = ChunkLabeler(client=OpenAIClient(model="llama3", api_key="not-used"))
Note: local models must support JSON-mode structured output.
Downstream use cases
The Chunk list produced by chunklabel is designed as input for further analysis:
- NLI: score the relationship between hypotheses and chunk categories
- NER: analyze co-occurrence between entity labels and categories
- Relation extraction: map entity-pair relations to chunk categories
- Conditional generation: use category as a conditioning signal for language models
License
MIT
Metadata
Release files for chunklabel 0.5.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| chunklabel-0.5.0.tar.gz | 156.8 kB | Without provenance | Details for chunklabel-0.5.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| chunklabel-0.5.0-py3-none-any.whl | Python 3 | none | any | Details for chunklabel-0.5.0-py3-none-any.whl |
Total release size: 182.2 kB
Release files / chunklabel-0.5.0.tar.gz
| Download URL | chunklabel-0.5.0.tar.gz |
|---|---|
| Size | 156.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
cb766dc793f19b849a6ef7a9e2a8751e06d65f15cb7491e848927e5d43ad0cbb
|
|
BLAKE2b-256 checksum How to use checksums |
df01bd6f30354f6b80f53541705ad80bdcb26d06d59b0902312aeb714f0c793a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.15
|
Release files / chunklabel-0.5.0-py3-none-any.whl
| Download URL | chunklabel-0.5.0-py3-none-any.whl |
|---|---|
| Size | 25.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
bc24a9a137c6d5b7a14cf33fdc2f174e502642049973d6efd1a71f9f4b68f823
|
|
BLAKE2b-256 checksum How to use checksums |
93619e96f2583ef0cfc429826c7f7f6b01321936ef78f67726a0df3d789232e9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.15
|
Security for chunklabel 0.5.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.