DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Merge PR #1368: account-scoped reading learning records
Bingxi Zhao (Frank)24da87ae4e0e
diff --cc deeptutor/api/routers/reading_extensions.pyindex 86899562a,a1a6e510d..3c0b1c1d0--- a/deeptutor/api/routers/reading_extensions.py+++ b/deeptutor/api/routers/reading_extensions.py@@@ -4,14 -4,13 +4,15 @@@ from __future__ import annotationimport asyncioimport inspect+import loggingimport refrom typing import Any+from uuid import uuid4from fastapi import APIRouter, HTTPException-from pydantic import BaseModel, Field, ValidationError+from pydantic import BaseModel, ConfigDict, Field, ValidationError+ from deeptutor.learning.storage import LearningStorefrom deeptutor.multi_user.learning_access import (allowed_reading_extensions,assert_learning_material,@@@ -81,18 -41,23 +82,35 @@@ def _verified_selection(candidate: strreturn value if value and value in _normal(unit_text) else ""+def _discard_late_worker_result(worker: asyncio.Future) -> None:+ """Retrieve abandoned worker failures and close unconsumed coroutines."""+ if worker.cancelled():+ return+ try:+ value = worker.result()+ if inspect.iscoroutine(value):+ value.close()+ except Exception:+ logger.exception("Reading extension worker failed after its request ended")+++ def _record_reading_activity(+ material_id: str,+ *,+ extension_id: str,+ action: str,+ locator: int,+ result_type: str,+ ) -> None:+ LearningStore().record_reading_activity(+ material_id,+ extension_id=extension_id,+ action=action,+ locator=locator,+ result_type=result_type,+ )++@router.get("/extensions")async def list_extensions() -> list[dict[str, Any]]:allowed = allowed_reading_extensions()@@@ -183,173 -140,35 +201,182 @@@ async def run_extension_action)if result.type not in extension.manifest.result_types:raise ValueError(f"Extension returned undeclared result type {result.type!r}.")+ dumped = result.model_dump()+ quiz_payload = dumped.get("payload")+ if dumped.get("type") == "quiz" and isinstance(quiz_payload, dict):+ await _persist_reading_quiz_pending(material_id, payload.locator, quiz_payload)- return dumpedexcept TimeoutError as exc:- registry.mark_timed_out(extension_id)+ logger.warning("Reading extension %s action %s timed out", extension_id, action)raise HTTPException(status_code=503,- detail={- "message": "This reading action is temporarily unavailable.",- "recoverable": True,- },+ detail=_unavailable_detail(reason="timed_out"),+ ) from exc+ except LLMError as exc:+ logger.warning(+ "Reading extension %s action %s failed via language model: %s",+ extension_id,+ action,+ exc,+ )+ raise HTTPException(+ status_code=503,+ detail=_unavailable_detail(+ reason=str(exc),+ message="This reading action needs a working language model.",+ ),) from excexcept Exception as exc:+ logger.exception("Reading extension %s action %s failed", extension_id, action)raise HTTPException(status_code=503,- detail={- "message": "This reading action is temporarily unavailable.",- "recoverable": True,- },+ detail=_unavailable_detail(reason=str(exc)),) from excfinally:+ if worker is not None and not worker.done():+ registry.mark_timed_out(extension_id)+ worker.add_done_callback(_discard_late_worker_result)registry.finish_action(extension_id)+ await asyncio.to_thread(+ _record_reading_activity,+ material_id,+ extension_id=extension_id,+ action=action,+ locator=payload.locator,+ result_type=result.type,+ )- return result.model_dump()++ return dumped++++def _choice_map(choices: list[Any]) -> dict[str, str]:+ return {+ chr(65 + index): str(choice)+ for index, choice in enumerate(choices)+ if isinstance(choice, str) or choice is not None+ }+++def _material_title(material_id: str) -> str:+ try:+ manifest = ReadingStore().manifest(material_id)+ except Exception:+ return ""+ return str(getattr(manifest, "title", "") or getattr(manifest, "filename", "") or "")+++async def _persist_reading_quiz_pending(+ material_id: str, locator: int, payload: dict[str, Any]+) -> None:+ questions = payload.get("questions")+ if not isinstance(questions, list) or not questions:+ return+ from deeptutor.services.session import get_sqlite_session_store++ # A regenerated quiz must not reuse q_1 and grade an old card against a new key.+ quiz_id = uuid4().hex+ for index, question in enumerate(questions):+ if isinstance(question, dict):+ question["id"] = f"{quiz_id}:{index}"+ await get_sqlite_session_store().put_reading_quiz_pending(material_id, locator, questions)++[email protected]("/materials/{material_id}/extensions/quiz/answers")+async def submit_quiz_answers(material_id: str, payload: QuizAnswersPayload) -> dict[str, Any]:+ try:+ assert_learning_material(material_id)+ except PermissionError as exc:+ raise HTTPException(status_code=403, detail=str(exc)) from exc++ from deeptutor.learning.assessment import (+ AssessmentRecord,+ RecordAssessmentError,+ is_correct_to_result,+ record_assessment,+ )+ from deeptutor.services.session import get_sqlite_session_store++ store = get_sqlite_session_store()+ question_ids = [item.question_id.strip() for item in payload.answers]+ pending = await store.get_reading_quiz_pending(material_id, payload.locator, question_ids)+ missing = [qid for qid in question_ids if qid not in pending]+ if missing:+ raise HTTPException(status_code=409, detail="This reading quiz has expired.")++ # Validate the entire batch before saving any answers.+ for item in payload.answers:+ question = pending[item.question_id.strip()]+ choices = question.get("choices")+ correct_index = question.get("correct_choice_index")+ if (+ not isinstance(choices, list)+ or type(correct_index) is not int+ or not 0 <= correct_index < len(choices)+ ):+ raise HTTPException(+ status_code=409, detail="This reading quiz has an invalid answer key."+ )+ if item.selected_index >= len(choices):+ raise HTTPException(status_code=422, detail="Selected answer is outside the choices.")++ session_id = payload.session_id.strip()+ section_title = payload.section_title.strip() or payload.source_anchor.strip()+ material_title = _material_title(material_id)+ if session_id:+ if await store.get_session(session_id) is None:+ raise HTTPException(status_code=404, detail="Reading session not found.")+ origin_type = "conversation" if session_id else "document_analysis"+ origin_ref = session_id or f"reading:{material_id}"+ turn_id = payload.turn_id.strip() or f"reading:{material_id}:loc:{payload.locator}"+ graded: list[dict[str, Any]] = []+ for item in payload.answers:+ question = pending[item.question_id.strip()]+ choices = question.get("choices") if isinstance(question.get("choices"), list) else []+ try:+ correct_index = int(question.get("correct_choice_index"))+ except (TypeError, ValueError):+ correct_index = -1+ is_correct = item.selected_index == correct_index+ result = is_correct_to_result(is_correct)+ options = _choice_map(choices)+ selected_text = (+ str(choices[item.selected_index]) if 0 <= item.selected_index < len(choices) else ""+ )+ correct_text = str(choices[correct_index]) if 0 <= correct_index < len(choices) else ""+ try:+ await record_assessment(+ AssessmentRecord(+ session_id=session_id,+ origin_type=origin_type,+ origin_ref=origin_ref,+ turn_id=turn_id,+ question_id=item.question_id.strip(),+ question=str(question.get("prompt") or "Reading quiz"),+ question_type="choice",+ options=options,+ user_answer=selected_text,+ correct_answer=correct_text,+ is_correct=is_correct,+ result=result,+ source="immersive_reading",+ assessment_type="focus_check",+ material_id=material_id,+ material_title=material_title,+ section_id=str(payload.locator),+ section_title=section_title,+ mastery_path_id=str(question.get("mastery_path_id") or ""),+ knowledge_point_id=str(question.get("knowledge_point_id") or ""),+ )+ )+ except RecordAssessmentError as exc:+ raise HTTPException(status_code=500, detail=str(exc)) from exc+ graded.append(+ {+ "question_id": item.question_id.strip(),+ "is_correct": is_correct,+ "result": result,+ }+ )+ return {"answers": graded}__all__ = ["router"]diff --cc deeptutor/learning/models.pyindex 34a37ea57,baef7372d..8c5b72104--- a/deeptutor/learning/models.py+++ b/deeptutor/learning/models.py@@@ -543,6 -529,8 +587,9 @@@ __all__ ="TopicMetadata","MasteryTopic","LearnerMasteryOverride",+ "DeferredObjective",+ "ReadingActivityRecord",+ "ReadingLearningRecords",+ "ReadingProgressRecord","LearningProgress",]