-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
403 lines (340 loc) · 13.3 KB
/
Copy pathmain.js
File metadata and controls
403 lines (340 loc) · 13.3 KB
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {}, err => {
console.log('ServiceWorker registration failed: ', err);
});
});
}
// Constants
const API_KEY = 'AIzaSyBlSmMlgbg6PiCObRP26XemuGPfZXhGO04';
const API_URL = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent';
// DOM Elements
const chatMessages = document.getElementById('chat-messages');
const userInput = document.getElementById('user-input');
const sendButton = document.getElementById('send-button');
const listenButton = document.getElementById('listen-button');
const newChatButton = document.querySelector('.new-chat-button');
// State management
let currentChatId = generateChatId();
let chatHistory = new Map();
let isProcessing = false;
// Initialize speech recognition
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.lang = 'en-US';
recognition.continuous = false;
recognition.interimResults = false;
// Enhanced prompt engineering with structured response guidance
function createEnhancedPrompt(message, context = []) {
return {
contents: [{
parts: [{
text: `You are Pyxis AI, a helpful and knowledgeable assistant. Please provide a clear, structured response using:
- Headings with Bold text and colons
- Bullet points using • symbol
- Numbered lists where appropriate
- CAPS for important information
- Clear paragraphs with line breaks
Previous context: ${context.join(' ')}
Current message: ${message}`
}]
}]
};
}
function toggleSidebar() {
const sidebar = document.querySelector('.sidebar');
sidebar.classList.toggle('show');
}
document.addEventListener('DOMContentLoaded', function() {
const sidebar = document.querySelector('.sidebar');
const chatContainer = document.querySelector('.chat-container');
// Create and add pin button
const pinButton = document.createElement('button');
pinButton.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-bar-right" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M6 8a.5.5 0 0 0 .5.5h5.793l-2.147 2.146a.5.5 0 0 0 .708.708l3-3a.5.5 0 0 0 0-.708l-3-3a.5.5 0 0 0-.708.708L12.293 7.5H6.5A.5.5 0 0 0 6 8m-2.5 7a.5.5 0 0 1-.5-.5v-13a.5.5 0 0 1 1 0v13a.5.5 0 0 1-.5.5"/></svg>';
pinButton.className = 'pin-button';
sidebar.appendChild(pinButton);
// Create hover area
const hoverArea = document.createElement('div');
hoverArea.className = 'sidebar-hover-area';
document.body.appendChild(hoverArea);
let isPinned = false;
let isHovering = false;
pinButton.addEventListener('click', function() {
isPinned = !isPinned;
sidebar.classList.toggle('pinned', isPinned);
pinButton.classList.toggle('active', isPinned);
if (isPinned) {
sidebar.style.left = '0';
} else {
sidebar.style.left = isHovering ? '0' : '-280px';
}
});
// Handle sidebar hover
function showSidebar() {
if (!isPinned) {
isHovering = true;
sidebar.style.left = '0';
}
}
function hideSidebar() {
if (!isPinned) {
isHovering = false;
sidebar.style.left = '-280px';
}
}
hoverArea.addEventListener('mouseenter', showSidebar);
sidebar.addEventListener('mouseenter', showSidebar);
sidebar.addEventListener('mouseleave', hideSidebar);
});
function usePrompt(value) {
const userInput = document.getElementById('user-input');
userInput.value = value;
}
// Ensure only 5 chats are displayed, show the rest as hidden
function limitChatHistory() {
const chatItems = document.querySelectorAll('.chat-item');
chatItems.forEach((item, index) => {
if (index >= 5) {
item.style.display = 'none'; // Hide chats after the 5th one
}
});
}
limitChatHistory();
// API interaction with retry mechanism
async function fetchAIResponse(prompt, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(`${API_URL}?key=${API_KEY}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(prompt)
});
if (response.status === 429) {
// Exponential backoff
await new Promise(resolve => setTimeout(resolve, 2000 * Math.pow(2, i)));
continue;
}
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
if (data.candidates && data.candidates[0]?.content?.parts?.[0]?.text) {
return data.candidates[0].content.parts[0].text;
} else {
throw new Error('Invalid response structure');
}
} catch (error) {
console.error(`Attempt ${i + 1} failed:`, error);
if (i === retries - 1) throw error;
}
}
}
// Enhanced message rendering with formatting
function addMessage(text, type) {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${type}-message`;
const avatar = document.createElement('div');
avatar.className = 'message-avatar';
avatar.textContent = type === 'user' ? 'U' : 'AI';
const content = document.createElement('div');
content.className = 'message-content';
// Format AI responses
if (type === 'ai') {
// Remove any asterisks from the text
text = text.replace(/\*/g, '');
// Split response into sections
const sections = text.split('\n\n');
sections.forEach(section => {
if (section.trim()) {
// Handle headings (lines ending with ':')
if (section.trim().match(/^.+:$/m)) {
const heading = document.createElement('h3');
heading.style.fontWeight = 'bold';
heading.style.fontSize = '1.2em';
heading.style.marginTop = '1em';
heading.textContent = section.trim();
content.appendChild(heading);
}
// Handle bullet points
else if (section.includes('•')) {
const ul = document.createElement('ul');
ul.style.marginLeft = '20px';
section.split('\n').forEach(line => {
if (line.trim()) {
const li = document.createElement('li');
li.textContent = line.replace('•', '').trim();
ul.appendChild(li);
}
});
content.appendChild(ul);
}
// Handle numbered lists
else if (section.match(/^\d+\./m)) {
const ol = document.createElement('ol');
ol.style.marginLeft = '20px';
section.split('\n').forEach(line => {
if (line.trim()) {
const li = document.createElement('li');
li.textContent = line.replace(/^\d+\./, '').trim();
ol.appendChild(li);
}
});
content.appendChild(ol);
}
// Handle important text (in caps)
else if (section.match(/[A-Z]{3,}/)) {
const p = document.createElement('p');
p.innerHTML = section.replace(/([A-Z]{3,})/g, '<strong style="color: #ff4444">$1</strong>');
content.appendChild(p);
}
// Regular paragraphs
else {
const p = document.createElement('p');
p.textContent = section;
p.style.marginBottom = '0.5em';
content.appendChild(p);
}
}
});
} else {
// User messages remain unchanged
content.textContent = text;
}
messageDiv.appendChild(avatar);
messageDiv.appendChild(content);
chatMessages.appendChild(messageDiv);
scrollToBottom();
}
// Message handling with improved context
async function sendMessage() {
if (isProcessing) return;
const message = userInput.value.trim();
if (!message) return;
isProcessing = true;
userInput.value = '';
userInput.style.height = 'auto';
// Add user message
addMessage(message, 'user');
// Get recent context
const recentMessages = Array.from(chatMessages.children)
.slice(-4)
.map(msg => msg.querySelector('.message-content').textContent);
// Show loading indicator
const loadingDiv = document.createElement('div');
loadingDiv.className = 'message ai-message loading';
loadingDiv.innerHTML = `
<div class="message-avatar">AI</div>
<div class="loading">
<div class="loading-dot"></div>
<div class="loading-dot"></div>
<div class="loading-dot"></div>
</div>
`;
chatMessages.appendChild(loadingDiv);
scrollToBottom();
try {
const prompt = createEnhancedPrompt(message, recentMessages);
const aiResponse = await fetchAIResponse(prompt);
// Process and clean the response
const processedResponse = aiResponse
.trim()
.replace(/^As Pyxis AI,?/i, '')
.replace(/^I would respond:?/i, '')
.trim();
loadingDiv.remove();
addMessage(processedResponse, 'ai');
// Save to chat history
saveChat(currentChatId, Array.from(chatMessages.children).map(msg => ({
type: msg.classList.contains('user-message') ? 'user' : 'ai',
content: msg.querySelector('.message-content').textContent
})));
updateChatList();
} catch (error) {
console.error('Error:', error);
loadingDiv.remove();
addMessage('Temporarily Closed. Please try after some time.', 'ai');
} finally {
isProcessing = false;
}
}
// Utility functions
function generateChatId() {
return `chat_${Date.now()}`;
}
function scrollToBottom() {
chatMessages.scrollTop = chatMessages.scrollHeight;
}
function saveChat(chatId, messages) {
chatHistory.set(chatId, messages);
try {
localStorage.setItem('chatHistory', JSON.stringify([...chatHistory]));
} catch (e) {
console.error('Error saving chat history:', e);
}
}
function loadChatHistory() {
try {
const saved = localStorage.getItem('chatHistory');
if (saved) {
chatHistory = new Map(JSON.parse(saved));
updateChatList();
}
} catch (error) {
console.error('Error loading chat history:', error);
chatHistory = new Map();
}
}
function updateChatList() {
const chatList = document.querySelector('.chat-list');
if (!chatList) return;
chatList.innerHTML = '';
chatHistory.forEach((messages, chatId) => {
const chatItem = document.createElement('div');
chatItem.className = `chat-item ${chatId === currentChatId ? 'active' : ''}`;
chatItem.textContent = messages[0]?.content?.slice(0, 30) + '...' || 'New Chat';
chatItem.onclick = () => loadChat(chatId);
chatList.appendChild(chatItem);
});
}
function loadChat(chatId) {
currentChatId = chatId;
chatMessages.innerHTML = '';
const messages = chatHistory.get(chatId) || [];
messages.forEach(msg => addMessage(msg.content, msg.type));
updateChatList();
}
// Event listeners
userInput.addEventListener('input', function() {
this.style.height = 'auto';
this.style.height = Math.min(this.scrollHeight, 200) + 'px';
});
sendButton.addEventListener('click', sendMessage);
userInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
listenButton.addEventListener('click', () => {
recognition.start();
});
newChatButton.addEventListener('click', () => {
currentChatId = generateChatId();
chatMessages.innerHTML = '';
addMessage('Hello! I\'m Pyxis AI. How can I help you today?', 'ai');
updateChatList();
});
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
userInput.value = transcript;
sendMessage();
};
// Initialize
document.addEventListener('DOMContentLoaded', () => {
loadChatHistory();
if (!chatHistory.has(currentChatId)) {
addMessage('Hello! I\'m Pyxis AI. How can I help you today?', 'ai');
}
});