Spaces:
Paused
Paused
| 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 = data; | |
| // Добавляем сгенерированное сообщение в конец массива 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}`); | |
| }); | |