v2: LangGraph multi-agent backend + transformer knowledge tracing (ONNX)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- .gitignore +6 -0
- .python-version +0 -1
- Dockerfile +17 -23
- README.md +107 -4
- backend/.env.example +12 -2
- backend/Dockerfile +14 -26
- backend/agent_communication/message_bus.py +0 -88
- backend/agent_communication/protocols.py +0 -52
- backend/agent_knowledge/__init__.py +0 -0
- backend/agent_knowledge/rules/__init__.py +0 -0
- backend/agent_knowledge/rules/assessment_rules.py +0 -87
- backend/agent_knowledge/rules/knowledge_rules.py +0 -47
- backend/agent_knowledge/rules/recommendation_rules.py +0 -44
- backend/agents/__init__.py +0 -0
- backend/agents/assessment_agent.py +115 -188
- backend/agents/base_agent.py +0 -73
- backend/agents/coordinator_agent.py +0 -275
- backend/agents/graph.py +83 -0
- backend/agents/init.py +0 -21
- backend/agents/knowledge_agent.py +9 -214
- backend/agents/metrics.py +71 -0
- backend/agents/recommendation_agent.py +92 -267
- backend/agents/schemas.py +61 -0
- backend/agents/state.py +34 -0
- backend/agents/teaching_agent.py +108 -141
- backend/agents/tutor_agent.py +56 -122
- backend/agents/tutor_chat.py +101 -0
- backend/app.py +93 -605
- backend/config.py +64 -13
- backend/curriculum/__init__.py +0 -0
- backend/curriculum/curriculum.json +65 -0
- backend/curriculum/seed.py +46 -0
- backend/curriculum/seed_questions.json +222 -0
- backend/knowledge_tracker.py +0 -167
- backend/llm_service.py +0 -329
- backend/ml/__init__.py +0 -0
- backend/ml/artifacts/bkt_params.json +124 -0
- backend/ml/artifacts/kt_meta.json +51 -0
- backend/ml/artifacts/kt_model.onnx +3 -0
- backend/ml/bandit.py +72 -0
- backend/ml/bkt.py +73 -0
- backend/ml/kt_runtime.py +107 -0
- backend/ml/memory.py +38 -0
- backend/models.py +133 -19
- backend/requirements.txt +15 -7
- backend/requirements_light.txt +0 -6
- backend/routes.py +476 -0
- backend/services/__init__.py +0 -0
- backend/services/auth.py +77 -0
.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
backend/ml/artifacts/kt_model.onnx filter=lfs diff=lfs merge=lfs -text
|
.gitignore
CHANGED
|
@@ -59,3 +59,9 @@ yarn-error.log*
|
|
| 59 |
|
| 60 |
# Misc
|
| 61 |
output.txt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
# Misc
|
| 61 |
output.txt
|
| 62 |
+
|
| 63 |
+
# Training artefacts (downloaded data, logs, sweep results)
|
| 64 |
+
training/data_cache/
|
| 65 |
+
training/logs/
|
| 66 |
+
training/results/*_sweep_*.json
|
| 67 |
+
backend/tests/__pycache__/
|
.python-version
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
3.10.2
|
|
|
|
|
|
Dockerfile
CHANGED
|
@@ -1,32 +1,26 @@
|
|
| 1 |
-
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
|
|
|
|
|
|
|
| 8 |
WORKDIR /app
|
| 9 |
|
| 10 |
-
|
| 11 |
-
RUN
|
| 12 |
-
build-essential \
|
| 13 |
-
&& rm -rf /var/lib/apt/lists/*
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
RUN pip install --no-cache-dir -r requirements.txt
|
| 18 |
|
| 19 |
-
|
| 20 |
-
COPY . .
|
| 21 |
-
|
| 22 |
-
# Create data directory
|
| 23 |
-
RUN mkdir -p /app/data
|
| 24 |
-
|
| 25 |
-
# Final working directory for the app
|
| 26 |
WORKDIR /app/backend
|
| 27 |
-
|
| 28 |
-
# Expose port
|
| 29 |
EXPOSE 7860
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hugging Face Space image (sdk: docker, app_port: 7860). Serves the Flask API in backend/.
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
|
| 4 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 5 |
+
PYTHONUNBUFFERED=1 \
|
| 6 |
+
PIP_NO_CACHE_DIR=1 \
|
| 7 |
+
PORT=7860
|
| 8 |
|
| 9 |
+
# HF Spaces run containers as uid 1000
|
| 10 |
+
RUN useradd -m -u 1000 user
|
| 11 |
WORKDIR /app
|
| 12 |
|
| 13 |
+
COPY backend/requirements.txt /app/backend/requirements.txt
|
| 14 |
+
RUN pip install -r /app/backend/requirements.txt
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
COPY --chown=user backend /app/backend
|
| 17 |
+
RUN mkdir -p /app/data && chown -R user /app/data
|
|
|
|
| 18 |
|
| 19 |
+
USER user
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
WORKDIR /app/backend
|
|
|
|
|
|
|
| 21 |
EXPOSE 7860
|
| 22 |
|
| 23 |
+
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:7860/api/health')"
|
| 24 |
+
|
| 25 |
+
# One process (the DB seeding and the in-process metrics assume it); threads for concurrency.
|
| 26 |
+
CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--workers", "1", "--threads", "8", "--worker-class", "gthread", "--timeout", "180", "app:app"]
|
README.md
CHANGED
|
@@ -1,12 +1,115 @@
|
|
| 1 |
---
|
| 2 |
title: Adaptive Elearning Backend
|
| 3 |
emoji: 🧠
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
app_port: 7860
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: Adaptive Elearning Backend
|
| 3 |
emoji: 🧠
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: gray
|
| 6 |
sdk: docker
|
| 7 |
app_port: 7860
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# Adaptive E-Learning System
|
| 12 |
+
|
| 13 |
+
Adaptive tutoring that models what each learner knows, teaches at their level, and brings topics
|
| 14 |
+
back just before they are forgotten.
|
| 15 |
+
|
| 16 |
+
- **Frontend**: React + Vite + Tailwind (Vercel), at https://adaptive-e-learning-system.vercel.app
|
| 17 |
+
- **Backend**: Flask API on a Hugging Face Space (Docker)
|
| 18 |
+
- **Agents**: LangGraph multi-agent graph with LangChain structured outputs (Gemini)
|
| 19 |
+
- **Learner model**: Bayesian Knowledge Tracing (online) plus a transformer knowledge-tracing model
|
| 20 |
+
trained on GPU and served on CPU through ONNX Runtime
|
| 21 |
+
|
| 22 |
+
## Architecture
|
| 23 |
+
|
| 24 |
+
```
|
| 25 |
+
React (Vercel) ──Bearer token──► Flask API (HF Space, gunicorn gthread)
|
| 26 |
+
│
|
| 27 |
+
├── Coordinator = LangGraph StateGraph
|
| 28 |
+
│ START → KnowledgeAgent (learner profile)
|
| 29 |
+
│ ├─► TeachingAgent: strategy bandit → structured lesson (LLM / cache / offline)
|
| 30 |
+
│ ├─► AssessmentAgent: plan (target 70% success) → question bank
|
| 31 |
+
│ │ ↺ generate_questions (one LLM call, only when the bank runs short)
|
| 32 |
+
│ ├─► TutorAgent: hint ladder (socratic → conceptual → direct)
|
| 33 |
+
│ └─► RecommendationAgent: readiness, ZPD, spaced-repetition urgency
|
| 34 |
+
├── Tutor chat = LangGraph MessagesState + SQLite checkpointer (memory per user × topic)
|
| 35 |
+
├── Learner model = BKT (persisted) + forgetting curve + transformer KT (ONNX)
|
| 36 |
+
└── SQLite (WAL): users, attempts, question bank, lesson cache, bandit posteriors
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
| Agent | Decides | How |
|
| 40 |
+
|---|---|---|
|
| 41 |
+
| Knowledge | What does the learner know right now? | BKT posterior per topic, exponential forgetting, transformer KT predictions of P(correct) for every topic × difficulty |
|
| 42 |
+
| Teaching | How to teach this learner? | Expert rules provide the prior; a Thompson-sampling bandit learns from follow-up quiz results which strategy works per knowledge bucket |
|
| 43 |
+
| Assessment | Which questions, at what difficulty? | Difficulty mix chosen so predicted success ≈ 70%; unseen bank items preferred and calibrated by empirical p-correct; server-side grading |
|
| 44 |
+
| Tutor | How much help to give? | Hint level escalates with attempts; the LLM phrases it using the learner's code, output and mastery |
|
| 45 |
+
| Recommendation | What next? | Prerequisite readiness gate, learning potential, zone of proximal development, review urgency, goals |
|
| 46 |
+
|
| 47 |
+
## Knowledge-tracing results
|
| 48 |
+
|
| 49 |
+
Trained on an RTX 5090 (`training/`). Metric: test AUC for predicting the next answer.
|
| 50 |
+
|
| 51 |
+
**Real student data** (ASSISTments, standard DKVMN splits), used to validate the training harness:
|
| 52 |
+
|
| 53 |
+
| Model | ASSIST2009 | ASSIST2015 |
|
| 54 |
+
|---|---|---|
|
| 55 |
+
| BKT (per-skill, grid-search fit) | 0.711 | 0.702 |
|
| 56 |
+
| DKT (LSTM) | **0.819** | **0.731** |
|
| 57 |
+
| Transformer KT (best of a 16-config sweep) | 0.810 | 0.727 |
|
| 58 |
+
|
| 59 |
+
DKT matches published numbers. On these small datasets the transformer does not beat DKT, which is
|
| 60 |
+
consistent with public KT benchmarks.
|
| 61 |
+
|
| 62 |
+
**App curriculum** (20 topics, 3 difficulties, time gaps; 7.15M interactions from a learner simulator
|
| 63 |
+
with prerequisites, ZPD learning and forgetting):
|
| 64 |
+
|
| 65 |
+
| Model | Test AUC |
|
| 66 |
+
|---|---|
|
| 67 |
+
| Oracle (simulator's true probabilities, upper bound) | 0.719 |
|
| 68 |
+
| **Transformer KT, deployed (669k params, 2.7 MB ONNX)** | **0.693** |
|
| 69 |
+
| DKT (LSTM) | 0.689 |
|
| 70 |
+
| BKT | 0.654 |
|
| 71 |
+
| v1 heuristic tracker | 0.607 |
|
| 72 |
+
|
| 73 |
+
The deployed model captures about 88% of the achievable discrimination above chance; the v1 heuristic captured about 49%.
|
| 74 |
+
The simulator is not real learner data. Retrain on real logs with
|
| 75 |
+
`--app-db data/database.db` once the app has users; the pipeline appends them to the training set.
|
| 76 |
+
|
| 77 |
+
## Running locally
|
| 78 |
+
|
| 79 |
+
```bash
|
| 80 |
+
# one isolated env for the whole project (GPU wheels bundle their own CUDA runtime;
|
| 81 |
+
# the system driver/CUDA are untouched)
|
| 82 |
+
conda env create -f environment.yml && conda activate elearn
|
| 83 |
+
|
| 84 |
+
# backend (offline mode without a key: question bank + curriculum lessons)
|
| 85 |
+
cd backend && cp .env.example .env # add GEMINI_API_KEY and SECRET_KEY
|
| 86 |
+
SESSION_COOKIE_SECURE=false python app.py # http://localhost:7860
|
| 87 |
+
pytest tests -q
|
| 88 |
+
|
| 89 |
+
# frontend
|
| 90 |
+
cd frontend && npm install && npm run dev # http://localhost:3000
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
Retrain the models (GPU):
|
| 94 |
+
|
| 95 |
+
```bash
|
| 96 |
+
python training/train_kt.py --dataset assist2009 --model all # benchmark
|
| 97 |
+
python training/train_kt.py --dataset curriculum --model transformer \
|
| 98 |
+
--students 100000 --d 128 --layers 3 --heads 4 --dropout 0.1 --export # production model → backend/ml/artifacts
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
## Deployment
|
| 102 |
+
|
| 103 |
+
- **HF Space**: built from the root `Dockerfile`. Set the secrets `SECRET_KEY` and `GEMINI_API_KEY`
|
| 104 |
+
(optional: `LLM_MODEL`). Enable persistent storage to keep the database across restarts; it is used
|
| 105 |
+
automatically when `/data` is mounted.
|
| 106 |
+
- **Vercel**: root `frontend/`, env `VITE_API_URL=https://sawabedarain-adaptive-elearning-backend.hf.space`.
|
| 107 |
+
|
| 108 |
+
## API
|
| 109 |
+
|
| 110 |
+
`POST /api/register` · `POST /api/login` · `GET /api/current-user` · `PUT /api/profile`
|
| 111 |
+
`GET /api/topics` · `POST /api/generate-lesson` · `POST /api/generate-quiz` · `POST /api/submit-answer`
|
| 112 |
+
`GET /api/progress-summary` · `GET /api/knowledge-states` · `GET /api/recommendations` · `GET /api/next-topic`
|
| 113 |
+
`GET /api/learning-path/<id>` · `GET /api/review-queue` · `GET /api/study-tips`
|
| 114 |
+
`POST /api/check-code` (sandboxed subprocess) · `POST /api/ask-challenge-hint`
|
| 115 |
+
`POST /api/tutor/chat` · `GET|DELETE /api/tutor/history` · `GET /api/agent-status` · `GET /api/model-info` · `GET /api/health`
|
backend/.env.example
CHANGED
|
@@ -1,2 +1,12 @@
|
|
| 1 |
-
|
| 2 |
-
SECRET_KEY=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Required in production: signs auth tokens (generate with: python -c "import secrets; print(secrets.token_hex(32))")
|
| 2 |
+
SECRET_KEY=change-me
|
| 3 |
+
|
| 4 |
+
# LLM (Google Gemini via LangChain). Without a key the app runs in offline mode:
|
| 5 |
+
# question bank + curriculum-based lessons, rule-based hints.
|
| 6 |
+
GEMINI_API_KEY=
|
| 7 |
+
LLM_MODEL=gemini-2.5-flash
|
| 8 |
+
|
| 9 |
+
# Optional
|
| 10 |
+
# DATA_DIR=/data # defaults to /data on HF persistent storage, else ../data
|
| 11 |
+
# CORS_ORIGINS=http://localhost:3000,https://adaptive-e-learning-system.vercel.app
|
| 12 |
+
# SESSION_COOKIE_SECURE=false # set false for plain-http local development
|
backend/Dockerfile
CHANGED
|
@@ -1,33 +1,21 @@
|
|
| 1 |
-
#
|
| 2 |
-
FROM python:3.
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
WORKDIR /app
|
| 11 |
|
| 12 |
-
# Install system dependencies (needed for some python packages like numpy/scikit-learn)
|
| 13 |
-
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 14 |
-
build-essential \
|
| 15 |
-
&& rm -rf /var/lib/apt/lists/*
|
| 16 |
-
|
| 17 |
-
# Copy the requirements file into the container
|
| 18 |
COPY requirements.txt .
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
RUN
|
| 22 |
-
|
| 23 |
-
# Copy the rest of the backend code
|
| 24 |
-
COPY . .
|
| 25 |
|
| 26 |
-
|
| 27 |
-
RUN mkdir -p /app/data
|
| 28 |
-
|
| 29 |
-
# Expose the port the app runs on
|
| 30 |
EXPOSE 7860
|
| 31 |
-
|
| 32 |
-
# Run the application
|
| 33 |
-
CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--timeout", "120", "--workers", "1", "app:app"]
|
|
|
|
| 1 |
+
# Standalone backend image (build context: backend/). The repo-root Dockerfile is the one HF Spaces uses.
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
|
| 4 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 5 |
+
PYTHONUNBUFFERED=1 \
|
| 6 |
+
PIP_NO_CACHE_DIR=1 \
|
| 7 |
+
PORT=7860 \
|
| 8 |
+
DATA_DIR=/app/data
|
| 9 |
|
| 10 |
+
RUN useradd -m -u 1000 user
|
| 11 |
+
WORKDIR /app/backend
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
COPY requirements.txt .
|
| 14 |
+
RUN pip install -r requirements.txt
|
| 15 |
|
| 16 |
+
COPY --chown=user . .
|
| 17 |
+
RUN mkdir -p /app/data && chown -R user /app/data
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
USER user
|
|
|
|
|
|
|
|
|
|
| 20 |
EXPOSE 7860
|
| 21 |
+
CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--workers", "1", "--threads", "8", "--worker-class", "gthread", "--timeout", "180", "app:app"]
|
|
|
|
|
|
backend/agent_communication/message_bus.py
DELETED
|
@@ -1,88 +0,0 @@
|
|
| 1 |
-
from datetime import datetime
|
| 2 |
-
from models import db, AgentMessage
|
| 3 |
-
import json
|
| 4 |
-
|
| 5 |
-
class AgentMessageBus:
|
| 6 |
-
"""
|
| 7 |
-
Central message bus for inter-agent communication.
|
| 8 |
-
Allows agents to subscribe to topics and send direct messages.
|
| 9 |
-
"""
|
| 10 |
-
|
| 11 |
-
_instance = None
|
| 12 |
-
|
| 13 |
-
def __new__(cls):
|
| 14 |
-
if cls._instance is None:
|
| 15 |
-
cls._instance = super(AgentMessageBus, cls).__new__(cls)
|
| 16 |
-
cls._instance.subscribers = {} # agent_id -> callback
|
| 17 |
-
return cls._instance
|
| 18 |
-
|
| 19 |
-
def subscribe(self, agent_id, callback):
|
| 20 |
-
"""
|
| 21 |
-
Register an agent to receive messages.
|
| 22 |
-
|
| 23 |
-
Args:
|
| 24 |
-
agent_id (str): The ID of the receiving agent.
|
| 25 |
-
callback (func): Function to call when message arrives.
|
| 26 |
-
"""
|
| 27 |
-
self.subscribers[agent_id] = callback
|
| 28 |
-
print(f"Agent {agent_id} subscribed to message bus.")
|
| 29 |
-
|
| 30 |
-
def send_message(self, from_agent, to_agent, message_type, content):
|
| 31 |
-
"""
|
| 32 |
-
Send a message from one agent to another.
|
| 33 |
-
"""
|
| 34 |
-
# Create persistent record
|
| 35 |
-
try:
|
| 36 |
-
message = AgentMessage(
|
| 37 |
-
from_agent=from_agent,
|
| 38 |
-
to_agent=to_agent,
|
| 39 |
-
message_type=message_type,
|
| 40 |
-
content=content,
|
| 41 |
-
status='pending'
|
| 42 |
-
)
|
| 43 |
-
# Use application context if running within request
|
| 44 |
-
if db.session:
|
| 45 |
-
db.session.add(message)
|
| 46 |
-
db.session.commit()
|
| 47 |
-
except Exception as e:
|
| 48 |
-
print(f"Warning: Could not save message to DB: {e}")
|
| 49 |
-
message = AgentMessage(
|
| 50 |
-
from_agent=from_agent,
|
| 51 |
-
to_agent=to_agent,
|
| 52 |
-
message_type=message_type,
|
| 53 |
-
content=content,
|
| 54 |
-
status='pending'
|
| 55 |
-
)
|
| 56 |
-
|
| 57 |
-
# Direct delivery if subscriber exists (Synchronous for now)
|
| 58 |
-
if to_agent in self.subscribers:
|
| 59 |
-
try:
|
| 60 |
-
response = self.subscribers[to_agent](message)
|
| 61 |
-
|
| 62 |
-
# Update status
|
| 63 |
-
if db.session:
|
| 64 |
-
message.status = 'processed'
|
| 65 |
-
message.processed_at = datetime.utcnow()
|
| 66 |
-
db.session.commit()
|
| 67 |
-
|
| 68 |
-
return response
|
| 69 |
-
except Exception as e:
|
| 70 |
-
print(f"Error delivering message to {to_agent}: {e}")
|
| 71 |
-
if db.session:
|
| 72 |
-
message.status = 'failed'
|
| 73 |
-
db.session.commit()
|
| 74 |
-
return None
|
| 75 |
-
else:
|
| 76 |
-
print(f"Agent {to_agent} not found or offline.")
|
| 77 |
-
return None
|
| 78 |
-
|
| 79 |
-
def broadcast(self, from_agent, message_type, content):
|
| 80 |
-
"""
|
| 81 |
-
Send a message to all subscribed agents (except sender).
|
| 82 |
-
"""
|
| 83 |
-
responses = {}
|
| 84 |
-
for agent_id in self.subscribers:
|
| 85 |
-
if agent_id != from_agent:
|
| 86 |
-
response = self.send_message(from_agent, agent_id, message_type, content)
|
| 87 |
-
responses[agent_id] = response
|
| 88 |
-
return responses
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/agent_communication/protocols.py
DELETED
|
@@ -1,52 +0,0 @@
|
|
| 1 |
-
class MessageProtocols:
|
| 2 |
-
"""
|
| 3 |
-
Defines standard message structures and types for agent communication.
|
| 4 |
-
Ensures all agents speak the same 'language'.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
# Message Types
|
| 8 |
-
KNOWLEDGE_REQUEST = 'knowledge_request'
|
| 9 |
-
KNOWLEDGE_RESPONSE = 'knowledge_response'
|
| 10 |
-
LEARNING_COMPLETE = 'learning_complete'
|
| 11 |
-
CONTENT_REQUEST = 'content_request'
|
| 12 |
-
ASSESSMENT_RESULT = 'assessment_result'
|
| 13 |
-
|
| 14 |
-
@staticmethod
|
| 15 |
-
def request_student_profile(user_id, topic_id=None):
|
| 16 |
-
"""Teaching Agent -> Knowledge Agent"""
|
| 17 |
-
return {
|
| 18 |
-
'type': MessageProtocols.KNOWLEDGE_REQUEST,
|
| 19 |
-
'user_id': user_id,
|
| 20 |
-
'topic_id': topic_id,
|
| 21 |
-
'fields': ['knowledge_level', 'learning_style', 'weak_areas', 'frustration_level']
|
| 22 |
-
}
|
| 23 |
-
|
| 24 |
-
@staticmethod
|
| 25 |
-
def provide_student_profile(user_id, profile_data):
|
| 26 |
-
"""Knowledge Agent -> Teaching Agent"""
|
| 27 |
-
return {
|
| 28 |
-
'type': MessageProtocols.KNOWLEDGE_RESPONSE,
|
| 29 |
-
'user_id': user_id,
|
| 30 |
-
'profile': profile_data
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
-
@staticmethod
|
| 34 |
-
def notify_assessment_complete(user_id, topic_id, score, details):
|
| 35 |
-
"""Assessment Agent -> Knowledge Agent"""
|
| 36 |
-
return {
|
| 37 |
-
'type': MessageProtocols.ASSESSMENT_RESULT,
|
| 38 |
-
'user_id': user_id,
|
| 39 |
-
'topic_id': topic_id,
|
| 40 |
-
'score': score,
|
| 41 |
-
'details': details
|
| 42 |
-
}
|
| 43 |
-
|
| 44 |
-
@staticmethod
|
| 45 |
-
def request_content_generation(topic_id, content_type, difficulty):
|
| 46 |
-
"""Coordinator -> Specialist Agent"""
|
| 47 |
-
return {
|
| 48 |
-
'type': MessageProtocols.CONTENT_REQUEST,
|
| 49 |
-
'topic_id': topic_id,
|
| 50 |
-
'content_type': content_type,
|
| 51 |
-
'difficulty': difficulty
|
| 52 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/agent_knowledge/__init__.py
ADDED
|
File without changes
|
backend/agent_knowledge/rules/__init__.py
ADDED
|
File without changes
|
backend/agent_knowledge/rules/assessment_rules.py
DELETED
|
@@ -1,87 +0,0 @@
|
|
| 1 |
-
import json
|
| 2 |
-
import os
|
| 3 |
-
import random
|
| 4 |
-
|
| 5 |
-
class AssessmentRuleEngine:
|
| 6 |
-
"""
|
| 7 |
-
Expert system for assessment decisions.
|
| 8 |
-
Selects questions and formats quizzes based on rules and templates.
|
| 9 |
-
"""
|
| 10 |
-
|
| 11 |
-
def __init__(self, knowledge_base_path=None):
|
| 12 |
-
if knowledge_base_path is None:
|
| 13 |
-
base_dir = os.path.dirname(os.path.dirname(__file__))
|
| 14 |
-
knowledge_base_path = os.path.join(base_dir, 'knowledge_bases', 'question_templates.json')
|
| 15 |
-
|
| 16 |
-
self.question_templates = []
|
| 17 |
-
self.rubrics = {}
|
| 18 |
-
self._load_knowledge_base(knowledge_base_path)
|
| 19 |
-
|
| 20 |
-
def _load_knowledge_base(self, path):
|
| 21 |
-
try:
|
| 22 |
-
with open(path, 'r') as f:
|
| 23 |
-
data = json.load(f)
|
| 24 |
-
self.question_templates = data.get('question_templates', [])
|
| 25 |
-
self.rubrics = data.get('assessment_rubrics', {})
|
| 26 |
-
except Exception as e:
|
| 27 |
-
print(f"Error loading assessment knowledge base: {e}")
|
| 28 |
-
|
| 29 |
-
def select_question_types(self, knowledge_level, topic_difficulty):
|
| 30 |
-
"""
|
| 31 |
-
Determine the mix of question types/difficulties.
|
| 32 |
-
"""
|
| 33 |
-
mix = {"beginner": 0, "intermediate": 0, "advanced": 0}
|
| 34 |
-
|
| 35 |
-
if knowledge_level < 0.3:
|
| 36 |
-
mix["beginner"] = 3
|
| 37 |
-
mix["intermediate"] = 1
|
| 38 |
-
elif knowledge_level < 0.7:
|
| 39 |
-
mix["beginner"] = 1
|
| 40 |
-
mix["intermediate"] = 2
|
| 41 |
-
mix["advanced"] = 1
|
| 42 |
-
else:
|
| 43 |
-
mix["intermediate"] = 2
|
| 44 |
-
mix["advanced"] = 3
|
| 45 |
-
|
| 46 |
-
return mix
|
| 47 |
-
|
| 48 |
-
def get_template_for_topic(self, topic_name, difficulty):
|
| 49 |
-
"""
|
| 50 |
-
Find a question template suitable for the topic and difficulty.
|
| 51 |
-
"""
|
| 52 |
-
candidates = []
|
| 53 |
-
for t in self.question_templates:
|
| 54 |
-
# Check if template is applicable to this topic (simple keyword match for now)
|
| 55 |
-
# In a real system, this would be a more robust tag matching
|
| 56 |
-
is_applicable = "all" in t['applicable_topics']
|
| 57 |
-
if not is_applicable:
|
| 58 |
-
for keyword in t['applicable_topics']:
|
| 59 |
-
if keyword in topic_name.lower():
|
| 60 |
-
is_applicable = True
|
| 61 |
-
break
|
| 62 |
-
|
| 63 |
-
if is_applicable:
|
| 64 |
-
candidates.append(t)
|
| 65 |
-
|
| 66 |
-
if not candidates:
|
| 67 |
-
return None
|
| 68 |
-
|
| 69 |
-
return random.choice(candidates)
|
| 70 |
-
|
| 71 |
-
def formulate_question_prompt(self, template, topic_name, difficulty):
|
| 72 |
-
"""
|
| 73 |
-
Use a template to create a specific prompt for the LLM to fill.
|
| 74 |
-
This reduces the LLM's work to just filling blanks/generating code.
|
| 75 |
-
"""
|
| 76 |
-
modifier = template['difficulty_modifiers'].get(difficulty, "Standard")
|
| 77 |
-
|
| 78 |
-
prompt = f"""
|
| 79 |
-
Generate a specific question about "{topic_name}" using this pattern:
|
| 80 |
-
"{template['pattern']}"
|
| 81 |
-
|
| 82 |
-
Constraint: {modifier}
|
| 83 |
-
Cognitive Level: {template['cognitive_level']}
|
| 84 |
-
|
| 85 |
-
Return the Code Snippet (if applicable), Options, Correct Answer, and Explanation.
|
| 86 |
-
"""
|
| 87 |
-
return prompt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/agent_knowledge/rules/knowledge_rules.py
DELETED
|
@@ -1,47 +0,0 @@
|
|
| 1 |
-
import math
|
| 2 |
-
from datetime import datetime
|
| 3 |
-
|
| 4 |
-
class KnowledgeRuleEngine:
|
| 5 |
-
"""
|
| 6 |
-
Expert system for knowledge tracking decisions.
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
def calculate_forgetting(self, last_practice_date, current_knowledge):
|
| 10 |
-
"""
|
| 11 |
-
Apply Ebbinghaus forgetting curve.
|
| 12 |
-
"""
|
| 13 |
-
if not last_practice_date:
|
| 14 |
-
return current_knowledge
|
| 15 |
-
|
| 16 |
-
days_elapsed = (datetime.utcnow() - last_practice_date).days
|
| 17 |
-
|
| 18 |
-
if days_elapsed <= 0:
|
| 19 |
-
return current_knowledge
|
| 20 |
-
|
| 21 |
-
# R = e^(-t/S)
|
| 22 |
-
# Stability (S) increases with knowledge strength
|
| 23 |
-
stability = max(1, current_knowledge * 30)
|
| 24 |
-
retention = math.exp(-days_elapsed / stability)
|
| 25 |
-
|
| 26 |
-
return current_knowledge * retention
|
| 27 |
-
|
| 28 |
-
def predict_growth(self, current_knowledge, is_correct, difficulty):
|
| 29 |
-
"""
|
| 30 |
-
Predict new knowledge level after an interaction.
|
| 31 |
-
"""
|
| 32 |
-
learning_rate = 0.1
|
| 33 |
-
difficulty_weight = 1.0
|
| 34 |
-
|
| 35 |
-
if difficulty == "advanced":
|
| 36 |
-
difficulty_weight = 1.2
|
| 37 |
-
elif difficulty == "beginner":
|
| 38 |
-
difficulty_weight = 0.8
|
| 39 |
-
|
| 40 |
-
if is_correct:
|
| 41 |
-
# Logarithmic growth: harder to improve as you get closer to 1.0
|
| 42 |
-
growth = learning_rate * difficulty_weight * (1 - current_knowledge)
|
| 43 |
-
return min(1.0, current_knowledge + growth)
|
| 44 |
-
else:
|
| 45 |
-
# Penalty is smaller than growth
|
| 46 |
-
penalty = learning_rate * 0.5 * current_knowledge
|
| 47 |
-
return max(0.0, current_knowledge - penalty)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/agent_knowledge/rules/recommendation_rules.py
DELETED
|
@@ -1,44 +0,0 @@
|
|
| 1 |
-
class RecommendationRuleEngine:
|
| 2 |
-
"""
|
| 3 |
-
Expert system for recommendation decisions.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
def score_topic(self, topic, user_knowledge_map):
|
| 7 |
-
"""
|
| 8 |
-
Score a topic for recommendation suitability.
|
| 9 |
-
Returns a score (higher is better).
|
| 10 |
-
"""
|
| 11 |
-
score = 0
|
| 12 |
-
current_knowledge = user_knowledge_map.get(topic.id, 0)
|
| 13 |
-
|
| 14 |
-
# Rule 1: Don't recommend mastered topics (unless for review)
|
| 15 |
-
if current_knowledge > 0.85:
|
| 16 |
-
return -1
|
| 17 |
-
|
| 18 |
-
# Rule 2: Prerequisites must be met
|
| 19 |
-
if not self._check_prerequisites(topic, user_knowledge_map):
|
| 20 |
-
return -10 # Blocked
|
| 21 |
-
|
| 22 |
-
# Rule 3: Prioritize active topics
|
| 23 |
-
if 0 < current_knowledge < 0.7:
|
| 24 |
-
score += 5
|
| 25 |
-
|
| 26 |
-
# Rule 4: Beginner topics get boost if nothing started
|
| 27 |
-
if current_knowledge == 0 and topic.difficulty == "beginner":
|
| 28 |
-
score += 3
|
| 29 |
-
|
| 30 |
-
return score
|
| 31 |
-
|
| 32 |
-
def _check_prerequisites(self, topic, knowledge_map):
|
| 33 |
-
if not topic.prerequisites:
|
| 34 |
-
return True
|
| 35 |
-
|
| 36 |
-
if isinstance(topic.prerequisites, str):
|
| 37 |
-
prereq_ids = [int(p) for p in topic.prerequisites.split(',') if p.strip()]
|
| 38 |
-
else:
|
| 39 |
-
prereq_ids = []
|
| 40 |
-
|
| 41 |
-
for pid in prereq_ids:
|
| 42 |
-
if knowledge_map.get(pid, 0) < 0.6:
|
| 43 |
-
return False
|
| 44 |
-
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/agents/__init__.py
ADDED
|
File without changes
|
backend/agents/assessment_agent.py
CHANGED
|
@@ -1,192 +1,119 @@
|
|
| 1 |
-
import json
|
| 2 |
"""
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
"""
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
from agent_knowledge.rules.assessment_rules import AssessmentRuleEngine
|
| 8 |
-
from agent_communication.message_bus import AgentMessageBus
|
| 9 |
-
from datetime import datetime
|
| 10 |
|
| 11 |
-
|
| 12 |
-
"""
|
| 13 |
-
Autonomous agent responsible for:
|
| 14 |
-
- Generating adaptive quizzes
|
| 15 |
-
- Evaluating answers
|
| 16 |
-
- Adjusting question difficulty
|
| 17 |
-
- Providing detailed feedback
|
| 18 |
-
"""
|
| 19 |
-
|
| 20 |
-
def __init__(self):
|
| 21 |
-
super().__init__("AA-001", "AssessmentAgent")
|
| 22 |
-
self.llm_service = LLMService()
|
| 23 |
-
self.rule_engine = AssessmentRuleEngine()
|
| 24 |
-
self.message_bus = AgentMessageBus()
|
| 25 |
-
self.quizzes_generated = 0
|
| 26 |
-
self.questions_evaluated = 0
|
| 27 |
-
self.difficulty_adjustments = 0
|
| 28 |
-
|
| 29 |
-
def perceive(self, student_state):
|
| 30 |
-
"""
|
| 31 |
-
Perceive student's quiz context
|
| 32 |
-
|
| 33 |
-
Args:
|
| 34 |
-
student_state: object with student's current state (e.g., knowledge_level)
|
| 35 |
-
"""
|
| 36 |
-
self.update_state("perceiving")
|
| 37 |
-
self.log(f"Perceiving assessment needs for user {student_state.user_id}")
|
| 38 |
-
|
| 39 |
-
self.user_id = student_state.user_id
|
| 40 |
-
self.topic_id = student_state.topic_id
|
| 41 |
-
self.knowledge_level = student_state.knowledge_level
|
| 42 |
-
self.recent_performance = student_state.recent_performance
|
| 43 |
-
self.quiz_type = student_state.quiz_type
|
| 44 |
-
|
| 45 |
-
# Logic to determine number of questions could be more dynamic
|
| 46 |
-
self.num_questions = 3 if self.knowledge_level < 0.5 else 5
|
| 47 |
-
return self.state
|
| 48 |
-
|
| 49 |
-
def decide(self):
|
| 50 |
-
"""
|
| 51 |
-
Autonomous decisions:
|
| 52 |
-
- What difficulty level for questions?
|
| 53 |
-
- How many questions?
|
| 54 |
-
- Question types (MCQ, coding, etc.)
|
| 55 |
-
- Focus areas
|
| 56 |
-
"""
|
| 57 |
-
self.update_state("deciding")
|
| 58 |
-
|
| 59 |
-
# Decide on the mix of questions (difficulty, type)
|
| 60 |
-
self.question_mix = self.rule_engine.select_question_types(
|
| 61 |
-
self.knowledge_level,
|
| 62 |
-
"intermediate" # topic difficulty placeholder
|
| 63 |
-
)
|
| 64 |
-
self.log(f"Decided question mix: {self.question_mix}")
|
| 65 |
-
return self
|
| 66 |
-
|
| 67 |
-
def act(self, topic, prompt=None):
|
| 68 |
-
"""
|
| 69 |
-
Execute: Generate adaptive quiz
|
| 70 |
-
"""
|
| 71 |
-
self.update_state("acting")
|
| 72 |
-
self.log(f"Generating quiz for topic: {topic.name}")
|
| 73 |
-
|
| 74 |
-
if not topic:
|
| 75 |
-
self.log("Topic not found", "error")
|
| 76 |
-
return {"error": "Topic not found"}
|
| 77 |
-
|
| 78 |
-
questions = []
|
| 79 |
-
try:
|
| 80 |
-
# 1. Try to generate questions from templates first (Rule-Based)
|
| 81 |
-
for difficulty, count in self.question_mix.items():
|
| 82 |
-
for _ in range(count):
|
| 83 |
-
template = self.rule_engine.get_template_for_topic(topic.name, difficulty)
|
| 84 |
-
if template:
|
| 85 |
-
# Use LLM just to fill the template (cheaper/faster than full gen)
|
| 86 |
-
# In future, fetch from ContentLibrary DB directly
|
| 87 |
-
q_prompt = self.rule_engine.formulate_question_prompt(
|
| 88 |
-
template, topic.name, difficulty
|
| 89 |
-
)
|
| 90 |
-
# We still use LLM service but with a very specific prompt
|
| 91 |
-
# This bridges the gap until we have a full static DB
|
| 92 |
-
generated = self.llm_service.generate_quiz_with_prompt(
|
| 93 |
-
topic.name, 1, custom_prompt=q_prompt
|
| 94 |
-
)
|
| 95 |
-
if generated:
|
| 96 |
-
questions.extend(generated)
|
| 97 |
-
|
| 98 |
-
# 2. Fallback or Fill remaining
|
| 99 |
-
if len(questions) < self.num_questions:
|
| 100 |
-
needed = self.num_questions - len(questions)
|
| 101 |
-
self.log(f"Template generation insufficient, requesting {needed} from LLM fallback.")
|
| 102 |
-
fallback_qs = self.llm_service.generate_quiz_with_prompt(
|
| 103 |
-
topic.name, needed, custom_prompt=prompt
|
| 104 |
-
)
|
| 105 |
-
if fallback_qs:
|
| 106 |
-
questions.extend(fallback_qs)
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
AssessmentAgent
|
| 3 |
+
decide (plan_quiz): choose quiz length and difficulty mix so predicted success ~= target
|
| 4 |
+
("desirable difficulty"), using the KT model's per-difficulty predictions
|
| 5 |
+
act (assemble_quiz): draw questions from the bank (no LLM), preferring unseen, well-calibrated items
|
| 6 |
+
generate_questions: only when the bank runs short — ONE structured LLM call, validated + deduplicated,
|
| 7 |
+
then loop back to assemble (a LangGraph cycle, max 2 rounds)
|
| 8 |
+
finalize_quiz: top-up from already-seen items if still short, then build the payload
|
| 9 |
"""
|
| 10 |
+
import math
|
| 11 |
+
import random
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
from langchain_core.messages import HumanMessage, SystemMessage
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
from models import QuestionBank, Topic, db
|
| 16 |
+
from services import content
|
| 17 |
+
|
| 18 |
+
from .metrics import tracked
|
| 19 |
+
from .schemas import Quiz
|
| 20 |
+
|
| 21 |
+
MAX_GENERATION_ROUNDS = 2
|
| 22 |
+
EXTRA_QUESTIONS = 3 # grow the bank a little beyond the immediate shortfall
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def allocate(weights, n):
|
| 26 |
+
"""Largest-remainder allocation of n slots proportional to weights."""
|
| 27 |
+
total = sum(weights.values()) or 1.0
|
| 28 |
+
raw = {k: n * w / total for k, w in weights.items()}
|
| 29 |
+
alloc = {k: int(math.floor(v)) for k, v in raw.items()}
|
| 30 |
+
for k in sorted(raw, key=lambda k: raw[k] - alloc[k], reverse=True)[: n - sum(alloc.values())]:
|
| 31 |
+
alloc[k] += 1
|
| 32 |
+
return alloc
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def make_nodes(ctx):
|
| 36 |
+
cfg = ctx.config
|
| 37 |
+
|
| 38 |
+
@tracked('assessment')
|
| 39 |
+
def plan_quiz(state):
|
| 40 |
+
tp = state['profile']['topics'].get(state['topic_id'], {})
|
| 41 |
+
pred = tp.get('predicted_success') or {'beginner': 0.7, 'intermediate': 0.55, 'advanced': 0.4}
|
| 42 |
+
practice = tp.get('practice_count', 0)
|
| 43 |
+
n = cfg.QUIZ_SIZE_MIN if practice < 5 else (cfg.QUIZ_SIZE_MAX if tp.get('effective_mastery', 0) > 0.7 else 5)
|
| 44 |
+
target = cfg.TARGET_SUCCESS_RATE
|
| 45 |
+
# Relative weighting: the difficulty whose predicted success is closest to the target dominates,
|
| 46 |
+
# even when every level is far from it (e.g. a brand-new learner).
|
| 47 |
+
closest = min(abs(p - target) for p in pred.values())
|
| 48 |
+
weights = {d: math.exp(-(abs(p - target) - closest) / 0.07) for d, p in pred.items()}
|
| 49 |
+
mix = allocate(weights, n)
|
| 50 |
+
expected = sum(pred[d] * c for d, c in mix.items()) / n
|
| 51 |
+
return {'quiz_plan': {'num_questions': n, 'difficulty_mix': mix, 'target_success': target,
|
| 52 |
+
'expected_success': round(expected, 3), 'predicted_success': pred},
|
| 53 |
+
'generation_rounds': state.get('generation_rounds', 0)}
|
| 54 |
+
|
| 55 |
+
@tracked('assessment')
|
| 56 |
+
def assemble_quiz(state):
|
| 57 |
+
plan = state['quiz_plan']
|
| 58 |
+
rows, shortfall = content.pick_questions(state['user_id'], state['topic_id'], plan['difficulty_mix'],
|
| 59 |
+
target_p=plan['target_success'])
|
| 60 |
+
return {'quiz': {'question_ids': [q.id for q in rows], 'shortfall': shortfall}}
|
| 61 |
+
|
| 62 |
+
def _generation_prompt(topic, shortfall, profile):
|
| 63 |
+
existing = [q.question for q in QuestionBank.query.filter_by(topic_id=topic.id).limit(40)]
|
| 64 |
+
weak = [w['name'] for w in profile.get('weak_topics', [])][:3]
|
| 65 |
+
templates = '\n'.join(f"- {t['id']} ({t['cognitive_level']}): {t['pattern'].splitlines()[0]}"
|
| 66 |
+
for t in ctx.question_templates)
|
| 67 |
+
wanted = ', '.join(f'{c} {d}' for d, c in shortfall.items())
|
| 68 |
+
total = sum(shortfall.values()) + EXTRA_QUESTIONS
|
| 69 |
+
return [
|
| 70 |
+
SystemMessage('You are an assessment designer who writes unambiguous multiple-choice questions '
|
| 71 |
+
'with exactly one correct answer and plausible distractors based on common misconceptions.'),
|
| 72 |
+
HumanMessage(
|
| 73 |
+
f"Write {total} multiple-choice questions on '{topic.name}': {topic.description}\n"
|
| 74 |
+
f"Difficulty counts needed: {wanted} (put the {EXTRA_QUESTIONS} extra at intermediate).\n"
|
| 75 |
+
f"Cover these concepts, spreading questions across them: {', '.join(topic.key_concepts or [])}.\n"
|
| 76 |
+
f"Vary question types using these templates:\n{templates}\n"
|
| 77 |
+
f"The learner is currently weak in: {', '.join(weak) or 'n/a'}.\n"
|
| 78 |
+
f"Do NOT repeat or paraphrase any of these existing questions:\n"
|
| 79 |
+
+ '\n'.join(f'- {q}' for q in existing[:30])
|
| 80 |
+
+ '\nRandomise which letter is correct. Keep code snippets short and put them inside the question text.'
|
| 81 |
+
),
|
| 82 |
+
]
|
| 83 |
+
|
| 84 |
+
@tracked('assessment')
|
| 85 |
+
def generate_questions(state):
|
| 86 |
+
topic = db.session.get(Topic, state['topic_id'])
|
| 87 |
+
rounds = state.get('generation_rounds', 0) + 1
|
| 88 |
+
result = ctx.llm.structured(Quiz, _generation_prompt(topic, state['quiz']['shortfall'], state['profile']))
|
| 89 |
+
if result is None:
|
| 90 |
+
return {'generation_rounds': MAX_GENERATION_ROUNDS, 'errors': ['question_generation_failed']}
|
| 91 |
+
added = content.add_questions(topic.id, [q.model_dump() for q in result.questions], source='llm')
|
| 92 |
+
return {'generation_rounds': rounds if added else MAX_GENERATION_ROUNDS}
|
| 93 |
+
|
| 94 |
+
@tracked('assessment')
|
| 95 |
+
def finalize_quiz(state):
|
| 96 |
+
plan, quiz = state['quiz_plan'], state['quiz']
|
| 97 |
+
ids = list(quiz['question_ids'])
|
| 98 |
+
missing = plan['num_questions'] - len(ids)
|
| 99 |
+
if missing > 0:
|
| 100 |
+
ids += [q.id for q in content.fill_from_any(state['user_id'], state['topic_id'], set(ids), missing)]
|
| 101 |
+
rows = {q.id: q for q in QuestionBank.query.filter(QuestionBank.id.in_(ids)).all()} if ids else {}
|
| 102 |
+
ordered = [rows[i] for i in ids if i in rows]
|
| 103 |
+
order = {'beginner': 0, 'intermediate': 1, 'advanced': 2}
|
| 104 |
+
ordered.sort(key=lambda q: (order.get(q.difficulty, 1), random.random())) # warm-up first
|
| 105 |
+
for q in ordered:
|
| 106 |
+
q.times_served = (q.times_served or 0) + 1
|
| 107 |
+
return {'quiz': {'questions': [q.to_public_dict() for q in ordered],
|
| 108 |
+
'metadata': {**plan, 'from_bank': len(quiz['question_ids']),
|
| 109 |
+
'generation_rounds': state.get('generation_rounds', 0)}}}
|
| 110 |
+
|
| 111 |
+
def route_after_assemble(state):
|
| 112 |
+
short = state['quiz'].get('shortfall')
|
| 113 |
+
if short and ctx.llm.available and state.get('generation_rounds', 0) < MAX_GENERATION_ROUNDS:
|
| 114 |
+
return 'generate_questions'
|
| 115 |
+
return 'finalize_quiz'
|
| 116 |
+
|
| 117 |
+
nodes = {'plan_quiz': plan_quiz, 'assemble_quiz': assemble_quiz,
|
| 118 |
+
'generate_questions': generate_questions, 'finalize_quiz': finalize_quiz}
|
| 119 |
+
return nodes, route_after_assemble
|
backend/agents/base_agent.py
DELETED
|
@@ -1,73 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Base Agent Class - All agents inherit from this
|
| 3 |
-
"""
|
| 4 |
-
from abc import ABC, abstractmethod
|
| 5 |
-
import logging
|
| 6 |
-
from datetime import datetime
|
| 7 |
-
|
| 8 |
-
logging.basicConfig(level=logging.INFO)
|
| 9 |
-
|
| 10 |
-
class StudentState:
|
| 11 |
-
"""Standardized student state object for agent perception"""
|
| 12 |
-
def __init__(self, user_id, **kwargs):
|
| 13 |
-
self.user_id = user_id
|
| 14 |
-
for key, value in kwargs.items():
|
| 15 |
-
setattr(self, key, value)
|
| 16 |
-
|
| 17 |
-
class BaseAgent(ABC):
|
| 18 |
-
"""Base class for all autonomous agents"""
|
| 19 |
-
|
| 20 |
-
def __init__(self, agent_id, name):
|
| 21 |
-
self.agent_id = agent_id
|
| 22 |
-
self.name = name
|
| 23 |
-
self.state = "idle"
|
| 24 |
-
self.memory = []
|
| 25 |
-
self.logger = logging.getLogger(f"Agent-{name}")
|
| 26 |
-
self.created_at = datetime.utcnow()
|
| 27 |
-
|
| 28 |
-
def log(self, message, level="info"):
|
| 29 |
-
"""Log agent activities"""
|
| 30 |
-
log_entry = {
|
| 31 |
-
"timestamp": datetime.utcnow().isoformat(),
|
| 32 |
-
"agent": self.name,
|
| 33 |
-
"message": message,
|
| 34 |
-
"state": self.state
|
| 35 |
-
}
|
| 36 |
-
self.memory.append(log_entry)
|
| 37 |
-
|
| 38 |
-
if level == "info":
|
| 39 |
-
self.logger.info(f"[{self.name}] {message}")
|
| 40 |
-
elif level == "error":
|
| 41 |
-
self.logger.error(f"[{self.name}] {message}")
|
| 42 |
-
elif level == "warning":
|
| 43 |
-
self.logger.warning(f"[{self.name}] {message}")
|
| 44 |
-
|
| 45 |
-
def update_state(self, new_state):
|
| 46 |
-
"""Update agent state"""
|
| 47 |
-
old_state = self.state
|
| 48 |
-
self.state = new_state
|
| 49 |
-
self.log(f"State transition: {old_state} → {new_state}")
|
| 50 |
-
|
| 51 |
-
@abstractmethod
|
| 52 |
-
def perceive(self, environment):
|
| 53 |
-
"""Perceive the environment - to be implemented by subclasses"""
|
| 54 |
-
pass
|
| 55 |
-
|
| 56 |
-
@abstractmethod
|
| 57 |
-
def decide(self):
|
| 58 |
-
"""Make autonomous decisions - to be implemented by subclasses"""
|
| 59 |
-
pass
|
| 60 |
-
|
| 61 |
-
@abstractmethod
|
| 62 |
-
def act(self):
|
| 63 |
-
"""Execute actions - to be implemented by subclasses"""
|
| 64 |
-
pass
|
| 65 |
-
|
| 66 |
-
def get_memory(self, limit=10):
|
| 67 |
-
"""Retrieve recent memory"""
|
| 68 |
-
return self.memory[-limit:]
|
| 69 |
-
|
| 70 |
-
def clear_memory(self):
|
| 71 |
-
"""Clear agent memory"""
|
| 72 |
-
self.memory = []
|
| 73 |
-
self.log("Memory cleared")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/agents/coordinator_agent.py
DELETED
|
@@ -1,275 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Coordinator Agent - Orchestrates all other agents
|
| 3 |
-
"""
|
| 4 |
-
from agents.base_agent import BaseAgent, StudentState
|
| 5 |
-
from agents.teaching_agent import TeachingAgent
|
| 6 |
-
from agents.assessment_agent import AssessmentAgent
|
| 7 |
-
from agents.knowledge_agent import KnowledgeAgent
|
| 8 |
-
from agents.tutor_agent import TutorAgent
|
| 9 |
-
from agents.recommendation_agent import RecommendationAgent
|
| 10 |
-
from datetime import datetime
|
| 11 |
-
import json
|
| 12 |
-
|
| 13 |
-
class CoordinatorAgent(BaseAgent):
|
| 14 |
-
"""
|
| 15 |
-
Master agent that coordinates all other agents
|
| 16 |
-
"""
|
| 17 |
-
|
| 18 |
-
def __init__(self):
|
| 19 |
-
super().__init__("CA-001", "CoordinatorAgent")
|
| 20 |
-
|
| 21 |
-
# Initialize all sub-agents
|
| 22 |
-
self.teaching_agent = TeachingAgent()
|
| 23 |
-
self.assessment_agent = AssessmentAgent()
|
| 24 |
-
self.knowledge_agent = KnowledgeAgent()
|
| 25 |
-
self.tutor_agent = TutorAgent()
|
| 26 |
-
self.recommendation_agent = RecommendationAgent()
|
| 27 |
-
|
| 28 |
-
self.tasks_coordinated = 0
|
| 29 |
-
|
| 30 |
-
self.log("Coordinator initialized with 5 sub-agents")
|
| 31 |
-
|
| 32 |
-
def perceive(self, environment):
|
| 33 |
-
"""
|
| 34 |
-
Perceive global learning environment
|
| 35 |
-
"""
|
| 36 |
-
self.update_state("perceiving")
|
| 37 |
-
self.log(f"Coordinating agents for task: {environment.get('task')}")
|
| 38 |
-
|
| 39 |
-
self.task = environment.get('task')
|
| 40 |
-
self.user_id = environment.get('user_id')
|
| 41 |
-
self.context = environment.get('context', {})
|
| 42 |
-
|
| 43 |
-
return self
|
| 44 |
-
|
| 45 |
-
def decide(self):
|
| 46 |
-
"""
|
| 47 |
-
Decide which agents to activate
|
| 48 |
-
"""
|
| 49 |
-
self.update_state("deciding")
|
| 50 |
-
|
| 51 |
-
# Route to appropriate agents based on task
|
| 52 |
-
self.active_agents = []
|
| 53 |
-
|
| 54 |
-
if self.task == "generate_lesson":
|
| 55 |
-
self.active_agents = [self.teaching_agent, self.knowledge_agent]
|
| 56 |
-
self.workflow = "sequential" # Knowledge first, then teaching
|
| 57 |
-
|
| 58 |
-
elif self.task == "generate_quiz":
|
| 59 |
-
self.active_agents = [self.knowledge_agent, self.assessment_agent]
|
| 60 |
-
self.workflow = "sequential"
|
| 61 |
-
|
| 62 |
-
elif self.task == "evaluate_answer":
|
| 63 |
-
self.active_agents = [self.assessment_agent, self.knowledge_agent]
|
| 64 |
-
self.workflow = "sequential"
|
| 65 |
-
|
| 66 |
-
elif self.task == "provide_hint":
|
| 67 |
-
self.active_agents = [self.tutor_agent]
|
| 68 |
-
self.workflow = "single"
|
| 69 |
-
|
| 70 |
-
elif self.task == "recommend_topic":
|
| 71 |
-
self.active_agents = [self.knowledge_agent, self.recommendation_agent]
|
| 72 |
-
self.workflow = "sequential"
|
| 73 |
-
|
| 74 |
-
elif self.task == "full_learning_session":
|
| 75 |
-
# Complex workflow involving all agents
|
| 76 |
-
self.active_agents = [
|
| 77 |
-
self.knowledge_agent,
|
| 78 |
-
self.recommendation_agent,
|
| 79 |
-
self.teaching_agent,
|
| 80 |
-
self.assessment_agent,
|
| 81 |
-
self.tutor_agent
|
| 82 |
-
]
|
| 83 |
-
self.workflow = "complex"
|
| 84 |
-
|
| 85 |
-
else:
|
| 86 |
-
self.log(f"Unknown task: {self.task}", "warning")
|
| 87 |
-
self.active_agents = []
|
| 88 |
-
self.workflow = "none"
|
| 89 |
-
|
| 90 |
-
self.log(f"Activating {len(self.active_agents)} agents in {self.workflow} workflow")
|
| 91 |
-
|
| 92 |
-
return self
|
| 93 |
-
|
| 94 |
-
def act(self):
|
| 95 |
-
"""
|
| 96 |
-
Execute coordinated agent workflow
|
| 97 |
-
"""
|
| 98 |
-
self.update_state("acting")
|
| 99 |
-
self.log("Executing coordinated workflow...")
|
| 100 |
-
|
| 101 |
-
results = {}
|
| 102 |
-
|
| 103 |
-
try:
|
| 104 |
-
# Create standardized student state
|
| 105 |
-
student_state = StudentState(
|
| 106 |
-
user_id=self.user_id,
|
| 107 |
-
**self.context
|
| 108 |
-
)
|
| 109 |
-
|
| 110 |
-
# Fetch Topic object if ID is present
|
| 111 |
-
current_topic = None
|
| 112 |
-
if self.context.get('topic_id'):
|
| 113 |
-
from models import Topic
|
| 114 |
-
current_topic = Topic.query.get(self.context['topic_id'])
|
| 115 |
-
|
| 116 |
-
if self.workflow == "single":
|
| 117 |
-
# Single agent execution
|
| 118 |
-
agent = self.active_agents[0]
|
| 119 |
-
agent.perceive(student_state)
|
| 120 |
-
agent.decide()
|
| 121 |
-
|
| 122 |
-
# Handle specific agent signatures
|
| 123 |
-
if isinstance(agent, TeachingAgent):
|
| 124 |
-
results = agent.act(topic=current_topic)
|
| 125 |
-
elif isinstance(agent, AssessmentAgent):
|
| 126 |
-
results = agent.act(topic=current_topic)
|
| 127 |
-
elif isinstance(agent, TutorAgent):
|
| 128 |
-
results = agent.act(prompt=self.context.get('question'))
|
| 129 |
-
elif isinstance(agent, KnowledgeAgent):
|
| 130 |
-
# KnowledgeAgent act requires specific action type usually
|
| 131 |
-
# For general single execution, we assume a state update or status check
|
| 132 |
-
action = self.context.get('action_type', 'get_status')
|
| 133 |
-
results = agent.act(self.user_id, action_type=action, **self.context)
|
| 134 |
-
elif isinstance(agent, RecommendationAgent):
|
| 135 |
-
results = agent.act()
|
| 136 |
-
|
| 137 |
-
elif self.workflow == "sequential":
|
| 138 |
-
# Sequential agent execution
|
| 139 |
-
# Note: This generic loop is hard to maintain with diverse signatures.
|
| 140 |
-
# We will customize it based on the specific sequence defined in decide()
|
| 141 |
-
|
| 142 |
-
for i, agent in enumerate(self.active_agents):
|
| 143 |
-
self.log(f"Step {i+1}: Executing {agent.name}")
|
| 144 |
-
|
| 145 |
-
# Update state with results from previous steps
|
| 146 |
-
for key, val in results.items():
|
| 147 |
-
setattr(student_state, key, val)
|
| 148 |
-
|
| 149 |
-
agent.perceive(student_state)
|
| 150 |
-
agent.decide()
|
| 151 |
-
|
| 152 |
-
agent_result = {}
|
| 153 |
-
if isinstance(agent, TeachingAgent):
|
| 154 |
-
# Teaching agent needs a topic. If not in context, maybe from previous agent?
|
| 155 |
-
topic_to_teach = current_topic
|
| 156 |
-
if 'next_best' in results: # From RecommendationAgent
|
| 157 |
-
# Mocking topic object from result dict if needed, or fetching DB
|
| 158 |
-
from models import Topic
|
| 159 |
-
topic_to_teach = Topic.query.get(results['next_best']['topic_id'])
|
| 160 |
-
|
| 161 |
-
if topic_to_teach:
|
| 162 |
-
agent_result = agent.act(topic=topic_to_teach)
|
| 163 |
-
else:
|
| 164 |
-
self.log("TeachingAgent needs a topic but none provided", "error")
|
| 165 |
-
|
| 166 |
-
elif isinstance(agent, AssessmentAgent):
|
| 167 |
-
agent_result = agent.act(topic=current_topic)
|
| 168 |
-
elif isinstance(agent, KnowledgeAgent):
|
| 169 |
-
# Sequential usually implies updating state after something
|
| 170 |
-
if 'quiz_score' in self.context:
|
| 171 |
-
agent_result = agent.act(self.user_id, 'update_state',
|
| 172 |
-
topic_id=current_topic.id,
|
| 173 |
-
is_correct=self.context.get('is_correct'),
|
| 174 |
-
difficulty=current_topic.difficulty)
|
| 175 |
-
else:
|
| 176 |
-
agent_result = agent.act(self.user_id, 'get_weak_areas')
|
| 177 |
-
|
| 178 |
-
elif isinstance(agent, RecommendationAgent):
|
| 179 |
-
agent_result = agent.act()
|
| 180 |
-
|
| 181 |
-
results[agent.name] = agent_result
|
| 182 |
-
|
| 183 |
-
elif self.workflow == "complex":
|
| 184 |
-
results = self._execute_complex_workflow(student_state, current_topic)
|
| 185 |
-
|
| 186 |
-
self.tasks_coordinated += 1
|
| 187 |
-
self.log(f"Workflow completed successfully")
|
| 188 |
-
self.update_state("completed")
|
| 189 |
-
|
| 190 |
-
return {
|
| 191 |
-
"success": True,
|
| 192 |
-
"results": results,
|
| 193 |
-
"workflow": self.workflow
|
| 194 |
-
}
|
| 195 |
-
|
| 196 |
-
except Exception as e:
|
| 197 |
-
self.log(f"Workflow error: {str(e)}", "error")
|
| 198 |
-
return {"success": False, "error": str(e)}
|
| 199 |
-
|
| 200 |
-
def _execute_complex_workflow(self, student_state, current_topic):
|
| 201 |
-
"""
|
| 202 |
-
Execute complex multi-agent workflow
|
| 203 |
-
"""
|
| 204 |
-
results = {}
|
| 205 |
-
|
| 206 |
-
# Step 1: Knowledge Agent analyzes current state
|
| 207 |
-
self.log("Complex workflow - Step 1: Knowledge analysis")
|
| 208 |
-
self.knowledge_agent.perceive(student_state)
|
| 209 |
-
# No decide/act needed for just analysis in this flow, but let's get weak areas
|
| 210 |
-
knowledge_result = self.knowledge_agent.act(self.user_id, 'get_weak_areas')
|
| 211 |
-
results['knowledge_analysis'] = knowledge_result
|
| 212 |
-
|
| 213 |
-
# Step 2: Recommendation Agent suggests path
|
| 214 |
-
self.log("Complex workflow - Step 2: Path recommendation")
|
| 215 |
-
self.recommendation_agent.perceive(student_state)
|
| 216 |
-
self.recommendation_agent.decide()
|
| 217 |
-
recommendation_result = self.recommendation_agent.act()
|
| 218 |
-
results['recommendations'] = recommendation_result
|
| 219 |
-
|
| 220 |
-
# Step 3: Teaching Agent creates lesson
|
| 221 |
-
if recommendation_result.get('next_best'):
|
| 222 |
-
next_topic_data = recommendation_result['next_best']
|
| 223 |
-
from models import Topic
|
| 224 |
-
next_topic = Topic.query.get(next_topic_data['topic_id'])
|
| 225 |
-
|
| 226 |
-
self.log("Complex workflow - Step 3: Lesson generation")
|
| 227 |
-
# Update student state with specific topic context
|
| 228 |
-
student_state.topic_id = next_topic.id
|
| 229 |
-
student_state.knowledge_level = next_topic_data.get('current_knowledge', 0)
|
| 230 |
-
|
| 231 |
-
self.teaching_agent.perceive(student_state)
|
| 232 |
-
self.teaching_agent.decide()
|
| 233 |
-
teaching_result = self.teaching_agent.act(topic=next_topic)
|
| 234 |
-
results['lesson'] = teaching_result
|
| 235 |
-
|
| 236 |
-
# Step 4: Assessment Agent prepares quiz for this new topic
|
| 237 |
-
self.log("Complex workflow - Step 4: Assessment preparation")
|
| 238 |
-
self.assessment_agent.perceive(student_state)
|
| 239 |
-
self.assessment_agent.decide()
|
| 240 |
-
assessment_result = self.assessment_agent.act(topic=next_topic)
|
| 241 |
-
results['assessment'] = assessment_result
|
| 242 |
-
|
| 243 |
-
return results
|
| 244 |
-
|
| 245 |
-
def get_agent_status(self):
|
| 246 |
-
"""
|
| 247 |
-
Get status of all agents
|
| 248 |
-
"""
|
| 249 |
-
return {
|
| 250 |
-
"coordinator": self.get_statistics(),
|
| 251 |
-
"sub_agents": {
|
| 252 |
-
"teaching": self.teaching_agent.get_statistics(),
|
| 253 |
-
"assessment": self.assessment_agent.get_statistics(),
|
| 254 |
-
"knowledge": self.knowledge_agent.get_statistics(),
|
| 255 |
-
"tutor": self.tutor_agent.get_statistics(),
|
| 256 |
-
"recommendation": self.recommendation_agent.get_statistics()
|
| 257 |
-
},
|
| 258 |
-
"total_memory": sum([
|
| 259 |
-
len(self.teaching_agent.memory),
|
| 260 |
-
len(self.assessment_agent.memory),
|
| 261 |
-
len(self.knowledge_agent.memory),
|
| 262 |
-
len(self.tutor_agent.memory),
|
| 263 |
-
len(self.recommendation_agent.memory)
|
| 264 |
-
])
|
| 265 |
-
}
|
| 266 |
-
|
| 267 |
-
def get_statistics(self):
|
| 268 |
-
"""Return coordinator statistics"""
|
| 269 |
-
return {
|
| 270 |
-
"agent": self.name,
|
| 271 |
-
"tasks_coordinated": self.tasks_coordinated,
|
| 272 |
-
"state": self.state,
|
| 273 |
-
"active_sub_agents": len(self.active_agents) if hasattr(self, 'active_agents') else 0,
|
| 274 |
-
"memory_size": len(self.memory)
|
| 275 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/agents/graph.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
CoordinatorAgent as a LangGraph StateGraph.
|
| 3 |
+
|
| 4 |
+
┌──────────────► recommend ──(full session)──┐
|
| 5 |
+
START ─► profile_learner┼──────────────► provide_hint ─► END │
|
| 6 |
+
(KnowledgeAgent) ├─► select_strategy ─► teach ─(full)─┐ │
|
| 7 |
+
│ ▲ (TeachingAgent) │ │
|
| 8 |
+
│ └─────────────────────────────┼───────┘
|
| 9 |
+
└─► plan_quiz ─► assemble_quiz ──► finalize_quiz ─► END
|
| 10 |
+
(AssessmentAgent) │ ▲
|
| 11 |
+
▼ │ (bank short & LLM available, ≤2 rounds)
|
| 12 |
+
generate_questions
|
| 13 |
+
"""
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
from langgraph.graph import END, START, StateGraph
|
| 17 |
+
|
| 18 |
+
from . import assessment_agent, knowledge_agent, recommendation_agent, teaching_agent, tutor_agent
|
| 19 |
+
from .metrics import METRICS
|
| 20 |
+
from .state import LearningState
|
| 21 |
+
|
| 22 |
+
TASK_ENTRY = {
|
| 23 |
+
'generate_lesson': 'select_strategy',
|
| 24 |
+
'generate_quiz': 'plan_quiz',
|
| 25 |
+
'provide_hint': 'provide_hint',
|
| 26 |
+
'recommend_topic': 'recommend',
|
| 27 |
+
'full_learning_session': 'recommend',
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def build_graph(ctx):
|
| 32 |
+
g = StateGraph(LearningState)
|
| 33 |
+
nodes = {}
|
| 34 |
+
nodes.update(knowledge_agent.make_nodes(ctx))
|
| 35 |
+
nodes.update(teaching_agent.make_nodes(ctx))
|
| 36 |
+
assessment_nodes, route_after_assemble = assessment_agent.make_nodes(ctx)
|
| 37 |
+
nodes.update(assessment_nodes)
|
| 38 |
+
nodes.update(tutor_agent.make_nodes(ctx))
|
| 39 |
+
nodes.update(recommendation_agent.make_nodes(ctx))
|
| 40 |
+
for name, fn in nodes.items():
|
| 41 |
+
g.add_node(name, fn)
|
| 42 |
+
|
| 43 |
+
g.add_edge(START, 'profile_learner')
|
| 44 |
+
g.add_conditional_edges('profile_learner', lambda s: TASK_ENTRY.get(s['task'], END),
|
| 45 |
+
list(set(TASK_ENTRY.values())) + [END])
|
| 46 |
+
g.add_conditional_edges('recommend',
|
| 47 |
+
lambda s: 'select_strategy' if s['task'] == 'full_learning_session' and s.get('topic_id') else END,
|
| 48 |
+
['select_strategy', END])
|
| 49 |
+
g.add_edge('select_strategy', 'teach')
|
| 50 |
+
g.add_conditional_edges('teach', lambda s: 'plan_quiz' if s['task'] == 'full_learning_session' else END,
|
| 51 |
+
['plan_quiz', END])
|
| 52 |
+
g.add_edge('plan_quiz', 'assemble_quiz')
|
| 53 |
+
g.add_conditional_edges('assemble_quiz', route_after_assemble, ['generate_questions', 'finalize_quiz'])
|
| 54 |
+
g.add_edge('generate_questions', 'assemble_quiz')
|
| 55 |
+
g.add_edge('finalize_quiz', END)
|
| 56 |
+
g.add_edge('provide_hint', END)
|
| 57 |
+
return g.compile()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Coordinator:
|
| 61 |
+
"""Thin facade used by the Flask routes."""
|
| 62 |
+
|
| 63 |
+
def __init__(self, ctx):
|
| 64 |
+
self.ctx = ctx
|
| 65 |
+
self.graph = build_graph(ctx)
|
| 66 |
+
|
| 67 |
+
def run(self, task, user_id, topic_id=None, **request):
|
| 68 |
+
if task not in TASK_ENTRY:
|
| 69 |
+
raise ValueError(f'Unknown task: {task}')
|
| 70 |
+
METRICS.start('coordinator')
|
| 71 |
+
t0 = time.perf_counter()
|
| 72 |
+
ok = True
|
| 73 |
+
try:
|
| 74 |
+
return self.graph.invoke({'task': task, 'user_id': user_id, 'topic_id': topic_id,
|
| 75 |
+
'request': request, 'trace': [], 'errors': []})
|
| 76 |
+
except Exception:
|
| 77 |
+
ok = False
|
| 78 |
+
raise
|
| 79 |
+
finally:
|
| 80 |
+
METRICS.finish('coordinator', int((time.perf_counter() - t0) * 1000), ok=ok, note=task)
|
| 81 |
+
|
| 82 |
+
def mermaid(self):
|
| 83 |
+
return self.graph.get_graph().draw_mermaid()
|
backend/agents/init.py
DELETED
|
@@ -1,21 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Multi-Agent System for Adaptive E-Learning
|
| 3 |
-
"""
|
| 4 |
-
|
| 5 |
-
from agents.base_agent import BaseAgent
|
| 6 |
-
from agents.teaching_agent import TeachingAgent
|
| 7 |
-
from agents.assessment_agent import AssessmentAgent
|
| 8 |
-
from agents.knowledge_agent import KnowledgeAgent
|
| 9 |
-
from agents.tutor_agent import TutorAgent
|
| 10 |
-
from agents.recommendation_agent import RecommendationAgent
|
| 11 |
-
from agents.coordinator_agent import CoordinatorAgent
|
| 12 |
-
|
| 13 |
-
__all__ = [
|
| 14 |
-
'BaseAgent',
|
| 15 |
-
'TeachingAgent',
|
| 16 |
-
'AssessmentAgent',
|
| 17 |
-
'KnowledgeAgent',
|
| 18 |
-
'TutorAgent',
|
| 19 |
-
'RecommendationAgent',
|
| 20 |
-
'CoordinatorAgent'
|
| 21 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/agents/knowledge_agent.py
CHANGED
|
@@ -1,216 +1,11 @@
|
|
|
|
|
|
|
|
| 1 |
|
| 2 |
-
"""
|
| 3 |
-
Knowledge Agent - Autonomous knowledge state management
|
| 4 |
-
"""
|
| 5 |
-
import json
|
| 6 |
-
from .base_agent import BaseAgent
|
| 7 |
-
from knowledge_tracker import KnowledgeTracker
|
| 8 |
-
from agent_knowledge.rules.knowledge_rules import KnowledgeRuleEngine
|
| 9 |
-
from models import db, KnowledgeState
|
| 10 |
-
import math
|
| 11 |
-
from datetime import datetime, timedelta
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
"""
|
| 21 |
-
|
| 22 |
-
def __init__(self):
|
| 23 |
-
super().__init__("KA-001", "KnowledgeAgent")
|
| 24 |
-
self.tracker = KnowledgeTracker()
|
| 25 |
-
self.rule_engine = KnowledgeRuleEngine()
|
| 26 |
-
self.predictions_made = 0
|
| 27 |
-
self.updates_performed = 0
|
| 28 |
-
|
| 29 |
-
def perceive(self, student_state):
|
| 30 |
-
"""
|
| 31 |
-
Perceive student's learning state
|
| 32 |
-
"""
|
| 33 |
-
self.update_state("perceiving")
|
| 34 |
-
self.user_id = getattr(student_state, 'user_id', None)
|
| 35 |
-
self.log(f"Perceiving knowledge state for user {self.user_id}")
|
| 36 |
-
|
| 37 |
-
self.topic_id = getattr(student_state, 'topic_id', None)
|
| 38 |
-
|
| 39 |
-
# Get all knowledge states
|
| 40 |
-
if self.user_id:
|
| 41 |
-
self.knowledge_states = KnowledgeState.query.filter_by(
|
| 42 |
-
user_id=self.user_id
|
| 43 |
-
).all()
|
| 44 |
-
else:
|
| 45 |
-
self.knowledge_states = []
|
| 46 |
-
|
| 47 |
-
self.log(f"Found {len(self.knowledge_states)} knowledge states")
|
| 48 |
-
|
| 49 |
-
return self
|
| 50 |
-
|
| 51 |
-
def decide(self):
|
| 52 |
-
"""
|
| 53 |
-
Autonomous decisions:
|
| 54 |
-
- Which topics need review?
|
| 55 |
-
- What's the optimal learning path?
|
| 56 |
-
- Are there knowledge gaps?
|
| 57 |
-
"""
|
| 58 |
-
self.update_state("deciding")
|
| 59 |
-
|
| 60 |
-
# Decision 1: Apply forgetting curves
|
| 61 |
-
topics_needing_review = []
|
| 62 |
-
for state in self.knowledge_states:
|
| 63 |
-
days_since_practice = (datetime.utcnow() - state.last_practiced).days
|
| 64 |
-
|
| 65 |
-
if days_since_practice > 7 and state.knowledge_level > 0.3:
|
| 66 |
-
topics_needing_review.append({
|
| 67 |
-
'topic_id': state.topic_id,
|
| 68 |
-
'days_since': days_since_practice,
|
| 69 |
-
'current_level': state.knowledge_level,
|
| 70 |
-
'priority': days_since_practice * (1 - state.knowledge_level)
|
| 71 |
-
})
|
| 72 |
-
|
| 73 |
-
# Sort by priority
|
| 74 |
-
topics_needing_review.sort(key=lambda x: x['priority'], reverse=True)
|
| 75 |
-
self.review_recommendations = topics_needing_review[:3]
|
| 76 |
-
|
| 77 |
-
# Decision 2: Identify knowledge gaps
|
| 78 |
-
self.knowledge_gaps = [
|
| 79 |
-
state for state in self.knowledge_states
|
| 80 |
-
if 0 < state.knowledge_level < 0.4
|
| 81 |
-
]
|
| 82 |
-
|
| 83 |
-
# Decision 3: Predict next knowledge level
|
| 84 |
-
if self.topic_id:
|
| 85 |
-
self.predicted_next_level = self._predict_knowledge_growth(self.topic_id)
|
| 86 |
-
else:
|
| 87 |
-
self.predicted_next_level = None
|
| 88 |
-
|
| 89 |
-
self.log(f"Decisions: {len(self.review_recommendations)} topics need review, "
|
| 90 |
-
f"{len(self.knowledge_gaps)} knowledge gaps found")
|
| 91 |
-
|
| 92 |
-
return self
|
| 93 |
-
|
| 94 |
-
def _predict_knowledge_growth(self, topic_id):
|
| 95 |
-
"""Predict knowledge growth based on learning patterns"""
|
| 96 |
-
state = KnowledgeState.query.filter_by(
|
| 97 |
-
user_id=self.user_id,
|
| 98 |
-
topic_id=topic_id
|
| 99 |
-
).first()
|
| 100 |
-
|
| 101 |
-
if not state:
|
| 102 |
-
return 0.15 # Expected growth for new topic
|
| 103 |
-
|
| 104 |
-
# Predict based on practice frequency and current level
|
| 105 |
-
if state.practice_count > 5:
|
| 106 |
-
# Experienced learner - slower growth
|
| 107 |
-
growth = 0.1 * (1 - state.knowledge_level)
|
| 108 |
-
else:
|
| 109 |
-
# New learner - faster initial growth
|
| 110 |
-
growth = 0.15 * (1 - state.knowledge_level)
|
| 111 |
-
|
| 112 |
-
predicted = min(1.0, state.knowledge_level + growth)
|
| 113 |
-
self.predictions_made += 1
|
| 114 |
-
|
| 115 |
-
self.log(f"Predicted knowledge growth: {state.knowledge_level:.2f} → {predicted:.2f}")
|
| 116 |
-
|
| 117 |
-
return predicted
|
| 118 |
-
|
| 119 |
-
def act(self, user_id=None, action_type="monitoring", **kwargs):
|
| 120 |
-
"""
|
| 121 |
-
Execute: Update knowledge states and provide recommendations
|
| 122 |
-
"""
|
| 123 |
-
self.update_state("acting")
|
| 124 |
-
|
| 125 |
-
if user_id:
|
| 126 |
-
self.user_id = user_id
|
| 127 |
-
|
| 128 |
-
# Dispatch based on action type
|
| 129 |
-
if action_type == 'update_state':
|
| 130 |
-
return self.update_knowledge_from_quiz(
|
| 131 |
-
kwargs.get('topic_id'),
|
| 132 |
-
kwargs.get('is_correct'),
|
| 133 |
-
kwargs.get('difficulty')
|
| 134 |
-
)
|
| 135 |
-
|
| 136 |
-
# Default / Monitoring / get_weak_areas logic
|
| 137 |
-
self.log(f"performing {action_type}...")
|
| 138 |
-
|
| 139 |
-
# Apply forgetting curves to all states
|
| 140 |
-
updated_states = []
|
| 141 |
-
for state in self.knowledge_states:
|
| 142 |
-
days_since = (datetime.utcnow() - state.last_practiced).days
|
| 143 |
-
|
| 144 |
-
if days_since > 0:
|
| 145 |
-
# Apply exponential forgetting
|
| 146 |
-
forgetting_factor = math.exp(-0.05 * days_since)
|
| 147 |
-
old_level = state.knowledge_level
|
| 148 |
-
state.knowledge_level *= forgetting_factor
|
| 149 |
-
|
| 150 |
-
if abs(old_level - state.knowledge_level) > 0.01:
|
| 151 |
-
updated_states.append({
|
| 152 |
-
'topic_id': state.topic_id,
|
| 153 |
-
'old_level': old_level,
|
| 154 |
-
'new_level': state.knowledge_level,
|
| 155 |
-
'decay': old_level - state.knowledge_level
|
| 156 |
-
})
|
| 157 |
-
self.updates_performed += 1
|
| 158 |
-
|
| 159 |
-
# Commit updates
|
| 160 |
-
if updated_states:
|
| 161 |
-
db.session.commit()
|
| 162 |
-
|
| 163 |
-
self.log(f"Updated {len(updated_states)} knowledge states")
|
| 164 |
-
self.update_state("completed")
|
| 165 |
-
|
| 166 |
-
return {
|
| 167 |
-
"review_recommendations": getattr(self, 'review_recommendations', []),
|
| 168 |
-
"knowledge_gaps": [
|
| 169 |
-
{
|
| 170 |
-
'topic_id': gap.topic_id,
|
| 171 |
-
'level': gap.knowledge_level,
|
| 172 |
-
'confidence': gap.confidence
|
| 173 |
-
}
|
| 174 |
-
for gap in getattr(self, 'knowledge_gaps', [])
|
| 175 |
-
],
|
| 176 |
-
"predicted_growth": getattr(self, 'predicted_next_level', None),
|
| 177 |
-
"updated_states": updated_states,
|
| 178 |
-
"agent": self.name,
|
| 179 |
-
"timestamp": datetime.utcnow().isoformat()
|
| 180 |
-
}
|
| 181 |
-
|
| 182 |
-
def update_knowledge_from_quiz(self, topic_id, is_correct, difficulty):
|
| 183 |
-
"""
|
| 184 |
-
Autonomous knowledge update based on quiz performance
|
| 185 |
-
"""
|
| 186 |
-
self.update_state("updating")
|
| 187 |
-
self.log(f"Updating knowledge for topic {topic_id}, correct={is_correct}")
|
| 188 |
-
|
| 189 |
-
# Use existing tracker but with agent logging
|
| 190 |
-
state = self.tracker.update_knowledge(
|
| 191 |
-
self.user_id,
|
| 192 |
-
topic_id,
|
| 193 |
-
is_correct,
|
| 194 |
-
difficulty
|
| 195 |
-
)
|
| 196 |
-
|
| 197 |
-
self.updates_performed += 1
|
| 198 |
-
self.log(f"Knowledge updated: {state.knowledge_level:.2f}, "
|
| 199 |
-
f"confidence: {state.confidence:.2f}")
|
| 200 |
-
|
| 201 |
-
return {
|
| 202 |
-
"new_level": state.knowledge_level,
|
| 203 |
-
"confidence": state.confidence,
|
| 204 |
-
"practice_count": state.practice_count,
|
| 205 |
-
"agent": self.name
|
| 206 |
-
}
|
| 207 |
-
|
| 208 |
-
def get_statistics(self):
|
| 209 |
-
"""Return agent statistics"""
|
| 210 |
-
return {
|
| 211 |
-
"agent": self.name,
|
| 212 |
-
"predictions_made": self.predictions_made,
|
| 213 |
-
"updates_performed": self.updates_performed,
|
| 214 |
-
"state": self.state,
|
| 215 |
-
"memory_size": len(self.memory)
|
| 216 |
-
}
|
|
|
|
| 1 |
+
"""KnowledgeAgent: builds the learner model every other agent conditions on."""
|
| 2 |
+
from .metrics import tracked
|
| 3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
def make_nodes(ctx):
|
| 6 |
+
@tracked('knowledge')
|
| 7 |
+
def profile_learner(state):
|
| 8 |
+
profile = ctx.knowledge.profile(state['user_id'])
|
| 9 |
+
return {'profile': profile}
|
| 10 |
+
|
| 11 |
+
return {'profile_learner': profile_learner}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/agents/metrics.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Thread-safe per-agent telemetry shown on the dashboard's agent panel."""
|
| 2 |
+
import functools
|
| 3 |
+
import threading
|
| 4 |
+
import time
|
| 5 |
+
from collections import deque
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
AGENTS = ('coordinator', 'knowledge', 'teaching', 'assessment', 'tutor', 'recommendation')
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class AgentMetrics:
|
| 12 |
+
def __init__(self):
|
| 13 |
+
self._lock = threading.Lock()
|
| 14 |
+
self._data = {a: {'runs': 0, 'errors': 0, 'total_ms': 0, 'state': 'idle', 'last_run_at': None}
|
| 15 |
+
for a in AGENTS}
|
| 16 |
+
self._log = deque(maxlen=200)
|
| 17 |
+
|
| 18 |
+
def start(self, agent):
|
| 19 |
+
with self._lock:
|
| 20 |
+
self._data[agent]['state'] = 'acting'
|
| 21 |
+
|
| 22 |
+
def finish(self, agent, ms, ok=True, note=None):
|
| 23 |
+
with self._lock:
|
| 24 |
+
d = self._data[agent]
|
| 25 |
+
d['runs'] += 1
|
| 26 |
+
d['total_ms'] += ms
|
| 27 |
+
d['errors'] += 0 if ok else 1
|
| 28 |
+
d['state'] = 'completed' if ok else 'error'
|
| 29 |
+
d['last_run_at'] = datetime.utcnow().isoformat(timespec='seconds')
|
| 30 |
+
self._log.append({'agent': agent, 'ms': ms, 'ok': ok, 'note': note, 'at': d['last_run_at']})
|
| 31 |
+
|
| 32 |
+
def snapshot(self):
|
| 33 |
+
with self._lock:
|
| 34 |
+
agents = {}
|
| 35 |
+
for name, d in self._data.items():
|
| 36 |
+
agents[name] = {
|
| 37 |
+
'agent': name,
|
| 38 |
+
'state': d['state'] if d['runs'] else 'idle',
|
| 39 |
+
'runs': d['runs'],
|
| 40 |
+
'errors': d['errors'],
|
| 41 |
+
'avg_latency_ms': round(d['total_ms'] / d['runs']) if d['runs'] else 0,
|
| 42 |
+
'last_run_at': d['last_run_at'],
|
| 43 |
+
'memory_size': sum(1 for e in self._log if e['agent'] == name),
|
| 44 |
+
}
|
| 45 |
+
return agents, list(self._log)[-20:]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
METRICS = AgentMetrics()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def tracked(agent, trace=True):
|
| 52 |
+
"""Decorator for LangGraph node functions: records latency/errors and (optionally) appends to state.trace."""
|
| 53 |
+
def deco(fn):
|
| 54 |
+
@functools.wraps(fn)
|
| 55 |
+
def wrapper(state, *args, **kwargs):
|
| 56 |
+
METRICS.start(agent)
|
| 57 |
+
t0 = time.perf_counter()
|
| 58 |
+
try:
|
| 59 |
+
update = fn(state, *args, **kwargs) or {}
|
| 60 |
+
except Exception:
|
| 61 |
+
METRICS.finish(agent, int((time.perf_counter() - t0) * 1000), ok=False)
|
| 62 |
+
raise
|
| 63 |
+
ms = int((time.perf_counter() - t0) * 1000)
|
| 64 |
+
METRICS.finish(agent, ms, note=fn.__name__)
|
| 65 |
+
if not trace:
|
| 66 |
+
return update
|
| 67 |
+
update.setdefault('trace', [])
|
| 68 |
+
update['trace'] = list(update['trace']) + [{'agent': agent, 'step': fn.__name__, 'ms': ms}]
|
| 69 |
+
return update
|
| 70 |
+
return wrapper
|
| 71 |
+
return deco
|
backend/agents/recommendation_agent.py
CHANGED
|
@@ -1,272 +1,97 @@
|
|
| 1 |
"""
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
"""
|
| 4 |
-
import
|
| 5 |
-
from .base_agent import BaseAgent
|
| 6 |
-
from llm_service import LLMService
|
| 7 |
-
from agent_knowledge.rules.recommendation_rules import RecommendationRuleEngine
|
| 8 |
-
from agent_communication.message_bus import AgentMessageBus
|
| 9 |
-
from models import Topic, KnowledgeState
|
| 10 |
-
from datetime import datetime
|
| 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 |
-
if
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
}
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
def decide(self):
|
| 49 |
-
"""
|
| 50 |
-
Autonomous decisions:
|
| 51 |
-
- What topic to recommend next?
|
| 52 |
-
- Short-term vs long-term path?
|
| 53 |
-
- Review vs new content?
|
| 54 |
-
"""
|
| 55 |
-
self.update_state("deciding")
|
| 56 |
-
|
| 57 |
-
# Decision 1: Calculate scores for all topics
|
| 58 |
-
topic_scores = []
|
| 59 |
-
|
| 60 |
-
for topic in self.all_topics:
|
| 61 |
-
if topic.id == self.current_topic_id:
|
| 62 |
-
continue # Skip current topic
|
| 63 |
-
|
| 64 |
-
score = self._calculate_topic_score(topic)
|
| 65 |
-
topic_scores.append((topic, score))
|
| 66 |
-
|
| 67 |
-
# Sort by score
|
| 68 |
-
topic_scores.sort(key=lambda x: x[1], reverse=True)
|
| 69 |
-
|
| 70 |
-
# Decision 2: Choose recommendation strategy
|
| 71 |
-
if len(self.knowledge_states) < 3:
|
| 72 |
-
# New learner - suggest foundation topics
|
| 73 |
-
self.strategy = "foundation_building"
|
| 74 |
-
self.recommendations = [t for t, s in topic_scores
|
| 75 |
-
if t.difficulty == 'beginner'][:3]
|
| 76 |
-
else:
|
| 77 |
-
# Experienced learner - balanced approach
|
| 78 |
-
self.strategy = "balanced_growth"
|
| 79 |
-
self.recommendations = [t for t, s in topic_scores[:5]]
|
| 80 |
-
|
| 81 |
-
self.log(f"Strategy: {self.strategy}, {len(self.recommendations)} recommendations")
|
| 82 |
-
|
| 83 |
-
return self
|
| 84 |
-
|
| 85 |
-
def _calculate_topic_score(self, topic):
|
| 86 |
-
"""
|
| 87 |
-
Autonomous scoring algorithm for topic recommendation
|
| 88 |
-
"""
|
| 89 |
-
score = 0
|
| 90 |
-
knowledge_level = self.knowledge_states.get(topic.id, 0)
|
| 91 |
-
|
| 92 |
-
# Factor 1: Unstarted topics (high priority for beginners)
|
| 93 |
-
if knowledge_level == 0:
|
| 94 |
-
score += 5
|
| 95 |
-
# Factor 2: In-progress topics
|
| 96 |
-
elif 0 < knowledge_level < 0.7:
|
| 97 |
-
score += 3
|
| 98 |
-
# Factor 3: Mastered topics (low priority)
|
| 99 |
-
elif knowledge_level >= 0.8:
|
| 100 |
-
score += 0.5
|
| 101 |
-
|
| 102 |
-
# Factor 4: Prerequisites
|
| 103 |
-
if topic.prerequisites:
|
| 104 |
-
prereq_ids = [int(x.strip()) for x in topic.prerequisites.split(',') if x.strip()]
|
| 105 |
-
prereqs_met = all(
|
| 106 |
-
self.knowledge_states.get(pid, 0) > 0.6
|
| 107 |
-
for pid in prereq_ids
|
| 108 |
-
)
|
| 109 |
-
|
| 110 |
-
if prereqs_met:
|
| 111 |
-
score += 3 # Ready to learn
|
| 112 |
-
else:
|
| 113 |
-
score -= 2 # Not ready yet
|
| 114 |
else:
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
score += 2
|
| 122 |
-
elif topic.difficulty == 'intermediate' and 0.3 <= avg_knowledge < 0.7:
|
| 123 |
-
score += 2
|
| 124 |
-
elif topic.difficulty == 'advanced' and avg_knowledge >= 0.7:
|
| 125 |
-
score += 2
|
| 126 |
-
|
| 127 |
-
# Factor 6: Goals alignment
|
| 128 |
-
if self.goals:
|
| 129 |
-
for goal in self.goals:
|
| 130 |
-
if goal.lower() in topic.name.lower() or goal.lower() in topic.category.lower():
|
| 131 |
-
score += 4
|
| 132 |
-
|
| 133 |
-
return score
|
| 134 |
-
|
| 135 |
-
def act(self):
|
| 136 |
-
"""
|
| 137 |
-
Execute: Provide recommendations
|
| 138 |
-
"""
|
| 139 |
-
self.update_state("acting")
|
| 140 |
-
self.log("Generating personalized recommendations...")
|
| 141 |
-
|
| 142 |
-
if not self.recommendations:
|
| 143 |
-
self.log("No suitable recommendations found", "warning")
|
| 144 |
-
self.update_state("completed")
|
| 145 |
-
return {
|
| 146 |
-
"recommendations": [],
|
| 147 |
-
"message": "Great progress! Review previous topics or explore new categories.",
|
| 148 |
-
"agent": self.name
|
| 149 |
-
}
|
| 150 |
-
|
| 151 |
-
# Build detailed recommendations
|
| 152 |
-
detailed_recommendations = []
|
| 153 |
-
|
| 154 |
-
for topic in self.recommendations:
|
| 155 |
-
knowledge_level = self.knowledge_states.get(topic.id, 0)
|
| 156 |
-
|
| 157 |
-
# Generate reason for recommendation
|
| 158 |
-
if knowledge_level == 0:
|
| 159 |
-
reason = "Ready to explore this new topic"
|
| 160 |
-
elif knowledge_level < 0.5:
|
| 161 |
-
reason = "Continue building on your progress"
|
| 162 |
-
elif knowledge_level < 0.8:
|
| 163 |
-
reason = "Almost there! Finish mastering this"
|
| 164 |
-
else:
|
| 165 |
-
reason = "Review to maintain mastery"
|
| 166 |
-
|
| 167 |
-
detailed_recommendations.append({
|
| 168 |
-
'topic_id': topic.id,
|
| 169 |
-
'name': topic.name,
|
| 170 |
-
'category': topic.category,
|
| 171 |
-
'difficulty': topic.difficulty,
|
| 172 |
-
'current_knowledge': knowledge_level,
|
| 173 |
-
'reason': reason,
|
| 174 |
-
'priority': 'high' if knowledge_level == 0 or 0.3 < knowledge_level < 0.7 else 'medium'
|
| 175 |
-
})
|
| 176 |
-
|
| 177 |
-
self.recommendations_made += 1
|
| 178 |
-
self.log(f"Recommendations generated (Total: {self.recommendations_made})")
|
| 179 |
-
|
| 180 |
-
# Store in memory
|
| 181 |
-
self.memory.append({
|
| 182 |
-
"action": "recommendations_generated",
|
| 183 |
-
"count": len(detailed_recommendations),
|
| 184 |
-
"strategy": self.strategy,
|
| 185 |
-
"user_id": self.user_id
|
| 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 |
-
'estimated_hours': self._estimate_learning_time(topic, knowledge_level)
|
| 230 |
-
})
|
| 231 |
-
|
| 232 |
-
# Add prerequisites to queue
|
| 233 |
-
if topic.prerequisites:
|
| 234 |
-
prereq_ids = [int(x.strip()) for x in topic.prerequisites.split(',') if x.strip()]
|
| 235 |
-
for pid in prereq_ids:
|
| 236 |
-
prereq_topic = Topic.query.get(pid)
|
| 237 |
-
if prereq_topic and prereq_topic.id not in visited:
|
| 238 |
-
queue.append(prereq_topic)
|
| 239 |
-
|
| 240 |
-
self.learning_paths_created += 1
|
| 241 |
-
self.log(f"Learning path created with {len(path)} steps")
|
| 242 |
-
|
| 243 |
-
return {
|
| 244 |
-
"path": path,
|
| 245 |
-
"total_topics": len(path),
|
| 246 |
-
"estimated_total_hours": sum(t['estimated_hours'] for t in path),
|
| 247 |
-
"agent": self.name
|
| 248 |
-
}
|
| 249 |
-
|
| 250 |
-
def _estimate_learning_time(self, topic, current_knowledge):
|
| 251 |
-
"""Estimate hours needed based on difficulty and current knowledge"""
|
| 252 |
-
base_hours = {
|
| 253 |
-
'beginner': 3,
|
| 254 |
-
'intermediate': 5,
|
| 255 |
-
'advanced': 8
|
| 256 |
-
}
|
| 257 |
-
|
| 258 |
-
hours = base_hours.get(topic.difficulty, 5)
|
| 259 |
-
remaining = 1 - current_knowledge
|
| 260 |
-
|
| 261 |
-
return round(hours * remaining, 1)
|
| 262 |
-
|
| 263 |
-
def get_statistics(self):
|
| 264 |
-
"""Return agent statistics"""
|
| 265 |
-
return {
|
| 266 |
-
"agent": self.name,
|
| 267 |
-
"recommendations_made": self.recommendations_made,
|
| 268 |
-
"learning_paths_created": self.learning_paths_created,
|
| 269 |
-
"current_strategy": self.strategy if hasattr(self, 'strategy') else None,
|
| 270 |
-
"state": self.state,
|
| 271 |
-
"memory_size": len(self.memory)
|
| 272 |
-
}
|
|
|
|
| 1 |
"""
|
| 2 |
+
RecommendationAgent: ranks what to study next from the learner model.
|
| 3 |
+
|
| 4 |
+
score = readiness gate (prerequisite mastery) -> don't recommend what can't be learned yet
|
| 5 |
+
+ learning potential (1 - effective mastery)
|
| 6 |
+
+ "zone of proximal development" bonus (predicted success 50-85%)
|
| 7 |
+
+ spaced-repetition urgency (recall below threshold)
|
| 8 |
+
+ momentum (already in progress) + goal match + curriculum order tie-break
|
| 9 |
"""
|
| 10 |
+
from models import Topic
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
from .metrics import tracked
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def score_topics(profile, topics, goals=(), exclude_id=None):
|
| 16 |
+
ranked = []
|
| 17 |
+
for t in topics:
|
| 18 |
+
if t.id == exclude_id:
|
| 19 |
+
continue
|
| 20 |
+
p = profile['topics'][t.id]
|
| 21 |
+
eff, ready = p['effective_mastery'], p['readiness']
|
| 22 |
+
pred = p['predicted_success'].get('intermediate', 0.5)
|
| 23 |
+
mastered = eff >= 0.85 and not p['due_for_review']
|
| 24 |
+
score = 0.0
|
| 25 |
+
score += 3.0 * ready - (3.0 if ready < 1.0 else 0.0)
|
| 26 |
+
score += 2.0 * (1 - eff)
|
| 27 |
+
score += 1.0 if 0.5 <= pred <= 0.85 else 0.0
|
| 28 |
+
if p['due_for_review']:
|
| 29 |
+
score += 2.5 * (1 - p['recall'])
|
| 30 |
+
if 0 < p['practice_count'] and eff < 0.85:
|
| 31 |
+
score += 1.0
|
| 32 |
+
if any(g.lower() in (t.name + ' ' + t.category).lower() for g in goals if g):
|
| 33 |
+
score += 2.0
|
| 34 |
+
score -= 0.04 * (t.position or 0)
|
| 35 |
+
if mastered:
|
| 36 |
+
score -= 4.0
|
| 37 |
+
|
| 38 |
+
if p['due_for_review']:
|
| 39 |
+
reason = f"Review due: estimated recall has dropped to {p['recall']:.0%}"
|
| 40 |
+
elif ready < 1.0:
|
| 41 |
+
reason = 'Build prerequisites first'
|
| 42 |
+
elif p['practice_count'] == 0:
|
| 43 |
+
reason = 'You are ready for this new topic'
|
| 44 |
+
elif eff < 0.5:
|
| 45 |
+
reason = 'Continue building on your progress'
|
| 46 |
+
elif eff < 0.85:
|
| 47 |
+
reason = 'Almost there, finish mastering this'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
else:
|
| 49 |
+
reason = 'Mastered: optional refresher'
|
| 50 |
+
ranked.append({
|
| 51 |
+
'topic_id': t.id, 'name': t.name, 'category': t.category, 'difficulty': t.difficulty,
|
| 52 |
+
'description': t.description, 'current_knowledge': round(eff, 3), 'readiness': ready,
|
| 53 |
+
'predicted_success': round(pred, 3), 'score': round(score, 3), 'reason': reason,
|
| 54 |
+
'priority': 'high' if score >= 4 else ('medium' if score >= 2 else 'low'),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
})
|
| 56 |
+
ranked.sort(key=lambda r: r['score'], reverse=True)
|
| 57 |
+
return ranked
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def learning_path(profile, topics, target_id, threshold=0.6):
|
| 61 |
+
"""Prerequisite-ordered path (DFS topological order) of unmastered topics leading to target."""
|
| 62 |
+
by_id = {t.id: t for t in topics}
|
| 63 |
+
path, seen = [], set()
|
| 64 |
+
|
| 65 |
+
def visit(tid):
|
| 66 |
+
if tid in seen or tid not in by_id:
|
| 67 |
+
return
|
| 68 |
+
seen.add(tid)
|
| 69 |
+
for p in by_id[tid].prerequisite_ids:
|
| 70 |
+
visit(p)
|
| 71 |
+
eff = profile['topics'][tid]['effective_mastery']
|
| 72 |
+
if eff < threshold or tid == target_id:
|
| 73 |
+
t = by_id[tid]
|
| 74 |
+
hours = {'beginner': 3, 'intermediate': 5, 'advanced': 8}.get(t.difficulty, 5) * (1 - eff)
|
| 75 |
+
path.append({'topic_id': tid, 'name': t.name, 'difficulty': t.difficulty,
|
| 76 |
+
'current_knowledge': round(eff, 3), 'estimated_hours': round(hours, 1)})
|
| 77 |
+
|
| 78 |
+
visit(target_id)
|
| 79 |
+
return {'target_topic_id': target_id, 'path': path, 'total_topics': len(path),
|
| 80 |
+
'estimated_total_hours': round(sum(p['estimated_hours'] for p in path), 1)}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def make_nodes(ctx):
|
| 84 |
+
@tracked('recommendation')
|
| 85 |
+
def recommend(state):
|
| 86 |
+
req = state.get('request', {})
|
| 87 |
+
topics = Topic.query.order_by(Topic.position, Topic.id).all()
|
| 88 |
+
ranked = score_topics(state['profile'], topics, goals=req.get('goals') or [],
|
| 89 |
+
exclude_id=req.get('current_topic_id'))
|
| 90 |
+
strategy = 'foundation_building' if state['profile']['topics_started'] < 3 else 'balanced_growth'
|
| 91 |
+
update = {'recommendations': {'recommendations': ranked[:5], 'next_best': ranked[0] if ranked else None,
|
| 92 |
+
'strategy': strategy, 'agent': 'RecommendationAgent'}}
|
| 93 |
+
if state.get('task') == 'full_learning_session' and not state.get('topic_id') and ranked:
|
| 94 |
+
update['topic_id'] = ranked[0]['topic_id']
|
| 95 |
+
return update
|
| 96 |
+
|
| 97 |
+
return {'recommend': recommend}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/agents/schemas.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pydantic schemas used for LLM structured outputs (LangChain `with_structured_output`)."""
|
| 2 |
+
from typing import List, Literal
|
| 3 |
+
|
| 4 |
+
from pydantic import BaseModel, Field
|
| 5 |
+
|
| 6 |
+
Difficulty = Literal['beginner', 'intermediate', 'advanced']
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class LessonSection(BaseModel):
|
| 10 |
+
title: str = Field(description='Section heading')
|
| 11 |
+
body_markdown: str = Field(description='Section content in Markdown. Use ```python fences for code.')
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class CodeExample(BaseModel):
|
| 15 |
+
title: str
|
| 16 |
+
code: str = Field(description='Runnable code, no Markdown fences')
|
| 17 |
+
language: str = Field(default='python')
|
| 18 |
+
explanation: str
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class PracticeChallenge(BaseModel):
|
| 22 |
+
prompt: str = Field(description='A single, self-contained exercise')
|
| 23 |
+
starter_code: str = Field(description='Starter code with TODOs; must run in plain Python with no imports beyond the standard library')
|
| 24 |
+
expected_output: str
|
| 25 |
+
hints: List[str] = Field(description='Three progressively more revealing hints')
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Lesson(BaseModel):
|
| 29 |
+
title: str
|
| 30 |
+
summary: str = Field(description='Two-sentence overview')
|
| 31 |
+
objectives: List[str] = Field(description='3-4 measurable learning objectives')
|
| 32 |
+
sections: List[LessonSection]
|
| 33 |
+
code_examples: List[CodeExample]
|
| 34 |
+
key_takeaways: List[str]
|
| 35 |
+
practice: PracticeChallenge
|
| 36 |
+
estimated_minutes: int = Field(ge=3, le=60)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class QuizOptions(BaseModel):
|
| 40 |
+
A: str
|
| 41 |
+
B: str
|
| 42 |
+
C: str
|
| 43 |
+
D: str
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class QuizQuestion(BaseModel):
|
| 47 |
+
question: str
|
| 48 |
+
options: QuizOptions
|
| 49 |
+
correct_answer: Literal['A', 'B', 'C', 'D']
|
| 50 |
+
explanation: str = Field(description='Why the answer is correct and why the main distractor is wrong (2-3 sentences)')
|
| 51 |
+
difficulty: Difficulty
|
| 52 |
+
concept: str = Field(description='The key concept this question assesses')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class Quiz(BaseModel):
|
| 56 |
+
questions: List[QuizQuestion]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class Hint(BaseModel):
|
| 60 |
+
hint: str = Field(description='The hint (2-4 sentences, no full solution unless the level is detailed)')
|
| 61 |
+
guiding_question: str = Field(default='', description='Optional question that nudges the learner')
|
backend/agents/state.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared LangGraph state and the dependency container passed to every agent node."""
|
| 2 |
+
import operator
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
from typing import Annotated, Any, Optional, TypedDict
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class LearningState(TypedDict, total=False):
|
| 8 |
+
# inputs
|
| 9 |
+
task: str # generate_lesson | generate_quiz | provide_hint | recommend_topic | full_learning_session
|
| 10 |
+
user_id: int
|
| 11 |
+
topic_id: Optional[int]
|
| 12 |
+
request: dict # task-specific inputs (question, code, attempt_count, fresh, goals ...)
|
| 13 |
+
# written by agents
|
| 14 |
+
profile: dict # KnowledgeAgent: learner model
|
| 15 |
+
strategy: dict # TeachingAgent (decide): chosen strategy + bandit context
|
| 16 |
+
lesson: dict # TeachingAgent (act)
|
| 17 |
+
quiz_plan: dict # AssessmentAgent (decide)
|
| 18 |
+
quiz: dict # AssessmentAgent (act)
|
| 19 |
+
generation_rounds: int # AssessmentAgent generate/validate loop counter
|
| 20 |
+
hint: dict # TutorAgent
|
| 21 |
+
recommendations: dict # RecommendationAgent
|
| 22 |
+
trace: Annotated[list, operator.add]
|
| 23 |
+
errors: Annotated[list, operator.add]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class AgentContext:
|
| 28 |
+
llm: Any # services.llm.LLMService
|
| 29 |
+
knowledge: Any # services.knowledge.KnowledgeService
|
| 30 |
+
bandit: Any # ml.bandit.StrategyBandit
|
| 31 |
+
teaching_rules: Any
|
| 32 |
+
tutor_rules: Any
|
| 33 |
+
question_templates: list = field(default_factory=list)
|
| 34 |
+
config: Any = None
|
backend/agents/teaching_agent.py
CHANGED
|
@@ -1,147 +1,114 @@
|
|
| 1 |
"""
|
| 2 |
-
|
|
|
|
|
|
|
| 3 |
"""
|
| 4 |
-
import json
|
| 5 |
-
from .base_agent import BaseAgent
|
| 6 |
-
from llm_service import LLMService
|
| 7 |
-
from agent_knowledge.rules.teaching_rules import TeachingRuleEngine
|
| 8 |
-
from agent_communication.message_bus import AgentMessageBus
|
| 9 |
-
from agent_communication.protocols import MessageProtocols
|
| 10 |
-
from datetime import datetime
|
| 11 |
import random
|
| 12 |
|
|
|
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
- Generating personalized lessons
|
| 18 |
-
- Adapting teaching style
|
| 19 |
-
- Selecting examples based on student performance
|
| 20 |
-
"""
|
| 21 |
-
|
| 22 |
-
def __init__(self):
|
| 23 |
-
super().__init__("TA-001", "TeachingAgent")
|
| 24 |
-
self.llm_service = LLMService()
|
| 25 |
-
self.rule_engine = TeachingRuleEngine()
|
| 26 |
-
self.message_bus = AgentMessageBus()
|
| 27 |
-
self.lessons_generated = 0
|
| 28 |
-
self.knowledge_level = 0.0
|
| 29 |
-
self.learning_style = "visual"
|
| 30 |
-
self.lesson_complexity = "beginner"
|
| 31 |
-
self.current_strategy = {}
|
| 32 |
-
|
| 33 |
-
def perceive(self, student_state):
|
| 34 |
-
self.update_state("perceiving")
|
| 35 |
-
self.log(f"Perceiving student state for user {student_state.user_id}")
|
| 36 |
-
|
| 37 |
-
# Update internal state based on student data
|
| 38 |
-
self.user_id = student_state.user_id
|
| 39 |
-
self.knowledge_level = student_state.knowledge_level
|
| 40 |
-
self.learning_style = student_state.learning_style or "visual"
|
| 41 |
-
|
| 42 |
-
# Determine lesson complexity based on knowledge level
|
| 43 |
-
if self.knowledge_level < 0.3:
|
| 44 |
-
self.lesson_complexity = "beginner"
|
| 45 |
-
elif self.knowledge_level < 0.7:
|
| 46 |
-
self.lesson_complexity = "intermediate"
|
| 47 |
-
else:
|
| 48 |
-
self.lesson_complexity = "advanced"
|
| 49 |
-
|
| 50 |
-
self.update_state("perceived")
|
| 51 |
-
return self.state
|
| 52 |
-
|
| 53 |
-
def decide(self):
|
| 54 |
-
self.update_state("deciding")
|
| 55 |
-
|
| 56 |
-
# Use rule engine to determine strategy
|
| 57 |
-
student_profile = {
|
| 58 |
-
"knowledge_level": self.knowledge_level,
|
| 59 |
-
"learning_style": self.learning_style,
|
| 60 |
-
# Mock recent performance for now, ideally comes from KnowledgeAgent
|
| 61 |
-
"recent_performance": 0.8
|
| 62 |
-
}
|
| 63 |
-
|
| 64 |
-
self.current_strategy = self.rule_engine.select_teaching_strategy(student_profile)
|
| 65 |
-
self.log(f"Selected teaching strategy: {self.current_strategy['name']}")
|
| 66 |
-
|
| 67 |
-
self.update_state("decided")
|
| 68 |
-
return self
|
| 69 |
-
|
| 70 |
-
def act(self, topic, prompt=None):
|
| 71 |
-
self.update_state("acting")
|
| 72 |
-
self.log(f"Generating lesson for topic: {topic.name} with strategy {self.current_strategy['name']}")
|
| 73 |
-
|
| 74 |
-
# 1. Request updated profile from KnowledgeAgent (Async/Simulated)
|
| 75 |
-
self.message_bus.send_message(
|
| 76 |
-
self.name,
|
| 77 |
-
"KnowledgeAgent",
|
| 78 |
-
MessageProtocols.KNOWLEDGE_REQUEST,
|
| 79 |
-
MessageProtocols.request_student_profile(self.user_id, topic.id)
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
TeachingAgent
|
| 3 |
+
decide: pick a pedagogical strategy = expert rules (prior) + Thompson-sampling bandit (learned)
|
| 4 |
+
act: produce a structured lesson (LLM structured output), reusing cached variants to save calls
|
| 5 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import random
|
| 7 |
|
| 8 |
+
from langchain_core.messages import HumanMessage, SystemMessage
|
| 9 |
|
| 10 |
+
from models import Topic, db
|
| 11 |
+
from services import content
|
| 12 |
+
from services.sandbox import ALLOWED_IMPORTS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
from .metrics import tracked
|
| 15 |
+
from .schemas import Lesson
|
| 16 |
+
|
| 17 |
+
SYSTEM = (
|
| 18 |
+
'You are an expert instructor who writes concise, accurate, engaging lessons for an adaptive '
|
| 19 |
+
'e-learning platform. Adapt depth and pacing to the learner profile you are given. '
|
| 20 |
+
'Use Markdown inside section bodies. Code must be correct and runnable.'
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def complexity_for(knowledge):
|
| 25 |
+
if knowledge < 0.3:
|
| 26 |
+
return 'beginner'
|
| 27 |
+
if knowledge < 0.7:
|
| 28 |
+
return 'intermediate'
|
| 29 |
+
return 'advanced'
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def make_nodes(ctx):
|
| 33 |
+
@tracked('teaching')
|
| 34 |
+
def select_strategy(state):
|
| 35 |
+
topic_id = state['topic_id']
|
| 36 |
+
tp = state['profile']['topics'].get(topic_id, {})
|
| 37 |
+
knowledge = tp.get('effective_mastery', 0.0)
|
| 38 |
+
style = state.get('request', {}).get('learning_style', 'mixed')
|
| 39 |
+
accuracy = tp.get('accuracy')
|
| 40 |
+
rule = ctx.teaching_rules.select_teaching_strategy({
|
| 41 |
+
'knowledge_level': knowledge,
|
| 42 |
+
'learning_style': style,
|
| 43 |
+
'recent_performance': accuracy if accuracy is not None else 1.0,
|
| 44 |
+
}) or ctx.teaching_rules.strategies[0]
|
| 45 |
+
name, bucket, samples = ctx.bandit.select(knowledge, rule_choice=rule['name'])
|
| 46 |
+
chosen = ctx.teaching_rules._find_strategy(name) or rule
|
| 47 |
+
return {'strategy': {
|
| 48 |
+
'name': name,
|
| 49 |
+
'description': chosen.get('description', ''),
|
| 50 |
+
'lesson_structure': chosen.get('lesson_structure', {}),
|
| 51 |
+
'rule_choice': rule['name'],
|
| 52 |
+
'bucket': bucket,
|
| 53 |
+
'bandit_samples': {k: round(v, 3) for k, v in samples.items()},
|
| 54 |
+
'complexity': complexity_for(knowledge),
|
| 55 |
+
'knowledge_level': knowledge,
|
| 56 |
+
}}
|
| 57 |
+
|
| 58 |
+
def _prompt(topic, strategy, profile, request):
|
| 59 |
+
tp = profile['topics'].get(topic.id, {})
|
| 60 |
+
weak_prereqs = [profile['topics'][p]['name'] for p in topic.prerequisite_ids
|
| 61 |
+
if p in profile['topics'] and profile['topics'][p]['effective_mastery'] < 0.5]
|
| 62 |
+
structure = ctx.teaching_rules.generate_lesson_structure(topic, {'name': strategy['name'],
|
| 63 |
+
'lesson_structure': strategy['lesson_structure']})
|
| 64 |
+
plan = '\n'.join(f"- {s['title']}: {s['instruction_for_llm'].replace('_', ' ')}" for s in structure['sections'])
|
| 65 |
+
goals = ', '.join(request.get('goals') or []) or 'not specified'
|
| 66 |
+
return [
|
| 67 |
+
SystemMessage(SYSTEM),
|
| 68 |
+
HumanMessage(
|
| 69 |
+
f"Write a lesson on **{topic.name}** ({topic.category}).\n"
|
| 70 |
+
f"Topic description: {topic.description}\n"
|
| 71 |
+
f"Key concepts to cover: {', '.join(topic.key_concepts or [])}\n\n"
|
| 72 |
+
f"Learner profile:\n"
|
| 73 |
+
f"- current mastery: {tp.get('effective_mastery', 0):.0%} (target level: {strategy['complexity']})\n"
|
| 74 |
+
f"- predicted success on intermediate questions: {tp.get('predicted_success', {}).get('intermediate', 0.5):.0%}\n"
|
| 75 |
+
f"- learning style: {request.get('learning_style', 'mixed')}; goals: {goals}\n"
|
| 76 |
+
f"- prerequisites still weak: {', '.join(weak_prereqs) or 'none'} (briefly recap these first if any)\n\n"
|
| 77 |
+
f"Pedagogical strategy: {strategy['name']} - {strategy['description']}\n"
|
| 78 |
+
f"Follow this section plan:\n{plan}\n\n"
|
| 79 |
+
f"Requirements: 3-6 sections; 1-3 code examples; 3-5 key takeaways; one practice challenge whose "
|
| 80 |
+
f"starter code runs in plain Python and only imports from: {', '.join(sorted(ALLOWED_IMPORTS))}. "
|
| 81 |
+
f"If the topic is not Python-specific, make the challenge a Python simulation of the idea. "
|
| 82 |
+
f"Target length ~{structure['metadata']['estimated_time'].split()[0]} minutes of reading."
|
| 83 |
+
),
|
| 84 |
+
]
|
| 85 |
+
|
| 86 |
+
@tracked('teaching')
|
| 87 |
+
def teach(state):
|
| 88 |
+
topic = db.session.get(Topic, state['topic_id'])
|
| 89 |
+
strategy = state['strategy']
|
| 90 |
+
request = state.get('request', {})
|
| 91 |
+
key = content.lesson_cache_key(topic.id, strategy['complexity'], strategy['name'])
|
| 92 |
+
cached = content.cached_lessons(key)
|
| 93 |
+
limit = ctx.config.LESSON_CACHE_VARIANTS
|
| 94 |
+
|
| 95 |
+
if cached and (len(cached) >= limit or not ctx.llm.available) and not request.get('fresh'):
|
| 96 |
+
row = random.choice(cached)
|
| 97 |
+
row.usage_count = (row.usage_count or 0) + 1
|
| 98 |
+
return {'lesson': {'lesson': row.meta_data, 'markdown': row.content, 'source': 'cache'}}
|
| 99 |
+
|
| 100 |
+
result = ctx.llm.structured(Lesson, _prompt(topic, strategy, state['profile'], request))
|
| 101 |
+
if result is not None:
|
| 102 |
+
lesson = result.model_dump()
|
| 103 |
+
md = content.lesson_to_markdown(lesson)
|
| 104 |
+
content.store_lesson(key, topic.id, strategy['complexity'], lesson, md)
|
| 105 |
+
return {'lesson': {'lesson': lesson, 'markdown': md, 'source': 'llm'}}
|
| 106 |
+
|
| 107 |
+
if cached:
|
| 108 |
+
row = random.choice(cached)
|
| 109 |
+
return {'lesson': {'lesson': row.meta_data, 'markdown': row.content, 'source': 'cache'}}
|
| 110 |
+
lesson = content.offline_lesson(topic, strategy['complexity'], strategy['name'])
|
| 111 |
+
return {'lesson': {'lesson': lesson, 'markdown': content.lesson_to_markdown(lesson), 'source': 'offline'},
|
| 112 |
+
'errors': ['llm_unavailable'] if ctx.llm.available else []}
|
| 113 |
+
|
| 114 |
+
return {'select_strategy': select_strategy, 'teach': teach}
|
backend/agents/tutor_agent.py
CHANGED
|
@@ -1,126 +1,60 @@
|
|
| 1 |
"""
|
| 2 |
-
|
|
|
|
|
|
|
| 3 |
"""
|
| 4 |
-
import
|
| 5 |
-
from .base_agent import BaseAgent
|
| 6 |
-
from llm_service import LLMService
|
| 7 |
-
from agent_knowledge.rules.tutor_rules import TutorRuleEngine
|
| 8 |
-
from datetime import datetime
|
| 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 |
-
Autonomous decisions:
|
| 49 |
-
- How much help to provide?
|
| 50 |
-
- What teaching approach?
|
| 51 |
-
- Level of motivation needed?
|
| 52 |
-
"""
|
| 53 |
-
self.update_state("deciding")
|
| 54 |
-
|
| 55 |
-
# Determine hint strategy
|
| 56 |
-
self.strategy = self.rule_engine.select_hint_strategy(
|
| 57 |
-
self.attempts, self.frustration_level
|
| 58 |
-
)
|
| 59 |
-
|
| 60 |
-
self.log(f"Decided strategy: {self.strategy['name'] if self.strategy else 'default'}")
|
| 61 |
-
|
| 62 |
-
return self
|
| 63 |
-
|
| 64 |
-
def act(self, prompt=None):
|
| 65 |
-
"""
|
| 66 |
-
Execute: Provide intelligent hint or answer based on the decided strategy
|
| 67 |
-
"""
|
| 68 |
-
self.update_state("acting")
|
| 69 |
-
self.log(f"Providing help with strategy: {self.strategy['name'] if self.strategy else 'default'}")
|
| 70 |
-
|
| 71 |
-
try:
|
| 72 |
-
|
| 73 |
-
self.update_state("completed")
|
| 74 |
-
|
| 75 |
-
return {
|
| 76 |
-
"hint": response,
|
| 77 |
-
"hint_level": self.hint_level,
|
| 78 |
-
"motivation": self.motivation_level,
|
| 79 |
-
"agent": self.name,
|
| 80 |
-
"timestamp": datetime.utcnow().isoformat()
|
| 81 |
-
}
|
| 82 |
-
|
| 83 |
-
except Exception as e:
|
| 84 |
-
self.log(f"Error generating hint: {str(e)}", "error")
|
| 85 |
-
self.update_state("error")
|
| 86 |
-
return {
|
| 87 |
-
"hint": "Think about what you've learned. Break the problem into smaller steps!",
|
| 88 |
-
"agent": self.name
|
| 89 |
-
}
|
| 90 |
-
|
| 91 |
-
def provide_motivation(self, user_performance):
|
| 92 |
-
"""
|
| 93 |
-
Autonomous motivational message based on performance
|
| 94 |
-
"""
|
| 95 |
-
self.update_state("motivating")
|
| 96 |
-
|
| 97 |
-
score = user_performance.get('score', 0)
|
| 98 |
-
improvement = user_performance.get('improvement', 0)
|
| 99 |
-
|
| 100 |
-
if score >= 0.8:
|
| 101 |
-
message = "🌟 Excellent work! You're mastering this topic. Ready for a challenge?"
|
| 102 |
-
elif score >= 0.6:
|
| 103 |
-
message = "👍 Good progress! Keep practicing and you'll get there."
|
| 104 |
-
elif improvement > 0.1:
|
| 105 |
-
message = "📈 Great improvement! Your hard work is paying off."
|
| 106 |
else:
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
"hints_provided": self.hints_provided,
|
| 122 |
-
"questions_answered": self.questions_answered,
|
| 123 |
-
"current_motivation_level": self.motivation_level,
|
| 124 |
-
"state": self.state,
|
| 125 |
-
"memory_size": len(self.memory)
|
| 126 |
-
}
|
|
|
|
| 1 |
"""
|
| 2 |
+
TutorAgent
|
| 3 |
+
provide_hint: hint ladder (socratic -> conceptual -> direct) chosen by expert rules from the
|
| 4 |
+
attempt count, phrased by the LLM with the learner's code, output and mastery as context.
|
| 5 |
"""
|
| 6 |
+
from langchain_core.messages import HumanMessage, SystemMessage
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
from models import Topic, db
|
| 9 |
+
|
| 10 |
+
from .metrics import tracked
|
| 11 |
+
from .schemas import Hint
|
| 12 |
+
|
| 13 |
+
LEVEL_INSTRUCTIONS = {
|
| 14 |
+
'subtle': 'Do NOT give the solution. Ask one guiding question and point at where to look.',
|
| 15 |
+
'moderate': 'Explain the underlying concept and outline the approach, but do not write the full solution.',
|
| 16 |
+
'detailed': 'Point out the specific mistake and show the minimal fix with a short code fragment.',
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def make_nodes(ctx):
|
| 21 |
+
@tracked('tutor')
|
| 22 |
+
def provide_hint(state):
|
| 23 |
+
req = state.get('request', {})
|
| 24 |
+
attempts = max(1, int(req.get('attempt_count') or 1))
|
| 25 |
+
strategy = ctx.tutor_rules.select_hint_strategy(attempts, req.get('frustration_level', 'normal')) or {}
|
| 26 |
+
level = strategy.get('hint_level', 'moderate')
|
| 27 |
+
topic = db.session.get(Topic, state['topic_id']) if state.get('topic_id') else None
|
| 28 |
+
tp = state['profile']['topics'].get(state.get('topic_id'), {}) if topic else {}
|
| 29 |
+
|
| 30 |
+
messages = [
|
| 31 |
+
SystemMessage('You are a patient, encouraging programming tutor. Keep hints to 2-4 sentences.'),
|
| 32 |
+
HumanMessage(
|
| 33 |
+
f"Topic: {topic.name if topic else 'general programming'} "
|
| 34 |
+
f"(learner mastery {tp.get('effective_mastery', 0):.0%}).\n"
|
| 35 |
+
f"Exercise / question: {req.get('question') or 'free practice'}\n"
|
| 36 |
+
f"Learner's code:\n```python\n{(req.get('challenge') or '')[:4000]}\n```\n"
|
| 37 |
+
f"Last output or error: {(req.get('last_output') or 'n/a')[:1500]}\n"
|
| 38 |
+
f"Attempt number: {attempts}. Hint strategy: {strategy.get('name', 'conceptual_reminder')}.\n"
|
| 39 |
+
f"{LEVEL_INSTRUCTIONS[level]}"
|
| 40 |
+
),
|
| 41 |
+
]
|
| 42 |
+
result = ctx.llm.structured(Hint, messages)
|
| 43 |
+
if result is not None:
|
| 44 |
+
text = result.hint + (f"\n\n{result.guiding_question}" if result.guiding_question else '')
|
| 45 |
+
source = 'llm'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
else:
|
| 47 |
+
lesson_hints = req.get('practice_hints') or []
|
| 48 |
+
if lesson_hints:
|
| 49 |
+
text = lesson_hints[min(attempts, len(lesson_hints)) - 1]
|
| 50 |
+
else:
|
| 51 |
+
concept = (topic.key_concepts or [topic.name])[0] if topic else 'the core idea'
|
| 52 |
+
text = {'subtle': f'What should the program print first? Trace your code line by line and check how it uses {concept}.',
|
| 53 |
+
'moderate': f'Revisit {concept}: write down the steps in plain words, then translate each step into one line of code.',
|
| 54 |
+
'detailed': 'Run a tiny version of the problem, print every intermediate value, and compare it with the expected output to locate the first line that differs.'}[level]
|
| 55 |
+
source = 'rules'
|
| 56 |
+
return {'hint': {'hint': text, 'hint_level': level, 'strategy': strategy.get('name'),
|
| 57 |
+
'motivation': ctx.tutor_rules.get_motivational_quote(),
|
| 58 |
+
'agent': 'TutorAgent', 'source': source}}
|
| 59 |
+
|
| 60 |
+
return {'provide_hint': provide_hint}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/agents/tutor_chat.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Conversational AI tutor with persistent memory.
|
| 3 |
+
|
| 4 |
+
A LangGraph MessagesState graph checkpointed to SQLite: one thread per (user, topic), so the
|
| 5 |
+
conversation survives restarts and is personalised with the learner model on every turn.
|
| 6 |
+
"""
|
| 7 |
+
import logging
|
| 8 |
+
import os
|
| 9 |
+
import sqlite3
|
| 10 |
+
|
| 11 |
+
from langchain_core.messages import AIMessage, HumanMessage, RemoveMessage, SystemMessage
|
| 12 |
+
from langgraph.graph import START, MessagesState, StateGraph
|
| 13 |
+
|
| 14 |
+
from models import Topic, db
|
| 15 |
+
|
| 16 |
+
from .metrics import tracked
|
| 17 |
+
|
| 18 |
+
log = logging.getLogger(__name__)
|
| 19 |
+
HISTORY_WINDOW = 16
|
| 20 |
+
MAX_STORED_MESSAGES = 60
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TutorChat:
|
| 24 |
+
def __init__(self, ctx, db_path):
|
| 25 |
+
self.ctx = ctx
|
| 26 |
+
os.makedirs(os.path.dirname(db_path) or '.', exist_ok=True)
|
| 27 |
+
try:
|
| 28 |
+
from langgraph.checkpoint.sqlite import SqliteSaver
|
| 29 |
+
self.checkpointer = SqliteSaver(sqlite3.connect(db_path, check_same_thread=False))
|
| 30 |
+
except ImportError: # pragma: no cover
|
| 31 |
+
from langgraph.checkpoint.memory import InMemorySaver
|
| 32 |
+
log.warning('langgraph-checkpoint-sqlite not installed; tutor memory is in-memory only')
|
| 33 |
+
self.checkpointer = InMemorySaver()
|
| 34 |
+
self.graph = self._build()
|
| 35 |
+
|
| 36 |
+
def _system_prompt(self, user_id, topic_id):
|
| 37 |
+
profile = self.ctx.knowledge.profile(user_id)
|
| 38 |
+
topic = db.session.get(Topic, topic_id) if topic_id else None
|
| 39 |
+
weak = ', '.join(w['name'] for w in profile['weak_topics']) or 'none yet'
|
| 40 |
+
due = ', '.join(r['name'] for r in profile['review_queue'][:3]) or 'none'
|
| 41 |
+
focus = ''
|
| 42 |
+
if topic:
|
| 43 |
+
tp = profile['topics'].get(topic.id, {})
|
| 44 |
+
focus = (f"The learner is currently studying '{topic.name}' ({topic.description}); "
|
| 45 |
+
f"their mastery is {tp.get('effective_mastery', 0):.0%}. Key concepts: "
|
| 46 |
+
f"{', '.join(topic.key_concepts or [])}.\n")
|
| 47 |
+
return (
|
| 48 |
+
'You are an expert, friendly AI tutor on an adaptive learning platform. Teach Socratically: '
|
| 49 |
+
'check understanding, give small worked examples, and prefer guiding questions over full '
|
| 50 |
+
'solutions for exercises. Use Markdown and ```python code fences. Keep answers focused '
|
| 51 |
+
'(under ~250 words unless asked for more).\n'
|
| 52 |
+
f"{focus}Learner's weak topics: {weak}. Topics due for review: {due}. "
|
| 53 |
+
f"Overall average mastery: {profile['average_knowledge']:.0%}."
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
def _build(self):
|
| 57 |
+
ctx = self.ctx
|
| 58 |
+
|
| 59 |
+
@tracked('tutor', trace=False)
|
| 60 |
+
def respond(state, config):
|
| 61 |
+
cfg = config['configurable']
|
| 62 |
+
history = state['messages'][-HISTORY_WINDOW:]
|
| 63 |
+
reply = ctx.llm.chat([SystemMessage(self._system_prompt(cfg['user_id'], cfg.get('topic_id')))] + history)
|
| 64 |
+
if reply is None:
|
| 65 |
+
topic = db.session.get(Topic, cfg['topic_id']) if cfg.get('topic_id') else None
|
| 66 |
+
concepts = ', '.join((topic.key_concepts or [])[:3]) if topic else ''
|
| 67 |
+
reply = ('I am running in offline mode right now (no LLM configured), so I cannot answer '
|
| 68 |
+
'free-form questions. ' + (f'For **{topic.name}**, focus on: {concepts}. ' if topic else '')
|
| 69 |
+
+ 'Try the lesson, the practice playground and the adaptive quiz meanwhile!')
|
| 70 |
+
update = [AIMessage(reply)]
|
| 71 |
+
overflow = len(state['messages']) + 1 - MAX_STORED_MESSAGES
|
| 72 |
+
if overflow > 0: # keep the checkpoint small
|
| 73 |
+
update += [RemoveMessage(id=m.id) for m in state['messages'][:overflow]]
|
| 74 |
+
return {'messages': update}
|
| 75 |
+
|
| 76 |
+
g = StateGraph(MessagesState)
|
| 77 |
+
g.add_node('respond', respond)
|
| 78 |
+
g.add_edge(START, 'respond')
|
| 79 |
+
return g.compile(checkpointer=self.checkpointer)
|
| 80 |
+
|
| 81 |
+
@staticmethod
|
| 82 |
+
def _config(user_id, topic_id):
|
| 83 |
+
return {'configurable': {'thread_id': f'user-{user_id}:topic-{topic_id or "general"}',
|
| 84 |
+
'user_id': user_id, 'topic_id': topic_id}}
|
| 85 |
+
|
| 86 |
+
def send(self, user_id, topic_id, message):
|
| 87 |
+
out = self.graph.invoke({'messages': [HumanMessage(message)]}, self._config(user_id, topic_id))
|
| 88 |
+
return out['messages'][-1].content
|
| 89 |
+
|
| 90 |
+
def history(self, user_id, topic_id):
|
| 91 |
+
snap = self.graph.get_state(self._config(user_id, topic_id))
|
| 92 |
+
msgs = snap.values.get('messages', []) if snap and snap.values else []
|
| 93 |
+
return [{'role': 'user' if isinstance(m, HumanMessage) else 'assistant', 'content': m.content}
|
| 94 |
+
for m in msgs if isinstance(m, (HumanMessage, AIMessage))]
|
| 95 |
+
|
| 96 |
+
def clear(self, user_id, topic_id):
|
| 97 |
+
thread = self._config(user_id, topic_id)['configurable']['thread_id']
|
| 98 |
+
try:
|
| 99 |
+
self.checkpointer.delete_thread(thread)
|
| 100 |
+
except Exception as exc: # pragma: no cover
|
| 101 |
+
log.warning('Could not clear tutor thread %s: %s', thread, exc)
|
backend/app.py
CHANGED
|
@@ -1,625 +1,113 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
from knowledge_tracker import KnowledgeTracker
|
| 5 |
-
from llm_service import LLMService
|
| 6 |
-
from config import Config
|
| 7 |
-
from agents.coordinator_agent import CoordinatorAgent
|
| 8 |
import os
|
| 9 |
-
from datetime import datetime
|
| 10 |
import re
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
# UPDATED CORS CONFIGURATION
|
| 16 |
-
CORS(app,
|
| 17 |
-
supports_credentials=True,
|
| 18 |
-
origins=['http://localhost:3000', 'https://adaptive-e-learning-system.vercel.app'], # placeholder - will improve with regex or wildcard
|
| 19 |
-
allow_headers=['Content-Type', 'Authorization'],
|
| 20 |
-
methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'])
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
|
| 30 |
-
# Initialize database and sample data
|
| 31 |
-
def init_db():
|
| 32 |
with app.app_context():
|
| 33 |
db.create_all()
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
if
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
description="Learn about arrays, lists, stacks, and queues", prerequisites="1"),
|
| 42 |
-
Topic(name="Object-Oriented Programming", category="Programming", difficulty="intermediate",
|
| 43 |
-
description="Classes, objects, inheritance, and polymorphism", prerequisites="1"),
|
| 44 |
-
Topic(name="Algorithms", category="Programming", difficulty="advanced",
|
| 45 |
-
description="Sorting, searching, and algorithm complexity", prerequisites="2"),
|
| 46 |
-
Topic(name="Machine Learning Basics", category="AI/ML", difficulty="intermediate",
|
| 47 |
-
description="Introduction to ML concepts and algorithms", prerequisites="1,2"),
|
| 48 |
-
Topic(name="Web Development", category="Web", difficulty="beginner",
|
| 49 |
-
description="HTML, CSS, and JavaScript fundamentals"),
|
| 50 |
-
Topic(name="Database Design", category="Database", difficulty="intermediate",
|
| 51 |
-
description="SQL and database normalization", prerequisites="1"),
|
| 52 |
-
Topic(name="Neural Networks", category="AI/ML", difficulty="advanced",
|
| 53 |
-
description="Deep learning and neural network architectures", prerequisites="5"),
|
| 54 |
-
]
|
| 55 |
-
db.session.bulk_save_objects(sample_topics)
|
| 56 |
-
db.session.commit()
|
| 57 |
-
|
| 58 |
-
# UPDATED: Root route now returns API info instead of template
|
| 59 |
-
@app.route('/')
|
| 60 |
-
def index():
|
| 61 |
-
return jsonify({
|
| 62 |
-
'message': 'Adaptive E-Learning API',
|
| 63 |
-
'version': '1.0.0',
|
| 64 |
-
'status': 'running',
|
| 65 |
-
'ai_agents': '5 autonomous agents active',
|
| 66 |
-
'endpoints': {
|
| 67 |
-
'auth': '/api/login, /api/register, /api/logout, /api/current-user',
|
| 68 |
-
'topics': '/api/topics, /api/topics/<id>',
|
| 69 |
-
'learning': '/api/generate-lesson',
|
| 70 |
-
'quiz': '/api/generate-quiz, /api/submit-answer',
|
| 71 |
-
'progress': '/api/progress-summary, /api/knowledge-state/<id>',
|
| 72 |
-
'utility': '/api/check-code, /api/ask-challenge-hint, /api/agent-status'
|
| 73 |
-
}
|
| 74 |
-
})
|
| 75 |
-
|
| 76 |
-
# REMOVED: All HTML template routes (dashboard, learn, quiz, progress)
|
| 77 |
-
# React frontend handles all routing
|
| 78 |
-
|
| 79 |
-
# API Routes
|
| 80 |
-
@app.route('/api/register', methods=['POST'])
|
| 81 |
-
def register():
|
| 82 |
-
data = request.json
|
| 83 |
-
|
| 84 |
-
existing_user = User.query.filter_by(username=data['username']).first()
|
| 85 |
-
if existing_user:
|
| 86 |
-
return jsonify({'error': 'Username already exists'}), 400
|
| 87 |
-
|
| 88 |
-
user = User(
|
| 89 |
-
username=data['username'],
|
| 90 |
-
email=data['email']
|
| 91 |
-
)
|
| 92 |
-
db.session.add(user)
|
| 93 |
-
db.session.commit()
|
| 94 |
-
|
| 95 |
-
session['user_id'] = user.id
|
| 96 |
-
session['username'] = user.username
|
| 97 |
-
|
| 98 |
-
return jsonify({
|
| 99 |
-
'message': 'User registered successfully',
|
| 100 |
-
'user_id': user.id,
|
| 101 |
-
'username': user.username
|
| 102 |
-
})
|
| 103 |
-
|
| 104 |
-
@app.route('/api/login', methods=['POST'])
|
| 105 |
-
def login():
|
| 106 |
-
data = request.json
|
| 107 |
-
user = User.query.filter_by(username=data['username']).first()
|
| 108 |
-
|
| 109 |
-
if user:
|
| 110 |
-
session['user_id'] = user.id
|
| 111 |
-
session['username'] = user.username
|
| 112 |
-
return jsonify({
|
| 113 |
-
'message': 'Login successful',
|
| 114 |
-
'user_id': user.id,
|
| 115 |
-
'username': user.username
|
| 116 |
-
})
|
| 117 |
-
else:
|
| 118 |
-
return jsonify({'error': 'User not found'}), 404
|
| 119 |
-
|
| 120 |
-
@app.route('/api/current-user', methods=['GET'])
|
| 121 |
-
def current_user():
|
| 122 |
-
if 'user_id' in session:
|
| 123 |
-
return jsonify({
|
| 124 |
-
'user_id': session['user_id'],
|
| 125 |
-
'username': session['username']
|
| 126 |
-
})
|
| 127 |
-
return jsonify({'error': 'Not logged in'}), 401
|
| 128 |
-
|
| 129 |
-
@app.route('/api/logout', methods=['POST'])
|
| 130 |
-
def logout():
|
| 131 |
-
session.clear()
|
| 132 |
-
return jsonify({'message': 'Logged out successfully'})
|
| 133 |
-
|
| 134 |
-
@app.route('/api/topics', methods=['GET'])
|
| 135 |
-
def get_topics():
|
| 136 |
-
topics = Topic.query.all()
|
| 137 |
-
return jsonify([{
|
| 138 |
-
'id': t.id,
|
| 139 |
-
'name': t.name,
|
| 140 |
-
'category': t.category,
|
| 141 |
-
'difficulty': t.difficulty,
|
| 142 |
-
'description': t.description
|
| 143 |
-
} for t in topics])
|
| 144 |
|
| 145 |
-
|
| 146 |
-
def get_topic(topic_id):
|
| 147 |
-
topic = Topic.query.get_or_404(topic_id)
|
| 148 |
-
return jsonify({
|
| 149 |
-
'id': topic.id,
|
| 150 |
-
'name': topic.name,
|
| 151 |
-
'category': topic.category,
|
| 152 |
-
'difficulty': topic.difficulty,
|
| 153 |
-
'description': topic.description
|
| 154 |
-
})
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
# Remove multiple consecutive blank lines
|
| 161 |
-
content = re.sub(r'\n\s*\n\s*\n+', '\n\n', content)
|
| 162 |
-
|
| 163 |
-
# Remove extra whitespace from each line
|
| 164 |
-
content = '\n'.join(line.strip() for line in content.split('\n'))
|
| 165 |
-
|
| 166 |
-
# Convert markdown code blocks to HTML
|
| 167 |
-
content = re.sub(r'```python\n(.*?)\n```', r'<pre><code class="python">\1</code></pre>', content, flags=re.DOTALL)
|
| 168 |
-
content = re.sub(r'```\n(.*?)\n```', r'<pre><code>\1</code></pre>', content, flags=re.DOTALL)
|
| 169 |
-
|
| 170 |
-
# Convert markdown headers to HTML
|
| 171 |
-
content = re.sub(r'^### (.*?)$', r'<h3>\1</h3>', content, flags=re.MULTILINE)
|
| 172 |
-
content = re.sub(r'^## (.*?)$', r'<h2>\1</h2>', content, flags=re.MULTILINE)
|
| 173 |
-
content = re.sub(r'^# (.*?)$', r'<h1>\1</h1>', content, flags=re.MULTILINE)
|
| 174 |
-
|
| 175 |
-
# Convert markdown bold to HTML
|
| 176 |
-
content = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', content)
|
| 177 |
-
|
| 178 |
-
# Convert inline code to HTML (before lists to preserve code in lists)
|
| 179 |
-
content = re.sub(r'`([^`]+)`', r'<code>\1</code>', content)
|
| 180 |
-
|
| 181 |
-
# Convert markdown lists to HTML - IMPROVED
|
| 182 |
-
lines = content.split('\n')
|
| 183 |
-
in_list = False
|
| 184 |
-
result_lines = []
|
| 185 |
-
|
| 186 |
-
for i, line in enumerate(lines):
|
| 187 |
-
line = line.strip()
|
| 188 |
-
|
| 189 |
-
# Skip empty lines
|
| 190 |
-
if not line:
|
| 191 |
-
if in_list:
|
| 192 |
-
result_lines.append('</ul>')
|
| 193 |
-
in_list = False
|
| 194 |
-
continue
|
| 195 |
-
|
| 196 |
-
# Handle list items
|
| 197 |
-
if line.startswith('- '):
|
| 198 |
-
if not in_list:
|
| 199 |
-
result_lines.append('<ul>')
|
| 200 |
-
in_list = True
|
| 201 |
-
result_lines.append(f'<li>{line[2:]}</li>')
|
| 202 |
-
else:
|
| 203 |
-
if in_list:
|
| 204 |
-
result_lines.append('</ul>')
|
| 205 |
-
in_list = False
|
| 206 |
-
result_lines.append(line)
|
| 207 |
-
|
| 208 |
-
if in_list:
|
| 209 |
-
result_lines.append('</ul>')
|
| 210 |
-
|
| 211 |
-
content = '\n'.join(result_lines)
|
| 212 |
-
|
| 213 |
-
# Convert paragraphs - NO NEWLINES
|
| 214 |
-
lines = content.split('\n')
|
| 215 |
-
formatted_lines = []
|
| 216 |
-
in_pre = False
|
| 217 |
-
|
| 218 |
-
for line in lines:
|
| 219 |
-
line = line.strip()
|
| 220 |
-
|
| 221 |
-
# Skip completely empty lines
|
| 222 |
-
if not line:
|
| 223 |
-
continue
|
| 224 |
-
|
| 225 |
-
# Handle pre blocks
|
| 226 |
-
if '<pre>' in line:
|
| 227 |
-
in_pre = True
|
| 228 |
-
formatted_lines.append(line)
|
| 229 |
-
continue
|
| 230 |
-
elif '</pre>' in line:
|
| 231 |
-
in_pre = False
|
| 232 |
-
formatted_lines.append(line)
|
| 233 |
-
continue
|
| 234 |
-
elif in_pre:
|
| 235 |
-
formatted_lines.append(line)
|
| 236 |
-
continue
|
| 237 |
-
|
| 238 |
-
# Keep HTML tags as-is
|
| 239 |
-
if line.startswith('<h') or line.startswith('<ul>') or line.startswith('</ul>') or line.startswith('<li>'):
|
| 240 |
-
formatted_lines.append(line)
|
| 241 |
-
else:
|
| 242 |
-
# Wrap non-HTML content in paragraph
|
| 243 |
-
formatted_lines.append(f'<p>{line}</p>')
|
| 244 |
-
|
| 245 |
-
# Join WITHOUT newlines to eliminate all spacing
|
| 246 |
-
return ''.join(formatted_lines)
|
| 247 |
-
|
| 248 |
-
def format_study_tips(content):
|
| 249 |
-
"""Format study tips markdown to HTML"""
|
| 250 |
-
import re
|
| 251 |
-
|
| 252 |
-
# Convert **bold** to HTML
|
| 253 |
-
content = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', content)
|
| 254 |
-
|
| 255 |
-
# Convert bullet points to HTML list
|
| 256 |
-
lines = content.split('\n')
|
| 257 |
-
formatted_lines = []
|
| 258 |
-
in_list = False
|
| 259 |
-
|
| 260 |
-
for line in lines:
|
| 261 |
-
line = line.strip()
|
| 262 |
-
if not line:
|
| 263 |
-
continue
|
| 264 |
-
|
| 265 |
-
# Check if it's a header
|
| 266 |
-
if line.endswith(':') and not line.startswith('-') and not line.startswith('•'):
|
| 267 |
-
if in_list:
|
| 268 |
-
formatted_lines.append('</ul>')
|
| 269 |
-
in_list = False
|
| 270 |
-
formatted_lines.append(f'<h3 style="color: var(--primary-color); margin-top: 1.5rem; margin-bottom: 0.75rem;">{line}</h3>')
|
| 271 |
-
# Check if it's a bullet point
|
| 272 |
-
elif line.startswith('- ') or line.startswith('• '):
|
| 273 |
-
if not in_list:
|
| 274 |
-
formatted_lines.append('<ul style="list-style-type: disc; margin-left: 1.5rem; line-height: 1.8;">')
|
| 275 |
-
in_list = True
|
| 276 |
-
# Remove the bullet character
|
| 277 |
-
text = line[2:] if line.startswith('- ') else line[2:]
|
| 278 |
-
formatted_lines.append(f'<li style="margin-bottom: 1rem; color: #4b5563;">{text}</li>')
|
| 279 |
-
else:
|
| 280 |
-
if in_list:
|
| 281 |
-
formatted_lines.append('</ul>')
|
| 282 |
-
in_list = False
|
| 283 |
-
formatted_lines.append(f'<p style="margin-bottom: 0.75rem; color: #4b5563;">{line}</p>')
|
| 284 |
-
|
| 285 |
-
if in_list:
|
| 286 |
-
formatted_lines.append('</ul>')
|
| 287 |
-
|
| 288 |
-
return ''.join(formatted_lines)
|
| 289 |
-
|
| 290 |
-
@app.route('/api/generate-lesson', methods=['POST'])
|
| 291 |
-
def generate_lesson():
|
| 292 |
-
if 'user_id' not in session:
|
| 293 |
-
return jsonify({'error': 'Not logged in'}), 401
|
| 294 |
-
|
| 295 |
-
data = request.json
|
| 296 |
-
topic_id = data['topic_id']
|
| 297 |
-
|
| 298 |
-
# Use Coordinator Agent
|
| 299 |
-
result = coordinator.perceive({
|
| 300 |
-
'task': 'generate_lesson',
|
| 301 |
-
'user_id': session['user_id'],
|
| 302 |
-
'context': {
|
| 303 |
-
'topic_id': topic_id,
|
| 304 |
-
'learning_history': []
|
| 305 |
-
}
|
| 306 |
-
}).decide().act()
|
| 307 |
-
|
| 308 |
-
if not result['success']:
|
| 309 |
-
return jsonify({'error': result.get('error')}), 500
|
| 310 |
-
|
| 311 |
-
# Extract teaching agent result
|
| 312 |
-
teaching_result = result['results'].get('TeachingAgent', {})
|
| 313 |
-
|
| 314 |
-
# Format content
|
| 315 |
-
content = format_lesson_content(teaching_result.get('content', ''))
|
| 316 |
-
|
| 317 |
-
# Save to database
|
| 318 |
-
topic = Topic.query.get(topic_id)
|
| 319 |
-
|
| 320 |
-
learning_session = LearningSession(
|
| 321 |
-
user_id=session['user_id'],
|
| 322 |
-
topic_id=topic_id,
|
| 323 |
-
content=content,
|
| 324 |
-
difficulty=teaching_result.get('metadata', {}).get('complexity', 'beginner')
|
| 325 |
-
)
|
| 326 |
-
db.session.add(learning_session)
|
| 327 |
-
db.session.commit()
|
| 328 |
-
|
| 329 |
-
return jsonify({
|
| 330 |
-
'content': content,
|
| 331 |
-
'difficulty': teaching_result.get('metadata', {}).get('complexity'),
|
| 332 |
-
'knowledge_level': teaching_result.get('metadata', {}).get('knowledge_level', 0),
|
| 333 |
-
'topic_name': topic.name,
|
| 334 |
-
'agent_metadata': teaching_result.get('metadata', {})
|
| 335 |
-
})
|
| 336 |
-
|
| 337 |
-
@app.route('/api/generate-quiz', methods=['POST'])
|
| 338 |
-
def generate_quiz():
|
| 339 |
-
if 'user_id' not in session:
|
| 340 |
-
return jsonify({'error': 'Not logged in'}), 401
|
| 341 |
-
|
| 342 |
-
data = request.json
|
| 343 |
-
topic_id = data['topic_id']
|
| 344 |
-
|
| 345 |
-
# Use Coordinator Agent
|
| 346 |
-
result = coordinator.perceive({
|
| 347 |
-
'task': 'generate_quiz',
|
| 348 |
-
'user_id': session['user_id'],
|
| 349 |
-
'context': {
|
| 350 |
-
'topic_id': topic_id,
|
| 351 |
-
'recent_performance': []
|
| 352 |
-
}
|
| 353 |
-
}).decide().act()
|
| 354 |
-
|
| 355 |
-
if not result['success']:
|
| 356 |
-
return jsonify({'error': result.get('error')}), 500
|
| 357 |
-
|
| 358 |
-
assessment_result = result['results'].get('AssessmentAgent', {})
|
| 359 |
-
|
| 360 |
-
topic = Topic.query.get(topic_id)
|
| 361 |
-
|
| 362 |
-
return jsonify({
|
| 363 |
-
'questions': assessment_result.get('questions', []),
|
| 364 |
-
'difficulty': 'adaptive',
|
| 365 |
-
'topic_name': topic.name,
|
| 366 |
-
'topic_id': topic_id,
|
| 367 |
-
'agent_metadata': assessment_result.get('metadata', {})
|
| 368 |
-
})
|
| 369 |
-
|
| 370 |
-
@app.route('/api/submit-answer', methods=['POST'])
|
| 371 |
-
def submit_answer():
|
| 372 |
-
if 'user_id' not in session:
|
| 373 |
-
return jsonify({'error': 'Not logged in'}), 401
|
| 374 |
-
|
| 375 |
-
data = request.json
|
| 376 |
-
topic_id = data['topic_id']
|
| 377 |
-
question = data['question']
|
| 378 |
-
user_answer = data['user_answer']
|
| 379 |
-
correct_answer = data['correct_answer']
|
| 380 |
-
difficulty = data['difficulty']
|
| 381 |
-
|
| 382 |
-
is_correct = user_answer == correct_answer
|
| 383 |
-
|
| 384 |
-
# Save quiz attempt
|
| 385 |
-
attempt = QuizAttempt(
|
| 386 |
-
user_id=session['user_id'],
|
| 387 |
-
topic_id=topic_id,
|
| 388 |
-
question=question,
|
| 389 |
-
user_answer=user_answer,
|
| 390 |
-
correct_answer=correct_answer,
|
| 391 |
-
is_correct=is_correct,
|
| 392 |
-
difficulty=difficulty
|
| 393 |
-
)
|
| 394 |
-
db.session.add(attempt)
|
| 395 |
-
db.session.commit()
|
| 396 |
-
|
| 397 |
-
# Update knowledge state
|
| 398 |
-
state = knowledge_tracker.update_knowledge(
|
| 399 |
-
session['user_id'],
|
| 400 |
-
topic_id,
|
| 401 |
-
is_correct,
|
| 402 |
-
difficulty
|
| 403 |
-
)
|
| 404 |
-
|
| 405 |
-
# Generate explanation
|
| 406 |
-
topic = Topic.query.get(topic_id)
|
| 407 |
-
explanation = llm_service.explain_answer(
|
| 408 |
-
question,
|
| 409 |
-
user_answer,
|
| 410 |
-
correct_answer,
|
| 411 |
-
topic.name
|
| 412 |
-
)
|
| 413 |
-
|
| 414 |
-
return jsonify({
|
| 415 |
-
'is_correct': is_correct,
|
| 416 |
-
'explanation': explanation,
|
| 417 |
-
'new_knowledge_level': state.knowledge_level,
|
| 418 |
-
'confidence': state.confidence
|
| 419 |
-
})
|
| 420 |
-
|
| 421 |
-
@app.route('/api/knowledge-state/<int:topic_id>', methods=['GET'])
|
| 422 |
-
def get_knowledge_state(topic_id):
|
| 423 |
-
if 'user_id' not in session:
|
| 424 |
-
return jsonify({'error': 'Not logged in'}), 401
|
| 425 |
-
|
| 426 |
-
state = knowledge_tracker.get_or_create_knowledge_state(
|
| 427 |
-
session['user_id'], topic_id
|
| 428 |
-
)
|
| 429 |
-
|
| 430 |
-
topic = Topic.query.get(topic_id)
|
| 431 |
-
|
| 432 |
-
return jsonify({
|
| 433 |
-
'topic_id': topic_id,
|
| 434 |
-
'topic_name': topic.name,
|
| 435 |
-
'knowledge_level': state.knowledge_level,
|
| 436 |
-
'confidence': state.confidence,
|
| 437 |
-
'practice_count': state.practice_count,
|
| 438 |
-
'last_practiced': state.last_practiced.isoformat()
|
| 439 |
-
})
|
| 440 |
|
| 441 |
-
@app.
|
| 442 |
-
def
|
| 443 |
-
|
| 444 |
-
return jsonify({'error': 'Not logged in'}), 401
|
| 445 |
-
|
| 446 |
-
summary = knowledge_tracker.get_progress_summary(session['user_id'])
|
| 447 |
-
|
| 448 |
-
# Enhance with topic names
|
| 449 |
-
for topic_list in ['weak_topics', 'strong_topics']:
|
| 450 |
-
for item in summary[topic_list]:
|
| 451 |
-
topic = Topic.query.get(item['id'])
|
| 452 |
-
if topic:
|
| 453 |
-
item['name'] = topic.name
|
| 454 |
-
|
| 455 |
-
return jsonify(summary)
|
| 456 |
|
| 457 |
-
@app.
|
| 458 |
-
def
|
| 459 |
-
|
| 460 |
-
return jsonify({'error': '
|
| 461 |
-
|
| 462 |
-
current_topic_id = request.args.get('current_topic_id', type=int)
|
| 463 |
-
|
| 464 |
-
# Use Coordinator Agent
|
| 465 |
-
result = coordinator.perceive({
|
| 466 |
-
'task': 'recommend_topic',
|
| 467 |
-
'user_id': session['user_id'],
|
| 468 |
-
'context': {
|
| 469 |
-
'current_topic_id': current_topic_id
|
| 470 |
-
}
|
| 471 |
-
}).decide().act()
|
| 472 |
-
|
| 473 |
-
if not result['success']:
|
| 474 |
-
return jsonify({'message': 'No recommendations'}), 404
|
| 475 |
-
|
| 476 |
-
recommendation_result = result['results'].get('RecommendationAgent', {})
|
| 477 |
-
next_best = recommendation_result.get('next_best')
|
| 478 |
-
|
| 479 |
-
if next_best:
|
| 480 |
-
return jsonify({
|
| 481 |
-
'id': next_best['topic_id'],
|
| 482 |
-
'name': next_best['name'],
|
| 483 |
-
'category': next_best['category'],
|
| 484 |
-
'difficulty': next_best['difficulty'],
|
| 485 |
-
'description': next_best['reason'],
|
| 486 |
-
'agent_recommendation': True
|
| 487 |
-
})
|
| 488 |
-
|
| 489 |
-
return jsonify({'message': 'No recommendations available'}), 404
|
| 490 |
|
| 491 |
-
@app.
|
| 492 |
-
def
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
summary = knowledge_tracker.get_progress_summary(session['user_id'])
|
| 497 |
-
|
| 498 |
-
weak_topic_names = []
|
| 499 |
-
strong_topic_names = []
|
| 500 |
-
|
| 501 |
-
for item in summary['weak_topics']:
|
| 502 |
-
topic = Topic.query.get(item['id'])
|
| 503 |
-
if topic:
|
| 504 |
-
weak_topic_names.append(topic.name)
|
| 505 |
-
|
| 506 |
-
for item in summary['strong_topics']:
|
| 507 |
-
topic = Topic.query.get(item['id'])
|
| 508 |
-
if topic:
|
| 509 |
-
strong_topic_names.append(topic.name)
|
| 510 |
-
|
| 511 |
-
tips = llm_service.generate_study_tips(weak_topic_names, strong_topic_names)
|
| 512 |
-
|
| 513 |
-
# Format the tips
|
| 514 |
-
formatted_tips = format_study_tips(tips)
|
| 515 |
-
|
| 516 |
-
return jsonify({'tips': formatted_tips})
|
| 517 |
|
| 518 |
-
|
| 519 |
-
def check_code():
|
| 520 |
-
"""Execute Python code safely and return output"""
|
| 521 |
-
if 'user_id' not in session:
|
| 522 |
-
return jsonify({'error': 'Not logged in'}), 401
|
| 523 |
-
|
| 524 |
-
data = request.json
|
| 525 |
-
user_code = data.get('code', '')
|
| 526 |
-
|
| 527 |
-
# Security: limit execution time and dangerous operations
|
| 528 |
-
if any(keyword in user_code.lower() for keyword in ['import os', 'import sys', 'eval', 'exec', 'open', 'file', '__import__']):
|
| 529 |
-
return jsonify({
|
| 530 |
-
'success': False,
|
| 531 |
-
'output': 'Error: Restricted operations detected. Please use only basic Python syntax.',
|
| 532 |
-
'error': True
|
| 533 |
-
})
|
| 534 |
-
|
| 535 |
-
try:
|
| 536 |
-
# Capture output
|
| 537 |
-
import io
|
| 538 |
-
import sys
|
| 539 |
-
from contextlib import redirect_stdout
|
| 540 |
-
|
| 541 |
-
output_buffer = io.StringIO()
|
| 542 |
-
|
| 543 |
-
with redirect_stdout(output_buffer):
|
| 544 |
-
# Create a restricted namespace
|
| 545 |
-
namespace = {'__builtins__': {
|
| 546 |
-
'print': print,
|
| 547 |
-
'input': lambda x='': '',
|
| 548 |
-
'len': len,
|
| 549 |
-
'range': range,
|
| 550 |
-
'str': str,
|
| 551 |
-
'int': int,
|
| 552 |
-
'float': float,
|
| 553 |
-
'list': list,
|
| 554 |
-
'dict': dict,
|
| 555 |
-
'set': set,
|
| 556 |
-
'tuple': tuple,
|
| 557 |
-
'sum': sum,
|
| 558 |
-
'max': max,
|
| 559 |
-
'min': min,
|
| 560 |
-
'abs': abs,
|
| 561 |
-
'round': round,
|
| 562 |
-
}}
|
| 563 |
-
|
| 564 |
-
# Execute code
|
| 565 |
-
exec(user_code, namespace)
|
| 566 |
-
|
| 567 |
-
output = output_buffer.getvalue()
|
| 568 |
-
|
| 569 |
-
return jsonify({
|
| 570 |
-
'success': True,
|
| 571 |
-
'output': output if output else 'Code executed successfully (no output)',
|
| 572 |
-
'error': False
|
| 573 |
-
})
|
| 574 |
-
|
| 575 |
-
except Exception as e:
|
| 576 |
-
return jsonify({
|
| 577 |
-
'success': False,
|
| 578 |
-
'output': f'Error: {str(e)}',
|
| 579 |
-
'error': True
|
| 580 |
-
})
|
| 581 |
|
| 582 |
-
@app.route('/api/ask-challenge-hint', methods=['POST'])
|
| 583 |
-
def ask_challenge_hint():
|
| 584 |
-
"""Get hint for practice challenge using LLM"""
|
| 585 |
-
if 'user_id' not in session:
|
| 586 |
-
return jsonify({'error': 'Not logged in'}), 401
|
| 587 |
-
|
| 588 |
-
data = request.json
|
| 589 |
-
|
| 590 |
-
# Use Coordinator Agent with Tutor Agent
|
| 591 |
-
result = coordinator.perceive({
|
| 592 |
-
'task': 'provide_hint',
|
| 593 |
-
'user_id': session['user_id'],
|
| 594 |
-
'context': {
|
| 595 |
-
'question': data.get('question'),
|
| 596 |
-
'challenge': data.get('challenge'),
|
| 597 |
-
'attempt_count': data.get('attempt_count', 1),
|
| 598 |
-
'frustration_level': 'normal'
|
| 599 |
-
}
|
| 600 |
-
}).decide().act()
|
| 601 |
-
|
| 602 |
-
if not result['success']:
|
| 603 |
-
return jsonify({'hint': 'Break the problem into smaller steps!'}), 200
|
| 604 |
-
|
| 605 |
-
tutor_result = result['results']
|
| 606 |
-
|
| 607 |
-
return jsonify({
|
| 608 |
-
'hint': tutor_result.get('hint'),
|
| 609 |
-
'hint_level': tutor_result.get('hint_level'),
|
| 610 |
-
'agent': tutor_result.get('agent')
|
| 611 |
-
})
|
| 612 |
|
| 613 |
-
|
| 614 |
-
def get_agent_status():
|
| 615 |
-
"""Get status of all agents"""
|
| 616 |
-
if 'user_id' not in session:
|
| 617 |
-
return jsonify({'error': 'Not logged in'}), 401
|
| 618 |
-
|
| 619 |
-
status = coordinator.get_agent_status()
|
| 620 |
-
return jsonify(status)
|
| 621 |
|
| 622 |
if __name__ == '__main__':
|
| 623 |
-
|
| 624 |
-
port = int(os.environ.get("PORT", 7860))
|
| 625 |
-
app.run(debug=True, host='0.0.0.0', port=port)
|
|
|
|
| 1 |
+
"""Flask application factory. `gunicorn app:app` serves the module-level instance."""
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import os
|
|
|
|
| 5 |
import re
|
| 6 |
+
import sqlite3
|
| 7 |
+
from types import SimpleNamespace
|
| 8 |
|
| 9 |
+
from flask import Flask, jsonify
|
| 10 |
+
from flask_cors import CORS
|
| 11 |
+
from sqlalchemy import event
|
| 12 |
+
from sqlalchemy.engine import Engine
|
| 13 |
+
|
| 14 |
+
from agent_knowledge.rules.teaching_rules import TeachingRuleEngine
|
| 15 |
+
from agent_knowledge.rules.tutor_rules import TutorRuleEngine
|
| 16 |
+
from agents.graph import Coordinator
|
| 17 |
+
from agents.state import AgentContext
|
| 18 |
+
from agents.tutor_chat import TutorChat
|
| 19 |
+
from config import BASE_DIR, Config
|
| 20 |
+
from curriculum.seed import seed_all
|
| 21 |
+
from ml.bandit import StrategyBandit
|
| 22 |
+
from models import db, migrate_schema
|
| 23 |
+
from routes import api
|
| 24 |
+
from services.knowledge import KnowledgeService
|
| 25 |
+
from services.llm import LLMService
|
| 26 |
+
|
| 27 |
+
logging.basicConfig(level=os.environ.get('LOG_LEVEL', 'INFO'),
|
| 28 |
+
format='%(asctime)s %(levelname)s %(name)s: %(message)s')
|
| 29 |
+
log = logging.getLogger('app')
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@event.listens_for(Engine, 'connect')
|
| 33 |
+
def _sqlite_pragmas(dbapi_conn, _record):
|
| 34 |
+
if isinstance(dbapi_conn, sqlite3.Connection):
|
| 35 |
+
cur = dbapi_conn.cursor()
|
| 36 |
+
cur.execute('PRAGMA journal_mode=WAL')
|
| 37 |
+
cur.execute('PRAGMA busy_timeout=5000')
|
| 38 |
+
cur.execute('PRAGMA synchronous=NORMAL')
|
| 39 |
+
cur.close()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def build_services(app):
|
| 43 |
+
cfg = SimpleNamespace(**{k: app.config[k] for k in app.config if k.isupper()})
|
| 44 |
+
with open(os.path.join(BASE_DIR, 'agent_knowledge', 'knowledge_bases', 'question_templates.json')) as f:
|
| 45 |
+
templates = json.load(f).get('question_templates', [])
|
| 46 |
+
teaching_rules = TeachingRuleEngine()
|
| 47 |
+
ctx = AgentContext(
|
| 48 |
+
llm=LLMService(cfg),
|
| 49 |
+
knowledge=KnowledgeService(cfg.ML_ARTIFACTS_DIR),
|
| 50 |
+
bandit=StrategyBandit(teaching_rules.strategies),
|
| 51 |
+
teaching_rules=teaching_rules,
|
| 52 |
+
tutor_rules=TutorRuleEngine(),
|
| 53 |
+
question_templates=templates,
|
| 54 |
+
config=cfg,
|
| 55 |
+
)
|
| 56 |
+
tutor_db = app.config.get('TUTOR_DB_PATH') or os.path.join(cfg.DATA_DIR, 'tutor_memory.db')
|
| 57 |
+
return SimpleNamespace(llm=ctx.llm, knowledge=ctx.knowledge, bandit=ctx.bandit, ctx=ctx,
|
| 58 |
+
coordinator=Coordinator(ctx), tutor_chat=TutorChat(ctx, tutor_db))
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
+
def create_app(config_object=Config):
|
| 62 |
+
app = Flask(__name__)
|
| 63 |
+
app.config.from_object(config_object)
|
| 64 |
+
if app.config['SECRET_KEY'] == 'dev-only-change-me' and not app.config.get('TESTING'):
|
| 65 |
+
log.warning('SECRET_KEY is not set: tokens will not survive restarts. Set SECRET_KEY in production.')
|
| 66 |
|
| 67 |
+
origins = list(app.config['CORS_ORIGINS'])
|
| 68 |
+
if app.config.get('CORS_ORIGIN_REGEX'):
|
| 69 |
+
origins.append(re.compile(app.config['CORS_ORIGIN_REGEX']))
|
| 70 |
+
CORS(app, supports_credentials=True, origins=origins,
|
| 71 |
+
allow_headers=['Content-Type', 'Authorization'], methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'])
|
| 72 |
|
| 73 |
+
if app.config['SQLALCHEMY_DATABASE_URI'].startswith('sqlite:///'):
|
| 74 |
+
os.makedirs(os.path.dirname(app.config['SQLALCHEMY_DATABASE_URI'][len('sqlite:///'):]), exist_ok=True)
|
| 75 |
+
db.init_app(app)
|
| 76 |
|
|
|
|
|
|
|
| 77 |
with app.app_context():
|
| 78 |
db.create_all()
|
| 79 |
+
migrate_schema()
|
| 80 |
+
added = seed_all()
|
| 81 |
+
if added:
|
| 82 |
+
log.info('Seeded %d questions into the question bank', added)
|
| 83 |
+
app.extensions['elearn'] = build_services(app)
|
| 84 |
+
log.info('LLM: %s | knowledge model: %s', app.extensions['elearn'].llm.info()['provider'],
|
| 85 |
+
'transformer+bkt' if app.extensions['elearn'].knowledge.kt.available else 'bkt')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
+
app.register_blueprint(api)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
@app.errorhandler(404)
|
| 90 |
+
def not_found(_e):
|
| 91 |
+
return jsonify({'error': 'Not found'}), 404
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
+
@app.errorhandler(405)
|
| 94 |
+
def not_allowed(_e):
|
| 95 |
+
return jsonify({'error': 'Method not allowed'}), 405
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
@app.errorhandler(500)
|
| 98 |
+
def server_error(_e):
|
| 99 |
+
db.session.rollback()
|
| 100 |
+
return jsonify({'error': 'Internal server error'}), 500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
@app.teardown_request
|
| 103 |
+
def _rollback_on_error(exc):
|
| 104 |
+
if exc is not None:
|
| 105 |
+
db.session.rollback()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
return app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
app = create_app() if os.environ.get('ELEARN_NO_AUTOAPP') != '1' else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
if __name__ == '__main__':
|
| 113 |
+
app.run(debug=os.environ.get('FLASK_DEBUG') == '1', host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
|
|
|
|
|
|
backend/config.py
CHANGED
|
@@ -3,19 +3,70 @@ from dotenv import load_dotenv
|
|
| 3 |
|
| 4 |
load_dotenv()
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
load_dotenv()
|
| 5 |
|
| 6 |
+
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _default_data_dir():
|
| 10 |
+
"""Prefer HF Spaces persistent storage (/data) when it is mounted and writable."""
|
| 11 |
+
if os.path.isdir('/data') and os.access('/data', os.W_OK):
|
| 12 |
+
return '/data'
|
| 13 |
+
return os.path.join(os.path.dirname(BASE_DIR), 'data')
|
| 14 |
+
|
| 15 |
|
| 16 |
+
def _bool(name, default=False):
|
| 17 |
+
return os.environ.get(name, str(default)).lower() in ('1', 'true', 'yes')
|
| 18 |
|
| 19 |
+
|
| 20 |
+
class Config:
|
| 21 |
+
SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-only-change-me'
|
| 22 |
+
|
| 23 |
+
DATA_DIR = os.environ.get('DATA_DIR') or _default_data_dir()
|
| 24 |
+
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///' + os.path.join(DATA_DIR, 'database.db')
|
| 25 |
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
| 26 |
+
SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True}
|
| 27 |
+
|
| 28 |
+
# Cross-site cookies (Vercel frontend -> HF backend) need SameSite=None; Secure.
|
| 29 |
+
# Bearer tokens are the primary auth mechanism, cookies are a fallback.
|
| 30 |
+
SESSION_COOKIE_SAMESITE = os.environ.get('SESSION_COOKIE_SAMESITE', 'None')
|
| 31 |
+
SESSION_COOKIE_SECURE = _bool('SESSION_COOKIE_SECURE', True)
|
| 32 |
+
TOKEN_MAX_AGE = int(os.environ.get('TOKEN_MAX_AGE', 60 * 60 * 24 * 14))
|
| 33 |
+
|
| 34 |
+
CORS_ORIGINS = [o.strip() for o in os.environ.get(
|
| 35 |
+
'CORS_ORIGINS',
|
| 36 |
+
'http://localhost:3000,http://localhost:5173,https://adaptive-e-learning-system.vercel.app'
|
| 37 |
+
).split(',') if o.strip()]
|
| 38 |
+
# Vercel preview deployments
|
| 39 |
+
CORS_ORIGIN_REGEX = os.environ.get('CORS_ORIGIN_REGEX', r'https://adaptive-e-learning-system.*\.vercel\.app')
|
| 40 |
+
|
| 41 |
+
# LLM
|
| 42 |
+
GEMINI_API_KEY = os.environ.get('GEMINI_API_KEY') or os.environ.get('GOOGLE_API_KEY')
|
| 43 |
+
LLM_PROVIDER = os.environ.get('LLM_PROVIDER', 'gemini' if GEMINI_API_KEY else 'offline')
|
| 44 |
+
LLM_MODEL = os.environ.get('LLM_MODEL', 'gemini-2.5-flash')
|
| 45 |
+
LLM_TEMPERATURE = float(os.environ.get('LLM_TEMPERATURE', 0.6))
|
| 46 |
+
LLM_TIMEOUT = int(os.environ.get('LLM_TIMEOUT', 60))
|
| 47 |
+
LLM_MAX_RETRIES = int(os.environ.get('LLM_MAX_RETRIES', 2))
|
| 48 |
+
|
| 49 |
+
# Content reuse: how many cached lesson variants to keep per (topic, level, strategy)
|
| 50 |
+
LESSON_CACHE_VARIANTS = int(os.environ.get('LESSON_CACHE_VARIANTS', 3))
|
| 51 |
+
QUIZ_SIZE_MIN = 4
|
| 52 |
+
QUIZ_SIZE_MAX = 6
|
| 53 |
+
|
| 54 |
+
# Knowledge tracing
|
| 55 |
+
ML_ARTIFACTS_DIR = os.environ.get('ML_ARTIFACTS_DIR') or os.path.join(BASE_DIR, 'ml', 'artifacts')
|
| 56 |
+
TARGET_SUCCESS_RATE = 0.7 # "desirable difficulty" target for adaptive quizzes
|
| 57 |
+
MASTERY_THRESHOLD = 0.8
|
| 58 |
+
PREREQ_READY_THRESHOLD = 0.6
|
| 59 |
+
|
| 60 |
+
# Code sandbox
|
| 61 |
+
SANDBOX_TIMEOUT_S = 5
|
| 62 |
+
SANDBOX_MEMORY_MB = 256
|
| 63 |
+
SANDBOX_MAX_OUTPUT = 10_000
|
| 64 |
+
|
| 65 |
+
DIFFICULTY_LEVELS = ['beginner', 'intermediate', 'advanced']
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class TestConfig(Config):
|
| 69 |
+
TESTING = True
|
| 70 |
+
SQLALCHEMY_DATABASE_URI = 'sqlite://'
|
| 71 |
+
SESSION_COOKIE_SECURE = False
|
| 72 |
+
LLM_PROVIDER = 'offline'
|
backend/curriculum/__init__.py
ADDED
|
File without changes
|
backend/curriculum/curriculum.json
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"version": 2,
|
| 3 |
+
"topics": [
|
| 4 |
+
{"slug": "python-basics", "name": "Python Basics", "category": "Programming", "difficulty": "beginner",
|
| 5 |
+
"description": "Variables, data types, operators, input/output and the Python REPL.",
|
| 6 |
+
"prerequisites": [], "key_concepts": ["variables", "int/float/str/bool", "operators", "print and f-strings", "type conversion"]},
|
| 7 |
+
{"slug": "control-flow", "name": "Control Flow", "category": "Programming", "difficulty": "beginner",
|
| 8 |
+
"description": "if/elif/else, for and while loops, break/continue and comprehensions.",
|
| 9 |
+
"prerequisites": ["python-basics"], "key_concepts": ["conditionals", "for loops", "while loops", "range()", "list comprehensions"]},
|
| 10 |
+
{"slug": "functions", "name": "Functions", "category": "Programming", "difficulty": "beginner",
|
| 11 |
+
"description": "Defining functions, arguments, return values, scope and lambdas.",
|
| 12 |
+
"prerequisites": ["control-flow"], "key_concepts": ["def and return", "default and keyword args", "*args/**kwargs", "scope (LEGB)", "lambda"]},
|
| 13 |
+
{"slug": "data-structures", "name": "Data Structures", "category": "Programming", "difficulty": "intermediate",
|
| 14 |
+
"description": "Lists, tuples, dicts, sets, stacks and queues and when to use each.",
|
| 15 |
+
"prerequisites": ["functions"], "key_concepts": ["lists vs tuples", "dict lookups", "sets", "stack/queue (deque)", "time complexity of operations"]},
|
| 16 |
+
{"slug": "oop", "name": "Object-Oriented Programming", "category": "Programming", "difficulty": "intermediate",
|
| 17 |
+
"description": "Classes, objects, inheritance, polymorphism and dunder methods.",
|
| 18 |
+
"prerequisites": ["functions"], "key_concepts": ["class and __init__", "instance vs class attributes", "inheritance and super()", "polymorphism", "dunder methods"]},
|
| 19 |
+
{"slug": "error-handling-testing", "name": "Error Handling & Testing", "category": "Programming", "difficulty": "intermediate",
|
| 20 |
+
"description": "Exceptions, try/except/finally, custom errors and unit testing with pytest.",
|
| 21 |
+
"prerequisites": ["functions"], "key_concepts": ["try/except/else/finally", "raising exceptions", "custom exceptions", "assert", "pytest basics"]},
|
| 22 |
+
{"slug": "algorithms", "name": "Algorithms", "category": "Programming", "difficulty": "advanced",
|
| 23 |
+
"description": "Sorting, searching, recursion, Big-O analysis and classic algorithm patterns.",
|
| 24 |
+
"prerequisites": ["data-structures"], "key_concepts": ["Big-O notation", "binary search", "merge/quick sort", "recursion", "two pointers and sliding window"]},
|
| 25 |
+
{"slug": "web-fundamentals", "name": "Web Development", "category": "Web", "difficulty": "beginner",
|
| 26 |
+
"description": "HTML structure, CSS styling and how browsers render pages.",
|
| 27 |
+
"prerequisites": [], "key_concepts": ["HTML elements", "CSS selectors", "box model", "flexbox", "HTTP request/response"]},
|
| 28 |
+
{"slug": "javascript-dom", "name": "JavaScript & the DOM", "category": "Web", "difficulty": "intermediate",
|
| 29 |
+
"description": "JavaScript syntax, events, DOM manipulation and async/await.",
|
| 30 |
+
"prerequisites": ["web-fundamentals"], "key_concepts": ["let/const", "arrow functions", "DOM querying", "event listeners", "promises and async/await"]},
|
| 31 |
+
{"slug": "rest-apis", "name": "REST APIs", "category": "Web", "difficulty": "intermediate",
|
| 32 |
+
"description": "Designing and consuming REST APIs with HTTP verbs, status codes and JSON.",
|
| 33 |
+
"prerequisites": ["functions", "web-fundamentals"], "key_concepts": ["HTTP methods", "status codes", "JSON", "statelessness", "authentication tokens"]},
|
| 34 |
+
{"slug": "database-design", "name": "Database Design", "category": "Database", "difficulty": "intermediate",
|
| 35 |
+
"description": "Relational modeling, keys, normalization and ER diagrams.",
|
| 36 |
+
"prerequisites": ["python-basics"], "key_concepts": ["tables and keys", "one-to-many / many-to-many", "normalization (1NF-3NF)", "indexes", "ER diagrams"]},
|
| 37 |
+
{"slug": "sql-querying", "name": "SQL Querying", "category": "Database", "difficulty": "intermediate",
|
| 38 |
+
"description": "SELECT, JOINs, GROUP BY, subqueries and window functions.",
|
| 39 |
+
"prerequisites": ["database-design"], "key_concepts": ["SELECT/WHERE", "JOIN types", "GROUP BY/HAVING", "subqueries", "window functions"]},
|
| 40 |
+
{"slug": "statistics", "name": "Statistics for Data Science", "category": "AI/ML", "difficulty": "beginner",
|
| 41 |
+
"description": "Descriptive statistics, probability, distributions and hypothesis testing.",
|
| 42 |
+
"prerequisites": ["python-basics"], "key_concepts": ["mean/median/variance", "probability rules", "normal distribution", "correlation", "hypothesis tests and p-values"]},
|
| 43 |
+
{"slug": "numpy-pandas", "name": "NumPy & Pandas", "category": "AI/ML", "difficulty": "intermediate",
|
| 44 |
+
"description": "Vectorized arrays, DataFrames, cleaning, grouping and joining data.",
|
| 45 |
+
"prerequisites": ["data-structures", "statistics"], "key_concepts": ["ndarray and broadcasting", "DataFrame indexing", "missing values", "groupby/aggregate", "merge/join"]},
|
| 46 |
+
{"slug": "ml-basics", "name": "Machine Learning Basics", "category": "AI/ML", "difficulty": "intermediate",
|
| 47 |
+
"description": "Supervised vs unsupervised learning, regression, classification and scikit-learn.",
|
| 48 |
+
"prerequisites": ["numpy-pandas"], "key_concepts": ["supervised vs unsupervised", "linear/logistic regression", "train/test split", "overfitting", "scikit-learn API"]},
|
| 49 |
+
{"slug": "model-evaluation", "name": "Model Evaluation", "category": "AI/ML", "difficulty": "intermediate",
|
| 50 |
+
"description": "Metrics, cross-validation, bias-variance trade-off and hyperparameter tuning.",
|
| 51 |
+
"prerequisites": ["ml-basics"], "key_concepts": ["accuracy/precision/recall/F1", "ROC-AUC", "cross-validation", "bias-variance", "grid/random search"]},
|
| 52 |
+
{"slug": "neural-networks", "name": "Neural Networks", "category": "AI/ML", "difficulty": "advanced",
|
| 53 |
+
"description": "Perceptrons, activation functions, backpropagation and gradient descent.",
|
| 54 |
+
"prerequisites": ["ml-basics"], "key_concepts": ["perceptron", "activation functions", "loss functions", "backpropagation", "gradient descent variants"]},
|
| 55 |
+
{"slug": "deep-learning-pytorch", "name": "Deep Learning with PyTorch", "category": "AI/ML", "difficulty": "advanced",
|
| 56 |
+
"description": "Tensors, autograd, nn.Module, training loops, CNNs and GPU training.",
|
| 57 |
+
"prerequisites": ["neural-networks"], "key_concepts": ["tensors and autograd", "nn.Module", "training loop", "CNNs", "GPU / mixed precision"]},
|
| 58 |
+
{"slug": "nlp-transformers", "name": "NLP & Transformers", "category": "AI/ML", "difficulty": "advanced",
|
| 59 |
+
"description": "Tokenization, embeddings, attention and the transformer architecture.",
|
| 60 |
+
"prerequisites": ["deep-learning-pytorch"], "key_concepts": ["tokenization", "embeddings", "self-attention", "encoder vs decoder", "fine-tuning"]},
|
| 61 |
+
{"slug": "llm-agents", "name": "LLM Apps & Agents", "category": "AI/ML", "difficulty": "advanced",
|
| 62 |
+
"description": "Prompting, RAG, tool calling and multi-agent orchestration with LangGraph.",
|
| 63 |
+
"prerequisites": ["nlp-transformers", "rest-apis"], "key_concepts": ["prompt engineering", "retrieval-augmented generation", "tool/function calling", "agent graphs (LangGraph)", "evaluation and guardrails"]}
|
| 64 |
+
]
|
| 65 |
+
}
|
backend/curriculum/seed.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Idempotent seeding of the curriculum and the starter question bank."""
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
from models import Topic, db
|
| 6 |
+
from services.content import add_questions
|
| 7 |
+
|
| 8 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def seed_curriculum():
|
| 12 |
+
with open(os.path.join(HERE, 'curriculum.json')) as f:
|
| 13 |
+
topics = json.load(f)['topics']
|
| 14 |
+
|
| 15 |
+
# Upsert by slug, falling back to name so v1 databases keep their topic IDs.
|
| 16 |
+
rows = {}
|
| 17 |
+
for pos, t in enumerate(topics):
|
| 18 |
+
row = Topic.query.filter_by(slug=t['slug']).first() or Topic.query.filter_by(name=t['name']).first()
|
| 19 |
+
if row is None:
|
| 20 |
+
row = Topic(name=t['name'])
|
| 21 |
+
db.session.add(row)
|
| 22 |
+
row.slug, row.name, row.category = t['slug'], t['name'], t['category']
|
| 23 |
+
row.difficulty, row.description = t['difficulty'], t['description']
|
| 24 |
+
row.key_concepts, row.position = t['key_concepts'], pos
|
| 25 |
+
rows[t['slug']] = row
|
| 26 |
+
db.session.flush()
|
| 27 |
+
for t in topics:
|
| 28 |
+
rows[t['slug']].prerequisites = ','.join(str(rows[p].id) for p in t['prerequisites'])
|
| 29 |
+
db.session.commit()
|
| 30 |
+
return rows
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def seed_questions(rows):
|
| 34 |
+
with open(os.path.join(HERE, 'seed_questions.json')) as f:
|
| 35 |
+
bank = json.load(f)
|
| 36 |
+
added = 0
|
| 37 |
+
for slug, questions in bank.items():
|
| 38 |
+
if slug in rows:
|
| 39 |
+
added += len(add_questions(rows[slug].id, questions, source='seed'))
|
| 40 |
+
db.session.commit()
|
| 41 |
+
return added
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def seed_all():
|
| 45 |
+
rows = seed_curriculum()
|
| 46 |
+
return seed_questions(rows)
|
backend/curriculum/seed_questions.json
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"python-basics": [
|
| 3 |
+
{"difficulty": "beginner", "concept": "type conversion", "question": "What does int(\"7\") + 3 evaluate to?",
|
| 4 |
+
"options": {"A": "10", "B": "\"73\"", "C": "TypeError", "D": "7.3"}, "correct_answer": "A",
|
| 5 |
+
"explanation": "int(\"7\") converts the string to the integer 7, so 7 + 3 = 10."},
|
| 6 |
+
{"difficulty": "intermediate", "concept": "operators", "question": "What is the value of 17 // 5 and 17 % 5 respectively?",
|
| 7 |
+
"options": {"A": "3.4 and 2", "B": "3 and 2", "C": "3 and 3", "D": "4 and 2"}, "correct_answer": "B",
|
| 8 |
+
"explanation": "// is floor division (17 // 5 = 3) and % gives the remainder (17 % 5 = 2)."},
|
| 9 |
+
{"difficulty": "advanced", "concept": "mutability", "question": "Given a = [1, 2]; b = a; b.append(3) — what is a?",
|
| 10 |
+
"options": {"A": "[1, 2]", "B": "[1, 2, 3]", "C": "[3]", "D": "Error"}, "correct_answer": "B",
|
| 11 |
+
"explanation": "b = a binds a second name to the same list object, so mutating b also changes a."}
|
| 12 |
+
],
|
| 13 |
+
"control-flow": [
|
| 14 |
+
{"difficulty": "beginner", "concept": "range()", "question": "How many times does `for i in range(2, 8):` loop?",
|
| 15 |
+
"options": {"A": "8", "B": "7", "C": "6", "D": "5"}, "correct_answer": "C",
|
| 16 |
+
"explanation": "range(2, 8) yields 2, 3, 4, 5, 6, 7 — six values; the stop value is excluded."},
|
| 17 |
+
{"difficulty": "intermediate", "concept": "list comprehensions", "question": "What does [x * x for x in range(5) if x % 2 == 0] produce?",
|
| 18 |
+
"options": {"A": "[0, 4, 16]", "B": "[1, 9]", "C": "[0, 1, 4, 9, 16]", "D": "[4, 16]"}, "correct_answer": "A",
|
| 19 |
+
"explanation": "The even values 0, 2, 4 are kept and squared: [0, 4, 16]."},
|
| 20 |
+
{"difficulty": "advanced", "concept": "loop else", "question": "When does the `else` block of a Python `for` loop run?",
|
| 21 |
+
"options": {"A": "Only when the loop body raises an exception", "B": "When the loop finishes without hitting `break`", "C": "Every time the condition is false", "D": "Never; it is a syntax error"}, "correct_answer": "B",
|
| 22 |
+
"explanation": "A loop's else clause runs once after normal completion and is skipped if the loop exits via break."}
|
| 23 |
+
],
|
| 24 |
+
"functions": [
|
| 25 |
+
{"difficulty": "beginner", "concept": "return", "question": "What does a Python function return if it has no return statement?",
|
| 26 |
+
"options": {"A": "0", "B": "An empty string", "C": "None", "D": "It raises an error"}, "correct_answer": "C",
|
| 27 |
+
"explanation": "Functions without an explicit return implicitly return None."},
|
| 28 |
+
{"difficulty": "intermediate", "concept": "*args/**kwargs", "question": "In def f(*args, **kwargs), calling f(1, 2, x=3) gives args and kwargs equal to:",
|
| 29 |
+
"options": {"A": "[1, 2] and {'x': 3}", "B": "(1, 2) and {'x': 3}", "C": "(1, 2, 3) and {}", "D": "(1, 2) and ('x', 3)"}, "correct_answer": "B",
|
| 30 |
+
"explanation": "Positional extras are collected into a tuple and keyword extras into a dict."},
|
| 31 |
+
{"difficulty": "advanced", "concept": "default and keyword args", "question": "Why is `def add(item, bucket=[])` a common bug?",
|
| 32 |
+
"options": {"A": "Lists cannot be default values", "B": "The default list is created once and shared across calls", "C": "bucket becomes a tuple", "D": "It makes the function recursive"}, "correct_answer": "B",
|
| 33 |
+
"explanation": "Default values are evaluated once at definition time, so the same list accumulates items across calls. Use bucket=None instead."}
|
| 34 |
+
],
|
| 35 |
+
"data-structures": [
|
| 36 |
+
{"difficulty": "beginner", "concept": "lists vs tuples", "question": "Which of these is immutable?",
|
| 37 |
+
"options": {"A": "list", "B": "dict", "C": "set", "D": "tuple"}, "correct_answer": "D",
|
| 38 |
+
"explanation": "Tuples cannot be modified after creation; lists, dicts and sets are mutable."},
|
| 39 |
+
{"difficulty": "intermediate", "concept": "dict lookups", "question": "What is the average time complexity of `key in my_dict`?",
|
| 40 |
+
"options": {"A": "O(1)", "B": "O(log n)", "C": "O(n)", "D": "O(n log n)"}, "correct_answer": "A",
|
| 41 |
+
"explanation": "Dictionaries are hash tables, so membership checks are O(1) on average."},
|
| 42 |
+
{"difficulty": "advanced", "concept": "stack/queue (deque)", "question": "Why prefer collections.deque over list for a FIFO queue?",
|
| 43 |
+
"options": {"A": "deque supports indexing faster", "B": "list.pop(0) is O(n) while deque.popleft() is O(1)", "C": "deque uses less memory per item", "D": "lists cannot hold mixed types"}, "correct_answer": "B",
|
| 44 |
+
"explanation": "Removing from the front of a list shifts every element (O(n)); a deque pops from either end in O(1)."}
|
| 45 |
+
],
|
| 46 |
+
"oop": [
|
| 47 |
+
{"difficulty": "beginner", "concept": "class and __init__", "question": "What is the role of __init__ in a Python class?",
|
| 48 |
+
"options": {"A": "It deletes the object", "B": "It initializes a newly created instance", "C": "It defines a class constant", "D": "It imports the class"}, "correct_answer": "B",
|
| 49 |
+
"explanation": "__init__ runs right after an instance is created and sets up its initial attributes."},
|
| 50 |
+
{"difficulty": "intermediate", "concept": "inheritance and super()", "question": "What does super().__init__(name) do inside a subclass __init__?",
|
| 51 |
+
"options": {"A": "Creates a new parent object", "B": "Calls the parent class initializer on the current instance", "C": "Copies the parent's methods", "D": "Makes the class abstract"}, "correct_answer": "B",
|
| 52 |
+
"explanation": "super() delegates to the next class in the MRO so the parent's initialization runs on self."},
|
| 53 |
+
{"difficulty": "advanced", "concept": "dunder methods", "question": "Which method should you implement so that len(obj) works?",
|
| 54 |
+
"options": {"A": "__size__", "B": "__count__", "C": "__len__", "D": "__length__"}, "correct_answer": "C",
|
| 55 |
+
"explanation": "The built-in len() calls the object's __len__ method."}
|
| 56 |
+
],
|
| 57 |
+
"error-handling-testing": [
|
| 58 |
+
{"difficulty": "beginner", "concept": "try/except/else/finally", "question": "When does a `finally` block run?",
|
| 59 |
+
"options": {"A": "Only if an exception occurs", "B": "Only if no exception occurs", "C": "Always, whether or not an exception occurs", "D": "Only when re-raising"}, "correct_answer": "C",
|
| 60 |
+
"explanation": "finally always executes, making it the right place for cleanup code."},
|
| 61 |
+
{"difficulty": "intermediate", "concept": "raising exceptions", "question": "Which is the best way to signal an invalid argument value?",
|
| 62 |
+
"options": {"A": "return -1", "B": "print('error')", "C": "raise ValueError('...')", "D": "exit()"}, "correct_answer": "C",
|
| 63 |
+
"explanation": "Raising ValueError communicates the problem explicitly and lets callers handle it."},
|
| 64 |
+
{"difficulty": "advanced", "concept": "pytest basics", "question": "How do you assert that a function raises ZeroDivisionError in pytest?",
|
| 65 |
+
"options": {"A": "assert f() == ZeroDivisionError", "B": "with pytest.raises(ZeroDivisionError): f()", "C": "pytest.expect(f, ZeroDivisionError)", "D": "try: f() except: pass"}, "correct_answer": "B",
|
| 66 |
+
"explanation": "pytest.raises is a context manager that fails the test unless the expected exception is raised."}
|
| 67 |
+
],
|
| 68 |
+
"algorithms": [
|
| 69 |
+
{"difficulty": "beginner", "concept": "binary search", "question": "Binary search requires the input to be:",
|
| 70 |
+
"options": {"A": "Sorted", "B": "Unique", "C": "Numeric", "D": "Of even length"}, "correct_answer": "A",
|
| 71 |
+
"explanation": "Binary search halves the range by comparing with the middle element, which only works on sorted data."},
|
| 72 |
+
{"difficulty": "intermediate", "concept": "merge/quick sort", "question": "What is the worst-case time complexity of merge sort?",
|
| 73 |
+
"options": {"A": "O(n)", "B": "O(n log n)", "C": "O(n^2)", "D": "O(log n)"}, "correct_answer": "B",
|
| 74 |
+
"explanation": "Merge sort always splits in half (log n levels) and merges in linear time per level."},
|
| 75 |
+
{"difficulty": "advanced", "concept": "two pointers and sliding window", "question": "Finding the longest substring without repeating characters is best solved in:",
|
| 76 |
+
"options": {"A": "O(n^3) brute force only", "B": "O(n) with a sliding window and a hash map", "C": "O(n log n) by sorting", "D": "O(1) with recursion"}, "correct_answer": "B",
|
| 77 |
+
"explanation": "A sliding window that tracks the last index of each character visits each character a constant number of times."}
|
| 78 |
+
],
|
| 79 |
+
"web-fundamentals": [
|
| 80 |
+
{"difficulty": "beginner", "concept": "HTML elements", "question": "Which HTML element creates a hyperlink?",
|
| 81 |
+
"options": {"A": "<link>", "B": "<a>", "C": "<href>", "D": "<nav>"}, "correct_answer": "B",
|
| 82 |
+
"explanation": "The anchor element <a href=\"...\"> creates clickable hyperlinks; <link> is for stylesheets."},
|
| 83 |
+
{"difficulty": "intermediate", "concept": "box model", "question": "With box-sizing: border-box, the declared width includes:",
|
| 84 |
+
"options": {"A": "Content only", "B": "Content and padding", "C": "Content, padding and border", "D": "Content, padding, border and margin"}, "correct_answer": "C",
|
| 85 |
+
"explanation": "border-box includes padding and border in the width; margin is always outside."},
|
| 86 |
+
{"difficulty": "advanced", "concept": "flexbox", "question": "In a flex row container, which property aligns items vertically?",
|
| 87 |
+
"options": {"A": "justify-content", "B": "align-items", "C": "flex-direction", "D": "text-align"}, "correct_answer": "B",
|
| 88 |
+
"explanation": "align-items works on the cross axis, which is vertical for a row; justify-content works on the main axis."}
|
| 89 |
+
],
|
| 90 |
+
"javascript-dom": [
|
| 91 |
+
{"difficulty": "beginner", "concept": "let/const", "question": "What happens if you reassign a variable declared with const?",
|
| 92 |
+
"options": {"A": "It silently keeps the old value", "B": "TypeError: Assignment to constant variable", "C": "It becomes undefined", "D": "It works normally"}, "correct_answer": "B",
|
| 93 |
+
"explanation": "const bindings cannot be reassigned; doing so throws a TypeError."},
|
| 94 |
+
{"difficulty": "intermediate", "concept": "event listeners", "question": "Which method attaches a click handler to an element?",
|
| 95 |
+
"options": {"A": "el.on('click', fn)", "B": "el.addEventListener('click', fn)", "C": "el.click = fn()", "D": "el.listen('click', fn)"}, "correct_answer": "B",
|
| 96 |
+
"explanation": "addEventListener registers a handler without overwriting other listeners."},
|
| 97 |
+
{"difficulty": "advanced", "concept": "promises and async/await", "question": "What does an async function always return?",
|
| 98 |
+
"options": {"A": "undefined", "B": "A Promise", "C": "The awaited value directly", "D": "A callback"}, "correct_answer": "B",
|
| 99 |
+
"explanation": "async functions wrap their return value in a Promise, even if you return a plain value."}
|
| 100 |
+
],
|
| 101 |
+
"rest-apis": [
|
| 102 |
+
{"difficulty": "beginner", "concept": "HTTP methods", "question": "Which HTTP method is conventionally used to create a new resource?",
|
| 103 |
+
"options": {"A": "GET", "B": "POST", "C": "DELETE", "D": "HEAD"}, "correct_answer": "B",
|
| 104 |
+
"explanation": "POST submits data to create a resource; GET only retrieves."},
|
| 105 |
+
{"difficulty": "intermediate", "concept": "status codes", "question": "What status code means the client is not authenticated?",
|
| 106 |
+
"options": {"A": "200", "B": "301", "C": "401", "D": "500"}, "correct_answer": "C",
|
| 107 |
+
"explanation": "401 Unauthorized indicates missing or invalid authentication; 403 means authenticated but not allowed."},
|
| 108 |
+
{"difficulty": "advanced", "concept": "statelessness", "question": "Which HTTP methods are defined as idempotent?",
|
| 109 |
+
"options": {"A": "POST and PATCH", "B": "GET, PUT and DELETE", "C": "Only GET", "D": "All of them"}, "correct_answer": "B",
|
| 110 |
+
"explanation": "Repeating GET, PUT or DELETE leaves the server in the same state; POST is not idempotent."}
|
| 111 |
+
],
|
| 112 |
+
"database-design": [
|
| 113 |
+
{"difficulty": "beginner", "concept": "tables and keys", "question": "What uniquely identifies each row in a table?",
|
| 114 |
+
"options": {"A": "Foreign key", "B": "Primary key", "C": "Index", "D": "Column name"}, "correct_answer": "B",
|
| 115 |
+
"explanation": "A primary key is a unique, non-null identifier for every row."},
|
| 116 |
+
{"difficulty": "intermediate", "concept": "one-to-many / many-to-many", "question": "How is a many-to-many relationship usually modeled?",
|
| 117 |
+
"options": {"A": "A single column with comma-separated IDs", "B": "A junction (association) table with two foreign keys", "C": "Duplicating rows in both tables", "D": "It cannot be modeled"}, "correct_answer": "B",
|
| 118 |
+
"explanation": "A junction table holds pairs of foreign keys, one row per relationship."},
|
| 119 |
+
{"difficulty": "advanced", "concept": "normalization (1NF-3NF)", "question": "A table violates 3NF when:",
|
| 120 |
+
"options": {"A": "It has a composite primary key", "B": "A non-key column depends on another non-key column", "C": "It has more than 10 columns", "D": "It contains NULL values"}, "correct_answer": "B",
|
| 121 |
+
"explanation": "3NF forbids transitive dependencies: non-key attributes must depend only on the key."}
|
| 122 |
+
],
|
| 123 |
+
"sql-querying": [
|
| 124 |
+
{"difficulty": "beginner", "concept": "SELECT/WHERE", "question": "Which clause filters rows before grouping?",
|
| 125 |
+
"options": {"A": "HAVING", "B": "WHERE", "C": "ORDER BY", "D": "LIMIT"}, "correct_answer": "B",
|
| 126 |
+
"explanation": "WHERE filters individual rows; HAVING filters groups after GROUP BY."},
|
| 127 |
+
{"difficulty": "intermediate", "concept": "JOIN types", "question": "A LEFT JOIN returns:",
|
| 128 |
+
"options": {"A": "Only matching rows", "B": "All rows from the left table plus matches from the right (NULL if none)", "C": "All rows from both tables", "D": "Only non-matching rows"}, "correct_answer": "B",
|
| 129 |
+
"explanation": "LEFT JOIN keeps every left-table row and fills unmatched right columns with NULL."},
|
| 130 |
+
{"difficulty": "advanced", "concept": "window functions", "question": "What does ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) compute?",
|
| 131 |
+
"options": {"A": "Total salary per department", "B": "A rank of each employee's salary within their department", "C": "The number of departments", "D": "The average salary"}, "correct_answer": "B",
|
| 132 |
+
"explanation": "The window restarts numbering for each department and orders by salary, giving a per-department ranking."}
|
| 133 |
+
],
|
| 134 |
+
"statistics": [
|
| 135 |
+
{"difficulty": "beginner", "concept": "mean/median/variance", "question": "Which measure is most robust to outliers?",
|
| 136 |
+
"options": {"A": "Mean", "B": "Median", "C": "Range", "D": "Variance"}, "correct_answer": "B",
|
| 137 |
+
"explanation": "The median depends only on the middle value(s), so extreme values barely affect it."},
|
| 138 |
+
{"difficulty": "intermediate", "concept": "normal distribution", "question": "About what percentage of a normal distribution lies within 2 standard deviations of the mean?",
|
| 139 |
+
"options": {"A": "50%", "B": "68%", "C": "95%", "D": "99.7%"}, "correct_answer": "C",
|
| 140 |
+
"explanation": "By the 68-95-99.7 rule, roughly 95% of values fall within ±2σ."},
|
| 141 |
+
{"difficulty": "advanced", "concept": "hypothesis tests and p-values", "question": "A p-value of 0.03 means:",
|
| 142 |
+
"options": {"A": "There is a 3% chance the null hypothesis is true", "B": "If the null hypothesis were true, data this extreme would occur about 3% of the time", "C": "The effect size is 3%", "D": "The alternative is 97% likely"}, "correct_answer": "B",
|
| 143 |
+
"explanation": "A p-value is the probability of observing data at least this extreme assuming the null hypothesis holds."}
|
| 144 |
+
],
|
| 145 |
+
"numpy-pandas": [
|
| 146 |
+
{"difficulty": "beginner", "concept": "ndarray and broadcasting", "question": "What is np.array([1, 2, 3]) * 2?",
|
| 147 |
+
"options": {"A": "[1, 2, 3, 1, 2, 3]", "B": "array([2, 4, 6])", "C": "Error", "D": "6"}, "correct_answer": "B",
|
| 148 |
+
"explanation": "NumPy applies arithmetic element-wise, unlike Python lists which repeat."},
|
| 149 |
+
{"difficulty": "intermediate", "concept": "DataFrame indexing", "question": "What is the difference between df.loc and df.iloc?",
|
| 150 |
+
"options": {"A": "loc is label-based, iloc is integer-position-based", "B": "They are identical", "C": "loc is faster", "D": "iloc only works on columns"}, "correct_answer": "A",
|
| 151 |
+
"explanation": "loc selects by index/column labels; iloc selects by integer positions."},
|
| 152 |
+
{"difficulty": "advanced", "concept": "groupby/aggregate", "question": "df.groupby('city')['sales'].transform('mean') returns:",
|
| 153 |
+
"options": {"A": "One row per city", "B": "A Series aligned to df where each row holds its city's mean sales", "C": "The overall mean", "D": "A pivot table"}, "correct_answer": "B",
|
| 154 |
+
"explanation": "transform broadcasts the group result back to the original shape, unlike agg which reduces it."}
|
| 155 |
+
],
|
| 156 |
+
"ml-basics": [
|
| 157 |
+
{"difficulty": "beginner", "concept": "supervised vs unsupervised", "question": "Which task is unsupervised learning?",
|
| 158 |
+
"options": {"A": "Predicting house prices", "B": "Classifying spam emails", "C": "Clustering customers by behavior", "D": "Detecting cats in labeled photos"}, "correct_answer": "C",
|
| 159 |
+
"explanation": "Clustering finds structure without labels; the others learn from labeled examples."},
|
| 160 |
+
{"difficulty": "intermediate", "concept": "overfitting", "question": "Training accuracy 99%, test accuracy 62% most likely indicates:",
|
| 161 |
+
"options": {"A": "Underfitting", "B": "Overfitting", "C": "Data leakage", "D": "A perfect model"}, "correct_answer": "B",
|
| 162 |
+
"explanation": "A large gap between training and test performance means the model memorized the training data."},
|
| 163 |
+
{"difficulty": "advanced", "concept": "train/test split", "question": "Why must a StandardScaler be fit only on the training split?",
|
| 164 |
+
"options": {"A": "It is faster", "B": "Fitting on all data leaks test-set statistics into training", "C": "Scalers cannot handle test data", "D": "It changes the labels"}, "correct_answer": "B",
|
| 165 |
+
"explanation": "Using test statistics during preprocessing leaks information and inflates evaluation scores."}
|
| 166 |
+
],
|
| 167 |
+
"model-evaluation": [
|
| 168 |
+
{"difficulty": "beginner", "concept": "accuracy/precision/recall/F1", "question": "Recall measures:",
|
| 169 |
+
"options": {"A": "TP / (TP + FP)", "B": "TP / (TP + FN)", "C": "(TP + TN) / total", "D": "FP / (FP + TN)"}, "correct_answer": "B",
|
| 170 |
+
"explanation": "Recall is the fraction of actual positives that the model found."},
|
| 171 |
+
{"difficulty": "intermediate", "concept": "cross-validation", "question": "What is the main benefit of k-fold cross-validation?",
|
| 172 |
+
"options": {"A": "It trains faster", "B": "It gives a more reliable performance estimate using every sample for validation once", "C": "It removes the need for a test set", "D": "It prevents all overfitting"}, "correct_answer": "B",
|
| 173 |
+
"explanation": "Rotating validation folds reduces the variance of the performance estimate."},
|
| 174 |
+
{"difficulty": "advanced", "concept": "ROC-AUC", "question": "On a dataset with 1% positives, which metric is most informative?",
|
| 175 |
+
"options": {"A": "Accuracy", "B": "Precision-recall AUC", "C": "Mean squared error", "D": "R-squared"}, "correct_answer": "B",
|
| 176 |
+
"explanation": "With heavy class imbalance accuracy is misleading; PR-AUC focuses on the rare positive class."}
|
| 177 |
+
],
|
| 178 |
+
"neural-networks": [
|
| 179 |
+
{"difficulty": "beginner", "concept": "activation functions", "question": "Why do neural networks need non-linear activation functions?",
|
| 180 |
+
"options": {"A": "To speed up training", "B": "Without them, stacked layers collapse into a single linear function", "C": "To reduce memory", "D": "To normalize inputs"}, "correct_answer": "B",
|
| 181 |
+
"explanation": "A composition of linear layers is still linear; non-linearities let networks model complex functions."},
|
| 182 |
+
{"difficulty": "intermediate", "concept": "backpropagation", "question": "Backpropagation computes gradients using:",
|
| 183 |
+
"options": {"A": "Random search", "B": "The chain rule of calculus", "C": "Matrix inversion", "D": "Genetic algorithms"}, "correct_answer": "B",
|
| 184 |
+
"explanation": "Gradients flow backwards layer by layer by repeatedly applying the chain rule."},
|
| 185 |
+
{"difficulty": "advanced", "concept": "gradient descent variants", "question": "What problem do residual connections mainly address in deep networks?",
|
| 186 |
+
"options": {"A": "Overfitting", "B": "Vanishing gradients in very deep stacks", "C": "Class imbalance", "D": "Slow data loading"}, "correct_answer": "B",
|
| 187 |
+
"explanation": "Skip connections give gradients a direct path backward, making very deep networks trainable."}
|
| 188 |
+
],
|
| 189 |
+
"deep-learning-pytorch": [
|
| 190 |
+
{"difficulty": "beginner", "concept": "training loop", "question": "Why call optimizer.zero_grad() each iteration?",
|
| 191 |
+
"options": {"A": "To reset model weights", "B": "Because PyTorch accumulates gradients by default", "C": "To move tensors to the GPU", "D": "To free the dataset"}, "correct_answer": "B",
|
| 192 |
+
"explanation": ".backward() adds to existing .grad values, so stale gradients must be cleared each step."},
|
| 193 |
+
{"difficulty": "intermediate", "concept": "nn.Module", "question": "What do model.train() and model.eval() change?",
|
| 194 |
+
"options": {"A": "The learning rate", "B": "The behaviour of layers like Dropout and BatchNorm", "C": "Whether gradients exist", "D": "The device"}, "correct_answer": "B",
|
| 195 |
+
"explanation": "They toggle training-specific behavior; disabling gradients requires torch.no_grad()."},
|
| 196 |
+
{"difficulty": "advanced", "concept": "GPU / mixed precision", "question": "What is the main benefit of bf16 autocast on modern GPUs?",
|
| 197 |
+
"options": {"A": "Higher numerical precision", "B": "Faster tensor-core math and lower memory with fp32-like range", "C": "It removes the need for an optimizer", "D": "It makes models deterministic"}, "correct_answer": "B",
|
| 198 |
+
"explanation": "bfloat16 keeps fp32's exponent range while halving memory traffic and using tensor cores."}
|
| 199 |
+
],
|
| 200 |
+
"nlp-transformers": [
|
| 201 |
+
{"difficulty": "beginner", "concept": "tokenization", "question": "What does a tokenizer do?",
|
| 202 |
+
"options": {"A": "Trains the model", "B": "Splits text into units and maps them to integer IDs", "C": "Translates languages", "D": "Removes stop words only"}, "correct_answer": "B",
|
| 203 |
+
"explanation": "Tokenizers convert raw text into token IDs the model can embed."},
|
| 204 |
+
{"difficulty": "intermediate", "concept": "self-attention", "question": "In self-attention, attention weights are computed from:",
|
| 205 |
+
"options": {"A": "Queries and keys", "B": "Values only", "C": "Labels", "D": "Positional encodings only"}, "correct_answer": "A",
|
| 206 |
+
"explanation": "Weights are softmax(QKᵀ/√d); they then form a weighted sum of the values."},
|
| 207 |
+
{"difficulty": "advanced", "concept": "encoder vs decoder", "question": "Why do GPT-style decoders use a causal attention mask?",
|
| 208 |
+
"options": {"A": "To save memory", "B": "So each position cannot attend to future tokens during next-token prediction", "C": "To support longer contexts", "D": "To ignore padding only"}, "correct_answer": "B",
|
| 209 |
+
"explanation": "The causal mask prevents information leaking from future tokens during autoregressive training."}
|
| 210 |
+
],
|
| 211 |
+
"llm-agents": [
|
| 212 |
+
{"difficulty": "beginner", "concept": "retrieval-augmented generation", "question": "What is the main goal of RAG?",
|
| 213 |
+
"options": {"A": "To fine-tune the model", "B": "To ground answers in retrieved documents supplied at query time", "C": "To compress the model", "D": "To generate images"}, "correct_answer": "B",
|
| 214 |
+
"explanation": "RAG retrieves relevant context and adds it to the prompt so answers are grounded and current."},
|
| 215 |
+
{"difficulty": "intermediate", "concept": "tool/function calling", "question": "In tool calling, who actually executes the tool?",
|
| 216 |
+
"options": {"A": "The LLM itself", "B": "The application, after the model emits a structured tool request", "C": "The tokenizer", "D": "The user manually"}, "correct_answer": "B",
|
| 217 |
+
"explanation": "The model only proposes a call with arguments; your code runs it and returns the result."},
|
| 218 |
+
{"difficulty": "advanced", "concept": "agent graphs (LangGraph)", "question": "What does a LangGraph checkpointer provide?",
|
| 219 |
+
"options": {"A": "Faster tokenization", "B": "Persisted graph state per thread, enabling memory, resumption and human-in-the-loop", "C": "Model quantization", "D": "Automatic prompt writing"}, "correct_answer": "B",
|
| 220 |
+
"explanation": "Checkpointers save state after each step so conversations and workflows can resume from where they left off."}
|
| 221 |
+
]
|
| 222 |
+
}
|
backend/knowledge_tracker.py
DELETED
|
@@ -1,167 +0,0 @@
|
|
| 1 |
-
import math
|
| 2 |
-
from datetime import datetime, timedelta
|
| 3 |
-
from models import db, KnowledgeState, QuizAttempt
|
| 4 |
-
from config import Config
|
| 5 |
-
|
| 6 |
-
class KnowledgeTracker:
|
| 7 |
-
def __init__(self):
|
| 8 |
-
self.learning_rate = Config.LEARNING_RATE
|
| 9 |
-
self.forgetting_rate = Config.FORGETTING_RATE
|
| 10 |
-
|
| 11 |
-
def get_or_create_knowledge_state(self, user_id, topic_id):
|
| 12 |
-
"""Get or create knowledge state for a user-topic pair"""
|
| 13 |
-
state = KnowledgeState.query.filter_by(
|
| 14 |
-
user_id=user_id,
|
| 15 |
-
topic_id=topic_id
|
| 16 |
-
).first()
|
| 17 |
-
|
| 18 |
-
if not state:
|
| 19 |
-
state = KnowledgeState(
|
| 20 |
-
user_id=user_id,
|
| 21 |
-
topic_id=topic_id,
|
| 22 |
-
knowledge_level=Config.INITIAL_KNOWLEDGE,
|
| 23 |
-
confidence=0.0
|
| 24 |
-
)
|
| 25 |
-
db.session.add(state)
|
| 26 |
-
db.session.commit()
|
| 27 |
-
|
| 28 |
-
return state
|
| 29 |
-
|
| 30 |
-
def update_knowledge(self, user_id, topic_id, is_correct, difficulty, time_taken=None):
|
| 31 |
-
"""Update knowledge state based on quiz performance"""
|
| 32 |
-
state = self.get_or_create_knowledge_state(user_id, topic_id)
|
| 33 |
-
|
| 34 |
-
# Apply forgetting curve based on time since last practice (only if knowledge > 0)
|
| 35 |
-
if state.knowledge_level > 0:
|
| 36 |
-
time_diff = (datetime.utcnow() - state.last_practiced).days
|
| 37 |
-
if time_diff > 0:
|
| 38 |
-
forgetting_factor = math.exp(-self.forgetting_rate * time_diff)
|
| 39 |
-
state.knowledge_level *= forgetting_factor
|
| 40 |
-
|
| 41 |
-
# Update based on current performance
|
| 42 |
-
difficulty_weight = self._get_difficulty_weight(difficulty)
|
| 43 |
-
|
| 44 |
-
if is_correct:
|
| 45 |
-
# Increase knowledge level
|
| 46 |
-
delta = self.learning_rate * difficulty_weight * (1 - state.knowledge_level)
|
| 47 |
-
state.knowledge_level = min(1.0, state.knowledge_level + delta)
|
| 48 |
-
state.confidence = min(1.0, state.confidence + 0.1)
|
| 49 |
-
else:
|
| 50 |
-
# Decrease knowledge level slightly (only if there was knowledge to begin with)
|
| 51 |
-
if state.knowledge_level > 0:
|
| 52 |
-
delta = self.learning_rate * difficulty_weight * state.knowledge_level * 0.3
|
| 53 |
-
state.knowledge_level = max(0.0, state.knowledge_level - delta)
|
| 54 |
-
state.confidence = max(0.0, state.confidence - 0.1)
|
| 55 |
-
|
| 56 |
-
# Update metadata
|
| 57 |
-
state.last_practiced = datetime.utcnow()
|
| 58 |
-
state.practice_count += 1
|
| 59 |
-
|
| 60 |
-
db.session.commit()
|
| 61 |
-
|
| 62 |
-
return state
|
| 63 |
-
|
| 64 |
-
def _get_difficulty_weight(self, difficulty):
|
| 65 |
-
"""Get weight based on difficulty level"""
|
| 66 |
-
weights = {
|
| 67 |
-
'beginner': 0.7,
|
| 68 |
-
'intermediate': 1.0,
|
| 69 |
-
'advanced': 1.3
|
| 70 |
-
}
|
| 71 |
-
return weights.get(difficulty, 1.0)
|
| 72 |
-
|
| 73 |
-
def get_recommended_difficulty(self, user_id, topic_id):
|
| 74 |
-
"""Recommend difficulty level based on knowledge state"""
|
| 75 |
-
state = self.get_or_create_knowledge_state(user_id, topic_id)
|
| 76 |
-
|
| 77 |
-
if state.knowledge_level < 0.3:
|
| 78 |
-
return 'beginner'
|
| 79 |
-
elif state.knowledge_level < 0.7:
|
| 80 |
-
return 'intermediate'
|
| 81 |
-
else:
|
| 82 |
-
return 'advanced'
|
| 83 |
-
|
| 84 |
-
def get_next_topic(self, user_id, current_topic_id=None):
|
| 85 |
-
"""Recommend next topic to learn based on knowledge states"""
|
| 86 |
-
from models import Topic
|
| 87 |
-
|
| 88 |
-
# Get all topics
|
| 89 |
-
all_topics = Topic.query.all()
|
| 90 |
-
|
| 91 |
-
# Get user's knowledge states
|
| 92 |
-
knowledge_states = KnowledgeState.query.filter_by(user_id=user_id).all()
|
| 93 |
-
knowledge_map = {ks.topic_id: ks.knowledge_level for ks in knowledge_states}
|
| 94 |
-
|
| 95 |
-
# Score topics based on various factors
|
| 96 |
-
topic_scores = []
|
| 97 |
-
for topic in all_topics:
|
| 98 |
-
if topic.id == current_topic_id:
|
| 99 |
-
continue
|
| 100 |
-
|
| 101 |
-
score = 0
|
| 102 |
-
knowledge_level = knowledge_map.get(topic.id, 0)
|
| 103 |
-
|
| 104 |
-
# Prefer topics that haven't been started or are in progress
|
| 105 |
-
if knowledge_level == 0:
|
| 106 |
-
score += 3 # Prioritize unstarted topics
|
| 107 |
-
elif 0 < knowledge_level < 0.7:
|
| 108 |
-
score += 2 # Then in-progress topics
|
| 109 |
-
elif knowledge_level >= 0.7:
|
| 110 |
-
score += 0.5 # Lower priority for mastered topics
|
| 111 |
-
|
| 112 |
-
# Check prerequisites
|
| 113 |
-
if topic.prerequisites:
|
| 114 |
-
prereq_ids = [int(x.strip()) for x in topic.prerequisites.split(',') if x.strip()]
|
| 115 |
-
prereq_met = all(knowledge_map.get(pid, 0) > 0.5 for pid in prereq_ids)
|
| 116 |
-
if prereq_met:
|
| 117 |
-
score += 2
|
| 118 |
-
elif any(knowledge_map.get(pid, 0) > 0 for pid in prereq_ids):
|
| 119 |
-
score += 1 # Some prerequisites started
|
| 120 |
-
else:
|
| 121 |
-
score -= 1 # Prerequisites not met, but don't exclude completely
|
| 122 |
-
else:
|
| 123 |
-
score += 1 # No prerequisites, easier to start
|
| 124 |
-
|
| 125 |
-
topic_scores.append((topic, score))
|
| 126 |
-
|
| 127 |
-
# Sort by score and return top topic
|
| 128 |
-
topic_scores.sort(key=lambda x: x[1], reverse=True)
|
| 129 |
-
|
| 130 |
-
if topic_scores:
|
| 131 |
-
return topic_scores[0][0]
|
| 132 |
-
return None
|
| 133 |
-
|
| 134 |
-
def get_progress_summary(self, user_id):
|
| 135 |
-
"""Get overall learning progress for a user"""
|
| 136 |
-
knowledge_states = KnowledgeState.query.filter_by(user_id=user_id).all()
|
| 137 |
-
|
| 138 |
-
if not knowledge_states:
|
| 139 |
-
return {
|
| 140 |
-
'average_knowledge': 0,
|
| 141 |
-
'topics_mastered': 0,
|
| 142 |
-
'topics_in_progress': 0,
|
| 143 |
-
'total_practice_count': 0,
|
| 144 |
-
'weak_topics': [],
|
| 145 |
-
'strong_topics': []
|
| 146 |
-
}
|
| 147 |
-
|
| 148 |
-
total_knowledge = sum(ks.knowledge_level for ks in knowledge_states)
|
| 149 |
-
avg_knowledge = total_knowledge / len(knowledge_states)
|
| 150 |
-
|
| 151 |
-
mastered = [ks for ks in knowledge_states if ks.knowledge_level >= 0.8]
|
| 152 |
-
in_progress = [ks for ks in knowledge_states if 0 < ks.knowledge_level < 0.8]
|
| 153 |
-
weak = [ks for ks in knowledge_states if ks.knowledge_level <= 0.3 and ks.knowledge_level > 0]
|
| 154 |
-
not_started = [ks for ks in knowledge_states if ks.knowledge_level == 0]
|
| 155 |
-
|
| 156 |
-
total_practice = sum(ks.practice_count for ks in knowledge_states)
|
| 157 |
-
|
| 158 |
-
return {
|
| 159 |
-
'average_knowledge': round(avg_knowledge, 2),
|
| 160 |
-
'topics_mastered': len(mastered),
|
| 161 |
-
'topics_in_progress': len(in_progress),
|
| 162 |
-
'total_practice_count': total_practice,
|
| 163 |
-
'weak_topics': [{'id': ks.topic_id, 'level': round(ks.knowledge_level, 2)}
|
| 164 |
-
for ks in sorted(weak + not_started, key=lambda x: x.knowledge_level)[:5]],
|
| 165 |
-
'strong_topics': [{'id': ks.topic_id, 'level': round(ks.knowledge_level, 2)}
|
| 166 |
-
for ks in sorted(mastered, key=lambda x: x.knowledge_level, reverse=True)[:5]]
|
| 167 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/llm_service.py
DELETED
|
@@ -1,329 +0,0 @@
|
|
| 1 |
-
import google.generativeai as genai
|
| 2 |
-
from config import Config
|
| 3 |
-
import json
|
| 4 |
-
import time
|
| 5 |
-
|
| 6 |
-
class LLMService:
|
| 7 |
-
def __init__(self):
|
| 8 |
-
genai.configure(api_key=Config.GEMINI_API_KEY)
|
| 9 |
-
self.model = genai.GenerativeModel('gemini-2.0-flash')
|
| 10 |
-
self.generation_config = {
|
| 11 |
-
'temperature': 0.7,
|
| 12 |
-
'top_p': 0.8,
|
| 13 |
-
'top_k': 40,
|
| 14 |
-
'max_output_tokens': 2048,
|
| 15 |
-
}
|
| 16 |
-
|
| 17 |
-
# ============ AGENT-COMPATIBLE METHODS ============
|
| 18 |
-
|
| 19 |
-
def generate_lesson_with_prompt(self, topic_name, difficulty, knowledge_level, custom_prompt=None):
|
| 20 |
-
"""
|
| 21 |
-
Generate lesson with custom prompt (for Teaching Agent)
|
| 22 |
-
|
| 23 |
-
Args:
|
| 24 |
-
topic_name: str - Name of the topic
|
| 25 |
-
difficulty: str - Difficulty level
|
| 26 |
-
knowledge_level: float - Current knowledge (0-1)
|
| 27 |
-
custom_prompt: str - Custom prompt from Teaching Agent (optional)
|
| 28 |
-
|
| 29 |
-
Returns:
|
| 30 |
-
str - Generated lesson content
|
| 31 |
-
"""
|
| 32 |
-
if custom_prompt:
|
| 33 |
-
prompt = custom_prompt
|
| 34 |
-
else:
|
| 35 |
-
# Use default prompt structure
|
| 36 |
-
prompt = self._default_lesson_prompt(topic_name, difficulty, knowledge_level)
|
| 37 |
-
|
| 38 |
-
try:
|
| 39 |
-
response = self.model.generate_content(
|
| 40 |
-
prompt,
|
| 41 |
-
generation_config=self.generation_config
|
| 42 |
-
)
|
| 43 |
-
return response.text
|
| 44 |
-
except Exception as e:
|
| 45 |
-
print(f"Error generating lesson: {e}")
|
| 46 |
-
return self._get_fallback_lesson(topic_name, difficulty)
|
| 47 |
-
|
| 48 |
-
def generate_quiz_with_prompt(self, topic_name, num_questions, custom_prompt=None):
|
| 49 |
-
"""
|
| 50 |
-
Generate quiz with custom prompt (for Assessment Agent)
|
| 51 |
-
|
| 52 |
-
Args:
|
| 53 |
-
topic_name: str - Name of the topic
|
| 54 |
-
num_questions: int - Number of questions to generate
|
| 55 |
-
custom_prompt: str - Custom prompt from Assessment Agent (optional)
|
| 56 |
-
|
| 57 |
-
Returns:
|
| 58 |
-
list - Array of quiz questions
|
| 59 |
-
"""
|
| 60 |
-
if custom_prompt:
|
| 61 |
-
prompt = custom_prompt
|
| 62 |
-
else:
|
| 63 |
-
prompt = self._default_quiz_prompt(topic_name, num_questions)
|
| 64 |
-
|
| 65 |
-
try:
|
| 66 |
-
response = self.model.generate_content(
|
| 67 |
-
prompt,
|
| 68 |
-
generation_config=self.generation_config
|
| 69 |
-
)
|
| 70 |
-
text = response.text.strip()
|
| 71 |
-
|
| 72 |
-
# Extract JSON from response
|
| 73 |
-
if '```json' in text:
|
| 74 |
-
text = text.split('```json')[1].split('```')[0]
|
| 75 |
-
elif '```' in text:
|
| 76 |
-
text = text.split('```')[1].split('```')[0]
|
| 77 |
-
|
| 78 |
-
questions = json.loads(text.strip())
|
| 79 |
-
|
| 80 |
-
# Validate structure
|
| 81 |
-
if isinstance(questions, list) and len(questions) > 0:
|
| 82 |
-
return questions
|
| 83 |
-
else:
|
| 84 |
-
raise ValueError("Invalid JSON structure")
|
| 85 |
-
|
| 86 |
-
except Exception as e:
|
| 87 |
-
print(f"Error generating quiz: {e}")
|
| 88 |
-
return self._get_fallback_quiz(topic_name, 'intermediate', num_questions)
|
| 89 |
-
|
| 90 |
-
def generate_hint_with_context(self, question, context, hint_level='moderate'):
|
| 91 |
-
"""
|
| 92 |
-
Generate hint with specific context (for Tutor Agent)
|
| 93 |
-
|
| 94 |
-
Args:
|
| 95 |
-
question: str - Student's question
|
| 96 |
-
context: dict - Context information
|
| 97 |
-
hint_level: str - Level of hint detail (subtle, moderate, detailed)
|
| 98 |
-
|
| 99 |
-
Returns:
|
| 100 |
-
str - Generated hint
|
| 101 |
-
"""
|
| 102 |
-
challenge = context.get('challenge', '')
|
| 103 |
-
attempt_count = context.get('attempt_count', 1)
|
| 104 |
-
|
| 105 |
-
hint_instructions = {
|
| 106 |
-
'subtle': 'Provide a gentle nudge without revealing the solution. Ask guiding questions.',
|
| 107 |
-
'moderate': 'Explain the concept and provide a partial solution or approach.',
|
| 108 |
-
'detailed': 'Provide clear explanation with example code, but encourage student to try.'
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
prompt = f"""
|
| 112 |
-
You are a supportive programming tutor.
|
| 113 |
-
|
| 114 |
-
STUDENT CONTEXT:
|
| 115 |
-
- Question: {question}
|
| 116 |
-
- Challenge: {challenge}
|
| 117 |
-
- Previous attempts: {attempt_count}
|
| 118 |
-
|
| 119 |
-
INSTRUCTIONS:
|
| 120 |
-
{hint_instructions.get(hint_level, hint_instructions['moderate'])}
|
| 121 |
-
|
| 122 |
-
Be encouraging and educational. Keep response 2-4 sentences.
|
| 123 |
-
"""
|
| 124 |
-
|
| 125 |
-
try:
|
| 126 |
-
response = self.model.generate_content(
|
| 127 |
-
prompt,
|
| 128 |
-
generation_config=self.generation_config
|
| 129 |
-
)
|
| 130 |
-
return response.text
|
| 131 |
-
except Exception as e:
|
| 132 |
-
print(f"Error generating hint: {e}")
|
| 133 |
-
return "Think about what you've learned. Break the problem into smaller steps!"
|
| 134 |
-
|
| 135 |
-
# ============ LEGACY METHODS (Still supported) ============
|
| 136 |
-
|
| 137 |
-
def generate_lesson(self, topic_name, difficulty, knowledge_level):
|
| 138 |
-
"""
|
| 139 |
-
Generate personalized lesson content (Legacy method)
|
| 140 |
-
Calls the agent-compatible method internally
|
| 141 |
-
"""
|
| 142 |
-
return self.generate_lesson_with_prompt(
|
| 143 |
-
topic_name,
|
| 144 |
-
difficulty,
|
| 145 |
-
knowledge_level,
|
| 146 |
-
custom_prompt=None
|
| 147 |
-
)
|
| 148 |
-
|
| 149 |
-
def generate_quiz_questions(self, topic_name, difficulty, num_questions=5):
|
| 150 |
-
"""
|
| 151 |
-
Generate quiz questions for a topic (Legacy method)
|
| 152 |
-
Calls the agent-compatible method internally
|
| 153 |
-
"""
|
| 154 |
-
prompt = self._default_quiz_prompt(topic_name, num_questions, difficulty)
|
| 155 |
-
return self.generate_quiz_with_prompt(topic_name, num_questions, prompt)
|
| 156 |
-
|
| 157 |
-
def explain_answer(self, question, user_answer, correct_answer, topic):
|
| 158 |
-
"""
|
| 159 |
-
Generate explanation for why an answer is correct/incorrect
|
| 160 |
-
Used by Assessment Agent
|
| 161 |
-
"""
|
| 162 |
-
prompt = f"""
|
| 163 |
-
Topic: {topic}
|
| 164 |
-
Question: {question}
|
| 165 |
-
Student's Answer: {user_answer}
|
| 166 |
-
Correct Answer: {correct_answer}
|
| 167 |
-
|
| 168 |
-
Provide a clear, encouraging explanation (2-3 sentences) about:
|
| 169 |
-
1. Why the correct answer is right
|
| 170 |
-
2. If wrong, what misconception the student might have
|
| 171 |
-
3. A tip to remember this concept
|
| 172 |
-
|
| 173 |
-
Be supportive and educational.
|
| 174 |
-
"""
|
| 175 |
-
|
| 176 |
-
try:
|
| 177 |
-
response = self.model.generate_content(
|
| 178 |
-
prompt,
|
| 179 |
-
generation_config=self.generation_config
|
| 180 |
-
)
|
| 181 |
-
return response.text
|
| 182 |
-
except Exception as e:
|
| 183 |
-
print(f"Error generating explanation: {e}")
|
| 184 |
-
if user_answer == correct_answer:
|
| 185 |
-
return f"Correct! The answer {correct_answer} demonstrates your understanding of {topic}."
|
| 186 |
-
else:
|
| 187 |
-
return f"The correct answer is {correct_answer}. Review the key concepts of {topic} to strengthen your understanding."
|
| 188 |
-
|
| 189 |
-
def generate_study_tips(self, weak_topics, strong_topics):
|
| 190 |
-
"""
|
| 191 |
-
Generate personalized study recommendations
|
| 192 |
-
Used by Recommendation Agent and dashboard
|
| 193 |
-
"""
|
| 194 |
-
weak_str = ', '.join(weak_topics) if weak_topics else 'None'
|
| 195 |
-
strong_str = ', '.join(strong_topics) if strong_topics else 'None'
|
| 196 |
-
|
| 197 |
-
prompt = f"""
|
| 198 |
-
Based on a student's performance:
|
| 199 |
-
|
| 200 |
-
Weak areas: {weak_str}
|
| 201 |
-
Strong areas: {strong_str}
|
| 202 |
-
|
| 203 |
-
Provide 3-5 personalized, actionable study tips.
|
| 204 |
-
|
| 205 |
-
FORMATTING RULES:
|
| 206 |
-
- Start each tip with a dash (-)
|
| 207 |
-
- Keep each tip to 2-3 sentences
|
| 208 |
-
- Use **bold** for key terms
|
| 209 |
-
- Be specific and encouraging
|
| 210 |
-
- Make tips actionable
|
| 211 |
-
|
| 212 |
-
Format as simple bullet points with dashes.
|
| 213 |
-
"""
|
| 214 |
-
|
| 215 |
-
try:
|
| 216 |
-
response = self.model.generate_content(
|
| 217 |
-
prompt,
|
| 218 |
-
generation_config=self.generation_config
|
| 219 |
-
)
|
| 220 |
-
return response.text
|
| 221 |
-
except Exception as e:
|
| 222 |
-
print(f"Error generating tips: {e}")
|
| 223 |
-
return "- Practice regularly with focused study sessions\n- Review weak topics daily\n- Build on your strengths\n- Take breaks to avoid burnout\n- Track your progress"
|
| 224 |
-
|
| 225 |
-
# ============ PRIVATE HELPER METHODS ============
|
| 226 |
-
|
| 227 |
-
def _default_lesson_prompt(self, topic_name, difficulty, knowledge_level):
|
| 228 |
-
"""Default lesson prompt structure"""
|
| 229 |
-
return f"""
|
| 230 |
-
Create a comprehensive lesson on "{topic_name}" for a student at {difficulty} level
|
| 231 |
-
with current knowledge level of {knowledge_level*100:.0f}%.
|
| 232 |
-
|
| 233 |
-
Structure the lesson as follows:
|
| 234 |
-
|
| 235 |
-
## Introduction
|
| 236 |
-
Brief overview (2-3 sentences)
|
| 237 |
-
|
| 238 |
-
## Core Concepts
|
| 239 |
-
Main ideas explained clearly with examples
|
| 240 |
-
|
| 241 |
-
## Practical Examples
|
| 242 |
-
Real code or scenarios (use proper formatting)
|
| 243 |
-
|
| 244 |
-
## Real-World Applications
|
| 245 |
-
Where this is used in industry
|
| 246 |
-
|
| 247 |
-
## Key Takeaways
|
| 248 |
-
3-5 bullet points summarizing main ideas
|
| 249 |
-
|
| 250 |
-
## Practice Challenge
|
| 251 |
-
ONE simple coding exercise that students can solve.
|
| 252 |
-
Format: "Write a Python program that [task description]. Expected output: [example]"
|
| 253 |
-
Make it achievable for {difficulty} level students.
|
| 254 |
-
|
| 255 |
-
FORMATTING RULES:
|
| 256 |
-
- Use ## for main headings, ### for subheadings
|
| 257 |
-
- Keep paragraphs SHORT (2-3 sentences max)
|
| 258 |
-
- Use bullet points (-) for lists
|
| 259 |
-
- Use **bold** for important terms
|
| 260 |
-
- Use code blocks with ```python for code examples
|
| 261 |
-
- Keep total length 400-600 words
|
| 262 |
-
- Make it engaging and easy to scan
|
| 263 |
-
- For Practice Challenge, give clear task and expected output
|
| 264 |
-
"""
|
| 265 |
-
|
| 266 |
-
def _default_quiz_prompt(self, topic_name, num_questions, difficulty='intermediate'):
|
| 267 |
-
"""Default quiz prompt structure"""
|
| 268 |
-
return f"""
|
| 269 |
-
Generate {num_questions} multiple-choice questions on "{topic_name}" at {difficulty} level.
|
| 270 |
-
|
| 271 |
-
For each question, provide:
|
| 272 |
-
1. The question
|
| 273 |
-
2. Four options (A, B, C, D)
|
| 274 |
-
3. The correct answer (letter only: A, B, C, or D)
|
| 275 |
-
4. A brief explanation
|
| 276 |
-
|
| 277 |
-
Return ONLY a valid JSON array with this exact structure:
|
| 278 |
-
[
|
| 279 |
-
{{
|
| 280 |
-
"question": "Question text here?",
|
| 281 |
-
"options": {{
|
| 282 |
-
"A": "Option A text",
|
| 283 |
-
"B": "Option B text",
|
| 284 |
-
"C": "Option C text",
|
| 285 |
-
"D": "Option D text"
|
| 286 |
-
}},
|
| 287 |
-
"correct_answer": "A",
|
| 288 |
-
"explanation": "Explanation here"
|
| 289 |
-
}}
|
| 290 |
-
]
|
| 291 |
-
|
| 292 |
-
Return ONLY the JSON array, no other text.
|
| 293 |
-
"""
|
| 294 |
-
|
| 295 |
-
def _get_fallback_lesson(self, topic_name, difficulty):
|
| 296 |
-
"""Fallback lesson content when API fails"""
|
| 297 |
-
return f"""
|
| 298 |
-
<h2>Introduction to {topic_name}</h2>
|
| 299 |
-
<p>Welcome to this {difficulty} level lesson on {topic_name}. This is an important topic that will help you build your knowledge.</p>
|
| 300 |
-
<h3>Core Concepts</h3>
|
| 301 |
-
<p>{topic_name} is a fundamental concept that requires understanding and practice. Let's break it down into manageable parts.</p>
|
| 302 |
-
<h3>Key Points to Remember</h3>
|
| 303 |
-
<ul>
|
| 304 |
-
<li>Start with the basics and build gradually</li>
|
| 305 |
-
<li>Practice regularly to reinforce learning</li>
|
| 306 |
-
<li>Apply concepts to real-world scenarios</li>
|
| 307 |
-
<li>Review and revise frequently</li>
|
| 308 |
-
</ul>
|
| 309 |
-
<h3>Next Steps</h3>
|
| 310 |
-
<p>Take the quiz to test your understanding and track your progress. Don't worry if you don't get everything right the first time - learning is a journey!</p>
|
| 311 |
-
<p><em>Note: This is a basic lesson. For detailed content, please check your internet connection and API settings.</em></p>
|
| 312 |
-
"""
|
| 313 |
-
|
| 314 |
-
def _get_fallback_quiz(self, topic_name, difficulty, num_questions):
|
| 315 |
-
"""Fallback quiz when API fails"""
|
| 316 |
-
questions = []
|
| 317 |
-
for i in range(min(num_questions, 3)):
|
| 318 |
-
questions.append({
|
| 319 |
-
"question": f"Sample question {i+1} about {topic_name} ({difficulty} level)?",
|
| 320 |
-
"options": {
|
| 321 |
-
"A": "This is option A",
|
| 322 |
-
"B": "This is option B",
|
| 323 |
-
"C": "This is option C",
|
| 324 |
-
"D": "This is option D"
|
| 325 |
-
},
|
| 326 |
-
"correct_answer": "A",
|
| 327 |
-
"explanation": f"This is a sample question for {topic_name}. Practice with real content by ensuring your API connection is working."
|
| 328 |
-
})
|
| 329 |
-
return questions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/ml/__init__.py
ADDED
|
File without changes
|
backend/ml/artifacts/bkt_params.json
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"topics": {
|
| 3 |
+
"python-basics": {
|
| 4 |
+
"p_init": 0.1,
|
| 5 |
+
"p_learn": 0.02,
|
| 6 |
+
"p_guess": 0.35,
|
| 7 |
+
"p_slip": 0.24
|
| 8 |
+
},
|
| 9 |
+
"control-flow": {
|
| 10 |
+
"p_init": 0.1,
|
| 11 |
+
"p_learn": 0.02,
|
| 12 |
+
"p_guess": 0.35,
|
| 13 |
+
"p_slip": 0.24
|
| 14 |
+
},
|
| 15 |
+
"functions": {
|
| 16 |
+
"p_init": 0.05,
|
| 17 |
+
"p_learn": 0.05,
|
| 18 |
+
"p_guess": 0.3,
|
| 19 |
+
"p_slip": 0.24
|
| 20 |
+
},
|
| 21 |
+
"data-structures": {
|
| 22 |
+
"p_init": 0.05,
|
| 23 |
+
"p_learn": 0.02,
|
| 24 |
+
"p_guess": 0.25,
|
| 25 |
+
"p_slip": 0.3
|
| 26 |
+
},
|
| 27 |
+
"oop": {
|
| 28 |
+
"p_init": 0.05,
|
| 29 |
+
"p_learn": 0.02,
|
| 30 |
+
"p_guess": 0.25,
|
| 31 |
+
"p_slip": 0.3
|
| 32 |
+
},
|
| 33 |
+
"error-handling-testing": {
|
| 34 |
+
"p_init": 0.02,
|
| 35 |
+
"p_learn": 0.02,
|
| 36 |
+
"p_guess": 0.25,
|
| 37 |
+
"p_slip": 0.3
|
| 38 |
+
},
|
| 39 |
+
"algorithms": {
|
| 40 |
+
"p_init": 0.02,
|
| 41 |
+
"p_learn": 0.02,
|
| 42 |
+
"p_guess": 0.25,
|
| 43 |
+
"p_slip": 0.3
|
| 44 |
+
},
|
| 45 |
+
"web-fundamentals": {
|
| 46 |
+
"p_init": 0.1,
|
| 47 |
+
"p_learn": 0.05,
|
| 48 |
+
"p_guess": 0.35,
|
| 49 |
+
"p_slip": 0.24
|
| 50 |
+
},
|
| 51 |
+
"javascript-dom": {
|
| 52 |
+
"p_init": 0.05,
|
| 53 |
+
"p_learn": 0.02,
|
| 54 |
+
"p_guess": 0.25,
|
| 55 |
+
"p_slip": 0.3
|
| 56 |
+
},
|
| 57 |
+
"rest-apis": {
|
| 58 |
+
"p_init": 0.02,
|
| 59 |
+
"p_learn": 0.02,
|
| 60 |
+
"p_guess": 0.25,
|
| 61 |
+
"p_slip": 0.3
|
| 62 |
+
},
|
| 63 |
+
"database-design": {
|
| 64 |
+
"p_init": 0.05,
|
| 65 |
+
"p_learn": 0.02,
|
| 66 |
+
"p_guess": 0.3,
|
| 67 |
+
"p_slip": 0.24
|
| 68 |
+
},
|
| 69 |
+
"sql-querying": {
|
| 70 |
+
"p_init": 0.02,
|
| 71 |
+
"p_learn": 0.02,
|
| 72 |
+
"p_guess": 0.25,
|
| 73 |
+
"p_slip": 0.3
|
| 74 |
+
},
|
| 75 |
+
"statistics": {
|
| 76 |
+
"p_init": 0.05,
|
| 77 |
+
"p_learn": 0.02,
|
| 78 |
+
"p_guess": 0.3,
|
| 79 |
+
"p_slip": 0.24
|
| 80 |
+
},
|
| 81 |
+
"numpy-pandas": {
|
| 82 |
+
"p_init": 0.02,
|
| 83 |
+
"p_learn": 0.02,
|
| 84 |
+
"p_guess": 0.25,
|
| 85 |
+
"p_slip": 0.3
|
| 86 |
+
},
|
| 87 |
+
"ml-basics": {
|
| 88 |
+
"p_init": 0.02,
|
| 89 |
+
"p_learn": 0.02,
|
| 90 |
+
"p_guess": 0.25,
|
| 91 |
+
"p_slip": 0.3
|
| 92 |
+
},
|
| 93 |
+
"model-evaluation": {
|
| 94 |
+
"p_init": 0.02,
|
| 95 |
+
"p_learn": 0.02,
|
| 96 |
+
"p_guess": 0.25,
|
| 97 |
+
"p_slip": 0.3
|
| 98 |
+
},
|
| 99 |
+
"neural-networks": {
|
| 100 |
+
"p_init": 0.02,
|
| 101 |
+
"p_learn": 0.02,
|
| 102 |
+
"p_guess": 0.25,
|
| 103 |
+
"p_slip": 0.3
|
| 104 |
+
},
|
| 105 |
+
"deep-learning-pytorch": {
|
| 106 |
+
"p_init": 0.02,
|
| 107 |
+
"p_learn": 0.02,
|
| 108 |
+
"p_guess": 0.25,
|
| 109 |
+
"p_slip": 0.3
|
| 110 |
+
},
|
| 111 |
+
"nlp-transformers": {
|
| 112 |
+
"p_init": 0.02,
|
| 113 |
+
"p_learn": 0.02,
|
| 114 |
+
"p_guess": 0.25,
|
| 115 |
+
"p_slip": 0.3
|
| 116 |
+
},
|
| 117 |
+
"llm-agents": {
|
| 118 |
+
"p_init": 0.02,
|
| 119 |
+
"p_learn": 0.02,
|
| 120 |
+
"p_guess": 0.25,
|
| 121 |
+
"p_slip": 0.3
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
}
|
backend/ml/artifacts/kt_meta.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"topics": [
|
| 3 |
+
"python-basics",
|
| 4 |
+
"control-flow",
|
| 5 |
+
"functions",
|
| 6 |
+
"data-structures",
|
| 7 |
+
"oop",
|
| 8 |
+
"error-handling-testing",
|
| 9 |
+
"algorithms",
|
| 10 |
+
"web-fundamentals",
|
| 11 |
+
"javascript-dom",
|
| 12 |
+
"rest-apis",
|
| 13 |
+
"database-design",
|
| 14 |
+
"sql-querying",
|
| 15 |
+
"statistics",
|
| 16 |
+
"numpy-pandas",
|
| 17 |
+
"ml-basics",
|
| 18 |
+
"model-evaluation",
|
| 19 |
+
"neural-networks",
|
| 20 |
+
"deep-learning-pytorch",
|
| 21 |
+
"nlp-transformers",
|
| 22 |
+
"llm-agents"
|
| 23 |
+
],
|
| 24 |
+
"difficulties": [
|
| 25 |
+
"beginner",
|
| 26 |
+
"intermediate",
|
| 27 |
+
"advanced"
|
| 28 |
+
],
|
| 29 |
+
"max_len": 200,
|
| 30 |
+
"gap_edges_hours": [
|
| 31 |
+
1,
|
| 32 |
+
24,
|
| 33 |
+
72,
|
| 34 |
+
168,
|
| 35 |
+
720
|
| 36 |
+
],
|
| 37 |
+
"architecture": "KTTransformer",
|
| 38 |
+
"d_model": 128,
|
| 39 |
+
"layers": 3,
|
| 40 |
+
"heads": 4,
|
| 41 |
+
"trained_at": "2026-10-05T13:26:25",
|
| 42 |
+
"metrics": {
|
| 43 |
+
"val_auc": 0.6918472296794957,
|
| 44 |
+
"test_auc": 0.6925657955356248,
|
| 45 |
+
"bkt_test_auc": 0.6542,
|
| 46 |
+
"dkt_test_auc": 0.6891,
|
| 47 |
+
"oracle_auc": 0.7193106599607085,
|
| 48 |
+
"legacy_v1_test_auc": 0.6067,
|
| 49 |
+
"baseline_note": "baselines from training/results/curriculum.json (same seed/split)"
|
| 50 |
+
}
|
| 51 |
+
}
|
backend/ml/artifacts/kt_model.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c283f9d678a3e5538985da80d1f8e64b689039a06e9f427b05b14559ff1c72b2
|
| 3 |
+
size 2738226
|
backend/ml/bandit.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Contextual Thompson-sampling bandit for teaching-strategy selection.
|
| 3 |
+
|
| 4 |
+
Arms are teaching strategies (scaffolding, direct_instruction, ...). Context is a coarse
|
| 5 |
+
learner bucket (knowledge low/mid/high). Each (bucket, arm) keeps a Beta(alpha, beta)
|
| 6 |
+
posterior over "the learner answers the follow-up quiz correctly".
|
| 7 |
+
|
| 8 |
+
Priors come from the expert knowledge base (effectiveness_score) plus a bonus for the
|
| 9 |
+
strategy the pedagogical rules prefer, so cold-start behaviour matches the rule engine
|
| 10 |
+
and real learner outcomes progressively take over.
|
| 11 |
+
"""
|
| 12 |
+
import random
|
| 13 |
+
|
| 14 |
+
from models import AgentKnowledge, db
|
| 15 |
+
|
| 16 |
+
PRIOR_STRENGTH = 4.0
|
| 17 |
+
RULE_BONUS = 2.0
|
| 18 |
+
AGENT_TYPE = 'teaching'
|
| 19 |
+
KNOWLEDGE_TYPE = 'bandit_arm'
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def context_bucket(knowledge_level):
|
| 23 |
+
if knowledge_level < 0.35:
|
| 24 |
+
return 'low'
|
| 25 |
+
if knowledge_level < 0.7:
|
| 26 |
+
return 'mid'
|
| 27 |
+
return 'high'
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class StrategyBandit:
|
| 31 |
+
def __init__(self, strategies, rng=None):
|
| 32 |
+
self.strategies = {s['name']: s for s in strategies}
|
| 33 |
+
self.rng = rng or random.Random()
|
| 34 |
+
|
| 35 |
+
def _arm(self, bucket, name, rule_choice=None):
|
| 36 |
+
key = f'{bucket}:{name}'
|
| 37 |
+
row = AgentKnowledge.query.filter_by(agent_type=AGENT_TYPE, knowledge_type=KNOWLEDGE_TYPE, key=key).first()
|
| 38 |
+
if row is None:
|
| 39 |
+
eff = float(self.strategies.get(name, {}).get('effectiveness_score', 0.5))
|
| 40 |
+
alpha = 1 + PRIOR_STRENGTH * eff + (RULE_BONUS if name == rule_choice else 0.0)
|
| 41 |
+
beta = 1 + PRIOR_STRENGTH * (1 - eff)
|
| 42 |
+
row = AgentKnowledge(agent_type=AGENT_TYPE, knowledge_type=KNOWLEDGE_TYPE, key=key,
|
| 43 |
+
content={'strategy': name, 'bucket': bucket, 'alpha': alpha, 'beta': beta},
|
| 44 |
+
effectiveness_score=alpha / (alpha + beta), usage_count=0)
|
| 45 |
+
db.session.add(row)
|
| 46 |
+
return row
|
| 47 |
+
|
| 48 |
+
def select(self, knowledge_level, rule_choice=None):
|
| 49 |
+
bucket = context_bucket(knowledge_level)
|
| 50 |
+
samples = {}
|
| 51 |
+
for name in self.strategies:
|
| 52 |
+
c = self._arm(bucket, name, rule_choice).content
|
| 53 |
+
samples[name] = self.rng.betavariate(c['alpha'], c['beta'])
|
| 54 |
+
db.session.commit()
|
| 55 |
+
best = max(samples, key=samples.get)
|
| 56 |
+
return best, bucket, samples
|
| 57 |
+
|
| 58 |
+
def update(self, bucket, name, reward, weight=1.0):
|
| 59 |
+
"""reward in [0, 1] (fractional Beta update); weight < 1 for partial evidence."""
|
| 60 |
+
row = self._arm(bucket, name)
|
| 61 |
+
c = dict(row.content)
|
| 62 |
+
c['alpha'] += weight * reward
|
| 63 |
+
c['beta'] += weight * (1 - reward)
|
| 64 |
+
row.content = c
|
| 65 |
+
row.usage_count = (row.usage_count or 0) + 1
|
| 66 |
+
row.effectiveness_score = c['alpha'] / (c['alpha'] + c['beta'])
|
| 67 |
+
db.session.commit()
|
| 68 |
+
|
| 69 |
+
def summary(self):
|
| 70 |
+
rows = AgentKnowledge.query.filter_by(agent_type=AGENT_TYPE, knowledge_type=KNOWLEDGE_TYPE).all()
|
| 71 |
+
return [{'bucket': r.content['bucket'], 'strategy': r.content['strategy'],
|
| 72 |
+
'expected_success': round(r.effectiveness_score, 3), 'pulls': r.usage_count} for r in rows]
|
backend/ml/bkt.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Bayesian Knowledge Tracing (Corbett & Anderson, 1995) with difficulty-aware guess/slip.
|
| 3 |
+
|
| 4 |
+
Each topic has four parameters:
|
| 5 |
+
p_init - P(L0): probability the skill is already known
|
| 6 |
+
p_learn - P(T): probability of learning on each practice opportunity
|
| 7 |
+
p_guess - P(G): probability of answering correctly while unmastered
|
| 8 |
+
p_slip - P(S): probability of answering incorrectly while mastered
|
| 9 |
+
|
| 10 |
+
Per-topic parameters are fitted offline (training/fit_bkt.py) and loaded from
|
| 11 |
+
ml/artifacts/bkt_params.json. Missing topics fall back to DEFAULT_PARAMS.
|
| 12 |
+
"""
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
from dataclasses import dataclass, asdict
|
| 16 |
+
|
| 17 |
+
DEFAULT_PARAMS = {'p_init': 0.10, 'p_learn': 0.15, 'p_guess': 0.22, 'p_slip': 0.10}
|
| 18 |
+
|
| 19 |
+
# Easier questions are easier to guess and harder to slip on; harder ones the opposite.
|
| 20 |
+
GUESS_SCALE = {'beginner': 1.3, 'intermediate': 1.0, 'advanced': 0.7}
|
| 21 |
+
SLIP_SCALE = {'beginner': 0.7, 'intermediate': 1.0, 'advanced': 1.4}
|
| 22 |
+
LEARN_SCALE = {'beginner': 0.8, 'intermediate': 1.0, 'advanced': 1.2}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass
|
| 26 |
+
class BKTParams:
|
| 27 |
+
p_init: float
|
| 28 |
+
p_learn: float
|
| 29 |
+
p_guess: float
|
| 30 |
+
p_slip: float
|
| 31 |
+
|
| 32 |
+
def for_difficulty(self, difficulty):
|
| 33 |
+
return BKTParams(
|
| 34 |
+
p_init=self.p_init,
|
| 35 |
+
p_learn=min(0.6, self.p_learn * LEARN_SCALE.get(difficulty, 1.0)),
|
| 36 |
+
p_guess=min(0.45, self.p_guess * GUESS_SCALE.get(difficulty, 1.0)),
|
| 37 |
+
p_slip=min(0.35, self.p_slip * SLIP_SCALE.get(difficulty, 1.0)),
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class BKTModel:
|
| 42 |
+
def __init__(self, params_path=None):
|
| 43 |
+
self.params = {}
|
| 44 |
+
if params_path and os.path.exists(params_path):
|
| 45 |
+
with open(params_path) as f:
|
| 46 |
+
raw = json.load(f)
|
| 47 |
+
self.params = {slug: BKTParams(**p) for slug, p in raw.get('topics', raw).items()}
|
| 48 |
+
|
| 49 |
+
def get(self, slug):
|
| 50 |
+
return self.params.get(slug) or BKTParams(**DEFAULT_PARAMS)
|
| 51 |
+
|
| 52 |
+
def prior(self, slug):
|
| 53 |
+
return self.get(slug).p_init
|
| 54 |
+
|
| 55 |
+
def update(self, p_mastery, is_correct, slug, difficulty='intermediate'):
|
| 56 |
+
"""One observation -> posterior P(mastered) after the learning transition."""
|
| 57 |
+
p = self.get(slug).for_difficulty(difficulty)
|
| 58 |
+
if is_correct:
|
| 59 |
+
num = p_mastery * (1 - p.p_slip)
|
| 60 |
+
den = num + (1 - p_mastery) * p.p_guess
|
| 61 |
+
else:
|
| 62 |
+
num = p_mastery * p.p_slip
|
| 63 |
+
den = num + (1 - p_mastery) * (1 - p.p_guess)
|
| 64 |
+
posterior = num / den if den > 0 else p_mastery
|
| 65 |
+
return min(0.999, posterior + (1 - posterior) * p.p_learn)
|
| 66 |
+
|
| 67 |
+
def p_correct(self, p_mastery, slug, difficulty='intermediate'):
|
| 68 |
+
"""Predicted probability of a correct answer at the given difficulty."""
|
| 69 |
+
p = self.get(slug).for_difficulty(difficulty)
|
| 70 |
+
return p_mastery * (1 - p.p_slip) + (1 - p_mastery) * p.p_guess
|
| 71 |
+
|
| 72 |
+
def to_json(self):
|
| 73 |
+
return {slug: asdict(p) for slug, p in self.params.items()}
|
backend/ml/kt_runtime.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
CPU inference for the transformer knowledge-tracing model (trained in training/train_kt.py
|
| 3 |
+
and exported to ONNX). Given a learner's interaction history it predicts, for every topic
|
| 4 |
+
and difficulty, the probability that the *next* answer will be correct.
|
| 5 |
+
|
| 6 |
+
Uses onnxruntime only (no torch) so the deployed image stays small. If the model or
|
| 7 |
+
onnxruntime is unavailable, `available` is False and callers fall back to BKT.
|
| 8 |
+
"""
|
| 9 |
+
import json
|
| 10 |
+
import logging
|
| 11 |
+
import os
|
| 12 |
+
import threading
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
log = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
# Hours since previous interaction -> bucket id (0 is reserved for BOS / unknown)
|
| 19 |
+
GAP_EDGES_HOURS = [1, 24, 72, 168, 720]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def gap_bucket(hours):
|
| 23 |
+
if hours is None:
|
| 24 |
+
return 0
|
| 25 |
+
for i, edge in enumerate(GAP_EDGES_HOURS):
|
| 26 |
+
if hours < edge:
|
| 27 |
+
return i + 1
|
| 28 |
+
return len(GAP_EDGES_HOURS) + 1
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class KTRuntime:
|
| 32 |
+
def __init__(self, artifacts_dir):
|
| 33 |
+
self.artifacts_dir = artifacts_dir
|
| 34 |
+
self._session = None
|
| 35 |
+
self._meta = None
|
| 36 |
+
self._lock = threading.Lock()
|
| 37 |
+
self._loaded = False
|
| 38 |
+
|
| 39 |
+
def _load(self):
|
| 40 |
+
with self._lock:
|
| 41 |
+
if self._loaded:
|
| 42 |
+
return
|
| 43 |
+
self._loaded = True
|
| 44 |
+
model_path = os.path.join(self.artifacts_dir, 'kt_model.onnx')
|
| 45 |
+
meta_path = os.path.join(self.artifacts_dir, 'kt_meta.json')
|
| 46 |
+
if not (os.path.exists(model_path) and os.path.exists(meta_path)):
|
| 47 |
+
log.info('KT model artifacts not found; using BKT only')
|
| 48 |
+
return
|
| 49 |
+
try:
|
| 50 |
+
import onnxruntime as ort
|
| 51 |
+
opts = ort.SessionOptions()
|
| 52 |
+
opts.intra_op_num_threads = 1
|
| 53 |
+
opts.inter_op_num_threads = 1
|
| 54 |
+
self._session = ort.InferenceSession(model_path, opts, providers=['CPUExecutionProvider'])
|
| 55 |
+
with open(meta_path) as f:
|
| 56 |
+
self._meta = json.load(f)
|
| 57 |
+
log.info('Loaded KT model (%s topics, val AUC %.3f)', len(self._meta['topics']),
|
| 58 |
+
self._meta.get('metrics', {}).get('val_auc', float('nan')))
|
| 59 |
+
except Exception as exc: # pragma: no cover - defensive
|
| 60 |
+
log.warning('Failed to load KT model: %s', exc)
|
| 61 |
+
self._session = None
|
| 62 |
+
|
| 63 |
+
@property
|
| 64 |
+
def available(self):
|
| 65 |
+
self._load()
|
| 66 |
+
return self._session is not None
|
| 67 |
+
|
| 68 |
+
@property
|
| 69 |
+
def meta(self):
|
| 70 |
+
self._load()
|
| 71 |
+
return self._meta or {}
|
| 72 |
+
|
| 73 |
+
def predict(self, history):
|
| 74 |
+
"""
|
| 75 |
+
history: list of dicts {slug, difficulty, correct, timestamp(datetime)} ordered by time.
|
| 76 |
+
returns: {slug: {difficulty: p_correct}} or None if model unavailable.
|
| 77 |
+
"""
|
| 78 |
+
if not self.available:
|
| 79 |
+
return None
|
| 80 |
+
meta = self._meta
|
| 81 |
+
topic_index = {s: i for i, s in enumerate(meta['topics'])}
|
| 82 |
+
diff_index = {d: i for i, d in enumerate(meta['difficulties'])}
|
| 83 |
+
max_len = meta['max_len'] - 1 # leave room for BOS
|
| 84 |
+
|
| 85 |
+
events = [h for h in history if h['slug'] in topic_index][-max_len:]
|
| 86 |
+
n_topics = len(meta['topics'])
|
| 87 |
+
topics, diffs, resp, gaps = [n_topics], [0], [2], [0] # BOS token
|
| 88 |
+
prev_ts = None
|
| 89 |
+
for e in events:
|
| 90 |
+
topics.append(topic_index[e['slug']])
|
| 91 |
+
diffs.append(diff_index.get(e['difficulty'], 1))
|
| 92 |
+
resp.append(1 if e['correct'] else 0)
|
| 93 |
+
hours = None if prev_ts is None else (e['timestamp'] - prev_ts).total_seconds() / 3600
|
| 94 |
+
gaps.append(gap_bucket(hours))
|
| 95 |
+
prev_ts = e['timestamp']
|
| 96 |
+
|
| 97 |
+
feeds = {
|
| 98 |
+
'topic': np.asarray([topics], dtype=np.int64),
|
| 99 |
+
'difficulty': np.asarray([diffs], dtype=np.int64),
|
| 100 |
+
'response': np.asarray([resp], dtype=np.int64),
|
| 101 |
+
'gap': np.asarray([gaps], dtype=np.int64),
|
| 102 |
+
}
|
| 103 |
+
probs = self._session.run(['probs'], feeds)[0][0] # [n_topics, n_diff]
|
| 104 |
+
return {
|
| 105 |
+
slug: {d: float(probs[ti, di]) for d, di in diff_index.items()}
|
| 106 |
+
for slug, ti in topic_index.items()
|
| 107 |
+
}
|
backend/ml/memory.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Forgetting model used for spaced repetition.
|
| 3 |
+
|
| 4 |
+
Recall probability decays exponentially, R = exp(-days / S), where the memory
|
| 5 |
+
stability S (in days) grows with successful practice and mastery — the same shape as
|
| 6 |
+
half-life regression (Settles & Meeder, 2016) with hand-set coefficients.
|
| 7 |
+
|
| 8 |
+
Forgetting is applied at *read* time to produce an "effective" mastery; it is never
|
| 9 |
+
written back to the database, so repeated reads don't compound decay.
|
| 10 |
+
"""
|
| 11 |
+
import math
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
|
| 14 |
+
REVIEW_RECALL_THRESHOLD = 0.7
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def stability_days(practice_count, correct_count, mastery):
|
| 18 |
+
correct_count = correct_count or 0
|
| 19 |
+
practice_count = practice_count or 0
|
| 20 |
+
wrong = max(0, practice_count - correct_count)
|
| 21 |
+
return max(0.5, 1.0 + 1.6 * correct_count ** 0.85 - 0.3 * wrong ** 0.7) * (0.5 + mastery)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def recall_probability(last_practiced, practice_count, correct_count, mastery, now=None):
|
| 25 |
+
if not last_practiced or not practice_count:
|
| 26 |
+
return 1.0
|
| 27 |
+
now = now or datetime.utcnow()
|
| 28 |
+
days = max(0.0, (now - last_practiced).total_seconds() / 86400)
|
| 29 |
+
return math.exp(-days / stability_days(practice_count, correct_count, mastery))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def effective_mastery(mastery, recall):
|
| 33 |
+
# Forgotten knowledge is easier to relearn than new material, so it never decays to zero.
|
| 34 |
+
return mastery * (0.35 + 0.65 * recall)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def days_until_review(practice_count, correct_count, mastery, threshold=REVIEW_RECALL_THRESHOLD):
|
| 38 |
+
return -math.log(threshold) * stability_days(practice_count, correct_count, mastery)
|
backend/models.py
CHANGED
|
@@ -1,98 +1,212 @@
|
|
| 1 |
-
from flask_sqlalchemy import SQLAlchemy
|
| 2 |
from datetime import datetime
|
| 3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
db = SQLAlchemy()
|
| 5 |
|
|
|
|
| 6 |
class User(db.Model):
|
| 7 |
id = db.Column(db.Integer, primary_key=True)
|
| 8 |
username = db.Column(db.String(80), unique=True, nullable=False)
|
| 9 |
email = db.Column(db.String(120), unique=True, nullable=False)
|
|
|
|
|
|
|
|
|
|
| 10 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 11 |
-
|
| 12 |
knowledge_states = db.relationship('KnowledgeState', backref='user', lazy=True)
|
| 13 |
learning_sessions = db.relationship('LearningSession', backref='user', lazy=True)
|
| 14 |
quiz_attempts = db.relationship('QuizAttempt', backref='user', lazy=True)
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
class Topic(db.Model):
|
| 17 |
id = db.Column(db.Integer, primary_key=True)
|
|
|
|
| 18 |
name = db.Column(db.String(100), nullable=False)
|
| 19 |
category = db.Column(db.String(50), nullable=False)
|
| 20 |
difficulty = db.Column(db.String(20), nullable=False)
|
| 21 |
description = db.Column(db.Text)
|
| 22 |
prerequisites = db.Column(db.String(200)) # Comma-separated topic IDs
|
| 23 |
-
|
|
|
|
|
|
|
| 24 |
knowledge_states = db.relationship('KnowledgeState', backref='topic', lazy=True)
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
class KnowledgeState(db.Model):
|
|
|
|
|
|
|
| 27 |
id = db.Column(db.Integer, primary_key=True)
|
| 28 |
-
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
|
| 29 |
topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'), nullable=False)
|
| 30 |
-
knowledge_level = db.Column(db.Float, default=0.0) #
|
| 31 |
-
confidence = db.Column(db.Float, default=0.0)
|
| 32 |
last_practiced = db.Column(db.DateTime, default=datetime.utcnow)
|
| 33 |
practice_count = db.Column(db.Integer, default=0)
|
|
|
|
| 34 |
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 35 |
|
|
|
|
| 36 |
class LearningSession(db.Model):
|
| 37 |
id = db.Column(db.Integer, primary_key=True)
|
| 38 |
-
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
|
| 39 |
topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'), nullable=False)
|
| 40 |
content = db.Column(db.Text, nullable=False)
|
| 41 |
difficulty = db.Column(db.String(20))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
duration = db.Column(db.Integer) # in seconds
|
| 43 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 44 |
|
|
|
|
| 45 |
class QuizAttempt(db.Model):
|
| 46 |
id = db.Column(db.Integer, primary_key=True)
|
| 47 |
-
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
|
| 48 |
topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'), nullable=False)
|
|
|
|
| 49 |
question = db.Column(db.Text, nullable=False)
|
| 50 |
user_answer = db.Column(db.Text)
|
| 51 |
correct_answer = db.Column(db.Text)
|
| 52 |
is_correct = db.Column(db.Boolean)
|
| 53 |
difficulty = db.Column(db.String(20))
|
| 54 |
time_taken = db.Column(db.Integer) # in seconds
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
class AgentKnowledge(db.Model):
|
| 58 |
-
"""Stores learned patterns and strategies for each agent"""
|
| 59 |
id = db.Column(db.Integer, primary_key=True)
|
| 60 |
-
agent_type = db.Column(db.String(50)
|
| 61 |
-
knowledge_type = db.Column(db.String(50))
|
|
|
|
| 62 |
content = db.Column(db.JSON)
|
| 63 |
effectiveness_score = db.Column(db.Float, default=0.5)
|
| 64 |
usage_count = db.Column(db.Integer, default=0)
|
| 65 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
|
|
|
|
|
|
| 66 |
|
| 67 |
class AgentMessage(db.Model):
|
| 68 |
-
"""Communication between agents"""
|
| 69 |
id = db.Column(db.Integer, primary_key=True)
|
| 70 |
from_agent = db.Column(db.String(50))
|
| 71 |
to_agent = db.Column(db.String(50))
|
| 72 |
-
message_type = db.Column(db.String(50))
|
| 73 |
content = db.Column(db.JSON)
|
| 74 |
-
status = db.Column(db.String(20))
|
| 75 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 76 |
processed_at = db.Column(db.DateTime)
|
| 77 |
|
|
|
|
| 78 |
class AgentPerformance(db.Model):
|
| 79 |
-
"""
|
| 80 |
id = db.Column(db.Integer, primary_key=True)
|
| 81 |
agent_id = db.Column(db.String(50))
|
| 82 |
action_type = db.Column(db.String(50))
|
| 83 |
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
|
| 84 |
-
success_metric = db.Column(db.Float)
|
| 85 |
api_calls_used = db.Column(db.Integer, default=0)
|
| 86 |
execution_time_ms = db.Column(db.Integer)
|
| 87 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 88 |
|
|
|
|
| 89 |
class ContentLibrary(db.Model):
|
| 90 |
-
"""
|
| 91 |
id = db.Column(db.Integer, primary_key=True)
|
| 92 |
topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'))
|
| 93 |
-
content_type = db.Column(db.String(50)
|
|
|
|
| 94 |
difficulty = db.Column(db.String(20))
|
| 95 |
content = db.Column(db.Text)
|
| 96 |
meta_data = db.Column(db.JSON)
|
| 97 |
quality_score = db.Column(db.Float, default=0.5)
|
| 98 |
-
usage_count = db.Column(db.Integer, default=0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from datetime import datetime
|
| 2 |
|
| 3 |
+
from flask_sqlalchemy import SQLAlchemy
|
| 4 |
+
from sqlalchemy import inspect, text
|
| 5 |
+
from werkzeug.security import check_password_hash, generate_password_hash
|
| 6 |
+
|
| 7 |
db = SQLAlchemy()
|
| 8 |
|
| 9 |
+
|
| 10 |
class User(db.Model):
|
| 11 |
id = db.Column(db.Integer, primary_key=True)
|
| 12 |
username = db.Column(db.String(80), unique=True, nullable=False)
|
| 13 |
email = db.Column(db.String(120), unique=True, nullable=False)
|
| 14 |
+
password_hash = db.Column(db.String(256)) # nullable for accounts created before v2
|
| 15 |
+
learning_style = db.Column(db.String(30), default='mixed')
|
| 16 |
+
goals = db.Column(db.JSON, default=list)
|
| 17 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 18 |
+
|
| 19 |
knowledge_states = db.relationship('KnowledgeState', backref='user', lazy=True)
|
| 20 |
learning_sessions = db.relationship('LearningSession', backref='user', lazy=True)
|
| 21 |
quiz_attempts = db.relationship('QuizAttempt', backref='user', lazy=True)
|
| 22 |
|
| 23 |
+
def set_password(self, password):
|
| 24 |
+
self.password_hash = generate_password_hash(password)
|
| 25 |
+
|
| 26 |
+
def check_password(self, password):
|
| 27 |
+
return bool(self.password_hash) and check_password_hash(self.password_hash, password)
|
| 28 |
+
|
| 29 |
+
def to_dict(self):
|
| 30 |
+
return {
|
| 31 |
+
'user_id': self.id,
|
| 32 |
+
'username': self.username,
|
| 33 |
+
'email': self.email,
|
| 34 |
+
'learning_style': self.learning_style or 'mixed',
|
| 35 |
+
'goals': self.goals or [],
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
class Topic(db.Model):
|
| 40 |
id = db.Column(db.Integer, primary_key=True)
|
| 41 |
+
slug = db.Column(db.String(80), unique=True)
|
| 42 |
name = db.Column(db.String(100), nullable=False)
|
| 43 |
category = db.Column(db.String(50), nullable=False)
|
| 44 |
difficulty = db.Column(db.String(20), nullable=False)
|
| 45 |
description = db.Column(db.Text)
|
| 46 |
prerequisites = db.Column(db.String(200)) # Comma-separated topic IDs
|
| 47 |
+
key_concepts = db.Column(db.JSON, default=list)
|
| 48 |
+
position = db.Column(db.Integer, default=0)
|
| 49 |
+
|
| 50 |
knowledge_states = db.relationship('KnowledgeState', backref='topic', lazy=True)
|
| 51 |
|
| 52 |
+
@property
|
| 53 |
+
def prerequisite_ids(self):
|
| 54 |
+
if not self.prerequisites:
|
| 55 |
+
return []
|
| 56 |
+
return [int(x) for x in self.prerequisites.split(',') if x.strip().isdigit()]
|
| 57 |
+
|
| 58 |
+
def to_dict(self):
|
| 59 |
+
return {
|
| 60 |
+
'id': self.id,
|
| 61 |
+
'slug': self.slug,
|
| 62 |
+
'name': self.name,
|
| 63 |
+
'category': self.category,
|
| 64 |
+
'difficulty': self.difficulty,
|
| 65 |
+
'description': self.description,
|
| 66 |
+
'prerequisites': self.prerequisite_ids,
|
| 67 |
+
'key_concepts': self.key_concepts or [],
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
class KnowledgeState(db.Model):
|
| 72 |
+
__table_args__ = (db.UniqueConstraint('user_id', 'topic_id', name='uq_knowledge_user_topic'),)
|
| 73 |
+
|
| 74 |
id = db.Column(db.Integer, primary_key=True)
|
| 75 |
+
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, index=True)
|
| 76 |
topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'), nullable=False)
|
| 77 |
+
knowledge_level = db.Column(db.Float, default=0.0) # BKT posterior P(mastered)
|
| 78 |
+
confidence = db.Column(db.Float, default=0.0)
|
| 79 |
last_practiced = db.Column(db.DateTime, default=datetime.utcnow)
|
| 80 |
practice_count = db.Column(db.Integer, default=0)
|
| 81 |
+
correct_count = db.Column(db.Integer, default=0)
|
| 82 |
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 83 |
|
| 84 |
+
|
| 85 |
class LearningSession(db.Model):
|
| 86 |
id = db.Column(db.Integer, primary_key=True)
|
| 87 |
+
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, index=True)
|
| 88 |
topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'), nullable=False)
|
| 89 |
content = db.Column(db.Text, nullable=False)
|
| 90 |
difficulty = db.Column(db.String(20))
|
| 91 |
+
strategy = db.Column(db.String(50))
|
| 92 |
+
context_bucket = db.Column(db.String(20))
|
| 93 |
+
reward_sum = db.Column(db.Float, default=0.0)
|
| 94 |
+
reward_count = db.Column(db.Integer, default=0)
|
| 95 |
duration = db.Column(db.Integer) # in seconds
|
| 96 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 97 |
|
| 98 |
+
|
| 99 |
class QuizAttempt(db.Model):
|
| 100 |
id = db.Column(db.Integer, primary_key=True)
|
| 101 |
+
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, index=True)
|
| 102 |
topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'), nullable=False)
|
| 103 |
+
question_id = db.Column(db.Integer, db.ForeignKey('question_bank.id'))
|
| 104 |
question = db.Column(db.Text, nullable=False)
|
| 105 |
user_answer = db.Column(db.Text)
|
| 106 |
correct_answer = db.Column(db.Text)
|
| 107 |
is_correct = db.Column(db.Boolean)
|
| 108 |
difficulty = db.Column(db.String(20))
|
| 109 |
time_taken = db.Column(db.Integer) # in seconds
|
| 110 |
+
created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class QuestionBank(db.Model):
|
| 114 |
+
"""Reusable question pool. Most quizzes are assembled from here without an LLM call."""
|
| 115 |
+
__tablename__ = 'question_bank'
|
| 116 |
+
|
| 117 |
+
id = db.Column(db.Integer, primary_key=True)
|
| 118 |
+
topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'), nullable=False, index=True)
|
| 119 |
+
difficulty = db.Column(db.String(20), nullable=False)
|
| 120 |
+
concept = db.Column(db.String(120))
|
| 121 |
+
question = db.Column(db.Text, nullable=False)
|
| 122 |
+
question_hash = db.Column(db.String(40), unique=True)
|
| 123 |
+
options = db.Column(db.JSON, nullable=False)
|
| 124 |
+
correct_answer = db.Column(db.String(1), nullable=False)
|
| 125 |
+
explanation = db.Column(db.Text)
|
| 126 |
+
source = db.Column(db.String(20), default='llm') # seed | llm
|
| 127 |
+
times_served = db.Column(db.Integer, default=0)
|
| 128 |
+
times_answered = db.Column(db.Integer, default=0)
|
| 129 |
+
times_correct = db.Column(db.Integer, default=0)
|
| 130 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 131 |
|
| 132 |
+
@property
|
| 133 |
+
def empirical_p_correct(self):
|
| 134 |
+
# Beta(2,2)-smoothed proportion correct, an item-difficulty estimate
|
| 135 |
+
return (self.times_correct + 2) / (self.times_answered + 4)
|
| 136 |
+
|
| 137 |
+
def to_public_dict(self):
|
| 138 |
+
"""What the client sees while answering: no answer key; grading happens server-side."""
|
| 139 |
+
return {
|
| 140 |
+
'id': self.id,
|
| 141 |
+
'question': self.question,
|
| 142 |
+
'options': self.options,
|
| 143 |
+
'difficulty': self.difficulty,
|
| 144 |
+
'concept': self.concept,
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
|
| 148 |
class AgentKnowledge(db.Model):
|
| 149 |
+
"""Stores learned patterns and strategies for each agent (e.g. bandit arm posteriors)."""
|
| 150 |
id = db.Column(db.Integer, primary_key=True)
|
| 151 |
+
agent_type = db.Column(db.String(50), index=True)
|
| 152 |
+
knowledge_type = db.Column(db.String(50))
|
| 153 |
+
key = db.Column(db.String(120), index=True)
|
| 154 |
content = db.Column(db.JSON)
|
| 155 |
effectiveness_score = db.Column(db.Float, default=0.5)
|
| 156 |
usage_count = db.Column(db.Integer, default=0)
|
| 157 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 158 |
+
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
| 159 |
+
|
| 160 |
|
| 161 |
class AgentMessage(db.Model):
|
| 162 |
+
"""Communication between agents (kept for backwards compatibility)."""
|
| 163 |
id = db.Column(db.Integer, primary_key=True)
|
| 164 |
from_agent = db.Column(db.String(50))
|
| 165 |
to_agent = db.Column(db.String(50))
|
| 166 |
+
message_type = db.Column(db.String(50))
|
| 167 |
content = db.Column(db.JSON)
|
| 168 |
+
status = db.Column(db.String(20))
|
| 169 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 170 |
processed_at = db.Column(db.DateTime)
|
| 171 |
|
| 172 |
+
|
| 173 |
class AgentPerformance(db.Model):
|
| 174 |
+
"""Per-run agent telemetry."""
|
| 175 |
id = db.Column(db.Integer, primary_key=True)
|
| 176 |
agent_id = db.Column(db.String(50))
|
| 177 |
action_type = db.Column(db.String(50))
|
| 178 |
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
|
| 179 |
+
success_metric = db.Column(db.Float)
|
| 180 |
api_calls_used = db.Column(db.Integer, default=0)
|
| 181 |
execution_time_ms = db.Column(db.Integer)
|
| 182 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 183 |
|
| 184 |
+
|
| 185 |
class ContentLibrary(db.Model):
|
| 186 |
+
"""Generated content cache (lessons, study tips) to reduce LLM calls."""
|
| 187 |
id = db.Column(db.Integer, primary_key=True)
|
| 188 |
topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'))
|
| 189 |
+
content_type = db.Column(db.String(50), index=True)
|
| 190 |
+
cache_key = db.Column(db.String(200), index=True)
|
| 191 |
difficulty = db.Column(db.String(20))
|
| 192 |
content = db.Column(db.Text)
|
| 193 |
meta_data = db.Column(db.JSON)
|
| 194 |
quality_score = db.Column(db.Float, default=0.5)
|
| 195 |
+
usage_count = db.Column(db.Integer, default=0)
|
| 196 |
+
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def migrate_schema():
|
| 200 |
+
"""Tiny additive migration for SQLite databases created by v1 (adds missing columns)."""
|
| 201 |
+
inspector = inspect(db.engine)
|
| 202 |
+
existing_tables = set(inspector.get_table_names())
|
| 203 |
+
with db.engine.begin() as conn:
|
| 204 |
+
for table in db.metadata.sorted_tables:
|
| 205 |
+
if table.name not in existing_tables:
|
| 206 |
+
continue
|
| 207 |
+
present = {c['name'] for c in inspector.get_columns(table.name)}
|
| 208 |
+
for column in table.columns:
|
| 209 |
+
if column.name in present:
|
| 210 |
+
continue
|
| 211 |
+
col_type = column.type.compile(dialect=db.engine.dialect)
|
| 212 |
+
conn.execute(text(f'ALTER TABLE "{table.name}" ADD COLUMN "{column.name}" {col_type}'))
|
backend/requirements.txt
CHANGED
|
@@ -1,8 +1,16 @@
|
|
| 1 |
-
|
| 2 |
-
Flask
|
|
|
|
| 3 |
Flask-SQLAlchemy==3.1.1
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
python-dotenv==1.
|
| 8 |
-
gunicorn==
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Runtime dependencies for the API (Hugging Face Space). No torch: the KT model runs on onnxruntime.
|
| 2 |
+
Flask==3.1.3
|
| 3 |
+
flask-cors==6.0.5
|
| 4 |
Flask-SQLAlchemy==3.1.1
|
| 5 |
+
SQLAlchemy==2.1.3
|
| 6 |
+
Werkzeug==3.1.9
|
| 7 |
+
itsdangerous==2.2.0
|
| 8 |
+
python-dotenv==1.2.4
|
| 9 |
+
gunicorn==26.2.0
|
| 10 |
+
numpy==2.4.6
|
| 11 |
+
onnxruntime==1.30.0
|
| 12 |
+
pydantic==2.13.5
|
| 13 |
+
langchain-core==1.6.6
|
| 14 |
+
langchain-google-genai==4.4.0
|
| 15 |
+
langgraph==1.2.12
|
| 16 |
+
langgraph-checkpoint-sqlite==3.1.1
|
backend/requirements_light.txt
DELETED
|
@@ -1,6 +0,0 @@
|
|
| 1 |
-
|
| 2 |
-
Flask==3.0.0
|
| 3 |
-
Flask-CORS==4.0.0
|
| 4 |
-
Flask-SQLAlchemy==3.1.1
|
| 5 |
-
google-generativeai==0.3.1
|
| 6 |
-
python-dotenv==1.0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/routes.py
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HTTP API. Response shapes of the v1 endpoints are preserved (plus new fields)."""
|
| 2 |
+
import hashlib
|
| 3 |
+
import re
|
| 4 |
+
from datetime import datetime, timedelta
|
| 5 |
+
|
| 6 |
+
from flask import Blueprint, current_app, g, jsonify, request, session
|
| 7 |
+
from langchain_core.messages import HumanMessage, SystemMessage
|
| 8 |
+
|
| 9 |
+
from agents.metrics import METRICS
|
| 10 |
+
from agents.recommendation_agent import learning_path, score_topics
|
| 11 |
+
from models import LearningSession, QuestionBank, QuizAttempt, Topic, User, db, ContentLibrary
|
| 12 |
+
from services import content
|
| 13 |
+
from services.auth import current_user_id, issue_token, login_required, rate_limited
|
| 14 |
+
from services.sandbox import run_code
|
| 15 |
+
|
| 16 |
+
api = Blueprint('api', __name__)
|
| 17 |
+
|
| 18 |
+
USERNAME_RE = re.compile(r'^[A-Za-z0-9_.-]{3,40}$')
|
| 19 |
+
EMAIL_RE = re.compile(r'^[^@\s]+@[^@\s]+\.[^@\s]+$')
|
| 20 |
+
BANDIT_WINDOW = timedelta(hours=48)
|
| 21 |
+
BANDIT_MAX_REWARDS_PER_LESSON = 6
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def svc():
|
| 25 |
+
return current_app.extensions['elearn']
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def body():
|
| 29 |
+
return request.get_json(silent=True) or {}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_topic_or_404(topic_id):
|
| 33 |
+
topic = db.session.get(Topic, int(topic_id)) if str(topic_id).isdigit() else None
|
| 34 |
+
if topic is None:
|
| 35 |
+
return None, (jsonify({'error': 'Topic not found'}), 404)
|
| 36 |
+
return topic, None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# ------------------------------------------------------------------ meta
|
| 40 |
+
|
| 41 |
+
@api.get('/')
|
| 42 |
+
def index():
|
| 43 |
+
s = svc()
|
| 44 |
+
return jsonify({
|
| 45 |
+
'message': 'Adaptive E-Learning API',
|
| 46 |
+
'version': '2.0.0',
|
| 47 |
+
'status': 'running',
|
| 48 |
+
'ai_agents': 'LangGraph multi-agent system: coordinator + knowledge, teaching, assessment, tutor, recommendation',
|
| 49 |
+
'llm': s.llm.info(),
|
| 50 |
+
'knowledge_model': s.knowledge.kt.meta.get('architecture', 'bkt') if s.knowledge.kt.available else 'bkt',
|
| 51 |
+
'endpoints': sorted(str(r) for r in current_app.url_map.iter_rules() if str(r).startswith('/api')),
|
| 52 |
+
})
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@api.get('/api/health')
|
| 56 |
+
def health():
|
| 57 |
+
db.session.execute(db.text('SELECT 1'))
|
| 58 |
+
return jsonify({'status': 'ok', 'time': datetime.utcnow().isoformat(timespec='seconds')})
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ------------------------------------------------------------------ auth
|
| 62 |
+
|
| 63 |
+
def _auth_response(user, message, status=200):
|
| 64 |
+
session['user_id'] = user.id
|
| 65 |
+
return jsonify({'message': message, 'token': issue_token(user.id), **user.to_dict()}), status
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@api.post('/api/register')
|
| 69 |
+
def register():
|
| 70 |
+
data = body()
|
| 71 |
+
username = (data.get('username') or '').strip()
|
| 72 |
+
email = (data.get('email') or '').strip().lower()
|
| 73 |
+
password = data.get('password') or ''
|
| 74 |
+
if not USERNAME_RE.match(username):
|
| 75 |
+
return jsonify({'error': 'Username must be 3-40 characters (letters, numbers, _ . -)'}), 400
|
| 76 |
+
if not EMAIL_RE.match(email):
|
| 77 |
+
return jsonify({'error': 'Please enter a valid email address'}), 400
|
| 78 |
+
if len(password) < 8:
|
| 79 |
+
return jsonify({'error': 'Password must be at least 8 characters'}), 400
|
| 80 |
+
if User.query.filter_by(username=username).first():
|
| 81 |
+
return jsonify({'error': 'Username already exists'}), 400
|
| 82 |
+
if User.query.filter_by(email=email).first():
|
| 83 |
+
return jsonify({'error': 'Email already registered'}), 400
|
| 84 |
+
user = User(username=username, email=email, learning_style=data.get('learning_style') or 'mixed', goals=[])
|
| 85 |
+
user.set_password(password)
|
| 86 |
+
db.session.add(user)
|
| 87 |
+
db.session.commit()
|
| 88 |
+
return _auth_response(user, 'User registered successfully', 201)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@api.post('/api/login')
|
| 92 |
+
def login():
|
| 93 |
+
data = body()
|
| 94 |
+
user = User.query.filter_by(username=(data.get('username') or '').strip()).first()
|
| 95 |
+
password = data.get('password') or ''
|
| 96 |
+
if user and user.password_hash is None and len(password) >= 8:
|
| 97 |
+
# v1 accounts had no password: the first login sets it.
|
| 98 |
+
user.set_password(password)
|
| 99 |
+
db.session.commit()
|
| 100 |
+
return _auth_response(user, 'Password set; login successful')
|
| 101 |
+
if not user or not user.check_password(password):
|
| 102 |
+
return jsonify({'error': 'Invalid username or password'}), 401
|
| 103 |
+
return _auth_response(user, 'Login successful')
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@api.get('/api/current-user')
|
| 107 |
+
def current_user():
|
| 108 |
+
uid = current_user_id()
|
| 109 |
+
user = db.session.get(User, uid) if uid else None
|
| 110 |
+
if not user:
|
| 111 |
+
return jsonify({'error': 'Not logged in'}), 401
|
| 112 |
+
return jsonify(user.to_dict())
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@api.post('/api/logout')
|
| 116 |
+
def logout():
|
| 117 |
+
session.clear()
|
| 118 |
+
return jsonify({'message': 'Logged out successfully'})
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@api.put('/api/profile')
|
| 122 |
+
@login_required
|
| 123 |
+
def update_profile():
|
| 124 |
+
data = body()
|
| 125 |
+
user = db.session.get(User, g.user_id)
|
| 126 |
+
if data.get('learning_style') in ('visual', 'reading', 'kinesthetic', 'auditory', 'mixed'):
|
| 127 |
+
user.learning_style = data['learning_style']
|
| 128 |
+
if isinstance(data.get('goals'), list):
|
| 129 |
+
user.goals = [str(x)[:60] for x in data['goals'][:10]]
|
| 130 |
+
db.session.commit()
|
| 131 |
+
return jsonify(user.to_dict())
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# ------------------------------------------------------------------ topics
|
| 135 |
+
|
| 136 |
+
@api.get('/api/topics')
|
| 137 |
+
def get_topics():
|
| 138 |
+
return jsonify([t.to_dict() for t in Topic.query.order_by(Topic.position, Topic.id).all()])
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@api.get('/api/topics/<int:topic_id>')
|
| 142 |
+
def get_topic(topic_id):
|
| 143 |
+
topic, err = get_topic_or_404(topic_id)
|
| 144 |
+
return err or jsonify(topic.to_dict())
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ------------------------------------------------------------------ learning
|
| 148 |
+
|
| 149 |
+
def _user_prefs():
|
| 150 |
+
user = db.session.get(User, g.user_id)
|
| 151 |
+
return {'learning_style': user.learning_style or 'mixed', 'goals': user.goals or []}
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@api.post('/api/generate-lesson')
|
| 155 |
+
@login_required
|
| 156 |
+
@rate_limited
|
| 157 |
+
def generate_lesson():
|
| 158 |
+
data = body()
|
| 159 |
+
topic, err = get_topic_or_404(data.get('topic_id'))
|
| 160 |
+
if err:
|
| 161 |
+
return err
|
| 162 |
+
out = svc().coordinator.run('generate_lesson', g.user_id, topic.id, fresh=bool(data.get('fresh')), **_user_prefs())
|
| 163 |
+
lesson, strategy = out['lesson'], out['strategy']
|
| 164 |
+
ls = LearningSession(user_id=g.user_id, topic_id=topic.id, content=lesson['markdown'],
|
| 165 |
+
difficulty=strategy['complexity'], strategy=strategy['name'], context_bucket=strategy['bucket'])
|
| 166 |
+
db.session.add(ls)
|
| 167 |
+
db.session.commit()
|
| 168 |
+
return jsonify({
|
| 169 |
+
'content': lesson['markdown'],
|
| 170 |
+
'lesson': lesson['lesson'],
|
| 171 |
+
'source': lesson['source'],
|
| 172 |
+
'session_id': ls.id,
|
| 173 |
+
'difficulty': strategy['complexity'],
|
| 174 |
+
'knowledge_level': strategy['knowledge_level'],
|
| 175 |
+
'topic_name': topic.name,
|
| 176 |
+
'agent_metadata': {
|
| 177 |
+
'teaching_style': strategy['name'],
|
| 178 |
+
'rule_choice': strategy['rule_choice'],
|
| 179 |
+
'bandit_samples': strategy['bandit_samples'],
|
| 180 |
+
'complexity': strategy['complexity'],
|
| 181 |
+
'example_count': len(lesson['lesson'].get('code_examples', [])),
|
| 182 |
+
'source': lesson['source'],
|
| 183 |
+
'trace': out.get('trace', []),
|
| 184 |
+
},
|
| 185 |
+
})
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@api.post('/api/generate-quiz')
|
| 189 |
+
@login_required
|
| 190 |
+
@rate_limited
|
| 191 |
+
def generate_quiz():
|
| 192 |
+
data = body()
|
| 193 |
+
topic, err = get_topic_or_404(data.get('topic_id'))
|
| 194 |
+
if err:
|
| 195 |
+
return err
|
| 196 |
+
out = svc().coordinator.run('generate_quiz', g.user_id, topic.id)
|
| 197 |
+
db.session.commit()
|
| 198 |
+
quiz = out['quiz']
|
| 199 |
+
if not quiz.get('questions'):
|
| 200 |
+
return jsonify({'error': 'No questions available for this topic yet'}), 503
|
| 201 |
+
return jsonify({
|
| 202 |
+
'questions': quiz['questions'],
|
| 203 |
+
'difficulty': 'adaptive',
|
| 204 |
+
'topic_name': topic.name,
|
| 205 |
+
'topic_id': topic.id,
|
| 206 |
+
'agent_metadata': {**quiz['metadata'], 'trace': out.get('trace', [])},
|
| 207 |
+
})
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def _reward_teaching_strategy(user_id, topic_id, is_correct):
|
| 211 |
+
"""Credit the teaching strategy of the learner's latest lesson on this topic (bandit feedback)."""
|
| 212 |
+
ls = (LearningSession.query.filter(LearningSession.user_id == user_id, LearningSession.topic_id == topic_id,
|
| 213 |
+
LearningSession.strategy.isnot(None),
|
| 214 |
+
LearningSession.created_at >= datetime.utcnow() - BANDIT_WINDOW)
|
| 215 |
+
.order_by(LearningSession.created_at.desc()).first())
|
| 216 |
+
if not ls or (ls.reward_count or 0) >= BANDIT_MAX_REWARDS_PER_LESSON:
|
| 217 |
+
return None
|
| 218 |
+
svc().bandit.update(ls.context_bucket or 'low', ls.strategy, 1.0 if is_correct else 0.0, weight=0.5)
|
| 219 |
+
ls.reward_count = (ls.reward_count or 0) + 1
|
| 220 |
+
ls.reward_sum = (ls.reward_sum or 0) + (1.0 if is_correct else 0.0)
|
| 221 |
+
return ls.strategy
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
@api.post('/api/submit-answer')
|
| 225 |
+
@login_required
|
| 226 |
+
def submit_answer():
|
| 227 |
+
data = body()
|
| 228 |
+
topic, err = get_topic_or_404(data.get('topic_id'))
|
| 229 |
+
if err:
|
| 230 |
+
return err
|
| 231 |
+
user_answer = str(data.get('user_answer') or '').strip().upper()[:1]
|
| 232 |
+
q = db.session.get(QuestionBank, int(data['question_id'])) if str(data.get('question_id', '')).isdigit() else None
|
| 233 |
+
if q is not None:
|
| 234 |
+
if q.topic_id != topic.id:
|
| 235 |
+
return jsonify({'error': 'Question does not belong to this topic'}), 400
|
| 236 |
+
is_correct = user_answer == q.correct_answer
|
| 237 |
+
difficulty, correct_answer, explanation, question_text = q.difficulty, q.correct_answer, q.explanation, q.question
|
| 238 |
+
q.times_answered = (q.times_answered or 0) + 1
|
| 239 |
+
q.times_correct = (q.times_correct or 0) + (1 if is_correct else 0)
|
| 240 |
+
else: # legacy payload (v1 frontend)
|
| 241 |
+
correct_answer = str(data.get('correct_answer') or '').strip().upper()[:1]
|
| 242 |
+
is_correct = bool(user_answer) and user_answer == correct_answer
|
| 243 |
+
difficulty = data.get('difficulty') if data.get('difficulty') in ('beginner', 'intermediate', 'advanced') else 'intermediate'
|
| 244 |
+
explanation = data.get('explanation') or f'The correct answer is {correct_answer}.'
|
| 245 |
+
question_text = str(data.get('question') or '')[:2000] or 'n/a'
|
| 246 |
+
|
| 247 |
+
db.session.add(QuizAttempt(user_id=g.user_id, topic_id=topic.id, question_id=q.id if q else None,
|
| 248 |
+
question=question_text, user_answer=user_answer, correct_answer=correct_answer,
|
| 249 |
+
is_correct=is_correct, difficulty=difficulty,
|
| 250 |
+
time_taken=int(data['time_taken']) if str(data.get('time_taken', '')).isdigit() else None))
|
| 251 |
+
state = svc().knowledge.record_answer(g.user_id, topic, is_correct, difficulty)
|
| 252 |
+
rewarded = _reward_teaching_strategy(g.user_id, topic.id, is_correct)
|
| 253 |
+
db.session.commit()
|
| 254 |
+
return jsonify({
|
| 255 |
+
'is_correct': is_correct,
|
| 256 |
+
'correct_answer': correct_answer,
|
| 257 |
+
'explanation': explanation,
|
| 258 |
+
'new_knowledge_level': round(state.knowledge_level, 4),
|
| 259 |
+
'confidence': state.confidence,
|
| 260 |
+
'rewarded_strategy': rewarded,
|
| 261 |
+
})
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
# ------------------------------------------------------------------ progress
|
| 265 |
+
|
| 266 |
+
def _profile():
|
| 267 |
+
return svc().knowledge.profile(g.user_id)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def _legacy_state(p):
|
| 271 |
+
return {'topic_id': p['topic_id'], 'topic_name': p['name'], 'knowledge_level': p['effective_mastery'],
|
| 272 |
+
'confidence': p['confidence'], 'practice_count': p['practice_count'],
|
| 273 |
+
'last_practiced': p['last_practiced'], **p}
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
@api.get('/api/knowledge-state/<int:topic_id>')
|
| 277 |
+
@login_required
|
| 278 |
+
def get_knowledge_state(topic_id):
|
| 279 |
+
p = _profile()['topics'].get(topic_id)
|
| 280 |
+
if p is None:
|
| 281 |
+
return jsonify({'error': 'Topic not found'}), 404
|
| 282 |
+
return jsonify(_legacy_state(p))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
@api.get('/api/knowledge-states')
|
| 286 |
+
@login_required
|
| 287 |
+
def get_knowledge_states():
|
| 288 |
+
"""Bulk endpoint: one request instead of one per topic."""
|
| 289 |
+
prof = _profile()
|
| 290 |
+
return jsonify({'model': prof['model'], 'states': [_legacy_state(p) for p in prof['topics'].values()]})
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
@api.get('/api/progress-summary')
|
| 294 |
+
@login_required
|
| 295 |
+
def progress_summary():
|
| 296 |
+
prof = _profile()
|
| 297 |
+
started = [p for p in prof['topics'].values() if p['practice_count']]
|
| 298 |
+
simplify = lambda items: [{'id': p['topic_id'], 'name': p['name'], 'level': round(p['effective_mastery'], 2)} for p in items]
|
| 299 |
+
return jsonify({
|
| 300 |
+
'average_knowledge': round(prof['average_knowledge'], 2),
|
| 301 |
+
'topics_mastered': sum(p['effective_mastery'] >= 0.8 for p in started),
|
| 302 |
+
'topics_in_progress': sum(0 < p['effective_mastery'] < 0.8 for p in started),
|
| 303 |
+
'topics_total': len(prof['topics']),
|
| 304 |
+
'total_practice_count': sum(p['practice_count'] for p in started),
|
| 305 |
+
'weak_topics': simplify(prof['weak_topics']),
|
| 306 |
+
'strong_topics': simplify(prof['strong_topics']),
|
| 307 |
+
'review_due': len(prof['review_queue']),
|
| 308 |
+
'model': prof['model'],
|
| 309 |
+
})
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
@api.get('/api/next-topic')
|
| 313 |
+
@login_required
|
| 314 |
+
def next_topic():
|
| 315 |
+
out = svc().coordinator.run('recommend_topic', g.user_id,
|
| 316 |
+
current_topic_id=request.args.get('current_topic_id', type=int), **_user_prefs())
|
| 317 |
+
best = out['recommendations'].get('next_best')
|
| 318 |
+
if not best:
|
| 319 |
+
return jsonify({'message': 'No recommendations available'}), 404
|
| 320 |
+
return jsonify({'id': best['topic_id'], 'name': best['name'], 'category': best['category'],
|
| 321 |
+
'difficulty': best['difficulty'], 'description': best['description'],
|
| 322 |
+
'reason': best['reason'], 'agent_recommendation': True, **best})
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
@api.get('/api/recommendations')
|
| 326 |
+
@login_required
|
| 327 |
+
def recommendations():
|
| 328 |
+
out = svc().coordinator.run('recommend_topic', g.user_id, **_user_prefs())
|
| 329 |
+
return jsonify(out['recommendations'])
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
@api.get('/api/learning-path/<int:topic_id>')
|
| 333 |
+
@login_required
|
| 334 |
+
def get_learning_path(topic_id):
|
| 335 |
+
topic, err = get_topic_or_404(topic_id)
|
| 336 |
+
if err:
|
| 337 |
+
return err
|
| 338 |
+
topics = Topic.query.order_by(Topic.position, Topic.id).all()
|
| 339 |
+
return jsonify(learning_path(_profile(), topics, topic.id))
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
@api.get('/api/review-queue')
|
| 343 |
+
@login_required
|
| 344 |
+
def review_queue():
|
| 345 |
+
prof = _profile()
|
| 346 |
+
return jsonify({'due': prof['review_queue'],
|
| 347 |
+
'upcoming': sorted((p for p in prof['topics'].values()
|
| 348 |
+
if p['practice_count'] and not p['due_for_review']),
|
| 349 |
+
key=lambda p: p['days_until_review'] or 0)[:5]})
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def _fallback_tips(prof, nxt):
|
| 353 |
+
tips = []
|
| 354 |
+
for r in prof['review_queue'][:2]:
|
| 355 |
+
tips.append(f"- **Review {r['name']}** today: your estimated recall is {r['recall']:.0%}. "
|
| 356 |
+
f"A short quiz now resets the forgetting curve.")
|
| 357 |
+
for w in prof['weak_topics'][:2]:
|
| 358 |
+
tips.append(f"- **Strengthen {w['name']}** ({w['effective_mastery']:.0%} mastery): re-read the lesson, "
|
| 359 |
+
f"then take a quiz. Quizzes adapt so you succeed about 70% of the time.")
|
| 360 |
+
if nxt:
|
| 361 |
+
tips.append(f"- **Next up: {nxt['name']}** ({nxt['reason'].lower()}).")
|
| 362 |
+
tips.append('- **Practise actively**: run and modify the playground code instead of only reading it.')
|
| 363 |
+
tips.append('- **Space your sessions**: 20-30 minutes daily beats one long weekly session.')
|
| 364 |
+
return '\n'.join(tips[:5])
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
@api.get('/api/study-tips')
|
| 368 |
+
@login_required
|
| 369 |
+
def study_tips():
|
| 370 |
+
prof = _profile()
|
| 371 |
+
topics = Topic.query.order_by(Topic.position, Topic.id).all()
|
| 372 |
+
ranked = score_topics(prof, topics)
|
| 373 |
+
nxt = ranked[0] if ranked else None
|
| 374 |
+
weak = [w['name'] for w in prof['weak_topics']]
|
| 375 |
+
strong = [s['name'] for s in prof['strong_topics']]
|
| 376 |
+
due = [r['name'] for r in prof['review_queue']]
|
| 377 |
+
fingerprint = hashlib.sha1(repr((weak, strong, due, nxt and nxt['name'])).encode()).hexdigest()[:12]
|
| 378 |
+
key = f'tips:{g.user_id}:{datetime.utcnow():%Y-%m-%d}:{fingerprint}'
|
| 379 |
+
tips = content.get_text_cache(key)
|
| 380 |
+
if tips is None:
|
| 381 |
+
llm = svc().llm
|
| 382 |
+
tips = llm.chat([
|
| 383 |
+
SystemMessage('You are a learning coach. Reply ONLY with 3-5 Markdown bullet points ("- "), '
|
| 384 |
+
'each 1-2 sentences, using **bold** for key terms. Be specific and encouraging.'),
|
| 385 |
+
HumanMessage(f'Weak areas: {weak or "none"}. Strong areas: {strong or "none"}. Due for review: '
|
| 386 |
+
f'{due or "none"}. Recommended next topic: {nxt["name"] if nxt else "n/a"}. '
|
| 387 |
+
f'Overall mastery {prof["average_knowledge"]:.0%}.'),
|
| 388 |
+
]) if llm.available else None
|
| 389 |
+
tips = tips or _fallback_tips(prof, nxt)
|
| 390 |
+
content.set_text_cache(key, tips)
|
| 391 |
+
db.session.commit()
|
| 392 |
+
return jsonify({'tips': tips, 'format': 'markdown'})
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
# ------------------------------------------------------------------ practice + tutor
|
| 396 |
+
|
| 397 |
+
@api.post('/api/check-code')
|
| 398 |
+
@login_required
|
| 399 |
+
@rate_limited
|
| 400 |
+
def check_code():
|
| 401 |
+
cfg = current_app.config
|
| 402 |
+
return jsonify(run_code(str(body().get('code') or ''), timeout_s=cfg['SANDBOX_TIMEOUT_S'],
|
| 403 |
+
memory_mb=cfg['SANDBOX_MEMORY_MB'], max_output=cfg['SANDBOX_MAX_OUTPUT'],
|
| 404 |
+
stdin=str(body().get('stdin') or '')))
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
@api.post('/api/ask-challenge-hint')
|
| 408 |
+
@login_required
|
| 409 |
+
@rate_limited
|
| 410 |
+
def ask_challenge_hint():
|
| 411 |
+
data = body()
|
| 412 |
+
topic_id = data.get('topic_id') if str(data.get('topic_id', '')).isdigit() else None
|
| 413 |
+
out = svc().coordinator.run('provide_hint', g.user_id, int(topic_id) if topic_id else None,
|
| 414 |
+
question=data.get('question'), challenge=data.get('challenge'),
|
| 415 |
+
attempt_count=data.get('attempt_count', 1), last_output=data.get('last_output'),
|
| 416 |
+
practice_hints=data.get('practice_hints') or [])
|
| 417 |
+
return jsonify(out['hint'])
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
@api.post('/api/tutor/chat')
|
| 421 |
+
@login_required
|
| 422 |
+
@rate_limited
|
| 423 |
+
def tutor_chat():
|
| 424 |
+
data = body()
|
| 425 |
+
message = str(data.get('message') or '').strip()
|
| 426 |
+
if not message:
|
| 427 |
+
return jsonify({'error': 'Message is empty'}), 400
|
| 428 |
+
topic_id = int(data['topic_id']) if str(data.get('topic_id', '')).isdigit() else None
|
| 429 |
+
reply = svc().tutor_chat.send(g.user_id, topic_id, message[:4000])
|
| 430 |
+
return jsonify({'reply': reply, 'topic_id': topic_id})
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
@api.get('/api/tutor/history')
|
| 434 |
+
@login_required
|
| 435 |
+
def tutor_history():
|
| 436 |
+
topic_id = request.args.get('topic_id', type=int)
|
| 437 |
+
return jsonify({'messages': svc().tutor_chat.history(g.user_id, topic_id), 'topic_id': topic_id})
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
@api.delete('/api/tutor/history')
|
| 441 |
+
@login_required
|
| 442 |
+
def tutor_clear():
|
| 443 |
+
svc().tutor_chat.clear(g.user_id, request.args.get('topic_id', type=int))
|
| 444 |
+
return jsonify({'message': 'Conversation cleared'})
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
# ------------------------------------------------------------------ system
|
| 448 |
+
|
| 449 |
+
@api.get('/api/agent-status')
|
| 450 |
+
@login_required
|
| 451 |
+
def agent_status():
|
| 452 |
+
agents, recent = METRICS.snapshot()
|
| 453 |
+
coord = agents.pop('coordinator')
|
| 454 |
+
return jsonify({
|
| 455 |
+
'coordinator': {**coord, 'tasks_coordinated': coord['runs']},
|
| 456 |
+
'sub_agents': agents,
|
| 457 |
+
'total_memory': len(recent),
|
| 458 |
+
'recent_activity': recent,
|
| 459 |
+
'llm': svc().llm.info(),
|
| 460 |
+
'framework': 'LangGraph',
|
| 461 |
+
})
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
@api.get('/api/model-info')
|
| 465 |
+
def model_info():
|
| 466 |
+
s = svc()
|
| 467 |
+
return jsonify({
|
| 468 |
+
'knowledge_tracing': {'available': s.knowledge.kt.available, **s.knowledge.kt.meta},
|
| 469 |
+
'bkt_topics_fitted': len(s.knowledge.bkt.params),
|
| 470 |
+
'teaching_bandit': s.bandit.summary(),
|
| 471 |
+
'question_bank': {'total': QuestionBank.query.count(),
|
| 472 |
+
'llm_generated': QuestionBank.query.filter_by(source='llm').count()},
|
| 473 |
+
'cached_lessons': ContentLibrary.query.filter_by(content_type='lesson').count(),
|
| 474 |
+
'llm': s.llm.info(),
|
| 475 |
+
'agent_graph_mermaid': s.coordinator.mermaid(),
|
| 476 |
+
})
|
backend/services/__init__.py
ADDED
|
File without changes
|
backend/services/auth.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Stateless bearer-token auth (works across the Vercel -> HF Spaces origin boundary, where
|
| 3 |
+
third-party cookies are often blocked), with the Flask session cookie as a fallback.
|
| 4 |
+
"""
|
| 5 |
+
import functools
|
| 6 |
+
import threading
|
| 7 |
+
import time
|
| 8 |
+
from collections import defaultdict, deque
|
| 9 |
+
|
| 10 |
+
from flask import current_app, g, jsonify, request, session
|
| 11 |
+
from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _serializer():
|
| 15 |
+
return URLSafeTimedSerializer(current_app.config['SECRET_KEY'], salt='auth-token')
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def issue_token(user_id):
|
| 19 |
+
return _serializer().dumps({'uid': user_id})
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _user_from_token():
|
| 23 |
+
header = request.headers.get('Authorization', '')
|
| 24 |
+
if not header.startswith('Bearer '):
|
| 25 |
+
return None
|
| 26 |
+
try:
|
| 27 |
+
data = _serializer().loads(header[7:], max_age=current_app.config['TOKEN_MAX_AGE'])
|
| 28 |
+
return int(data['uid'])
|
| 29 |
+
except (BadSignature, SignatureExpired, KeyError, ValueError):
|
| 30 |
+
return None
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def current_user_id():
|
| 34 |
+
return _user_from_token() or session.get('user_id')
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def login_required(fn):
|
| 38 |
+
@functools.wraps(fn)
|
| 39 |
+
def wrapper(*args, **kwargs):
|
| 40 |
+
uid = current_user_id()
|
| 41 |
+
if not uid:
|
| 42 |
+
return jsonify({'error': 'Not logged in'}), 401
|
| 43 |
+
g.user_id = uid
|
| 44 |
+
return fn(*args, **kwargs)
|
| 45 |
+
return wrapper
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class RateLimiter:
|
| 49 |
+
"""Small in-process sliding-window limiter for LLM-backed endpoints."""
|
| 50 |
+
|
| 51 |
+
def __init__(self, limit, window_s):
|
| 52 |
+
self.limit, self.window = limit, window_s
|
| 53 |
+
self.hits = defaultdict(deque)
|
| 54 |
+
self.lock = threading.Lock()
|
| 55 |
+
|
| 56 |
+
def allow(self, key):
|
| 57 |
+
now = time.monotonic()
|
| 58 |
+
with self.lock:
|
| 59 |
+
q = self.hits[key]
|
| 60 |
+
while q and now - q[0] > self.window:
|
| 61 |
+
q.popleft()
|
| 62 |
+
if len(q) >= self.limit:
|
| 63 |
+
return False
|
| 64 |
+
q.append(now)
|
| 65 |
+
return True
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
LLM_LIMITER = RateLimiter(limit=30, window_s=60)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def rate_limited(fn):
|
| 72 |
+
@functools.wraps(fn)
|
| 73 |
+
def wrapper(*args, **kwargs):
|
| 74 |
+
if not LLM_LIMITER.allow(getattr(g, 'user_id', request.remote_addr)):
|
| 75 |
+
return jsonify({'error': 'Too many requests, please slow down a little.'}), 429
|
| 76 |
+
return fn(*args, **kwargs)
|
| 77 |
+
return wrapper
|