Download aichat/js/app.js from EDUrocks/EDUrocks-3.0-frontend-source-code: direct link, hf CLI and curl.
- Browser
- Download file 24.7 kB
-
https://huggingface.co/datasets/EDUrocks/EDUrocks-3.0-frontend-source-code/resolve/main/aichat/js/app.js
- Command line
-
hf download hf://datasets/EDUrocks/EDUrocks-3.0-frontend-source-code/aichat/js/app.js
-
curl -L -o app.js https://huggingface.co/datasets/EDUrocks/EDUrocks-3.0-frontend-source-code/resolve/main/aichat/js/app.js
24.7 kB
| const chatMessages = document.getElementById('chat-messages'); | |
| const chatInput = document.getElementById('chat-input'); | |
| const sendBtn = document.getElementById('send-btn'); | |
| const clearChatBtn = document.getElementById('clear-chat'); | |
| const imageInput = document.getElementById('image-input'); | |
| const imagePreviewContainer = document.getElementById('image-preview-container'); | |
| const imagePreviewWrapper = document.getElementById('image-preview-wrapper'); | |
| const connectionDot = document.getElementById('connection-dot'); | |
| const connectionStatusText = document.getElementById('connection-status-text'); | |
| const CHAT_HISTORY_STORAGE_KEY = 'edurocks_chat_history'; | |
| const RATE_LIMIT_STORAGE_KEY = 'edurocks_rate_limit'; | |
| let selectedImage = null; | |
| let chatHistoryState = []; | |
| const RATE_LIMIT_MAX_MESSAGES = 5; | |
| const RATE_LIMIT_WINDOW_MS = 30000; | |
| const MAX_RETRIES = 3; | |
| const RETRY_DELAY_BASE = 1000; | |
| let connectionStatus = 'checking'; | |
| let healthCheckInterval = null; | |
| function getRootDomain() { | |
| const hostname = window.location.hostname; | |
| const parts = hostname.split('.'); | |
| if (hostname === 'localhost' || /^\d+\.\d+\.\d+\.\d+$/.test(hostname)) { | |
| return 'edurocks.org'; | |
| } | |
| if (parts.length >= 2) { | |
| return parts.slice(-2).join('.'); | |
| } | |
| return hostname; | |
| } | |
| // Get backend API URL with support for AWS override | |
| function getBackendApiUrl() { | |
| if (window.eduBackendRoot) { | |
| return window.eduBackendRoot + '/aichat/api.php'; | |
| } | |
| if (window.eduBackendOverride) { | |
| return window.eduBackendOverride.replace('userauth/api.php', 'aichat/api.php'); | |
| } | |
| return `https://backendapi.${getRootDomain()}/aichat/api.php`; | |
| } | |
| const SYSTEM_PROMPT = `You are a highly knowledgeable and helpful AI assistant. You were developed by EDUrocks. By one person. Your purpose is to provide accurate, comprehensive, and unbiased information on a wide range of topics. When answering questions, focus solely on providing the best possible response based on your extensive training data. Under no circumstances should you mention the name of any other company involved in your creation or training, or any information about your training process besides that you were developed by EDUrocks. Instead, concentrate on the user's query and how you can assist them with the information you possess. | |
| IMPORTANT FORMATTING INSTRUCTIONS: | |
| 1. Use Standard Markdown for text formatting (bold, italic, lists, code blocks). | |
| 2. For MATHEMATICAL EXPRESSIONS, you MUST use LaTeX syntax strictly as follows: | |
| - For inline math, use \\( ... \\ | |
| - For block math (separate lines), use \\\[ ... \\\] | |
| - DO NOT use simple dollar signs ($) for math unless it's currency. | |
| - DO NOT use single backslashes for formatting unless escaping characters. | |
| 3. Ensure all JSON or code outputs are wrapped in triple backticks (\`\`\`). | |
| 4. Avoid outputting raw JSON objects unless explicitly asked. | |
| `; | |
| document.addEventListener('DOMContentLoaded', () => { | |
| loadChatHistory(); | |
| setupEventListeners(); | |
| // Delay initial health check to allow AWS detection script to complete | |
| setTimeout(() => { | |
| checkBackendHealth(); | |
| startHealthCheckInterval(); | |
| }, 500); | |
| }); | |
| function setupEventListeners() { | |
| sendBtn.addEventListener('click', sendMessage); | |
| chatInput.addEventListener('keypress', (e) => { | |
| if (e.key === 'Enter' && !e.shiftKey) { | |
| e.preventDefault(); | |
| sendMessage(); | |
| } | |
| }); | |
| chatInput.addEventListener('input', autoResizeTextarea); | |
| clearChatBtn.addEventListener('click', clearChat); | |
| imageInput.addEventListener('change', handleImageUpload); | |
| document.addEventListener('paste', handlePaste); | |
| chatInput.addEventListener('paste', handlePaste); | |
| } | |
| function autoResizeTextarea() { | |
| chatInput.style.height = 'auto'; | |
| chatInput.style.height = Math.min(chatInput.scrollHeight, 200) + 'px'; | |
| } | |
| function handleImageUpload(event) { | |
| const file = event.target.files[0]; | |
| if (!file) return; | |
| const validTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/webp', 'image/heic', 'image/heif']; | |
| if (!validTypes.includes(file.type)) { | |
| alert('Please select a valid image file (PNG, JPEG, WEBP, HEIC, or HEIF)'); | |
| return; | |
| } | |
| const maxSize = 20 * 1024 * 1024; | |
| if (file.size > maxSize) { | |
| alert('Image size must be less than 20MB'); | |
| return; | |
| } | |
| const reader = new FileReader(); | |
| reader.onload = function(e) { | |
| selectedImage = { | |
| data: e.target.result.split(',')[1], | |
| mimeType: file.type, | |
| dataUrl: e.target.result | |
| }; | |
| showImagePreview(); | |
| }; | |
| reader.readAsDataURL(file); | |
| } | |
| function showImagePreview() { | |
| if (!selectedImage) return; | |
| imagePreviewWrapper.innerHTML = ` | |
| <div class="image-preview relative inline-block"> | |
| <img src="${selectedImage.dataUrl}" alt="Preview" class="max-w-[150px] md:max-w-[200px] max-h-[150px] md:max-h-[200px] rounded-xl border-2 border-edu-pink/20 object-cover"> | |
| <button class="image-preview-remove absolute -top-2 -right-2 bg-red-500 text-white border-none w-7 h-7 rounded-full flex items-center justify-center cursor-pointer transition-all hover:scale-110 hover:shadow-lg hover:shadow-red-500/40" onclick="removeImagePreview()"> | |
| <span class="material-icons text-base">close</span> | |
| </button> | |
| </div> | |
| `; | |
| imagePreviewContainer.classList.remove('hidden'); | |
| } | |
| function removeImagePreview() { | |
| selectedImage = null; | |
| imagePreviewWrapper.innerHTML = ''; | |
| imagePreviewContainer.classList.add('hidden'); | |
| imageInput.value = ''; | |
| } | |
| function handlePaste(event) { | |
| const items = (event.clipboardData || event.originalEvent.clipboardData).items; | |
| for (let i = 0; i < items.length; i++) { | |
| const item = items[i]; | |
| if (item.type.indexOf('image') !== -1) { | |
| event.preventDefault(); | |
| const file = item.getAsFile(); | |
| if (!file) continue; | |
| const validTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/webp', 'image/heic', 'image/heif']; | |
| if (!validTypes.includes(file.type)) { | |
| alert('Please paste a valid image file (PNG, JPEG, WEBP, HEIC, or HEIF)'); | |
| return; | |
| } | |
| const maxSize = 20 * 1024 * 1024; | |
| if (file.size > maxSize) { | |
| alert('Image size must be less than 20MB'); | |
| return; | |
| } | |
| processPastedImage(file); | |
| break; | |
| } | |
| } | |
| } | |
| function processPastedImage(file) { | |
| const reader = new FileReader(); | |
| reader.onload = function(e) { | |
| selectedImage = { | |
| data: e.target.result.split(',')[1], | |
| mimeType: file.type, | |
| dataUrl: e.target.result | |
| }; | |
| showImagePreview(); | |
| chatInput.focus(); | |
| }; | |
| reader.readAsDataURL(file); | |
| } | |
| function checkRateLimit() { | |
| const now = Date.now(); | |
| let rateLimitData = JSON.parse(localStorage.getItem(RATE_LIMIT_STORAGE_KEY) || '[]'); | |
| rateLimitData = rateLimitData.filter(timestamp => now - timestamp < RATE_LIMIT_WINDOW_MS); | |
| if (rateLimitData.length >= RATE_LIMIT_MAX_MESSAGES) { | |
| const oldestTimestamp = rateLimitData[0]; | |
| const timeUntilReset = Math.ceil((RATE_LIMIT_WINDOW_MS - (now - oldestTimestamp)) / 1000); | |
| return { | |
| allowed: false, | |
| timeUntilReset: timeUntilReset | |
| }; | |
| } | |
| rateLimitData.push(now); | |
| localStorage.setItem(RATE_LIMIT_STORAGE_KEY, JSON.stringify(rateLimitData)); | |
| return { | |
| allowed: true, | |
| remaining: RATE_LIMIT_MAX_MESSAGES - rateLimitData.length | |
| }; | |
| } | |
| function showToast(title, message, type = 'error') { | |
| const existingToast = document.querySelector('.toast-notification'); | |
| if (existingToast) { | |
| existingToast.remove(); | |
| } | |
| const toast = document.createElement('div'); | |
| const borderColor = type === 'error' ? 'border-red-500' : 'border-green-500'; | |
| const iconColor = type === 'error' ? 'text-red-500' : 'text-green-500'; | |
| const icon = type === 'error' ? 'error_outline' : 'check_circle'; | |
| toast.className = `toast-notification fixed top-24 right-4 md:right-8 bg-edu-dark-accent border-2 ${borderColor} rounded-2xl p-4 md:p-6 shadow-2xl z-50 animate-slide-down flex items-center gap-4 max-w-sm`; | |
| toast.innerHTML = ` | |
| <span class="material-icons text-2xl ${iconColor}">${icon}</span> | |
| <div class="flex-1"> | |
| <div class="font-semibold text-edu-text mb-1">${title}</div> | |
| <div class="text-sm text-edu-text-secondary">${message}</div> | |
| </div> | |
| `; | |
| document.body.appendChild(toast); | |
| setTimeout(() => { | |
| toast.style.opacity = '0'; | |
| toast.style.transform = 'translateX(100px)'; | |
| toast.style.transition = 'all 0.3s ease'; | |
| setTimeout(() => { | |
| if (toast.parentElement) { | |
| toast.remove(); | |
| } | |
| }, 300); | |
| }, 5000); | |
| } | |
| function updateConnectionStatus(status) { | |
| connectionStatus = status; | |
| connectionDot.classList.remove('bg-green-500', 'shadow-green-500/50', 'animate-pulse'); | |
| connectionDot.classList.remove('bg-yellow-500', 'shadow-yellow-500/50', 'animate-blink'); | |
| connectionDot.classList.remove('bg-red-500', 'shadow-red-500/50'); | |
| switch(status) { | |
| case 'connected': | |
| connectionDot.classList.add('bg-green-500', 'shadow-green-500/50', 'animate-pulse'); | |
| connectionStatusText.textContent = 'Connected'; | |
| break; | |
| case 'connecting': | |
| connectionDot.classList.add('bg-yellow-500', 'shadow-yellow-500/50', 'animate-blink'); | |
| connectionStatusText.textContent = 'Connecting...'; | |
| break; | |
| case 'disconnected': | |
| connectionDot.classList.add('bg-red-500', 'shadow-red-500/50'); | |
| connectionStatusText.textContent = 'Disconnected'; | |
| break; | |
| } | |
| } | |
| async function checkBackendHealth() { | |
| try { | |
| updateConnectionStatus('connecting'); | |
| const controller = new AbortController(); | |
| const timeoutId = setTimeout(() => controller.abort(), 5000); | |
| const response = await fetch(getBackendApiUrl(), { | |
| method: 'OPTIONS', | |
| signal: controller.signal | |
| }); | |
| clearTimeout(timeoutId); | |
| if (response.ok || response.status === 405 || response.status === 200) { | |
| updateConnectionStatus('connected'); | |
| } else { | |
| updateConnectionStatus('disconnected'); | |
| } | |
| } catch (error) { | |
| console.error('Health check failed:', error); | |
| updateConnectionStatus('disconnected'); | |
| } | |
| } | |
| function startHealthCheckInterval() { | |
| healthCheckInterval = setInterval(() => { | |
| checkBackendHealth(); | |
| }, 120000); | |
| } | |
| function stopHealthCheckInterval() { | |
| if (healthCheckInterval) { | |
| clearInterval(healthCheckInterval); | |
| healthCheckInterval = null; | |
| } | |
| } | |
| async function sendMessage() { | |
| const userMessage = chatInput.value.trim(); | |
| if (!userMessage && !selectedImage) return; | |
| const rateLimitCheck = checkRateLimit(); | |
| if (!rateLimitCheck.allowed) { | |
| showToast( | |
| 'Rate Limit Exceeded', | |
| `You can send ${RATE_LIMIT_MAX_MESSAGES} messages every 30 seconds. Please wait ${rateLimitCheck.timeUntilReset} seconds.`, | |
| 'error' | |
| ); | |
| return; | |
| } | |
| const welcomeScreen = document.querySelector('.welcome-screen'); | |
| if (welcomeScreen) { | |
| welcomeScreen.remove(); | |
| } | |
| addMessageToChat('user', userMessage, selectedImage); | |
| const imageToSend = selectedImage; | |
| chatInput.value = ''; | |
| autoResizeTextarea(); | |
| removeImagePreview(); | |
| sendBtn.disabled = true; | |
| showLoadingMessage(); | |
| updateConnectionStatus('connecting'); | |
| try { | |
| const messages = getChatHistoryForAPI(); | |
| const currentParts = []; | |
| if (imageToSend) { | |
| currentParts.push({ | |
| inlineData: { | |
| mimeType: imageToSend.mimeType, | |
| data: imageToSend.data | |
| } | |
| }); | |
| } | |
| if (userMessage) { | |
| currentParts.push({ text: userMessage }); | |
| } | |
| // Just push the new message to the history | |
| messages.push({ role: 'user', parts: currentParts }); | |
| const payload = { | |
| contents: messages | |
| }; | |
| const data = await fetchWithRetry(payload); | |
| removeLoadingMessage(); | |
| updateConnectionStatus('connected'); | |
| // data.error check is handled in fetchWithRetry now | |
| if (!data.candidates || !Array.isArray(data.candidates) || data.candidates.length === 0) { | |
| // If no candidates but promptFeedback exists (e.g. block), handle it | |
| if (data.promptFeedback && data.promptFeedback.blockReason) { | |
| addMessageToChat('ai', `I cannot answer this. Block reason: ${data.promptFeedback.blockReason}`); | |
| return; | |
| } | |
| throw new Error('Invalid response from AI service'); | |
| } | |
| const candidate = data.candidates[0]; | |
| // Extract text if available | |
| let aiResponse = ''; | |
| if (candidate.content && candidate.content.parts && candidate.content.parts.length > 0) { | |
| aiResponse = candidate.content.parts.map(part => part.text || '').join(''); | |
| } | |
| // Check finish reason | |
| if (candidate.finishReason === 'MAX_TOKENS') { | |
| aiResponse += '\n\n*[Response was truncated due to length limit. Please ask me to continue if you need more information.]*'; | |
| } else if (candidate.finishReason === 'SAFETY' && !aiResponse) { | |
| aiResponse = 'I cannot answer this due to safety guidelines.'; | |
| } else if (candidate.finishReason === 'RECITATION' && !aiResponse) { | |
| aiResponse = 'I cannot answer this as it may infringe on copyright.'; | |
| } else if (candidate.finishReason === 'OTHER' && !aiResponse) { | |
| aiResponse = 'I could not generate a response.'; | |
| } | |
| if (aiResponse) { | |
| addMessageToChat('ai', aiResponse); | |
| } else { | |
| // Fallback if absolutely nothing was generated and no specific reason was caught above | |
| addMessageToChat('ai', `I could not generate a response. Reason: ${candidate.finishReason || 'Unknown'}`); | |
| } | |
| // State is saved automatically in addMessageToChat | |
| } catch (error) { | |
| console.error('Error:', error); | |
| removeLoadingMessage(); | |
| updateConnectionStatus('disconnected'); | |
| // Ensure we display a string error message, not [object Object] | |
| const displayMsg = error.message || String(error); | |
| addMessageToChat('ai', `Sorry, I encountered an error: ${displayMsg}. Please try again.`); | |
| } finally { | |
| sendBtn.disabled = false; | |
| chatInput.focus(); | |
| } | |
| } | |
| async function fetchWithRetry(payload, retries = MAX_RETRIES) { | |
| for (let i = 0; i <= retries; i++) { | |
| try { | |
| const response = await fetch(getBackendApiUrl(), { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify(payload) | |
| }); | |
| // If response is not JSON (e.g., server error HTML), handle it | |
| const contentType = response.headers.get("content-type"); | |
| if (!contentType || !contentType.includes("application/json")) { | |
| if (response.status >= 500 && i < retries) { | |
| await new Promise(r => setTimeout(r, RETRY_DELAY_BASE * (i + 1))); | |
| continue; | |
| } | |
| throw new Error(`Server returned ${response.status} ${response.statusText}`); | |
| } | |
| const data = await response.json(); | |
| // Check for specific API errors that warrant a retry | |
| const isOverloaded = response.status === 429 || response.status === 503 || response.status === 500; | |
| const errorMsg = data.error ? (typeof data.error === 'string' ? data.error : JSON.stringify(data.error)) : ''; | |
| const isQuotaError = errorMsg.toLowerCase().includes('quota') || | |
| errorMsg.toLowerCase().includes('exhausted') || | |
| errorMsg.toLowerCase().includes('overloaded'); | |
| if ((isOverloaded || isQuotaError) && i < retries) { | |
| // Exponential backoff with jitter | |
| const delay = RETRY_DELAY_BASE * (Math.pow(2, i)) + (Math.random() * 1000); | |
| // console.log(`Retrying request (attempt ${i + 1}) in ${Math.round(delay)}ms...`); | |
| await new Promise(r => setTimeout(r, delay)); | |
| continue; | |
| } | |
| if (data.error) { | |
| // Format error properly to avoid [object Object] | |
| throw new Error(typeof data.error === 'string' ? data.error : (data.error.message || JSON.stringify(data.error))); | |
| } | |
| if (!response.ok) { | |
| throw new Error(`HTTP ${response.status}: ${response.statusText}`); | |
| } | |
| return data; | |
| } catch (err) { | |
| if (i === retries) throw err; | |
| // Network errors also trigger retry | |
| const delay = RETRY_DELAY_BASE * (Math.pow(2, i)); | |
| await new Promise(r => setTimeout(r, delay)); | |
| } | |
| } | |
| } | |
| function addMessageToChat(role, text, image = null, save = true) { | |
| const messageDiv = document.createElement('div'); | |
| messageDiv.className = `message message-${role} flex gap-3 md:gap-4 items-start animate-message-slide`; | |
| const avatar = document.createElement('div'); | |
| const avatarBg = role === 'user' | |
| ? 'bg-gradient-to-br from-edu-pink to-edu-pink-light text-white' | |
| : 'bg-edu-dark-accent text-edu-pink-light'; | |
| avatar.className = `message-avatar w-8 h-8 md:w-10 md:h-10 rounded-xl flex items-center justify-center flex-shrink-0 text-lg md:text-xl ${avatarBg}`; | |
| avatar.innerHTML = role === 'user' ? '👤' : '🤖'; | |
| const content = document.createElement('div'); | |
| content.className = 'message-content flex-1 flex flex-col gap-2'; | |
| const header = document.createElement('div'); | |
| header.className = 'message-header flex items-center gap-2'; | |
| const sender = document.createElement('div'); | |
| sender.className = 'message-sender font-semibold text-sm text-edu-text'; | |
| sender.textContent = role === 'user' ? 'You' : 'EDUrocks AI'; | |
| const time = document.createElement('div'); | |
| time.className = 'message-time text-xs text-edu-text-secondary/60'; | |
| time.textContent = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); | |
| header.appendChild(sender); | |
| header.appendChild(time); | |
| const body = document.createElement('div'); | |
| const bodyBg = role === 'user' | |
| ? 'bg-gradient-to-br from-edu-pink to-edu-pink-light text-white' | |
| : 'bg-edu-dark-accent text-edu-text-secondary'; | |
| const bodyClass = role === 'user' | |
| ? `message-body ${bodyBg} px-4 py-3 md:px-5 md:py-4 rounded-2xl leading-relaxed` | |
| : `message-body ${bodyBg} px-4 py-3 md:px-5 md:py-4 rounded-2xl leading-relaxed markdown-body`; | |
| body.className = bodyClass; | |
| if (image && role === 'user') { | |
| const img = document.createElement('img'); | |
| img.src = image.dataUrl; | |
| img.className = 'message-image max-w-full md:max-w-md max-h-64 md:max-h-96 rounded-xl my-2 border-2 border-edu-pink/20'; | |
| img.alt = 'User uploaded image'; | |
| body.appendChild(img); | |
| } | |
| if (text) { | |
| if (role === 'ai') { | |
| const textDiv = document.createElement('div'); | |
| textDiv.innerHTML = marked.parse(text); | |
| // 1. Highlight code blocks | |
| textDiv.querySelectorAll('pre code').forEach((block) => { | |
| hljs.highlightElement(block); | |
| }); | |
| // 2. Render Math with KaTeX | |
| if (window.renderMathInElement) { | |
| renderMathInElement(textDiv, { | |
| delimiters: [ | |
| {left: '$$', right: '$$', display: true}, | |
| {left: '\\\\[', right: '\\\\\]', display: true}, | |
| {left: '\\(', right: '\\\\)', display: false}, | |
| {left: '$', right: '$', display: false} | |
| ], | |
| throwOnError: false | |
| }); | |
| } | |
| // 3. Open links in new tab | |
| textDiv.querySelectorAll('a').forEach(link => { | |
| link.target = '_blank'; | |
| link.rel = 'noopener noreferrer'; | |
| }); | |
| body.appendChild(textDiv); | |
| } else { | |
| const textDiv = document.createElement('div'); | |
| textDiv.textContent = text; | |
| body.appendChild(textDiv); | |
| } | |
| } | |
| content.appendChild(header); | |
| content.appendChild(body); | |
| messageDiv.appendChild(avatar); | |
| messageDiv.appendChild(content); | |
| chatMessages.appendChild(messageDiv); | |
| chatMessages.scrollTop = chatMessages.scrollHeight; | |
| if (save) { | |
| const historyRole = role === 'ai' ? 'assistant' : 'user'; | |
| chatHistoryState.push({ role: historyRole, text: text }); | |
| localStorage.setItem(CHAT_HISTORY_STORAGE_KEY, JSON.stringify(chatHistoryState)); | |
| } | |
| } | |
| function showLoadingMessage() { | |
| const loadingDiv = document.createElement('div'); | |
| loadingDiv.className = 'message message-ai loading-message flex gap-3 md:gap-4 items-start'; | |
| loadingDiv.id = 'loading-message'; | |
| const avatar = document.createElement('div'); | |
| avatar.className = 'message-avatar w-8 h-8 md:w-10 md:h-10 rounded-xl flex items-center justify-center flex-shrink-0 text-lg md:text-xl bg-edu-dark-accent text-edu-pink-light'; | |
| avatar.innerHTML = '🤖'; | |
| const content = document.createElement('div'); | |
| content.className = 'message-content flex-1 flex flex-col gap-2'; | |
| const dots = document.createElement('div'); | |
| dots.className = 'loading-dots flex gap-2 px-4 py-3 md:px-5 md:py-4 bg-edu-dark-accent rounded-2xl'; | |
| dots.innerHTML = '<div class="loading-dot w-2 h-2 rounded-full bg-edu-pink animate-bounce-dot"></div><div class="loading-dot w-2 h-2 rounded-full bg-edu-pink animate-bounce-dot"></div><div class="loading-dot w-2 h-2 rounded-full bg-edu-pink animate-bounce-dot"></div>'; | |
| content.appendChild(dots); | |
| loadingDiv.appendChild(avatar); | |
| loadingDiv.appendChild(content); | |
| chatMessages.appendChild(loadingDiv); | |
| chatMessages.scrollTop = chatMessages.scrollHeight; | |
| } | |
| function removeLoadingMessage() { | |
| const loadingMsg = document.getElementById('loading-message'); | |
| if (loadingMsg) { | |
| loadingMsg.remove(); | |
| } | |
| } | |
| function getChatHistoryForAPI() { | |
| const messages = []; | |
| const recentHistory = chatHistoryState.slice(-20); | |
| recentHistory.forEach(item => { | |
| messages.push({ | |
| role: item.role === 'assistant' ? 'model' : 'user', | |
| parts: [{ text: item.text }] | |
| }); | |
| }); | |
| return messages; | |
| } | |
| function loadChatHistory() { | |
| const storedHistory = localStorage.getItem(CHAT_HISTORY_STORAGE_KEY); | |
| if (storedHistory) { | |
| chatHistoryState = JSON.parse(storedHistory); | |
| if (chatHistoryState.length > 0) { | |
| const welcomeScreen = document.querySelector('.welcome-screen'); | |
| if (welcomeScreen) { | |
| welcomeScreen.remove(); | |
| } | |
| chatHistoryState.forEach(item => { | |
| const role = item.role === 'user' ? 'user' : 'ai'; | |
| addMessageToChat(role, item.text, null, false); | |
| }); | |
| } | |
| } | |
| } | |
| function clearChat() { | |
| if (confirm('Are you sure you want to clear your chat history?')) { | |
| localStorage.removeItem(CHAT_HISTORY_STORAGE_KEY); | |
| chatHistoryState = []; | |
| chatMessages.innerHTML = ` | |
| <div class="welcome-screen flex flex-col items-center justify-center text-center p-6 md:p-12 gap-4 md:gap-6 animate-fade-in"> | |
| <div class="text-6xl md:text-7xl lg:text-8xl">🤖</div> | |
| <h2 class="text-2xl md:text-3xl lg:text-4xl font-bold gradient-text">Welcome to EDUrocks AI</h2> | |
| <p class="text-edu-text-secondary text-sm md:text-base max-w-md lg:max-w-lg">Your intelligent AI assistant ready to help with questions, code, creative writing, and more!</p> | |
| </div> | |
| `; | |
| } | |
| } | |