@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.
package/dist/server.js CHANGED
@@ -4034,9 +4034,9 @@ ${context != null ? context : "None"}` },
4034
4034
  }
4035
4035
  const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
4036
4036
  if (isSelfHost || Boolean(process.env.VERCEL)) {
4037
- try {
4038
- const _g2 = globalThis;
4039
- if (typeof _g2.__retrivoraDispatchChat === "function") {
4037
+ const _g2 = globalThis;
4038
+ if (typeof _g2.__retrivoraDispatchChat === "function") {
4039
+ try {
4040
4040
  const res = await _g2.__retrivoraDispatchChat({
4041
4041
  model: this.model,
4042
4042
  messages: formattedMessages,
@@ -4046,8 +4046,9 @@ ${context != null ? context : "None"}` },
4046
4046
  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) {
4047
4047
  return res.response.choices[0].message.content;
4048
4048
  }
4049
+ } catch (dispatchErr) {
4050
+ throw dispatchErr;
4049
4051
  }
4050
- } catch (e) {
4051
4052
  }
4052
4053
  }
4053
4054
  const { data } = await this.http.post(path2, payload);
@@ -4099,9 +4100,9 @@ ${context != null ? context : "None"}` },
4099
4100
  const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
4100
4101
  let streamBody = null;
4101
4102
  if (isSelfHost || Boolean(process.env.VERCEL)) {
4102
- try {
4103
- const _g3 = globalThis;
4104
- if (typeof _g3.__retrivoraDispatchChat === "function") {
4103
+ const _g3 = globalThis;
4104
+ if (typeof _g3.__retrivoraDispatchChat === "function") {
4105
+ try {
4105
4106
  const res = yield new __await(_g3.__retrivoraDispatchChat({
4106
4107
  model: this.model,
4107
4108
  messages: formattedMessages,
@@ -4115,8 +4116,9 @@ ${context != null ? context : "None"}` },
4115
4116
  yield res.response.choices[0].message.content;
4116
4117
  return;
4117
4118
  }
4119
+ } catch (dispatchErr) {
4120
+ throw dispatchErr;
4118
4121
  }
4119
- } catch (e) {
4120
4122
  }
4121
4123
  }
4122
4124
  if (!streamBody) {
@@ -4187,9 +4189,9 @@ ${context != null ? context : "None"}` },
4187
4189
  }
4188
4190
  const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
4189
4191
  if (isSelfHost || Boolean(process.env.VERCEL)) {
4190
- try {
4191
- const _g2 = globalThis;
4192
- if (typeof _g2.__retrivoraDispatchEmbedding === "function") {
4192
+ const _g2 = globalThis;
4193
+ if (typeof _g2.__retrivoraDispatchEmbedding === "function") {
4194
+ try {
4193
4195
  const res = await _g2.__retrivoraDispatchEmbedding({
4194
4196
  model: this.model,
4195
4197
  input: text
@@ -4197,8 +4199,9 @@ ${context != null ? context : "None"}` },
4197
4199
  if ((_c = (_b = res == null ? void 0 : res.data) == null ? void 0 : _b[0]) == null ? void 0 : _c.embedding) {
4198
4200
  return res.data[0].embedding;
4199
4201
  }
4202
+ } catch (dispatchErr) {
4203
+ throw dispatchErr;
4200
4204
  }
4201
- } catch (e) {
4202
4205
  }
4203
4206
  }
4204
4207
  const { data } = await this.http.post(path2, payload);
@@ -4791,7 +4794,8 @@ var Reranker = class {
4791
4794
  return matches.sort((a, b) => b.score - a.score).slice(0, limit);
4792
4795
  }
