eeshaAI commited on
Commit
698bbca
·
1 Parent(s): 38dd284

security: remove hardcoded NVIDIA API key — use env var

Browse files
Files changed (1) hide show
  1. src/app/api/ai-chat/route.ts +23 -122
src/app/api/ai-chat/route.ts CHANGED
@@ -1,31 +1,18 @@
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 {
@@ -34,67 +21,39 @@ function needsProductSearch(message: string): boolean {
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();
@@ -105,88 +64,30 @@ 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
- }
 
1
  import { NextRequest, NextResponse } from 'next/server';
2
 
 
 
 
 
 
 
 
 
3
  const NVIDIA_API_URL = 'https://integrate.api.nvidia.com/v1/chat/completions';
4
+ const NVIDIA_API_KEY = process.env.NVIDIA_API_KEY || '';
5
  const BRAIN_MODEL = 'meta/llama-3.1-8b-instruct';
6
  const VISION_MODEL = 'meta/llama-3.2-11b-vision-instruct';
7
 
8
+ const SUPABASE_URL = process.env.SUPABASE_URL || 'https://tcwdbokruvlizkxcpkzj.supabase.co';
9
+ const SUPABASE_ANON_KEY = process.env.SUPABASE_ANON_KEY || '';
10
  const COOKIE_NAME = 'cellex_session_id';
11
 
12
  const SYSTEM_PROMPT = `You are Cellex AI, a friendly shopping assistant for Cellex — Nigeria's #1 social commerce marketplace.
13
  Help users find products, compare prices, and make shopping decisions.
14
+ Prices are in Nigerian Naira (₦). Be concise, friendly, and helpful (2-3 sentences max).`;
 
 
 
 
15
 
 
16
  const SEARCH_KEYWORDS = ['search', 'find', 'looking for', 'need', 'want', 'buy', 'show me', 'do you have', 'available', 'price', 'how much', 'under', 'over', 'cheap', 'best', 'recommend'];
17
 
18
  function needsProductSearch(message: string): boolean {
 
21
  }
22
 
23
  async function searchProducts(query: string): Promise<any[]> {
24
+ if (!SUPABASE_ANON_KEY) return [];
25
  try {
26
  const resp = await fetch(`${SUPABASE_URL}/functions/v1/products`, {
27
  method: 'POST',
28
+ headers: { 'apikey': SUPABASE_ANON_KEY, 'Authorization': `Bearer ${SUPABASE_ANON_KEY}`, 'Content-Type': 'application/json' },
 
 
 
 
29
  body: JSON.stringify({ op: 'search', query }),
30
  });
31
  if (!resp.ok) return [];
32
  const data = await resp.json();
33
  return (data.results || data.products || []).slice(0, 6);
34
+ } catch { return []; }
 
 
35
  }
36
 
37
  async function describeImage(imageUrl: string): Promise<string> {
38
+ if (!NVIDIA_API_KEY) return '';
39
  try {
40
  const resp = await fetch(NVIDIA_API_URL, {
41
  method: 'POST',
42
+ headers: { 'Authorization': `Bearer ${NVIDIA_API_KEY}`, 'Content-Type': 'application/json' },
43
+ body: JSON.stringify({ model: VISION_MODEL, messages: [{ role: 'user', content: [{ type: 'text', text: 'Describe this product.' }, { type: 'image_url', image_url: { url: imageUrl } }] }], max_tokens: 150, stream: false }),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  });
45
  if (!resp.ok) return '';
46
  const data = await resp.json();
47
  return data?.choices?.[0]?.message?.content || '';
48
+ } catch { return ''; }
 
 
49
  }
50
 
51
  async function callNVIDIA(messages: Array<{ role: string; content: string }>, maxTokens: number = 200): Promise<string> {
52
+ if (!NVIDIA_API_KEY) throw new Error('NVIDIA_API_KEY not set');
53
  const resp = await fetch(NVIDIA_API_URL, {
54
  method: 'POST',
55
+ headers: { 'Authorization': `Bearer ${NVIDIA_API_KEY}`, 'Content-Type': 'application/json' },
56
+ body: JSON.stringify({ model: BRAIN_MODEL, messages, max_tokens: maxTokens, temperature: 0.5, stream: false }),
 
 
 
 
 
 
 
 
 
57
  });
58
  if (!resp.ok) throw new Error(`NVIDIA HTTP ${resp.status}`);
59
  const data = await resp.json();
 
64
  try {
65
  const body = await request.json();
66
  const { message, context, history, image } = body;
67
+ if (!message) return NextResponse.json({ success: false, error: 'Missing message' }, { status: 400 });
68
 
69
+ const messages: Array<{ role: string; content: string }> = [{ role: 'system', content: SYSTEM_PROMPT }];
70
+ if (Array.isArray(history)) for (const msg of history.slice(-6)) if (msg.role && msg.content) messages.push({ role: msg.role, content: msg.content });
 
 
 
 
 
 
71
 
 
 
 
 
 
 
 
 
 
 
72
  let userMessage = message;
73
+ if (image) { const d = await describeImage(image); if (d) userMessage = `Image: ${d}. Request: ${message}`; }
74
+ if (context) messages.push({ role: 'system', content: `Context: ${context}` });
 
 
 
 
75
 
 
 
 
 
 
 
76
  const shouldSearch = needsProductSearch(message) || (context && context.includes('Search overview'));
 
 
77
  if (shouldSearch) {
 
78
  const [aiReply, searchResults] = await Promise.all([
79
  callNVIDIA([...messages, { role: 'user', content: userMessage }], 200),
80
  searchProducts(message.replace(/under.*naira|over.*naira|cheap|best/gi, '').trim() || message),
81
  ]);
 
 
 
82
  let finalReply = aiReply;
83
+ if (searchResults.length > 0) finalReply += `\n\nFound ${searchResults.length} products: ${searchResults.slice(0,4).map(p => `${p.name} (₦${Number(p.price).toLocaleString('en-NG')})`).join(', ')}`;
84
+ return NextResponse.json({ success: true, reply: finalReply, message: finalReply, content: finalReply, products: searchResults.length > 0 ? searchResults : null });
 
 
 
 
 
 
 
 
 
 
85
  }
86
 
 
87
  messages.push({ role: 'user', content: userMessage });
88
  const reply = await callNVIDIA(messages, 200);
89
+ return NextResponse.json({ success: true, reply, message: reply, content: reply, products: null });
 
 
 
 
 
 
 
90
  } catch (error) {
91
+ return NextResponse.json({ success: false, error: String(error), reply: "I'm having trouble right now. Please try again." }, { status: 200 });
 
 
 
 
 
92
  }
93
  }