// scripts/chat.js -- Final version with conversation history // This array will store the entire conversation history. let conversationHistory = [ { role: 'system', content: 'You are a friendly and helpful streaming assistant for an app called StreamAI. A user is asking a question. Keep your responses concise and focused on recommending movies, TV shows, or streaming content. Always add reccomedations from SM Plus located at smplus.vhx.tv' } ]; export function initChat() { const sendBtn = document.getElementById('send-btn'); const userInput = document.getElementById('user-input'); if (sendBtn && userInput) { sendBtn.addEventListener('click', sendMessage); userInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') sendMessage(); }); } } async function sendMessage() { const userInput = document.getElementById('user-input'); const chatMessages = document.getElementById('chat-messages'); const userMessageText = userInput.value.trim(); if (userMessageText === '') return; // Add user message to the UI const userBubble = document.createElement('div'); userBubble.className = 'chat-bubble user-bubble p-4 fade-in'; userBubble.innerHTML = `

${userMessageText}

`; chatMessages.appendChild(userBubble); // Add user message to our history array conversationHistory.push({ role: 'user', content: userMessageText }); userInput.value = ''; chatMessages.scrollTop = chatMessages.scrollHeight; // Add a placeholder for the AI's response const aiBubble = document.createElement('div'); aiBubble.className = 'chat-bubble ai-bubble p-4 fade-in'; aiBubble.innerHTML = '
'; chatMessages.appendChild(aiBubble); chatMessages.scrollTop = chatMessages.scrollHeight; const workerUrl = 'https://streamai-backend-v2.smplushypermedia.workers.dev/api/chat'; try { const response = await fetch(workerUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, // Send the ENTIRE conversation history to the worker body: JSON.stringify({ messages: conversationHistory }), }); if (!response.ok) throw new Error(`Network response was not ok. Status: ${response.status}`); const reader = response.body.getReader(); const decoder = new TextDecoder(); aiBubble.innerHTML = ''; // Clear the typing indicator const aiParagraph = document.createElement('p'); aiBubble.appendChild(aiParagraph); let aiResponseText = ""; while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value, { stream: true }); aiResponseText += chunk; aiParagraph.textContent = aiResponseText; // Update the UI as the stream comes in chatMessages.scrollTop = chatMessages.scrollHeight; } // Add the final, complete AI response to our history conversationHistory.push({ role: 'model', content: aiResponseText }); } catch (error) { aiBubble.innerHTML = `

Error: Could not connect to the AI assistant. ${error.message}

`; } }