Skip to content

feat: DocumentSplitter — add split_by="token" mode using tiktoken - #12529

Merged
anakin87 merged 9 commits into
deepset-ai:mainfrom
rautaditya2606:feat/document-splitter-token
Sep 4, 2026
Merged

anakin87 merged 9 commits into
deepset-ai:mainfrom
rautaditya2606:feat/document-splitter-token

Conversation

@rautaditya2606

Copy link
Copy Markdown
Contributor

Related Issues

closes #12528

Proposed Changes

DocumentSplitter supports 7 split_by modes but not token-based splitting. Users who need
simple token-aware chunking are forced to use RecursiveDocumentSplitter even when they don't
need recursion. This PR adds split_by="token" to DocumentSplitter using tiktoken, aligning
it with the existing split_unit="token" support in RecursiveDocumentSplitter.

What changed:

  • split_by="token" added to the Literal type and valid_split_by list
  • New tokenizer_encoding: str = "o200k_base" param (keyword-only, matches RecursiveDocumentSplitter default)
  • Lazy tiktoken import via LazyImport — same pattern as RecursiveDocumentSplitter
  • __init__: eager tiktoken_imports.check() if token mode; sets self._tiktoken_tokenizer = None
  • warm_up(): loads tiktoken encoder if token mode — mirrors sentence splitter pattern exactly
  • run(): auto-triggers warm_up() for token mode — same lazy-init pattern as sentence mode
  • _split_by_token(): encode → slice by [i : i + split_length] with step = split_length - split_overlap → decode; tracks cur_page and cur_start_idx; delegates to _create_docs_from_splits
  • to_dict(): serialises tokenizer_encoding

Before:

# No token-aware option — forced to use RecursiveDocumentSplitter
splitter = RecursiveDocumentSplitter(split_length=256, split_overlap=32, split_unit="token")

After:

splitter = DocumentSplitter(split_by="token", split_length=256, split_overlap=32)
result = splitter.run(documents=[Document(content="...")])

How did you test it?

Added TestSplittingByToken class (7 @pytest.mark.integration tests) to
test/components/preprocessors/test_document_splitter.py:

  • test_basic_chunking — chunks produced, no chunk exceeds split_length tokens
  • test_metadata_set — source_id, split_id, split_idx_start, page_number all set correctly
  • test_overlap_produces_shared_text — overlap produces correct index overlap between consecutive chunks
  • test_page_tracking — page_number advances correctly across \f boundaries
  • test_empty_document_skipped — empty content skipped with correct log message
  • test_custom_encoding — tokenizer_encoding="cl100k_base" works correctly
  • test_serialization_roundtrip — to_dict / from_dict round-trip preserves all params

All 56 existing unit tests and 7 new integration tests pass. mypy clean.

hatch run test:unit test/components/preprocessors/test_document_splitter.py
hatch run test:integration test/components/preprocessors/test_document_splitter.py
hatch run test:types

Notes for the reviewer

  • _split_by_token is self-contained and does not share code with RecursiveDocumentSplitter —
    the recursive splitter's tokenizer logic is deeply intertwined with its overlap and chunk-length
    helpers. A future refactor can extract shared utilities if needed.
  • split_threshold is not applied in token mode — consistent with how it is silently irrelevant
    for sentence and function modes.
  • The existing split_overlap >= split_length guard at _init_checks L153–154 covers token mode
    automatically — no additional guard needed.

Checklist

  • I have read the contributors guidelines and the code of conduct.
  • I have updated the related issue with new insights and changes.
  • I have added unit tests and updated the docstrings.
  • I've used one of the conventional commit types for my PR title: fix:, feat:, build:, chore:, ci:, docs:, style:, refactor:, perf:, test: and added ! in case the PR includes breaking changes.
  • I have documented my code.
  • I have added a release note file, following the contributors guidelines.
  • I have run pre-commit hooks and fixed any issue.

@rautaditya2606
rautaditya2606 requested a review from a team as a code owner August 31, 2026 10:57
@rautaditya2606
rautaditya2606 requested review from anakin87 and a lite review from Copilot and removed request for a team August 31, 2026 10:57
@vercel

vercel Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

@rautaditya2606 is attempting to deploy a commit to the deepset Team on Vercel.

A member of the Team first needs to authorize it.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot added topic:tests type:documentation Improvements on the docs labels Aug 31, 2026
@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  haystack/components/preprocessors
  document_preprocessor.py
  document_splitter.py 210, 236
Project Total  

This report was generated by python-coverage-comment-action

@anakin87 anakin87 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left some initial comments.

I'd appreciate it if also @davidsbatista could take a look as he previously worked on this component (if I am not mistaken)

@rautaditya2606

rautaditya2606 commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

hey @anakin87 , made all the changes. please let me know if anything else needs fixing

@davidsbatista

Copy link
Copy Markdown
Contributor

You also need to update the DocumentPreprocessor to expose the new mode "token"

haystack/components/preprocessors/document_preprocessor.py

split_by: Literal["function", "page", "passage", "period", "word", "line", "sentence"] = "word",

@rautaditya2606

Copy link
Copy Markdown
Contributor Author

Hello @davidsbatista, I've implemented this as you suggested

@anakin87

anakin87 commented Sep 2, 2026

Copy link
Copy Markdown
Member

Apart from a minor comment, it looks good. @davidsbatista could you take a final look?

@davidsbatista

Copy link
Copy Markdown
Contributor

Looks already pretty good to me. I would only add two more tests to TestSplittingByTokenIntegration they cover page splitting and tracking that every other split mode already has:

    def test_add_page_number_to_metadata_with_no_overlap_token_split(self):
          splitter = DocumentSplitter(split_by="token", split_length=5, split_overlap=0)
          text = "one two three four five\fsix seven eight nine ten\feleven twelve thirteen fourteen fifteen"
          doc = Document(content=text)
          docs = splitter.run(documents=[doc])["documents"]

          assert len(docs) > 1
          assert docs[0].meta["page_number"] == 1
          for d in docs:
              expected_page = 1 + text[: d.meta["split_idx_start"]].count("\f")
              assert d.meta["page_number"] == expected_page
          assert docs[-1].meta["page_number"] == 3

      def test_add_page_number_to_metadata_with_overlap_token_split(self):
          splitter = DocumentSplitter(split_by="token", split_length=5, split_overlap=2)
          text = "one two three four five\fsix seven eight nine ten\feleven twelve thirteen fourteen fifteen"
          doc = Document(content=text)
          docs = splitter.run(documents=[doc])["documents"]

          assert len(docs) > 1
          for d in docs:
              expected_page = 1 + text[: d.meta["split_idx_start"]].count("\f")
              assert d.meta["page_number"] == expected_page
          assert docs[-1].meta["page_number"] == 3

@rautaditya2606

Copy link
Copy Markdown
Contributor Author

Hello @davidsbatista, I have added the tests

@vercel

vercel Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
haystack-docs Ready Ready Preview Sep 3, 2026 11:47am UTC

Request Review

@davidsbatista davidsbatista left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good to me, only waiting for @anakin87 approval and then we can merge

@anakin87
anakin87 merged commit 58c00bf into deepset-ai:main Sep 4, 2026
24 checks passed
@rautaditya2606

Copy link
Copy Markdown
Contributor Author

thank you for the review @davidsbatista and @anakin87

This branch was successfully deployed

1 active deployment
Preview — 67530c47 Deployed Sep 3, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

topic:tests type:documentation Improvements on the docs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: DocumentSplitter — add split_by="token" mode using tiktoken

4 participants