Spaces:
Sleeping
Sleeping
File size: 13,621 Bytes
4e3ac7f c7faf5f 4e3ac7f c7faf5f 4e3ac7f c7faf5f 4e3ac7f | 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 | """
Irish Maths AI — FastAPI backend.
Serves the chat API and static frontend.
"""
import os
import json
import hashlib
import hmac
import time
import httpx
from dotenv import load_dotenv
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse
from pydantic import BaseModel
from rag import search_curriculum, build_index
load_dotenv()
app = FastAPI(title="Irish Maths AI")
APP_PIN = os.getenv("APP_PIN", "AP19")
PIN_SECRET = os.getenv("PIN_SECRET", "mathai-pin-secret-key-2026")
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
# Load curriculum for topic browser
with open(os.path.join(DATA_DIR, "curriculum.json"), "r", encoding="utf-8") as f:
CURRICULUM = json.load(f)
# Build RAG index on startup
try:
build_index()
except Exception as e:
print(f"Warning: RAG index build failed ({e}). Will retry on first query.")
# ── Models ────────────────────────────────────────────────────────────────
class ChatRequest(BaseModel):
message: str
level: str = "" # "primary", "junior_cycle", "senior_cycle" or ""
class_group: str = "" # e.g. "5th Class", "Higher Level"
role: str = "student" # "student" or "teacher"
history: list = [] # prior messages [{role, content}]
SYSTEM_PROMPT_STUDENT = """You are **Mathaí** (pronounced "Mah-hee"), a friendly, encouraging Irish maths tutor.
RULES:
- You teach maths aligned to the Irish curriculum (Primary, Junior Cycle, Senior Cycle).
- Adapt your language to the student's class level. Use simple words for younger students.
- Always show step-by-step working. Use LaTeX notation wrapped in $...$ for inline maths and $$...$$ for display maths.
- After explaining, offer a practice question so the student can try.
- Be warm, positive and patient. Use emoji sparingly (🎯 ✅ 💡).
- If curriculum context is provided, reference the exact strand and topic.
- If you don't know, say so honestly. Never invent wrong maths.
- Keep answers concise — students lose focus on long walls of text.
- For primary students (Junior Infants to 6th Class), use very simple English and visual examples.
- For secondary students, be more rigorous but still clear.
You are speaking to a STUDENT."""
SYSTEM_PROMPT_TEACHER = """You are **Mathaí** (pronounced "Mah-hee"), an expert assistant for Irish maths teachers.
RULES:
- Provide curriculum-aligned resources, lesson plan ideas and assessment suggestions.
- Reference specific strands, topics and learning outcomes from the Irish curriculum.
- Use LaTeX notation wrapped in $...$ for inline maths and $$...$$ for display maths.
- Suggest differentiation strategies for mixed-ability classes.
- Be professional but approachable.
- If curriculum context is provided, cite exact strand, stage and learning outcomes.
You are speaking to a TEACHER."""
def _build_messages(req: ChatRequest, curriculum_context: str):
system = SYSTEM_PROMPT_TEACHER if req.role == "teacher" else SYSTEM_PROMPT_STUDENT
level_hint = ""
if req.class_group:
level_hint = f"\nThe user is in: {req.class_group}."
elif req.level:
labels = {"primary": "Primary School", "junior_cycle": "Junior Cycle", "senior_cycle": "Senior Cycle"}
level_hint = f"\nThe user's level: {labels.get(req.level, req.level)}."
if curriculum_context:
system += f"\n\n--- CURRICULUM CONTEXT (use this to ground your answer) ---\n{curriculum_context}"
if level_hint:
system += level_hint
messages = [{"role": "system", "content": system}]
# Add conversation history (last 10 turns max)
for msg in req.history[-10:]:
if msg.get("role") in ("user", "assistant"):
messages.append({"role": msg["role"], "content": msg["content"]})
messages.append({"role": "user", "content": req.message})
return messages
def _fallback_reply(question, rag_results, api_error=""):
"""Generate a helpful curriculum-based reply when OpenAI API is unreachable."""
parts = []
parts.append("**I'm currently in offline mode** (can't reach the AI service), but here's what I found from the Irish curriculum:\n")
if rag_results:
for i, r in enumerate(rag_results[:3], 1):
m = r["metadata"]
label = m.get("topic_label", "Topic")
stage = m.get("stage_label", "") or m.get("level_label", "")
classes = m.get("classes", "")
strand = m.get("strand_label", "")
parts.append(f"**{i}. {label}** ({stage})")
if classes:
parts.append(f" Classes: {classes}")
parts.append(f" Strand: {strand}")
# Show the learning outcomes from the chunk text
lines = r["text"].split("\n")
outcomes = [l.strip() for l in lines if l.strip().startswith("- ")]
for o in outcomes[:4]:
parts.append(f" {o}")
parts.append("")
parts.append("💡 **Tip:** Try these search terms to explore further, or check [curriculumonline.ie](https://www.curriculumonline.ie/primary/curriculum-areas/mathematics/) for the full curriculum.")
else:
parts.append("I couldn't find a specific curriculum match for your question.")
parts.append("\n💡 Try asking about a specific topic like *fractions*, *algebra*, *Pythagoras*, or *area and perimeter*.")
if api_error and "timeout" not in api_error.lower():
parts.append(f"\n*(Connection issue: {api_error[:100]})*")
return "\n".join(parts)
# ── Endpoints ─────────────────────────────────────────────────────────────
@app.post("/api/chat")
async def chat(req: ChatRequest):
if not GROQ_API_KEY:
return JSONResponse(
{"reply": "⚠️ Groq API key not configured. Add GROQ_API_KEY to your .env file. Get a free key at console.groq.com", "sources": []},
status_code=200,
)
# RAG: find relevant curriculum chunks
rag_results = search_curriculum(req.message, level=req.level, n_results=4)
curriculum_context = "\n\n".join(r["text"] for r in rag_results)
sources = []
for r in rag_results:
m = r["metadata"]
sources.append({
"strand": m.get("strand_label", ""),
"topic": m.get("topic_label", ""),
"level": m.get("level_label", ""),
"stage": m.get("stage_label", ""),
"classes": m.get("classes", ""),
})
messages = _build_messages(req, curriculum_context)
try:
async with httpx.AsyncClient(timeout=60, verify=True) as client:
resp = await client.post(
"https://api.groq.com/openai/v1/chat/completions",
headers={
"Authorization": f"Bearer {GROQ_API_KEY}",
"Content-Type": "application/json",
},
json={
"model": "llama-3.3-70b-versatile",
"messages": messages,
"temperature": 0.4,
"max_tokens": 1500,
},
)
data = resp.json()
if "error" in data:
reply = _fallback_reply(req.message, rag_results, api_error=data["error"].get("message", ""))
else:
reply = data["choices"][0]["message"]["content"]
except Exception as e:
# Network blocked / timeout — use curriculum-based fallback
reply = _fallback_reply(req.message, rag_results, api_error=str(e))
return {"reply": reply, "sources": sources}
@app.get("/api/curriculum")
async def get_curriculum():
"""Return the full curriculum tree for the topic browser."""
return CURRICULUM
@app.get("/api/curriculum/{level}")
async def get_curriculum_level(level: str):
"""Return curriculum for a specific level."""
if level in CURRICULUM:
return CURRICULUM[level]
return JSONResponse({"error": "Level not found"}, status_code=404)
@app.get("/api/quick-topics")
async def quick_topics():
"""Return popular quick-start topics for the home screen."""
return {
"student": {
"primary": [
{"label": "Adding & Subtracting", "query": "Help me with addition and subtraction", "icon": "➕"},
{"label": "Times Tables", "query": "Practice my times tables", "icon": "✖️"},
{"label": "Fractions", "query": "Explain fractions to me", "icon": "🍕"},
{"label": "Telling Time", "query": "Help me tell the time", "icon": "🕐"},
{"label": "Shapes", "query": "Teach me about shapes", "icon": "🔷"},
{"label": "Money", "query": "Help me with euros and cent", "icon": "💶"},
],
"junior_cycle": [
{"label": "Algebra", "query": "Explain solving equations", "icon": "🔤"},
{"label": "Pythagoras", "query": "Explain the theorem of Pythagoras with examples", "icon": "📐"},
{"label": "Statistics", "query": "How do I calculate mean, median and mode?", "icon": "📊"},
{"label": "Trigonometry", "query": "Explain sin, cos and tan", "icon": "📏"},
{"label": "Coordinate Geometry", "query": "How do I find the slope of a line?", "icon": "📈"},
{"label": "Percentages", "query": "Help me with percentage problems", "icon": "💯"},
],
"senior_cycle": [
{"label": "Differentiation", "query": "Explain differentiation from first principles", "icon": "📉"},
{"label": "Integration", "query": "How do I integrate functions?", "icon": "∫"},
{"label": "Sequences & Series", "query": "Explain arithmetic and geometric sequences", "icon": "🔢"},
{"label": "Probability", "query": "Help with Bernoulli trials", "icon": "🎲"},
{"label": "Complex Numbers", "query": "Explain complex numbers and the Argand diagram", "icon": "💠"},
{"label": "Financial Maths", "query": "How do I solve compound interest problems?", "icon": "🏦"},
],
},
"teacher": [
{"label": "Lesson Plan Ideas", "query": "Suggest a lesson plan for teaching fractions to 4th class", "icon": "📋"},
{"label": "Differentiation Strategies", "query": "How can I differentiate maths for mixed-ability classes?", "icon": "🎯"},
{"label": "Assessment Ideas", "query": "Suggest assessment activities for Junior Cycle algebra", "icon": "✅"},
{"label": "Real-World Maths", "query": "Give me real-world examples to make maths engaging for 2nd years", "icon": "🌍"},
{"label": "Worksheet Generator", "query": "Create 10 practice questions on area and perimeter for 5th class", "icon": "📝"},
{"label": "Exam Prep", "query": "What are the key Leaving Cert Higher Level topics to revise?", "icon": "🎓"},
],
}
# ── Static files ──────────────────────────────────────────────────────────
app.mount("/static", StaticFiles(directory=os.path.join(os.path.dirname(__file__), "static")), name="static")
# ── PIN Auth ──────────────────────────────────────────────────────────────
class PinRequest(BaseModel):
pin: str
def _make_pin_token():
"""Create an HMAC token that proves PIN was entered correctly."""
payload = f"mathai-ok-{int(time.time()) // (86400 * 365)}"
sig = hmac.new(PIN_SECRET.encode(), payload.encode(), hashlib.sha256).hexdigest()[:32]
return f"{payload}.{sig}"
def _verify_pin_token(token: str) -> bool:
try:
parts = token.rsplit(".", 1)
if len(parts) != 2:
return False
payload, sig = parts
expected = hmac.new(PIN_SECRET.encode(), payload.encode(), hashlib.sha256).hexdigest()[:32]
return hmac.compare_digest(sig, expected)
except Exception:
return False
@app.post("/api/pin/verify")
async def verify_pin(req: PinRequest):
if req.pin == APP_PIN:
return {"ok": True, "token": _make_pin_token()}
return JSONResponse({"ok": False, "error": "Incorrect code"}, status_code=401)
@app.post("/api/pin/check")
async def check_pin_token(request: Request):
body = await request.json()
token = body.get("token", "")
return {"ok": _verify_pin_token(token)}
@app.get("/")
async def root():
return FileResponse(os.path.join(os.path.dirname(__file__), "static", "index.html"))
if __name__ == "__main__":
import uvicorn
port = int(os.getenv("PORT", "8700"))
print("\n 🧮 Irish Maths AI — Mathaí")
print(f" http://localhost:{port}\n")
uvicorn.run(app, host="0.0.0.0", port=port)
|