@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.
@@ -3934,9 +3934,9 @@ ${context != null ? context : "None"}` },
3934
3934
  }
3935
3935
  const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
3936
3936
  if (isSelfHost || Boolean(process.env.VERCEL)) {
3937
- try {
3938
- const _g2 = globalThis;
3939
- if (typeof _g2.__retrivoraDispatchChat === "function") {
3937
+ const _g2 = globalThis;
3938
+ if (typeof _g2.__retrivoraDispatchChat === "function") {
3939
+ try {
3940
3940
  const res = await _g2.__retrivoraDispatchChat({
3941
3941
  model: this.model,
3942
3942
  messages: formattedMessages,
@@ -3946,8 +3946,9 @@ ${context != null ? context : "None"}` },
3946
3946
  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) {
3947
3947
  return res.response.choices[0].message.content;
3948
3948
  }
3949
+ } catch (dispatchErr) {
3950
+ throw dispatchErr;
3949
3951
  }
3950
- } catch (e) {
3951
3952
  }
3952
3953
  }
3953
3954
  const { data } = await this.http.post(path2, payload);
@@ -3999,9 +4000,9 @@ ${context != null ? context : "None"}` },
3999
4000
  const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
4000
4001
  let streamBody = null;
4001
4002
  if (isSelfHost || Boolean(process.env.VERCEL)) {
4002
- try {
4003
- const _g3 = globalThis;
4004
- if (typeof _g3.__retrivoraDispatchChat === "function") {
4003
+ const _g3 = globalThis;
4004
+ if (typeof _g3.__retrivoraDispatchChat === "function") {
4005
+ try {
4005
4006
  const res = yield new __await(_g3.__retrivoraDispatchChat({
4006
4007
  model: this.model,
4007
4008
  messages: formattedMessages,
@@ -4015,8 +4016,9 @@ ${context != null ? context : "None"}` },
4015
4016
  yield res.response.choices[0].message.content;
4016
4017
  return;
4017
4018
  }
4019
+ } catch (dispatchErr) {
4020
+ throw dispatchErr;
4018
4021
  }
4019
- } catch (e) {
4020
4022
  }
4021
4023
  }
4022
4024
  if (!streamBody) {
@@ -4087,9 +4089,9 @@ ${context != null ? context : "None"}` },
4087
4089
  }
4088
4090
  const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
4089
4091
  if (isSelfHost || Boolean(process.env.VERCEL)) {
4090
- try {
4091
- const _g2 = globalThis;
4092
- if (typeof _g2.__retrivoraDispatchEmbedding === "function") {
4092
+ const _g2 = globalThis;
4093
+ if (typeof _g2.__retrivoraDispatchEmbedding === "function") {
4094
+ try {
4093
4095
  const res = await _g2.__retrivoraDispatchEmbedding({
4094
4096
  model: this.model,
4095
4097
  input: text
@@ -4097,8 +4099,9 @@ ${context != null ? context : "None"}` },
4097
4099
  if ((_c = (_b = res == null ? void 0 : res.data) == null ? void 0 : _b[0]) == null ? void 0 : _c.embedding) {
4098
4100
  return res.data[0].embedding;
4099
4101
  }
4102
+ } catch (dispatchErr) {
4103
+ throw dispatchErr;
4100
4104
  }
4101
- } catch (e) {
4102
4105
  }
4103
4106
  }
4104
4107
  const { data } = await this.http.post(path2, payload);
@@ -4691,7 +4694,8 @@ var Reranker = class {
4691
4694
  return matches.sort((a, b) => b.score - a.score).slice(0, limit);
4692
4695
  }
