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/unique-code-ast-chunk-ids.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@voltagent/rag": patch
---

Keep code chunk IDs unique when token splitting expands an AST block before other blocks.
33 changes: 33 additions & 0 deletions packages/rag/src/chunkers/code-chunker-ast-ids.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { whitespaceTokenizer } from "../utils/tokenizer";
import { CodeChunker } from "./code-chunker";

describe("CodeChunker AST expansion", () => {
it("assigns unique IDs when a split AST block precedes smaller blocks", () => {
const blocks = ["one two three four five", "six", "seven"];
const text = ["```txt", ...blocks, "```"].join("\n");
const chunks = new CodeChunker(whitespaceTokenizer).chunk(text, {
maxTokens: 2,
parser: (source) =>
blocks.map((block) => {
const start = source.indexOf(block);
return { kind: "function", start, end: start + block.length };
}),
});

expect(chunks.map((chunk) => chunk.content)).toEqual([
"one two",
"three four",
"five",
"six",
"seven",
]);
expect(chunks.map((chunk) => chunk.id)).toEqual([
"code-0",
"code-1",
"code-2",
"code-3",
"code-4",
]);
});
});
4 changes: 2 additions & 2 deletions packages/rag/src/chunkers/code-chunker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,10 @@ export class CodeChunker implements Chunker<CodeChunkerOptions> {
tokenizer,
label: `${label}-ast`,
});
tokenChunks.forEach((chunk, idx) => {
tokenChunks.forEach((chunk) => {
chunks.push({
...chunk,
id: `${label}-${chunks.length + idx}`,
id: `${label}-${chunks.length}`,
start: segment.start + block.start + chunk.start,
end: segment.start + block.start + chunk.end,
metadata: buildMetadata({
Expand Down