File size: 3,847 Bytes
abed4cc
5d38af1
e6227e8
5669f71
abed4cc
5d38af1
 
2b785ca
 
df04541
9f5172e
 
 
 
 
 
587da90
4bbe8d3
49050b3
 
4bbe8d3
4f2b1cc
4bbe8d3
 
 
9f5172e
49050b3
5743387
 
587da90
e25c36c
4f2b1cc
0d0b67b
f97d87a
5743387
 
f65a4fc
77079b7
5db491c
9f5172e
a97fdfd
f65a4fc
 
 
 
ffa39a1
f65a4fc
 
 
 
ffa39a1
f65a4fc
 
 
 
5743387
587da90
f65a4fc
816553a
f65a4fc
a41e935
5db491c
816553a
5db491c
f67ae85
 
3088c46
f67ae85
 
 
 
4f2b1cc
 
f67ae85
 
4f2b1cc
f67ae85
 
 
4f2b1cc
f67ae85
 
 
abed4cc
 
e0c2616
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
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: 60 * 1000, // 60 секунд
  max: 8, // лимит каждые 60 секунд на IP
  handler: function (req, res) {
    return res.status(429).json({ error: "", title: "Ожидайте", text: "Слишком много запросов. Попробуйте позже.", okb: "Ок", oklink: "", cancelable: "true" });
  },
});

// Применение ограничителя скорости перед обработчиком маршрута /pl и /crebeta
app.use('/pl', limiter);

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

app.post('/update', async (req, res) => {
  res.json({ 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 messages = req.body.messages;
  const lang = req.body.lang || "ru";
  const chatid = req.body.chatid || "";
  const apiKey = req.body.api || getRandomApiKey();

  let allMessages;

  if (messages && Array.isArray(messages) && messages.length > 0) {
    allMessages = [
      { 'role': 'system', 'content': `Если тебя спрашивают, кто ты, отвечай: "Я ИИ доктор ${chatid} и моя задача предоставлять информацию по медицинским вопросам. ${start}. Отвечай на языке: ${lang}` },
      ...messages
    ];
  } else if (prompt) {
    allMessages = [
      { 'role': 'system', 'content': `Если тебя спрашивают, кто ты, отвечай: "Я ИИ доктор ${chatid} и моя задача предоставлять информацию по медицинским вопросам. ${start}. Отвечай на языке: ${lang}` },
      { 'role': 'user', 'content': prompt }
    ];
  } else {
    return res.status(400).json({ error: "", title: "Ошибка", text: "Нет запроса!", okb: "Ок", oklink: "", cancelable: "true" });
  }

  try {
    const response = await axios.post('https://text.pollinations.ai/openai', {
      messages: allMessages,
      max_tokens: 4000,
      temperature: 0.3,
      model: "openai",
      presence_penalty: 0.2,
    }, {
      headers: {
        // 'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
    });

    if (response.data.choices && response.data.choices.length > 0 && response.data.choices[0].message && response.data.choices[0].message.content) {
      const content = response.data.choices[0].message.content;
      res.json({ content });
    } else {
      res.json({ error: "", title: "Ошибка", text: "Произошла ошибка на сервере. (Ошибка прочтения)", okb: "Ок", oklink: "", cancelable: "true" });
    }
  } catch (error) {
    console.error(error);
    res.json({ error: "", title: "Ошибка", text: "Произошла ошибка на сервере. (Ошибка при генерации)", okb: "Ок", oklink: "", cancelable: "true" });
  }
});

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