-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver-production.js
More file actions
496 lines (410 loc) · 15.1 KB
/
server-production.js
File metadata and controls
496 lines (410 loc) · 15.1 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { GoogleGenAI } from '@google/genai';
import { CONFIG, validateBotData } from './config.js';
import path from 'path';
import { fileURLToPath } from 'url';
import rateLimit from 'express-rate-limit';
import helmet from 'helmet';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Load environment variables
dotenv.config({ path: '.env.production' });
const app = express();
// Security middleware
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
fontSrc: ["'self'", "https://fonts.gstatic.com"],
scriptSrc: ["'self'"],
imgSrc: ["'self'", "data:", "https:"],
},
},
}));
// CORS configuration
const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(',') || ['http://localhost:3001'];
app.use(cors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true
}));
// Rate limiting
const limiter = rateLimit({
windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 900000, // 15 minutes
max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100,
message: 'Too many requests from this IP, please try again later.',
standardHeaders: true,
legacyHeaders: false,
});
app.use('/api/', limiter);
app.use(express.json({ limit: '10mb' }));
// Serve static files in production
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'dist')));
}
const PORT = process.env.PORT || 3001;
let botsData = null;
// Middleware to validate API key from environment
const validateApiKey = (req, res, next) => {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
return res.status(500).json({
error: 'Server configuration error: GEMINI_API_KEY not set'
});
}
// Attach API key to request for use in handlers
req.geminiApiKey = apiKey;
next();
};
// Health check endpoint
app.get('/health', (req, res) => {
res.status(200).json({
status: 'healthy',
timestamp: new Date().toISOString(),
uptime: process.uptime()
});
});
// API endpoints with validation
app.post('/api/generate-world', validateApiKey, async (req, res) => {
try {
const { topic, roles } = req.body;
if (!topic || !roles || !Array.isArray(roles)) {
return res.status(400).json({ error: 'Invalid request: topic and roles required' });
}
const ai = new GoogleGenAI({ apiKey: req.geminiApiKey });
const tools = [{ googleSearch: {} }];
const config = {
thinkingConfig: { thinkingLevel: CONFIG.THINKING_LEVEL },
tools,
temperature: CONFIG.TEMPERATURE,
maxOutputTokens: CONFIG.MAX_OUTPUT_TOKENS_WORLD,
};
const contents = [{
role: 'user',
parts: [{
text: `Create global rules and environment for a virtual world simulation.
Topic: ${topic}
Roles: ${roles.join(', ')}
Output a JSON object with:
- project: description of the project
- roles: array of roles
- rules: object with communication, knowledge_share, tasks
- knowledgeDomains: object mapping each role to their knowledge areas
Output ONLY valid JSON, no markdown.`,
}],
}];
const response = await ai.models.generateContent({
model: CONFIG.MODEL,
config,
contents,
});
const text = response.candidates[0].content.parts[0].text;
const worldBrain = JSON.parse(text.replace(/```json\n?/g, '').replace(/```\n?/g, ''));
res.json({ worldBrain });
} catch (error) {
console.error('World generation error:', error);
res.status(500).json({ error: 'Failed to generate world brain' });
}
});
// Generate bots endpoint
app.post('/api/generate-bots', validateApiKey, async (req, res) => {
try {
const { totalBots, topic, roles, worldBrain } = req.body;
if (!totalBots || !topic || !roles || !worldBrain) {
return res.status(400).json({ error: 'Invalid request: missing required fields' });
}
const ai = new GoogleGenAI({ apiKey: req.geminiApiKey });
const botsPerRole = Math.ceil(totalBots / roles.length);
const allBots = [];
let botIdCounter = 1;
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.write(`data: ${JSON.stringify({ type: 'start', totalRoles: roles.length })}\n\n`);
for (const role of roles) {
res.write(`data: ${JSON.stringify({ type: 'role-start', role, botsPerRole })}\n\n`);
const tools = [{ googleSearch: {} }];
const config = {
thinkingConfig: { thinkingLevel: CONFIG.THINKING_LEVEL },
tools,
temperature: 0.4,
maxOutputTokens: CONFIG.MAX_OUTPUT_TOKENS_ROLE,
};
const contents = [{
role: 'user',
parts: [{
text: `Generate ${botsPerRole} independent ${role} bots for a virtual world simulation.
Topic: ${topic}
World Rules: ${JSON.stringify(worldBrain)}
Each bot must have:
- id (number)
- role (string: "${role}")
- name (unique human name)
- knowledge (array of 3-5 expertise areas)
- personality (one of: analytical/creative/critical/optimistic/detail-oriented/pragmatic)
- bias (string: what they focus on)
- confidence (number between 0.5-1.0)
Output ONLY a valid JSON array of ${botsPerRole} bot objects, no markdown.`,
}],
}];
const response = await ai.models.generateContent({
model: CONFIG.MODEL,
config,
contents,
});
const text = response.candidates[0].content.parts[0].text;
const bots = JSON.parse(text.replace(/```json\n?/g, '').replace(/```\n?/g, ''));
bots.forEach(bot => {
bot.id = botIdCounter++;
allBots.push(bot);
});
res.write(`data: ${JSON.stringify({ type: 'role-complete', role, botsGenerated: bots.length })}\n\n`);
await new Promise(resolve => setTimeout(resolve, 2000));
}
const finalBots = allBots.slice(0, totalBots);
botsData = {
worldBrain,
bots: finalBots,
metadata: {
totalBots: finalBots.length,
topic,
roles,
generatedAt: new Date().toISOString()
}
};
res.write(`data: ${JSON.stringify({ type: 'complete', bots: finalBots, metadata: botsData.metadata })}\n\n`);
res.end();
} catch (error) {
console.error('Bot generation error:', error);
res.write(`data: ${JSON.stringify({ type: 'error', error: 'Failed to generate bots' })}\n\n`);
res.end();
}
});
// Set bots endpoint with validation
app.post('/api/set-bots', (req, res) => {
try {
const { bots, metadata } = req.body;
const validation = validateBotData({ bots, metadata });
if (!validation.valid) {
console.error('Bot validation failed:', validation.error);
return res.status(400).json({ error: `Invalid bot data: ${validation.error}` });
}
botsData = {
worldBrain: metadata?.worldBrain || {},
bots,
metadata: metadata || {
totalBots: bots.length,
topic: 'Imported',
roles: [...new Set(bots.map(b => b.role))],
importedAt: new Date().toISOString()
}
};
console.log(`✅ Imported ${bots.length} bots to server (validated)`);
res.json({ success: true, botsCount: bots.length });
} catch (error) {
console.error('Error setting bots:', error);
res.status(500).json({ error: 'Failed to set bots' });
}
});
// Get bots endpoint
app.get('/api/bots', (req, res) => {
if (!botsData) {
return res.json({ bots: [], metadata: null });
}
res.json(botsData);
});
// Helper function for delays
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// Review Post with Batch Processing
app.post('/api/review-post', validateApiKey, async (req, res) => {
try {
const { postContent, batchSize = 10, cooldownMs = 3000, temperature = 0.4 } = req.body;
if (!botsData || !botsData.bots.length) {
return res.status(400).json({ error: 'No bots generated yet. Generate bots first.' });
}
const ai = new GoogleGenAI({ apiKey: req.geminiApiKey });
const bots = botsData.bots;
const allReviews = [];
const batches = [];
for (let i = 0; i < bots.length; i += batchSize) {
batches.push(bots.slice(i, i + batchSize));
}
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.write(`data: ${JSON.stringify({ type: 'start', totalBatches: batches.length, totalBots: bots.length })}\n\n`);
for (let i = 0; i < batches.length; i++) {
const batch = batches[i];
const batchNum = i + 1;
res.write(`data: ${JSON.stringify({ type: 'batch-start', batchNum, totalBatches: batches.length, botsInBatch: batch.length })}\n\n`);
try {
const botDescriptions = batch.map(b =>
`Bot ${b.id}: ${b.name} (${b.role}) - Personality: ${b.personality}, Focus: ${b.bias || 'general'}, Confidence: ${b.confidence}`
).join('\n');
const tools = [{ googleSearch: {} }];
const config = {
thinkingConfig: { thinkingLevel: CONFIG.THINKING_LEVEL },
tools,
temperature: temperature || 0.4,
maxOutputTokens: CONFIG.MAX_OUTPUT_TOKENS_REVIEW,
responseMimeType: 'application/json',
};
const contents = [{
role: 'user',
parts: [{
text: `You are simulating ${batch.length} independent AI bots reviewing a post.
BOTS:
${botDescriptions}
POST TO REVIEW:
${postContent}
Each bot must independently review this post based on their role, personality, and focus area.
Output ONLY a valid JSON array with ${batch.length} objects, one per bot:
[
{
"botId": 1,
"botName": "Alice",
"role": "Software Engineer",
"review": "Brief review in 1-2 sentences",
"score": 8,
"sentiment": "positive",
"keyPoints": ["point1", "point2"],
"suggestions": "One brief suggestion"
}
]
CRITICAL:
- Output ONLY the JSON array, nothing else
- No markdown, no explanations, no extra text
- Keep reviews SHORT (1-2 sentences max)
- Each review must be unique and independent
- Ensure all JSON is properly closed with brackets`,
}],
}];
const response = await ai.models.generateContent({
model: CONFIG.MODEL,
config,
contents,
});
if (!response.candidates || !response.candidates[0]) {
throw new Error('No response from Gemini API');
}
const candidate = response.candidates[0];
if (!candidate.content || !candidate.content.parts || !candidate.content.parts[0]) {
throw new Error('Invalid response structure from Gemini');
}
const text = candidate.content.parts[0].text;
let cleanedText = text.trim();
cleanedText = cleanedText.replace(/```json\n?/g, '').replace(/```\n?/g, '');
cleanedText = cleanedText.trim();
const jsonMatch = cleanedText.match(/\[[\s\S]*\]/);
if (!jsonMatch) {
throw new Error('No JSON array found in response. Try reducing batch size to 5-10 bots.');
}
const reviews = JSON.parse(jsonMatch[0]);
allReviews.push(...reviews);
res.write(`data: ${JSON.stringify({ type: 'batch-complete', batchNum, reviews: reviews.length })}\n\n`);
} catch (error) {
console.error(`[Batch ${batchNum}] Error:`, error.message);
res.write(`data: ${JSON.stringify({ type: 'batch-error', batchNum, error: error.message })}\n\n`);
}
if (i < batches.length - 1) {
res.write(`data: ${JSON.stringify({ type: 'cooldown', ms: cooldownMs })}\n\n`);
await wait(cooldownMs);
}
}
res.write(`data: ${JSON.stringify({ type: 'generating-summary', totalReviews: allReviews.length })}\n\n`);
if (allReviews.length === 0) {
res.write(`data: ${JSON.stringify({ type: 'error', error: 'No reviews were successfully generated. Please try again with a smaller batch size or check your API key.' })}\n\n`);
res.end();
return;
}
const avgScore = (allReviews.reduce((sum, r) => sum + r.score, 0) / allReviews.length).toFixed(2);
const sentimentCounts = allReviews.reduce((acc, r) => {
acc[r.sentiment] = (acc[r.sentiment] || 0) + 1;
return acc;
}, {});
const tools = [{ googleSearch: {} }];
const config = {
thinkingConfig: { thinkingLevel: CONFIG.THINKING_LEVEL },
tools,
temperature: 0.3,
maxOutputTokens: CONFIG.MAX_OUTPUT_TOKENS_REVIEW,
responseMimeType: 'application/json',
};
const contents = [{
role: 'user',
parts: [{
text: `Analyze ${allReviews.length} bot reviews and create a comprehensive summary.
POST:
${postContent}
REVIEWS DATA:
- Average Score: ${avgScore}/10
- Sentiment: ${JSON.stringify(sentimentCounts)}
- Sample Reviews: ${JSON.stringify(allReviews.slice(0, 10))}
Create a final summary with:
1. Overall verdict (good/bad/mixed)
2. Top 3 strengths
3. Top 3 weaknesses
4. Key improvement suggestions
5. Role-specific insights
6. Actionable next steps
Output as JSON:
{
"overallVerdict": "string",
"averageScore": ${avgScore},
"sentiment": ${JSON.stringify(sentimentCounts)},
"strengths": ["str1", "str2", "str3"],
"weaknesses": ["weak1", "weak2", "weak3"],
"suggestions": ["sug1", "sug2", "sug3"],
"roleInsights": {"role": "insight"},
"nextSteps": ["step1", "step2"]
}
Output ONLY valid JSON, no markdown.`,
}],
}];
const summaryResponse = await ai.models.generateContent({
model: CONFIG.MODEL,
config,
contents,
});
const summaryText = summaryResponse.candidates[0].content.parts[0].text;
let cleanedSummary = summaryText.trim().replace(/```json\n?/g, '').replace(/```\n?/g, '').trim();
const summaryMatch = cleanedSummary.match(/\{[\s\S]*\}/);
const summary = summaryMatch ? JSON.parse(summaryMatch[0]) : { overallVerdict: 'Analysis complete', averageScore: avgScore };
res.write(`data: ${JSON.stringify({ type: 'complete', reviews: allReviews, summary })}\n\n`);
res.end();
} catch (error) {
console.error('Review error:', error);
res.write(`data: ${JSON.stringify({ type: 'error', error: error.message })}\n\n`);
res.end();
}
});
// Serve frontend in production
if (process.env.NODE_ENV === 'production') {
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
}
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Error:', err);
res.status(500).json({
error: process.env.NODE_ENV === 'production'
? 'Internal server error'
: err.message
});
});
app.listen(PORT, () => {
console.log(`\n🚀 Virtual World Bot Reviewer API (Production)`);
console.log(`📡 Server: http://localhost:${PORT}`);
console.log(`🔑 Model: ${CONFIG.MODEL}`);
console.log(`🔒 Security: Enabled`);
console.log(`⚡ Rate Limiting: ${process.env.RATE_LIMIT_MAX_REQUESTS} requests per ${process.env.RATE_LIMIT_WINDOW_MS}ms\n`);
});