@retrivora-ai/rag-engine 2.0.6 → 2.0.7

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.
@@ -3899,9 +3899,9 @@ ${context != null ? context : "None"}` },
3899
3899
  }
3900
3900
  const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
3901
3901
  if (isSelfHost || Boolean(process.env.VERCEL)) {
3902
- try {
3903
- const _g2 = globalThis;
3904
- if (typeof _g2.__retrivoraDispatchChat === "function") {
3902
+ const _g2 = globalThis;
3903
+ if (typeof _g2.__retrivoraDispatchChat === "function") {
3904
+ try {
3905
3905
  const res = await _g2.__retrivoraDispatchChat({
3906
3906
  model: this.model,
3907
3907
  messages: formattedMessages,
@@ -3911,8 +3911,9 @@ ${context != null ? context : "None"}` },
3911
3911
  if ((_e = (_d = (_c = (_b = res == null ? void 0 : res.response) == null ? void 0 : _b.choices) == null ? void 0 : _c[0]) == null ? void 0 : _d.message) == null ? void 0 : _e.content) {
3912
3912
  return res.response.choices[0].message.content;
3913
3913
  }
3914
+ } catch (dispatchErr) {
3915
+ throw dispatchErr;
3914
3916
  }
3915
- } catch (e) {
3916
3917
  }
3917
3918
  }
3918
3919
  const { data } = await this.http.post(path2, payload);
@@ -3964,9 +3965,9 @@ ${context != null ? context : "None"}` },
3964
3965
  const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
3965
3966
  let streamBody = null;
3966
3967
  if (isSelfHost || Boolean(process.env.VERCEL)) {
3967
- try {
3968
- const _g3 = globalThis;
3969
- if (typeof _g3.__retrivoraDispatchChat === "function") {
3968
+ const _g3 = globalThis;
3969
+ if (typeof _g3.__retrivoraDispatchChat === "function") {
3970
+ try {
3970
3971
  const res = yield new __await(_g3.__retrivoraDispatchChat({
3971
3972
  model: this.model,
3972
3973
  messages: formattedMessages,
@@ -3980,8 +3981,9 @@ ${context != null ? context : "None"}` },
3980
3981
  yield res.response.choices[0].message.content;
3981
3982
  return;
3982
3983
  }
3984
+ } catch (dispatchErr) {
3985
+ throw dispatchErr;
3983
3986
  }
3984
- } catch (e) {
3985
3987
  }
3986
3988
  }
3987
3989
  if (!streamBody) {
@@ -4052,9 +4054,9 @@ ${context != null ? context : "None"}` },
4052
4054
  }
4053
4055
  const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
4054
4056
  if (isSelfHost || Boolean(process.env.VERCEL)) {
4055
- try {
4056
- const _g2 = globalThis;
4057
- if (typeof _g2.__retrivoraDispatchEmbedding === "function") {
4057
+ const _g2 = globalThis;
4058
+ if (typeof _g2.__retrivoraDispatchEmbedding === "function") {
4059
+ try {
4058
4060
  const res = await _g2.__retrivoraDispatchEmbedding({
4059
4061
  model: this.model,
4060
4062
  input: text
@@ -4062,8 +4064,9 @@ ${context != null ? context : "None"}` },
4062
4064
  if ((_c = (_b = res == null ? void 0 : res.data) == null ? void 0 : _b[0]) == null ? void 0 : _c.embedding) {
4063
4065
  return res.data[0].embedding;
4064
4066
  }
4067
+ } catch (dispatchErr) {
4068
+ throw dispatchErr;
4065
4069
  }
4066
- } catch (e) {
4067
4070
  }
4068
4071
  }
4069
4072
  const { data } = await this.http.post(path2, payload);
@@ -4656,7 +4659,8 @@ var Reranker = class {
4656
4659
  return matches.sort((a, b) => b.score - a.score).slice(0, limit);
4657
4660
  }
