@guidekit/knowledge 1.0.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 +21 -0
- package/dist/index.cjs +668 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +121 -0
- package/dist/index.d.ts +121 -0
- package/dist/index.js +657 -0
- package/dist/index.js.map +1 -0
- package/package.json +33 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,657 @@
|
|
|
1
|
+
import { KnowledgeError, ErrorCodes } from '@guidekit/core';
|
|
2
|
+
|
|
3
|
+
// src/knowledge-store.ts
|
|
4
|
+
|
|
5
|
+
// src/chunker.ts
|
|
6
|
+
var HEADING_RE = /^#{1,6}\s+/;
|
|
7
|
+
function isHeadingLine(line) {
|
|
8
|
+
return HEADING_RE.test(line);
|
|
9
|
+
}
|
|
10
|
+
function extractHeading(line) {
|
|
11
|
+
return line.replace(HEADING_RE, "").trim();
|
|
12
|
+
}
|
|
13
|
+
function normalize(text) {
|
|
14
|
+
return text.replace(/\n{3,}/g, "\n\n").trim();
|
|
15
|
+
}
|
|
16
|
+
function makeChunk(doc, content, index, startOffset, headingContext) {
|
|
17
|
+
const trimmed = normalize(content);
|
|
18
|
+
if (trimmed.length === 0) return null;
|
|
19
|
+
return {
|
|
20
|
+
id: `${doc.id}:${index}`,
|
|
21
|
+
documentId: doc.id,
|
|
22
|
+
content: trimmed,
|
|
23
|
+
index,
|
|
24
|
+
startOffset,
|
|
25
|
+
endOffset: startOffset + content.length,
|
|
26
|
+
...headingContext !== void 0 ? { headingContext } : {}
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function chunkByHeading(doc) {
|
|
30
|
+
const lines = doc.content.split("\n");
|
|
31
|
+
const chunks = [];
|
|
32
|
+
let current = "";
|
|
33
|
+
let currentStart = 0;
|
|
34
|
+
let currentHeading;
|
|
35
|
+
let offset = 0;
|
|
36
|
+
let idx = 0;
|
|
37
|
+
for (let i = 0; i < lines.length; i++) {
|
|
38
|
+
const line = lines[i];
|
|
39
|
+
const lineWithNewline = i < lines.length - 1 ? line + "\n" : line;
|
|
40
|
+
if (isHeadingLine(line)) {
|
|
41
|
+
if (current.length > 0) {
|
|
42
|
+
const chunk = makeChunk(doc, current, idx, currentStart, currentHeading);
|
|
43
|
+
if (chunk) {
|
|
44
|
+
chunks.push(chunk);
|
|
45
|
+
idx++;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
currentHeading = extractHeading(line);
|
|
49
|
+
currentStart = offset;
|
|
50
|
+
current = lineWithNewline;
|
|
51
|
+
} else {
|
|
52
|
+
current += lineWithNewline;
|
|
53
|
+
}
|
|
54
|
+
offset += lineWithNewline.length;
|
|
55
|
+
}
|
|
56
|
+
if (current.length > 0) {
|
|
57
|
+
const chunk = makeChunk(doc, current, idx, currentStart, currentHeading);
|
|
58
|
+
if (chunk) chunks.push(chunk);
|
|
59
|
+
}
|
|
60
|
+
return chunks;
|
|
61
|
+
}
|
|
62
|
+
function chunkByParagraph(doc) {
|
|
63
|
+
const parts = doc.content.split("\n\n");
|
|
64
|
+
const chunks = [];
|
|
65
|
+
let offset = 0;
|
|
66
|
+
let idx = 0;
|
|
67
|
+
let lastHeading;
|
|
68
|
+
for (let i = 0; i < parts.length; i++) {
|
|
69
|
+
const part = parts[i];
|
|
70
|
+
const startOffset = offset;
|
|
71
|
+
offset += part.length + (i < parts.length - 1 ? 2 : 0);
|
|
72
|
+
const lines = part.split("\n");
|
|
73
|
+
for (const line of lines) {
|
|
74
|
+
if (isHeadingLine(line)) {
|
|
75
|
+
lastHeading = extractHeading(line);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const chunk = makeChunk(doc, part, idx, startOffset, lastHeading);
|
|
79
|
+
if (chunk) {
|
|
80
|
+
chunks.push(chunk);
|
|
81
|
+
idx++;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return chunks;
|
|
85
|
+
}
|
|
86
|
+
function chunkByFixed(doc, chunkSize, overlap) {
|
|
87
|
+
const content = doc.content;
|
|
88
|
+
const chunks = [];
|
|
89
|
+
let pos = 0;
|
|
90
|
+
let idx = 0;
|
|
91
|
+
while (pos < content.length) {
|
|
92
|
+
const end = Math.min(pos + chunkSize, content.length);
|
|
93
|
+
const slice = content.slice(pos, end);
|
|
94
|
+
let headingContext;
|
|
95
|
+
const lines = slice.split("\n");
|
|
96
|
+
for (const line of lines) {
|
|
97
|
+
if (isHeadingLine(line)) {
|
|
98
|
+
headingContext = extractHeading(line);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const chunk = makeChunk(doc, slice, idx, pos, headingContext);
|
|
102
|
+
if (chunk) {
|
|
103
|
+
chunks.push(chunk);
|
|
104
|
+
idx++;
|
|
105
|
+
}
|
|
106
|
+
const step = chunkSize - overlap;
|
|
107
|
+
pos += step > 0 ? step : chunkSize;
|
|
108
|
+
}
|
|
109
|
+
return chunks;
|
|
110
|
+
}
|
|
111
|
+
function chunkDocument(doc, options) {
|
|
112
|
+
const strategy = options?.strategy ?? "heading";
|
|
113
|
+
switch (strategy) {
|
|
114
|
+
case "heading":
|
|
115
|
+
return chunkByHeading(doc);
|
|
116
|
+
case "paragraph":
|
|
117
|
+
return chunkByParagraph(doc);
|
|
118
|
+
case "fixed":
|
|
119
|
+
return chunkByFixed(doc, options?.chunkSize ?? 512, options?.overlap ?? 64);
|
|
120
|
+
default:
|
|
121
|
+
return chunkByHeading(doc);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// src/tokenizer.ts
|
|
126
|
+
var STOPWORDS = /* @__PURE__ */ new Set([
|
|
127
|
+
"a",
|
|
128
|
+
"an",
|
|
129
|
+
"the",
|
|
130
|
+
"and",
|
|
131
|
+
"or",
|
|
132
|
+
"but",
|
|
133
|
+
"not",
|
|
134
|
+
"no",
|
|
135
|
+
"nor",
|
|
136
|
+
"so",
|
|
137
|
+
"yet",
|
|
138
|
+
"is",
|
|
139
|
+
"are",
|
|
140
|
+
"was",
|
|
141
|
+
"were",
|
|
142
|
+
"be",
|
|
143
|
+
"been",
|
|
144
|
+
"being",
|
|
145
|
+
"am",
|
|
146
|
+
"have",
|
|
147
|
+
"has",
|
|
148
|
+
"had",
|
|
149
|
+
"having",
|
|
150
|
+
"do",
|
|
151
|
+
"does",
|
|
152
|
+
"did",
|
|
153
|
+
"doing",
|
|
154
|
+
"will",
|
|
155
|
+
"would",
|
|
156
|
+
"could",
|
|
157
|
+
"should",
|
|
158
|
+
"shall",
|
|
159
|
+
"may",
|
|
160
|
+
"might",
|
|
161
|
+
"must",
|
|
162
|
+
"can",
|
|
163
|
+
"i",
|
|
164
|
+
"me",
|
|
165
|
+
"my",
|
|
166
|
+
"myself",
|
|
167
|
+
"we",
|
|
168
|
+
"our",
|
|
169
|
+
"ours",
|
|
170
|
+
"ourselves",
|
|
171
|
+
"you",
|
|
172
|
+
"your",
|
|
173
|
+
"yours",
|
|
174
|
+
"yourself",
|
|
175
|
+
"yourselves",
|
|
176
|
+
"he",
|
|
177
|
+
"him",
|
|
178
|
+
"his",
|
|
179
|
+
"himself",
|
|
180
|
+
"she",
|
|
181
|
+
"her",
|
|
182
|
+
"hers",
|
|
183
|
+
"herself",
|
|
184
|
+
"it",
|
|
185
|
+
"its",
|
|
186
|
+
"itself",
|
|
187
|
+
"they",
|
|
188
|
+
"them",
|
|
189
|
+
"their",
|
|
190
|
+
"theirs",
|
|
191
|
+
"themselves",
|
|
192
|
+
"what",
|
|
193
|
+
"which",
|
|
194
|
+
"who",
|
|
195
|
+
"whom",
|
|
196
|
+
"this",
|
|
197
|
+
"that",
|
|
198
|
+
"these",
|
|
199
|
+
"those",
|
|
200
|
+
"if",
|
|
201
|
+
"then",
|
|
202
|
+
"else",
|
|
203
|
+
"when",
|
|
204
|
+
"where",
|
|
205
|
+
"why",
|
|
206
|
+
"how",
|
|
207
|
+
"whether",
|
|
208
|
+
"in",
|
|
209
|
+
"on",
|
|
210
|
+
"at",
|
|
211
|
+
"to",
|
|
212
|
+
"for",
|
|
213
|
+
"from",
|
|
214
|
+
"by",
|
|
215
|
+
"with",
|
|
216
|
+
"about",
|
|
217
|
+
"against",
|
|
218
|
+
"between",
|
|
219
|
+
"through",
|
|
220
|
+
"during",
|
|
221
|
+
"before",
|
|
222
|
+
"after",
|
|
223
|
+
"above",
|
|
224
|
+
"below",
|
|
225
|
+
"up",
|
|
226
|
+
"down",
|
|
227
|
+
"out",
|
|
228
|
+
"off",
|
|
229
|
+
"over",
|
|
230
|
+
"under",
|
|
231
|
+
"again",
|
|
232
|
+
"further",
|
|
233
|
+
"of",
|
|
234
|
+
"into",
|
|
235
|
+
"as",
|
|
236
|
+
"until",
|
|
237
|
+
"while",
|
|
238
|
+
"among",
|
|
239
|
+
"within",
|
|
240
|
+
"without",
|
|
241
|
+
"than",
|
|
242
|
+
"too",
|
|
243
|
+
"very",
|
|
244
|
+
"just",
|
|
245
|
+
"also",
|
|
246
|
+
"now",
|
|
247
|
+
"here",
|
|
248
|
+
"there",
|
|
249
|
+
"all",
|
|
250
|
+
"any",
|
|
251
|
+
"both",
|
|
252
|
+
"each",
|
|
253
|
+
"few",
|
|
254
|
+
"more",
|
|
255
|
+
"most",
|
|
256
|
+
"other",
|
|
257
|
+
"some",
|
|
258
|
+
"such",
|
|
259
|
+
"only",
|
|
260
|
+
"own",
|
|
261
|
+
"same",
|
|
262
|
+
"much",
|
|
263
|
+
"many",
|
|
264
|
+
"enough",
|
|
265
|
+
"every",
|
|
266
|
+
"once",
|
|
267
|
+
"twice",
|
|
268
|
+
"already",
|
|
269
|
+
"always",
|
|
270
|
+
"never",
|
|
271
|
+
"often",
|
|
272
|
+
"still",
|
|
273
|
+
"because",
|
|
274
|
+
"since",
|
|
275
|
+
"although",
|
|
276
|
+
"though",
|
|
277
|
+
"however",
|
|
278
|
+
"therefore",
|
|
279
|
+
"either",
|
|
280
|
+
"neither",
|
|
281
|
+
"nor",
|
|
282
|
+
"rather",
|
|
283
|
+
"per",
|
|
284
|
+
"via",
|
|
285
|
+
"don",
|
|
286
|
+
"doesn",
|
|
287
|
+
"didn",
|
|
288
|
+
"won",
|
|
289
|
+
"wouldn",
|
|
290
|
+
"couldn",
|
|
291
|
+
"shouldn",
|
|
292
|
+
"isn",
|
|
293
|
+
"aren",
|
|
294
|
+
"wasn",
|
|
295
|
+
"weren",
|
|
296
|
+
"hasn",
|
|
297
|
+
"haven",
|
|
298
|
+
"hadn"
|
|
299
|
+
]);
|
|
300
|
+
function tokenize(text) {
|
|
301
|
+
return text.toLowerCase().split(/\W+/).filter(Boolean);
|
|
302
|
+
}
|
|
303
|
+
function removeStopwords(tokens) {
|
|
304
|
+
return tokens.filter((t) => !STOPWORDS.has(t));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// src/bm25.ts
|
|
308
|
+
var BM25Index = class {
|
|
309
|
+
k1;
|
|
310
|
+
b;
|
|
311
|
+
/** Inverted index: term -> (chunkId -> frequency) */
|
|
312
|
+
invertedIndex = /* @__PURE__ */ new Map();
|
|
313
|
+
/** Document length in tokens per chunk */
|
|
314
|
+
docLengths = /* @__PURE__ */ new Map();
|
|
315
|
+
/** Stored chunks */
|
|
316
|
+
chunks = /* @__PURE__ */ new Map();
|
|
317
|
+
/** Track which chunks belong to which document */
|
|
318
|
+
docToChunks = /* @__PURE__ */ new Map();
|
|
319
|
+
/** Running total of all document lengths for avgdl computation */
|
|
320
|
+
totalDocLength = 0;
|
|
321
|
+
constructor(options) {
|
|
322
|
+
this.k1 = options?.k1 ?? 1.2;
|
|
323
|
+
this.b = options?.b ?? 0.75;
|
|
324
|
+
}
|
|
325
|
+
/** Add chunks from a document to the index. */
|
|
326
|
+
addDocument(chunks) {
|
|
327
|
+
for (const chunk of chunks) {
|
|
328
|
+
if (this.chunks.has(chunk.id)) continue;
|
|
329
|
+
const tokens = removeStopwords(tokenize(chunk.content));
|
|
330
|
+
this.chunks.set(chunk.id, chunk);
|
|
331
|
+
this.docLengths.set(chunk.id, tokens.length);
|
|
332
|
+
this.totalDocLength += tokens.length;
|
|
333
|
+
let chunkSet = this.docToChunks.get(chunk.documentId);
|
|
334
|
+
if (!chunkSet) {
|
|
335
|
+
chunkSet = /* @__PURE__ */ new Set();
|
|
336
|
+
this.docToChunks.set(chunk.documentId, chunkSet);
|
|
337
|
+
}
|
|
338
|
+
chunkSet.add(chunk.id);
|
|
339
|
+
const freqs = /* @__PURE__ */ new Map();
|
|
340
|
+
for (const token of tokens) {
|
|
341
|
+
freqs.set(token, (freqs.get(token) ?? 0) + 1);
|
|
342
|
+
}
|
|
343
|
+
for (const [term, freq] of freqs) {
|
|
344
|
+
let postings = this.invertedIndex.get(term);
|
|
345
|
+
if (!postings) {
|
|
346
|
+
postings = /* @__PURE__ */ new Map();
|
|
347
|
+
this.invertedIndex.set(term, postings);
|
|
348
|
+
}
|
|
349
|
+
postings.set(chunk.id, freq);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
/** Remove all chunks belonging to a document. */
|
|
354
|
+
removeDocument(documentId) {
|
|
355
|
+
const chunkIds = this.docToChunks.get(documentId);
|
|
356
|
+
if (!chunkIds) return;
|
|
357
|
+
for (const chunkId of chunkIds) {
|
|
358
|
+
const docLen = this.docLengths.get(chunkId) ?? 0;
|
|
359
|
+
this.totalDocLength -= docLen;
|
|
360
|
+
this.docLengths.delete(chunkId);
|
|
361
|
+
this.chunks.delete(chunkId);
|
|
362
|
+
for (const [, postings] of this.invertedIndex) {
|
|
363
|
+
postings.delete(chunkId);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
this.docToChunks.delete(documentId);
|
|
367
|
+
}
|
|
368
|
+
/** Search the index. Returns chunks sorted by relevance (descending). */
|
|
369
|
+
search(query, topK = 10) {
|
|
370
|
+
const queryTerms = removeStopwords(tokenize(query));
|
|
371
|
+
if (queryTerms.length === 0 || this.size === 0) return [];
|
|
372
|
+
const N = this.size;
|
|
373
|
+
const avgdl = this.totalDocLength / N;
|
|
374
|
+
const scores = /* @__PURE__ */ new Map();
|
|
375
|
+
for (const term of queryTerms) {
|
|
376
|
+
const postings = this.invertedIndex.get(term);
|
|
377
|
+
if (!postings) continue;
|
|
378
|
+
const n = postings.size;
|
|
379
|
+
const idf = Math.log((N - n + 0.5) / (n + 0.5) + 1);
|
|
380
|
+
for (const [chunkId, freq] of postings) {
|
|
381
|
+
const dl = this.docLengths.get(chunkId) ?? 0;
|
|
382
|
+
const tf = freq * (this.k1 + 1) / (freq + this.k1 * (1 - this.b + this.b * (dl / avgdl)));
|
|
383
|
+
const prev = scores.get(chunkId) ?? 0;
|
|
384
|
+
scores.set(chunkId, prev + idf * tf);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const results = [];
|
|
388
|
+
for (const [chunkId, score] of scores) {
|
|
389
|
+
const chunk = this.chunks.get(chunkId);
|
|
390
|
+
results.push({ chunk, score });
|
|
391
|
+
}
|
|
392
|
+
results.sort((a, b) => b.score - a.score);
|
|
393
|
+
return results.slice(0, topK);
|
|
394
|
+
}
|
|
395
|
+
/** Number of chunks in the index. */
|
|
396
|
+
get size() {
|
|
397
|
+
return this.chunks.size;
|
|
398
|
+
}
|
|
399
|
+
/** Clear the entire index. */
|
|
400
|
+
clear() {
|
|
401
|
+
this.invertedIndex.clear();
|
|
402
|
+
this.docLengths.clear();
|
|
403
|
+
this.chunks.clear();
|
|
404
|
+
this.docToChunks.clear();
|
|
405
|
+
this.totalDocLength = 0;
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
// src/tfidf.ts
|
|
410
|
+
var TFIDFIndex = class {
|
|
411
|
+
/** Inverted index: term -> (chunkId -> frequency) */
|
|
412
|
+
invertedIndex = /* @__PURE__ */ new Map();
|
|
413
|
+
/** Stored chunks */
|
|
414
|
+
chunks = /* @__PURE__ */ new Map();
|
|
415
|
+
/** Track which chunks belong to which document */
|
|
416
|
+
docToChunks = /* @__PURE__ */ new Map();
|
|
417
|
+
/** Add chunks from a document to the index. */
|
|
418
|
+
addDocument(chunks) {
|
|
419
|
+
for (const chunk of chunks) {
|
|
420
|
+
if (this.chunks.has(chunk.id)) continue;
|
|
421
|
+
const tokens = removeStopwords(tokenize(chunk.content));
|
|
422
|
+
this.chunks.set(chunk.id, chunk);
|
|
423
|
+
let chunkSet = this.docToChunks.get(chunk.documentId);
|
|
424
|
+
if (!chunkSet) {
|
|
425
|
+
chunkSet = /* @__PURE__ */ new Set();
|
|
426
|
+
this.docToChunks.set(chunk.documentId, chunkSet);
|
|
427
|
+
}
|
|
428
|
+
chunkSet.add(chunk.id);
|
|
429
|
+
const freqs = /* @__PURE__ */ new Map();
|
|
430
|
+
for (const token of tokens) {
|
|
431
|
+
freqs.set(token, (freqs.get(token) ?? 0) + 1);
|
|
432
|
+
}
|
|
433
|
+
for (const [term, freq] of freqs) {
|
|
434
|
+
let postings = this.invertedIndex.get(term);
|
|
435
|
+
if (!postings) {
|
|
436
|
+
postings = /* @__PURE__ */ new Map();
|
|
437
|
+
this.invertedIndex.set(term, postings);
|
|
438
|
+
}
|
|
439
|
+
postings.set(chunk.id, freq);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
/** Remove all chunks belonging to a document. */
|
|
444
|
+
removeDocument(documentId) {
|
|
445
|
+
const chunkIds = this.docToChunks.get(documentId);
|
|
446
|
+
if (!chunkIds) return;
|
|
447
|
+
for (const chunkId of chunkIds) {
|
|
448
|
+
this.chunks.delete(chunkId);
|
|
449
|
+
for (const [, postings] of this.invertedIndex) {
|
|
450
|
+
postings.delete(chunkId);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
this.docToChunks.delete(documentId);
|
|
454
|
+
}
|
|
455
|
+
/** Search the index. Returns chunks sorted by relevance (descending). */
|
|
456
|
+
search(query, topK = 10) {
|
|
457
|
+
const queryTerms = removeStopwords(tokenize(query));
|
|
458
|
+
if (queryTerms.length === 0 || this.size === 0) return [];
|
|
459
|
+
const N = this.size;
|
|
460
|
+
const scores = /* @__PURE__ */ new Map();
|
|
461
|
+
for (const term of queryTerms) {
|
|
462
|
+
const postings = this.invertedIndex.get(term);
|
|
463
|
+
if (!postings) continue;
|
|
464
|
+
const df = postings.size;
|
|
465
|
+
const idf = Math.log(N / df);
|
|
466
|
+
for (const [chunkId, freq] of postings) {
|
|
467
|
+
const tf = 1 + Math.log(freq);
|
|
468
|
+
const prev = scores.get(chunkId) ?? 0;
|
|
469
|
+
scores.set(chunkId, prev + tf * idf);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
const results = [];
|
|
473
|
+
for (const [chunkId, score] of scores) {
|
|
474
|
+
const chunk = this.chunks.get(chunkId);
|
|
475
|
+
results.push({ chunk, score });
|
|
476
|
+
}
|
|
477
|
+
results.sort((a, b) => b.score - a.score);
|
|
478
|
+
return results.slice(0, topK);
|
|
479
|
+
}
|
|
480
|
+
/** Number of chunks in the index. */
|
|
481
|
+
get size() {
|
|
482
|
+
return this.chunks.size;
|
|
483
|
+
}
|
|
484
|
+
/** Clear the entire index. */
|
|
485
|
+
clear() {
|
|
486
|
+
this.invertedIndex.clear();
|
|
487
|
+
this.chunks.clear();
|
|
488
|
+
this.docToChunks.clear();
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
// src/attribution.ts
|
|
493
|
+
function buildAttribution(chunk, score, title) {
|
|
494
|
+
const truncated = chunk.content.length > 200;
|
|
495
|
+
const excerpt = truncated ? chunk.content.slice(0, 200) + "..." : chunk.content;
|
|
496
|
+
return {
|
|
497
|
+
documentId: chunk.documentId,
|
|
498
|
+
chunkId: chunk.id,
|
|
499
|
+
title,
|
|
500
|
+
relevanceScore: score,
|
|
501
|
+
excerpt
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
function formatAttributions(results) {
|
|
505
|
+
if (results.length === 0) return "";
|
|
506
|
+
const sorted = [...results].sort((a, b) => b.score - a.score).slice(0, 10);
|
|
507
|
+
const lines = sorted.map((r, i) => {
|
|
508
|
+
const excerpt = r.source.excerpt.length > 100 ? r.source.excerpt.slice(0, 100) + "..." : r.source.excerpt;
|
|
509
|
+
return `[${i + 1}] *${r.source.title}* (relevance: ${r.score.toFixed(2)}) \u2014 "${excerpt}"`;
|
|
510
|
+
});
|
|
511
|
+
return `**Sources:**
|
|
512
|
+
${lines.join("\n")}`;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// src/knowledge-store.ts
|
|
516
|
+
var KnowledgeStore = class {
|
|
517
|
+
options;
|
|
518
|
+
documents = /* @__PURE__ */ new Map();
|
|
519
|
+
bm25 = new BM25Index();
|
|
520
|
+
tfidf = new TFIDFIndex();
|
|
521
|
+
totalChunks = 0;
|
|
522
|
+
constructor(options) {
|
|
523
|
+
this.options = {
|
|
524
|
+
engine: options?.engine ?? "bm25",
|
|
525
|
+
maxDocuments: options?.maxDocuments ?? 100,
|
|
526
|
+
maxTotalChunks: options?.maxTotalChunks ?? 5e3,
|
|
527
|
+
topK: options?.topK ?? 5,
|
|
528
|
+
chunker: options?.chunker
|
|
529
|
+
};
|
|
530
|
+
if (options?.persistConsent) {
|
|
531
|
+
console.warn(
|
|
532
|
+
"[GuideKit] KnowledgeStore persistence via IndexedDB is not yet implemented. Data is in-memory only."
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
/** Add a document. Chunks it and indexes all chunks. */
|
|
537
|
+
addDocument(doc) {
|
|
538
|
+
if (this.documents.size >= this.options.maxDocuments) {
|
|
539
|
+
throw new KnowledgeError({
|
|
540
|
+
code: ErrorCodes.KNOWLEDGE_STORE_QUOTA,
|
|
541
|
+
message: `Maximum document limit (${this.options.maxDocuments}) reached`,
|
|
542
|
+
suggestion: "Remove unused documents before adding new ones."
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
const chunks = chunkDocument(doc, this.options.chunker);
|
|
546
|
+
if (this.totalChunks + chunks.length > this.options.maxTotalChunks) {
|
|
547
|
+
throw new KnowledgeError({
|
|
548
|
+
code: ErrorCodes.KNOWLEDGE_STORE_QUOTA,
|
|
549
|
+
message: `Adding ${chunks.length} chunks would exceed the total chunk limit (${this.options.maxTotalChunks})`,
|
|
550
|
+
suggestion: "Remove documents or increase maxTotalChunks."
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
const storedDoc = { ...doc, chunks };
|
|
554
|
+
this.documents.set(doc.id, storedDoc);
|
|
555
|
+
this.bm25.addDocument(chunks);
|
|
556
|
+
this.tfidf.addDocument(chunks);
|
|
557
|
+
this.totalChunks += chunks.length;
|
|
558
|
+
}
|
|
559
|
+
/** Remove a document and its chunks from the index. */
|
|
560
|
+
removeDocument(id) {
|
|
561
|
+
const doc = this.documents.get(id);
|
|
562
|
+
if (!doc) return;
|
|
563
|
+
const chunkCount = doc.chunks?.length ?? 0;
|
|
564
|
+
this.bm25.removeDocument(id);
|
|
565
|
+
this.tfidf.removeDocument(id);
|
|
566
|
+
this.documents.delete(id);
|
|
567
|
+
this.totalChunks -= chunkCount;
|
|
568
|
+
}
|
|
569
|
+
/** Update a document (remove + re-add). */
|
|
570
|
+
updateDocument(id, doc) {
|
|
571
|
+
this.removeDocument(id);
|
|
572
|
+
this.addDocument(doc);
|
|
573
|
+
}
|
|
574
|
+
/** Search the knowledge base. */
|
|
575
|
+
search(query, options) {
|
|
576
|
+
const engine = options?.engine ?? this.options.engine;
|
|
577
|
+
const topK = options?.topK ?? this.options.topK;
|
|
578
|
+
const index = engine === "tfidf" ? this.tfidf : this.bm25;
|
|
579
|
+
let scored = index.search(query, this.totalChunks || 1);
|
|
580
|
+
if (options?.documentIds && options.documentIds.length > 0) {
|
|
581
|
+
const allowed = new Set(options.documentIds);
|
|
582
|
+
scored = scored.filter((s) => allowed.has(s.chunk.documentId));
|
|
583
|
+
}
|
|
584
|
+
if (options?.minScore !== void 0) {
|
|
585
|
+
scored = scored.filter((s) => s.score >= options.minScore);
|
|
586
|
+
}
|
|
587
|
+
scored = scored.slice(0, topK);
|
|
588
|
+
return scored.map((s) => {
|
|
589
|
+
const doc = this.documents.get(s.chunk.documentId);
|
|
590
|
+
const title = doc?.title ?? s.chunk.documentId;
|
|
591
|
+
return {
|
|
592
|
+
chunk: s.chunk,
|
|
593
|
+
score: s.score,
|
|
594
|
+
source: buildAttribution(s.chunk, s.score, title)
|
|
595
|
+
};
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
/** Get a document by ID. */
|
|
599
|
+
getDocument(id) {
|
|
600
|
+
return this.documents.get(id);
|
|
601
|
+
}
|
|
602
|
+
/** Get all document IDs. */
|
|
603
|
+
getDocumentIds() {
|
|
604
|
+
return [...this.documents.keys()];
|
|
605
|
+
}
|
|
606
|
+
/** Clear all documents and indexes. */
|
|
607
|
+
clear() {
|
|
608
|
+
this.documents.clear();
|
|
609
|
+
this.bm25.clear();
|
|
610
|
+
this.tfidf.clear();
|
|
611
|
+
this.totalChunks = 0;
|
|
612
|
+
}
|
|
613
|
+
/** Get store statistics. */
|
|
614
|
+
getStats() {
|
|
615
|
+
return {
|
|
616
|
+
documentCount: this.documents.size,
|
|
617
|
+
chunkCount: this.totalChunks
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
};
|
|
621
|
+
|
|
622
|
+
// src/context-provider.ts
|
|
623
|
+
function createKnowledgeContextProvider(store, options) {
|
|
624
|
+
const tokenBudget = options?.tokenBudget ?? 500;
|
|
625
|
+
const searchOptions = options?.searchOptions;
|
|
626
|
+
const header = options?.header ?? "Relevant Knowledge";
|
|
627
|
+
const maxChars = tokenBudget * 4;
|
|
628
|
+
return (query) => {
|
|
629
|
+
const results = store.search(query, searchOptions);
|
|
630
|
+
if (results.length === 0) return "";
|
|
631
|
+
const sectionHeader = `## ${header}
|
|
632
|
+
|
|
633
|
+
`;
|
|
634
|
+
const attributionFooter = `
|
|
635
|
+
|
|
636
|
+
${formatAttributions(results)}`;
|
|
637
|
+
const reservedChars = sectionHeader.length + attributionFooter.length;
|
|
638
|
+
let remaining = maxChars - reservedChars;
|
|
639
|
+
const chunks = [];
|
|
640
|
+
for (const result of results) {
|
|
641
|
+
const entry = result.chunk.content;
|
|
642
|
+
const cost = entry.length + (chunks.length > 0 ? 2 : 0);
|
|
643
|
+
if (cost > remaining) break;
|
|
644
|
+
chunks.push(entry);
|
|
645
|
+
remaining -= cost;
|
|
646
|
+
}
|
|
647
|
+
if (chunks.length === 0) return "";
|
|
648
|
+
return sectionHeader + chunks.join("\n\n") + attributionFooter;
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// src/index.ts
|
|
653
|
+
var KNOWLEDGE_VERSION = "0.1.0";
|
|
654
|
+
|
|
655
|
+
export { BM25Index, KNOWLEDGE_VERSION, KnowledgeStore, TFIDFIndex, buildAttribution, chunkDocument, createKnowledgeContextProvider, formatAttributions, removeStopwords, tokenize };
|
|
656
|
+
//# sourceMappingURL=index.js.map
|
|
657
|
+
//# sourceMappingURL=index.js.map
|