@gnldev/rag 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +40 -0
- package/dist/chunk.d.ts +22 -0
- package/dist/chunk.js +127 -0
- package/dist/chunk.js.map +1 -0
- package/dist/graph-rag.d.ts +46 -0
- package/dist/graph-rag.js +152 -0
- package/dist/graph-rag.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/postgres-vector-store.d.ts +50 -0
- package/dist/postgres-vector-store.js +165 -0
- package/dist/postgres-vector-store.js.map +1 -0
- package/dist/rag-tool.d.ts +42 -0
- package/dist/rag-tool.js +30 -0
- package/dist/rag-tool.js.map +1 -0
- package/dist/rerank.d.ts +8 -0
- package/dist/rerank.js +38 -0
- package/dist/rerank.js.map +1 -0
- package/dist/semantic-memory.d.ts +41 -0
- package/dist/semantic-memory.js +90 -0
- package/dist/semantic-memory.js.map +1 -0
- package/dist/vector-store.d.ts +72 -0
- package/dist/vector-store.js +101 -0
- package/dist/vector-store.js.map +1 -0
- package/package.json +73 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Karaca Yılmaz (https://gnl.dev)
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# @gnldev/rag
|
|
2
|
+
|
|
3
|
+
**Vector store + RAG tool** for AI SDK agents. Used as a tool inside `runDurable`, it's automatically
|
|
4
|
+
**replayable** (thanks to durableTool the retrieval is journaled: on resume it comes back from the record
|
|
5
|
+
instead of running again).
|
|
6
|
+
|
|
7
|
+
> Install: `pnpm add @gnldev/rag` — or use it from a [repo clone](https://github.com/Karaca7/gnldev): `pnpm install && pnpm -r build`.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm i @gnldev/rag # peer: @gnldev/durable, ai, zod
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { InMemoryVectorStore, indexDocuments, createRagTool, llmReranker } from '@gnldev/rag';
|
|
15
|
+
|
|
16
|
+
const store = new InMemoryVectorStore();
|
|
17
|
+
await indexDocuments(store, embed, [{ id: 'p1', text: 'Return policy: 30 days…' }]);
|
|
18
|
+
|
|
19
|
+
const searchPolicy = createRagTool({
|
|
20
|
+
store, embed, topK: 3,
|
|
21
|
+
rerank: llmReranker({ model }), rerankTopK: 2, // optional LLM reranker
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
await runDurable({ runId: 'r1', journal, model, tools: { searchPolicy }, prompt: '…' });
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## API
|
|
28
|
+
- `InMemoryVectorStore` · `indexDocuments(store, embed, docs)` · `VectorStore` interface (plug in your own
|
|
29
|
+
backend)
|
|
30
|
+
- `createRagTool({ store, embed, topK?, rerank?, rerankTopK?, description? })` → AI SDK tool
|
|
31
|
+
- `llmReranker({ model })` → `Reranker`
|
|
32
|
+
- `SemanticMemory` — vector-based recall (memory integration)
|
|
33
|
+
|
|
34
|
+
## How it works
|
|
35
|
+
Since RAG is a tool, it naturally fits into the durable agent loop: retrieval + rerank are journaled once
|
|
36
|
+
and replayed rather than repeated. For cross-run reuse, it can be combined with `@gnldev/cache`.
|
|
37
|
+
|
|
38
|
+
## License
|
|
39
|
+
|
|
40
|
+
Apache-2.0 — see [LICENSE](./LICENSE).
|
package/dist/chunk.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { VectorDoc } from './vector-store.js';
|
|
2
|
+
export interface ChunkOptions {
|
|
3
|
+
/** Target chunk size (characters). Default 1200. */
|
|
4
|
+
size?: number;
|
|
5
|
+
/** Overlap between consecutive chunks (characters, must be smaller than size). Default 120. */
|
|
6
|
+
overlap?: number;
|
|
7
|
+
strategy?: 'recursive' | 'markdown' | 'character';
|
|
8
|
+
}
|
|
9
|
+
/** Chunk + (in markdown) heading trail. */
|
|
10
|
+
export interface Chunk {
|
|
11
|
+
text: string;
|
|
12
|
+
/** heading breadcrumb of the section in the markdown strategy (e.g. "Setup > Docker"). */
|
|
13
|
+
heading?: string;
|
|
14
|
+
}
|
|
15
|
+
/** Split raw text into chunks (strategy + size + overlap). */
|
|
16
|
+
export declare function chunkText(text: string, opts?: ChunkOptions): Chunk[];
|
|
17
|
+
/**
|
|
18
|
+
* Split documents → VectorDoc list ready for `indexDocuments`. Chunk id is `<docId>#<i>`
|
|
19
|
+
* (deterministic → re-indexing upserts to the same ids, no duplicate records); metadata
|
|
20
|
+
* is inherited + a `{ source, chunk }` trail is added (and a `heading` breadcrumb in markdown).
|
|
21
|
+
*/
|
|
22
|
+
export declare function chunkDocuments(docs: VectorDoc[], opts?: ChunkOptions): VectorDoc[];
|
package/dist/chunk.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
const DEFAULT_SIZE = 1200;
|
|
2
|
+
const DEFAULT_OVERLAP = 120;
|
|
3
|
+
function resolveOpts(opts) {
|
|
4
|
+
const size = opts?.size ?? DEFAULT_SIZE;
|
|
5
|
+
const overlap = opts?.overlap ?? Math.min(DEFAULT_OVERLAP, Math.floor(size / 4));
|
|
6
|
+
if (size < 1)
|
|
7
|
+
throw new Error('@gnldev/rag chunk: size must be >= 1');
|
|
8
|
+
if (overlap < 0 || overlap >= size)
|
|
9
|
+
throw new Error('@gnldev/rag chunk: 0 <= overlap < size must hold');
|
|
10
|
+
return { size, overlap, strategy: opts?.strategy ?? 'recursive' };
|
|
11
|
+
}
|
|
12
|
+
/** Separator priority list: paragraph → line → sentence → word. Last resort: hard cut. */
|
|
13
|
+
const SEPARATORS = ['\n\n', '\n', '. ', ' '];
|
|
14
|
+
/** GREEDILY merges pieces up to the target size (preserving the separator); a piece that alone stays over size passes through as-is. */
|
|
15
|
+
function mergeGreedy(pieces, sep, size) {
|
|
16
|
+
const out = [];
|
|
17
|
+
let cur = '';
|
|
18
|
+
for (const p of pieces) {
|
|
19
|
+
const joined = cur === '' ? p : cur + sep + p;
|
|
20
|
+
if (joined.length <= size || cur === '')
|
|
21
|
+
cur = joined;
|
|
22
|
+
else {
|
|
23
|
+
out.push(cur);
|
|
24
|
+
cur = p;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (cur !== '')
|
|
28
|
+
out.push(cur);
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
/** Recursive split: start from the coarsest separator; any unit exceeding size is re-split with the next separator. */
|
|
32
|
+
function splitRecursive(text, size, sepIdx = 0) {
|
|
33
|
+
if (text.length <= size)
|
|
34
|
+
return text.trim() === '' ? [] : [text];
|
|
35
|
+
if (sepIdx >= SEPARATORS.length) {
|
|
36
|
+
const out = []; // no natural boundary left → hard cut
|
|
37
|
+
for (let i = 0; i < text.length; i += size)
|
|
38
|
+
out.push(text.slice(i, i + size));
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
const sep = SEPARATORS[sepIdx];
|
|
42
|
+
const pieces = text.split(sep).filter((p) => p.trim() !== '');
|
|
43
|
+
if (pieces.length <= 1)
|
|
44
|
+
return splitRecursive(text, size, sepIdx + 1);
|
|
45
|
+
const merged = mergeGreedy(pieces, sep, size);
|
|
46
|
+
return merged.flatMap((m) => (m.length <= size ? [m] : splitRecursive(m, size, sepIdx + 1)));
|
|
47
|
+
}
|
|
48
|
+
/** Apply overlap to consecutive chunks: the tail of the previous chunk is prepended to each one (context continuity). */
|
|
49
|
+
function applyOverlap(chunks, overlap) {
|
|
50
|
+
if (overlap === 0 || chunks.length <= 1)
|
|
51
|
+
return chunks;
|
|
52
|
+
return chunks.map((c, i) => (i === 0 ? c : chunks[i - 1].slice(-overlap) + c));
|
|
53
|
+
}
|
|
54
|
+
/** Section the markdown by heading hierarchy: each section = breadcrumb + body. */
|
|
55
|
+
function splitMarkdownSections(text) {
|
|
56
|
+
const lines = text.split('\n');
|
|
57
|
+
const sections = [];
|
|
58
|
+
const crumbs = [];
|
|
59
|
+
let buf = [];
|
|
60
|
+
const flush = () => {
|
|
61
|
+
const body = buf.join('\n');
|
|
62
|
+
if (body.trim() !== '') {
|
|
63
|
+
const heading = crumbs.map((c) => c.title).join(' > ') || undefined;
|
|
64
|
+
sections.push({ heading, body });
|
|
65
|
+
}
|
|
66
|
+
buf = [];
|
|
67
|
+
};
|
|
68
|
+
for (const line of lines) {
|
|
69
|
+
const m = /^(#{1,6})\s+(.+)$/.exec(line);
|
|
70
|
+
if (m) {
|
|
71
|
+
flush();
|
|
72
|
+
const level = m[1].length;
|
|
73
|
+
while (crumbs.length && crumbs[crumbs.length - 1].level >= level)
|
|
74
|
+
crumbs.pop();
|
|
75
|
+
crumbs.push({ level, title: m[2].trim() });
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
buf.push(line);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
flush();
|
|
82
|
+
return sections;
|
|
83
|
+
}
|
|
84
|
+
/** Split raw text into chunks (strategy + size + overlap). */
|
|
85
|
+
export function chunkText(text, opts) {
|
|
86
|
+
const { size, overlap, strategy } = resolveOpts(opts);
|
|
87
|
+
if (text.trim() === '')
|
|
88
|
+
return [];
|
|
89
|
+
if (strategy === 'character') {
|
|
90
|
+
const out = [];
|
|
91
|
+
const stride = size - overlap;
|
|
92
|
+
for (let i = 0; i < text.length; i += stride) {
|
|
93
|
+
out.push(text.slice(i, i + size));
|
|
94
|
+
if (i + size >= text.length)
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
return out.map((t) => ({ text: t }));
|
|
98
|
+
}
|
|
99
|
+
if (strategy === 'markdown') {
|
|
100
|
+
return splitMarkdownSections(text).flatMap(({ heading, body }) => applyOverlap(splitRecursive(body.trim(), size), overlap).map((t) => ({ text: t, ...(heading ? { heading } : {}) })));
|
|
101
|
+
}
|
|
102
|
+
return applyOverlap(splitRecursive(text, size), overlap).map((t) => ({ text: t }));
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Split documents → VectorDoc list ready for `indexDocuments`. Chunk id is `<docId>#<i>`
|
|
106
|
+
* (deterministic → re-indexing upserts to the same ids, no duplicate records); metadata
|
|
107
|
+
* is inherited + a `{ source, chunk }` trail is added (and a `heading` breadcrumb in markdown).
|
|
108
|
+
*/
|
|
109
|
+
export function chunkDocuments(docs, opts) {
|
|
110
|
+
const out = [];
|
|
111
|
+
for (const doc of docs) {
|
|
112
|
+
const chunks = chunkText(doc.text, opts);
|
|
113
|
+
if (chunks.length <= 1) {
|
|
114
|
+
out.push(doc); // not split → original id/metadata as-is (no pointless #0 derivation)
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
chunks.forEach((c, i) => {
|
|
118
|
+
out.push({
|
|
119
|
+
id: `${doc.id}#${i}`,
|
|
120
|
+
text: c.text,
|
|
121
|
+
metadata: { ...doc.metadata, source: doc.id, chunk: i, ...(c.heading ? { heading: c.heading } : {}) },
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
//# sourceMappingURL=chunk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chunk.js","sourceRoot":"","sources":["../src/chunk.ts"],"names":[],"mappings":"AA0BA,MAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,MAAM,eAAe,GAAG,GAAG,CAAC;AAE5B,SAAS,WAAW,CAAC,IAAmB;IACtC,MAAM,IAAI,GAAG,IAAI,EAAE,IAAI,IAAI,YAAY,CAAC;IACxC,MAAM,OAAO,GAAG,IAAI,EAAE,OAAO,IAAI,IAAI,CAAC,GA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E,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE;aACtG,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["// Chunking helpers — the common `document.chunk()` shape (code-first, class-free).\n// `chunkText` splits raw text into chunks; `chunkDocuments` splits VectorDocs and produces a new\n// VectorDoc list ready for `indexDocuments` (id: `<source>#<i>`, metadata inherited + source trail).\n// Strategies:\n// 'recursive' (default): splits preferring paragraph → line → sentence → word boundaries\n// (the general-purpose strategy with the highest semantic coherence).\n// 'markdown': splits by heading hierarchy; adds a `heading` breadcrumb metadata to each chunk\n// (for context display during retrieval), large text within a section is split recursively.\n// 'character': fixed window (fastest; when boundary quality doesn't matter).\nimport type { VectorDoc } from './vector-store.js';\n\nexport interface ChunkOptions {\n /** Target chunk size (characters). Default 1200. */\n size?: number;\n /** Overlap between consecutive chunks (characters, must be smaller than size). Default 120. */\n overlap?: number;\n strategy?: 'recursive' | 'markdown' | 'character';\n}\n\n/** Chunk + (in markdown) heading trail. */\nexport interface Chunk {\n text: string;\n /** heading breadcrumb of the section in the markdown strategy (e.g. \"Setup > Docker\"). */\n heading?: string;\n}\n\nconst DEFAULT_SIZE = 1200;\nconst DEFAULT_OVERLAP = 120;\n\nfunction resolveOpts(opts?: ChunkOptions): { size: number; overlap: number; strategy: NonNullable<ChunkOptions['strategy']> } {\n const size = opts?.size ?? DEFAULT_SIZE;\n const overlap = opts?.overlap ?? Math.min(DEFAULT_OVERLAP, Math.floor(size / 4));\n if (size < 1) throw new Error('@gnldev/rag chunk: size must be >= 1');\n if (overlap < 0 || overlap >= size) throw new Error('@gnldev/rag chunk: 0 <= overlap < size must hold');\n return { size, overlap, strategy: opts?.strategy ?? 'recursive' };\n}\n\n/** Separator priority list: paragraph → line → sentence → word. Last resort: hard cut. */\nconst SEPARATORS = ['\\n\\n', '\\n', '. ', ' '];\n\n/** GREEDILY merges pieces up to the target size (preserving the separator); a piece that alone stays over size passes through as-is. */\nfunction mergeGreedy(pieces: string[], sep: string, size: number): string[] {\n const out: string[] = [];\n let cur = '';\n for (const p of pieces) {\n const joined = cur === '' ? p : cur + sep + p;\n if (joined.length <= size || cur === '') cur = joined;\n else {\n out.push(cur);\n cur = p;\n }\n }\n if (cur !== '') out.push(cur);\n return out;\n}\n\n/** Recursive split: start from the coarsest separator; any unit exceeding size is re-split with the next separator. */\nfunction splitRecursive(text: string, size: number, sepIdx = 0): string[] {\n if (text.length <= size) return text.trim() === '' ? [] : [text];\n if (sepIdx >= SEPARATORS.length) {\n const out: string[] = []; // no natural boundary left → hard cut\n for (let i = 0; i < text.length; i += size) out.push(text.slice(i, i + size));\n return out;\n }\n const sep = SEPARATORS[sepIdx]!;\n const pieces = text.split(sep).filter((p) => p.trim() !== '');\n if (pieces.length <= 1) return splitRecursive(text, size, sepIdx + 1);\n const merged = mergeGreedy(pieces, sep, size);\n return merged.flatMap((m) => (m.length <= size ? [m] : splitRecursive(m, size, sepIdx + 1)));\n}\n\n/** Apply overlap to consecutive chunks: the tail of the previous chunk is prepended to each one (context continuity). */\nfunction applyOverlap(chunks: string[], overlap: number): string[] {\n if (overlap === 0 || chunks.length <= 1) return chunks;\n return chunks.map((c, i) => (i === 0 ? c : chunks[i - 1]!.slice(-overlap) + c));\n}\n\n/** Section the markdown by heading hierarchy: each section = breadcrumb + body. */\nfunction splitMarkdownSections(text: string): { heading?: string; body: string }[] {\n const lines = text.split('\\n');\n const sections: { heading?: string; body: string }[] = [];\n const crumbs: { level: number; title: string }[] = [];\n let buf: string[] = [];\n const flush = () => {\n const body = buf.join('\\n');\n if (body.trim() !== '') {\n const heading = crumbs.map((c) => c.title).join(' > ') || undefined;\n sections.push({ heading, body });\n }\n buf = [];\n };\n for (const line of lines) {\n const m = /^(#{1,6})\\s+(.+)$/.exec(line);\n if (m) {\n flush();\n const level = m[1]!.length;\n while (crumbs.length && crumbs[crumbs.length - 1]!.level >= level) crumbs.pop();\n crumbs.push({ level, title: m[2]!.trim() });\n } else {\n buf.push(line);\n }\n }\n flush();\n return sections;\n}\n\n/** Split raw text into chunks (strategy + size + overlap). */\nexport function chunkText(text: string, opts?: ChunkOptions): Chunk[] {\n const { size, overlap, strategy } = resolveOpts(opts);\n if (text.trim() === '') return [];\n if (strategy === 'character') {\n const out: string[] = [];\n const stride = size - overlap;\n for (let i = 0; i < text.length; i += stride) {\n out.push(text.slice(i, i + size));\n if (i + size >= text.length) break;\n }\n return out.map((t) => ({ text: t }));\n }\n if (strategy === 'markdown') {\n return splitMarkdownSections(text).flatMap(({ heading, body }) =>\n applyOverlap(splitRecursive(body.trim(), size), overlap).map((t) => ({ text: t, ...(heading ? { heading } : {}) })),\n );\n }\n return applyOverlap(splitRecursive(text, size), overlap).map((t) => ({ text: t }));\n}\n\n/**\n * Split documents → VectorDoc list ready for `indexDocuments`. Chunk id is `<docId>#<i>`\n * (deterministic → re-indexing upserts to the same ids, no duplicate records); metadata\n * is inherited + a `{ source, chunk }` trail is added (and a `heading` breadcrumb in markdown).\n */\nexport function chunkDocuments(docs: VectorDoc[], opts?: ChunkOptions): VectorDoc[] {\n const out: VectorDoc[] = [];\n for (const doc of docs) {\n const chunks = chunkText(doc.text, opts);\n if (chunks.length <= 1) {\n out.push(doc); // not split → original id/metadata as-is (no pointless #0 derivation)\n continue;\n }\n chunks.forEach((c, i) => {\n out.push({\n id: `${doc.id}#${i}`,\n text: c.text,\n metadata: { ...doc.metadata, source: doc.id, chunk: i, ...(c.heading ? { heading: c.heading } : {}) },\n });\n });\n }\n return out;\n}\n"]}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { VectorStore, VectorItem, VectorMatch, QueryOptions } from './vector-store.js';
|
|
2
|
+
export interface GraphRagOptions {
|
|
3
|
+
/** Edge threshold: two chunks become neighbors in the graph if their cosine similarity exceeds this. Default 0.75. */
|
|
4
|
+
threshold?: number;
|
|
5
|
+
/** Neighbor expansion depth (hops). 0 = plain vector search. Default 1. */
|
|
6
|
+
hops?: number;
|
|
7
|
+
/** Score decay factor per hop: neighbor's score = source's score × decay × edge weight. Default 0.7. */
|
|
8
|
+
decay?: number;
|
|
9
|
+
/** Number of direct results seeding the expansion (independent of query topK). Default 4. */
|
|
10
|
+
seeds?: number;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* VectorStore that traverses a similarity graph. Edges are built incrementally on upsert (a new
|
|
14
|
+
* item is compared against all existing ones — O(n) / item). Query: the best `seeds` direct results
|
|
15
|
+
* are taken, each seed's neighbors join with a `decay`-attenuated score (for `hops` rounds), the
|
|
16
|
+
* combined list is sorted by score and `topK` is returned. If a node is reached via multiple paths,
|
|
17
|
+
* the HIGHEST score is kept.
|
|
18
|
+
*/
|
|
19
|
+
export declare class GraphRag implements VectorStore {
|
|
20
|
+
private items;
|
|
21
|
+
private byId;
|
|
22
|
+
private edges;
|
|
23
|
+
private readonly threshold;
|
|
24
|
+
private readonly hops;
|
|
25
|
+
private readonly decay;
|
|
26
|
+
private readonly seeds;
|
|
27
|
+
constructor(opts?: GraphRagOptions);
|
|
28
|
+
upsert(newItems: VectorItem[]): Promise<void>;
|
|
29
|
+
private rebuildEdgesFor;
|
|
30
|
+
/**
|
|
31
|
+
* `opts` was missing from this signature, and TypeScript accepted the class as a `VectorStore`
|
|
32
|
+
* anyway: a function of fewer parameters is assignable to a type that declares more. So the one
|
|
33
|
+
* mechanism this module has for keeping two data sets apart was silently absent from one of its
|
|
34
|
+
* three implementations, and nothing — not `tsc`, not the tests, not a review — said so.
|
|
35
|
+
*
|
|
36
|
+
* Measured before this fix, two namespaces with one document each:
|
|
37
|
+
* query(q, 5, { namespace: 'org:acme' }) -> acme-1, globex-1
|
|
38
|
+
* query(q, 5, { namespace: 'does-not-exist' }) -> 2 rows
|
|
39
|
+
*/
|
|
40
|
+
query(embedding: number[], topK: number, opts?: QueryOptions): Promise<VectorMatch[]>;
|
|
41
|
+
/** Observability/test: graph statistics (node/edge count). */
|
|
42
|
+
stats(): {
|
|
43
|
+
nodes: number;
|
|
44
|
+
edges: number;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// GraphRAG — retrieval over a similarity GRAPH between chunks (the common "graph RAG" pattern).
|
|
2
|
+
// Catches what plain vector search misses: chunks that don't directly resemble the query but are
|
|
3
|
+
// STRONGLY connected to chunks that do resemble the query (indirect relevance) join the results.
|
|
4
|
+
//
|
|
5
|
+
// Design: implements the `VectorStore` interface → DROP-IN for `createRagTool`/`indexDocuments`.
|
|
6
|
+
// The graph is in-memory and built from upserted chunks (the common graph-RAG approach also works in-memory
|
|
7
|
+
// over chunks); for a persistent corpus, keeping chunks in a persistent store and rebuilding
|
|
8
|
+
// GraphRAG as a query-time layer is the user's pattern. Since it runs durable inside `createRagTool`,
|
|
9
|
+
// the query RESULT is journaled → the graph isn't retraversed on resume/replay (exactly-once RAG preserved).
|
|
10
|
+
import { cosineSimilarity } from 'ai';
|
|
11
|
+
import { matchesFilter } from './vector-store.js';
|
|
12
|
+
/**
|
|
13
|
+
* VectorStore that traverses a similarity graph. Edges are built incrementally on upsert (a new
|
|
14
|
+
* item is compared against all existing ones — O(n) / item). Query: the best `seeds` direct results
|
|
15
|
+
* are taken, each seed's neighbors join with a `decay`-attenuated score (for `hops` rounds), the
|
|
16
|
+
* combined list is sorted by score and `topK` is returned. If a node is reached via multiple paths,
|
|
17
|
+
* the HIGHEST score is kept.
|
|
18
|
+
*/
|
|
19
|
+
export class GraphRag {
|
|
20
|
+
items = [];
|
|
21
|
+
byId = new Map(); // id → items index
|
|
22
|
+
edges = new Map(); // id → neighbors (edge weight = similarity)
|
|
23
|
+
threshold;
|
|
24
|
+
hops;
|
|
25
|
+
decay;
|
|
26
|
+
seeds;
|
|
27
|
+
constructor(opts = {}) {
|
|
28
|
+
this.threshold = opts.threshold ?? 0.75;
|
|
29
|
+
this.hops = opts.hops ?? 1;
|
|
30
|
+
this.decay = opts.decay ?? 0.7;
|
|
31
|
+
this.seeds = opts.seeds ?? 4;
|
|
32
|
+
if (this.threshold < -1 || this.threshold > 1)
|
|
33
|
+
throw new Error('@gnldev/rag GraphRag: threshold must be in the range [-1,1]');
|
|
34
|
+
if (this.decay <= 0 || this.decay > 1)
|
|
35
|
+
throw new Error('@gnldev/rag GraphRag: 0 < decay <= 1 must hold');
|
|
36
|
+
}
|
|
37
|
+
async upsert(newItems) {
|
|
38
|
+
for (const it of newItems) {
|
|
39
|
+
const existing = this.byId.get(it.id);
|
|
40
|
+
if (existing !== undefined) {
|
|
41
|
+
this.items[existing] = it;
|
|
42
|
+
this.rebuildEdgesFor(it.id); // embedding may have changed → refresh edges
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
this.byId.set(it.id, this.items.length);
|
|
46
|
+
this.items.push(it);
|
|
47
|
+
this.edges.set(it.id, []);
|
|
48
|
+
// Incremental edge building: the new item is scored once against everyone existing IN ITS OWN
|
|
49
|
+
// namespace. Filtering at query time is not enough here and that is what makes this store
|
|
50
|
+
// different from the others: an edge is a permanent structure, so a graph built across two
|
|
51
|
+
// namespaces lets a walk enter one organization's document from another's and carry its score back.
|
|
52
|
+
// Measured before this: two namespaces, one document each -> `{"nodes":2,"edges":1}`.
|
|
53
|
+
for (const other of this.items) {
|
|
54
|
+
if (other.id === it.id)
|
|
55
|
+
continue;
|
|
56
|
+
if (other.namespace !== it.namespace)
|
|
57
|
+
continue;
|
|
58
|
+
const w = cosineSimilarity(it.embedding, other.embedding);
|
|
59
|
+
if (w >= this.threshold) {
|
|
60
|
+
this.edges.get(it.id).push({ id: other.id, w });
|
|
61
|
+
this.edges.get(other.id).push({ id: it.id, w });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
rebuildEdgesFor(id) {
|
|
67
|
+
// Strip the old edges from both directions and recompute (upsert-update path; rare).
|
|
68
|
+
for (const [k, list] of this.edges) {
|
|
69
|
+
if (k === id)
|
|
70
|
+
continue;
|
|
71
|
+
this.edges.set(k, list.filter((e) => e.id !== id));
|
|
72
|
+
}
|
|
73
|
+
const it = this.items[this.byId.get(id)];
|
|
74
|
+
const mine = [];
|
|
75
|
+
for (const other of this.items) {
|
|
76
|
+
if (other.id === id)
|
|
77
|
+
continue;
|
|
78
|
+
if (other.namespace !== it.namespace)
|
|
79
|
+
continue; // same rule as upsert — see the note there
|
|
80
|
+
const w = cosineSimilarity(it.embedding, other.embedding);
|
|
81
|
+
if (w >= this.threshold) {
|
|
82
|
+
mine.push({ id: other.id, w });
|
|
83
|
+
this.edges.get(other.id).push({ id, w });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
this.edges.set(id, mine);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* `opts` was missing from this signature, and TypeScript accepted the class as a `VectorStore`
|
|
90
|
+
* anyway: a function of fewer parameters is assignable to a type that declares more. So the one
|
|
91
|
+
* mechanism this module has for keeping two data sets apart was silently absent from one of its
|
|
92
|
+
* three implementations, and nothing — not `tsc`, not the tests, not a review — said so.
|
|
93
|
+
*
|
|
94
|
+
* Measured before this fix, two namespaces with one document each:
|
|
95
|
+
* query(q, 5, { namespace: 'org:acme' }) -> acme-1, globex-1
|
|
96
|
+
* query(q, 5, { namespace: 'does-not-exist' }) -> 2 rows
|
|
97
|
+
*/
|
|
98
|
+
async query(embedding, topK, opts) {
|
|
99
|
+
if (this.items.length === 0)
|
|
100
|
+
return [];
|
|
101
|
+
// Narrow FIRST, then score. Scoring an item this caller may not see and discarding it later would
|
|
102
|
+
// still let it seed the graph walk below and lend its score to a neighbour.
|
|
103
|
+
const visible = this.items.filter((it) => (opts?.namespace === undefined || it.namespace === opts.namespace)
|
|
104
|
+
&& matchesFilter(it.metadata, opts?.filter));
|
|
105
|
+
if (visible.length === 0)
|
|
106
|
+
return [];
|
|
107
|
+
const allowed = new Set(visible.map((it) => it.id));
|
|
108
|
+
// 1) Direct similarity: everyone visible is scored (in-memory corpus; same cost as InMemoryVectorStore).
|
|
109
|
+
const direct = visible
|
|
110
|
+
.map((it) => ({ id: it.id, score: cosineSimilarity(embedding, it.embedding) }))
|
|
111
|
+
.sort((a, b) => b.score - a.score);
|
|
112
|
+
// 2) Graph expansion: walk from the best `seeds` seeds to their neighbors; score = source × decay × edge.
|
|
113
|
+
const best = new Map(direct.map((d) => [d.id, d.score])); // id → best known score
|
|
114
|
+
let frontier = direct.slice(0, this.seeds).map((d) => ({ id: d.id, score: d.score }));
|
|
115
|
+
for (let hop = 0; hop < this.hops; hop++) {
|
|
116
|
+
const next = [];
|
|
117
|
+
for (const node of frontier) {
|
|
118
|
+
for (const e of this.edges.get(node.id) ?? []) {
|
|
119
|
+
// Belt and braces: edges are built within a namespace, so this cannot fire today. It stays
|
|
120
|
+
// because a corpus upserted before that rule existed still carries cross-namespace edges,
|
|
121
|
+
// and a walk over stale edges is indistinguishable from a walk over correct ones.
|
|
122
|
+
if (!allowed.has(e.id))
|
|
123
|
+
continue;
|
|
124
|
+
const s = node.score * this.decay * e.w;
|
|
125
|
+
if (s > (best.get(e.id) ?? -Infinity)) {
|
|
126
|
+
best.set(e.id, s);
|
|
127
|
+
next.push({ id: e.id, score: s });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
frontier = next;
|
|
132
|
+
if (frontier.length === 0)
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
// 3) Combined ranking → topK.
|
|
136
|
+
return [...best.entries()]
|
|
137
|
+
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)) // deterministic tie-break by id on equal score
|
|
138
|
+
.slice(0, topK)
|
|
139
|
+
.map(([id, score]) => {
|
|
140
|
+
const it = this.items[this.byId.get(id)];
|
|
141
|
+
return { id, text: it.text, metadata: it.metadata, score };
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
/** Observability/test: graph statistics (node/edge count). */
|
|
145
|
+
stats() {
|
|
146
|
+
let e = 0;
|
|
147
|
+
for (const list of this.edges.values())
|
|
148
|
+
e += list.length;
|
|
149
|
+
return { nodes: this.items.length, edges: e / 2 }; // stored bidirectionally
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
//# sourceMappingURL=graph-rag.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph-rag.js","sourceRoot":"","sources":["../src/graph-rag.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,iGAAiG;AACjG,iGAAiG;AACjG,EAAE;AACF,iGAAiG;AACjG,4GAA4G;AAC5G,6FAA6F;AAC7F,sGAAsG;AACtG,6GAA6G;AAC7G,OAAO,EAAE,gBAAgB,EAAE,MAAM,IAAI,CAAC;AACtC,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAclD;;;;;;GAMG;AACH,MAAM,OAAO,QAAQ;IACX,KAAK,GAAiB,EAAE,CAAC;IACzB,IAAI,GAAG,IAAI,GAAG,EAAkB,CAAC,CAAC,mBAAmB;IACrD,KAAK,GAAG,IAAI,GAAG,EAAuC,CAAC,CAAC,4CAA4C;IAC3F,SAAS,CAAS;IAClB,IAAI,CAAS;IACb,KAAK,CAAS;IACd,KAAK,CAAS;IAE/B,YAAY,OAAwB,EAAE;QACpC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC;QACxC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC;QAC3B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,GAAG,CAAC;QAC/B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,CAAC,CAAC;QAC7B,IAAI,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,SAAS,GAAG,CAAC;YAAE,MAAM,IAAI,KA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ourcesContent":["// GraphRAG — retrieval over a similarity GRAPH between chunks (the common \"graph RAG\" pattern).\n// Catches what plain vector search misses: chunks that don't directly resemble the query but are\n// STRONGLY connected to chunks that do resemble the query (indirect relevance) join the results.\n//\n// Design: implements the `VectorStore` interface → DROP-IN for `createRagTool`/`indexDocuments`.\n// The graph is in-memory and built from upserted chunks (the common graph-RAG approach also works in-memory\n// over chunks); for a persistent corpus, keeping chunks in a persistent store and rebuilding\n// GraphRAG as a query-time layer is the user's pattern. Since it runs durable inside `createRagTool`,\n// the query RESULT is journaled → the graph isn't retraversed on resume/replay (exactly-once RAG preserved).\nimport { cosineSimilarity } from 'ai';\nimport { matchesFilter } from './vector-store.js';\nimport type { VectorStore, VectorItem, VectorMatch, QueryOptions } from './vector-store.js';\n\nexport interface GraphRagOptions {\n /** Edge threshold: two chunks become neighbors in the graph if their cosine similarity exceeds this. Default 0.75. */\n threshold?: number;\n /** Neighbor expansion depth (hops). 0 = plain vector search. Default 1. */\n hops?: number;\n /** Score decay factor per hop: neighbor's score = source's score × decay × edge weight. Default 0.7. */\n decay?: number;\n /** Number of direct results seeding the expansion (independent of query topK). Default 4. */\n seeds?: number;\n}\n\n/**\n * VectorStore that traverses a similarity graph. Edges are built incrementally on upsert (a new\n * item is compared against all existing ones — O(n) / item). Query: the best `seeds` direct results\n * are taken, each seed's neighbors join with a `decay`-attenuated score (for `hops` rounds), the\n * combined list is sorted by score and `topK` is returned. If a node is reached via multiple paths,\n * the HIGHEST score is kept.\n */\nexport class GraphRag implements VectorStore {\n private items: VectorItem[] = [];\n private byId = new Map<string, number>(); // id → items index\n private edges = new Map<string, { id: string; w: number }[]>(); // id → neighbors (edge weight = similarity)\n private readonly threshold: number;\n private readonly hops: number;\n private readonly decay: number;\n private readonly seeds: number;\n\n constructor(opts: GraphRagOptions = {}) {\n this.threshold = opts.threshold ?? 0.75;\n this.hops = opts.hops ?? 1;\n this.decay = opts.decay ?? 0.7;\n this.seeds = opts.seeds ?? 4;\n if (this.threshold < -1 || this.threshold > 1) throw new Error('@gnldev/rag GraphRag: threshold must be in the range [-1,1]');\n if (this.decay <= 0 || this.decay > 1) throw new Error('@gnldev/rag GraphRag: 0 < decay <= 1 must hold');\n }\n\n async upsert(newItems: VectorItem[]): Promise<void> {\n for (const it of newItems) {\n const existing = this.byId.get(it.id);\n if (existing !== undefined) {\n this.items[existing] = it;\n this.rebuildEdgesFor(it.id); // embedding may have changed → refresh edges\n continue;\n }\n this.byId.set(it.id, this.items.length);\n this.items.push(it);\n this.edges.set(it.id, []);\n // Incremental edge building: the new item is scored once against everyone existing IN ITS OWN\n // namespace. Filtering at query time is not enough here and that is what makes this store\n // different from the others: an edge is a permanent structure, so a graph built across two\n // namespaces lets a walk enter one organization's document from another's and carry its score back.\n // Measured before this: two namespaces, one document each -> `{\"nodes\":2,\"edges\":1}`.\n for (const other of this.items) {\n if (other.id === it.id) continue;\n if (other.namespace !== it.namespace) continue;\n const w = cosineSimilarity(it.embedding, other.embedding);\n if (w >= this.threshold) {\n this.edges.get(it.id)!.push({ id: other.id, w });\n this.edges.get(other.id)!.push({ id: it.id, w });\n }\n }\n }\n }\n\n private rebuildEdgesFor(id: string): void {\n // Strip the old edges from both directions and recompute (upsert-update path; rare).\n for (const [k, list] of this.edges) {\n if (k === id) continue;\n this.edges.set(k, list.filter((e) => e.id !== id));\n }\n const it = this.items[this.byId.get(id)!]!;\n const mine: { id: string; w: number }[] = [];\n for (const other of this.items) {\n if (other.id === id) continue;\n if (other.namespace !== it.namespace) continue; // same rule as upsert — see the note there\n const w = cosineSimilarity(it.embedding, other.embedding);\n if (w >= this.threshold) {\n mine.push({ id: other.id, w });\n this.edges.get(other.id)!.push({ id, w });\n }\n }\n this.edges.set(id, mine);\n }\n\n /**\n * `opts` was missing from this signature, and TypeScript accepted the class as a `VectorStore`\n * anyway: a function of fewer parameters is assignable to a type that declares more. So the one\n * mechanism this module has for keeping two data sets apart was silently absent from one of its\n * three implementations, and nothing — not `tsc`, not the tests, not a review — said so.\n *\n * Measured before this fix, two namespaces with one document each:\n * query(q, 5, { namespace: 'org:acme' }) -> acme-1, globex-1\n * query(q, 5, { namespace: 'does-not-exist' }) -> 2 rows\n */\n async query(embedding: number[], topK: number, opts?: QueryOptions): Promise<VectorMatch[]> {\n if (this.items.length === 0) return [];\n // Narrow FIRST, then score. Scoring an item this caller may not see and discarding it later would\n // still let it seed the graph walk below and lend its score to a neighbour.\n const visible = this.items.filter((it) =>\n (opts?.namespace === undefined || it.namespace === opts.namespace)\n && matchesFilter(it.metadata, opts?.filter));\n if (visible.length === 0) return [];\n const allowed = new Set(visible.map((it) => it.id));\n\n // 1) Direct similarity: everyone visible is scored (in-memory corpus; same cost as InMemoryVectorStore).\n const direct = visible\n .map((it) => ({ id: it.id, score: cosineSimilarity(embedding, it.embedding) }))\n .sort((a, b) => b.score - a.score);\n\n // 2) Graph expansion: walk from the best `seeds` seeds to their neighbors; score = source × decay × edge.\n const best = new Map<string, number>(direct.map((d) => [d.id, d.score])); // id → best known score\n let frontier = direct.slice(0, this.seeds).map((d) => ({ id: d.id, score: d.score }));\n for (let hop = 0; hop < this.hops; hop++) {\n const next: { id: string; score: number }[] = [];\n for (const node of frontier) {\n for (const e of this.edges.get(node.id) ?? []) {\n // Belt and braces: edges are built within a namespace, so this cannot fire today. It stays\n // because a corpus upserted before that rule existed still carries cross-namespace edges,\n // and a walk over stale edges is indistinguishable from a walk over correct ones.\n if (!allowed.has(e.id)) continue;\n const s = node.score * this.decay * e.w;\n if (s > (best.get(e.id) ?? -Infinity)) {\n best.set(e.id, s);\n next.push({ id: e.id, score: s });\n }\n }\n }\n frontier = next;\n if (frontier.length === 0) break;\n }\n\n // 3) Combined ranking → topK.\n return [...best.entries()]\n .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)) // deterministic tie-break by id on equal score\n .slice(0, topK)\n .map(([id, score]) => {\n const it = this.items[this.byId.get(id)!]!;\n return { id, text: it.text, metadata: it.metadata, score };\n });\n }\n\n /** Observability/test: graph statistics (node/edge count). */\n stats(): { nodes: number; edges: number } {\n let e = 0;\n for (const list of this.edges.values()) e += list.length;\n return { nodes: this.items.length, edges: e / 2 }; // stored bidirectionally\n }\n}\n"]}
|