diff --git a/chat-core.js b/chat-core.js index f90497a..c601132 100644 --- a/chat-core.js +++ b/chat-core.js @@ -502,26 +502,44 @@ document.addEventListener("DOMContentLoaded", () => { } } - const messages = []; - if (window.aiInstructions) { - messages.push({ role: "system", content: window.aiInstructions }); - } - const memories = Memory.getMemories(); - if (memories?.length) { - messages.push({ role: "system", content: `Relevant memory:\n${memories.join("\n")}\nUse it in your response.` }); - } - - const HISTORY = 10; - const end = currentSession.messages.length - 1; - const start = Math.max(0, end - HISTORY); - for (let i = start; i < end; i++) { - messages.push(currentSession.messages[i]); - } - - const lastUser = overrideContent || currentSession.messages[end]?.content; - if (lastUser) { - messages.push({ role: "user", content: lastUser }); - } + const sanitizeForApi = (message) => { + if (!message || typeof message !== "object") return null; + let { role, content } = message; + if (typeof content !== "string" || !content.trim()) return null; + if (role === "ai") role = "assistant"; + if (role === "assistant" || role === "user") { + return { role, content }; + } + return null; + }; + + const messages = []; + if (typeof window.aiInstructions === "string" && window.aiInstructions.trim()) { + messages.push({ role: "system", content: window.aiInstructions }); + } + const memories = Memory.getMemories(); + if (Array.isArray(memories) && memories.length) { + messages.push({ role: "system", content: `Relevant memory:\n${memories.join("\n")}\nUse it in your response.` }); + } + + const HISTORY = 10; + const end = currentSession.messages.length - 1; + const start = Math.max(0, end - HISTORY); + for (let i = start; i < end; i++) { + const sanitized = sanitizeForApi(currentSession.messages[i]); + if (sanitized) messages.push(sanitized); + } + + let lastUserMessage = typeof overrideContent === "string" ? overrideContent : null; + if (!lastUserMessage) { + const potential = currentSession.messages[end]; + if (potential?.role === "user" && typeof potential.content === "string") { + lastUserMessage = potential.content; + } + } + if (lastUserMessage && lastUserMessage.trim()) { + messages.push({ role: "user", content: lastUserMessage }); + } const modelSelectEl = document.getElementById("model-select"); const model = modelSelectEl?.value || currentSession.model || Storage.getDefaultModel();