Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

Block 17: Server-side question answer persistence, eliminate client-supplied expected_answer

whf526bc1c5508b
diff --git a/deeptutor/api/routers/guided_learning.py b/deeptutor/api/routers/guided_learning.py
index d0e1be11a..62ce7d4e0 100644
--- a/deeptutor/api/routers/guided_learning.py
+++ b/deeptutor/api/routers/guided_learning.py
@@ -55,7 +55,6 @@ class AnswerRequest(BaseModel):
knowledge_point_id: str
module_id: str = ""
user_answer: str = ""
- expected_answer: str = ""
self_attribution: str = ""
@@ -86,20 +85,20 @@ async def submit_answer(book_id: str, body: AnswerRequest):
progress = service.get_or_create(book_id)
- if not body.expected_answer.strip():
- raise HTTPException(status_code=400, detail="expected_answer is required for server-side grading")
-
- # TODO: expected_answer currently comes from the client because there is no
- # server-side question store. Once questions are persisted server-side,
- # look up the expected answer by question_id instead of trusting the caller.
+ # Look up expected answer from server-side store
+ store = LearningStore()
+ all_answers = store.load_question_answers(book_id)
+ expected_answer = all_answers.get(body.question_id, "")
+ if not expected_answer:
+ raise HTTPException(status_code=400, detail=f"No stored answer for question_id={body.question_id}")
# Server-side grading
- is_correct = _grade_answer(body.user_answer, body.expected_answer)
+ is_correct = _grade_answer(body.user_answer, expected_answer)
# Classify error type if wrong
error_type = None
if not is_correct:
- error_type = _classify_error(body.user_answer, body.expected_answer)
+ error_type = _classify_error(body.user_answer, expected_answer)
attempt = QuizAttempt(
question_id=body.question_id,
diff --git a/deeptutor/capabilities/guided_learning.py b/deeptutor/capabilities/guided_learning.py
index 9d5596ef7..31041ce4f 100644
--- a/deeptutor/capabilities/guided_learning.py
+++ b/deeptutor/capabilities/guided_learning.py
@@ -77,6 +77,7 @@ class GuidedLearningCapability(BaseCapability):
) -> None:
if service is not None:
self._service = service
+ self._store = service._store
else:
self._store = store or LearningStore()
self._service = LearningService(self._store)
@@ -107,6 +108,41 @@ class GuidedLearningCapability(BaseCapability):
except json.JSONDecodeError:
return default or {}
+ # ── Answer extraction ───────────────────────────────────────────────
+
+ @staticmethod
+ def _extract_answers(data: dict, prefix: str) -> dict[str, str]:
+ """Extract {question_id: answer} from LLM response data."""
+ answers: dict[str, str] = {}
+ questions = data.get("questions", [])
+ for i, ans in enumerate(data.get("answers", [])):
+ qid = f"{prefix}_{i}"
+ if i < len(questions) and isinstance(questions[i], dict):
+ qid = questions[i].get("question_id") or questions[i].get("id") or qid
+ answers[qid] = str(ans)
+ for i, ex in enumerate(data.get("exercises", [])):
+ if isinstance(ex, dict) and "answer" in ex:
+ qid = ex.get("question_id") or ex.get("id") or f"{prefix}_{i}"
+ answers[qid] = str(ex["answer"])
+ for i, q in enumerate(data.get("questions", [])):
+ if isinstance(q, dict) and "answer" in q:
+ qid = q.get("question_id") or q.get("id") or f"{prefix}_{i}"
+ answers[qid] = str(q["answer"])
+ return answers
+
+ @staticmethod
+ def _inject_question_ids(data: dict, prefix: str) -> dict:
+ """Add question_ids array so clients can reference server-stored answers."""
+ items = data.get("questions") or data.get("exercises") or []
+ ids = []
+ for i, item in enumerate(items):
+ if isinstance(item, dict):
+ ids.append(item.get("question_id") or item.get("id") or f"{prefix}_{i}")
+ else:
+ ids.append(f"{prefix}_{i}")
+ data["question_ids"] = ids
+ return data
+
# ── RAG retrieval ───────────────────────────────────────────────────
async def _retrieve_context(self, query: str) -> str:
@@ -171,6 +207,9 @@ class GuidedLearningCapability(BaseCapability):
async with stream.stage("diagnostic_phase1", source=self.manifest.name):
response = await self._call_llm(DIAGNOSTIC_PHASE1_SYSTEM, DIAGNOSTIC_PHASE1_USER)
data = self._safe_json_parse(response, default={"questions": [], "answers": []})
+ answers = self._extract_answers(data, "diag1")
+ self._store.save_question_answers(self._resolve_book_id(context), answers)
+ self._inject_question_ids(data, "diag1")
progress.diagnostic = DiagnosticResult(
total_questions=len(data.get("questions", [])),
phase1_result=data,
@@ -184,9 +223,12 @@ class GuidedLearningCapability(BaseCapability):
async with stream.stage("diagnostic_phase2", source=self.manifest.name):
response = await self._call_llm(DIAGNOSTIC_PHASE2_SYSTEM, DIAGNOSTIC_PHASE2_USER)
data = self._safe_json_parse(response, default={})
+ answers = self._extract_answers(data, "diag2")
+ self._store.save_question_answers(self._resolve_book_id(context), answers)
+ self._inject_question_ids(data, "diag2")
if progress.diagnostic is not None:
progress.diagnostic.phase2_results = {"phase2": data}
- await stream.content(response)
+ await stream.content(json.dumps(data, ensure_ascii=False))
self._service.advance_stage(progress, LearningStage.METACOGNITIVE_INTRO)
async def _run_metacognitive_intro(
@@ -285,10 +327,15 @@ class GuidedLearningCapability(BaseCapability):
self, progress: LearningProgress, context: UnifiedContext, stream: StreamBus
) -> None:
async with stream.stage("practice", source=self.manifest.name):
+ prefix = f"{progress.current_module_id}_practice" if progress.current_module_id else "practice"
response = await self._call_llm(
PRACTICE_SYSTEM, PRACTICE_USER.format(module_name=self._current_module_name(progress))
)
- await stream.content(response)
+ data = self._safe_json_parse(response, default={})
+ answers = self._extract_answers(data, prefix)
+ self._store.save_question_answers(self._resolve_book_id(context), answers)
+ self._inject_question_ids(data, prefix)
+ await stream.content(json.dumps(data, ensure_ascii=False))
self._service.advance_stage(progress, LearningStage.ERROR_DIAGNOSIS)
async def _run_error_diagnosis(
@@ -303,10 +350,15 @@ class GuidedLearningCapability(BaseCapability):
self, progress: LearningProgress, context: UnifiedContext, stream: StreamBus
) -> None:
async with stream.stage("module_test", source=self.manifest.name):
+ prefix = f"{progress.current_module_id}_modtest" if progress.current_module_id else "modtest"
response = await self._call_llm(
MODULE_TEST_SYSTEM, MODULE_TEST_USER.format(module_name=self._current_module_name(progress))
)
- await stream.content(response)
+ data = self._safe_json_parse(response, default={})
+ answers = self._extract_answers(data, prefix)
+ self._store.save_question_answers(self._resolve_book_id(context), answers)
+ self._inject_question_ids(data, prefix)
+ await stream.content(json.dumps(data, ensure_ascii=False))
self._init_repetition_states(progress)
self._service.advance_stage(progress, LearningStage.REVIEW)
diff --git a/deeptutor/learning/storage.py b/deeptutor/learning/storage.py
index 154f5f3db..908b42a4d 100644
--- a/deeptutor/learning/storage.py
+++ b/deeptutor/learning/storage.py
@@ -50,5 +50,29 @@ class LearningStore:
def exists(self, book_id: str) -> bool:
return self._path(book_id).exists()
+ def _questions_path(self, book_id: str) -> Path:
+ if "/" in book_id or "\\" in book_id or ".." in book_id or ":" in book_id:
+ raise ValueError(f"Invalid book_id: {book_id!r}")
+ return self._root / "questions" / f"{book_id}.json"
+
+ def save_question_answers(self, book_id: str, answers: dict[str, str]) -> None:
+ """Save generated question answers for server-side grading."""
+ import json
+
+ path = self._questions_path(book_id)
+ existing = self.load_question_answers(book_id)
+ existing.update(answers)
+ text = json.dumps(existing, ensure_ascii=False, indent=2)
+ _atomic_write_text(path, text)
+
+ def load_question_answers(self, book_id: str) -> dict[str, str]:
+ """Load question answers. Returns {} if none saved."""
+ import json
+
+ path = self._questions_path(book_id)
+ if not path.exists():
+ return {}
+ return json.loads(path.read_text(encoding="utf-8"))
+
__all__ = ["LearningStore"]
diff --git a/web/lib/learning-api.ts b/web/lib/learning-api.ts
index ad7e66ac2..ec253dd2f 100644
--- a/web/lib/learning-api.ts
+++ b/web/lib/learning-api.ts
@@ -5,7 +5,6 @@ export interface AnswerRequest {
knowledge_point_id: string;
module_id?: string;
user_answer: string;
- expected_answer: string;
self_attribution?: string;
}