File size: 2,512 Bytes
5796df2
5d38af1
8f22f37
7d1620b
2927323
587da90
5d38af1
79a2685
662dd32
fa87bc3
662dd32
79a2685
5d38af1
587da90
2927323
c46abf9
 
9c7d162
 
 
 
2927323
eedf466
2927323
205949e
2d0acac
205949e
 
2927323
 
 
 
 
205949e
2927323
4783543
 
9c7d162
4783543
2927323
 
 
 
 
f304da9
2927323
f304da9
2927323
 
2d0acac
2927323
 
 
 
 
 
 
 
 
 
5d38af1
8f6b7be
587da90
7d1620b
5d38af1
 
587da90
2b60bab
 
 
 
 
 
79a2685
2b60bab
587da90
5d38af1
79a2685
587da90
abed4cc
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
app.post('/gen', async (req, res) => {
  const prompt = req.body.prompt;
  const img = req.body.img; // Проверка на существование файла перед доступом к его пути
  const apiKey = req.body.api || openai_key;
  let payload;

  if (!prompt) {
    return res.json({ content: '+ошибка+❌ Ошибка данных, повторите попытку.-ошибка-' });
  }

  if (prompt.replace(/[\s\n]/g, '').length > 250) {
    return res.json({ content: '+ошибка+❌ Максимум символов: 250-ошибка-' });
  }

  // Создание тела запроса в зависимости от наличия изображения
  if (img) {
    // Если изображение предоставлено

    // Обрезка строки base64 до 1 МБ
    const trimmedBase64Image = base64Image && base64Image.substring(0, 1024000);
    
    payload = {
      "model": "gpt-4-vision-preview",
      "messages": [
        {
          "role": "system",
          "content": start,
        },
        {
          "role": "user",
          "content": [
            {
              "type": "text",
              "text": prompt,
            },
            {
              "type": "image_url",
              "image_url": { "url": `data:image/jpeg;base64,${trimmedBase64Image}` },
            },
          ],
        }
      ],
    };
  } else {
    // Если изображение не предоставлено   gpt-4-1106-preview
    payload = {
      "model": "gpt-4-vision-preview",
      "messages": [
        {
          "role": "system",
          "content": start,
        },
        {
          "role": "user",
          "content": prompt,
        }
      ],
    };
  }

  try {
    const response = await axios.post(base_url, payload, {
      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(content);
      res.json({ content });
    } else {
      res.json({ content: '+ошибка+❌ Не удалось прочитать ответ.-ошибка-' });
    }
  } catch (error) {
    console.error(error);
    res.json({ content: '+ошибка+❌ Произошла ошибка сервера при генерации.-ошибка-' });
  }
});