Skip to main content

agrag.chunking.token.TokenChunker

Bases: SpanChunker

Cuts the text into windows of chunk_size tokens.

Neighbouring chunks overlap when chunk_overlap is set, and each chunk keeps its exact span in the document.

Attributes:

  • chunk_size (int) – The window size, counted with tokenizer.
  • chunk_overlap (int | float) – The overlap between neighbours. An int counts tokens. A float from 0 up to 1 is a share of chunk_size.
  • tokenizer (str) – The tokenizer that counts size. "character" counts characters.

Functions:

  • chunk – Split a document into chunks.
  • fingerprint – Return the hash of settings(), 16 hex characters.
  • model_copy – Copy the chunker, validating any changed setting.
  • model_post_init – Build the engine once, so a bad setting fails at construction.
  • settings – Return the strategy name and every setting as JSON-safe data.
  • spans – Return the half-open character spans this strategy cuts text into.

chunk​

chunk(document:Document) -> list[Chunk]

Split a document into chunks.

Every chunk has non-empty text, indexes run from 0 without gaps, and a chunk with text provenance has text equal to document.text at its offsets.

Parameters:

  • document (Document) – The document to split.

Returns:

  • list[Chunk] – The chunks, in document order, each with chunker and chunker_hash set. A strategy that sets chunker itself keeps its value.

Raises:

  • ChunkingError – The strategy returned chunks that break the contract.

chunk_overlap​

chunk_overlap: int | float = Field(default=0, ge=0)

chunk_size​

chunk_size: int = Field(default=256, gt=0)

fingerprint​

fingerprint() -> str

Return the hash of settings(), 16 hex characters.

model_config​

model_config = ConfigDict(frozen=True, extra='forbid')

model_copy​

model_copy(*, update:Mapping[str, Any] | None = None, deep:bool = False) -> Self

Copy the chunker, validating any changed setting.

A plain copy keeps the fingerprint and the splitter of the original. A copy with changes is built again from its configuration.

model_post_init​

model_post_init(context:Any) -> None

Build the engine once, so a bad setting fails at construction.

settings​

settings() -> dict[str, Any]

Return the strategy name and every setting as JSON-safe data.

A setting that is itself a chunker appears as that chunker's settings.

spans​

spans(text:str) -> list[tuple[int, int]]

Return the half-open character spans this strategy cuts text into.

A cut inside a character that a tokenizer splits into several tokens makes an empty piece. This method drops empty pieces, and no text is lost with them.

Parameters:

  • text (str) – The text to cut.

Returns:

  • list[tuple[int, int]] – The spans, in order, all non-empty.

strategy​

strategy: str

The strategy name, "token".

tokenizer​

tokenizer: str = DEFAULT_TOKENIZER