Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
693 lines (597 loc) · 23.5 KB
/
Copy pathapp.js
File metadata and controls
693 lines (597 loc) · 23.5 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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
// State Management
let apiKey = localStorage.getItem('groq_api_key') || '';
let chats = JSON.parse(localStorage.getItem('groq_chats')) || [];
let activeChatId = localStorage.getItem('groq_active_chat_id') || '';
let currentTheme = localStorage.getItem('groq_theme') || 'dark';
// DOM Elements
const modalOverlay = document.getElementById('api-modal');
const apiKeyInput = document.getElementById('api-key-input');
const saveKeyBtn = document.getElementById('save-key-btn');
const appContainer = document.getElementById('app');
const sidebar = document.getElementById('sidebar');
const menuToggle = document.getElementById('menu-toggle');
const themeToggle = document.getElementById('theme-toggle');
const themeIcon = document.getElementById('theme-icon');
const modelSelect = document.getElementById('model-select');
const chatHistory = document.getElementById('chat-history');
const newChatBtn = document.getElementById('new-chat-btn');
const clearAllBtn = document.getElementById('clear-all-btn');
const changeKeyBtn = document.getElementById('change-key-btn');
const messagesContainer = document.getElementById('messages-container');
const welcomeScreen = document.getElementById('welcome-screen');
const messagesDiv = document.getElementById('messages');
const currentModelName = document.getElementById('current-model-name');
const userInput = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');
const suggestionCards = document.querySelectorAll('.suggestion-card');
// Initialize Application
document.addEventListener('DOMContentLoaded', () => {
initTheme();
initApp();
setupEventListeners();
});
function initTheme() {
if (currentTheme === 'light') {
document.body.classList.add('light-theme');
themeIcon.innerHTML = `<path d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364-6.364l-.707.707M6.343 17.657l-.707.707m0-12.728l.707.707m11.314 11.314l.707.707M12 8a4 4 0 1 1 0 8 4 4 0 0 1 0-8z"/>`;
} else {
document.body.classList.remove('light-theme');
themeIcon.innerHTML = `<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>`;
}
}
function initApp() {
if (!apiKey) {
modalOverlay.classList.remove('hidden');
appContainer.classList.add('hidden');
return;
}
modalOverlay.classList.add('hidden');
appContainer.classList.remove('hidden');
if (chats.length === 0) {
createNewChat();
} else {
if (!activeChatId) {
activeChatId = chats[0].id;
}
loadChat(activeChatId);
}
renderSidebar();
}
function setupEventListeners() {
// API Key Event Listeners
saveKeyBtn.addEventListener('click', saveApiKey);
apiKeyInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') saveApiKey();
});
// Theme Toggle
themeToggle.addEventListener('click', toggleTheme);
// Sidebar Mobile Toggle
menuToggle.addEventListener('click', () => {
sidebar.classList.toggle('open');
});
// Close sidebar clicking outside on mobile
document.addEventListener('click', (e) => {
if (window.innerWidth <= 768 &&
!sidebar.contains(e.target) &&
!menuToggle.contains(e.target) &&
sidebar.classList.contains('open')) {
sidebar.classList.remove('open');
}
});
// New Chat Button
newChatBtn.addEventListener('click', () => {
createNewChat();
if (window.innerWidth <= 768) {
sidebar.classList.remove('open');
}
});
// Clear All Chats
clearAllBtn.addEventListener('click', () => {
if (confirm('Are you sure you want to delete all chats?')) {
chats = [];
activeChatId = '';
localStorage.removeItem('groq_chats');
localStorage.removeItem('groq_active_chat_id');
createNewChat();
renderSidebar();
}
});
// Change API Key Button
changeKeyBtn.addEventListener('click', () => {
modalOverlay.classList.remove('hidden');
appContainer.classList.add('hidden');
});
// Model Change Selector
modelSelect.addEventListener('change', () => {
const selectedModelText = modelSelect.options[modelSelect.selectedIndex].text;
currentModelName.textContent = selectedModelText;
});
// Suggestion Cards clicks
suggestionCards.forEach(card => {
card.addEventListener('click', () => {
const promptText = card.getAttribute('data-prompt');
userInput.value = promptText;
userInput.style.height = 'auto';
userInput.style.height = userInput.scrollHeight + 'px';
sendBtn.removeAttribute('disabled');
userInput.focus();
});
});
// User Textarea Inputs
userInput.addEventListener('input', () => {
userInput.style.height = 'auto';
userInput.style.height = userInput.scrollHeight + 'px';
if (userInput.value.trim().length > 0) {
sendBtn.removeAttribute('disabled');
} else {
sendBtn.setAttribute('disabled', 'true');
}
});
userInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
sendBtn.addEventListener('click', sendMessage);
}
// Save Key and Authenticate
function saveApiKey() {
const key = apiKeyInput.value.trim();
if (!key) {
alert('Please enter a valid Groq API Key.');
return;
}
apiKey = key;
localStorage.setItem('groq_api_key', apiKey);
initApp();
}
// Toggle Theme Modes
function toggleTheme() {
if (document.body.classList.contains('light-theme')) {
currentTheme = 'dark';
} else {
currentTheme = 'light';
}
localStorage.setItem('groq_theme', currentTheme);
initTheme();
}
// Spawning and Switching Chats
function createNewChat() {
const newChat = {
id: 'chat_' + Date.now(),
title: 'New Chat',
messages: []
};
chats.unshift(newChat);
activeChatId = newChat.id;
saveChats();
loadChat(activeChatId);
renderSidebar();
}
function loadChat(chatId) {
activeChatId = chatId;
localStorage.setItem('groq_active_chat_id', activeChatId);
const activeChat = chats.find(c => c.id === chatId);
if (!activeChat) return;
// Reset current active class
const items = chatHistory.querySelectorAll('.history-item');
items.forEach(item => {
if (item.getAttribute('data-id') === chatId) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
messagesDiv.innerHTML = '';
if (activeChat.messages.length === 0) {
welcomeScreen.classList.remove('hidden');
messagesDiv.parentElement.classList.add('welcome-bg');
} else {
welcomeScreen.classList.add('hidden');
messagesDiv.parentElement.classList.remove('welcome-bg');
activeChat.messages.forEach((msg, idx) => {
if (msg.role === 'tool') {
return;
}
if (msg.tool_calls) {
const thoughtId = 'thought_hist_' + idx;
appendThoughtBox(thoughtId);
let logHTML = '';
msg.tool_calls.forEach(toolCall => {
const funcName = toolCall.function.name;
const funcArgs = toolCall.function.arguments;
logHTML += `<div class="tool-call-log">⚙️ <strong>Running Tool:</strong> <code>${funcName}</code></div>`;
logHTML += `<div class="tool-call-log">💬 <strong>Args:</strong> <code>${funcArgs}</code></div>`;
const toolResp = activeChat.messages.find((m, i) => i > idx && m.role === 'tool' && m.tool_call_id === toolCall.id);
if (toolResp) {
const trimmedOut = toolResp.content.length > 150 ? toolResp.content.substring(0, 150) + '...' : toolResp.content;
logHTML += `<div class="tool-call-log">✅ <strong>Output:</strong> ${escapedHTML(trimmedOut)}</div>`;
}
});
updateThoughtLogs(thoughtId, logHTML);
const detailsEl = document.querySelector(`#${thoughtId} details`);
if (detailsEl) detailsEl.removeAttribute('open');
return;
}
appendMessageHTML(msg.role, msg.content);
});
scrollToBottom();
}
}
function saveChats() {
localStorage.setItem('groq_chats', JSON.stringify(chats));
localStorage.setItem('groq_active_chat_id', activeChatId);
}
function renderSidebar() {
chatHistory.innerHTML = '';
chats.forEach(chat => {
const item = document.createElement('div');
item.className = `history-item ${chat.id === activeChatId ? 'active' : ''}`;
item.setAttribute('data-id', chat.id);
const titleSpan = document.createElement('span');
titleSpan.textContent = chat.title;
titleSpan.style.overflow = 'hidden';
titleSpan.style.textOverflow = 'ellipsis';
titleSpan.style.whiteSpace = 'nowrap';
titleSpan.style.marginRight = '8px';
titleSpan.style.flex = '1';
item.appendChild(titleSpan);
// Delete button for this chat
const delBtn = document.createElement('span');
delBtn.innerHTML = '✕';
delBtn.style.cursor = 'pointer';
delBtn.style.opacity = '0.5';
delBtn.style.fontSize = '0.8rem';
delBtn.style.padding = '2px 6px';
delBtn.style.borderRadius = '4px';
delBtn.addEventListener('click', (e) => {
e.stopPropagation();
deleteChat(chat.id);
});
item.appendChild(delBtn);
item.addEventListener('click', () => loadChat(chat.id));
chatHistory.appendChild(item);
});
}
function deleteChat(chatId) {
chats = chats.filter(c => c.id !== chatId);
if (activeChatId === chatId) {
activeChatId = chats.length > 0 ? chats[0].id : '';
}
saveChats();
initApp();
}
// --- Agent Tools and Functions ---
const agentTools = [
{
type: "function",
function: {
name: "get_current_time",
description: "Get the current system/local date and time.",
parameters: { type: "object", properties: {} }
}
},
{
type: "function",
function: {
name: "calculate",
description: "Evaluate basic mathematical expressions. Supporting standard operators: +, -, *, /, (, ).",
parameters: {
type: "object",
properties: {
expression: {
type: "string",
description: "The math equation to compute, e.g., '12 * (3.5 + 4)'"
}
},
required: ["expression"]
}
}
},
{
type: "function",
function: {
name: "search_wikipedia",
description: "Search Wikipedia for general information on concepts, historical events, famous people, or topics.",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "The search term to query Wikipedia for."
}
},
required: ["query"]
}
}
}
];
function getCurrentTime() {
return "Current local time: " + new Date().toLocaleString();
}
function calculateExpression(expression) {
try {
const clean = expression.replace(/[^0-9+\-*/().\s]/g, '');
const result = Function('"use strict"; return (' + clean + ')')();
return `Calculation Result for '${expression}': ${result}`;
} catch (e) {
return `Error evaluating calculation: ${e.message}`;
}
}
async function searchWikipedia(query) {
try {
const searchUrl = `https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(query)}&format=json&origin=*`;
const res = await fetch(searchUrl);
const data = await res.json();
const results = data.query?.search;
if (!results || results.length === 0) {
return `No Wikipedia results found for '${query}'.`;
}
const topTitle = results[0].title;
const summaryUrl = `https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=1&explaintext=1&titles=${encodeURIComponent(topTitle)}&format=json&origin=*`;
const summaryRes = await fetch(summaryUrl);
const summaryData = await summaryRes.json();
const pages = summaryData.query?.pages;
const pageId = Object.keys(pages)[0];
if (pageId === "-1") {
return `Found Wikipedia article '${topTitle}', but failed to retrieve its summary content.`;
}
return `Source: Wikipedia - Article: ${topTitle}\n\nSummary:\n${pages[pageId].extract}`;
} catch (e) {
return `Error retrieving Wikipedia summary: ${e.message}`;
}
}
// --- DOM Rendering Helpers for Thoughts ---
function appendThoughtBox(id) {
const messageDiv = document.createElement('div');
messageDiv.className = 'message ai agent-thought-message';
messageDiv.id = id;
messageDiv.innerHTML = `
<div class="message-content">
<details class="agent-thought-container" open>
<summary class="agent-thought-title">
<span>🤖 Agent Thought Process</span>
</summary>
<div class="agent-thought-details" id="${id}_logs">
<div class="tool-call-log">Thinking...</div>
</div>
</details>
</div>
`;
messagesDiv.appendChild(messageDiv);
}
function updateThoughtLogs(id, logHTML) {
const logsDiv = document.getElementById(`${id}_logs`);
if (logsDiv) {
logsDiv.innerHTML = logHTML;
}
}
function removeThoughtBox(id) {
const box = document.getElementById(id);
if (box) box.remove();
}
function escapedHTML(str) {
if (!str) return '';
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
}
// Message Sending and API Integration
async function sendMessage() {
const text = userInput.value.trim();
if (!text) return;
// Reset Input
userInput.value = '';
userInput.style.height = 'auto';
sendBtn.setAttribute('disabled', 'true');
const activeChat = chats.find(c => c.id === activeChatId);
if (!activeChat) return;
// Hide suggestions
welcomeScreen.classList.add('hidden');
// Save user message
activeChat.messages.push({ role: 'user', content: text });
appendMessageHTML('user', text);
scrollToBottom();
// Auto update chat title if it's the first message
if (activeChat.title === 'New Chat') {
activeChat.title = text.length > 25 ? text.substring(0, 25) + '...' : text;
renderSidebar();
}
saveChats();
// Prepare typing placeholder
const loaderId = 'loader_' + Date.now();
appendLoaderHTML(loaderId);
scrollToBottom();
try {
const selectedModel = modelSelect.value;
let loopCnt = 0;
const maxLoops = 5;
let finalResponseText = '';
let toolCallsMade = false;
let thoughtId = 'thought_' + Date.now();
let logHTML = '';
// Continue calling API while LLM requests tool execution
while (loopCnt < maxLoops) {
loopCnt++;
// Format conversation history for API request
const apiMessages = activeChat.messages.map(m => {
if (m.tool_calls) {
return {
role: m.role,
content: m.content || null,
tool_calls: m.tool_calls
};
}
if (m.role === 'tool') {
return {
role: m.role,
tool_call_id: m.tool_call_id,
name: m.name,
content: m.content
};
}
return {
role: m.role,
content: m.content
};
});
// Add system prompt context at the start
apiMessages.unshift({
role: 'system',
content: `You are an advanced AI agent chatbot powered by Groq.
You have access to tools that can check local time, perform math calculations, and lookup Wikipedia articles.
Use tools when requested or when answering a query requires information that you do not know.
Keep your replies structured, informative, and friendly. Explain briefly what tools you used if you called any.`
});
const response = await fetch('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: selectedModel,
messages: apiMessages,
tools: agentTools,
tool_choice: "auto",
temperature: 0.5,
max_tokens: 1524
})
});
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
throw new Error(errData.error?.message || `HTTP ${response.status}`);
}
const data = await response.json();
const responseMessage = data.choices[0].message;
const toolCalls = responseMessage.tool_calls;
if (toolCalls && toolCalls.length > 0) {
// If it is the first tool call of this message, remove loader and append thought box
if (!toolCallsMade) {
removeLoaderHTML(loaderId);
appendThoughtBox(thoughtId);
toolCallsMade = true;
}
// Add tool calls to history
activeChat.messages.push({
role: 'assistant',
content: responseMessage.content || '',
tool_calls: toolCalls
});
for (let toolCall of toolCalls) {
const funcName = toolCall.function.name;
const funcArgs = JSON.parse(toolCall.function.arguments);
logHTML += `<div class="tool-call-log">⚙️ <strong>Running Tool:</strong> <code>${funcName}</code></div>`;
logHTML += `<div class="tool-call-log">💬 <strong>Args:</strong> <code>${JSON.stringify(funcArgs)}</code></div>`;
updateThoughtLogs(thoughtId, logHTML + `<div class="tool-call-log">🤔 Executing...</div>`);
scrollToBottom();
let toolOut = '';
if (funcName === 'get_current_time') {
toolOut = getCurrentTime();
} else if (funcName === 'calculate') {
toolOut = calculateExpression(funcArgs.expression);
} else if (funcName === 'search_wikipedia') {
toolOut = await searchWikipedia(funcArgs.query);
} else {
toolOut = `Error: Tool '${funcName}' not found.`;
}
const trimmedOut = toolOut.length > 150 ? toolOut.substring(0, 150) + '...' : toolOut;
logHTML += `<div class="tool-call-log">✅ <strong>Output:</strong> ${escapedHTML(trimmedOut)}</div>`;
updateThoughtLogs(thoughtId, logHTML);
scrollToBottom();
// Push tool result message
activeChat.messages.push({
role: 'tool',
tool_call_id: toolCall.id,
name: funcName,
content: toolOut
});
}
saveChats();
// Show a mini loader at the bottom during the next reasoning step
appendLoaderHTML(loaderId);
scrollToBottom();
} else {
// Final text response reached
finalResponseText = responseMessage.content || '';
break;
}
}
// Clean up and display final response
removeLoaderHTML(loaderId);
// Collapse the thought box details after completion
if (toolCallsMade) {
const detailsEl = document.querySelector(`#${thoughtId} details`);
if (detailsEl) detailsEl.removeAttribute('open');
}
if (finalResponseText) {
activeChat.messages.push({ role: 'assistant', content: finalResponseText });
appendMessageHTML('assistant', finalResponseText);
saveChats();
scrollToBottom();
} else if (!toolCallsMade) {
throw new Error("No response content generated by the AI model.");
}
} catch (error) {
console.error('API Error:', error);
removeLoaderHTML(loaderId);
appendMessageHTML('assistant', `⚠️ **Error connecting to Groq:** ${error.message}\n\nPlease check that your API key is correct and you have an active internet connection.`);
scrollToBottom();
}
}
// DOM Rendering Utilities
function appendMessageHTML(role, text) {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${role === 'user' ? 'user' : 'ai'}`;
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
contentDiv.innerHTML = formatMarkdown(text);
messageDiv.appendChild(contentDiv);
messagesDiv.appendChild(messageDiv);
}
function appendLoaderHTML(id) {
const messageDiv = document.createElement('div');
messageDiv.className = 'message ai';
messageDiv.id = id;
const contentDiv = document.createElement('div');
contentDiv.className = 'message-content';
contentDiv.innerHTML = `
<div class="loader-dots">
<span></span>
<span></span>
<span></span>
</div>
`;
messageDiv.appendChild(contentDiv);
messagesDiv.appendChild(messageDiv);
}
function removeLoaderHTML(id) {
const loader = document.getElementById(id);
if (loader) loader.remove();
}
function scrollToBottom() {
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
// Markdown Formatter (Lightweight)
function formatMarkdown(text) {
// Escape HTML to prevent XSS
let escaped = text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
// 1. Code blocks (```language ... ```)
escaped = escaped.replace(/```(\w*)\n([\s\S]*?)```/g, (match, lang, code) => {
return `<pre><code class="language-${lang}">${code.trim()}</code></pre>`;
});
// 2. Inline Code (`code`)
escaped = escaped.replace(/`([^`]+)`/g, '<code>$1</code>');
// 3. Bold (**text**)
escaped = escaped.replace(/\*\*([\s\S]+?)\*\*/g, '<strong>$1</strong>');
// 4. Italic (*text*)
escaped = escaped.replace(/\*([\s\S]+?)\*/g, '<em>$1</em>');
// 5. Line breaks
escaped = escaped.replace(/\n/g, '<br>');
return escaped;
}