DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Block 19: Interactive diagnostic phases — wait_for_input, server-side grading, answer stripping, correct_count, CLI timeout
whf5451aa60b4d3
diff --git a/deeptutor/capabilities/guided_learning.py b/deeptutor/capabilities/guided_learning.pyindex 31041ce4f..89c3c95d0 100644--- a/deeptutor/capabilities/guided_learning.py+++ b/deeptutor/capabilities/guided_learning.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport jsonimport time+from typing import Anyfrom deeptutor.core.capability_protocol import BaseCapability, CapabilityManifestfrom deeptutor.core.context import UnifiedContext@@ -15,6 +16,7 @@ from deeptutor.learning.models import (LearningModule,LearningProgress,LearningStage,+ QuizAttempt,)from deeptutor.learning.scheduler import SpacedRepetitionSchedulerfrom deeptutor.learning.service import LearningService@@ -130,6 +132,15 @@ class GuidedLearningCapability(BaseCapability):answers[qid] = str(q["answer"])return answers+ _ANSWER_KEYS = {"answer", "correct_answer", "explanation", "solution"}++ @classmethod+ def _strip_answer(cls, question: Any) -> Any:+ """Remove answer-bearing fields from a question before streaming to client."""+ if not isinstance(question, dict):+ return question+ return {k: v for k, v in question.items() if k not in cls._ANSWER_KEYS}+@staticmethoddef _inject_question_ids(data: dict, prefix: str) -> dict:"""Add question_ids array so clients can reference server-stored answers."""@@ -207,14 +218,42 @@ 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": []})+ book_id = self._resolve_book_id(context)answers = self._extract_answers(data, "diag1")- self._store.save_question_answers(self._resolve_book_id(context), answers)+ self._store.save_question_answers(book_id, answers)self._inject_question_ids(data, "diag1")++ questions = data.get("questions", [])+ qids = data.get("question_ids", [])+ correct_count = 0+ for i, q in enumerate(questions):+ qid = qids[i] if i < len(qids) else f"diag1_{i}"+ await stream.content(+ json.dumps({"question": self._strip_answer(q), "question_id": qid}, ensure_ascii=False),+ source=self.manifest.name,+ )+ user_answer = await stream.wait_for_input("请回答", source=self.manifest.name, timeout=120)+ stored = self._store.load_question_answers(book_id)+ expected = stored.get(qid, "")+ is_correct = bool(expected) and user_answer.strip().lower() == expected.strip().lower()+ if is_correct:+ correct_count += 1+ self._service.record_quiz_attempt(+ progress,+ QuizAttempt(+ question_id=qid,+ knowledge_point_id="",+ module_id="",+ is_correct=is_correct,+ user_answer=user_answer,+ ),+ )+progress.diagnostic = DiagnosticResult(- total_questions=len(data.get("questions", [])),+ total_questions=len(questions),+ correct_count=correct_count,phase1_result=data,)- await stream.content(json.dumps(data, ensure_ascii=False))self._service.advance_stage(progress, LearningStage.DIAGNOSTIC_PHASE2)async def _run_diagnostic_phase2(@@ -223,12 +262,40 @@ 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={})+ book_id = self._resolve_book_id(context)answers = self._extract_answers(data, "diag2")- self._store.save_question_answers(self._resolve_book_id(context), answers)+ self._store.save_question_answers(book_id, answers)self._inject_question_ids(data, "diag2")++ questions = data.get("questions", [])+ qids = data.get("question_ids", [])+ correct_count = 0+ for i, q in enumerate(questions):+ qid = qids[i] if i < len(qids) else f"diag2_{i}"+ await stream.content(+ json.dumps({"question": self._strip_answer(q), "question_id": qid}, ensure_ascii=False),+ source=self.manifest.name,+ )+ user_answer = await stream.wait_for_input("请回答", source=self.manifest.name, timeout=120)+ stored = self._store.load_question_answers(book_id)+ expected = stored.get(qid, "")+ is_correct = bool(expected) and user_answer.strip().lower() == expected.strip().lower()+ if is_correct:+ correct_count += 1+ self._service.record_quiz_attempt(+ progress,+ QuizAttempt(+ question_id=qid,+ knowledge_point_id="",+ module_id="",+ is_correct=is_correct,+ user_answer=user_answer,+ ),+ )+if progress.diagnostic is not None:progress.diagnostic.phase2_results = {"phase2": data}- await stream.content(json.dumps(data, ensure_ascii=False))+ progress.diagnostic.phase2_correct_count = correct_countself._service.advance_stage(progress, LearningStage.METACOGNITIVE_INTRO)async def _run_metacognitive_intro(diff --git a/deeptutor/core/stream_bus.py b/deeptutor/core/stream_bus.pyindex 4ab32dcd8..664bb656c 100644--- a/deeptutor/core/stream_bus.py+++ b/deeptutor/core/stream_bus.py@@ -259,8 +259,15 @@ class StreamBus:prompt: str,source: str = "",stage: str = "",+ timeout: float | None = None,) -> str:- """Pause capability execution and wait for user input from the frontend."""+ """Pause capability execution and wait for user input from the frontend.++ Returns the user's input, or an empty string if *timeout* seconds elapse+ with no input (e.g. when running from a CLI that cannot send input).+ Pass ``timeout=None`` (the default) to wait indefinitely for interactive+ clients; pass a finite value for headless/CLI entry points.+ """await self.emit(StreamEvent(type=StreamEventType.WAIT_FOR_INPUT,@@ -272,7 +279,9 @@ class StreamBus:input_queue: asyncio.Queue[str] = asyncio.Queue()self._input_listeners.append(input_queue)try:- return await input_queue.get()+ return await asyncio.wait_for(input_queue.get(), timeout=timeout)+ except asyncio.TimeoutError:+ return ""finally:if input_queue in self._input_listeners:self._input_listeners.remove(input_queue)diff --git a/deeptutor/learning/models.py b/deeptutor/learning/models.pyindex d0f5ad477..44ea02625 100644--- a/deeptutor/learning/models.py+++ b/deeptutor/learning/models.py@@ -96,6 +96,8 @@ class DiagnosticResult(BaseModel):skipped_modules: list[str] = Field(default_factory=list)inferred_modules: list[str] = Field(default_factory=list)total_questions: int = 0+ correct_count: int = 0+ phase2_correct_count: int = 0phase1_result: dict = Field(default_factory=dict)phase2_results: dict[str, dict] = Field(default_factory=dict)