@retrivora-ai/rag-engine 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.
Files changed (61) hide show
  1. package/.env.example +77 -0
  2. package/README.md +149 -0
  3. package/dist/DocumentChunker-BUrIrcPk.d.mts +43 -0
  4. package/dist/DocumentChunker-BUrIrcPk.d.ts +43 -0
  5. package/dist/RAGPipeline-BmkIv1HD.d.mts +298 -0
  6. package/dist/RAGPipeline-BmkIv1HD.d.ts +298 -0
  7. package/dist/chunk-NCG2JKXB.mjs +1254 -0
  8. package/dist/chunk-ZPXLQR5Q.mjs +67 -0
  9. package/dist/handlers/index.d.mts +68 -0
  10. package/dist/handlers/index.d.ts +68 -0
  11. package/dist/handlers/index.js +1319 -0
  12. package/dist/handlers/index.mjs +13 -0
  13. package/dist/index.d.mts +93 -0
  14. package/dist/index.d.ts +93 -0
  15. package/dist/index.js +612 -0
  16. package/dist/index.mjs +551 -0
  17. package/dist/server.d.mts +211 -0
  18. package/dist/server.d.ts +211 -0
  19. package/dist/server.js +1457 -0
  20. package/dist/server.mjs +148 -0
  21. package/package.json +90 -0
  22. package/src/app/api/chat/route.ts +4 -0
  23. package/src/app/api/health/route.ts +4 -0
  24. package/src/app/api/ingest/route.ts +26 -0
  25. package/src/app/favicon.ico +0 -0
  26. package/src/app/globals.css +163 -0
  27. package/src/app/layout.tsx +35 -0
  28. package/src/app/page.tsx +506 -0
  29. package/src/components/ChatWidget.tsx +91 -0
  30. package/src/components/ChatWindow.tsx +248 -0
  31. package/src/components/ConfigProvider.tsx +56 -0
  32. package/src/components/MessageBubble.tsx +99 -0
  33. package/src/components/SourceCard.tsx +66 -0
  34. package/src/components/ThemeProvider.tsx +8 -0
  35. package/src/components/ThemeToggle.tsx +29 -0
  36. package/src/config/RagConfig.ts +159 -0
  37. package/src/config/UniversalProfiles.ts +83 -0
  38. package/src/config/serverConfig.ts +142 -0
  39. package/src/handlers/index.ts +202 -0
  40. package/src/hooks/useHydrated.ts +13 -0
  41. package/src/hooks/useRagChat.ts +167 -0
  42. package/src/hooks/useStoredMessages.ts +53 -0
  43. package/src/index.ts +27 -0
  44. package/src/llm/ILLMProvider.ts +60 -0
  45. package/src/llm/LLMFactory.ts +54 -0
  46. package/src/llm/providers/AnthropicProvider.ts +87 -0
  47. package/src/llm/providers/OllamaProvider.ts +102 -0
  48. package/src/llm/providers/OpenAIProvider.ts +92 -0
  49. package/src/llm/providers/UniversalLLMAdapter.ts +154 -0
  50. package/src/rag/DocumentChunker.ts +105 -0
  51. package/src/rag/RAGPipeline.ts +196 -0
  52. package/src/server.ts +30 -0
  53. package/src/types/pdf-parse.d.ts +13 -0
  54. package/src/utils/DocumentParser.ts +75 -0
  55. package/src/utils/templateUtils.ts +78 -0
  56. package/src/vectordb/IVectorDB.ts +75 -0
  57. package/src/vectordb/VectorDBFactory.ts +41 -0
  58. package/src/vectordb/adapters/MongoDbAdapter.ts +175 -0
  59. package/src/vectordb/adapters/PgVectorAdapter.ts +159 -0
  60. package/src/vectordb/adapters/PineconeAdapter.ts +115 -0
  61. package/src/vectordb/adapters/UniversalVectorDBAdapter.ts +177 -0
