Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

Merge pull request #1070 from contributor

Bingxi Zhao (Frank)72885edfcfce
diff --cc deeptutor/services/config/runtime_settings.py
index 9b98ab52f,97a5230c8..b6b362166
--- a/deeptutor/services/config/runtime_settings.py
+++ b/deeptutor/services/config/runtime_settings.py
@@@ -309,11 -289,15 +309,13 @@@ DEFAULT_GRAPHRAG_SETTINGS: dict[str, An
"dynamic_community_selection": False,
}
-# LightRAG retrieval + indexing knobs (HKUDS/LightRAG via RAG-Anything). ``top_k``
+# LightRAG retrieval + indexing knobs (HKUDS/LightRAG native SDK). ``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). ``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.
+# GraphRAG's. These ride into ``QueryParam`` and the pinned SDK constructor.
+# ``max_concurrent_files`` sizes the native parser worker pool after DeepTutor
+# has frozen each ParseService result; pre-parsing itself remains serial.
+ # Stable catalog references let LightRAG use a dedicated LLM while the global
+ # active chat model remains unchanged for ordinary chat.
DEFAULT_LIGHTRAG_SETTINGS: dict[str, Any] = {
"version": 1,
"top_k": 60,
@@@ -321,17 -305,10 +323,19 @@@
"max_concurrent_files": 1,
"llm_model_max_async": 4,
"entity_extract_max_gleaning": 1,
+ "llm_profile_id": "",
+ "llm_model_id": "",
}
+# LightRAG Server connection defaults. Individual knowledge bases remain free
+# to override the URL/key when they are connected; this account-level slice is
+# the reusable starting point shown on the engine page and in the create flow.
+DEFAULT_LIGHTRAG_SERVER_SETTINGS: dict[str, Any] = {
+ "version": 1,
+ "server_url": "",
+ "api_key": "",
+}
+
IGNORE_PROCESS_OVERRIDES_ENV = "DEEPTUTOR_IGNORE_PROCESS_ENV_OVERRIDES"
TRUTHY = {"1", "true", "yes", "on"}
FALSY = {"0", "false", "no", "off"}
@@@ -923,15 -873,10 +927,17 @@@ class RuntimeSettingsService
"entity_extract_max_gleaning": _coerce_clamped_int(
settings.get("entity_extract_max_gleaning"), 1, 0, 5
),
+ "llm_profile_id": _string(settings.get("llm_profile_id"))[:128],
+ "llm_model_id": _string(settings.get("llm_model_id"))[:128],
}
+ def _normalize_lightrag_server(self, settings: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "version": 1,
+ "server_url": _string(settings.get("server_url")).rstrip("/"),
+ "api_key": _string(settings.get("api_key")),
+ }
+
def _normalize_document_parsing(self, settings: dict[str, Any]) -> dict[str, Any]:
"""Normalize the full v2 structure, migrating a v1 flat file in place.
diff --cc deeptutor/services/rag/pipelines/lightrag/config.py
index 4c215948c,27a582aed..9017a8735
--- a/deeptutor/services/rag/pipelines/lightrag/config.py
+++ b/deeptutor/services/rag/pipelines/lightrag/config.py
@@@ -188,14 -216,68 +188,63 @@@ def constructor_kwargs_from_settings()
return {}
- def build_llm_model_func(*, io_bridge: OwnerLoopBridge | None = None):
+ def lightrag_llm_selection_from_settings() -> dict[str, str] | None:
- """Read the stable catalog reference for LightRAG's dedicated LLM.
-
- Both IDs are required so callers cannot accidentally combine one half of an
- old selection with the currently-active half of another model. Empty fields
- mean "use the global active chat model".
- """
++ """Return a complete dedicated catalog reference, or use the active LLM."""
+ try:
+ from deeptutor.services.config import load_lightrag_settings
+
+ settings = load_lightrag_settings()
+ profile_id = str(settings.get("llm_profile_id") or "").strip()
+ model_id = str(settings.get("llm_model_id") or "").strip()
+ if not profile_id and not model_id:
+ return None
+ if not profile_id or not model_id:
+ logger.warning("Ignoring incomplete LightRAG LLM selection; using the active model")
+ return None
+ return {"profile_id": profile_id, "model_id": model_id}
+ except Exception:
+ logger.warning(
- "Could not read LightRAG LLM selection; using the active model", exc_info=True
++ "Could not read LightRAG LLM selection; using the active model",
++ exc_info=True,
+ )
+ return None
+
+
+ def _resolve_override_llm_config(selection: dict[str, str] | None):
- """Resolve a stored catalog selection without exposing catalog secrets."""
+ if selection is None:
+ return None
+ try:
+ from deeptutor.services.model_selection.runtime import (
+ resolve_llm_config_for_selection,
+ )
+
+ return resolve_llm_config_for_selection(selection)
+ except ValueError:
+ logger.warning(
+ "LightRAG LLM selection %s no longer exists in the catalog; using the active model",
+ selection,
+ )
+ return None
+
+
+ def build_llm_model_func(
+ *,
+ io_bridge: OwnerLoopBridge | None = None,
+ llm_selection: dict[str, str] | None = None,
+ ):
"""Wrap DeepTutor's unified LLM callable for LightRAG.
Drops LightRAG's internal kwargs while preserving explicit ``messages``.
"""
- from deeptutor.services.llm import get_llm_client
- config = _resolve_override_llm_config(llm_selection)
- if config is None:
++ override = _resolve_override_llm_config(llm_selection)
++ if override is None:
+ from deeptutor.services.llm import get_llm_client
+
+ base = get_llm_client().get_model_func()
+ else:
+ from deeptutor.services.llm.client import LLMClient
- base = get_llm_client().get_model_func()
- base = LLMClient(config=config, configure_env=False).get_model_func()
++ base = LLMClient(config=override, configure_env=False).get_model_func()
async def llm_model_func(
prompt="",
@@@ -219,11 -301,21 +268,21 @@@
return llm_model_func
- def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):
+ def build_vision_model_func(
+ *,
+ io_bridge: OwnerLoopBridge | None = None,
+ llm_selection: dict[str, str] | None = None,
+ ):
- """Wrap DeepTutor's vision-capable callable for RAG-Anything's image step."""
- config = _resolve_override_llm_config(llm_selection)
- if config is None:
+ """Map rc2 ``image_inputs`` to DeepTutor's vision callable."""
- from deeptutor.services.llm import get_llm_client
++ override = _resolve_override_llm_config(llm_selection)
++ if override is None:
+ from deeptutor.services.llm import get_llm_client
+
+ base = get_llm_client().get_vision_model_func()
+ else:
+ from deeptutor.services.llm.client import LLMClient
- base = get_llm_client().get_vision_model_func()
- base = LLMClient(config=config, configure_env=False).get_vision_model_func()
++ base = LLMClient(config=override, configure_env=False).get_vision_model_func()
async def vision_model_func(
prompt="",
@@@ -319,9 -398,8 +378,10 @@@ __all__ =
"normalize_mode",
"query_kwargs_from_settings",
"indexing_kwargs_from_settings",
- "lightrag_kwargs_from_settings",
+ "constructor_kwargs_from_settings",
++ "lightrag_llm_selection_from_settings",
"build_llm_model_func",
"build_vision_model_func",
+ "vision_model_available",
"build_embedding_func",
]
diff --cc deeptutor/services/rag/pipelines/lightrag/engine.py
index f84ad2069,b83036362..9fe8db9dc
--- a/deeptutor/services/rag/pipelines/lightrag/engine.py
+++ b/deeptutor/services/rag/pipelines/lightrag/engine.py
@@@ -15,218 -26,103 +15,223 @@@ from .config import
build_embedding_func,
build_llm_model_func,
build_vision_model_func,
+ constructor_kwargs_from_settings,
indexing_kwargs_from_settings,
- lightrag_kwargs_from_settings,
+ lightrag_llm_selection_from_settings,
normalize_mode,
query_kwargs_from_settings,
)
+from .ingress import IngressError, StagedDocument, pending_root
from .worker import OwnerLoopBridge
-logger = logging.getLogger(__name__)
+LIGHTRAG_DISTRIBUTION = "lightrag-hku"
+LIGHTRAG_VERSION = "1.5.7rc2"
+PARSER_ENGINE = "deeptutor"
-def _accepts(target: Any, name: str) -> bool:
- """Whether ``target``'s constructor takes a keyword called *name*.
+class LightRagContractError(RuntimeError):
+ """Raised when the pinned SDK returns a shape DeepTutor cannot trust."""
- 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
+def installed_version() -> str:
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 version(LIGHTRAG_DISTRIBUTION)
+ except PackageNotFoundError as exc:
+ raise LightRagContractError(
+ "LightRAG is not installed. Install `deeptutor[rag-lightrag]`."
+ ) from exc
+
+
+def _require_exact_version() -> None:
+ current = installed_version()
+ if current != LIGHTRAG_VERSION:
+ raise LightRagContractError(
+ f"DeepTutor requires {LIGHTRAG_DISTRIBUTION}=={LIGHTRAG_VERSION}; found {current}"
)
- 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 _validate_component(value: str, *, label: str) -> str:
+ path = Path(str(value or ""))
+ if path.is_absolute() or ".." in path.parts or path.name != str(value):
+ raise IngressError(f"{label} must be a canonical basename: {value!r}")
+ if not path.name or path.name in {".", ".."}:
+ raise IngressError(f"{label} is empty or invalid")
+ return path.name
-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)),
+def _safe_candidate(root: Path, candidate: Path) -> Path | None:
+ if candidate.is_symlink() or not candidate.is_file():
+ return None
+ resolved_root = root.resolve(strict=True)
+ resolved = candidate.resolve(strict=True)
+ try:
+ resolved.relative_to(resolved_root)
+ except ValueError as exc:
+ raise IngressError(
+ f"LightRAG source resolver escaped version ingress: {candidate}"
+ ) from exc
+ return resolved
+
+
+def _controlled_class():
+ from lightrag import LightRAG
+
+ class DeepTutorLightRAG(LightRAG):
+ def _resolve_source_file_for_parser(
+ self,
+ file_path: str,
+ *,
+ source_file: str | None = None,
+ parser_engine: str | None = None,
+ ) -> str:
+ if parser_engine not in (None, PARSER_ENGINE):
+ raise IngressError(
+ f"Unsupported parser engine for DeepTutor ingress: {parser_engine}"
+ )
+ name = _validate_component(file_path, label="file_path")
+ if source_file is not None:
+ source_name = _validate_component(source_file, label="source_file")
+ if source_name != name:
+ raise IngressError(
+ f"LightRAG source hints disagree: {name!r} != {source_name!r}"
+ )
+ root = pending_root(Path(self.working_dir))
+ root.mkdir(parents=True, exist_ok=True)
+ matches = [
+ resolved
+ for candidate in (root / name, root / "__parsed__" / name)
+ if (resolved := _safe_candidate(root, candidate)) is not None
+ ]
+ if len(matches) != 1:
+ reason = "missing" if not matches else "ambiguous"
+ raise IngressError(f"Version-local LightRAG source is {reason}: {name}")
+ return str(matches[0])
+
+ return DeepTutorLightRAG
+
+
+_SUFFIXES = frozenset(
+ {
+ "txt",
+ "md",
+ "mdx",
+ "pdf",
+ "doc",
+ "docx",
+ "ppt",
+ "pptx",
+ "xls",
+ "xlsx",
+ "rtf",
+ "odt",
+ "tex",
+ "epub",
+ "html",
+ "htm",
+ "csv",
+ "json",
+ "xml",
+ "yaml",
+ "yml",
+ "log",
+ "conf",
+ "ini",
+ "properties",
+ "sql",
+ "sh",
+ "c",
+ "h",
+ "cpp",
+ "hpp",
+ "py",
+ "java",
+ "js",
+ "ts",
+ "swift",
+ "go",
+ "rb",
+ "php",
+ "css",
+ "scss",
+ "less",
+ "png",
+ "jpg",
+ "jpeg",
+ "webp",
+ "gif",
+ "bmp",
+ "tiff",
+ }
+)
+
+
+def _register_parser() -> None:
+ from lightrag.parser.registry import ParserSpec, register_parser
+
+ register_parser(
+ ParserSpec(
+ engine_name=PARSER_ENGINE,
+ impl="deeptutor.services.rag.pipelines.lightrag.parser:DeepTutorParser",
+ suffixes=_SUFFIXES,
+ queue_group="native",
)
- 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``.
+def workspace_for(working_dir: Path) -> str:
+ identity = str(Path(working_dir).resolve()).encode("utf-8")
+ return f"deeptutor_{hashlib.sha256(identity).hexdigest()[:16]}"
- Pinned to RAG-Anything's config-based constructor; this is the single spot
- to touch if its API changes between releases.
- """
- from raganything import RAGAnything, RAGAnythingConfig
- config = _build_config(RAGAnythingConfig, working_dir)
- adapter_kwargs: dict[str, Any] = {"llm_selection": lightrag_llm_selection_from_settings()}
+def build_rag(
+ working_dir: Path,
+ *,
+ io_bridge: OwnerLoopBridge | None = None,
+ enable_vlm: bool = False,
+) -> Any:
+ """Construct one exact-version, version-isolated LightRAG instance."""
+ _require_exact_version()
+ _register_parser()
+ from lightrag.llm_roles import RoleLLMConfig
+
- adapter_kwargs = {"io_bridge": io_bridge} if io_bridge is not None else {}
++ llm_adapter_kwargs: dict[str, Any] = {"llm_selection": lightrag_llm_selection_from_settings()}
++ embedding_adapter_kwargs: dict[str, Any] = {}
+ if io_bridge is not None:
- adapter_kwargs["io_bridge"] = io_bridge
- 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),
++ llm_adapter_kwargs["io_bridge"] = io_bridge
++ embedding_adapter_kwargs["io_bridge"] = io_bridge
+ constructor = {
+ "working_dir": str(Path(working_dir)),
+ "workspace": workspace_for(working_dir),
- "llm_model_func": build_llm_model_func(**adapter_kwargs),
- "embedding_func": build_embedding_func(**adapter_kwargs),
++ "llm_model_func": build_llm_model_func(**llm_adapter_kwargs),
++ "embedding_func": build_embedding_func(**embedding_adapter_kwargs),
+ "auto_manage_storages_states": False,
+ "vlm_process_enable": bool(enable_vlm),
+ **indexing_kwargs_from_settings(),
+ **constructor_kwargs_from_settings(),
}
- 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 init
- # nevertheless runs a one-time installation check on its *default* parser
- # (``mineru``); when MinerU isn't installed that check hard-fails indexing
- # with "Parser 'mineru' is not properly installed" — even though the user
- # picked an entirely different parse engine (see issue #594). Marking the
- # check as already satisfied skips that spurious gate for a parser we don't
- # use, while leaving the real pre-parsed insert path untouched.
- rag._parser_installation_checked = True
- return rag
-
-
-async def insert(rag: Any, content_list: list[dict], *, file_name: str, doc_id: str) -> None:
- """Insert a pre-parsed ``content_list`` (multimodal-aware, no re-parsing)."""
- await rag.insert_content_list(
- content_list=content_list,
- file_path=file_name,
- doc_id=doc_id,
+ if enable_vlm:
+ constructor["role_llm_configs"] = {
- "vlm": RoleLLMConfig(func=build_vision_model_func(**adapter_kwargs))
++ "vlm": RoleLLMConfig(func=build_vision_model_func(**llm_adapter_kwargs))
+ }
+ return _controlled_class()(**constructor)
+
+
+async def initialize(rag: Any) -> None:
+ result = rag.initialize_storages()
+ if inspect.isawaitable(result):
+ await result
+
+
+async def enqueue(rag: Any, staged: list[StagedDocument]) -> str:
+ if not staged:
+ raise ValueError("Cannot enqueue an empty LightRAG batch")
+ return await rag.apipeline_enqueue_documents(
+ [""] * len(staged),
+ file_paths=[item.canonical_name for item in staged],
+ docs_format="pending_parse",
+ parse_engine=PARSER_ENGINE,
+ process_options=[item.process_options for item in staged],
+ chunk_options=[item.chunk_options for item in staged],
)
diff --cc tests/api/test_knowledge_router.py
index 358ad9419,d3d503396..05f5b2cba
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@@ -2132,118 -1929,58 +2132,166 @@@ def test_lightrag_config_endpoint_round
assert again["top_k"] == 42
+def test_lightrag_server_defaults_are_redacted_and_reused_for_probe(
+ monkeypatch, tmp_path: Path
+) -> None:
+ service = RuntimeSettingsService(tmp_path, process_env={})
+ monkeypatch.setattr(config_module, "get_runtime_settings_service", lambda: service)
+ monkeypatch.setattr(
+ config_module, "load_lightrag_server_settings", service.load_lightrag_server
+ )
+
+ calls: list[tuple[str, str]] = []
+
+ class Result:
+ ok = True
+
+ def to_dict(self) -> dict:
+ return {
+ "ok": True,
+ "base_url": "http://localhost:9621",
+ "reachable": True,
+ "auth_required": True,
+ "auth_ok": True,
+ "core_version": "1.0",
+ "api_version": "1",
+ "error": None,
+ }
+
+ async def fake_probe(server_url: str, api_key: str):
+ calls.append((server_url, api_key))
+ return Result()
+
+ probe_module = importlib.import_module("deeptutor.services.rag.pipelines.lightrag_server.probe")
+ monkeypatch.setattr(probe_module, "probe_server", fake_probe)
+
+ with TestClient(_build_app()) as client:
+ saved = client.put(
+ "/api/v1/knowledge/rag-pipelines/lightrag-server/config",
+ json={"server_url": "http://localhost:9621/", "api_key": "private-key"},
+ )
+ assert saved.status_code == 200
+ assert saved.json() == {
+ "server_url": "http://localhost:9621",
+ "api_key_set": True,
+ "configured": True,
+ }
+ assert "private-key" not in saved.text
+
+ probed = client.post(
+ "/api/v1/knowledge/probe-lightrag-server",
+ json={
+ "server_url": "http://localhost:9621",
+ "use_saved_api_key": True,
+ },
+ )
+
+ assert probed.status_code == 200
+ assert calls == [("http://localhost:9621", "private-key")]
+
+
+def test_llamaindex_config_endpoint_round_trips_vector_index_knobs(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """The vector-index form depends on every field surviving a save/reload."""
+ service = RuntimeSettingsService(tmp_path, process_env={})
+ monkeypatch.setattr(config_module, "get_runtime_settings_service", lambda: service)
+
+ client = TestClient(_build_app())
+ initial = client.get("/api/v1/knowledge/rag-pipelines/llamaindex/config")
+ assert initial.status_code == 200
+ assert initial.json()["vector_index_type"] == "flat"
+
+ saved = client.put(
+ "/api/v1/knowledge/rag-pipelines/llamaindex/config",
+ json={
+ "vector_index_type": "hnsw",
+ "hnsw_m": 24,
+ "hnsw_ef_construction": 128,
+ "hnsw_ef_search": 48,
+ },
+ )
+ assert saved.status_code == 200
+ assert saved.json()["vector_index_type"] == "hnsw"
+ assert saved.json()["hnsw_m"] == 24
+ assert saved.json()["hnsw_ef_construction"] == 128
+ assert saved.json()["hnsw_ef_search"] == 48
+
+ again = client.get("/api/v1/knowledge/rag-pipelines/llamaindex/config").json()
+ assert again["vector_index_type"] == "hnsw"
+ assert again["hnsw_ef_search"] == 48
+
+
+def test_llamaindex_config_endpoint_round_trips_reranker_knobs(monkeypatch, tmp_path: Path) -> None:
+ """The reranker form depends on both fields surviving save/reload."""
+ service = RuntimeSettingsService(tmp_path, process_env={})
+ monkeypatch.setattr(config_module, "get_runtime_settings_service", lambda: service)
+
+ client = TestClient(_build_app())
+ initial = client.get("/api/v1/knowledge/rag-pipelines/llamaindex/config")
+ assert initial.status_code == 200
+ assert initial.json()["reranker_model"] == ""
+ assert initial.json()["rerank_top_k"] == 50
+
+ saved = client.put(
+ "/api/v1/knowledge/rag-pipelines/llamaindex/config",
+ json={
+ "reranker_model": " BAAI/bge-reranker-base ",
+ "rerank_top_k": 25,
+ },
+ )
+ assert saved.status_code == 200
+ assert saved.json()["reranker_model"] == "BAAI/bge-reranker-base"
+ assert saved.json()["rerank_top_k"] == 25
+
+ again = client.get("/api/v1/knowledge/rag-pipelines/llamaindex/config").json()
+ assert again["reranker_model"] == "BAAI/bge-reranker-base"
+ assert again["rerank_top_k"] == 25
++
++
+ def test_lightrag_config_validates_dedicated_llm_selection(monkeypatch, tmp_path: Path) -> None:
- """The LightRAG override references a real catalog pair, not free text."""
+ from deeptutor.services.config.model_catalog import ModelCatalogService
+
+ settings_service = RuntimeSettingsService(tmp_path, process_env={})
+ catalog_service = ModelCatalogService(tmp_path / "model_catalog.json")
+ catalog_service.save(
+ {
+ "services": {
+ "llm": {
+ "active_profile_id": "profile-1",
+ "active_model_id": "model-1",
+ "profiles": [
+ {
+ "id": "profile-1",
- "name": "Local",
- "binding": "ollama",
- "models": [{"id": "model-1", "model": "qwen"}],
++ "name": "Dedicated",
++ "binding": "openai",
++ "base_url": "https://api.openai.com/v1",
++ "api_key": "secret",
++ "models": [{"id": "model-1", "name": "Model", "model": "gpt-4o"}],
+ }
+ ],
+ }
+ }
+ }
+ )
- monkeypatch.setattr(
- "deeptutor.services.config.get_runtime_settings_service",
- lambda: settings_service,
- )
- monkeypatch.setattr(
- "deeptutor.services.config.get_model_catalog_service",
- lambda: catalog_service,
- )
++ monkeypatch.setattr(config_module, "get_runtime_settings_service", lambda: settings_service)
++ monkeypatch.setattr(config_module, "get_model_catalog_service", lambda: catalog_service)
+
+ client = TestClient(_build_app())
+ saved = client.put(
+ "/api/v1/knowledge/rag-pipelines/lightrag/config",
+ json={"llm_profile_id": "profile-1", "llm_model_id": "model-1"},
+ )
+ assert saved.status_code == 200
- assert saved.json()["llm_profile_id"] == "profile-1"
- assert saved.json()["llm_model_id"] == "model-1"
+
+ unknown = client.put(
+ "/api/v1/knowledge/rag-pipelines/lightrag/config",
+ json={"llm_model_id": "missing"},
+ )
+ assert unknown.status_code == 422
+
+ cleared = client.put(
+ "/api/v1/knowledge/rag-pipelines/lightrag/config",
+ json={"llm_profile_id": "", "llm_model_id": ""},
+ )
+ assert cleared.status_code == 200
- assert cleared.json()["llm_profile_id"] == ""
- assert cleared.json()["llm_model_id"] == ""
diff --cc tests/services/config/test_graphrag_lightrag_settings.py
index bf287afb0,d4467bb6d..9c13c6fc7
--- a/tests/services/config/test_graphrag_lightrag_settings.py
+++ b/tests/services/config/test_graphrag_lightrag_settings.py
@@@ -93,29 -108,10 +108,31 @@@ def test_lightrag_settings_written_befo
assert loaded["max_concurrent_files"] == 1
assert loaded["llm_model_max_async"] == 4
assert loaded["entity_extract_max_gleaning"] == 1
+ assert loaded["llm_profile_id"] == ""
+ assert loaded["llm_model_id"] == ""
+def test_lightrag_server_defaults_round_trip_without_exposing_shape_drift(
+ tmp_path: Path,
+) -> None:
+ svc = RuntimeSettingsService(tmp_path, process_env={})
+ assert svc.load_lightrag_server() == {
+ "version": 1,
+ "server_url": "",
+ "api_key": "",
+ }
+
+ saved = svc.save_lightrag_server(
+ {"server_url": " http://localhost:9621/ ", "api_key": " secret "}
+ )
+ assert saved == {
+ "version": 1,
+ "server_url": "http://localhost:9621",
+ "api_key": "secret",
+ }
+ assert (tmp_path / "lightrag_server.json").exists()
+
+
def test_response_type_capped(tmp_path: Path) -> None:
svc = RuntimeSettingsService(tmp_path, process_env={})
saved = svc.save_graphrag({"response_type": "x" * 500})
diff --cc tests/services/rag/test_lightrag_pipeline.py
index ac13e2870,7cf7bead9..3e82371ef
--- a/tests/services/rag/test_lightrag_pipeline.py
+++ b/tests/services/rag/test_lightrag_pipeline.py
@@@ -63,148 -73,282 +63,255 @@@ def test_factory_routes_without_importi
assert normalize_provider_name("LightRAG") == "lightrag"
+ ("value", "expected"),
+ [("MIX", "mix"), ("local", "local"), (None, "hybrid"), ("invalid", "hybrid")],
+)
+def test_normalize_mode(value, expected) -> None:
+ assert config.normalize_mode(value) == expected
+
+
+def test_availability_checks_native_lightrag_module(monkeypatch) -> None:
+ seen: list[str] = []
+
+ def find_spec(name: str):
+ seen.append(name)
+ return None
+
+ monkeypatch.setattr(config.importlib.util, "find_spec", find_spec)
+ assert config.is_lightrag_available() is False
+ assert seen == ["lightrag"]
+
+
+ def test_lightrag_llm_selection_requires_both_catalog_ids(monkeypatch) -> None:
+ settings_cases = [
+ ({}, None),
+ ({"llm_profile_id": "p", "llm_model_id": "m"}, {"profile_id": "p", "model_id": "m"}),
+ ({"llm_profile_id": "p", "llm_model_id": ""}, None),
+ ({"llm_profile_id": "", "llm_model_id": "m"}, None),
+ ]
+ for settings, expected in settings_cases:
+ monkeypatch.setattr(
+ "deeptutor.services.config.load_lightrag_settings",
+ lambda settings=settings: settings,
+ )
- assert lr_config.lightrag_llm_selection_from_settings() == expected
-
++ assert config.lightrag_llm_selection_from_settings() == expected
+
-def test_lightrag_llm_adapter_resolves_dedicated_catalog_selection(
- monkeypatch,
-) -> None:
- class _Config:
- model = "light-model"
+
- class _Client:
++def test_lightrag_llm_adapter_resolves_dedicated_catalog_selection(monkeypatch) -> None:
++ class Client:
+ def __init__(self, *, config, configure_env) -> None:
- assert config is cfg
++ assert config is selected_config
+ assert configure_env is False
+
+ def get_model_func(self):
+ async def model_func(_prompt, **kwargs):
+ assert kwargs["max_retries"] == 0
+ return "ok"
+
+ return model_func
+
- cfg = _Config()
++ selected_config = object()
+ monkeypatch.setattr(
+ "deeptutor.services.model_selection.runtime.resolve_llm_config_for_selection",
- lambda selection: cfg,
++ lambda selection: selected_config,
+ )
- monkeypatch.setattr("deeptutor.services.llm.client.LLMClient", _Client)
++ monkeypatch.setattr("deeptutor.services.llm.client.LLMClient", Client)
+
- adapter = lr_config.build_llm_model_func(llm_selection={"profile_id": "p", "model_id": "m"})
++ adapter = config.build_llm_model_func(llm_selection={"profile_id": "p", "model_id": "m"})
+ assert asyncio.run(adapter("prompt")) == "ok"
+
+
-def test_lightrag_vision_adapter_resolves_dedicated_catalog_selection(
- monkeypatch,
-) -> None:
- class _Config:
- model = "light-model"
-
- class _Client:
++def test_lightrag_vision_adapter_resolves_dedicated_catalog_selection(monkeypatch) -> None:
++ class Client:
+ def __init__(self, *, config, configure_env) -> None:
- assert config is cfg
++ assert config is selected_config
+ assert configure_env is False
+
+ def get_vision_model_func(self):
+ async def model_func(_prompt, **kwargs):
+ assert kwargs["allow_image_fallback"] is False
++ assert kwargs["image_data"] == "sentinel"
+ return "ok"
+
+ return model_func
+
- cfg = _Config()
++ selected_config = object()
+ monkeypatch.setattr(
+ "deeptutor.services.model_selection.runtime.resolve_llm_config_for_selection",
- lambda selection: cfg,
++ lambda selection: selected_config,
+ )
- monkeypatch.setattr("deeptutor.services.llm.client.LLMClient", _Client)
-
- adapter = lr_config.build_vision_model_func(llm_selection={"profile_id": "p", "model_id": "m"})
- assert asyncio.run(adapter("prompt")) == "ok"
-
-
- "given,expected",
- [
- ("hybrid", "hybrid"),
- ("MIX", "mix"),
- ("naive", "naive"),
- ("local", "local"),
- ("global", "global"),
- ("", "hybrid"),
- (None, "hybrid"),
- ("bogus", "hybrid"),
- ],
-)
-def test_normalize_mode(given, expected) -> None:
- assert lr_config.normalize_mode(given) == expected
-
-
-def test_is_lightrag_available_false_when_dependency_missing(monkeypatch) -> None:
- def fake_find_spec(name):
- return None if name == "raganything" else object()
++ monkeypatch.setattr("deeptutor.services.llm.client.LLMClient", Client)
+
- monkeypatch.setattr(lr_config.importlib.util, "find_spec", fake_find_spec)
- assert lr_config.is_lightrag_available() is False
++ adapter = config.build_vision_model_func(llm_selection={"profile_id": "p", "model_id": "m"})
++ assert asyncio.run(adapter("prompt", image_inputs=[{"base64": "sentinel"}])) == "ok"
+
+
-# --------------------------------------------------------------------------- #
-# storage
-# --------------------------------------------------------------------------- #
-
-
-def test_storage_meta_and_has_output(tmp_path) -> None:
- root = tmp_path / "version-1"
- root.mkdir()
- assert storage.has_output(root) is False
- assert storage.has_output(None) is False
-
- (root / "vdb_chunks.json").write_text("{}", encoding="utf-8")
- assert storage.has_output(root) is False
++def test_build_rag_keeps_dedicated_llm_selection_out_of_embedding_kwargs(
++ monkeypatch, tmp_path: Path
++) -> None:
++ """The 1.6 native adapter must not pass LLM-only kwargs to embedding."""
+
- (root / "graph_chunk_entity_relation.graphml").write_text("<graph/>", encoding="utf-8")
- assert storage.has_output(root) is False
++ class NativeLightRag:
++ def __init__(self, **kwargs) -> None:
++ self.kwargs = kwargs
+
- (root / "kv_store_doc_status.json").write_text(
- json.dumps(
- {
- "doc-1": {
- "status": "failed",
- "file_path": "bad.docx",
- "error_msg": "embedding failed",
- "chunks_list": [],
- }
- }
- ),
- encoding="utf-8",
++ fake_lightrag = types.ModuleType("lightrag")
++ fake_lightrag.__path__ = [] # type: ignore[attr-defined]
++ fake_roles = types.ModuleType("lightrag.llm_roles")
++ fake_roles.RoleLLMConfig = object # type: ignore[attr-defined]
++ monkeypatch.setitem(sys.modules, "lightrag", fake_lightrag)
++ monkeypatch.setitem(sys.modules, "lightrag.llm_roles", fake_roles)
++ monkeypatch.setattr(engine, "_require_exact_version", lambda: None)
++ monkeypatch.setattr(engine, "_register_parser", lambda: None)
++ monkeypatch.setattr(engine, "_controlled_class", lambda: NativeLightRag)
++ monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)
++ monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)
++ selection = {"profile_id": "profile-1", "model_id": "model-1"}
++ monkeypatch.setattr(engine, "lightrag_llm_selection_from_settings", lambda: selection)
++ llm_calls: list[dict[str, object]] = []
++ embedding_calls: list[object] = []
++
++ def build_llm(**kwargs):
++ llm_calls.append(kwargs)
++ return "llm"
++
++ def build_embedding(*, io_bridge=None):
++ embedding_calls.append(io_bridge)
++ return "embedding"
++
++ monkeypatch.setattr(engine, "build_llm_model_func", build_llm)
++ monkeypatch.setattr(engine, "build_embedding_func", build_embedding)
++
++ rag = engine.build_rag(tmp_path)
++
++ assert llm_calls == [{"llm_selection": selection}]
++ assert embedding_calls == [None]
++ assert rag.kwargs["embedding_func"] == "embedding"
++
++
+@REQUIRES_LIGHTRAG
+def test_distribution_identity_is_exact_rc2() -> None:
+ assert engine.installed_version() == "1.5.7rc2"
+ assert engine.LIGHTRAG_DISTRIBUTION == "lightrag-hku"
+
+
+def test_preflight_rejects_a_different_installed_lightrag_version(monkeypatch) -> None:
+ from deeptutor.services.rag import preflight
+
+ monkeypatch.setattr(config, "is_lightrag_available", lambda: True)
+ monkeypatch.setattr(engine, "installed_version", lambda: "1.5.8")
+ monkeypatch.setattr(preflight, "_active_embedding", lambda: ("embedding", 3))
+ monkeypatch.setattr(preflight, "_active_chat_model", lambda: ("chat", "openai"))
+ report = preflight._lightrag_preflight()
+ package = next(check for check in report["checks"] if check["key"] == "package")
+ assert package["ok"] is False
+ assert package["detail"] == "Found 1.5.8; required 1.5.7rc2."
+
+
+def test_workspace_is_stable_and_version_specific(tmp_path: Path) -> None:
+ first = engine.workspace_for(tmp_path / "version-1")
+ assert first == engine.workspace_for(tmp_path / "version-1")
+ assert first != engine.workspace_for(tmp_path / "version-2")
+ assert first.startswith("deeptutor_")
+
+
+def _resolver(tmp_path: Path):
+ cls = engine._controlled_class()
+ rag = object.__new__(cls)
+ rag.working_dir = str(tmp_path)
+ return rag
+
+
+@REQUIRES_LIGHTRAG
+def test_source_resolver_only_reads_version_ingress(tmp_path: Path, monkeypatch) -> None:
+ pending = pending_root(tmp_path)
+ pending.mkdir(parents=True)
+ expected = pending / "doc.pdf"
+ expected.write_bytes(b"right")
+ decoy = tmp_path / "decoy"
+ decoy.mkdir()
+ (decoy / "doc.pdf").write_bytes(b"wrong")
+ monkeypatch.chdir(decoy)
+ rag = _resolver(tmp_path)
+ assert rag._resolve_source_file_for_parser("doc.pdf", parser_engine="deeptutor") == str(
+ expected.resolve()
)
- assert storage.has_output(root) is False
- assert storage.failure_summary(root) == "bad.docx: embedding failed"
- assert storage.document_error(root, "doc-1") == "embedding failed"
- (root / "kv_store_doc_status.json").write_text(
- json.dumps(
- {
- "doc-1": {
- "status": "processed",
- "file_path": "good.docx",
- "chunks_list": ["chunk-1"],
- }
- }
- ),
- encoding="utf-8",
- )
- assert storage.has_output(root) is True
-
- storage.write_meta(root)
- meta = json.loads((root / storage.META_FILENAME).read_text())
- assert meta["signature"] == "lightrag"
- assert meta["provider"] == "lightrag"
-
-
-class _FakeEmbeddingFunc:
- """Stands in for ``lightrag.utils.EmbeddingFunc``.
-
- Its signature is deliberately limited to the real dataclass's fields, so a
- constructor kwarg the pinned dependency does not accept fails here too.
- ``test_fake_embedding_func_matches_the_real_dataclass`` pins the two
- together whenever LightRAG is installed.
- """
-
- def __init__(
- self,
- *,
- embedding_dim,
- func,
- max_token_size=8192,
- send_dimensions=None,
- model_name=None,
- supports_asymmetric=False,
- ) -> None:
- self.embedding_dim = embedding_dim
- self.func = func
- self.max_token_size = max_token_size
- self.send_dimensions = send_dimensions
- self.model_name = model_name
- self.supports_asymmetric = supports_asymmetric
-
- async def __call__(self, *args, **kwargs):
- if not self.supports_asymmetric:
- kwargs.pop("context", None)
- return await self.func(*args, **kwargs)
-
-
-class _LegacyFakeEmbeddingFunc:
- """Models LightRAG before ``supports_asymmetric`` was introduced."""
-
- def __init__(
- self,
- *,
- embedding_dim,
- func,
- max_token_size=8192,
- send_dimensions=None,
- model_name=None,
- ) -> None:
- self.embedding_dim = embedding_dim
- self.func = func
- self.max_token_size = max_token_size
- self.send_dimensions = send_dimensions
- self.model_name = model_name
-
- async def __call__(self, *args, **kwargs):
- return await self.func(*args, **kwargs)
-
-
-class _RecordingBridge:
- def __init__(self) -> None:
- self.calls = 0
- async def run(self, factory):
- self.calls += 1
- return await factory()
+@REQUIRES_LIGHTRAG
[email protected]("bad", ["../doc.pdf", "/tmp/doc.pdf", "nested/doc.pdf"])
+def test_source_resolver_rejects_noncanonical_paths(tmp_path: Path, bad: str) -> None:
+ rag = _resolver(tmp_path)
+ with pytest.raises(IngressError):
+ rag._resolve_source_file_for_parser(bad, parser_engine="deeptutor")
-def _install_fake_lightrag(monkeypatch, embedding_func_cls=_FakeEmbeddingFunc) -> None:
- fake_lightrag = types.ModuleType("lightrag")
- fake_utils = types.ModuleType("lightrag.utils")
- fake_utils.EmbeddingFunc = embedding_func_cls
- monkeypatch.setitem(sys.modules, "lightrag", fake_lightrag)
- monkeypatch.setitem(sys.modules, "lightrag.utils", fake_utils)
+@REQUIRES_LIGHTRAG
+def test_source_resolver_rejects_symlink_and_ambiguity(tmp_path: Path) -> None:
+ pending = pending_root(tmp_path)
+ archived = pending / "__parsed__"
+ archived.mkdir(parents=True)
+ outside = tmp_path / "outside.pdf"
+ outside.write_bytes(b"outside")
+ (pending / "doc.pdf").symlink_to(outside)
+ rag = _resolver(tmp_path)
+ with pytest.raises(IngressError, match="missing"):
+ rag._resolve_source_file_for_parser("doc.pdf", parser_engine="deeptutor")
+ (pending / "doc.pdf").unlink()
+ (pending / "doc.pdf").write_bytes(b"one")
+ (archived / "doc.pdf").write_bytes(b"two")
+ with pytest.raises(IngressError, match="ambiguous"):
+ rag._resolve_source_file_for_parser("doc.pdf", parser_engine="deeptutor")
-def test_fake_embedding_func_matches_the_real_dataclass() -> None:
- """Guard against the stub drifting from the dependency it stands in for."""
- import dataclasses
+@REQUIRES_LIGHTRAG
+def test_source_resolver_rejects_other_parser(tmp_path: Path) -> None:
+ with pytest.raises(IngressError, match="Unsupported parser"):
+ _resolver(tmp_path)._resolve_source_file_for_parser("doc.pdf", parser_engine="mineru")
- lightrag_utils = pytest.importorskip("lightrag.utils")
- real_fields = {field.name for field in dataclasses.fields(lightrag_utils.EmbeddingFunc)}
- stub = _FakeEmbeddingFunc if "supports_asymmetric" in real_fields else _LegacyFakeEmbeddingFunc
- stub_fields = set(inspect.signature(stub.__init__).parameters.keys() - {"self"})
- assert stub_fields == real_fields
+def test_vision_adapter_maps_one_base64_unchanged(monkeypatch) -> None:
+ captured: dict[str, object] = {}
+ class Client:
+ def get_vision_model_func(self):
+ async def call(prompt, **kwargs):
+ captured["prompt"] = prompt
+ captured.update(kwargs)
+ return "seen"
-def test_embedding_func_returns_numpy_array(monkeypatch) -> None:
- _install_fake_lightrag(monkeypatch)
+ return call
- class _Config:
- dim = 3
- max_tokens = 99
+ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: Client())
+ func = config.build_vision_model_func()
+ assert asyncio.run(func("describe", image_inputs=[{"base64": "sentinel"}])) == "seen"
+ assert captured["image_data"] == "sentinel"
+ assert captured["allow_image_fallback"] is False
- class _Client:
- async def embed(self, texts, *, input_type=None):
- del input_type
- return [[1, 2, 3] for _ in texts]
- monkeypatch.setattr("deeptutor.services.embedding.get_embedding_config", lambda: _Config())
- monkeypatch.setattr("deeptutor.services.embedding.get_embedding_client", lambda: _Client())
+ "value",
+ [None, [], [{"base64": "a"}, {"base64": "b"}], [{}], ["image"], [{"base64": ""}]],
+)
+def test_vision_adapter_rejects_invalid_inputs(monkeypatch, value) -> None:
+ class Client:
+ def get_vision_model_func(self):
+ async def call(*_args, **_kwargs):
+ raise AssertionError("prompt-only fallback must not run")
- bridge = _RecordingBridge()
- embedding = lr_config.build_embedding_func(io_bridge=bridge)
- vectors = asyncio.run(embedding.func(["a", "b"]))
- assert embedding.embedding_dim == 3
- assert embedding.max_token_size == 99
- assert vectors.shape == (2, 3)
- assert hasattr(vectors, "size")
- assert bridge.calls == 1
+ return call
+ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: Client())
+ with pytest.raises(ValueError):
+ asyncio.run(config.build_vision_model_func()("describe", image_inputs=value))
- ("embedding_func_cls", "expected_opt_in"),
- [
- (_FakeEmbeddingFunc, True),
- (_LegacyFakeEmbeddingFunc, None),
- ],
-)
-def test_embedding_func_maps_lightrag_query_and_document_context(
- monkeypatch,
- embedding_func_cls,
- expected_opt_in,
-) -> None:
+
+@REQUIRES_LIGHTRAG
+def test_embedding_adapter_preserves_query_and_document_roles(monkeypatch) -> None:
calls: list[tuple[list[str], str | None]] = []
- _install_fake_lightrag(monkeypatch, embedding_func_cls)
- class _Config:
+ class EmbeddingConfig:
dim = 3
max_tokens = 99
diff --cc tests/services/rag/test_lightrag_settings_wiring.py
index 87684ceb1,2331fe028..a72c2ca99
--- a/tests/services/rag/test_lightrag_settings_wiring.py
+++ b/tests/services/rag/test_lightrag_settings_wiring.py
@@@ -7,60 -16,155 +7,89 @@@ from pathlib import Pat
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
+from deeptutor.services.rag.pipelines.lightrag import engine
+pytestmark = pytest.mark.skipif(
+ importlib.util.find_spec("lightrag") is None,
+ reason="requires the optional rag-lightrag extra",
+)
-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)
+class _NativeLightRag:
+ def __init__(self, **kwargs) -> None:
+ self.kwargs = kwargs
- return install
+def _stub_build(monkeypatch) -> None:
+ monkeypatch.setattr(engine, "_require_exact_version", lambda: None)
+ monkeypatch.setattr(engine, "_register_parser", lambda: None)
+ monkeypatch.setattr(engine, "_controlled_class", lambda: _NativeLightRag)
+ monkeypatch.setattr(engine, "build_llm_model_func", lambda **_kwargs: "llm")
+ monkeypatch.setattr(engine, "build_embedding_func", lambda **_kwargs: "embedding")
++ monkeypatch.setattr(engine, "lightrag_llm_selection_from_settings", lambda: None)
[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:
+def test_native_constructor_receives_every_supported_knob(monkeypatch, tmp_path: Path) -> None:
+ _stub_build(monkeypatch)
monkeypatch.setattr(
- engine_module, "indexing_kwargs_from_settings", lambda: {"max_concurrent_files": 4}
+ engine, "indexing_kwargs_from_settings", lambda: {"max_parallel_parse_native": 4}
)
monkeypatch.setattr(
- engine_module,
- "lightrag_kwargs_from_settings",
+ engine,
+ "constructor_kwargs_from_settings",
lambda: {"llm_model_max_async": 8, "entity_extract_max_gleaning": 2},
)
- monkeypatch.setattr(
- engine_module,
- "lightrag_llm_selection_from_settings",
- lambda: {"profile_id": "profile-1", "model_id": "model-1"},
- )
-
-
-def test_modern_raganything_receives_every_knob(
- fake_raganything, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- fake_raganything(_ModernRag, _ModernConfig)
- llm_selection_args: list[dict[str, str] | None] = []
-
- def record_llm_adapter(**kwargs):
- llm_selection_args.append(kwargs.get("llm_selection"))
- return lambda *args, **kwargs: None
-
- monkeypatch.setattr(engine_module, "build_llm_model_func", record_llm_adapter)
- monkeypatch.setattr(
- engine_module,
- "build_vision_model_func",
- lambda **_kwargs: lambda *args, **kwargs: None,
- )
- monkeypatch.setattr(
- engine_module,
- "build_embedding_func",
- lambda **_kwargs: lambda *args, **kwargs: None,
- )
- rag = engine_module.build_rag(tmp_path)
+ rag = engine.build_rag(tmp_path)
- assert rag.config.max_concurrent_files == 4
- assert llm_selection_args == [{"profile_id": "profile-1", "model_id": "model-1"}]
- assert rag.lightrag_kwargs == {"llm_model_max_async": 8, "entity_extract_max_gleaning": 2}
+ assert rag.kwargs["working_dir"] == str(tmp_path)
+ assert rag.kwargs["workspace"] == engine.workspace_for(tmp_path)
+ assert rag.kwargs["llm_model_func"] == "llm"
+ assert rag.kwargs["embedding_func"] == "embedding"
+ assert rag.kwargs["auto_manage_storages_states"] is False
+ assert rag.kwargs["max_parallel_parse_native"] == 4
+ assert rag.kwargs["llm_model_max_async"] == 8
+ assert rag.kwargs["entity_extract_max_gleaning"] == 2
+ assert rag.kwargs["vlm_process_enable"] is False
+ assert "role_llm_configs" not in rag.kwargs
-def test_legacy_raganything_still_builds(
- fake_raganything, tmp_path: Path, caplog: pytest.LogCaptureFixture
++def test_dedicated_selection_reaches_llm_but_not_embedding_adapter(
++ monkeypatch, tmp_path: Path
+ ) -> 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)
++ _stub_build(monkeypatch)
++ selection = {"profile_id": "profile-1", "model_id": "model-1"}
++ monkeypatch.setattr(engine, "lightrag_llm_selection_from_settings", lambda: selection)
++ llm_calls: list[dict[str, object]] = []
++ embedding_calls: list[dict[str, object]] = []
+
- 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 build_llm(**kwargs):
++ llm_calls.append(kwargs)
++ return "llm"
+
++ def build_embedding(**kwargs):
++ embedding_calls.append(kwargs)
++ return "embedding"
+
-def test_mixed_versions_drop_only_the_unsupported_knob(fake_raganything, tmp_path: Path) -> None:
- fake_raganything(_LegacyRag, _ModernConfig)
++ monkeypatch.setattr(engine, "build_llm_model_func", build_llm)
++ monkeypatch.setattr(engine, "build_embedding_func", build_embedding)
++ monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)
++ monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)
+
- rag = engine_module.build_rag(tmp_path)
++ engine.build_rag(tmp_path)
+
- assert rag.config.max_concurrent_files == 4
- assert rag.lightrag_kwargs is None
++ assert llm_calls == [{"llm_selection": selection}]
++ assert embedding_calls == [{}]
+
+
-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)
+def test_vlm_role_is_only_configured_when_enabled(monkeypatch, tmp_path: Path) -> None:
+ _stub_build(monkeypatch)
+ monkeypatch.setattr(engine, "build_vision_model_func", lambda **_kwargs: "vision")
+ monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)
+ monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)
- rag = engine_module.build_rag(tmp_path)
+ rag = engine.build_rag(tmp_path, enable_vlm=True)
- assert rag.config.max_concurrent_files == 1 # the library default
- assert rag.lightrag_kwargs is None
+ role = rag.kwargs["role_llm_configs"]["vlm"]
+ assert role.func == "vision"
+ assert rag.kwargs["vlm_process_enable"] is True
diff --cc web/lib/knowledge-api.ts
index d7a96342c,914364ee4..1395c18b9
--- a/web/lib/knowledge-api.ts
+++ b/web/lib/knowledge-api.ts
@@@ -94,14 -83,11 +94,17 @@@ export interface LightRagConfig
llm_model_max_async: number;
/** Extra extraction passes per chunk, to recover missed entities. */
entity_extract_max_gleaning: number;
+ /** Stable catalog reference, or empty strings for the global active chat model. */
+ llm_profile_id: string;
+ llm_model_id: string;
}
+export interface LightRagServerConfig {
+ server_url: string;
+ api_key_set: boolean;
+ configured: boolean;
+}
+
export interface PreflightCheck {
key: string;
label: string;