优化缓存命中

This commit is contained in:
2026-07-29 09:48:44 +08:00
parent 7247b1d832
commit 886df10775
3 changed files with 23 additions and 18 deletions

View File

@@ -1,8 +1,5 @@
// AI Prompt 模板 — 模块化拼接 // AI Prompt 模板 — 模块化拼接
function buildSystemPrompt(username, isAdmin) { function buildSystemPrompt(username, isAdmin) {
const now = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false });
// 稳定前缀放前面(提升缓存命中率)
const role = '你是智能财务助手"小财"。结合对话历史理解用户意图只返回JSON。'; const role = '你是智能财务助手"小财"。结合对话历史理解用户意图只返回JSON。';
const intent = [ const intent = [
@@ -69,10 +66,7 @@ function buildSystemPrompt(username, isAdmin) {
'- 无法确定物品名 → action="ask" 追问' '- 无法确定物品名 → action="ask" 追问'
].join('\n'); ].join('\n');
// 变动的放最后 return [role, intent, permission, deleteRules, attachmentRules, prohibitionRules, modifyGuide, purchaseRules].join('\n');
const timeInfo = '当前服务器时间:' + now;
return [role, intent, permission, deleteRules, attachmentRules, prohibitionRules, modifyGuide, purchaseRules, timeInfo].join('\n');
} }
module.exports = { buildSystemPrompt }; module.exports = { buildSystemPrompt };

View File

@@ -7,7 +7,7 @@ const { broadcastToRoom } = require('./ws');
// 对话历史(内存) // 对话历史(内存)
const conversationHistory = new Map(); const conversationHistory = new Map();
function getHistory(roomId) { if (!conversationHistory.has(roomId)) conversationHistory.set(roomId, []); return conversationHistory.get(roomId); } function getHistory(roomId) { if (!conversationHistory.has(roomId)) conversationHistory.set(roomId, []); return conversationHistory.get(roomId); }
function addToHistory(roomId, role, content) { const h = getHistory(roomId); h.push({ role, content }); if (h.length > 60) conversationHistory.set(roomId, h.slice(-40)); } function addToHistory(roomId, role, content) { var h = getHistory(roomId); h.push({ role: role, content: content }); if (h.length > 60) conversationHistory.set(roomId, h.slice(-30)); }
// 待处理操作 // 待处理操作
const pendingActions = new Map(); const pendingActions = new Map();

View File

@@ -61,21 +61,32 @@ router.post('/:roomId/messages', authMiddleware, async (req, res) => {
}); });
async function analyzeWithDeepSeek(text, historyMessages, username, isAdmin, roomId) { async function analyzeWithDeepSeek(text, historyMessages, username, isAdmin, roomId) {
// 注入当前房间采购清单上下文 // 采购清单(单独消息)
const purchases = db.prepare("SELECT item, quantity, amount, status, created_at FROM purchases WHERE room_id = ? ORDER BY created_at DESC LIMIT 10").all(roomId); var purchases = db.prepare("SELECT item, quantity, amount, status, created_at FROM purchases WHERE room_id = ? ORDER BY created_at DESC LIMIT 10").all(roomId);
const purchaseContext = purchases.length var purchaseMsg = purchases.length
? `\n📋 当前房间采购清单最近10条\n${purchases.map(p => `- ${p.item} | ×${p.quantity} | ¥${p.amount} | ${p.status} | ${p.created_at}`).join('\n')}` ? '📋 当前房间采购清单最近10条\n' + purchases.map(function(p) { return '- ' + p.item + ' | ×' + p.quantity + ' | ¥' + p.amount + ' | ' + p.status + ' | ' + p.created_at; }).join('\n')
: ''; : '';
const systemPrompt = buildSystemPrompt(username, isAdmin) + purchaseContext; // 系统提示词(稳定,不含时间)
const messages = [ var systemPrompt = buildSystemPrompt(username, isAdmin);
{ role: 'system', content: systemPrompt }, var messages = [
...historyMessages.slice(-30), { role: 'system', content: systemPrompt }
{ role: 'user', content: `${username}: ${text}` }
]; ];
// 全量历史,每 30 条一轮前缀稳定期,轮内全部命中
historyMessages.forEach(function(m) { messages.push(m); });
// 采购清单、时间放最后,变动不影响历史命中
if (purchaseMsg) messages.push({ role: 'system', content: purchaseMsg });
messages.push({ role: 'system', content: '当前服务器时间:' + new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false }) });
// 当前消息已在 historyMessages 中,不再重复 push
const content = await callDeepSeek(messages, username); const content = await callDeepSeek(messages, username);
console.log('🤖 AI 返回:', content); console.log('🤖 AI 返回:', content.substring(0, 200));
// 打印消息结构,方便排查缓存
console.log('📋 消息结构:', messages.map(function(m, i) {
var preview = m.content.substring(0, 60).split('\n').join(' ');
return '[' + i + '] ' + m.role + ' (' + m.content.length + '字): ' + preview;
}).join('\n'));
try { try {
var cleaned = content.replace(/```json|```/g, '').trim(); var cleaned = content.replace(/```json|```/g, '').trim();
if (!cleaned) { console.warn('⚠️ AI 返回空内容'); return { action: 'ignore' }; }
var parsed = JSON.parse(cleaned); var parsed = JSON.parse(cleaned);
// 支持批量AI 可能返回数组 // 支持批量AI 可能返回数组
if (Array.isArray(parsed)) { if (Array.isArray(parsed)) {