Spaces:
Runtime error
Runtime error
Create script.js
Browse files- public/script.js +50 -0
public/script.js
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const chatWindow = document.getElementById('chat-window');
|
2 |
+
const userInput = document.getElementById('user-input');
|
3 |
+
const sendBtn = document.getElementById('send-btn');
|
4 |
+
let conversation = [];
|
5 |
+
|
6 |
+
sendBtn.addEventListener('click', async () => {
|
7 |
+
const userMessage = userInput.value.trim();
|
8 |
+
if (!userMessage) return;
|
9 |
+
|
10 |
+
conversation.push({ role: 'user', content: userMessage });
|
11 |
+
displayMessage('user', userMessage);
|
12 |
+
userInput.value = '';
|
13 |
+
|
14 |
+
const loadingDiv = document.createElement('div');
|
15 |
+
loadingDiv.textContent = 'Assistant is typing...';
|
16 |
+
loadingDiv.className = 'message assistant';
|
17 |
+
chatWindow.appendChild(loadingDiv);
|
18 |
+
chatWindow.scrollTop = chatWindow.scrollHeight;
|
19 |
+
|
20 |
+
try {
|
21 |
+
const response = await fetch('/chat', {
|
22 |
+
method: 'POST',
|
23 |
+
headers: { 'Content-Type': 'application/json' },
|
24 |
+
body: JSON.stringify({ messages: conversation }),
|
25 |
+
});
|
26 |
+
const data = await response.json();
|
27 |
+
|
28 |
+
chatWindow.removeChild(loadingDiv);
|
29 |
+
|
30 |
+
if (data.response) {
|
31 |
+
const assistantMessage = data.response.content;
|
32 |
+
conversation.push({ role: 'assistant', content: assistantMessage });
|
33 |
+
displayMessage('assistant', assistantMessage);
|
34 |
+
} else {
|
35 |
+
displayMessage('assistant', 'Sorry, I encountered an error.');
|
36 |
+
}
|
37 |
+
} catch (error) {
|
38 |
+
console.error(error);
|
39 |
+
chatWindow.removeChild(loadingDiv);
|
40 |
+
displayMessage('assistant', 'Sorry, something went wrong.');
|
41 |
+
}
|
42 |
+
});
|
43 |
+
|
44 |
+
function displayMessage(role, content) {
|
45 |
+
const messageDiv = document.createElement('div');
|
46 |
+
messageDiv.textContent = content;
|
47 |
+
messageDiv.className = `message ${role}`;
|
48 |
+
chatWindow.appendChild(messageDiv);
|
49 |
+
chatWindow.scrollTop = chatWindow.scrollHeight;
|
50 |
+
}
|