4658
4661
  const scoredMatches = matches.map((match) => {
4659
- const contentLower = match.content.toLowerCase();
4662
+ var _a2;
4663
+ const contentLower = ((_a2 = match == null ? void 0 : match.content) != null ? _a2 : "").toLowerCase();
4660
4664
  let keywordScore = 0;
4661
4665
  keywords.forEach((keyword) => {
4662
4666
  if (contentLower.includes(keyword)) {
@@ -4677,7 +4681,10 @@ var Reranker = class {
4677
4681
  [{ role: "user", content: `Query: "${query}"
4678
4682
 
4679
4683
  Documents:
4680
- ${topN.map((m, i) => `[${i}] ${m.content.replace(/\n/g, " ")}`).join("\n")}` }],
4684
+ ${topN.map((m, i) => {
4685
+ var _a2;
4686
+ return `[${i}] ${((_a2 = m == null ? void 0 : m.content) != null ? _a2 : "").replace(/\n/g, " ")}`;
4687
+ }).join("\n")}` }],
4681
4688
  "",
4682
4689
  {
4683
4690
  systemPrompt: 'You are a relevance ranking expert. Given the user query and a list of retrieved document chunks, rank the chunks by relevance to the query. Return the result as a comma-separated list of document indices in order of relevance, from most relevant to least relevant. Use the indices provided in brackets like [0], [1], etc. Only return the indices (e.g., "2,0,1"), nothing else. Do not include brackets in the output.',
@@ -5842,10 +5849,10 @@ Return ONLY 'vector', 'graph', or 'both'. No explanation.`;
5842
5849
  "",
5843
5850
  { temperature: 0, maxTokens: 10 }
5844
5851
  );
5845
- const cleanResponse = response.trim().toLowerCase();
5846
- if (cleanResponse.includes("vector")) return "vector";
5847
- if (cleanResponse.includes("graph")) return "graph";
5852
+ const cleanResponse = (response != null ? response : "").trim().toLowerCase();
5848
5853
  if (cleanResponse.includes("both")) return "both";
5854
+ if (cleanResponse.includes("graph")) return "graph";
5855
+ if (cleanResponse.includes("vector")) return "vector";
5849
5856
  } catch (error) {
5850
5857
  console.warn("[QueryProcessor] LLM strategy classification failed, falling back to keywords:", error);
5851
5858
  }
@@ -6019,7 +6026,10 @@ var IntentClassifier = class {
6019
6026
  hasCategoricalFields = catKeys.size > 0;
6020
6027
  numericFieldCount = numericKeys.size;
6021
6028
  categoricalFieldCount = catKeys.size;
6022
- if (productKeyMatches >= 2 || docs.some((d) => d.content.toLowerCase().includes("price") || d.content.toLowerCase().includes("brand"))) {
6029
+ if (productKeyMatches >= 2 || docs.some((d) => {
6030
+ var _a2, _b;
6031
+ return ((_a2 = d == null ? void 0 : d.content) != null ? _a2 : "").toLowerCase().includes("price") || ((_b = d == null ? void 0 : d.content) != null ? _b : "").toLowerCase().includes("brand");
6032
+ })) {
6023
6033
  isProductLike = true;
6024
6034
  }
6025
6035
  }
@@ -6299,7 +6309,10 @@ var TextRendererStrategy = class {
6299
6309
  return { type: "text", title, data: { content: data } };
6300
6310
  }
6301
6311
  const docs = Array.isArray(data) ? data : [];
6302
- const text = docs.map((d) => d.content).join("\n\n");
6312
+ const text = docs.map((d) => {
6313
+ var _a2;
6314
+ return (_a2 = d == null ? void 0 : d.content) != null ? _a2 : "";
6315
+ }).join("\n\n");
6303
6316
  return { type: "text", title, data: { content: text || "No detailed content available." } };
6304
6317
  }
6305
6318
  };
@@ -6548,6 +6561,19 @@ var UITransformer = class _UITransformer {
6548
6561
  if (!retrievedData || retrievedData.length === 0) {
6549
6562
  return this.createTextResponse("No data available", "No relevant data found for your query.");
6550
6563
  }
6564
+ console.log("[UITransformer.transform] Processing retrievedData:", {
6565
+ userQuery,
6566
+ retrievedCount: retrievedData.length,
6567
+ sample: retrievedData.slice(0, 2).map((item) => {
6568
+ var _a3;
6569
+ return {
6570
+ id: item == null ? void 0 : item.id,
6571
+ contentType: typeof (item == null ? void 0 : item.content),
6572
+ contentSnippet: String((_a3 = item == null ? void 0 : item.content) != null ? _a3 : "").substring(0, 150),
6573
+ metadataKeys: Object.keys((item == null ? void 0 : item.metadata) || {})
6574
+ };
6575
+ })
6576
+ });
6551
6577
  const resolvedIntent = intent != null ? intent : this.detectIntentHeuristic(userQuery);
6552
6578
  const filteredData = resolvedIntent.filterInStockOnly ? retrievedData.filter((item) => this.determineStockStatus(item)) : retrievedData;
6553
6579
  const profile = this.profileData(filteredData);
@@ -7037,7 +7063,10 @@ ${schemaProfileText}` : ""}`;
7037
7063
  type: "radar_chart",
7038
7064
  title: "Product Comparison",
7039
7065
  description: `Comparing ${data.length} items across ${radarData.length} attributes`,
7040
- data: radarData.length > 0 ? radarData : data.map((d) => ({ attribute: d.content.substring(0, 40) }))
7066
+ data: radarData.length > 0 ? radarData : data.map((d) => {
7067
+ var _a2;
7068
+ return { attribute: ((_a2 = d == null ? void 0 : d.content) != null ? _a2 : "").substring(0, 40) };
7069
+ })
7041
7070
  };
7042
7071
  }
7043
7072
  static transformToTable(data, query = "") {
@@ -7054,7 +7083,10 @@ ${schemaProfileText}` : ""}`;
7054
7083
  static transformToText(data) {
7055
7084
  return this.createTextResponse(
7056
7085
  "Retrieved Context",
7057
- data.map((item) => item.content).join("\n\n"),
7086
+ data.map((item) => {
7087
+ var _a2;
7088
+ return (_a2 = item == null ? void 0 : item.content) != null ? _a2 : "";
7089
+ }).join("\n\n"),
7058
7090
  `Found ${data.length} relevant results`
7059
7091
  );
7060
7092
  }
@@ -7215,6 +7247,7 @@ ${schemaProfileText}` : ""}`;
7215
7247
  return productTerms && productAction && !nonProductEntityTerms;
7216
7248
  }
7217
7249
  static isProductData(item) {
7250
+ if (!item) return false;
7218
7251
  const content = (item.content || "").toLowerCase();
7219
7252
  const productKeywords = [
7220
7253
  "product",
@@ -7473,12 +7506,12 @@ ${schemaProfileText}` : ""}`;
7473
7506
  }
7474
7507
  static extractTimeSeriesData(data) {
7475
7508
  return data.map((item) => {
7476
- var _a2, _b, _c, _d, _e;
7509
+ var _a2, _b, _c, _d, _e, _f;
7477
7510
  const meta = item.metadata || {};
7478
7511
  return {
7479
7512
  timestamp: (_b = (_a2 = meta.timestamp) != null ? _a2 : meta.date) != null ? _b : (/* @__PURE__ */ new Date()).toISOString(),
7480
7513
  value: (_d = (_c = meta.value) != null ? _c : item.score) != null ? _d : 0,
7481
- label: (_e = meta.label) != null ? _e : item.content.substring(0, 50)
7514
+ label: (_f = meta.label) != null ? _f : ((_e = item == null ? void 0 : item.content) != null ? _e : "").substring(0, 50)
7482
7515
  };
7483
7516
  });
7484
7517
  }
@@ -7592,7 +7625,8 @@ ${schemaProfileText}` : ""}`;
7592
7625
  }, query.includes(normalizedField) ? 3 : 0);
7593
7626
  }
