Anonizy commited on
Commit
bfc6ae9
·
verified ·
1 Parent(s): ffcdf20

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +29 -18
server.js CHANGED
@@ -1,5 +1,6 @@
1
  const express = require('express');
2
  const http = require('http');
 
3
  const proxy = require('express-http-proxy');
4
  const socketIo = require('socket.io');
5
  const moment = require('moment-timezone');
@@ -9,14 +10,33 @@ const server = http.createServer(app);
9
  const io = socketIo(server);
10
 
11
  const targetUrl = 'https://api.openai.com';
12
- const openaiKeys = process.env.OPENAI_KEYS.split(','); // Assume keys are separated by commas
13
- let currentKeyIndex = 0;
14
  const port = 7860;
15
  const baseUrl = getExternalUrl(process.env.SPACE_ID);
16
 
17
  let requestDetails = [];
18
  let ipRequestCounts = {};
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  io.on('connection', (socket) => {
21
  console.log('A user connected to the websocket for live logs.');
22
  });
@@ -26,13 +46,6 @@ function logAndEmit(message) {
26
  io.emit('log', message);
27
  }
28
 
29
- function getNextKey() {
30
- // This function cycles through the keys in a round-robin manner
31
- const key = openaiKeys[currentKeyIndex];
32
- currentKeyIndex = (currentKeyIndex + 1) % openaiKeys.length;
33
- return key;
34
- }
35
-
36
  app.use('/api', (req, res, next) => {
37
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
38
  ipRequestCounts[ip] = (ipRequestCounts[ip] || 0) + 1;
@@ -52,16 +65,14 @@ app.use('/api', (req, res, next) => {
52
  next();
53
  }, proxy(targetUrl, {
54
  proxyReqOptDecorator: function(proxyReqOpts, srcReq) {
55
- proxyReqOpts.headers['Authorization'] = 'Bearer ' + getNextKey();
56
- return proxyReqOpts;
57
- },
58
- userResDecorator: function(proxyRes, proxyResData, userReq, userRes) {
59
- // Check response for indication of invalid key
60
- if (proxyRes.statusCode === 401 || proxyRes.statusCode === 403) {
61
- logAndEmit(`Error detected with API key, switching keys...`);
62
- getNextKey(); // Immediately get next key to avoid using the same failed key
63
  }
64
- return proxyResData; // Pass through the original response data
65
  }
66
  }));
67
 
 
1
  const express = require('express');
2
  const http = require('http');
3
+ const axios = require('axios');
4
  const proxy = require('express-http-proxy');
5
  const socketIo = require('socket.io');
6
  const moment = require('moment-timezone');
 
10
  const io = socketIo(server);
11
 
12
  const targetUrl = 'https://api.openai.com';
13
+ const openaiKeys = process.env.OPENAI_KEYS.split(',');
14
+ let validKeys = [];
15
  const port = 7860;
16
  const baseUrl = getExternalUrl(process.env.SPACE_ID);
17
 
18
  let requestDetails = [];
19
  let ipRequestCounts = {};
20
 
21
+ async function validateKeys() {
22
+ const testUrl = 'https://api.openai.com/v1/models';
23
+ validKeys = [];
24
+ for (let key of openaiKeys) {
25
+ try {
26
+ await axios.get(testUrl, { headers: { 'Authorization': `Bearer ${key}` } });
27
+ validKeys.push(key); // Add valid key to the array
28
+ console.log(`Key validated successfully: ${key}`);
29
+ } catch (error) {
30
+ console.log(`Key validation failed for: ${key}`, error.message);
31
+ }
32
+ }
33
+ if (validKeys.length === 0) {
34
+ console.log("No valid API keys available.");
35
+ }
36
+ }
37
+ validateKeys();
38
+ setInterval(validateKeys, 3600000); // Validate keys every hour
39
+
40
  io.on('connection', (socket) => {
41
  console.log('A user connected to the websocket for live logs.');
42
  });
 
46
  io.emit('log', message);
47
  }
48
 
 
 
 
 
 
 
 
49
  app.use('/api', (req, res, next) => {
50
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
51
  ipRequestCounts[ip] = (ipRequestCounts[ip] || 0) + 1;
 
65
  next();
66
  }, proxy(targetUrl, {
67
  proxyReqOptDecorator: function(proxyReqOpts, srcReq) {
68
+ if (validKeys.length > 0) {
69
+ proxyReqOpts.headers['Authorization'] = 'Bearer ' + validKeys[0];
70
+ } else {
71
+ console.error("No valid API keys. Check server logs for details.");
72
+ srcReq.res.status(500).send('API key error. Please try again later.');
73
+ return null;
 
 
74
  }
75
+ return proxyReqOpts;
76
  }
77
  }));
78