Rooni commited on
Commit
180c75f
·
verified ·
1 Parent(s): 4496c0d

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +55 -89
server.js CHANGED
@@ -5,141 +5,107 @@ const axios = require('axios');
5
  const app = express();
6
  app.use(express.json());
7
 
8
- const openai_key = process.env.OPENAI_KEY;
 
 
9
 
10
  const limiter = rateLimit({
11
- windowMs: 5 * 1000, // 30 секунд
12
- max: 1, // лимит каждые 30 секунд на IP
13
  handler: function (req, res) {
14
  return res.status(429).json("wait");
15
  },
16
  });
17
 
18
- // Применение ограничителя скорости перед обработчиком маршрута /generate
19
- app.use('/pl', limiter);
20
-
21
- const start = `${process.env.start}`;
22
 
23
- app.post('/cr', async (req, res) => {
24
- res.json({ content: `{"whate":"🪨", "howe":"ОБНОВИТЕСЬ", "text":"Текущая версия приложения устарела. Установите новую из нашего телеграм канала: @yufi_ru", "succ":"победа", "what":"Версию", "how":"Обновите", "howl":"@yufi_ru"}` });
 
 
25
  });
26
 
27
- app.post('/pl', async (req, res) => {
28
- const prompt = req.body.prompt;
29
- const apiKey = req.body.api || openai_key;
30
-
31
- if (!prompt) {
32
- return res.status(400).json("wait"); // Не удалось принять данные
33
- }
34
 
 
35
  try {
36
- const response = await axios.post('https://openai-gemini-iota.vercel.app/v1/chat/completions', {
37
- messages: [{'role': 'system', 'content': start}, {'role': 'user', 'content': prompt}],
 
 
 
 
38
  max_tokens: 2000,
39
- temperature: 0.8,
40
- // presence_penalty: 0.0,
41
- //frequency_penalty: -0.1,
42
- //model: "gemini-1.5-pro-latest",
43
- model: "deepseek-chat",
44
- //model: "gemini-1.5-flash-latest",
45
  }, {
46
  headers: {
47
- 'Authorization': `Bearer ${apiKey}`,
48
  'Content-Type': 'application/json',
49
  },
50
  });
51
 
52
- if (response.data.choices && response.data.choices.length > 0 && response.data.choices[0].message) {
53
- const content = response.data.choices[0].message.content.trim();
54
- //console.log(`\n---\nПользователь: ${prompt}\n Ответ:\n ${content}`);
55
- res.json({ content });
56
- } else {
57
- res.status(500).json({ content: 'errora' }); // Ошибка прочтения
58
- }
59
  } catch (error) {
60
  console.error(error);
61
- res.status(500).json({ content: 'errorb' }); // ❌ Произошла ошибка сервера при генерации.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  }
63
  });
64
 
65
  app.post('/cre', async (req, res) => {
66
  const prompt = req.body.prompt;
67
- const apiKey = req.body.api || openai_key;
68
 
69
  if (!prompt) {
70
  return res.status(400).json("wait"); // Не удалось принять данные
71
  }
72
 
73
  try {
74
- const response = await axios.post('https://vercel.com/roonis-projects/openai-gemini/v1/chat/completions', {
75
- messages: [{'role': 'system', 'content': start}, {'role': 'system', 'content': 'И ОБЯЗАТЕЛЬНО, всегда в конце "text" проси обновить приложение, уведомляя о том, что скоро в жтой версии перестанешь отвечать!'}, {'role': 'user', 'content': prompt}],
76
- max_tokens: 2000,
77
- temperature: 0.6,
78
- // presence_penalty: 0.0,
79
- //frequency_penalty: -0.1,
80
- model: "gemini-1.5-pro-002",
81
- // model: "deepseek-chat",
82
- //model: "gemini-1.5-flash-latest",
83
- }, {
84
- headers: {
85
- 'Authorization': `Bearer ${apiKey}`,
86
- 'Content-Type': 'application/json',
87
- },
88
- });
89
-
90
- if (response.data.choices && response.data.choices.length > 0 && response.data.choices[0].message) {
91
- const content = response.data.choices[0].message.content.trim();
92
- // console.log(`\n---\nПользователь: ${prompt}\n Ответ:\n ${content}`);
93
- res.json({ content });
94
- } else {
95
- res.status(500).json({ content: 'errora' }); // Ошибка прочтения
96
- }
97
- } catch (error) {
98
- console.error(error);
99
- res.status(500).json({ content: 'errorb' }); // ❌ Произошла ошибка сервера при генерации.
100
  }
101
  });
102
 
103
  app.post('/crebeta', async (req, res) => {
104
  const prompt = req.body.prompt;
105
- const apiKey = req.body.api || openai_key;
106
 
107
  if (!prompt) {
108
  return res.status(400).json("wait"); // Не удалось принять данные
109
  }
110
 
111
  try {
112
- const response = await axios.post('https://geminiyufi.vercel.app/v1/chat/completions', {
113
- messages: [{'role': 'system', 'content': start}, {'role': 'user', 'content': prompt}],
114
- max_tokens: 2000,
115
- temperature: 0.24,
116
- // presence_penalty: 0.0,
117
- //frequency_penalty: -0.1,
118
- model: "gemini-1.5-pro-002",
119
- // model: "gemma-2-27b-it",
120
- //model: "gemini-1.5-flash-latest",
121
- }, {
122
- headers: {
123
- 'Authorization': `Bearer ${apiKey}`,
124
- 'Content-Type': 'application/json',
125
- },
126
- });
127
-
128
- if (response.data.choices && response.data.choices.length > 0 && response.data.choices[0].message) {
129
- const content = response.data.choices[0].message.content.trim();
130
- // console.log(`\n---\nПользователь: ${prompt}\n Ответ:\n ${content}`);
131
- res.json({ content });
132
- } else {
133
- res.status(500).json({ content: 'errora' }); // Ошибка прочтения
134
- }
135
- } catch (error) {
136
- console.error(error);
137
- res.status(500).json({ content: 'errorb' }); // ❌ Произошла ошибка сервера при генерации.
138
  }
139
  });
140
 
141
-
142
  const port = 7860;
143
  app.listen(port, () => {
144
  console.log(`API сервер запущен на порту ${port}`);
145
- });
 
5
  const app = express();
6
  app.use(express.json());
7
 
8
+ const apiKeys = process.env.OPENAI_KEYS.split(',');
9
+
10
+ const start = process.env.start;
11
 
12
  const limiter = rateLimit({
13
+ windowMs: 5 * 1000, // 5 секунд
14
+ max: 1, // лимит на 1 запрос каждые 5 секунд на IP
15
  handler: function (req, res) {
16
  return res.status(429).json("wait");
17
  },
18
  });
19
 
20
+ // Применение ограничителя скорости перед обработчиком маршрута /pl
21
+ app.use('/pl', limiter);
 
 
22
 
23
+ app.post('/cr', (req, res) => {
24
+ res.json({
25
+ content: '{"whate":"🪨","howe":"ОБНОВИТЕСЬ","text":"Текущая версия приложения устарела. Установите новую из нашего телеграм канала: @yufi_ru","succ":"победа","what":"Версию","how":"Обновите","howl":"@yufi_ru"}'
26
+ });
27
  });
28
 
29
+ // Функция для получения случайного API ключа
30
+ const getRandomApiKey = () => apiKeys[Math.floor(Math.random() * apiKeys.length)];
 
 
 
 
 
31
 
32
+ const generateResponse = async (url, prompt, additionalMessages, temperature) => {
33
  try {
34
+ const response = await axios.post(url, {
35
+ messages: [
36
+ { role: 'system', content: start },
37
+ ...additionalMessages,
38
+ { role: 'user', content: prompt }
39
+ ],
40
  max_tokens: 2000,
41
+ temperature: temperature,
42
+ model: additionalMessages.length > 0 ? "gemini-1.5-pro-002" : "deepseek-chat",
 
 
 
 
43
  }, {
44
  headers: {
45
+ 'Authorization': `Bearer ${getRandomApiKey()}`,
46
  'Content-Type': 'application/json',
47
  },
48
  });
49
 
50
+ return response.data.choices && response.data.choices.length > 0 && response.data.choices[0].message
51
+ ? response.data.choices[0].message.content.trim()
52
+ : null;
53
+
 
 
 
54
  } catch (error) {
55
  console.error(error);
56
+ throw new Error('Error during generation');
57
+ }
58
+ };
59
+
60
+ app.post('/pl', async (req, res) => {
61
+ const prompt = req.body.prompt;
62
+
63
+ if (!prompt) {
64
+ return res.status(400).json("wait"); // Не удалось принять данные
65
+ }
66
+
67
+ try {
68
+ const content = await generateResponse('https://openai-gemini-iota.vercel.app/v1/chat/completions', prompt, [], 0.8);
69
+ content ? res.json({ content }) : res.status(500).json({ content: 'errora' });
70
+ } catch {
71
+ res.status(500).json({ content: 'errorb' });
72
  }
73
  });
74
 
75
  app.post('/cre', async (req, res) => {
76
  const prompt = req.body.prompt;
 
77
 
78
  if (!prompt) {
79
  return res.status(400).json("wait"); // Не удалось принять данные
80
  }
81
 
82
  try {
83
+ const additionalMessages = [
84
+ { role: 'system', content: 'И ОБЯЗАТЕЛЬНО, всегда в конце "text" проси обновить приложение, уведомляя о том, что скоро в жтой версии перестанешь отвечать!' }
85
+ ];
86
+ const content = await generateResponse('https://vercel.com/roonis-projects/openai-gemini/v1/chat/completions', prompt, additionalMessages, 0.6);
87
+ content ? res.json({ content }) : res.status(500).json({ content: 'errora' });
88
+ } catch {
89
+ res.status(500).json({ content: 'errorb' });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  }
91
  });
92
 
93
  app.post('/crebeta', async (req, res) => {
94
  const prompt = req.body.prompt;
 
95
 
96
  if (!prompt) {
97
  return res.status(400).json("wait"); // Не удалось принять данные
98
  }
99
 
100
  try {
101
+ const content = await generateResponse('https://geminiyufi.vercel.app/v1/chat/completions', prompt, [], 0.24);
102
+ content ? res.json({ content }) : res.status(500).json({ content: 'errora' });
103
+ } catch {
104
+ res.status(500).json({ content: 'errorb' });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  }
106
  });
107
 
 
108
  const port = 7860;
109
  app.listen(port, () => {
110
  console.log(`API сервер запущен на порту ${port}`);
111
+ });