优化缓存命中
This commit is contained in:
@@ -1,8 +1,5 @@
|
||||
// AI Prompt 模板 — 模块化拼接
|
||||
function buildSystemPrompt(username, isAdmin) {
|
||||
const now = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false });
|
||||
|
||||
// 稳定前缀放前面(提升缓存命中率)
|
||||
const role = '你是智能财务助手"小财"。结合对话历史理解用户意图,只返回JSON。';
|
||||
|
||||
const intent = [
|
||||
@@ -69,10 +66,7 @@ function buildSystemPrompt(username, isAdmin) {
|
||||
'- 无法确定物品名 → action="ask" 追问'
|
||||
].join('\n');
|
||||
|
||||
// 变动的放最后
|
||||
const timeInfo = '当前服务器时间:' + now;
|
||||
|
||||
return [role, intent, permission, deleteRules, attachmentRules, prohibitionRules, modifyGuide, purchaseRules, timeInfo].join('\n');
|
||||
return [role, intent, permission, deleteRules, attachmentRules, prohibitionRules, modifyGuide, purchaseRules].join('\n');
|
||||
}
|
||||
|
||||
module.exports = { buildSystemPrompt };
|
||||
|
||||
@@ -7,7 +7,7 @@ const { broadcastToRoom } = require('./ws');
|
||||
// 对话历史(内存)
|
||||
const conversationHistory = new Map();
|
||||
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();
|
||||
|
||||
@@ -61,21 +61,32 @@ router.post('/:roomId/messages', authMiddleware, async (req, res) => {
|
||||
});
|
||||
|
||||
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);
|
||||
const purchaseContext = purchases.length
|
||||
? `\n📋 当前房间采购清单(最近10条):\n${purchases.map(p => `- ${p.item} | ×${p.quantity} | ¥${p.amount} | ${p.status} | ${p.created_at}`).join('\n')}`
|
||||
// 采购清单(单独消息)
|
||||
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);
|
||||
var purchaseMsg = purchases.length
|
||||
? '📋 当前房间采购清单(最近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 = [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
...historyMessages.slice(-30),
|
||||
{ role: 'user', content: `${username}: ${text}` }
|
||||
// 系统提示词(稳定,不含时间)
|
||||
var systemPrompt = buildSystemPrompt(username, isAdmin);
|
||||
var messages = [
|
||||
{ role: 'system', content: systemPrompt }
|
||||
];
|
||||
// 全量历史,每 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);
|
||||
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 {
|
||||
var cleaned = content.replace(/```json|```/g, '').trim();
|
||||
if (!cleaned) { console.warn('⚠️ AI 返回空内容'); return { action: 'ignore' }; }
|
||||
var parsed = JSON.parse(cleaned);
|
||||
// 支持批量:AI 可能返回数组
|
||||
if (Array.isArray(parsed)) {
|
||||
|
||||
Reference in New Issue
Block a user