crawl4ai icon indicating copy to clipboard operation
crawl4ai copied to clipboard

fix(chunking): preserve sentence order in NlpSentenceChunking.chunk()

Open devteamaegis opened this issue 6 months ago • 0 comments

Summary

NlpSentenceChunking.chunk() currently returns list(set(sens)). Because Python's set is unordered, the sentences returned by sent_tokenize are shuffled into an arbitrary order and duplicate sentences are silently discarded.

Before:

return list(set(sens))   # arbitrary order, deduplicates silently

After:

return sens              # document order, keeps duplicates

Impact

Any caller that relies on chunks being in the same order as the original text (e.g. context-window filling, RAG pipeline chunking, sequential LLM prompts) gets non-deterministic, out-of-order results with the old code.

Tests

Added tests/unit/test_nlp_sentence_chunking_order.py with two tests:

  • test_nlp_sentence_chunking_preserves_order — verifies sentences come back in document order.
  • test_nlp_sentence_chunking_keeps_duplicates — verifies duplicate sentences are not silently dropped.

The test file uses a lightweight stub to avoid importing the full crawl4ai package (which requires playwright and pyOpenSSL at import time).

Fixes #1909

devteamaegis avatar May 28 '26 16:05 devteamaegis