@retrivora-ai/rag-engine 0.1.5 → 0.1.6
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/{DocumentChunker-cfaMidtA.d.mts → DocumentChunker-BEyzadsv.d.mts} +2 -2
- package/dist/{DocumentChunker-cfaMidtA.d.ts → DocumentChunker-BEyzadsv.d.ts} +2 -2
- package/dist/{PineconeProvider-NJ675H7U.mjs → PineconeProvider-ZRAFNFEC.mjs} +1 -1
- package/dist/{PostgreSQLProvider-ISNMD3BE.mjs → PostgreSQLProvider-ZNXA67IM.mjs} +1 -1
- package/dist/{QdrantProvider-LJWOIGES.mjs → QdrantProvider-NYGHAA7C.mjs} +1 -1
- package/dist/{RagConfig-DG_0f8ka.d.mts → RagConfig-hBGXJmSx.d.mts} +3 -3
- package/dist/{RagConfig-DG_0f8ka.d.ts → RagConfig-hBGXJmSx.d.ts} +3 -3
- package/dist/{chunk-6FODXNUF.mjs → chunk-5K23H7JL.mjs} +27 -1
- package/dist/chunk-HSBXE2WV.mjs +1758 -0
- package/dist/{chunk-S5DRHETN.mjs → chunk-IUTAZ7QR.mjs} +31 -2
- package/dist/{chunk-AALIF3AL.mjs → chunk-ZM6TYIDH.mjs} +3 -3
- package/dist/handlers/index.d.mts +3 -44
- package/dist/handlers/index.d.ts +3 -44
- package/dist/handlers/index.js +1322 -57
- package/dist/handlers/index.mjs +1 -1
- package/dist/index-Bx182KKn.d.ts +64 -0
- package/dist/index-Ck2pt7-8.d.mts +64 -0
- package/dist/index.d.mts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/server.d.mts +65 -18
- package/dist/server.d.ts +65 -18
- package/dist/server.js +1322 -57
- package/dist/server.mjs +4 -4
- package/package.json +2 -1
- package/src/config/serverConfig.ts +3 -0
- package/src/core/BatchProcessor.ts +347 -0
- package/src/core/ConfigValidator.ts +560 -0
- package/src/core/Pipeline.ts +89 -39
- package/src/core/ProviderHealthCheck.ts +565 -0
- package/src/core/VectorPlugin.ts +49 -8
- package/src/handlers/index.ts +2 -2
- package/src/providers/vectordb/BaseVectorProvider.ts +1 -1
- package/src/providers/vectordb/MilvusProvider.ts +1 -1
- package/src/providers/vectordb/MongoDBProvider.ts +1 -1
- package/src/providers/vectordb/PineconeProvider.ts +4 -4
- package/src/providers/vectordb/PostgreSQLProvider.ts +35 -3
- package/src/providers/vectordb/QdrantProvider.ts +32 -2
- package/src/rag/DocumentChunker.ts +2 -2
- package/src/types/index.ts +3 -3
- package/dist/chunk-BP4U4TT5.mjs +0 -548
|
@@ -0,0 +1,1758 @@
|
|
|
1
|
+
import {
|
|
2
|
+
LLMFactory
|
|
3
|
+
} from "./chunk-JI6VD5TJ.mjs";
|
|
4
|
+
import {
|
|
5
|
+
mergeDefined
|
|
6
|
+
} from "./chunk-UKDXCXW7.mjs";
|
|
7
|
+
import {
|
|
8
|
+
__spreadProps,
|
|
9
|
+
__spreadValues
|
|
10
|
+
} from "./chunk-I4E63NIC.mjs";
|
|
11
|
+
|
|
12
|
+
// src/handlers/index.ts
|
|
13
|
+
import { NextResponse } from "next/server";
|
|
14
|
+
|
|
15
|
+
// src/config/serverConfig.ts
|
|
16
|
+
var VECTOR_DB_PROVIDERS = ["pinecone", "pgvector", "postgresql", "mongodb", "milvus", "qdrant", "chromadb", "redis", "weaviate", "rest", "universal_rest", "custom"];
|
|
17
|
+
var LLM_PROVIDERS = ["openai", "anthropic", "ollama", "rest", "universal_rest", "custom"];
|
|
18
|
+
var EMBEDDING_PROVIDERS = ["openai", "ollama", "rest", "universal_rest", "custom"];
|
|
19
|
+
function readString(env, name) {
|
|
20
|
+
var _a;
|
|
21
|
+
const value = (_a = env[name]) == null ? void 0 : _a.trim();
|
|
22
|
+
return value ? value : void 0;
|
|
23
|
+
}
|
|
24
|
+
function readNumber(env, name, fallback) {
|
|
25
|
+
const value = env[name];
|
|
26
|
+
if (!value) return fallback;
|
|
27
|
+
const parsed = Number(value);
|
|
28
|
+
if (!Number.isFinite(parsed)) {
|
|
29
|
+
throw new Error(`[getRagConfig] ${name} must be a valid number`);
|
|
30
|
+
}
|
|
31
|
+
return parsed;
|
|
32
|
+
}
|
|
33
|
+
function readEnum(env, name, fallback, allowed) {
|
|
34
|
+
var _a;
|
|
35
|
+
const value = (_a = readString(env, name)) != null ? _a : fallback;
|
|
36
|
+
if (allowed.includes(value)) {
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
throw new Error(`[getRagConfig] ${name} must be one of: ${allowed.join(", ")}`);
|
|
40
|
+
}
|
|
41
|
+
function getRagConfig(env = process.env) {
|
|
42
|
+
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, _K;
|
|
43
|
+
const projectId = (_b = (_a = readString(env, "RAG_PROJECT_ID")) != null ? _a : readString(env, "NEXT_PUBLIC_PROJECT_ID")) != null ? _b : "__default__";
|
|
44
|
+
const vectorProvider = readEnum(env, "VECTOR_DB_PROVIDER", "pinecone", VECTOR_DB_PROVIDERS);
|
|
45
|
+
const llmProvider = readEnum(env, "LLM_PROVIDER", "openai", LLM_PROVIDERS);
|
|
46
|
+
const embeddingProvider = readEnum(env, "EMBEDDING_PROVIDER", "openai", EMBEDDING_PROVIDERS);
|
|
47
|
+
const embeddingDimensions = readNumber(env, "EMBEDDING_DIMENSIONS", 1536);
|
|
48
|
+
const vectorDbOptions = {};
|
|
49
|
+
if (vectorProvider === "pinecone") {
|
|
50
|
+
vectorDbOptions.apiKey = (_c = readString(env, "PINECONE_API_KEY")) != null ? _c : "";
|
|
51
|
+
vectorDbOptions.environment = (_d = readString(env, "PINECONE_ENVIRONMENT")) != null ? _d : "";
|
|
52
|
+
} else if (vectorProvider === "pgvector") {
|
|
53
|
+
vectorDbOptions.connectionString = (_e = readString(env, "PGVECTOR_CONNECTION_STRING")) != null ? _e : "";
|
|
54
|
+
vectorDbOptions.dimensions = embeddingDimensions;
|
|
55
|
+
} else if (vectorProvider === "rest") {
|
|
56
|
+
vectorDbOptions.baseUrl = (_f = readString(env, "VECTOR_DB_REST_URL")) != null ? _f : "";
|
|
57
|
+
vectorDbOptions.headers = readString(env, "VECTOR_DB_REST_API_KEY") ? { "api-key": readString(env, "VECTOR_DB_REST_API_KEY") } : {};
|
|
58
|
+
} else if (vectorProvider === "universal_rest") {
|
|
59
|
+
vectorDbOptions.baseUrl = (_h = (_g = readString(env, "VECTOR_BASE_URL")) != null ? _g : readString(env, "VECTOR_DB_REST_URL")) != null ? _h : "";
|
|
60
|
+
vectorDbOptions.profile = readString(env, "VECTOR_UNIVERSAL_PROFILE");
|
|
61
|
+
vectorDbOptions.headers = readString(env, "VECTOR_DB_REST_API_KEY") ? { Authorization: `Bearer ${readString(env, "VECTOR_DB_REST_API_KEY")}` } : {};
|
|
62
|
+
} else if (vectorProvider === "mongodb") {
|
|
63
|
+
vectorDbOptions.uri = (_i = readString(env, "MONGODB_URI")) != null ? _i : "";
|
|
64
|
+
vectorDbOptions.database = (_j = readString(env, "MONGODB_DB")) != null ? _j : "";
|
|
65
|
+
vectorDbOptions.collection = (_k = readString(env, "MONGODB_COLLECTION")) != null ? _k : "";
|
|
66
|
+
vectorDbOptions.indexName = (_l = readString(env, "MONGODB_INDEX_NAME")) != null ? _l : "vector_index";
|
|
67
|
+
} else if (vectorProvider === "qdrant") {
|
|
68
|
+
vectorDbOptions.baseUrl = (_m = readString(env, "QDRANT_URL")) != null ? _m : "http://localhost:6333";
|
|
69
|
+
vectorDbOptions.apiKey = readString(env, "QDRANT_API_KEY");
|
|
70
|
+
}
|
|
71
|
+
const llmApiKeyByProvider = {
|
|
72
|
+
openai: readString(env, "OPENAI_API_KEY"),
|
|
73
|
+
anthropic: readString(env, "ANTHROPIC_API_KEY"),
|
|
74
|
+
ollama: void 0,
|
|
75
|
+
universal_rest: readString(env, "LLM_API_KEY")
|
|
76
|
+
};
|
|
77
|
+
const embeddingApiKeyByProvider = {
|
|
78
|
+
openai: readString(env, "OPENAI_API_KEY"),
|
|
79
|
+
ollama: void 0,
|
|
80
|
+
custom: (_n = readString(env, "EMBEDDING_API_KEY")) != null ? _n : readString(env, "OPENAI_API_KEY")
|
|
81
|
+
};
|
|
82
|
+
return {
|
|
83
|
+
projectId,
|
|
84
|
+
vectorDb: {
|
|
85
|
+
provider: vectorProvider,
|
|
86
|
+
indexName: (_o = readString(env, "VECTOR_DB_INDEX")) != null ? _o : "rag-index",
|
|
87
|
+
options: vectorDbOptions
|
|
88
|
+
},
|
|
89
|
+
llm: {
|
|
90
|
+
provider: llmProvider,
|
|
91
|
+
model: (_p = readString(env, "LLM_MODEL")) != null ? _p : "gpt-4o",
|
|
92
|
+
apiKey: (_q = llmApiKeyByProvider[llmProvider]) != null ? _q : "",
|
|
93
|
+
baseUrl: readString(env, "LLM_BASE_URL"),
|
|
94
|
+
systemPrompt: readString(env, "LLM_SYSTEM_PROMPT"),
|
|
95
|
+
maxTokens: readNumber(env, "LLM_MAX_TOKENS", 1024),
|
|
96
|
+
temperature: readNumber(env, "LLM_TEMPERATURE", 0.7),
|
|
97
|
+
options: {
|
|
98
|
+
profile: readString(env, "LLM_UNIVERSAL_PROFILE")
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
embedding: {
|
|
102
|
+
provider: embeddingProvider,
|
|
103
|
+
model: (_r = readString(env, "EMBEDDING_MODEL")) != null ? _r : "text-embedding-3-small",
|
|
104
|
+
apiKey: embeddingApiKeyByProvider[embeddingProvider],
|
|
105
|
+
baseUrl: readString(env, "EMBEDDING_BASE_URL"),
|
|
106
|
+
dimensions: embeddingDimensions,
|
|
107
|
+
options: {
|
|
108
|
+
profile: readString(env, "EMBEDDING_UNIVERSAL_PROFILE")
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
ui: {
|
|
112
|
+
title: (_t = (_s = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _s : readString(env, "UI_TITLE")) != null ? _t : "AI Assistant",
|
|
113
|
+
subtitle: (_v = (_u = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _u : readString(env, "UI_SUBTITLE")) != null ? _v : "Powered by RAG",
|
|
114
|
+
primaryColor: (_x = (_w = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _w : readString(env, "UI_PRIMARY_COLOR")) != null ? _x : "#10b981",
|
|
115
|
+
accentColor: (_z = (_y = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _y : readString(env, "UI_ACCENT_COLOR")) != null ? _z : "#3b82f6",
|
|
116
|
+
logoUrl: (_A = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _A : readString(env, "UI_LOGO_URL"),
|
|
117
|
+
placeholder: (_C = (_B = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _B : readString(env, "UI_PLACEHOLDER")) != null ? _C : "Ask me anything\u2026",
|
|
118
|
+
showSources: ((_E = (_D = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _D : readString(env, "UI_SHOW_SOURCES")) != null ? _E : "true") !== "false",
|
|
119
|
+
welcomeMessage: (_G = (_F = readString(env, "NEXT_PUBLIC_WELCOME_MESSAGE")) != null ? _F : readString(env, "UI_WELCOME_MESSAGE")) != null ? _G : "Hello! I'm your AI assistant. Ask me anything about your documents.",
|
|
120
|
+
visualStyle: (_I = (_H = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _H : readString(env, "UI_VISUAL_STYLE")) != null ? _I : "glass",
|
|
121
|
+
borderRadius: (_K = (_J = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _J : readString(env, "UI_BORDER_RADIUS")) != null ? _K : "xl"
|
|
122
|
+
},
|
|
123
|
+
rag: {
|
|
124
|
+
topK: readNumber(env, "RAG_TOP_K", 5),
|
|
125
|
+
scoreThreshold: readNumber(env, "RAG_SCORE_THRESHOLD", 0),
|
|
126
|
+
chunkSize: readNumber(env, "RAG_CHUNK_SIZE", 1e3),
|
|
127
|
+
chunkOverlap: readNumber(env, "RAG_CHUNK_OVERLAP", 200)
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/core/ConfigResolver.ts
|
|
133
|
+
var ConfigResolver = class {
|
|
134
|
+
/**
|
|
135
|
+
* Resolves the final configuration by merging host-provided config with defaults.
|
|
136
|
+
* @param hostConfig - Partial configuration passed from the host application.
|
|
137
|
+
*/
|
|
138
|
+
static resolve(hostConfig) {
|
|
139
|
+
const envConfig = getRagConfig();
|
|
140
|
+
if (!hostConfig) {
|
|
141
|
+
return envConfig;
|
|
142
|
+
}
|
|
143
|
+
return __spreadProps(__spreadValues(__spreadValues({}, envConfig), hostConfig), {
|
|
144
|
+
projectId: hostConfig.projectId || envConfig.projectId,
|
|
145
|
+
vectorDb: hostConfig.vectorDb ? __spreadProps(__spreadValues(__spreadValues({}, envConfig.vectorDb), hostConfig.vectorDb), {
|
|
146
|
+
options: __spreadValues(__spreadValues({}, envConfig.vectorDb.options), hostConfig.vectorDb.options || {})
|
|
147
|
+
}) : envConfig.vectorDb,
|
|
148
|
+
llm: hostConfig.llm ? __spreadProps(__spreadValues(__spreadValues({}, envConfig.llm), hostConfig.llm), {
|
|
149
|
+
options: __spreadValues(__spreadValues({}, envConfig.llm.options || {}), hostConfig.llm.options || {})
|
|
150
|
+
}) : envConfig.llm,
|
|
151
|
+
embedding: hostConfig.embedding ? __spreadProps(__spreadValues(__spreadValues({}, envConfig.embedding), hostConfig.embedding), {
|
|
152
|
+
options: __spreadValues(__spreadValues({}, envConfig.embedding.options || {}), hostConfig.embedding.options || {})
|
|
153
|
+
}) : envConfig.embedding,
|
|
154
|
+
ui: hostConfig.ui ? mergeDefined(envConfig.ui, hostConfig.ui) : envConfig.ui,
|
|
155
|
+
rag: hostConfig.rag ? __spreadValues(__spreadValues({}, envConfig.rag), hostConfig.rag) : envConfig.rag
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Validates the configuration for required fields.
|
|
160
|
+
*/
|
|
161
|
+
static validate(config) {
|
|
162
|
+
if (!config.projectId) {
|
|
163
|
+
throw new Error("[ConfigResolver] projectId is required");
|
|
164
|
+
}
|
|
165
|
+
if (!config.vectorDb.provider) {
|
|
166
|
+
throw new Error("[ConfigResolver] vectorDb.provider is required");
|
|
167
|
+
}
|
|
168
|
+
if (!config.llm.provider) {
|
|
169
|
+
throw new Error("[ConfigResolver] llm.provider is required");
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
// src/core/ConfigValidator.ts
|
|
175
|
+
var ConfigValidator = class {
|
|
176
|
+
/**
|
|
177
|
+
* Validates the entire RagConfig object.
|
|
178
|
+
* Returns an array of validation errors. Empty array = valid config.
|
|
179
|
+
*/
|
|
180
|
+
static validate(config) {
|
|
181
|
+
const errors = [];
|
|
182
|
+
if (!config.projectId) {
|
|
183
|
+
errors.push({
|
|
184
|
+
field: "projectId",
|
|
185
|
+
message: "projectId is required",
|
|
186
|
+
severity: "error"
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
errors.push(...this.validateVectorDbConfig(config.vectorDb));
|
|
190
|
+
errors.push(...this.validateLLMConfig(config.llm));
|
|
191
|
+
if (config.embedding) {
|
|
192
|
+
errors.push(...this.validateEmbeddingConfig(config.embedding));
|
|
193
|
+
} else if (config.llm.provider === "anthropic") {
|
|
194
|
+
errors.push({
|
|
195
|
+
field: "embedding",
|
|
196
|
+
message: "Embedding config is required when using Anthropic LLM",
|
|
197
|
+
suggestion: 'Provide embedding config with provider (e.g., "openai")',
|
|
198
|
+
severity: "error"
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
if (config.ui) {
|
|
202
|
+
errors.push(...this.validateUIConfig(config.ui));
|
|
203
|
+
}
|
|
204
|
+
if (config.rag) {
|
|
205
|
+
errors.push(...this.validateRAGConfig(config.rag));
|
|
206
|
+
}
|
|
207
|
+
return errors;
|
|
208
|
+
}
|
|
209
|
+
static validateVectorDbConfig(config) {
|
|
210
|
+
const errors = [];
|
|
211
|
+
if (!config.provider) {
|
|
212
|
+
errors.push({
|
|
213
|
+
field: "vectorDb.provider",
|
|
214
|
+
message: "Vector database provider is required",
|
|
215
|
+
severity: "error"
|
|
216
|
+
});
|
|
217
|
+
return errors;
|
|
218
|
+
}
|
|
219
|
+
if (!config.indexName) {
|
|
220
|
+
errors.push({
|
|
221
|
+
field: "vectorDb.indexName",
|
|
222
|
+
message: "Vector database index name is required",
|
|
223
|
+
severity: "error"
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
switch (config.provider) {
|
|
227
|
+
case "pinecone":
|
|
228
|
+
errors.push(...this.validatePineconeConfig(config));
|
|
229
|
+
break;
|
|
230
|
+
case "pgvector":
|
|
231
|
+
case "postgresql":
|
|
232
|
+
errors.push(...this.validatePostgresConfig(config));
|
|
233
|
+
break;
|
|
234
|
+
case "mongodb":
|
|
235
|
+
errors.push(...this.validateMongoDBConfig(config));
|
|
236
|
+
break;
|
|
237
|
+
case "milvus":
|
|
238
|
+
errors.push(...this.validateMilvusConfig(config));
|
|
239
|
+
break;
|
|
240
|
+
case "qdrant":
|
|
241
|
+
errors.push(...this.validateQdrantConfig(config));
|
|
242
|
+
break;
|
|
243
|
+
case "chromadb":
|
|
244
|
+
errors.push(...this.validateChromaDBConfig(config));
|
|
245
|
+
break;
|
|
246
|
+
case "redis":
|
|
247
|
+
errors.push(...this.validateRedisConfig(config));
|
|
248
|
+
break;
|
|
249
|
+
case "weaviate":
|
|
250
|
+
errors.push(...this.validateWeaviateConfig(config));
|
|
251
|
+
break;
|
|
252
|
+
case "universal_rest":
|
|
253
|
+
case "rest":
|
|
254
|
+
errors.push(...this.validateRestConfig(config));
|
|
255
|
+
break;
|
|
256
|
+
}
|
|
257
|
+
return errors;
|
|
258
|
+
}
|
|
259
|
+
static validatePineconeConfig(config) {
|
|
260
|
+
const errors = [];
|
|
261
|
+
const opts = config.options;
|
|
262
|
+
if (!opts.apiKey) {
|
|
263
|
+
errors.push({
|
|
264
|
+
field: "vectorDb.options.apiKey",
|
|
265
|
+
message: "Pinecone API key is required",
|
|
266
|
+
suggestion: "Set PINECONE_API_KEY environment variable",
|
|
267
|
+
severity: "error"
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
if (!opts.environment) {
|
|
271
|
+
errors.push({
|
|
272
|
+
field: "vectorDb.options.environment",
|
|
273
|
+
message: "Pinecone environment is required",
|
|
274
|
+
suggestion: 'Set PINECONE_ENVIRONMENT environment variable (e.g., "gcp-starter")',
|
|
275
|
+
severity: "error"
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
return errors;
|
|
279
|
+
}
|
|
280
|
+
static validatePostgresConfig(config) {
|
|
281
|
+
const errors = [];
|
|
282
|
+
const opts = config.options;
|
|
283
|
+
if (!opts.connectionString) {
|
|
284
|
+
errors.push({
|
|
285
|
+
field: "vectorDb.options.connectionString",
|
|
286
|
+
message: "PostgreSQL connection string is required",
|
|
287
|
+
suggestion: "Set PGVECTOR_CONNECTION_STRING environment variable",
|
|
288
|
+
severity: "error"
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
return errors;
|
|
292
|
+
}
|
|
293
|
+
static validateMongoDBConfig(config) {
|
|
294
|
+
const errors = [];
|
|
295
|
+
const opts = config.options;
|
|
296
|
+
if (!opts.uri) {
|
|
297
|
+
errors.push({
|
|
298
|
+
field: "vectorDb.options.uri",
|
|
299
|
+
message: "MongoDB connection URI is required",
|
|
300
|
+
suggestion: "Set MONGODB_URI environment variable",
|
|
301
|
+
severity: "error"
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
if (!opts.database) {
|
|
305
|
+
errors.push({
|
|
306
|
+
field: "vectorDb.options.database",
|
|
307
|
+
message: "MongoDB database name is required",
|
|
308
|
+
suggestion: "Set MONGODB_DB environment variable",
|
|
309
|
+
severity: "error"
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
if (!opts.collection) {
|
|
313
|
+
errors.push({
|
|
314
|
+
field: "vectorDb.options.collection",
|
|
315
|
+
message: "MongoDB collection name is required",
|
|
316
|
+
suggestion: "Set MONGODB_COLLECTION environment variable",
|
|
317
|
+
severity: "error"
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
return errors;
|
|
321
|
+
}
|
|
322
|
+
static validateMilvusConfig(config) {
|
|
323
|
+
const errors = [];
|
|
324
|
+
const opts = config.options;
|
|
325
|
+
if (!opts.host) {
|
|
326
|
+
errors.push({
|
|
327
|
+
field: "vectorDb.options.host",
|
|
328
|
+
message: "Milvus host is required",
|
|
329
|
+
suggestion: "Set MILVUS_HOST environment variable",
|
|
330
|
+
severity: "error"
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
if (!opts.port) {
|
|
334
|
+
errors.push({
|
|
335
|
+
field: "vectorDb.options.port",
|
|
336
|
+
message: "Milvus port is required",
|
|
337
|
+
suggestion: "Set MILVUS_PORT environment variable (default: 19530)",
|
|
338
|
+
severity: "error"
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
return errors;
|
|
342
|
+
}
|
|
343
|
+
static validateQdrantConfig(config) {
|
|
344
|
+
const errors = [];
|
|
345
|
+
const opts = config.options;
|
|
346
|
+
if (!opts.baseUrl && !opts.url) {
|
|
347
|
+
errors.push({
|
|
348
|
+
field: "vectorDb.options.baseUrl",
|
|
349
|
+
message: "Qdrant base URL is required",
|
|
350
|
+
suggestion: 'Set QDRANT_URL environment variable (e.g., "http://localhost:6333")',
|
|
351
|
+
severity: "error"
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
return errors;
|
|
355
|
+
}
|
|
356
|
+
static validateChromaDBConfig(config) {
|
|
357
|
+
const errors = [];
|
|
358
|
+
const opts = config.options;
|
|
359
|
+
if (!opts.host && !opts.path) {
|
|
360
|
+
errors.push({
|
|
361
|
+
field: "vectorDb.options.host",
|
|
362
|
+
message: "ChromaDB host or path is required",
|
|
363
|
+
suggestion: "Set CHROMADB_HOST or CHROMADB_PATH environment variable",
|
|
364
|
+
severity: "error"
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
return errors;
|
|
368
|
+
}
|
|
369
|
+
static validateRedisConfig(config) {
|
|
370
|
+
const errors = [];
|
|
371
|
+
const opts = config.options;
|
|
372
|
+
if (!opts.url && (!opts.host || !opts.port)) {
|
|
373
|
+
errors.push({
|
|
374
|
+
field: "vectorDb.options.url",
|
|
375
|
+
message: "Redis connection URL or host:port is required",
|
|
376
|
+
suggestion: "Set REDIS_URL or REDIS_HOST/REDIS_PORT environment variables",
|
|
377
|
+
severity: "error"
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
return errors;
|
|
381
|
+
}
|
|
382
|
+
static validateWeaviateConfig(config) {
|
|
383
|
+
const errors = [];
|
|
384
|
+
const opts = config.options;
|
|
385
|
+
if (!opts.url) {
|
|
386
|
+
errors.push({
|
|
387
|
+
field: "vectorDb.options.url",
|
|
388
|
+
message: "Weaviate instance URL is required",
|
|
389
|
+
suggestion: "Set WEAVIATE_URL environment variable",
|
|
390
|
+
severity: "error"
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
return errors;
|
|
394
|
+
}
|
|
395
|
+
static validateRestConfig(config) {
|
|
396
|
+
const errors = [];
|
|
397
|
+
const opts = config.options;
|
|
398
|
+
if (!opts.baseUrl) {
|
|
399
|
+
errors.push({
|
|
400
|
+
field: "vectorDb.options.baseUrl",
|
|
401
|
+
message: "REST API base URL is required",
|
|
402
|
+
suggestion: "Set VECTOR_BASE_URL environment variable",
|
|
403
|
+
severity: "error"
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
return errors;
|
|
407
|
+
}
|
|
408
|
+
static validateLLMConfig(config) {
|
|
409
|
+
var _a;
|
|
410
|
+
const errors = [];
|
|
411
|
+
if (!config.provider) {
|
|
412
|
+
errors.push({
|
|
413
|
+
field: "llm.provider",
|
|
414
|
+
message: "LLM provider is required",
|
|
415
|
+
severity: "error"
|
|
416
|
+
});
|
|
417
|
+
return errors;
|
|
418
|
+
}
|
|
419
|
+
if (!config.model) {
|
|
420
|
+
errors.push({
|
|
421
|
+
field: "llm.model",
|
|
422
|
+
message: "LLM model name is required",
|
|
423
|
+
suggestion: `e.g., "gpt-4o" for OpenAI, "claude-3-opus" for Anthropic`,
|
|
424
|
+
severity: "error"
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
switch (config.provider) {
|
|
428
|
+
case "openai":
|
|
429
|
+
if (!config.apiKey) {
|
|
430
|
+
errors.push({
|
|
431
|
+
field: "llm.apiKey",
|
|
432
|
+
message: "OpenAI API key is required",
|
|
433
|
+
suggestion: "Set OPENAI_API_KEY environment variable",
|
|
434
|
+
severity: "error"
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
break;
|
|
438
|
+
case "anthropic":
|
|
439
|
+
if (!config.apiKey) {
|
|
440
|
+
errors.push({
|
|
441
|
+
field: "llm.apiKey",
|
|
442
|
+
message: "Anthropic API key is required",
|
|
443
|
+
suggestion: "Set ANTHROPIC_API_KEY environment variable",
|
|
444
|
+
severity: "error"
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
break;
|
|
448
|
+
case "ollama":
|
|
449
|
+
if (!config.baseUrl) {
|
|
450
|
+
errors.push({
|
|
451
|
+
field: "llm.baseUrl",
|
|
452
|
+
message: "Ollama base URL is required",
|
|
453
|
+
suggestion: 'Set LLM_BASE_URL environment variable (e.g., "http://localhost:11434")',
|
|
454
|
+
severity: "error"
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
break;
|
|
458
|
+
case "rest":
|
|
459
|
+
case "universal_rest":
|
|
460
|
+
if (!config.baseUrl && !((_a = config.options) == null ? void 0 : _a.baseUrl)) {
|
|
461
|
+
errors.push({
|
|
462
|
+
field: "llm.baseUrl",
|
|
463
|
+
message: "REST API base URL is required",
|
|
464
|
+
suggestion: "Set LLM_BASE_URL environment variable",
|
|
465
|
+
severity: "error"
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
break;
|
|
469
|
+
}
|
|
470
|
+
if (config.temperature !== void 0) {
|
|
471
|
+
if (config.temperature < 0 || config.temperature > 2) {
|
|
472
|
+
errors.push({
|
|
473
|
+
field: "llm.temperature",
|
|
474
|
+
message: "Temperature must be between 0 and 2",
|
|
475
|
+
severity: "error"
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (config.maxTokens !== void 0 && config.maxTokens <= 0) {
|
|
480
|
+
errors.push({
|
|
481
|
+
field: "llm.maxTokens",
|
|
482
|
+
message: "maxTokens must be greater than 0",
|
|
483
|
+
severity: "error"
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
return errors;
|
|
487
|
+
}
|
|
488
|
+
static validateEmbeddingConfig(config) {
|
|
489
|
+
const errors = [];
|
|
490
|
+
if (!config.provider) {
|
|
491
|
+
errors.push({
|
|
492
|
+
field: "embedding.provider",
|
|
493
|
+
message: "Embedding provider is required",
|
|
494
|
+
severity: "error"
|
|
495
|
+
});
|
|
496
|
+
return errors;
|
|
497
|
+
}
|
|
498
|
+
if (!config.model) {
|
|
499
|
+
errors.push({
|
|
500
|
+
field: "embedding.model",
|
|
501
|
+
message: "Embedding model name is required",
|
|
502
|
+
suggestion: 'e.g., "text-embedding-3-small" for OpenAI',
|
|
503
|
+
severity: "error"
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
if (config.provider === "openai" && !config.apiKey) {
|
|
507
|
+
errors.push({
|
|
508
|
+
field: "embedding.apiKey",
|
|
509
|
+
message: "OpenAI API key is required for embedding",
|
|
510
|
+
suggestion: "Set OPENAI_API_KEY environment variable",
|
|
511
|
+
severity: "error"
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
if (config.provider === "ollama" && !config.baseUrl) {
|
|
515
|
+
errors.push({
|
|
516
|
+
field: "embedding.baseUrl",
|
|
517
|
+
message: "Ollama base URL is required",
|
|
518
|
+
suggestion: "Set EMBEDDING_BASE_URL environment variable",
|
|
519
|
+
severity: "error"
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
if (config.dimensions !== void 0 && config.dimensions <= 0) {
|
|
523
|
+
errors.push({
|
|
524
|
+
field: "embedding.dimensions",
|
|
525
|
+
message: "Embedding dimensions must be greater than 0",
|
|
526
|
+
severity: "error"
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
return errors;
|
|
530
|
+
}
|
|
531
|
+
static validateUIConfig(config) {
|
|
532
|
+
const errors = [];
|
|
533
|
+
if (config.primaryColor) {
|
|
534
|
+
if (!this.isValidCSSColor(config.primaryColor)) {
|
|
535
|
+
errors.push({
|
|
536
|
+
field: "ui.primaryColor",
|
|
537
|
+
message: "Invalid CSS color format",
|
|
538
|
+
suggestion: "Use valid CSS colors: hex (#FF0000), rgb, hsl, or named colors",
|
|
539
|
+
severity: "warning"
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
if (config.borderRadius) {
|
|
544
|
+
const validValues = ["none", "sm", "md", "lg", "xl", "full"];
|
|
545
|
+
if (!validValues.includes(config.borderRadius)) {
|
|
546
|
+
errors.push({
|
|
547
|
+
field: "ui.borderRadius",
|
|
548
|
+
message: `borderRadius must be one of: ${validValues.join(", ")}`,
|
|
549
|
+
severity: "warning"
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
if (config.visualStyle) {
|
|
554
|
+
const validValues = ["glass", "solid"];
|
|
555
|
+
if (!validValues.includes(config.visualStyle)) {
|
|
556
|
+
errors.push({
|
|
557
|
+
field: "ui.visualStyle",
|
|
558
|
+
message: `visualStyle must be one of: ${validValues.join(", ")}`,
|
|
559
|
+
severity: "warning"
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
return errors;
|
|
564
|
+
}
|
|
565
|
+
static validateRAGConfig(config) {
|
|
566
|
+
const errors = [];
|
|
567
|
+
if (config.topK !== void 0) {
|
|
568
|
+
if (typeof config.topK !== "number" || config.topK <= 0) {
|
|
569
|
+
errors.push({
|
|
570
|
+
field: "rag.topK",
|
|
571
|
+
message: "topK must be a positive integer",
|
|
572
|
+
severity: "error"
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
if (config.scoreThreshold !== void 0) {
|
|
577
|
+
if (typeof config.scoreThreshold !== "number" || config.scoreThreshold < 0 || config.scoreThreshold > 1) {
|
|
578
|
+
errors.push({
|
|
579
|
+
field: "rag.scoreThreshold",
|
|
580
|
+
message: "scoreThreshold must be between 0 and 1",
|
|
581
|
+
severity: "error"
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
if (config.chunkSize !== void 0) {
|
|
586
|
+
if (typeof config.chunkSize !== "number" || config.chunkSize <= 0) {
|
|
587
|
+
errors.push({
|
|
588
|
+
field: "rag.chunkSize",
|
|
589
|
+
message: "chunkSize must be a positive integer",
|
|
590
|
+
severity: "error"
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
if (config.chunkOverlap !== void 0) {
|
|
595
|
+
if (typeof config.chunkOverlap !== "number" || config.chunkOverlap < 0) {
|
|
596
|
+
errors.push({
|
|
597
|
+
field: "rag.chunkOverlap",
|
|
598
|
+
message: "chunkOverlap must be a non-negative integer",
|
|
599
|
+
severity: "error"
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
return errors;
|
|
604
|
+
}
|
|
605
|
+
static isValidCSSColor(color) {
|
|
606
|
+
const s = new Option().style;
|
|
607
|
+
s.color = color;
|
|
608
|
+
return s.color !== "";
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Throws if there are error-level validation issues.
|
|
612
|
+
* Logs warnings to console.
|
|
613
|
+
*/
|
|
614
|
+
static validateAndThrow(config) {
|
|
615
|
+
const errors = this.validate(config);
|
|
616
|
+
const errorItems = errors.filter((e) => e.severity === "error");
|
|
617
|
+
const warnings = errors.filter((e) => e.severity === "warning");
|
|
618
|
+
if (warnings.length > 0) {
|
|
619
|
+
console.warn("[ConfigValidator] Configuration warnings:");
|
|
620
|
+
warnings.forEach((w) => {
|
|
621
|
+
console.warn(` ${w.field}: ${w.message}`);
|
|
622
|
+
if (w.suggestion) console.warn(` Suggestion: ${w.suggestion}`);
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
if (errorItems.length > 0) {
|
|
626
|
+
const message = errorItems.map((e) => `${e.field}: ${e.message}${e.suggestion ? ` (${e.suggestion})` : ""}`).join("\n ");
|
|
627
|
+
throw new Error(`[ConfigValidator] Configuration validation failed:
|
|
628
|
+
${message}`);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
};
|
|
632
|
+
|
|
633
|
+
// src/rag/DocumentChunker.ts
|
|
634
|
+
var DocumentChunker = class {
|
|
635
|
+
constructor(chunkSize = 1e3, chunkOverlap = 200) {
|
|
636
|
+
this.chunkSize = chunkSize;
|
|
637
|
+
this.chunkOverlap = chunkOverlap;
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* Split a single text string into overlapping chunks.
|
|
641
|
+
*/
|
|
642
|
+
chunk(text, options = {}) {
|
|
643
|
+
const {
|
|
644
|
+
chunkSize = this.chunkSize,
|
|
645
|
+
chunkOverlap = this.chunkOverlap,
|
|
646
|
+
docId = `doc_${Date.now()}`,
|
|
647
|
+
metadata = {}
|
|
648
|
+
} = options;
|
|
649
|
+
const cleaned = text.replace(/\r\n/g, "\n").trim();
|
|
650
|
+
if (!cleaned) return [];
|
|
651
|
+
const sentences = cleaned.split(new RegExp("(?<=[.!?])\\s+|\\n{2,}")).map((s) => s.trim()).filter(Boolean);
|
|
652
|
+
const chunks = [];
|
|
653
|
+
let current = "";
|
|
654
|
+
let chunkIndex = 0;
|
|
655
|
+
for (const sentence of sentences) {
|
|
656
|
+
if ((current + " " + sentence).trim().length <= chunkSize) {
|
|
657
|
+
current = current ? `${current} ${sentence}` : sentence;
|
|
658
|
+
} else {
|
|
659
|
+
if (current) {
|
|
660
|
+
chunks.push({
|
|
661
|
+
id: `${docId}_chunk_${chunkIndex++}`,
|
|
662
|
+
content: current.trim(),
|
|
663
|
+
metadata: __spreadProps(__spreadValues({}, metadata), { docId, chunkIndex: chunkIndex - 1 })
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
if (chunkOverlap > 0 && current.length > chunkOverlap) {
|
|
667
|
+
current = current.slice(-chunkOverlap) + " " + sentence;
|
|
668
|
+
} else {
|
|
669
|
+
current = sentence;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
if (current.trim()) {
|
|
674
|
+
chunks.push({
|
|
675
|
+
id: `${docId}_chunk_${chunkIndex}`,
|
|
676
|
+
content: current.trim(),
|
|
677
|
+
metadata: __spreadProps(__spreadValues({}, metadata), { docId, chunkIndex })
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
return chunks;
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Chunk multiple documents at once.
|
|
684
|
+
*/
|
|
685
|
+
chunkMany(documents) {
|
|
686
|
+
return documents.flatMap(
|
|
687
|
+
(doc) => this.chunk(doc.content, { docId: doc.docId, metadata: doc.metadata })
|
|
688
|
+
);
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
|
|
692
|
+
// src/core/ProviderRegistry.ts
|
|
693
|
+
var ProviderRegistry = class {
|
|
694
|
+
/**
|
|
695
|
+
* Register a custom vector provider.
|
|
696
|
+
*/
|
|
697
|
+
static registerVectorProvider(name, providerClass) {
|
|
698
|
+
this.vectorProviders[name] = providerClass;
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Creates a vector database provider based on the configuration.
|
|
702
|
+
*/
|
|
703
|
+
static async createVectorProvider(config) {
|
|
704
|
+
const { provider } = config;
|
|
705
|
+
if (this.vectorProviders[provider]) {
|
|
706
|
+
return new this.vectorProviders[provider](config);
|
|
707
|
+
}
|
|
708
|
+
switch (provider) {
|
|
709
|
+
case "pinecone":
|
|
710
|
+
const { PineconeProvider } = await import("./PineconeProvider-ZRAFNFEC.mjs");
|
|
711
|
+
return new PineconeProvider(config);
|
|
712
|
+
case "pgvector":
|
|
713
|
+
case "postgresql":
|
|
714
|
+
const { PostgreSQLProvider } = await import("./PostgreSQLProvider-ZNXA67IM.mjs");
|
|
715
|
+
return new PostgreSQLProvider(config);
|
|
716
|
+
case "mongodb":
|
|
717
|
+
const { MongoDBProvider } = await import("./MongoDBProvider-WWVJG3WT.mjs");
|
|
718
|
+
return new MongoDBProvider(config);
|
|
719
|
+
case "milvus":
|
|
720
|
+
const { MilvusProvider } = await import("./MilvusProvider-OO6QGZDZ.mjs");
|
|
721
|
+
return new MilvusProvider(config);
|
|
722
|
+
case "qdrant":
|
|
723
|
+
const { QdrantProvider } = await import("./QdrantProvider-NYGHAA7C.mjs");
|
|
724
|
+
return new QdrantProvider(config);
|
|
725
|
+
case "chromadb":
|
|
726
|
+
const { ChromaDBProvider } = await import("./ChromaDBProvider-QNI7UCX4.mjs");
|
|
727
|
+
return new ChromaDBProvider(config);
|
|
728
|
+
case "redis":
|
|
729
|
+
const { RedisProvider } = await import("./RedisProvider-ASONNYBI.mjs");
|
|
730
|
+
return new RedisProvider(config);
|
|
731
|
+
case "weaviate":
|
|
732
|
+
const { WeaviateProvider } = await import("./WeaviateProvider-PSDCUGC7.mjs");
|
|
733
|
+
return new WeaviateProvider(config);
|
|
734
|
+
default:
|
|
735
|
+
throw new Error(`[ProviderRegistry] Unsupported vector provider: ${provider}`);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Creates an LLM provider based on the configuration.
|
|
740
|
+
*/
|
|
741
|
+
static createLLMProvider(llmConfig, embeddingConfig) {
|
|
742
|
+
return LLMFactory.create(llmConfig, embeddingConfig);
|
|
743
|
+
}
|
|
744
|
+
};
|
|
745
|
+
ProviderRegistry.vectorProviders = {};
|
|
746
|
+
|
|
747
|
+
// src/core/BatchProcessor.ts
|
|
748
|
+
function isTransientError(error) {
|
|
749
|
+
if (!(error instanceof Error)) return false;
|
|
750
|
+
const message = error.message.toLowerCase();
|
|
751
|
+
if (message.includes("econnrefused") || message.includes("econnreset") || message.includes("timeout") || message.includes("network") || message.includes("socket")) {
|
|
752
|
+
return true;
|
|
753
|
+
}
|
|
754
|
+
if (message.includes("429") || message.includes("503") || message.includes("502") || message.includes("rate limit") || message.includes("too many requests")) {
|
|
755
|
+
return true;
|
|
756
|
+
}
|
|
757
|
+
return false;
|
|
758
|
+
}
|
|
759
|
+
function calculateBackoffDelay(attempt, initialDelayMs, maxDelayMs, multiplier) {
|
|
760
|
+
const exponentialDelay = Math.min(
|
|
761
|
+
initialDelayMs * Math.pow(multiplier, attempt),
|
|
762
|
+
maxDelayMs
|
|
763
|
+
);
|
|
764
|
+
const jitter = exponentialDelay * 0.1 * (Math.random() * 2 - 1);
|
|
765
|
+
return Math.max(0, exponentialDelay + jitter);
|
|
766
|
+
}
|
|
767
|
+
function sleep(ms) {
|
|
768
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
769
|
+
}
|
|
770
|
+
var BatchProcessor = class {
|
|
771
|
+
/**
|
|
772
|
+
* Processes an array of items in configurable batches with retry logic.
|
|
773
|
+
*
|
|
774
|
+
* @param items - Items to process
|
|
775
|
+
* @param processor - Async function that processes a batch of items
|
|
776
|
+
* @param options - Configuration for batch size, retries, etc.
|
|
777
|
+
* @returns Object with results, errors, and statistics
|
|
778
|
+
*
|
|
779
|
+
* @example
|
|
780
|
+
* const docs = [...];
|
|
781
|
+
* const result = await BatchProcessor.processBatch(
|
|
782
|
+
* docs,
|
|
783
|
+
* (batch) => vectorDB.batchUpsert(batch),
|
|
784
|
+
* { batchSize: 100, maxRetries: 3 }
|
|
785
|
+
* );
|
|
786
|
+
*/
|
|
787
|
+
static async processBatch(items, processor, options) {
|
|
788
|
+
const {
|
|
789
|
+
batchSize = 100,
|
|
790
|
+
maxRetries = 3,
|
|
791
|
+
initialDelayMs = 100,
|
|
792
|
+
maxDelayMs = 1e4,
|
|
793
|
+
backoffMultiplier = 2,
|
|
794
|
+
throwOnPartialFailure = false
|
|
795
|
+
} = options != null ? options : {};
|
|
796
|
+
const results = [];
|
|
797
|
+
const errors = [];
|
|
798
|
+
const batches = [];
|
|
799
|
+
for (let i = 0; i < items.length; i += batchSize) {
|
|
800
|
+
batches.push(items.slice(i, i + batchSize));
|
|
801
|
+
}
|
|
802
|
+
if (batches.length === 0) {
|
|
803
|
+
return { results: [], errors: [], totalProcessed: 0, totalFailed: 0 };
|
|
804
|
+
}
|
|
805
|
+
for (let batchIndex = 0; batchIndex < batches.length; batchIndex++) {
|
|
806
|
+
const batch = batches[batchIndex];
|
|
807
|
+
let success = false;
|
|
808
|
+
let lastError;
|
|
809
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
810
|
+
try {
|
|
811
|
+
const result = await processor(batch);
|
|
812
|
+
results.push(result);
|
|
813
|
+
success = true;
|
|
814
|
+
break;
|
|
815
|
+
} catch (err) {
|
|
816
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
817
|
+
if (!isTransientError(err) || attempt === maxRetries) {
|
|
818
|
+
break;
|
|
819
|
+
}
|
|
820
|
+
const delay = calculateBackoffDelay(
|
|
821
|
+
attempt,
|
|
822
|
+
initialDelayMs,
|
|
823
|
+
maxDelayMs,
|
|
824
|
+
backoffMultiplier
|
|
825
|
+
);
|
|
826
|
+
await sleep(delay);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
if (!success && lastError) {
|
|
830
|
+
errors.push({
|
|
831
|
+
index: batchIndex,
|
|
832
|
+
error: lastError,
|
|
833
|
+
itemCount: batch.length
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
const totalProcessed = items.length - (errors.length > 0 ? errors.reduce((sum, e) => sum + (e.itemCount || 0), 0) : 0);
|
|
838
|
+
const totalFailed = errors.reduce((sum, e) => sum + (e.itemCount || 0), 0);
|
|
839
|
+
if (throwOnPartialFailure && errors.length > 0) {
|
|
840
|
+
const errorMessages = errors.map((e) => `Batch ${e.index} (${e.itemCount} items): ${e.error.message}`).join("\n");
|
|
841
|
+
throw new Error(
|
|
842
|
+
`[BatchProcessor] Batch processing failed:
|
|
843
|
+
${errorMessages}`
|
|
844
|
+
);
|
|
845
|
+
}
|
|
846
|
+
return { results, errors, totalProcessed, totalFailed };
|
|
847
|
+
}
|
|
848
|
+
/**
|
|
849
|
+
* Processes items sequentially (one at a time) with retry logic.
|
|
850
|
+
* Useful for operations that don't support batching or when granular
|
|
851
|
+
* error tracking is needed.
|
|
852
|
+
*/
|
|
853
|
+
static async processSequential(items, processor, options) {
|
|
854
|
+
const {
|
|
855
|
+
maxRetries = 3,
|
|
856
|
+
initialDelayMs = 100,
|
|
857
|
+
maxDelayMs = 1e4,
|
|
858
|
+
backoffMultiplier = 2,
|
|
859
|
+
throwOnPartialFailure = false
|
|
860
|
+
} = options != null ? options : {};
|
|
861
|
+
const results = [];
|
|
862
|
+
const errors = [];
|
|
863
|
+
for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
|
|
864
|
+
const item = items[itemIndex];
|
|
865
|
+
let success = false;
|
|
866
|
+
let lastError;
|
|
867
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
868
|
+
try {
|
|
869
|
+
const result = await processor(item);
|
|
870
|
+
results.push(result);
|
|
871
|
+
success = true;
|
|
872
|
+
break;
|
|
873
|
+
} catch (err) {
|
|
874
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
875
|
+
if (!isTransientError(err) || attempt === maxRetries) {
|
|
876
|
+
break;
|
|
877
|
+
}
|
|
878
|
+
const delay = calculateBackoffDelay(
|
|
879
|
+
attempt,
|
|
880
|
+
initialDelayMs,
|
|
881
|
+
maxDelayMs,
|
|
882
|
+
backoffMultiplier
|
|
883
|
+
);
|
|
884
|
+
await sleep(delay);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
if (!success && lastError) {
|
|
888
|
+
errors.push({ index: itemIndex, error: lastError, itemCount: 1 });
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
const totalProcessed = items.length - errors.length;
|
|
892
|
+
const totalFailed = errors.length;
|
|
893
|
+
if (throwOnPartialFailure && errors.length > 0) {
|
|
894
|
+
const errorMessages = errors.map((e) => `Item ${e.index}: ${e.error.message}`).join("\n");
|
|
895
|
+
throw new Error(
|
|
896
|
+
`[BatchProcessor] Sequential processing failed:
|
|
897
|
+
${errorMessages}`
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
return { results, errors, totalProcessed, totalFailed };
|
|
901
|
+
}
|
|
902
|
+
/**
|
|
903
|
+
* Maps over items with retry logic, returning results in order.
|
|
904
|
+
* Like Array.map() but with async processing and automatic retries.
|
|
905
|
+
*/
|
|
906
|
+
static async mapWithRetry(items, mapper, options) {
|
|
907
|
+
const result = await this.processSequential(items, mapper, options);
|
|
908
|
+
if (result.errors.length > 0) {
|
|
909
|
+
console.warn(
|
|
910
|
+
`[BatchProcessor] mapWithRetry: ${result.errors.length} items failed`
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
const orderedResults = new Array(items.length);
|
|
914
|
+
let resultIndex = 0;
|
|
915
|
+
let errorIndex = 0;
|
|
916
|
+
for (let i = 0; i < items.length; i++) {
|
|
917
|
+
if (errorIndex < result.errors.length && result.errors[errorIndex].index === i) {
|
|
918
|
+
orderedResults[i] = void 0;
|
|
919
|
+
errorIndex++;
|
|
920
|
+
} else {
|
|
921
|
+
orderedResults[i] = result.results[resultIndex];
|
|
922
|
+
resultIndex++;
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
return orderedResults.filter((r) => r !== void 0);
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Parallel processor with concurrency limit.
|
|
929
|
+
* Processes up to `concurrency` items at the same time.
|
|
930
|
+
*/
|
|
931
|
+
static async processConcurrent(items, processor, concurrency = 5, options) {
|
|
932
|
+
const { throwOnPartialFailure = false } = options != null ? options : {};
|
|
933
|
+
const results = [];
|
|
934
|
+
const errors = [];
|
|
935
|
+
for (let i = 0; i < items.length; i += concurrency) {
|
|
936
|
+
const chunk = items.slice(i, i + concurrency).map((item, idx) => ({
|
|
937
|
+
item,
|
|
938
|
+
originalIndex: i + idx
|
|
939
|
+
}));
|
|
940
|
+
const chunkPromises = chunk.map(async ({ item, originalIndex }) => {
|
|
941
|
+
try {
|
|
942
|
+
const result = await processor(item);
|
|
943
|
+
return { success: true, result, index: originalIndex };
|
|
944
|
+
} catch (err) {
|
|
945
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
946
|
+
return { success: false, error, index: originalIndex };
|
|
947
|
+
}
|
|
948
|
+
});
|
|
949
|
+
const chunkResults = await Promise.all(chunkPromises);
|
|
950
|
+
for (const { success, result, error, index } of chunkResults) {
|
|
951
|
+
if (success) {
|
|
952
|
+
results.push(result);
|
|
953
|
+
} else {
|
|
954
|
+
errors.push({ index, error, itemCount: 1 });
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
const totalProcessed = items.length - errors.length;
|
|
959
|
+
const totalFailed = errors.length;
|
|
960
|
+
if (throwOnPartialFailure && errors.length > 0) {
|
|
961
|
+
const errorMessages = errors.map((e) => `Item ${e.index}: ${e.error.message}`).join("\n");
|
|
962
|
+
throw new Error(
|
|
963
|
+
`[BatchProcessor] Concurrent processing failed:
|
|
964
|
+
${errorMessages}`
|
|
965
|
+
);
|
|
966
|
+
}
|
|
967
|
+
return { results, errors, totalProcessed, totalFailed };
|
|
968
|
+
}
|
|
969
|
+
};
|
|
970
|
+
|
|
971
|
+
// src/core/Pipeline.ts
|
|
972
|
+
var Pipeline = class {
|
|
973
|
+
constructor(config) {
|
|
974
|
+
this.initialised = false;
|
|
975
|
+
var _a, _b, _c, _d;
|
|
976
|
+
this.config = config;
|
|
977
|
+
this.chunker = new DocumentChunker(
|
|
978
|
+
(_b = (_a = config.rag) == null ? void 0 : _a.chunkSize) != null ? _b : 1e3,
|
|
979
|
+
(_d = (_c = config.rag) == null ? void 0 : _c.chunkOverlap) != null ? _d : 200
|
|
980
|
+
);
|
|
981
|
+
}
|
|
982
|
+
async initialize() {
|
|
983
|
+
if (this.initialised) return;
|
|
984
|
+
this.vectorDB = await ProviderRegistry.createVectorProvider(this.config.vectorDb);
|
|
985
|
+
this.llmProvider = ProviderRegistry.createLLMProvider(this.config.llm, this.config.embedding);
|
|
986
|
+
if (this.config.llm.provider === "anthropic") {
|
|
987
|
+
const { LLMFactory: LLMFactory2 } = await import("./LLMFactory-JFOY2V4X.mjs");
|
|
988
|
+
this.embeddingProvider = LLMFactory2.createEmbeddingProvider(this.config.embedding);
|
|
989
|
+
} else {
|
|
990
|
+
this.embeddingProvider = this.llmProvider;
|
|
991
|
+
}
|
|
992
|
+
await this.vectorDB.initialize();
|
|
993
|
+
this.initialised = true;
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* Ingest documents with automatic chunking, embedding, and batch processing.
|
|
997
|
+
* Handles retries for transient failures.
|
|
998
|
+
*/
|
|
999
|
+
async ingest(documents, namespace) {
|
|
1000
|
+
await this.initialize();
|
|
1001
|
+
const ns = namespace != null ? namespace : this.config.projectId;
|
|
1002
|
+
const results = [];
|
|
1003
|
+
for (const doc of documents) {
|
|
1004
|
+
try {
|
|
1005
|
+
const chunks = this.chunker.chunk(doc.content, {
|
|
1006
|
+
docId: doc.docId,
|
|
1007
|
+
metadata: doc.metadata
|
|
1008
|
+
});
|
|
1009
|
+
const batchOptions = {
|
|
1010
|
+
batchSize: 50,
|
|
1011
|
+
// Embedding batch size
|
|
1012
|
+
maxRetries: 3,
|
|
1013
|
+
initialDelayMs: 100
|
|
1014
|
+
};
|
|
1015
|
+
const vectors = await BatchProcessor.mapWithRetry(
|
|
1016
|
+
chunks.map((c) => c.content),
|
|
1017
|
+
(text) => this.embeddingProvider.embed(text),
|
|
1018
|
+
batchOptions
|
|
1019
|
+
);
|
|
1020
|
+
if (vectors.length !== chunks.length) {
|
|
1021
|
+
throw new Error(`Embedding failed: got ${vectors.length} vectors for ${chunks.length} chunks`);
|
|
1022
|
+
}
|
|
1023
|
+
const upsertDocs = chunks.map((chunk, i) => ({
|
|
1024
|
+
id: chunk.id,
|
|
1025
|
+
vector: vectors[i],
|
|
1026
|
+
content: chunk.content,
|
|
1027
|
+
metadata: chunk.metadata
|
|
1028
|
+
}));
|
|
1029
|
+
const upsertBatchOptions = {
|
|
1030
|
+
batchSize: 100,
|
|
1031
|
+
maxRetries: 3,
|
|
1032
|
+
initialDelayMs: 100
|
|
1033
|
+
};
|
|
1034
|
+
const upsertResult = await BatchProcessor.processBatch(
|
|
1035
|
+
upsertDocs,
|
|
1036
|
+
(batch) => this.vectorDB.batchUpsert(batch, ns),
|
|
1037
|
+
upsertBatchOptions
|
|
1038
|
+
);
|
|
1039
|
+
if (upsertResult.errors.length > 0) {
|
|
1040
|
+
console.warn(`[Pipeline] Ingestion: ${upsertResult.errors.length} batches failed for doc ${doc.docId}`);
|
|
1041
|
+
}
|
|
1042
|
+
results.push({
|
|
1043
|
+
docId: doc.docId,
|
|
1044
|
+
chunksIngested: upsertResult.totalProcessed
|
|
1045
|
+
});
|
|
1046
|
+
} catch (error) {
|
|
1047
|
+
console.error(`[Pipeline] Failed to ingest document ${doc.docId}:`, error);
|
|
1048
|
+
results.push({
|
|
1049
|
+
docId: doc.docId,
|
|
1050
|
+
chunksIngested: 0
|
|
1051
|
+
});
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
return results;
|
|
1055
|
+
}
|
|
1056
|
+
async ask(question, history = [], namespace) {
|
|
1057
|
+
var _a, _b, _c, _d;
|
|
1058
|
+
await this.initialize();
|
|
1059
|
+
const ns = namespace != null ? namespace : this.config.projectId;
|
|
1060
|
+
const topK = (_b = (_a = this.config.rag) == null ? void 0 : _a.topK) != null ? _b : 5;
|
|
1061
|
+
const scoreThreshold = (_d = (_c = this.config.rag) == null ? void 0 : _c.scoreThreshold) != null ? _d : 0;
|
|
1062
|
+
try {
|
|
1063
|
+
const queryVector = await this.embeddingProvider.embed(question);
|
|
1064
|
+
const rawMatches = await this.vectorDB.query(queryVector, topK, ns);
|
|
1065
|
+
const sources = rawMatches.filter((m) => m.score >= scoreThreshold);
|
|
1066
|
+
const context = sources.length ? sources.map((m, i) => `[Source ${i + 1}]
|
|
1067
|
+
${m.content}`).join("\n\n---\n\n") : "No relevant context found.";
|
|
1068
|
+
const messages = [...history, { role: "user", content: question }];
|
|
1069
|
+
const reply = await this.llmProvider.chat(messages, context);
|
|
1070
|
+
return { reply, sources };
|
|
1071
|
+
} catch (error) {
|
|
1072
|
+
throw new Error(`[Pipeline] Chat failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
};
|
|
1076
|
+
|
|
1077
|
+
// src/core/ProviderHealthCheck.ts
|
|
1078
|
+
var ProviderHealthCheck = class {
|
|
1079
|
+
/**
|
|
1080
|
+
* Validates vector database configuration before initialization.
|
|
1081
|
+
* Performs connectivity checks and verifies required resources exist.
|
|
1082
|
+
*/
|
|
1083
|
+
static async checkVectorProvider(config) {
|
|
1084
|
+
const timestamp = Date.now();
|
|
1085
|
+
const configErrors = ConfigValidator.validate({
|
|
1086
|
+
projectId: "health-check",
|
|
1087
|
+
vectorDb: config,
|
|
1088
|
+
llm: { provider: "openai", model: "gpt-4o" },
|
|
1089
|
+
// dummy
|
|
1090
|
+
embedding: { provider: "openai", model: "text-embedding-3-small" }
|
|
1091
|
+
});
|
|
1092
|
+
const vectorDbErrors = configErrors.filter((e) => e.field.startsWith("vectorDb"));
|
|
1093
|
+
if (vectorDbErrors.length > 0) {
|
|
1094
|
+
return {
|
|
1095
|
+
healthy: false,
|
|
1096
|
+
provider: config.provider,
|
|
1097
|
+
error: `Configuration validation failed: ${vectorDbErrors.map((e) => e.message).join("; ")}`,
|
|
1098
|
+
timestamp
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
try {
|
|
1102
|
+
switch (config.provider) {
|
|
1103
|
+
case "pinecone":
|
|
1104
|
+
return await this.checkPinecone(config, timestamp);
|
|
1105
|
+
case "pgvector":
|
|
1106
|
+
case "postgresql":
|
|
1107
|
+
return await this.checkPostgres(config, timestamp);
|
|
1108
|
+
case "mongodb":
|
|
1109
|
+
return await this.checkMongoDB(config, timestamp);
|
|
1110
|
+
case "milvus":
|
|
1111
|
+
return await this.checkMilvus(config, timestamp);
|
|
1112
|
+
case "qdrant":
|
|
1113
|
+
return await this.checkQdrant(config, timestamp);
|
|
1114
|
+
case "chromadb":
|
|
1115
|
+
return await this.checkChromaDB(config, timestamp);
|
|
1116
|
+
case "redis":
|
|
1117
|
+
return await this.checkRedis(config, timestamp);
|
|
1118
|
+
case "weaviate":
|
|
1119
|
+
return await this.checkWeaviate(config, timestamp);
|
|
1120
|
+
case "rest":
|
|
1121
|
+
case "universal_rest":
|
|
1122
|
+
return await this.checkRestAPI(config, timestamp);
|
|
1123
|
+
default:
|
|
1124
|
+
return {
|
|
1125
|
+
healthy: false,
|
|
1126
|
+
provider: config.provider,
|
|
1127
|
+
error: `Unsupported provider: ${config.provider}`,
|
|
1128
|
+
timestamp
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
} catch (error) {
|
|
1132
|
+
return {
|
|
1133
|
+
healthy: false,
|
|
1134
|
+
provider: config.provider,
|
|
1135
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1136
|
+
timestamp
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
static async checkPinecone(config, timestamp) {
|
|
1141
|
+
var _a, _b;
|
|
1142
|
+
const opts = config.options;
|
|
1143
|
+
try {
|
|
1144
|
+
const { Pinecone } = await import("@pinecone-database/pinecone");
|
|
1145
|
+
const client = new Pinecone({ apiKey: opts.apiKey });
|
|
1146
|
+
const indexes = await client.listIndexes();
|
|
1147
|
+
const indexNames = (_b = (_a = indexes.indexes) == null ? void 0 : _a.map((i) => i.name)) != null ? _b : [];
|
|
1148
|
+
if (!indexNames.includes(config.indexName)) {
|
|
1149
|
+
return {
|
|
1150
|
+
healthy: false,
|
|
1151
|
+
provider: "pinecone",
|
|
1152
|
+
error: `Index "${config.indexName}" not found. Available: ${indexNames.join(", ")}`,
|
|
1153
|
+
timestamp
|
|
1154
|
+
};
|
|
1155
|
+
}
|
|
1156
|
+
return {
|
|
1157
|
+
healthy: true,
|
|
1158
|
+
provider: "pinecone",
|
|
1159
|
+
capabilities: {
|
|
1160
|
+
indexes: indexNames.length,
|
|
1161
|
+
targetIndex: config.indexName
|
|
1162
|
+
},
|
|
1163
|
+
timestamp
|
|
1164
|
+
};
|
|
1165
|
+
} catch (error) {
|
|
1166
|
+
return {
|
|
1167
|
+
healthy: false,
|
|
1168
|
+
provider: "pinecone",
|
|
1169
|
+
error: `Connection failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1170
|
+
timestamp
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
static async checkPostgres(config, timestamp) {
|
|
1175
|
+
const opts = config.options;
|
|
1176
|
+
try {
|
|
1177
|
+
const { Client } = await import("pg");
|
|
1178
|
+
const client = new Client({ connectionString: opts.connectionString });
|
|
1179
|
+
await client.connect();
|
|
1180
|
+
const result = await client.query(`
|
|
1181
|
+
SELECT EXISTS(
|
|
1182
|
+
SELECT 1 FROM pg_extension WHERE extname = 'vector'
|
|
1183
|
+
);
|
|
1184
|
+
`);
|
|
1185
|
+
const hasVector = result.rows[0].exists;
|
|
1186
|
+
await client.end();
|
|
1187
|
+
return {
|
|
1188
|
+
healthy: true,
|
|
1189
|
+
provider: "postgresql",
|
|
1190
|
+
capabilities: { pgvectorInstalled: hasVector },
|
|
1191
|
+
timestamp
|
|
1192
|
+
};
|
|
1193
|
+
} catch (error) {
|
|
1194
|
+
return {
|
|
1195
|
+
healthy: false,
|
|
1196
|
+
provider: "postgresql",
|
|
1197
|
+
error: `Connection failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1198
|
+
timestamp
|
|
1199
|
+
};
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
static async checkMongoDB(config, timestamp) {
|
|
1203
|
+
const opts = config.options;
|
|
1204
|
+
try {
|
|
1205
|
+
const { MongoClient } = await import("mongodb");
|
|
1206
|
+
const client = new MongoClient(opts.uri);
|
|
1207
|
+
await client.connect();
|
|
1208
|
+
const db = client.db(opts.database);
|
|
1209
|
+
const collections = await db.listCollections().toArray();
|
|
1210
|
+
const collectionNames = collections.map((c) => c.name);
|
|
1211
|
+
const hasCollection = collectionNames.includes(opts.collection);
|
|
1212
|
+
await client.close();
|
|
1213
|
+
return {
|
|
1214
|
+
healthy: true,
|
|
1215
|
+
provider: "mongodb",
|
|
1216
|
+
capabilities: {
|
|
1217
|
+
collections: collectionNames.length,
|
|
1218
|
+
targetCollection: hasCollection ? opts.collection : "NOT FOUND"
|
|
1219
|
+
},
|
|
1220
|
+
timestamp
|
|
1221
|
+
};
|
|
1222
|
+
} catch (error) {
|
|
1223
|
+
return {
|
|
1224
|
+
healthy: false,
|
|
1225
|
+
provider: "mongodb",
|
|
1226
|
+
error: `Connection failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1227
|
+
timestamp
|
|
1228
|
+
};
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
static async checkMilvus(config, timestamp) {
|
|
1232
|
+
const opts = config.options;
|
|
1233
|
+
const host = opts.host || "localhost";
|
|
1234
|
+
const port = opts.port || 19530;
|
|
1235
|
+
try {
|
|
1236
|
+
const controller = new AbortController();
|
|
1237
|
+
const timeoutId = setTimeout(() => controller.abort(), 5e3);
|
|
1238
|
+
const response = await fetch(`http://${host}:${port}/healthz`, {
|
|
1239
|
+
signal: controller.signal
|
|
1240
|
+
});
|
|
1241
|
+
clearTimeout(timeoutId);
|
|
1242
|
+
if (!response.ok) {
|
|
1243
|
+
throw new Error(`Health check returned ${response.status}`);
|
|
1244
|
+
}
|
|
1245
|
+
return {
|
|
1246
|
+
healthy: true,
|
|
1247
|
+
provider: "milvus",
|
|
1248
|
+
capabilities: { endpoint: `${host}:${port}` },
|
|
1249
|
+
timestamp
|
|
1250
|
+
};
|
|
1251
|
+
} catch (error) {
|
|
1252
|
+
return {
|
|
1253
|
+
healthy: false,
|
|
1254
|
+
provider: "milvus",
|
|
1255
|
+
error: `Connection failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1256
|
+
timestamp
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
static async checkQdrant(config, timestamp) {
|
|
1261
|
+
const opts = config.options;
|
|
1262
|
+
const baseUrl = opts.baseUrl || opts.url || "http://localhost:6333";
|
|
1263
|
+
try {
|
|
1264
|
+
const response = await fetch(`${baseUrl}/health`);
|
|
1265
|
+
if (!response.ok) {
|
|
1266
|
+
throw new Error(`Health check returned ${response.status}`);
|
|
1267
|
+
}
|
|
1268
|
+
const health = await response.json();
|
|
1269
|
+
return {
|
|
1270
|
+
healthy: true,
|
|
1271
|
+
provider: "qdrant",
|
|
1272
|
+
capabilities: health,
|
|
1273
|
+
timestamp
|
|
1274
|
+
};
|
|
1275
|
+
} catch (error) {
|
|
1276
|
+
return {
|
|
1277
|
+
healthy: false,
|
|
1278
|
+
provider: "qdrant",
|
|
1279
|
+
error: `Connection failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1280
|
+
timestamp
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
static async checkChromaDB(config, timestamp) {
|
|
1285
|
+
const opts = config.options;
|
|
1286
|
+
const host = opts.host || "localhost";
|
|
1287
|
+
const port = opts.port || 8e3;
|
|
1288
|
+
try {
|
|
1289
|
+
const response = await fetch(`http://${host}:${port}/api/v1/heartbeat`);
|
|
1290
|
+
if (!response.ok) {
|
|
1291
|
+
throw new Error(`Health check returned ${response.status}`);
|
|
1292
|
+
}
|
|
1293
|
+
return {
|
|
1294
|
+
healthy: true,
|
|
1295
|
+
provider: "chromadb",
|
|
1296
|
+
capabilities: { endpoint: `${host}:${port}` },
|
|
1297
|
+
timestamp
|
|
1298
|
+
};
|
|
1299
|
+
} catch (error) {
|
|
1300
|
+
return {
|
|
1301
|
+
healthy: false,
|
|
1302
|
+
provider: "chromadb",
|
|
1303
|
+
error: `Connection failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1304
|
+
timestamp
|
|
1305
|
+
};
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
static async checkRedis(config, timestamp) {
|
|
1309
|
+
const opts = config.options;
|
|
1310
|
+
const url = opts.url || `redis://${opts.host}:${opts.port}`;
|
|
1311
|
+
try {
|
|
1312
|
+
await fetch(url);
|
|
1313
|
+
return {
|
|
1314
|
+
healthy: true,
|
|
1315
|
+
provider: "redis",
|
|
1316
|
+
capabilities: { endpoint: url },
|
|
1317
|
+
timestamp
|
|
1318
|
+
};
|
|
1319
|
+
} catch (error) {
|
|
1320
|
+
return {
|
|
1321
|
+
healthy: false,
|
|
1322
|
+
provider: "redis",
|
|
1323
|
+
error: `Connection check failed: ${error instanceof Error ? error.message : String(error)}. Ensure Redis is running at ${url}`,
|
|
1324
|
+
timestamp
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
static async checkWeaviate(config, timestamp) {
|
|
1329
|
+
const opts = config.options;
|
|
1330
|
+
const url = (opts.url || "http://localhost:8080").replace(/\/$/, "");
|
|
1331
|
+
try {
|
|
1332
|
+
const response = await fetch(`${url}/.well-known/ready`);
|
|
1333
|
+
if (!response.ok) {
|
|
1334
|
+
throw new Error(`Health check returned ${response.status}`);
|
|
1335
|
+
}
|
|
1336
|
+
return {
|
|
1337
|
+
healthy: true,
|
|
1338
|
+
provider: "weaviate",
|
|
1339
|
+
capabilities: { endpoint: url },
|
|
1340
|
+
timestamp
|
|
1341
|
+
};
|
|
1342
|
+
} catch (error) {
|
|
1343
|
+
return {
|
|
1344
|
+
healthy: false,
|
|
1345
|
+
provider: "weaviate",
|
|
1346
|
+
error: `Connection failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1347
|
+
timestamp
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
static async checkRestAPI(config, timestamp) {
|
|
1352
|
+
const opts = config.options;
|
|
1353
|
+
const baseUrl = (opts.baseUrl || "").replace(/\/$/, "");
|
|
1354
|
+
if (!baseUrl) {
|
|
1355
|
+
return {
|
|
1356
|
+
healthy: false,
|
|
1357
|
+
provider: "rest",
|
|
1358
|
+
error: "baseUrl is required",
|
|
1359
|
+
timestamp
|
|
1360
|
+
};
|
|
1361
|
+
}
|
|
1362
|
+
try {
|
|
1363
|
+
const response = await fetch(`${baseUrl}/health`, {
|
|
1364
|
+
headers: opts.headers ? JSON.parse(opts.headers) : {}
|
|
1365
|
+
});
|
|
1366
|
+
return {
|
|
1367
|
+
healthy: response.ok,
|
|
1368
|
+
provider: "rest",
|
|
1369
|
+
error: response.ok ? void 0 : `Health check returned ${response.status}`,
|
|
1370
|
+
timestamp
|
|
1371
|
+
};
|
|
1372
|
+
} catch (error) {
|
|
1373
|
+
return {
|
|
1374
|
+
healthy: false,
|
|
1375
|
+
provider: "rest",
|
|
1376
|
+
error: `Connection failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1377
|
+
timestamp
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
/**
|
|
1382
|
+
* Validates LLM provider configuration.
|
|
1383
|
+
*/
|
|
1384
|
+
static async checkLLMProvider(config) {
|
|
1385
|
+
const timestamp = Date.now();
|
|
1386
|
+
try {
|
|
1387
|
+
switch (config.provider) {
|
|
1388
|
+
case "openai":
|
|
1389
|
+
return await this.checkOpenAI(config, timestamp);
|
|
1390
|
+
case "anthropic":
|
|
1391
|
+
return await this.checkAnthropic(config, timestamp);
|
|
1392
|
+
case "ollama":
|
|
1393
|
+
return await this.checkOllama(config, timestamp);
|
|
1394
|
+
case "rest":
|
|
1395
|
+
case "universal_rest":
|
|
1396
|
+
return await this.checkLLMRestAPI(config, timestamp);
|
|
1397
|
+
default:
|
|
1398
|
+
return {
|
|
1399
|
+
healthy: false,
|
|
1400
|
+
provider: config.provider,
|
|
1401
|
+
error: `Unsupported provider: ${config.provider}`,
|
|
1402
|
+
timestamp
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
} catch (error) {
|
|
1406
|
+
return {
|
|
1407
|
+
healthy: false,
|
|
1408
|
+
provider: config.provider,
|
|
1409
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1410
|
+
timestamp
|
|
1411
|
+
};
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
static async checkOpenAI(config, timestamp) {
|
|
1415
|
+
try {
|
|
1416
|
+
const OpenAI = await import("openai");
|
|
1417
|
+
const client = new OpenAI.default({ apiKey: config.apiKey });
|
|
1418
|
+
const models = await client.models.list();
|
|
1419
|
+
const hasModel = models.data.some((m) => m.id === config.model);
|
|
1420
|
+
return {
|
|
1421
|
+
healthy: true,
|
|
1422
|
+
provider: "openai",
|
|
1423
|
+
capabilities: {
|
|
1424
|
+
model: config.model,
|
|
1425
|
+
available: hasModel,
|
|
1426
|
+
totalModels: models.data.length
|
|
1427
|
+
},
|
|
1428
|
+
timestamp
|
|
1429
|
+
};
|
|
1430
|
+
} catch (error) {
|
|
1431
|
+
return {
|
|
1432
|
+
healthy: false,
|
|
1433
|
+
provider: "openai",
|
|
1434
|
+
error: `Connection failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1435
|
+
timestamp
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
static async checkAnthropic(config, timestamp) {
|
|
1440
|
+
try {
|
|
1441
|
+
const { default: Anthropic } = await import("@anthropic-ai/sdk");
|
|
1442
|
+
const client = new Anthropic({ apiKey: config.apiKey });
|
|
1443
|
+
await client.messages.create({
|
|
1444
|
+
model: config.model,
|
|
1445
|
+
max_tokens: 10,
|
|
1446
|
+
messages: [{ role: "user", content: "ping" }]
|
|
1447
|
+
});
|
|
1448
|
+
return {
|
|
1449
|
+
healthy: true,
|
|
1450
|
+
provider: "anthropic",
|
|
1451
|
+
capabilities: { model: config.model },
|
|
1452
|
+
timestamp
|
|
1453
|
+
};
|
|
1454
|
+
} catch (error) {
|
|
1455
|
+
return {
|
|
1456
|
+
healthy: false,
|
|
1457
|
+
provider: "anthropic",
|
|
1458
|
+
error: `Connection failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1459
|
+
timestamp
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
static async checkOllama(config, timestamp) {
|
|
1464
|
+
const baseUrl = (config.baseUrl || "http://localhost:11434").replace(/\/$/, "");
|
|
1465
|
+
try {
|
|
1466
|
+
const response = await fetch(`${baseUrl}/api/tags`);
|
|
1467
|
+
if (!response.ok) {
|
|
1468
|
+
throw new Error(`Health check returned ${response.status}`);
|
|
1469
|
+
}
|
|
1470
|
+
const data = await response.json();
|
|
1471
|
+
const models = data.models || [];
|
|
1472
|
+
const hasModel = models.some((m) => m.name === config.model);
|
|
1473
|
+
return {
|
|
1474
|
+
healthy: true,
|
|
1475
|
+
provider: "ollama",
|
|
1476
|
+
capabilities: {
|
|
1477
|
+
model: config.model,
|
|
1478
|
+
available: hasModel,
|
|
1479
|
+
totalModels: models.length
|
|
1480
|
+
},
|
|
1481
|
+
timestamp
|
|
1482
|
+
};
|
|
1483
|
+
} catch (error) {
|
|
1484
|
+
return {
|
|
1485
|
+
healthy: false,
|
|
1486
|
+
provider: "ollama",
|
|
1487
|
+
error: `Connection failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1488
|
+
timestamp
|
|
1489
|
+
};
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
static async checkLLMRestAPI(config, timestamp) {
|
|
1493
|
+
var _a, _b;
|
|
1494
|
+
const baseUrlRaw = config.baseUrl || ((_a = config.options) == null ? void 0 : _a.baseUrl);
|
|
1495
|
+
const baseUrl = (typeof baseUrlRaw === "string" ? baseUrlRaw : "").replace(/\/$/, "");
|
|
1496
|
+
if (!baseUrl) {
|
|
1497
|
+
return {
|
|
1498
|
+
healthy: false,
|
|
1499
|
+
provider: config.provider,
|
|
1500
|
+
error: "baseUrl is required",
|
|
1501
|
+
timestamp
|
|
1502
|
+
};
|
|
1503
|
+
}
|
|
1504
|
+
try {
|
|
1505
|
+
const headers = (_b = config.options) == null ? void 0 : _b.headers;
|
|
1506
|
+
const response = await fetch(`${baseUrl}/health`, {
|
|
1507
|
+
headers: headers || void 0
|
|
1508
|
+
});
|
|
1509
|
+
return {
|
|
1510
|
+
healthy: response.ok,
|
|
1511
|
+
provider: config.provider,
|
|
1512
|
+
error: response.ok ? void 0 : `Health check returned ${response.status}`,
|
|
1513
|
+
timestamp
|
|
1514
|
+
};
|
|
1515
|
+
} catch (error) {
|
|
1516
|
+
return {
|
|
1517
|
+
healthy: false,
|
|
1518
|
+
provider: config.provider,
|
|
1519
|
+
error: `Connection failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1520
|
+
timestamp
|
|
1521
|
+
};
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
/**
|
|
1525
|
+
* Runs comprehensive health checks on all configured providers.
|
|
1526
|
+
*/
|
|
1527
|
+
static async checkAll(vectorDbConfig, llmConfig, embeddingConfig) {
|
|
1528
|
+
const [vectorDb, llm, embedding] = await Promise.all([
|
|
1529
|
+
this.checkVectorProvider(vectorDbConfig),
|
|
1530
|
+
this.checkLLMProvider(llmConfig),
|
|
1531
|
+
embeddingConfig ? this.checkLLMProvider(embeddingConfig) : Promise.resolve(void 0)
|
|
1532
|
+
]);
|
|
1533
|
+
return {
|
|
1534
|
+
vectorDb,
|
|
1535
|
+
llm,
|
|
1536
|
+
embedding,
|
|
1537
|
+
allHealthy: vectorDb.healthy && llm.healthy && (!embedding || embedding.healthy)
|
|
1538
|
+
};
|
|
1539
|
+
}
|
|
1540
|
+
};
|
|
1541
|
+
|
|
1542
|
+
// src/core/VectorPlugin.ts
|
|
1543
|
+
var VectorPlugin = class {
|
|
1544
|
+
/**
|
|
1545
|
+
* Initializes the plugin with the host configuration.
|
|
1546
|
+
* @param hostConfig - Configuration object passed from the host application.
|
|
1547
|
+
* @throws Error if configuration is invalid or providers are unhealthy
|
|
1548
|
+
*
|
|
1549
|
+
* @example
|
|
1550
|
+
* const plugin = new VectorPlugin({
|
|
1551
|
+
* projectId: 'my-app',
|
|
1552
|
+
* vectorDb: {
|
|
1553
|
+
* provider: 'pinecone',
|
|
1554
|
+
* indexName: 'my-index',
|
|
1555
|
+
* options: { apiKey: process.env.PINECONE_API_KEY }
|
|
1556
|
+
* },
|
|
1557
|
+
* llm: {
|
|
1558
|
+
* provider: 'openai',
|
|
1559
|
+
* model: 'gpt-4o',
|
|
1560
|
+
* apiKey: process.env.OPENAI_API_KEY
|
|
1561
|
+
* }
|
|
1562
|
+
* });
|
|
1563
|
+
*/
|
|
1564
|
+
constructor(hostConfig) {
|
|
1565
|
+
this.config = ConfigResolver.resolve(hostConfig);
|
|
1566
|
+
ConfigValidator.validateAndThrow(this.config);
|
|
1567
|
+
this.pipeline = new Pipeline(this.config);
|
|
1568
|
+
}
|
|
1569
|
+
/**
|
|
1570
|
+
* Get the current resolved configuration.
|
|
1571
|
+
*/
|
|
1572
|
+
getConfig() {
|
|
1573
|
+
return this.config;
|
|
1574
|
+
}
|
|
1575
|
+
/**
|
|
1576
|
+
* Perform pre-flight health checks on all configured providers.
|
|
1577
|
+
* Useful to verify connectivity before running operations.
|
|
1578
|
+
*
|
|
1579
|
+
* @returns Health status for vector DB, LLM, and embedding providers
|
|
1580
|
+
*/
|
|
1581
|
+
async checkHealth() {
|
|
1582
|
+
return ProviderHealthCheck.checkAll(
|
|
1583
|
+
this.config.vectorDb,
|
|
1584
|
+
this.config.llm,
|
|
1585
|
+
this.config.embedding
|
|
1586
|
+
);
|
|
1587
|
+
}
|
|
1588
|
+
/**
|
|
1589
|
+
* Run a chat query.
|
|
1590
|
+
*/
|
|
1591
|
+
async chat(message, history = [], namespace) {
|
|
1592
|
+
return this.pipeline.ask(message, history, namespace);
|
|
1593
|
+
}
|
|
1594
|
+
/**
|
|
1595
|
+
* Ingest documents into the vector database.
|
|
1596
|
+
*/
|
|
1597
|
+
async ingest(documents, namespace) {
|
|
1598
|
+
return this.pipeline.ingest(documents, namespace);
|
|
1599
|
+
}
|
|
1600
|
+
};
|
|
1601
|
+
|
|
1602
|
+
// src/utils/DocumentParser.ts
|
|
1603
|
+
var DocumentParser = class {
|
|
1604
|
+
/**
|
|
1605
|
+
* Extract text from a File or Buffer based on its type.
|
|
1606
|
+
*/
|
|
1607
|
+
static async parse(file, fileName, mimeType) {
|
|
1608
|
+
var _a;
|
|
1609
|
+
const extension = (_a = fileName.split(".").pop()) == null ? void 0 : _a.toLowerCase();
|
|
1610
|
+
if (extension === "txt" || extension === "md" || mimeType === "text/plain" || mimeType === "text/markdown") {
|
|
1611
|
+
return this.readAsText(file);
|
|
1612
|
+
}
|
|
1613
|
+
if (extension === "json" || mimeType === "application/json") {
|
|
1614
|
+
const text = await this.readAsText(file);
|
|
1615
|
+
try {
|
|
1616
|
+
const obj = JSON.parse(text);
|
|
1617
|
+
return JSON.stringify(obj, null, 2);
|
|
1618
|
+
} catch (e) {
|
|
1619
|
+
return text;
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
if (extension === "csv" || mimeType === "text/csv") {
|
|
1623
|
+
return this.readAsText(file);
|
|
1624
|
+
}
|
|
1625
|
+
if (extension === "pdf" || mimeType === "application/pdf") {
|
|
1626
|
+
try {
|
|
1627
|
+
const pdf = await import("pdf-parse/lib/pdf-parse.js");
|
|
1628
|
+
const buffer = Buffer.isBuffer(file) ? file : Buffer.from(await file.arrayBuffer());
|
|
1629
|
+
const data = await pdf.default(buffer);
|
|
1630
|
+
return data.text;
|
|
1631
|
+
} catch (err) {
|
|
1632
|
+
console.warn('[DocumentParser] PDF parsing failed. Make sure "pdf-parse" is installed.', err);
|
|
1633
|
+
return `[PDF Parsing Error for ${fileName}]`;
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
if (extension === "docx" || mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
|
|
1637
|
+
try {
|
|
1638
|
+
const mammoth = await import("mammoth");
|
|
1639
|
+
const buffer = Buffer.isBuffer(file) ? file : Buffer.from(await file.arrayBuffer());
|
|
1640
|
+
const result = await mammoth.extractRawText({ buffer });
|
|
1641
|
+
return result.value;
|
|
1642
|
+
} catch (err) {
|
|
1643
|
+
console.warn('[DocumentParser] DOCX parsing failed. Make sure "mammoth" is installed.', err);
|
|
1644
|
+
return `[DOCX Parsing Error for ${fileName}]`;
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
try {
|
|
1648
|
+
return await this.readAsText(file);
|
|
1649
|
+
} catch (e) {
|
|
1650
|
+
throw new Error(`[DocumentParser] Unsupported file format: ${fileName} (${mimeType})`);
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
static async readAsText(file) {
|
|
1654
|
+
if (Buffer.isBuffer(file)) {
|
|
1655
|
+
return file.toString("utf-8");
|
|
1656
|
+
}
|
|
1657
|
+
return await file.text();
|
|
1658
|
+
}
|
|
1659
|
+
};
|
|
1660
|
+
|
|
1661
|
+
// src/handlers/index.ts
|
|
1662
|
+
function createChatHandler(config) {
|
|
1663
|
+
const plugin = new VectorPlugin(config);
|
|
1664
|
+
return async function POST(req) {
|
|
1665
|
+
try {
|
|
1666
|
+
const body = await req.json();
|
|
1667
|
+
const { message, history = [], namespace } = body;
|
|
1668
|
+
if (!(message == null ? void 0 : message.trim())) {
|
|
1669
|
+
return NextResponse.json({ error: "message is required" }, { status: 400 });
|
|
1670
|
+
}
|
|
1671
|
+
const result = await plugin.chat(message, history, namespace);
|
|
1672
|
+
return NextResponse.json(result);
|
|
1673
|
+
} catch (err) {
|
|
1674
|
+
const message = err instanceof Error ? err.message : "Internal server error";
|
|
1675
|
+
return NextResponse.json({ error: message }, { status: 500 });
|
|
1676
|
+
}
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
function createIngestHandler(config) {
|
|
1680
|
+
const plugin = new VectorPlugin(config);
|
|
1681
|
+
return async function POST(req) {
|
|
1682
|
+
try {
|
|
1683
|
+
const body = await req.json();
|
|
1684
|
+
const { documents, namespace } = body;
|
|
1685
|
+
if (!Array.isArray(documents) || documents.length === 0) {
|
|
1686
|
+
return NextResponse.json({ error: "documents array is required" }, { status: 400 });
|
|
1687
|
+
}
|
|
1688
|
+
const results = await plugin.ingest(documents, namespace);
|
|
1689
|
+
return NextResponse.json({ results });
|
|
1690
|
+
} catch (err) {
|
|
1691
|
+
const message = err instanceof Error ? err.message : "Internal server error";
|
|
1692
|
+
return NextResponse.json({ error: message }, { status: 500 });
|
|
1693
|
+
}
|
|
1694
|
+
};
|
|
1695
|
+
}
|
|
1696
|
+
function createHealthHandler(config) {
|
|
1697
|
+
const plugin = new VectorPlugin(config);
|
|
1698
|
+
return async function GET() {
|
|
1699
|
+
try {
|
|
1700
|
+
const health = await plugin.checkHealth();
|
|
1701
|
+
const status = health.allHealthy ? "ok" : "degraded";
|
|
1702
|
+
return NextResponse.json(__spreadProps(__spreadValues({
|
|
1703
|
+
status
|
|
1704
|
+
}, health), {
|
|
1705
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
1706
|
+
}));
|
|
1707
|
+
} catch (err) {
|
|
1708
|
+
const message = err instanceof Error ? err.message : "Unknown error";
|
|
1709
|
+
return NextResponse.json({ status: "error", error: message }, { status: 500 });
|
|
1710
|
+
}
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
function createUploadHandler(config) {
|
|
1714
|
+
const plugin = new VectorPlugin(config);
|
|
1715
|
+
return async function POST(req) {
|
|
1716
|
+
try {
|
|
1717
|
+
const formData = await req.formData();
|
|
1718
|
+
const files = formData.getAll("files");
|
|
1719
|
+
const namespace = formData.get("namespace") || void 0;
|
|
1720
|
+
if (!files || files.length === 0) {
|
|
1721
|
+
return NextResponse.json({ error: "No files provided" }, { status: 400 });
|
|
1722
|
+
}
|
|
1723
|
+
const documents = await Promise.all(
|
|
1724
|
+
files.map(async (file) => {
|
|
1725
|
+
const content = await DocumentParser.parse(file, file.name, file.type);
|
|
1726
|
+
return {
|
|
1727
|
+
docId: file.name,
|
|
1728
|
+
content,
|
|
1729
|
+
metadata: {
|
|
1730
|
+
fileName: file.name,
|
|
1731
|
+
fileSize: file.size,
|
|
1732
|
+
fileType: file.type,
|
|
1733
|
+
uploadedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1734
|
+
}
|
|
1735
|
+
};
|
|
1736
|
+
})
|
|
1737
|
+
);
|
|
1738
|
+
const results = await plugin.ingest(documents, namespace);
|
|
1739
|
+
return NextResponse.json({ message: "Upload successful", results });
|
|
1740
|
+
} catch (err) {
|
|
1741
|
+
const message = err instanceof Error ? err.message : "Upload failed";
|
|
1742
|
+
return NextResponse.json({ error: message }, { status: 500 });
|
|
1743
|
+
}
|
|
1744
|
+
};
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
export {
|
|
1748
|
+
getRagConfig,
|
|
1749
|
+
ConfigResolver,
|
|
1750
|
+
DocumentChunker,
|
|
1751
|
+
ProviderRegistry,
|
|
1752
|
+
Pipeline,
|
|
1753
|
+
VectorPlugin,
|
|
1754
|
+
createChatHandler,
|
|
1755
|
+
createIngestHandler,
|
|
1756
|
+
createHealthHandler,
|
|
1757
|
+
createUploadHandler
|
|
1758
|
+
};
|