4793
4796
  const scoredMatches = matches.map((match) => {
4794
- const contentLower = match.content.toLowerCase();
4797
+ var _a2;
4798
+ const contentLower = ((_a2 = match == null ? void 0 : match.content) != null ? _a2 : "").toLowerCase();
4795
4799
  let keywordScore = 0;
4796
4800
  keywords.forEach((keyword) => {
4797
4801
  if (contentLower.includes(keyword)) {
@@ -4812,7 +4816,10 @@ var Reranker = class {
4812
4816
  [{ role: "user", content: `Query: "${query}"
4813
4817
 
4814
4818
  Documents:
4815
- ${topN.map((m, i) => `[${i}] ${m.content.replace(/\n/g, " ")}`).join("\n")}` }],
4819
+ ${topN.map((m, i) => {
4820
+ var _a2;
4821
+ return `[${i}] ${((_a2 = m == null ? void 0 : m.content) != null ? _a2 : "").replace(/\n/g, " ")}`;
4822
+ }).join("\n")}` }],
4816
4823
  "",
4817
4824
  {
4818
4825
  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.',
@@ -5983,10 +5990,10 @@ Return ONLY 'vector', 'graph', or 'both'. No explanation.`;
5983
5990
  "",
5984
5991
  { temperature: 0, maxTokens: 10 }
5985
5992
  );
5986
- const cleanResponse = response.trim().toLowerCase();
5987
- if (cleanResponse.includes("vector")) return "vector";
5988
- if (cleanResponse.includes("graph")) return "graph";
5993
+ const cleanResponse = (response != null ? response : "").trim().toLowerCase();
5989
5994
  if (cleanResponse.includes("both")) return "both";
5995
+ if (cleanResponse.includes("graph")) return "graph";
5996
+ if (cleanResponse.includes("vector")) return "vector";
5990
5997
  } catch (error) {
5991
5998
  console.warn("[QueryProcessor] LLM strategy classification failed, falling back to keywords:", error);
5992
5999
  }
@@ -6160,7 +6167,10 @@ var IntentClassifier = class {
6160
6167
  hasCategoricalFields = catKeys.size > 0;
6161
6168
  numericFieldCount = numericKeys.size;
6162
6169
  categoricalFieldCount = catKeys.size;
6163
- if (productKeyMatches >= 2 || docs.some((d) => d.content.toLowerCase().includes("price") || d.content.toLowerCase().includes("brand"))) {
6170
+ if (productKeyMatches >= 2 || docs.some((d) => {
6171
+ var _a2, _b;
6172
+ 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");
6173
+ })) {
6164
6174
  isProductLike = true;
6165
6175
  }
6166
6176
  }
@@ -6440,7 +6450,10 @@ var TextRendererStrategy = class {
6440
6450
  return { type: "text", title, data: { content: data } };
6441
6451
  }
6442
6452
  const docs = Array.isArray(data) ? data : [];
6443
- const text = docs.map((d) => d.content).join("\n\n");
6453
+ const text = docs.map((d) => {
6454
+ var _a2;
6455
+ return (_a2 = d == null ? void 0 : d.content) != null ? _a2 : "";
6456
+ }).join("\n\n");
6444
6457
  return { type: "text", title, data: { content: text || "No detailed content available." } };
6445
6458
  }
6446
6459
  };
@@ -6697,6 +6710,19 @@ var UITransformer = class _UITransformer {
6697
6710
  if (!retrievedData || retrievedData.length === 0) {
6698
6711
  return this.createTextResponse("No data available", "No relevant data found for your query.");
6699
6712
  }
6713
+ console.log("[UITransformer.transform] Processing retrievedData:", {
6714
+ userQuery,
6715
+ retrievedCount: retrievedData.length,
6716
+ sample: retrievedData.slice(0, 2).map((item) => {
6717
+ var _a3;
6718
+ return {
6719
+ id: item == null ? void 0 : item.id,
6720
+ contentType: typeof (item == null ? void 0 : item.content),
6721
+ contentSnippet: String((_a3 = item == null ? void 0 : item.content) != null ? _a3 : "").substring(0, 150),
6722
+ metadataKeys: Object.keys((item == null ? void 0 : item.metadata) || {})
6723
+ };
6724
+ })
6725
+ });
6700
6726
  const resolvedIntent = intent != null ? intent : this.detectIntentHeuristic(userQuery);
6701
6727
  const filteredData = resolvedIntent.filterInStockOnly ? retrievedData.filter((item) => this.determineStockStatus(item)) : retrievedData;
6702
6728
  const profile = this.profileData(filteredData);
@@ -7186,7 +7212,10 @@ ${schemaProfileText}` : ""}`;
7186
7212
  type: "radar_chart",
7187
7213
  title: "Product Comparison",
7188
7214
  description: `Comparing ${data.length} items across ${radarData.length} attributes`,
7189
- data: radarData.length > 0 ? radarData : data.map((d) => ({ attribute: d.content.substring(0, 40) }))
7215
+ data: radarData.length > 0 ? radarData : data.map((d) => {
7216
+ var _a2;
7217
+ return { attribute: ((_a2 = d == null ? void 0 : d.content) != null ? _a2 : "").substring(0, 40) };
7218
+ })
7190
7219
  };
7191
7220
  }
7192
7221
  static transformToTable(data, query = "") {
@@ -7203,7 +7232,10 @@ ${schemaProfileText}` : ""}`;
7203
7232
  static transformToText(data) {
7204
7233
  return this.createTextResponse(
7205
7234
  "Retrieved Context",
7206
- data.map((item) => item.content).join("\n\n"),
7235
+ data.map((item) => {
7236
+ var _a2;
7237
+ return (_a2 = item == null ? void 0 : item.content) != null ? _a2 : "";
7238
+ }).join("\n\n"),
7207
7239
  `Found ${data.length} relevant results`
7208
7240
  );
7209
7241
  }
@@ -7364,6 +7396,7 @@ ${schemaProfileText}` : ""}`;
7364
7396
  return productTerms && productAction && !nonProductEntityTerms;
7365
7397
  }
7366
7398
  static isProductData(item) {
7399
+ if (!item) return false;
7367
7400
  const content = (item.content || "").toLowerCase();
7368
7401
  const productKeywords = [
7369
7402
  "product",
@@ -7622,12 +7655,12 @@ ${schemaProfileText}` : ""}`;
7622
7655
  }
7623
7656
  static extractTimeSeriesData(data) {
7624
7657
  return data.map((item) => {
7625
- var _a2, _b, _c, _d, _e;
7658
+ var _a2, _b, _c, _d, _e, _f;
7626
7659
  const meta = item.metadata || {};
7627
7660
  return {
7628
7661
  timestamp: (_b = (_a2 = meta.timestamp) != null ? _a2 : meta.date) != null ? _b : (/* @__PURE__ */ new Date()).toISOString(),
7629
7662
  value: (_d = (_c = meta.value) != null ? _c : item.score) != null ? _d : 0,
7630
- label: (_e = meta.label) != null ? _e : item.content.substring(0, 50)
7663
+ label: (_f = meta.label) != null ? _f : ((_e = item == null ? void 0 : item.content) != null ? _e : "").substring(0, 50)
7631
7664
  };
7632
7665
  });
7633
7666
  }
@@ -7741,7 +7774,8 @@ ${schemaProfileText}` : ""}`;
7741
7774
  }, query.includes(normalizedField) ? 3 : 0);
7742
7775
  }