package/dist/server.js ADDED
@@ -0,0 +1,1457 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
+ // If the importer is in node compatibility mode or this is not an ESM
39
+ // file that has been converted to a CommonJS file using a Babel-
40
+ // compatible transform (i.e. "__esModule" has not been set), then set
41
+ // "default" to the CommonJS "module.exports" for node compatibility.
42
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
+ mod
44
+ ));
45
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+
47
+ // src/server.ts
48
+ var server_exports = {};
49
+ __export(server_exports, {
50
+ AnthropicProvider: () => AnthropicProvider,
51
+ DocumentChunker: () => DocumentChunker,
52
+ LLMFactory: () => LLMFactory,
53
+ MongoDbAdapter: () => MongoDbAdapter,
54
+ OllamaProvider: () => OllamaProvider,
55
+ OpenAIProvider: () => OpenAIProvider,
56
+ PgVectorAdapter: () => PgVectorAdapter,
57
+ PineconeAdapter: () => PineconeAdapter,
58
+ RAGPipeline: () => RAGPipeline,
59
+ VectorDBFactory: () => VectorDBFactory,
60
+ createChatHandler: () => createChatHandler,
61
+ createHealthHandler: () => createHealthHandler,
62
+ createIngestHandler: () => createIngestHandler,
63
+ createUploadHandler: () => createUploadHandler,
64
+ getRagConfig: () => getRagConfig
65
+ });
66
+ module.exports = __toCommonJS(server_exports);
67
+
68
+ // src/vectordb/adapters/PineconeAdapter.ts
69
+ var import_pinecone = require("@pinecone-database/pinecone");
70
+ var PineconeAdapter = class {
71
+ constructor(config) {
72
+ this.indexName = config.indexName;
73
+ const opts = config.options;
74
+ if (!opts.apiKey) throw new Error("[PineconeAdapter] options.apiKey is required");
75
+ this.apiKey = opts.apiKey;
76
+ }
77
+ async initialize() {
78
+ var _a, _b;
79
+ this.client = new import_pinecone.Pinecone({ apiKey: this.apiKey });
80
+ const indexes = await this.client.listIndexes();
81
+ const names = (_b = (_a = indexes.indexes) == null ? void 0 : _a.map((i) => i.name)) != null ? _b : [];
82
+ if (!names.includes(this.indexName)) {
83
+ throw new Error(
84
+ `[PineconeAdapter] Index "${this.indexName}" not found. Available: ${names.join(", ")}`
85
+ );
86
+ }
87
+ }
88
+ index(namespace) {
89
+ const idx = this.client.index(this.indexName);
90
+ return namespace ? idx.namespace(namespace) : idx.namespace("");
91
+ }
92
+ async upsert(doc, namespace) {
93
+ var _a;
94
+ await this.index(namespace).upsert({
95
+ records: [
96
+ {
97
+ id: doc.id,
98
+ values: doc.vector,
99
+ metadata: __spreadValues({
100
+ content: doc.content
101
+ }, (_a = doc.metadata) != null ? _a : {})
102
+ }
103
+ ]
104
+ });
105
+ }
106
+ async batchUpsert(docs, namespace) {
107
+ const BATCH = 100;
108
+ for (let i = 0; i < docs.length; i += BATCH) {
109
+ const records = docs.slice(i, i + BATCH).map((d) => {
110
+ var _a;
111
+ return {
112
+ id: d.id,
113
+ values: d.vector,
114
+ metadata: __spreadValues({
115
+ content: d.content
116
+ }, (_a = d.metadata) != null ? _a : {})
117
+ };
118
+ });
119
+ await this.index(namespace).upsert({ records });
120
+ }
121
+ }
122
+ async query(vector, topK, namespace, filter) {
123
+ var _a;
124
+ const result = await this.index(namespace).query(__spreadValues({
125
+ vector,
126
+ topK,
127
+ includeMetadata: true
128
+ }, filter ? { filter } : {}));
129
+ return ((_a = result.matches) != null ? _a : []).map((m) => {
130
+ var _a2, _b, _c;
131
+ return {
132
+ id: m.id,
133
+ score: (_a2 = m.score) != null ? _a2 : 0,
134
+ content: (_c = (_b = m.metadata) == null ? void 0 : _b.content) != null ? _c : "",
135
+ metadata: m.metadata
136
+ };
137
+ });
138
+ }
139
+ async delete(id, namespace) {
140
+ await this.index(namespace).deleteOne({ id });
141
+ }
142
+ async deleteNamespace(namespace) {
143
+ await this.client.index(this.indexName).namespace(namespace).deleteAll();
144
+ }
145
+ async ping() {
146
+ try {
147
+ await this.client.listIndexes();
148
+ return true;
149
+ } catch (err) {
150
+ console.error("[PineconeAdapter] Ping failed:", err);
151
+ return false;
152
+ }
153
+ }
154
+ async disconnect() {
155
+ }
156
+ };
157
+
158
+ // src/vectordb/adapters/PgVectorAdapter.ts
159
+ var import_pg = require("pg");
160
+ var PgVectorAdapter = class {
161
+ constructor(config) {
162
+ var _a;
163
+ this.tableName = config.indexName.replace(/[^a-z0-9_]/gi, "_");
164
+ const opts = config.options;
165
+ if (!opts.connectionString) {
166
+ throw new Error("[PgVectorAdapter] options.connectionString is required");
167
+ }
168
+ this.connectionString = opts.connectionString;
169
+ this.dimensions = (_a = opts.dimensions) != null ? _a : 1536;
170
+ }
171
+ async initialize() {
172
+ this.pool = new import_pg.Pool({ connectionString: this.connectionString });
173
+ const client = await this.pool.connect();
174
+ try {
175
+ await client.query("CREATE EXTENSION IF NOT EXISTS vector");
176
+ await client.query(`
177
+ CREATE TABLE IF NOT EXISTS ${this.tableName} (
178
+ id TEXT PRIMARY KEY,
179
+ namespace TEXT NOT NULL DEFAULT '',
180
+ content TEXT NOT NULL,
181
+ metadata JSONB,
182
+ embedding VECTOR(${this.dimensions})
183
+ )
184
+ `);
185
+ await client.query(`
186
+ CREATE INDEX IF NOT EXISTS ${this.tableName}_embedding_idx
187
+ ON ${this.tableName}
188
+ USING hnsw (embedding vector_cosine_ops)
189
+ `);
190
+ } finally {
191
+ client.release();
192
+ }
193
+ }
194
+ async upsert(doc, namespace = "") {
195
+ var _a;
196
+ const vectorLiteral = `[${doc.vector.join(",")}]`;
197
+ await this.pool.query(
198
+ `INSERT INTO ${this.tableName} (id, namespace, content, metadata, embedding)
199
+ VALUES ($1, $2, $3, $4, $5::vector)
200
+ ON CONFLICT (id) DO UPDATE
201
+ SET namespace = EXCLUDED.namespace,
202
+ content = EXCLUDED.content,
203
+ metadata = EXCLUDED.metadata,
204
+ embedding = EXCLUDED.embedding`,
205
+ [doc.id, namespace, doc.content, JSON.stringify((_a = doc.metadata) != null ? _a : {}), vectorLiteral]
206
+ );
207
+ }
208
+ async batchUpsert(docs, namespace = "") {
209
+ for (const doc of docs) {
210
+ await this.upsert(doc, namespace);
211
+ }
212
+ }
213
+ async query(vector, topK, namespace, filter) {
214
+ const vectorLiteral = `[${vector.join(",")}]`;
215
+ let whereClause = namespace ? `WHERE namespace = $3` : "";
216
+ const params = [vectorLiteral, topK];
217
+ if (namespace) params.push(namespace);
218
+ if (filter && Object.keys(filter).length > 0) {
219
+ const filterConditions = Object.entries(filter).map(([key, val]) => {
220
+ const paramIdx = params.length + 1;
221
+ params.push(JSON.stringify(val));
222
+ return `metadata->>'${key}' = $${paramIdx}`;
223
+ }).join(" AND ");
224
+ whereClause = whereClause ? `${whereClause} AND ${filterConditions}` : `WHERE ${filterConditions}`;
225
+ }
226
+ const result = await this.pool.query(
227
+ `SELECT id,
228
+ content,
229
+ metadata,
230
+ 1 - (embedding <=> $1::vector) AS score
231
+ FROM ${this.tableName}
232
+ ${whereClause}
233
+ ORDER BY embedding <=> $1::vector
234
+ LIMIT $2`,
235
+ params
236
+ );
237
+ return result.rows.map((row) => ({
238
+ id: String(row.id),
239
+ score: parseFloat(String(row.score)),
240
+ content: String(row.content),
241
+ metadata: row.metadata
242
+ }));
243
+ }
244
+ async delete(id, namespace) {
245
+ const where = namespace ? "WHERE id = $1 AND namespace = $2" : "WHERE id = $1";
246
+ const params = namespace ? [id, namespace] : [id];
247
+ await this.pool.query(`DELETE FROM ${this.tableName} ${where}`, params);
248
+ }
249
+ async deleteNamespace(namespace) {
250
+ await this.pool.query(
251
+ `DELETE FROM ${this.tableName} WHERE namespace = $1`,
252
+ [namespace]
253
+ );
254
+ }
255
+ async ping() {
256
+ try {
257
+ await this.pool.query("SELECT 1");
258
+ return true;
259
+ } catch (err) {
260
+ console.error("[PgVectorAdapter] Ping failed:", err);
261
+ return false;
262
+ }
263
+ }
264
+ async disconnect() {
265
+ try {
266
+ await this.pool.end();
267
+ } catch (err) {
268
+ console.error("[PgVectorAdapter] Failed to disconnect:", err);
269
+ }
270
+ }
271
+ };
272
+
273
+ // src/vectordb/adapters/UniversalVectorDBAdapter.ts
274
+ var import_axios = __toESM(require("axios"));
275
+
276
+ // src/utils/templateUtils.ts
277
+ function isRecord(value) {
278
+ return typeof value === "object" && value !== null;
279
+ }
280
+ function resolvePath(obj, path) {
281
+ if (!path || !obj) return void 0;
282
+ return path.replace(/\[(\w+)\]/g, ".$1").replace(/^\./, "").split(".").reduce((current, segment) => {
283
+ if (!isRecord(current) && !Array.isArray(current)) {
284
+ return void 0;
285
+ }
286
+ return current[segment];
287
+ }, obj);
288
+ }
289
+ function buildPayload(template, vars) {
290
+ let raw = template;
291
+ for (const [key, val] of Object.entries(vars)) {
292
+ const stringifiedVal = val === void 0 ? "null" : JSON.stringify(val);
293
+ raw = raw.replace(new RegExp(`"\\{\\{${key}\\}\\}"`, "g"), stringifiedVal);
294
+ raw = raw.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), stringifiedVal);
295
+ }
296
+ try {
297
+ return JSON.parse(raw);
298
+ } catch (err) {
299
+ throw new Error(`Failed to parse payload template: ${err.message}
300
+ Raw payload: ${raw}`);
301
+ }
302
+ }
303
+
304
+ // src/config/UniversalProfiles.ts
305
+ var OPENAI_BASE = {
306
+ chatPath: "/chat/completions",
307
+ embedPath: "/embeddings",
308
+ responseExtractPath: "choices[0].message.content",
309
+ embedExtractPath: "data[0].embedding",
310
+ chatPayloadTemplate: '{"model":"{{model}}","messages":{{messages}},"max_tokens":{{maxTokens}},"temperature":{{temperature}}}'
311
+ };
312
+ var LLM_PROFILES = {
313
+ "openai-compatible": OPENAI_BASE,
314
+ "litellm": __spreadProps(__spreadValues({}, OPENAI_BASE), {
315
+ chatPayloadTemplate: '{"model":"{{model}}","messages":{{messages}},"max_tokens":{{maxTokens}},"temperature":{{temperature}},"stream":false}'
316
+ }),
317
+ "anthropic-claude": {
318
+ chatPath: "/v1/messages",
319
+ responseExtractPath: "content[0].text",
320
+ headers: { "anthropic-version": "2023-06-01" },
321
+ chatPayloadTemplate: '{"model":"{{model}}","messages":{{messages}},"max_tokens":{{maxTokens}}}'
322
+ },
323
+ "google-gemini": {
324
+ chatPath: "/v1beta/models/{{model}}:generateContent",
325
+ responseExtractPath: "candidates[0].content.parts[0].text",
326
+ chatPayloadTemplate: '{"contents":[{"parts":[{"text":"{{messages}}"}]}]}'
327
+ },
328
+ "github-copilot": __spreadProps(__spreadValues({}, OPENAI_BASE), {
329
+ chatPayloadTemplate: '{"model":"{{model}}","messages":{{messages}},"temperature":{{temperature}}}'
330
+ }),
331
+ "ollama-standard": {
332
+ chatPath: "/api/chat",
333
+ embedPath: "/api/embeddings",
334
+ responseExtractPath: "message.content",
335
+ embedExtractPath: "embedding",
336
+ chatPayloadTemplate: '{"model":"{{model}}","messages":{{messages}},"stream":false}',
337
+ embedPayloadTemplate: '{"model":"{{model}}","prompt":"{{input}}"}'
338
+ }
339
+ };
340
+ var VECTOR_PROFILES = {
341
+ "pinecone-rest": {
342
+ queryPath: "/query",
343
+ upsertPath: "/vectors/upsert",
344
+ responseExtractPath: "matches",
345
+ idPath: "id",
346
+ scorePath: "score",
347
+ contentPath: "metadata.content",
348
+ metadataPath: "metadata",
349
+ queryPayloadTemplate: '{"vector":{{vector}},"topK":{{topK}},"includeMetadata":true,"namespace":"{{namespace}}"}'
350
+ },
351
+ "mongodb-atlas": {
352
+ queryPath: "/action/aggregate",
353
+ responseExtractPath: "documents",
354
+ idPath: "_id",
355
+ scorePath: "score",
356
+ contentPath: "content",
357
+ metadataPath: "metadata",
358
+ queryPayloadTemplate: '{"collection":"{{index}}","database":"ai_db","dataSource":"Cluster0","pipeline":[{"$vectorSearch":{"index":"vector_index","path":"embedding","queryVector":{{vector}},"numCandidates":100,"limit":{{topK}}}},{"$project":{"_id":1,"content":1,"metadata":1,"score":{"$meta":"vectorSearchScore"}}}]}'
359
+ },
360
+ "chromadb": {
361
+ queryPath: "/api/v1/collections/{{index}}/query",
362
+ upsertPath: "/api/v1/collections/{{index}}/add",
363
+ responseExtractPath: "matches",
364
+ idPath: "id",
365
+ scorePath: "distance",
366
+ contentPath: "document",
367
+ metadataPath: "metadata"
368
+ },
369
+ "qdrant": {
370
+ queryPath: "/collections/{{index}}/points/search",
371
+ upsertPath: "/collections/{{index}}/points",
372
+ responseExtractPath: "result",
373
+ idPath: "id",
374
+ scorePath: "score",
375
+ contentPath: "payload.content",
376
+ metadataPath: "payload"
377
+ }
378
+ };
379
+
380
+ // src/vectordb/adapters/UniversalVectorDBAdapter.ts
381
+ var UniversalVectorDBAdapter = class {
382
+ constructor(config) {
383
+ var _a, _b, _c;
384
+ this.indexName = config.indexName;
385
+ const options = (_a = config.options) != null ? _a : {};
386
+ let profile = {};
387
+ if (typeof options.profile === "string") {
388
+ profile = VECTOR_PROFILES[options.profile] || {};
389
+ } else if (typeof options.profile === "object" && options.profile !== null) {
390
+ profile = options.profile;
391
+ }
392
+ this.opts = __spreadValues(__spreadValues({}, profile), (_b = config.options) != null ? _b : {});
393
+ if (!this.opts.baseUrl) {
394
+ throw new Error("[UniversalVectorDBAdapter] options.baseUrl is required");
395
+ }
396
+ this.http = import_axios.default.create({
397
+ baseURL: this.opts.baseUrl,
398
+ headers: __spreadValues({
399
+ "Content-Type": "application/json"
400
+ }, this.opts.headers || {}),
401
+ timeout: (_c = this.opts.timeout) != null ? _c : 3e4
402
+ });
403
+ }
404
+ async initialize() {
405
+ if (this.opts.pingPath) {
406
+ const ok = await this.ping();
407
+ if (!ok) {
408
+ throw new Error(`[UniversalVectorDBAdapter] Could not reach health endpoint: ${this.opts.pingPath}`);
409
+ }
410
+ }
411
+ }
412
+ async upsert(doc, namespace) {
413
+ var _a, _b;
414
+ const path = (_a = this.opts.upsertPath) != null ? _a : "/upsert";
415
+ if (this.opts.upsertPayloadTemplate) {
416
+ const payload = buildPayload(this.opts.upsertPayloadTemplate, {
417
+ id: doc.id,
418
+ vector: doc.vector,
419
+ content: doc.content,
420
+ metadata: (_b = doc.metadata) != null ? _b : {},
421
+ namespace: namespace != null ? namespace : "",
422
+ index: this.indexName
423
+ });
424
+ await this.http.post(path, payload);
425
+ } else {
426
+ await this.http.post(path, __spreadValues({
427
+ index: this.indexName,
428
+ namespace
429
+ }, doc));
430
+ }
431
+ }
432
+ async batchUpsert(docs, namespace) {
433
+ var _a;
434
+ const path = (_a = this.opts.upsertPath) != null ? _a : "/upsert";
435
+ if (this.opts.batchUpsertPayloadTemplate) {
436
+ const payload = buildPayload(this.opts.batchUpsertPayloadTemplate, {
437
+ vectors: docs,
438
+ namespace: namespace != null ? namespace : "",
439
+ index: this.indexName
440
+ });
441
+ await this.http.post(path, payload);
442
+ } else {
443
+ await Promise.all(docs.map((doc) => this.upsert(doc, namespace)));
444
+ }
445
+ }
446
+ async query(vector, topK, namespace, filter) {
447
+ var _a, _b, _c, _d, _e, _f;
448
+ const path = (_a = this.opts.queryPath) != null ? _a : "/query";
449
+ let payload;
450
+ if (this.opts.queryPayloadTemplate) {
451
+ payload = buildPayload(this.opts.queryPayloadTemplate, {
452
+ vector,
453
+ topK,
454
+ namespace: namespace != null ? namespace : "",
455
+ index: this.indexName,
456
+ filter: filter != null ? filter : {}
457
+ });
458
+ } else {
459
+ payload = { index: this.indexName, namespace, vector, topK, filter };
460
+ }
461
+ const { data } = await this.http.post(path, payload);
462
+ const extractPath = (_b = this.opts.responseExtractPath) != null ? _b : "matches";
463
+ const matchesRaw = resolvePath(data, extractPath);
464
+ if (!Array.isArray(matchesRaw)) {
465
+ throw new Error(`[UniversalVectorDBAdapter] Expected an array at responseExtractPath '${extractPath}', but got ${typeof matchesRaw}`);
466
+ }
467
+ const idPath = (_c = this.opts.idPath) != null ? _c : "id";
468
+ const scorePath = (_d = this.opts.scorePath) != null ? _d : "score";
469
+ const contentPath = (_e = this.opts.contentPath) != null ? _e : "content";
470
+ const metadataPath = (_f = this.opts.metadataPath) != null ? _f : "metadata";
471
+ return matchesRaw.map((match) => ({
472
+ id: String(resolvePath(match, idPath) || ""),
473
+ score: Number(resolvePath(match, scorePath) || 0),
474
+ content: String(resolvePath(match, contentPath) || ""),
475
+ metadata: resolvePath(match, metadataPath) || {}
476
+ }));
477
+ }
478
+ async delete(id, namespace) {
479
+ var _a;
480
+ const path = (_a = this.opts.deletePath) != null ? _a : "/delete";
481
+ await this.http.post(path, { index: this.indexName, namespace, id });
482
+ }
483
+ async deleteNamespace(namespace) {
484
+ var _a;
485
+ const path = (_a = this.opts.deleteNamespacePath) != null ? _a : "/delete-namespace";
486
+ await this.http.post(path, { index: this.indexName, namespace });
487
+ }
488
+ async ping() {
489
+ try {
490
+ if (this.opts.pingPath) {
491
+ await this.http.get(this.opts.pingPath);
492
+ }
493
+ return true;
494
+ } catch (err) {
495
+ console.error("[UniversalVectorDBAdapter] Ping failed:", err);
496
+ return false;
497
+ }
498
+ }
499
+ async disconnect() {
500
+ }
501
+ };
502
+
503
+ // src/vectordb/adapters/MongoDbAdapter.ts
504
+ var import_mongodb = require("mongodb");
505
+ var MongoDbAdapter = class {
506
+ constructor(options) {
507
+ this.uri = options.uri;
508
+ this.dbName = options.database;
509
+ this.collectionName = options.collection;
510
+ this.indexName = options.indexName || "vector_index";
511
+ this.embeddingKey = options.embeddingKey || "embedding";
512
+ this.contentKey = options.contentKey || "content";
513
+ this.metadataKey = options.metadataKey || "metadata";
514
+ if (!this.uri || !this.dbName || !this.collectionName) {
515
+ throw new Error("MongoDbAdapter requires uri, database, and collection options.");
516
+ }
517
+ this.client = new import_mongodb.MongoClient(this.uri);
518
+ }
519
+ async initialize() {
520
+ await this.client.connect();
521
+ this.db = this.client.db(this.dbName);
522
+ this.collection = this.db.collection(this.collectionName);
523
+ }
524
+ async upsert(doc, namespace) {
525
+ if (!this.collection) await this.initialize();
526
+ const document = __spreadValues({
527
+ _id: doc.id,
528
+ [this.embeddingKey]: doc.vector,
529
+ [this.contentKey]: doc.content,
530
+ [this.metadataKey]: doc.metadata || {}
531
+ }, namespace ? { namespace } : {});
532
+ await this.collection.updateOne(
533
+ { _id: doc.id },
534
+ { $set: document },
535
+ { upsert: true }
536
+ );
537
+ }
538
+ async batchUpsert(docs, namespace) {
539
+ if (!this.collection) await this.initialize();
540
+ const operations = docs.map((doc) => ({
541
+ updateOne: {
542
+ filter: { _id: doc.id },
543
+ update: {
544
+ $set: __spreadValues({
545
+ _id: doc.id,
546
+ [this.embeddingKey]: doc.vector,
547
+ [this.contentKey]: doc.content,
548
+ [this.metadataKey]: doc.metadata || {}
549
+ }, namespace ? { namespace } : {})
550
+ },
551
+ upsert: true
552
+ }
553
+ }));
554
+ await this.collection.bulkWrite(operations);
555
+ }
556
+ async query(vector, topK, namespace, filter) {
557
+ if (!this.collection) await this.initialize();
558
+ const pipeline = [
559
+ {
560
+ $vectorSearch: __spreadValues({
561
+ index: this.indexName,
562
+ path: this.embeddingKey,
563
+ queryVector: vector,
564
+ numCandidates: Math.max(topK * 10, 100),
565
+ limit: topK
566
+ }, filter || namespace ? {
567
+ filter: __spreadValues(__spreadValues({}, filter || {}), namespace ? { namespace } : {})
568
+ } : {})
569
+ },
570
+ {
571
+ $project: {
572
+ score: { $meta: "vectorSearchScore" },
573
+ content: `$${this.contentKey}`,
574
+ metadata: `$${this.metadataKey}`
575
+ }
576
+ }
577
+ ];
578
+ const results = await this.collection.aggregate(pipeline).toArray();
579
+ return results.map((res) => ({
580
+ id: res._id.toString(),
581
+ score: res.score,
582
+ content: res.content,
583
+ metadata: res.metadata
584
+ }));
585
+ }
586
+ async delete(id, namespace) {
587
+ if (!this.collection) await this.initialize();
588
+ const query = __spreadValues({ _id: id }, namespace ? { namespace } : {});
589
+ await this.collection.deleteOne(query);
590
+ }
591
+ async deleteNamespace(namespace) {
592
+ if (!this.collection) await this.initialize();
593
+ await this.collection.deleteMany({ namespace });
594
+ }
595
+ async ping() {
596
+ try {
597
+ if (!this.collection) await this.initialize();
598
+ await this.db.command({ ping: 1 });
599
+ return true;
600
+ } catch (err) {
601
+ console.error("[MongoDbAdapter] Ping failed:", err);
602
+ return false;
603
+ }
604
+ }
605
+ async disconnect() {
606
+ try {
607
+ await this.client.close();
608
+ this.db = void 0;
609
+ this.collection = void 0;
610
+ } catch (err) {
611
+ console.error("[MongoDbAdapter] Failed to disconnect:", err);
612
+ }
613
+ }
614
+ };
615
+
616
+ // src/vectordb/VectorDBFactory.ts
617
+ var VectorDBFactory = class {
618
+ static create(config) {
619
+ var _a;
620
+ switch (config.provider) {
621
+ case "pinecone":
622
+ return new PineconeAdapter(config);
623
+ case "pgvector":
624
+ return new PgVectorAdapter(config);
625
+ case "mongodb":
626
+ return new MongoDbAdapter(config.options);
627
+ case "rest":
628
+ case "universal_rest":
629
+ case "custom":
630
+ return new UniversalVectorDBAdapter(config);
631
+ default:
632
+ if ((_a = config.options) == null ? void 0 : _a.baseUrl) {
633
+ return new UniversalVectorDBAdapter(config);
634
+ }
635
+ throw new Error(
636
+ `[VectorDBFactory] Unknown provider "${config.provider}". Supported: pinecone | pgvector | mongodb | rest`
637
+ );
638
+ }
639
+ }
640
+ };
641
+
642
+ // src/llm/providers/OpenAIProvider.ts
643
+ var import_openai = __toESM(require("openai"));
644
+ var OpenAIProvider = class {
645
+ constructor(llmConfig, embeddingConfig) {
646
+ if (!llmConfig.apiKey) throw new Error("[OpenAIProvider] llmConfig.apiKey is required");
647
+ this.client = new import_openai.default({ apiKey: llmConfig.apiKey });
648
+ this.llmConfig = llmConfig;
649
+ this.embeddingConfig = embeddingConfig;
650
+ }
651
+ async chat(messages, context, options) {
652
+ var _a, _b, _c, _d, _e, _f, _g, _h;
653
+ const systemContent = (_a = this.llmConfig.systemPrompt) != null ? _a : `You are a helpful assistant. Answer questions based on the provided context.
654
+
655
+ Context:
656
+ ${context}`;
657
+ const systemMessage = {
658
+ role: "system",
659
+ content: systemContent.includes("{{context}}") ? systemContent.replace("{{context}}", context) : `${systemContent}
660
+
661
+ Context:
662
+ ${context}`
663
+ };
664
+ const formattedMessages = [
665
+ systemMessage,
666
+ ...messages.map((m) => ({
667
+ role: m.role,
668
+ content: m.content
669
+ }))
670
+ ];
671
+ const completion = await this.client.chat.completions.create({
672
+ model: this.llmConfig.model,
673
+ messages: formattedMessages,
674
+ max_tokens: (_c = (_b = options == null ? void 0 : options.maxTokens) != null ? _b : this.llmConfig.maxTokens) != null ? _c : 1024,
675
+ temperature: (_e = (_d = options == null ? void 0 : options.temperature) != null ? _d : this.llmConfig.temperature) != null ? _e : 0.7,
676
+ stop: options == null ? void 0 : options.stop
677
+ });
678
+ return (_h = (_g = (_f = completion.choices[0]) == null ? void 0 : _f.message) == null ? void 0 : _g.content) != null ? _h : "";
679
+ }
680
+ async embed(text, options) {
681
+ const results = await this.batchEmbed([text], options);
682
+ return results[0];
683
+ }
684
+ async batchEmbed(texts, options) {
685
+ var _a, _b, _c, _d, _e;
686
+ const model = (_c = (_b = options == null ? void 0 : options.model) != null ? _b : (_a = this.embeddingConfig) == null ? void 0 : _a.model) != null ? _c : "text-embedding-3-small";
687
+ const apiKey = (_e = (_d = this.embeddingConfig) == null ? void 0 : _d.apiKey) != null ? _e : this.llmConfig.apiKey;
688
+ const client = apiKey !== this.llmConfig.apiKey ? new import_openai.default({ apiKey }) : this.client;
689
+ const response = await client.embeddings.create({ model, input: texts });
690
+ return response.data.map((d) => d.embedding);
691
+ }
692
+ async ping() {
693
+ try {
694
+ await this.client.models.list();
695
+ return true;
696
+ } catch (err) {
697
+ console.error("[OpenAIProvider] Ping failed:", err);
698
+ return false;
699
+ }
700
+ }
701
+ };
702
+
703
+ // src/llm/providers/AnthropicProvider.ts
704
+ var import_sdk = __toESM(require("@anthropic-ai/sdk"));
705
+ var AnthropicProvider = class {
706
+ constructor(llmConfig, embeddingConfig) {
707
+ if (!llmConfig.apiKey) throw new Error("[AnthropicProvider] llmConfig.apiKey is required");
708
+ this.client = new import_sdk.default({ apiKey: llmConfig.apiKey });
709
+ this.llmConfig = llmConfig;
710
+ this.embeddingConfig = embeddingConfig;
711
+ }
712
+ async chat(messages, context, options) {
713
+ var _a, _b, _c;
714
+ const systemPrompt = (_a = this.llmConfig.systemPrompt) != null ? _a : `You are a helpful assistant. Use the context below to answer the user's question accurately.
715
+
716
+ Context:
717
+ ${context}`;
718
+ const system = systemPrompt.includes("{{context}}") ? systemPrompt.replace("{{context}}", context) : `${systemPrompt}
719
+
720
+ Context:
721
+ ${context}`;
722
+ const anthropicMessages = messages.map((m) => ({
723
+ role: m.role === "assistant" ? "assistant" : "user",
724
+ content: m.content
725
+ }));
726
+ const response = await this.client.messages.create({
727
+ model: this.llmConfig.model,
728
+ max_tokens: (_c = (_b = options == null ? void 0 : options.maxTokens) != null ? _b : this.llmConfig.maxTokens) != null ? _c : 1024,
729
+ system,
730
+ messages: anthropicMessages
731
+ });
732
+ const block = response.content[0];
733
+ return block.type === "text" ? block.text : "";
734
+ }
735
+ /**
736
+ * Anthropic does not offer an embedding API.
737
+ * This method throws with a clear error so developers know to configure
738
+ * a separate embedding provider (OpenAI or Ollama).
739
+ */
740
+ async embed(text, options) {
741
+ void text;
742
+ void options;
743
+ throw new Error(
744
+ '[AnthropicProvider] Anthropic does not provide an embedding API. Set embedding.provider to "openai" or "ollama" in your RagConfig.'
745
+ );
746
+ }
747
+ async batchEmbed(texts, options) {
748
+ void texts;
749
+ void options;
750
+ throw new Error(
751
+ "[AnthropicProvider] Anthropic does not provide an embedding API."
752
+ );
753
+ }
754
+ async ping() {
755
+ try {
756
+ await this.client.models.list();
757
+ return true;
758
+ } catch (err) {
759
+ console.error("[AnthropicProvider] Ping failed:", err);
760
+ return false;
761
+ }
762
+ }
763
+ };
764
+
765
+ // src/llm/providers/OllamaProvider.ts
766
+ var import_axios2 = __toESM(require("axios"));
767
+ var OllamaProvider = class {
768
+ constructor(llmConfig, embeddingConfig) {
769
+ var _a;
770
+ const baseURL = (_a = llmConfig.baseUrl) != null ? _a : "http://localhost:11434";
771
+ this.http = import_axios2.default.create({ baseURL, timeout: 12e4 });
772
+ this.llmConfig = llmConfig;
773
+ this.embeddingConfig = embeddingConfig;
774
+ }
775
+ async chat(messages, context, options) {
776
+ var _a, _b, _c, _d, _e;
777
+ const systemPrompt = (_a = this.llmConfig.systemPrompt) != null ? _a : `You are a helpful assistant. Use the provided context to answer the user's question.
778
+
779
+ Context:
780
+ ${context}`;
781
+ const system = systemPrompt.includes("{{context}}") ? systemPrompt.replace("{{context}}", context) : `${systemPrompt}
782
+
783
+ Context:
784
+ ${context}`;
785
+ const { data } = await this.http.post("/api/chat", {
786
+ model: this.llmConfig.model,
787
+ stream: false,
788
+ options: {
789
+ temperature: (_c = (_b = options == null ? void 0 : options.temperature) != null ? _b : this.llmConfig.temperature) != null ? _c : 0.7,
790
+ num_predict: (_e = (_d = options == null ? void 0 : options.maxTokens) != null ? _d : this.llmConfig.maxTokens) != null ? _e : 1024
791
+ },
792
+ messages: [
793
+ { role: "system", content: system },
794
+ ...messages.map((m) => ({ role: m.role, content: m.content }))
795
+ ]
796
+ });
797
+ return data.message.content;
798
+ }
799
+ async embed(text, options) {
800
+ var _a, _b, _c, _d, _e, _f, _g;
801
+ const model = (_c = (_b = options == null ? void 0 : options.model) != null ? _b : (_a = this.embeddingConfig) == null ? void 0 : _a.model) != null ? _c : "nomic-embed-text";
802
+ const baseURL = (_f = (_e = (_d = this.embeddingConfig) == null ? void 0 : _d.baseUrl) != null ? _e : this.llmConfig.baseUrl) != null ? _f : "http://localhost:11434";
803
+ const client = baseURL !== ((_g = this.llmConfig.baseUrl) != null ? _g : "http://localhost:11434") ? import_axios2.default.create({ baseURL, timeout: 6e4 }) : this.http;
804
+ const { data } = await client.post("/api/embeddings", {
805
+ model,
806
+ prompt: text
807
+ });
808
+ return data.embedding;
809
+ }
810
+ async batchEmbed(texts, options) {
811
+ const vectors = [];
812
+ for (const text of texts) {
813
+ vectors.push(await this.embed(text, options));
814
+ }
815
+ return vectors;
816
+ }
817
+ async ping() {
818
+ try {
819
+ await this.http.get("/api/tags");
820
+ return true;
821
+ } catch (err) {
822
+ console.error("[OllamaProvider] Ping failed:", err);
823
+ return false;
824
+ }
825
+ }
826
+ };
827
+
828
+ // src/llm/providers/UniversalLLMAdapter.ts
829
+ var import_axios3 = __toESM(require("axios"));
830
+ var UniversalLLMAdapter = class {
831
+ constructor(config) {
832
+ var _a, _b, _c, _d, _e, _f, _g;
833
+ this.model = config.model;
834
+ const llmConfig = config;
835
+ const options = (_a = llmConfig.options) != null ? _a : {};
836
+ let profile = {};
837
+ if (typeof options.profile === "string") {
838
+ profile = LLM_PROFILES[options.profile] || {};
839
+ } else if (typeof options.profile === "object" && options.profile !== null) {
840
+ profile = options.profile;
841
+ }
842
+ this.opts = __spreadValues(__spreadValues({}, profile), (_b = llmConfig.options) != null ? _b : {});
843
+ this.systemPrompt = (_c = llmConfig.systemPrompt) != null ? _c : "You are a helpful AI assistant. Use the provided context to answer the user.";
844
+ this.maxTokens = (_d = llmConfig.maxTokens) != null ? _d : 1024;
845
+ this.temperature = (_e = llmConfig.temperature) != null ? _e : 0;
846
+ const baseUrl = (_f = llmConfig.baseUrl) != null ? _f : this.opts.baseUrl;
847
+ if (!baseUrl) {
848
+ throw new Error("[UniversalLLMAdapter] baseUrl is required in config or config.options");
849
+ }
850
+ this.http = import_axios3.default.create({
851
+ baseURL: baseUrl,
852
+ headers: __spreadValues(__spreadValues({
853
+ "Content-Type": "application/json"
854
+ }, config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}), this.opts.headers || {}),
855
+ timeout: (_g = this.opts.timeout) != null ? _g : 6e4
856
+ });
857
+ }
858
+ async chat(messages, context) {
859
+ var _a, _b;
860
+ const path = (_a = this.opts.chatPath) != null ? _a : "/chat/completions";
861
+ const formattedMessages = [
862
+ { role: "system", content: `${this.systemPrompt}
863
+
864
+ Context:
865
+ ${context != null ? context : "None"}` },
866
+ ...messages
867
+ ];
868
+ let payload;
869
+ if (this.opts.chatPayloadTemplate) {
870
+ payload = buildPayload(this.opts.chatPayloadTemplate, {
871
+ model: this.model,
872
+ messages: formattedMessages,
873
+ maxTokens: this.maxTokens,
874
+ temperature: this.temperature
875
+ });
876
+ } else {
877
+ payload = {
878
+ model: this.model,
879
+ messages: formattedMessages,
880
+ max_tokens: this.maxTokens,
881
+ temperature: this.temperature
882
+ };
883
+ }
884
+ const { data } = await this.http.post(path, payload);
885
+ const extractPath = (_b = this.opts.responseExtractPath) != null ? _b : "choices[0].message.content";
886
+ const result = resolvePath(data, extractPath);
887
+ if (result === void 0) {
888
+ throw new Error(`[UniversalLLMAdapter] Could not extract text from path '${extractPath}' in response.`);
889
+ }
890
+ return String(result);
891
+ }
892
+ async embed(text) {
893
+ var _a, _b;
894
+ const path = (_a = this.opts.embedPath) != null ? _a : "/embeddings";
895
+ let payload;
896
+ if (this.opts.embedPayloadTemplate) {
897
+ payload = buildPayload(this.opts.embedPayloadTemplate, {
898
+ model: this.model,
899
+ input: text
900
+ });
901
+ } else {
902
+ payload = {
903
+ model: this.model,
904
+ input: text
905
+ };
906
+ }
907
+ const { data } = await this.http.post(path, payload);
908
+ const extractPath = (_b = this.opts.embedExtractPath) != null ? _b : "data[0].embedding";
909
+ const vector = resolvePath(data, extractPath);
910
+ if (!Array.isArray(vector)) {
911
+ throw new Error(`[UniversalLLMAdapter] Expected a number array at '${extractPath}' for embeddings.`);
912
+ }
913
+ return vector;
914
+ }
915
+ async batchEmbed(texts) {
916
+ const vectors = [];
917
+ for (const text of texts) {
918
+ vectors.push(await this.embed(text));
919
+ }
920
+ return vectors;
921
+ }
922
+ async ping() {
923
+ try {
924
+ if (this.opts.pingPath) {
925
+ await this.http.get(this.opts.pingPath);
926
+ }
927
+ return true;
928
+ } catch (err) {
929
+ console.error("[UniversalLLMAdapter] Ping failed:", err);
930
+ return false;
931
+ }
932
+ }
933
+ };
934
+
935
+ // src/llm/LLMFactory.ts
936
+ var LLMFactory = class _LLMFactory {
937
+ static create(llmConfig, embeddingConfig) {
938
+ var _a;
939
+ switch (llmConfig.provider) {
940
+ case "openai":
941
+ return new OpenAIProvider(llmConfig, embeddingConfig);
942
+ case "anthropic":
943
+ return new AnthropicProvider(llmConfig, embeddingConfig);
944
+ case "ollama":
945
+ return new OllamaProvider(llmConfig, embeddingConfig);
946
+ case "rest":
947
+ case "universal_rest":
948
+ case "custom":
949
+ return new UniversalLLMAdapter(llmConfig);
950
+ default:
951
+ if (llmConfig.baseUrl || ((_a = llmConfig.options) == null ? void 0 : _a.baseUrl)) {
952
+ return new UniversalLLMAdapter(llmConfig);
953
+ }
954
+ throw new Error(
955
+ `[LLMFactory] Unknown provider "${llmConfig.provider}". Supported: openai | anthropic | ollama | rest | custom`
956
+ );
957
+ }
958
+ }
959
+ /**
960
+ * Creates a dedicated embedding-only provider.
961
+ * Useful when the LLM provider (e.g. Anthropic) doesn't support embeddings.
962
+ */
963
+ static createEmbeddingProvider(embeddingConfig) {
964
+ const fakeLLMConfig = {
965
+ provider: embeddingConfig.provider,
966
+ model: embeddingConfig.model,
967
+ apiKey: embeddingConfig.apiKey,
968
+ baseUrl: embeddingConfig.baseUrl,
969
+ options: embeddingConfig.options
970
+ };
971
+ return _LLMFactory.create(fakeLLMConfig, embeddingConfig);
972
+ }
973
+ };
974
+
975
+ // src/rag/DocumentChunker.ts
976
+ var DocumentChunker = class {
977
+ constructor(chunkSize = 1e3, chunkOverlap = 200) {
978
+ this.chunkSize = chunkSize;
979
+ this.chunkOverlap = chunkOverlap;
980
+ }
981
+ /**
982
+ * Split a single text string into overlapping chunks.
983
+ */
984
+ chunk(text, options = {}) {
985
+ const {
986
+ chunkSize = this.chunkSize,
987
+ chunkOverlap = this.chunkOverlap,
988
+ docId = `doc_${Date.now()}`,
989
+ metadata = {}
990
+ } = options;
991
+ const cleaned = text.replace(/\r\n/g, "\n").trim();
992
+ if (!cleaned) return [];
993
+ const sentences = cleaned.split(new RegExp("(?<=[.!?])\\s+|\\n{2,}")).map((s) => s.trim()).filter(Boolean);
994
+ const chunks = [];
995
+ let current = "";
996
+ let chunkIndex = 0;
997
+ for (const sentence of sentences) {
998
+ if ((current + " " + sentence).trim().length <= chunkSize) {
999
+ current = current ? `${current} ${sentence}` : sentence;
1000
+ } else {
1001
+ if (current) {
1002
+ chunks.push({
1003
+ id: `${docId}_chunk_${chunkIndex++}`,
1004
+ content: current.trim(),
1005
+ metadata: __spreadProps(__spreadValues({}, metadata), { docId, chunkIndex: chunkIndex - 1 })
1006
+ });
1007
+ }
1008
+ if (chunkOverlap > 0 && current.length > chunkOverlap) {
1009
+ current = current.slice(-chunkOverlap) + " " + sentence;
1010
+ } else {
1011
+ current = sentence;
1012
+ }
1013
+ }
1014
+ }
1015
+ if (current.trim()) {
1016
+ chunks.push({
1017
+ id: `${docId}_chunk_${chunkIndex}`,
1018
+ content: current.trim(),
1019
+ metadata: __spreadProps(__spreadValues({}, metadata), { docId, chunkIndex })
1020
+ });
1021
+ }
1022
+ return chunks;
1023
+ }
1024
+ /**
1025
+ * Chunk multiple documents at once.
1026
+ */
1027
+ chunkMany(documents) {
1028
+ return documents.flatMap(
1029
+ (doc) => this.chunk(doc.content, { docId: doc.docId, metadata: doc.metadata })
1030
+ );
1031
+ }
1032
+ };
1033
+
1034
+ // src/rag/RAGPipeline.ts
1035
+ var RAGPipeline = class {
1036
+ constructor(config, adapters) {
1037
+ this.initialised = false;
1038
+ var _a, _b, _c, _d, _e, _f;
1039
+ this.config = config;
1040
+ this.vectorDB = (_a = adapters == null ? void 0 : adapters.vectorDB) != null ? _a : VectorDBFactory.create(config.vectorDb);
1041
+ this.llmProvider = (_b = adapters == null ? void 0 : adapters.llmProvider) != null ? _b : LLMFactory.create(config.llm, config.embedding);
1042
+ if (adapters == null ? void 0 : adapters.embeddingProvider) {
1043
+ this.embeddingProvider = adapters.embeddingProvider;
1044
+ } else if (config.llm.provider === "anthropic") {
1045
+ this.embeddingProvider = LLMFactory.createEmbeddingProvider(config.embedding);
1046
+ } else {
1047
+ this.embeddingProvider = this.llmProvider;
1048
+ }
1049
+ this.chunker = new DocumentChunker(
1050
+ (_d = (_c = config.rag) == null ? void 0 : _c.chunkSize) != null ? _d : 1e3,
1051
+ (_f = (_e = config.rag) == null ? void 0 : _e.chunkOverlap) != null ? _f : 200
1052
+ );
1053
+ }
1054
+ /** Lazily initialise the vector DB connection */
1055
+ async init() {
1056
+ if (!this.initialised) {
1057
+ await this.vectorDB.initialize();
1058
+ this.initialised = true;
1059
+ }
1060
+ }
1061
+ // ---------------------------------------------------------------------------
1062
+ // INGEST
1063
+ // ---------------------------------------------------------------------------
1064
+ /**
1065
+ * Ingest one or more documents into the vector DB.
1066
+ * Automatically chunks, embeds, and upserts each chunk.
1067
+ */
1068
+ async ingest(documents, namespace) {
1069
+ await this.init();
1070
+ const ns = namespace != null ? namespace : this.config.projectId;
1071
+ const results = [];
1072
+ for (const doc of documents) {
1073
+ const chunks = this.chunker.chunk(doc.content, {
1074
+ docId: doc.docId,
1075
+ metadata: doc.metadata
1076
+ });
1077
+ const chunkTexts = chunks.map((c) => c.content);
1078
+ const vectors = await this.embeddingProvider.batchEmbed(chunkTexts);
1079
+ const upsertDocs = chunks.map((chunk, i) => ({
1080
+ id: chunk.id,
1081
+ vector: vectors[i],
1082
+ content: chunk.content,
1083
+ metadata: chunk.metadata
1084
+ }));
1085
+ await this.vectorDB.batchUpsert(upsertDocs, ns);
1086
+ results.push({ docId: doc.docId, chunksIngested: chunks.length });
1087
+ console.log(`[RAGPipeline] Ingested ${chunks.length} chunks for doc: ${doc.docId}`);
1088
+ }
1089
+ return results;
1090
+ }
1091
+ // ---------------------------------------------------------------------------
1092
+ // ASK
1093
+ // ---------------------------------------------------------------------------
1094
+ /**
1095
+ * Run a full RAG query:
1096
+ * 1. Embed the user question
1097
+ * 2. Retrieve top-K relevant chunks from the vector DB
1098
+ * 3. Filter by score threshold
1099
+ * 4. Build context string
1100
+ * 5. Call the LLM with chat history + context
1101
+ */
1102
+ async ask(question, history = [], namespace) {
1103
+ var _a, _b, _c, _d;
1104
+ await this.init();
1105
+ const ns = namespace != null ? namespace : this.config.projectId;
1106
+ const topK = (_b = (_a = this.config.rag) == null ? void 0 : _a.topK) != null ? _b : 5;
1107
+ const scoreThreshold = (_d = (_c = this.config.rag) == null ? void 0 : _c.scoreThreshold) != null ? _d : 0;
1108
+ const queryVector = await this.embeddingProvider.embed(question);
1109
+ const rawMatches = await this.vectorDB.query(queryVector, topK, ns);
1110
+ const sources = rawMatches.filter((m) => m.score >= scoreThreshold);
1111
+ const context = sources.length ? sources.map((m, i) => `[Source ${i + 1}]
1112
+ ${m.content}`).join("\n\n---\n\n") : "No relevant context found.";
1113
+ const messages = [
1114
+ ...history,
1115
+ { role: "user", content: question }
1116
+ ];
1117
+ const reply = await this.llmProvider.chat(messages, context);
1118
+ return { reply, sources };
1119
+ }
1120
+ // ---------------------------------------------------------------------------
1121
+ // HEALTH
1122
+ // ---------------------------------------------------------------------------
1123
+ async health() {
1124
+ const [vectorDB, llm] = await Promise.all([
1125
+ this.vectorDB.ping().catch(() => false),
1126
+ this.llmProvider.ping().catch(() => false)
1127
+ ]);
1128
+ return { vectorDB, llm };
1129
+ }
1130
+ // ---------------------------------------------------------------------------
1131
+ // DATA MANAGEMENT
1132
+ // ---------------------------------------------------------------------------
1133
+ async deleteDocument(docId, namespace) {
1134
+ await this.init();
1135
+ const ns = namespace != null ? namespace : this.config.projectId;
1136
+ await this.vectorDB.delete(docId, ns);
1137
+ }
1138
+ async deleteProject(namespace) {
1139
+ await this.init();
1140
+ const ns = namespace != null ? namespace : this.config.projectId;
1141
+ await this.vectorDB.deleteNamespace(ns);
1142
+ }
1143
+ };
1144
+
1145
+ // src/config/serverConfig.ts
1146
+ var VECTOR_DB_PROVIDERS = ["pinecone", "pgvector", "mongodb", "rest", "universal_rest", "custom"];
1147
+ var LLM_PROVIDERS = ["openai", "anthropic", "ollama", "rest", "universal_rest", "custom"];
1148
+ var EMBEDDING_PROVIDERS = ["openai", "ollama", "rest", "universal_rest", "custom"];
1149
+ function readString(env, name) {
1150
+ var _a;
1151
+ const value = (_a = env[name]) == null ? void 0 : _a.trim();
1152
+ return value ? value : void 0;
1153
+ }
1154
+ function readNumber(env, name, fallback) {
1155
+ const value = env[name];
1156
+ if (!value) return fallback;
1157
+ const parsed = Number(value);
1158
+ if (!Number.isFinite(parsed)) {
1159
+ throw new Error(`[getRagConfig] ${name} must be a valid number`);
1160
+ }
1161
+ return parsed;
1162
+ }
1163
+ function readEnum(env, name, fallback, allowed) {
1164
+ var _a;
1165
+ const value = (_a = readString(env, name)) != null ? _a : fallback;
1166
+ if (allowed.includes(value)) {
1167
+ return value;
1168
+ }
1169
+ throw new Error(`[getRagConfig] ${name} must be one of: ${allowed.join(", ")}`);
1170
+ }
1171
+ function getRagConfig(env = process.env) {
1172
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J;
1173
+ const projectId = (_b = (_a = readString(env, "RAG_PROJECT_ID")) != null ? _a : readString(env, "NEXT_PUBLIC_PROJECT_ID")) != null ? _b : "default";
1174
+ const vectorProvider = readEnum(env, "VECTOR_DB_PROVIDER", "pinecone", VECTOR_DB_PROVIDERS);
1175
+ const llmProvider = readEnum(env, "LLM_PROVIDER", "openai", LLM_PROVIDERS);
1176
+ const embeddingProvider = readEnum(env, "EMBEDDING_PROVIDER", "openai", EMBEDDING_PROVIDERS);
1177
+ const embeddingDimensions = readNumber(env, "EMBEDDING_DIMENSIONS", 1536);
1178
+ const vectorDbOptions = {};
1179
+ if (vectorProvider === "pinecone") {
1180
+ vectorDbOptions.apiKey = (_c = readString(env, "PINECONE_API_KEY")) != null ? _c : "";
1181
+ vectorDbOptions.environment = (_d = readString(env, "PINECONE_ENVIRONMENT")) != null ? _d : "";
1182
+ } else if (vectorProvider === "pgvector") {
1183
+ vectorDbOptions.connectionString = (_e = readString(env, "PGVECTOR_CONNECTION_STRING")) != null ? _e : "";
1184
+ vectorDbOptions.dimensions = embeddingDimensions;
1185
+ } else if (vectorProvider === "rest") {
1186
+ vectorDbOptions.baseUrl = (_f = readString(env, "VECTOR_DB_REST_URL")) != null ? _f : "";
1187
+ vectorDbOptions.headers = readString(env, "VECTOR_DB_REST_API_KEY") ? { "api-key": readString(env, "VECTOR_DB_REST_API_KEY") } : {};
1188
+ } else if (vectorProvider === "universal_rest") {
1189
+ vectorDbOptions.baseUrl = (_h = (_g = readString(env, "VECTOR_BASE_URL")) != null ? _g : readString(env, "VECTOR_DB_REST_URL")) != null ? _h : "";
1190
+ vectorDbOptions.profile = readString(env, "VECTOR_UNIVERSAL_PROFILE");
1191
+ vectorDbOptions.headers = readString(env, "VECTOR_DB_REST_API_KEY") ? { Authorization: `Bearer ${readString(env, "VECTOR_DB_REST_API_KEY")}` } : {};
1192
+ } else if (vectorProvider === "mongodb") {
1193
+ vectorDbOptions.uri = (_i = readString(env, "MONGODB_URI")) != null ? _i : "";
1194
+ vectorDbOptions.database = (_j = readString(env, "MONGODB_DB")) != null ? _j : "";
1195
+ vectorDbOptions.collection = (_k = readString(env, "MONGODB_COLLECTION")) != null ? _k : "";
1196
+ vectorDbOptions.indexName = (_l = readString(env, "MONGODB_INDEX_NAME")) != null ? _l : "vector_index";
1197
+ }
1198
+ const llmApiKeyByProvider = {
1199
+ openai: readString(env, "OPENAI_API_KEY"),
1200
+ anthropic: readString(env, "ANTHROPIC_API_KEY"),
1201
+ ollama: void 0,
1202
+ universal_rest: readString(env, "LLM_API_KEY")
1203
+ };
1204
+ const embeddingApiKeyByProvider = {
1205
+ openai: readString(env, "OPENAI_API_KEY"),
1206
+ ollama: void 0,
1207
+ custom: (_m = readString(env, "EMBEDDING_API_KEY")) != null ? _m : readString(env, "OPENAI_API_KEY")
1208
+ };
1209
+ return {
1210
+ projectId,
1211
+ vectorDb: {
1212
+ provider: vectorProvider,
1213
+ indexName: (_n = readString(env, "VECTOR_DB_INDEX")) != null ? _n : "rag-index",
1214
+ options: vectorDbOptions
1215
+ },
1216
+ llm: {
1217
+ provider: llmProvider,
1218
+ model: (_o = readString(env, "LLM_MODEL")) != null ? _o : "gpt-4o",
1219
+ apiKey: (_p = llmApiKeyByProvider[llmProvider]) != null ? _p : "",
1220
+ baseUrl: readString(env, "LLM_BASE_URL"),
1221
+ systemPrompt: readString(env, "LLM_SYSTEM_PROMPT"),
1222
+ maxTokens: readNumber(env, "LLM_MAX_TOKENS", 1024),
1223
+ temperature: readNumber(env, "LLM_TEMPERATURE", 0.7),
1224
+ options: {
1225
+ profile: readString(env, "LLM_UNIVERSAL_PROFILE")
1226
+ }
1227
+ },
1228
+ embedding: {
1229
+ provider: embeddingProvider,
1230
+ model: (_q = readString(env, "EMBEDDING_MODEL")) != null ? _q : "text-embedding-3-small",
1231
+ apiKey: embeddingApiKeyByProvider[embeddingProvider],
1232
+ baseUrl: readString(env, "EMBEDDING_BASE_URL"),
1233
+ dimensions: embeddingDimensions,
1234
+ options: {
1235
+ profile: readString(env, "EMBEDDING_UNIVERSAL_PROFILE")
1236
+ }
1237
+ },
1238
+ ui: {
1239
+ title: (_s = (_r = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _r : readString(env, "UI_TITLE")) != null ? _s : "AI Assistant",
1240
+ subtitle: (_u = (_t = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _t : readString(env, "UI_SUBTITLE")) != null ? _u : "Powered by RAG",
1241
+ primaryColor: (_w = (_v = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _v : readString(env, "UI_PRIMARY_COLOR")) != null ? _w : "#10b981",
1242
+ accentColor: (_y = (_x = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _x : readString(env, "UI_ACCENT_COLOR")) != null ? _y : "#3b82f6",
1243
+ logoUrl: (_z = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _z : readString(env, "UI_LOGO_URL"),
1244
+ placeholder: (_B = (_A = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _A : readString(env, "UI_PLACEHOLDER")) != null ? _B : "Ask me anything\u2026",
1245
+ showSources: ((_D = (_C = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _C : readString(env, "UI_SHOW_SOURCES")) != null ? _D : "true") !== "false",
1246
+ welcomeMessage: (_F = (_E = readString(env, "NEXT_PUBLIC_WELCOME_MESSAGE")) != null ? _E : readString(env, "UI_WELCOME_MESSAGE")) != null ? _F : "Hello! I'm your AI assistant. Ask me anything about your documents.",
1247
+ visualStyle: (_H = (_G = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _G : readString(env, "UI_VISUAL_STYLE")) != null ? _H : "glass",
1248
+ borderRadius: (_J = (_I = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _I : readString(env, "UI_BORDER_RADIUS")) != null ? _J : "xl"
1249
+ },
1250
+ rag: {
1251
+ topK: readNumber(env, "RAG_TOP_K", 5),
1252
+ scoreThreshold: readNumber(env, "RAG_SCORE_THRESHOLD", 0),
1253
+ chunkSize: readNumber(env, "RAG_CHUNK_SIZE", 1e3),
1254
+ chunkOverlap: readNumber(env, "RAG_CHUNK_OVERLAP", 200)
1255
+ }
1256
+ };
1257
+ }
1258
+
1259
+ // src/handlers/index.ts
1260
+ var import_server = require("next/server");
1261
+
1262
+ // src/utils/DocumentParser.ts
1263
+ var DocumentParser = class {
1264
+ /**
1265
+ * Extract text from a File or Buffer based on its type.
1266
+ */
1267
+ static async parse(file, fileName, mimeType) {
1268
+ var _a;
1269
+ const extension = (_a = fileName.split(".").pop()) == null ? void 0 : _a.toLowerCase();
1270
+ if (extension === "txt" || extension === "md" || mimeType === "text/plain" || mimeType === "text/markdown") {
1271
+ return this.readAsText(file);
1272
+ }
1273
+ if (extension === "json" || mimeType === "application/json") {
1274
+ const text = await this.readAsText(file);
1275
+ try {
1276
+ const obj = JSON.parse(text);
1277
+ return JSON.stringify(obj, null, 2);
1278
+ } catch (e) {
1279
+ return text;
1280
+ }
1281
+ }
1282
+ if (extension === "csv" || mimeType === "text/csv") {
1283
+ return this.readAsText(file);
1284
+ }
1285
+ if (extension === "pdf" || mimeType === "application/pdf") {
1286
+ try {
1287
+ const pdf = await import("pdf-parse/lib/pdf-parse.js");
1288
+ const buffer = Buffer.isBuffer(file) ? file : Buffer.from(await file.arrayBuffer());
1289
+ const data = await pdf.default(buffer);
1290
+ return data.text;
1291
+ } catch (err) {
1292
+ console.warn('[DocumentParser] PDF parsing failed. Make sure "pdf-parse" is installed.', err);
1293
+ return `[PDF Parsing Error for ${fileName}]`;
1294
+ }
1295
+ }
1296
+ if (extension === "docx" || mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
1297
+ try {
1298
+ const mammoth = await import("mammoth");
1299
+ const buffer = Buffer.isBuffer(file) ? file : Buffer.from(await file.arrayBuffer());
1300
+ const result = await mammoth.extractRawText({ buffer });
1301
+ return result.value;
1302
+ } catch (err) {
1303
+ console.warn('[DocumentParser] DOCX parsing failed. Make sure "mammoth" is installed.', err);
1304
+ return `[DOCX Parsing Error for ${fileName}]`;
1305
+ }
1306
+ }
1307
+ try {
1308
+ return await this.readAsText(file);
1309
+ } catch (e) {
1310
+ throw new Error(`[DocumentParser] Unsupported file format: ${fileName} (${mimeType})`);
1311
+ }
1312
+ }
1313
+ static async readAsText(file) {
1314
+ if (Buffer.isBuffer(file)) {
1315
+ return file.toString("utf-8");
1316
+ }
1317
+ return await file.text();
1318
+ }
1319
+ };
1320
+
1321
+ // src/handlers/index.ts
1322
+ function createChatHandler(config, adapters) {
1323
+ let pipeline = null;
1324
+ function getPipeline() {
1325
+ if (!pipeline) pipeline = new RAGPipeline(config, adapters);
1326
+ return pipeline;
1327
+ }
1328
+ return async function POST(req) {
1329
+ try {
1330
+ const body = await req.json();
1331
+ const { message, history = [], namespace } = body;
1332
+ if (!(message == null ? void 0 : message.trim())) {
1333
+ return import_server.NextResponse.json({ error: "message is required" }, { status: 400 });
1334
+ }
1335
+ const rag = getPipeline();
1336
+ const result = await rag.ask(message, history, namespace);
1337
+ return import_server.NextResponse.json(result);
1338
+ } catch (err) {
1339
+ const message = err instanceof Error ? err.message : "Internal server error";
1340
+ return import_server.NextResponse.json({ error: message }, { status: 500 });
1341
+ }
1342
+ };
1343
+ }
1344
+ function createIngestHandler(config, adapters) {
1345
+ let pipeline = null;
1346
+ function getPipeline() {
1347
+ if (!pipeline) pipeline = new RAGPipeline(config, adapters);
1348
+ return pipeline;
1349
+ }
1350
+ return async function POST(req) {
1351
+ try {
1352
+ const body = await req.json();
1353
+ const { documents, namespace } = body;
1354
+ if (!Array.isArray(documents) || documents.length === 0) {
1355
+ return import_server.NextResponse.json(
1356
+ { error: "documents array is required and must not be empty" },
1357
+ { status: 400 }
1358
+ );
1359
+ }
1360
+ const rag = getPipeline();
1361
+ const results = await rag.ingest(documents, namespace);
1362
+ const totalChunks = results.reduce((sum, r) => sum + r.chunksIngested, 0);
1363
+ return import_server.NextResponse.json({ results, totalChunks });
1364
+ } catch (err) {
1365
+ const message = err instanceof Error ? err.message : "Internal server error";
1366
+ return import_server.NextResponse.json({ error: message }, { status: 500 });
1367
+ }
1368
+ };
1369
+ }
1370
+ function createHealthHandler(config, adapters) {
1371
+ let pipeline = null;
1372
+ function getPipeline() {
1373
+ if (!pipeline) pipeline = new RAGPipeline(config, adapters);
1374
+ return pipeline;
1375
+ }
1376
+ return async function GET() {
1377
+ try {
1378
+ const rag = getPipeline();
1379
+ const health = await rag.health();
1380
+ const status = health.vectorDB && health.llm ? "ok" : "degraded";
1381
+ return import_server.NextResponse.json(__spreadProps(__spreadValues({
1382
+ status
1383
+ }, health), {
1384
+ project: config.projectId,
1385
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1386
+ }));
1387
+ } catch (err) {
1388
+ const message = err instanceof Error ? err.message : "Unknown error";
1389
+ return import_server.NextResponse.json(
1390
+ { status: "error", error: message, timestamp: (/* @__PURE__ */ new Date()).toISOString() },
1391
+ { status: 500 }
1392
+ );
1393
+ }
1394
+ };
1395
+ }
1396
+ function createUploadHandler(config, adapters) {
1397
+ let pipeline = null;
1398
+ function getPipeline() {
1399
+ if (!pipeline) pipeline = new RAGPipeline(config, adapters);
1400
+ return pipeline;
1401
+ }
1402
+ return async function POST(req) {
1403
+ try {
1404
+ const formData = await req.formData();
1405
+ const files = formData.getAll("files");
1406
+ const namespace = formData.get("namespace") || void 0;
1407
+ if (!files || files.length === 0) {
1408
+ return import_server.NextResponse.json({ error: "No files provided" }, { status: 400 });
1409
+ }
1410
+ const documents = await Promise.all(
1411
+ files.map(async (file) => {
1412
+ const content = await DocumentParser.parse(file, file.name, file.type);
1413
+ return {
1414
+ docId: file.name,
1415
+ content,
1416
+ metadata: {
1417
+ fileName: file.name,
1418
+ fileSize: file.size,
1419
+ fileType: file.type,
1420
+ uploadedAt: (/* @__PURE__ */ new Date()).toISOString()
1421
+ }
1422
+ };
1423
+ })
1424
+ );
1425
+ const rag = getPipeline();
1426
+ const results = await rag.ingest(documents, namespace);
1427
+ const totalChunks = results.reduce((sum, r) => sum + r.chunksIngested, 0);
1428
+ return import_server.NextResponse.json({
1429
+ message: "Upload successful",
1430
+ filesProcessed: files.length,
1431
+ totalChunks,
1432
+ results
1433
+ });
1434
+ } catch (err) {
1435
+ const message = err instanceof Error ? err.message : "Upload failed";
1436
+ return import_server.NextResponse.json({ error: message }, { status: 500 });
1437
+ }
1438
+ };
1439
+ }
1440
+ // Annotate the CommonJS export names for ESM import in node:
1441
+ 0 && (module.exports = {
1442
+ AnthropicProvider,
1443
+ DocumentChunker,
1444
+ LLMFactory,
1445
+ MongoDbAdapter,
1446
+ OllamaProvider,
1447
+ OpenAIProvider,
1448
+ PgVectorAdapter,
1449
+ PineconeAdapter,
1450
+ RAGPipeline,
1451
+ VectorDBFactory,
1452
+ createChatHandler,
1453
+ createHealthHandler,
1454
+ createIngestHandler,
1455
+ createUploadHandler,
1456
+ getRagConfig
1457
+ });