eeshaAI commited on
Commit
f580c68
·
1 Parent(s): b01ae33

feat: fast AI via Llama-3.1-8B direct (1-3s), vision relay via Llama-3.2-11B, product search in parallel

Browse files
Files changed (1) hide show
  1. src/app/api/ai-chat/route.ts +175 -32
src/app/api/ai-chat/route.ts CHANGED
@@ -1,49 +1,192 @@
1
  import { NextRequest, NextResponse } from 'next/server';
2
 
3
- const SUPABASE_URL = process.env.SUPABASE_URL || 'https://tcwdbokruvlizkxcpkzj.supabase.co';
4
- const SUPABASE_ANON_KEY = process.env.SUPABASE_ANON_KEY || '';
5
- const EDGE_FUNCTIONS_URL = `${SUPABASE_URL}/functions/v1`;
 
 
 
 
 
 
 
 
 
 
 
 
6
  const COOKIE_NAME = 'cellex_session_id';
7
 
8
- export async function POST(request: NextRequest) {
9
- if (!SUPABASE_ANON_KEY) {
10
- return NextResponse.json({ success: false, error: 'SUPABASE_ANON_KEY not set' }, { status: 500 });
11
- }
 
 
 
12
 
13
- const sessionId = request.cookies.get(COOKIE_NAME)?.value || '';
14
- const body = await request.text();
15
 
16
- const headers: Record<string, string> = {
17
- 'apikey': SUPABASE_ANON_KEY,
18
- 'Content-Type': 'application/json',
19
- };
20
- if (sessionId) {
21
- headers['Authorization'] = `Bearer ${sessionId}`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  }
 
23
 
 
24
  try {
25
- const resp = await fetch(`${EDGE_FUNCTIONS_URL}/ai-chat`, {
26
  method: 'POST',
27
- headers,
28
- body,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- const text = await resp.text();
32
- try {
33
- const data = JSON.parse(text);
34
- // Map edge function response fields to what the frontend expects
35
- const reply = data.response || data.reply || data.message || data.content || '';
36
  return NextResponse.json({
37
- success: data.success !== false,
38
- reply,
39
- message: reply,
40
- content: reply,
41
- products: data.products || null,
42
- }, { status: resp.status });
43
- } catch {
44
- return NextResponse.json({ success: false, error: `Non-JSON response: ${text.substring(0, 200)}` }, { status: 500 });
45
  }
 
 
 
 
 
 
 
 
 
 
 
 
46
  } catch (error) {
47
- return NextResponse.json({ success: false, error: String(error) }, { status: 500 });
 
 
 
 
 
48
  }
49
  }
 
 
 
 
 
1
  import { NextRequest, NextResponse } from 'next/server';
2
 
3
+ /**
4
+ * AI Chat API route — calls NVIDIA NIM directly for fast responses (1-3s).
5
+ * Uses Llama-3.1-8B-Instruct (sub-1s latency) for chat + overview generation.
6
+ * Falls back to edge function for product search (which needs Supabase DB).
7
+ *
8
+ * Vision relay: Llama-3.2-11B-Vision for image-to-text (when user uploads image).
9
+ */
10
+
11
+ const NVIDIA_API_URL = 'https://integrate.api.nvidia.com/v1/chat/completions';
12
+ const NVIDIA_API_KEY = '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';
13
+ const BRAIN_MODEL = 'meta/llama-3.1-8b-instruct';
14
+ const VISION_MODEL = 'meta/llama-3.2-11b-vision-instruct';
15
+
16
+ const SUPABASE_URL = 'https://tcwdbokruvlizkxcpkzj.supabase.co';
17
+ const SUPABASE_ANON_KEY = process.env.SUPABASE_ANON_KEY || 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InRjd2Rib2tydXVsaXpreGNwa3pqIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjAxMDkyNjQsImV4cCI6MjA3NTY4NTI2NH0.p871FXUakrWQ7PhhZr8Ly2BxLOhwQjRJiDGd59wAhyg';
18
  const COOKIE_NAME = 'cellex_session_id';
19
 
20
+ const SYSTEM_PROMPT = `You are Cellex AI, a friendly shopping assistant for Cellex — Nigeria's #1 social commerce marketplace.
21
+ Help users find products, compare prices, and make shopping decisions.
22
+ Prices are in Nigerian Naira (₦). Be concise, friendly, and helpful (2-3 sentences max).
23
+ If users ask about specific products, mention you can search for them.
24
+ For return policy: 7-day returns on most items in original condition.
25
+ For delivery: 48-hour shipping within Nigeria, free shipping on orders over ₦50,000.
26
+ For payment: PalmPay bank transfer with auto-verification, pay on delivery available.`;
27
 
28
+ // Keywords that trigger product search
29
+ const SEARCH_KEYWORDS = ['search', 'find', 'looking for', 'need', 'want', 'buy', 'show me', 'do you have', 'available', 'price', 'how much', 'under', 'over', 'cheap', 'best', 'recommend'];
30
 
31
+ function needsProductSearch(message: string): boolean {
32
+ const lower = message.toLowerCase();
33
+ return SEARCH_KEYWORDS.some(kw => lower.includes(kw));
34
+ }
35
+
36
+ async function searchProducts(query: string): Promise<any[]> {
37
+ try {
38
+ const resp = await fetch(`${SUPABASE_URL}/functions/v1/products`, {
39
+ method: 'POST',
40
+ headers: {
41
+ 'apikey': SUPABASE_ANON_KEY,
42
+ 'Authorization': `Bearer ${SUPABASE_ANON_KEY}`,
43
+ 'Content-Type': 'application/json',
44
+ },
45
+ body: JSON.stringify({ op: 'search', query }),
46
+ });
47
+ if (!resp.ok) return [];
48
+ const data = await resp.json();
49
+ return (data.results || data.products || []).slice(0, 6);
50
+ } catch {
51
+ return [];
52
  }
53
+ }
54
 
55
+ async function describeImage(imageUrl: string): Promise<string> {
56
  try {
57
+ const resp = await fetch(NVIDIA_API_URL, {
58
  method: 'POST',
59
+ headers: {
60
+ 'Authorization': `Bearer ${NVIDIA_API_KEY}`,
61
+ 'Content-Type': 'application/json',
62
+ },
63
+ body: JSON.stringify({
64
+ model: VISION_MODEL,
65
+ messages: [{
66
+ role: 'user',
67
+ content: [
68
+ { type: 'text', text: 'Describe this product in detail (color, type, material, brand if visible) so I can search for it.' },
69
+ { type: 'image_url', image_url: { url: imageUrl } },
70
+ ],
71
+ }],
72
+ max_tokens: 150,
73
+ stream: false,
74
+ }),
75
  });
76
+ if (!resp.ok) return '';
77
+ const data = await resp.json();
78
+ return data?.choices?.[0]?.message?.content || '';
79
+ } catch {
80
+ return '';
81
+ }
82
+ }
83
+
84
+ async function callNVIDIA(messages: Array<{ role: string; content: string }>, maxTokens: number = 200): Promise<string> {
85
+ const resp = await fetch(NVIDIA_API_URL, {
86
+ method: 'POST',
87
+ headers: {
88
+ 'Authorization': `Bearer ${NVIDIA_API_KEY}`,
89
+ 'Content-Type': 'application/json',
90
+ },
91
+ body: JSON.stringify({
92
+ model: BRAIN_MODEL,
93
+ messages,
94
+ max_tokens: maxTokens,
95
+ temperature: 0.5,
96
+ stream: false,
97
+ }),
98
+ });
99
+ if (!resp.ok) throw new Error(`NVIDIA HTTP ${resp.status}`);
100
+ const data = await resp.json();
101
+ return data?.choices?.[0]?.message?.content || '';
102
+ }
103
+
104
+ export async function POST(request: NextRequest) {
105
+ try {
106
+ const body = await request.json();
107
+ const { message, context, history, image } = body;
108
+
109
+ if (!message || typeof message !== 'string') {
110
+ return NextResponse.json({ success: false, error: 'Missing "message"' }, { status: 400 });
111
+ }
112
+
113
+ // Build messages
114
+ const messages: Array<{ role: string; content: string }> = [
115
+ { role: 'system', content: SYSTEM_PROMPT },
116
+ ];
117
+
118
+ // Add history
119
+ if (Array.isArray(history)) {
120
+ for (const msg of history.slice(-6)) {
121
+ if (msg.role && msg.content) {
122
+ messages.push({ role: msg.role, content: msg.content });
123
+ }
124
+ }
125
+ }
126
+
127
+ // Handle image (vision relay)
128
+ let userMessage = message;
129
+ if (image) {
130
+ const description = await describeImage(image);
131
+ if (description) {
132
+ userMessage = `User uploaded an image of: ${description}. User request: ${message}`;
133
+ }
134
+ }
135
+
136
+ // Add context
137
+ if (context) {
138
+ messages.push({ role: 'system', content: `Context: ${context}` });
139
+ }
140
+
141
+ // Check if this needs product search
142
+ const shouldSearch = needsProductSearch(message) || (context && context.includes('Search overview'));
143
+
144
+ let products: any[] = [];
145
+ if (shouldSearch) {
146
+ // Search products in parallel with AI response
147
+ const [aiReply, searchResults] = await Promise.all([
148
+ callNVIDIA([...messages, { role: 'user', content: userMessage }], 200),
149
+ searchProducts(message.replace(/under.*naira|over.*naira|cheap|best/gi, '').trim() || message),
150
+ ]);
151
+ products = searchResults;
152
+
153
+ // If we found products, enhance the reply
154
+ let finalReply = aiReply;
155
+ if (products.length > 0) {
156
+ const productList = products.slice(0, 4).map(p => `${p.name} (${formatPrice(p.price)})`).join(', ');
157
+ finalReply = `${aiReply}\n\nI found ${products.length} products for you: ${productList}`;
158
+ }
159
 
 
 
 
 
 
160
  return NextResponse.json({
161
+ success: true,
162
+ reply: finalReply,
163
+ message: finalReply,
164
+ content: finalReply,
165
+ products: products.length > 0 ? products : null,
166
+ });
 
 
167
  }
168
+
169
+ // Simple chat (no product search) — fast path
170
+ messages.push({ role: 'user', content: userMessage });
171
+ const reply = await callNVIDIA(messages, 200);
172
+
173
+ return NextResponse.json({
174
+ success: true,
175
+ reply,
176
+ message: reply,
177
+ content: reply,
178
+ products: null,
179
+ });
180
  } catch (error) {
181
+ console.error('AI chat error:', error);
182
+ return NextResponse.json({
183
+ success: false,
184
+ error: String(error),
185
+ reply: "I'm having trouble right now. Please try again.",
186
+ }, { status: 200 });
187
  }
188
  }
189
+
190
+ function formatPrice(n: number): string {
191
+ return `₦${Number(n || 0).toLocaleString('en-NG', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`;
192
+ }