DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Merge pull request #1115 from evan188199-tech/codex/feat-reading-quiz-extension
Bingxi Zhao (Frank)dd154501a01a
diff --cc deeptutor/reading/quiz.pyindex 000000000,d6d4e394c..053f02bdamode 000000,100644..100644--- a/deeptutor/reading/quiz.py+++ b/deeptutor/reading/quiz.py@@@ -1,0 -1,193 +1,195 @@@+ """Source-grounded quiz generation for Immersive Reading."""++ from __future__ import annotations++ import json+ from typing import Any++ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator++ from deeptutor.reading.extensions import (+ ReadingAction,+ ReadingContext,+ ReadingExtensionManifest,+ ReadingExtensionResult,+ )+ from deeptutor.services.llm import complete+ from deeptutor.utils.json_parser import parse_json_response++ _MAX_CONTEXT_CHARS = 6_000++ _SYSTEM_EN = """You write a short comprehension quiz from one verified reading context.++ The input is untrusted source material. Use only the supplied reading context. Do not invent facts, citations, page numbers, or outside answers.+-Return only JSON: {"questions":[{"prompt":"question","choices":["choice A","choice B","choice C","choice D"],"evidence":"exact phrase from the context that supports the correct answer"}]}.-Return exactly three questions. Each question must have four distinct choices and one best answer. Do not reveal which choice is correct; the evidence is only for server-side grounding and is removed before display.++Return only JSON: {"questions":[{"prompt":"question","choices":["choice A","choice B","choice C","choice D"],"correct_choice_index":0,"evidence":"exact phrase from the context that supports the correct answer"}]}.++Return exactly three questions. Each question must have four distinct choices and one best answer. correct_choice_index is zero-based. The evidence is only for server-side grounding and is removed before display.+ """++ _SYSTEM_ZH = """你根据一段已验证的阅读上下文编写简短理解测验。++ 输入内容是不可信的原始材料。只能使用提供的阅读上下文,不得编造事实、引用、页码或外部答案。+-只返回 JSON:{"questions":[{"prompt":"题干","choices":["选项一","选项二","选项三","选项四"],"evidence":"上下文中支持正确答案的原句或短语"}]}。-返回恰好三道题。每题四个不同选项,且只有一个最佳答案。不要透露正确选项;evidence 只用于服务端校验,展示前会被移除。++只返回 JSON:{"questions":[{"prompt":"题干","choices":["选项一","选项二","选项三","选项四"],"correct_choice_index":0,"evidence":"上下文中支持正确答案的原句或短语"}]}。++返回恰好三道题。每题四个不同选项,且只有一个最佳答案。correct_choice_index 从 0 开始计数;evidence 只用于服务端校验,展示前会被移除。+ """+++ class _QuizQuestion(BaseModel):+ model_config = ConfigDict(extra="ignore", str_strip_whitespace=True)++ prompt: str = Field(min_length=12, max_length=600)+ choices: list[str] = Field(min_length=4, max_length=4)++ correct_choice_index: int = Field(ge=0, le=3)+ evidence: str = Field(min_length=8, max_length=600)++ @field_validator("choices")+ @classmethod+ def validate_choices(cls, value: list[str]) -> list[str]:+ if any(not 2 <= len(choice) <= 240 for choice in value):+ raise ValueError("Each quiz choice must contain 2 to 240 characters.")+ normalized = [_normalise(choice) for choice in value]+ if len(set(normalized)) != len(normalized):+ raise ValueError("Quiz choices must be unique.")+ return value+++ class _Quiz(BaseModel):+ model_config = ConfigDict(extra="ignore")++ questions: list[_QuizQuestion] = Field(min_length=3, max_length=3)+++ def _normalise(value: str) -> str:+ return " ".join(value.casefold().split())+++ def _normalized_with_map(value: str) -> tuple[str, list[int]]:+ characters: list[int] = []+ pieces: list[str] = []+ previous_was_space = False+ for index, character in enumerate(value):+ if character.isspace():+ if pieces and not previous_was_space:+ pieces.append(" ")+ previous_was_space = True+ continue+ characters.append(index)+ pieces.append(character)+ previous_was_space = False+ return "".join(pieces).strip(), characters+++ def _selection_range(text: str, selection: str) -> tuple[int, int] | None:+ exact = text.find(selection)+ if exact >= 0:+ return exact, exact + len(selection)++ normalized_text, positions = _normalized_with_map(text)+ normalized_selection, _ = _normalized_with_map(selection)+ found = normalized_text.find(normalized_selection)+ if found < 0 or not positions:+ return None+ start = positions[found]+ end = positions[min(found + len(normalized_selection), len(positions)) - 1] + 1+ return start, end+++ def _grounding_context(text: str, selection: str) -> str:+ if not selection:+ return text[:_MAX_CONTEXT_CHARS]+ bounds = _selection_range(text, selection)+ if bounds is None:+ return text[:_MAX_CONTEXT_CHARS]+ start, end = bounds+ prefix_len = min(2_000, start)+ suffix_len = min(2_000, max(0, len(text) - end))+ prefix_start = max(0, start - prefix_len)+ suffix_end = min(len(text), end + suffix_len)+ return text[prefix_start:suffix_end][:_MAX_CONTEXT_CHARS]+++ def _is_zh(locale: str) -> bool:+ return locale.lower().startswith("zh")+++ def _prompt(context: ReadingContext) -> str:+ return json.dumps(+ {+ "selection": context.selection,+ "surrounding_context": _grounding_context(+ context.visible_text,+ context.selection,+ ),+ },+ ensure_ascii=False,+ )+++ def _quiz(raw: str, context: ReadingContext) -> _Quiz:+ data: Any = parse_json_response(raw, fallback=None)+ if not isinstance(data, dict):+ raise ValueError("Reading quiz model returned invalid JSON.")+ try:+ quiz = _Quiz.model_validate({"questions": data.get("questions")})+ except ValidationError as exc:+ raise ValueError("Reading quiz model returned an invalid shape.") from exc++ normalized_context = _normalise(context.visible_text)+ if any(_normalise(question.evidence) not in normalized_context for question in quiz.questions):+ raise ValueError("Reading quiz evidence must come from the reading context.")+ return quiz+++ class ReadingQuizExtension:+ """Return bounded comprehension questions grounded in the current unit."""++ manifest = ReadingExtensionManifest(+ id="quiz",+ version="1.0.0",+ name="Reading quiz",+ actions=[+ ReadingAction(id="start", label="Quiz me", requires=["visible_text"]),+ ],+ result_types=["quiz"],+ )++ async def run_action(self, action: str, context: ReadingContext) -> ReadingExtensionResult:+ if action != "start":+ raise ValueError(f"Unsupported reading-quiz action: {action}")+ if not context.visible_text.strip():+ raise ValueError("Reading quiz requires visible text.")++ from deeptutor.services.model_selection.tasks import task_llm_scope++ with task_llm_scope():+ raw = await complete(+ prompt=_prompt(context),+ system_prompt=_SYSTEM_ZH if _is_zh(context.locale) else _SYSTEM_EN,+ temperature=0.3,+ max_tokens=1000,+ max_retries=0,+ response_format={"type": "json_object"},+ )+ quiz = _quiz(raw, context)+ return ReadingExtensionResult(+ type="quiz",+ title="阅读测验" if _is_zh(context.locale) else "Reading quiz",+ message="Questions use the current passage."+ if not _is_zh(context.locale)+ else "题目基于当前段落。",+ payload={+ "questions": [+ {+ "id": f"q_{index}",+ "prompt": question.prompt,+ "choices": question.choices,++ "correct_choice_index": question.correct_choice_index,+ }+ for index, question in enumerate(quiz.questions, start=1)+ ]+ },+ )+++ __all__ = ["ReadingQuizExtension"]diff --cc pyproject.tomlindex a320b5ac0,836445495..c725ef74f--- a/pyproject.toml+++ b/pyproject.toml@@@ -85,9 -84,7 +85,10 @@@ dependencies =deeptutor = "deeptutor_cli.main:main"[project.entry-points."deeptutor.reading_extensions"]+read_aloud = "deeptutor.reading.read_aloud:ReadAloudExtension"+guided_learning = "deeptutor.reading.study_guidance:StudyGuidanceExtension"+vocabulary = "deeptutor.reading.vocabulary:VocabularyExtension"+ quiz = "deeptutor.reading.quiz:ReadingQuizExtension"[project.optional-dependencies]# Compatibility extra for source installs and older docs. These packages arediff --cc tests/reading/test_quiz.pyindex 000000000,9d42b6b0b..d7ccf76d7mode 000000,100644..100644--- a/tests/reading/test_quiz.py+++ b/tests/reading/test_quiz.py@@@ -1,0 -1,213 +1,216 @@@+ from __future__ import annotations++ import json+ from pathlib import Path+ import tomllib++ from fastapi import FastAPI+ from fastapi.testclient import TestClient+ import pytest++ from deeptutor.api.routers import reading_extensions+ from deeptutor.reading import ReadingStore+ from deeptutor.reading.extensions import ReadingContext, ReadingExtensionRegistry+ from deeptutor.reading.quiz import ReadingQuizExtension+ from deeptutor.services.path_service import PathService+++ def _context(selection: str = "") -> ReadingContext:+ return ReadingContext(+ material_id="material",+ locator=1,+ locale="en",+ selection=selection,+ visible_text=("Before context verified phrase supports the answer after context " * 4),+ )+++ def _model_response(evidence: str = "verified phrase supports the answer") -> str:+ return json.dumps(+ {+ "questions": [+ {+ "prompt": "Which phrase does the passage verify?",+ "choices": [+ "An unrelated phrase",+ "A checked phrase",+ "A guessed phrase",+ "An omitted phrase",+ ],++ "correct_choice_index": 1,+ "evidence": evidence,+ }+ ]+ * 3+ }+ )+++ @pytest.mark.asyncio+ async def test_quiz_returns_a_bounded_quiz_without_grounding_metadata(monkeypatch):+ calls = []++ async def complete(**kwargs):+ calls.append(kwargs)+ return _model_response()++ monkeypatch.setattr("deeptutor.reading.quiz.complete", complete)+ result = await ReadingQuizExtension().run_action("start", _context())++ assert result.type == "quiz"+ assert result.title == "Reading quiz"+ assert result.message == "Questions use the current passage."+ assert len(result.payload["questions"]) == 3+ assert result.payload["questions"][0] == {+ "id": "q_1",+ "prompt": "Which phrase does the passage verify?",+ "choices": [+ "An unrelated phrase",+ "A checked phrase",+ "A guessed phrase",+ "An omitted phrase",+ ],++ "correct_choice_index": 1,+ }+ assert calls[0]["response_format"] == {"type": "json_object"}+++ @pytest.mark.asyncio+ async def test_quiz_bounds_and_centers_the_verified_context(monkeypatch):+ text = "".join(f"sentence {index} " for index in range(2_000))+ selection = "sentence 1999"+ calls = []++ async def complete(**kwargs):+ calls.append(kwargs)+ return _model_response(evidence=selection)++ monkeypatch.setattr("deeptutor.reading.quiz.complete", complete)+ await ReadingQuizExtension().run_action(+ "start",+ ReadingContext(+ material_id="material",+ locator=1,+ selection=selection,+ visible_text=text,+ ),+ )++ prompt = json.loads(calls[0]["prompt"])+ assert len(prompt["surrounding_context"]) <= 6_000+ assert selection in prompt["surrounding_context"]+++ @pytest.mark.asyncio+ async def test_missing_visible_text_fails_before_an_llm_call(monkeypatch):+ async def complete(**_kwargs):+ pytest.fail("missing visible text must not invoke the model")++ monkeypatch.setattr("deeptutor.reading.quiz.complete", complete)+ with pytest.raises(ValueError, match="requires visible text"):+ await ReadingQuizExtension().run_action(+ "start",+ ReadingContext(+ material_id="material",+ locator=1,+ visible_text=" ",+ ),+ )+++ @pytest.mark.parametrize(+ "response",+ [+ "not json",+ json.dumps({"questions": []}),+ json.dumps(+ {+ "questions": [+ {+ "prompt": "Which phrase does the passage verify?",+ "choices": [+ "A checked phrase",+ "A checked phrase",+ "A guessed phrase",+ "An omitted phrase",+ ],++ "correct_choice_index": 0,+ "evidence": "verified phrase supports the answer",+ }+ ]+ * 3+ }+ ),+ _model_response(evidence="outside facts are forbidden"),+ ],+ )+ @pytest.mark.asyncio+ async def test_invalid_or_ungrounded_model_output_is_rejected(monkeypatch, response):+ async def complete(**_kwargs):+ return response++ monkeypatch.setattr("deeptutor.reading.quiz.complete", complete)+ with pytest.raises(ValueError):+ await ReadingQuizExtension().run_action("start", _context())+++ def test_quiz_is_registered_as_a_packaged_extension():+ project = tomllib.loads(Path("pyproject.toml").read_text(encoding="utf-8"))+ group = project["project"]["entry-points"]["deeptutor.reading_extensions"]++ assert group["quiz"] == "deeptutor.reading.quiz:ReadingQuizExtension"+++ def _client(monkeypatch) -> TestClient:+ registry = ReadingExtensionRegistry([ReadingQuizExtension()])+ monkeypatch.setattr(+ reading_extensions,+ "get_reading_extension_registry",+ lambda: registry,+ )+ app = FastAPI()+ app.include_router(reading_extensions.router, prefix="/api/v1/reading")+ return TestClient(app)+++ def test_quiz_crosses_the_api_boundary_with_stored_text(monkeypatch, tmp_path):+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))+ PathService.reset_instance()+ source = tmp_path / "source.txt"+ source.write_text(+ "Stored passage where a verified phrase supports the answer.",+ encoding="utf-8",+ )+ material = ReadingStore().ingest(source)+ captured = {}++ async def complete(**kwargs):+ captured.update(kwargs)+ return _model_response(evidence="verified phrase supports the answer")++ monkeypatch.setattr("deeptutor.reading.quiz.complete", complete)+ client = _client(monkeypatch)+ try:+ response = client.post(+ f"/api/v1/reading/materials/{material.material_id}/extensions/quiz/actions/start",+ json={+ "locator": 1,+ "selection": "verified phrase supports the answer",+ "visible_text": "forged phrase",+ "locale": "en",+ },+ )+ finally:+ PathService.reset_instance()++ assert response.status_code == 200, response.text+ body = response.json()+ assert body["type"] == "quiz"+ assert len(body["payload"]["questions"]) == 3+ prompt = json.loads(captured["prompt"])+ assert prompt["selection"] == "verified phrase supports the answer"+ assert (+ "Stored passage where a verified phrase supports the answer."+ in prompt["surrounding_context"]+ )+ assert "forged phrase" not in prompt["surrounding_context"]diff --cc web/components/reading/ReadingExtensionBar.tsxindex 24e71d6c1,bfa99394f..cda981ac4--- a/web/components/reading/ReadingExtensionBar.tsx+++ b/web/components/reading/ReadingExtensionBar.tsx@@@ -10,12 -10,6 +10,19 @@@ importtype ReadingExtensionResult,} from "@/lib/reading-api";+type VocabularyTerm = {+ term: string;+ meaning: string;+ usage: string;+};+++type QuizQuestion = {++ id?: string;++ prompt: string;++ choices: string[];++ correct_choice_index?: number;++};++export function ReadingExtensionBar({materialId,locator,@@@ -168,15 -130,9 +175,18 @@@}function builtInActionLabel(extensionId: string, actionId: string) {+ if (extensionId === "read_aloud" && actionId === "read") {+ return "Read aloud";+ }+ if (extensionId === "guided_learning" && actionId === "guide") {+ return "Guide me";+ }+ if (extensionId === "vocabulary" && actionId === "explain") {+ return "Explain vocabulary";+ }+ if (extensionId === "quiz" && actionId === "start") {+ return "Quiz me";+ }return "";}@@@ -190,11 -146,11 +200,7 @@@ function ExtensionResult(onClose: () => void;}) {const questions = Array.isArray(result.payload.questions)-- ? (result.payload.questions as Array<{-- id?: string;-- prompt: string;-- choices: string[];-- }>)++ ? (result.payload.questions as QuizQuestion[]): [];const items = Array.isArray(result.payload.items)? result.payload.items.map(String)@@@ -238,33 -178,8 +244,51 @@@))}</ul>) : null}- {questions.map((question, index) => (- <div key={question.id || index} className="mt-3">+ {steps.length ? (+ <ol className="mt-2 list-decimal space-y-1 pl-5">+ {steps.map((step, index) => (+ <li key={`${index}-${step}`}>{step}</li>+ ))}+ </ol>+ ) : null}+ {terms.length ? (+ <dl className="mt-2 space-y-2">+ {terms.map((term, index) => (+ <div+ key={`${index}-${term.term}`}+ className="border-t border-[var(--border)] pt-2 first:border-t-0 first:pt-0"+ >+ <dt className="font-medium">{term.term}</dt>+ <dd className="mt-1 text-[var(--muted-foreground)]">+ {term.meaning}+ </dd>+ <dd className="mt-1 text-[var(--muted-foreground)]">+ {term.usage}+ </dd>+ </div>+ ))}+ </dl>+ ) : null}- {questions.map((question, index) => (- <div key={question.id || index} className="mt-3">++ {questions.length ? <QuizQuestions questions={questions} /> : null}++ </section>++ );++}++++function QuizQuestions({ questions }: { questions: QuizQuestion[] }) {++ const { t } = useTranslation();++ const [answers, setAnswers] = useState<Record<string, number>>({});++++ return questions.map((question, index) => {++ const key = question.id || String(index);++ const selected = answers[key];++ const correctChoiceIndex = Number.isInteger(question.correct_choice_index)++ ? Number(question.correct_choice_index)++ : -1;++ const canGrade =++ correctChoiceIndex >= 0 && correctChoiceIndex < question.choices.length;++ if (!canGrade) {++ return (++ <div key={key} className="mt-3"><p className="font-medium">{question.prompt}</p><ol className="mt-1 list-inside list-[upper-alpha] space-y-0.5 text-[var(--muted-foreground)]">{question.choices.map((choice) => (@@@ -272,7 -187,7 +296,39 @@@))}</ol></div>-- ))}-- </section>-- );++ );++ }++ return (++ <fieldset key={key} className="mt-3">++ <legend className="font-medium">{question.prompt}</legend>++ <div className="mt-1 grid gap-1">++ {question.choices.map((choice, choiceIndex) => (++ <button++ key={choice}++ type="button"++ aria-pressed={selected === choiceIndex}++ onClick={() =>++ setAnswers((current) => ({ ...current, [key]: choiceIndex }))++ }++ className="rounded-md border border-[var(--border)] px-2 py-1.5 text-left text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] aria-pressed:bg-[var(--muted)] aria-pressed:text-[var(--foreground)]"++ >++ {String.fromCharCode(65 + choiceIndex)}. {choice}++ </button>++ ))}++ </div>++ {selected !== undefined ? (++ <p++ role="status"++ className={`mt-1 font-medium ${++ selected === correctChoiceIndex++ ? "text-emerald-600 dark:text-emerald-400"++ : "text-amber-600 dark:text-amber-400"++ }`}++ >++ {selected === correctChoiceIndex ? t("Correct") : t("Incorrect")}++ </p>++ ) : null}++ </fieldset>++ );++ });}diff --cc web/locales/en/app.jsonindex 4626cb99c,b00a72d19..cafe3ea08--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@@ -494,7 -434,7 +494,8 @@@"View": "View","Close": "Close","No speech voice is available in this browser.": "No speech voice is available in this browser.",+ "Explain vocabulary": "Explain vocabulary",+ "Quiz me": "Quiz me","messages": "messages","Failed to load session": "Failed to load session","Added Successfully!": "Added Successfully!",diff --cc web/locales/zh/app.jsonindex e9f0bc8ab,e0959d0f4..e4d446d88--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@@ -494,7 -434,7 +494,8 @@@"View": "查看","Close": "关闭","No speech voice is available in this browser.": "此浏览器没有可用的语音。",+ "Explain vocabulary": "解释词汇",+ "Quiz me": "测一测","messages": "条消息","Failed to load session": "加载会话失败","Added Successfully!": "保存成功!",diff --cc web/tests/reading-extensions.test.tsindex 05ca7f9ab,a6361193f..584937a2b--- a/web/tests/reading-extensions.test.ts+++ b/web/tests/reading-extensions.test.ts@@@ -41,57 -47,9 +41,72 @@@ test("a malformed extension catalog can);});+test("browser speech is stoppable and cannot continue after navigation", () => {+ assert.match(component, /const \[speaking, setSpeaking\] = useState\(false\)/);+ assert.match(component, /function stopSpeaking\(\)/);+ assert.match(component, /window\.speechSynthesis\?\.cancel\(\)/);+ assert.match(component, /utterance\.onend = \(\) => setSpeaking\(false\)/);+ assert.match(component, /utterance\.onerror = \(\) => setSpeaking\(false\)/);+ assert.match(component, /\}, \[locator, materialId\]\);/);+ assert.match(component, /aria-label=\{t\("Stop reading aloud"\)\}/);+});++test("the built-in read-aloud action is localized", () => {+ assert.match(+ component,+ /extensionId === "read_aloud" && actionId === "read"/,+ );+ assert.match(english, /"Read aloud": "Read aloud"/);+ assert.match(chinese, /"Read aloud": "朗读"/);+ assert.match(english, /"Reading aloud": "Reading aloud"/);+ assert.match(chinese, /"Reading aloud": "正在朗读"/);+ assert.match(english, /"Stop reading aloud": "Stop reading aloud"/);+ assert.match(chinese, /"Stop reading aloud": "停止朗读"/);+});++test("the built-in study-guidance action is localized", () => {+ assert.match(component, /function builtInActionLabel/);+ assert.match(+ component,+ /extensionId === "guided_learning" && actionId === "guide"/,+ );+ assert.match(component, /t\(builtInLabel\)/);+ assert.match(english, /"Guide me": "Guide me"/);+ assert.match(chinese, /"Guide me": "引导我"/);+});++test("study-guidance steps are visible in the result card", () => {+ assert.match(component, /result\.payload\.steps/);+ assert.match(component, /steps\.map\(\(step, index\) =>/);+ assert.match(component, /list-decimal/);+});++test("the built-in vocabulary action is localized", () => {+ assert.match(component, /extensionId === "vocabulary" && actionId === "explain"/);+ assert.match(english, /"Explain vocabulary": "Explain vocabulary"/);+ assert.match(chinese, /"Explain vocabulary": "解释词汇"/);+});++test("vocabulary terms are visible in the result card", () => {+ assert.match(component, /result\.payload\.terms/);+ assert.match(component, /String\(term\.term \|\| ""\)/);+ assert.match(component, /terms\.map\(\(term, index\) =>/);+ assert.match(component, /<dt className="font-medium">\{term\.term\}<\/dt>/);+ assert.match(component, /\{term\.meaning\}/);+ assert.match(component, /\{term\.usage\}/);+});+++ test("the built-in reading-quiz action is localized", () => {+ assert.match(component, /extensionId === "quiz" && actionId === "start"/);+ assert.match(component, /t\(builtInLabel\)/);+ assert.match(english, /"Quiz me": "Quiz me"/);+ assert.match(chinese, /"Quiz me": "测一测"/);+ });++++test("reading quizzes reveal grading only after the learner answers", () => {++ assert.match(component, /correct_choice_index\?: number/);++ assert.match(component, /const \[answers, setAnswers\] = useState/);++ assert.match(component, /aria-pressed=\{selected === choiceIndex\}/);++ assert.match(component, /selected === correctChoiceIndex/);++ assert.match(component, /t\("Correct"\).*t\("Incorrect"\)/s);++});