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
5 changes: 5 additions & 0 deletions .changeset/slumber-token-overlap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@voltagent/rag": patch
---

Use the configured tokenizer to select overlap text in SlumberChunker.
60 changes: 60 additions & 0 deletions packages/rag/src/__tests__/token-chunker.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,67 @@
import { describe, expect, it } from "vitest";
import { TokenChunker } from "../chunkers/token-chunker";
import { createTikTokenizer } from "../utils/tokenizer";

describe("TokenChunker", () => {
it.each([
{ maxTokens: 2.9, overlap: 0 },
{ maxTokens: 3, overlap: 1.9 },
])("floors fractional token options %j", (options) => {
const chunker = new TokenChunker();
const text = "A😀B😀C";
expect(chunker.chunk(text, options)).toEqual(
chunker.chunk(text, {
maxTokens: Math.floor(options.maxTokens),
overlap: Math.floor(options.overlap),
}),
);
});

it.each(["maxTokens", "overlap"] as const)("rejects non-finite %s", (option) => {
for (const value of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) {
expect(() => new TokenChunker().chunk("A😀B", { [option]: value })).toThrow(RangeError);
}
});

it.each(["😀", "𠮷"])("keeps %s whole without repeating it at zero overlap", (word) => {
const tokenizer = createTikTokenizer({ encoding: "cl100k_base" });
const text = `A${word}B`;
const chunks = new TokenChunker(tokenizer).chunk(text, { maxTokens: 2, overlap: 0 });
expect(chunks.map(({ content }) => content)).toEqual(["A", word, "B"]);
expect(chunks.map(({ content }) => content).join("")).toBe(text);
for (const chunk of chunks) {
expect(chunk.tokens).toBe(tokenizer.countTokens(chunk.content));
expect(text.slice(chunk.start, chunk.end)).toBe(chunk.content);
}
// A character larger than the budget is emitted alone, without dropping bytes.
expect(chunks[1]?.tokens).toBe(tokenizer.countTokens(word));
});

it.each([1, 2])("rounds overlap %i down to complete source spans", (overlap) => {
const tokenizer = createTikTokenizer({ encoding: "cl100k_base" });
const text = "A😀B😀C";
const chunks = new TokenChunker(tokenizer).chunk(text, { maxTokens: 3, overlap });
expect(chunks.at(-1)?.end).toBe(text.length);
for (const [index, chunk] of chunks.entries()) {
expect(chunk.tokens).toBe(tokenizer.countTokens(chunk.content));
expect(chunk.tokens).toBeLessThanOrEqual(3);
expect(text.slice(chunk.start, chunk.end)).toBe(chunk.content);
for (const boundary of [chunk.start, chunk.end]) {
expect(text.slice(boundary - 1, boundary + 1)).not.toMatch(
/[\uD800-\uDBFF][\uDC00-\uDFFF]/,
);
}
if (index === 0) continue;
const previous = chunks[index - 1];
expect(chunk.start).toBeGreaterThan(previous.start);
expect(chunk.start).toBeLessThanOrEqual(previous.end);
expect(tokenizer.countTokens(text.slice(chunk.start, previous.end))).toBeLessThanOrEqual(
overlap,
);
expect(chunk.content).not.toContain("\uFFFD");
Comment thread
embrace897 marked this conversation as resolved.
Resolved
}
});

it("splits text by token count with overlap", () => {
const chunker = new TokenChunker();
const text = "one two three four five six seven eight nine ten";
Expand Down
58 changes: 58 additions & 0 deletions packages/rag/src/__tests__/tokenizer-unicode.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { describe, expect, it } from "vitest";
import { createTikTokenizer } from "../utils/tokenizer";

describe("tiktoken source spans", () => {
it.each([
[
"a𠮷z",
[
[0, 1],
[1, 3],
[1, 3],
[1, 3],
[1, 3],
[3, 4],
],
],
[
"A😀B",
[
[0, 1],
[1, 3],
[1, 3],
[3, 4],
],
],
] as const)("maps split UTF-8 tokens in %j to complete source characters", (text, ranges) => {
const tokenizer = createTikTokenizer({ encoding: "cl100k_base" });
expect(tokenizer.tokenize(text).map(({ start, end }) => [start, end])).toEqual(ranges);
});

it.each(["gpt2", "r50k_base", "p50k_base", "p50k_edit", "cl100k_base", "o200k_base"] as const)(
"preserves source positions with %s",
(encoding) => {
const tokenizer = createTikTokenizer({ encoding });
for (const text of [
"plain ASCII",
"你好世界",
"𠮷野家",
"👩‍💻 works",
"a\uFFFDz",
"a\uD800z",
"",
]) {
const tokens = tokenizer.tokenize(text);
expect(tokens).toHaveLength(tokenizer.countTokens(text));
for (const token of tokens) {
expect(token.start).toBeGreaterThanOrEqual(0);
expect(token.end).toBeLessThanOrEqual(text.length);
expect(token.end).toBeGreaterThan(token.start);
expect(text.slice(token.start, token.end)).toBe(token.value);
Comment thread
embrace897 marked this conversation as resolved.
Resolved
const startCode = text.charCodeAt(token.start);
expect(startCode >= 0xdc00 && startCode <= 0xdfff).toBe(false);
}
expect(tokens.at(-1)?.end ?? 0).toBe(text.length);
}
},
);
});
66 changes: 66 additions & 0 deletions packages/rag/src/chunkers/slumber-chunker-overlap.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import type { Tokenizer } from "../types";
import { SlumberChunker } from "./slumber-chunker";

const tokenize: Tokenizer["tokenize"] = (text) =>
Array.from(text.matchAll(/[a-z]+|\S/gi), (match) => ({
value: match[0],
start: match.index,
end: match.index + match[0].length,
}));

describe("SlumberChunker overlap", () => {
it.each(["𠮷", "👩‍💻"])("keeps Unicode overlap in the source for %j", (word) => {
const text = `First.${word} works.`;
const chunks = new SlumberChunker().chunk(text, {
maxTokens: 6,
minTokens: 1,
overlapTokens: 1,
});
const overlaps = chunks.filter((chunk) => chunk.label === "slumber-overlap");
expect(overlaps.length).toBeGreaterThan(0);
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
const wordStart = text.indexOf(word);
expect(
overlaps.some((chunk) => chunk.start < wordStart + word.length && chunk.end > wordStart),
).toBe(true);
expect(overlaps[0]?.content).toBe(Array.from(word)[0]);
for (const overlap of overlaps) {
expect(overlap.end).toBeLessThanOrEqual(text.length);
expect(text.slice(overlap.start, overlap.end)).toBe(overlap.content);
expect(overlap.content).not.toContain("\uFFFD");
const first = overlap.content.charCodeAt(0);
const last = overlap.content.charCodeAt(overlap.content.length - 1);
expect(first >= 0xdc00 && first <= 0xdfff).toBe(false);
expect(last >= 0xd800 && last <= 0xdbff).toBe(false);
}
});

it.each([" ", " ", "\n", "\r\n"])("preserves the overlap source range after %j", (separator) => {
const text = `First.${separator}red-blue.`;
const chunks = new SlumberChunker().chunk(text, {
maxTokens: 4,
minTokens: 2,
overlapTokens: 1,
tokenizer: { tokenize, countTokens: (value) => tokenize(value).length },
});
const overlap = chunks.find((chunk) => chunk.label === "slumber-overlap");
expect(overlap).toBeDefined();
expect(overlap?.content).toBe("red");
expect(overlap?.start).toBe(text.indexOf("red"));
expect(overlap?.end).toBe(text.indexOf("red") + 3);
expect(text.slice(overlap?.start, overlap?.end)).toBe(overlap?.content);
});

it("uses the configured tokenizer to select the overlap and its source range", () => {
const text = "First.red-blue.";
const chunks = new SlumberChunker().chunk(text, {
maxTokens: 4,
minTokens: 2,
overlapTokens: 1,
tokenizer: { tokenize, countTokens: (value) => tokenize(value).length },
});

expect(chunks.map(({ content }) => content)).toEqual(["First.", "red", "red-blue."]);
expect(chunks[1]).toMatchObject({ start: 6, end: 9 });
});
});
13 changes: 8 additions & 5 deletions packages/rag/src/chunkers/slumber-chunker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,16 @@ export class SlumberChunker implements Chunker<SlumberChunkerOptions> {
if (i === merged.length - 1) break;
const next = merged[i + 1];
if (!next) continue;
const overlapContent = next.content.split(/\s+/).slice(0, overlapTokens).join(" ");
if (overlapContent) {
const sourceContent = text.slice(next.start, next.end);
const tokens = tokenizer.tokenize(sourceContent);
const first = tokens[0];
const last = tokens[Math.min(tokens.length, Math.floor(overlapTokens)) - 1];
if (first && last && last.end > first.start) {
withOverlap.push({
id: `${label}-overlap-${i}`,
content: overlapContent,
start: next.start,
end: next.start + overlapContent.length,
content: sourceContent.slice(first.start, last.end),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
start: next.start + first.start,
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
end: next.start + last.end,
label: `${label}-overlap`,
metadata: buildMetadata({
format: "slumber",
Expand Down
46 changes: 39 additions & 7 deletions packages/rag/src/chunkers/token-chunker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import { buildLineMap, positionForRange } from "../utils/position";
import { defaultTokenizer, sliceByTokenRange } from "../utils/tokenizer";

export type TokenChunkerOptions = {
/** Finite values are floored and clamped to at least one. Oversized characters are emitted alone. */
maxTokens?: number;
/** Finite values are floored; overlap is rounded down to complete source characters. */
overlap?: number;
tokenizer?: Tokenizer;
label?: string;
Expand All @@ -19,8 +21,13 @@ export class TokenChunker implements Chunker<TokenChunkerOptions> {

chunk(text: string, options?: TokenChunkerOptions): Chunk[] {
const tokenizer = options?.tokenizer ?? this.tokenizer;
const maxTokens = Math.max(1, options?.maxTokens ?? 200);
const overlap = Math.max(0, Math.min(options?.overlap ?? 0, maxTokens - 1));
const requestedMaxTokens = options?.maxTokens ?? 200;
const requestedOverlap = options?.overlap ?? 0;
if (!Number.isFinite(requestedMaxTokens) || !Number.isFinite(requestedOverlap)) {
throw new RangeError("maxTokens and overlap must be finite numbers.");
}
const maxTokens = Math.max(1, Math.floor(requestedMaxTokens));
const overlap = Math.max(0, Math.min(Math.floor(requestedOverlap), maxTokens - 1));
const lineMap = buildLineMap(text);

const tokens = tokenizer.tokenize(text);
Expand All @@ -31,11 +38,28 @@ export class TokenChunker implements Chunker<TokenChunkerOptions> {
const chunks: Chunk[] = [];
let startIndex = 0;
let chunkIndex = 0;
const step = Math.max(1, maxTokens - overlap);
const isBoundary = (index: number) =>
index === tokens.length || tokens[index - 1].end <= tokens[index].start;

while (startIndex < tokens.length) {
const endIndex = Math.min(tokens.length - 1, startIndex + maxTokens - 1);
const content = sliceByTokenRange(text, tokens, startIndex, endIndex);
let end = Math.min(tokens.length, startIndex + maxTokens);
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
while (end > startIndex && !isBoundary(end)) end -= 1;
if (end === startIndex) {
// Keep an oversized character whole and always advance.
end = startIndex + 1;
while (!isBoundary(end)) end += 1;
}
let content = sliceByTokenRange(text, tokens, startIndex, end - 1);
let tokenCount = tokenizer.countTokens(content);
while (tokenCount > maxTokens) {
let previous = end - 1;
while (previous > startIndex && !isBoundary(previous)) previous -= 1;
if (previous === startIndex) break;
end = previous;
content = sliceByTokenRange(text, tokens, startIndex, end - 1);
tokenCount = tokenizer.countTokens(content);
}
const endIndex = end - 1;

chunks.push({
id: `token-${chunkIndex}`,
Expand All @@ -56,12 +80,20 @@ export class TokenChunker implements Chunker<TokenChunkerOptions> {
),
},
}),
tokens: endIndex - startIndex + 1,
tokens: tokenCount,
label: options?.label ?? "token",
});

if (endIndex === tokens.length - 1) break;
startIndex += step;
let nextStart = Math.max(startIndex + 1, end - overlap);
while (
nextStart < end &&
(!isBoundary(nextStart) ||
tokenizer.countTokens(sliceByTokenRange(text, tokens, nextStart, endIndex)) > overlap)
) {
nextStart += 1;
}
startIndex = nextStart;
chunkIndex += 1;
}

Expand Down
Loading