151 lines
4.6 KiB
JavaScript
151 lines
4.6 KiB
JavaScript
const router = require('express').Router();
|
||
const { getSupabaseClient } = require('./supabaseClient');
|
||
const { SupportAgent } = require('./support-ai-agent/support-agent');
|
||
|
||
// Хранилище агентов для разных пользователей
|
||
const userAgents = new Map();
|
||
|
||
/**
|
||
* Получить или создать агента для пользователя
|
||
*/
|
||
function getUserAgent(userId, systemPrompt) {
|
||
if (!userAgents.has(userId)) {
|
||
const config = {
|
||
threadId: userId,
|
||
temperature: 0.7
|
||
};
|
||
if (systemPrompt) {
|
||
config.systemPrompt = systemPrompt;
|
||
}
|
||
userAgents.set(userId, new SupportAgent(config));
|
||
}
|
||
return userAgents.get(userId);
|
||
}
|
||
|
||
// POST /api/support
|
||
router.post('/support', async (req, res) => {
|
||
const supabase = getSupabaseClient();
|
||
const { user_id, message, system_prompt } = req.body;
|
||
|
||
if (!user_id || !message) {
|
||
return res.status(400).json({ error: 'user_id и message обязательны' });
|
||
}
|
||
|
||
try {
|
||
// Сохраняем сообщение пользователя в базу данных
|
||
const { error: insertError } = await supabase
|
||
.from('support')
|
||
.insert({ user_id, message, is_from_user: true });
|
||
|
||
if (insertError) {
|
||
return res.status(400).json({ error: insertError.message });
|
||
}
|
||
|
||
// Получаем агента для пользователя
|
||
const agent = getUserAgent(user_id, system_prompt);
|
||
|
||
// Обновляем системный промпт если передан
|
||
if (system_prompt) {
|
||
agent.updateSystemPrompt(system_prompt);
|
||
}
|
||
|
||
// Получаем ответ от AI-агента
|
||
const aiResponse = await agent.processMessage(message);
|
||
|
||
if (!aiResponse.success) {
|
||
console.error('Ошибка AI-агента:', aiResponse.error);
|
||
return res.status(500).json({
|
||
error: 'Ошибка при генерации ответа',
|
||
reply: 'Извините, произошла ошибка. Попробуйте позже.'
|
||
});
|
||
}
|
||
|
||
// Сохраняем ответ агента в базу данных
|
||
const { error: responseError } = await supabase
|
||
.from('support')
|
||
.insert({
|
||
user_id,
|
||
message: aiResponse.content,
|
||
is_from_user: false
|
||
});
|
||
|
||
if (responseError) {
|
||
console.error('Ошибка сохранения ответа:', responseError);
|
||
// Не возвращаем ошибку пользователю, так как ответ уже сгенерирован
|
||
}
|
||
|
||
// Возвращаем ответ пользователю
|
||
res.json({
|
||
reply: aiResponse.content,
|
||
success: true
|
||
});
|
||
|
||
} catch (error) {
|
||
console.error('Ошибка в supportApi:', error);
|
||
res.status(500).json({
|
||
error: 'Внутренняя ошибка сервера',
|
||
reply: 'Извините, произошла ошибка. Попробуйте позже.'
|
||
});
|
||
}
|
||
});
|
||
|
||
// POST /api/support/configure - Настройка системного промпта
|
||
router.post('/support/configure', async (req, res) => {
|
||
const { user_id, system_prompt } = req.body;
|
||
|
||
if (!user_id) {
|
||
return res.status(400).json({ error: 'user_id обязателен' });
|
||
}
|
||
|
||
try {
|
||
const agent = getUserAgent(user_id, system_prompt);
|
||
|
||
if (system_prompt) {
|
||
agent.updateSystemPrompt(system_prompt);
|
||
}
|
||
|
||
res.json({
|
||
message: 'Конфигурация агента обновлена',
|
||
current_system_prompt: agent.getSystemPrompt(),
|
||
success: true
|
||
});
|
||
|
||
} catch (error) {
|
||
console.error('Ошибка в /support/configure:', error);
|
||
res.status(500).json({
|
||
error: 'Внутренняя ошибка сервера',
|
||
success: false
|
||
});
|
||
}
|
||
});
|
||
|
||
// DELETE /api/support/history/:userId - Очистка истории диалога
|
||
router.delete('/support/history/:userId', async (req, res) => {
|
||
const { userId } = req.params;
|
||
|
||
try {
|
||
if (userAgents.has(userId)) {
|
||
const agent = userAgents.get(userId);
|
||
await agent.clearHistory();
|
||
|
||
res.json({
|
||
message: 'История диалога очищена',
|
||
success: true
|
||
});
|
||
} else {
|
||
res.json({
|
||
message: 'Агент для данного пользователя не найден',
|
||
success: true
|
||
});
|
||
}
|
||
|
||
} catch (error) {
|
||
console.error('Ошибка в /support/history:', error);
|
||
res.status(500).json({
|
||
error: 'Внутренняя ошибка сервера',
|
||
success: false
|
||
});
|
||
}
|
||
});
|
||
|
||
module.exports = router; |