Spaces:
Sleeping
Sleeping
const express = require('express'); | |
const rateLimit = require('express-rate-limit'); | |
const axios = require('axios'); | |
const app = express(); | |
app.use(express.json()); | |
// Доверие к одному прокси (например, Heroku) | |
app.set('trust proxy', 1); | |
const openai_keys = process.env.OPENAI_KEY.split(','); | |
function getRandomApiKey() { | |
const randomIndex = Math.floor(Math.random() * openai_keys.length); | |
return openai_keys[randomIndex]; | |
} | |
const limiter = rateLimit({ | |
windowMs: 5 * 1000, // 5 секунд | |
max: 1, // лимит каждые 5 секунд на IP | |
handler: function (req, res) { | |
return res.status(429).json("wait"); | |
}, | |
}); | |
// Применение ограничителя скорости перед обработчиком маршрута /pl и /crebeta | |
app.use('/pl', limiter); | |
app.use('/plbeta', limiter); | |
const start = `${process.env.start}`; | |
const startconnect = `${process.env.startconnect}`; | |
app.post('/update', async (req, res) => { | |
res.json({ content: `{"error":"", "title":"Требуется обновление", "text":"Текущая версия приложения устарела. Установите новую из нашего телеграм канала: @yufi_ru", "okb":"Обновить", "oklink":"https://t.me/yufi_ru", "cancelable":"false"` }); | |
}); | |
app.post('/pl', async (req, res) => { | |
const prompt = req.body.prompt; | |
const apiKey = req.body.api || getRandomApiKey(); | |
const prs = ""; | |
if (req.body.mode = "1") { | |
prs = start; | |
}else{ | |
prs = startconnect; | |
} | |
if (!prompt) { | |
return res.status(400).json("wait"); // Не удалось принять данные | |
} | |
try { | |
const response = await axios.post('https://openai-gemini-iota.vercel.app/v1/chat/completions', { | |
messages: [{'role': 'system', 'content': prs}, {'role': 'user', 'content': prompt}], | |
max_tokens: 2000, | |
temperature: 0.19, | |
model: "gemini-1.5-pro-001", | |
}, { | |
headers: { | |
'Authorization': `Bearer ${apiKey}`, | |
'Content-Type': 'application/json', | |
}, | |
}); | |
if (response.data.choices && response.data.choices.length > 0 && response.data.choices[0].message) { | |
const content = response.data.choices[0].message.content.trim(); | |
// console.log(`\n---\nПользователь: ${prompt}\n Ответ:\n ${content}`); | |
res.json({ content }); | |
} else { | |
//res.status(500).json({ content: 'errora' }); // Ошибка прочтения | |
res.json({ content: `{"error":"", "title":"Ошибка", "text":"Произошла ошибка на сервере. (Ошибка прочтения)", "okb":"Ок", "oklink":"", "cancelable":"true"` }) | |
} | |
} catch (error) { | |
console.error(error); | |
//res.status(500).json({ content: 'errorb' }); // ❌ Произошла ошибка сервера при генерации. | |
res.json({ content: `{"error":"", "title":"Ошибка", "text":"Произошла ошибка на сервере. (Ошибка при генерации)", "okb":"Ок", "oklink":"", "cancelable":"true"` }) | |
} | |
}); | |
app.post('/plbeta', async (req, res) => { | |
const prompt = req.body.prompt; | |
const apiKey = req.body.api || getRandomApiKey(); | |
const prs = ""; | |
if (req.body.mode = "1") { | |
prs = start; | |
}else{ | |
prs = startconnect; | |
} | |
if (!prompt) { | |
return res.status(400).json("wait"); // Не удалось принять данные | |
} | |
try { | |
const response = await axios.post('https://geminiyufi.vercel.app/v1/chat/completions', { | |
messages: [{'role': 'system', 'content': prs}, {'role': 'user', 'content': prompt}], | |
max_tokens: 2000, | |
temperature: 0.24, | |
model: "gemini-1.5-pro-001", | |
}, { | |
headers: { | |
'Authorization': `Bearer ${apiKey}`, | |
'Content-Type': 'application/json', | |
}, | |
}); | |
if (response.data.choices && response.data.choices.length > 0 && response.data.choices[0].message) { | |
const content = response.data.choices[0].message.content.trim(); | |
// console.log(`\n---\nПользователь: ${prompt}\n Ответ:\n ${content}`); | |
res.json({ content }); | |
} else { | |
//res.status(500).json({ content: 'errora' }); // Ошибка прочтения | |
res.json({ content: `{"error":"", "title":"Ошибка", "text":"Произошла ошибка на сервере. (Ошибка прочтения)", "okb":"Ок", "oklink":"", "cancelable":"true"` }) | |
} | |
} catch (error) { | |
console.error(error); | |
//res.status(500).json({ content: 'errorb' }); // ❌ Произошла ошибка сервера при генерации. | |
res.json({ content: `{"error":"", "title":"Ошибка", "text":"Произошла ошибка на сервере. (Ошибка при генерации)", "okb":"Ок", "oklink":"", "cancelable":"true"` }) | |
} | |
}); | |
const port = 7860; | |
app.listen(port, () => { | |
console.log(`API сервер запущен на порту ${port}`); | |
}); | |