diff --git a/deeptutor/services/rag/pipelines/lightrag/engine.py b/deeptutor/services/rag/pipelines/lightrag/engine.py index 7e642c6d6..d2e4758a6 100644 --- a/deeptutor/services/rag/pipelines/lightrag/engine.py +++ b/deeptutor/services/rag/pipelines/lightrag/engine.py @@ -212,4 +212,149 @@ async def query(rag: Any, question: str, mode: str | None = None) -> str: return result if isinstance(result, str) else str(result) -__all__ = ["build_rag", "ensure_ready", "finalize", "insert", "query"] +async def query_with_sources( + rag: Any, question: str, mode: str | None = None +) -> tuple[str, list[dict[str, Any]]]: + """Return a LightRAG answer together with its structured provenance. + + ``RAGAnything.aquery`` owns the answer path, including its optional VLM + enhancement. LightRAG exposes the records used for retrieval separately via + ``aquery_data``. Keeping those calls separate preserves the existing answer + behavior while allowing DeepTutor to surface citation metadata. + """ + answer = await query(rag, question, mode) + return answer, await query_sources(rag, question, mode) + + +async def query_sources(rag: Any, question: str, mode: str | None = None) -> list[dict[str, Any]]: + """Fetch and normalize the structured records used by a LightRAG query. + + ``aquery_data`` was added by LightRAG after some supported RAG-Anything + releases. Missing or failed provenance must not turn a successful answer + into a failed user request, so older installations gracefully return no + citations. + """ + await ensure_ready(rag) + lightrag = getattr(rag, "lightrag", None) + aquery_data = getattr(lightrag, "aquery_data", None) + if not callable(aquery_data): + logger.debug("Installed LightRAG has no structured query data API.") + return [] + + resolved = normalize_mode(mode) or DEFAULT_MODE + extra = query_kwargs_from_settings() + try: + from lightrag import QueryParam + + try: + result = await aquery_data(question, param=QueryParam(mode=resolved, **extra)) + except TypeError: + if not extra: + raise + logger.debug("LightRAG rejected extra provenance query kwargs; retrying mode-only.") + result = await aquery_data(question, param=QueryParam(mode=resolved)) + except Exception as exc: + logger.warning("LightRAG provenance lookup failed; omitting citations: %s", exc) + return [] + + return _query_data_to_sources(result) + + +def _query_data_to_sources(result: Any) -> list[dict[str, Any]]: + """Map LightRAG's structured retrieval result to DeepTutor citations.""" + if not isinstance(result, dict): + return [] + data = result.get("data") + if not isinstance(data, dict): + return [] + + reference_paths = { + str(record.get("reference_id")): str(record.get("file_path")) + for record in data.get("references", []) + if isinstance(record, dict) and record.get("reference_id") and record.get("file_path") + } + sources: list[dict[str, Any]] = [] + + def source_path(record: dict[str, Any]) -> str: + return str( + record.get("file_path") or reference_paths.get(str(record.get("reference_id")), "") + ) + + def source_title(path: str, fallback: str) -> str: + return Path(path).name if path else fallback + + for record in data.get("chunks", []): + if not isinstance(record, dict): + continue + path = source_path(record) + content = str(record.get("content") or "") + chunk_id = str(record.get("chunk_id") or "") + if not (path or content or chunk_id): + continue + sources.append( + { + "title": source_title(path, "LightRAG chunk"), + "content": content[:200], + "source": path, + "page": str(record.get("page") or ""), + "chunk_id": chunk_id, + "reference_id": str(record.get("reference_id") or ""), + } + ) + + for record in data.get("entities", []): + if not isinstance(record, dict): + continue + path = source_path(record) + entity_id = str(record.get("entity_name") or record.get("entity_id") or "") + description = str(record.get("description") or "") + if not (path or entity_id or description): + continue + sources.append( + { + "title": entity_id or source_title(path, "LightRAG entity"), + "content": description[:200], + "source": path, + "page": str(record.get("page") or ""), + "entity_id": entity_id, + "entity_type": str(record.get("entity_type") or ""), + "source_id": str(record.get("source_id") or ""), + "reference_id": str(record.get("reference_id") or ""), + } + ) + + for record in data.get("relationships", []): + if not isinstance(record, dict): + continue + path = source_path(record) + source_id = str(record.get("src_id") or "") + target_id = str(record.get("tgt_id") or "") + relation_id = str(record.get("relation_id") or f"{source_id}->{target_id}") + description = str(record.get("description") or "") + if not (path or relation_id or description): + continue + sources.append( + { + "title": relation_id or source_title(path, "LightRAG relationship"), + "content": description[:200], + "source": path, + "page": str(record.get("page") or ""), + "relation_id": relation_id, + "source_entity_id": source_id, + "target_entity_id": target_id, + "source_id": str(record.get("source_id") or ""), + "reference_id": str(record.get("reference_id") or ""), + } + ) + + return sources + + +__all__ = [ + "build_rag", + "ensure_ready", + "finalize", + "insert", + "query", + "query_with_sources", +] diff --git a/deeptutor/services/rag/pipelines/lightrag/pipeline.py b/deeptutor/services/rag/pipelines/lightrag/pipeline.py index 29b5660c0..ad76b5d0e 100644 --- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py +++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py @@ -319,7 +319,7 @@ class LightRagPipeline: try: self._ensure_available() rag = engine.build_rag(storage.working_dir(root_dir)) - answer = await engine.query(rag, query, mode) + answer, sources = await engine.query_with_sources(rag, query, mode) except lr_config.LightRagNotAvailableError as exc: return self._error_result(query, exc, error_type="not_configured") except Exception as exc: @@ -331,7 +331,7 @@ class LightRagPipeline: "query": query, "answer": answer, "content": answer, - "sources": [], + "sources": sources, "provider": storage.PROVIDER, "mode": mode, } diff --git a/tests/services/rag/test_lightrag_pipeline.py b/tests/services/rag/test_lightrag_pipeline.py index 33706761e..baba720ed 100644 --- a/tests/services/rag/test_lightrag_pipeline.py +++ b/tests/services/rag/test_lightrag_pipeline.py @@ -726,6 +726,108 @@ def test_lightrag_query_surfaces_raganything_initialization_failure() -> None: asyncio.run(engine.query(_Rag(), "hello", "hybrid")) +def test_lightrag_query_with_sources_keeps_answer_and_exposes_provenance(monkeypatch) -> None: + """The answer path remains RAG-Anything while citations use LightRAG data.""" + captured: dict[str, object] = {} + + class _QueryParam: + def __init__(self, **kwargs) -> None: + captured["query_param"] = kwargs + + fake_lightrag = types.ModuleType("lightrag") + fake_lightrag.QueryParam = _QueryParam + monkeypatch.setitem(sys.modules, "lightrag", fake_lightrag) + monkeypatch.setattr(engine, "query_kwargs_from_settings", lambda: {"top_k": 3}) + + class _LightRag: + async def aquery_data(self, question, *, param): + captured["provenance_query"] = question + captured["provenance_param"] = param + return { + "status": "success", + "data": { + "references": [{"reference_id": "ref-1", "file_path": "/kb/book.pdf"}], + "chunks": [ + { + "chunk_id": "chunk-1", + "content": "The retrieved passage.", + "reference_id": "ref-1", + } + ], + "entities": [ + { + "entity_name": "Newton's laws", + "entity_type": "concept", + "description": "A mechanics foundation.", + "source_id": "chunk-1", + "reference_id": "ref-1", + } + ], + "relationships": [ + { + "src_id": "force", + "tgt_id": "acceleration", + "description": "Force produces acceleration.", + "source_id": "chunk-1", + "reference_id": "ref-1", + } + ], + }, + } + + class _Rag: + lightrag = _LightRag() + + async def aquery(self, question, mode=None, **kwargs): + captured["answer_query"] = (question, mode, kwargs) + return "Grounded answer" + + answer, sources = asyncio.run(engine.query_with_sources(_Rag(), "What is force?", "hybrid")) + + assert answer == "Grounded answer" + assert captured["answer_query"] == ("What is force?", "hybrid", {"top_k": 3}) + assert captured["provenance_query"] == "What is force?" + assert captured["query_param"] == {"mode": "hybrid", "top_k": 3} + assert sources == [ + { + "title": "book.pdf", + "content": "The retrieved passage.", + "source": "/kb/book.pdf", + "page": "", + "chunk_id": "chunk-1", + "reference_id": "ref-1", + }, + { + "title": "Newton's laws", + "content": "A mechanics foundation.", + "source": "/kb/book.pdf", + "page": "", + "entity_id": "Newton's laws", + "entity_type": "concept", + "source_id": "chunk-1", + "reference_id": "ref-1", + }, + { + "title": "force->acceleration", + "content": "Force produces acceleration.", + "source": "/kb/book.pdf", + "page": "", + "relation_id": "force->acceleration", + "source_entity_id": "force", + "target_entity_id": "acceleration", + "source_id": "chunk-1", + "reference_id": "ref-1", + }, + ] + + +def test_lightrag_query_sources_falls_back_when_structured_api_is_unavailable() -> None: + class _Rag: + lightrag = object() + + assert asyncio.run(engine.query_sources(_Rag(), "hello", "hybrid")) == [] + + # --------------------------------------------------------------------------- # # pipeline lifecycle (engine + parse service stubbed) # --------------------------------------------------------------------------- # @@ -763,11 +865,11 @@ def _stub_engine(monkeypatch, answer: str = "ANSWER") -> list[dict]: encoding="utf-8", ) - async def fake_query(rag, question, mode): - return f"{answer}|{mode}" + async def fake_query_with_sources(rag, question, mode): + return f"{answer}|{mode}", [] monkeypatch.setattr(engine, "insert", fake_insert) - monkeypatch.setattr(engine, "query", fake_query) + monkeypatch.setattr(engine, "query_with_sources", fake_query_with_sources) return inserts @@ -1365,6 +1467,26 @@ def test_search_happy_path_resolves_mode(tmp_path, monkeypatch) -> None: assert res["provider"] == "lightrag" +def test_search_returns_lightrag_provenance_sources(tmp_path, monkeypatch) -> None: + _force_available(monkeypatch, True) + _stub_engine(monkeypatch) + _stub_parse(monkeypatch, blocks=[{"type": "text", "text": "x", "page_idx": 0}]) + pipe = LightRagPipeline(kb_base_dir=str(tmp_path)) + pdf = tmp_path / "a.pdf" + pdf.write_bytes(b"%PDF") + asyncio.run(pipe.initialize("kb", [str(pdf)])) + + async def fake_query_with_sources(rag, question, mode): + return "Grounded", [{"title": "a.pdf", "chunk_id": "chunk-1"}] + + monkeypatch.setattr(engine, "query_with_sources", fake_query_with_sources) + + res = asyncio.run(pipe.search("question?", "kb")) + + assert res["answer"] == "Grounded" + assert res["sources"] == [{"title": "a.pdf", "chunk_id": "chunk-1"}] + + def test_explicit_mode_overrides_kb_config(tmp_path, monkeypatch) -> None: _force_available(monkeypatch, True) _stub_engine(monkeypatch, answer="A")