DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(lightrag): expose concurrency and extraction knobs in settings (#877)
Ademola Balogune3f1152ea8fe
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 24c259a6a..498c70564 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -1333,10 +1333,13 @@ async def update_graphrag_pipeline_config(payload: GraphRagConfigUpdate):class LightRagConfigUpdate(BaseModel):- """Partial update for LightRAG query knobs (omitted fields kept)."""+ """Partial update for LightRAG query + indexing knobs (omitted fields kept)."""top_k: int | None = Noneresponse_type: str | None = None+ max_concurrent_files: int | None = None+ llm_model_max_async: int | None = None+ entity_extract_max_gleaning: int | None = None@router.get("/rag-pipelines/lightrag/config")diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.pyindex 0066469b1..ce2e3f568 100644--- a/deeptutor/services/config/runtime_settings.py+++ b/deeptutor/services/config/runtime_settings.py@@ -286,15 +286,20 @@ DEFAULT_GRAPHRAG_SETTINGS: dict[str, Any] = {"dynamic_community_selection": False,}-# LightRAG retrieval knobs (HKUDS/LightRAG via RAG-Anything). ``top_k`` is the-# number of entities/relations the query pulls; ``response_type`` mirrors+# LightRAG retrieval + indexing knobs (HKUDS/LightRAG via RAG-Anything). ``top_k``+# is the number of entities/relations the query pulls; ``response_type`` mirrors# GraphRAG's. These ride into ``QueryParam`` via the engine's aquery() call;# wiring is defensive (an older RAG-Anything that rejects a kwarg degrades to a-# mode-only query).+# mode-only query). ``max_concurrent_files`` maps to RAGAnythingConfig's batch+# knob; ``llm_model_max_async`` / ``entity_extract_max_gleaning`` ride into+# LightRAG's own constructor via RAGAnything's ``lightrag_kwargs`` passthrough.DEFAULT_LIGHTRAG_SETTINGS: dict[str, Any] = {"version": 1,"top_k": 60,"response_type": "Multiple Paragraphs",+ "max_concurrent_files": 1,+ "llm_model_max_async": 4,+ "entity_extract_max_gleaning": 1,}IGNORE_PROCESS_OVERRIDES_ENV = "DEEPTUTOR_IGNORE_PROCESS_ENV_OVERRIDES"@@ -844,6 +849,15 @@ class RuntimeSettingsService:"version": 1,"top_k": _coerce_clamped_int(settings.get("top_k"), 60, 1, 200),"response_type": self._normalize_response_type(settings.get("response_type")),+ "max_concurrent_files": _coerce_clamped_int(+ settings.get("max_concurrent_files"), 1, 1, 16+ ),+ "llm_model_max_async": _coerce_clamped_int(+ settings.get("llm_model_max_async"), 4, 1, 32+ ),+ "entity_extract_max_gleaning": _coerce_clamped_int(+ settings.get("entity_extract_max_gleaning"), 1, 0, 5+ ),}def _normalize_document_parsing(self, settings: dict[str, Any]) -> dict[str, Any]:diff --git a/deeptutor/services/rag/pipelines/lightrag/config.py b/deeptutor/services/rag/pipelines/lightrag/config.pyindex 70e77f2ae..1b7e15faf 100644--- a/deeptutor/services/rag/pipelines/lightrag/config.py+++ b/deeptutor/services/rag/pipelines/lightrag/config.py@@ -86,6 +86,47 @@ def query_kwargs_from_settings() -> dict:return {}+def indexing_kwargs_from_settings() -> dict:+ """``RAGAnythingConfig`` batch-processing knobs from runtime settings.++ Only ``max_concurrent_files`` is exposed for now (issue #640); the config+ object accepts several other batch/context knobs we deliberately leave on+ RAG-Anything's own defaults. Empty on any read error, so a bad settings+ file falls back to RAG-Anything's built-in default of 1.+ """+ try:+ from deeptutor.services.config import load_lightrag_settings++ settings = load_lightrag_settings()+ return {"max_concurrent_files": int(settings.get("max_concurrent_files", 1))}+ except Exception:+ return {}+++def lightrag_kwargs_from_settings() -> dict:+ """Extra kwargs forwarded to LightRAG's own constructor via RAG-Anything's+ ``lightrag_kwargs`` passthrough.++ ``llm_model_max_async`` bounds how many concurrent LLM calls LightRAG's+ internal priority queue issues (covers both query and entity-extraction+ traffic, since both ride the same wrapped ``llm_model_func``).+ ``entity_extract_max_gleaning`` controls how many extra extraction passes+ LightRAG runs per chunk to recover entities/relations the first pass+ missed. Empty on any read error, so a bad settings file falls back to+ LightRAG's own built-in defaults.+ """+ try:+ from deeptutor.services.config import load_lightrag_settings++ settings = load_lightrag_settings()+ return {+ "llm_model_max_async": int(settings.get("llm_model_max_async", 4)),+ "entity_extract_max_gleaning": int(settings.get("entity_extract_max_gleaning", 1)),+ }+ except Exception:+ return {}++def build_llm_model_func(*, io_bridge: OwnerLoopBridge | None = None):"""Wrap DeepTutor's unified LLM callable for LightRAG.@@ -190,6 +231,8 @@ __all__ = ["is_lightrag_available","normalize_mode","query_kwargs_from_settings",+ "indexing_kwargs_from_settings",+ "lightrag_kwargs_from_settings","build_llm_model_func","build_vision_model_func","build_embedding_func",diff --git a/deeptutor/services/rag/pipelines/lightrag/engine.py b/deeptutor/services/rag/pipelines/lightrag/engine.pyindex 8bf237bda..f318a557d 100644--- a/deeptutor/services/rag/pipelines/lightrag/engine.py+++ b/deeptutor/services/rag/pipelines/lightrag/engine.py@@ -23,6 +23,8 @@ from .config import (build_embedding_func,build_llm_model_func,build_vision_model_func,+ indexing_kwargs_from_settings,+ lightrag_kwargs_from_settings,normalize_mode,query_kwargs_from_settings,)@@ -31,6 +33,55 @@ from .worker import OwnerLoopBridgelogger = logging.getLogger(__name__)+def _accepts(target: Any, name: str) -> bool:+ """Whether ``target``'s constructor takes a keyword called *name*.++ The settings knobs below ride on RAG-Anything parameters that arrived in+ different releases — ``lightrag_kwargs`` only exists from ~1.2.5, while the+ supported range starts at 1.0.1. Asking first keeps an older install+ working on RAG-Anything's own defaults instead of dying with a TypeError+ that takes the whole LightRAG engine down. Same defensive posture the query+ path already takes for ``QueryParam`` kwargs.+ """+ import inspect++ try:+ return name in inspect.signature(target).parameters+ except (TypeError, ValueError):+ return False+++def _drop_unsupported(target: Any, kwargs: dict[str, Any], *, what: str) -> dict[str, Any]:+ supported = {key: value for key, value in kwargs.items() if _accepts(target, key)}+ for key in kwargs.keys() - supported.keys():+ logger.warning(+ "Installed RAG-Anything does not accept %s=%r on %s; leaving it at "+ "the library default. Upgrade raganything to use this setting.",+ key,+ kwargs[key],+ what,+ )+ return supported+++def _build_config(config_cls: Any, working_dir: Path) -> Any:+ knobs = _drop_unsupported(config_cls, indexing_kwargs_from_settings(), what="RAGAnythingConfig")+ return config_cls(working_dir=str(working_dir), **knobs)+++def _construct(rag_cls: Any, **kwargs: Any) -> Any:+ extra = lightrag_kwargs_from_settings()+ if extra and _accepts(rag_cls, "lightrag_kwargs"):+ kwargs["lightrag_kwargs"] = extra+ elif extra:+ logger.warning(+ "Installed RAG-Anything has no lightrag_kwargs passthrough; %s stay "+ "at LightRAG's defaults. Upgrade raganything to use these settings.",+ ", ".join(sorted(extra)),+ )+ return rag_cls(**kwargs)++def build_rag(working_dir: Path, *, io_bridge: OwnerLoopBridge | None = None) -> Any:"""Construct a RAG-Anything instance rooted at ``working_dir``.@@ -39,14 +90,14 @@ def build_rag(working_dir: Path, *, io_bridge: OwnerLoopBridge | None = None) ->"""from raganything import RAGAnything, RAGAnythingConfig- config = RAGAnythingConfig(working_dir=str(working_dir))+ config = _build_config(RAGAnythingConfig, working_dir)adapter_kwargs = {"io_bridge": io_bridge} if io_bridge is not None else {}- rag = RAGAnything(- config=config,- llm_model_func=build_llm_model_func(**adapter_kwargs),- vision_model_func=build_vision_model_func(**adapter_kwargs),- embedding_func=build_embedding_func(**adapter_kwargs),- )+ funcs = {+ "llm_model_func": build_llm_model_func(**adapter_kwargs),+ "vision_model_func": build_vision_model_func(**adapter_kwargs),+ "embedding_func": build_embedding_func(**adapter_kwargs),+ }+ rag = _construct(RAGAnything, config=config, **funcs)# DeepTutor always feeds RAG-Anything a pre-parsed ``content_list`` (the# parse layer runs upstream via DeepTutor's own ParseService), so# RAG-Anything's bundled document parser is never invoked. Its LightRAG initdiff --git a/pyproject.toml b/pyproject.tomlindex 79d0af434..a99699742 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -237,7 +237,11 @@ graphrag = ["graphrag>=3.0.1,<4.0.0; python_version < '3.14'"]# `python_version` marker as graphrag to avoid a silent backtrack/downgrade on# 3.14+. Floor is 1.0.1 (no 1.0.0 was ever published) with a <2.0.0 ceiling so# a future API-breaking 2.x isn't pulled in silently.-rag-lightrag = ["raganything>=1.0.1,<2.0.0; python_version < '3.14'"]+# 1.2.5 is the first release carrying the ``lightrag_kwargs`` passthrough the+# LightRAG concurrency/extraction settings ride on. Older installs still run —+# engine.py drops knobs the installed version cannot take — but a fresh install+# should get the capable one.+rag-lightrag = ["raganything>=1.2.5,<2.0.0; python_version < '3.14'"]# Dev/test tooling. Mirrors requirements/dev.txt.dev = [diff --git a/tests/services/rag/test_lightrag_settings_wiring.py b/tests/services/rag/test_lightrag_settings_wiring.pynew file mode 100644index 000000000..edffb235e--- /dev/null+++ b/tests/services/rag/test_lightrag_settings_wiring.py@@ -0,0 +1,145 @@+"""The LightRAG settings knobs must not break older RAG-Anything installs.++``max_concurrent_files`` rides on ``RAGAnythingConfig`` and+``llm_model_max_async`` / ``entity_extract_max_gleaning`` ride on RAG-Anything's+``lightrag_kwargs`` passthrough — a parameter that only exists from ~1.2.5,+while the supported range starts at 1.0.1. Passing it blind raised TypeError+and took the whole engine down, so the wiring asks the installed class first.++raganything is an optional extra and is absent from CI, so these tests exercise+``build_rag`` against stand-in classes with each constructor shape.+"""++from __future__ import annotations++from pathlib import Path+import sys+import types+from typing import Any++import pytest++from deeptutor.services.rag.pipelines.lightrag import engine as engine_module+++class _ModernConfig:+ """RAG-Anything >= 1.2.5: config takes the batch knob."""++ def __init__(self, working_dir: str, max_concurrent_files: int = 1) -> None:+ self.working_dir = working_dir+ self.max_concurrent_files = max_concurrent_files+++class _LegacyConfig:+ """RAG-Anything 1.0.x: no batch knob at all."""++ def __init__(self, working_dir: str) -> None:+ self.working_dir = working_dir+++class _ModernRag:+ """RAG-Anything >= 1.2.5: exposes the lightrag_kwargs passthrough."""++ def __init__(+ self,+ config: Any,+ llm_model_func: Any,+ vision_model_func: Any,+ embedding_func: Any,+ lightrag_kwargs: dict[str, Any] | None = None,+ ) -> None:+ self.config = config+ self.lightrag_kwargs = lightrag_kwargs+ self.set_content_source_func = None+++class _LegacyRag:+ """RAG-Anything 1.0.x: no passthrough."""++ def __init__(+ self,+ config: Any,+ llm_model_func: Any,+ vision_model_func: Any,+ embedding_func: Any,+ ) -> None:+ self.config = config+ self.lightrag_kwargs = None+ self.set_content_source_func = None+++def fake_raganything(monkeypatch: pytest.MonkeyPatch):+ """Install a stand-in ``raganything`` module with the given class shapes."""++ def install(rag_cls: type, config_cls: type) -> None:+ module = types.ModuleType("raganything")+ module.RAGAnything = rag_cls # type: ignore[attr-defined]+ module.RAGAnythingConfig = config_cls # type: ignore[attr-defined]+ monkeypatch.setitem(sys.modules, "raganything", module)++ return install++[email protected](autouse=True)+def _stub_adapters(monkeypatch: pytest.MonkeyPatch) -> None:+ for name in ("build_llm_model_func", "build_vision_model_func", "build_embedding_func"):+ monkeypatch.setattr(engine_module, name, lambda **_kwargs: lambda *a, **k: None)++[email protected](autouse=True)+def _settings(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ engine_module, "indexing_kwargs_from_settings", lambda: {"max_concurrent_files": 4}+ )+ monkeypatch.setattr(+ engine_module,+ "lightrag_kwargs_from_settings",+ lambda: {"llm_model_max_async": 8, "entity_extract_max_gleaning": 2},+ )+++def test_modern_raganything_receives_every_knob(fake_raganything, tmp_path: Path) -> None:+ fake_raganything(_ModernRag, _ModernConfig)++ rag = engine_module.build_rag(tmp_path)++ assert rag.config.max_concurrent_files == 4+ assert rag.lightrag_kwargs == {"llm_model_max_async": 8, "entity_extract_max_gleaning": 2}+++def test_legacy_raganything_still_builds(+ fake_raganything, tmp_path: Path, caplog: pytest.LogCaptureFixture+) -> None:+ """The knobs are dropped with a warning rather than raising TypeError."""+ fake_raganything(_LegacyRag, _LegacyConfig)++ with caplog.at_level("WARNING"):+ rag = engine_module.build_rag(tmp_path)++ assert rag.lightrag_kwargs is None+ assert not hasattr(rag.config, "max_concurrent_files")+ assert "max_concurrent_files" in caplog.text+ assert "lightrag_kwargs" in caplog.text+++def test_mixed_versions_drop_only_the_unsupported_knob(fake_raganything, tmp_path: Path) -> None:+ fake_raganything(_LegacyRag, _ModernConfig)++ rag = engine_module.build_rag(tmp_path)++ assert rag.config.max_concurrent_files == 4+ assert rag.lightrag_kwargs is None+++def test_no_configured_knobs_passes_nothing_extra(+ fake_raganything, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(engine_module, "indexing_kwargs_from_settings", dict)+ monkeypatch.setattr(engine_module, "lightrag_kwargs_from_settings", dict)+ fake_raganything(_ModernRag, _ModernConfig)++ rag = engine_module.build_rag(tmp_path)++ assert rag.config.max_concurrent_files == 1 # the library default+ assert rag.lightrag_kwargs is None