7594
7627
  static resolveTableCellValue(item, column) {
7595
- if (column === "Content") return item.content.substring(0, 100);
7628
+ var _a2, _b, _c;
7629
+ if (column === "Content") return ((_a2 = item == null ? void 0 : item.content) != null ? _a2 : "").substring(0, 100);
7596
7630
  const meta = item.metadata || {};
7597
7631
  const normalizedColumn = this.normalizeComparableField(column);
7598
7632
  const exactMetadata = Object.entries(meta).find(
@@ -7603,9 +7637,9 @@ ${schemaProfileText}` : ""}`;
7603
7637
  }
7604
7638
  const aliasValue = this.resolveAliasedTableCell(meta, column);
7605
7639
  if (aliasValue !== void 0) return this.toDisplayValue(aliasValue);
7606
- const contentValue = this.extractContentFieldValue(item.content, column);
7640
+ const contentValue = this.extractContentFieldValue((_b = item == null ? void 0 : item.content) != null ? _b : "", column);
7607
7641
  if (contentValue !== null) return contentValue;
7608
- const aliasContentValue = this.extractAliasedContentFieldValue(item.content, column);
7642
+ const aliasContentValue = this.extractAliasedContentFieldValue((_c = item == null ? void 0 : item.content) != null ? _c : "", column);
7609
7643
  return aliasContentValue != null ? aliasContentValue : "";
7610
7644
  }
