feat: add TokenChunker for token-level chunking via tiktoken (closes #44) - #82
Conversation
adaumsilva
left a comment
There was a problem hiding this comment.
Thanks for adding TokenChunker @prashantshukla01 . The existing tests and Ruff pass, but testing with real tiktoken revealed two issues:
-
Unicode text can be corrupted. Decoding an arbitrary token window can split a character’s UTF-8 bytes. With
chunk_tokens=1andoverlap_tokens=0,"🙂"becomes chunks containing"�"and"��". Please preserve complete characters at chunk boundaries while respecting the token limit. If a character cannot fit, raise a clear error rather than silently corrupting it. Add emoji and CJK regression tests. -
Special-token strings cause valid document text to fail. Encoding
"Hello <|endoftext|> world"raises ValueError. Please treat these strings as ordinary text, for example withencode(document.content, disallowed_special=()), and add a regression test.
Please ensure the tests cover these tokenizer behaviors; the current ASCII-only fake-tokenizer cases miss them.
Also resolve the changelog conflict while preserving existing entries. I’ll handle the broader changelog cleanup afterward.
Please request another review once the fixes are pushed and CI passes.
|
Thanks for contributing @prashantshukla01 I requestes a few changes before merging the PR. Please, address these changes. |
|
Hi @adaumsilva, I've pushed the fixes addressing your feedback:
All unit tests (41/41), |
adaumsilva
left a comment
There was a problem hiding this comment.
Thanks for addressing the requested changes! I verified with real tiktoken that Unicode characters remain intact, special-token strings are treated as ordinary text, and an insufficient token budget raises a clear error.
All 41 chunker tests pass locally, Ruff and mypy for the chunker module pass, and all GitHub checks are green. The changelog update also preserves existing entries.
No blocking issues remain. Approved—thanks for contributing TokenChunker!
|
Great work! Thanks for contributing @prashantshukla01 PR Merged! Remember to star the repo if you didn't yet. |
Description
Adds
TokenChunkerto split text into chunks measured in tokens usingtiktoken. This ensures chunks align directly with embedding-model and LLM token limits instead of relying on character counts.Closes #44
Changes
TokenChunkersubclassingTextChunkerinragframework/document/chunkers.pywith sliding window and token overlap.tiktokenwith installation instructions.token_countandchunk_indexin chunk metadata following existing conventions.tokens = ["tiktoken>=0.7"]optional dependency and included it in theallextra inpyproject.toml.TokenChunkerinragframework/document/__init__.py.tests/test_document/test_chunkers.pyusing a faketiktokenmodule to avoid network downloads in CI.CHANGELOG.mdunder[Unreleased].Type of change
Checklist
pytest tests/ -vpasses locallyruff check ragframework/passesmypy ragframework/passesCHANGELOG.mdupdated under[Unreleased]