google.com, pub-9561355152071528, DIRECT, f08c47fec0942fa0 google.com, pub-9561355152071528, DIRECT, f08c47fec0942fa0

AI Study Helper

AI Study Helper

Hello! I’m your AI Study Helper. You can:

  • Ask questions about any academic subject
  • Upload images of problems or diagrams
  • Get detailed explanations with examples

Select a subject above for better answers!

AI Study Helper – Powered by Google AI

`; // Add click handler for remove button previewContainer.querySelector('.remove-image-btn').addEventListener('click', () => { uploadedImage = null; fileInput.value = ''; previewContainer.remove(); sendBtn.disabled = userInput.value.trim() === ''; }); // Add preview to the chat const messageElement = document.createElement('div'); messageElement.className = 'message user-message'; messageElement.innerHTML = `

Uploaded image:

`; messageElement.appendChild(previewContainer); chatMessages.appendChild(messageElement); scrollToBottom(); sendBtn.disabled = false; }; reader.readAsDataURL(file); } // Send user message and get AI response async function sendMessage() { const message = userInput.value.trim(); if ((message === '' && !uploadedImage) || isWaitingForResponse) return; // Add user message to chat (if text exists) if (message !== '') { addUserMessage(message); } // Clear input userInput.value = ''; userInput.style.height = 'auto'; sendBtn.disabled = true; // Show typing indicator showTypingIndicator(); isWaitingForResponse = true; try { // Get AI response const response = await getAIResponse(message); addAIMessage(response); } catch (error) { console.error('Error:', error); addAIMessage("Sorry, I'm having trouble answering right now. Please try again later."); // Fallback response if API fails setTimeout(() => { addAIMessage(getFallbackResponse(message)); }, 1000); } finally { // Hide typing indicator and reset state hideTypingIndicator(); isWaitingForResponse = false; sendBtn.disabled = userInput.value.trim() === '' && !uploadedImage; // Clear uploaded image after sending if (uploadedImage) { uploadedImage = null; fileInput.value = ''; document.querySelector('.image-preview-container')?.remove(); } } } // Get response from AI API async function getAIResponse(message) { let requestBody; if (uploadedImage) { // Prepare request with image const imageData = uploadedImage.split(',')[1]; // Remove data URL prefix requestBody = { contents: [{ parts: [ { text: `You are an expert tutor in ${currentSubject}. Analyze this image and provide a detailed explanation.` }, { inlineData: { mimeType: "image/jpeg", data: imageData } }, ...(message ? [{ text: `Additional context: ${message}` }] : []) ] }] }; } else { // Text-only request requestBody = { contents: [{ parts: [{ text: `You are an expert tutor in ${currentSubject}. Provide a clear, detailed, and accurate response to: "${message}". Format with headings, bullet points, and examples where appropriate.` }] }] }; } const response = await fetch(`${API_URL}?key=${API_KEY}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(requestBody) }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.error?.message || `API request failed with status ${response.status}`); } const data = await response.json(); return data.candidates[0].content.parts[0].text; } // Fallback response if API fails function getFallbackResponse(message) { const subjectResponses = { 'hindi': `Regarding your Hindi question "${message}":\n\nImportant concepts to consider:\n- व्याकरण (Grammar)\n- काव्यांश (Poetry)\n- गद्यांश (Prose)`, 'english': `About your English question "${message}":\n\nKey areas to review:\n1. Grammar rules\n2. Literary devices\n3. Composition techniques`, 'mathematics': `For your Math question "${message}", consider these steps:\n\n1. Identify the problem type\n2. Recall relevant formulas\n3. Work through examples`, 'physics': `Your Physics question "${message}" relates to:\n\n• Fundamental principles\n• Mathematical formulations\n• Practical applications`, 'chemistry': `Regarding Chemistry question "${message}":\n\nKey concepts:\n- Chemical equations\n- Periodic trends\n- Reaction mechanisms`, 'biology': `For your Biology question "${message}":\n\nImportant aspects:\n1. Biological processes\n2. Diagrams and structures\n3. Terminology` }; return subjectResponses[currentSubject] || `I'm analyzing your question: "${message}". Here are general study tips:\n\n• Break the problem into smaller parts\n• Look for similar examples\n• Make notes of key concepts`; } // Add user message to chat function addUserMessage(message) { const messageElement = document.createElement('div'); messageElement.className = 'message user-message'; messageElement.textContent = message; chatMessages.appendChild(messageElement); scrollToBottom(); } // Add AI message to chat function addAIMessage(message) { hideTypingIndicator(); const messageElement = document.createElement('div'); messageElement.className = 'message ai-message'; // Simple markdown formatting const formattedMessage = message .replace(/\*\*(.*?)\*\*/g, '$1') // bold .replace(/\*(.*?)\*/g, '$1') // italic .replace(/^# (.*$)/gm, '

$1

') // headings .replace(/^## (.*$)/gm, '

$1

') .replace(/^### (.*$)/gm, '
$1
') .replace(/`(.*?)`/g, '$1') // inline code .replace(/```([\s\S]*?)```/g, '
$1
') // code blocks .replace(/^- (.*$)/gm, '
  • $1
  • ') // lists .replace(/^> (.*$)/gm, '
    $1
    '); // quotes // Handle line breaks and paragraphs const paragraphs = formattedMessage.split('\n\n'); let htmlContent = ''; paragraphs.forEach(para => { if (para.startsWith('<') || para.trim() === '') { htmlContent += para; } else { htmlContent += `

    ${para.replace(/\n/g, '
    ')}

    `; } }); // Handle lists htmlContent = htmlContent.replace(/
  • .*?<\/li>/g, (match) => { if (!htmlContent.includes('
      ')) { return `
        ${match}`; } if (htmlContent.indexOf('
      ') > htmlContent.indexOf(match)) { return match; } return `${match}
    `; }); messageElement.innerHTML = htmlContent; chatMessages.appendChild(messageElement); scrollToBottom(); } // Add system message to chat function addSystemMessage(message) { const messageElement = document.createElement('div'); messageElement.className = 'message ai-message'; messageElement.innerHTML = `

    ${message}

    `; chatMessages.appendChild(messageElement); scrollToBottom(); } // Show typing indicator function showTypingIndicator() { const typingElement = document.createElement('div'); typingElement.className = 'typing-indicator'; typingElement.id = 'typing-indicator'; typingElement.innerHTML = `
    `; chatMessages.appendChild(typingElement); scrollToBottom(); } // Hide typing indicator function hideTypingIndicator() { const typingElement = document.getElementById('typing-indicator'); if (typingElement) { typingElement.remove(); } } // Scroll chat to bottom function scrollToBottom() { chatMessages.scrollTop = chatMessages.scrollHeight; } // Initialize the app init();