All checks were successful
Gitea Actions Demo / Explore-Gitea-Actions (push) Successful in 2m50s
132 lines
4.1 KiB
JavaScript
132 lines
4.1 KiB
JavaScript
const fs = require('fs').promises;
|
||
const path = require('path');
|
||
|
||
class MessageHistory {
|
||
constructor() {
|
||
this.historyFile = path.join(__dirname, '..', 'chat_history.json');
|
||
this.messages = []; // 内存中的消息历史
|
||
this.maxMessages = 100; // 最大保存消息数量
|
||
}
|
||
|
||
// 服务器启动时初始化,从JSON文件预加载历史
|
||
async initialize() {
|
||
try {
|
||
const data = await fs.readFile(this.historyFile, 'utf8');
|
||
this.messages = JSON.parse(data);
|
||
console.log(`已加载 ${this.messages.length} 条历史消息`);
|
||
} catch (error) {
|
||
if (error.code === 'ENOENT') {
|
||
console.log('历史文件不存在,创建新的消息历史');
|
||
this.messages = [];
|
||
await this.saveToFile();
|
||
} else {
|
||
console.error('加载历史消息失败:', error);
|
||
this.messages = [];
|
||
}
|
||
}
|
||
}
|
||
|
||
// 添加新消息(用户输入和助手回复)
|
||
async addMessage(userInput, assistantResponse) {
|
||
// 添加用户消息
|
||
this.messages.push({
|
||
role: 'user',
|
||
content: userInput
|
||
});
|
||
|
||
// 添加助手回复
|
||
this.messages.push({
|
||
role: 'assistant',
|
||
content: assistantResponse
|
||
});
|
||
|
||
// 限制消息数量(保留最近的对话)
|
||
if (this.messages.length > this.maxMessages * 2) {
|
||
this.messages = this.messages.slice(-this.maxMessages * 2);
|
||
}
|
||
|
||
// 同时保存到文件和内存
|
||
await this.saveToFile();
|
||
|
||
console.log(`已保存对话,当前历史消息数: ${this.messages.length}`);
|
||
}
|
||
|
||
// 获取用于大模型的消息格式
|
||
getMessagesForLLM(includeSystem = true, recentCount = 10) {
|
||
const messages = [];
|
||
|
||
// 添加系统消息
|
||
// if (includeSystem) {
|
||
// messages.push({
|
||
// role: 'system',
|
||
// content: 'You are a helpful assistant.'
|
||
// });
|
||
// }
|
||
|
||
// 获取最近的对话历史
|
||
const recentMessages = this.messages.slice(-recentCount * 2); // 用户+助手成对出现
|
||
messages.push(...recentMessages.map(msg => ({
|
||
role: msg.role,
|
||
content: msg.content
|
||
})));
|
||
|
||
return messages;
|
||
}
|
||
|
||
// 获取完整历史(包含时间戳)
|
||
getFullHistory() {
|
||
return [...this.messages];
|
||
}
|
||
|
||
// 清空历史
|
||
async clearHistory() {
|
||
this.messages = [];
|
||
await this.saveToFile();
|
||
console.log('历史消息已清空');
|
||
}
|
||
|
||
// 保存到JSON文件
|
||
async saveToFile() {
|
||
try {
|
||
await fs.writeFile(this.historyFile, JSON.stringify(this.messages, null, 2), 'utf8');
|
||
} catch (error) {
|
||
console.error('保存历史消息到文件失败:', error);
|
||
}
|
||
}
|
||
|
||
// 导出历史(备份)
|
||
async exportHistory(filename) {
|
||
const exportPath = filename || `chat_backup_${new Date().toISOString().split('T')[0]}.json`;
|
||
try {
|
||
await fs.writeFile(exportPath, JSON.stringify(this.messages, null, 2), 'utf8');
|
||
console.log(`历史消息已导出到: ${exportPath}`);
|
||
return exportPath;
|
||
} catch (error) {
|
||
console.error('导出历史消息失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
// 导入历史
|
||
async importHistory(filename) {
|
||
try {
|
||
const data = await fs.readFile(filename, 'utf8');
|
||
const importedMessages = JSON.parse(data);
|
||
|
||
// 验证消息格式
|
||
if (Array.isArray(importedMessages)) {
|
||
this.messages = importedMessages;
|
||
await this.saveToFile();
|
||
console.log(`已导入 ${this.messages.length} 条历史消息`);
|
||
return true;
|
||
} else {
|
||
throw new Error('无效的消息格式');
|
||
}
|
||
} catch (error) {
|
||
console.error('导入历史消息失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = { MessageHistory }; |