kspchary commited on
Commit
054e177
·
verified ·
1 Parent(s): aa4435e

Upload server.js

Browse files
Files changed (1) hide show
  1. server.js +27 -168
server.js CHANGED
@@ -57,7 +57,7 @@ if (cluster.isPrimary) {
57
  // 1. Rate Limiting for Fairness (Essential for 10k+ Users)
58
  const limiter = rateLimit({
59
  windowMs: 15 * 60 * 1000, // 15 minutes
60
- max: 50, // limit each IP to 50 requests per window
61
  message: { error: "Too many requests. Please wait a moment." },
62
  standardHeaders: true,
63
  legacyHeaders: false,
@@ -91,7 +91,7 @@ if (cluster.isPrimary) {
91
  }
92
 
93
  const SYSTEM_PROMPTS = {
94
- vibe: "You are an expert full-stack developer and friendly Davii ai assistant. Be professional, direct, and kind.",
95
  ui: "You are a world-class UI/UX and CSS expert. Focus on modern aesthetics, glassmorphism, animations, and beautiful responsive layouts.",
96
  security: "You are a Cyber-Security Teacher and Researcher. ...",
97
  logic: "You are a backend architect specializing in algorithms ...",
@@ -131,13 +131,6 @@ Rules:
131
  "codellama/CodeLlama-7b-hf"
132
  ];
133
 
134
- const VISION_MODELS = [
135
- "llava-hf/llava-1.5-7b-hf",
136
- "Qwen/Qwen2-VL-7B-Instruct",
137
- "meta-llama/Llama-3.2-11B-Vision-Instruct",
138
- "llava-hf/llava-v1.6-vicuna-7b-hf"
139
- ];
140
-
141
  // Worker-Local Queue (Scales with number of workers)
142
  const requestQueue = [];
143
  let activeRequests = 0;
@@ -160,89 +153,6 @@ Rules:
160
  });
161
 
162
  async function callHuggingFace(model, messages, res, isInternalThought = false) {
163
- const isVisionModel = VISION_MODELS.includes(model);
164
-
165
- // Stage 1: Try OpenAI-compatible endpoint
166
- let API_URL = isVisionModel
167
- ? `https://api-inference.huggingface.co/models/${model}/v1/chat/completions`
168
- : `https://router.huggingface.co/v1/chat/completions`;
169
-
170
- console.log(`[Worker ${process.pid}] [Stage 1] Calling ${isVisionModel ? 'Vision' : 'Text'} Model: ${model}`);
171
-
172
- try {
173
- let response = await fetch(API_URL, {
174
- method: "POST",
175
- headers: {
176
- "Authorization": `Bearer ${HF_TOKEN}`,
177
- "Content-Type": "application/json"
178
- },
179
- body: JSON.stringify({
180
- model: model,
181
- messages: messages,
182
- max_tokens: 5000,
183
- temperature: 0.7,
184
- stream: true
185
- })
186
- });
187
-
188
- // Stage 2 Fallback: If vision model and Stage 1 fails with specific errors, try native format
189
- if (isVisionModel && (!response.ok || response.status === 404)) {
190
- console.log(`[Worker ${process.pid}] [Stage 1 Failed] Falling back to Direct Inference for: ${model}`);
191
- const nativeApiUrl = `https://api-inference.huggingface.co/models/${model}`;
192
-
193
- // Construct native payload (non-streaming, basic)
194
- const lastUserMessage = messages.findLast(m => m.role === "user");
195
- const textContent = Array.isArray(lastUserMessage.content)
196
- ? lastUserMessage.content.find(c => c.type === "text")?.text
197
- : lastUserMessage.content;
198
- const imageContent = Array.isArray(lastUserMessage.content)
199
- ? lastUserMessage.content.find(c => c.type === "image_url")?.image_url?.url
200
- : null;
201
-
202
- // Native format: some models want {inputs: {image: ..., text: ...}}, others just binary
203
- const nativePayload = imageContent
204
- ? { inputs: textContent, image: imageContent.includes("base64,") ? imageContent.split("base64,")[1] : imageContent }
205
- : { inputs: textContent };
206
-
207
- console.log(`[Worker ${process.pid}] [Stage 2] Calling Native API: ${nativeApiUrl}`);
208
-
209
- const fallbackResponse = await fetch(nativeApiUrl, {
210
- method: "POST",
211
- headers: {
212
- "Authorization": `Bearer ${HF_TOKEN}`,
213
- "Content-Type": "application/json"
214
- },
215
- body: JSON.stringify(nativePayload)
216
- });
217
-
218
- if (fallbackResponse.ok) {
219
- const result = await fallbackResponse.json();
220
- let generatedText = Array.isArray(result) ? result[0].generated_text : (result.generated_text || JSON.stringify(result));
221
-
222
- // Simple stream simulation for fallback
223
- res.write(`data: ${JSON.stringify({ choices: [{ delta: { content: generatedText } }] })}\n\n`);
224
- res.write("data: [DONE]\n\n");
225
- return generatedText;
226
- }
227
- }
228
-
229
- if (response.status === 429) throw new Error("RATE_LIMIT");
230
- if (response.status === 503) throw new Error("MODEL_LOADING");
231
-
232
- if (!response.ok) {
233
- const err = await response.json().catch(() => ({}));
234
- console.error(`[Worker ${process.pid}] HF API Error [${response.status}]:`, JSON.stringify(err, null, 2));
235
- throw new Error(err.error?.message || err.error || `HF Error ${response.status}`);
236
- }
237
-
238
- return streamResponse(response, res, isInternalThought);
239
- } catch (error) {
240
- console.error(`[Worker ${process.pid}] Call Error:`, error.message);
241
- throw error;
242
- }
243
- }
244
-
245
- async function callHuggingFaceRouterInternal(model, messages, res, isInternalThought = false) {
246
  const API_URL = `https://router.huggingface.co/v1/chat/completions`;
247
  const response = await fetch(API_URL, {
248
  method: "POST",
@@ -258,12 +168,15 @@ Rules:
258
  stream: true
259
  })
260
  });