7743
7776
  static resolveTableCellValue(item, column) {
7744
- if (column === "Content") return item.content.substring(0, 100);
7777
+ var _a2, _b, _c;
7778
+ if (column === "Content") return ((_a2 = item == null ? void 0 : item.content) != null ? _a2 : "").substring(0, 100);
7745
7779
  const meta = item.metadata || {};
7746
7780
  const normalizedColumn = this.normalizeComparableField(column);
7747
7781
  const exactMetadata = Object.entries(meta).find(
@@ -7752,9 +7786,9 @@ ${schemaProfileText}` : ""}`;
7752
7786
  }
7753
7787
  const aliasValue = this.resolveAliasedTableCell(meta, column);
7754
7788
  if (aliasValue !== void 0) return this.toDisplayValue(aliasValue);
7755
- const contentValue = this.extractContentFieldValue(item.content, column);
7789
+ const contentValue = this.extractContentFieldValue((_b = item == null ? void 0 : item.content) != null ? _b : "", column);
7756
7790
  if (contentValue !== null) return contentValue;
7757
- const aliasContentValue = this.extractAliasedContentFieldValue(item.content, column);
7791
+ const aliasContentValue = this.extractAliasedContentFieldValue((_c = item == null ? void 0 : item.content) != null ? _c : "", column);
7758
7792
  return aliasContentValue != null ? aliasContentValue : "";
7759
7793
  }
