Spaces:
Runtime error
Runtime error
| const chatWindow = document.getElementById('chat-window'); | |
| const userInput = document.getElementById('user-input'); | |
| const sendBtn = document.getElementById('send-btn'); | |
| let conversation = []; | |
| sendBtn.addEventListener('click', async () => { | |
| const userMessage = userInput.value.trim(); | |
| if (!userMessage) return; | |
| conversation.push({ role: 'user', content: userMessage }); | |
| displayMessage('user', userMessage); | |
| userInput.value = ''; | |
| const loadingDiv = document.createElement('div'); | |
| loadingDiv.textContent = 'Assistant is typing...'; | |
| loadingDiv.className = 'message assistant'; | |
| chatWindow.appendChild(loadingDiv); | |
| chatWindow.scrollTop = chatWindow.scrollHeight; | |
| try { | |
| const response = await fetch('/chat', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify({ messages: conversation }), | |
| }); | |
| const data = await response.json(); | |
| chatWindow.removeChild(loadingDiv); | |
| if (data.response) { | |
| const assistantMessage = data.response.content; | |
| conversation.push({ role: 'assistant', content: assistantMessage }); | |
| displayMessage('assistant', assistantMessage); | |
| } else { | |
| displayMessage('assistant', 'Sorry, I encountered an error.'); | |
| } | |
| } catch (error) { | |
| console.error(error); | |
| chatWindow.removeChild(loadingDiv); | |
| displayMessage('assistant', 'Sorry, something went wrong.'); | |
| } | |
| }); | |
| function displayMessage(role, content) { | |
| const messageDiv = document.createElement('div'); | |
| messageDiv.textContent = content; | |
| messageDiv.className = `message ${role}`; | |
| chatWindow.appendChild(messageDiv); | |
| chatWindow.scrollTop = chatWindow.scrollHeight; | |
| } |