261
- if (!response.ok) throw new Error(`Router Fallback Failed: ${response.status}`);
262
- return streamResponse(response, res, isInternalThought);
263
- }
264
 
265
- async function streamResponse(response, res, isInternalThought) {
266
- if (!isInternalThought && !res.headersSent) {
 
 
 
 
 
 
267
  res.setHeader('Content-Type', 'text/event-stream');
268
  res.setHeader('Cache-Control', 'no-cache');
269
  res.setHeader('Connection', 'keep-alive');
@@ -354,41 +267,14 @@ Rules:
354
  }
355
 
356
  async function handleVibeRequest(req, res) {
357
- const { prompt, mode = "vibe", history = [], sessionId = "default", images = [] } = req.body;
358
- if (!prompt && images.length === 0) return res.status(400).json({ error: "Prompt or images are required" });
359
-
360
- const systemContent = String(SYSTEM_PROMPTS[mode] || SYSTEM_PROMPTS.vibe);
361
-
362
- // Prepare messages
363
- let messages = [];
364
-
365
- // Handle Multimodal (Images + Text)
366
- if (images.length > 0) {
367
- const userContent = [];
368
-
369
- // Standard multimodal format: First text, then images
370
- userContent.push({ type: "text", text: `${systemContent}\n\n${prompt || "What is in this image?"}` });
371
-
372
- images.forEach(img => {
373
- // High-precision base64 check - ensure no weird line breaks or spaces
374
- const cleanImg = img.trim();
375
- userContent.push({
376
- type: "image_url",
377
- image_url: { url: cleanImg }
378
- });
379
- });
380
-
381
- messages = [{ role: "user", content: userContent }];
382
- } else {
383
- messages = [{ role: "system", content: systemContent }, ...history, { role: "user", content: prompt }];
384
- }
385
 
386
- const currentModelList = images.length > 0 ? VISION_MODELS : (mode === 'deepseek' ? DEEPSEEK_MODELS : MODELS);
 
 
387
  let lastError = null;
388
 
389
- // For logging purposes
390
- const displayPrompt = prompt || (images.length > 0 ? "[Image Attachment]" : "");
391
-
392
  for (let i = 0; i < currentModelList.length; i++) {
393
  const model = currentModelList[i];
394
  try {
@@ -401,11 +287,9 @@ Rules:
401
  if (!isAgentMode) {
402
  finalText = await callHuggingFace(model, messages, res, false);
403
  } else {
404
- if (!res.headersSent) {
405
- res.setHeader('Content-Type', 'text/event-stream');
406
- res.setHeader('Cache-Control', 'no-cache');
407
- res.setHeader('Connection', 'keep-alive');
408
- }
409
  headersSent = true;
410
 
411
  while (loopCount < maxLoops) {
@@ -447,7 +331,7 @@ Rules:
447
  try {
448
  const logEntry = {
449
  timestamp: new Date().toISOString(),
450
- prompt: displayPrompt,
451
  response: finalText,
452
  mode,
453
  model: model,
@@ -477,44 +361,19 @@ Rules:
477
  return;
478
  } catch (error) {
479
  lastError = error;
480
- console.error(`[Worker ${process.pid}] Model ${model} failed:`, error.message);
481
- // Continue to next model in currentModelList
482
- }
483
- }
484
-
485
- if (images.length > 0) {
486
- console.log(`[Worker ${process.pid}] All vision models failed. Attempting text-only fallback.`);
487
- try {
488
- const fallbackModel = MODELS[0]; // Use first reliable text model
489
- const warningMsg = "\n\n*(Note: Image processing is temporarily unavailable. Responding based on your text prompt instead...)*\n\n";
490
-
491
- // Construct a clean text-only message list
492
- const textOnlyMessages = [{ role: "system", content: systemContent }, ...history, { role: "user", content: prompt || "Describe the attached images (Note: Processing unavailable)" }];
493
-
494
- // Stream the response with a prefix
495
- if (!res.headersSent) {
496
- res.setHeader('Content-Type', 'text/event-stream');
497
  }
498
- res.write(`data: ${JSON.stringify({ token: warningMsg })}\n\n`);
499
-
500
- await callHuggingFace(fallbackModel, textOnlyMessages, res, false);
501
- return;
502
- } catch (fallbackErr) {
503
- console.error(`[Worker ${process.pid}] Global Fallback Failed:`, fallbackErr.message);
504
  }
505
  }
506
 
507
  const finalErrorMessage = lastError?.message === "RATE_LIMIT"
508
  ? "Server busy (10k+ load cap reached). Please wait a few seconds."
509
- : `Image Processing Error: ${lastError?.message}. Please try again later or with a different image.`;
510
-
511
- if (!res.headersSent) {
512
- res.status(503).json({ error: finalErrorMessage });
513
- } else {
514
- res.write(`data: ${JSON.stringify({ error: finalErrorMessage })}\n\n`);
515
- res.write("data: [DONE]\n\n");
516
- res.end();
517
- }
518
  }
519
 
520
  app.post("/image", async (req, res) => {
@@ -538,7 +397,7 @@ Rules:
538
  }
539
  });
540
 
541
- app.get("/", (req, res) => res.send(`Davii ai [Worker ${process.pid}] is powering the vibe! 🛸`));
542
 
543
  const PORT = 7860;
544
  app.listen(PORT, () => console.log(`[Worker ${process.pid}] Multi-core node running on port ${PORT}`));
 
57
  // 1. Rate Limiting for Fairness (Essential for 10k+ Users)
58
  const limiter = rateLimit({
59
  windowMs: 15 * 60 * 1000, // 15 minutes
60
+ max: 10000, // Practically unlimited: 10,000 requests per 15 mins
61
  message: { error: "Too many requests. Please wait a moment." },
62
  standardHeaders: true,
63
  legacyHeaders: false,
 
91
  }
92
 
93
  const SYSTEM_PROMPTS = {
94
+ vibe: "You are an expert full-stack developer and friendly Prachee ai assistant. Be professional, direct, and kind.",
95
  ui: "You are a world-class UI/UX and CSS expert. Focus on modern aesthetics, glassmorphism, animations, and beautiful responsive layouts.",
96
  security: "You are a Cyber-Security Teacher and Researcher. ...",
97
  logic: "You are a backend architect specializing in algorithms ...",
 
131
  "codellama/CodeLlama-7b-hf"
132
  ];
133
 
 
 
 
 
 
 
 
134
  // Worker-Local Queue (Scales with number of workers)
135
  const requestQueue = [];
136
  let activeRequests = 0;
 
153
  });
154
 
155
  async function callHuggingFace(model, messages, res, isInternalThought = false) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  const API_URL = `https://router.huggingface.co/v1/chat/completions`;
157
  const response = await fetch(API_URL, {
158
  method: "POST",
 
168
  stream: true
169
  })
170
  });
 
 
 
171
 
172
+ if (response.status === 429) throw new Error("RATE_LIMIT");
173
+ if (response.status === 503) throw new Error("MODEL_LOADING");
174
+ if (!response.ok) {
175
+ const err = await response.json().catch(() => ({}));
176
+ throw new Error(err.error?.message || `HF Error ${response.status}`);
177
+ }
178
+
179
+ if (!isInternalThought) {
180
  res.setHeader('Content-Type', 'text/event-stream');
181
  res.setHeader('Cache-Control', 'no-cache');
182
  res.setHeader('Connection', 'keep-alive');
 
267
  }
268
 
269
  async function handleVibeRequest(req, res) {
270
+ const { prompt, mode = "vibe", history = [], sessionId = "default" } = req.body;
271
+ if (!prompt) return res.status(400).json({ error: "Prompt is required" });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
 
273
+ const systemContent = SYSTEM_PROMPTS[mode] || SYSTEM_PROMPTS.vibe;
274
+ let messages = [{ role: "system", content: systemContent }, ...history, { role: "user", content: prompt }];
275
+ const currentModelList = mode === 'deepseek' ? DEEPSEEK_MODELS : MODELS;
276
  let lastError = null;
277
 
 
 
 
278
  for (let i = 0; i < currentModelList.length; i++) {
279
  const model = currentModelList[i];
280
  try {
 
287
  if (!isAgentMode) {
288
  finalText = await callHuggingFace(model, messages, res, false);
289
  } else {
290
+ res.setHeader('Content-Type', 'text/event-stream');
291
+ res.setHeader('Cache-Control', 'no-cache');
292
+ res.setHeader('Connection', 'keep-alive');
 
 
293
  headersSent = true;
294
 
295
  while (loopCount < maxLoops) {
 
331
  try {
332
  const logEntry = {
333
  timestamp: new Date().toISOString(),
334
+ prompt,
335
  response: finalText,
336
  mode,
337
  model: model,
 
361
  return;
362
  } catch (error) {
363
  lastError = error;
364
+ if (res.headersSent) {
365
+ res.write(`data: ${JSON.stringify({ token: "\n\n[System] All models busy. Retrying later..." })}\n\n`);
366
+ res.write("data: [DONE]\n\n");
367
+ return res.end();
 
 
 
 
 
 
 
 
 
 
 
 
 
368
  }
 
 
 
 
 
 
369
  }
370
  }
371
 
372
  const finalErrorMessage = lastError?.message === "RATE_LIMIT"
373
  ? "Server busy (10k+ load cap reached). Please wait a few seconds."
374
+ : `System logic error or busy models. Error: ${lastError?.message}`;
375
+
376
+ res.status(503).json({ error: finalErrorMessage });
 
 
 
 
 
 
377
  }
378
 
379
  app.post("/image", async (req, res) => {
 
397
  }
398
  });
399
 
400
+ app.get("/", (req, res) => res.send(`Prachee ai [Worker ${process.pid}] is powering the vibe! 🛸`));
401
 
402
  const PORT = 7860;
403
  app.listen(PORT, () => console.log(`[Worker ${process.pid}] Multi-core node running on port ${PORT}`));