@retrivora-ai/rag-engine 1.1.9 → 1.2.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/dist/index.js CHANGED
@@ -227,6 +227,24 @@ function MessageBubble({
227
227
  }
228
228
  return void 0;
229
229
  };
230
+ const productsFromSources = import_react4.default.useMemo(() => {
231
+ if (isUser || !sources) return [];
232
+ return sources.filter((s) => {
233
+ const m = s.metadata || {};
234
+ return m.price || m.image || m.img || m.thumbnail || m.images || m.brand || m.type === "product";
235
+ }).map((s) => {
236
+ const m = s.metadata || {};
237
+ return {
238
+ id: s.id,
239
+ name: m.name || m.title || s.content.split("\n")[0] || "Unknown Product",
240
+ brand: m.brand,
241
+ price: m.price,
242
+ image: resolveImage(m),
243
+ link: m.link,
244
+ description: s.content
245
+ };
246
+ });
247
+ }, [sources, isUser]);
230
248
  const { productsFromContent, cleanContent } = import_react4.default.useMemo(() => {
231
249
  if (isUser) return { productsFromContent: [], cleanContent: message.content };
232
250
  const jsonRegex = /```json\s*([\s\S]*?)\s*```/g;
@@ -250,7 +268,23 @@ function MessageBubble({
250
268
  }
251
269
  return { productsFromContent: products, cleanContent: content.trim() };
252
270
  }, [message.content, isUser]);
253
- const allProducts = productsFromContent;
271
+ const allProducts = import_react4.default.useMemo(() => {
272
+ if (productsFromContent.length > 0) return productsFromContent;
273
+ const uniqueProducts = [];
274
+ const seenIds = /* @__PURE__ */ new Set();
275
+ const contentLower = message.content.toLowerCase();
276
+ for (const p of productsFromSources) {
277
+ const identifier = p.id || p.name;
278
+ if (seenIds.has(identifier)) continue;
279
+ const nameMatch = contentLower.includes(p.name.toLowerCase());
280
+ const brandMatch = p.brand ? contentLower.includes(p.brand.toLowerCase()) : false;
281
+ if (nameMatch || brandMatch) {
282
+ seenIds.add(identifier);
283
+ uniqueProducts.push(p);
284
+ }
285
+ }
286
+ return uniqueProducts;
287
+ }, [productsFromSources, productsFromContent, message.content]);
254
288
  const hasProducts = allProducts.length > 0;
255
289
  return /* @__PURE__ */ import_react4.default.createElement("div", { className: `flex gap-3 ${isUser ? "flex-row-reverse" : "flex-row"} items-start` }, /* @__PURE__ */ import_react4.default.createElement(
256
290
  "div",
@@ -597,6 +631,32 @@ function ChatWindow({
597
631
  const isEmpty = messages.length === 0;
598
632
  const currentRadius = BORDER_RADIUS_MAP[ui.borderRadius || "xl"];
599
633
  const isGlass = ui.visualStyle !== "solid";
634
+ const [suggestions, setSuggestions] = (0, import_react7.useState)([]);
635
+ const [isSuggesting, setIsSuggesting] = (0, import_react7.useState)(false);
636
+ (0, import_react7.useEffect)(() => {
637
+ if (input.trim().length < 3) {
638
+ return;
639
+ }
640
+ const timer = setTimeout(async () => {
641
+ setIsSuggesting(true);
642
+ try {
643
+ const response = await fetch("/api/suggestions", {
644
+ method: "POST",
645
+ headers: { "Content-Type": "application/json" },
646
+ body: JSON.stringify({ query: input, namespace: projectId })
647
+ });
648
+ const data = await response.json();
649
+ if (data.suggestions) {
650
+ setSuggestions(data.suggestions);
651
+ }
652
+ } catch (err) {
653
+ console.error("Failed to fetch suggestions:", err);
654
+ } finally {
655
+ setIsSuggesting(false);
656
+ }
657
+ }, 800);
658
+ return () => clearTimeout(timer);
659
+ }, [input, projectId]);
600
660
  return /* @__PURE__ */ import_react7.default.createElement(
601
661
  "div",
602
662
  {
@@ -708,12 +768,32 @@ function ChatWindow({
708
768
  onAddToCart
709
769
  }
710
770
  ), error && /* @__PURE__ */ import_react7.default.createElement("div", { className: "flex items-center gap-2 text-rose-500 dark:text-rose-400 text-sm bg-rose-50 dark:bg-rose-400/10 border border-rose-200 dark:border-rose-400/20 rounded-xl px-4 py-3" }, /* @__PURE__ */ import_react7.default.createElement(import_lucide_react5.TriangleAlert, { className: "w-4 h-4 flex-shrink-0" }), /* @__PURE__ */ import_react7.default.createElement("span", null, error)), /* @__PURE__ */ import_react7.default.createElement("div", { ref: bottomRef })),
711
- /* @__PURE__ */ import_react7.default.createElement("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]"}` }, /* @__PURE__ */ import_react7.default.createElement("div", { className: `flex items-end gap-2 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 p-2 focus-within:border-slate-300 dark:focus-within:border-white/20 transition-all ${ui.borderRadius === "full" ? "rounded-3xl" : "rounded-2xl"}` }, /* @__PURE__ */ import_react7.default.createElement(
771
+ /* @__PURE__ */ import_react7.default.createElement("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]"}` }, (suggestions.length > 0 || isSuggesting) && !isLoading && /* @__PURE__ */ import_react7.default.createElement("div", { className: "mb-3 flex flex-wrap gap-2 animate-in fade-in slide-in-from-bottom-2 duration-300" }, suggestions.map((suggestion) => /* @__PURE__ */ import_react7.default.createElement(
772
+ "button",
773
+ {
774
+ key: suggestion,
775
+ onClick: () => {
776
+ var _a2;
777
+ setInput(suggestion);
778
+ setSuggestions([]);
779
+ (_a2 = inputRef.current) == null ? void 0 : _a2.focus();
780
+ },
781
+ className: "flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-[11px] font-medium bg-white dark:bg-white/5 border border-slate-200 dark:border-white/10 text-slate-600 dark:text-white/60 hover:text-slate-900 dark:hover:text-white/90 hover:border-slate-300 dark:hover:border-white/20 transition-all shadow-sm cursor-pointer group"
782
+ },
783
+ /* @__PURE__ */ import_react7.default.createElement(import_lucide_react5.Sparkles, { className: "w-3 h-3 text-amber-400" }),
784
+ suggestion
785
+ )), isSuggesting && suggestions.length === 0 && /* @__PURE__ */ import_react7.default.createElement("div", { className: "flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-[11px] font-medium text-slate-400 dark:text-white/30 animate-pulse" }, /* @__PURE__ */ import_react7.default.createElement(import_lucide_react5.Sparkles, { className: "w-3 h-3" }), "Thinking...")), /* @__PURE__ */ import_react7.default.createElement("div", { className: `flex items-end gap-2 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 p-2 focus-within:border-slate-300 dark:focus-within:border-white/20 transition-all ${ui.borderRadius === "full" ? "rounded-3xl" : "rounded-2xl"}` }, /* @__PURE__ */ import_react7.default.createElement(
712
786
  "textarea",
713
787
  {
714
788
  ref: inputRef,
715
789
  value: input,
716
- onChange: (e) => setInput(e.target.value),
790
+ onChange: (e) => {
791
+ const val = e.target.value;
792
+ setInput(val);
793
+ if (val.trim().length < 3) {
794
+ setSuggestions([]);
795
+ }
796
+ },
717
797
  onKeyDown: handleKeyDown,
718
798
  placeholder: ui.placeholder,
719
799
  rows: 1,
package/dist/index.mjs CHANGED
@@ -185,6 +185,24 @@ function MessageBubble({
185
185
  }
186
186
  return void 0;
187
187
  };
188
+ const productsFromSources = React4.useMemo(() => {
189
+ if (isUser || !sources) return [];
190
+ return sources.filter((s) => {
191
+ const m = s.metadata || {};
192
+ return m.price || m.image || m.img || m.thumbnail || m.images || m.brand || m.type === "product";
193
+ }).map((s) => {
194
+ const m = s.metadata || {};
195
+ return {
196
+ id: s.id,
197
+ name: m.name || m.title || s.content.split("\n")[0] || "Unknown Product",
198
+ brand: m.brand,
199
+ price: m.price,
200
+ image: resolveImage(m),
201
+ link: m.link,
202
+ description: s.content
203
+ };
204
+ });
205
+ }, [sources, isUser]);
188
206
  const { productsFromContent, cleanContent } = React4.useMemo(() => {
189
207
  if (isUser) return { productsFromContent: [], cleanContent: message.content };
190
208
  const jsonRegex = /```json\s*([\s\S]*?)\s*```/g;
@@ -208,7 +226,23 @@ function MessageBubble({
208
226
  }
209
227
  return { productsFromContent: products, cleanContent: content.trim() };
210
228
  }, [message.content, isUser]);
211
- const allProducts = productsFromContent;
229
+ const allProducts = React4.useMemo(() => {
230
+ if (productsFromContent.length > 0) return productsFromContent;
231
+ const uniqueProducts = [];
232
+ const seenIds = /* @__PURE__ */ new Set();
233
+ const contentLower = message.content.toLowerCase();
234
+ for (const p of productsFromSources) {
235
+ const identifier = p.id || p.name;
236
+ if (seenIds.has(identifier)) continue;
237
+ const nameMatch = contentLower.includes(p.name.toLowerCase());
238
+ const brandMatch = p.brand ? contentLower.includes(p.brand.toLowerCase()) : false;
239
+ if (nameMatch || brandMatch) {
240
+ seenIds.add(identifier);
241
+ uniqueProducts.push(p);
242
+ }
243
+ }
244
+ return uniqueProducts;
245
+ }, [productsFromSources, productsFromContent, message.content]);
212
246
  const hasProducts = allProducts.length > 0;
213
247
  return /* @__PURE__ */ React4.createElement("div", { className: `flex gap-3 ${isUser ? "flex-row-reverse" : "flex-row"} items-start` }, /* @__PURE__ */ React4.createElement(
214
248
  "div",
@@ -539,6 +573,32 @@ function ChatWindow({
539
573
  const isEmpty = messages.length === 0;
540
574
  const currentRadius = BORDER_RADIUS_MAP[ui.borderRadius || "xl"];
541
575
  const isGlass = ui.visualStyle !== "solid";
576
+ const [suggestions, setSuggestions] = useState4([]);
577
+ const [isSuggesting, setIsSuggesting] = useState4(false);
578
+ useEffect4(() => {
579
+ if (input.trim().length < 3) {
580
+ return;
581
+ }
582
+ const timer = setTimeout(async () => {
583
+ setIsSuggesting(true);
584
+ try {
585
+ const response = await fetch("/api/suggestions", {
586
+ method: "POST",
587
+ headers: { "Content-Type": "application/json" },
588
+ body: JSON.stringify({ query: input, namespace: projectId })
589
+ });
590
+ const data = await response.json();
591
+ if (data.suggestions) {
592
+ setSuggestions(data.suggestions);
593
+ }
594
+ } catch (err) {
595
+ console.error("Failed to fetch suggestions:", err);
596
+ } finally {
597
+ setIsSuggesting(false);
598
+ }
599
+ }, 800);
600
+ return () => clearTimeout(timer);
601
+ }, [input, projectId]);
542
602
  return /* @__PURE__ */ React7.createElement(
543
603
  "div",
544
604
  {
@@ -650,12 +710,32 @@ function ChatWindow({
650
710
  onAddToCart
651
711
  }
652
712
  ), error && /* @__PURE__ */ React7.createElement("div", { className: "flex items-center gap-2 text-rose-500 dark:text-rose-400 text-sm bg-rose-50 dark:bg-rose-400/10 border border-rose-200 dark:border-rose-400/20 rounded-xl px-4 py-3" }, /* @__PURE__ */ React7.createElement(TriangleAlert, { className: "w-4 h-4 flex-shrink-0" }), /* @__PURE__ */ React7.createElement("span", null, error)), /* @__PURE__ */ React7.createElement("div", { ref: bottomRef })),
653
- /* @__PURE__ */ React7.createElement("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]"}` }, /* @__PURE__ */ React7.createElement("div", { className: `flex items-end gap-2 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 p-2 focus-within:border-slate-300 dark:focus-within:border-white/20 transition-all ${ui.borderRadius === "full" ? "rounded-3xl" : "rounded-2xl"}` }, /* @__PURE__ */ React7.createElement(
713
+ /* @__PURE__ */ React7.createElement("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]"}` }, (suggestions.length > 0 || isSuggesting) && !isLoading && /* @__PURE__ */ React7.createElement("div", { className: "mb-3 flex flex-wrap gap-2 animate-in fade-in slide-in-from-bottom-2 duration-300" }, suggestions.map((suggestion) => /* @__PURE__ */ React7.createElement(
714
+ "button",
715
+ {
716
+ key: suggestion,
717
+ onClick: () => {
718
+ var _a2;
719
+ setInput(suggestion);
720
+ setSuggestions([]);
721
+ (_a2 = inputRef.current) == null ? void 0 : _a2.focus();
722
+ },
723
+ className: "flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-[11px] font-medium bg-white dark:bg-white/5 border border-slate-200 dark:border-white/10 text-slate-600 dark:text-white/60 hover:text-slate-900 dark:hover:text-white/90 hover:border-slate-300 dark:hover:border-white/20 transition-all shadow-sm cursor-pointer group"
724
+ },
725
+ /* @__PURE__ */ React7.createElement(Sparkles, { className: "w-3 h-3 text-amber-400" }),
726
+ suggestion
727
+ )), isSuggesting && suggestions.length === 0 && /* @__PURE__ */ React7.createElement("div", { className: "flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-[11px] font-medium text-slate-400 dark:text-white/30 animate-pulse" }, /* @__PURE__ */ React7.createElement(Sparkles, { className: "w-3 h-3" }), "Thinking...")), /* @__PURE__ */ React7.createElement("div", { className: `flex items-end gap-2 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 p-2 focus-within:border-slate-300 dark:focus-within:border-white/20 transition-all ${ui.borderRadius === "full" ? "rounded-3xl" : "rounded-2xl"}` }, /* @__PURE__ */ React7.createElement(
654
728
  "textarea",
655
729
  {
656
730
  ref: inputRef,
657
731
  value: input,
658
- onChange: (e) => setInput(e.target.value),
732
+ onChange: (e) => {
733
+ const val = e.target.value;
734
+ setInput(val);
735
+ if (val.trim().length < 3) {
736
+ setSuggestions([]);
737
+ }
738
+ },
659
739
  onKeyDown: handleKeyDown,
660
740
  placeholder: ui.placeholder,
661
741
  rows: 1,
package/dist/server.d.mts CHANGED
@@ -1,7 +1,7 @@
1
- import { i as VectorDBConfig, L as LLMConfig, c as EmbeddingConfig, g as RagConfig, e as IngestDocument, C as ChatMessage, b as ChatResponse, k as RetrievalResult, h as UpsertDocument, V as VectorMatch, G as GraphDBConfig, l as GraphNode, m as Edge, n as GraphSearchResult, I as ILLMProvider, j as VectorDBProvider, f as LLMProvider, d as EmbeddingProvider, R as RAGConfig, U as UIConfig, a as ChatOptions, E as EmbedOptions } from './RagConfig-FyMB_UG6.mjs';
1
+ import { i as VectorDBConfig, L as LLMConfig, c as EmbeddingConfig, g as RagConfig, e as IngestDocument, C as ChatMessage, b as ChatResponse, k as RetrievalResult, h as UpsertDocument, V as VectorMatch, G as GraphDBConfig, l as GraphNode, m as Edge, n as GraphSearchResult, I as ILLMProvider, j as VectorDBProvider, f as LLMProvider, d as EmbeddingProvider, R as RAGConfig, U as UIConfig, a as ChatOptions, E as EmbedOptions } from './RagConfig-BOLOz0_O.mjs';
2
2
  export { C as Chunk, a as ChunkOptions, D as DocumentChunker } from './DocumentChunker-Dh9TvmGG.mjs';
3
- import { H as HealthCheckResult, I as IProviderValidator, a as IProviderHealthChecker } from './index-D-lfcqlL.mjs';
4
- export { C as ConfigValidator, V as ValidationError, b as VectorPlugin, c as createChatHandler, d as createHealthHandler, e as createIngestHandler, f as createStreamHandler, g as createUploadHandler, s as sseErrorFrame, h as sseFrame, i as sseMetaFrame, j as sseTextFrame } from './index-D-lfcqlL.mjs';
3
+ import { H as HealthCheckResult, I as IProviderValidator, a as IProviderHealthChecker } from './index-64BDupW3.mjs';
4
+ export { C as ConfigValidator, V as ValidationError, b as VectorPlugin, c as createChatHandler, d as createHealthHandler, e as createIngestHandler, f as createStreamHandler, g as createUploadHandler, s as sseErrorFrame, h as sseFrame, i as sseMetaFrame, j as sseTextFrame } from './index-64BDupW3.mjs';
5
5
  import 'next/server';
6
6
 
7
7
  /**
@@ -166,6 +166,10 @@ declare class Pipeline {
166
166
  * Rewrite the user query for better retrieval performance.
167
167
  */
168
168
  private rewriteQuery;
169
+ /**
170
+ * Generate 3-5 short, relevant questions based on the vector database content.
171
+ */
172
+ getSuggestions(query: string, namespace?: string): Promise<string[]>;
169
173
  }
170
174
 
171
175
  /**
package/dist/server.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { i as VectorDBConfig, L as LLMConfig, c as EmbeddingConfig, g as RagConfig, e as IngestDocument, C as ChatMessage, b as ChatResponse, k as RetrievalResult, h as UpsertDocument, V as VectorMatch, G as GraphDBConfig, l as GraphNode, m as Edge, n as GraphSearchResult, I as ILLMProvider, j as VectorDBProvider, f as LLMProvider, d as EmbeddingProvider, R as RAGConfig, U as UIConfig, a as ChatOptions, E as EmbedOptions } from './RagConfig-FyMB_UG6.js';
1
+ import { i as VectorDBConfig, L as LLMConfig, c as EmbeddingConfig, g as RagConfig, e as IngestDocument, C as ChatMessage, b as ChatResponse, k as RetrievalResult, h as UpsertDocument, V as VectorMatch, G as GraphDBConfig, l as GraphNode, m as Edge, n as GraphSearchResult, I as ILLMProvider, j as VectorDBProvider, f as LLMProvider, d as EmbeddingProvider, R as RAGConfig, U as UIConfig, a as ChatOptions, E as EmbedOptions } from './RagConfig-BOLOz0_O.js';
2
2
  export { C as Chunk, a as ChunkOptions, D as DocumentChunker } from './DocumentChunker-Dh9TvmGG.js';
3
- import { H as HealthCheckResult, I as IProviderValidator, a as IProviderHealthChecker } from './index-CYgr00ot.js';
4
- export { C as ConfigValidator, V as ValidationError, b as VectorPlugin, c as createChatHandler, d as createHealthHandler, e as createIngestHandler, f as createStreamHandler, g as createUploadHandler, s as sseErrorFrame, h as sseFrame, i as sseMetaFrame, j as sseTextFrame } from './index-CYgr00ot.js';
3
+ import { H as HealthCheckResult, I as IProviderValidator, a as IProviderHealthChecker } from './index-DbtE8wLM.js';
4
+ export { C as ConfigValidator, V as ValidationError, b as VectorPlugin, c as createChatHandler, d as createHealthHandler, e as createIngestHandler, f as createStreamHandler, g as createUploadHandler, s as sseErrorFrame, h as sseFrame, i as sseMetaFrame, j as sseTextFrame } from './index-DbtE8wLM.js';
5
5
  import 'next/server';
6
6
 
7
7
  /**
@@ -166,6 +166,10 @@ declare class Pipeline {
166
166
  * Rewrite the user query for better retrieval performance.
167
167
  */
168
168
  private rewriteQuery;
169
+ /**
170
+ * Generate 3-5 short, relevant questions based on the vector database content.
171
+ */
172
+ getSuggestions(query: string, namespace?: string): Promise<string[]>;
169
173
  }
170
174
 
171
175
  /**
package/dist/server.js CHANGED
@@ -4177,6 +4177,50 @@ Optimized Search Query:`;
4177
4177
  );
4178
4178
  return rewrite.trim() || question;
4179
4179
  }
4180
+ /**
4181
+ * Generate 3-5 short, relevant questions based on the vector database content.
4182
+ */
4183
+ async getSuggestions(query, namespace) {
4184
+ if (!query || query.trim().length < 3) {
4185
+ return [];
4186
+ }
4187
+ await this.initialize();
4188
+ const ns = namespace != null ? namespace : this.config.projectId;
4189
+ try {
4190
+ const { sources } = await this.retrieve(query, { namespace: ns, topK: 3 });
4191
+ if (sources.length === 0) {
4192
+ return [];
4193
+ }
4194
+ const context = sources.map((s) => s.content).join("\n\n---\n\n");
4195
+ const prompt = `
4196
+ Based on the following snippets from a document, what are 3 short, relevant questions a user might ask?
4197
+ Focus on questions that can be answered by the context.
4198
+ Keep each question under 10 words and make them very specific to the content.
4199
+ Return ONLY a JSON array of strings like ["Question 1", "Question 2", "Question 3"].
4200
+
4201
+ Context:
4202
+ ${context}
4203
+
4204
+ Suggestions:`;
4205
+ const response = await this.llmProvider.chat(
4206
+ [
4207
+ { role: "system", content: "You are a helpful assistant that generates search suggestions." },
4208
+ { role: "user", content: prompt }
4209
+ ],
4210
+ ""
4211
+ );
4212
+ const match = response.match(/\[[\s\S]*\]/);
4213
+ if (match) {
4214
+ const suggestions = JSON.parse(match[0]);
4215
+ if (Array.isArray(suggestions)) {
4216
+ return suggestions.map((s) => String(s)).slice(0, 3);
4217
+ }
4218
+ }
4219
+ } catch (error) {
4220
+ console.error("[Pipeline] Failed to generate suggestions:", error);
4221
+ }
4222
+ return [];
4223
+ }
4180
4224
  };
4181
4225
 
4182
4226
  // src/core/ProviderHealthCheck.ts
@@ -4331,6 +4375,13 @@ var VectorPlugin = class {
4331
4375
  await this.validationPromise;
4332
4376
  return this.pipeline.ingest(documents, namespace);
4333
4377
  }
4378
+ /**
4379
+ * Get auto-suggestions based on a query prefix.
4380
+ */
4381
+ async getSuggestions(query, namespace) {
4382
+ await this.validationPromise;
4383
+ return this.pipeline.getSuggestions(query, namespace);
4384
+ }
4334
4385
  };
4335
4386
 
4336
4387
  // src/config/ConfigBuilder.ts
package/dist/server.mjs CHANGED
@@ -39,7 +39,7 @@ import {
39
39
  sseFrame,
40
40
  sseMetaFrame,
41
41
  sseTextFrame
42
- } from "./chunk-OCDCJUNE.mjs";
42
+ } from "./chunk-GCPPRD2G.mjs";
43
43
  import "./chunk-YLTMFW4M.mjs";
44
44
  import {
45
45
  PineconeProvider
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@retrivora-ai/rag-engine",
3
- "version": "1.1.9",
3
+ "version": "1.2.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": "MIT",
@@ -0,0 +1,4 @@
1
+ import { createSuggestionsHandler } from '@/handlers';
2
+ import { getRagConfig } from '@/config/serverConfig';
3
+
4
+ export const POST = createSuggestionsHandler(getRagConfig());
@@ -4,12 +4,13 @@ import React, { useState } from 'react';
4
4
  import { MessageSquare, X } from 'lucide-react';
5
5
  import { ChatWindow } from './ChatWindow';
6
6
  import { useConfig } from './ConfigProvider';
7
+ import { Product } from '../types';
7
8
 
8
9
  interface ChatWidgetProps {
9
10
  /** Position of the floating button. Defaults to bottom-right. */
10
11
  position?: 'bottom-right' | 'bottom-left';
11
12
  /** Called when the user clicks 'Add to Cart' on a product */
12
- onAddToCart?: (product: any) => void;
13
+ onAddToCart?: (product: Product) => void;
13
14
  }
14
15
 
15
16
  const DEFAULT_DIMENSIONS = { width: 380, height: 600 };
@@ -16,6 +16,7 @@ import { MessageBubble } from './MessageBubble';
16
16
  import { useConfig } from './ConfigProvider';
17
17
  import { useRagChat } from '../hooks/useRagChat';
18
18
  import { BORDER_RADIUS_MAP, CHAT_SUGGESTIONS } from '../config/uiConstants';
19
+ import { Product } from '../types';
19
20
 
20
21
  interface ChatWindowProps {
21
22
  /** Additional className for the wrapper div */
@@ -37,7 +38,7 @@ interface ChatWindowProps {
37
38
  /** Whether the window is currently maximized */
38
39
  isMaximized?: boolean;
39
40
  /** Called when the user clicks 'Add to Cart' on a product */
40
- onAddToCart?: (product: any) => void;
41
+ onAddToCart?: (product: Product) => void;
41
42
  }
42
43
 
43
44
  export function ChatWindow({
@@ -97,6 +98,37 @@ export function ChatWindow({
97
98
  const currentRadius = BORDER_RADIUS_MAP[ui.borderRadius || 'xl'];
98
99
  const isGlass = ui.visualStyle !== 'solid';
99
100
 
101
+ const [suggestions, setSuggestions] = useState<string[]>([]);
102
+ const [isSuggesting, setIsSuggesting] = useState(false);
103
+
104
+ // Auto-suggestions fetcher (debounced)
105
+ useEffect(() => {
106
+ if (input.trim().length < 3) {
107
+ return;
108
+ }
109
+
110
+ const timer = setTimeout(async () => {
111
+ setIsSuggesting(true);
112
+ try {
113
+ const response = await fetch('/api/suggestions', {
114
+ method: 'POST',
115
+ headers: { 'Content-Type': 'application/json' },
116
+ body: JSON.stringify({ query: input, namespace: projectId }),
117
+ });
118
+ const data = await response.json();
119
+ if (data.suggestions) {
120
+ setSuggestions(data.suggestions);
121
+ }
122
+ } catch (err) {
123
+ console.error('Failed to fetch suggestions:', err);
124
+ } finally {
125
+ setIsSuggesting(false);
126
+ }
127
+ }, 800); // 800ms debounce to save costs/latency
128
+
129
+ return () => clearTimeout(timer);
130
+ }, [input, projectId]);
131
+
100
132
  return (
101
133
  <div
102
134
  className={`relative flex flex-col border border-slate-200 dark:border-white/10 shadow-2xl transition-all duration-300 ${currentRadius} ${
@@ -265,11 +297,44 @@ export function ChatWindow({
265
297
 
266
298
  {/* ── Input ── */}
267
299
  <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]'}`}>
300
+
301
+ {/* Dynamic Suggestions */}
302
+ {(suggestions.length > 0 || isSuggesting) && !isLoading && (
303
+ <div className="mb-3 flex flex-wrap gap-2 animate-in fade-in slide-in-from-bottom-2 duration-300">
304
+ {suggestions.map((suggestion) => (
305
+ <button
306
+ key={suggestion}
307
+ onClick={() => {
308
+ setInput(suggestion);
309
+ setSuggestions([]);
310
+ inputRef.current?.focus();
311
+ }}
312
+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-[11px] font-medium bg-white dark:bg-white/5 border border-slate-200 dark:border-white/10 text-slate-600 dark:text-white/60 hover:text-slate-900 dark:hover:text-white/90 hover:border-slate-300 dark:hover:border-white/20 transition-all shadow-sm cursor-pointer group"
313
+ >
314
+ <Sparkles className="w-3 h-3 text-amber-400" />
315
+ {suggestion}
316
+ </button>
317
+ ))}
318
+ {isSuggesting && suggestions.length === 0 && (
319
+ <div className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-[11px] font-medium text-slate-400 dark:text-white/30 animate-pulse">
320
+ <Sparkles className="w-3 h-3" />
321
+ Thinking...
322
+ </div>
323
+ )}
324
+ </div>
325
+ )}
326
+
268
327
  <div className={`flex items-end gap-2 bg-slate-50 dark:bg-white/5 border border-slate-200 dark:border-white/10 p-2 focus-within:border-slate-300 dark:focus-within:border-white/20 transition-all ${ui.borderRadius === 'full' ? 'rounded-3xl' : 'rounded-2xl'}`}>
269
328
  <textarea
270
329
  ref={inputRef}
271
330
  value={input}
272
- onChange={(e) => setInput(e.target.value)}
331
+ onChange={(e) => {
332
+ const val = e.target.value;
333
+ setInput(val);
334
+ if (val.trim().length < 3) {
335
+ setSuggestions([]);
336
+ }
337
+ }}
273
338
  onKeyDown={handleKeyDown}
274
339
  placeholder={ui.placeholder}
275
340
  rows={1}
@@ -8,7 +8,7 @@ import { ChatMessage } from '../llm/ILLMProvider';
8
8
  import { VectorMatch } from '../types';
9
9
  import { SourceCard } from './SourceCard';
10
10
  import { ProductCarousel } from './ProductCarousel';
11
- import { Product } from './ProductCard';
11
+ import { Product } from '../types';
12
12
 
13
13
  interface MessageBubbleProps {
14
14
  message: ChatMessage;
@@ -33,26 +33,48 @@ export function MessageBubble({
33
33
  // Helper to extract image from metadata or object
34
34
  const resolveImage = (data: Record<string, unknown>): string | undefined => {
35
35
  if (!data) return undefined;
36
-
36
+
37
37
  // Check single string fields
38
38
  const singleFields = ['image', 'img', 'thumbnail'];
39
39
  for (const field of singleFields) {
40
40
  const val = data[field];
41
41
  if (typeof val === 'string' && val) return val;
42
42
  }
43
-
43
+
44
44
  // Check images array
45
45
  if (Array.isArray(data.images) && data.images.length > 0) {
46
46
  if (typeof data.images[0] === 'string') return data.images[0];
47
47
  }
48
-
48
+
49
49
  return undefined;
50
50
  };
51
51
 
52
+ // Extract products from sources
53
+ const productsFromSources = React.useMemo(() => {
54
+ if (isUser || !sources) return [];
55
+ return sources
56
+ .filter(s => {
57
+ const m = s.metadata || {};
58
+ return m.price || m.image || m.img || m.thumbnail || m.images || m.brand || m.type === 'product';
59
+ })
60
+ .map(s => {
61
+ const m = (s.metadata || {}) as Record<string, unknown>;
62
+ return {
63
+ id: s.id,
64
+ name: (m.name || m.title || s.content.split('\n')[0] || 'Unknown Product') as string,
65
+ brand: m.brand as string,
66
+ price: m.price as string | number,
67
+ image: resolveImage(m),
68
+ link: m.link as string,
69
+ description: s.content
70
+ };
71
+ });
72
+ }, [sources, isUser]);
73
+
52
74
  // Extract products from content (structured JSON)
53
75
  const { productsFromContent, cleanContent } = React.useMemo(() => {
54
76
  if (isUser) return { productsFromContent: [], cleanContent: message.content };
55
-
77
+
56
78
  const jsonRegex = /```json\s*([\s\S]*?)\s*```/g;
57
79
  const products: Product[] = [];
58
80
  let content = message.content;
@@ -80,19 +102,41 @@ export function MessageBubble({
80
102
  return { productsFromContent: products, cleanContent: content.trim() };
81
103
  }, [message.content, isUser]);
82
104
 
83
- const allProducts = productsFromContent;
105
+ const allProducts = React.useMemo(() => {
106
+ // If the LLM explicitly provided products in a structured format, only show those.
107
+ if (productsFromContent.length > 0) return productsFromContent;
108
+
109
+ // Fallback: Show unique products from sources, but ONLY if they are mentioned in the message text.
110
+ // This aligns the carousel with what the assistant is actually "displaying" in its response.
111
+ const uniqueProducts: Product[] = [];
112
+ const seenIds = new Set();
113
+ const contentLower = message.content.toLowerCase();
84
114
 
115
+ for (const p of productsFromSources) {
116
+ const identifier = p.id || p.name;
117
+ if (seenIds.has(identifier)) continue;
118
+
119
+ // Check if the product name or brand is mentioned in the assistant's text
120
+ const nameMatch = contentLower.includes(p.name.toLowerCase());
121
+ const brandMatch = p.brand ? contentLower.includes(p.brand.toLowerCase()) : false;
122
+
123
+ if (nameMatch || brandMatch) {
124
+ seenIds.add(identifier);
125
+ uniqueProducts.push(p);
126
+ }
127
+ }
128
+
129
+ return uniqueProducts;
130
+ }, [productsFromSources, productsFromContent, message.content]);
85
131
 
86
- // Only surface product cards if the LLM explicitly provided them via structured JSON
87
132
  const hasProducts = allProducts.length > 0;
88
133
 
89
134
  return (
90
135
  <div className={`flex gap-3 ${isUser ? 'flex-row-reverse' : 'flex-row'} items-start`}>
91
136
  {/* Avatar */}
92
137
  <div
93
- className={`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center shadow-lg ${
94
- isUser ? 'text-white' : 'bg-slate-100 dark:bg-white/10 text-slate-700 dark:text-white/80'
95
- }`}
138
+ className={`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center shadow-lg ${isUser ? 'text-white' : 'bg-slate-100 dark:bg-white/10 text-slate-700 dark:text-white/80'
139
+ }`}
96
140
  style={isUser ? { background: `linear-gradient(135deg, ${primaryColor}, ${accentColor})` } : {}}
97
141
  >
98
142
  {isUser
@@ -104,11 +148,10 @@ export function MessageBubble({
104
148
  <div className={`flex flex-col gap-1 max-w-[90%] ${isUser ? 'items-end' : 'items-start'}`}>
105
149
  {/* Bubble */}
106
150
  <div
107
- className={`relative px-4 py-3 rounded-2xl text-sm leading-relaxed shadow-sm dark:shadow-lg ${
108
- isUser
151
+ className={`relative px-4 py-3 rounded-2xl text-sm leading-relaxed shadow-sm dark:shadow-lg ${isUser
109
152
  ? 'text-white rounded-tr-sm'
110
153
  : 'bg-white dark:bg-white/5 border border-slate-200 dark:border-white/10 text-slate-800 dark:text-white/90 rounded-tl-sm'
111
- }`}
154
+ }`}
112
155
  style={
113
156
  isUser
114
157
  ? { background: `linear-gradient(135deg, ${primaryColor}, ${accentColor})` }
@@ -126,7 +169,7 @@ export function MessageBubble({
126
169
  <ReactMarkdown remarkPlugins={[remarkGfm]}>
127
170
  {cleanContent || message.content}
128
171
  </ReactMarkdown>
129
-
172
+
130
173
  {isStreaming && message.content && (
131
174
  <span className="inline-block w-1.5 h-3.5 ml-1 bg-emerald-500 animate-pulse align-middle" />
132
175
  )}
@@ -137,9 +180,9 @@ export function MessageBubble({
137
180
  {/* Product Carousel (Outside the bubble) */}
138
181
  {!isUser && hasProducts && (
139
182
  <div className="w-full mt-1">
140
- <ProductCarousel
141
- products={allProducts}
142
- primaryColor={primaryColor}
183
+ <ProductCarousel
184
+ products={allProducts}
185
+ primaryColor={primaryColor}
143
186
  onAddToCart={onAddToCart}
144
187
  />
145
188
  </div>
@@ -4,15 +4,7 @@ import React from 'react';
4
4
  import Image from 'next/image';
5
5
  import { ShoppingCart, ExternalLink } from 'lucide-react';
6
6
 
7
- export interface Product {
8
- id: string | number;
9
- name: string;
10
- brand?: string;
11
- price?: string | number;
12
- image?: string;
13
- link?: string;
14
- description?: string;
15
- }
7
+ import { Product } from '../types';
16
8
 
17
9
  interface ProductCardProps {
18
10
  product: Product;
@@ -2,7 +2,8 @@
2
2
 
3
3
  import React, { useRef, useState, useEffect } from 'react';
4
4
  import { ChevronLeft, ChevronRight } from 'lucide-react';
5
- import { Product, ProductCard } from './ProductCard';
5
+ import { ProductCard } from './ProductCard';
6
+ import { Product } from '../types';
6
7
 
7
8
  interface ProductCarouselProps {
8
9
  products: Product[];