File size: 3,819 Bytes
9f8a208
abed4cc
5d38af1
9f8a208
5669f71
abed4cc
5d38af1
 
2b785ca
 
df04541
d73ca0f
 
9f5172e
 
 
 
587da90
4bbe8d3
1cc4d60
 
4bbe8d3
1cc4d60
4bbe8d3
 
 
1cc4d60
9f5172e
a97fdfd
5743387
 
f16210d
587da90
e25c36c
 
0d0b67b
f97d87a
1cc4d60
9f8a208
 
 
1cc4d60
9f8a208
e78c52b
9f8a208
 
 
 
 
 
 
 
 
 
1cc4d60
 
9f8a208
 
 
1cc4d60
9f8a208
1cc4d60
9f8a208
 
1cc4d60
5743387
1cc4d60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efaa50c
9f8a208
efaa50c
 
 
e25c36c
efaa50c
1cc4d60
d01b1a6
 
 
 
 
587da90
3792746
 
1cc4d60
3792746
 
 
1cc4d60
 
 
5743387
1cc4d60
3792746
 
 
abed4cc
 
e0c2616
9f8a208
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
require('dotenv').config();
const express = require('express');
const rateLimit = require('express-rate-limit');
const { HfInference } = require('@huggingface/inference');

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: 15, // лимит каждые 60 секунд на IP
  handler: function (req, res) {
    return res.status(429).json({ content: "wait" });
  },
});

// Применение ограничителя скорости перед обработчиком маршрута /pl и /plbeta
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 hf_api_key = getRandomApiKey();
    const client = new HfInference(hf_api_key);
  
    try {
      const chatCompletion = await client.chatCompletion({
        model: "Qwen/Qwen2.5-Coder-32B-Instruct",
        messages: [
          {
            role: "system",
            content: prs
          },
          {
            role: "user",
            content: prompt
          }
        ],
        max_tokens: 1200,
      });
  
      if (chatCompletion && chatCompletion.choices && chatCompletion.choices.length > 0 && chatCompletion.choices[0].message) {
        return chatCompletion.choices[0].message.content.trim();
      } else {
        throw new Error("Ошибка прочтения ответа");
      }
    } catch (error) {
      console.error("Ошибка при обращении к Hugging Face:", error);
      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}`);
});