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/count-constructor-keywords.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@voltagent/rag": patch
---

Count words such as `constructor` correctly when extracting document keywords, so inherited object properties do not affect their frequency or ranking.
49 changes: 49 additions & 0 deletions packages/rag/src/__tests__/document-keywords.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { describe, expect, it } from "vitest";
import { StructuredDocument } from "../document/document";

describe("StructuredDocument keyword frequencies", () => {
it.each(["constructor", "CONSTRUCTOR"])("counts the word %s without inherited values", (word) => {
const doc = StructuredDocument.fromText(
`alpha beta gamma delta epsilon ${word} ${word} ${word}`,
);

doc.extract({ keywords: true });

expect(doc.getNodes()[0]?.metadata?.keywords).toEqual([
"constructor",
"alpha",
"beta",
"gamma",
"delta",
]);
});

it("counts inherited-property names across document nodes", () => {
const doc = new StructuredDocument([
{ text: "alpha beta constructor", docId: "first" },
{ text: "constructor constructor", docId: "second" },
]);

doc.extract({ keywords: true });

for (const node of doc.getNodes()) {
expect(node.metadata?.keywords).toEqual(["constructor", "alpha", "beta"]);
}
});

it("keeps frequency ranking and encounter order for ordinary words", () => {
const doc = StructuredDocument.fromText("alpha beta beta gamma");

doc.extract({ keywords: true });

expect(doc.getNodes()[0]?.metadata?.keywords).toEqual(["beta", "alpha", "gamma"]);
});

it("returns no keywords for text without matching words", () => {
const doc = StructuredDocument.fromText("123 !");

doc.extract({ keywords: true });

expect(doc.getNodes()[0]?.metadata?.keywords).toEqual([]);
});
});
2 changes: 1 addition & 1 deletion packages/rag/src/document/extractors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export function extractSummary(nodes: DocNode[]): DocNode[] {
}

export function extractKeywords(nodes: DocNode[], topN = 5): DocNode[] {
const freq: Record<string, number> = {};
const freq: Record<string, number> = Object.create(null);
const words = nodes.flatMap((n) => n.text.toLowerCase().match(/\b[a-z]{3,}\b/g) || []);
words.forEach((w) => {
freq[w] = (freq[w] ?? 0) + 1;
Expand Down