swaroop77 commited on
Commit
b405f41
·
verified ·
1 Parent(s): 801abfd

Upload script.js

Browse files
Files changed (1) hide show
  1. static/script.js +142 -0
static/script.js ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ document.addEventListener('DOMContentLoaded', () => {
2
+ const chatbox = document.getElementById('chatbox');
3
+ const userInput = document.getElementById('userInput');
4
+ const sendBtn = document.getElementById('sendBtn');
5
+ const clearMemoryBtn = document.getElementById('clearMemoryBtn'); // Get the new button
6
+
7
+ // Function to append a message to the chatbox
8
+ function appendMessage(sender, text) {
9
+ const messageElement = document.createElement('div');
10
+ messageElement.classList.add('message', `${sender}-message`);
11
+
12
+ const p = document.createElement('p');
13
+ // Use textContent to avoid HTML injection
14
+ p.textContent = text;
15
+
16
+ messageElement.appendChild(p);
17
+ chatbox.appendChild(messageElement);
18
+
19
+ // Auto-scroll to the bottom
20
+ chatbox.scrollTop = chatbox.scrollHeight;
21
+ }
22
+
23
+ // Function to send message to backend
24
+ async function sendMessage() {
25
+ const messageText = userInput.value.trim();
26
+ if (messageText === "") {
27
+ return; // Don't send empty messages
28
+ }
29
+
30
+ // Append user message to chatbox
31
+ appendMessage('user', messageText);
32
+
33
+ // Clear input and disable buttons
34
+ userInput.value = '';
35
+ userInput.disabled = true;
36
+ sendBtn.disabled = true;
37
+ if (clearMemoryBtn) clearMemoryBtn.disabled = true;
38
+
39
+
40
+ // Optional: Add a loading indicator
41
+ const loadingElement = document.createElement('div');
42
+ loadingElement.classList.add('message', 'assistant-message', 'loading-indicator');
43
+ loadingElement.textContent = 'AI is thinking...';
44
+ chatbox.appendChild(loadingElement);
45
+ chatbox.scrollTop = chatbox.scrollHeight; // Scroll to show indicator
46
+
47
+
48
+ try {
49
+ const response = await fetch('/chat', {
50
+ method: 'POST',
51
+ headers: {
52
+ 'Content-Type': 'application/json',
53
+ },
54
+ body: JSON.stringify({ message: messageText }),
55
+ });
56
+
57
+ // Remove loading indicator
58
+ if (chatbox.contains(loadingElement)) {
59
+ chatbox.removeChild(loadingElement);
60
+ }
61
+
62
+
63
+ if (!response.ok) {
64
+ const errorData = await response.json().catch(() => ({})); // Try parsing JSON, fallback to empty object
65
+ const errorMessage = errorData.response || `Server returned status ${response.status}: ${response.statusText}`;
66
+ throw new Error(`Chat request failed: ${errorMessage}`);
67
+ }
68
+
69
+ const data = await response.json();
70
+ appendMessage('assistant', data.response);
71
+
72
+ } catch (error) {
73
+ console.error('Error sending message:', error);
74
+ // Remove loading indicator if still present
75
+ if (chatbox.contains(loadingElement)) {
76
+ chatbox.removeChild(loadingElement);
77
+ }
78
+ appendMessage('assistant', `Error: Could not get a response. ${error.message}`);
79
+ } finally {
80
+ // Re-enable input and buttons
81
+ userInput.disabled = false;
82
+ sendBtn.disabled = false;
83
+ if (clearMemoryBtn) clearMemoryBtn.disabled = false;
84
+ userInput.focus(); // Put focus back on input field
85
+ }
86
+ }
87
+
88
+ // Function to clear memory
89
+ async function clearMemory() {
90
+ if (confirm("Are you sure you want to clear the chat history? This will start a new conversation.")) {
91
+ // Disable buttons during clear
92
+ userInput.disabled = true;
93
+ sendBtn.disabled = true;
94
+ if (clearMemoryBtn) clearMemoryBtn.disabled = true;
95
+
96
+ try {
97
+ const response = await fetch('/clear_memory', {
98
+ method: 'POST',
99
+ });
100
+
101
+ if (!response.ok) {
102
+ const errorData = await response.json().catch(() => ({}));
103
+ const errorMessage = errorData.status || `Server returned status ${response.status}: ${response.statusText}`;
104
+ throw new Error(`Clear memory request failed: ${errorMessage}`);
105
+ }
106
+
107
+ // Clear the chatbox UI and add initial message
108
+ chatbox.innerHTML = ''; // Clear all messages
109
+ appendMessage('assistant', 'Chat history cleared. Starting a new conversation!');
110
+ appendMessage('assistant', 'Hello! I\'m an AI chatbot with memory. How can I help you today?');
111
+
112
+
113
+ } catch (error) {
114
+ console.error('Error clearing memory:', error);
115
+ appendMessage('assistant', `Error: Could not clear chat history. ${error.message}`);
116
+ } finally {
117
+ // Re-enable buttons
118
+ userInput.disabled = false;
119
+ sendBtn.disabled = false;
120
+ if (clearMemoryBtn) clearMemoryBtn.disabled = false;
121
+ userInput.focus();
122
+ }
123
+ }
124
+ }
125
+
126
+
127
+ // Event listeners
128
+ sendBtn.addEventListener('click', sendMessage);
129
+ userInput.addEventListener('keypress', function(event) {
130
+ if (event.key === 'Enter') {
131
+ event.preventDefault(); // Prevent newline in input
132
+ sendMessage();
133
+ }
134
+ });
135
+
136
+ // Add event listener for the clear memory button
137
+ if (clearMemoryBtn) {
138
+ clearMemoryBtn.addEventListener('click', clearMemory);
139
+ }
140
+
141
+ // Initial welcome message is already in index.html
142
+ });