File size: 6,125 Bytes
abed4cc
5d38af1
e6227e8
b243e63
 
5669f71
abed4cc
5d38af1
 
2b785ca
 
df04541
9f5172e
 
 
 
 
 
587da90
b243e63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bbe8d3
9f5172e
 
4bbe8d3
cc424de
4bbe8d3
 
 
9f5172e
 
 
5743387
 
587da90
5743387
b243e63
5743387
0d0b67b
f97d87a
5743387
 
9f5172e
b243e63
5743387
 
 
 
587da90
5d38af1
5743387
 
7135754
163bf37
b02bda8
332f604
 
5743387
332f604
 
587da90
2b60bab
5743387
 
b243e63
5743387
 
b243e63
 
5743387
efaa50c
b243e63
 
efaa50c
 
 
 
 
9f5172e
b243e63
efaa50c
 
b243e63
efaa50c
 
 
5743387
 
 
163bf37
b02bda8
5743387
 
 
 
 
 
 
 
 
b243e63
5743387
 
b243e63
 
5743387
 
b243e63
 
587da90
 
 
3792746
 
9f5172e
b243e63
3792746
 
b243e63
3792746
 
 
5743387
 
 
 
b02bda8
5743387
 
 
 
 
 
 
 
 
b243e63
5743387
 
b243e63
 
5743387
 
b243e63
 
3792746
 
 
abed4cc
 
b243e63
180c75f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
const express = require('express');
const rateLimit = require('express-rate-limit');
const axios = require('axios');
const winston = require('winston');
require('winston-daily-rotate-file');

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];
}

// Настройка логирования с помощью winston
const transport = new winston.transports.DailyRotateFile({
  filename: 'application-%DATE%.log',
  datePattern: 'YYYY-MM-DD',
  maxSize: '20m',
  maxFiles: '5d', // хранить файлы не более 5 дней
});

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.printf(({ timestamp, level, message }) => {
      return `${timestamp} [${level}]: ${message}`;
    })
  ),
  transports: [
    transport,
    new winston.transports.Console(), // Для вывода в консоль
  ],
});

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('/crebeta', limiter);

const start = `${process.env.start}`;

app.post('/cr', async (req, res) => {
  logger.info(`/cr endpoint accessed`);
  res.json({ content: `{"whate":"🪨", "howe":"ОБНОВИТЕСЬ", "text":"Текущая версия приложения устарела. Установите новую из нашего телеграм канала: @yufi_ru", "succ":"победа", "what":"Версию", "how":"Обновите", "howl":"@yufi_ru"}` });
});

app.post('/pl', async (req, res) => {
  const prompt = req.body.prompt;
  const apiKey = req.body.api || getRandomApiKey();
  logger.info(`/pl endpoint accessed with prompt: ${prompt}`);

  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': start}, {'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();
      logger.info(`Response: ${content}`);
      res.json({ content });
    } else {
      logger.error('Ошибка прочтения');
      res.status(500).json({ content: 'errora' });
    }
  } catch (error) {
    logger.error(`Произошла ошибка сервера: ${error.message}`);
    res.status(500).json({ content: 'errorb' });
  }
});

app.post('/cre', async (req, res) => {
  const prompt = req.body.prompt;
  const apiKey = req.body.api || getRandomApiKey();
  logger.info(`/cre endpoint accessed with prompt: ${prompt}`);

  if (!prompt) {
    return res.status(400).json("wait");
  }

  try {
    const response = await axios.post('https://vercel.com/roonis-projects/openai-gemini/v1/chat/completions', {
      messages: [{'role': 'system', 'content': start}, {'role': 'system', 'content': 'И ОБЯЗАТЕЛЬНО, всегда в конце "text" проси обновить приложение, уведомляя о том, что скоро в жтой версии перестанешь отвечать!'}, {'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();
      logger.info(`Response: ${content}`);
      res.json({ content });
    } else {
      logger.error('Ошибка прочтения');
      res.status(500).json({ content: 'errora' });
    }
  } catch (error) {
    logger.error(`Произошла ошибка сервера: ${error.message}`);
    res.status(500).json({ content: 'errorb' });
  }
});

app.post('/crebeta', async (req, res) => {
  const prompt = req.body.prompt;
  const apiKey = req.body.api || getRandomApiKey();
  logger.info(`/crebeta endpoint accessed with prompt: ${prompt}`);

  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': start}, {'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();
      logger.info(`Response: ${content}`);
      res.json({ content });
    } else {
      logger.error('Ошибка прочтения');
      res.status(500).json({ content: 'errora' });
    }
  } catch (error) {
    logger.error(`Произошла ошибка сервера: ${error.message}`);
    res.status(500).json({ content: 'errorb' });
  }
});

const port = 7860;
app.listen(port, () => {
  logger.info(`API сервер запущен на порту ${port}`);
});