File size: 2,566 Bytes
abed4cc
d9c17f2
abed4cc
d9c17f2
 
a0a4e09
55f0cda
a0a4e09
d9c17f2
 
38033f0
54d7e71
0cbae74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6f9ea4
f4fded1
a6f9ea4
 
 
 
0cbae74
 
 
 
54d7e71
38033f0
a0a4e09
d9c17f2
 
 
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
const express = require('express');
const axios = require('axios');
const app = express();
const PORT = process.env.PORT || 7860;
const apiToken = process.env.API_KEY;

app.use(express.json());

app.post('/chat', async (req, res) => {
    const { messages, temperature, max_tokens } = req.body;

    try {
        const { default: fetch } = await import('node-fetch');

        const response = await fetch('https://api-inference.huggingface.co/models/codellama/CodeLlama-34b-Instruct-hf', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiToken}`
            },
            body: JSON.stringify({
                "inputs": messages,
                "parameters": {
                    "temperature": temperature || 0.7,
                    "max_new_tokens": max_tokens || 100
                }
            })
        });

        const text = await response.text(); // Получаем текст ответа
        console.log("Response text:", text); // Логируем ответ

        // Проверяем, если ответ содержит JSON
        if (response.headers.get('content-type')?.includes('application/json')) {
            let data;
            try {
                data = JSON.parse(text); // Пытаемся распарсить JSON
            } catch (jsonError) {
                console.error("JSON parsing error:", jsonError);
                return res.status(500).json({ error: `Ошибка парсинга JSON: ${jsonError.message}` });
            }

            const generatedText = data.generated_text;

            // Добавляем сгенерированное сообщение в конец массива messages
            messages.push({ role: 'assistant', content: generatedText });
            res.json({ messages });
        } else {
            console.error("Received non-JSON response:", text);

            const generatedText = text;

            // Добавляем сгенерированное сообщение в конец массива messages
            messages.push({ role: 'assistant', content: generatedText });
            res.json({ messages });
        }
    } catch (error) {
        console.error("Error during text generation:", error);
        res.status(500).json({ error: `Произошла ошибка при генерации текста: ${error.message}` });
    }
});

app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});