DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Merge remote-tracking branch 'origin/dev' into dev
Bingxi Zhao (Frank)367195b7cf3e
diff --cc deeptutor/api/routers/reading_extensions.pyindex 73a340280,5684afa2f..1b39a2261--- a/deeptutor/api/routers/reading_extensions.py+++ b/deeptutor/api/routers/reading_extensions.py@@@ -21,11 -22,29 +22,30 @@@ from deeptutor.reading.extensions imporReadingExtensionResult,get_reading_extension_registry,)+ from deeptutor.services.llm.exceptions import LLMErrorlogger = logging.getLogger(__name__)+router = APIRouter()- ACTION_TIMEOUT_S = 30+ # Quiz / translation / vocabulary all call an LLM. Thirty seconds is enough to+ # trip a hanging *sync* plugin, but too short for a grounded three-question+ # quiz on a reasoning model — and a timeout used to circuit-break the extension+ # for the rest of the process.+ ACTION_TIMEOUT_S = 120+++ def _unavailable_detail(+ *,+ reason: str = "",+ message: str = "This reading action is temporarily unavailable.",+ ) -> dict[str, Any]:+ detail: dict[str, Any] = {+ "message": message,+ "recoverable": True,+ }+ if reason:+ detail["reason"] = reason[:500]+ return detailclass ActionPayload(BaseModel):@@@ -111,30 -136,31 +149,33 @@@ async def run_extension_actionstatus_code=422,detail="This reading unit is too large for the extension protocol.",) from exc- if not registry.begin_action(extension_id):+ # Sync plugins run on a private worker we cannot kill; a timeout must+ # open the circuit so later clicks do not queue behind the stuck call.+ # Async plugins (quiz, translation, …) are cancelled with the request,+ # so a slow LLM must not disable the button for the rest of the process.+ run = extension.run_action+ sync_plugin = not inspect.iscoroutinefunction(run)+ if not registry.begin_action(extension_id, circuit_break=sync_plugin):raise HTTPException(status_code=503,- detail={- "message": "This reading action is temporarily unavailable.",- "recoverable": True,- },+ detail=_unavailable_detail(reason="busy_or_circuit_open"),)+ # Only a still-running worker needs the circuit kept open (#1448).+ # Async cancellation finishes before the reservation is released, including+ # sync handlers that return an awaitable after their worker has finished.+ worker: asyncio.Future | None = Nonetry:async with asyncio.timeout(ACTION_TIMEOUT_S):- if sync_plugin:- loop = asyncio.get_running_loop()- value = await loop.run_in_executor(- registry.executor_for(extension_id),- run,- action,- context,- )- if inspect.isawaitable(value):- value = await value+ handler = extension.run_action+ if inspect.iscoroutinefunction(handler):+ value = await handler(action, context)else:- value = await run(action, context)+ worker = asyncio.get_running_loop().run_in_executor(+ registry.executor_for(extension_id), handler, action, context+ )+ value = await asyncio.shield(worker)+ if inspect.isawaitable(value):+ value = await valueresult = (valueif isinstance(value, ReadingExtensionResult)@@@ -142,29 -168,50 +183,41 @@@)if result.type not in extension.manifest.result_types:raise ValueError(f"Extension returned undeclared result type {result.type!r}.")- return result.model_dump()+ 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:- if sync_plugin:- registry.mark_timed_out(extension_id)- logger.warning(- "Reading extension %s action %s timed out after %ss (sync=%s)",- extension_id,- action,- ACTION_TIMEOUT_S,- sync_plugin,- )+ 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,- )+ 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)diff --cc tests/reading/test_extension_router.pyindex a3fe4cc30,73fbd459e..a730975e6--- a/tests/reading/test_extension_router.py+++ b/tests/reading/test_extension_router.py@@@ -193,75 -212,67 +193,159 @@@ def test_timed_out_sync_extension_opensrelease.set()[email protected]("use_uvloop", [False, True])+def test_async_reading_action_runs_on_its_event_loop(material, monkeypatch, use_uvloop):+ """Vocabulary/translation actions must work under Uvicorn's uvloop (#1448)."""+ if use_uvloop:+ pytest.importorskip("uvloop")++ async def run(*_args):+ asyncio.get_running_loop()+ return ReadingExtensionResult(type="card", payload={"body": "translated"})++ registry = ReadingExtensionRegistry([_extension(run)])+ monkeypatch.setattr(reading_extensions, "get_reading_extension_registry", lambda: registry)+ app = FastAPI()+ app.include_router(reading_extensions.router, prefix="/api/reading")+ with TestClient(app, backend_options={"use_uvloop": use_uvloop}) as client:+ response = client.post(+ f"/api/reading/materials/{material.material_id}/extensions/sample/actions/open",+ json={"locator": 1},+ )+ assert response.status_code == 200+ assert response.json()["payload"]["body"] == "translated"++[email protected]("sync_wrapper", [False, True])+def test_async_reading_action_can_be_retried_after_timeout(material, monkeypatch, sync_wrapper):+ calls = 0++ async def run(*_args):+ nonlocal calls+ calls += 1+ if calls == 1:+ await asyncio.sleep(1)+ return ReadingExtensionResult(type="card")++ handler = (lambda *args: run(*args)) if sync_wrapper else run+ monkeypatch.setattr(reading_extensions, "ACTION_TIMEOUT_S", 0.01)+ client = _client(monkeypatch, _extension(handler))+ url = f"/api/reading/materials/{material.material_id}/extensions/sample/actions/open"+ assert client.post(url, json={"locator": 1}).status_code == 503+ assert client.post(url, json={"locator": 1}).status_code == 200+ assert calls == 2+++def test_reading_action_logs_the_cause_of_unavailability(material, monkeypatch, caplog):+ def run(*_args):+ raise RuntimeError("provider unavailable")++ client = _client(monkeypatch, _extension(run))+ response = client.post(+ f"/api/reading/materials/{material.material_id}/extensions/sample/actions/open",+ json={"locator": 1},+ )+ assert response.status_code == 503+ assert any(+ record.exc_info and "action open failed" in record.message for record in caplog.records+ )+++def test_sync_reading_failure_does_not_disable_retry(material, monkeypatch):+ calls = 0++ def run(*_args):+ nonlocal calls+ calls += 1+ if calls == 1:+ raise RuntimeError("temporary provider failure")+ return ReadingExtensionResult(type="card")++ client = _client(monkeypatch, _extension(run))+ url = f"/api/reading/materials/{material.material_id}/extensions/sample/actions/open"+ assert client.post(url, json={"locator": 1}).status_code == 503+ assert client.post(url, json={"locator": 1}).status_code == 200++++++def test_language_model_errors_are_reported_distinctly(material, monkeypatch):++ from deeptutor.services.llm.exceptions import LLMAuthenticationError++++ def run(*_args):++ raise LLMAuthenticationError("Invalid API key")++++ client = _client(monkeypatch, _extension(run))++ response = client.post(++ f"/api/reading/materials/{material.material_id}/extensions/sample/actions/open",++ json={"locator": 1},++ )++++ assert response.status_code == 503++ detail = response.json()["detail"]++ assert detail["recoverable"] is True++ assert "language model" in detail["message"].lower()+++++ def test_timed_out_async_extension_can_retry(material, monkeypatch):+ calls = 0++ async def run(*_args):+ nonlocal calls+ calls += 1+ if calls == 1:+ await asyncio.sleep(1)+ return ReadingExtensionResult(type="card")++ monkeypatch.setattr(reading_extensions, "ACTION_TIMEOUT_S", 0.01)+ client = _client(monkeypatch, _extension(run))++ first = client.post(+ f"/api/reading/materials/{material.material_id}/extensions/sample/actions/open",+ json={"locator": 1},+ )+ second = client.post(+ f"/api/reading/materials/{material.material_id}/extensions/sample/actions/open",+ json={"locator": 1},+ )++ assert first.status_code == 503+ assert first.json()["detail"]["reason"] == "timed_out"+ assert second.status_code == 200+ assert calls == 2+++ def test_async_extension_ignores_stale_circuit(material, monkeypatch):+ async def run(*_args):+ return ReadingExtensionResult(type="card", payload={"body": "ok"})++ extension = _extension(run)+ registry = ReadingExtensionRegistry([extension])+ registry.mark_timed_out("sample")+ monkeypatch.setattr(+ reading_extensions,+ "get_reading_extension_registry",+ lambda: registry,+ )+ app = FastAPI()+ app.include_router(reading_extensions.router, prefix="/api/reading")+ client = TestClient(app)++ response = client.post(+ f"/api/reading/materials/{material.material_id}/extensions/sample/actions/open",+ json={"locator": 1},+ )++ assert response.status_code == 200, response.text+ assert response.json()["type"] == "card"+++ def test_plugin_exception_reason_is_returned(material, monkeypatch):+ client = _client(+ monkeypatch,+ _extension(lambda *_: (_ for _ in ()).throw(RuntimeError("broken plugin"))),+ )+ response = client.post(+ f"/api/reading/materials/{material.material_id}/extensions/sample/actions/open",+ json={"locator": 1},+ )+ assert response.status_code == 503+ assert response.json()["detail"]["reason"] == "broken plugin"diff --cc web/locales/en/app.jsonindex e0fb8b5a3,e89c9f654..a2a87e0bf--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@@ -4052,6 -4072,5 +4052,27 @@@"Your DeepTutor login expired during authorization. Sign in, then start a new Invidious connection.": "Your DeepTutor login expired during authorization. Sign in, then start a new Invidious connection.","The account could not be connected. Please start a new connection.": "The account could not be connected. Please start a new connection.","Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.": "Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.",+ "{{count}} tool calls": "{{count}} tool calls",- "Working notes": "Working notes"++ "Working notes": "Working notes",++ "risk {{risk}}%": "risk {{risk}}%",++ "recent failure": "recent failure",++ "Show all {{count}} reviews": "Show all {{count}} reviews",++ "Show fewer": "Show fewer",++ "Start review for {{name}}": "Start review for {{name}}",++ "memory {{retrievability}}% · stability {{stability}} days": "memory {{retrievability}}% · stability {{stability}} days",++ "risk {{risk}}% · {{lapses}} lapses": "risk {{risk}}% · {{lapses}} lapses",++ "Retention evidence ({{count}})": "Retention evidence ({{count}})",++ "Showing the latest 20 events": "Showing the latest 20 events",++ "correct": "correct",++ "incorrect": "incorrect",++ "qualitative": "qualitative",++ "review": "review",++ "Unknown Source": "Unknown Source",++ "Assessment Type": "Assessment Type",++ "Focus Check": "Focus Check",++ "Qualitative": "Qualitative",++ "Partially Correct": "Partially Correct",++ "Not Graded": "Not Graded",++ "Partner Chat": "Partner Chat",+ "Failed to save answer. Please try again.": "Failed to save answer. Please try again."}diff --cc web/locales/zh/app.jsonindex ba51b8c8e,f34cfdb13..ac7e45e9a--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@@ -4052,6 -4072,5 +4052,27 @@@"Your DeepTutor login expired during authorization. Sign in, then start a new Invidious connection.": "授权期间 DeepTutor 登录已失效,请先登录 DeepTutor,再重新关联 Invidious。","The account could not be connected. Please start a new connection.": "账号关联失败,请重新发起关联。","Sign in with your Invidious account, then approve read-only access to return here. Your DeepTutor login is separate.": "请使用 Invidious 账号登录,确认只读授权后会自动返回此页。DeepTutor 与 Invidious 使用各自的登录账号。",+ "{{count}} tool calls": "{{count}} 次工具调用",- "Working notes": "过程记录"++ "Working notes": "过程记录",++ "risk {{risk}}%": "遗忘风险 {{risk}}%",++ "recent failure": "近期失败",++ "Show all {{count}} reviews": "显示全部 {{count}} 项复习",++ "Show fewer": "收起",++ "Start review for {{name}}": "开始复习 {{name}}",++ "memory {{retrievability}}% · stability {{stability}} days": "记忆可提取度 {{retrievability}}% · 稳定性 {{stability}} 天",++ "risk {{risk}}% · {{lapses}} lapses": "遗忘风险 {{risk}}% · 遗忘 {{lapses}} 次",++ "Retention evidence ({{count}})": "记忆证据({{count}})",++ "Showing the latest 20 events": "显示最近 20 条记录",++ "correct": "答对",++ "incorrect": "答错",++ "qualitative": "定性评估",++ "review": "复习",++ "Unknown Source": "未知来源",++ "Assessment Type": "评估类型",++ "Focus Check": "专注检测",++ "Qualitative": "定性评估",++ "Partially Correct": "部分正确",++ "Not Graded": "未评分",++ "Partner Chat": "伙伴对话",+ "Failed to save answer. Please try again.": "答案保存失败,请重试。"}