File size: 6,881 Bytes
7d29472
dd1b723
7d29472
 
 
 
 
 
 
 
dd1b723
7d29472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1b723
7d29472
 
 
 
 
dd1b723
7d29472
 
 
 
 
dd1b723
 
7d29472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1b723
7d29472
 
 
dd1b723
7d29472
 
 
dd1b723
7d29472
 
 
 
 
 
dd1b723
 
7d29472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1b723
7d29472
 
 
 
dd1b723
7d29472
 
 
dd1b723
 
7d29472
 
 
 
dd1b723
7d29472
 
 
dd1b723
7d29472
 
 
dd1b723
7d29472
 
 
dd1b723
7d29472
 
 
 
dd1b723
7d29472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.0';

class Chatbot {
constructor() {
this.generator = null;
this.isGenerating = false;
this.conversationHistory = [];
this.maxHistoryLength = 10;
this.currentModel = 'Xenova/distilgpt2';
this.currentDevice = 'wasm';

this.initializeElements();
this.attachEventListeners();
this.loadModel();
}

initializeElements() {
this.messagesContainer = document.getElementById('messages');
this.messageInput = document.getElementById('message-input');
this.sendButton = document.getElementById('send-button');
this.clearButton = document.getElementById('clear-chat');
this.modelSelect = document.getElementById('model-select');
this.deviceSelect = document.getElementById('device-select');
this.typingIndicator = document.getElementById('typing-indicator');
this.loadingOverlay = document.getElementById('loading-overlay');
this.errorToast = document.getElementById('error-toast');
this.errorMessage = document.getElementById('error-message');
this.charCount = document.getElementById('char-count');
this.dismissErrorBtn = document.getElementById('dismiss-error');
}

attachEventListeners() {
this.sendButton.addEventListener('click', () => this.sendMessage());
this.clearButton.addEventListener('click', () => this.clearChat());
this.modelSelect.addEventListener('change', (e) => this.changeModel(e.target.value));
this.deviceSelect.addEventListener('change', (e) => this.changeDevice(e.target.value));

this.messageInput.addEventListener('input', () => {
this.updateCharCount();
this.autoResizeTextarea();
this.sendButton.disabled = !this.messageInput.value.trim() || this.isGenerating;
});

this.messageInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
this.sendMessage();
}
});

this.dismissErrorBtn.addEventListener('click', () => this.hideError());

// Check for WebGPU support
this.checkWebGPUSupport();
}

async checkWebGPUSupport() {
if (!navigator.gpu) {
this.deviceSelect.querySelector('option[value="webgpu"]').disabled = true;
this.deviceSelect.value = 'wasm';
this.currentDevice = 'wasm';
}
}

async loadModel() {
this.showLoading();
try {
const config = {
device: this.currentDevice,
dtype: this.currentDevice === 'webgpu' ? 'fp16' : 'q4'
};

this.generator = await pipeline('text-generation', this.currentModel, config);
this.hideLoading();
this.sendButton.disabled = !this.messageInput.value.trim();
} catch (error) {
console.error('Error loading model:', error);
this.hideLoading();
this.showError('Failed to load model. Please try again or select a different model.');
this.sendButton.disabled = true;
}
}

async changeModel(modelName) {
if (modelName === this.currentModel) return;

this.currentModel = modelName;
await this.loadModel();
}

async changeDevice(device) {
if (device === this.currentDevice) return;

this.currentDevice = device;
await this.loadModel();
}

async sendMessage() {
const message = this.messageInput.value.trim();
if (!message || this.isGenerating) return;

this.addMessage(message, 'user');
this.messageInput.value = '';
this.updateCharCount();
this.autoResizeTextarea();
this.sendButton.disabled = true;
this.isGenerating = true;
this.showTypingIndicator();

try {
const prompt = this.buildPrompt(message);
const response = await this.generateResponse(prompt);
this.addMessage(response, 'bot');
} catch (error) {
console.error('Error generating response:', error);
this.showError('Failed to generate response. Please try again.');
} finally {
this.isGenerating = false;
this.hideTypingIndicator();
this.sendButton.disabled = !this.messageInput.value.trim();
}
}

buildPrompt(userMessage) {
let prompt = "You are a helpful AI assistant. Respond in a friendly and informative way.\n\n";

// Include recent conversation history
if (this.conversationHistory.length > 0) {
const recentHistory = this.conversationHistory.slice(-4);
recentHistory.forEach(msg => {
if (msg.role === 'user') {
prompt += `User: ${msg.content}\n`;
} else {
prompt += `Assistant: ${msg.content}\n`;
}
});
}

prompt += `User: ${userMessage}\nAssistant:`;
return prompt;
}

async generateResponse(prompt) {
const maxNewTokens = 100;
const temperature = 0.7;

const result = await this.generator(prompt, {
max_new_tokens: maxNewTokens,
temperature: temperature,
do_sample: true,
pad_token_id: 50256,
return_full_text: false
});

let response = result[0].generated_text.trim();

// Clean up the response
response = response.replace(/^(Assistant:|AI:|Bot:)/i, '').trim();
response = response.split('\n')[0]; // Take only the first line

if (!response) {
response = "I'm not sure how to respond to that. Could you try rephrasing?";
}

return response;
}

addMessage(content, role) {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${role}-message`;

const messageContent = document.createElement('div');
messageContent.className = 'message-content';
messageContent.innerHTML = `<p>${this.escapeHtml(content)}</p>`;

const messageTime = document.createElement('div');
messageTime.className = 'message-time';
messageTime.textContent = role === 'user' ? 'You' : 'Bot';

messageDiv.appendChild(messageContent);
messageDiv.appendChild(messageTime);

this.messagesContainer.appendChild(messageDiv);
this.scrollToBottom();

// Update conversation history
this.conversationHistory.push({ role, content });
if (this.conversationHistory.length > this.maxHistoryLength) {
this.conversationHistory.shift();
}
}

clearChat() {
this.messagesContainer.innerHTML = `
<div class="message bot-message">
  <div class="message-content">
    <p>Hello! I'm your AI assistant. How can I help you today?</p>
  </div>
  <div class="message-time">Bot</div>
</div>
`;
this.conversationHistory = [];
this.scrollToBottom();
}

updateCharCount() {
const length = this.messageInput.value.length;
this.charCount.textContent = `${length} / 500`;
}

autoResizeTextarea() {
this.messageInput.style.height = 'auto';
this.messageInput.style.height = Math.min(this.messageInput.scrollHeight, 120) + 'px';
}

showTypingIndicator() {
this.typingIndicator.classList.remove('hidden');
this.scrollToBottom();
}

hideTypingIndicator() {
this.typingIndicator.classList.add('hidden');
}

showLoading() {
this.loadingOverlay.classList.remove('hidden');
}

hideLoading() {
this.loadingOverlay.classList.add('hidden');
}

showError(message) {
this.errorMessage.textContent = message;
this.errorToast.classList.remove('hidden');
setTimeout(() => this.hideError(), 5000);
}

hideError() {
this.errorToast.classList.add('hidden');
}

scrollToBottom() {
this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
}

escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
}

// Initialize the chatbot when the page loads
document.addEventListener('DOMContentLoaded', () => {
new Chatbot();
});