4693
4696
  const scoredMatches = matches.map((match) => {
4694
- const contentLower = match.content.toLowerCase();
4697
+ var _a2;
4698
+ const contentLower = ((_a2 = match == null ? void 0 : match.content) != null ? _a2 : "").toLowerCase();
4695
4699
  let keywordScore = 0;
4696
4700
  keywords.forEach((keyword) => {
4697
4701
  if (contentLower.includes(keyword)) {
@@ -4712,7 +4716,10 @@ var Reranker = class {
4712
4716
  [{ role: "user", content: `Query: "${query}"
4713
4717
 
4714
4718
  Documents:
4715
- ${topN.map((m, i) => `[${i}] ${m.content.replace(/\n/g, " ")}`).join("\n")}` }],
4719
+ ${topN.map((m, i) => {
4720
+ var _a2;
4721
+ return `[${i}] ${((_a2 = m == null ? void 0 : m.content) != null ? _a2 : "").replace(/\n/g, " ")}`;
4722
+ }).join("\n")}` }],
4716
4723
  "",
4717
4724
  {
4718
4725
  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.',
@@ -5877,10 +5884,10 @@ Return ONLY 'vector', 'graph', or 'both'. No explanation.`;
5877
5884
  "",
5878
5885
  { temperature: 0, maxTokens: 10 }
5879
5886
  );
5880
- const cleanResponse = response.trim().toLowerCase();
5881
- if (cleanResponse.includes("vector")) return "vector";
5882
- if (cleanResponse.includes("graph")) return "graph";
5887
+ const cleanResponse = (response != null ? response : "").trim().toLowerCase();
5883
5888
  if (cleanResponse.includes("both")) return "both";
5889
+ if (cleanResponse.includes("graph")) return "graph";
5890
+ if (cleanResponse.includes("vector")) return "vector";
5884
5891
  } catch (error) {
5885
5892
  console.warn("[QueryProcessor] LLM strategy classification failed, falling back to keywords:", error);
5886
5893
  }
@@ -6054,7 +6061,10 @@ var IntentClassifier = class {
6054
6061
  hasCategoricalFields = catKeys.size > 0;
6055
6062
  numericFieldCount = numericKeys.size;
6056
6063
  categoricalFieldCount = catKeys.size;
6057
- if (productKeyMatches >= 2 || docs.some((d) => d.content.toLowerCase().includes("price") || d.content.toLowerCase().includes("brand"))) {
6064
+ if (productKeyMatches >= 2 || docs.some((d) => {
6065
+ var _a2, _b;
6066
+ 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");
6067
+ })) {
6058
6068
  isProductLike = true;
6059
6069
  }
6060
6070
  }
@@ -6334,7 +6344,10 @@ var TextRendererStrategy = class {
6334
6344
  return { type: "text", title, data: { content: data } };
6335
6345
  }
6336
6346
  const docs = Array.isArray(data) ? data : [];
6337
- const text = docs.map((d) => d.content).join("\n\n");
6347
+ const text = docs.map((d) => {
6348
+ var _a2;
6349
+ return (_a2 = d == null ? void 0 : d.content) != null ? _a2 : "";
6350
+ }).join("\n\n");
6338
6351
  return { type: "text", title, data: { content: text || "No detailed content available." } };
6339
6352
  }
6340
6353
  };
@@ -6583,6 +6596,19 @@ var UITransformer = class _UITransformer {
6583
6596
  if (!retrievedData || retrievedData.length === 0) {
6584
6597
  return this.createTextResponse("No data available", "No relevant data found for your query.");
6585
6598
  }
6599
+ console.log("[UITransformer.transform] Processing retrievedData:", {
6600
+ userQuery,
6601
+ retrievedCount: retrievedData.length,
6602
+ sample: retrievedData.slice(0, 2).map((item) => {
6603
+ var _a3;
6604
+ return {
6605
+ id: item == null ? void 0 : item.id,
6606
+ contentType: typeof (item == null ? void 0 : item.content),
6607
+ contentSnippet: String((_a3 = item == null ? void 0 : item.content) != null ? _a3 : "").substring(0, 150),
6608
+ metadataKeys: Object.keys((item == null ? void 0 : item.metadata) || {})
6609
+ };
6610
+ })
6611
+ });
6586
6612
  const resolvedIntent = intent != null ? intent : this.detectIntentHeuristic(userQuery);
6587
6613
  const filteredData = resolvedIntent.filterInStockOnly ? retrievedData.filter((item) => this.determineStockStatus(item)) : retrievedData;
6588
6614
  const profile = this.profileData(filteredData);
@@ -7072,7 +7098,10 @@ ${schemaProfileText}` : ""}`;
7072
7098
  type: "radar_chart",
7073
7099
  title: "Product Comparison",
7074
7100
  description: `Comparing ${data.length} items across ${radarData.length} attributes`,
7075
- data: radarData.length > 0 ? radarData : data.map((d) => ({ attribute: d.content.substring(0, 40) }))
7101
+ data: radarData.length > 0 ? radarData : data.map((d) => {
7102
+ var _a2;
7103
+ return { attribute: ((_a2 = d == null ? void 0 : d.content) != null ? _a2 : "").substring(0, 40) };
7104
+ })
7076
7105
  };
7077
7106
  }
7078
7107
  static transformToTable(data, query = "") {
@@ -7089,7 +7118,10 @@ ${schemaProfileText}` : ""}`;
7089
7118
  static transformToText(data) {
7090
7119
  return this.createTextResponse(
7091
7120
  "Retrieved Context",
7092
- data.map((item) => item.content).join("\n\n"),
7121
+ data.map((item) => {
7122
+ var _a2;
7123
+ return (_a2 = item == null ? void 0 : item.content) != null ? _a2 : "";
7124
+ }).join("\n\n"),
7093
7125
  `Found ${data.length} relevant results`
7094
7126
  );
7095
7127
  }
@@ -7250,6 +7282,7 @@ ${schemaProfileText}` : ""}`;
7250
7282
  return productTerms && productAction && !nonProductEntityTerms;
7251
7283
  }
7252
7284
  static isProductData(item) {
7285
+ if (!item) return false;
7253
7286
  const content = (item.content || "").toLowerCase();
7254
7287
  const productKeywords = [
7255
7288
  "product",
@@ -7508,12 +7541,12 @@ ${schemaProfileText}` : ""}`;
7508
7541
  }
7509
7542
  static extractTimeSeriesData(data) {
7510
7543
  return data.map((item) => {
7511
- var _a2, _b, _c, _d, _e;
7544
+ var _a2, _b, _c, _d, _e, _f;
7512
7545
  const meta = item.metadata || {};
7513
7546
  return {
7514
7547
  timestamp: (_b = (_a2 = meta.timestamp) != null ? _a2 : meta.date) != null ? _b : (/* @__PURE__ */ new Date()).toISOString(),
7515
7548
  value: (_d = (_c = meta.value) != null ? _c : item.score) != null ? _d : 0,
7516
- label: (_e = meta.label) != null ? _e : item.content.substring(0, 50)
7549
+ label: (_f = meta.label) != null ? _f : ((_e = item == null ? void 0 : item.content) != null ? _e : "").substring(0, 50)
7517
7550
  };
7518
7551
  });
7519
7552
  }
@@ -7627,7 +7660,8 @@ ${schemaProfileText}` : ""}`;
7627
7660
  }, query.includes(normalizedField) ? 3 : 0);
7628
7661
  }
