DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Block 2: Replace _mock_llm() with real await complete() via DeepTutor LLM factory
whf99fec2e51e8a
diff --git a/.hermes_block2_spec.md b/.hermes_block2_spec.mdnew file mode 100644index 000000000..70a4224e5--- /dev/null+++ b/.hermes_block2_spec.md@@ -0,0 +1,116 @@+# Block 2: 删除 _mock_llm,接入真实 LLM++将 `deeptutor/capabilities/guided_learning.py` 中的硬编码 mock 替换为真实 LLM 调用。++## 前置知识++LLM API (from Block 1):+```python+from deeptutor.services.llm import complete+# async function, returns str+response = await complete(+ prompt="user message here",+ system_prompt="system instructions here",+)+```++## 修改文件++`deeptutor/capabilities/guided_learning.py`++## 要做的事++### 1. 删除 _mock_llm (约第 73-102 行)+整个 `_mock_llm` 方法体,包括 docstring "Return canned responses for testing..."++### 2. 新增 _call_llm 方法+```python+async def _call_llm(self, system_prompt: str, user_message: str) -> str:+ """Call real LLM via DeepTutor's complete() function."""+ try:+ from deeptutor.services.llm import complete+ response = await complete(+ prompt=user_message,+ system_prompt=system_prompt,+ )+ return response+ except Exception as e:+ import logging+ logging.getLogger(__name__).error(f"LLM call failed: {e}")+ return json.dumps({"error": f"LLM call failed: {e}"})+```++### 3. 所有 stage handler 方法签名加 async+因为这 12 个 handler 现在调用 `await self._call_llm(...)`,它们的签名必须从 `def` 改为 `async def`:+- `_run_diagnostic_phase1` → `async def`+- `_run_diagnostic_phase2` → `async def`+- `_run_metacognitive_intro` → `async def`+- `_run_plan` → `async def`+- `_run_pretest` → `async def`+- `_run_explain` → `async def`+- `_run_feynman_check` → `async def`+- `_run_practice` → `async def`+- `_run_error_diagnosis` → `async def`+- `_run_module_test` → `async def`+- `_run_review` → `async def`++### 4. 替换调用+每个 handler 中的 `self._mock_llm(...)` 改为 `await self._call_llm(...)`。++例如:+```python+# Before+response = self._mock_llm("diagnostic", "generate diagnostic phase1 screening questions")++# After+response = await self._call_llm("你是教育诊断专家...", "请生成摸底测试题...")+```++### 5. 临时 Prompt+每个 stage 使用简单中文 prompt(Block 3 会替换为标准模板):+- diagnostic → system="你是一个教育诊断专家。请出题测试学生水平,返回JSON格式。" user="生成摸底测试题"+- metacognitive → system="你介绍高效学习方法" user="介绍主动回忆、间隔重复和费曼技巧"+- plan → system="你是一个学习规划师" user="基于诊断结果制定学习计划"+- pretest → system="请出一道预习题,返回JSON格式{\"question\":\"...\",\"hint\":\"...\"}" user="为知识点出预习题"+- explain → system="你是一个耐心专业的老师。用通俗语言讲解知识点,300-500字。" user="讲解这个知识点"+- feynman → system="判断学生是否能用费曼技巧解释清楚概念。返回JSON{\"passed\":bool,\"feedback\":\"...\",\"gap\":\"...\"}" user="费曼检验"+- practice → system="生成3-5道练习题,难度递进。返回JSON{\"exercises\":[...]}" user="生成练习题"+- error_diagnosis → system="分析学生做错的题目属于什么错误类型。返回JSON{\"error_type\":\"...\",\"analysis\":\"...\"}" user="诊断错误"+- module_test → system="出一套10题模块测验,覆盖所有知识点,通过线70%。返回JSON。" user="生成模块测验"+- review → system="生成间隔复习内容:核心概念回顾、易错点提醒" user="生成复习内容"++## 注意++- `_safe_json_parse` 保留不动(已存在)+- `_STAGE_HANDLERS` 字典不动+- `run()` 方法中的 `await handler(self, progress, context, stream)` 已经是 await xxx 格式,不需要改++## 验收++```bash+cd D:\Project\DeepTutor && .venv\Scripts\python.exe -c "+from deeptutor.capabilities.guided_learning import GuidedLearningCapability+import inspect++c = GuidedLearningCapability()++# 1. _mock_llm 已删除+assert not hasattr(c, '_mock_llm'), 'FATAL: _mock_llm still exists'++# 2. _call_llm 存在且是 async+assert hasattr(c, '_call_llm'), 'FATAL: _call_llm missing'+assert inspect.iscoroutinefunction(c._call_llm), 'FATAL: _call_llm not async'++# 3. 所有 stage handler 都是 async+for stage_name, handler in GuidedLearningCapability._STAGE_HANDLERS.items():+ assert inspect.iscoroutinefunction(handler), f'FATAL: {stage_name} handler not async'++# 4. 无 mock_llm 残留+src = inspect.getsource(GuidedLearningCapability)+assert '_mock_llm' not in src, 'FATAL: mock_llm still in source'+assert '_call_llm' in src, 'OK: _call_llm found'++# 5. import 链正常+print('BLOCK 2 PASSED - All checks passed')+"+```diff --git a/deeptutor/capabilities/guided_learning.py b/deeptutor/capabilities/guided_learning.pyindex 887275aef..7def889ff 100644--- a/deeptutor/capabilities/guided_learning.py+++ b/deeptutor/capabilities/guided_learning.py@@ -68,39 +68,6 @@ class GuidedLearningCapability(BaseCapability):return ref.get("book_id") or ref.get("id", "default")return getattr(context, "session_id", "default")- # ── Mock LLM ─────────────────────────────────────────────────────────-- def _mock_llm(self, system_prompt: str, user_message: str) -> str:- """Return canned responses for testing. Replace with real LLM calls later."""- lower = (system_prompt + " " + user_message).lower()- if "diagnostic" in lower:- return json.dumps({- "questions": ["Q1: placeholder", "Q2: placeholder"],- "answers": ["A1", "A2"],- })- if "explain" in lower:- return "这是一个概念型知识点的模拟讲解..."- if "feynman" in lower:- return "模拟费曼检验结果:通过"- if "pretest" in lower:- return json.dumps({"question": "模拟预习题", "hint": "模拟提示"})- if "practice" in lower:- return json.dumps({- "exercises": [- {"question": "练习1", "answer": "答案1"},- {"question": "练习2", "answer": "答案2"},- ]- })- if "module_test" in lower:- return json.dumps({- "questions": ["测验1", "测验2"],- "answers": ["答案1", "答案2"],- "pass": True,- })- if "review" in lower:- return "模拟复习内容"- return "mock response"-# ── Safe JSON parse ──────────────────────────────────────────────────@staticmethod@@ -111,6 +78,22 @@ class GuidedLearningCapability(BaseCapability):except json.JSONDecodeError:return default or {}+ # ── Real LLM call ───────────────────────────────────────────────────++ async def _call_llm(self, system_prompt: str, user_message: str) -> str:+ """Call real LLM via DeepTutor's complete() function."""+ try:+ from deeptutor.services.llm import complete+ response = await complete(+ prompt=user_message,+ system_prompt=system_prompt,+ )+ return response+ except Exception as e:+ import logging+ logging.getLogger(__name__).error(f"LLM call failed: {e}")+ return json.dumps({"error": f"LLM call failed: {e}"})+# ── State machine entry ──────────────────────────────────────────────async def run(self, context: UnifiedContext, stream: StreamBus) -> None:@@ -136,8 +119,9 @@ class GuidedLearningCapability(BaseCapability):self, progress: LearningProgress, context: UnifiedContext, stream: StreamBus) -> None:async with stream.stage("diagnostic_phase1", source=self.manifest.name):- response = self._mock_llm(- "diagnostic", "generate diagnostic phase1 screening questions"+ response = await self._call_llm(+ "你是一个教育诊断专家。请出题测试学生水平,返回JSON格式。",+ "生成摸底测试题",)data = self._safe_json_parse(response, default={"questions": [], "answers": []})progress.diagnostic = DiagnosticResult(@@ -151,8 +135,9 @@ class GuidedLearningCapability(BaseCapability):self, progress: LearningProgress, context: UnifiedContext, stream: StreamBus) -> None:async with stream.stage("diagnostic_phase2", source=self.manifest.name):- response = self._mock_llm(- "diagnostic", "generate diagnostic phase2 deep dive"+ response = await self._call_llm(+ "你是一个教育诊断专家。请出题测试学生水平,返回JSON格式。",+ "生成摸底测试题",)data = self._safe_json_parse(response, default={})if progress.diagnostic is not None:@@ -164,7 +149,10 @@ class GuidedLearningCapability(BaseCapability):self, progress: LearningProgress, context: UnifiedContext, stream: StreamBus) -> None:async with stream.stage("metacognitive_intro", source=self.manifest.name):- response = self._mock_llm("metacognitive", "introduce learning methods")+ response = await self._call_llm(+ "你介绍高效学习方法",+ "介绍主动回忆、间隔重复和费曼技巧",+ )await stream.content(response)self._service.advance_stage(progress, LearningStage.PLAN)@@ -172,7 +160,10 @@ class GuidedLearningCapability(BaseCapability):self, progress: LearningProgress, context: UnifiedContext, stream: StreamBus) -> None:async with stream.stage("plan", source=self.manifest.name):- response = self._mock_llm("plan", "generate study plan from diagnostic results")+ response = await self._call_llm(+ "你是一个学习规划师",+ "基于诊断结果制定学习计划",+ )await stream.content(response)if not progress.modules:mock_module = LearningModule(@@ -202,7 +193,10 @@ class GuidedLearningCapability(BaseCapability):self, progress: LearningProgress, context: UnifiedContext, stream: StreamBus) -> None:async with stream.stage("pretest", source=self.manifest.name):- response = self._mock_llm("pretest", "generate pretest guess question")+ response = await self._call_llm(+ '请出一道预习题,返回JSON格式{"question":"...","hint":"..."}',+ "为知识点出预习题",+ )await stream.content(response)self._service.advance_stage(progress, LearningStage.EXPLAIN)@@ -210,7 +204,10 @@ class GuidedLearningCapability(BaseCapability):self, progress: LearningProgress, context: UnifiedContext, stream: StreamBus) -> None:async with stream.stage("explain", source=self.manifest.name):- response = self._mock_llm("explain", "teach this knowledge point")+ response = await self._call_llm(+ "你是一个耐心专业的老师。用通俗语言讲解知识点,300-500字。",+ "讲解这个知识点",+ )await stream.content(response)self._service.advance_stage(progress, LearningStage.FEYNMAN_CHECK)@@ -218,7 +215,10 @@ class GuidedLearningCapability(BaseCapability):self, progress: LearningProgress, context: UnifiedContext, stream: StreamBus) -> None:async with stream.stage("feynman_check", source=self.manifest.name):- response = self._mock_llm("feynman", "verify understanding via feynman technique")+ response = await self._call_llm(+ '判断学生是否能用费曼技巧解释清楚概念。返回JSON{"passed":bool,"feedback":"...","gap":"..."}',+ "费曼检验",+ )await stream.content(response)kps = self._current_knowledge_points(progress)if progress.current_kp_index + 1 < len(kps):@@ -237,7 +237,10 @@ class GuidedLearningCapability(BaseCapability):self, progress: LearningProgress, context: UnifiedContext, stream: StreamBus) -> None:async with stream.stage("practice", source=self.manifest.name):- response = self._mock_llm("practice", "generate 3-5 exercises with Bloom + interleaving")+ response = await self._call_llm(+ '生成3-5道练习题,难度递进。返回JSON{"exercises":[...]}',+ "生成练习题",+ )await stream.content(response)self._service.advance_stage(progress, LearningStage.ERROR_DIAGNOSIS)@@ -245,7 +248,10 @@ class GuidedLearningCapability(BaseCapability):self, progress: LearningProgress, context: UnifiedContext, stream: StreamBus) -> None:async with stream.stage("error_diagnosis", source=self.manifest.name):- response = self._mock_llm("error_diagnosis", "self-attribution and AI confirmation")+ response = await self._call_llm(+ '分析学生做错的题目属于什么错误类型。返回JSON{"error_type":"...","analysis":"..."}',+ "诊断错误",+ )await stream.content(response)self._service.advance_stage(progress, LearningStage.MODULE_TEST)@@ -253,7 +259,10 @@ class GuidedLearningCapability(BaseCapability):self, progress: LearningProgress, context: UnifiedContext, stream: StreamBus) -> None:async with stream.stage("module_test", source=self.manifest.name):- response = self._mock_llm("module_test", "10-question module test with mastery gate")+ response = await self._call_llm(+ "出一套10题模块测验,覆盖所有知识点,通过线70%。返回JSON。",+ "生成模块测验",+ )await stream.content(response)self._init_repetition_states(progress)self._service.advance_stage(progress, LearningStage.REVIEW)@@ -288,7 +297,10 @@ class GuidedLearningCapability(BaseCapability):async with stream.stage("review", source=self.manifest.name):self._init_repetition_states(progress)self._schedule_reviews(progress)- response = self._mock_llm("review", "spaced repetition review")+ response = await self._call_llm(+ "生成间隔复习内容:核心概念回顾、易错点提醒",+ "生成复习内容",+ )await stream.content(response)if self._advance_to_next_module(progress):self._service.advance_stage(progress, LearningStage.PRETEST)