StreamAI / scripts /chat.js
privateuserh's picture
Update scripts/chat.js
98f15d2 verified
// scripts/chat.js -- FINAL VERSION
let conversationHistory = [
{
role: 'system',
content: 'You are a friendly and helpful streaming assistant for an app called StreamAI. Keep your responses concise and focused on recommending movies, TV shows, or streaming content.'
}
];
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;
const userBubble = document.createElement('div');
userBubble.className = 'chat-bubble user-bubble p-4 fade-in';
userBubble.innerHTML = `<p>${userMessageText}</p>`;
chatMessages.appendChild(userBubble);
conversationHistory.push({ role: 'user', content: userMessageText });
userInput.value = '';
chatMessages.scrollTop = chatMessages.scrollHeight;
const aiBubble = document.createElement('div');
aiBubble.className = 'chat-bubble ai-bubble p-4 fade-in';
aiBubble.innerHTML = '<div class="typing-indicator"><span></span><span></span><span></span></div>';
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' },
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 = '';
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;
chatMessages.scrollTop = chatMessages.scrollHeight;
}
conversationHistory.push({ role: 'model', content: aiResponseText });
} catch (error) {
aiBubble.innerHTML = `<p class="text-red-400">Error: Could not connect to the AI assistant. ${error.message}</p>`;
}
}