| require('dotenv').config(); |
| const express = require('express'); |
| const rateLimit = require('express-rate-limit'); |
| const axios = require('axios'); |
|
|
| const app = express(); |
| app.use(express.json()); |
|
|
| |
| 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: 60 * 1000, |
| max: 15, |
| handler: function (req, res) { |
| return res.status(429).json({ content: "wait" }); |
| }, |
| }); |
|
|
| |
| 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"}` }); |
| }); |
|
|
| async function sendRequest(prompt, prs) { |
| const apiKey = getRandomApiKey(); |
| const baseUrl = process.env.BASE_URL || 'https://api.openai.com/v1/chat/completions'; |
| const modelName = process.env.MODEL_NAME || 'gpt-3.5-turbo'; |
|
|
| try { |
| const response = await axios.post( |
| baseUrl, |
| { |
| model: modelName, |
| messages: [ |
| { role: 'system', content: prs }, |
| { role: 'user', content: prompt } |
| ], |
| max_tokens: 1200, |
| temperature: 0.7 |
| }, |
| { |
| headers: { |
| |
| 'Content-Type': 'application/json' |
| } |
| } |
| ); |
|
|
| if ( |
| response.data && |
| response.data.choices && |
| response.data.choices.length > 0 |
| ) { |
| return response.data.choices[0].message.content.trim(); |
| } else { |
| throw new Error('Ошибка прочтения ответа'); |
| } |
| } catch (error) { |
| console.error('Ошибка при обращении к модели:', error.message); |
| if (error.response) { |
| console.error('Статус ошибки:', error.response.status); |
| console.error('Тело ошибки:', error.response.data); |
| } |
| throw new Error('Ошибка при генерации'); |
| } |
| } |
|
|
| app.post('/pl', async (req, res) => { |
| const prompt = req.body.prompt; |
| let prs; |
|
|
| if (req.body.mode === "1") { |
| prs = start; |
| } else { |
| prs = startconnect; |
| } |
|
|
| if (!prompt) { |
| return res.status(400).json({ content: "wait" }); |
| } |
|
|
| try { |
| const content = await sendRequest(prompt, prs); |
| res.json({ content }); |
| } catch (error) { |
| res.json({ content: `{"error":"", "title":"Ошибка", "text":"Произошла ошибка на сервере. (${error.message})", "okb":"Ок", "oklink":"", "cancelable":"true"}` }); |
| } |
| }); |
|
|
| app.post('/plbeta', async (req, res) => { |
| const prompt = req.body.prompt; |
| let prs; |
|
|
| if (req.body.mode === "1") { |
| prs = start; |
| } else { |
| prs = startconnect; |
| } |
|
|
| if (!prompt) { |
| return res.status(400).json({ content: "wait" }); |
| } |
|
|
| try { |
| const content = await sendRequest(prompt, prs); |
| console.log(`\n---\nПользователь: ${prompt}\n Ответ:\n ${content}`); |
| res.json({ content }); |
| } catch (error) { |
| res.json({ content: `{"error":"", "title":"Ошибка", "text":"Произошла ошибка на сервере. (${error.message})", "okb":"Ок", "oklink":"", "cancelable":"true"}` }); |
| } |
| }); |
|
|
| const port = 7860; |
| app.listen(port, () => { |
| console.log(`API сервер запущен на порту ${port}`); |
| }); |