fix(rag): use the configured tokenizer for Slumber overlap

EM
3d ago
+267-21

PR Checklist

  • The proposed commit message follows Conventional Commits.

Bugs / Features

  • Related issue(s) linked. Reproduced directly on main.
  • Tests for the changes have been added.
  • Docs have been added or updated.
  • A patch changeset for @voltagent/rag has been added.

What is the current behavior?

SlumberChunker selects overlap by splitting on whitespace, so one requested token can contain several tokens with the configured tokenizer. Token positions also drift when individual tiktoken IDs contain only part of a UTF-8 character.

What is the new behavior?

Select overlap with the configured tokenizer and derive its content and range from the source text. Map tiktoken byte spans to complete source characters, preserving token counts when several tokens share a character. Reuse byte-length tables across tokenizer instances and compute UTF-8 character widths without per-character buffers.

TokenChunker windows now stop at complete source-span boundaries and count tokens from the emitted content. Overlap is rounded down to avoid splitting a source span. An indivisible span larger than the budget is emitted alone, with its actual token count.

Regression tests cover punctuation, separator whitespace, six encodings, explicit Unicode ranges, overlaps that actually include supplementary characters, and zero/nonzero TokenChunker overlap with split Unicode tokens.

Notes for reviewers

  • RAG package: vitest run --typecheck — 66 tests passed across 21 files.
  • Package build: tsup --config tsup.config.ts — CommonJS, ESM, and declarations passed.
  • Changed-file Biome and git diff --check passed.
  • These checks used an isolated dependency installation with Vitest 3.2.4, TypeScript 5.9.2, and tsup 8.5.0. The full monorepo checks were not run.
  • js-tiktoken@1.0.14 already exports getEncodingNameForModel and the rank data used here. The dependency minimum is unchanged.

OpenAI Codex assisted with reproduction, implementation, and local validation.

Summary by CodeRabbit

  • Bug Fixes

    • Improved text chunking for Unicode content, preserving complete characters and avoiding replacement characters or split surrogate pairs.
    • Overlap selection now follows configured tokenizer boundaries, including for whitespace and newline separators.
    • Chunk token counts and source ranges now better reflect the text included in each chunk.
  • Tests

    • Added coverage for Unicode token spans, chunk boundaries, and tokenizer-configured overlap behavior.