@retrivora-ai/rag-engine 0.1.3 → 0.1.5
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/ChromaDBProvider-QNI7UCX4.mjs +8 -0
- package/dist/DocumentChunker-cfaMidtA.d.mts +93 -0
- package/dist/DocumentChunker-cfaMidtA.d.ts +93 -0
- package/dist/LLMFactory-JFOY2V4X.mjs +8 -0
- package/dist/MilvusProvider-OO6QGZDZ.mjs +8 -0
- package/dist/MongoDBProvider-WWVJG3WT.mjs +8 -0
- package/dist/PineconeProvider-NJ675H7U.mjs +8 -0
- package/dist/PostgreSQLProvider-ISNMD3BE.mjs +8 -0
- package/dist/QdrantProvider-LJWOIGES.mjs +8 -0
- package/dist/RagConfig-DG_0f8ka.d.mts +145 -0
- package/dist/RagConfig-DG_0f8ka.d.ts +145 -0
- package/dist/RedisProvider-ASONNYBI.mjs +8 -0
- package/dist/WeaviateProvider-PSDCUGC7.mjs +8 -0
- package/dist/chunk-6FODXNUF.mjs +91 -0
- package/dist/chunk-7NXI6ZWX.mjs +89 -0
- package/dist/chunk-AALIF3AL.mjs +91 -0
- package/dist/chunk-BP4U4TT5.mjs +548 -0
- package/dist/chunk-HUGLYKD6.mjs +84 -0
- package/dist/chunk-I4E63NIC.mjs +24 -0
- package/dist/chunk-JI6VD5TJ.mjs +387 -0
- package/dist/chunk-QEYVWVT5.mjs +102 -0
- package/dist/chunk-S5DRHETN.mjs +110 -0
- package/dist/{chunk-ZPXLQR5Q.mjs → chunk-UKDXCXW7.mjs} +5 -23
- package/dist/chunk-V75V7BT2.mjs +117 -0
- package/dist/chunk-VOIWNO5O.mjs +11 -0
- package/dist/chunk-VPNRDXIA.mjs +74 -0
- package/dist/handlers/index.d.mts +9 -33
- package/dist/handlers/index.d.ts +9 -33
- package/dist/handlers/index.js +1477 -962
- package/dist/handlers/index.mjs +4 -2
- package/dist/index.d.mts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -2
- package/dist/index.mjs +4 -2
- package/dist/server.d.mts +220 -53
- package/dist/server.d.ts +220 -53
- package/dist/server.js +1531 -1099
- package/dist/server.mjs +55 -131
- package/package.json +19 -2
- package/src/app/page.tsx +1 -1
- package/src/components/MessageBubble.tsx +1 -1
- package/src/components/SourceCard.tsx +1 -1
- package/src/config/RagConfig.ts +1 -1
- package/src/config/serverConfig.ts +2 -2
- package/src/core/ConfigResolver.ts +69 -0
- package/src/core/Pipeline.ts +101 -0
- package/src/core/ProviderRegistry.ts +71 -0
- package/src/core/VectorPlugin.ts +52 -0
- package/src/handlers/index.ts +21 -100
- package/src/hooks/useRagChat.ts +1 -1
- package/src/index.ts +2 -6
- package/src/providers/vectordb/BaseVectorProvider.ts +61 -0
- package/src/providers/vectordb/ChromaDBProvider.ts +94 -0
- package/src/providers/vectordb/MilvusProvider.ts +100 -0
- package/src/providers/vectordb/MongoDBProvider.ts +118 -0
- package/src/{vectordb/adapters/PineconeAdapter.ts → providers/vectordb/PineconeProvider.ts} +21 -56
- package/src/{vectordb/adapters/PgVectorAdapter.ts → providers/vectordb/PostgreSQLProvider.ts} +23 -58
- package/src/providers/vectordb/QdrantProvider.ts +95 -0
- package/src/providers/vectordb/RedisProvider.ts +84 -0
- package/src/providers/vectordb/WeaviateProvider.ts +124 -0
- package/src/server.ts +16 -8
- package/src/test-refactor.ts +59 -0
- package/src/types/index.ts +24 -0
- package/src/utils/templateUtils.ts +6 -6
- package/dist/DocumentChunker-BUrIrcPk.d.mts +0 -43
- package/dist/DocumentChunker-BUrIrcPk.d.ts +0 -43
- package/dist/RAGPipeline-BmkIv1HD.d.mts +0 -298
- package/dist/RAGPipeline-BmkIv1HD.d.ts +0 -298
- package/dist/chunk-NVOMLHXW.mjs +0 -1259
- package/src/rag/RAGPipeline.ts +0 -200
- package/src/vectordb/IVectorDB.ts +0 -75
- package/src/vectordb/VectorDBFactory.ts +0 -41
- package/src/vectordb/adapters/MongoDbAdapter.ts +0 -175
- package/src/vectordb/adapters/UniversalVectorDBAdapter.ts +0 -177
package/dist/chunk-NVOMLHXW.mjs
DELETED
|
@@ -1,1259 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
__spreadProps,
|
|
3
|
-
__spreadValues,
|
|
4
|
-
buildPayload,
|
|
5
|
-
resolvePath
|
|
6
|
-
} from "./chunk-ZPXLQR5Q.mjs";
|
|
7
|
-
|
|
8
|
-
// src/handlers/index.ts
|
|
9
|
-
import { NextResponse } from "next/server";
|
|
10
|
-
|
|
11
|
-
// src/vectordb/adapters/PineconeAdapter.ts
|
|
12
|
-
import { Pinecone } from "@pinecone-database/pinecone";
|
|
13
|
-
var PineconeAdapter = class {
|
|
14
|
-
constructor(config) {
|
|
15
|
-
this.indexName = config.indexName;
|
|
16
|
-
const opts = config.options;
|
|
17
|
-
if (!opts.apiKey) throw new Error("[PineconeAdapter] options.apiKey is required");
|
|
18
|
-
this.apiKey = opts.apiKey;
|
|
19
|
-
}
|
|
20
|
-
async initialize() {
|
|
21
|
-
var _a, _b;
|
|
22
|
-
this.client = new Pinecone({ apiKey: this.apiKey });
|
|
23
|
-
const indexes = await this.client.listIndexes();
|
|
24
|
-
const names = (_b = (_a = indexes.indexes) == null ? void 0 : _a.map((i) => i.name)) != null ? _b : [];
|
|
25
|
-
if (!names.includes(this.indexName)) {
|
|
26
|
-
throw new Error(
|
|
27
|
-
`[PineconeAdapter] Index "${this.indexName}" not found. Available: ${names.join(", ")}`
|
|
28
|
-
);
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
index(namespace) {
|
|
32
|
-
const idx = this.client.index(this.indexName);
|
|
33
|
-
return namespace ? idx.namespace(namespace) : idx.namespace("");
|
|
34
|
-
}
|
|
35
|
-
async upsert(doc, namespace) {
|
|
36
|
-
var _a;
|
|
37
|
-
await this.index(namespace).upsert({
|
|
38
|
-
records: [
|
|
39
|
-
{
|
|
40
|
-
id: doc.id,
|
|
41
|
-
values: doc.vector,
|
|
42
|
-
metadata: __spreadValues({
|
|
43
|
-
content: doc.content
|
|
44
|
-
}, (_a = doc.metadata) != null ? _a : {})
|
|
45
|
-
}
|
|
46
|
-
]
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
async batchUpsert(docs, namespace) {
|
|
50
|
-
const BATCH = 100;
|
|
51
|
-
for (let i = 0; i < docs.length; i += BATCH) {
|
|
52
|
-
const records = docs.slice(i, i + BATCH).map((d) => {
|
|
53
|
-
var _a;
|
|
54
|
-
return {
|
|
55
|
-
id: d.id,
|
|
56
|
-
values: d.vector,
|
|
57
|
-
metadata: __spreadValues({
|
|
58
|
-
content: d.content
|
|
59
|
-
}, (_a = d.metadata) != null ? _a : {})
|
|
60
|
-
};
|
|
61
|
-
});
|
|
62
|
-
await this.index(namespace).upsert({ records });
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
async query(vector, topK, namespace, filter) {
|
|
66
|
-
var _a;
|
|
67
|
-
const result = await this.index(namespace).query(__spreadValues({
|
|
68
|
-
vector,
|
|
69
|
-
topK,
|
|
70
|
-
includeMetadata: true
|
|
71
|
-
}, filter ? { filter } : {}));
|
|
72
|
-
return ((_a = result.matches) != null ? _a : []).map((m) => {
|
|
73
|
-
var _a2;
|
|
74
|
-
const metadata = m.metadata;
|
|
75
|
-
const content = (metadata == null ? void 0 : metadata.content) || (metadata == null ? void 0 : metadata.text) || (metadata == null ? void 0 : metadata.body) || (metadata == null ? void 0 : metadata.description) || "";
|
|
76
|
-
return {
|
|
77
|
-
id: m.id,
|
|
78
|
-
score: (_a2 = m.score) != null ? _a2 : 0,
|
|
79
|
-
content,
|
|
80
|
-
metadata
|
|
81
|
-
};
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
async delete(id, namespace) {
|
|
85
|
-
await this.index(namespace).deleteOne({ id });
|
|
86
|
-
}
|
|
87
|
-
async deleteNamespace(namespace) {
|
|
88
|
-
await this.client.index(this.indexName).namespace(namespace).deleteAll();
|
|
89
|
-
}
|
|
90
|
-
async ping() {
|
|
91
|
-
try {
|
|
92
|
-
await this.client.listIndexes();
|
|
93
|
-
return true;
|
|
94
|
-
} catch (err) {
|
|
95
|
-
console.error("[PineconeAdapter] Ping failed:", err);
|
|
96
|
-
return false;
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
async disconnect() {
|
|
100
|
-
}
|
|
101
|
-
};
|
|
102
|
-
|
|
103
|
-
// src/vectordb/adapters/PgVectorAdapter.ts
|
|
104
|
-
import { Pool } from "pg";
|
|
105
|
-
var PgVectorAdapter = class {
|
|
106
|
-
constructor(config) {
|
|
107
|
-
var _a;
|
|
108
|
-
this.tableName = config.indexName.replace(/[^a-z0-9_]/gi, "_");
|
|
109
|
-
const opts = config.options;
|
|
110
|
-
if (!opts.connectionString) {
|
|
111
|
-
throw new Error("[PgVectorAdapter] options.connectionString is required");
|
|
112
|
-
}
|
|
113
|
-
this.connectionString = opts.connectionString;
|
|
114
|
-
this.dimensions = (_a = opts.dimensions) != null ? _a : 1536;
|
|
115
|
-
}
|
|
116
|
-
async initialize() {
|
|
117
|
-
this.pool = new Pool({ connectionString: this.connectionString });
|
|
118
|
-
const client = await this.pool.connect();
|
|
119
|
-
try {
|
|
120
|
-
await client.query("CREATE EXTENSION IF NOT EXISTS vector");
|
|
121
|
-
await client.query(`
|
|
122
|
-
CREATE TABLE IF NOT EXISTS ${this.tableName} (
|
|
123
|
-
id TEXT PRIMARY KEY,
|
|
124
|
-
namespace TEXT NOT NULL DEFAULT '',
|
|
125
|
-
content TEXT NOT NULL,
|
|
126
|
-
metadata JSONB,
|
|
127
|
-
embedding VECTOR(${this.dimensions})
|
|
128
|
-
)
|
|
129
|
-
`);
|
|
130
|
-
await client.query(`
|
|
131
|
-
CREATE INDEX IF NOT EXISTS ${this.tableName}_embedding_idx
|
|
132
|
-
ON ${this.tableName}
|
|
133
|
-
USING hnsw (embedding vector_cosine_ops)
|
|
134
|
-
`);
|
|
135
|
-
} finally {
|
|
136
|
-
client.release();
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
async upsert(doc, namespace = "") {
|
|
140
|
-
var _a;
|
|
141
|
-
const vectorLiteral = `[${doc.vector.join(",")}]`;
|
|
142
|
-
await this.pool.query(
|
|
143
|
-
`INSERT INTO ${this.tableName} (id, namespace, content, metadata, embedding)
|
|
144
|
-
VALUES ($1, $2, $3, $4, $5::vector)
|
|
145
|
-
ON CONFLICT (id) DO UPDATE
|
|
146
|
-
SET namespace = EXCLUDED.namespace,
|
|
147
|
-
content = EXCLUDED.content,
|
|
148
|
-
metadata = EXCLUDED.metadata,
|
|
149
|
-
embedding = EXCLUDED.embedding`,
|
|
150
|
-
[doc.id, namespace, doc.content, JSON.stringify((_a = doc.metadata) != null ? _a : {}), vectorLiteral]
|
|
151
|
-
);
|
|
152
|
-
}
|
|
153
|
-
async batchUpsert(docs, namespace = "") {
|
|
154
|
-
for (const doc of docs) {
|
|
155
|
-
await this.upsert(doc, namespace);
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
async query(vector, topK, namespace, filter) {
|
|
159
|
-
const vectorLiteral = `[${vector.join(",")}]`;
|
|
160
|
-
let whereClause = namespace ? `WHERE namespace = $3` : "";
|
|
161
|
-
const params = [vectorLiteral, topK];
|
|
162
|
-
if (namespace) params.push(namespace);
|
|
163
|
-
if (filter && Object.keys(filter).length > 0) {
|
|
164
|
-
const filterConditions = Object.entries(filter).map(([key, val]) => {
|
|
165
|
-
const paramIdx = params.length + 1;
|
|
166
|
-
params.push(JSON.stringify(val));
|
|
167
|
-
return `metadata->>'${key}' = $${paramIdx}`;
|
|
168
|
-
}).join(" AND ");
|
|
169
|
-
whereClause = whereClause ? `${whereClause} AND ${filterConditions}` : `WHERE ${filterConditions}`;
|
|
170
|
-
}
|
|
171
|
-
const result = await this.pool.query(
|
|
172
|
-
`SELECT id,
|
|
173
|
-
content,
|
|
174
|
-
metadata,
|
|
175
|
-
1 - (embedding <=> $1::vector) AS score
|
|
176
|
-
FROM ${this.tableName}
|
|
177
|
-
${whereClause}
|
|
178
|
-
ORDER BY embedding <=> $1::vector
|
|
179
|
-
LIMIT $2`,
|
|
180
|
-
params
|
|
181
|
-
);
|
|
182
|
-
return result.rows.map((row) => ({
|
|
183
|
-
id: String(row.id),
|
|
184
|
-
score: parseFloat(String(row.score)),
|
|
185
|
-
content: String(row.content),
|
|
186
|
-
metadata: row.metadata
|
|
187
|
-
}));
|
|
188
|
-
}
|
|
189
|
-
async delete(id, namespace) {
|
|
190
|
-
const where = namespace ? "WHERE id = $1 AND namespace = $2" : "WHERE id = $1";
|
|
191
|
-
const params = namespace ? [id, namespace] : [id];
|
|
192
|
-
await this.pool.query(`DELETE FROM ${this.tableName} ${where}`, params);
|
|
193
|
-
}
|
|
194
|
-
async deleteNamespace(namespace) {
|
|
195
|
-
await this.pool.query(
|
|
196
|
-
`DELETE FROM ${this.tableName} WHERE namespace = $1`,
|
|
197
|
-
[namespace]
|
|
198
|
-
);
|
|
199
|
-
}
|
|
200
|
-
async ping() {
|
|
201
|
-
try {
|
|
202
|
-
await this.pool.query("SELECT 1");
|
|
203
|
-
return true;
|
|
204
|
-
} catch (err) {
|
|
205
|
-
console.error("[PgVectorAdapter] Ping failed:", err);
|
|
206
|
-
return false;
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
async disconnect() {
|
|
210
|
-
try {
|
|
211
|
-
await this.pool.end();
|
|
212
|
-
} catch (err) {
|
|
213
|
-
console.error("[PgVectorAdapter] Failed to disconnect:", err);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
};
|
|
217
|
-
|
|
218
|
-
// src/vectordb/adapters/UniversalVectorDBAdapter.ts
|
|
219
|
-
import axios from "axios";
|
|
220
|
-
|
|
221
|
-
// src/config/UniversalProfiles.ts
|
|
222
|
-
var OPENAI_BASE = {
|
|
223
|
-
chatPath: "/chat/completions",
|
|
224
|
-
embedPath: "/embeddings",
|
|
225
|
-
responseExtractPath: "choices[0].message.content",
|
|
226
|
-
embedExtractPath: "data[0].embedding",
|
|
227
|
-
chatPayloadTemplate: '{"model":"{{model}}","messages":{{messages}},"max_tokens":{{maxTokens}},"temperature":{{temperature}}}'
|
|
228
|
-
};
|
|
229
|
-
var LLM_PROFILES = {
|
|
230
|
-
"openai-compatible": OPENAI_BASE,
|
|
231
|
-
"litellm": __spreadProps(__spreadValues({}, OPENAI_BASE), {
|
|
232
|
-
chatPayloadTemplate: '{"model":"{{model}}","messages":{{messages}},"max_tokens":{{maxTokens}},"temperature":{{temperature}},"stream":false}'
|
|
233
|
-
}),
|
|
234
|
-
"anthropic-claude": {
|
|
235
|
-
chatPath: "/v1/messages",
|
|
236
|
-
responseExtractPath: "content[0].text",
|
|
237
|
-
headers: { "anthropic-version": "2023-06-01" },
|
|
238
|
-
chatPayloadTemplate: '{"model":"{{model}}","messages":{{messages}},"max_tokens":{{maxTokens}}}'
|
|
239
|
-
},
|
|
240
|
-
"google-gemini": {
|
|
241
|
-
chatPath: "/v1beta/models/{{model}}:generateContent",
|
|
242
|
-
responseExtractPath: "candidates[0].content.parts[0].text",
|
|
243
|
-
chatPayloadTemplate: '{"contents":[{"parts":[{"text":"{{messages}}"}]}]}'
|
|
244
|
-
},
|
|
245
|
-
"github-copilot": __spreadProps(__spreadValues({}, OPENAI_BASE), {
|
|
246
|
-
chatPayloadTemplate: '{"model":"{{model}}","messages":{{messages}},"temperature":{{temperature}}}'
|
|
247
|
-
}),
|
|
248
|
-
"ollama-standard": {
|
|
249
|
-
chatPath: "/api/chat",
|
|
250
|
-
embedPath: "/api/embeddings",
|
|
251
|
-
responseExtractPath: "message.content",
|
|
252
|
-
embedExtractPath: "embedding",
|
|
253
|
-
chatPayloadTemplate: '{"model":"{{model}}","messages":{{messages}},"stream":false}',
|
|
254
|
-
embedPayloadTemplate: '{"model":"{{model}}","prompt":"{{input}}"}'
|
|
255
|
-
}
|
|
256
|
-
};
|
|
257
|
-
var VECTOR_PROFILES = {
|
|
258
|
-
"pinecone-rest": {
|
|
259
|
-
queryPath: "/query",
|
|
260
|
-
upsertPath: "/vectors/upsert",
|
|
261
|
-
responseExtractPath: "matches",
|
|
262
|
-
idPath: "id",
|
|
263
|
-
scorePath: "score",
|
|
264
|
-
contentPath: "metadata.content",
|
|
265
|
-
metadataPath: "metadata",
|
|
266
|
-
queryPayloadTemplate: '{"vector":{{vector}},"topK":{{topK}},"includeMetadata":true,"namespace":"{{namespace}}"}'
|
|
267
|
-
},
|
|
268
|
-
"mongodb-atlas": {
|
|
269
|
-
queryPath: "/action/aggregate",
|
|
270
|
-
responseExtractPath: "documents",
|
|
271
|
-
idPath: "_id",
|
|
272
|
-
scorePath: "score",
|
|
273
|
-
contentPath: "content",
|
|
274
|
-
metadataPath: "metadata",
|
|
275
|
-
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"}}}]}'
|
|
276
|
-
},
|
|
277
|
-
"chromadb": {
|
|
278
|
-
queryPath: "/api/v1/collections/{{index}}/query",
|
|
279
|
-
upsertPath: "/api/v1/collections/{{index}}/add",
|
|
280
|
-
responseExtractPath: "matches",
|
|
281
|
-
idPath: "id",
|
|
282
|
-
scorePath: "distance",
|
|
283
|
-
contentPath: "document",
|
|
284
|
-
metadataPath: "metadata"
|
|
285
|
-
},
|
|
286
|
-
"qdrant": {
|
|
287
|
-
queryPath: "/collections/{{index}}/points/search",
|
|
288
|
-
upsertPath: "/collections/{{index}}/points",
|
|
289
|
-
responseExtractPath: "result",
|
|
290
|
-
idPath: "id",
|
|
291
|
-
scorePath: "score",
|
|
292
|
-
contentPath: "payload.content",
|
|
293
|
-
metadataPath: "payload"
|
|
294
|
-
}
|
|
295
|
-
};
|
|
296
|
-
|
|
297
|
-
// src/vectordb/adapters/UniversalVectorDBAdapter.ts
|
|
298
|
-
var UniversalVectorDBAdapter = class {
|
|
299
|
-
constructor(config) {
|
|
300
|
-
var _a, _b, _c;
|
|
301
|
-
this.indexName = config.indexName;
|
|
302
|
-
const options = (_a = config.options) != null ? _a : {};
|
|
303
|
-
let profile = {};
|
|
304
|
-
if (typeof options.profile === "string") {
|
|
305
|
-
profile = VECTOR_PROFILES[options.profile] || {};
|
|
306
|
-
} else if (typeof options.profile === "object" && options.profile !== null) {
|
|
307
|
-
profile = options.profile;
|
|
308
|
-
}
|
|
309
|
-
this.opts = __spreadValues(__spreadValues({}, profile), (_b = config.options) != null ? _b : {});
|
|
310
|
-
if (!this.opts.baseUrl) {
|
|
311
|
-
throw new Error("[UniversalVectorDBAdapter] options.baseUrl is required");
|
|
312
|
-
}
|
|
313
|
-
this.http = axios.create({
|
|
314
|
-
baseURL: this.opts.baseUrl,
|
|
315
|
-
headers: __spreadValues({
|
|
316
|
-
"Content-Type": "application/json"
|
|
317
|
-
}, this.opts.headers || {}),
|
|
318
|
-
timeout: (_c = this.opts.timeout) != null ? _c : 3e4
|
|
319
|
-
});
|
|
320
|
-
}
|
|
321
|
-
async initialize() {
|
|
322
|
-
if (this.opts.pingPath) {
|
|
323
|
-
const ok = await this.ping();
|
|
324
|
-
if (!ok) {
|
|
325
|
-
throw new Error(`[UniversalVectorDBAdapter] Could not reach health endpoint: ${this.opts.pingPath}`);
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
async upsert(doc, namespace) {
|
|
330
|
-
var _a, _b;
|
|
331
|
-
const path = (_a = this.opts.upsertPath) != null ? _a : "/upsert";
|
|
332
|
-
if (this.opts.upsertPayloadTemplate) {
|
|
333
|
-
const payload = buildPayload(this.opts.upsertPayloadTemplate, {
|
|
334
|
-
id: doc.id,
|
|
335
|
-
vector: doc.vector,
|
|
336
|
-
content: doc.content,
|
|
337
|
-
metadata: (_b = doc.metadata) != null ? _b : {},
|
|
338
|
-
namespace: namespace != null ? namespace : "",
|
|
339
|
-
index: this.indexName
|
|
340
|
-
});
|
|
341
|
-
await this.http.post(path, payload);
|
|
342
|
-
} else {
|
|
343
|
-
await this.http.post(path, __spreadValues({
|
|
344
|
-
index: this.indexName,
|
|
345
|
-
namespace
|
|
346
|
-
}, doc));
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
async batchUpsert(docs, namespace) {
|
|
350
|
-
var _a;
|
|
351
|
-
const path = (_a = this.opts.upsertPath) != null ? _a : "/upsert";
|
|
352
|
-
if (this.opts.batchUpsertPayloadTemplate) {
|
|
353
|
-
const payload = buildPayload(this.opts.batchUpsertPayloadTemplate, {
|
|
354
|
-
vectors: docs,
|
|
355
|
-
namespace: namespace != null ? namespace : "",
|
|
356
|
-
index: this.indexName
|
|
357
|
-
});
|
|
358
|
-
await this.http.post(path, payload);
|
|
359
|
-
} else {
|
|
360
|
-
await Promise.all(docs.map((doc) => this.upsert(doc, namespace)));
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
async query(vector, topK, namespace, filter) {
|
|
364
|
-
var _a, _b, _c, _d, _e, _f;
|
|
365
|
-
const path = (_a = this.opts.queryPath) != null ? _a : "/query";
|
|
366
|
-
let payload;
|
|
367
|
-
if (this.opts.queryPayloadTemplate) {
|
|
368
|
-
payload = buildPayload(this.opts.queryPayloadTemplate, {
|
|
369
|
-
vector,
|
|
370
|
-
topK,
|
|
371
|
-
namespace: namespace != null ? namespace : "",
|
|
372
|
-
index: this.indexName,
|
|
373
|
-
filter: filter != null ? filter : {}
|
|
374
|
-
});
|
|
375
|
-
} else {
|
|
376
|
-
payload = { index: this.indexName, namespace, vector, topK, filter };
|
|
377
|
-
}
|
|
378
|
-
const { data } = await this.http.post(path, payload);
|
|
379
|
-
const extractPath = (_b = this.opts.responseExtractPath) != null ? _b : "matches";
|
|
380
|
-
const matchesRaw = resolvePath(data, extractPath);
|
|
381
|
-
if (!Array.isArray(matchesRaw)) {
|
|
382
|
-
throw new Error(`[UniversalVectorDBAdapter] Expected an array at responseExtractPath '${extractPath}', but got ${typeof matchesRaw}`);
|
|
383
|
-
}
|
|
384
|
-
const idPath = (_c = this.opts.idPath) != null ? _c : "id";
|
|
385
|
-
const scorePath = (_d = this.opts.scorePath) != null ? _d : "score";
|
|
386
|
-
const contentPath = (_e = this.opts.contentPath) != null ? _e : "content";
|
|
387
|
-
const metadataPath = (_f = this.opts.metadataPath) != null ? _f : "metadata";
|
|
388
|
-
return matchesRaw.map((match) => ({
|
|
389
|
-
id: String(resolvePath(match, idPath) || ""),
|
|
390
|
-
score: Number(resolvePath(match, scorePath) || 0),
|
|
391
|
-
content: String(resolvePath(match, contentPath) || ""),
|
|
392
|
-
metadata: resolvePath(match, metadataPath) || {}
|
|
393
|
-
}));
|
|
394
|
-
}
|
|
395
|
-
async delete(id, namespace) {
|
|
396
|
-
var _a;
|
|
397
|
-
const path = (_a = this.opts.deletePath) != null ? _a : "/delete";
|
|
398
|
-
await this.http.post(path, { index: this.indexName, namespace, id });
|
|
399
|
-
}
|
|
400
|
-
async deleteNamespace(namespace) {
|
|
401
|
-
var _a;
|
|
402
|
-
const path = (_a = this.opts.deleteNamespacePath) != null ? _a : "/delete-namespace";
|
|
403
|
-
await this.http.post(path, { index: this.indexName, namespace });
|
|
404
|
-
}
|
|
405
|
-
async ping() {
|
|
406
|
-
try {
|
|
407
|
-
if (this.opts.pingPath) {
|
|
408
|
-
await this.http.get(this.opts.pingPath);
|
|
409
|
-
}
|
|
410
|
-
return true;
|
|
411
|
-
} catch (err) {
|
|
412
|
-
console.error("[UniversalVectorDBAdapter] Ping failed:", err);
|
|
413
|
-
return false;
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
async disconnect() {
|
|
417
|
-
}
|
|
418
|
-
};
|
|
419
|
-
|
|
420
|
-
// src/vectordb/adapters/MongoDbAdapter.ts
|
|
421
|
-
import { MongoClient } from "mongodb";
|
|
422
|
-
var MongoDbAdapter = class {
|
|
423
|
-
constructor(options) {
|
|
424
|
-
this.uri = options.uri;
|
|
425
|
-
this.dbName = options.database;
|
|
426
|
-
this.collectionName = options.collection;
|
|
427
|
-
this.indexName = options.indexName || "vector_index";
|
|
428
|
-
this.embeddingKey = options.embeddingKey || "embedding";
|
|
429
|
-
this.contentKey = options.contentKey || "content";
|
|
430
|
-
this.metadataKey = options.metadataKey || "metadata";
|
|
431
|
-
if (!this.uri || !this.dbName || !this.collectionName) {
|
|
432
|
-
throw new Error("MongoDbAdapter requires uri, database, and collection options.");
|
|
433
|
-
}
|
|
434
|
-
this.client = new MongoClient(this.uri);
|
|
435
|
-
}
|
|
436
|
-
async initialize() {
|
|
437
|
-
await this.client.connect();
|
|
438
|
-
this.db = this.client.db(this.dbName);
|
|
439
|
-
this.collection = this.db.collection(this.collectionName);
|
|
440
|
-
}
|
|
441
|
-
async upsert(doc, namespace) {
|
|
442
|
-
if (!this.collection) await this.initialize();
|
|
443
|
-
const document = __spreadValues({
|
|
444
|
-
_id: doc.id,
|
|
445
|
-
[this.embeddingKey]: doc.vector,
|
|
446
|
-
[this.contentKey]: doc.content,
|
|
447
|
-
[this.metadataKey]: doc.metadata || {}
|
|
448
|
-
}, namespace ? { namespace } : {});
|
|
449
|
-
await this.collection.updateOne(
|
|
450
|
-
{ _id: doc.id },
|
|
451
|
-
{ $set: document },
|
|
452
|
-
{ upsert: true }
|
|
453
|
-
);
|
|
454
|
-
}
|
|
455
|
-
async batchUpsert(docs, namespace) {
|
|
456
|
-
if (!this.collection) await this.initialize();
|
|
457
|
-
const operations = docs.map((doc) => ({
|
|
458
|
-
updateOne: {
|
|
459
|
-
filter: { _id: doc.id },
|
|
460
|
-
update: {
|
|
461
|
-
$set: __spreadValues({
|
|
462
|
-
_id: doc.id,
|
|
463
|
-
[this.embeddingKey]: doc.vector,
|
|
464
|
-
[this.contentKey]: doc.content,
|
|
465
|
-
[this.metadataKey]: doc.metadata || {}
|
|
466
|
-
}, namespace ? { namespace } : {})
|
|
467
|
-
},
|
|
468
|
-
upsert: true
|
|
469
|
-
}
|
|
470
|
-
}));
|
|
471
|
-
await this.collection.bulkWrite(operations);
|
|
472
|
-
}
|
|
473
|
-
async query(vector, topK, namespace, filter) {
|
|
474
|
-
if (!this.collection) await this.initialize();
|
|
475
|
-
const pipeline = [
|
|
476
|
-
{
|
|
477
|
-
$vectorSearch: __spreadValues({
|
|
478
|
-
index: this.indexName,
|
|
479
|
-
path: this.embeddingKey,
|
|
480
|
-
queryVector: vector,
|
|
481
|
-
numCandidates: Math.max(topK * 10, 100),
|
|
482
|
-
limit: topK
|
|
483
|
-
}, filter || namespace ? {
|
|
484
|
-
filter: __spreadValues(__spreadValues({}, filter || {}), namespace ? { namespace } : {})
|
|
485
|
-
} : {})
|
|
486
|
-
},
|
|
487
|
-
{
|
|
488
|
-
$project: {
|
|
489
|
-
score: { $meta: "vectorSearchScore" },
|
|
490
|
-
content: `$${this.contentKey}`,
|
|
491
|
-
metadata: `$${this.metadataKey}`
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
|
-
];
|
|
495
|
-
const results = await this.collection.aggregate(pipeline).toArray();
|
|
496
|
-
return results.map((res) => ({
|
|
497
|
-
id: res._id.toString(),
|
|
498
|
-
score: res.score,
|
|
499
|
-
content: res.content,
|
|
500
|
-
metadata: res.metadata
|
|
501
|
-
}));
|
|
502
|
-
}
|
|
503
|
-
async delete(id, namespace) {
|
|
504
|
-
if (!this.collection) await this.initialize();
|
|
505
|
-
const query = __spreadValues({ _id: id }, namespace ? { namespace } : {});
|
|
506
|
-
await this.collection.deleteOne(query);
|
|
507
|
-
}
|
|
508
|
-
async deleteNamespace(namespace) {
|
|
509
|
-
if (!this.collection) await this.initialize();
|
|
510
|
-
await this.collection.deleteMany({ namespace });
|
|
511
|
-
}
|
|
512
|
-
async ping() {
|
|
513
|
-
try {
|
|
514
|
-
if (!this.collection) await this.initialize();
|
|
515
|
-
await this.db.command({ ping: 1 });
|
|
516
|
-
return true;
|
|
517
|
-
} catch (err) {
|
|
518
|
-
console.error("[MongoDbAdapter] Ping failed:", err);
|
|
519
|
-
return false;
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
async disconnect() {
|
|
523
|
-
try {
|
|
524
|
-
await this.client.close();
|
|
525
|
-
this.db = void 0;
|
|
526
|
-
this.collection = void 0;
|
|
527
|
-
} catch (err) {
|
|
528
|
-
console.error("[MongoDbAdapter] Failed to disconnect:", err);
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
};
|
|
532
|
-
|
|
533
|
-
// src/vectordb/VectorDBFactory.ts
|
|
534
|
-
var VectorDBFactory = class {
|
|
535
|
-
static create(config) {
|
|
536
|
-
var _a;
|
|
537
|
-
switch (config.provider) {
|
|
538
|
-
case "pinecone":
|
|
539
|
-
return new PineconeAdapter(config);
|
|
540
|
-
case "pgvector":
|
|
541
|
-
return new PgVectorAdapter(config);
|
|
542
|
-
case "mongodb":
|
|
543
|
-
return new MongoDbAdapter(config.options);
|
|
544
|
-
case "rest":
|
|
545
|
-
case "universal_rest":
|
|
546
|
-
case "custom":
|
|
547
|
-
return new UniversalVectorDBAdapter(config);
|
|
548
|
-
default:
|
|
549
|
-
if ((_a = config.options) == null ? void 0 : _a.baseUrl) {
|
|
550
|
-
return new UniversalVectorDBAdapter(config);
|
|
551
|
-
}
|
|
552
|
-
throw new Error(
|
|
553
|
-
`[VectorDBFactory] Unknown provider "${config.provider}". Supported: pinecone | pgvector | mongodb | rest`
|
|
554
|
-
);
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
};
|
|
558
|
-
|
|
559
|
-
// src/llm/providers/OpenAIProvider.ts
|
|
560
|
-
import OpenAI from "openai";
|
|
561
|
-
var OpenAIProvider = class {
|
|
562
|
-
constructor(llmConfig, embeddingConfig) {
|
|
563
|
-
if (!llmConfig.apiKey) throw new Error("[OpenAIProvider] llmConfig.apiKey is required");
|
|
564
|
-
this.client = new OpenAI({ apiKey: llmConfig.apiKey });
|
|
565
|
-
this.llmConfig = llmConfig;
|
|
566
|
-
this.embeddingConfig = embeddingConfig;
|
|
567
|
-
}
|
|
568
|
-
async chat(messages, context, options) {
|
|
569
|
-
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
570
|
-
const systemContent = (_a = this.llmConfig.systemPrompt) != null ? _a : `You are a helpful assistant. Answer questions based on the provided context.
|
|
571
|
-
|
|
572
|
-
Context:
|
|
573
|
-
${context}`;
|
|
574
|
-
const systemMessage = {
|
|
575
|
-
role: "system",
|
|
576
|
-
content: systemContent.includes("{{context}}") ? systemContent.replace("{{context}}", context) : `${systemContent}
|
|
577
|
-
|
|
578
|
-
Context:
|
|
579
|
-
${context}`
|
|
580
|
-
};
|
|
581
|
-
const formattedMessages = [
|
|
582
|
-
systemMessage,
|
|
583
|
-
...messages.map((m) => ({
|
|
584
|
-
role: m.role,
|
|
585
|
-
content: m.content
|
|
586
|
-
}))
|
|
587
|
-
];
|
|
588
|
-
const completion = await this.client.chat.completions.create({
|
|
589
|
-
model: this.llmConfig.model,
|
|
590
|
-
messages: formattedMessages,
|
|
591
|
-
max_tokens: (_c = (_b = options == null ? void 0 : options.maxTokens) != null ? _b : this.llmConfig.maxTokens) != null ? _c : 1024,
|
|
592
|
-
temperature: (_e = (_d = options == null ? void 0 : options.temperature) != null ? _d : this.llmConfig.temperature) != null ? _e : 0.7,
|
|
593
|
-
stop: options == null ? void 0 : options.stop
|
|
594
|
-
});
|
|
595
|
-
return (_h = (_g = (_f = completion.choices[0]) == null ? void 0 : _f.message) == null ? void 0 : _g.content) != null ? _h : "";
|
|
596
|
-
}
|
|
597
|
-
async embed(text, options) {
|
|
598
|
-
const results = await this.batchEmbed([text], options);
|
|
599
|
-
return results[0];
|
|
600
|
-
}
|
|
601
|
-
async batchEmbed(texts, options) {
|
|
602
|
-
var _a, _b, _c, _d, _e;
|
|
603
|
-
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";
|
|
604
|
-
const apiKey = (_e = (_d = this.embeddingConfig) == null ? void 0 : _d.apiKey) != null ? _e : this.llmConfig.apiKey;
|
|
605
|
-
const client = apiKey !== this.llmConfig.apiKey ? new OpenAI({ apiKey }) : this.client;
|
|
606
|
-
const response = await client.embeddings.create({ model, input: texts });
|
|
607
|
-
return response.data.map((d) => d.embedding);
|
|
608
|
-
}
|
|
609
|
-
async ping() {
|
|
610
|
-
try {
|
|
611
|
-
await this.client.models.list();
|
|
612
|
-
return true;
|
|
613
|
-
} catch (err) {
|
|
614
|
-
console.error("[OpenAIProvider] Ping failed:", err);
|
|
615
|
-
return false;
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
};
|
|
619
|
-
|
|
620
|
-
// src/llm/providers/AnthropicProvider.ts
|
|
621
|
-
import Anthropic from "@anthropic-ai/sdk";
|
|
622
|
-
var AnthropicProvider = class {
|
|
623
|
-
constructor(llmConfig, embeddingConfig) {
|
|
624
|
-
if (!llmConfig.apiKey) throw new Error("[AnthropicProvider] llmConfig.apiKey is required");
|
|
625
|
-
this.client = new Anthropic({ apiKey: llmConfig.apiKey });
|
|
626
|
-
this.llmConfig = llmConfig;
|
|
627
|
-
this.embeddingConfig = embeddingConfig;
|
|
628
|
-
}
|
|
629
|
-
async chat(messages, context, options) {
|
|
630
|
-
var _a, _b, _c;
|
|
631
|
-
const systemPrompt = (_a = this.llmConfig.systemPrompt) != null ? _a : `You are a helpful assistant. Use the context below to answer the user's question accurately.
|
|
632
|
-
|
|
633
|
-
Context:
|
|
634
|
-
${context}`;
|
|
635
|
-
const system = systemPrompt.includes("{{context}}") ? systemPrompt.replace("{{context}}", context) : `${systemPrompt}
|
|
636
|
-
|
|
637
|
-
Context:
|
|
638
|
-
${context}`;
|
|
639
|
-
const anthropicMessages = messages.map((m) => ({
|
|
640
|
-
role: m.role === "assistant" ? "assistant" : "user",
|
|
641
|
-
content: m.content
|
|
642
|
-
}));
|
|
643
|
-
const response = await this.client.messages.create({
|
|
644
|
-
model: this.llmConfig.model,
|
|
645
|
-
max_tokens: (_c = (_b = options == null ? void 0 : options.maxTokens) != null ? _b : this.llmConfig.maxTokens) != null ? _c : 1024,
|
|
646
|
-
system,
|
|
647
|
-
messages: anthropicMessages
|
|
648
|
-
});
|
|
649
|
-
const block = response.content[0];
|
|
650
|
-
return block.type === "text" ? block.text : "";
|
|
651
|
-
}
|
|
652
|
-
/**
|
|
653
|
-
* Anthropic does not offer an embedding API.
|
|
654
|
-
* This method throws with a clear error so developers know to configure
|
|
655
|
-
* a separate embedding provider (OpenAI or Ollama).
|
|
656
|
-
*/
|
|
657
|
-
async embed(text, options) {
|
|
658
|
-
void text;
|
|
659
|
-
void options;
|
|
660
|
-
throw new Error(
|
|
661
|
-
'[AnthropicProvider] Anthropic does not provide an embedding API. Set embedding.provider to "openai" or "ollama" in your RagConfig.'
|
|
662
|
-
);
|
|
663
|
-
}
|
|
664
|
-
async batchEmbed(texts, options) {
|
|
665
|
-
void texts;
|
|
666
|
-
void options;
|
|
667
|
-
throw new Error(
|
|
668
|
-
"[AnthropicProvider] Anthropic does not provide an embedding API."
|
|
669
|
-
);
|
|
670
|
-
}
|
|
671
|
-
async ping() {
|
|
672
|
-
try {
|
|
673
|
-
await this.client.models.list();
|
|
674
|
-
return true;
|
|
675
|
-
} catch (err) {
|
|
676
|
-
console.error("[AnthropicProvider] Ping failed:", err);
|
|
677
|
-
return false;
|
|
678
|
-
}
|
|
679
|
-
}
|
|
680
|
-
};
|
|
681
|
-
|
|
682
|
-
// src/llm/providers/OllamaProvider.ts
|
|
683
|
-
import axios2 from "axios";
|
|
684
|
-
var OllamaProvider = class {
|
|
685
|
-
constructor(llmConfig, embeddingConfig) {
|
|
686
|
-
var _a;
|
|
687
|
-
const baseURL = (_a = llmConfig.baseUrl) != null ? _a : "http://localhost:11434";
|
|
688
|
-
this.http = axios2.create({ baseURL, timeout: 12e4 });
|
|
689
|
-
this.llmConfig = llmConfig;
|
|
690
|
-
this.embeddingConfig = embeddingConfig;
|
|
691
|
-
}
|
|
692
|
-
async chat(messages, context, options) {
|
|
693
|
-
var _a, _b, _c, _d, _e;
|
|
694
|
-
const systemPrompt = (_a = this.llmConfig.systemPrompt) != null ? _a : `You are a helpful assistant. Use the provided context to answer the user's question.
|
|
695
|
-
|
|
696
|
-
Context:
|
|
697
|
-
${context}`;
|
|
698
|
-
const system = systemPrompt.includes("{{context}}") ? systemPrompt.replace("{{context}}", context) : `${systemPrompt}
|
|
699
|
-
|
|
700
|
-
Context:
|
|
701
|
-
${context}`;
|
|
702
|
-
const { data } = await this.http.post("/api/chat", {
|
|
703
|
-
model: this.llmConfig.model,
|
|
704
|
-
stream: false,
|
|
705
|
-
options: {
|
|
706
|
-
temperature: (_c = (_b = options == null ? void 0 : options.temperature) != null ? _b : this.llmConfig.temperature) != null ? _c : 0.7,
|
|
707
|
-
num_predict: (_e = (_d = options == null ? void 0 : options.maxTokens) != null ? _d : this.llmConfig.maxTokens) != null ? _e : 1024
|
|
708
|
-
},
|
|
709
|
-
messages: [
|
|
710
|
-
{ role: "system", content: system },
|
|
711
|
-
...messages.map((m) => ({ role: m.role, content: m.content }))
|
|
712
|
-
]
|
|
713
|
-
});
|
|
714
|
-
return data.message.content;
|
|
715
|
-
}
|
|
716
|
-
async embed(text, options) {
|
|
717
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
718
|
-
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";
|
|
719
|
-
const baseURL = (_f = (_e = (_d = this.embeddingConfig) == null ? void 0 : _d.baseUrl) != null ? _e : this.llmConfig.baseUrl) != null ? _f : "http://localhost:11434";
|
|
720
|
-
const client = baseURL !== ((_g = this.llmConfig.baseUrl) != null ? _g : "http://localhost:11434") ? axios2.create({ baseURL, timeout: 6e4 }) : this.http;
|
|
721
|
-
const { data } = await client.post("/api/embeddings", {
|
|
722
|
-
model,
|
|
723
|
-
prompt: text
|
|
724
|
-
});
|
|
725
|
-
return data.embedding;
|
|
726
|
-
}
|
|
727
|
-
async batchEmbed(texts, options) {
|
|
728
|
-
const vectors = [];
|
|
729
|
-
for (const text of texts) {
|
|
730
|
-
vectors.push(await this.embed(text, options));
|
|
731
|
-
}
|
|
732
|
-
return vectors;
|
|
733
|
-
}
|
|
734
|
-
async ping() {
|
|
735
|
-
try {
|
|
736
|
-
await this.http.get("/api/tags");
|
|
737
|
-
return true;
|
|
738
|
-
} catch (err) {
|
|
739
|
-
console.error("[OllamaProvider] Ping failed:", err);
|
|
740
|
-
return false;
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
};
|
|
744
|
-
|
|
745
|
-
// src/llm/providers/UniversalLLMAdapter.ts
|
|
746
|
-
import axios3 from "axios";
|
|
747
|
-
var UniversalLLMAdapter = class {
|
|
748
|
-
constructor(config) {
|
|
749
|
-
var _a, _b, _c, _d, _e, _f, _g;
|
|
750
|
-
this.model = config.model;
|
|
751
|
-
const llmConfig = config;
|
|
752
|
-
const options = (_a = llmConfig.options) != null ? _a : {};
|
|
753
|
-
let profile = {};
|
|
754
|
-
if (typeof options.profile === "string") {
|
|
755
|
-
profile = LLM_PROFILES[options.profile] || {};
|
|
756
|
-
} else if (typeof options.profile === "object" && options.profile !== null) {
|
|
757
|
-
profile = options.profile;
|
|
758
|
-
}
|
|
759
|
-
this.opts = __spreadValues(__spreadValues({}, profile), (_b = llmConfig.options) != null ? _b : {});
|
|
760
|
-
this.systemPrompt = (_c = llmConfig.systemPrompt) != null ? _c : "You are a helpful AI assistant. Use the provided context to answer the user.";
|
|
761
|
-
this.maxTokens = (_d = llmConfig.maxTokens) != null ? _d : 1024;
|
|
762
|
-
this.temperature = (_e = llmConfig.temperature) != null ? _e : 0;
|
|
763
|
-
const baseUrl = (_f = llmConfig.baseUrl) != null ? _f : this.opts.baseUrl;
|
|
764
|
-
if (!baseUrl) {
|
|
765
|
-
throw new Error("[UniversalLLMAdapter] baseUrl is required in config or config.options");
|
|
766
|
-
}
|
|
767
|
-
this.http = axios3.create({
|
|
768
|
-
baseURL: baseUrl,
|
|
769
|
-
headers: __spreadValues(__spreadValues({
|
|
770
|
-
"Content-Type": "application/json"
|
|
771
|
-
}, config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}), this.opts.headers || {}),
|
|
772
|
-
timeout: (_g = this.opts.timeout) != null ? _g : 6e4
|
|
773
|
-
});
|
|
774
|
-
}
|
|
775
|
-
async chat(messages, context) {
|
|
776
|
-
var _a, _b;
|
|
777
|
-
const path = (_a = this.opts.chatPath) != null ? _a : "/chat/completions";
|
|
778
|
-
const formattedMessages = [
|
|
779
|
-
{ role: "system", content: `${this.systemPrompt}
|
|
780
|
-
|
|
781
|
-
Context:
|
|
782
|
-
${context != null ? context : "None"}` },
|
|
783
|
-
...messages
|
|
784
|
-
];
|
|
785
|
-
let payload;
|
|
786
|
-
if (this.opts.chatPayloadTemplate) {
|
|
787
|
-
payload = buildPayload(this.opts.chatPayloadTemplate, {
|
|
788
|
-
model: this.model,
|
|
789
|
-
messages: formattedMessages,
|
|
790
|
-
maxTokens: this.maxTokens,
|
|
791
|
-
temperature: this.temperature
|
|
792
|
-
});
|
|
793
|
-
} else {
|
|
794
|
-
payload = {
|
|
795
|
-
model: this.model,
|
|
796
|
-
messages: formattedMessages,
|
|
797
|
-
max_tokens: this.maxTokens,
|
|
798
|
-
temperature: this.temperature
|
|
799
|
-
};
|
|
800
|
-
}
|
|
801
|
-
const { data } = await this.http.post(path, payload);
|
|
802
|
-
const extractPath = (_b = this.opts.responseExtractPath) != null ? _b : "choices[0].message.content";
|
|
803
|
-
const result = resolvePath(data, extractPath);
|
|
804
|
-
if (result === void 0) {
|
|
805
|
-
throw new Error(`[UniversalLLMAdapter] Could not extract text from path '${extractPath}' in response.`);
|
|
806
|
-
}
|
|
807
|
-
return String(result);
|
|
808
|
-
}
|
|
809
|
-
async embed(text) {
|
|
810
|
-
var _a, _b;
|
|
811
|
-
const path = (_a = this.opts.embedPath) != null ? _a : "/embeddings";
|
|
812
|
-
let payload;
|
|
813
|
-
if (this.opts.embedPayloadTemplate) {
|
|
814
|
-
payload = buildPayload(this.opts.embedPayloadTemplate, {
|
|
815
|
-
model: this.model,
|
|
816
|
-
input: text
|
|
817
|
-
});
|
|
818
|
-
} else {
|
|
819
|
-
payload = {
|
|
820
|
-
model: this.model,
|
|
821
|
-
input: text
|
|
822
|
-
};
|
|
823
|
-
}
|
|
824
|
-
const { data } = await this.http.post(path, payload);
|
|
825
|
-
const extractPath = (_b = this.opts.embedExtractPath) != null ? _b : "data[0].embedding";
|
|
826
|
-
const vector = resolvePath(data, extractPath);
|
|
827
|
-
if (!Array.isArray(vector)) {
|
|
828
|
-
throw new Error(`[UniversalLLMAdapter] Expected a number array at '${extractPath}' for embeddings.`);
|
|
829
|
-
}
|
|
830
|
-
return vector;
|
|
831
|
-
}
|
|
832
|
-
async batchEmbed(texts) {
|
|
833
|
-
const vectors = [];
|
|
834
|
-
for (const text of texts) {
|
|
835
|
-
vectors.push(await this.embed(text));
|
|
836
|
-
}
|
|
837
|
-
return vectors;
|
|
838
|
-
}
|
|
839
|
-
async ping() {
|
|
840
|
-
try {
|
|
841
|
-
if (this.opts.pingPath) {
|
|
842
|
-
await this.http.get(this.opts.pingPath);
|
|
843
|
-
}
|
|
844
|
-
return true;
|
|
845
|
-
} catch (err) {
|
|
846
|
-
console.error("[UniversalLLMAdapter] Ping failed:", err);
|
|
847
|
-
return false;
|
|
848
|
-
}
|
|
849
|
-
}
|
|
850
|
-
};
|
|
851
|
-
|
|
852
|
-
// src/llm/LLMFactory.ts
|
|
853
|
-
var LLMFactory = class _LLMFactory {
|
|
854
|
-
static create(llmConfig, embeddingConfig) {
|
|
855
|
-
var _a;
|
|
856
|
-
switch (llmConfig.provider) {
|
|
857
|
-
case "openai":
|
|
858
|
-
return new OpenAIProvider(llmConfig, embeddingConfig);
|
|
859
|
-
case "anthropic":
|
|
860
|
-
return new AnthropicProvider(llmConfig, embeddingConfig);
|
|
861
|
-
case "ollama":
|
|
862
|
-
return new OllamaProvider(llmConfig, embeddingConfig);
|
|
863
|
-
case "rest":
|
|
864
|
-
case "universal_rest":
|
|
865
|
-
case "custom":
|
|
866
|
-
return new UniversalLLMAdapter(llmConfig);
|
|
867
|
-
default:
|
|
868
|
-
if (llmConfig.baseUrl || ((_a = llmConfig.options) == null ? void 0 : _a.baseUrl)) {
|
|
869
|
-
return new UniversalLLMAdapter(llmConfig);
|
|
870
|
-
}
|
|
871
|
-
throw new Error(
|
|
872
|
-
`[LLMFactory] Unknown provider "${llmConfig.provider}". Supported: openai | anthropic | ollama | rest | custom`
|
|
873
|
-
);
|
|
874
|
-
}
|
|
875
|
-
}
|
|
876
|
-
/**
|
|
877
|
-
* Creates a dedicated embedding-only provider.
|
|
878
|
-
* Useful when the LLM provider (e.g. Anthropic) doesn't support embeddings.
|
|
879
|
-
*/
|
|
880
|
-
static createEmbeddingProvider(embeddingConfig) {
|
|
881
|
-
const fakeLLMConfig = {
|
|
882
|
-
provider: embeddingConfig.provider,
|
|
883
|
-
model: embeddingConfig.model,
|
|
884
|
-
apiKey: embeddingConfig.apiKey,
|
|
885
|
-
baseUrl: embeddingConfig.baseUrl,
|
|
886
|
-
options: embeddingConfig.options
|
|
887
|
-
};
|
|
888
|
-
return _LLMFactory.create(fakeLLMConfig, embeddingConfig);
|
|
889
|
-
}
|
|
890
|
-
};
|
|
891
|
-
|
|
892
|
-
// src/rag/DocumentChunker.ts
|
|
893
|
-
var DocumentChunker = class {
|
|
894
|
-
constructor(chunkSize = 1e3, chunkOverlap = 200) {
|
|
895
|
-
this.chunkSize = chunkSize;
|
|
896
|
-
this.chunkOverlap = chunkOverlap;
|
|
897
|
-
}
|
|
898
|
-
/**
|
|
899
|
-
* Split a single text string into overlapping chunks.
|
|
900
|
-
*/
|
|
901
|
-
chunk(text, options = {}) {
|
|
902
|
-
const {
|
|
903
|
-
chunkSize = this.chunkSize,
|
|
904
|
-
chunkOverlap = this.chunkOverlap,
|
|
905
|
-
docId = `doc_${Date.now()}`,
|
|
906
|
-
metadata = {}
|
|
907
|
-
} = options;
|
|
908
|
-
const cleaned = text.replace(/\r\n/g, "\n").trim();
|
|
909
|
-
if (!cleaned) return [];
|
|
910
|
-
const sentences = cleaned.split(new RegExp("(?<=[.!?])\\s+|\\n{2,}")).map((s) => s.trim()).filter(Boolean);
|
|
911
|
-
const chunks = [];
|
|
912
|
-
let current = "";
|
|
913
|
-
let chunkIndex = 0;
|
|
914
|
-
for (const sentence of sentences) {
|
|
915
|
-
if ((current + " " + sentence).trim().length <= chunkSize) {
|
|
916
|
-
current = current ? `${current} ${sentence}` : sentence;
|
|
917
|
-
} else {
|
|
918
|
-
if (current) {
|
|
919
|
-
chunks.push({
|
|
920
|
-
id: `${docId}_chunk_${chunkIndex++}`,
|
|
921
|
-
content: current.trim(),
|
|
922
|
-
metadata: __spreadProps(__spreadValues({}, metadata), { docId, chunkIndex: chunkIndex - 1 })
|
|
923
|
-
});
|
|
924
|
-
}
|
|
925
|
-
if (chunkOverlap > 0 && current.length > chunkOverlap) {
|
|
926
|
-
current = current.slice(-chunkOverlap) + " " + sentence;
|
|
927
|
-
} else {
|
|
928
|
-
current = sentence;
|
|
929
|
-
}
|
|
930
|
-
}
|
|
931
|
-
}
|
|
932
|
-
if (current.trim()) {
|
|
933
|
-
chunks.push({
|
|
934
|
-
id: `${docId}_chunk_${chunkIndex}`,
|
|
935
|
-
content: current.trim(),
|
|
936
|
-
metadata: __spreadProps(__spreadValues({}, metadata), { docId, chunkIndex })
|
|
937
|
-
});
|
|
938
|
-
}
|
|
939
|
-
return chunks;
|
|
940
|
-
}
|
|
941
|
-
/**
|
|
942
|
-
* Chunk multiple documents at once.
|
|
943
|
-
*/
|
|
944
|
-
chunkMany(documents) {
|
|
945
|
-
return documents.flatMap(
|
|
946
|
-
(doc) => this.chunk(doc.content, { docId: doc.docId, metadata: doc.metadata })
|
|
947
|
-
);
|
|
948
|
-
}
|
|
949
|
-
};
|
|
950
|
-
|
|
951
|
-
// src/rag/RAGPipeline.ts
|
|
952
|
-
var RAGPipeline = class {
|
|
953
|
-
constructor(config, adapters) {
|
|
954
|
-
this.initialised = false;
|
|
955
|
-
var _a, _b, _c, _d, _e, _f;
|
|
956
|
-
this.config = config;
|
|
957
|
-
this.vectorDB = (_a = adapters == null ? void 0 : adapters.vectorDB) != null ? _a : VectorDBFactory.create(config.vectorDb);
|
|
958
|
-
this.llmProvider = (_b = adapters == null ? void 0 : adapters.llmProvider) != null ? _b : LLMFactory.create(config.llm, config.embedding);
|
|
959
|
-
if (adapters == null ? void 0 : adapters.embeddingProvider) {
|
|
960
|
-
this.embeddingProvider = adapters.embeddingProvider;
|
|
961
|
-
} else if (config.llm.provider === "anthropic") {
|
|
962
|
-
this.embeddingProvider = LLMFactory.createEmbeddingProvider(config.embedding);
|
|
963
|
-
} else {
|
|
964
|
-
this.embeddingProvider = this.llmProvider;
|
|
965
|
-
}
|
|
966
|
-
this.chunker = new DocumentChunker(
|
|
967
|
-
(_d = (_c = config.rag) == null ? void 0 : _c.chunkSize) != null ? _d : 1e3,
|
|
968
|
-
(_f = (_e = config.rag) == null ? void 0 : _e.chunkOverlap) != null ? _f : 200
|
|
969
|
-
);
|
|
970
|
-
}
|
|
971
|
-
/** Lazily initialise the vector DB connection */
|
|
972
|
-
async init() {
|
|
973
|
-
if (!this.initialised) {
|
|
974
|
-
await this.vectorDB.initialize();
|
|
975
|
-
this.initialised = true;
|
|
976
|
-
}
|
|
977
|
-
}
|
|
978
|
-
// ---------------------------------------------------------------------------
|
|
979
|
-
// INGEST
|
|
980
|
-
// ---------------------------------------------------------------------------
|
|
981
|
-
/**
|
|
982
|
-
* Ingest one or more documents into the vector DB.
|
|
983
|
-
* Automatically chunks, embeds, and upserts each chunk.
|
|
984
|
-
*/
|
|
985
|
-
async ingest(documents, namespace) {
|
|
986
|
-
await this.init();
|
|
987
|
-
const ns = namespace != null ? namespace : this.config.projectId;
|
|
988
|
-
const results = [];
|
|
989
|
-
for (const doc of documents) {
|
|
990
|
-
const chunks = this.chunker.chunk(doc.content, {
|
|
991
|
-
docId: doc.docId,
|
|
992
|
-
metadata: doc.metadata
|
|
993
|
-
});
|
|
994
|
-
const chunkTexts = chunks.map((c) => c.content);
|
|
995
|
-
const vectors = await this.embeddingProvider.batchEmbed(chunkTexts);
|
|
996
|
-
const upsertDocs = chunks.map((chunk, i) => ({
|
|
997
|
-
id: chunk.id,
|
|
998
|
-
vector: vectors[i],
|
|
999
|
-
content: chunk.content,
|
|
1000
|
-
metadata: chunk.metadata
|
|
1001
|
-
}));
|
|
1002
|
-
await this.vectorDB.batchUpsert(upsertDocs, ns);
|
|
1003
|
-
results.push({ docId: doc.docId, chunksIngested: chunks.length });
|
|
1004
|
-
console.log(`[RAGPipeline] Ingested ${chunks.length} chunks for doc: ${doc.docId}`);
|
|
1005
|
-
}
|
|
1006
|
-
return results;
|
|
1007
|
-
}
|
|
1008
|
-
// ---------------------------------------------------------------------------
|
|
1009
|
-
// ASK
|
|
1010
|
-
// ---------------------------------------------------------------------------
|
|
1011
|
-
/**
|
|
1012
|
-
* Run a full RAG query:
|
|
1013
|
-
* 1. Embed the user question
|
|
1014
|
-
* 2. Retrieve top-K relevant chunks from the vector DB
|
|
1015
|
-
* 3. Filter by score threshold
|
|
1016
|
-
* 4. Build context string
|
|
1017
|
-
* 5. Call the LLM with chat history + context
|
|
1018
|
-
*/
|
|
1019
|
-
async ask(question, history = [], namespace) {
|
|
1020
|
-
var _a, _b, _c, _d;
|
|
1021
|
-
await this.init();
|
|
1022
|
-
const ns = namespace != null ? namespace : this.config.projectId;
|
|
1023
|
-
const topK = (_b = (_a = this.config.rag) == null ? void 0 : _a.topK) != null ? _b : 5;
|
|
1024
|
-
const scoreThreshold = (_d = (_c = this.config.rag) == null ? void 0 : _c.scoreThreshold) != null ? _d : 0;
|
|
1025
|
-
console.log(`[RAGPipeline] Searching Pinecone (Namespace: "${ns}", TopK: ${topK})...`);
|
|
1026
|
-
const queryVector = await this.embeddingProvider.embed(question);
|
|
1027
|
-
const rawMatches = await this.vectorDB.query(queryVector, topK, ns);
|
|
1028
|
-
console.log(`[RAGPipeline] Found ${rawMatches.length} raw matches in Pinecone.`);
|
|
1029
|
-
const sources = rawMatches.filter((m) => m.score >= scoreThreshold);
|
|
1030
|
-
console.log(`[RAGPipeline] ${sources.length} sources remaining after threshold filter (min: ${scoreThreshold}).`);
|
|
1031
|
-
const context = sources.length ? sources.map((m, i) => `[Source ${i + 1}]
|
|
1032
|
-
${m.content}`).join("\n\n---\n\n") : "No relevant context found.";
|
|
1033
|
-
const messages = [
|
|
1034
|
-
...history,
|
|
1035
|
-
{ role: "user", content: question }
|
|
1036
|
-
];
|
|
1037
|
-
const reply = await this.llmProvider.chat(messages, context);
|
|
1038
|
-
return { reply, sources };
|
|
1039
|
-
}
|
|
1040
|
-
// ---------------------------------------------------------------------------
|
|
1041
|
-
// HEALTH
|
|
1042
|
-
// ---------------------------------------------------------------------------
|
|
1043
|
-
async health() {
|
|
1044
|
-
const [vectorDB, llm] = await Promise.all([
|
|
1045
|
-
this.vectorDB.ping().catch(() => false),
|
|
1046
|
-
this.llmProvider.ping().catch(() => false)
|
|
1047
|
-
]);
|
|
1048
|
-
return { vectorDB, llm };
|
|
1049
|
-
}
|
|
1050
|
-
// ---------------------------------------------------------------------------
|
|
1051
|
-
// DATA MANAGEMENT
|
|
1052
|
-
// ---------------------------------------------------------------------------
|
|
1053
|
-
async deleteDocument(docId, namespace) {
|
|
1054
|
-
await this.init();
|
|
1055
|
-
const ns = namespace != null ? namespace : this.config.projectId;
|
|
1056
|
-
await this.vectorDB.delete(docId, ns);
|
|
1057
|
-
}
|
|
1058
|
-
async deleteProject(namespace) {
|
|
1059
|
-
await this.init();
|
|
1060
|
-
const ns = namespace != null ? namespace : this.config.projectId;
|
|
1061
|
-
await this.vectorDB.deleteNamespace(ns);
|
|
1062
|
-
}
|
|
1063
|
-
};
|
|
1064
|
-
|
|
1065
|
-
// src/utils/DocumentParser.ts
|
|
1066
|
-
var DocumentParser = class {
|
|
1067
|
-
/**
|
|
1068
|
-
* Extract text from a File or Buffer based on its type.
|
|
1069
|
-
*/
|
|
1070
|
-
static async parse(file, fileName, mimeType) {
|
|
1071
|
-
var _a;
|
|
1072
|
-
const extension = (_a = fileName.split(".").pop()) == null ? void 0 : _a.toLowerCase();
|
|
1073
|
-
if (extension === "txt" || extension === "md" || mimeType === "text/plain" || mimeType === "text/markdown") {
|
|
1074
|
-
return this.readAsText(file);
|
|
1075
|
-
}
|
|
1076
|
-
if (extension === "json" || mimeType === "application/json") {
|
|
1077
|
-
const text = await this.readAsText(file);
|
|
1078
|
-
try {
|
|
1079
|
-
const obj = JSON.parse(text);
|
|
1080
|
-
return JSON.stringify(obj, null, 2);
|
|
1081
|
-
} catch (e) {
|
|
1082
|
-
return text;
|
|
1083
|
-
}
|
|
1084
|
-
}
|
|
1085
|
-
if (extension === "csv" || mimeType === "text/csv") {
|
|
1086
|
-
return this.readAsText(file);
|
|
1087
|
-
}
|
|
1088
|
-
if (extension === "pdf" || mimeType === "application/pdf") {
|
|
1089
|
-
try {
|
|
1090
|
-
const pdf = await import("pdf-parse/lib/pdf-parse.js");
|
|
1091
|
-
const buffer = Buffer.isBuffer(file) ? file : Buffer.from(await file.arrayBuffer());
|
|
1092
|
-
const data = await pdf.default(buffer);
|
|
1093
|
-
return data.text;
|
|
1094
|
-
} catch (err) {
|
|
1095
|
-
console.warn('[DocumentParser] PDF parsing failed. Make sure "pdf-parse" is installed.', err);
|
|
1096
|
-
return `[PDF Parsing Error for ${fileName}]`;
|
|
1097
|
-
}
|
|
1098
|
-
}
|
|
1099
|
-
if (extension === "docx" || mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
|
|
1100
|
-
try {
|
|
1101
|
-
const mammoth = await import("mammoth");
|
|
1102
|
-
const buffer = Buffer.isBuffer(file) ? file : Buffer.from(await file.arrayBuffer());
|
|
1103
|
-
const result = await mammoth.extractRawText({ buffer });
|
|
1104
|
-
return result.value;
|
|
1105
|
-
} catch (err) {
|
|
1106
|
-
console.warn('[DocumentParser] DOCX parsing failed. Make sure "mammoth" is installed.', err);
|
|
1107
|
-
return `[DOCX Parsing Error for ${fileName}]`;
|
|
1108
|
-
}
|
|
1109
|
-
}
|
|
1110
|
-
try {
|
|
1111
|
-
return await this.readAsText(file);
|
|
1112
|
-
} catch (e) {
|
|
1113
|
-
throw new Error(`[DocumentParser] Unsupported file format: ${fileName} (${mimeType})`);
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
static async readAsText(file) {
|
|
1117
|
-
if (Buffer.isBuffer(file)) {
|
|
1118
|
-
return file.toString("utf-8");
|
|
1119
|
-
}
|
|
1120
|
-
return await file.text();
|
|
1121
|
-
}
|
|
1122
|
-
};
|
|
1123
|
-
|
|
1124
|
-
// src/handlers/index.ts
|
|
1125
|
-
function createChatHandler(config, adapters) {
|
|
1126
|
-
let pipeline = null;
|
|
1127
|
-
function getPipeline() {
|
|
1128
|
-
if (!pipeline) pipeline = new RAGPipeline(config, adapters);
|
|
1129
|
-
return pipeline;
|
|
1130
|
-
}
|
|
1131
|
-
return async function POST(req) {
|
|
1132
|
-
try {
|
|
1133
|
-
const body = await req.json();
|
|
1134
|
-
const { message, history = [], namespace } = body;
|
|
1135
|
-
if (!(message == null ? void 0 : message.trim())) {
|
|
1136
|
-
return NextResponse.json({ error: "message is required" }, { status: 400 });
|
|
1137
|
-
}
|
|
1138
|
-
const rag = getPipeline();
|
|
1139
|
-
const result = await rag.ask(message, history, namespace);
|
|
1140
|
-
return NextResponse.json(result);
|
|
1141
|
-
} catch (err) {
|
|
1142
|
-
const message = err instanceof Error ? err.message : "Internal server error";
|
|
1143
|
-
return NextResponse.json({ error: message }, { status: 500 });
|
|
1144
|
-
}
|
|
1145
|
-
};
|
|
1146
|
-
}
|
|
1147
|
-
function createIngestHandler(config, adapters) {
|
|
1148
|
-
let pipeline = null;
|
|
1149
|
-
function getPipeline() {
|
|
1150
|
-
if (!pipeline) pipeline = new RAGPipeline(config, adapters);
|
|
1151
|
-
return pipeline;
|
|
1152
|
-
}
|
|
1153
|
-
return async function POST(req) {
|
|
1154
|
-
try {
|
|
1155
|
-
const body = await req.json();
|
|
1156
|
-
const { documents, namespace } = body;
|
|
1157
|
-
if (!Array.isArray(documents) || documents.length === 0) {
|
|
1158
|
-
return NextResponse.json(
|
|
1159
|
-
{ error: "documents array is required and must not be empty" },
|
|
1160
|
-
{ status: 400 }
|
|
1161
|
-
);
|
|
1162
|
-
}
|
|
1163
|
-
const rag = getPipeline();
|
|
1164
|
-
const results = await rag.ingest(documents, namespace);
|
|
1165
|
-
const totalChunks = results.reduce((sum, r) => sum + r.chunksIngested, 0);
|
|
1166
|
-
return NextResponse.json({ results, totalChunks });
|
|
1167
|
-
} catch (err) {
|
|
1168
|
-
const message = err instanceof Error ? err.message : "Internal server error";
|
|
1169
|
-
return NextResponse.json({ error: message }, { status: 500 });
|
|
1170
|
-
}
|
|
1171
|
-
};
|
|
1172
|
-
}
|
|
1173
|
-
function createHealthHandler(config, adapters) {
|
|
1174
|
-
let pipeline = null;
|
|
1175
|
-
function getPipeline() {
|
|
1176
|
-
if (!pipeline) pipeline = new RAGPipeline(config, adapters);
|
|
1177
|
-
return pipeline;
|
|
1178
|
-
}
|
|
1179
|
-
return async function GET() {
|
|
1180
|
-
try {
|
|
1181
|
-
const rag = getPipeline();
|
|
1182
|
-
const health = await rag.health();
|
|
1183
|
-
const status = health.vectorDB && health.llm ? "ok" : "degraded";
|
|
1184
|
-
return NextResponse.json(__spreadProps(__spreadValues({
|
|
1185
|
-
status
|
|
1186
|
-
}, health), {
|
|
1187
|
-
project: config.projectId,
|
|
1188
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
1189
|
-
}));
|
|
1190
|
-
} catch (err) {
|
|
1191
|
-
const message = err instanceof Error ? err.message : "Unknown error";
|
|
1192
|
-
return NextResponse.json(
|
|
1193
|
-
{ status: "error", error: message, timestamp: (/* @__PURE__ */ new Date()).toISOString() },
|
|
1194
|
-
{ status: 500 }
|
|
1195
|
-
);
|
|
1196
|
-
}
|
|
1197
|
-
};
|
|
1198
|
-
}
|
|
1199
|
-
function createUploadHandler(config, adapters) {
|
|
1200
|
-
let pipeline = null;
|
|
1201
|
-
function getPipeline() {
|
|
1202
|
-
if (!pipeline) pipeline = new RAGPipeline(config, adapters);
|
|
1203
|
-
return pipeline;
|
|
1204
|
-
}
|
|
1205
|
-
return async function POST(req) {
|
|
1206
|
-
try {
|
|
1207
|
-
const formData = await req.formData();
|
|
1208
|
-
const files = formData.getAll("files");
|
|
1209
|
-
const namespace = formData.get("namespace") || void 0;
|
|
1210
|
-
if (!files || files.length === 0) {
|
|
1211
|
-
return NextResponse.json({ error: "No files provided" }, { status: 400 });
|
|
1212
|
-
}
|
|
1213
|
-
const documents = await Promise.all(
|
|
1214
|
-
files.map(async (file) => {
|
|
1215
|
-
const content = await DocumentParser.parse(file, file.name, file.type);
|
|
1216
|
-
return {
|
|
1217
|
-
docId: file.name,
|
|
1218
|
-
content,
|
|
1219
|
-
metadata: {
|
|
1220
|
-
fileName: file.name,
|
|
1221
|
-
fileSize: file.size,
|
|
1222
|
-
fileType: file.type,
|
|
1223
|
-
uploadedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1224
|
-
}
|
|
1225
|
-
};
|
|
1226
|
-
})
|
|
1227
|
-
);
|
|
1228
|
-
const rag = getPipeline();
|
|
1229
|
-
const results = await rag.ingest(documents, namespace);
|
|
1230
|
-
const totalChunks = results.reduce((sum, r) => sum + r.chunksIngested, 0);
|
|
1231
|
-
return NextResponse.json({
|
|
1232
|
-
message: "Upload successful",
|
|
1233
|
-
filesProcessed: files.length,
|
|
1234
|
-
totalChunks,
|
|
1235
|
-
results
|
|
1236
|
-
});
|
|
1237
|
-
} catch (err) {
|
|
1238
|
-
const message = err instanceof Error ? err.message : "Upload failed";
|
|
1239
|
-
return NextResponse.json({ error: message }, { status: 500 });
|
|
1240
|
-
}
|
|
1241
|
-
};
|
|
1242
|
-
}
|
|
1243
|
-
|
|
1244
|
-
export {
|
|
1245
|
-
PineconeAdapter,
|
|
1246
|
-
PgVectorAdapter,
|
|
1247
|
-
MongoDbAdapter,
|
|
1248
|
-
VectorDBFactory,
|
|
1249
|
-
OpenAIProvider,
|
|
1250
|
-
AnthropicProvider,
|
|
1251
|
-
OllamaProvider,
|
|
1252
|
-
LLMFactory,
|
|
1253
|
-
DocumentChunker,
|
|
1254
|
-
RAGPipeline,
|
|
1255
|
-
createChatHandler,
|
|
1256
|
-
createIngestHandler,
|
|
1257
|
-
createHealthHandler,
|
|
1258
|
-
createUploadHandler
|
|
1259
|
-
};
|