""" BrightMind API Backend Secure FastAPI backend for BrightLearn iOS app Deployed on Hugging Face Spaces """ import os import time import json import hashlib from datetime import datetime, timedelta from typing import Optional, Dict, Any from functools import wraps from collections import defaultdict from fastapi import FastAPI, HTTPException, Header, Request, Depends from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from pydantic import BaseModel, Field import requests # ============================================ # CONFIGURATION # ============================================ # Secrets (set in HF Space settings) APP_SECRET_KEY = os.environ.get("appkey", "") # Key iOS app sends HF_TOKEN = os.environ.get("HF_TOKEN", "") # Hugging Face API token RATE_LIMIT_PER_MINUTE = int(os.environ.get("RATE_LIMIT_PER_MINUTE", "30")) # LLM Model - Using a reliable model available on HF Inference API LLM_MODEL = "meta-llama/Llama-3.1-70B-Instruct" # ============================================ # RATE LIMITING # ============================================ rate_limit_store: Dict[str, list] = defaultdict(list) def check_rate_limit(client_id: str) -> bool: """Check if client has exceeded rate limit""" now = time.time() window_start = now - 60 # 1 minute window # Clean old entries rate_limit_store[client_id] = [ t for t in rate_limit_store[client_id] if t > window_start ] if len(rate_limit_store[client_id]) >= RATE_LIMIT_PER_MINUTE: return False rate_limit_store[client_id].append(now) return True # ============================================ # SECURITY # ============================================ def get_client_id(request: Request) -> str: """Generate unique client ID from request""" forwarded = request.headers.get("X-Forwarded-For", "") ip = forwarded.split(",")[0].strip() if forwarded else request.client.host user_agent = request.headers.get("User-Agent", "") return hashlib.sha256(f"{ip}:{user_agent}".encode()).hexdigest()[:16] async def verify_api_key( x_api_key: Optional[str] = Header(None, alias="X-API-Key"), x_app_version: Optional[str] = Header(None, alias="X-App-Version"), ): """Verify the API key from iOS app""" if not APP_SECRET_KEY: # No key configured - allow all (development mode) return True if not x_api_key: raise HTTPException(status_code=401, detail="Missing API key") if x_api_key != APP_SECRET_KEY: raise HTTPException(status_code=401, detail="Invalid API key") return True # ============================================ # FASTAPI APP # ============================================ app = FastAPI( title="BrightMind API", description="Secure backend for BrightLearn iOS app", version="1.0.0", ) # CORS - restrict to your app in production app.add_middleware( CORSMiddleware, allow_origins=["*"], # In production, restrict this allow_credentials=True, allow_methods=["POST", "GET"], allow_headers=["*"], ) # ============================================ # REQUEST/RESPONSE MODELS # ============================================ class AlbertRequest(BaseModel): message: str = Field(..., min_length=1, max_length=2000) user_name: Optional[str] = "Student" age_group: Optional[str] = "9-12" history: Optional[list] = [] class MathMindRequest(BaseModel): message: str = Field(..., min_length=1, max_length=2000) grade_level: Optional[str] = "9-12" history: Optional[list] = [] class LessonPlanRequest(BaseModel): topic: str = Field(..., min_length=1, max_length=500) subject: str grade_level: str duration: int = Field(ge=15, le=180) difficulty: str = "Intermediate" class ContentRequest(BaseModel): topic: str = Field(..., min_length=1, max_length=500) subject: str grade_level: str content_type: str content_length: str = "Medium" difficulty: str = "Intermediate" class QuizRequest(BaseModel): topic: str = Field(..., min_length=1, max_length=500) subject: str grade_level: str question_count: int = Field(ge=3, le=20) question_types: list = ["multiple_choice"] standards: str = "none" class RubricRequest(BaseModel): assignment_type: str learning_objectives: str grade_level: str point_scale: int = 100 special_needs: list = [] class CareerGrowthRequest(BaseModel): current_role: str years_experience: str career_goal: str timeline: str class InterviewPrepRequest(BaseModel): position: str school_type: str = "Public" subject_grade: Optional[str] = "" concerns: Optional[str] = "" class ReportCommentsRequest(BaseModel): student_name: str subject: str grade_level: str performance: str areas_of_strength: str areas_for_improvement: str class ParentCommunicationRequest(BaseModel): topic: str student_name: str context: str tone: str = "Professional" class ESLToolkitRequest(BaseModel): content_type: str # sentence_frames, cloze, vocabulary, etc. topic: str proficiency_level: str grade_level: str class ECERequest(BaseModel): activity_type: str topic: str age_group: str # Pre-K, K, 1st, 2nd duration: int = 30 class CareerExplorationRequest(BaseModel): interests: str skills: str grade_level: str class DifferentiationRequest(BaseModel): content: str learning_needs: list grade_level: str class CompensationRequest(BaseModel): current_role: str years_experience: str location: str certifications: list = [] # --- NEW SYNCED FEATURE REQUEST MODELS --- class AlbertProRequest(BaseModel): message: str = Field(..., min_length=1, max_length=2000) user_name: Optional[str] = "Student" age_group: Optional[str] = "9-12" history: Optional[list] = [] class MathDiagnosticRequest(BaseModel): topic: str = Field(..., min_length=1, max_length=500) grade_level: Optional[str] = "7" student_responses: str = Field(..., min_length=1, max_length=5000) class ContentProRequest(BaseModel): topic: str = Field(..., min_length=1, max_length=500) subject: str grade_level: str difficulty: str = "Intermediate" content_type: str content_length: str = "Medium" class SmartPracticeRequest(BaseModel): action: str # 'get_question' or 'check_answer' subject: str difficulty: Optional[str] = "medium" learning_style: Optional[str] = "steps" answer: Optional[str] = None history: Optional[list] = [] misconceptions: Optional[list] = [] class StudentGameRequest(BaseModel): subject: str grade_range: str = "6-8" question_count: int = Field(default=10, ge=3, le=20) class APIResponse(BaseModel): success: bool response: str timestamp: str # ============================================ # LLM HELPER # ============================================ def call_llm(system_prompt: str, user_message: str, max_tokens: int = 2000) -> str: """Call Hugging Face LLM with error handling""" if not HF_TOKEN: raise HTTPException(status_code=500, detail="LLM not configured") try: # Use HuggingFace Inference API with OpenAI-compatible endpoint API_URL = "https://router.huggingface.co/v1/chat/completions" headers = { "Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json", } payload = { "model": LLM_MODEL, "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_message}, ], "max_tokens": max_tokens, "temperature": 0.7, } response = requests.post(API_URL, headers=headers, json=payload, timeout=90) response.raise_for_status() result = response.json() return result["choices"][0]["message"]["content"].strip() except requests.exceptions.Timeout: raise HTTPException(status_code=504, detail="LLM request timed out") except Exception as e: raise HTTPException(status_code=500, detail=f"LLM error: {str(e)}") # ============================================ # SYSTEM PROMPTS # ============================================ PROMPTS = { "albert": """You are Albert, a friendly and knowledgeable AI learning assistant. Your name is Albert and you're talking to {user_name}, a student in grade {age_group}. CRITICAL: Adjust your response based on the student's grade level ({age_group}): - K-2 (Kindergarten to 2nd grade): Use very simple words, short sentences, fun comparisons to everyday things kids know (toys, animals, family). Use lots of encouragement and emojis. - 3-5 (3rd to 5th grade): Use clear explanations with relatable examples. Can introduce some new vocabulary with definitions. Keep it engaging and fun. - 6-8 (Middle School): Can use more complex vocabulary and concepts. Provide deeper explanations with real-world applications. Encourage critical thinking. - 9-12 (High School): Use academic language appropriate for teens. Provide comprehensive explanations with nuance. Can discuss abstract concepts and multiple perspectives. Guidelines: - Be encouraging and supportive - Break down complex topics appropriately for the grade level - Ask follow-up questions to ensure understanding - Be patient and never condescending - Match vocabulary and sentence complexity to the grade level""", "mathmind": """You are MathMind, an expert math tutor for grade {grade_level} students. CRITICAL: Adjust your explanation based on the student's grade level ({grade_level}): - K-2: Use counting, basic addition/subtraction, simple shapes. Use visual examples (apples, toys, fingers). Very simple language with encouragement. - 3-5: Cover multiplication, division, fractions, basic geometry. Use real-world examples (pizza slices, money). Clear step-by-step explanations. - 6-8: Include pre-algebra, ratios, percentages, basic equations. Introduce mathematical vocabulary. Show multiple solution methods. - 9-12: Cover algebra, geometry proofs, trigonometry, pre-calculus. Use formal mathematical notation. Explain underlying concepts and theorems. Guidelines: - Explain mathematical concepts step by step appropriate for the grade level - Use LaTeX notation for math: \\( inline \\) and \\[ block \\] - Provide examples and practice problems at the right difficulty - Be encouraging when students struggle - Match problem complexity to the grade level""", "lesson_plan": """You are an expert curriculum designer. Create a detailed lesson plan with: - Learning objectives (SMART goals) - Materials needed - Introduction/Hook (5-10 min) - Direct instruction - Guided practice - Independent practice - Assessment strategies - Differentiation ideas - Closure activity Format in clear markdown with headers.""", "content": """You are an expert educational content creator. Generate high-quality {content_type} that: - Is appropriate for {grade_level} level - Covers the topic thoroughly - Includes clear instructions - Has engaging activities - Is formatted in clean markdown""", "quiz": """You are an expert assessment designer. Create a quiz with: - Clear, unambiguous questions - Appropriate difficulty for {grade_level} - Mix of question types as requested - Answer key at the end - Aligned to {standards} standards if specified Format in markdown.""", "rubric": """You are an expert in inclusive assessment design. Create a rubric that: - Has clear criteria and descriptors - Uses the {point_scale}-point scale - Accommodates diverse learners - Includes specific, measurable criteria - Is fair and transparent Format as a clear table in markdown.""", "career_growth": """You are a career development coach for educators. Create a personalized career plan with: - Current situation analysis - SMART goals for the timeline - Specific action steps - Professional development recommendations - Networking strategies - Milestones and checkpoints Format in markdown with actionable items.""", "interview_prep": """You are an expert interview coach for educators. Provide: - Common interview questions for this position - STAR method response frameworks - Tips specific to {school_type} schools - Questions to ask the interviewer - Confidence-building strategies Format in clear, actionable markdown.""", "report_comments": """You are an expert at writing personalized, constructive report card comments. Write comments that: - Are specific and meaningful - Highlight strengths genuinely - Frame improvements constructively - Are appropriate for parents to read - Encourage continued growth""", "parent_communication": """You are an expert at culturally sensitive parent communication. Write a message that: - Is professional yet warm - Respects cultural differences - Clearly communicates the topic - Invites collaboration - Provides next steps if needed""", "esl_toolkit": """You are an ESL/ELL specialist. Create {content_type} materials that: - Are appropriate for {proficiency_level} English learners - Support language acquisition - Include visual supports where helpful - Build academic vocabulary - Are culturally responsive""", "ece": """You are an early childhood education specialist. Create age-appropriate activities that: - Are developmentally appropriate for {age_group} - Include play-based learning - Support multiple domains (cognitive, social, physical) - Are safe and engaging - Include simple materials""", "career_exploration": """You are a career counselor for students. Help explore careers that: - Match their interests and skills - Include educational pathways - Provide realistic salary expectations - Suggest related careers to explore - Include next steps for exploration""", "differentiation": """You are a differentiation specialist. Adapt the content to: - Meet the specified learning needs - Maintain rigor while increasing access - Provide multiple means of engagement - Include scaffolds and supports - Suggest modifications and accommodations""", "compensation": """You are a compensation and career advancement advisor for educators. Provide: - Salary benchmarks for the role and location - Advancement pathways with salary increases - Additional income opportunities - Certification ROI analysis - Negotiation strategies""", # --- NEW SYNCED FEATURE PROMPTS --- "albert_pro": """You are Albert Pro, a friendly and enthusiastic learning assistant for {age_group} year olds. You explain things in a fun, age-appropriate way. You're patient, encouraging, and make learning enjoyable. {user_context} Always be positive and use simple language that {age_group} year olds can understand. IMPORTANT: When a student asks a question, you MUST provide a helpful, informative answer. Do not just say "I'm here to help" or ask them to tell you more - actually answer their question in an age-appropriate way. Be specific and educational while keeping it fun and engaging.""", "math_diagnostic": """You are an expert math education specialist trained in identifying and addressing common mathematical misconceptions. Analyze the following student responses and provide a detailed diagnosis. ## Context - **Math Topic**: {topic} - **Grade Level**: {grade_level} ## Student Responses to Analyze {student_responses} ## Your Task Analyze these responses and identify the underlying **misconceptions** (not just errors). A misconception is a flawed way of thinking that leads to systematic errors. Provide your analysis in this exact format: # ๐Ÿ“Š Misconception Analysis Report ## Overview Provide a brief summary of the analysis (2-3 sentences about what you found). ## ๐Ÿ”ด Misconceptions Identified For EACH misconception found, provide: ### Misconception 1: [Name of Misconception] **Students Affected:** [List which students show this misconception] **What They Think:** > Explain in plain language what the student believes (the flawed mental model) **Why This Happens:** - Explain the cognitive reason behind this misconception - Common prior knowledge that leads to this error **Evidence from Responses:** - Quote specific student answers that demonstrate this misconception **๐Ÿ”ง 5-Minute Fix (Do This Tomorrow):** 1. **Step 1:** [Specific action with example dialogue] 2. **Step 2:** [Follow-up activity] 3. **Step 3:** [Practice problems to assign] **๐Ÿ’ก Key Question to Ask Students:** > [A powerful question that exposes the misconception] --- [Repeat for each misconception found] ## โœ… Students Without Major Misconceptions List any students who showed correct understanding and are ready for grade-level work. ## ๐Ÿ“‹ Recommended Student Groupings | Group | Misconception | Students | Priority | |-------|--------------|----------|----------| | Group A | [Misconception name] | [Students] | High/Medium/Low | | Group B | [Misconception name] | [Students] | High/Medium/Low | ## ๐ŸŽฏ Immediate Next Steps 1. [Action for tomorrow] 2. [Action for this week] 3. [Follow-up assessment suggestion] --- **Important Guidelines:** - Be specific and actionable - teachers should be able to use this immediately - Focus on the THINKING ERROR, not just the wrong answer - Provide interventions that address the root cause - Use simple, teacher-friendly language - Include specific examples and dialogue teachers can use - Make the 5-minute fix realistic to do in a busy classroom""", "content_pro": """You are an expert educational content creator. Create {content_length} educational {content_type} about the topic. Requirements: - Appropriate for {grade_level} grade level - {difficulty} difficulty level - {content_length} length - Well-structured and engaging - Include examples and explanations - Use clear, age-appropriate language Format the content with clear sections, headings, and examples.""", "smart_practice_question": """You are an adaptive math tutor. Generate a single practice question. Subject: {subject} Difficulty: {difficulty} (easy=single-step, medium=two steps, hard=multiple steps) {focus_context} Recent conversation: {recent_history} Rules: 1. Generate ONE clear math problem 2. Do NOT give the answer 3. Keep it to 1-3 sentences max 4. Make it appropriate for the difficulty level Respond with ONLY the question, nothing else.""", "smart_practice_check": """You are checking a student's math answer. Question: {question} Student's answer: {answer} Subject: {subject} Teaching style: {style_prompt} Respond with ONLY a JSON object (no markdown): {{ "isCorrect": true or false, "feedback": "2-3 sentences. If wrong, explain using their style. Be encouraging.", "misconception": "If wrong, name the specific misconception. If correct, empty string.", "misconceptionDescription": "Brief description for report. If correct, empty string." }}""", } # ============================================ # API ENDPOINTS # ============================================ @app.get("/") async def root(): """Health check endpoint""" return {"status": "healthy", "service": "BrightMind API", "version": "1.0.0"} @app.get("/health") async def health(): """Health check""" return {"status": "ok", "timestamp": datetime.utcnow().isoformat()} # --- ASK ALBERT --- @app.post("/api/albert", response_model=APIResponse) async def albert( request: Request, data: AlbertRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") system_prompt = PROMPTS["albert"].format( age_group=data.age_group, user_name=data.user_name, ) # Include history context context = "" if data.history: context = "Previous conversation:\n" for msg in data.history[-5:]: # Last 5 messages role = "Student" if msg.get("role") == "user" else "Albert" context += f"{role}: {msg.get('content', '')}\n" context += "\nCurrent message:\n" response = call_llm(system_prompt, context + data.message) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- MATHMIND --- @app.post("/api/mathmind", response_model=APIResponse) async def mathmind( request: Request, data: MathMindRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") system_prompt = PROMPTS["mathmind"].format(grade_level=data.grade_level) context = "" if data.history: context = "Previous conversation:\n" for msg in data.history[-5:]: role = "Student" if msg.get("role") == "user" else "MathMind" context += f"{role}: {msg.get('content', '')}\n" context += "\nCurrent question:\n" response = call_llm(system_prompt, context + data.message, max_tokens=3000) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- LESSON PLAN --- @app.post("/api/lesson-plan", response_model=APIResponse) async def lesson_plan( request: Request, data: LessonPlanRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") user_message = f"""Create a {data.duration}-minute lesson plan: Topic: {data.topic} Subject: {data.subject} Grade Level: {data.grade_level} Difficulty: {data.difficulty}""" response = call_llm(PROMPTS["lesson_plan"], user_message, max_tokens=3000) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- CONTENT GENERATOR --- @app.post("/api/content", response_model=APIResponse) async def content( request: Request, data: ContentRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") system_prompt = PROMPTS["content"].format( content_type=data.content_type, grade_level=data.grade_level, ) user_message = f"""Create {data.content_length} {data.content_type}: Topic: {data.topic} Subject: {data.subject} Grade Level: {data.grade_level} Difficulty: {data.difficulty}""" response = call_llm(system_prompt, user_message, max_tokens=4000) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- QUIZ GENERATOR --- @app.post("/api/quiz", response_model=APIResponse) async def quiz( request: Request, data: QuizRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") system_prompt = PROMPTS["quiz"].format( grade_level=data.grade_level, standards=data.standards, ) user_message = f"""Create a {data.question_count}-question quiz: Topic: {data.topic} Subject: {data.subject} Grade Level: {data.grade_level} Question Types: {', '.join(data.question_types)} Standards Alignment: {data.standards}""" response = call_llm(system_prompt, user_message, max_tokens=3000) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- RUBRIC GENERATOR --- @app.post("/api/rubric", response_model=APIResponse) async def rubric( request: Request, data: RubricRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") system_prompt = PROMPTS["rubric"].format(point_scale=data.point_scale) special_needs_text = ", ".join(data.special_needs) if data.special_needs else "None specified" user_message = f"""Create an inclusive rubric: Assignment Type: {data.assignment_type} Learning Objectives: {data.learning_objectives} Grade Level: {data.grade_level} Point Scale: {data.point_scale} Special Needs to Accommodate: {special_needs_text}""" response = call_llm(system_prompt, user_message, max_tokens=3000) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- CAREER GROWTH --- @app.post("/api/career-growth", response_model=APIResponse) async def career_growth( request: Request, data: CareerGrowthRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") user_message = f"""Create a career development plan: Current Role: {data.current_role} Years of Experience: {data.years_experience} Career Goal: {data.career_goal} Timeline: {data.timeline}""" response = call_llm(PROMPTS["career_growth"], user_message, max_tokens=3000) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- INTERVIEW PREP --- @app.post("/api/interview-prep", response_model=APIResponse) async def interview_prep( request: Request, data: InterviewPrepRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") system_prompt = PROMPTS["interview_prep"].format(school_type=data.school_type) user_message = f"""Prepare for this interview: Position: {data.position} School Type: {data.school_type} Subject/Grade Level: {data.subject_grade or 'Not specified'} Specific Concerns: {data.concerns or 'None'}""" response = call_llm(system_prompt, user_message, max_tokens=3000) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- REPORT COMMENTS --- @app.post("/api/report-comments", response_model=APIResponse) async def report_comments( request: Request, data: ReportCommentsRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") user_message = f"""Write a report card comment: Student Name: {data.student_name} Subject: {data.subject} Grade Level: {data.grade_level} Performance Level: {data.performance} Strengths: {data.areas_of_strength} Areas for Improvement: {data.areas_for_improvement}""" response = call_llm(PROMPTS["report_comments"], user_message) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- PARENT COMMUNICATION --- @app.post("/api/parent-communication", response_model=APIResponse) async def parent_communication( request: Request, data: ParentCommunicationRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") user_message = f"""Write a parent communication: Topic: {data.topic} Student Name: {data.student_name} Context: {data.context} Tone: {data.tone}""" response = call_llm(PROMPTS["parent_communication"], user_message) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- ESL TOOLKIT --- @app.post("/api/esl-toolkit", response_model=APIResponse) async def esl_toolkit( request: Request, data: ESLToolkitRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") system_prompt = PROMPTS["esl_toolkit"].format( content_type=data.content_type, proficiency_level=data.proficiency_level, ) user_message = f"""Create ESL materials: Content Type: {data.content_type} Topic: {data.topic} Proficiency Level: {data.proficiency_level} Grade Level: {data.grade_level}""" response = call_llm(system_prompt, user_message, max_tokens=3000) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- ECE (Early Childhood) --- @app.post("/api/ece", response_model=APIResponse) async def ece( request: Request, data: ECERequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") system_prompt = PROMPTS["ece"].format(age_group=data.age_group) user_message = f"""Create an early childhood activity: Activity Type: {data.activity_type} Topic: {data.topic} Age Group: {data.age_group} Duration: {data.duration} minutes""" response = call_llm(system_prompt, user_message) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- CAREER EXPLORATION --- @app.post("/api/career-exploration", response_model=APIResponse) async def career_exploration( request: Request, data: CareerExplorationRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") user_message = f"""Help explore careers: Interests: {data.interests} Skills: {data.skills} Grade Level: {data.grade_level}""" response = call_llm(PROMPTS["career_exploration"], user_message) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- DIFFERENTIATION --- @app.post("/api/differentiation", response_model=APIResponse) async def differentiation( request: Request, data: DifferentiationRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") user_message = f"""Differentiate this content: Content: {data.content} Learning Needs: {', '.join(data.learning_needs)} Grade Level: {data.grade_level}""" response = call_llm(PROMPTS["differentiation"], user_message, max_tokens=3000) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- COMPENSATION & ADVANCEMENT --- @app.post("/api/compensation", response_model=APIResponse) async def compensation( request: Request, data: CompensationRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") certifications_text = ", ".join(data.certifications) if data.certifications else "None" user_message = f"""Provide compensation and advancement guidance: Current Role: {data.current_role} Years of Experience: {data.years_experience} Location: {data.location} Current Certifications: {certifications_text}""" response = call_llm(PROMPTS["compensation"], user_message) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # ============================================ # NEW SYNCED FEATURE ENDPOINTS # ============================================ # --- ALBERT PRO --- @app.post("/api/albert-pro", response_model=APIResponse) async def albert_pro( request: Request, data: AlbertProRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") user_context = f"The student's name is {data.user_name}." if data.user_name else "" system_prompt = PROMPTS["albert_pro"].format( age_group=data.age_group, user_context=user_context, ) # Include history context context = "" if data.history: context = "Previous conversation:\n" for msg in data.history[-10:]: # Last 10 messages role = "Student" if msg.get("role") == "user" else "Albert Pro" context += f"{role}: {msg.get('content', '')}\n" context += "\nCurrent message:\n" response = call_llm(system_prompt, context + data.message, max_tokens=1500) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- MATH DIAGNOSTIC --- @app.post("/api/math-diagnostic", response_model=APIResponse) async def math_diagnostic( request: Request, data: MathDiagnosticRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") # Build the analysis prompt user_message = PROMPTS["math_diagnostic"].format( topic=data.topic.replace("-", " "), grade_level=data.grade_level, student_responses=data.student_responses, ) response = call_llm( "You are an expert math education specialist trained in identifying student misconceptions.", user_message, max_tokens=3500 ) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- CONTENT PRO --- @app.post("/api/content-pro", response_model=APIResponse) async def content_pro( request: Request, data: ContentProRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") system_prompt = PROMPTS["content_pro"].format( content_type=data.content_type, grade_level=data.grade_level, difficulty=data.difficulty, content_length=data.content_length, ) user_message = f"""Create {data.content_length} educational {data.content_type.lower()} about "{data.topic}" for {data.grade_level} students studying {data.subject}. Topic: {data.topic} Subject: {data.subject} Grade Level: {data.grade_level} Difficulty: {data.difficulty}""" response = call_llm(system_prompt, user_message, max_tokens=4000) return APIResponse( success=True, response=response, timestamp=datetime.utcnow().isoformat(), ) # --- SMART PRACTICE --- # Subject topic details for better questions SMART_PRACTICE_SUBJECTS = { "fractions": { "topics": ["Adding fractions", "Subtracting fractions", "Multiplying fractions", "Dividing fractions"], "misconceptions": ["Adding numerators AND denominators", "Not finding common denominator", "Forgetting to flip when dividing"] }, "algebra": { "topics": ["Combining like terms", "Solving one-step equations", "Solving two-step equations", "Distributive property"], "misconceptions": ["Adding unlike terms", "Forgetting to apply operation to both sides", "Sign errors"] }, "decimals": { "topics": ["Adding decimals", "Subtracting decimals", "Multiplying decimals", "Dividing decimals"], "misconceptions": ["Not lining up decimal points", "Miscounting decimal places", "Moving decimal wrong direction"] }, "geometry": { "topics": ["Perimeter of rectangles", "Area of rectangles", "Area of triangles", "Circumference of circles"], "misconceptions": ["Confusing area and perimeter", "Forgetting radius vs diameter", "Not dividing by 2 for triangle"] }, "negative-numbers": { "topics": ["Adding negative numbers", "Subtracting negative numbers", "Multiplying negative numbers"], "misconceptions": ["Double negative errors", "Wrong sign when multiplying negatives", "Confusing subtraction direction"] }, "ratios": { "topics": ["Writing ratios", "Equivalent ratios", "Unit rates", "Solving proportions"], "misconceptions": ["Reversing ratio order", "Not keeping units consistent", "Cross-multiplying incorrectly"] } } LEARNING_STYLE_PROMPTS = { "visual": "Use visual representations and emoji to illustrate. Describe pictures.", "steps": "Break down into clear numbered steps. Show each step explicitly.", "examples": "Relate to real-world situations like pizza, money, sports.", "practice": "Be brief and direct. Quick tip, then move on." } DEFAULT_QUESTIONS = { "fractions": {"easy": "What is 1/4 + 1/4?", "medium": "What is 2/3 + 1/6?", "hard": "What is 3/4 - 2/5?"}, "algebra": {"easy": "Simplify: 3x + 2x", "medium": "Solve: x + 5 = 12", "hard": "Solve: 2x + 3 = 11"}, "decimals": {"easy": "What is 0.5 + 0.3?", "medium": "What is 2.5 ร— 0.4?", "hard": "What is 3.6 รท 0.9?"}, "geometry": {"easy": "What is the perimeter of a square with side 5?", "medium": "What is the area of a rectangle with length 6 and width 4?", "hard": "What is the area of a circle with radius 3? (Use ฯ€ = 3.14)"}, "negative-numbers": {"easy": "What is -3 + 5?", "medium": "What is -4 - (-2)?", "hard": "What is -6 ร— -3?"}, "ratios": {"easy": "Write the ratio of 4 apples to 8 oranges in simplest form.", "medium": "If 3 notebooks cost $6, how much do 5 notebooks cost?", "hard": "Solve: 4/x = 12/15"} } @app.post("/api/smart-practice") async def smart_practice( request: Request, data: SmartPracticeRequest, _: bool = Depends(verify_api_key), ): client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") if data.action == "get_question": return await _generate_practice_question(data) elif data.action == "check_answer": return await _check_practice_answer(data) else: raise HTTPException(status_code=400, detail="Invalid action. Use 'get_question' or 'check_answer'") async def _generate_practice_question(data: SmartPracticeRequest): """Generate a practice question based on subject and difficulty""" subject_info = SMART_PRACTICE_SUBJECTS.get(data.subject, {"topics": [], "misconceptions": []}) focus_context = "" if data.misconceptions: misconception_topics = [m.get("topic", "") for m in data.misconceptions if m.get("topic")] if misconception_topics: focus_context = f"The student has shown these misconceptions: {', '.join(misconception_topics)}. Generate a question that helps them practice and overcome these specific gaps." recent_history = "" if data.history: recent_history = "\n".join([f"{m.get('role', 'user')}: {m.get('content', '')}" for m in data.history[-4:]]) prompt = PROMPTS["smart_practice_question"].format( subject=data.subject, difficulty=data.difficulty, focus_context=focus_context, recent_history=recent_history, ) try: question = call_llm("You are an adaptive math tutor.", prompt, max_tokens=150) except: # Fallback to default question subject_defaults = DEFAULT_QUESTIONS.get(data.subject, DEFAULT_QUESTIONS["fractions"]) question = subject_defaults.get(data.difficulty, "What is 2 + 3?") return JSONResponse(content={ "success": True, "question": question, "timestamp": datetime.utcnow().isoformat(), }) async def _check_practice_answer(data: SmartPracticeRequest): """Check a student's answer and provide feedback""" if not data.answer: raise HTTPException(status_code=400, detail="Answer is required for check_answer action") # Find the last question from history question = "the previous question" if data.history: for msg in reversed(data.history): if msg.get("role") == "assistant": question = msg.get("content", question) break style_prompt = LEARNING_STYLE_PROMPTS.get(data.learning_style, LEARNING_STYLE_PROMPTS["steps"]) prompt = PROMPTS["smart_practice_check"].format( question=question, answer=data.answer, subject=data.subject, style_prompt=style_prompt, ) try: response_text = call_llm("You are a helpful math tutor checking student answers.", prompt, max_tokens=300) # Try to parse JSON response # Clean up response cleaned = response_text.replace("```json", "").replace("```", "").strip() parsed = json.loads(cleaned) return JSONResponse(content={ "success": True, "is_correct": parsed.get("isCorrect", False), "feedback": parsed.get("feedback", "Let me help you with that..."), "misconception": parsed.get("misconception", ""), "misconception_description": parsed.get("misconceptionDescription", ""), "timestamp": datetime.utcnow().isoformat(), }) except: # Fallback response return JSONResponse(content={ "success": True, "is_correct": False, "feedback": "Let me think about that... Let's try looking at this differently. What steps did you use to get your answer?", "misconception": "", "misconception_description": "", "timestamp": datetime.utcnow().isoformat(), }) # ============================================ # STUDENT GAME ENDPOINT # ============================================ # Fallback quiz questions by subject FALLBACK_QUIZ_QUESTIONS = { 'Mathematics': [ {"question": "What is 7 + 8?", "options": ["14", "15", "16", "17"], "correctIndex": 1, "explanation": "7 + 8 = 15"}, {"question": "What is 12 - 5?", "options": ["6", "7", "8", "9"], "correctIndex": 1, "explanation": "12 - 5 = 7"}, {"question": "What is 6 x 4?", "options": ["20", "22", "24", "26"], "correctIndex": 2, "explanation": "6 x 4 = 24"}, {"question": "What is 36 รท 6?", "options": ["4", "5", "6", "7"], "correctIndex": 2, "explanation": "36 รท 6 = 6"}, {"question": "What is the next number: 2, 4, 6, 8, ?", "options": ["9", "10", "11", "12"], "correctIndex": 1, "explanation": "The pattern adds 2 each time. 8 + 2 = 10"}, {"question": "How many sides does a hexagon have?", "options": ["5", "6", "7", "8"], "correctIndex": 1, "explanation": "A hexagon has 6 sides"}, {"question": "What is 1/2 + 1/2?", "options": ["1/4", "1/2", "1", "2"], "correctIndex": 2, "explanation": "1/2 + 1/2 = 1 whole"}, {"question": "What is 100 - 37?", "options": ["53", "63", "73", "83"], "correctIndex": 1, "explanation": "100 - 37 = 63"}, {"question": "How many minutes are in 1 hour?", "options": ["30", "45", "60", "100"], "correctIndex": 2, "explanation": "There are 60 minutes in 1 hour"}, {"question": "Perimeter of a square with sides 5 cm?", "options": ["15 cm", "20 cm", "25 cm", "10 cm"], "correctIndex": 1, "explanation": "4 ร— 5 = 20 cm"}, ], 'Science': [ {"question": "What do plants need to make food?", "options": ["Water only", "Sunlight and water", "Air only", "Soil only"], "correctIndex": 1, "explanation": "Plants use sunlight and water for photosynthesis"}, {"question": "What is the largest planet?", "options": ["Earth", "Mars", "Jupiter", "Saturn"], "correctIndex": 2, "explanation": "Jupiter is the largest planet"}, {"question": "What type of animal is a frog?", "options": ["Mammal", "Reptile", "Amphibian", "Fish"], "correctIndex": 2, "explanation": "Frogs are amphibians"}, {"question": "What is H2O?", "options": ["Salt", "Sugar", "Water", "Air"], "correctIndex": 2, "explanation": "H2O is water"}, {"question": "What force keeps us on the ground?", "options": ["Magnetism", "Friction", "Gravity", "Electricity"], "correctIndex": 2, "explanation": "Gravity pulls us toward Earth"}, {"question": "What organ pumps blood?", "options": ["Brain", "Lungs", "Heart", "Stomach"], "correctIndex": 2, "explanation": "The heart pumps blood"}, {"question": "What is the closest star to Earth?", "options": ["Moon", "Mars", "Sun", "Polaris"], "correctIndex": 2, "explanation": "The Sun is our closest star"}, {"question": "Animals that eat only plants are called?", "options": ["Carnivores", "Herbivores", "Omnivores", "Decomposers"], "correctIndex": 1, "explanation": "Herbivores eat only plants"}, {"question": "In what state of matter is ice?", "options": ["Gas", "Liquid", "Solid", "Plasma"], "correctIndex": 2, "explanation": "Ice is solid water"}, {"question": "What gas do humans breathe in?", "options": ["Nitrogen", "Carbon Dioxide", "Oxygen", "Helium"], "correctIndex": 2, "explanation": "We breathe in oxygen"}, ], 'History': [ {"question": "Who was the first US President?", "options": ["Lincoln", "Jefferson", "Washington", "Adams"], "correctIndex": 2, "explanation": "George Washington was the first President"}, {"question": "When did World War II end?", "options": ["1943", "1944", "1945", "1946"], "correctIndex": 2, "explanation": "WWII ended in 1945"}, {"question": "Who built the pyramids?", "options": ["Romans", "Greeks", "Egyptians", "Mayans"], "correctIndex": 2, "explanation": "Ancient Egyptians built the pyramids"}, {"question": "Who wrote the Declaration of Independence?", "options": ["Washington", "Franklin", "Jefferson", "Adams"], "correctIndex": 2, "explanation": "Thomas Jefferson wrote it"}, {"question": "What ship brought the Pilgrims?", "options": ["Santa Maria", "Mayflower", "Titanic", "Nina"], "correctIndex": 1, "explanation": "The Mayflower brought the Pilgrims"}, {"question": "Who first walked on the moon?", "options": ["Aldrin", "Armstrong", "Glenn", "Gagarin"], "correctIndex": 1, "explanation": "Neil Armstrong was first on the moon"}, {"question": "Who invented the telephone?", "options": ["Edison", "Bell", "Tesla", "Franklin"], "correctIndex": 1, "explanation": "Alexander Graham Bell invented it"}, {"question": "What ancient wonder is in Egypt?", "options": ["Colosseum", "Great Pyramid", "Hanging Gardens", "Lighthouse"], "correctIndex": 1, "explanation": "The Great Pyramid of Giza"}, {"question": "Who was King of Rock and Roll?", "options": ["Jackson", "Elvis", "Beatles", "Berry"], "correctIndex": 1, "explanation": "Elvis Presley was the King of Rock"}, {"question": "What did Romans build roads with?", "options": ["Wood", "Stone", "Brick", "Dirt"], "correctIndex": 1, "explanation": "Romans built stone roads"}, ], 'English': [ {"question": "What is a noun?", "options": ["Action word", "Describing word", "Person/place/thing", "Connecting word"], "correctIndex": 2, "explanation": "A noun is a person, place, or thing"}, {"question": "Which word is a verb?", "options": ["Happy", "Run", "Beautiful", "The"], "correctIndex": 1, "explanation": "Run is an action word (verb)"}, {"question": "What ends a question?", "options": ["Period", "Exclamation", "Question mark", "Comma"], "correctIndex": 2, "explanation": "Questions end with ?"}, {"question": "What is opposite of hot?", "options": ["Warm", "Cold", "Wet", "Dry"], "correctIndex": 1, "explanation": "Cold is the opposite of hot"}, {"question": "Which is spelled correctly?", "options": ["Freind", "Friend", "Frend", "Freand"], "correctIndex": 1, "explanation": "Friend is correct"}, {"question": "A synonym for happy?", "options": ["Sad", "Angry", "Joyful", "Tired"], "correctIndex": 2, "explanation": "Joyful means happy"}, {"question": "What type of word is 'quickly'?", "options": ["Noun", "Verb", "Adjective", "Adverb"], "correctIndex": 3, "explanation": "Quickly is an adverb"}, {"question": "What is plural of child?", "options": ["Childs", "Childes", "Children", "Childrens"], "correctIndex": 2, "explanation": "Children is the plural"}, {"question": "Which rhymes with cat?", "options": ["Dog", "Hat", "Cup", "Bed"], "correctIndex": 1, "explanation": "Hat rhymes with cat"}, {"question": "Which sentence is correct?", "options": ["Him went", "He went", "Her went", "Me went"], "correctIndex": 1, "explanation": "He went is grammatically correct"}, ], 'Geography': [ {"question": "What is the largest continent?", "options": ["Africa", "North America", "Asia", "Europe"], "correctIndex": 2, "explanation": "Asia is the largest continent"}, {"question": "What is the longest river?", "options": ["Amazon", "Nile", "Mississippi", "Yangtze"], "correctIndex": 1, "explanation": "The Nile is the longest river"}, {"question": "Which ocean is largest?", "options": ["Atlantic", "Indian", "Arctic", "Pacific"], "correctIndex": 3, "explanation": "The Pacific is the largest ocean"}, {"question": "Where is the Eiffel Tower?", "options": ["Italy", "Spain", "France", "Germany"], "correctIndex": 2, "explanation": "The Eiffel Tower is in France"}, {"question": "US capital city?", "options": ["New York", "Los Angeles", "Washington D.C.", "Chicago"], "correctIndex": 2, "explanation": "Washington D.C. is the capital"}, {"question": "Tallest mountain?", "options": ["K2", "Mount Everest", "Kilimanjaro", "Mount Fuji"], "correctIndex": 1, "explanation": "Mount Everest is the tallest"}, {"question": "Two languages of Canada?", "options": ["English/Spanish", "English/French", "French/Spanish", "English/German"], "correctIndex": 1, "explanation": "English and French are official"}, {"question": "Brazil is on which continent?", "options": ["Africa", "Europe", "South America", "Asia"], "correctIndex": 2, "explanation": "Brazil is in South America"}, {"question": "What is an island?", "options": ["Land surrounded by water", "Water surrounded by land", "Tall mountain", "Dry desert"], "correctIndex": 0, "explanation": "An island is land surrounded by water"}, {"question": "Map showing mountains is called?", "options": ["Political", "Climate", "Physical", "Road"], "correctIndex": 2, "explanation": "Physical maps show terrain"}, ], } @app.post("/api/student-game") async def student_game( request: Request, data: StudentGameRequest, _: bool = Depends(verify_api_key), ): """Generate quiz questions for the student game""" client_id = get_client_id(request) if not check_rate_limit(client_id): raise HTTPException(status_code=429, detail="Rate limit exceeded") subject = data.subject question_count = data.question_count # Build prompt for LLM prompt = f"""Generate exactly {question_count} educational multiple-choice quiz questions about {subject} for {data.grade_range} grade students. Return as a JSON array with no extra text: [ {{"question": "...", "options": ["A", "B", "C", "D"], "correctIndex": 0, "explanation": "..."}} ] Requirements: - Age-appropriate vocabulary - 4 answer choices each - Brief explanations - Varied difficulty Generate {question_count} questions now:""" try: response_text = call_llm("You are an educational quiz generator.", prompt, max_tokens=3000) # Try to parse JSON from response questions = [] try: # Find JSON array in response json_match = response_text if '[' in response_text: start = response_text.index('[') end = response_text.rindex(']') + 1 json_match = response_text[start:end] parsed = json.loads(json_match) if isinstance(parsed, list): questions = [ { "question": q.get("question", ""), "options": q.get("options", []), "correctIndex": q.get("correctIndex", 0), "explanation": q.get("explanation", "") } for q in parsed if q.get("question") and len(q.get("options", [])) == 4 ] except: pass # Use fallback if parsing failed or not enough questions if len(questions) < question_count: fallback = FALLBACK_QUIZ_QUESTIONS.get(subject, FALLBACK_QUIZ_QUESTIONS.get('Science', [])) questions = fallback[:question_count] return JSONResponse(content={ "success": True, "questions": questions, "timestamp": datetime.utcnow().isoformat(), }) except Exception as e: # Return fallback questions on any error fallback = FALLBACK_QUIZ_QUESTIONS.get(subject, FALLBACK_QUIZ_QUESTIONS.get('Science', [])) return JSONResponse(content={ "success": True, "questions": fallback[:question_count], "timestamp": datetime.utcnow().isoformat(), }) # ============================================ # ERROR HANDLERS # ============================================ @app.exception_handler(HTTPException) async def http_exception_handler(request: Request, exc: HTTPException): return JSONResponse( status_code=exc.status_code, content={ "success": False, "error": exc.detail, "timestamp": datetime.utcnow().isoformat(), }, ) @app.exception_handler(Exception) async def general_exception_handler(request: Request, exc: Exception): return JSONResponse( status_code=500, content={ "success": False, "error": "Internal server error", "timestamp": datetime.utcnow().isoformat(), }, ) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)