@voltx/rag 0.1.0 → 0.3.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/dist/index.mjs CHANGED
@@ -1,13 +1,11 @@
1
- // src/index.ts
1
+ // src/splitters.ts
2
2
  var CharacterSplitter = class {
3
- constructor(chunkSize = 1e3, overlap = 200) {
4
- this.chunkSize = chunkSize;
5
- this.overlap = overlap;
3
+ chunkSize;
4
+ overlap;
5
+ constructor(options = {}) {
6
+ this.chunkSize = options.chunkSize ?? 1e3;
7
+ this.overlap = options.overlap ?? 200;
6
8
  }
7
- /**
8
- * Find the best split point near `pos` by looking for sentence/paragraph
9
- * boundaries first, then word boundaries, falling back to exact position.
10
- */
11
9
  findBreakPoint(text, pos) {
12
10
  if (pos >= text.length) return text.length;
13
11
  const searchStart = Math.max(0, pos - Math.floor(this.chunkSize * 0.2));
@@ -21,9 +19,7 @@ var CharacterSplitter = class {
21
19
  }
22
20
  }
23
21
  for (let i = pos; i >= searchStart; i--) {
24
- if (/\s/.test(text[i])) {
25
- return i + 1;
26
- }
22
+ if (/\s/.test(text[i])) return i + 1;
27
23
  }
28
24
  return pos;
29
25
  }
@@ -34,57 +30,502 @@ var CharacterSplitter = class {
34
30
  while (start < text.length) {
35
31
  const rawEnd = Math.min(start + this.chunkSize, text.length);
36
32
  const end = rawEnd >= text.length ? rawEnd : this.findBreakPoint(text, rawEnd);
37
- chunks.push({
38
- id: `chunk-${index++}`,
39
- content: text.slice(start, end).trim(),
40
- metadata: { start, end }
41
- });
33
+ const content = text.slice(start, end).trim();
34
+ if (content.length > 0) {
35
+ chunks.push({
36
+ id: `chunk-${index++}`,
37
+ content,
38
+ metadata: { start, end, splitter: "character" }
39
+ });
40
+ }
42
41
  const step = end - start - this.overlap;
43
42
  start += step > 0 ? step : end - start;
44
43
  }
44
+ return chunks;
45
+ }
46
+ };
47
+ var RecursiveTextSplitter = class {
48
+ chunkSize;
49
+ overlap;
50
+ separators;
51
+ constructor(options = {}) {
52
+ this.chunkSize = options.chunkSize ?? 1e3;
53
+ this.overlap = options.overlap ?? 200;
54
+ this.separators = options.separators ?? ["\n\n", "\n", ". ", " ", ""];
55
+ }
56
+ split(text) {
57
+ const rawChunks = this.splitText(text, this.separators);
58
+ const merged = this.mergeWithOverlap(rawChunks);
59
+ return merged.map((content, i) => ({
60
+ id: `chunk-${i}`,
61
+ content,
62
+ metadata: { index: i, splitter: "recursive" }
63
+ }));
64
+ }
65
+ /**
66
+ * Recursively split text. Try the first separator; if any resulting piece
67
+ * is still too large, recurse with the next separator in the list.
68
+ */
69
+ splitText(text, separators) {
70
+ const results = [];
71
+ let bestSep = "";
72
+ let bestIdx = 0;
73
+ for (let i = 0; i < separators.length; i++) {
74
+ const sep = separators[i];
75
+ if (sep === "") {
76
+ bestSep = sep;
77
+ bestIdx = i;
78
+ break;
79
+ }
80
+ if (text.includes(sep)) {
81
+ bestSep = sep;
82
+ bestIdx = i;
83
+ break;
84
+ }
85
+ }
86
+ const pieces = bestSep === "" ? [...text] : text.split(bestSep);
87
+ const remainingSeps = separators.slice(bestIdx + 1);
88
+ let current = "";
89
+ for (const piece of pieces) {
90
+ const candidate = current ? current + bestSep + piece : piece;
91
+ if (candidate.length <= this.chunkSize) {
92
+ current = candidate;
93
+ } else {
94
+ if (current.trim()) {
95
+ results.push(current.trim());
96
+ }
97
+ if (piece.length > this.chunkSize && remainingSeps.length > 0) {
98
+ const subChunks = this.splitText(piece, remainingSeps);
99
+ results.push(...subChunks);
100
+ current = "";
101
+ } else {
102
+ current = piece;
103
+ }
104
+ }
105
+ }
106
+ if (current.trim()) {
107
+ results.push(current.trim());
108
+ }
109
+ return results;
110
+ }
111
+ /**
112
+ * Merge chunks with overlap to maintain context between adjacent chunks.
113
+ */
114
+ mergeWithOverlap(chunks) {
115
+ if (this.overlap <= 0 || chunks.length <= 1) return chunks;
116
+ const result = [];
117
+ for (let i = 0; i < chunks.length; i++) {
118
+ if (i === 0) {
119
+ result.push(chunks[i]);
120
+ } else {
121
+ const prev = chunks[i - 1];
122
+ const overlapText = prev.slice(-this.overlap);
123
+ const spaceIdx = overlapText.indexOf(" ");
124
+ const cleanOverlap = spaceIdx >= 0 ? overlapText.slice(spaceIdx + 1) : overlapText;
125
+ result.push((cleanOverlap + " " + chunks[i]).trim());
126
+ }
127
+ }
128
+ return result;
129
+ }
130
+ };
131
+ var MarkdownSplitter = class {
132
+ chunkSize;
133
+ overlap;
134
+ includeHeaders;
135
+ constructor(options = {}) {
136
+ this.chunkSize = options.chunkSize ?? 1500;
137
+ this.overlap = options.overlap ?? 100;
138
+ this.includeHeaders = options.includeHeaders ?? true;
139
+ }
140
+ split(text) {
141
+ const sections = this.splitByHeadings(text);
142
+ const chunks = [];
143
+ let index = 0;
144
+ const fallback = new RecursiveTextSplitter({
145
+ chunkSize: this.chunkSize,
146
+ overlap: this.overlap
147
+ });
148
+ for (const section of sections) {
149
+ if (section.content.length <= this.chunkSize) {
150
+ chunks.push({
151
+ id: `chunk-${index++}`,
152
+ content: section.content.trim(),
153
+ metadata: {
154
+ ...section.headers,
155
+ splitter: "markdown"
156
+ }
157
+ });
158
+ } else {
159
+ const subChunks = fallback.split(section.content);
160
+ for (const sub of subChunks) {
161
+ chunks.push({
162
+ id: `chunk-${index++}`,
163
+ content: sub.content.trim(),
164
+ metadata: {
165
+ ...section.headers,
166
+ ...sub.metadata,
167
+ splitter: "markdown"
168
+ }
169
+ });
170
+ }
171
+ }
172
+ }
45
173
  return chunks.filter((c) => c.content.length > 0);
46
174
  }
175
+ splitByHeadings(text) {
176
+ const lines = text.split("\n");
177
+ const sections = [];
178
+ const headerStack = {};
179
+ let currentContent = "";
180
+ for (const line of lines) {
181
+ const headerMatch = line.match(/^(#{1,6})\s+(.+)$/);
182
+ if (headerMatch) {
183
+ if (currentContent.trim()) {
184
+ sections.push({
185
+ content: this.includeHeaders ? this.buildHeaderPrefix(headerStack) + currentContent.trim() : currentContent.trim(),
186
+ headers: { ...headerStack }
187
+ });
188
+ }
189
+ const level = headerMatch[1].length;
190
+ const title = headerMatch[2].trim();
191
+ for (let i = level; i <= 6; i++) {
192
+ delete headerStack[`h${i}`];
193
+ }
194
+ headerStack[`h${level}`] = title;
195
+ currentContent = "";
196
+ } else {
197
+ currentContent += line + "\n";
198
+ }
199
+ }
200
+ if (currentContent.trim()) {
201
+ sections.push({
202
+ content: this.includeHeaders ? this.buildHeaderPrefix(headerStack) + currentContent.trim() : currentContent.trim(),
203
+ headers: { ...headerStack }
204
+ });
205
+ }
206
+ return sections;
207
+ }
208
+ buildHeaderPrefix(headers) {
209
+ const parts = [];
210
+ for (let i = 1; i <= 6; i++) {
211
+ const h = headers[`h${i}`];
212
+ if (h) parts.push(h);
213
+ }
214
+ return parts.length > 0 ? parts.join(" > ") + "\n\n" : "";
215
+ }
216
+ };
217
+
218
+ // src/loaders.ts
219
+ import { readFile } from "fs/promises";
220
+ import { existsSync } from "fs";
221
+ var TextLoader = class {
222
+ name = "text";
223
+ async load(source) {
224
+ if (existsSync(source)) {
225
+ return readFile(source, "utf-8");
226
+ }
227
+ return source;
228
+ }
229
+ };
230
+ var MarkdownLoader = class {
231
+ name = "markdown";
232
+ async load(source) {
233
+ let text;
234
+ if (existsSync(source)) {
235
+ text = await readFile(source, "utf-8");
236
+ } else {
237
+ text = source;
238
+ }
239
+ const frontMatterRegex = /^---\s*\n[\s\S]*?\n---\s*\n/;
240
+ return text.replace(frontMatterRegex, "").trim();
241
+ }
47
242
  };
243
+ var JSONLoader = class {
244
+ name = "json";
245
+ textKeys;
246
+ separator;
247
+ constructor(options = {}) {
248
+ this.textKeys = options.textKeys ?? ["content", "text", "body", "description"];
249
+ this.separator = options.separator ?? "\n\n";
250
+ }
251
+ async load(source) {
252
+ let raw;
253
+ if (existsSync(source)) {
254
+ raw = await readFile(source, "utf-8");
255
+ } else {
256
+ raw = source;
257
+ }
258
+ const data = JSON.parse(raw);
259
+ const texts = this.extractTexts(data);
260
+ return texts.join(this.separator);
261
+ }
262
+ extractTexts(data) {
263
+ const results = [];
264
+ if (Array.isArray(data)) {
265
+ for (const item of data) {
266
+ results.push(...this.extractTexts(item));
267
+ }
268
+ } else if (data !== null && typeof data === "object") {
269
+ const obj = data;
270
+ for (const key of this.textKeys) {
271
+ if (key in obj && typeof obj[key] === "string") {
272
+ results.push(obj[key]);
273
+ }
274
+ }
275
+ if (results.length === 0) {
276
+ for (const value of Object.values(obj)) {
277
+ if (typeof value === "string" && value.length > 20) {
278
+ results.push(value);
279
+ } else if (typeof value === "object" && value !== null) {
280
+ results.push(...this.extractTexts(value));
281
+ }
282
+ }
283
+ }
284
+ } else if (typeof data === "string") {
285
+ results.push(data);
286
+ }
287
+ return results;
288
+ }
289
+ };
290
+ var WebLoader = class {
291
+ name = "web";
292
+ async load(source) {
293
+ const response = await fetch(source);
294
+ if (!response.ok) {
295
+ throw new Error(`[voltx/rag] WebLoader failed to fetch ${source}: ${response.status}`);
296
+ }
297
+ const contentType = response.headers.get("content-type") ?? "";
298
+ const text = await response.text();
299
+ if (contentType.includes("text/html")) {
300
+ return this.stripHTML(text);
301
+ }
302
+ return text;
303
+ }
304
+ stripHTML(html) {
305
+ return html.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<[^>]+>/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, " ").replace(/\s+/g, " ").trim();
306
+ }
307
+ };
308
+
309
+ // src/embedder.ts
310
+ import { embed, embedMany } from "@voltx/ai";
311
+ function createEmbedder(config) {
312
+ const { model } = config;
313
+ return {
314
+ name: `voltx-embedder:${model}`,
315
+ async embed(text) {
316
+ const result = await embed({ model, value: text });
317
+ return result.embedding;
318
+ },
319
+ async embedBatch(texts) {
320
+ if (texts.length === 0) return [];
321
+ if (texts.length === 1) {
322
+ const result2 = await embed({ model, value: texts[0] });
323
+ return [result2.embedding];
324
+ }
325
+ const result = await embedMany({ model, values: texts });
326
+ return result.embeddings;
327
+ }
328
+ };
329
+ }
330
+
331
+ // src/document.ts
332
+ var MDocument = class _MDocument {
333
+ content;
334
+ format;
335
+ chunks = null;
336
+ constructor(content, format) {
337
+ this.content = content;
338
+ this.format = format;
339
+ }
340
+ /** Create from plain text */
341
+ static fromText(content) {
342
+ return new _MDocument(content, "text");
343
+ }
344
+ /** Create from markdown */
345
+ static fromMarkdown(content) {
346
+ return new _MDocument(content, "markdown");
347
+ }
348
+ /** Create from JSON string */
349
+ static fromJSON(content) {
350
+ JSON.parse(content);
351
+ return new _MDocument(content, "json");
352
+ }
353
+ /** Create from HTML (strips tags) */
354
+ static fromHTML(html) {
355
+ const text = html.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<[^>]+>/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&nbsp;/g, " ").replace(/\s+/g, " ").trim();
356
+ return new _MDocument(text, "html");
357
+ }
358
+ /** Get the raw content */
359
+ getContent() {
360
+ return this.content;
361
+ }
362
+ /** Get the document format */
363
+ getFormat() {
364
+ return this.format;
365
+ }
366
+ /**
367
+ * Split the document into chunks using the specified strategy.
368
+ * Returns the chunks and caches them for subsequent embed() calls.
369
+ */
370
+ chunk(options = {}) {
371
+ const strategy = options.strategy ?? this.defaultStrategy();
372
+ const splitter = this.createSplitter(strategy, options);
373
+ this.chunks = splitter.split(this.content);
374
+ return this.chunks;
375
+ }
376
+ /**
377
+ * Embed the chunks using the provided embedder.
378
+ * Must call chunk() first.
379
+ */
380
+ async embed(embedder) {
381
+ if (!this.chunks) {
382
+ throw new Error("[voltx/rag] Call chunk() before embed()");
383
+ }
384
+ const texts = this.chunks.map((c) => c.content);
385
+ const embeddings = await embedder.embedBatch(texts);
386
+ for (let i = 0; i < this.chunks.length; i++) {
387
+ this.chunks[i].embedding = embeddings[i];
388
+ }
389
+ return this.chunks;
390
+ }
391
+ /** Get cached chunks (null if chunk() hasn't been called) */
392
+ getChunks() {
393
+ return this.chunks;
394
+ }
395
+ defaultStrategy() {
396
+ if (this.format === "markdown") return "markdown";
397
+ return "recursive";
398
+ }
399
+ createSplitter(strategy, options) {
400
+ switch (strategy) {
401
+ case "markdown":
402
+ return new MarkdownSplitter({
403
+ chunkSize: options.chunkSize,
404
+ overlap: options.overlap,
405
+ includeHeaders: options.includeHeaders
406
+ });
407
+ case "character":
408
+ return new CharacterSplitter({
409
+ chunkSize: options.chunkSize,
410
+ overlap: options.overlap
411
+ });
412
+ case "recursive":
413
+ default:
414
+ return new RecursiveTextSplitter({
415
+ chunkSize: options.chunkSize,
416
+ overlap: options.overlap,
417
+ separators: options.separators
418
+ });
419
+ }
420
+ }
421
+ };
422
+
423
+ // src/utils.ts
424
+ function cosineSimilarity(a, b) {
425
+ if (a.length !== b.length) {
426
+ throw new Error(
427
+ `[voltx/rag] Vector dimension mismatch: ${a.length} vs ${b.length}`
428
+ );
429
+ }
430
+ let dotProduct = 0;
431
+ let normA = 0;
432
+ let normB = 0;
433
+ for (let i = 0; i < a.length; i++) {
434
+ dotProduct += a[i] * b[i];
435
+ normA += a[i] * a[i];
436
+ normB += b[i] * b[i];
437
+ }
438
+ const magnitude = Math.sqrt(normA) * Math.sqrt(normB);
439
+ if (magnitude === 0) return 0;
440
+ return dotProduct / magnitude;
441
+ }
442
+
443
+ // src/index.ts
48
444
  var RAGPipeline = class {
49
- config;
445
+ loader;
446
+ splitter;
447
+ embedder;
448
+ vectorStore;
50
449
  constructor(config) {
51
- this.config = config;
52
- }
53
- /** Ingest a document: load → split → embed → store */
54
- async ingest(source) {
55
- const { loader, splitter = new CharacterSplitter(), embedder, vectorStore } = this.config;
56
- const text = loader ? await loader.load(source) : source;
57
- const chunks = splitter.split(text);
58
- const docs = [];
59
- for (const chunk of chunks) {
60
- const embedding = await embedder.embed(chunk.content);
61
- docs.push({
62
- id: chunk.id,
63
- content: chunk.content,
64
- embedding,
65
- metadata: chunk.metadata
66
- });
67
- }
68
- await vectorStore.upsert(docs);
69
- return docs.length;
450
+ this.loader = config.loader;
451
+ this.splitter = config.splitter ?? new RecursiveTextSplitter();
452
+ this.embedder = config.embedder;
453
+ this.vectorStore = config.vectorStore;
70
454
  }
71
- /** Query: embed question → search vector store → return sources */
72
- async query(question, topK = 5) {
73
- const { embedder, vectorStore } = this.config;
74
- const embedding = await embedder.embed(question);
75
- const results = await vectorStore.search(embedding, topK);
455
+ /**
456
+ * Ingest a document: load → split → embed (batch) → store in vector DB.
457
+ *
458
+ * @param source - File path, URL, or raw text (depends on loader)
459
+ * @param idPrefix - Optional prefix for chunk IDs (default: "doc")
460
+ * @returns Number of chunks ingested and their IDs
461
+ */
462
+ async ingest(source, idPrefix = "doc") {
463
+ const text = this.loader ? await this.loader.load(source) : source;
464
+ const chunks = this.splitter.split(text);
465
+ const texts = chunks.map((c) => c.content);
466
+ const embeddings = await this.embedder.embedBatch(texts);
467
+ const docs = chunks.map((chunk, i) => ({
468
+ id: `${idPrefix}-${chunk.id}`,
469
+ content: chunk.content,
470
+ embedding: embeddings[i],
471
+ metadata: chunk.metadata
472
+ }));
473
+ await this.vectorStore.upsert(docs);
76
474
  return {
77
- sources: results.map((r) => r.document)
475
+ chunks: docs.length,
476
+ ids: docs.map((d) => d.id)
78
477
  };
79
478
  }
479
+ /**
480
+ * Query: embed question → search vector store → return ranked sources.
481
+ *
482
+ * @param question - The user's question
483
+ * @param options - Query options (topK, minScore)
484
+ */
485
+ async query(question, options = {}) {
486
+ const { topK = 5, minScore = 0 } = options;
487
+ const queryEmbedding = await this.embedder.embed(question);
488
+ const results = await this.vectorStore.search(queryEmbedding, topK);
489
+ const filtered = minScore > 0 ? results.filter((r) => r.score >= minScore) : results;
490
+ return {
491
+ sources: filtered.map((r) => r.document),
492
+ queryEmbedding
493
+ };
494
+ }
495
+ /**
496
+ * Convenience: query + format sources into a context string for LLM prompts.
497
+ */
498
+ async getContext(question, options = {}) {
499
+ const { sources } = await this.query(question, options);
500
+ if (sources.length === 0) {
501
+ return "No relevant context found.";
502
+ }
503
+ return sources.map((s, i) => `[Source ${i + 1}]
504
+ ${s.content}`).join("\n\n---\n\n");
505
+ }
506
+ /**
507
+ * Delete documents from the vector store by IDs.
508
+ */
509
+ async delete(ids) {
510
+ await this.vectorStore.delete(ids);
511
+ }
80
512
  };
81
513
  function createRAGPipeline(config) {
82
514
  return new RAGPipeline(config);
83
515
  }
84
- var VERSION = "0.1.0";
516
+ var VERSION = "0.3.0";
85
517
  export {
86
518
  CharacterSplitter,
519
+ JSONLoader,
520
+ MDocument,
521
+ MarkdownLoader,
522
+ MarkdownSplitter,
87
523
  RAGPipeline,
524
+ RecursiveTextSplitter,
525
+ TextLoader,
88
526
  VERSION,
527
+ WebLoader,
528
+ cosineSimilarity,
529
+ createEmbedder,
89
530
  createRAGPipeline
90
531
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltx/rag",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "VoltX RAG pipeline primitives — document loading, chunking, embedding, retrieval",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -13,17 +13,20 @@
13
13
  "require": "./dist/index.js"
14
14
  }
15
15
  },