7760
7794
  static resolveAliasedTableCell(meta, column) {
@@ -7804,6 +7838,7 @@ ${schemaProfileText}` : ""}`;
7804
7838
  return { inStockCount: inStock, outOfStockCount: outOfStock };
7805
7839
  }
7806
7840
  static determineStockStatus(item) {
7841
+ if (!item) return true;
7807
7842
  const meta = item.metadata || {};
7808
7843
  const stockValue = resolveMetadataValue(meta, "stock");
7809
7844
  if (stockValue !== void 0) {
@@ -7849,35 +7884,64 @@ ${schemaProfileText}` : ""}`;
7849
7884
  return resolveMetadataValue(meta, uiKey);
7850
7885
  }
7851
7886
  static extractProductInfo(item, config, trainedSchema) {
7852
- var _a2;
7887
+ var _a2, _b;
7888
+ if (!item) return null;
7853
7889
  const meta = item.metadata || {};
7890
+ const content = item.content || "";
7854
7891
  const name = this.getDynamicVal(meta, "name", config, trainedSchema);
7855
7892
  const price = this.getDynamicVal(meta, "price", config, trainedSchema);
7856
7893
  const brand = this.getDynamicVal(meta, "brand", config, trainedSchema);
7857
7894
  const description = this.cleanProductDescription(
7858
- (_a2 = this.extractProductDescriptionFromContent(item.content)) != null ? _a2 : this.getProductDescriptionValue(meta, config, trainedSchema)
7895
+ (_a2 = this.extractProductDescriptionFromContent(content)) != null ? _a2 : this.getProductDescriptionValue(meta, config, trainedSchema)
7859
7896
  );
7860
7897
  if (name || this.isProductData(item)) {
7861
7898
  let finalName = name ? String(name) : void 0;
7899
+ if (!finalName && content) {
7900
+ const nameMatch = content.match(/(?:Product|Item|Name):\s*([^\n]+)/i);
7901
+ finalName = nameMatch ? nameMatch[1].trim() : (_b = content.split("\n")[0]) == null ? void 0 : _b.substring(0, 60);
7902
+ }
7862
7903
  if (!finalName) {
7863
- const nameMatch = item.content.match(/(?:Product|Item|Name):\s*([^\n]+)/i);
7864
- finalName = nameMatch ? nameMatch[1].trim() : item.content.split("\n")[0].substring(0, 60);
7904
+ console.warn(
7905
+ `[UITransformer] Unable to read product name from metadata or content for item ${item.id}. Defaulting to 'Unnamed Product'.`,
7906
+ { metadataKeys: Object.keys(meta), contentLength: content.length }
7907
+ );
7865
7908
  }
7866
7909
  let finalPrice = typeof price === "number" || typeof price === "string" ? price : void 0;
7867
- if (!finalPrice) {
7868
- const priceMatch = item.content.match(/(?:Price|Cost):\s*\$?([\d,.]+)/i) || item.content.match(/\$\s*([\d,.]+)/);
7910
+ if (!finalPrice && content) {
7911
+ const priceMatch = content.match(/(?:Price|Cost):\s*\$?([\d,.]+)/i) || content.match(/\$\s*([\d,.]+)/);
7869
7912
  if (priceMatch) finalPrice = priceMatch[1].replace(/,/g, "");
7870
7913
  }
7914
+ if (finalPrice === void 0) {
7915
+ console.warn(
7916
+ `[UITransformer] Unable to read product price from metadata or content for item ${item.id}.`,
7917
+ { metadataKeys: Object.keys(meta), contentSnippet: content.substring(0, 100) }
7918
+ );
7919
+ }
7871
7920
  const imageValue = this.getDynamicVal(meta, "image", config, trainedSchema);
7921
+ if (!imageValue) {
7922
+ console.debug(
7923
+ `[UITransformer] Unable to read product image URL from metadata for item ${item.id}.`
7924
+ );
7925
+ }
7926
+ if (!description) {
7927
+ console.debug(
7928
+ `[UITransformer] Unable to read product description from metadata or content for item ${item.id}.`
7929
+ );
7930
+ }
7872
7931
  return {
7873
7932
  id: item.id,
7874
- name: finalName,
7933
+ name: finalName || "Unnamed Product",
7875
7934
  price: finalPrice,
7876
7935
  image: typeof imageValue === "string" ? imageValue : void 0,
7877
7936
  brand: brand ? String(brand) : void 0,
7878
7937
  description,
7879
7938
  inStock: this.determineStockStatus(item)
7880
7939
  };
7940
+ } else {
7941
+ console.warn(
7942
+ `[UITransformer] Item ${item.id} skipped: unable to read name or identify as product data from metadata/content.`,
7943
+ { metadataKeys: Object.keys(meta), contentSnippet: content.substring(0, 100) }
7944
+ );
7881
7945
  }
7882
7946
  return null;
7883
7947
  }
@@ -7962,13 +8026,13 @@ RULES:
7962
8026
  5. If no relevant data is found, return text: "I cannot answer this question based on the available information."`;
7963
8027
  }
7964
8028
  static buildContextSummary(sources, maxChars = 6e3) {
7965
- const items = sources.map((s, i) => {
8029
+ const items = (sources || []).filter(Boolean).map((s, i) => {
7966
8030
  var _a2, _b, _c, _d;
7967
8031
  return {
7968
8032
  index: i + 1,
7969
- content: (_b = (_a2 = s.content) == null ? void 0 : _a2.substring(0, 400)) != null ? _b : "",
7970
- metadata: (_c = s.metadata) != null ? _c : {},
7971
- score: (_d = s.score) != null ? _d : 0
8033
+ content: (_b = (_a2 = s == null ? void 0 : s.content) == null ? void 0 : _a2.substring(0, 400)) != null ? _b : "",
8034
+ metadata: (_c = s == null ? void 0 : s.metadata) != null ? _c : {},
8035
+ score: (_d = s == null ? void 0 : s.score) != null ? _d : 0
7972
8036
  };
7973
8037
  });
7974
8038
  const full = JSON.stringify(items, null, 2);
@@ -8537,17 +8601,33 @@ ${m.content}`).join("\n\n---\n\n");
8537
8601
  const hasNumericPredicates = Array.isArray(filter.__numericPredicates) && filter.__numericPredicates.length > 0;
8538
8602
  const wantsExhaustiveList = hasNumericPredicates || hasMetadataFilter || /\b(list|all|show|provide|give|get|browse|find|search|display)\b/i.test(question);
8539
8603
  const retrievalLimit = wantsExhaustiveList ? Math.max(topK * 20, 100) : topK * 2;
8540
- const rawSources = (strategyResult === "vector" || strategyResult === "both") && queryVector && queryVector.length > 0 ? yield new __await(this.vectorDB.query(queryVector, retrievalLimit, ns, filter)) : [];
8604
+ 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"));
8605
+ console.log("[Pipeline] Raw vectorDB.query response:", {
8606
+ rawCount: rawSources.length,
8607
+ sample: rawSources.slice(0, 2).map((s) => {
8608
+ var _a3;
8609
+ return {
8610
+ id: s == null ? void 0 : s.id,
8611
+ score: s == null ? void 0 : s.score,
8612
+ contentType: typeof (s == null ? void 0 : s.content),
8613
+ contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
8614
+ metadataKeys: Object.keys((s == null ? void 0 : s.metadata) || {})
8615
+ };
8616
+ })
8617
+ });
8541
8618
  const retrieveEnd = performance.now();
8542
8619
  const embedMs = retrieveEnd - embedStart;
8543
8620
  const retrieveMs = retrieveEnd - embedStart;
8544
8621
  const rerankStart = performance.now();
8545
- const structuredSources = this.applyStructuredFilters(rawSources, filter);
8546
- let fullSources = hasNumericPredicates ? structuredSources : structuredSources.filter((m) => m.score >= scoreThreshold);
8622
+ const structuredSources = this.applyStructuredFilters(rawSources, filter).filter((s) => Boolean(s && typeof s === "object"));
8623
+ let fullSources = hasNumericPredicates ? structuredSources : structuredSources.filter((m) => {
8624
+ var _a3;
8625
+ return ((_a3 = m == null ? void 0 : m.score) != null ? _a3 : 0) >= scoreThreshold;
8626
+ });
8547
8627
  const rerankLimit = wantsExhaustiveList ? retrievalLimit : topK;
8548
8628
  const useReranking = arch !== "naive" && (arch === "retrieve-and-rerank" || ((_m = this.config.rag) == null ? void 0 : _m.useReranking));
8549
8629
  if (!hasNumericPredicates && useReranking) {
8550
- fullSources = yield new __await(this.reranker.rerank(fullSources, question, rerankLimit));
8630
+ fullSources = (yield new __await(this.reranker.rerank(fullSources, question, rerankLimit))).filter((s) => Boolean(s && typeof s === "object"));
8551
8631
  } else if (!wantsExhaustiveList) {
8552
8632
  fullSources = fullSources.slice(0, topK);
8553
8633
  }
@@ -8562,13 +8642,33 @@ ${(_a3 = m == null ? void 0 : m.content) != null ? _a3 : ""}`;
8562
8642
  displayCount = fullSources.length;
8563
8643
  } else {
8564
8644
  const baseThreshold = Math.max(scoreThreshold, 0.4);
8565
- const highlyRelevant = fullSources.filter((m) => m.score >= baseThreshold);
8645
+ const highlyRelevant = fullSources.filter((m) => {
8646
+ var _a3;
8647
+ return ((_a3 = m == null ? void 0 : m.score) != null ? _a3 : 0) >= baseThreshold;
8648
+ });
8566
8649
  displayCount = Math.max(highlyRelevant.length, topK);
8567
8650
  if (displayCount > 15) {
8568
8651
  displayCount = 15;
8569
8652
  }
8570
8653
  }
8571
- const sources = [...fullSources].sort((a, b) => b.score - a.score).slice(0, displayCount);
8654
+ const sources = [...fullSources].filter((s) => Boolean(s && typeof s === "object")).sort((a, b) => {
8655
+ var _a3, _b2;
8656
+ return ((_a3 = b == null ? void 0 : b.score) != null ? _a3 : 0) - ((_b2 = a == null ? void 0 : a.score) != null ? _b2 : 0);
8657
+ }).slice(0, displayCount);
8658
+ console.log("[Pipeline] Final sources for prompt & UI:", {
8659
+ count: sources.length,
8660
+ sources: sources.map((s, idx) => {
8661
+ var _a3;
8662
+ return {
8663
+ rank: idx + 1,
8664
+ id: s == null ? void 0 : s.id,
8665
+ score: s == null ? void 0 : s.score,
8666
+ contentType: typeof (s == null ? void 0 : s.content),
8667
+ contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
8668
+ metadata: s == null ? void 0 : s.metadata
8669
+ };
8670
+ })
8671
+ });
8572
8672
  if (graphData && graphData.nodes.length > 0) {
8573
8673
  const graphContext = graphData.nodes.map(
8574
8674
  (n) => `Entity: ${n.label} (${n.id})${n.properties ? " - " + JSON.stringify(n.properties) : ""}`
@@ -8594,18 +8694,18 @@ ${context}`;
8594
8694
  }
