Update server.js
Browse files
server.js
CHANGED
|
@@ -1,31 +1,46 @@
|
|
| 1 |
-
|
| 2 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
|
|
|
| 4 |
const app = express();
|
| 5 |
app.use(express.json());
|
| 6 |
|
| 7 |
-
|
| 8 |
-
const
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
});
|
| 30 |
|
| 31 |
-
app.listen(7860, () => console.log(
|
|
|
|
| 1 |
+
//require('dotenv').config();
|
| 2 |
+
const Groq = require('groq-sdk');
|
| 3 |
+
const express = require('express');
|
| 4 |
+
const fs = require('fs');
|
| 5 |
+
const path = require('path');
|
| 6 |
+
const os = require('os');
|
| 7 |
|
| 8 |
+
const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });
|
| 9 |
const app = express();
|
| 10 |
app.use(express.json());
|
| 11 |
|
| 12 |
+
app.post('/chat', async (req, res) => {
|
| 13 |
+
const { sessionId, message } = req.body;
|
| 14 |
+
if (!sessionId || !message) return res.status(400).json({ error: 'Missing sessionId or message' });
|
| 15 |
+
|
| 16 |
+
const sessionFile = path.join(os.tmpdir(), sessionId);
|
| 17 |
+
let history = fs.existsSync(sessionFile) ? JSON.parse(fs.readFileSync(sessionFile, 'utf8')) : [];
|
| 18 |
+
|
| 19 |
+
history.push({ role: 'user', content: message });
|
| 20 |
+
|
| 21 |
+
const chatCompletion = await groq.chat.completions.create({
|
| 22 |
+
messages: history,
|
| 23 |
+
model: 'deepseek-r1-distill-qwen-32b',
|
| 24 |
+
temperature: 0.6,
|
| 25 |
+
max_completion_tokens: 4096,
|
| 26 |
+
top_p: 0.95,
|
| 27 |
+
stream: true
|
| 28 |
+
});
|
| 29 |
+
|
| 30 |
+
res.setHeader('Content-Type', 'text/plain');
|
| 31 |
+
res.setHeader('Transfer-Encoding', 'chunked');
|
| 32 |
+
|
| 33 |
+
let responseText = '';
|
| 34 |
+
for await (const chunk of chatCompletion) {
|
| 35 |
+
const content = chunk.choices[0]?.delta?.content || '';
|
| 36 |
+
responseText += content;
|
| 37 |
+
res.write(content);
|
| 38 |
}
|
| 39 |
+
|
| 40 |
+
history.push({ role: 'assistant', content: responseText });
|
| 41 |
+
fs.writeFileSync(sessionFile, JSON.stringify(history));
|
| 42 |
+
|
| 43 |
+
res.end();
|
| 44 |
});
|
| 45 |
|
| 46 |
+
app.listen(7860, () => console.log('Server running on port 7860'));
|