DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Block 4: RAG retrieval via RAGService injected into system prompt before LLM call
whff761c34d292d
diff --git a/.hermes_block4_spec.md b/.hermes_block4_spec.mdnew file mode 100644index 000000000..62c1bf0c7--- /dev/null+++ b/.hermes_block4_spec.md@@ -0,0 +1,94 @@+# Block 4: RAG 检索注入++在 `_call_llm` 之前,用 `RAGService` 检索知识库内容,注入 system prompt。++## 修改文件++`deeptutor/capabilities/guided_learning.py`++## 要求++### 1. __init__ 新增可选参数+在 `__init__` 签名中添加:+```python+def __init__(+ self,+ service: LearningService | None = None,+ scheduler: SpacedRepetitionScheduler | None = None,+ store: LearningStore | None = None,+ kb_name: str | None = None, # NEW+ kb_base_dir: str | None = None, # NEW+) -> None:+```+保存为 `self._kb_name` 和 `self._kb_base_dir`++### 2. 新增 _retrieve_context 方法+```python+async def _retrieve_context(self, query: str) -> str:+ """Retrieve relevant content from knowledge base. Returns '' if no KB configured."""+ if not self._kb_name:+ return ""+ try:+ from deeptutor.services.rag.service import RAGService+ rag = RAGService(kb_base_dir=self._kb_base_dir)+ result = await rag.search(query=query, kb_name=self._kb_name)+ content = result.get("content") or result.get("answer") or ""+ if content:+ return f"\n\n参考教材内容:\n{content}"+ return ""+ except Exception as e:+ import logging+ logging.getLogger(__name__).warning(f"RAG retrieval failed: {e}")+ return ""+```++### 3. _call_llm 注入 RAG 上下文+修改 `_call_llm`,在调用 LLM 前先检索:+```python+async def _call_llm(self, system_prompt: str, user_message: str) -> str:+ try:+ from deeptutor.services.llm import complete+ # RAG retrieval+ rag_context = await self._retrieve_context(user_message)+ if rag_context:+ system_prompt = system_prompt + rag_context+ response = await complete(+ prompt=user_message,+ system_prompt=system_prompt,+ )+ return response+ except Exception as e:+ ...+```++## 验收++```bash+cd D:\Project\DeepTutor && .venv\Scripts\python.exe -c "+from deeptutor.capabilities.guided_learning import GuidedLearningCapability++# 1. 无 KB 时降级+c = GuidedLearningCapability()+assert c._kb_name is None++# 2. 有 KB 时保存参数+c2 = GuidedLearningCapability(kb_name='test_kb', kb_base_dir='./data/knowledge_bases')+assert c2._kb_name == 'test_kb'++# 3. _retrieve_context 存在且是 async+import inspect+assert hasattr(c, '_retrieve_context')+assert inspect.iscoroutinefunction(c._retrieve_context)++# 4. 无 KB 时 _retrieve_context 返回空+import asyncio+result = asyncio.run(c._retrieve_context('test query'))+assert result == ''++# 5. _call_llm 调用 _retrieve_context+src = inspect.getsource(GuidedLearningCapability._call_llm)+assert '_retrieve_context' in src, 'RAG not called in _call_llm'++print('BLOCK 4 PASSED')+"+```diff --git a/deeptutor/capabilities/guided_learning.py b/deeptutor/capabilities/guided_learning.pyindex 3c2a97df6..098704b11 100644--- a/deeptutor/capabilities/guided_learning.py+++ b/deeptutor/capabilities/guided_learning.py@@ -72,6 +72,8 @@ class GuidedLearningCapability(BaseCapability):service: LearningService | None = None,scheduler: SpacedRepetitionScheduler | None = None,store: LearningStore | None = None,+ kb_name: str | None = None,+ kb_base_dir: str | None = None,) -> None:if service is not None:self._service = service@@ -79,6 +81,8 @@ class GuidedLearningCapability(BaseCapability):self._store = store or LearningStore()self._service = LearningService(self._store)self._scheduler = scheduler or SpacedRepetitionScheduler()+ self._kb_name = kb_name+ self._kb_base_dir = kb_base_dirdef _resolve_book_id(self, context: UnifiedContext) -> str:book_id = getattr(context, "book_id", None)@@ -103,12 +107,35 @@ class GuidedLearningCapability(BaseCapability):except json.JSONDecodeError:return default or {}+ # ── RAG retrieval ───────────────────────────────────────────────────++ async def _retrieve_context(self, query: str) -> str:+ """Retrieve relevant content from knowledge base. Returns '' if no KB configured."""+ if not self._kb_name:+ return ""+ try:+ from deeptutor.services.rag.service import RAGService+ rag = RAGService(kb_base_dir=self._kb_base_dir)+ result = await rag.search(query=query, kb_name=self._kb_name)+ content = result.get("content") or result.get("answer") or ""+ if content:+ return f"\n\n参考教材内容:\n{content}"+ return ""+ except Exception as e:+ import logging+ logging.getLogger(__name__).warning(f"RAG retrieval failed: {e}")+ return ""+# ── 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+ # RAG retrieval+ rag_context = await self._retrieve_context(user_message)+ if rag_context:+ system_prompt = system_prompt + rag_contextresponse = await complete(prompt=user_message,system_prompt=system_prompt,