import hashlib
import importlib.metadata
import json
from dataclasses import dataclass
import tiktoken
from chonkie import RecursiveChunker
@dataclass(frozen=True)
class Source:
tenant_id: str
document_id: str
title: str
text: str
def digest(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def encode_id(parts: list) -> str:
return digest(json.dumps(parts, ensure_ascii=False, separators=(",", ":")))
def count_tokens(text: str) -> int:
enc = tiktoken.get_encoding("cl100k_base")
return len(enc.encode(text, disallowed_special=()))
def prefix(source: Source) -> str:
return f"Document: {source.title}\n\n"
def strategy_id(chunk_size: int, max_input_tokens: int) -> str:
return encode_id([
"recursive", "cl100k_base", chunk_size, max_input_tokens,
importlib.metadata.version("chonkie"),
importlib.metadata.version("chonkie-core"),
importlib.metadata.version("tokie"),
importlib.metadata.version("tiktoken"),
])
def row_id(source: Source, row: dict) -> str:
return encode_id([
source.tenant_id, source.document_id, row["source_version"],
row["strategy_id"], row["start"], row["end"], row["embedding_text"],
])
def audit(source: Source, rows: list[dict], chunk_size: int,
max_input_tokens: int) -> None:
version = digest(source.text)
expected_strategy = strategy_id(chunk_size, max_input_tokens)
cursor, seen = 0, set()
for row in rows:
if (row["tenant_id"], row["document_id"], row["source_version"],
row["strategy_id"]) != (
source.tenant_id, source.document_id, version, expected_strategy):
raise ValueError("Source metadata mismatch")
start, end = row["start"], row["end"]
if type(start) is not int or type(end) is not int:
raise ValueError("Offsets must be integers")
if not (cursor <= start < end <= len(source.text)):
raise ValueError("Invalid or overlapping source offsets")
if source.text[cursor:start].strip():
raise ValueError("Source content missing before chunk")
if source.text[start:end] != row["text"]:
raise ValueError("Chunk does not match source span")
payload = prefix(source) + row["text"]
actual = count_tokens(payload)
if row["embedding_text"] != payload or row["token_count"] != actual:
raise ValueError("Embedding payload or token count mismatch")
if actual > max_input_tokens:
raise ValueError("Embedding payload exceeds configured budget")
if row["chunk_id"] != row_id(source, row) or row["chunk_id"] in seen:
raise ValueError("Invalid or duplicate chunk ID")
seen.add(row["chunk_id"])
cursor = end
if source.text[cursor:].strip():
raise ValueError("Source content missing after last chunk")
def prepare(source: Source, chunk_size: int = 64,
max_input_tokens: int = 96) -> list[dict]:
if not all(isinstance(v, str) and v.strip()
for v in [source.tenant_id, source.document_id, source.title]):
raise ValueError("Trusted source identifiers and title are required")
if not isinstance(source.text, str):
raise ValueError("Source text must be a string")
if type(chunk_size) is not int or type(max_input_tokens) is not int:
raise ValueError("Budgets must be integers")
if not (0 < chunk_size < max_input_tokens):
raise ValueError("Leave room for the embedding prefix")
if count_tokens(prefix(source)) >= max_input_tokens:
raise ValueError("Title prefix exhausts the embedding budget")
if not source.text.strip():
return []
chunker = RecursiveChunker(
tokenizer=tiktoken.get_encoding("cl100k_base"),
chunk_size=chunk_size,
min_characters_per_chunk=1,
)
version = digest(source.text)
strategy = strategy_id(chunk_size, max_input_tokens)
rows = []
for chunk in chunker.chunk(source.text):
payload = prefix(source) + chunk.text
row = {
"tenant_id": source.tenant_id, "document_id": source.document_id,
"source_version": version, "strategy_id": strategy,
"start": chunk.start_index, "end": chunk.end_index,
"text": chunk.text, "embedding_text": payload,
"token_count": count_tokens(payload),
}
row["chunk_id"] = row_id(source, row)
rows.append(row)
audit(source, rows, chunk_size, max_input_tokens)
return rows
if __name__ == "__main__":
source = Source("demo-tenant", "handbook-1", "示例手册",
("中文与 English 同行。保留 emoji 🦛 与 e\u0301。\n\n" * 8))
rows = prepare(source)
print(json.dumps({"chunks": len(rows),
"max_payload_tokens": max(r["token_count"] for r in rows),
"budget": 96}, ensure_ascii=False))