fix: память только в браузере, сервер ничего не хранит

This commit is contained in:
2026-06-01 23:09:18 +03:00
parent edbcde0dcc
commit 55fb1f658b
2 changed files with 12 additions and 40 deletions
+5 -34
View File
@@ -40,63 +40,34 @@ app.post('/api/whisper', upload.single('audio'), async (req, res) => {
}
});
// ====== Session memory ======
const sessions = {}; // sessionId → messages[]
app.get('/api/history', (req, res) => {
const sid = req.query.sid || 'default';
res.json({ messages: sessions[sid] || [] });
});
app.post('/api/chat', async (req, res) => {
try {
const { model, message, sid, history } = req.body;
const { model, message, history } = req.body;
const m = MODELS[model];
if (!m) return res.status(400).json({ error: 'Неизвестная модель' });
// Собираем историю: system + предыдущие сообщения + новое
const id = sid || 'default';
const msgs = history || sessions[id] || [];
const fullMessages = [
{ role: 'system', content: m.system },
...msgs,
...(history || []),
{ role: 'user', content: message || 'Привет' },
];
// Обрезаем чтобы не выйти за лимит токенов
// Обрезаем чтобы не выйти за лимит
while (JSON.stringify(fullMessages).length > 32000 && fullMessages.length > 2)
fullMessages.splice(1, 2);
const r = await fetch(`${API_BASE}/v1/chat/completions`, {
method: 'POST',
headers: { Authorization: `Bearer ${API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({
model: m.id, temperature: m.temp, max_tokens: m.tokens,
messages: fullMessages,
}),
body: JSON.stringify({ model: m.id, temperature: m.temp, max_tokens: m.tokens, messages: fullMessages }),
});
const data = await r.json();
const response = data.choices?.[0]?.message?.content || 'Нет ответа';
// Сохраняем историю
sessions[id] = [
...msgs,
{ role: 'user', content: message },
{ role: 'assistant', content: response },
];
res.json({ response, sid: id });
res.json({ response: data.choices?.[0]?.message?.content || 'Нет ответа' });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
app.post('/api/reset', (req, res) => {
const sid = req.body.sid || 'default';
delete sessions[sid];
res.json({ ok: true });
});
app.get('/', (_req, res) => res.sendFile(path.join(__dirname, 'public', 'index.html')));
app.listen(PORT, () => console.log(`Say:${PORT}`));