56 lines
1.6 KiB
JavaScript
56 lines
1.6 KiB
JavaScript
// Conversation history and localStorage functionality
|
|
import { getSystemMessage } from "./config.js";
|
|
|
|
// Helper function to generate a page-specific key for localStorage
|
|
export function getPageSpecificKey(baseKey) {
|
|
// Use the current page's URL to create a unique key
|
|
// Replace non-alphanumeric characters to make it a valid key
|
|
const pageIdentifier = window.location.href.replace(/[^a-zA-Z0-9]/g, "_");
|
|
return `${baseKey}-${pageIdentifier}`;
|
|
}
|
|
|
|
// Functions for conversation history persistence
|
|
export function saveConversationHistory(chatHistory) {
|
|
const historyToSave = chatHistory.filter((msg) => msg.role !== "system");
|
|
localStorage.setItem(
|
|
getPageSpecificKey("hermes-conversation-history"),
|
|
JSON.stringify(historyToSave),
|
|
);
|
|
}
|
|
|
|
export function loadConversationHistory() {
|
|
const saved = localStorage.getItem(
|
|
getPageSpecificKey("hermes-conversation-history"),
|
|
);
|
|
if (saved) {
|
|
try {
|
|
const parsedHistory = JSON.parse(saved);
|
|
// Filter out any system messages that might have been saved before our fix
|
|
return parsedHistory.filter((msg) => msg.role !== "system");
|
|
} catch (e) {
|
|
console.error("Error parsing conversation history:", e);
|
|
}
|
|
}
|
|
return [];
|
|
}
|
|
|
|
export async function clearConversationHistory() {
|
|
localStorage.removeItem(getPageSpecificKey("hermes-conversation-history"));
|
|
return [
|
|
{
|
|
role: "system",
|
|
content: await getSystemMessage(),
|
|
},
|
|
];
|
|
}
|
|
|
|
// Initialize chat history
|
|
export async function initializeChatHistory() {
|
|
return [
|
|
{
|
|
role: "system",
|
|
content: await getSystemMessage(),
|
|
},
|
|
...loadConversationHistory(),
|
|
];
|
|
}
|