File size: 6,003 Bytes
c502257
dd1b723
c502257
 
 
 
dd1b723
c502257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1b723
c502257
dd1b723
c502257
 
 
 
 
dd1b723
c502257
 
 
 
 
 
 
dd1b723
c502257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1b723
c502257
 
dd1b723
c502257
 
 
dd1b723
c502257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1b723
 
c502257
 
dd1b723
c502257
 
dd1b723
c502257
 
 
dd1b723
 
c502257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd1b723
c502257
 
 
dd1b723
c502257
 
 
dd1b723
c502257
 
dd1b723
c502257
 
 
 
dd1b723
c502257
 
 
 
 
 
 
 
 
 
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
import { pipeline, TextStreamer } from 'https://cdn.jsdelivr.net/npm/@huggingface/[email protected]';

// DOM Elements
const messagesContainer = document.getElementById('messages');
const userInput = document.getElementById('userInput');
const sendBtn = document.getElementById('sendBtn');
const status = document.getElementById('status');
const loadingOverlay = document.getElementById('loadingOverlay');
const loadingText = document.getElementById('loadingText');
const progressFill = document.getElementById('progressFill');
const progressText = document.getElementById('progressText');

// State
let generator = null;
let conversationHistory = [
{ role: "system", content: "You are a helpful, friendly, and knowledgeable AI assistant. Provide clear, concise, and
accurate responses." }
];
let isGenerating = false;

// Initialize the application
async function initializeApp() {
try {
updateLoadingStatus('Loading AI model...', 0);

// Create a text generation pipeline with progress callback
generator = await pipeline(
"text-generation",
"onnx-community/Llama-3.2-1B-Instruct-q4f16",
{
dtype: "q4f16",
device: "webgpu",
progress_callback: (progress) => {
if (progress.status === 'progress') {
const percent = Math.round((progress.loaded / progress.total) * 100);
updateLoadingStatus(`Loading ${progress.file}...`, percent);
} else if (progress.status === 'done') {
updateLoadingStatus('Initializing model...', 95);
}
}
}
);

updateLoadingStatus('Ready!', 100);

// Hide loading overlay after a short delay
setTimeout(() => {
loadingOverlay.classList.add('hidden');
enableChat();
}, 500);

} catch (error) {
console.error('Error initializing model:', error);
updateLoadingStatus('Error loading model. Please refresh the page.', 0);
status.textContent = 'Failed to load AI model. Please refresh.';
status.style.color = '#FF3B30';
}
}

function updateLoadingStatus(text, percent) {
loadingText.textContent = text;
progressFill.style.width = `${percent}%`;
progressText.textContent = `${percent}%`;
}

function enableChat() {
userInput.disabled = false;
sendBtn.disabled = false;
status.textContent = 'Ready to chat';
userInput.focus();
}

function addMessage(role, content) {
// Remove welcome message if it exists
const welcomeMessage = messagesContainer.querySelector('.welcome-message');
if (welcomeMessage) {
welcomeMessage.remove();
}

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

const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
contentDiv.textContent = content;

messageDiv.appendChild(contentDiv);
messagesContainer.appendChild(messageDiv);

// Scroll to bottom
messagesContainer.scrollTop = messagesContainer.scrollHeight;

return contentDiv;
}

function addTypingIndicator() {
const messageDiv = document.createElement('div');
messageDiv.className = 'message assistant';
messageDiv.id = 'typing-indicator';

const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';

const typingDiv = document.createElement('div');
typingDiv.className = 'typing-indicator';
typingDiv.innerHTML = `
<div class="typing-dot"></div>
<div class="typing-dot"></div>
<div class="typing-dot"></div>
`;

contentDiv.appendChild(typingDiv);
messageDiv.appendChild(contentDiv);
messagesContainer.appendChild(messageDiv);

messagesContainer.scrollTop = messagesContainer.scrollHeight;

return messageDiv;
}

function removeTypingIndicator() {
const indicator = document.getElementById('typing-indicator');
if (indicator) {
indicator.remove();
}
}

async function generateResponse(userMessage) {
if (isGenerating) return;

isGenerating = true;
sendBtn.disabled = true;
userInput.disabled = true;
status.textContent = 'Thinking...';

// Add user message to conversation history
conversationHistory.push({ role: "user", content: userMessage });

// Show typing indicator
const typingIndicator = addTypingIndicator();

try {
let assistantMessage = '';
let messageElement = null;

// Create a custom streamer with callback
const streamer = new TextStreamer(generator.tokenizer, {
skip_prompt: true,
skip_special_tokens: true,
callback_function: (text) => {
// Remove typing indicator on first token
if (!messageElement) {
removeTypingIndicator();
messageElement = addMessage('assistant', '');
}

// Append the new text
assistantMessage += text;
messageElement.textContent = assistantMessage;

// Scroll to bottom
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
});

// Generate response with streaming
const output = await generator(conversationHistory, {
max_new_tokens: 512,
do_sample: false,
temperature: 0.7,
streamer: streamer,
});

// Get the final response
const finalResponse = output[0].generated_text.at(-1).content;

// Update conversation history
conversationHistory.push({ role: "assistant", content: finalResponse });

// Ensure the final message is displayed
if (messageElement) {
messageElement.textContent = finalResponse;
}

status.textContent = 'Ready to chat';

} catch (error) {
console.error('Error generating response:', error);
removeTypingIndicator();
addMessage('assistant', 'Sorry, I encountered an error. Please try again.');
status.textContent = 'Error occurred';
} finally {
isGenerating = false;
sendBtn.disabled = false;
userInput.disabled = false;
userInput.focus();
}
}

function handleSend() {
const message = userInput.value.trim();

if (!message || isGenerating) return;

// Add user message to UI
addMessage('user', message);

// Clear input
userInput.value = '';
userInput.style.height = 'auto';

// Generate response
generateResponse(message);
}

// Event Listeners
sendBtn.addEventListener('click', handleSend);

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

// Auto-resize textarea
userInput.addEventListener('input', () => {
userInput.style.height = 'auto';
userInput.style.height = userInput.scrollHeight + 'px';
});

// Initialize the app
initializeApp();