Spaces:
Runtime error
Runtime error
File size: 1,791 Bytes
04444fe |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
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;
} |