-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
335 lines (281 loc) · 9.89 KB
/
index.js
File metadata and controls
335 lines (281 loc) · 9.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const { GoogleGenerativeAI } = require('@google/generative-ai');
const { createClient } = require('@supabase/supabase-js');
// Load environment variables
require('dotenv').config();
const app = express();
// Security middleware
app.use(helmet({
crossOriginResourcePolicy: { policy: "cross-origin" }
}));
// CORS configuration
app.use(cors({
origin: true,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
}));
// Body parsing middleware
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// Logging middleware
app.use(morgan('combined'));
// Initialize Google Gemini AI
let model;
try {
if (!process.env.GEMINI_API_KEY) {
console.error('❌ GEMINI_API_KEY is required');
process.exit(1);
}
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
model = genAI.getGenerativeModel({ model: "gemini-2.0-flash-exp" });
console.log('✅ Gemini AI initialized successfully');
} catch (error) {
console.error('❌ Failed to initialize Gemini AI:', error);
process.exit(1);
}
// Initialize Supabase
let supabase;
try {
if (!process.env.SUPABASE_URL || !process.env.SUPABASE_ANON_KEY) {
console.error('❌ SUPABASE_URL and SUPABASE_ANON_KEY are required');
process.exit(1);
}
supabase = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_ANON_KEY
);
console.log('✅ Supabase initialized successfully');
} catch (error) {
console.error('❌ Failed to initialize Supabase:', error);
process.exit(1);
}
// Auth verification middleware
const verifyAuth = async (req, res, next) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing or invalid authorization header' });
}
const token = authHeader.substring(7);
const { data: { user }, error } = await supabase.auth.getUser(token);
if (error || !user) {
return res.status(401).json({ error: 'Invalid or expired token' });
}
req.user = user;
next();
} catch (error) {
console.error('Auth verification error:', error);
res.status(401).json({ error: 'Authentication failed' });
}
};
// Helper functions
const getOrCreateConversation = async (userId, conversationId = null, title = 'New Chat') => {
try {
if (conversationId) {
const { data, error } = await supabase
.from('conversations')
.select('*')
.eq('id', conversationId)
.eq('user_id', userId)
.single();
if (!error && data) {
return data;
}
}
const { data, error } = await supabase
.from('conversations')
.insert({
user_id: userId,
title: title,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
})
.select()
.single();
if (error) {
throw error;
}
return data;
} catch (error) {
console.error('Error in getOrCreateConversation:', error);
throw error;
}
};
const getConversationHistory = async (conversationId, limit = 20) => {
try {
const { data, error } = await supabase
.from('messages')
.select('*')
.eq('conversation_id', conversationId)
.order('created_at', { ascending: true })
.limit(limit);
if (error) {
throw error;
}
return data || [];
} catch (error) {
console.error('Error fetching conversation history:', error);
throw error;
}
};
const saveMessage = async (conversationId, role, content) => {
try {
const { data, error } = await supabase
.from('messages')
.insert({
conversation_id: conversationId,
role: role,
content: content,
created_at: new Date().toISOString()
})
.select()
.single();
if (error) {
throw error;
}
return data;
} catch (error) {
console.error('Error saving message:', error);
throw error;
}
};
// Routes
app.get('/api/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
services: {
gemini: !!model,
supabase: !!supabase
}
});
});
app.get('/api/conversations', verifyAuth, async (req, res) => {
try {
const { data, error } = await supabase
.from('conversations')
.select('*')
.eq('user_id', req.user.id)
.order('updated_at', { ascending: false });
if (error) {
throw error;
}
res.json(data || []);
} catch (error) {
console.error('Error fetching conversations:', error);
res.status(500).json({ error: 'Failed to fetch conversations' });
}
});
app.get('/api/conversations/:id/messages', verifyAuth, async (req, res) => {
try {
const conversationId = req.params.id;
const messages = await getConversationHistory(conversationId);
res.json(messages);
} catch (error) {
console.error('Error fetching messages:', error);
res.status(500).json({ error: 'Failed to fetch messages' });
}
});
app.post('/api/chat', verifyAuth, async (req, res) => {
try {
const { prompt, conversation_id, model_name = 'gemini-2.0-flash-exp' } = req.body;
if (!prompt) {
return res.status(400).json({ error: 'Missing required parameter: prompt' });
}
console.log(`Chat request from user ${req.user.id}: ${prompt.substring(0, 50)}...`);
const conversation = await getOrCreateConversation(
req.user.id,
conversation_id,
prompt.substring(0, 50) + '...'
);
const history = await getConversationHistory(conversation.id);
await saveMessage(conversation.id, 'user', prompt);
let contextMessages = [];
history.forEach(msg => {
if (msg.role === 'user') {
contextMessages.push(`User: ${msg.content}`);
} else if (msg.role === 'assistant') {
contextMessages.push(`Assistant: ${msg.content}`);
}
});
contextMessages.push(`User: ${prompt}`);
let fullContext;
if (history.length > 0) {
const previousMessages = contextMessages.slice(0, -1).join('\n');
fullContext = `Previous conversation:\n${previousMessages}\n\nCurrent message:\n${prompt}\n\nPlease respond remembering our previous conversation and maintain context.`;
} else {
fullContext = prompt;
}
console.log(`Context length: ${history.length + 1} messages`);
const result = await model.generateContent(fullContext);
const response = await result.response;
const aiResponse = response.text();
await saveMessage(conversation.id, 'assistant', aiResponse);
if (history.length === 0) {
await supabase
.from('conversations')
.update({
title: prompt.substring(0, 50) + (prompt.length > 50 ? '...' : '')
})
.eq('id', conversation.id);
}
res.json({
content: aiResponse,
conversation_id: conversation.id,
model_used: model_name
});
} catch (error) {
console.error('Error in chat endpoint:', error);
if (error.message && error.message.includes('API_KEY')) {
return res.status(500).json({
error: 'Invalid or missing Gemini API key. Please check your configuration.'
});
}
res.status(500).json({
error: 'Failed to generate response. Please try again.',
details: error.message
});
}
});
app.delete('/api/conversations/:id', verifyAuth, async (req, res) => {
try {
const conversationId = req.params.id;
const { error } = await supabase
.from('conversations')
.delete()
.eq('id', conversationId)
.eq('user_id', req.user.id);
if (error) {
throw error;
}
res.json({ message: 'Conversation deleted successfully' });
} catch (error) {
console.error('Error deleting conversation:', error);
res.status(500).json({ error: 'Failed to delete conversation' });
}
});
app.get('/api/models', (req, res) => {
res.json({
text_models: [
{ id: 'gemini-2.0-flash-exp', name: 'Gemini 2.0 Flash Experimental' },
{ id: 'gemini-1.5-pro', name: 'Gemini 1.5 Pro' },
{ id: 'gemini-1.5-flash', name: 'Gemini 1.5 Flash' }
],
default_model: 'gemini-2.0-flash-exp'
});
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Unhandled error:', err);
res.status(500).json({ error: 'Internal server error' });
});
// 404 handler
app.use((req, res) => {
res.status(404).json({ error: 'Endpoint not found' });
});
// Export for Vercel
module.exports = app;