7629
7662
  static resolveTableCellValue(item, column) {
7630
- if (column === "Content") return item.content.substring(0, 100);
7663
+ var _a2, _b, _c;
7664
+ if (column === "Content") return ((_a2 = item == null ? void 0 : item.content) != null ? _a2 : "").substring(0, 100);
7631
7665
  const meta = item.metadata || {};
7632
7666
  const normalizedColumn = this.normalizeComparableField(column);
7633
7667
  const exactMetadata = Object.entries(meta).find(
@@ -7638,9 +7672,9 @@ ${schemaProfileText}` : ""}`;
7638
7672
  }
7639
7673
  const aliasValue = this.resolveAliasedTableCell(meta, column);
7640
7674
  if (aliasValue !== void 0) return this.toDisplayValue(aliasValue);
7641
- const contentValue = this.extractContentFieldValue(item.content, column);
7675
+ const contentValue = this.extractContentFieldValue((_b = item == null ? void 0 : item.content) != null ? _b : "", column);
7642
7676
  if (contentValue !== null) return contentValue;
7643
- const aliasContentValue = this.extractAliasedContentFieldValue(item.content, column);
7677
+ const aliasContentValue = this.extractAliasedContentFieldValue((_c = item == null ? void 0 : item.content) != null ? _c : "", column);
7644
7678
  return aliasContentValue != null ? aliasContentValue : "";
7645
7679
  }