8595
8695
  yield {
8596
8696
  reply: "",
8597
- sources: sources.map((s) => {
8598
- var _a3;
8697
+ sources: (sources || []).filter((s) => Boolean(s && typeof s === "object")).map((s) => {
8698
+ var _a3, _b2, _c2;
8599
8699
  return {
8600
8700
  id: s.id,
8601
- score: s.score,
8602
- content: s.content,
8603
- metadata: (_a3 = s.metadata) != null ? _a3 : {},
8701
+ score: (_a3 = s.score) != null ? _a3 : 0,
8702
+ content: (_b2 = s == null ? void 0 : s.content) != null ? _b2 : "",
8703
+ metadata: (_c2 = s == null ? void 0 : s.metadata) != null ? _c2 : {},
8604
8704
  namespace: ns
8605
8705
  };
8606
8706
  })
8607
8707
  };
8608
- const allMetadataKeys = Array.from(new Set(sources.flatMap((s) => Object.keys(s.metadata || {}))));
8708
+ const allMetadataKeys = Array.from(new Set(sources.filter(Boolean).flatMap((s) => Object.keys((s == null ? void 0 : s.metadata) || {}))));
8609
8709
  const cachedSchema = allMetadataKeys.length > 0 ? SchemaMapper.getCached(ns, allMetadataKeys) : void 0;
8610
8710
  if (allMetadataKeys.length > 0 && !cachedSchema) {
8611
8711
  SchemaMapper.train(this.llmProvider, ns, allMetadataKeys).catch(() => {
@@ -8897,6 +8997,8 @@ ${context}`;
8897
8997
  });
8898
8998
  }
8899
8999
  resolveNumericPredicateValue(source, predicate) {
9000
+ var _a2;
9001
+ if (!source) return null;
8900
9002
  const meta = source.metadata || {};
8901
9003
  const field = predicate.field;
8902
9004
  const entries = Object.entries(meta).filter(([, value]) => value !== null && value !== void 0 && typeof value !== "object");
@@ -8908,7 +9010,7 @@ ${context}`;
8908
9010
  const value = this.toFiniteNumber(Array.isArray(fuzzy) ? fuzzy[1] : fuzzy.value);
8909
9011
  if (value !== null) return value;
8910
9012
  }
8911
- const contentValue = this.extractNumericValueFromContent(source.content, field);
9013
+ const contentValue = this.extractNumericValueFromContent((_a2 = source.content) != null ? _a2 : "", field);
8912
9014
  if (contentValue !== null) return contentValue;
8913
9015
  }
8914
9016
  for (const [key, value] of entries) {
@@ -8919,6 +9021,7 @@ ${context}`;
8919
9021
  return null;
8920
9022
  }
8921
9023
  extractNumericValueFromContent(content, field) {
9024
+ if (!content || typeof content !== "string") return null;
8922
9025
  const escapedWords = field.split(/\s+|_+|-+/).filter(Boolean).map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
8923
9026
  if (escapedWords.length === 0) return null;
8924
9027
  const pattern = new RegExp(`(?:${escapedWords.join("[\\\\s_:-]*")})\\s*[:\\-\u2013]?\\s*([\\d,]+(?:\\.\\d+)?)`, "i");
@@ -9004,6 +9107,20 @@ ${context}`;
9004
9107
  resolvedSources.push(source);
9005
9108
  }
9006
9109
  }
9110
+ console.log("[Pipeline] retrieve() response:", {
9111
+ query,
9112
+ namespace: ns,
9113
+ count: resolvedSources.length,
9114
+ sample: resolvedSources.slice(0, 2).map((s) => {
9115
+ var _a3;
9116
+ return {
9117
+ id: s == null ? void 0 : s.id,
9118
+ score: s == null ? void 0 : s.score,
9119
+ contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
9120
+ metadata: s == null ? void 0 : s.metadata
9121
+ };
9122
+ })
9123
+ });
9007
9124
  return { sources: resolvedSources, graphData };
9008
9125
  }
9009
9126
  /** Rewrite the user query for better retrieval performance. */