From fc94678a4e01ed9a75531657a410c0642b7ea16e Mon Sep 17 00:00:00 2001 From: gtdd123 <230968026+gtdd123@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:01:08 +0800 Subject: [PATCH] fix(rag): split paragraphs with Windows line endings --- .changeset/rag-paragraph-line-endings.md | 7 +++++++ .../rag/src/__tests__/recursive-chunker.spec.ts | 16 ++++++++++++++++ packages/rag/src/utils/text.ts | 3 ++- 3 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 .changeset/rag-paragraph-line-endings.md diff --git a/.changeset/rag-paragraph-line-endings.md b/.changeset/rag-paragraph-line-endings.md new file mode 100644 index 000000000..776ca298d --- /dev/null +++ b/.changeset/rag-paragraph-line-endings.md @@ -0,0 +1,7 @@ +--- +"@voltagent/rag": patch +--- + +Preserve paragraph boundaries when recursive chunking text with CRLF or CR line endings. + +Fixes #1566. diff --git a/packages/rag/src/__tests__/recursive-chunker.spec.ts b/packages/rag/src/__tests__/recursive-chunker.spec.ts index a664a2f83..e4ab584e3 100644 --- a/packages/rag/src/__tests__/recursive-chunker.spec.ts +++ b/packages/rag/src/__tests__/recursive-chunker.spec.ts @@ -1,7 +1,23 @@ import { describe, expect, it } from "vitest"; import { RecursiveChunker } from "../chunkers/recursive-chunker"; +import { whitespaceTokenizer } from "../utils/tokenizer"; describe("RecursiveChunker", () => { + it.each(["\n", "\r\n", "\r"])("splits blank lines with %j without changing offsets", (eol) => { + const paragraphs = [ + `Refund requests are accepted.${eol}Include your order number.`, + "Shipping times vary by destination.", + ]; + const text = paragraphs.join(eol.repeat(2)); + const chunker = new RecursiveChunker(whitespaceTokenizer); + const chunks = chunker.chunk(text, { maxTokens: 40 }); + + expect(chunks.map((chunk) => chunk.content)).toEqual(paragraphs); + for (const chunk of chunks) { + expect(text.slice(chunk.start, chunk.end)).toBe(chunk.content); + } + }); + it("splits long paragraphs then falls back to sentence/token chunking", () => { const text = [ "Paragraph one short.", diff --git a/packages/rag/src/utils/text.ts b/packages/rag/src/utils/text.ts index fe93e0edd..855cee8f4 100644 --- a/packages/rag/src/utils/text.ts +++ b/packages/rag/src/utils/text.ts @@ -58,7 +58,8 @@ export function splitIntoParagraphs( tokenizer: Tokenizer = whitespaceTokenizer, ): Segment[] { const parts = text - .split(/\n{2,}/) + // Treat a CRLF pair as one line break while preserving source offsets. + .split(/(?:\r?\n|\r(?!\n)){2,}/) .map((part) => part.trim()) .filter(Boolean);