7646
7680
  static resolveAliasedTableCell(meta, column) {
@@ -7690,6 +7724,7 @@ ${schemaProfileText}` : ""}`;
7690
7724
  return { inStockCount: inStock, outOfStockCount: outOfStock };
7691
7725
  }
7692
7726
  static determineStockStatus(item) {
7727
+ if (!item) return true;
7693
7728
  const meta = item.metadata || {};
7694
7729
  const stockValue = resolveMetadataValue(meta, "stock");
7695
7730
  if (stockValue !== void 0) {
@@ -7735,35 +7770,64 @@ ${schemaProfileText}` : ""}`;
7735
7770
  return resolveMetadataValue(meta, uiKey);
7736
7771
  }
7737
7772
  static extractProductInfo(item, config, trainedSchema) {
7738
- var _a2;
7773
+ var _a2, _b;
7774
+ if (!item) return null;
7739
7775
  const meta = item.metadata || {};
7776
+ const content = item.content || "";
7740
7777
  const name = this.getDynamicVal(meta, "name", config, trainedSchema);
7741
7778
  const price = this.getDynamicVal(meta, "price", config, trainedSchema);
7742
7779
  const brand = this.getDynamicVal(meta, "brand", config, trainedSchema);
7743
7780
  const description = this.cleanProductDescription(
7744
- (_a2 = this.extractProductDescriptionFromContent(item.content)) != null ? _a2 : this.getProductDescriptionValue(meta, config, trainedSchema)
7781
+ (_a2 = this.extractProductDescriptionFromContent(content)) != null ? _a2 : this.getProductDescriptionValue(meta, config, trainedSchema)
7745
7782
  );
7746
7783
  if (name || this.isProductData(item)) {
7747
7784
  let finalName = name ? String(name) : void 0;
7785
+ if (!finalName && content) {
7786
+ const nameMatch = content.match(/(?:Product|Item|Name):\s*([^\n]+)/i);
7787
+ finalName = nameMatch ? nameMatch[1].trim() : (_b = content.split("\n")[0]) == null ? void 0 : _b.substring(0, 60);
7788
+ }
7748
7789
  if (!finalName) {
7749
- const nameMatch = item.content.match(/(?:Product|Item|Name):\s*([^\n]+)/i);
7750
- finalName = nameMatch ? nameMatch[1].trim() : item.content.split("\n")[0].substring(0, 60);
7790
+ console.warn(
7791
+ `[UITransformer] Unable to read product name from metadata or content for item ${item.id}. Defaulting to 'Unnamed Product'.`,
7792
+ { metadataKeys: Object.keys(meta), contentLength: content.length }
7793
+ );
7751
7794
  }
7752
7795
  let finalPrice = typeof price === "number" || typeof price === "string" ? price : void 0;
7753
- if (!finalPrice) {
7754
- const priceMatch = item.content.match(/(?:Price|Cost):\s*\$?([\d,.]+)/i) || item.content.match(/\$\s*([\d,.]+)/);
7796
+ if (!finalPrice && content) {
7797
+ const priceMatch = content.match(/(?:Price|Cost):\s*\$?([\d,.]+)/i) || content.match(/\$\s*([\d,.]+)/);
7755
7798
  if (priceMatch) finalPrice = priceMatch[1].replace(/,/g, "");
7756
7799
  }
7800
+ if (finalPrice === void 0) {
7801
+ console.warn(
7802
+ `[UITransformer] Unable to read product price from metadata or content for item ${item.id}.`,
7803
+ { metadataKeys: Object.keys(meta), contentSnippet: content.substring(0, 100) }
7804
+ );
7805
+ }
7757
7806
  const imageValue = this.getDynamicVal(meta, "image", config, trainedSchema);
7807
+ if (!imageValue) {
7808
+ console.debug(
7809
+ `[UITransformer] Unable to read product image URL from metadata for item ${item.id}.`
7810
+ );
7811
+ }
7812
+ if (!description) {
7813
+ console.debug(
7814
+ `[UITransformer] Unable to read product description from metadata or content for item ${item.id}.`
7815
+ );
7816
+ }
7758
7817
  return {
7759
7818
  id: item.id,
7760
- name: finalName,
7819
+ name: finalName || "Unnamed Product",
7761
7820
  price: finalPrice,
7762
7821
  image: typeof imageValue === "string" ? imageValue : void 0,
7763
7822
  brand: brand ? String(brand) : void 0,
7764
7823
  description,
7765
7824
  inStock: this.determineStockStatus(item)
7766
7825
  };
7826
+ } else {
7827
+ console.warn(
7828
+ `[UITransformer] Item ${item.id} skipped: unable to read name or identify as product data from metadata/content.`,
7829
+ { metadataKeys: Object.keys(meta), contentSnippet: content.substring(0, 100) }
7830
+ );
7767
7831
  }
7768
7832
  return null;
7769
7833
  }
@@ -7848,13 +7912,13 @@ RULES:
7848
7912
  5. If no relevant data is found, return text: "I cannot answer this question based on the available information."`;
7849
7913
  }
7850
7914
  static buildContextSummary(sources, maxChars = 6e3) {
7851
- const items = sources.map((s, i) => {
7915
+ const items = (sources || []).filter(Boolean).map((s, i) => {
7852
7916
  var _a2, _b, _c, _d;
7853
7917
  return {
7854
7918
  index: i + 1,
7855
- content: (_b = (_a2 = s.content) == null ? void 0 : _a2.substring(0, 400)) != null ? _b : "",
7856
- metadata: (_c = s.metadata) != null ? _c : {},
7857
- score: (_d = s.score) != null ? _d : 0
7919
+ content: (_b = (_a2 = s == null ? void 0 : s.content) == null ? void 0 : _a2.substring(0, 400)) != null ? _b : "",
7920
+ metadata: (_c = s == null ? void 0 : s.metadata) != null ? _c : {},
7921
+ score: (_d = s == null ? void 0 : s.score) != null ? _d : 0
7858
7922
  };
7859
7923
  });
7860
7924
  const full = JSON.stringify(items, null, 2);
@@ -8423,17 +8487,33 @@ ${m.content}`).join("\n\n---\n\n");
8423
8487
  const hasNumericPredicates = Array.isArray(filter.__numericPredicates) && filter.__numericPredicates.length > 0;
8424
8488
  const wantsExhaustiveList = hasNumericPredicates || hasMetadataFilter || /\b(list|all|show|provide|give|get|browse|find|search|display)\b/i.test(question);
8425
8489
  const retrievalLimit = wantsExhaustiveList ? Math.max(topK * 20, 100) : topK * 2;
8426
- const rawSources = (strategyResult === "vector" || strategyResult === "both") && queryVector && queryVector.length > 0 ? yield new __await(this.vectorDB.query(queryVector, retrievalLimit, ns, filter)) : [];
8490
+ 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"));
8491
+ console.log("[Pipeline] Raw vectorDB.query response:", {
8492
+ rawCount: rawSources.length,
8493
+ sample: rawSources.slice(0, 2).map((s) => {
8494
+ var _a3;
8495
+ return {
8496
+ id: s == null ? void 0 : s.id,
8497
+ score: s == null ? void 0 : s.score,
8498
+ contentType: typeof (s == null ? void 0 : s.content),
8499
+ contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
8500
+ metadataKeys: Object.keys((s == null ? void 0 : s.metadata) || {})
8501
+ };
8502
+ })
8503
+ });
8427
8504
  const retrieveEnd = performance.now();
8428
8505
  const embedMs = retrieveEnd - embedStart;
8429
8506
  const retrieveMs = retrieveEnd - embedStart;
8430
8507
  const rerankStart = performance.now();
8431
- const structuredSources = this.applyStructuredFilters(rawSources, filter);
8432
- let fullSources = hasNumericPredicates ? structuredSources : structuredSources.filter((m) => m.score >= scoreThreshold);
8508
+ const structuredSources = this.applyStructuredFilters(rawSources, filter).filter((s) => Boolean(s && typeof s === "object"));
8509
+ let fullSources = hasNumericPredicates ? structuredSources : structuredSources.filter((m) => {
8510
+ var _a3;
8511
+ return ((_a3 = m == null ? void 0 : m.score) != null ? _a3 : 0) >= scoreThreshold;
8512
+ });
8433
8513
  const rerankLimit = wantsExhaustiveList ? retrievalLimit : topK;
8434
8514
  const useReranking = arch !== "naive" && (arch === "retrieve-and-rerank" || ((_m = this.config.rag) == null ? void 0 : _m.useReranking));
8435
8515
  if (!hasNumericPredicates && useReranking) {
8436
- fullSources = yield new __await(this.reranker.rerank(fullSources, question, rerankLimit));
8516
+ fullSources = (yield new __await(this.reranker.rerank(fullSources, question, rerankLimit))).filter((s) => Boolean(s && typeof s === "object"));
8437
8517
  } else if (!wantsExhaustiveList) {
8438
8518
  fullSources = fullSources.slice(0, topK);
8439
8519
  }
@@ -8448,13 +8528,33 @@ ${(_a3 = m == null ? void 0 : m.content) != null ? _a3 : ""}`;
8448
8528
  displayCount = fullSources.length;
8449
8529
  } else {
8450
8530
  const baseThreshold = Math.max(scoreThreshold, 0.4);
8451
- const highlyRelevant = fullSources.filter((m) => m.score >= baseThreshold);
8531
+ const highlyRelevant = fullSources.filter((m) => {
8532
+ var _a3;
8533
+ return ((_a3 = m == null ? void 0 : m.score) != null ? _a3 : 0) >= baseThreshold;
8534
+ });
8452
8535
  displayCount = Math.max(highlyRelevant.length, topK);
8453
8536
  if (displayCount > 15) {
8454
8537
  displayCount = 15;
8455
8538
  }
8456
8539
  }
8457
- const sources = [...fullSources].sort((a, b) => b.score - a.score).slice(0, displayCount);
8540
+ const sources = [...fullSources].filter((s) => Boolean(s && typeof s === "object")).sort((a, b) => {
8541
+ var _a3, _b2;
8542
+ return ((_a3 = b == null ? void 0 : b.score) != null ? _a3 : 0) - ((_b2 = a == null ? void 0 : a.score) != null ? _b2 : 0);
8543
+ }).slice(0, displayCount);
8544
+ console.log("[Pipeline] Final sources for prompt & UI:", {
8545
+ count: sources.length,
8546
+ sources: sources.map((s, idx) => {
8547
+ var _a3;
8548
+ return {
8549
+ rank: idx + 1,
8550
+ id: s == null ? void 0 : s.id,
8551
+ score: s == null ? void 0 : s.score,
8552
+ contentType: typeof (s == null ? void 0 : s.content),
8553
+ contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
8554
+ metadata: s == null ? void 0 : s.metadata
8555
+ };
8556
+ })
8557
+ });
8458
8558
  if (graphData && graphData.nodes.length > 0) {
8459
8559
  const graphContext = graphData.nodes.map(
8460
8560
  (n) => `Entity: ${n.label} (${n.id})${n.properties ? " - " + JSON.stringify(n.properties) : ""}`
@@ -8480,18 +8580,18 @@ ${context}`;
8480
8580
  }
