@retrivora-ai/rag-engine 2.0.8 → 2.1.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@retrivora-ai/rag-engine",
3
- "version": "2.0.8",
3
+ "version": "2.1.1",
4
4
  "description": "Retrivora AI is a plug-and-play AI engine for RAG chat experiences — generic vector DB + LLM provider, embeddable or standalone.",
5
5
  "author": "Abhinav Alkuchi",
6
6
  "license": "UNLICENSED",
@@ -52,10 +52,10 @@ interface WindowWithSpeech extends Window {
52
52
  webkitSpeechRecognition?: new () => ISpeechRecognition;
53
53
  }
54
54
 
55
- export function ChatWindow({
56
- className = '',
57
- style,
58
- onClose,
55
+ export function ChatWindow({
56
+ className = '',
57
+ style,
58
+ onClose,
59
59
  showClose = false,
60
60
  onResizeStart,
61
61
  onResetResize,
@@ -129,7 +129,7 @@ export function ChatWindow({
129
129
  alert('Speech recognition is not supported in your browser.');
130
130
  return;
131
131
  }
132
-
132
+
133
133
  if (isListening) {
134
134
  recognitionRef.current.stop();
135
135
  } else {
@@ -178,7 +178,7 @@ export function ChatWindow({
178
178
  const sendMessage = useCallback(async () => {
179
179
  const text = input.trim();
180
180
  if (!text || isLoading) return;
181
-
181
+
182
182
  if (isListening) {
183
183
  recognitionRef.current?.stop();
184
184
  }
@@ -250,11 +250,10 @@ export function ChatWindow({
250
250
  return (
251
251
  <div
252
252
  ref={windowRef}
253
- className={`relative flex flex-col h-full flex-1 border border-slate-200 dark:border-white/10 shadow-2xl transition-all duration-300 ${currentRadius} ${
254
- isGlass
255
- ? 'bg-white/90 dark:bg-[#0f0f1a]/90 backdrop-blur-xl'
253
+ className={`relative flex flex-col h-full flex-1 border border-slate-200 dark:border-white/10 shadow-2xl transition-all duration-300 ${currentRadius} ${isGlass
254
+ ? 'bg-white/90 dark:bg-[#0f0f1a]/90 backdrop-blur-xl'
256
255
  : 'bg-white dark:bg-[#0f0f1a]'
257
- } ${className}`}
256
+ } ${className}`}
258
257
  style={{ '--primary': ui.primaryColor, '--accent': ui.accentColor, ...style } as React.CSSProperties}
259
258
  >
260
259
  {/* Resize Handle (Top-Left) */}
@@ -293,11 +292,13 @@ export function ChatWindow({
293
292
  </div>
294
293
 
295
294
  <div className="flex items-center gap-1.5">
296
- {/* Online indicator */}
297
- <span className="flex items-center gap-1 text-[10px] text-emerald-500 dark:text-emerald-400 mr-2">
298
- <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 dark:bg-emerald-400 animate-pulse" />
299
- Online
300
- </span>
295
+ {/* Online indicator & Deployment ID badge */}
296
+ <div className="flex items-center gap-1.5 mr-2">
297
+ <span className="flex items-center gap-1 text-[10px] text-emerald-500 dark:text-emerald-400">
298
+ <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 dark:bg-emerald-400 animate-pulse" />
299
+ Online
300
+ </span>
301
+ </div>
301
302
 
302
303
  <div className="flex items-center bg-slate-100/50 dark:bg-white/5 rounded-lg p-0.5 border border-slate-200/50 dark:border-white/5">
303
304
  {mounted && messages.length > 0 && (
@@ -427,9 +428,9 @@ export function ChatWindow({
427
428
  >
428
429
  <X className="w-5 h-5" />
429
430
  </button>
430
- <DocumentUpload
431
- namespace={projectId}
432
- onUploadComplete={() => setIsUploadModalOpen(false)}
431
+ <DocumentUpload
432
+ namespace={projectId}
433
+ onUploadComplete={() => setIsUploadModalOpen(false)}
433
434
  />
434
435
  </div>
435
436
  </div>
@@ -437,7 +438,7 @@ export function ChatWindow({
437
438
 
438
439
  {/* ── Input ── */}
439
440
  <div className={`px-4 pb-4 pt-2 border-t border-slate-200 dark:border-white/10 ${isGlass ? 'bg-transparent' : 'bg-white dark:bg-[#0f0f1a]'}`}>
440
-
441
+
441
442
  {/* Dynamic Suggestions */}
442
443
  {(suggestions.length > 0 || isSuggesting) && !isLoading && (
443
444
  <div className="mb-3 flex flex-wrap gap-2 animate-in fade-in slide-in-from-bottom-2 duration-300">
@@ -488,11 +489,10 @@ export function ChatWindow({
488
489
  type="button"
489
490
  onClick={toggleListening}
490
491
  disabled={isLoading}
491
- className={`flex-shrink-0 w-9 h-9 rounded-xl flex items-center justify-center transition-all hover:scale-105 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100 disabled:active:scale-100 ${
492
- isListening
492
+ className={`flex-shrink-0 w-9 h-9 rounded-xl flex items-center justify-center transition-all hover:scale-105 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100 disabled:active:scale-100 ${isListening
493
493
  ? 'bg-rose-500 text-white animate-pulse shadow-md shadow-rose-500/20'
494
494
  : 'text-slate-400 dark:text-white/40 hover:bg-slate-200 dark:hover:bg-white/10'
495
- }`}
495
+ }`}
496
496
  title={isListening ? 'Stop listening' : 'Start voice input'}
497
497
  >
498
498
  {isListening ? <MicOff className="w-4 h-4" /> : <Mic className="w-4 h-4" />}
@@ -1193,7 +1193,7 @@ You are a helpful assistant. Use the provided context to answer questions accura
1193
1193
  Focus on extracting the core intent and entities. Do not answer the question, just rewrite it.
1194
1194
 
1195
1195
  History:
1196
- ${history.map(m => `${m.role}: ${m.content}`).join('\n')}
1196
+ ${(history || []).map(m => `${m?.role || 'user'}: ${m?.content ?? ''}`).join('\n')}
1197
1197
 
1198
1198
  New Question: ${question}
1199
1199
 
@@ -1222,9 +1222,9 @@ Optimized Search Query:`;
1222
1222
 
1223
1223
  try {
1224
1224
  const { sources } = await this.retrieve(query, { namespace: ns, topK: 5 });
1225
- if (sources.length === 0) return [];
1225
+ if (!sources || sources.length === 0) return [];
1226
1226
 
1227
- const context = sources.map((s) => s.content).join('\n\n---\n\n');
1227
+ const context = sources.map((s) => s?.content ?? '').join('\n\n---\n\n');
1228
1228
  const prompt = `Based on the following snippets from a document, what are at least 5 short, relevant questions a user might ask?
1229
1229
  Focus on questions that can be answered by the context.
1230
1230
  Keep each question under 10 words and make them very specific to the content.
@@ -175,11 +175,11 @@ export class GeminiProvider implements ILLMProvider {
175
175
  * - Messages must strictly alternate between `user` and `model`.
176
176
  */
177
177
  private buildGeminiContents(messages: ChatMessage[]): Array<{ role: 'user' | 'model'; parts: [{ text: string }] }> {
178
- return messages
179
- .filter((m) => m.role !== 'system')
178
+ return (messages || [])
179
+ .filter((m): m is ChatMessage => Boolean(m && typeof m === 'object' && m.role !== 'system'))
180
180
  .map((m) => ({
181
- role: m.role === 'assistant' ? ('model' as const) : ('user' as const),
182
- parts: [{ text: m.content }] as [{ text: string }],
181
+ role: m.role === 'assistant' ? 'model' : 'user',
182
+ parts: [{ text: typeof m.content === 'string' ? m.content : (m.content != null ? String(m.content) : '') }],
183
183
  }));
184
184
  }
185
185
 
@@ -95,12 +95,16 @@ export class GroqProvider implements ILLMProvider {
95
95
  content: buildSystemContent(basePrompt, context),
96
96
  };
97
97
 
98
+ const safeMessages = (Array.isArray(messages) ? messages : [])
99
+ .filter((m): m is ChatMessage => Boolean(m && typeof m === 'object'))
100
+ .map((m) => ({
101
+ role: (m.role || 'user') as 'user' | 'assistant',
102
+ content: typeof m.content === 'string' ? m.content : (m.content != null ? String(m.content) : ''),
103
+ }));
104
+
98
105
  const formattedMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
99
106
  systemMessage,
100
- ...messages.map((m) => ({
101
- role: m.role as 'user' | 'assistant',
102
- content: m.content,
103
- })),
107
+ ...safeMessages,
104
108
  ];
105
109
 
106
110
  const completion = await this.client.chat.completions.create({
@@ -125,12 +129,16 @@ export class GroqProvider implements ILLMProvider {
125
129
  content: buildSystemContent(basePrompt, context),
126
130
  };
127
131
 
132
+ const safeStreamMessages = (Array.isArray(messages) ? messages : [])
133
+ .filter((m): m is ChatMessage => Boolean(m && typeof m === 'object'))
134
+ .map((m) => ({
135
+ role: (m.role || 'user') as 'user' | 'assistant',
136
+ content: typeof m.content === 'string' ? m.content : (m.content != null ? String(m.content) : ''),
137
+ }));
138
+
128
139
  const formattedMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
129
140
  systemMessage,
130
- ...messages.map((m) => ({
131
- role: m.role as 'user' | 'assistant',
132
- content: m.content,
133
- })),
141
+ ...safeStreamMessages,
134
142
  ];
135
143
 
136
144
  const stream = await this.client.chat.completions.create({
@@ -91,12 +91,16 @@ export class OpenAIProvider implements ILLMProvider {
91
91
  content: buildSystemContent(basePrompt, context),
92
92
  };
93
93
 
94
+ const safeMessages = (Array.isArray(messages) ? messages : [])
95
+ .filter((m): m is ChatMessage => Boolean(m && typeof m === 'object'))
96
+ .map((m) => ({
97
+ role: (m.role || 'user') as 'user' | 'assistant',
98
+ content: typeof m.content === 'string' ? m.content : (m.content != null ? String(m.content) : ''),
99
+ }));
100
+
94
101
  const formattedMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
95
102
  systemMessage,
96
- ...messages.map((m) => ({
97
- role: m.role as 'user' | 'assistant',
98
- content: m.content,
99
- })),
103
+ ...safeMessages,
100
104
  ];
101
105
 
102
106
  const completion = await this.client.chat.completions.create({
@@ -121,12 +125,16 @@ export class OpenAIProvider implements ILLMProvider {
121
125
  content: buildSystemContent(basePrompt, context),
122
126
  };
123
127
 
128
+ const safeStreamMessages = (Array.isArray(messages) ? messages : [])
129
+ .filter((m): m is ChatMessage => Boolean(m && typeof m === 'object'))
130
+ .map((m) => ({
131
+ role: (m.role || 'user') as 'user' | 'assistant',
132
+ content: typeof m.content === 'string' ? m.content : (m.content != null ? String(m.content) : ''),
133
+ }));
134
+
124
135
  const formattedMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
125
136
  systemMessage,
126
- ...messages.map((m) => ({
127
- role: m.role as 'user' | 'assistant',
128
- content: m.content,
129
- })),
137
+ ...safeStreamMessages,
130
138
  ];
131
139
 
132
140
  const stream = await this.client.chat.completions.create({
@@ -99,12 +99,16 @@ export class QwenProvider implements ILLMProvider {
99
99
  content: buildSystemContent(basePrompt, context),
100
100
  };
101
101
 
102
+ const safeMessages = (Array.isArray(messages) ? messages : [])
103
+ .filter((m): m is ChatMessage => Boolean(m && typeof m === 'object'))
104
+ .map((m) => ({
105
+ role: (m.role || 'user') as 'user' | 'assistant',
106
+ content: typeof m.content === 'string' ? m.content : (m.content != null ? String(m.content) : ''),
107
+ }));
108
+
102
109
  const formattedMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
103
110
  systemMessage,
104
- ...messages.map((m) => ({
105
- role: m.role as 'user' | 'assistant',
106
- content: m.content,
107
- })),
111
+ ...safeMessages,
108
112
  ];
109
113
 
110
114
  const completion = await this.client.chat.completions.create({
@@ -129,12 +133,16 @@ export class QwenProvider implements ILLMProvider {
129
133
  content: buildSystemContent(basePrompt, context),
130
134
  };
131
135
 
136
+ const safeStreamMessages = (Array.isArray(messages) ? messages : [])
137
+ .filter((m): m is ChatMessage => Boolean(m && typeof m === 'object'))
138
+ .map((m) => ({
139
+ role: (m.role || 'user') as 'user' | 'assistant',
140
+ content: typeof m.content === 'string' ? m.content : (m.content != null ? String(m.content) : ''),
141
+ }));
142
+
132
143
  const formattedMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
133
144
  systemMessage,
134
- ...messages.map((m) => ({
135
- role: m.role as 'user' | 'assistant',
136
- content: m.content,
137
- })),
145
+ ...safeStreamMessages,
138
146
  ];
139
147
 
140
148
  const stream = await this.client.chat.completions.create({
@@ -83,9 +83,16 @@ export class UniversalLLMAdapter implements ILLMProvider {
83
83
  async chat(messages: ChatMessage[], context?: string): Promise<string> {
84
84
  const path = this.opts.chatPath ?? '/chat/completions';
85
85
 
86
+ const safeMessages = (Array.isArray(messages) ? messages : [])
87
+ .filter((m): m is ChatMessage => Boolean(m && typeof m === 'object'))
88
+ .map((m) => ({
89
+ role: m.role || 'user',
90
+ content: typeof m.content === 'string' ? m.content : (m.content != null ? String(m.content) : ''),
91
+ }));
92
+
86
93
  const formattedMessages = [
87
94
  { role: 'system', content: `${this.systemPrompt}\n\nContext:\n${context ?? 'None'}` },
88
- ...messages,
95
+ ...safeMessages,
89
96
  ];
90
97
 
91
98
  let payload: unknown;
@@ -166,9 +173,16 @@ export class UniversalLLMAdapter implements ILLMProvider {
166
173
  const extractPath = (this.opts.responseExtractPath ?? 'choices[0].message.content')
167
174
  .replace('message.content', 'delta.content');
168
175
 
176
+ const safeMessages = (Array.isArray(messages) ? messages : [])
177
+ .filter((m): m is ChatMessage => Boolean(m && typeof m === 'object'))
178
+ .map((m) => ({
179
+ role: m.role || 'user',
180
+ content: typeof m.content === 'string' ? m.content : (m.content != null ? String(m.content) : ''),
181
+ }));
182
+
169
183
  const formattedMessages = [
170
184
  { role: 'system', content: `${this.systemPrompt}\n\nContext:\n${context ?? 'None'}` },
171
- ...messages,
185
+ ...safeMessages,
172
186
  ];
173
187
 
174
188
  let payload: unknown;
@@ -126,10 +126,10 @@ export class IntentClassifier {
126
126
  // ─── Intent Heuristic Checkers ─────────────────────────────────────────────
127
127
 
128
128
  private static isInformationLookup(query: string): boolean {
129
- // Exact single-fact pattern matches e.g. "What is X?", "Explain Y", "Price of Z", "Can Auvira be assigned..."
130
- if (/^(what|who|explain|define|where|when|why|how|how does|can|could|does|do|is|are|has|have|will|should|would|meaning of)\s+/i.test(query)) {
129
+ // Exact single-fact pattern matches e.g. "What is X?", "Explain Y", "Explore Z", "Tell me about A"
130
+ if (/^(what|who|explain|explore|define|where|when|why|how|how does|can|could|does|do|is|are|has|have|will|should|would|meaning of|tell me about|show details of|overview of|summarize)\s+/i.test(query)) {
131
131
  // Exclude comparison or analytical phrasing inside "what is the trend..."
132
- if (!/\b(compare|versus|vs\.?|trend|monthly|revenue|top selling|best)\b/i.test(query)) {
132
+ if (!/\b(compare|versus|vs\.?|trend|monthly|revenue|top 10|top selling|best|chart|graph|plot|breakdown|analytics)\b/i.test(query)) {
133
133
  return true;
134
134
  }
135
135
  }
@@ -10,7 +10,7 @@ export class Rule1SpecificInfoRule implements IRenderRule {
10
10
  // Check specific fact/definition/explanation indicators
11
11
  const isFactQuery =
12
12
  intent === 'information_lookup' ||
13
- /^(what|who|explain|define|where|when|why|meaning of)\s+/i.test(q) ||
13
+ /^(what|who|explain|explore|define|where|when|why|meaning of|tell me about|show details of|overview of|summarize)\s+/i.test(q) ||
14
14
  /^(what is the price of|price of|cost of)\b/i.test(q);
15
15
 
16
16
  const isNonVisual = !/\b(compare|versus|vs\.?|trend|monthly|revenue|best|top 10|chart|table|list|grid)\b/i.test(q);
@@ -196,6 +196,7 @@ export function isLikelyUiOnlyMessage(text: string): boolean {
196
196
  export function extractProductsFromSources(sources: VectorMatch[] | undefined, isUser: boolean): Product[] {
197
197
  if (isUser || !sources) return [];
198
198
  return sources
199
+ .filter((s): s is VectorMatch => Boolean(s && typeof s === 'object'))
199
200
  .filter(s => {
200
201
  const m = s.metadata ?? {};
201
202
  const keys = Object.keys(m).map(k => k.toLowerCase());
@@ -204,7 +205,7 @@ export function extractProductsFromSources(sources: VectorMatch[] | undefined, i
204
205
  );
205
206
  const hasProductIdentity = keys.some(k => ['brand', 'model'].includes(k)) &&
206
207
  keys.some(k => ['name', 'title', 'product_name', 'product'].includes(k));
207
- const hasPricePattern = /\$\s*\d+/.test(s.content);
208
+ const hasPricePattern = /\$\s*\d+/.test(s?.content ?? '');
208
209
  return hasStrongProductKey || hasProductIdentity || hasPricePattern || m.type === 'product';
209
210
  })
210
211
  .map(s => {
@@ -215,13 +216,13 @@ export function extractProductsFromSources(sources: VectorMatch[] | undefined, i
215
216
  const description = resolveMetadataValue(m, 'description') as string;
216
217
 
217
218
  return {
218
- id: s.id,
219
+ id: s?.id ?? `prod_${Math.random().toString(36).substring(2, 8)}`,
219
220
  name: name ?? (s?.content ?? '').split('\n')[0] ?? 'Unknown Product',
220
221
  brand: brand,
221
222
  price: price,
222
223
  image: resolveImage(m),
223
224
  link: resolveMetadataValue(m, 'link') as string,
224
- description: description ? description : '' //description ?? s.content,
225
+ description: description ? description : '',
225
226
  };
226
227
  });
227
228
  }
@@ -1121,6 +1121,15 @@ RULES:
1121
1121
  query: string,
1122
1122
  ): UITransformationResponse | null {
1123
1123
  if (profile.records.length === 0) return null;
1124
+
1125
+ const q = query.toLowerCase().trim();
1126
+ // Do not automatically force charts unless query contains visual or analytical intent
1127
+ const isExplicitVisualOrAnalytic = /\b(chart|graph|plot|visualize|trend|monthly|revenue|top\s*\d+|breakdown|analytics|compare|versus|vs\.?|histogram|pie|bar|line|distribution|percentage|share|summary of metrics)\b/i.test(q);
1128
+
1129
+ if (!isExplicitVisualOrAnalytic) {
1130
+ return null;
1131
+ }
1132
+
1124
1133
  if (profile.dateFields.length > 0 && profile.numericFields.length > 0) {
1125
1134
  return this.transformToLineChart(profile);
1126
1135
  }
@@ -1265,6 +1274,7 @@ RULES:
1265
1274
  }
1266
1275
 
1267
1276
  private static getProductCategory(item: VectorMatch): string | null {
1277
+ if (!item) return null;
1268
1278
  const meta = item.metadata || {};
1269
1279
  const metadataCategory = resolveMetadataValue(meta, 'category');
1270
1280
  if (this.isUsableCategory(metadataCategory)) return String(metadataCategory).trim();
@@ -1401,6 +1411,7 @@ RULES:
1401
1411
  };
1402
1412
 
1403
1413
  data.forEach(item => {
1414
+ if (!item) return;
1404
1415
  Object.keys(item.metadata || {}).forEach(addField);
1405
1416
  for (const match of (item.content || '').matchAll(/(?:^|\n)\s*([A-Za-z][A-Za-z0-9_ /-]{1,50})\s*[:\-–]\s*([^\n]+)/g)) {
1406
1417
  addField(match[1]);
@@ -1551,6 +1562,7 @@ RULES:
1551
1562
  }
1552
1563
 
1553
1564
  private static extractStockQuantity(item: VectorMatch): number | null {
1565
+ if (!item) return null;
1554
1566
  const meta = item.metadata || {};
1555
1567
  const stockValue = resolveMetadataValue(meta, 'stock');
1556
1568
  const numericStock = this.toFiniteNumber(stockValue);