Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/rag-paragraph-line-endings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@voltagent/rag": patch
---

Preserve paragraph boundaries when recursive chunking text with CRLF or CR line endings.

Fixes #1566.
16 changes: 16 additions & 0 deletions packages/rag/src/__tests__/recursive-chunker.spec.ts
Original file line number Diff line number Diff line change
@@ -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.",
Expand Down
3 changes: 2 additions & 1 deletion packages/rag/src/utils/text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down