8481
8581
  yield {
8482
8582
  reply: "",
8483
- sources: sources.map((s) => {
8484
- var _a3;
8583
+ sources: (sources || []).filter((s) => Boolean(s && typeof s === "object")).map((s) => {
8584
+ var _a3, _b2, _c2;
8485
8585
  return {
8486
8586
  id: s.id,
8487
- score: s.score,
8488
- content: s.content,
8489
- metadata: (_a3 = s.metadata) != null ? _a3 : {},
8587
+ score: (_a3 = s.score) != null ? _a3 : 0,
8588
+ content: (_b2 = s == null ? void 0 : s.content) != null ? _b2 : "",
8589
+ metadata: (_c2 = s == null ? void 0 : s.metadata) != null ? _c2 : {},
8490
8590
  namespace: ns
8491
8591
  };
8492
8592
  })
8493
8593
  };
8494
- const allMetadataKeys = Array.from(new Set(sources.flatMap((s) => Object.keys(s.metadata || {}))));
8594
+ const allMetadataKeys = Array.from(new Set(sources.filter(Boolean).flatMap((s) => Object.keys((s == null ? void 0 : s.metadata) || {}))));
8495
8595
  const cachedSchema = allMetadataKeys.length > 0 ? SchemaMapper.getCached(ns, allMetadataKeys) : void 0;
8496
8596
  if (allMetadataKeys.length > 0 && !cachedSchema) {
8497
8597
  SchemaMapper.train(this.llmProvider, ns, allMetadataKeys).catch(() => {
@@ -8783,6 +8883,8 @@ ${context}`;
8783
8883
  });
8784
8884
  }
8785
8885
  resolveNumericPredicateValue(source, predicate) {
8886
+ var _a2;
8887
+ if (!source) return null;
8786
8888
  const meta = source.metadata || {};
8787
8889
  const field = predicate.field;
8788
8890
  const entries = Object.entries(meta).filter(([, value]) => value !== null && value !== void 0 && typeof value !== "object");
@@ -8794,7 +8896,7 @@ ${context}`;
8794
8896
  const value = this.toFiniteNumber(Array.isArray(fuzzy) ? fuzzy[1] : fuzzy.value);
8795
8897
  if (value !== null) return value;
8796
8898
  }
8797
- const contentValue = this.extractNumericValueFromContent(source.content, field);
8899
+ const contentValue = this.extractNumericValueFromContent((_a2 = source.content) != null ? _a2 : "", field);
8798
8900
  if (contentValue !== null) return contentValue;
8799
8901
  }
8800
8902
  for (const [key, value] of entries) {
@@ -8805,6 +8907,7 @@ ${context}`;
8805
8907
  return null;
8806
8908
  }
8807
8909
  extractNumericValueFromContent(content, field) {
8910
+ if (!content || typeof content !== "string") return null;
8808
8911
  const escapedWords = field.split(/\s+|_+|-+/).filter(Boolean).map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
8809
8912
  if (escapedWords.length === 0) return null;
8810
8913
  const pattern = new RegExp(`(?:${escapedWords.join("[\\\\s_:-]*")})\\s*[:\\-\u2013]?\\s*([\\d,]+(?:\\.\\d+)?)`, "i");
@@ -8890,6 +8993,20 @@ ${context}`;
8890
8993
  resolvedSources.push(source);
8891
8994
  }
8892
8995
  }
8996
+ console.log("[Pipeline] retrieve() response:", {
8997
+ query,
8998
+ namespace: ns,
8999
+ count: resolvedSources.length,
9000
+ sample: resolvedSources.slice(0, 2).map((s) => {
9001
+ var _a3;
9002
+ return {
9003
+ id: s == null ? void 0 : s.id,
9004
+ score: s == null ? void 0 : s.score,
9005
+ contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
9006
+ metadata: s == null ? void 0 : s.metadata
9007
+ };
9008
+ })
9009
+ });
8893
9010
  return { sources: resolvedSources, graphData };
8894
9011
  }
8895
9012
  /** Rewrite the user query for better retrieval performance. */