Advanced APIs
These helpers support structured document loading, semantic processing and
retrieval pipelines around the chunking API. Signatures and defaults
below are generated from source. The source and budget contracts
define canonical text, coordinates and payload limits; the
indexing API covers persistent stores and backend delivery.
Most names are available from omnichunk. Import helpers documented with a
module-specific path from that module, for example
from omnichunk.formats import load_rst.
Loaders return LoadedDocument(text, segments, format_name, warnings, source_id, metadata, elements).
The final three fields are optional and default to None, {} and ().
Its text
is the canonical source for subsequent chunks. FormatSegment.char_start and
char_end are half-open character offsets into that string; finalized
Chunk.byte_range values are half-open UTF-8 byte offsets. PDF, DOCX and
notebook coordinates therefore refer to extracted text, not container bytes.
Preserve context.format_metadata for page, cell or document-element citations.
Pass filepath, a loaded document and a ChunkOptions instance to
chunk_loaded_document(). The filepath supplies a source label; options
controls the same size, context, overlap and overflow policies as ordinary
chunking. Loader warnings are carried into source metadata and chunk parse errors.
An empty result with loader warnings raises ChunkingError when chunked.
| Loader |
Input and behavior |
load_ipynb |
Notebook JSON string; include_outputs=False excludes outputs. Enabling it includes textual stream, error and plain-text display output, not binary images. Invalid JSON/cells produce loader warnings. |
load_pdf_bytes |
PDF bytes; requires omnichunk[pdf]. Extracts page text with page metadata; it does not perform OCR. |
load_docx_bytes |
DOCX bytes; requires omnichunk[docx]. Extracts paragraphs and tables in document order. |
load_docling_document |
Already-extracted DoclingDocument or exported dictionary; requires omnichunk[docling]. Retains element/page/geometry and row/cell provenance. See the Docling guide for the supported schema and context/budget policies. |
load_latex |
LaTeX source string; retains source syntax and identifies prose, code environments and supported math regions. It does not compile TeX. |
load_rst |
reStructuredText source string; identifies prose and code directives without docutils. It does not resolve external literalinclude files. |
from pathlib import Path
from omnichunk import ChunkOptions, chunk_loaded_document, load_ipynb
loaded = load_ipynb(Path("analysis.ipynb").read_text(encoding="utf-8"))
chunks = chunk_loaded_document(
"analysis.ipynb", loaded,
ChunkOptions(max_chunk_size=800, context_mode="none"),
)
A prose, code or table span using character offsets in canonical text.
Table metadata contains row_ranges: contiguous canonical UTF-8 byte
ranges as {start, end} dictionaries. Ordinary segments need no row map.
Source code in src/omnichunk/formats/types.py
23
24
25
26
27
28
29
30
31
32
33
34 | @dataclass(frozen=True)
class FormatSegment:
"""A prose, code or table span using character offsets in canonical text.
Table metadata contains ``row_ranges``: contiguous canonical UTF-8 byte
ranges as ``{start, end}`` dictionaries. Ordinary segments need no row map.
"""
char_start: int
char_end: int
kind: Literal["prose", "code", "table"]
metadata: dict[str, Any] = field(default_factory=dict)
|
Segments use prose/code, or table with metadata["row_ranges"] containing
ordered, contiguous canonical UTF-8 {start, end} row ranges. DocumentElement
records use canonical UTF-8 byte ranges; segment offsets remain characters.
LoadedDocument.elements supplies the references projected onto final chunks.
Existing loaders leave the new fields at their defaults.
Canonical extraction text and engine segments, with optional source lineage.
metadata extends the source descriptor; elements are projected onto
final chunk context after splitting/overlap. Existing loaders leave these
fields empty. An explicit ChunkOptions source ID overrides source_id.
Source code in src/omnichunk/formats/types.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52 | @dataclass(frozen=True)
class LoadedDocument:
"""Canonical extraction text and engine segments, with optional source lineage.
``metadata`` extends the source descriptor; ``elements`` are projected onto
final chunk context after splitting/overlap. Existing loaders leave these
fields empty. An explicit ChunkOptions source ID overrides ``source_id``.
"""
text: str
segments: tuple[FormatSegment, ...]
format_name: str
warnings: tuple[str, ...] = ()
source_id: str | None = None
metadata: dict[str, Any] = field(default_factory=dict)
elements: tuple[DocumentElement, ...] = ()
|
Chunk canonical loader text with the same public source and budget contracts.
Source code in src/omnichunk/formats/chunk.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57 | def chunk_loaded_document(
filepath: str,
loaded: LoadedDocument,
options: ChunkOptions,
) -> list[Chunk]:
"""Chunk canonical loader text with the same public source and budget contracts."""
from omnichunk.config import validate_options
from omnichunk.finalize import finalize_chunks, source_descriptor
validate_options(options)
source_options = replace(options, source_id=options.source_id or loaded.source_id)
validate_options(source_options)
index = TextIndex(loaded.text)
source = source_descriptor(
filepath,
index,
source_options,
format_name=loaded.format_name,
metadata={**loaded.metadata, "warnings": list(loaded.warnings)},
)
engine_options = replace(options, overlap=None, overlap_lines=0)
candidates = _iter_loaded_chunks(filepath, loaded, engine_options)
chunks = list(
finalize_chunks(
filepath,
loaded.text,
candidates,
options,
index=index,
source=source,
context_for_range=(
lambda context, span: element_context(context, span, loaded, index.raw_bytes)
)
if loaded.elements
else None,
)
)
return _finalize_chunk_indexes(chunks)
|
Parse a Jupyter notebook JSON string into canonical text and segments.
include_outputs (default False) controls whether stdout / stderr /
error / rich-display output cells are appended after each code cell.
Source code in src/omnichunk/formats/ipynb.py
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122 | def load_ipynb(content: str, *, include_outputs: bool = False) -> LoadedDocument:
"""Parse a Jupyter notebook JSON string into canonical text and segments.
``include_outputs`` (default False) controls whether stdout / stderr /
error / rich-display output cells are appended after each code cell.
"""
warnings: list[str] = []
try:
data: dict[str, Any] = json.loads(content)
except json.JSONDecodeError as exc:
return LoadedDocument(
text="",
segments=(),
format_name="ipynb",
warnings=(f"invalid_json: {exc}",),
)
cells = data.get("cells") if isinstance(data, dict) else None
if not isinstance(cells, list):
return LoadedDocument(
text="",
segments=(),
format_name="ipynb",
warnings=("missing_or_invalid_cells",),
)
parts: list[str] = []
segments: list[FormatSegment] = []
cursor = 0
for idx, cell in enumerate(cells):
if not isinstance(cell, dict):
warnings.append(f"cell_{idx}_not_object")
continue
ctype = str(cell.get("cell_type", "") or "")
src = cell.get("source", "")
cell_text = "".join(str(x) for x in src) if isinstance(src, list) else str(src)
cell_meta = _cell_metadata(cell)
if ctype == "markdown":
if cell_text:
start = cursor
parts.append(cell_text)
cursor += len(cell_text)
segments.append(
FormatSegment(
char_start=start,
char_end=cursor,
kind="prose",
metadata={"cell": idx, "cell_type": "markdown", **cell_meta},
)
)
elif ctype == "code":
lang = _code_language(cell)
if cell_text:
start = cursor
parts.append(cell_text)
cursor += len(cell_text)
segments.append(
FormatSegment(
char_start=start,
char_end=cursor,
kind="code",
metadata={
"cell": idx,
"cell_type": "code",
"language": lang,
**cell_meta,
},
)
)
# Skip outputs entirely when include_outputs is False, even if
# present in the notebook JSON.
if include_outputs:
out_text = _extract_cell_outputs(cell)
if out_text.strip():
start = cursor
parts.append(out_text)
cursor += len(out_text)
segments.append(
FormatSegment(
char_start=start,
char_end=cursor,
kind="prose",
metadata={"cell": idx, "cell_type": "output", **cell_meta},
)
)
elif ctype == "raw":
# Raw cells are plain text per nbformat — surface as prose with
# a 'raw' marker in metadata so consumers can disambiguate.
if cell_text:
start = cursor
parts.append(cell_text)
cursor += len(cell_text)
segments.append(
FormatSegment(
char_start=start,
char_end=cursor,
kind="prose",
metadata={"cell": idx, "cell_type": "raw", **cell_meta},
)
)
else:
warnings.append(f"unknown_cell_type:{ctype}")
full_text = "".join(parts)
return LoadedDocument(
text=full_text,
segments=tuple(segments),
format_name="ipynb",
warnings=tuple(warnings),
)
|
Extract text from PDF bytes; one segment per page (full text coverage).
Source code in src/omnichunk/formats/pdf.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84 | def load_pdf_bytes(raw: bytes) -> LoadedDocument:
"""Extract text from PDF bytes; one segment per page (full text coverage)."""
try:
PdfReader = importlib.import_module("pypdf").PdfReader
except ImportError as exc:
raise ImportError(
"PDF support requires pypdf. Install with: pip install omnichunk[pdf]"
) from exc
warnings: list[str] = []
reader = PdfReader(io.BytesIO(raw))
page_texts: list[str] = []
for page_number, page in enumerate(reader.pages, start=1):
extracted = ""
try:
extracted = page.extract_text(extraction_mode="layout")
except Exception:
try:
extracted = page.extract_text()
except Exception as exc:
warnings.append(f"page_{page_number}_extract_failed:{type(exc).__name__}")
extracted = ""
if not extracted:
warnings.append(f"page_{page_number}_empty_text")
page_texts.append(extracted or "")
parts: list[str] = []
segments: list[FormatSegment] = []
cursor = 0
for i, page_text in enumerate(page_texts):
sep = f"\n\n--- page {i + 1} ---\n\n" if i > 0 else ""
block = sep + page_text
start = cursor
parts.append(block)
cursor += len(block)
if not block.strip():
continue
kind: Literal["prose", "code"] = "code" if _looks_code_like(page_text) else "prose"
segments.append(
FormatSegment(
char_start=start,
char_end=cursor,
kind=kind,
metadata={"page": i + 1, "pdf": True},
)
)
full_text = "".join(parts)
if not segments and full_text.strip():
segments.append(
FormatSegment(
char_start=0,
char_end=len(full_text),
kind="prose",
metadata={"page": 1, "pdf": True, "fallback": "full_document"},
)
)
filtered = tuple(
s
for s in segments
if s.char_end > s.char_start and full_text[s.char_start : s.char_end].strip()
)
if not page_texts:
warnings.append("empty_pdf")
return LoadedDocument(
text=full_text,
segments=filtered,
format_name="pdf",
warnings=tuple(warnings),
)
|
Extract text from DOCX bytes into prose segments (paragraphs and tables).
Source code in src/omnichunk/formats/docx_loader.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94 | def load_docx_bytes(raw: bytes) -> LoadedDocument:
"""Extract text from DOCX bytes into prose segments (paragraphs and tables)."""
try:
Document = importlib.import_module("docx").Document
CT_Tbl = importlib.import_module("docx.oxml.table").CT_Tbl
CT_P = importlib.import_module("docx.oxml.text.paragraph").CT_P
Table = importlib.import_module("docx.table").Table
Paragraph = importlib.import_module("docx.text.paragraph").Paragraph
except ImportError as exc:
raise ImportError(
"DOCX support requires python-docx. Install with: pip install omnichunk[docx]"
) from exc
warnings: list[str] = []
document = Document(io.BytesIO(raw))
def iter_block_items(parent: Any) -> Any:
parent_elm = parent.element.body
for child in parent_elm.iterchildren():
if isinstance(child, CT_P):
yield Paragraph(child, parent)
elif isinstance(child, CT_Tbl):
yield Table(child, parent)
parts: list[str] = []
segments: list[FormatSegment] = []
cursor = 0
block_index = 0
for block in iter_block_items(document):
if isinstance(block, Paragraph):
ptext = block.text
if not ptext.strip():
block_index += 1
continue
style_name = ""
try:
style_name = block.style.name if block.style is not None else ""
except Exception:
warnings.append(f"paragraph_style_{block_index}")
start = cursor
chunk = ptext + "\n\n"
parts.append(chunk)
cursor += len(chunk)
meta: dict[str, Any] = {"docx_block": "paragraph", "index": block_index}
if style_name and "Heading" in style_name:
meta["heading_style"] = style_name
segments.append(
FormatSegment(
char_start=start,
char_end=cursor,
kind="prose",
metadata=meta,
)
)
else:
table = block
rows_text: list[str] = []
for row in table.rows:
cells = [c.text.strip() for c in row.cells]
rows_text.append("\t".join(cells))
tbl = "\n".join(rows_text) + "\n\n"
if not tbl.strip():
block_index += 1
continue
start = cursor
parts.append(tbl)
cursor += len(tbl)
segments.append(
FormatSegment(
char_start=start,
char_end=cursor,
kind="prose",
metadata={"docx_block": "table", "index": block_index},
)
)
block_index += 1
full_text = "".join(parts)
return LoadedDocument(
text=full_text,
segments=tuple(segments),
format_name="docx",
warnings=tuple(warnings),
)
|
Split LaTeX into prose and code (verbatim-like) segments.
Source code in src/omnichunk/formats/tex.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153 | def load_latex(content: str) -> LoadedDocument:
"""Split LaTeX into prose and code (verbatim-like) segments."""
warnings: list[str] = []
text = content
segments: list[FormatSegment] = []
if _unbalanced_begin_end(text):
warnings.append("possible_unbalanced_begin_end")
# Collect all atomic regions in one pass: code envs + math envs + display/inline math.
SegKind = Literal["prose", "code"]
atomic: list[tuple[int, int, SegKind, dict[str, object]]] = []
for match in _CODE_ENV_PATTERN.finditer(text):
env = match.group(1)
opts = match.groupdict().get("opts")
lang = _lstlisting_language(opts)
meta: dict[str, object] = {"latex_env": env}
if lang:
meta["latex_language"] = lang
atomic.append((match.start(), match.end(), "code", meta))
for match in _MATH_ENV_PATTERN.finditer(text):
atomic.append(
(
match.start(),
match.end(),
"prose",
{"latex_math": match.group(1)},
)
)
for math_re, label in (
(_MATH_DISPLAY_BRACKET, "display_bracket"),
(_MATH_DISPLAY_DOLLARS, "display_dollars"),
(_MATH_INLINE_PAREN, "inline_paren"),
):
for match in math_re.finditer(text):
atomic.append((match.start(), match.end(), "prose", {"latex_math": label}))
# Resolve overlaps deterministically: keep the longest, drop the rest.
atomic.sort(key=lambda x: (x[0], -(x[1] - x[0])))
deduped: list[tuple[int, int, Literal["prose", "code"], dict[str, object]]] = []
last_end = -1
for s, e, kind, meta in atomic:
if s < last_end:
continue
deduped.append((s, e, kind, meta))
last_end = e
last = 0
for s, e, kind, meta in deduped:
if s > last:
_append_tex_prose_segments(text[last:s], last, segments, text)
segments.append(FormatSegment(char_start=s, char_end=e, kind=kind, metadata=meta))
last = e
if last < len(text):
_append_tex_prose_segments(text[last:], last, segments, text)
# Reconstruction invariant: chunk_loaded_document drops whitespace-only
# segments. Math blocks and atomic environments often have whitespace
# boundaries that would otherwise vanish from the output. Merge any
# uncovered gap into the closest non-empty neighbour by extending its
# range. We prefer extending the LEFT neighbour so byte ranges grow
# forward.
segments.sort(key=lambda seg: seg.char_start)
if segments:
adjusted: list[FormatSegment] = []
cursor = 0
for seg in segments:
if seg.char_start > cursor:
# Stretch the previous segment forward into the gap if we
# already have one; otherwise stretch the current one back.
if adjusted:
prev = adjusted[-1]
adjusted[-1] = FormatSegment(
char_start=prev.char_start,
char_end=seg.char_start,
kind=prev.kind,
metadata=prev.metadata,
)
else:
seg = FormatSegment(
char_start=cursor,
char_end=seg.char_end,
kind=seg.kind,
metadata=seg.metadata,
)
adjusted.append(seg)
cursor = max(cursor, seg.char_end)
if cursor < len(text):
prev = adjusted[-1]
adjusted[-1] = FormatSegment(
char_start=prev.char_start,
char_end=len(text),
kind=prev.kind,
metadata=prev.metadata,
)
segments = adjusted
ordered = sorted(segments, key=lambda s: s.char_start)
# Reconstruction invariant: the chunk engine concatenates the segment
# spans verbatim. We must not drop whitespace-only gaps between math
# blocks (or any other atomic span), so we keep ALL non-empty segments.
filtered = tuple(s for s in ordered if s.char_end > s.char_start)
return LoadedDocument(
text=text,
segments=filtered,
format_name="latex",
warnings=tuple(warnings),
)
|
Split RST into prose and code-block segments.
Source code in src/omnichunk/formats/rst.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66 | def load_rst(content: str) -> LoadedDocument:
"""Split RST into prose and code-block segments."""
if not content:
return LoadedDocument(text="", segments=(), format_name="rst", warnings=())
segments: list[FormatSegment] = []
last = 0
for match in _CODE_DIRECTIVE_RE.finditer(content):
if match.start() > last:
_append_prose(content, last, match.start(), segments)
directive = match.group(1)
lang = (match.group("lang") or "").strip()
segments.append(
FormatSegment(
char_start=match.start(),
char_end=match.end(),
kind="code",
metadata={"rst_directive": directive, "rst_language": lang or "text"},
)
)
last = match.end()
if last < len(content):
_append_prose(content, last, len(content), segments)
ordered = tuple(sorted(segments, key=lambda s: s.char_start))
return LoadedDocument(
text=content,
segments=ordered,
format_name="rst",
warnings=(),
)
|
Semantic splitting and reranking
Install omnichunk[semantic] for NumPy-based helpers. Embedding providers are
caller-supplied; get_local_embedder() additionally requires
omnichunk[sentence-transformers] and loads its selected model on the first
embedding call. Creating the provider checks that the dependency is installed.
Model selection and any model download remain the caller's responsibility.
split_sentences(text) returns (sentence_text, char_start, char_end) triples
that cover the source contiguously. Its default is a language heuristic.
A custom splitter_fn must return strings that reconstruct the entire source,
including whitespace, in order; a splitter that strips whitespace is rejected.
For detect_semantic_boundaries(), supply an embed_fn returning an (N, D)
array for the N input windows, one row per window. window counts sentences
around each position. A boundary is proposed when adjacent-window similarity is
below threshold or is a strict local minimum; it is not solely a threshold
filter. min_chunk_sentences constrains semantic groups on both sides.
SemanticBoundaryResult.boundary_indices gives the sentence indices after
which to split. SemanticSplitter.split(filepath, text, options) then applies
shared source and budget finalization; size limits can divide semantic groups
further. Use positive windows and minimum sentence counts.
omnichunk.semantic.sentences.split_sentences(text, *, splitter_fn=None)
Split text into sentences, returning (sentence_text, char_start, char_end) triples.
If splitter_fn is provided, it is called with the full text and must return
a list of sentence strings that reconstruct the source exactly. The function
maps them back to character offsets in source order, without re-encoding.
The dependency-free default is a heuristic: ASCII .!? requires whitespace
followed by an uppercase letter, an uncased letter, a digit or an opening
delimiter. Japanese/Chinese 。!? also splits without whitespace. Closing
quotes/brackets and following whitespace stay with the preceding sentence.
Blank lines (including CRLF) always split. Abbreviations and other ambiguous
linguistic boundaries require a caller-provided splitter.
If nltk is installed and splitter_fn is None, the caller may optionally
adapt nltk.tokenize.sent_tokenize to retain whitespace before passing it as
splitter_fn. A splitter that discards source characters is rejected.
Returns list of (sentence_text, char_start, char_end) where
char_start is inclusive, char_end is exclusive.
All returned ranges must cover the full text contiguously.
Empty strings are merged into the previous sentence, or the next if first.
Source code in src/omnichunk/semantic/sentences.py
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134 | def split_sentences(
text: str,
*,
splitter_fn: Callable[[str], list[str]] | None = None,
) -> list[tuple[str, int, int]]:
"""Split text into sentences, returning (sentence_text, char_start, char_end) triples.
If splitter_fn is provided, it is called with the full text and must return
a list of sentence strings that reconstruct the source exactly. The function
maps them back to character offsets in source order, without re-encoding.
The dependency-free default is a heuristic: ASCII .!? requires whitespace
followed by an uppercase letter, an uncased letter, a digit or an opening
delimiter. Japanese/Chinese 。!? also splits without whitespace. Closing
quotes/brackets and following whitespace stay with the preceding sentence.
Blank lines (including CRLF) always split. Abbreviations and other ambiguous
linguistic boundaries require a caller-provided splitter.
If nltk is installed and splitter_fn is None, the caller may optionally
adapt nltk.tokenize.sent_tokenize to retain whitespace before passing it as
splitter_fn. A splitter that discards source characters is rejected.
Returns list of (sentence_text, char_start, char_end) where
char_start is inclusive, char_end is exclusive.
All returned ranges must cover the full text contiguously.
Empty strings are merged into the previous sentence, or the next if first.
"""
if splitter_fn is None:
return _default_split_triples(text)
strings = splitter_fn(text)
out: list[tuple[str, int, int]] = []
cursor = 0
for s in strings:
if s == "":
if out:
ps, a, b = out[-1]
out[-1] = (ps + s, a, b)
else:
out.append((s, cursor, cursor))
continue
idx = text.find(s, cursor)
if idx < 0:
raise ValueError(
"splitter_fn produced a sentence not found in order in the source text"
)
end = idx + len(s)
out.append((s, idx, end))
cursor = end
if cursor != len(text):
raise ValueError("splitter_fn sentences do not cover the full text")
return _collapse_empty_triples(out, full_text=text)
|
omnichunk.semantic.boundaries.detect_semantic_boundaries(sentences, *, embed_fn, window=3, threshold=0.3, min_chunk_sentences=1)
Detect semantic boundaries via sliding-window cosine similarity.
Source code in src/omnichunk/semantic/boundaries.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86 | def detect_semantic_boundaries(
sentences: Sequence[str],
*,
embed_fn: Callable[[list[str]], NDArray[Any]],
window: int = 3,
threshold: float = 0.3,
min_chunk_sentences: int = 1,
) -> SemanticBoundaryResult:
"""Detect semantic boundaries via sliding-window cosine similarity."""
if window < 1:
raise ValueError("window must be >= 1")
n = len(sentences)
if n == 0:
return SemanticBoundaryResult((), ())
w = int(window)
windows: list[str] = []
left = w // 2
right = w - left - 1
for i in range(n):
lo = max(0, i - left)
hi = min(n, i + right + 1)
windows.append("".join(sentences[lo:hi]))
arr = np.asarray(embed_fn(windows))
if arr.ndim != 2 or arr.shape[0] != n:
raise ValueError(f"embed_fn must return 2D array with shape ({n}, D), got {arr.shape}")
if n == 1:
return SemanticBoundaryResult((), ())
sims = np.asarray(_batch_cosine_similarity(arr), dtype=np.float64)
sims_tuple = tuple(float(x) for x in sims.tolist())
last_boundary = -1
boundaries: list[int] = []
for k in range(len(sims)):
is_valley = 0 < k < len(sims) - 1 and sims[k] < sims[k - 1] and sims[k] < sims[k + 1]
is_low = sims[k] < threshold
span = k - last_boundary
remaining = n - k - 1
if (
(is_low or is_valley)
and span >= min_chunk_sentences
and remaining >= min_chunk_sentences
):
boundaries.append(k)
last_boundary = k
return SemanticBoundaryResult(tuple(boundaries), sims_tuple)
|
omnichunk.semantic.boundaries.SemanticBoundaryResult
dataclass
Result of semantic boundary detection.
Source code in src/omnichunk/semantic/boundaries.py
13
14
15
16
17
18
19
20
21
22
23 | @dataclass(frozen=True)
class SemanticBoundaryResult:
"""Result of semantic boundary detection."""
boundary_indices: tuple[int, ...]
"""Sorted sentence indices after which a boundary is placed.
Boundary at index i means: sentences[:i+1] go in one chunk,
sentences[i+1:] start the next chunk."""
similarity_scores: tuple[float, ...]
"""Cosine similarity between adjacent window embeddings.
len(similarity_scores) == len(sentences) - 1."""
|
boundary_indices
instance-attribute
Sorted sentence indices after which a boundary is placed.
Boundary at index i means: sentences[:i+1] go in one chunk,
sentences[i+1:] start the next chunk.
similarity_scores
instance-attribute
Cosine similarity between adjacent window embeddings.
len(similarity_scores) == len(sentences) - 1.
omnichunk.semantic.splitter.SemanticSplitter
dataclass
Propose semantic boundaries and finalize source spans using shared policies.
embed_fn returns a floating array with one row per input. window is
the number of sentences in an embedding window, threshold controls low
similarities, and min_chunk_sentences constrains semantic boundaries.
The size budget can force a further split within a semantic group.
Source code in src/omnichunk/semantic/splitter.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100 | @dataclass(frozen=True)
class SemanticSplitter:
"""Propose semantic boundaries and finalize source spans using shared policies.
``embed_fn`` returns a floating array with one row per input. ``window`` is
the number of sentences in an embedding window, ``threshold`` controls low
similarities, and ``min_chunk_sentences`` constrains semantic boundaries.
The size budget can force a further split within a semantic group.
"""
embed_fn: Callable[[list[str]], NDArray[Any]]
window: int = 3
threshold: float = 0.3
min_chunk_sentences: int = 1
sentence_splitter_fn: Callable[[str], list[str]] | None = None
def split(self, filepath: str, text: str, options: ChunkOptions) -> list[Chunk]:
"""Return final chunks without requiring any private precomputed indices."""
from omnichunk.engine.semantic_engine import _validated_embed_fn
effective = replace(
options,
filepath=filepath,
semantic=True,
semantic_embed_fn=self.embed_fn,
semantic_window=self.window,
semantic_threshold=self.threshold,
semantic_min_sentences=self.min_chunk_sentences,
semantic_sentence_splitter=self.sentence_splitter_fn,
)
validate_options(effective)
index = TextIndex(text)
effective = replace(effective, _precomputed_text_index=index)
validated = replace(self, embed_fn=_validated_embed_fn(self.embed_fn))
chunks = list(
finalize_chunks(
filepath,
text,
validated._candidates(filepath, text, effective),
effective,
index=index,
)
)
return [replace(chunk, total_chunks=len(chunks)) for chunk in chunks]
def _candidates(self, filepath: str, text: str, options: ChunkOptions) -> Iterator[Chunk]:
"""Internal engine input: source spans only; no duplicate budget enforcement."""
if not text.strip():
return
index = options._precomputed_text_index or TextIndex(text)
language = options.language or detect_language(filepath=filepath, content=text)
sentences = split_sentences(text, splitter_fn=self.sentence_splitter_fn)
if not sentences:
return
boundaries = detect_semantic_boundaries(
[sentence for sentence, _, _ in sentences],
embed_fn=self.embed_fn,
window=self.window,
threshold=self.threshold,
min_chunk_sentences=self.min_chunk_sentences,
).boundary_indices
start_sentence = 0
for position, end_sentence in enumerate((*boundaries, len(sentences) - 1)):
start = sentences[start_sentence][1]
end = sentences[end_sentence][2]
byte_start = index.byte_offset_for_char(start)
byte_end = index.byte_offset_for_char(end)
chunk_text = text[start:end]
yield Chunk(
text=chunk_text,
contextualized_text=chunk_text,
byte_range=ByteRange(byte_start, byte_end),
line_range=LineRange(
index.line_for_char(start), index.line_for_char(max(start, end - 1))
),
index=position,
total_chunks=-1,
context=ChunkContext(
filepath=filepath, language=language, content_type=ContentType.PROSE
),
)
start_sentence = end_sentence + 1
|
split(filepath, text, options)
Return final chunks without requiring any private precomputed indices.
Source code in src/omnichunk/semantic/splitter.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62 | def split(self, filepath: str, text: str, options: ChunkOptions) -> list[Chunk]:
"""Return final chunks without requiring any private precomputed indices."""
from omnichunk.engine.semantic_engine import _validated_embed_fn
effective = replace(
options,
filepath=filepath,
semantic=True,
semantic_embed_fn=self.embed_fn,
semantic_window=self.window,
semantic_threshold=self.threshold,
semantic_min_sentences=self.min_chunk_sentences,
semantic_sentence_splitter=self.sentence_splitter_fn,
)
validate_options(effective)
index = TextIndex(text)
effective = replace(effective, _precomputed_text_index=index)
validated = replace(self, embed_fn=_validated_embed_fn(self.embed_fn))
chunks = list(
finalize_chunks(
filepath,
text,
validated._candidates(filepath, text, effective),
effective,
index=index,
)
)
return [replace(chunk, total_chunks=len(chunks)) for chunk in chunks]
|
omnichunk.semantic.embedders.get_local_embedder(model_name='all-MiniLM-L6-v2')
Return an embed function backed by a local sentence-transformers model.
Raises :class:ImportError with an install hint if the optional extra is
not present. The model itself is loaded lazily on the first embed call.
Example::
from omnichunk.semantic.embedders import get_local_embedder
embed = get_local_embedder()
chunks = chunker.semantic_chunk("doc.md", text, embed_fn=embed)
Source code in src/omnichunk/semantic/embedders.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69 | def get_local_embedder(
model_name: str = "all-MiniLM-L6-v2",
) -> Callable[[list[str]], NDArray[Any]]:
"""Return an embed function backed by a local sentence-transformers model.
Raises :class:`ImportError` with an install hint if the optional extra is
not present. The model itself is loaded lazily on the first embed call.
Example::
from omnichunk.semantic.embedders import get_local_embedder
embed = get_local_embedder()
chunks = chunker.semantic_chunk("doc.md", text, embed_fn=embed)
"""
_import_sentence_transformers() # fail loud now if the extra is missing
return _LocalEmbedder(model_name)
|
TF-IDF and topic shifts
build_tfidf_matrix(documents) returns a dense, L2-normalized matrix with one row
per input document. max_vocab limits vocabulary size; min_df is the minimum
number of documents containing a token. For larger collections,
build_tfidf_sparse() returns a SciPy CSR matrix when SciPy is installed and
falls back to a dense NumPy array otherwise. Install omnichunk[scipy] when the
sparse return type is required.
detect_topic_shifts() compares mean TF-IDF vectors on each side of a sentence
gap. window_size overrides the legacy window width. method="fixed" uses
threshold; method="adaptive" uses the document's mean similarity minus
k standard deviations. min_shift_gap spaces accepted boundaries apart.
return_scores=True returns (shift_indices, scores) with one similarity per
gap, useful for inspecting a chosen policy. These are lexical heuristics and do
not require an embedding model.
omnichunk.semantic.tfidf.build_tfidf_matrix(documents, *, max_vocab=4096, min_df=1)
Build a dense, L2-normalized TF-IDF matrix of shape (N, V).
API is unchanged from earlier releases: callers always receive a dense
numpy array. For large corpora prefer :func:build_tfidf_sparse,
which avoids materializing the (mostly zero) dense matrix.
Source code in src/omnichunk/semantic/tfidf.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102 | def build_tfidf_matrix(
documents: Sequence[str],
*,
max_vocab: int = 4096,
min_df: int = 1,
) -> NDArray[Any]:
"""Build a dense, L2-normalized TF-IDF matrix of shape ``(N, V)``.
API is unchanged from earlier releases: callers always receive a dense
``numpy`` array. For large corpora prefer :func:`build_tfidf_sparse`,
which avoids materializing the (mostly zero) dense matrix.
"""
n_docs = len(documents)
if n_docs == 0:
return np.zeros((0, 1), dtype=np.float64)
doc_tokens, t2i, idf = _vocab_and_idf(documents, max_vocab=max_vocab, min_df=min_df)
v = len(t2i)
if v == 0:
return np.zeros((n_docs, 1), dtype=np.float64)
tf_mat: NDArray[Any] = np.zeros((n_docs, v), dtype=np.float64)
rows, cols, data = _coo_tf(doc_tokens, t2i)
if data:
np.add.at(tf_mat, (np.asarray(rows), np.asarray(cols)), np.asarray(data))
# TF weighting: (1 + log(tf)) * idf, vectorized over nonzero entries only.
out = np.zeros_like(tf_mat)
mask = tf_mat > 0
out[mask] = 1.0 + np.log(tf_mat[mask])
out *= idf[None, :]
norms = np.linalg.norm(out, axis=1, keepdims=True)
norms = np.where(norms == 0, 1.0, norms)
return cast("NDArray[Any]", out / norms)
|
omnichunk.semantic.tfidf.build_tfidf_sparse(documents, *, max_vocab=4096, min_df=1)
Build an L2-normalized TF-IDF matrix as a scipy.sparse.csr_matrix.
Logically identical to :func:build_tfidf_matrix but stores only nonzero
entries, which is dramatically smaller for large documents where each
sentence touches a tiny slice of the vocabulary.
Falls back to the dense :func:build_tfidf_matrix (returning an
ndarray) when scipy is not installed, so callers must accept either
a CSR matrix or a dense array.
Source code in src/omnichunk/semantic/tfidf.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149 | def build_tfidf_sparse(
documents: Sequence[str],
*,
max_vocab: int = 4096,
min_df: int = 1,
) -> Any:
"""Build an L2-normalized TF-IDF matrix as a ``scipy.sparse.csr_matrix``.
Logically identical to :func:`build_tfidf_matrix` but stores only nonzero
entries, which is dramatically smaller for large documents where each
sentence touches a tiny slice of the vocabulary.
Falls back to the dense :func:`build_tfidf_matrix` (returning an
``ndarray``) when ``scipy`` is not installed, so callers must accept either
a CSR matrix or a dense array.
"""
sp = _scipy_sparse()
if sp is None:
return build_tfidf_matrix(documents, max_vocab=max_vocab, min_df=min_df)
n_docs = len(documents)
if n_docs == 0:
return sp.csr_matrix((0, 1), dtype=np.float64)
doc_tokens, t2i, idf = _vocab_and_idf(documents, max_vocab=max_vocab, min_df=min_df)
v = len(t2i)
if v == 0:
return sp.csr_matrix((n_docs, 1), dtype=np.float64)
rows, cols, data = _coo_tf(doc_tokens, t2i)
tf = sp.coo_matrix(
(np.asarray(data, dtype=np.float64), (np.asarray(rows), np.asarray(cols))),
shape=(n_docs, v),
).tocsr()
# (1 + log(tf)) on stored entries, then scale columns by idf.
weighted = tf.copy()
weighted.data = 1.0 + np.log(weighted.data)
weighted = weighted @ sp.diags(idf)
norms = np.sqrt(weighted.multiply(weighted).sum(axis=1))
norms = np.asarray(norms).reshape(-1)
norms[norms == 0] = 1.0
inv = sp.diags(1.0 / norms)
return (inv @ weighted).tocsr()
|
omnichunk.semantic.tfidf.detect_topic_shifts(sentences, *, window=5, window_size=None, threshold=0.5, method='fixed', k=1.0, min_shift_gap=3, max_vocab=2048, return_scores=False)
detect_topic_shifts(sentences: Sequence[str], *, window: int = ..., window_size: int | None = ..., threshold: float = ..., method: str = ..., k: float = ..., min_shift_gap: int = ..., max_vocab: int = ..., return_scores: Literal[False] = ...) -> tuple[int, ...]
detect_topic_shifts(sentences: Sequence[str], *, window: int = ..., window_size: int | None = ..., threshold: float = ..., method: str = ..., k: float = ..., min_shift_gap: int = ..., max_vocab: int = ..., return_scores: Literal[True]) -> tuple[tuple[int, ...], list[float]]
Detect topic shifts from TF-IDF coherence over sliding windows.
Each gap between adjacent sentences is scored by the cosine similarity of
the mean TF-IDF vectors of the window_size sentences on each side
(smoothing out single-sentence noise). A gap becomes a boundary when its
score falls below the threshold.
method="fixed" (default): use threshold directly.
method="adaptive": threshold = mean(scores) - k * std(scores),
making detection relative to the document's own similarity distribution —
far more robust on homogeneous (all-code / all-prose) documents.
window is retained for backward compatibility and is used as the
window width when window_size is not given.
With return_scores=True returns (shift_indices, scores) where
scores[g] is the coherence score at the gap after sentences[g]
(len(scores) == max(0, len(sentences) - 1)), for plotting/debugging.
Source code in src/omnichunk/semantic/tfidf.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284 | def detect_topic_shifts(
sentences: Sequence[str],
*,
window: int = 5,
window_size: int | None = None,
threshold: float = 0.5,
method: str = "fixed",
k: float = 1.0,
min_shift_gap: int = 3,
max_vocab: int = 2048,
return_scores: bool = False,
) -> tuple[int, ...] | tuple[tuple[int, ...], list[float]]:
"""Detect topic shifts from TF-IDF coherence over sliding windows.
Each gap between adjacent sentences is scored by the cosine similarity of
the mean TF-IDF vectors of the ``window_size`` sentences on each side
(smoothing out single-sentence noise). A gap becomes a boundary when its
score falls below the threshold.
``method="fixed"`` (default): use ``threshold`` directly.
``method="adaptive"``: ``threshold = mean(scores) - k * std(scores)``,
making detection relative to the document's own similarity distribution —
far more robust on homogeneous (all-code / all-prose) documents.
``window`` is retained for backward compatibility and is used as the
window width when ``window_size`` is not given.
With ``return_scores=True`` returns ``(shift_indices, scores)`` where
``scores[g]`` is the coherence score at the gap after ``sentences[g]``
(``len(scores) == max(0, len(sentences) - 1)``), for plotting/debugging.
"""
w = window if window_size is None else window_size
scores = _coherence_scores(sentences, window_size=max(1, int(w)), max_vocab=max_vocab)
if scores.size == 0:
return ((), []) if return_scores else ()
if method == "adaptive":
thr = float(np.mean(scores) - float(k) * np.std(scores))
elif method == "fixed":
thr = float(threshold)
else:
raise ValueError(f"method must be 'fixed' or 'adaptive', got {method!r}")
last_shift_after: int | None = None
out: list[int] = []
for g in range(scores.size):
if float(scores[g]) < thr and (
last_shift_after is None or g - last_shift_after >= min_shift_gap
):
out.append(g)
last_shift_after = g
shifts = tuple(out)
if return_scores:
return shifts, [float(x) for x in scores.tolist()]
return shifts
|
Diversity and embedding caches
rerank_chunks() selects up to top_k candidates by maximal marginal relevance.
Provide a query vector of dimension D and an (N, D) embedding matrix aligned
with the N chunks. Inputs are normalized internally. Choose lambda_ between
0 and 1: 1 emphasizes query relevance, while 0 favors diversity after the
first, most relevant choice. Ties use input order. This function selects from
existing candidates; it neither embeds text nor enforces a context budget.
EmbeddingCache(max_size=4096).wrap() caches deterministic provider outputs.
Provider identity, optional namespace, model_revision and preprocessing
partition cached entries. Change those identities or clear the cache when model
behavior changes. Misses, including provider calls, are serialized under a lock;
stats() exposes hits, misses and resident entries.
omnichunk.semantic.rerank.rerank_chunks(query_embedding, chunk_embeddings, chunks, *, top_k=10, lambda_=0.5)
Return up to top_k chunks reranked by Maximal Marginal Relevance.
lambda_ trades relevance for diversity:
lambda_ == 1.0 -> pure relevance (chunks ranked by cosine similarity
to the query).
lambda_ == 0.0 -> pure diversity (after the single most relevant
chunk, each pick is the one least similar to those already chosen).
query_embedding is a 1D vector of dimension D; chunk_embeddings
is (N, D) aligned with chunks. Cosine similarity is used throughout,
so inputs need not be pre-normalized. Selection is deterministic (ties
broken by the smaller chunk index).
Source code in src/omnichunk/semantic/rerank.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77 | def rerank_chunks(
query_embedding: NDArray[Any],
chunk_embeddings: NDArray[Any],
chunks: list[Chunk],
*,
top_k: int = 10,
lambda_: float = 0.5,
) -> list[Chunk]:
"""Return up to ``top_k`` chunks reranked by Maximal Marginal Relevance.
``lambda_`` trades relevance for diversity:
- ``lambda_ == 1.0`` -> pure relevance (chunks ranked by cosine similarity
to the query).
- ``lambda_ == 0.0`` -> pure diversity (after the single most relevant
chunk, each pick is the one least similar to those already chosen).
``query_embedding`` is a 1D vector of dimension ``D``; ``chunk_embeddings``
is ``(N, D)`` aligned with ``chunks``. Cosine similarity is used throughout,
so inputs need not be pre-normalized. Selection is deterministic (ties
broken by the smaller chunk index).
"""
n = len(chunks)
if n == 0 or top_k <= 0:
return []
emb = np.asarray(chunk_embeddings, dtype=np.float64)
if emb.ndim != 2 or emb.shape[0] != n:
raise ValueError(f"chunk_embeddings must be 2D with shape ({n}, D), got {emb.shape}")
query = np.asarray(query_embedding, dtype=np.float64).reshape(-1)
normalized = _l2_normalize(emb)
q_norm = query / (np.linalg.norm(query) or 1.0)
query_sim = normalized @ q_norm # (N,)
lam = float(lambda_)
k = min(int(top_k), n)
# First selection: the most query-relevant chunk (independent of lambda).
first = int(np.argmax(query_sim))
selected = [first]
remaining = [i for i in range(n) if i != first]
max_sim_to_selected = normalized @ normalized[first] # (N,)
while remaining and len(selected) < k:
mmr = lam * query_sim - (1.0 - lam) * max_sim_to_selected
# Deterministic argmax over remaining: highest score, then smallest index.
best = max(remaining, key=lambda i: (float(mmr[i]), -i))
selected.append(best)
remaining.remove(best)
sims_to_best = normalized @ normalized[best]
max_sim_to_selected = np.maximum(max_sim_to_selected, sims_to_best)
return [chunks[i] for i in selected]
|
omnichunk.semantic.cache.EmbeddingCache
Cache vectors by provider identity, revision, preprocessing and source text.
A lock serializes cache misses, including provider calls, so concurrent uses
cannot mix model outputs or compute the same missing batch more than once.
Cache only deterministic providers. When mutating a provider's model or
preprocessing, change the corresponding namespace field or clear the cache.
Source code in src/omnichunk/semantic/cache.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121 | class EmbeddingCache:
"""Cache vectors by provider identity, revision, preprocessing and source text.
A lock serializes cache misses, including provider calls, so concurrent uses
cannot mix model outputs or compute the same missing batch more than once.
Cache only deterministic providers. When mutating a provider's model or
preprocessing, change the corresponding namespace field or clear the cache.
"""
def __init__(self, max_size: int = 4096) -> None:
self._max = max(0, int(max_size))
self._store: OrderedDict[tuple[Any, ...], NDArray[Any]] = OrderedDict()
self._providers: dict[int, object] = {}
self._dimensions: dict[tuple[Any, ...], int] = {}
self._lock = RLock()
self.hits = 0
self.misses = 0
def stats(self) -> dict[str, int]:
with self._lock:
return {"hits": self.hits, "misses": self.misses, "size": len(self._store)}
def clear(self) -> None:
with self._lock:
self._store.clear()
self._dimensions.clear()
self._providers.clear()
self.hits = self.misses = 0
def wrap(
self,
embed_fn: Callable[[list[str]], NDArray[Any]],
*,
namespace: str | None = None,
model_revision: str = "",
preprocessing: str = "",
) -> Callable[[list[str]], NDArray[Any]]:
"""Wrap a provider without sharing vectors with another callable.
Bound methods use the instance/function pair as identity. The optional
namespace, model revision and preprocessing revision further partition
that provider's cache. Provider references prevent Python object ID reuse.
"""
owner = getattr(embed_fn, "__self__", None)
function = getattr(embed_fn, "__func__", None)
identity = (id(owner), id(function)) if function is not None else (id(embed_fn),)
scope = (identity, namespace, model_revision, preprocessing)
@wraps(embed_fn)
def cached_embed(texts: list[str]) -> NDArray[Any]:
with self._lock:
# Retain identities even when a wrapper survives clear().
if function is not None:
self._providers[id(owner)] = owner
self._providers[id(function)] = function
else:
self._providers[id(embed_fn)] = embed_fn
if not texts:
return np.empty((0, self._dimensions.get(scope, 0)), dtype=np.float64)
results: list[NDArray[Any] | None] = [None] * len(texts)
pending: OrderedDict[tuple[Any, ...], list[int]] = OrderedDict()
pending_text: dict[tuple[Any, ...], str] = {}
for index, text in enumerate(texts):
key = (*scope, hashlib.sha256(text.encode("utf-8")).hexdigest())
cached = self._store.get(key)
if cached is not None:
self.hits += 1
self._store.move_to_end(key)
results[index] = cached
elif key in pending:
pending[key].append(index)
else:
self.misses += 1
pending[key] = [index]
pending_text[key] = text
if pending:
batch = [pending_text[key] for key in pending]
computed = np.asarray(embed_fn(batch))
if computed.ndim != 2 or computed.shape[0] != len(batch):
raise ValueError("embed_fn must return a 2D array with one row per input")
if computed.shape[1] < 1 or not np.issubdtype(computed.dtype, np.floating):
raise ValueError(
"embed_fn must return a float array with a positive dimension"
)
if not np.all(np.isfinite(computed)):
raise ValueError("embed_fn returned NaN or Inf values")
expected = self._dimensions.get(scope)
if expected is not None and expected != computed.shape[1]:
raise ValueError(
"embed_fn changed embedding dimension within its namespace"
)
self._dimensions[scope] = computed.shape[1]
for row, key in enumerate(pending):
# Providers may reuse their output buffers on the next call.
vector = computed[row].copy()
if self._max:
self._store[key] = vector
self._store.move_to_end(key)
for index in pending[key]:
results[index] = vector
while len(self._store) > self._max:
self._store.popitem(last=False)
# Do not expose cache-owned mutable vectors to the caller.
return np.array(results)
return cached_embed
|
wrap(embed_fn, *, namespace=None, model_revision='', preprocessing='')
Wrap a provider without sharing vectors with another callable.
Bound methods use the instance/function pair as identity. The optional
namespace, model revision and preprocessing revision further partition
that provider's cache. Provider references prevent Python object ID reuse.
Source code in src/omnichunk/semantic/cache.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121 | def wrap(
self,
embed_fn: Callable[[list[str]], NDArray[Any]],
*,
namespace: str | None = None,
model_revision: str = "",
preprocessing: str = "",
) -> Callable[[list[str]], NDArray[Any]]:
"""Wrap a provider without sharing vectors with another callable.
Bound methods use the instance/function pair as identity. The optional
namespace, model revision and preprocessing revision further partition
that provider's cache. Provider references prevent Python object ID reuse.
"""
owner = getattr(embed_fn, "__self__", None)
function = getattr(embed_fn, "__func__", None)
identity = (id(owner), id(function)) if function is not None else (id(embed_fn),)
scope = (identity, namespace, model_revision, preprocessing)
@wraps(embed_fn)
def cached_embed(texts: list[str]) -> NDArray[Any]:
with self._lock:
# Retain identities even when a wrapper survives clear().
if function is not None:
self._providers[id(owner)] = owner
self._providers[id(function)] = function
else:
self._providers[id(embed_fn)] = embed_fn
if not texts:
return np.empty((0, self._dimensions.get(scope, 0)), dtype=np.float64)
results: list[NDArray[Any] | None] = [None] * len(texts)
pending: OrderedDict[tuple[Any, ...], list[int]] = OrderedDict()
pending_text: dict[tuple[Any, ...], str] = {}
for index, text in enumerate(texts):
key = (*scope, hashlib.sha256(text.encode("utf-8")).hexdigest())
cached = self._store.get(key)
if cached is not None:
self.hits += 1
self._store.move_to_end(key)
results[index] = cached
elif key in pending:
pending[key].append(index)
else:
self.misses += 1
pending[key] = [index]
pending_text[key] = text
if pending:
batch = [pending_text[key] for key in pending]
computed = np.asarray(embed_fn(batch))
if computed.ndim != 2 or computed.shape[0] != len(batch):
raise ValueError("embed_fn must return a 2D array with one row per input")
if computed.shape[1] < 1 or not np.issubdtype(computed.dtype, np.floating):
raise ValueError(
"embed_fn must return a float array with a positive dimension"
)
if not np.all(np.isfinite(computed)):
raise ValueError("embed_fn returned NaN or Inf values")
expected = self._dimensions.get(scope)
if expected is not None and expected != computed.shape[1]:
raise ValueError(
"embed_fn changed embedding dimension within its namespace"
)
self._dimensions[scope] = computed.shape[1]
for row, key in enumerate(pending):
# Providers may reuse their output buffers on the next call.
vector = computed[row].copy()
if self._max:
self._store[key] = vector
self._store.move_to_end(key)
for index in pending[key]:
results[index] = vector
while len(self._store) > self._max:
self._store.popitem(last=False)
# Do not expose cache-owned mutable vectors to the caller.
return np.array(results)
return cached_embed
|
Entity graphs
build_chunk_graph(chunks) connects chunks sharing names in
chunk.context.entities. Graph indices are positions in the supplied sequence,
not necessarily the chunks' own index fields. min_entity_occurrences=2
requires an entity to occur in at least two distinct chunks; ignore_types
excludes import/export entity types by default. Names are matched as strings, so
use a suitable document scope when unrelated symbols share names. This graph
does not infer calls or dependencies from source text.
ChunkGraph stores entity nodes and shared-entity edges, with lookup methods and
to_dict() / from_dict() conversion. Analytics treat edges as undirected.
compute_centrality() uses unweighted shortest paths; find_communities() uses
weighted, deterministic label propagation. These pure-Python routines target
small graphs (roughly fewer than 500 chunks). to_networkx_dict() exports
node-link data with nodes and links keys for further analysis; NetworkX is
optional and is not imported by these helpers.
omnichunk.graph.build_chunk_graph(chunks, *, min_entity_occurrences=2, ignore_types=frozenset({'import', 'export'}))
Source code in src/omnichunk/graph/builder.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75 | def build_chunk_graph(
chunks: Sequence[Chunk],
*,
min_entity_occurrences: int = 2,
ignore_types: frozenset[str] = frozenset({"import", "export"}),
) -> ChunkGraph:
n = len(chunks)
if n == 0:
return ChunkGraph(chunk_count=0)
chunk_entities: list[set[str]] = [set() for _ in range(n)]
inverted: dict[str, list[tuple[int, bool]]] = defaultdict(list)
entity_type_for: dict[str, str] = {}
for idx, ch in enumerate(chunks):
for ent in ch.context.entities:
tval = ent.type.value
if tval in ignore_types:
continue
name = ent.name
chunk_entities[idx].add(name)
inverted[name].append((idx, ent.is_partial))
entity_type_for.setdefault(name, tval)
nodes: dict[str, EntityNode] = {}
for name, occ in sorted(inverted.items()):
chunk_indices = tuple(sorted({i for i, _ in occ}))
if len(chunk_indices) < min_entity_occurrences:
continue
partial_in = tuple(sorted({i for i, p in occ if p}))
nodes[name] = EntityNode(
name=name,
entity_type=entity_type_for.get(name, ""),
chunk_indices=chunk_indices,
is_partial_in=partial_in,
)
pair_keys: set[tuple[int, int]] = set()
for node in nodes.values():
cis = list(node.chunk_indices)
for i in range(len(cis)):
for j in range(i + 1, len(cis)):
a, b = cis[i], cis[j]
if a > b:
a, b = b, a
pair_keys.add((a, b))
edges: list[ChunkEdge] = []
for a, b in sorted(pair_keys):
union = chunk_entities[a] | chunk_entities[b]
inter = chunk_entities[a] & chunk_entities[b]
if not inter:
continue
shared_names = tuple(sorted(inter))
weight = len(shared_names) / len(union) if union else 0.0
edges.append(
ChunkEdge(
chunk_a=a,
chunk_b=b,
shared_entities=shared_names,
weight=weight,
)
)
return ChunkGraph(nodes=nodes, edges=edges, chunk_count=n)
|
omnichunk.graph.ChunkGraph
dataclass
Entity-chunk relationship graph built from a list of chunks.
Source code in src/omnichunk/graph/types.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96 | @dataclass
class ChunkGraph:
"""Entity-chunk relationship graph built from a list of chunks."""
nodes: dict[str, EntityNode] = field(default_factory=dict)
edges: list[ChunkEdge] = field(default_factory=list)
chunk_count: int = 0
def entity_chunks(self, entity_name: str) -> list[int]:
node = self.nodes.get(entity_name)
return list(node.chunk_indices) if node else []
def chunk_neighbors(self, chunk_index: int) -> list[int]:
neighbors: set[int] = set()
for edge in self.edges:
if edge.chunk_a == chunk_index:
neighbors.add(edge.chunk_b)
elif edge.chunk_b == chunk_index:
neighbors.add(edge.chunk_a)
return sorted(neighbors)
def to_dict(self) -> dict[str, Any]:
return {
"chunk_count": self.chunk_count,
"nodes": {
name: {
"type": node.entity_type,
"chunks": list(node.chunk_indices),
"partial_in": list(node.is_partial_in),
}
for name, node in self.nodes.items()
},
"edges": [
{
"chunk_a": e.chunk_a,
"chunk_b": e.chunk_b,
"shared": list(e.shared_entities),
"weight": e.weight,
}
for e in self.edges
],
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> ChunkGraph:
nodes: dict[str, EntityNode] = {}
raw_nodes = data.get("nodes") or {}
for name, payload in raw_nodes.items():
nodes[name] = EntityNode(
name=name,
entity_type=str(payload.get("type", "")),
chunk_indices=tuple(int(x) for x in payload.get("chunks", [])),
is_partial_in=tuple(int(x) for x in payload.get("partial_in", [])),
)
edges: list[ChunkEdge] = []
for e in data.get("edges") or []:
edges.append(
ChunkEdge(
chunk_a=int(e["chunk_a"]),
chunk_b=int(e["chunk_b"]),
shared_entities=tuple(str(x) for x in e.get("shared", [])),
weight=float(e.get("weight", 0.0)),
)
)
edges.sort(key=lambda x: (x.chunk_a, x.chunk_b))
return cls(
nodes=nodes,
edges=edges,
chunk_count=int(data.get("chunk_count", 0)),
)
|
omnichunk.graph.EntityNode
dataclass
A named entity that appears in one or more chunks.
Source code in src/omnichunk/graph/types.py
| @dataclass(frozen=True)
class EntityNode:
"""A named entity that appears in one or more chunks."""
name: str
entity_type: str
chunk_indices: tuple[int, ...]
is_partial_in: tuple[int, ...]
|
omnichunk.graph.ChunkEdge
dataclass
A directed edge: chunk_a and chunk_b share at least one entity.
Source code in src/omnichunk/graph/types.py
| @dataclass(frozen=True)
class ChunkEdge:
"""A directed edge: chunk_a and chunk_b share at least one entity."""
chunk_a: int
chunk_b: int
shared_entities: tuple[str, ...]
weight: float
|
omnichunk.graph.compute_centrality(graph)
Betweenness centrality per chunk index via Brandes' algorithm.
Higher values mark chunks that lie on many shortest information paths
between other chunks — the structural "hubs" of the document. Computed on
the unweighted shortest-path structure (edges as hops) and normalized for
an undirected graph. Returns {} for an empty graph.
Source code in src/omnichunk/graph/analysis.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79 | def compute_centrality(graph: ChunkGraph) -> dict[int, float]:
"""Betweenness centrality per chunk index via Brandes' algorithm.
Higher values mark chunks that lie on many shortest information paths
between other chunks — the structural "hubs" of the document. Computed on
the unweighted shortest-path structure (edges as hops) and normalized for
an undirected graph. Returns ``{}`` for an empty graph.
"""
n = graph.chunk_count
if n == 0:
return {}
adj = _adjacency(graph)
betweenness: dict[int, float] = {v: 0.0 for v in range(n)}
for s in range(n):
stack: list[int] = []
preds: dict[int, list[int]] = {w: [] for w in range(n)}
sigma: dict[int, float] = dict.fromkeys(range(n), 0.0)
sigma[s] = 1.0
dist: dict[int, int] = dict.fromkeys(range(n), -1)
dist[s] = 0
queue: deque[int] = deque([s])
while queue:
v = queue.popleft()
stack.append(v)
for w in sorted(adj[v]):
if dist[w] < 0:
dist[w] = dist[v] + 1
queue.append(w)
if dist[w] == dist[v] + 1:
sigma[w] += sigma[v]
preds[w].append(v)
delta: dict[int, float] = dict.fromkeys(range(n), 0.0)
while stack:
w = stack.pop()
for v in preds[w]:
if sigma[w] > 0:
delta[v] += (sigma[v] / sigma[w]) * (1.0 + delta[w])
if w != s:
betweenness[w] += delta[w]
# Undirected: each shortest path counted in both directions.
for v in betweenness:
betweenness[v] /= 2.0
return betweenness
|
omnichunk.graph.find_communities(graph)
Detect communities via deterministic weighted label propagation.
Each chunk starts in its own community and repeatedly adopts the label
with the greatest summed edge weight among its neighbors (ties broken by
the smallest label). Returns a list of communities, each a sorted list of
chunk indices; the list is ordered by each community's smallest member.
Source code in src/omnichunk/graph/analysis.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122 | def find_communities(graph: ChunkGraph) -> list[list[int]]:
"""Detect communities via deterministic weighted label propagation.
Each chunk starts in its own community and repeatedly adopts the label
with the greatest summed edge weight among its neighbors (ties broken by
the smallest label). Returns a list of communities, each a sorted list of
chunk indices; the list is ordered by each community's smallest member.
"""
n = graph.chunk_count
if n == 0:
return []
adj = _adjacency(graph)
labels = list(range(n))
# Deterministic, bounded iteration -> guaranteed termination.
for _ in range(100):
changed = False
for v in range(n):
neighbors = adj[v]
if not neighbors:
continue
weight_by_label: dict[int, float] = defaultdict(float)
for nb, w in neighbors.items():
weight_by_label[labels[nb]] += w
# Max weight; tie-break on smallest label for determinism.
best_label = min(
weight_by_label,
key=lambda lbl: (-weight_by_label[lbl], lbl),
)
if labels[v] != best_label:
labels[v] = best_label
changed = True
if not changed:
break
groups: dict[int, list[int]] = defaultdict(list)
for v in range(n):
groups[labels[v]].append(v)
communities = [sorted(members) for members in groups.values()]
communities.sort(key=lambda members: members[0])
return communities
|
omnichunk.graph.to_networkx_dict(graph)
Export the weighted chunk graph as a networkx node-link dict.
The returned dict is compatible with networkx.node_link_graph (keys
nodes and links) and tagged {"format": "networkx_dict"} so
downstream tooling can detect it::
import networkx as nx
G = nx.node_link_graph(to_networkx_dict(graph))
Source code in src/omnichunk/graph/analysis.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150 | def to_networkx_dict(graph: ChunkGraph) -> dict[str, Any]:
"""Export the weighted chunk graph as a networkx node-link dict.
The returned dict is compatible with ``networkx.node_link_graph`` (keys
``nodes`` and ``links``) and tagged ``{"format": "networkx_dict"}`` so
downstream tooling can detect it::
import networkx as nx
G = nx.node_link_graph(to_networkx_dict(graph))
"""
return {
"format": "networkx_dict",
"directed": False,
"multigraph": False,
"graph": {"chunk_count": graph.chunk_count},
"nodes": [{"id": i} for i in range(graph.chunk_count)],
"links": [
{
"source": e.chunk_a,
"target": e.chunk_b,
"weight": e.weight,
"shared": list(e.shared_entities),
}
for e in graph.edges
],
}
|
Language capabilities, deduplication and tracing
language_capabilities() returns a LanguageCapability for each supported code
language. It reports file extensions, grammar registration and availability,
parser and query availability, extraction mode ("ast", "regex", or "none"),
and the grammar module when registered. A bundled query does not imply exhaustive
syntax support; check chunk diagnostics for input-specific parse errors.
dedup_chunks(chunks, *, method="simhash", threshold=0.85) returns the kept
chunks and a mapping from removed chunk indexes to kept indexes. method accepts
"exact", "simhash", or "minhash"; the approximate methods use threshold
as a similarity cutoff and candidate bucketing, so they can miss near duplicates.
Use unique chunk indexes in the input when interpreting the mapping.
maybe_span(tracer, name, **initial_attrs) is a context manager for an optional
OpenTelemetry-compatible tracer. name names the span and keyword arguments
become initial attributes; a missing tracer yields None without opening a span.
omnichunk.parser.languages.LanguageCapability
dataclass
Code-language support in this environment, independently of filename detection.
Source code in src/omnichunk/parser/languages.py
31
32
33
34
35
36
37
38
39
40
41
42 | @dataclass(frozen=True)
class LanguageCapability:
"""Code-language support in this environment, independently of filename detection."""
language: Language
extensions: tuple[str, ...]
grammar_registered: bool
grammar_available: bool
parser_available: bool
query_available: bool
extraction: Literal["ast", "regex", "none"]
grammar_module: str | None = None
|
omnichunk.parser.languages.language_capabilities()
Return the deterministic code-language matrix for installed optional grammars.
query_available reports a bundled query, not exhaustive syntax coverage.
grammar_available means the grammar loaded, while parser_available
also verifies parser construction. Input syntax diagnostics remain in context.
Source code in src/omnichunk/parser/languages.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82 | def language_capabilities() -> tuple[LanguageCapability, ...]:
"""Return the deterministic code-language matrix for installed optional grammars.
``query_available`` reports a bundled query, not exhaustive syntax coverage.
``grammar_available`` means the grammar loaded, while ``parser_available``
also verifies parser construction. Input syntax diagnostics remain in context.
"""
from omnichunk.parser.query_patterns import get_query_source
from omnichunk.util.detect import _CODE_LANGUAGES, _EXTENSION_LANGUAGE
rows: list[LanguageCapability] = []
for language in sorted(_CODE_LANGUAGES):
grammar = _GRAMMARS.get(language)
available = grammar is not None and get_language(language) is not None
parser_available = available and get_parser(language) is not None
rows.append(
LanguageCapability(
language=language,
extensions=tuple(
sorted(
extension
for extension, detected in _EXTENSION_LANGUAGE.items()
if detected == language
)
),
grammar_registered=grammar is not None,
grammar_available=available,
parser_available=parser_available,
query_available=get_query_source(language) is not None,
extraction="ast"
if parser_available
else "regex"
if language == "python"
else "none",
grammar_module=grammar.module_name if grammar else None,
)
)
return tuple(rows)
|
omnichunk.dedup.dedup_chunks(chunks, *, method='simhash', threshold=0.85)
Remove near-duplicate chunks; duplicate_map maps removed index → kept index.
Source code in src/omnichunk/dedup.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27 | def dedup_chunks(
chunks: Sequence[Chunk],
*,
method: Literal["exact", "simhash", "minhash"] = "simhash",
threshold: float = 0.85,
) -> tuple[list[Chunk], dict[int, int]]:
"""Remove near-duplicate chunks; ``duplicate_map`` maps removed index → kept index."""
if not chunks:
return [], {}
if method == "exact":
return _dedup_exact(chunks)
if method == "simhash":
return _dedup_simhash(chunks, threshold=threshold)
return _dedup_minhash(chunks, threshold=threshold)
|
omnichunk.otel.util.maybe_span(tracer, name, **initial_attrs)
OpenTelemetry span context manager; no-op when tracer is None.
Source code in src/omnichunk/otel/util.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56 | @contextmanager
def maybe_span(tracer: object | None, name: str, **initial_attrs: Any) -> Iterator[Any]:
"""OpenTelemetry span context manager; no-op when ``tracer`` is None."""
if tracer is None:
yield None
return
enter = getattr(tracer, "start_as_current_span", None)
if enter is None:
yield None
return
with enter(name) as span:
for k, v in initial_attrs.items():
_span_set(span, k, v)
yield span
|
Retrieval and chunk evaluation
Ranking and evidence metrics answer different questions. score_ranking()
compares ordered passage IDs with explicit relevance grades. k is a positive
integer cutoff, and grades must be finite and nonnegative. Unjudged IDs have
zero relevance. Positive judgments define recall's denominator; nDCG uses graded
exponential gains and an ideal ranking from all judgments. Repeated IDs consume
rank slots without repeated credit. With no positive judgments, all ranking
scores are zero.
score_evidence() compares unions of EvidenceSpan(source_id, start, end) values
using half-open UTF-8 byte coordinates. Matching IDs must identify the same
canonical source revision; the span class validates coordinates, not the actual
source bytes. Overlapping ranges count once, and ranges from different sources
never match. Precision, recall and intersection-over-union are byte-weighted.
Both sets empty yields all ones; only one set empty yields all zeros. Neither
ranking nor evidence metrics measures generated answer correctness.
omnichunk.retrieval_eval.score_ranking(retrieved_ids, relevance, *, k=5)
Compute Recall@k, reciprocal rank@k and graded nDCG@k.
Unjudged IDs have relevance zero. Positive judgments define the recall
denominator; nDCG uses exponential gains (2**grade - 1) and an ideal
ranking from all judgments, including missed passages. Grades must be
finite and nonnegative. Duplicate IDs consume rank slots but receive no
repeated credit. No positive judgments yields zero for all three scores.
Source code in src/omnichunk/retrieval_eval.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126 | def score_ranking(
retrieved_ids: Sequence[str], relevance: Mapping[str, float], *, k: int = 5
) -> RankingMetrics:
"""Compute Recall@k, reciprocal rank@k and graded nDCG@k.
Unjudged IDs have relevance zero. Positive judgments define the recall
denominator; nDCG uses exponential gains (``2**grade - 1``) and an ideal
ranking from *all* judgments, including missed passages. Grades must be
finite and nonnegative. Duplicate IDs consume rank slots but receive no
repeated credit. No positive judgments yields zero for all three scores.
"""
if not isinstance(k, int) or isinstance(k, bool) or k < 1:
raise ValueError("k must be a positive integer")
for passage_id in retrieved_ids:
_validate_id(passage_id)
grades: dict[str, float] = {}
for passage_id, grade in relevance.items():
_validate_id(passage_id)
if isinstance(grade, bool) or not isinstance(grade, Real):
raise ValueError("Relevance grades must be finite nonnegative real numbers")
try:
number = float(grade)
except (OverflowError, ValueError) as exc:
raise ValueError("Relevance grades must be finite nonnegative real numbers") from exc
if not math.isfinite(number) or number < 0:
raise ValueError("Relevance grades must be finite nonnegative real numbers")
grades[passage_id] = number
positive = sorted((value for value in grades.values() if value > 0), reverse=True)
maximum = positive[0] if positive else 0.0
def gain(grade: float) -> float:
# Scaling by 2**(-maximum) cancels between DCG and IDCG, avoiding
# overflow for large valid grades. expm1 preserves tiny positive grades.
return -math.expm1(-grade * math.log(2)) * math.pow(2.0, grade - maximum)
seen: set[str] = set()
hits, reciprocal_rank, dcg = 0, 0.0, 0.0
for rank, passage_id in enumerate(retrieved_ids[:k], start=1):
if passage_id in seen:
continue
seen.add(passage_id)
grade = grades.get(passage_id, 0.0)
if grade > 0:
hits += 1
if reciprocal_rank == 0:
reciprocal_rank = 1.0 / rank
dcg += gain(grade) / math.log2(rank + 1)
ideal = sum(gain(grade) / math.log2(rank + 1) for rank, grade in enumerate(positive[:k], 1))
return RankingMetrics(
recall_at_k=hits / len(positive) if positive else 0.0,
mrr_at_k=reciprocal_rank,
ndcg_at_k=dcg / ideal if ideal else 0.0,
k=k,
relevant_count=len(positive),
retrieved_count=min(k, len(retrieved_ids)),
)
|
omnichunk.retrieval_eval.RankingMetrics
dataclass
Scores at one cutoff; relevant_count counts all positive judgments.
Source code in src/omnichunk/retrieval_eval.py
42
43
44
45
46
47
48
49
50
51 | @dataclass(frozen=True)
class RankingMetrics:
"""Scores at one cutoff; relevant_count counts all positive judgments."""
recall_at_k: float
mrr_at_k: float
ndcg_at_k: float
k: int
relevant_count: int
retrieved_count: int
|
omnichunk.retrieval_eval.EvidenceSpan
dataclass
A nonempty half-open UTF-8 byte range in one canonical source revision.
The caller must use the same canonical text and revision for matching source
IDs. This value validates coordinates, not the original source bytes.
Source code in src/omnichunk/retrieval_eval.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 | @dataclass(frozen=True)
class EvidenceSpan:
"""A nonempty half-open UTF-8 byte range in one canonical source revision.
The caller must use the same canonical text and revision for matching source
IDs. This value validates coordinates, not the original source bytes.
"""
source_id: str
start: int
end: int
def __post_init__(self) -> None:
_validate_id(self.source_id)
if (
not isinstance(self.start, int)
or isinstance(self.start, bool)
or not isinstance(self.end, int)
or isinstance(self.end, bool)
or self.start < 0
or self.end <= self.start
):
raise ValueError("Evidence spans require integer coordinates with 0 <= start < end")
|
omnichunk.retrieval_eval.score_evidence(retrieved, relevant)
Measure precision, recall and IoU of source-byte unions per document.
Repeated/overlapping ranges count once; identically numbered ranges in
different sources never match. Both sets empty gives 1 for all metrics.
If only one set is empty, all metrics are 0. These are byte-weighted scores,
so non-ASCII characters contribute their full UTF-8 width.
Source code in src/omnichunk/retrieval_eval.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180 | def score_evidence(
retrieved: Sequence[EvidenceSpan], relevant: Sequence[EvidenceSpan]
) -> EvidenceMetrics:
"""Measure precision, recall and IoU of source-byte unions per document.
Repeated/overlapping ranges count once; identically numbered ranges in
different sources never match. Both sets empty gives 1 for all metrics.
If only one set is empty, all metrics are 0. These are byte-weighted scores,
so non-ASCII characters contribute their full UTF-8 width.
"""
predicted, expected = _union(retrieved), _union(relevant)
predicted_size = sum(end - start for spans in predicted.values() for start, end in spans)
expected_size = sum(end - start for spans in expected.values() for start, end in spans)
intersection = 0
for source_id, spans in predicted.items():
gold = expected.get(source_id, [])
cursor = 0
for start, end in spans:
while cursor < len(gold) and gold[cursor][1] <= start:
cursor += 1
index = cursor
while index < len(gold) and gold[index][0] < end:
gold_start, gold_end = gold[index]
intersection += max(0, min(end, gold_end) - max(start, gold_start))
index += 1
union_size = predicted_size + expected_size - intersection
both_empty = predicted_size == expected_size == 0
return EvidenceMetrics(
precision=intersection / predicted_size if predicted_size else float(both_empty),
recall=intersection / expected_size if expected_size else float(both_empty),
iou=intersection / union_size if union_size else 1.0,
retrieved_bytes=predicted_size,
relevant_bytes=expected_size,
intersection_bytes=intersection,
)
|
omnichunk.retrieval_eval.EvidenceMetrics
dataclass
Source-byte union metrics and their exact integer denominators.
Source code in src/omnichunk/retrieval_eval.py
54
55
56
57
58
59
60
61
62
63 | @dataclass(frozen=True)
class EvidenceMetrics:
"""Source-byte union metrics and their exact integer denominators."""
precision: float
recall: float
iou: float
retrieved_bytes: int
relevant_bytes: int
intersection_bytes: int
|
Offline chunk diagnostics
evaluate_chunks(chunks, source=None, metrics="all") returns an EvalReport
with per-chunk and aggregate values. Supply the exact canonical source for
reconstruction and coverage; these values are otherwise None. Aggregate
coverage measures the union of correctly reconstructed byte ranges, so overlap
does not earn duplicate coverage. density uses non-whitespace character counts.
coherence and boundary_quality are TF-IDF sentence heuristics requiring NumPy,
not retrieval scores or learned quality judgments. Select a sequence of metric
names to avoid unwanted work; unknown names raise ValueError. Unavailable or
unrequested values are None. eval_report_to_dict() produces a plain mapping.
omnichunk.eval.evaluate_chunks(chunks, source=None, *, metrics='all')
Offline metrics for chunk quality (no embeddings).
Source code in src/omnichunk/eval.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94 | def evaluate_chunks(
chunks: Sequence[Chunk],
source: str | None = None,
*,
metrics: Sequence[str] | Literal["all"] = "all",
) -> EvalReport:
"""Offline metrics for chunk quality (no embeddings)."""
if metrics == "all":
want = frozenset({"reconstruction", "density", "coherence", "boundary_quality", "coverage"})
else:
want = frozenset(metrics)
allowed = {"reconstruction", "density", "coherence", "boundary_quality", "coverage"}
if want - allowed:
raise ValueError(f"Unknown evaluation metrics: {sorted(want - allowed)}")
raw_source = source.encode("utf-8") if source is not None else None
n = len(chunks)
per: list[ChunkEvalScores] = []
for i, ch in enumerate(chunks):
rec = (
_metric_reconstruction(ch, source, raw_source=raw_source)
if "reconstruction" in want
else None
)
dens = _metric_density(ch) if "density" in want else None
coh = _metric_coherence(ch) if "coherence" in want else None
bq = _metric_boundary(chunks, i) if "boundary_quality" in want and n > 1 else None
cov = (
_metric_coverage_chunk(chunks, i, source, raw_source=raw_source)
if "coverage" in want
else None
)
per.append(
ChunkEvalScores(
index=ch.index,
reconstruction=rec,
density=dens,
coherence=coh,
boundary_quality=bq,
coverage=cov,
)
)
agg: dict[str, float | None] = {}
for name in ("reconstruction", "density", "coherence", "boundary_quality", "coverage"):
if name not in want:
agg[name] = None
continue
vals = [getattr(row, name) for row in per]
nums = [v for v in vals if v is not None]
agg[name] = float(sum(nums) / len(nums)) if nums else None
if "coverage" in want and raw_source is not None:
intervals = sorted(
(c.byte_range.start, c.byte_range.end)
for c in chunks
if _metric_reconstruction(c, source, raw_source=raw_source) == 1.0
)
covered, end = 0, 0
for start, finish in intervals:
covered += max(0, finish - max(start, end))
end = max(end, finish)
agg["coverage"] = covered / len(raw_source) if raw_source else 1.0
return EvalReport(per_chunk=tuple(per), aggregate=agg)
|
omnichunk.eval.ChunkEvalScores
dataclass
Source code in src/omnichunk/eval.py
| @dataclass(frozen=True)
class ChunkEvalScores:
index: int
reconstruction: float | None
density: float | None
coherence: float | None
boundary_quality: float | None
coverage: float | None
|
omnichunk.eval.EvalReport
dataclass
Source code in src/omnichunk/eval.py
| @dataclass(frozen=True)
class EvalReport:
per_chunk: tuple[ChunkEvalScores, ...]
aggregate: dict[str, float | None]
|
omnichunk.eval.eval_report_to_dict(report)
Source code in src/omnichunk/eval.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192 | def eval_report_to_dict(report: EvalReport) -> dict[str, Any]:
return {
"aggregate": dict(report.aggregate),
"per_chunk": [
{
"index": row.index,
"reconstruction": row.reconstruction,
"density": row.density,
"coherence": row.coherence,
"boundary_quality": row.boundary_quality,
"coverage": row.coverage,
}
for row in report.per_chunk
],
}
|
Context budget selection
TokenBudgetOptimizer(budget, ...) selects existing chunks without splitting
them. scores passed to select() must align with the chunks; omitted scores
are all 1. strategy="greedy" visits chunks in descending score order, while
strategy="dp" maximizes total score within the budget using knapsack selection.
The latter falls back to greedy when len(chunks) * budget exceeds 50 million.
preserve_order=True sorts selected chunks by starting byte offset; this is
source-local ordering, not a cross-document ranking.
size_unit accepts "tokens", "chars" or "nws" and measures rendered
contextualized_text. Token sizing uses recorded rendered_token_count; manual
contextualized chunks lacking that metadata are rejected. Raw-only manual chunks
can use token_count, whose accuracy depends on how it was populated.
BudgetResult.total_tokens uses the selected unit despite its field name.
deduplicate_overlap=True removes lower-scored similar text using token-set
Jaccard similarity and overlap_threshold; it does not compare source ranges.
The optimizer adds individual chunk sizes. Reserve room for prompts, separators
and citations, and measure the final joined context with the downstream tokenizer:
token counts need not be additive across joins. Selection does not establish a
complete model-input guarantee.
omnichunk.budget.TokenBudgetOptimizer
Select chunks whose rendered payloads fit within the selected size budget.
Reserve space separately for prompts, separators and citation labels. Token
counts use the tokenizer recorded when chunking; approximate counts remain
estimates. BudgetResult.total_tokens uses the selected size_unit.
Source code in src/omnichunk/budget/optimizer.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103 | class TokenBudgetOptimizer:
"""Select chunks whose rendered payloads fit within the selected size budget.
Reserve space separately for prompts, separators and citation labels. Token
counts use the tokenizer recorded when chunking; approximate counts remain
estimates. ``BudgetResult.total_tokens`` uses the selected ``size_unit``.
"""
def __init__(
self,
budget: int,
*,
strategy: str = "greedy",
preserve_order: bool = True,
deduplicate_overlap: bool = False,
overlap_threshold: float = 0.85,
size_unit: str = "tokens",
) -> None:
if budget <= 0:
raise ValueError("budget must be > 0")
if strategy not in ("greedy", "dp"):
raise ValueError("strategy must be 'greedy' or 'dp'")
if size_unit not in ("tokens", "chars", "nws"):
raise ValueError("size_unit must be 'tokens', 'chars' or 'nws'")
if not (0 < overlap_threshold <= 1):
raise ValueError("overlap_threshold must be in (0, 1]")
self.budget = budget
self.strategy = strategy
self.preserve_order = preserve_order
self.deduplicate_overlap = deduplicate_overlap
self.overlap_threshold = overlap_threshold
self.size_unit = size_unit
def select(
self,
chunks: Sequence[Chunk],
*,
scores: Sequence[float] | None = None,
) -> BudgetResult:
if not chunks:
return BudgetResult(
selected=[],
total_tokens=0,
dropped=[],
budget=self.budget,
strategy=self.strategy,
)
if scores is not None and len(scores) != len(chunks):
raise ValueError("scores must have same length as chunks")
effective_scores = list(scores) if scores is not None else [1.0] * len(chunks)
working: list[Chunk] = list(chunks)
working_scores: list[float] = list(effective_scores)
if self.deduplicate_overlap:
working, working_scores = _deduplicate(working, working_scores, self.overlap_threshold)
if self.strategy == "greedy":
selected_indices = _greedy_select(working, working_scores, self.budget, self.size_unit)
else:
selected_indices = _dp_select(working, working_scores, self.budget, self.size_unit)
selected = [working[i] for i in selected_indices]
if self.preserve_order:
selected.sort(key=lambda c: c.byte_range.start)
selected_ids = {id(c) for c in selected}
dropped = [c for c in chunks if id(c) not in selected_ids]
total = sum(_chunk_size(c, self.size_unit) for c in selected)
return BudgetResult(
selected=selected,
total_tokens=total,
dropped=dropped,
budget=self.budget,
strategy=self.strategy,
)
|
omnichunk.budget.BudgetResult
dataclass
Result of token budget optimization.
Source code in src/omnichunk/budget/optimizer.py
14
15
16
17
18
19
20
21
22 | @dataclass(frozen=True)
class BudgetResult:
"""Result of token budget optimization."""
selected: list[Chunk]
total_tokens: int
dropped: list[Chunk]
budget: int
strategy: str
|
Use PluginRegistry(revision="my-parser-v1") and pass it as registry= to
Chunker for an explicit pipeline scope. A parser callback receives
(filepath, content) and returns a tree-like object or None; a formatter
receives a chunk sequence and returns a string. Register these through the
registry's register_parser() and register_formatter() methods, and call
chunker.format(chunks, name) to use a formatter. Change revision when plugin
behavior changes so persisted configuration identities can change with it.
Legacy module-level registration is global. A Chunker constructed without an
explicit registry snapshots those registrations at construction; later global
registrations do not alter that chunker. Language names are stripped and
lowercased; formatter names are stripped and case-sensitive. Duplicate names
raise ValueError unless overwrite=True. Module-level listing functions return
sorted global names, rather than inspecting a particular chunker's registry.
omnichunk.plugins.PluginRegistry
Explicit per-pipeline registry. Mutations are isolated from other chunkers.
Source code in src/omnichunk/plugins.py
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170 | class PluginRegistry:
"""Explicit per-pipeline registry. Mutations are isolated from other chunkers."""
def __init__(self, *, revision: str = "") -> None:
self.revision = revision
self.parsers: dict[str, Callable[[str, str], Any]] = {}
self.formatters: dict[str, Callable[[Sequence[Any]], str]] = {}
self._lock = RLock()
@classmethod
def from_global(cls) -> PluginRegistry:
registry = cls()
with _LOCK:
registry.parsers.update(_PARSER_REGISTRY)
registry.formatters.update(_FORMATTER_REGISTRY)
return registry
def register_parser(
self, language: str, parser: Callable[[str, str], Any], *, overwrite: bool = False
) -> None:
key = _norm_lang(language)
if not key or not callable(parser):
raise ValueError("Parser requires a language and callable")
with self._lock:
if key in self.parsers and not overwrite:
raise ValueError(f"Parser for {key!r} already registered")
self.parsers[key] = parser
def register_formatter(
self, name: str, formatter: Callable[[Sequence[Any]], str], *, overwrite: bool = False
) -> None:
key = name.strip()
if not key or not callable(formatter):
raise ValueError("Formatter requires a name and callable")
with self._lock:
if key in self.formatters and not overwrite:
raise ValueError(f"Formatter {key!r} already registered")
self.formatters[key] = formatter
@property
def fingerprint(self) -> str:
"""Behavior revision plus registered provider identities, without object IDs."""
from omnichunk.config import _identity
with self._lock:
state = {
"revision": self.revision,
"parsers": {name: _identity(provider) for name, provider in self.parsers.items()},
"formatters": {
name: _identity(provider) for name, provider in self.formatters.items()
},
}
return hashlib.sha256(
json.dumps(state, sort_keys=True, separators=(",", ":")).encode()
).hexdigest()
def iterate(self, iterator: Any) -> Any:
"""Scope each generator advance, restoring context before returning output."""
iterator = iter(iterator)
try:
while True:
token = _ACTIVE.set(self)
try:
item = next(iterator)
except StopIteration:
return
finally:
_ACTIVE.reset(token)
yield item
finally:
close = getattr(iterator, "close", None)
if close is not None:
token = _ACTIVE.set(self)
try:
close()
finally:
_ACTIVE.reset(token)
|
fingerprint
property
Behavior revision plus registered provider identities, without object IDs.
iterate(iterator)
Scope each generator advance, restoring context before returning output.
Source code in src/omnichunk/plugins.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170 | def iterate(self, iterator: Any) -> Any:
"""Scope each generator advance, restoring context before returning output."""
iterator = iter(iterator)
try:
while True:
token = _ACTIVE.set(self)
try:
item = next(iterator)
except StopIteration:
return
finally:
_ACTIVE.reset(token)
yield item
finally:
close = getattr(iterator, "close", None)
if close is not None:
token = _ACTIVE.set(self)
try:
close()
finally:
_ACTIVE.reset(token)
|
omnichunk.plugins.register_parser(lang, parser_fn, *, overwrite=False)
Register parser_fn(filepath, content) returning a tree-like object or None.
Source code in src/omnichunk/plugins.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34 | def register_parser(
lang: str,
parser_fn: Callable[[str, str], Any],
*,
overwrite: bool = False,
) -> None:
"""Register ``parser_fn(filepath, content)`` returning a tree-like object or ``None``."""
key = _norm_lang(lang)
if not key or not callable(parser_fn):
raise ValueError("Parser requires a language and callable")
with _LOCK:
if key in _PARSER_REGISTRY and not overwrite:
raise ValueError(f"Parser for language {key!r} is already registered")
_PARSER_REGISTRY[key] = parser_fn
|
Register a custom output formatter: (chunks) -> str.
Source code in src/omnichunk/plugins.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 | def register_formatter(
name: str,
formatter_fn: Callable[[Sequence[Any]], str],
*,
overwrite: bool = False,
) -> None:
"""Register a custom output formatter: ``(chunks) -> str``."""
key = name.strip()
if not key:
raise ValueError("Formatter name must be non-empty")
if not callable(formatter_fn):
raise ValueError("Formatter requires a callable")
with _LOCK:
if key in _FORMATTER_REGISTRY and not overwrite:
raise ValueError(f"Formatter {key!r} is already registered")
_FORMATTER_REGISTRY[key] = formatter_fn
|
omnichunk.plugins.list_registered_parsers()
Source code in src/omnichunk/plugins.py
| def list_registered_parsers() -> list[str]:
with _LOCK:
return sorted(_PARSER_REGISTRY)
|
Source code in src/omnichunk/plugins.py
| def list_registered_formatters() -> list[str]:
with _LOCK:
return sorted(_FORMATTER_REGISTRY)
|
Serialization and export
Use chunk_to_dict() / chunk_from_dict() for complete versioned chunk records,
including context, source identity and metadata. The reader accepts legacy v1
and unversioned records and rejects unsupported schema versions.
chunks_to_jsonl() returns these records as JSON Lines; output_path optionally
writes UTF-8 output. chunks_to_csv() flattens a selected set of fields for
inspection and is not a complete round-trip format.
stable_chunk_id() identifies a content occurrence within a logical source;
filepath explicitly overrides that source identity when supplied.
chunk_content_fingerprint() hashes raw UTF-8 text, while
chunk_embedding_fingerprint() includes rendered text and chunk configuration.
Track the embedding model revision separately. See the
identity contracts
before replacing an existing index.
omnichunk.serialization.chunk_to_dict(chunk)
Convert every chunk field to the versioned JSON representation.
Unversioned v1 dictionaries remain readable with :func:chunk_from_dict.
Unknown schema versions are rejected rather than silently losing fields.
Source code in src/omnichunk/serialization.py
34
35
36
37
38
39
40
41
42
43 | def chunk_to_dict(chunk: Chunk) -> dict[str, Any]:
"""Convert every chunk field to the versioned JSON representation.
Unversioned v1 dictionaries remain readable with :func:`chunk_from_dict`.
Unknown schema versions are rejected rather than silently losing fields.
"""
value = _to_serializable(chunk)
if not isinstance(value, dict):
return {}
return {"schema_version": CHUNK_SCHEMA_VERSION, **value}
|
omnichunk.serialization.chunk_from_dict(data)
Read v2 or legacy v1/unversioned chunks, including all context fields.
Source code in src/omnichunk/serialization.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128 | def chunk_from_dict(data: dict[str, Any]) -> Chunk:
"""Read v2 or legacy v1/unversioned chunks, including all context fields."""
schema = data.get("schema_version", 1)
if type(schema) is not int or schema not in (1, CHUNK_SCHEMA_VERSION):
raise ValueError(f"Unsupported chunk schema version: {schema!r}")
ctx_raw = data.get("context") or {}
ct_raw = ctx_raw.get("content_type", "prose")
if isinstance(ct_raw, str):
try:
content_type = ContentType(ct_raw)
except ValueError:
content_type = ContentType.PROSE
else:
content_type = ContentType.PROSE
entities = [
_entity_info_from_dict(e) for e in ctx_raw.get("entities") or [] if isinstance(e, dict)
]
scope = [_entity_info_from_dict(e) for e in ctx_raw.get("scope") or []]
siblings = [
SiblingInfo(
name=str(s["name"]),
type=EntityType(s["type"]),
position=s["position"],
distance=int(s["distance"]),
signature=str(s.get("signature", "")),
)
for s in ctx_raw.get("siblings") or []
]
imports = [ImportInfo(**i) for i in ctx_raw.get("imports") or []]
source_raw = data.get("source")
source = SourceDescriptor(**source_raw) if source_raw is not None else None
br = data.get("byte_range") or {}
lr = data.get("line_range") or {}
return Chunk(
text=str(data.get("text", "")),
contextualized_text=str(data.get("contextualized_text", data.get("text", ""))),
byte_range=ByteRange(start=int(br.get("start", 0)), end=int(br.get("end", 0))),
line_range=LineRange(start=int(lr.get("start", 0)), end=int(lr.get("end", 0))),
index=int(data.get("index", 0)),
total_chunks=int(data.get("total_chunks", -1)),
context=ChunkContext(
filepath=str(ctx_raw.get("filepath", "")),
language=cast(Language, ctx_raw.get("language", "plaintext")),
content_type=content_type,
scope=scope,
breadcrumb=list(ctx_raw.get("breadcrumb") or []),
entities=entities,
siblings=siblings,
imports=imports,
heading_hierarchy=list(ctx_raw.get("heading_hierarchy") or []),
section_type=str(ctx_raw.get("section_type", "")),
parse_errors=list(ctx_raw.get("parse_errors") or []),
format_metadata=dict(ctx_raw.get("format_metadata", {})),
),
token_count=int(data.get("token_count", 0)),
char_count=int(data.get("char_count", 0)),
nws_count=int(data.get("nws_count", 0)),
source=source,
config_fingerprint=str(data.get("config_fingerprint", "")),
occurrence=int(data.get("occurrence", 0)),
metadata=dict(data.get("metadata") or {}),
)
|
omnichunk.serialization.chunks_to_jsonl(chunks, *, output_path=None)
Serialize chunks into JSONL. Optionally write output to a file path.
Source code in src/omnichunk/serialization.py
131
132
133
134
135
136
137
138
139
140
141
142
143 | def chunks_to_jsonl(chunks: Sequence[Chunk], *, output_path: str | None = None) -> str:
"""Serialize chunks into JSONL. Optionally write output to a file path."""
lines = [
json.dumps(chunk_to_dict(chunk), ensure_ascii=False, sort_keys=True) for chunk in chunks
]
payload = "\n".join(lines)
if lines:
payload += "\n"
if output_path:
Path(output_path).write_text(payload, encoding="utf-8")
return payload
|
omnichunk.serialization.chunks_to_csv(chunks, *, output_path=None)
Serialize chunks into CSV with flattened context fields.
Source code in src/omnichunk/serialization.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200 | def chunks_to_csv(chunks: Sequence[Chunk], *, output_path: str | None = None) -> str:
"""Serialize chunks into CSV with flattened context fields."""
columns = [
"filepath",
"language",
"content_type",
"index",
"total_chunks",
"byte_start",
"byte_end",
"line_start",
"line_end",
"token_count",
"char_count",
"nws_count",
"breadcrumb",
"section_type",
"entity_count",
"text",
"contextualized_text",
]
buffer = StringIO()
writer = csv.DictWriter(buffer, fieldnames=columns)
writer.writeheader()
for chunk in chunks:
writer.writerow(
{
"filepath": chunk.context.filepath,
"language": chunk.context.language,
"content_type": chunk.context.content_type.value,
"index": chunk.index,
"total_chunks": chunk.total_chunks,
"byte_start": chunk.byte_range.start,
"byte_end": chunk.byte_range.end,
"line_start": chunk.line_range.start,
"line_end": chunk.line_range.end,
"token_count": chunk.token_count,
"char_count": chunk.char_count,
"nws_count": chunk.nws_count,
"breadcrumb": " > ".join(chunk.context.breadcrumb),
"section_type": chunk.context.section_type,
"entity_count": len(chunk.context.entities),
"text": chunk.text,
"contextualized_text": chunk.contextualized_text,
}
)
payload = buffer.getvalue()
if output_path:
Path(output_path).write_text(payload, encoding="utf-8")
return payload
|
omnichunk.serialization.stable_chunk_id(chunk, filepath=None)
Identify a content-anchored occurrence within a logical document.
V2 identity excludes byte offsets, chunk index, configuration and rendered
context, so an unchanged block can move without changing its ID. Equal raw
blocks are disambiguated by their source-order occurrence. A rename
preserves identity only when the caller preserves source.source_id.
Legacy/manual chunks without a source descriptor use index to distinguish
repeats. Rebuild old vector indexes; the v1 positional ID is not reused.
Source code in src/omnichunk/serialization.py
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494 | def stable_chunk_id(chunk: Chunk, filepath: str | None = None) -> str:
"""Identify a content-anchored occurrence within a logical document.
V2 identity excludes byte offsets, chunk index, configuration and rendered
context, so an unchanged block can move without changing its ID. Equal raw
blocks are disambiguated by their source-order ``occurrence``. A rename
preserves identity only when the caller preserves ``source.source_id``.
Legacy/manual chunks without a source descriptor use ``index`` to distinguish
repeats. Rebuild old vector indexes; the v1 positional ID is not reused.
"""
source_id = (
filepath
if filepath is not None
else (chunk.source.source_id if chunk.source is not None else chunk.context.filepath)
)
occurrence = chunk.occurrence if chunk.source is not None else chunk.index
return _fingerprint(
["omnichunk-occurrence-v2", source_id, chunk_content_fingerprint(chunk), occurrence]
)
|
omnichunk.serialization.chunk_content_fingerprint(chunk)
SHA-256 of the exact raw UTF-8 text, independent of its location.
Source code in src/omnichunk/serialization.py
| def chunk_content_fingerprint(chunk: Chunk) -> str:
"""SHA-256 of the exact raw UTF-8 text, independent of its location."""
return hashlib.sha256(chunk.text.encode("utf-8")).hexdigest()
|
omnichunk.serialization.chunk_embedding_fingerprint(chunk)
Fingerprint payload and configuration for embedding invalidation.
Source revision and offsets are deliberately excluded: an unrelated edit
must not invalidate a byte-identical payload. External embedding model
versioning must additionally be tracked by the embedding/indexing client.
Source code in src/omnichunk/serialization.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516 | def chunk_embedding_fingerprint(chunk: Chunk) -> str:
"""Fingerprint payload and configuration for embedding invalidation.
Source revision and offsets are deliberately excluded: an unrelated edit
must not invalidate a byte-identical payload. External embedding model
versioning must additionally be tracked by the embedding/indexing client.
"""
return _fingerprint(
[
"omnichunk-embedding-v2",
chunk_content_fingerprint(chunk),
chunk.contextualized_text,
chunk.config_fingerprint,
]
)
|
Framework documents and vector payloads
Framework converters require the corresponding LangChain or LlamaIndex extra.
use_contextualized_text=True selects rendered content; choose False for raw
source text. Both retain a complete serialized chunk snapshot in document
metadata. For native pipeline adapters, see the indexing API.
For extracted documents, convert the chunks directly to preserve element lineage.
LlamaIndex's include_metadata_in_content=False excludes all metadata from
EMBED/LLM rendering while retaining it for citations and filters. Its default
True preserves existing metadata rendering, excluding only the chunk snapshot.
Vector payload converters return dictionaries without writing to a service or
computing embeddings. Supply one nonempty vector per chunk in the same order,
with a consistent dimension and finite float32-representable real values.
Set use_contextualized_text to match the text actually embedded.
Prefer chunks_to_pinecone_upsert_request() for a Pinecone request envelope.
namespace belongs on that envelope. Aligned filter_metadata entries add flat
queryable fields; generated-name collisions, unsupported values and metadata
larger than max_metadata_bytes fail explicitly. The legacy
chunks_to_pinecone_vectors() per-vector namespace shape is not an SDK request.
chunks_to_weaviate_objects() emits REST batch objects; with the Python v4 client,
pass each object's id as uuid and its properties/vector explicitly.
weaviate_object_id() converts stable chunk IDs for matching deletions.
chunks_to_supabase_rows() returns insert-ready row dictionaries; the caller
owns the database schema and writes.
omnichunk.serialization.chunks_to_langchain_docs(chunks, *, use_contextualized_text=True)
Convert chunks to LangChain Document objects.
Source code in src/omnichunk/serialization.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222 | def chunks_to_langchain_docs(
chunks: Sequence[Chunk],
*,
use_contextualized_text: bool = True,
) -> list[Any]:
"""Convert chunks to LangChain Document objects."""
document_cls = _import_langchain_document_class()
docs: list[Any] = []
for chunk in chunks:
content = chunk.contextualized_text if use_contextualized_text else chunk.text
docs.append(
document_cls(
id=stable_chunk_id(chunk),
page_content=content,
metadata=_chunk_metadata(chunk),
)
)
return docs
|
omnichunk.serialization.chunks_to_llamaindex_docs(chunks, *, use_contextualized_text=True, include_metadata_in_content=True)
Convert chunks to LlamaIndex Document objects.
Set include_metadata_in_content=False to keep EMBED/LLM rendering equal
to the budgeted raw/contextualized payload. The default retains the existing
framework metadata rendering behavior; the snapshot itself is always excluded.
Source code in src/omnichunk/serialization.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432 | def chunks_to_llamaindex_docs(
chunks: Sequence[Chunk],
*,
use_contextualized_text: bool = True,
include_metadata_in_content: bool = True,
) -> list[Any]:
"""Convert chunks to LlamaIndex Document objects.
Set ``include_metadata_in_content=False`` to keep EMBED/LLM rendering equal
to the budgeted raw/contextualized payload. The default retains the existing
framework metadata rendering behavior; the snapshot itself is always excluded.
"""
document_cls = _import_llamaindex_document_class()
docs: list[Any] = []
for chunk in chunks:
content = chunk.contextualized_text if use_contextualized_text else chunk.text
metadata = _chunk_metadata(chunk)
excluded = ["omnichunk"] if include_metadata_in_content else list(metadata)
docs.append(
document_cls(
id_=stable_chunk_id(chunk),
text=content,
metadata=metadata,
# The full provenance snapshot also contains raw/rendered text.
# Keep it accessible without duplicating that text in prompts.
excluded_embed_metadata_keys=excluded,
excluded_llm_metadata_keys=excluded,
)
)
return docs
|
omnichunk.serialization.chunks_to_pinecone_upsert_request(chunks, embeddings, *, namespace='', use_contextualized_text=True, filter_metadata=None, max_metadata_bytes=40 * 1024)
Build index.upsert(**request) with namespace on the request envelope.
Pinecone metadata permits flat scalars and string lists, so complete source,
chunk and format metadata is preserved as JSON in metadata['omnichunk'].
Supply per-chunk filter_metadata for queryable ACL/page/source fields.
Names colliding with generated fields, unsupported values and oversized
metadata fail explicitly. No fields are silently dropped or truncated.
Existing legacy vector IDs are retained; this is a request-shape migration.
Source code in src/omnichunk/serialization.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345 | def chunks_to_pinecone_upsert_request(
chunks: Sequence[Chunk],
embeddings: Sequence[list[float]],
*,
namespace: str = "",
use_contextualized_text: bool = True,
filter_metadata: Sequence[Mapping[str, Any]] | None = None,
max_metadata_bytes: int = 40 * 1024,
) -> dict[str, Any]:
"""Build ``index.upsert(**request)`` with namespace on the request envelope.
Pinecone metadata permits flat scalars and string lists, so complete source,
chunk and format metadata is preserved as JSON in ``metadata['omnichunk']``.
Supply per-chunk ``filter_metadata`` for queryable ACL/page/source fields.
Names colliding with generated fields, unsupported values and oversized
metadata fail explicitly. No fields are silently dropped or truncated.
Existing legacy vector IDs are retained; this is a request-shape migration.
"""
if not isinstance(namespace, str):
raise ValueError("namespace must be a string")
if type(max_metadata_bytes) is not int or not 0 < max_metadata_bytes <= 40 * 1024:
raise ValueError("max_metadata_bytes must be between 1 and 40960")
if filter_metadata is not None and len(filter_metadata) != len(chunks):
raise ValueError("filter_metadata length must match chunks length")
vectors = chunks_to_pinecone_vectors(
chunks, embeddings, use_contextualized_text=use_contextualized_text
)
for index, (chunk, vector) in enumerate(zip(chunks, vectors)):
metadata = vector["metadata"]
metadata["omnichunk"] = json.dumps(
_chunk_snapshot(chunk),
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
allow_nan=False,
)
if filter_metadata is not None:
if not isinstance(filter_metadata[index], Mapping):
raise ValueError("filter_metadata entries must be mappings")
extra = _strict_json_copy(filter_metadata[index])
for key, value in extra.items():
if key.startswith("$"):
raise ValueError("Pinecone filter metadata keys cannot start with '$'")
if key in metadata:
raise ValueError(f"filter_metadata collides with generated field {key!r}")
if not (
type(value) in (str, bool, int, float)
or (isinstance(value, list) and all(type(item) is str for item in value))
):
raise ValueError("Pinecone filter metadata requires scalars or string lists")
if type(value) is int:
try:
exact = math.isfinite(float(value)) and int(float(value)) == value
except OverflowError:
exact = False
if not exact:
raise ValueError(
"Pinecone integer filter metadata must be exactly representable "
"as float64; use strings for identifiers"
)
metadata[key] = value
encoded = json.dumps(metadata, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
if len(encoded.encode("utf-8")) > max_metadata_bytes:
raise ValueError(f"Pinecone metadata exceeds {max_metadata_bytes} bytes")
return {"namespace": namespace, "vectors": vectors}
|
omnichunk.serialization.chunks_to_pinecone_vectors(chunks, embeddings, *, namespace='', use_contextualized_text=True)
Convert chunks to Pinecone upsert-ready dicts (no Pinecone client required).
Each dict has id, values, metadata. If namespace is non-empty, a
top-level namespace key is set on each dict for legacy compatibility.
That legacy shape is not an SDK request. Prefer
:func:chunks_to_pinecone_upsert_request, which places the namespace on the
request envelope and preserves complete chunk metadata.
Source code in src/omnichunk/serialization.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252 | def chunks_to_pinecone_vectors(
chunks: Sequence[Chunk],
embeddings: Sequence[list[float]],
*,
namespace: str = "",
use_contextualized_text: bool = True,
) -> list[dict[str, Any]]:
"""Convert chunks to Pinecone upsert-ready dicts (no Pinecone client required).
Each dict has ``id``, ``values``, ``metadata``. If ``namespace`` is non-empty, a
top-level ``namespace`` key is set on each dict for legacy compatibility.
That legacy shape is not an SDK request. Prefer
:func:`chunks_to_pinecone_upsert_request`, which places the namespace on the
request envelope and preserves complete chunk metadata.
"""
embeddings = _validated_vectors(chunks, embeddings)
out: list[dict[str, Any]] = []
for chunk, values in zip(chunks, embeddings):
row: dict[str, Any] = {
"id": _stable_vector_id(chunk),
"values": list(values),
"metadata": _vectordb_metadata(chunk, use_contextualized_text=use_contextualized_text),
}
if namespace:
row["namespace"] = namespace
out.append(row)
return out
|
omnichunk.serialization.chunks_to_weaviate_objects(chunks, embeddings, *, class_name='OmnichunkDocument', use_contextualized_text=True)
Convert chunks to Weaviate REST batch objects with deterministic UUIDs.
Retries address the same object. Convert removal IDs with
:func:weaviate_object_id before deleting from Weaviate. For the Python v4
client, pass id as uuid and properties/vector explicitly.
Existing objects imported without IDs require a one-time rebuild.
Source code in src/omnichunk/serialization.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375 | def chunks_to_weaviate_objects(
chunks: Sequence[Chunk],
embeddings: Sequence[list[float]],
*,
class_name: str = "OmnichunkDocument",
use_contextualized_text: bool = True,
) -> list[dict[str, Any]]:
"""Convert chunks to Weaviate REST batch objects with deterministic UUIDs.
Retries address the same object. Convert removal IDs with
:func:`weaviate_object_id` before deleting from Weaviate. For the Python v4
client, pass ``id`` as ``uuid`` and ``properties``/``vector`` explicitly.
Existing objects imported without IDs require a one-time rebuild.
"""
embeddings = _validated_vectors(chunks, embeddings)
return [
{
"class": class_name,
"id": weaviate_object_id(stable_chunk_id(chunk)),
"vector": list(values),
"properties": _vectordb_metadata(
chunk,
use_contextualized_text=use_contextualized_text,
),
}
for chunk, values in zip(chunks, embeddings)
]
|
omnichunk.serialization.weaviate_object_id(chunk_id)
Map a stable chunk ID to its Weaviate UUID, also for incremental deletions.
Source code in src/omnichunk/serialization.py
| def weaviate_object_id(chunk_id: str) -> str:
"""Map a stable chunk ID to its Weaviate UUID, also for incremental deletions."""
return str(uuid5(NAMESPACE_URL, f"omnichunk:{chunk_id}"))
|
omnichunk.serialization.chunks_to_supabase_rows(chunks, embeddings, *, use_contextualized_text=True)
Convert chunks to Supabase / pgvector INSERT-ready dicts (no client required).
Source code in src/omnichunk/serialization.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398 | def chunks_to_supabase_rows(
chunks: Sequence[Chunk],
embeddings: Sequence[list[float]],
*,
use_contextualized_text: bool = True,
) -> list[dict[str, Any]]:
"""Convert chunks to Supabase / pgvector INSERT-ready dicts (no client required)."""
embeddings = _validated_vectors(chunks, embeddings)
rows: list[dict[str, Any]] = []
for chunk, values in zip(chunks, embeddings):
meta = _vectordb_metadata(chunk, use_contextualized_text=use_contextualized_text)
content = meta.pop("text")
rows.append(
{
"content": content,
"embedding": list(values),
**meta,
}
)
return rows
|