7611
7645
  static resolveAliasedTableCell(meta, column) {
@@ -7655,6 +7689,7 @@ ${schemaProfileText}` : ""}`;
7655
7689
  return { inStockCount: inStock, outOfStockCount: outOfStock };
7656
7690
  }
7657
7691
  static determineStockStatus(item) {
7692
+ if (!item) return true;
7658
7693
  const meta = item.metadata || {};
7659
7694
  const stockValue = resolveMetadataValue(meta, "stock");
7660
7695
  if (stockValue !== void 0) {
@@ -7700,35 +7735,64 @@ ${schemaProfileText}` : ""}`;
7700
7735
  return resolveMetadataValue(meta, uiKey);
7701
7736
  }
7702
7737
  static extractProductInfo(item, config, trainedSchema) {
7703
- var _a2;
7738
+ var _a2, _b;
7739
+ if (!item) return null;
7704
7740
  const meta = item.metadata || {};
7741
+ const content = item.content || "";
7705
7742
  const name = this.getDynamicVal(meta, "name", config, trainedSchema);
7706
7743
  const price = this.getDynamicVal(meta, "price", config, trainedSchema);
7707
7744
  const brand = this.getDynamicVal(meta, "brand", config, trainedSchema);
7708
7745
  const description = this.cleanProductDescription(
7709
- (_a2 = this.extractProductDescriptionFromContent(item.content)) != null ? _a2 : this.getProductDescriptionValue(meta, config, trainedSchema)
7746
+ (_a2 = this.extractProductDescriptionFromContent(content)) != null ? _a2 : this.getProductDescriptionValue(meta, config, trainedSchema)
7710
7747
  );
7711
7748
  if (name || this.isProductData(item)) {
7712
7749
  let finalName = name ? String(name) : void 0;
7750
+ if (!finalName && content) {
7751
+ const nameMatch = content.match(/(?:Product|Item|Name):\s*([^\n]+)/i);
7752
+ finalName = nameMatch ? nameMatch[1].trim() : (_b = content.split("\n")[0]) == null ? void 0 : _b.substring(0, 60);
7753
+ }
7713
7754
  if (!finalName) {
7714
- const nameMatch = item.content.match(/(?:Product|Item|Name):\s*([^\n]+)/i);
7715
- finalName = nameMatch ? nameMatch[1].trim() : item.content.split("\n")[0].substring(0, 60);
7755
+ console.warn(
7756
+ `[UITransformer] Unable to read product name from metadata or content for item ${item.id}. Defaulting to 'Unnamed Product'.`,
7757
+ { metadataKeys: Object.keys(meta), contentLength: content.length }
7758
+ );
7716
7759
  }
7717
7760
  let finalPrice = typeof price === "number" || typeof price === "string" ? price : void 0;
7718
- if (!finalPrice) {
7719
- const priceMatch = item.content.match(/(?:Price|Cost):\s*\$?([\d,.]+)/i) || item.content.match(/\$\s*([\d,.]+)/);
7761
+ if (!finalPrice && content) {
7762
+ const priceMatch = content.match(/(?:Price|Cost):\s*\$?([\d,.]+)/i) || content.match(/\$\s*([\d,.]+)/);
7720
7763
  if (priceMatch) finalPrice = priceMatch[1].replace(/,/g, "");
7721
7764
  }
7765
+ if (finalPrice === void 0) {
7766
+ console.warn(
7767
+ `[UITransformer] Unable to read product price from metadata or content for item ${item.id}.`,
7768
+ { metadataKeys: Object.keys(meta), contentSnippet: content.substring(0, 100) }
7769
+ );
7770
+ }
7722
7771
  const imageValue = this.getDynamicVal(meta, "image", config, trainedSchema);
7772
+ if (!imageValue) {
7773
+ console.debug(
7774
+ `[UITransformer] Unable to read product image URL from metadata for item ${item.id}.`
7775
+ );
7776
+ }
7777
+ if (!description) {
7778
+ console.debug(
7779
+ `[UITransformer] Unable to read product description from metadata or content for item ${item.id}.`
7780
+ );
7781
+ }
7723
7782
  return {
7724
7783
  id: item.id,
7725
- name: finalName,
7784
+ name: finalName || "Unnamed Product",
7726
7785
  price: finalPrice,
7727
7786
  image: typeof imageValue === "string" ? imageValue : void 0,
7728
7787
  brand: brand ? String(brand) : void 0,
7729
7788
  description,
7730
7789
  inStock: this.determineStockStatus(item)
7731
7790
  };
7791
+ } else {
7792
+ console.warn(
7793
+ `[UITransformer] Item ${item.id} skipped: unable to read name or identify as product data from metadata/content.`,
7794
+ { metadataKeys: Object.keys(meta), contentSnippet: content.substring(0, 100) }
7795
+ );
7732
7796
  }
7733
7797
  return null;
7734
7798
  }
@@ -7813,13 +7877,13 @@ RULES:
7813
7877
  5. If no relevant data is found, return text: "I cannot answer this question based on the available information."`;
7814
7878
  }
7815
7879
  static buildContextSummary(sources, maxChars = 6e3) {
7816
- const items = sources.map((s, i) => {
7880
+ const items = (sources || []).filter(Boolean).map((s, i) => {
7817
7881
  var _a2, _b, _c, _d;
7818
7882
  return {
7819
7883
  index: i + 1,
7820
- content: (_b = (_a2 = s.content) == null ? void 0 : _a2.substring(0, 400)) != null ? _b : "",
7821
- metadata: (_c = s.metadata) != null ? _c : {},
7822
- score: (_d = s.score) != null ? _d : 0
7884
+ content: (_b = (_a2 = s == null ? void 0 : s.content) == null ? void 0 : _a2.substring(0, 400)) != null ? _b : "",
7885
+ metadata: (_c = s == null ? void 0 : s.metadata) != null ? _c : {},
7886
+ score: (_d = s == null ? void 0 : s.score) != null ? _d : 0
7823
7887
  };
7824
7888
  });
7825
7889
  const full = JSON.stringify(items, null, 2);
@@ -8388,17 +8452,33 @@ ${m.content}`).join("\n\n---\n\n");
8388
8452
  const hasNumericPredicates = Array.isArray(filter.__numericPredicates) && filter.__numericPredicates.length > 0;
8389
8453
  const wantsExhaustiveList = hasNumericPredicates || hasMetadataFilter || /\b(list|all|show|provide|give|get|browse|find|search|display)\b/i.test(question);
8390
8454
  const retrievalLimit = wantsExhaustiveList ? Math.max(topK * 20, 100) : topK * 2;
8391
- const rawSources = (strategyResult === "vector" || strategyResult === "both") && queryVector && queryVector.length > 0 ? yield new __await(this.vectorDB.query(queryVector, retrievalLimit, ns, filter)) : [];
8455
+ const rawSources = ((strategyResult === "vector" || strategyResult === "both") && queryVector && queryVector.length > 0 ? yield new __await(this.vectorDB.query(queryVector, retrievalLimit, ns, filter)) : []).filter((s) => Boolean(s && typeof s === "object"));
8456
+ console.log("[Pipeline] Raw vectorDB.query response:", {
8457
+ rawCount: rawSources.length,
8458
+ sample: rawSources.slice(0, 2).map((s) => {
8459
+ var _a3;
8460
+ return {
8461
+ id: s == null ? void 0 : s.id,
8462
+ score: s == null ? void 0 : s.score,
8463
+ contentType: typeof (s == null ? void 0 : s.content),
8464
+ contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
8465
+ metadataKeys: Object.keys((s == null ? void 0 : s.metadata) || {})
8466
+ };
8467
+ })
8468
+ });
8392
8469
  const retrieveEnd = performance.now();
8393
8470
  const embedMs = retrieveEnd - embedStart;
8394
8471
  const retrieveMs = retrieveEnd - embedStart;
8395
8472
  const rerankStart = performance.now();
8396
- const structuredSources = this.applyStructuredFilters(rawSources, filter);
8397
- let fullSources = hasNumericPredicates ? structuredSources : structuredSources.filter((m) => m.score >= scoreThreshold);
8473
+ const structuredSources = this.applyStructuredFilters(rawSources, filter).filter((s) => Boolean(s && typeof s === "object"));
8474
+ let fullSources = hasNumericPredicates ? structuredSources : structuredSources.filter((m) => {
8475
+ var _a3;
8476
+ return ((_a3 = m == null ? void 0 : m.score) != null ? _a3 : 0) >= scoreThreshold;
8477
+ });
8398
8478
  const rerankLimit = wantsExhaustiveList ? retrievalLimit : topK;
8399
8479
  const useReranking = arch !== "naive" && (arch === "retrieve-and-rerank" || ((_m = this.config.rag) == null ? void 0 : _m.useReranking));
8400
8480
  if (!hasNumericPredicates && useReranking) {
8401
- fullSources = yield new __await(this.reranker.rerank(fullSources, question, rerankLimit));
8481
+ fullSources = (yield new __await(this.reranker.rerank(fullSources, question, rerankLimit))).filter((s) => Boolean(s && typeof s === "object"));
8402
8482
  } else if (!wantsExhaustiveList) {
8403
8483
  fullSources = fullSources.slice(0, topK);
8404
8484
  }
@@ -8413,13 +8493,33 @@ ${(_a3 = m == null ? void 0 : m.content) != null ? _a3 : ""}`;
8413
8493
  displayCount = fullSources.length;
8414
8494
  } else {
8415
8495
  const baseThreshold = Math.max(scoreThreshold, 0.4);
8416
- const highlyRelevant = fullSources.filter((m) => m.score >= baseThreshold);
8496
+ const highlyRelevant = fullSources.filter((m) => {
8497
+ var _a3;
8498
+ return ((_a3 = m == null ? void 0 : m.score) != null ? _a3 : 0) >= baseThreshold;
8499
+ });
8417
8500
  displayCount = Math.max(highlyRelevant.length, topK);
8418
8501
  if (displayCount > 15) {
8419
8502
  displayCount = 15;
8420
8503
  }
8421
8504
  }
8422
- const sources = [...fullSources].sort((a, b) => b.score - a.score).slice(0, displayCount);
8505
+ const sources = [...fullSources].filter((s) => Boolean(s && typeof s === "object")).sort((a, b) => {
8506
+ var _a3, _b2;
8507
+ return ((_a3 = b == null ? void 0 : b.score) != null ? _a3 : 0) - ((_b2 = a == null ? void 0 : a.score) != null ? _b2 : 0);
8508
+ }).slice(0, displayCount);
8509
+ console.log("[Pipeline] Final sources for prompt & UI:", {
8510
+ count: sources.length,
8511
+ sources: sources.map((s, idx) => {
8512
+ var _a3;
8513
+ return {
8514
+ rank: idx + 1,
8515
+ id: s == null ? void 0 : s.id,
8516
+ score: s == null ? void 0 : s.score,
8517
+ contentType: typeof (s == null ? void 0 : s.content),
8518
+ contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
8519
+ metadata: s == null ? void 0 : s.metadata
8520
+ };
8521
+ })
8522
+ });
8423
8523
  if (graphData && graphData.nodes.length > 0) {
8424
8524
  const graphContext = graphData.nodes.map(
8425
8525
  (n) => `Entity: ${n.label} (${n.id})${n.properties ? " - " + JSON.stringify(n.properties) : ""}`
@@ -8445,18 +8545,18 @@ ${context}`;
8445
8545
  }
