DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(rag): cite what retrieval actually returned (#694)
Bingxi Zhao (Frank)9f25da9f77ea
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.pyindex 34d60d174..1a0517b8d 100644--- a/deeptutor/tools/builtin/__init__.py+++ b/deeptutor/tools/builtin/__init__.py@@ -74,6 +74,23 @@ class BrainstormTool(_PromptHintsMixin, BaseTool):return ToolResult(content=result.get("answer", ""), metadata=result)+def _rag_sources(result: dict[str, Any], *, query: str, kb_name: str) -> list[dict[str, Any]]:+ """Citations for one ``rag`` call, from the retrieval's own provenance.++ Every pipeline normalises what it retrieved into ``result["sources"]``+ (``{title, content, source, page, chunk_id, score}`` — see the GraphRAG and+ LightRAG-server pipelines). Forward those so a grounded claim is traceable+ to the chunk / entity / report behind it; without this the tool reported+ only an echo of its own query (issue #694). ``type``/``kb_name`` are kept on+ every entry so consumers that key on them still work, and an engine that+ surfaces no provenance still yields the echo rather than nothing.+ """+ retrieved = [item for item in (result.get("sources") or []) if isinstance(item, dict)]+ if not retrieved:+ return [{"type": "rag", "query": query, "kb_name": kb_name}]+ return [{"type": "rag", "kb_name": kb_name, **item} for item in retrieved]++class RAGTool(_PromptHintsMixin, BaseTool):def get_definition(self) -> ToolDefinition:return ToolDefinition(@@ -118,7 +135,7 @@ class RAGTool(_PromptHintsMixin, BaseTool):content = result.get("answer") or result.get("content", "")return ToolResult(content=content,- sources=[{"type": "rag", "query": query, "kb_name": kb_name}],+ sources=_rag_sources(result, query=query, kb_name=kb_name),metadata=result,)diff --git a/tests/core/test_builtin_tools.py b/tests/core/test_builtin_tools.pyindex 91e2c27e2..12be382d6 100644--- a/tests/core/test_builtin_tools.py+++ b/tests/core/test_builtin_tools.py@@ -150,6 +150,43 @@ async def test_rag_tool_forwards_query_and_extra_kwargs(monkeypatch: pytest.Monkassert captured["only_need_context"] is True+async def test_rag_tool_cites_retrieved_sources(monkeypatch: pytest.MonkeyPatch) -> None:+ """The retrieval's own provenance must reach the citation stream — echoing+ the query back was all a grounded answer used to carry (issue #694)."""++ async def fake_rag_search(**_kwargs: Any) -> dict[str, Any]:+ return {+ "answer": "grounded answer",+ "sources": [+ {"title": "Chapter 3", "chunk_id": "chunk-7", "content": "…tensors…"},+ {"title": "tensor", "chunk_id": "entity-2", "content": "…rank…"},+ ],+ }++ _install_module(monkeypatch, "deeptutor.tools.rag_tool", rag_search=fake_rag_search)++ result = await RAGTool().execute(query="what is a tensor", kb_name="demo-kb")++ assert [s["chunk_id"] for s in result.sources] == ["chunk-7", "entity-2"]+ assert [s["title"] for s in result.sources] == ["Chapter 3", "tensor"]+ assert all(s["type"] == "rag" and s["kb_name"] == "demo-kb" for s in result.sources)+++async def test_rag_tool_falls_back_to_query_echo(monkeypatch: pytest.MonkeyPatch) -> None:+ """An engine that surfaces no provenance still names the KB it consulted."""++ async def fake_rag_search(**_kwargs: Any) -> dict[str, Any]:+ return {"answer": "grounded answer", "sources": []}++ _install_module(monkeypatch, "deeptutor.tools.rag_tool", rag_search=fake_rag_search)++ result = await RAGTool().execute(query="what is a tensor", kb_name="demo-kb")++ assert result.sources == [{"type": "rag", "query": "what is a tensor", "kb_name": "demo-kb"}]++@pytest.mark.asyncioasync def test_rag_tool_rejects_empty_query(monkeypatch: pytest.MonkeyPatch) -> None:called = False