@retrivora-ai/rag-engine 1.7.6 → 1.7.8

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.
@@ -2211,65 +2211,410 @@ var QueryProcessor = class {
2211
2211
  }
2212
2212
  };
2213
2213
 
2214
- // src/core/Pipeline.ts
2215
- var LRUEmbeddingCache = class {
2216
- constructor(maxSize = 500) {
2217
- this.cache = /* @__PURE__ */ new Map();
2218
- this.maxSize = maxSize;
2219
- }
2220
- get(key) {
2221
- const value = this.cache.get(key);
2222
- if (value !== void 0) {
2223
- this.cache.delete(key);
2224
- this.cache.set(key, value);
2214
+ // src/utils/UITransformer.ts
2215
+ var UITransformer = class {
2216
+ /**
2217
+ * Main transformation method
2218
+ * Analyzes user query and retrieved data to determine the best visualization format
2219
+ *
2220
+ * @param userQuery - The original user question/query
2221
+ * @param retrievedData - Vector database retrieval results
2222
+ * @returns Structured JSON response for UI rendering
2223
+ */
2224
+ static transform(userQuery, retrievedData) {
2225
+ if (!retrievedData || retrievedData.length === 0) {
2226
+ return this.createTextResponse("No data available", "No relevant data found for your query.");
2227
+ }
2228
+ const analysis = this.analyzeData(userQuery, retrievedData);
2229
+ switch (analysis.suggestedType) {
2230
+ case "product_carousel":
2231
+ return this.transformToProductCarousel(retrievedData);
2232
+ case "pie_chart":
2233
+ return this.transformToPieChart(retrievedData);
2234
+ case "bar_chart":
2235
+ return this.transformToBarChart(retrievedData);
2236
+ case "line_chart":
2237
+ return this.transformToLineChart(retrievedData);
2238
+ case "table":
2239
+ return this.transformToTable(retrievedData);
2240
+ default:
2241
+ return this.transformToText(retrievedData);
2225
2242
  }
2226
- return value;
2227
2243
  }
2228
- set(key, value) {
2229
- if (this.cache.has(key)) {
2230
- this.cache.delete(key);
2231
- } else if (this.cache.size >= this.maxSize) {
2232
- const oldestKey = this.cache.keys().next().value;
2233
- if (oldestKey !== void 0) this.cache.delete(oldestKey);
2244
+ /**
2245
+ * Analyzes the data and query to suggest the best visualization type
2246
+ */
2247
+ static analyzeData(query, data) {
2248
+ const queryLower = query.toLowerCase();
2249
+ const hasProducts = data.some(
2250
+ (item) => this.isProductData(item)
2251
+ );
2252
+ const hasTimeSeries = data.some(
2253
+ (item) => this.isTimeSeriesData(item)
2254
+ );
2255
+ const hasCategories = this.detectCategories(data).length > 0;
2256
+ const isDistributionQuery = queryLower.includes("distribution") || queryLower.includes("breakdown") || queryLower.includes("percentage") || queryLower.includes("proportion");
2257
+ const isComparisonQuery = queryLower.includes("compare") || queryLower.includes("vs") || queryLower.includes("difference");
2258
+ const isTrendQuery = queryLower.includes("trend") || queryLower.includes("over time") || queryLower.includes("growth") || queryLower.includes("decline");
2259
+ if (hasProducts && !hasTimeSeries && !isDistributionQuery) {
2260
+ return { suggestedType: "product_carousel", confidence: 0.95, hasProducts, hasTimeSeries, hasCategories };
2234
2261
  }
2235
- this.cache.set(key, value);
2262
+ if (isTrendQuery && hasTimeSeries) {
2263
+ return { suggestedType: "line_chart", confidence: 0.9, hasProducts, hasTimeSeries, hasCategories };
2264
+ }
2265
+ if (isDistributionQuery && hasCategories) {
2266
+ return { suggestedType: "pie_chart", confidence: 0.85, hasProducts, hasTimeSeries, hasCategories };
2267
+ }
2268
+ if (isComparisonQuery && hasCategories && data.length > 2) {
2269
+ return { suggestedType: "bar_chart", confidence: 0.8, hasProducts, hasTimeSeries, hasCategories };
2270
+ }
2271
+ if (data.length > 5 && this.hasMultipleFields(data)) {
2272
+ return { suggestedType: "table", confidence: 0.75, hasProducts, hasTimeSeries, hasCategories };
2273
+ }
2274
+ return { suggestedType: "text", confidence: 0.5, hasProducts, hasTimeSeries, hasCategories };
2236
2275
  }
2237
- clear() {
2238
- this.cache.clear();
2276
+ /**
2277
+ * Transform data to product carousel format
2278
+ */
2279
+ static transformToProductCarousel(data) {
2280
+ const products = data.filter((item) => this.isProductData(item)).map((item) => this.extractProductInfo(item)).filter((p) => p !== null);
2281
+ return {
2282
+ type: "product_carousel",
2283
+ title: "Recommended Products",
2284
+ description: `Found ${products.length} relevant products`,
2285
+ data: products
2286
+ };
2239
2287
  }
2240
- get size() {
2241
- return this.cache.size;
2288
+ /**
2289
+ * Transform data to pie chart format
2290
+ */
2291
+ static transformToPieChart(data) {
2292
+ const categories = this.detectCategories(data);
2293
+ const categoryData = this.aggregateByCategory(data, categories);
2294
+ const pieData = Object.entries(categoryData).map(([label, count]) => ({
2295
+ label,
2296
+ value: count,
2297
+ inStock: this.checkStockStatus(label, data)
2298
+ }));
2299
+ return {
2300
+ type: "pie_chart",
2301
+ title: "Distribution by Category",
2302
+ description: `Showing breakdown across ${categories.length} categories`,
2303
+ data: pieData
2304
+ };
2242
2305
  }
2243
- };
2244
- var Pipeline = class {
2245
- constructor(config) {
2246
- this.config = config;
2247
- /** LRU-bounded cache: avoids re-embedding identical queries within the same process. */
2248
- this.embeddingCache = new LRUEmbeddingCache(500);
2249
- this.initialised = false;
2250
- var _a, _b, _c, _d, _e;
2251
- this.chunker = new DocumentChunker(
2252
- (_b = (_a = config.rag) == null ? void 0 : _a.chunkSize) != null ? _b : 1e3,
2253
- (_d = (_c = config.rag) == null ? void 0 : _c.chunkOverlap) != null ? _d : 200
2306
+ /**
2307
+ * Transform data to bar chart format
2308
+ */
2309
+ static transformToBarChart(data) {
2310
+ const categories = this.detectCategories(data);
2311
+ const categoryData = this.aggregateByCategory(data, categories);
2312
+ const barData = Object.entries(categoryData).map(([category, value]) => ({
2313
+ category,
2314
+ value,
2315
+ inStock: this.checkStockStatus(category, data)
2316
+ }));
2317
+ return {
2318
+ type: "bar_chart",
2319
+ title: "Comparison by Category",
2320
+ description: `Comparing ${categories.length} categories`,
2321
+ data: barData
2322
+ };
2323
+ }
2324
+ /**
2325
+ * Transform data to line chart format
2326
+ */
2327
+ static transformToLineChart(data) {
2328
+ const timePoints = this.extractTimeSeriesData(data);
2329
+ const lineData = timePoints.map((point) => ({
2330
+ timestamp: point.timestamp,
2331
+ value: point.value,
2332
+ label: point.label
2333
+ }));
2334
+ return {
2335
+ type: "line_chart",
2336
+ title: "Trend Over Time",
2337
+ description: `Showing ${lineData.length} data points`,
2338
+ data: lineData
2339
+ };
2340
+ }
2341
+ /**
2342
+ * Transform data to table format
2343
+ */
2344
+ static transformToTable(data) {
2345
+ const columns = this.extractTableColumns(data);
2346
+ const rows = data.map((item) => this.extractTableRow(item, columns));
2347
+ const tableData = {
2348
+ columns,
2349
+ rows
2350
+ };
2351
+ return {
2352
+ type: "table",
2353
+ title: "Detailed Results",
2354
+ description: `Showing ${data.length} results`,
2355
+ data: tableData
2356
+ };
2357
+ }
2358
+ /**
2359
+ * Transform data to text format (fallback)
2360
+ */
2361
+ static transformToText(data) {
2362
+ const textContent = data.map((item) => item.content).join("\n\n");
2363
+ return this.createTextResponse(
2364
+ "Search Results",
2365
+ textContent,
2366
+ `Found ${data.length} relevant results`
2254
2367
  );
2255
- if (((_e = config.rag) == null ? void 0 : _e.chunkingStrategy) === "llamaindex") {
2256
- this.llamaIngestor = new LlamaIndexIngestor();
2368
+ }
2369
+ /**
2370
+ * Helper: Create text response
2371
+ */
2372
+ static createTextResponse(title, content, description) {
2373
+ return {
2374
+ type: "text",
2375
+ title,
2376
+ description,
2377
+ data: { content }
2378
+ };
2379
+ }
2380
+ /**
2381
+ * Helper: Check if data item is product-related
2382
+ */
2383
+ static isProductData(item) {
2384
+ const content = (item.content || "").toLowerCase();
2385
+ const productKeywords = ["product", "price", "stock", "item", "sku", "brand", "model"];
2386
+ return productKeywords.some((kw) => content.includes(kw)) || Object.keys(item.metadata || {}).some(
2387
+ (k) => ["name", "price", "product", "sku"].includes(k.toLowerCase())
2388
+ );
2389
+ }
2390
+ /**
2391
+ * Helper: Check if data contains time series
2392
+ */
2393
+ static isTimeSeriesData(item) {
2394
+ const content = (item.content || "").toLowerCase();
2395
+ const timeKeywords = ["date", "time", "year", "month", "week", "day", "hour", "trend", "historical"];
2396
+ return timeKeywords.some((kw) => content.includes(kw)) || Object.keys(item.metadata || {}).some(
2397
+ (k) => ["date", "timestamp", "time", "period"].includes(k.toLowerCase())
2398
+ );
2399
+ }
2400
+ /**
2401
+ * Helper: Extract product information from vector match
2402
+ */
2403
+ static extractProductInfo(item) {
2404
+ const meta = item.metadata || {};
2405
+ if (meta.name || meta.product) {
2406
+ return {
2407
+ id: item.id,
2408
+ name: meta.name || meta.product,
2409
+ price: meta.price,
2410
+ image: meta.image || meta.imageUrl,
2411
+ brand: meta.brand,
2412
+ description: item.content,
2413
+ inStock: this.determineStockStatus(item)
2414
+ };
2257
2415
  }
2258
- this.reranker = new Reranker();
2416
+ const nameMatch = item.content.match(/(?:Product|Item|Name):\s*([^\n]+)/i);
2417
+ const priceMatch = item.content.match(/(?:Price|Cost):\s*\$?([\d.]+)/i);
2418
+ if (nameMatch) {
2419
+ return {
2420
+ id: item.id,
2421
+ name: nameMatch[1],
2422
+ price: priceMatch ? parseFloat(priceMatch[1]) : void 0,
2423
+ description: item.content,
2424
+ inStock: this.determineStockStatus(item)
2425
+ };
2426
+ }
2427
+ return null;
2259
2428
  }
2260
- async initialize() {
2261
- var _a, _b;
2262
- if (this.initialised) return;
2263
- const CHART_MARKER = "<!-- UI_PROTOCOL_V7 -->";
2264
- const chartInstruction = `
2265
-
2266
- ${CHART_MARKER}
2267
- ### UNIVERSAL UI PROTOCOL V7 (STRICT MODE)
2268
-
2269
- You are responsible for returning a SINGLE structured UI block when visualization is required.
2270
-
2271
- ---
2272
-
2429
+ /**
2430
+ * Helper: Detect categories in data
2431
+ */
2432
+ static detectCategories(data) {
2433
+ const categories = /* @__PURE__ */ new Set();
2434
+ data.forEach((item) => {
2435
+ const meta = item.metadata || {};
2436
+ if (meta.category) {
2437
+ categories.add(String(meta.category));
2438
+ }
2439
+ if (meta.type) {
2440
+ categories.add(String(meta.type));
2441
+ }
2442
+ if (meta.tag) {
2443
+ const tags = Array.isArray(meta.tag) ? meta.tag : [meta.tag];
2444
+ tags.forEach((t) => categories.add(String(t)));
2445
+ }
2446
+ const categoryMatch = item.content.match(/(?:Category|Type|Class):\s*([^\n]+)/i);
2447
+ if (categoryMatch) {
2448
+ categories.add(categoryMatch[1].trim());
2449
+ }
2450
+ });
2451
+ return Array.from(categories);
2452
+ }
2453
+ /**
2454
+ * Helper: Aggregate data by category
2455
+ */
2456
+ static aggregateByCategory(data, categories) {
2457
+ const result = {};
2458
+ categories.forEach((cat) => {
2459
+ result[cat] = 0;
2460
+ });
2461
+ data.forEach((item) => {
2462
+ const meta = item.metadata || {};
2463
+ const itemCategory = meta.category || meta.type || "Other";
2464
+ if (result.hasOwnProperty(itemCategory)) {
2465
+ result[itemCategory]++;
2466
+ } else {
2467
+ result["Other"] = (result["Other"] || 0) + 1;
2468
+ }
2469
+ });
2470
+ return result;
2471
+ }
2472
+ /**
2473
+ * Helper: Extract time series data
2474
+ */
2475
+ static extractTimeSeriesData(data) {
2476
+ return data.map((item) => {
2477
+ const meta = item.metadata || {};
2478
+ return {
2479
+ timestamp: meta.timestamp || meta.date || (/* @__PURE__ */ new Date()).toISOString(),
2480
+ value: meta.value || item.score || 0,
2481
+ label: meta.label || item.content.substring(0, 50)
2482
+ };
2483
+ });
2484
+ }
2485
+ /**
2486
+ * Helper: Extract table columns
2487
+ */
2488
+ static extractTableColumns(data) {
2489
+ const columnSet = /* @__PURE__ */ new Set();
2490
+ columnSet.add("Content");
2491
+ data.forEach((item) => {
2492
+ Object.keys(item.metadata || {}).forEach((key) => {
2493
+ columnSet.add(key.charAt(0).toUpperCase() + key.slice(1));
2494
+ });
2495
+ });
2496
+ return Array.from(columnSet);
2497
+ }
2498
+ /**
2499
+ * Helper: Extract table row
2500
+ */
2501
+ static extractTableRow(item, columns) {
2502
+ const meta = item.metadata || {};
2503
+ return columns.map((col) => {
2504
+ if (col === "Content") {
2505
+ return item.content.substring(0, 100);
2506
+ }
2507
+ const metaKey = col.charAt(0).toLowerCase() + col.slice(1);
2508
+ const value = meta[metaKey];
2509
+ return value !== void 0 ? String(value) : "";
2510
+ });
2511
+ }
2512
+ /**
2513
+ * Helper: Check stock status
2514
+ */
2515
+ static checkStockStatus(category, data) {
2516
+ const item = data.find((d) => {
2517
+ const meta = d.metadata || {};
2518
+ return meta.category === category || meta.type === category;
2519
+ });
2520
+ return this.determineStockStatus(item || {});
2521
+ }
2522
+ /**
2523
+ * Helper: Determine if item is in stock
2524
+ */
2525
+ static determineStockStatus(item) {
2526
+ const meta = item.metadata || {};
2527
+ if (meta.inStock !== void 0) {
2528
+ return Boolean(meta.inStock);
2529
+ }
2530
+ if (meta.stock !== void 0) {
2531
+ return Boolean(meta.stock);
2532
+ }
2533
+ if (meta.available !== void 0) {
2534
+ return Boolean(meta.available);
2535
+ }
2536
+ const content = (item.content || "").toLowerCase();
2537
+ if (content.includes("out of stock") || content.includes("unavailable")) {
2538
+ return false;
2539
+ }
2540
+ if (content.includes("in stock") || content.includes("available")) {
2541
+ return true;
2542
+ }
2543
+ return true;
2544
+ }
2545
+ /**
2546
+ * Helper: Check if data has multiple fields
2547
+ */
2548
+ static hasMultipleFields(data) {
2549
+ const fieldCount = /* @__PURE__ */ new Set();
2550
+ data.forEach((item) => {
2551
+ Object.keys(item.metadata || {}).forEach((key) => {
2552
+ fieldCount.add(key);
2553
+ });
2554
+ });
2555
+ return fieldCount.size > 2;
2556
+ }
2557
+ };
2558
+
2559
+ // src/core/Pipeline.ts
2560
+ var LRUEmbeddingCache = class {
2561
+ constructor(maxSize = 500) {
2562
+ this.cache = /* @__PURE__ */ new Map();
2563
+ this.maxSize = maxSize;
2564
+ }
2565
+ get(key) {
2566
+ const value = this.cache.get(key);
2567
+ if (value !== void 0) {
2568
+ this.cache.delete(key);
2569
+ this.cache.set(key, value);
2570
+ }
2571
+ return value;
2572
+ }
2573
+ set(key, value) {
2574
+ if (this.cache.has(key)) {
2575
+ this.cache.delete(key);
2576
+ } else if (this.cache.size >= this.maxSize) {
2577
+ const oldestKey = this.cache.keys().next().value;
2578
+ if (oldestKey !== void 0) this.cache.delete(oldestKey);
2579
+ }
2580
+ this.cache.set(key, value);
2581
+ }
2582
+ clear() {
2583
+ this.cache.clear();
2584
+ }
2585
+ get size() {
2586
+ return this.cache.size;
2587
+ }
2588
+ };
2589
+ var Pipeline = class {
2590
+ constructor(config) {
2591
+ this.config = config;
2592
+ /** LRU-bounded cache: avoids re-embedding identical queries within the same process. */
2593
+ this.embeddingCache = new LRUEmbeddingCache(500);
2594
+ this.initialised = false;
2595
+ var _a, _b, _c, _d, _e;
2596
+ this.chunker = new DocumentChunker(
2597
+ (_b = (_a = config.rag) == null ? void 0 : _a.chunkSize) != null ? _b : 1e3,
2598
+ (_d = (_c = config.rag) == null ? void 0 : _c.chunkOverlap) != null ? _d : 200
2599
+ );
2600
+ if (((_e = config.rag) == null ? void 0 : _e.chunkingStrategy) === "llamaindex") {
2601
+ this.llamaIngestor = new LlamaIndexIngestor();
2602
+ }
2603
+ this.reranker = new Reranker();
2604
+ }
2605
+ async initialize() {
2606
+ var _a, _b;
2607
+ if (this.initialised) return;
2608
+ const CHART_MARKER = "<!-- UI_PROTOCOL_V7 -->";
2609
+ const chartInstruction = `
2610
+
2611
+ ${CHART_MARKER}
2612
+ ### UNIVERSAL UI PROTOCOL V7 (STRICT MODE)
2613
+
2614
+ You are responsible for returning a SINGLE structured UI block when visualization is required.
2615
+
2616
+ ---
2617
+
2273
2618
  ## 1. INTENT CLASSIFICATION (MANDATORY)
2274
2619
 
2275
2620
  Classify the query into ONE of the following intents:
@@ -2389,6 +2734,8 @@ Classify the query into ONE of the following intents:
2389
2734
  - ALWAYS return EXACTLY ONE \`\`\`ui\`\`\` block
2390
2735
  - JSON must be VALID
2391
2736
  - No explanation inside block
2737
+ - NEVER use ASCII charts, Markdown tables, or text-based drawings for data.
2738
+ - If data is tabular or statistical, ALWAYS use the \`\`\`ui\`\`\` block.
2392
2739
 
2393
2740
  ---
2394
2741
 
@@ -2444,914 +2791,575 @@ User: "distribution of products across categories"
2444
2791
  { "label": "Electronics", "value": 10 }
2445
2792
  ]
2446
2793
  },
2447
- "insights": ["Beauty dominates inventory"]
2448
- }
2449
- \`\`\`
2450
- `;
2451
- if (!((_a = this.config.llm.systemPrompt) == null ? void 0 : _a.includes(CHART_MARKER))) {
2452
- let cleanPrompt = this.config.llm.systemPrompt || "";
2453
- cleanPrompt = cleanPrompt.replace(/\n\n### UNIVERSAL UI PROTOCOL[\s\S]*?(?=\n\n|$)/g, "");
2454
- cleanPrompt = cleanPrompt.replace(/<!-- UI_PROTOCOL_V\d+ -->[\s\S]*?(?=\n\n|$)/g, "");
2455
- this.config.llm.systemPrompt = cleanPrompt.trim() + chartInstruction;
2456
- }
2457
- console.log(`[Pipeline] Initializing with provider: ${this.config.vectorDb.provider}...`);
2458
- this.vectorDB = await ProviderRegistry.createVectorProvider(this.config.vectorDb);
2459
- const { llmProvider, embeddingProvider } = await EmbeddingStrategyResolver.resolve(
2460
- this.config.llm,
2461
- this.config.embedding
2462
- );
2463
- this.llmProvider = llmProvider;
2464
- this.embeddingProvider = embeddingProvider;
2465
- if (this.config.graphDb) {
2466
- this.graphDB = await ProviderRegistry.createGraphProvider(this.config.graphDb);
2467
- await this.graphDB.initialize();
2468
- this.entityExtractor = new EntityExtractor(this.llmProvider);
2469
- }
2470
- await this.vectorDB.initialize();
2471
- if (((_b = this.config.rag) == null ? void 0 : _b.architecture) === "agentic") {
2472
- this.agent = new LangChainAgent(this, this.config);
2473
- await this.agent.initialize(this.llmProvider);
2474
- }
2475
- this.initialised = true;
2476
- }
2477
- /**
2478
- * Ingest documents with automatic chunking, embedding, and batch upsert.
2479
- * Handles retries for transient failures.
2480
- */
2481
- async ingest(documents, namespace) {
2482
- await this.initialize();
2483
- const ns = namespace != null ? namespace : this.config.projectId;
2484
- const results = [];
2485
- for (const doc of documents) {
2486
- try {
2487
- const chunks = await this.prepareChunks(doc);
2488
- const vectors = await this.processEmbeddings(chunks);
2489
- const upsertDocs = chunks.map((chunk, i) => ({
2490
- id: chunk.id,
2491
- vector: vectors[i],
2492
- content: chunk.content,
2493
- metadata: chunk.metadata
2494
- }));
2495
- const totalProcessed = await this.processUpserts(upsertDocs, ns);
2496
- results.push({
2497
- docId: doc.docId,
2498
- chunksIngested: totalProcessed
2499
- });
2500
- if (this.graphDB && this.entityExtractor) {
2501
- await this.processGraphIngestion(doc.docId, chunks);
2502
- }
2503
- } catch (error) {
2504
- console.error(`[Pipeline] Failed to ingest document ${doc.docId}:`, error);
2505
- results.push({ docId: doc.docId, chunksIngested: 0 });
2506
- }
2507
- }
2508
- return results;
2509
- }
2510
- /**
2511
- * Step 1: Chunk the document content.
2512
- */
2513
- async prepareChunks(doc) {
2514
- var _a, _b;
2515
- if (this.llamaIngestor) {
2516
- return await this.llamaIngestor.chunk(doc.content, {
2517
- docId: doc.docId,
2518
- metadata: doc.metadata,
2519
- chunkSize: (_a = this.config.rag) == null ? void 0 : _a.chunkSize,
2520
- chunkOverlap: (_b = this.config.rag) == null ? void 0 : _b.chunkOverlap
2521
- });
2522
- }
2523
- return this.chunker.chunk(doc.content, {
2524
- docId: doc.docId,
2525
- metadata: doc.metadata
2526
- });
2527
- }
2528
- /**
2529
- * Step 2: Generate embeddings for chunks with retry logic.
2530
- * Uses batchEmbed when available for efficiency; falls back to sequential embedding.
2531
- */
2532
- async processEmbeddings(chunks) {
2533
- const embedBatchOptions = {
2534
- batchSize: 50,
2535
- maxRetries: 3,
2536
- initialDelayMs: 100
2537
- };
2538
- const vectors = await BatchProcessor.mapWithRetry(
2539
- chunks.map((c) => c.content),
2540
- (text) => this.embeddingProvider.embed(text, { taskType: "document" }),
2541
- embedBatchOptions
2542
- );
2543
- if (vectors.length !== chunks.length) {
2544
- throw new Error(
2545
- `[Pipeline] Embedding mismatch: got ${vectors.length} vectors for ${chunks.length} chunks. Check embedding provider logs for individual chunk failures.`
2546
- );
2547
- }
2548
- return vectors;
2549
- }
2550
- /**
2551
- * Step 3: Upsert chunks to vector database with retry logic.
2552
- */
2553
- async processUpserts(upsertDocs, namespace) {
2554
- const upsertBatchOptions = {
2555
- batchSize: 100,
2556
- maxRetries: 3,
2557
- initialDelayMs: 100
2558
- };
2559
- const upsertResult = await BatchProcessor.processBatch(
2560
- upsertDocs,
2561
- (batch) => this.vectorDB.batchUpsert(batch, namespace),
2562
- upsertBatchOptions
2563
- );
2564
- if (upsertResult.errors.length > 0) {
2565
- console.warn(`[Pipeline] Ingestion: ${upsertResult.errors.length} batches failed`);
2566
- }
2567
- return upsertResult.totalProcessed;
2568
- }
2569
- /**
2570
- * Step 4: Optional graph-based entity extraction and ingestion.
2571
- */
2572
- async processGraphIngestion(docId, chunks) {
2573
- console.log(`[Pipeline] Extracting entities for doc ${docId} (${chunks.length} chunks)...`);
2574
- const extractionOptions = {
2575
- batchSize: 2,
2576
- // Low concurrency for LLM extraction
2577
- maxRetries: 1,
2578
- initialDelayMs: 500
2579
- };
2580
- await BatchProcessor.processBatch(
2581
- chunks,
2582
- async (batch) => {
2583
- for (const chunk of batch) {
2584
- try {
2585
- const { nodes, edges } = await this.entityExtractor.extract(chunk.content);
2586
- if (nodes.length > 0) await this.graphDB.addNodes(nodes);
2587
- if (edges.length > 0) await this.graphDB.addEdges(edges);
2588
- } catch (err) {
2589
- console.warn(`[Pipeline] Entity extraction failed for chunk:`, err);
2590
- }
2591
- }
2592
- },
2593
- extractionOptions
2594
- );
2595
- }
2596
- async ask(question, history = [], namespace) {
2597
- var _a;
2598
- await this.initialize();
2599
- if (((_a = this.config.rag) == null ? void 0 : _a.architecture) === "agentic" && this.agent) {
2600
- console.log("[Pipeline] \u{1F916} Executing in Agentic Mode...");
2601
- const agentReply = await this.agent.run(question, history);
2602
- return { reply: agentReply, sources: [] };
2603
- }
2604
- const stream = this.askStream(question, history, namespace);
2605
- let reply = "";
2606
- let sources = [];
2607
- let graphData;
2608
- try {
2609
- for (var iter = __forAwait(stream), more, temp, error; more = !(temp = await iter.next()).done; more = false) {
2610
- const chunk = temp.value;
2611
- if (typeof chunk === "string") {
2612
- reply += chunk;
2613
- } else if ("sources" in chunk) {
2614
- sources = chunk.sources;
2615
- graphData = chunk.graphData;
2616
- }
2617
- }
2618
- } catch (temp) {
2619
- error = [temp];
2620
- } finally {
2621
- try {
2622
- more && (temp = iter.return) && await temp.call(iter);
2623
- } finally {
2624
- if (error)
2625
- throw error[0];
2626
- }
2627
- }
2628
- return { reply, sources, graphData };
2629
- }
2630
- /**
2631
- * High-performance streaming RAG flow.
2632
- * Yields text chunks first, then the retrieval metadata at the end.
2633
- */
2634
- askStream(_0) {
2635
- return __asyncGenerator(this, arguments, function* (question, history = [], namespace) {
2636
- var _a, _b, _c, _d, _e, _f, _g;
2637
- yield new __await(this.initialize());
2638
- const ns = namespace != null ? namespace : this.config.projectId;
2639
- const topK = (_b = (_a = this.config.rag) == null ? void 0 : _a.topK) != null ? _b : 5;
2640
- const scoreThreshold = (_d = (_c = this.config.rag) == null ? void 0 : _c.scoreThreshold) != null ? _d : 0;
2641
- try {
2642
- let searchQuery = question;
2643
- if ((_e = this.config.rag) == null ? void 0 : _e.useQueryTransformation) {
2644
- searchQuery = yield new __await(this.rewriteQuery(question, history));
2645
- }
2646
- const hints = QueryProcessor.extractQueryFieldHints(question, (_f = this.config.rag) == null ? void 0 : _f.filterableFields);
2647
- const filter = QueryProcessor.buildQueryFilter(question, hints);
2648
- console.log(`[Pipeline] \u{1F9E9} Extracted filters:`, JSON.stringify(filter));
2649
- const { sources: rawSources, graphData } = yield new __await(this.retrieve(searchQuery, {
2650
- namespace: ns,
2651
- topK: topK * 2,
2652
- filter
2653
- }));
2654
- let sources = rawSources.filter((m) => m.score >= scoreThreshold);
2655
- if ((_g = this.config.rag) == null ? void 0 : _g.useReranking) {
2656
- sources = yield new __await(this.reranker.rerank(sources, question, topK));
2657
- } else {
2658
- sources = sources.slice(0, topK);
2659
- }
2660
- let context = sources.length ? sources.map((m, i) => `[Source ${i + 1}]
2661
- ${m.content}`).join("\n\n---\n\n") : "No relevant context found.";
2662
- if (graphData && graphData.nodes.length > 0) {
2663
- const graphContext = graphData.nodes.map(
2664
- (n) => `Entity: ${n.label} (${n.id})${n.properties ? " - " + JSON.stringify(n.properties) : ""}`
2665
- ).join("\n");
2666
- context = `GRAPH KNOWLEDGE:
2667
- ${graphContext}
2668
-
2669
- VECTOR CONTEXT:
2670
- ${context}`;
2671
- }
2672
- const messages = [...history, { role: "user", content: question }];
2673
- if (this.llmProvider.chatStream) {
2674
- const stream = this.llmProvider.chatStream(messages, context);
2675
- if (!stream) {
2676
- throw new Error(`[Pipeline] ${this.config.llm.provider} chatStream returned undefined`);
2677
- }
2678
- try {
2679
- for (var iter = __forAwait(stream), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
2680
- const chunk = temp.value;
2681
- yield chunk;
2682
- }
2683
- } catch (temp) {
2684
- error = [temp];
2685
- } finally {
2686
- try {
2687
- more && (temp = iter.return) && (yield new __await(temp.call(iter)));
2688
- } finally {
2689
- if (error)
2690
- throw error[0];
2691
- }
2692
- }
2693
- } else {
2694
- const reply = yield new __await(this.llmProvider.chat(messages, context));
2695
- yield reply;
2696
- }
2697
- yield { reply: "", sources, graphData };
2698
- } catch (error2) {
2699
- throw new Error(`[Pipeline] Stream failed: ${error2 instanceof Error ? error2.message : String(error2)}`);
2700
- }
2701
- });
2702
- }
2703
- /**
2704
- * Universal retrieval method combining all enabled providers.
2705
- * Uses an LRU-bounded embedding cache to avoid re-embedding the same query.
2706
- */
2707
- async retrieve(query, options) {
2708
- var _a, _b, _c;
2709
- const ns = (_a = options.namespace) != null ? _a : this.config.projectId;
2710
- const topK = (_b = options.topK) != null ? _b : 5;
2711
- const cacheKey = `${ns}::${query}`;
2712
- let queryVector = this.embeddingCache.get(cacheKey);
2713
- const [retrievedVector, graphData] = await Promise.all([
2714
- queryVector ? Promise.resolve(queryVector) : this.embeddingProvider.embed(query, { taskType: "query" }),
2715
- this.graphDB && ((_c = this.config.rag) == null ? void 0 : _c.useGraphRetrieval) ? this.graphDB.query(query) : Promise.resolve(void 0)
2716
- ]);
2717
- if (!queryVector) {
2718
- this.embeddingCache.set(cacheKey, retrievedVector);
2719
- queryVector = retrievedVector;
2720
- }
2721
- const sources = await this.vectorDB.query(queryVector, topK, ns, options.filter);
2722
- return { sources, graphData };
2723
- }
2724
- /**
2725
- * Rewrite the user query for better retrieval performance.
2726
- */
2727
- async rewriteQuery(question, history) {
2728
- const prompt = `
2729
- Given the following conversation history and a new question, rewrite the question to be a better search query for a vector database.
2730
- Focus on extracting the core intent and entities. Do not answer the question, just rewrite it.
2731
-
2732
- History:
2733
- ${history.map((m) => `${m.role}: ${m.content}`).join("\n")}
2734
-
2735
- New Question: ${question}
2736
-
2737
- Optimized Search Query:`;
2738
- const rewrite = await this.llmProvider.chat(
2739
- [
2740
- { role: "system", content: "You are an assistant that optimizes search queries for RAG systems." },
2741
- { role: "user", content: prompt }
2742
- ],
2743
- ""
2744
- );
2745
- return rewrite.trim() || question;
2746
- }
2747
- /**
2748
- * Generate 3-5 short, relevant questions based on the vector database content.
2749
- */
2750
- async getSuggestions(query, namespace) {
2751
- if (!query || query.trim().length < 3) {
2752
- return [];
2753
- }
2754
- await this.initialize();
2755
- const ns = namespace != null ? namespace : this.config.projectId;
2756
- try {
2757
- const { sources } = await this.retrieve(query, { namespace: ns, topK: 3 });
2758
- if (sources.length === 0) {
2759
- return [];
2760
- }
2761
- const context = sources.map((s) => s.content).join("\n\n---\n\n");
2762
- const prompt = `
2763
- Based on the following snippets from a document, what are 3 short, relevant questions a user might ask?
2764
- Focus on questions that can be answered by the context.
2765
- Keep each question under 10 words and make them very specific to the content.
2766
- Return ONLY a JSON array of strings like ["Question 1", "Question 2", "Question 3"].
2767
-
2768
- Context:
2769
- ${context}
2770
-
2771
- Suggestions:`;
2772
- const response = await this.llmProvider.chat(
2773
- [
2774
- { role: "system", content: "You are a helpful assistant that generates search suggestions." },
2775
- { role: "user", content: prompt }
2776
- ],
2777
- ""
2778
- );
2779
- const match = response.match(/\[[\s\S]*\]/);
2780
- if (match) {
2781
- const suggestions = JSON.parse(match[0]);
2782
- if (Array.isArray(suggestions)) {
2783
- return suggestions.map((s) => String(s)).slice(0, 3);
2784
- }
2785
- }
2786
- } catch (error) {
2787
- console.error("[Pipeline] Failed to generate suggestions:", error);
2788
- }
2789
- return [];
2790
- }
2791
- };
2792
-
2793
- // src/core/ProviderHealthCheck.ts
2794
- var ProviderHealthCheck = class {
2795
- /**
2796
- * Validates vector database configuration before initialization.
2797
- */
2798
- static async checkVectorProvider(config) {
2799
- const timestamp = Date.now();
2800
- const configErrors = await ConfigValidator.validate({
2801
- projectId: "health-check",
2802
- vectorDb: config,
2803
- llm: { provider: "openai", model: "gpt-4o", apiKey: "none" },
2804
- embedding: { provider: "openai", model: "text-embedding-3-small", apiKey: "none" }
2805
- });
2806
- const vectorDbErrors = configErrors.filter((e) => e.field.startsWith("vectorDb"));
2807
- if (vectorDbErrors.length > 0) {
2808
- return {
2809
- healthy: false,
2810
- provider: config.provider,
2811
- error: `Configuration validation failed: ${vectorDbErrors.map((e) => e.message).join("; ")}`,
2812
- timestamp
2813
- };
2814
- }
2815
- try {
2816
- const checker = await ProviderRegistry.getVectorHealthChecker(config.provider);
2817
- if (checker) {
2818
- return await checker.check(config);
2819
- }
2820
- return await this.fallbackVectorHealthCheck(config, timestamp);
2821
- } catch (error) {
2822
- return {
2823
- healthy: false,
2824
- provider: config.provider,
2825
- error: error instanceof Error ? error.message : String(error),
2826
- timestamp
2827
- };
2828
- }
2829
- }
2830
- static async fallbackVectorHealthCheck(config, timestamp) {
2831
- const opts = config.options || {};
2832
- const baseUrl = opts.baseUrl || opts.uri;
2833
- if (baseUrl && baseUrl.startsWith("http")) {
2834
- try {
2835
- const response = await fetch(`${baseUrl.replace(/\/$/, "")}/health`);
2836
- return {
2837
- healthy: response.ok,
2838
- provider: config.provider,
2839
- error: response.ok ? void 0 : `Health check failed: ${response.status}`,
2840
- timestamp
2841
- };
2842
- } catch (e) {
2843
- return { healthy: false, provider: config.provider, error: "Provider unreachable", timestamp };
2844
- }
2845
- }
2846
- return {
2847
- healthy: true,
2848
- provider: config.provider,
2849
- error: "Pluggable health check not implemented; basic reachability assumed.",
2850
- timestamp
2851
- };
2852
- }
2853
- /**
2854
- * Validates LLM provider configuration.
2855
- */
2856
- static async checkLLMProvider(config) {
2857
- const timestamp = Date.now();
2858
- try {
2859
- const checker = LLMFactory.getHealthChecker(config.provider);
2860
- if (checker) {
2861
- return await checker.check(config);
2862
- }
2863
- return {
2864
- healthy: true,
2865
- provider: config.provider,
2866
- error: "Pluggable health check not implemented; basic reachability assumed.",
2867
- timestamp
2868
- };
2869
- } catch (error) {
2870
- return {
2871
- healthy: false,
2872
- provider: config.provider,
2873
- error: error instanceof Error ? error.message : String(error),
2874
- timestamp
2875
- };
2876
- }
2877
- }
2878
- /**
2879
- * Runs comprehensive health checks on all configured providers in parallel.
2880
- */
2881
- static async checkAll(vectorDbConfig, llmConfig, embeddingConfig) {
2882
- const [vectorDb, llm, embedding] = await Promise.all([
2883
- this.checkVectorProvider(vectorDbConfig),
2884
- this.checkLLMProvider(llmConfig),
2885
- embeddingConfig ? this.checkLLMProvider(embeddingConfig) : Promise.resolve(void 0)
2886
- ]);
2887
- return {
2888
- vectorDb,
2889
- llm,
2890
- embedding,
2891
- allHealthy: vectorDb.healthy && llm.healthy && (!embedding || embedding.healthy)
2892
- };
2893
- }
2894
- };
2895
-
2896
- // src/core/VectorPlugin.ts
2897
- var VectorPlugin = class {
2898
- constructor(hostConfig) {
2899
- this.config = ConfigResolver.resolve(hostConfig);
2900
- this.validationPromise = ConfigValidator.validateAndThrow(this.config);
2901
- this.pipeline = new Pipeline(this.config);
2902
- }
2903
- /**
2904
- * Get the current resolved configuration.
2905
- */
2906
- getConfig() {
2907
- return this.config;
2908
- }
2909
- /**
2910
- * Perform pre-flight health checks on all configured providers.
2911
- * Useful to verify connectivity before running operations.
2912
- *
2913
- * @returns Health status for vector DB, LLM, and embedding providers
2914
- */
2915
- async checkHealth() {
2916
- return ProviderHealthCheck.checkAll(
2917
- this.config.vectorDb,
2918
- this.config.llm,
2919
- this.config.embedding
2920
- );
2921
- }
2922
- /**
2923
- * Run a chat query.
2924
- */
2925
- async chat(message, history = [], namespace) {
2926
- await this.validationPromise;
2927
- return this.pipeline.ask(message, history, namespace);
2928
- }
2929
- /**
2930
- * Run a streaming chat query.
2931
- */
2932
- chatStream(_0) {
2933
- return __asyncGenerator(this, arguments, function* (message, history = [], namespace) {
2934
- yield new __await(this.validationPromise);
2935
- yield* __yieldStar(this.pipeline.askStream(message, history, namespace));
2936
- });
2937
- }
2938
- /**
2939
- * Ingest documents into the vector database.
2940
- */
2941
- async ingest(documents, namespace) {
2942
- await this.validationPromise;
2943
- return this.pipeline.ingest(documents, namespace);
2944
- }
2945
- /**
2946
- * Get auto-suggestions based on a query prefix.
2947
- */
2948
- async getSuggestions(query, namespace) {
2949
- await this.validationPromise;
2950
- return this.pipeline.getSuggestions(query, namespace);
2951
- }
2952
- };
2953
-
2954
- // src/utils/DocumentParser.ts
2955
- var DocumentParser = class {
2956
- /**
2957
- * Extract text from a File or Buffer based on its type.
2958
- */
2959
- static async parse(file, fileName, mimeType) {
2960
- var _a;
2961
- const extension = (_a = fileName.split(".").pop()) == null ? void 0 : _a.toLowerCase();
2962
- if (extension === "txt" || extension === "md" || mimeType === "text/plain" || mimeType === "text/markdown") {
2963
- return this.readAsText(file);
2964
- }
2965
- if (extension === "json" || mimeType === "application/json") {
2966
- const text = await this.readAsText(file);
2967
- try {
2968
- const obj = JSON.parse(text);
2969
- return JSON.stringify(obj, null, 2);
2970
- } catch (e) {
2971
- return text;
2972
- }
2973
- }
2974
- if (extension === "csv" || mimeType === "text/csv") {
2975
- return this.readAsText(file);
2976
- }
2977
- if (extension === "pdf" || mimeType === "application/pdf") {
2978
- try {
2979
- const pdf = await import("pdf-parse");
2980
- const buffer = Buffer.isBuffer(file) ? file : Buffer.from(await file.arrayBuffer());
2981
- const data = await pdf.default(buffer);
2982
- return data.text;
2983
- } catch (err) {
2984
- console.warn('[DocumentParser] PDF parsing failed. Make sure "pdf-parse" is installed.', err);
2985
- return `[PDF Parsing Error for ${fileName}]`;
2986
- }
2987
- }
2988
- if (extension === "docx" || mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
2989
- try {
2990
- const mammoth = await import("mammoth");
2991
- const buffer = Buffer.isBuffer(file) ? file : Buffer.from(await file.arrayBuffer());
2992
- const result = await mammoth.extractRawText({ buffer });
2993
- return result.value;
2994
- } catch (err) {
2995
- console.warn('[DocumentParser] DOCX parsing failed. Make sure "mammoth" is installed.', err);
2996
- return `[DOCX Parsing Error for ${fileName}]`;
2997
- }
2794
+ "insights": ["Beauty dominates inventory"]
2795
+ }
2796
+ \`\`\`
2797
+ `;
2798
+ if (!((_a = this.config.llm.systemPrompt) == null ? void 0 : _a.includes(CHART_MARKER))) {
2799
+ let cleanPrompt = this.config.llm.systemPrompt || "";
2800
+ cleanPrompt = cleanPrompt.replace(/\n\n### UNIVERSAL UI PROTOCOL[\s\S]*?(?=\n\n|$)/g, "");
2801
+ cleanPrompt = cleanPrompt.replace(/<!-- UI_PROTOCOL_V\d+ -->[\s\S]*?(?=\n\n|$)/g, "");
2802
+ this.config.llm.systemPrompt = cleanPrompt.trim() + chartInstruction;
2998
2803
  }
2999
- try {
3000
- return await this.readAsText(file);
3001
- } catch (e) {
3002
- throw new Error(`[DocumentParser] Unsupported file format: ${fileName} (${mimeType})`);
2804
+ console.log(`[Pipeline] Initializing with provider: ${this.config.vectorDb.provider}...`);
2805
+ this.vectorDB = await ProviderRegistry.createVectorProvider(this.config.vectorDb);
2806
+ const { llmProvider, embeddingProvider } = await EmbeddingStrategyResolver.resolve(
2807
+ this.config.llm,
2808
+ this.config.embedding
2809
+ );
2810
+ this.llmProvider = llmProvider;
2811
+ this.embeddingProvider = embeddingProvider;
2812
+ if (this.config.graphDb) {
2813
+ this.graphDB = await ProviderRegistry.createGraphProvider(this.config.graphDb);
2814
+ await this.graphDB.initialize();
2815
+ this.entityExtractor = new EntityExtractor(this.llmProvider);
3003
2816
  }
3004
- }
3005
- static async readAsText(file) {
3006
- if (Buffer.isBuffer(file)) {
3007
- return file.toString("utf-8");
2817
+ await this.vectorDB.initialize();
2818
+ if (((_b = this.config.rag) == null ? void 0 : _b.architecture) === "agentic") {
2819
+ this.agent = new LangChainAgent(this, this.config);
2820
+ await this.agent.initialize(this.llmProvider);
3008
2821
  }
3009
- return await file.text();
2822
+ this.initialised = true;
3010
2823
  }
3011
- };
3012
-
3013
- // src/utils/UITransformer.ts
3014
- var UITransformer = class {
3015
2824
  /**
3016
- * Main transformation method
3017
- * Analyzes user query and retrieved data to determine the best visualization format
3018
- *
3019
- * @param userQuery - The original user question/query
3020
- * @param retrievedData - Vector database retrieval results
3021
- * @returns Structured JSON response for UI rendering
2825
+ * Ingest documents with automatic chunking, embedding, and batch upsert.
2826
+ * Handles retries for transient failures.
3022
2827
  */
3023
- static transform(userQuery, retrievedData) {
3024
- if (!retrievedData || retrievedData.length === 0) {
3025
- return this.createTextResponse("No data available", "No relevant data found for your query.");
3026
- }
3027
- const analysis = this.analyzeData(userQuery, retrievedData);
3028
- switch (analysis.suggestedType) {
3029
- case "product_carousel":
3030
- return this.transformToProductCarousel(retrievedData);
3031
- case "pie_chart":
3032
- return this.transformToPieChart(retrievedData);
3033
- case "bar_chart":
3034
- return this.transformToBarChart(retrievedData);
3035
- case "line_chart":
3036
- return this.transformToLineChart(retrievedData);
3037
- case "table":
3038
- return this.transformToTable(retrievedData);
3039
- default:
3040
- return this.transformToText(retrievedData);
2828
+ async ingest(documents, namespace) {
2829
+ await this.initialize();
2830
+ const ns = namespace != null ? namespace : this.config.projectId;
2831
+ const results = [];
2832
+ for (const doc of documents) {
2833
+ try {
2834
+ const chunks = await this.prepareChunks(doc);
2835
+ const vectors = await this.processEmbeddings(chunks);
2836
+ const upsertDocs = chunks.map((chunk, i) => ({
2837
+ id: chunk.id,
2838
+ vector: vectors[i],
2839
+ content: chunk.content,
2840
+ metadata: chunk.metadata
2841
+ }));
2842
+ const totalProcessed = await this.processUpserts(upsertDocs, ns);
2843
+ results.push({
2844
+ docId: doc.docId,
2845
+ chunksIngested: totalProcessed
2846
+ });
2847
+ if (this.graphDB && this.entityExtractor) {
2848
+ await this.processGraphIngestion(doc.docId, chunks);
2849
+ }
2850
+ } catch (error) {
2851
+ console.error(`[Pipeline] Failed to ingest document ${doc.docId}:`, error);
2852
+ results.push({ docId: doc.docId, chunksIngested: 0 });
2853
+ }
3041
2854
  }
2855
+ return results;
3042
2856
  }
3043
2857
  /**
3044
- * Analyzes the data and query to suggest the best visualization type
2858
+ * Step 1: Chunk the document content.
3045
2859
  */
3046
- static analyzeData(query, data) {
3047
- const queryLower = query.toLowerCase();
3048
- const hasProducts = data.some(
3049
- (item) => this.isProductData(item)
3050
- );
3051
- const hasTimeSeries = data.some(
3052
- (item) => this.isTimeSeriesData(item)
3053
- );
3054
- const hasCategories = this.detectCategories(data).length > 0;
3055
- const isDistributionQuery = queryLower.includes("distribution") || queryLower.includes("breakdown") || queryLower.includes("percentage") || queryLower.includes("proportion");
3056
- const isComparisonQuery = queryLower.includes("compare") || queryLower.includes("vs") || queryLower.includes("difference");
3057
- const isTrendQuery = queryLower.includes("trend") || queryLower.includes("over time") || queryLower.includes("growth") || queryLower.includes("decline");
3058
- if (hasProducts && !hasTimeSeries && !isDistributionQuery) {
3059
- return { suggestedType: "product_carousel", confidence: 0.95, hasProducts, hasTimeSeries, hasCategories };
3060
- }
3061
- if (isTrendQuery && hasTimeSeries) {
3062
- return { suggestedType: "line_chart", confidence: 0.9, hasProducts, hasTimeSeries, hasCategories };
3063
- }
3064
- if (isDistributionQuery && hasCategories) {
3065
- return { suggestedType: "pie_chart", confidence: 0.85, hasProducts, hasTimeSeries, hasCategories };
3066
- }
3067
- if (isComparisonQuery && hasCategories && data.length > 2) {
3068
- return { suggestedType: "bar_chart", confidence: 0.8, hasProducts, hasTimeSeries, hasCategories };
3069
- }
3070
- if (data.length > 5 && this.hasMultipleFields(data)) {
3071
- return { suggestedType: "table", confidence: 0.75, hasProducts, hasTimeSeries, hasCategories };
2860
+ async prepareChunks(doc) {
2861
+ var _a, _b;
2862
+ if (this.llamaIngestor) {
2863
+ return await this.llamaIngestor.chunk(doc.content, {
2864
+ docId: doc.docId,
2865
+ metadata: doc.metadata,
2866
+ chunkSize: (_a = this.config.rag) == null ? void 0 : _a.chunkSize,
2867
+ chunkOverlap: (_b = this.config.rag) == null ? void 0 : _b.chunkOverlap
2868
+ });
3072
2869
  }
3073
- return { suggestedType: "text", confidence: 0.5, hasProducts, hasTimeSeries, hasCategories };
2870
+ return this.chunker.chunk(doc.content, {
2871
+ docId: doc.docId,
2872
+ metadata: doc.metadata
2873
+ });
3074
2874
  }
3075
2875
  /**
3076
- * Transform data to product carousel format
2876
+ * Step 2: Generate embeddings for chunks with retry logic.
2877
+ * Uses batchEmbed when available for efficiency; falls back to sequential embedding.
3077
2878
  */
3078
- static transformToProductCarousel(data) {
3079
- const products = data.filter((item) => this.isProductData(item)).map((item) => this.extractProductInfo(item)).filter((p) => p !== null);
3080
- return {
3081
- type: "product_carousel",
3082
- title: "Recommended Products",
3083
- description: `Found ${products.length} relevant products`,
3084
- data: products
2879
+ async processEmbeddings(chunks) {
2880
+ const embedBatchOptions = {
2881
+ batchSize: 50,
2882
+ maxRetries: 3,
2883
+ initialDelayMs: 100
3085
2884
  };
2885
+ const vectors = await BatchProcessor.mapWithRetry(
2886
+ chunks.map((c) => c.content),
2887
+ (text) => this.embeddingProvider.embed(text, { taskType: "document" }),
2888
+ embedBatchOptions
2889
+ );
2890
+ if (vectors.length !== chunks.length) {
2891
+ throw new Error(
2892
+ `[Pipeline] Embedding mismatch: got ${vectors.length} vectors for ${chunks.length} chunks. Check embedding provider logs for individual chunk failures.`
2893
+ );
2894
+ }
2895
+ return vectors;
3086
2896
  }
3087
2897
  /**
3088
- * Transform data to pie chart format
2898
+ * Step 3: Upsert chunks to vector database with retry logic.
3089
2899
  */
3090
- static transformToPieChart(data) {
3091
- const categories = this.detectCategories(data);
3092
- const categoryData = this.aggregateByCategory(data, categories);
3093
- const pieData = Object.entries(categoryData).map(([label, count]) => ({
3094
- label,
3095
- value: count,
3096
- inStock: this.checkStockStatus(label, data)
3097
- }));
3098
- return {
3099
- type: "pie_chart",
3100
- title: "Distribution by Category",
3101
- description: `Showing breakdown across ${categories.length} categories`,
3102
- data: pieData
2900
+ async processUpserts(upsertDocs, namespace) {
2901
+ const upsertBatchOptions = {
2902
+ batchSize: 100,
2903
+ maxRetries: 3,
2904
+ initialDelayMs: 100
3103
2905
  };
2906
+ const upsertResult = await BatchProcessor.processBatch(
2907
+ upsertDocs,
2908
+ (batch) => this.vectorDB.batchUpsert(batch, namespace),
2909
+ upsertBatchOptions
2910
+ );
2911
+ if (upsertResult.errors.length > 0) {
2912
+ console.warn(`[Pipeline] Ingestion: ${upsertResult.errors.length} batches failed`);
2913
+ }
2914
+ return upsertResult.totalProcessed;
3104
2915
  }
3105
2916
  /**
3106
- * Transform data to bar chart format
2917
+ * Step 4: Optional graph-based entity extraction and ingestion.
3107
2918
  */
3108
- static transformToBarChart(data) {
3109
- const categories = this.detectCategories(data);
3110
- const categoryData = this.aggregateByCategory(data, categories);
3111
- const barData = Object.entries(categoryData).map(([category, value]) => ({
3112
- category,
3113
- value,
3114
- inStock: this.checkStockStatus(category, data)
3115
- }));
3116
- return {
3117
- type: "bar_chart",
3118
- title: "Comparison by Category",
3119
- description: `Comparing ${categories.length} categories`,
3120
- data: barData
2919
+ async processGraphIngestion(docId, chunks) {
2920
+ console.log(`[Pipeline] Extracting entities for doc ${docId} (${chunks.length} chunks)...`);
2921
+ const extractionOptions = {
2922
+ batchSize: 2,
2923
+ // Low concurrency for LLM extraction
2924
+ maxRetries: 1,
2925
+ initialDelayMs: 500
3121
2926
  };
2927
+ await BatchProcessor.processBatch(
2928
+ chunks,
2929
+ async (batch) => {
2930
+ for (const chunk of batch) {
2931
+ try {
2932
+ const { nodes, edges } = await this.entityExtractor.extract(chunk.content);
2933
+ if (nodes.length > 0) await this.graphDB.addNodes(nodes);
2934
+ if (edges.length > 0) await this.graphDB.addEdges(edges);
2935
+ } catch (err) {
2936
+ console.warn(`[Pipeline] Entity extraction failed for chunk:`, err);
2937
+ }
2938
+ }
2939
+ },
2940
+ extractionOptions
2941
+ );
2942
+ }
2943
+ async ask(question, history = [], namespace) {
2944
+ var _a;
2945
+ await this.initialize();
2946
+ if (((_a = this.config.rag) == null ? void 0 : _a.architecture) === "agentic" && this.agent) {
2947
+ console.log("[Pipeline] \u{1F916} Executing in Agentic Mode...");
2948
+ const agentReply = await this.agent.run(question, history);
2949
+ return { reply: agentReply, sources: [] };
2950
+ }
2951
+ const stream = this.askStream(question, history, namespace);
2952
+ let reply = "";
2953
+ let sources = [];
2954
+ let graphData;
2955
+ try {
2956
+ for (var iter = __forAwait(stream), more, temp, error; more = !(temp = await iter.next()).done; more = false) {
2957
+ const chunk = temp.value;
2958
+ if (typeof chunk === "string") {
2959
+ reply += chunk;
2960
+ } else if ("sources" in chunk) {
2961
+ sources = chunk.sources;
2962
+ graphData = chunk.graphData;
2963
+ }
2964
+ }
2965
+ } catch (temp) {
2966
+ error = [temp];
2967
+ } finally {
2968
+ try {
2969
+ more && (temp = iter.return) && await temp.call(iter);
2970
+ } finally {
2971
+ if (error)
2972
+ throw error[0];
2973
+ }
2974
+ }
2975
+ return { reply, sources, graphData };
3122
2976
  }
3123
2977
  /**
3124
- * Transform data to line chart format
2978
+ * High-performance streaming RAG flow.
2979
+ * Yields text chunks first, then the retrieval metadata at the end.
3125
2980
  */
3126
- static transformToLineChart(data) {
3127
- const timePoints = this.extractTimeSeriesData(data);
3128
- const lineData = timePoints.map((point) => ({
3129
- timestamp: point.timestamp,
3130
- value: point.value,
3131
- label: point.label
3132
- }));
3133
- return {
3134
- type: "line_chart",
3135
- title: "Trend Over Time",
3136
- description: `Showing ${lineData.length} data points`,
3137
- data: lineData
3138
- };
2981
+ askStream(_0) {
2982
+ return __asyncGenerator(this, arguments, function* (question, history = [], namespace) {
2983
+ var _a, _b, _c, _d, _e, _f, _g;
2984
+ yield new __await(this.initialize());
2985
+ const ns = namespace != null ? namespace : this.config.projectId;
2986
+ const topK = (_b = (_a = this.config.rag) == null ? void 0 : _a.topK) != null ? _b : 5;
2987
+ const scoreThreshold = (_d = (_c = this.config.rag) == null ? void 0 : _c.scoreThreshold) != null ? _d : 0;
2988
+ try {
2989
+ let searchQuery = question;
2990
+ if ((_e = this.config.rag) == null ? void 0 : _e.useQueryTransformation) {
2991
+ searchQuery = yield new __await(this.rewriteQuery(question, history));
2992
+ }
2993
+ const hints = QueryProcessor.extractQueryFieldHints(question, (_f = this.config.rag) == null ? void 0 : _f.filterableFields);
2994
+ const filter = QueryProcessor.buildQueryFilter(question, hints);
2995
+ console.log(`[Pipeline] \u{1F9E9} Extracted filters:`, JSON.stringify(filter));
2996
+ const { sources: rawSources, graphData } = yield new __await(this.retrieve(searchQuery, {
2997
+ namespace: ns,
2998
+ topK: topK * 2,
2999
+ filter
3000
+ }));
3001
+ let sources = rawSources.filter((m) => m.score >= scoreThreshold);
3002
+ if ((_g = this.config.rag) == null ? void 0 : _g.useReranking) {
3003
+ sources = yield new __await(this.reranker.rerank(sources, question, topK));
3004
+ } else {
3005
+ sources = sources.slice(0, topK);
3006
+ }
3007
+ let context = sources.length ? sources.map((m, i) => `[Source ${i + 1}]
3008
+ ${m.content}`).join("\n\n---\n\n") : "No relevant context found.";
3009
+ if (graphData && graphData.nodes.length > 0) {
3010
+ const graphContext = graphData.nodes.map(
3011
+ (n) => `Entity: ${n.label} (${n.id})${n.properties ? " - " + JSON.stringify(n.properties) : ""}`
3012
+ ).join("\n");
3013
+ context = `GRAPH KNOWLEDGE:
3014
+ ${graphContext}
3015
+
3016
+ VECTOR CONTEXT:
3017
+ ${context}`;
3018
+ }
3019
+ const messages = [...history, { role: "user", content: question }];
3020
+ if (this.llmProvider.chatStream) {
3021
+ const stream = this.llmProvider.chatStream(messages, context);
3022
+ if (!stream) {
3023
+ throw new Error(`[Pipeline] ${this.config.llm.provider} chatStream returned undefined`);
3024
+ }
3025
+ try {
3026
+ for (var iter = __forAwait(stream), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
3027
+ const chunk = temp.value;
3028
+ yield chunk;
3029
+ }
3030
+ } catch (temp) {
3031
+ error = [temp];
3032
+ } finally {
3033
+ try {
3034
+ more && (temp = iter.return) && (yield new __await(temp.call(iter)));
3035
+ } finally {
3036
+ if (error)
3037
+ throw error[0];
3038
+ }
3039
+ }
3040
+ } else {
3041
+ const reply = yield new __await(this.llmProvider.chat(messages, context));
3042
+ yield reply;
3043
+ }
3044
+ const uiTransformation = UITransformer.transform(question, sources);
3045
+ yield {
3046
+ reply: "",
3047
+ sources,
3048
+ graphData,
3049
+ ui_transformation: uiTransformation
3050
+ };
3051
+ } catch (error2) {
3052
+ throw new Error(`[Pipeline] Stream failed: ${error2 instanceof Error ? error2.message : String(error2)}`);
3053
+ }
3054
+ });
3139
3055
  }
3140
3056
  /**
3141
- * Transform data to table format
3057
+ * Universal retrieval method combining all enabled providers.
3058
+ * Uses an LRU-bounded embedding cache to avoid re-embedding the same query.
3142
3059
  */
3143
- static transformToTable(data) {
3144
- const columns = this.extractTableColumns(data);
3145
- const rows = data.map((item) => this.extractTableRow(item, columns));
3146
- const tableData = {
3147
- columns,
3148
- rows
3149
- };
3150
- return {
3151
- type: "table",
3152
- title: "Detailed Results",
3153
- description: `Showing ${data.length} results`,
3154
- data: tableData
3155
- };
3060
+ async retrieve(query, options) {
3061
+ var _a, _b, _c;
3062
+ const ns = (_a = options.namespace) != null ? _a : this.config.projectId;
3063
+ const topK = (_b = options.topK) != null ? _b : 5;
3064
+ const cacheKey = `${ns}::${query}`;
3065
+ let queryVector = this.embeddingCache.get(cacheKey);
3066
+ const [retrievedVector, graphData] = await Promise.all([
3067
+ queryVector ? Promise.resolve(queryVector) : this.embeddingProvider.embed(query, { taskType: "query" }),
3068
+ this.graphDB && ((_c = this.config.rag) == null ? void 0 : _c.useGraphRetrieval) ? this.graphDB.query(query) : Promise.resolve(void 0)
3069
+ ]);
3070
+ if (!queryVector) {
3071
+ this.embeddingCache.set(cacheKey, retrievedVector);
3072
+ queryVector = retrievedVector;
3073
+ }
3074
+ const sources = await this.vectorDB.query(queryVector, topK, ns, options.filter);
3075
+ return { sources, graphData };
3156
3076
  }
3157
3077
  /**
3158
- * Transform data to text format (fallback)
3078
+ * Rewrite the user query for better retrieval performance.
3159
3079
  */
3160
- static transformToText(data) {
3161
- const textContent = data.map((item) => item.content).join("\n\n");
3162
- return this.createTextResponse(
3163
- "Search Results",
3164
- textContent,
3165
- `Found ${data.length} relevant results`
3080
+ async rewriteQuery(question, history) {
3081
+ const prompt = `
3082
+ Given the following conversation history and a new question, rewrite the question to be a better search query for a vector database.
3083
+ Focus on extracting the core intent and entities. Do not answer the question, just rewrite it.
3084
+
3085
+ History:
3086
+ ${history.map((m) => `${m.role}: ${m.content}`).join("\n")}
3087
+
3088
+ New Question: ${question}
3089
+
3090
+ Optimized Search Query:`;
3091
+ const rewrite = await this.llmProvider.chat(
3092
+ [
3093
+ { role: "system", content: "You are an assistant that optimizes search queries for RAG systems." },
3094
+ { role: "user", content: prompt }
3095
+ ],
3096
+ ""
3166
3097
  );
3098
+ return rewrite.trim() || question;
3167
3099
  }
3168
3100
  /**
3169
- * Helper: Create text response
3101
+ * Generate 3-5 short, relevant questions based on the vector database content.
3170
3102
  */
3171
- static createTextResponse(title, content, description) {
3172
- return {
3173
- type: "text",
3174
- title,
3175
- description,
3176
- data: { content }
3177
- };
3103
+ async getSuggestions(query, namespace) {
3104
+ if (!query || query.trim().length < 3) {
3105
+ return [];
3106
+ }
3107
+ await this.initialize();
3108
+ const ns = namespace != null ? namespace : this.config.projectId;
3109
+ try {
3110
+ const { sources } = await this.retrieve(query, { namespace: ns, topK: 3 });
3111
+ if (sources.length === 0) {
3112
+ return [];
3113
+ }
3114
+ const context = sources.map((s) => s.content).join("\n\n---\n\n");
3115
+ const prompt = `
3116
+ Based on the following snippets from a document, what are 3 short, relevant questions a user might ask?
3117
+ Focus on questions that can be answered by the context.
3118
+ Keep each question under 10 words and make them very specific to the content.
3119
+ Return ONLY a JSON array of strings like ["Question 1", "Question 2", "Question 3"].
3120
+
3121
+ Context:
3122
+ ${context}
3123
+
3124
+ Suggestions:`;
3125
+ const response = await this.llmProvider.chat(
3126
+ [
3127
+ { role: "system", content: "You are a helpful assistant that generates search suggestions." },
3128
+ { role: "user", content: prompt }
3129
+ ],
3130
+ ""
3131
+ );
3132
+ const match = response.match(/\[[\s\S]*\]/);
3133
+ if (match) {
3134
+ const suggestions = JSON.parse(match[0]);
3135
+ if (Array.isArray(suggestions)) {
3136
+ return suggestions.map((s) => String(s)).slice(0, 3);
3137
+ }
3138
+ }
3139
+ } catch (error) {
3140
+ console.error("[Pipeline] Failed to generate suggestions:", error);
3141
+ }
3142
+ return [];
3178
3143
  }
3144
+ };
3145
+
3146
+ // src/core/ProviderHealthCheck.ts
3147
+ var ProviderHealthCheck = class {
3179
3148
  /**
3180
- * Helper: Check if data item is product-related
3149
+ * Validates vector database configuration before initialization.
3181
3150
  */
3182
- static isProductData(item) {
3183
- const content = (item.content || "").toLowerCase();
3184
- const productKeywords = ["product", "price", "stock", "item", "sku", "brand", "model"];
3185
- return productKeywords.some((kw) => content.includes(kw)) || Object.keys(item.metadata || {}).some(
3186
- (k) => ["name", "price", "product", "sku"].includes(k.toLowerCase())
3187
- );
3151
+ static async checkVectorProvider(config) {
3152
+ const timestamp = Date.now();
3153
+ const configErrors = await ConfigValidator.validate({
3154
+ projectId: "health-check",
3155
+ vectorDb: config,
3156
+ llm: { provider: "openai", model: "gpt-4o", apiKey: "none" },
3157
+ embedding: { provider: "openai", model: "text-embedding-3-small", apiKey: "none" }
3158
+ });
3159
+ const vectorDbErrors = configErrors.filter((e) => e.field.startsWith("vectorDb"));
3160
+ if (vectorDbErrors.length > 0) {
3161
+ return {
3162
+ healthy: false,
3163
+ provider: config.provider,
3164
+ error: `Configuration validation failed: ${vectorDbErrors.map((e) => e.message).join("; ")}`,
3165
+ timestamp
3166
+ };
3167
+ }
3168
+ try {
3169
+ const checker = await ProviderRegistry.getVectorHealthChecker(config.provider);
3170
+ if (checker) {
3171
+ return await checker.check(config);
3172
+ }
3173
+ return await this.fallbackVectorHealthCheck(config, timestamp);
3174
+ } catch (error) {
3175
+ return {
3176
+ healthy: false,
3177
+ provider: config.provider,
3178
+ error: error instanceof Error ? error.message : String(error),
3179
+ timestamp
3180
+ };
3181
+ }
3188
3182
  }
3189
- /**
3190
- * Helper: Check if data contains time series
3191
- */
3192
- static isTimeSeriesData(item) {
3193
- const content = (item.content || "").toLowerCase();
3194
- const timeKeywords = ["date", "time", "year", "month", "week", "day", "hour", "trend", "historical"];
3195
- return timeKeywords.some((kw) => content.includes(kw)) || Object.keys(item.metadata || {}).some(
3196
- (k) => ["date", "timestamp", "time", "period"].includes(k.toLowerCase())
3197
- );
3183
+ static async fallbackVectorHealthCheck(config, timestamp) {
3184
+ const opts = config.options || {};
3185
+ const baseUrl = opts.baseUrl || opts.uri;
3186
+ if (baseUrl && baseUrl.startsWith("http")) {
3187
+ try {
3188
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}/health`);
3189
+ return {
3190
+ healthy: response.ok,
3191
+ provider: config.provider,
3192
+ error: response.ok ? void 0 : `Health check failed: ${response.status}`,
3193
+ timestamp
3194
+ };
3195
+ } catch (e) {
3196
+ return { healthy: false, provider: config.provider, error: "Provider unreachable", timestamp };
3197
+ }
3198
+ }
3199
+ return {
3200
+ healthy: true,
3201
+ provider: config.provider,
3202
+ error: "Pluggable health check not implemented; basic reachability assumed.",
3203
+ timestamp
3204
+ };
3198
3205
  }
3199
3206
  /**
3200
- * Helper: Extract product information from vector match
3207
+ * Validates LLM provider configuration.
3201
3208
  */
3202
- static extractProductInfo(item) {
3203
- const meta = item.metadata || {};
3204
- if (meta.name || meta.product) {
3209
+ static async checkLLMProvider(config) {
3210
+ const timestamp = Date.now();
3211
+ try {
3212
+ const checker = LLMFactory.getHealthChecker(config.provider);
3213
+ if (checker) {
3214
+ return await checker.check(config);
3215
+ }
3205
3216
  return {
3206
- id: item.id,
3207
- name: meta.name || meta.product,
3208
- price: meta.price,
3209
- image: meta.image || meta.imageUrl,
3210
- brand: meta.brand,
3211
- description: item.content,
3212
- inStock: this.determineStockStatus(item)
3217
+ healthy: true,
3218
+ provider: config.provider,
3219
+ error: "Pluggable health check not implemented; basic reachability assumed.",
3220
+ timestamp
3213
3221
  };
3214
- }
3215
- const nameMatch = item.content.match(/(?:Product|Item|Name):\s*([^\n]+)/i);
3216
- const priceMatch = item.content.match(/(?:Price|Cost):\s*\$?([\d.]+)/i);
3217
- if (nameMatch) {
3222
+ } catch (error) {
3218
3223
  return {
3219
- id: item.id,
3220
- name: nameMatch[1],
3221
- price: priceMatch ? parseFloat(priceMatch[1]) : void 0,
3222
- description: item.content,
3223
- inStock: this.determineStockStatus(item)
3224
+ healthy: false,
3225
+ provider: config.provider,
3226
+ error: error instanceof Error ? error.message : String(error),
3227
+ timestamp
3224
3228
  };
3225
3229
  }
3226
- return null;
3227
3230
  }
3228
3231
  /**
3229
- * Helper: Detect categories in data
3232
+ * Runs comprehensive health checks on all configured providers in parallel.
3230
3233
  */
3231
- static detectCategories(data) {
3232
- const categories = /* @__PURE__ */ new Set();
3233
- data.forEach((item) => {
3234
- const meta = item.metadata || {};
3235
- if (meta.category) {
3236
- categories.add(String(meta.category));
3237
- }
3238
- if (meta.type) {
3239
- categories.add(String(meta.type));
3240
- }
3241
- if (meta.tag) {
3242
- const tags = Array.isArray(meta.tag) ? meta.tag : [meta.tag];
3243
- tags.forEach((t) => categories.add(String(t)));
3244
- }
3245
- const categoryMatch = item.content.match(/(?:Category|Type|Class):\s*([^\n]+)/i);
3246
- if (categoryMatch) {
3247
- categories.add(categoryMatch[1].trim());
3248
- }
3249
- });
3250
- return Array.from(categories);
3234
+ static async checkAll(vectorDbConfig, llmConfig, embeddingConfig) {
3235
+ const [vectorDb, llm, embedding] = await Promise.all([
3236
+ this.checkVectorProvider(vectorDbConfig),
3237
+ this.checkLLMProvider(llmConfig),
3238
+ embeddingConfig ? this.checkLLMProvider(embeddingConfig) : Promise.resolve(void 0)
3239
+ ]);
3240
+ return {
3241
+ vectorDb,
3242
+ llm,
3243
+ embedding,
3244
+ allHealthy: vectorDb.healthy && llm.healthy && (!embedding || embedding.healthy)
3245
+ };
3246
+ }
3247
+ };
3248
+
3249
+ // src/core/VectorPlugin.ts
3250
+ var VectorPlugin = class {
3251
+ constructor(hostConfig) {
3252
+ this.config = ConfigResolver.resolve(hostConfig);
3253
+ this.validationPromise = ConfigValidator.validateAndThrow(this.config);
3254
+ this.pipeline = new Pipeline(this.config);
3251
3255
  }
3252
3256
  /**
3253
- * Helper: Aggregate data by category
3257
+ * Get the current resolved configuration.
3254
3258
  */
3255
- static aggregateByCategory(data, categories) {
3256
- const result = {};
3257
- categories.forEach((cat) => {
3258
- result[cat] = 0;
3259
- });
3260
- data.forEach((item) => {
3261
- const meta = item.metadata || {};
3262
- const itemCategory = meta.category || meta.type || "Other";
3263
- if (result.hasOwnProperty(itemCategory)) {
3264
- result[itemCategory]++;
3265
- } else {
3266
- result["Other"] = (result["Other"] || 0) + 1;
3267
- }
3268
- });
3269
- return result;
3259
+ getConfig() {
3260
+ return this.config;
3270
3261
  }
3271
3262
  /**
3272
- * Helper: Extract time series data
3263
+ * Perform pre-flight health checks on all configured providers.
3264
+ * Useful to verify connectivity before running operations.
3265
+ *
3266
+ * @returns Health status for vector DB, LLM, and embedding providers
3273
3267
  */
3274
- static extractTimeSeriesData(data) {
3275
- return data.map((item) => {
3276
- const meta = item.metadata || {};
3277
- return {
3278
- timestamp: meta.timestamp || meta.date || (/* @__PURE__ */ new Date()).toISOString(),
3279
- value: meta.value || item.score || 0,
3280
- label: meta.label || item.content.substring(0, 50)
3281
- };
3282
- });
3268
+ async checkHealth() {
3269
+ return ProviderHealthCheck.checkAll(
3270
+ this.config.vectorDb,
3271
+ this.config.llm,
3272
+ this.config.embedding
3273
+ );
3283
3274
  }
3284
3275
  /**
3285
- * Helper: Extract table columns
3276
+ * Run a chat query.
3286
3277
  */
3287
- static extractTableColumns(data) {
3288
- const columnSet = /* @__PURE__ */ new Set();
3289
- columnSet.add("Content");
3290
- data.forEach((item) => {
3291
- Object.keys(item.metadata || {}).forEach((key) => {
3292
- columnSet.add(key.charAt(0).toUpperCase() + key.slice(1));
3293
- });
3294
- });
3295
- return Array.from(columnSet);
3278
+ async chat(message, history = [], namespace) {
3279
+ await this.validationPromise;
3280
+ return this.pipeline.ask(message, history, namespace);
3296
3281
  }
3297
3282
  /**
3298
- * Helper: Extract table row
3283
+ * Run a streaming chat query.
3299
3284
  */
3300
- static extractTableRow(item, columns) {
3301
- const meta = item.metadata || {};
3302
- return columns.map((col) => {
3303
- if (col === "Content") {
3304
- return item.content.substring(0, 100);
3305
- }
3306
- const metaKey = col.charAt(0).toLowerCase() + col.slice(1);
3307
- const value = meta[metaKey];
3308
- return value !== void 0 ? String(value) : "";
3285
+ chatStream(_0) {
3286
+ return __asyncGenerator(this, arguments, function* (message, history = [], namespace) {
3287
+ yield new __await(this.validationPromise);
3288
+ yield* __yieldStar(this.pipeline.askStream(message, history, namespace));
3309
3289
  });
3310
3290
  }
3311
3291
  /**
3312
- * Helper: Check stock status
3292
+ * Ingest documents into the vector database.
3313
3293
  */
3314
- static checkStockStatus(category, data) {
3315
- const item = data.find((d) => {
3316
- const meta = d.metadata || {};
3317
- return meta.category === category || meta.type === category;
3318
- });
3319
- return this.determineStockStatus(item || {});
3294
+ async ingest(documents, namespace) {
3295
+ await this.validationPromise;
3296
+ return this.pipeline.ingest(documents, namespace);
3320
3297
  }
3321
3298
  /**
3322
- * Helper: Determine if item is in stock
3299
+ * Get auto-suggestions based on a query prefix.
3323
3300
  */
3324
- static determineStockStatus(item) {
3325
- const meta = item.metadata || {};
3326
- if (meta.inStock !== void 0) {
3327
- return Boolean(meta.inStock);
3301
+ async getSuggestions(query, namespace) {
3302
+ await this.validationPromise;
3303
+ return this.pipeline.getSuggestions(query, namespace);
3304
+ }
3305
+ };
3306
+
3307
+ // src/utils/DocumentParser.ts
3308
+ var DocumentParser = class {
3309
+ /**
3310
+ * Extract text from a File or Buffer based on its type.
3311
+ */
3312
+ static async parse(file, fileName, mimeType) {
3313
+ var _a;
3314
+ const extension = (_a = fileName.split(".").pop()) == null ? void 0 : _a.toLowerCase();
3315
+ if (extension === "txt" || extension === "md" || mimeType === "text/plain" || mimeType === "text/markdown") {
3316
+ return this.readAsText(file);
3328
3317
  }
3329
- if (meta.stock !== void 0) {
3330
- return Boolean(meta.stock);
3318
+ if (extension === "json" || mimeType === "application/json") {
3319
+ const text = await this.readAsText(file);
3320
+ try {
3321
+ const obj = JSON.parse(text);
3322
+ return JSON.stringify(obj, null, 2);
3323
+ } catch (e) {
3324
+ return text;
3325
+ }
3331
3326
  }
3332
- if (meta.available !== void 0) {
3333
- return Boolean(meta.available);
3327
+ if (extension === "csv" || mimeType === "text/csv") {
3328
+ return this.readAsText(file);
3334
3329
  }
3335
- const content = (item.content || "").toLowerCase();
3336
- if (content.includes("out of stock") || content.includes("unavailable")) {
3337
- return false;
3330
+ if (extension === "pdf" || mimeType === "application/pdf") {
3331
+ try {
3332
+ const pdf = await import("pdf-parse");
3333
+ const buffer = Buffer.isBuffer(file) ? file : Buffer.from(await file.arrayBuffer());
3334
+ const data = await pdf.default(buffer);
3335
+ return data.text;
3336
+ } catch (err) {
3337
+ console.warn('[DocumentParser] PDF parsing failed. Make sure "pdf-parse" is installed.', err);
3338
+ return `[PDF Parsing Error for ${fileName}]`;
3339
+ }
3338
3340
  }
3339
- if (content.includes("in stock") || content.includes("available")) {
3340
- return true;
3341
+ if (extension === "docx" || mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
3342
+ try {
3343
+ const mammoth = await import("mammoth");
3344
+ const buffer = Buffer.isBuffer(file) ? file : Buffer.from(await file.arrayBuffer());
3345
+ const result = await mammoth.extractRawText({ buffer });
3346
+ return result.value;
3347
+ } catch (err) {
3348
+ console.warn('[DocumentParser] DOCX parsing failed. Make sure "mammoth" is installed.', err);
3349
+ return `[DOCX Parsing Error for ${fileName}]`;
3350
+ }
3351
+ }
3352
+ try {
3353
+ return await this.readAsText(file);
3354
+ } catch (e) {
3355
+ throw new Error(`[DocumentParser] Unsupported file format: ${fileName} (${mimeType})`);
3341
3356
  }
3342
- return true;
3343
3357
  }
3344
- /**
3345
- * Helper: Check if data has multiple fields
3346
- */
3347
- static hasMultipleFields(data) {
3348
- const fieldCount = /* @__PURE__ */ new Set();
3349
- data.forEach((item) => {
3350
- Object.keys(item.metadata || {}).forEach((key) => {
3351
- fieldCount.add(key);
3352
- });
3353
- });
3354
- return fieldCount.size > 2;
3358
+ static async readAsText(file) {
3359
+ if (Buffer.isBuffer(file)) {
3360
+ return file.toString("utf-8");
3361
+ }
3362
+ return await file.text();
3355
3363
  }
3356
3364
  };
3357
3365