8446
8546
  yield {
8447
8547
  reply: "",
8448
- sources: sources.map((s) => {
8449
- var _a3;
8548
+ sources: (sources || []).filter((s) => Boolean(s && typeof s === "object")).map((s) => {
8549
+ var _a3, _b2, _c2;
8450
8550
  return {
8451
8551
  id: s.id,
8452
- score: s.score,
8453
- content: s.content,
8454
- metadata: (_a3 = s.metadata) != null ? _a3 : {},
8552
+ score: (_a3 = s.score) != null ? _a3 : 0,
8553
+ content: (_b2 = s == null ? void 0 : s.content) != null ? _b2 : "",
8554
+ metadata: (_c2 = s == null ? void 0 : s.metadata) != null ? _c2 : {},
8455
8555
  namespace: ns
8456
8556
  };
8457
8557
  })
8458
8558
  };
8459
- const allMetadataKeys = Array.from(new Set(sources.flatMap((s) => Object.keys(s.metadata || {}))));
8559
+ const allMetadataKeys = Array.from(new Set(sources.filter(Boolean).flatMap((s) => Object.keys((s == null ? void 0 : s.metadata) || {}))));
8460
8560
  const cachedSchema = allMetadataKeys.length > 0 ? SchemaMapper.getCached(ns, allMetadataKeys) : void 0;
8461
8561
  if (allMetadataKeys.length > 0 && !cachedSchema) {
8462
8562
  SchemaMapper.train(this.llmProvider, ns, allMetadataKeys).catch(() => {
@@ -8748,6 +8848,8 @@ ${context}`;
8748
8848
  });
8749
8849
  }
8750
8850
  resolveNumericPredicateValue(source, predicate) {
8851
+ var _a2;
8852
+ if (!source) return null;
8751
8853
  const meta = source.metadata || {};
8752
8854
  const field = predicate.field;
8753
8855
  const entries = Object.entries(meta).filter(([, value]) => value !== null && value !== void 0 && typeof value !== "object");
@@ -8759,7 +8861,7 @@ ${context}`;
8759
8861
  const value = this.toFiniteNumber(Array.isArray(fuzzy) ? fuzzy[1] : fuzzy.value);
8760
8862
  if (value !== null) return value;
8761
8863
  }
8762
- const contentValue = this.extractNumericValueFromContent(source.content, field);
8864
+ const contentValue = this.extractNumericValueFromContent((_a2 = source.content) != null ? _a2 : "", field);
8763
8865
  if (contentValue !== null) return contentValue;
8764
8866
  }
8765
8867
  for (const [key, value] of entries) {
@@ -8770,6 +8872,7 @@ ${context}`;
8770
8872
  return null;
8771
8873
  }
8772
8874
  extractNumericValueFromContent(content, field) {
8875
+ if (!content || typeof content !== "string") return null;
8773
8876
  const escapedWords = field.split(/\s+|_+|-+/).filter(Boolean).map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
8774
8877
  if (escapedWords.length === 0) return null;
8775
8878
  const pattern = new RegExp(`(?:${escapedWords.join("[\\\\s_:-]*")})\\s*[:\\-\u2013]?\\s*([\\d,]+(?:\\.\\d+)?)`, "i");
@@ -8855,6 +8958,20 @@ ${context}`;
8855
8958
  resolvedSources.push(source);
8856
8959
  }
8857
8960
  }
8961
+ console.log("[Pipeline] retrieve() response:", {
8962
+ query,
8963
+ namespace: ns,
8964
+ count: resolvedSources.length,
8965
+ sample: resolvedSources.slice(0, 2).map((s) => {
8966
+ var _a3;
8967
+ return {
8968
+ id: s == null ? void 0 : s.id,
8969
+ score: s == null ? void 0 : s.score,
8970
+ contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
8971
+ metadata: s == null ? void 0 : s.metadata
8972
+ };
8973
+ })
8974
+ });
8858
8975
  return { sources: resolvedSources, graphData };
8859
8976
  }
8860
8977
  /** Rewrite the user query for better retrieval performance. */