16
+ "scripts": {
17
+ "build": "tsup src/index.ts --format cjs,esm --dts",
18
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
19
+ "clean": "rm -rf dist"
20
+ },
16
21
  "dependencies": {
17
- "@voltx/core": "0.1.0",
18
- "@voltx/db": "0.1.0"
22
+ "@voltx/ai": "workspace:*",
23
+ "@voltx/db": "workspace:*"
19
24
  },
20
25
  "devDependencies": {
21
26
  "tsup": "^8.0.0",
22
27
  "typescript": "^5.7.0"
23
28
  },
24
- "files": [
25
- "dist"
26
- ],
29
+ "files": ["dist"],
27
30
  "license": "MIT",
28
31
  "repository": {
29
32
  "type": "git",
@@ -38,11 +41,9 @@
38
41
  "retrieval-augmented-generation",
39
42
  "embeddings",
40
43
  "chunking",
41
- "pipeline"
42
- ],
43
- "scripts": {
44
- "build": "tsup src/index.ts --format cjs,esm --dts",
45
- "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
46
- "clean": "rm -rf dist"
47
- }
48
- }
44
+ "pipeline",
45
+ "document-loaders",
46
+ "text-splitters",
47
+ "vector-search"
48
+ ]
49
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Promptly AI Team
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.