Skip to content

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

integrate lightrag-server & other fixes.

Bingxi Zhao (Frank)eef785ae1ef0
diff --git a/CONTAINERIZATION.md b/CONTAINERIZATION.md
index 1c3bd6546..ff2ea1997 100644
--- a/CONTAINERIZATION.md
+++ b/CONTAINERIZATION.md
@@ -243,14 +243,18 @@ After the container is up, the backend and frontend run as the non-root
`supervisord` as root (PID 1) with its `uvicorn`/`node` children as
`deeptutor` (UID 1000).
-### Known minor follow-up
-
-`supervisord` emits
-`CRIT could not write pidfile /var/run/supervisord.pid` on startup
-because `/var/run` tmpfs is `mode=0755` (owned by root) and the
-now-unprivileged PID 1 can't write there. Children still spawn fine and
-reach RUNNING state. The fix is `mode=1777` on `/var/run` (matching
-`/tmp`); deferred to keep this PR focused.
+### Supervisord pidfile
+
+`supervisord` (PID 1) runs as **root**, which owns the `/var/run` tmpfs, so
+it writes `/var/run/supervisord.pid` cleanly even at `mode=0755`. An earlier
+build dropped PID 1 *itself* to the unprivileged `deeptutor` user (via
+`gosu`); that PID 1 couldn't write the root-owned `/var/run` and logged a
+cosmetic `CRIT could not write pidfile /var/run/supervisord.pid` on every
+start under rootless podman. Running supervisord as root and dropping only
+its child programs to `deeptutor` (the `user=` directives above) resolved
+both that CRIT and the fatal `/dev/fd/1,2` EACCES seen under rootful Docker.
+If you ever revert PID 1 to a non-root user, set `/var/run` to `mode=1777`
+(matching `/tmp`) so the pidfile stays writable.
---
diff --git a/README.md b/README.md
index aeef16f6f..a37c24e5e 100644
--- a/README.md
+++ b/README.md
@@ -472,7 +472,7 @@ Each partner has a `SOUL.md`, model selection, channels, tool policy, and assign
<img src="assets/figs/web-1.4.6+/partners/02-IM%20config%20for%20each%20partner.png" alt="Per-partner IM channel configuration" width="900">
</div>
-The channel layer is schema-driven and can connect to IM platforms such as Feishu, Telegram, Slack, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Matrix, and Microsoft Teams depending on installed extras and configured credentials. A partner can also be connected as a subagent and consulted from a normal chat turn — see **My Agents** below.
+The channel layer is schema-driven and can connect to IM platforms such as Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Matrix, Mochat, and Microsoft Teams depending on installed extras and configured credentials. A partner can also be connected as a subagent and consulted from a normal chat turn — see **My Agents** below.
</details>
@@ -572,7 +572,7 @@ You don't have to write every skill yourself — **Import from EduHub** browses
<img src="assets/figs/web-1.4.6+/memory/00-overview.png" alt="DeepTutor memory overview" width="900">
</div>
-Memory is a file-backed, three-layer system you can read, curate, and audit — deliberately *not* a hidden vector store. **L1** is the workspace mirror plus an append-only event trace (`trace/<surface>/<date>.jsonl`); **L2** is per-surface curated facts (`L2/<surface>.md`); **L3** is cross-surface synthesis (`L3/<profile|recent|scope>.md`). Because L2 cites L1 and L3 cites L2, nothing in your profile is unaccountable.
+Memory is a file-backed, three-layer system you can read, curate, and audit — deliberately *not* a hidden vector store. **L1** is the workspace mirror plus an append-only event trace (`trace/<surface>/<date>.jsonl`); **L2** is per-surface curated facts (`L2/<surface>.md`); **L3** is cross-surface synthesis (`L3/<profile|recent|scope|preferences>.md`). Because L2 cites L1 and L3 cites L2, nothing in your profile is unaccountable.
<div align="center">
<img src="assets/figs/web-1.4.6+/memory/01-3%20layer%20memory%20graph.png" alt="DeepTutor memory graph" width="900">
@@ -673,7 +673,7 @@ The repo ships a root [`SKILL.md`](SKILL.md) — a ~150-line handover doc that t
| `deeptutor chat` | Interactive REPL with capability, tool, KB, notebook, and history controls |
| `deeptutor partner list/create/start/stop` | Manage IM-connected partners |
| `deeptutor kb list/info/create/add/search/set-default/delete` | Manage LlamaIndex knowledge bases |
-| `deeptutor skill search/install/list/remove/login/publish/update` | Manage skills, install from hubs, and publish your own (`eduhub:<slug>` by default, see Ecosystem) |
+| `deeptutor skill search/install/list/remove/login/logout/publish/update` | Manage skills, install from hubs, and publish your own (`eduhub:<slug>` by default, see Ecosystem) |
| `deeptutor memory show/clear` | Inspect L2/L3 memory docs or clear L1/all memory |
| `deeptutor session list/show/open/rename/delete` | Manage shared sessions |
| `deeptutor notebook list/create/show/add-md/replace-md/remove-record` | Manage notebooks from Markdown files |
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index 04144380b..c91e44b33 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -1539,6 +1539,84 @@ async def connect_linked_folder_route(payload: ConnectFolderRequest):
}
+class ProbeLightRagServerRequest(BaseModel):
+ server_url: str
+ api_key: str = ""
+
+
+class ConnectLightRagServerRequest(BaseModel):
+ name: str
+ server_url: str
+ api_key: str = ""
+ search_mode: str = ""
+
+
[email protected]("/probe-lightrag-server")
+async def probe_lightrag_server_route(payload: ProbeLightRagServerRequest):
+ """Test-connect to an external LightRAG server before binding a KB to it.
+
+ Returns the verdict (reachable? is it a LightRAG server? API key accepted?)
+ so the UI can confirm before any registration happens. Creates nothing.
+ """
+ from deeptutor.services.rag.pipelines.lightrag_server.probe import probe_server
+
+ server_url = (payload.server_url or "").strip()
+ if not server_url:
+ raise HTTPException(status_code=400, detail="server_url is required.")
+ result = await probe_server(server_url, payload.api_key or "")
+ return result.to_dict()
+
+
[email protected]("/connect-lightrag-server")
+async def connect_lightrag_server_route(payload: ConnectLightRagServerRequest):
+ """Connect an external LightRAG server as a retrieval-only knowledge base.
+
+ Re-probes server-side (never trusts the client's verdict), then registers a
+ pointer (``type: lightrag_server``). Retrieval is offloaded to the server's
+ ``/query`` endpoint — no copy, no local index.
+ """
+ from deeptutor.services.rag.pipelines.lightrag_server.config import SUPPORTED_MODES
+ from deeptutor.services.rag.pipelines.lightrag_server.probe import probe_server
+
+ name = (payload.name or "").strip()
+ server_url = (payload.server_url or "").strip()
+ if not name or not server_url:
+ raise HTTPException(status_code=400, detail="Both name and server_url are required.")
+
+ result = await probe_server(server_url, payload.api_key or "")
+ if not result.ok:
+ raise HTTPException(
+ status_code=400, detail=result.error or "Could not connect to the LightRAG server."
+ )
+
+ search_mode = (payload.search_mode or "").strip().lower()
+ if search_mode and search_mode not in SUPPORTED_MODES:
+ search_mode = ""
+
+ try:
+ manager = get_kb_manager()
+ entry = manager.register_lightrag_server_kb(
+ name,
+ result.base_url,
+ api_key=payload.api_key or "",
+ search_mode=search_mode,
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=400, detail=str(e))
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.error(f"Error connecting LightRAG server: {e}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+ return {
+ "status": "connected",
+ "name": name,
+ "server_url": entry["server_url"],
+ "rag_provider": entry["rag_provider"],
+ }
+
+
@router.get("/list", response_model=list[KnowledgeBaseInfo])
async def list_knowledge_bases():
"""List all available knowledge bases with their details."""
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index 779a58a2b..72f6f903b 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -192,6 +192,12 @@ class DocumentParsingTest(BaseModel):
engine: Optional[str] = None
+class DocumentParsingInstall(BaseModel):
+ """One-click pip install of an optional parser engine's package(s)."""
+
+ engine: str
+
+
def _invalidate_runtime_caches() -> None:
"""Force runtime clients/config to pick up the latest saved catalog.
@@ -502,6 +508,10 @@ def _document_parsing_payload() -> dict[str, Any]:
"""State for the Document Parsing settings page: active engine, all engine
slices (MinerU token redacted), engine availability, and per-engine
readiness (so the UI can surface the "models not downloaded" gate)."""
+ from deeptutor.services.parsing.engines._install import (
+ installable_engines,
+ model_downloadable_engines,
+ )
from deeptutor.services.parsing.engines.factory import (
get_parser,
list_engines,
@@ -540,6 +550,9 @@ def _document_parsing_payload() -> dict[str, Any]:
"engines": redacted,
"available_engines": available,
"readiness": readiness,
+ # Engine ids that support one-click pip install / model download here.
+ "installable": sorted(installable_engines()),
+ "model_downloadable": sorted(model_downloadable_engines()),
# MinerU-specific UI state (token presence + CLI probe).
"mineru": {
"api_token_set": bool(mineru_slice.get("api_token")),
@@ -632,6 +645,76 @@ async def test_document_parsing(payload: DocumentParsingTest):
}
+def _normalize_engine_name(name: str) -> str:
+ return (name or "").strip().lower().replace("-", "_").replace(" ", "_")
+
+
[email protected]("/document-parsing/install")
+async def start_document_parsing_install(payload: DocumentParsingInstall):
+ """Kick off a one-click ``pip install`` of an optional engine's package(s).
+
+ Returns ``{ok, message}`` immediately; progress is polled via the shared job
+ status endpoint. Only one job runs at a time (process-wide singleton). The
+ engine must be in the install allow-list (``ENGINE_PIP_SPECS``)."""
+ _require_settings_admin()
+ from deeptutor.services.parsing.engines._install import (
+ ENGINE_PIP_SPECS,
+ get_background_job_manager,
+ )
+
+ engine = _normalize_engine_name(payload.engine)
+ specs = ENGINE_PIP_SPECS.get(engine)
+ if not specs:
+ return {"ok": False, "message": f"No installable package for engine '{engine}'."}
+ return get_background_job_manager().start_install(engine=engine, specs=specs)
+
+
[email protected]("/document-parsing/models/download")
+async def start_document_parsing_model_download(payload: DocumentParsingInstall):
+ """Kick off a one-click model-weight download for an engine (e.g. Docling).
+
+ Runs the engine's downloader console script (``docling-tools models
+ download``) as a background subprocess; progress is polled via the shared job
+ status endpoint. The engine must be in ``ENGINE_MODEL_DOWNLOADERS`` and its
+ script reachable next to the server's python or on PATH."""
+ _require_settings_admin()
+ from deeptutor.services.parsing.engines._install import (
+ get_background_job_manager,
+ model_downloadable_engines,
+ resolve_model_downloader,
+ )
+
+ engine = _normalize_engine_name(payload.engine)
+ if engine not in model_downloadable_engines():
+ return {"ok": False, "message": f"No model download for engine '{engine}'."}
+ cmd = resolve_model_downloader(engine)
+ if not cmd:
+ return {
+ "ok": False,
+ "message": (
+ f"The {engine} model downloader wasn't found. Reinstall the engine "
+ f"(pip install deeptutor[parse-{engine}]) so its CLI is on PATH."
+ ),
+ }
+ return get_background_job_manager().start_model_download(engine=engine, cmd=cmd)
+
+
[email protected]("/document-parsing/job/status")
+async def document_parsing_job_status(cursor: int = 0):
+ _require_settings_admin()
+ from deeptutor.services.parsing.engines._install import get_background_job_manager
+
+ return get_background_job_manager().status(cursor)
+
+
[email protected]("/document-parsing/job/cancel")
+async def cancel_document_parsing_job():
+ _require_settings_admin()
+ from deeptutor.services.parsing.engines._install import get_background_job_manager
+
+ return get_background_job_manager().cancel()
+
+
@router.post("/mineru/models/download")
async def start_mineru_models_download(payload: MinerUModelDownloadPayload):
"""Kick off a one-click model download via ``mineru-models-download``.
diff --git a/deeptutor/knowledge/kb_types.py b/deeptutor/knowledge/kb_types.py
index 2d82b3af6..ddd9c7976 100644
--- a/deeptutor/knowledge/kb_types.py
+++ b/deeptutor/knowledge/kb_types.py
@@ -18,14 +18,21 @@ flavours exist today:
*local* CLI (Claude Code / Codex), keyed by an optional ``cwd``; or a
``partner`` (one of the user's own partners), keyed by ``partner_id``. It has
no path on disk and nothing to index or retrieve. See ``capabilities/subagent``.
+* ``lightrag_server`` — a pointer (``server_url`` + optional ``api_key``) to an
+ external, standalone LightRAG server the user already runs and indexed. We
+ never index or store anything locally: retrieval is offloaded to that server's
+ ``/query`` endpoint and the bound ``rag_provider`` (``lightrag-server``) shapes
+ the result for the ``rag`` tool. One server instance = one workspace = one KB.
+ See ``services/rag/pipelines/lightrag_server``.
All connected flavours share the same lifecycle quirks: no on-disk folder under
``base_dir``, no embedding reconcile, and deletion must never touch the
-external files. The :func:`is_connected_kb` / :func:`external_root_of` helpers
+external resource. The :func:`is_connected_kb` / :func:`external_root_of` helpers
let the manager treat them uniformly without sprinkling ``type`` literals
-across the codebase. ``subagent`` is connected but points at no folder, so
-:func:`external_root_of` returns ``None`` for it — nothing resolves it to a
-path because the capability owns the turn and never touches rag.
+across the codebase. ``subagent`` and ``lightrag_server`` are connected but point
+at no folder, so :func:`external_root_of` returns ``None`` for them — a subagent
+is driven by its capability and a LightRAG server is reached over HTTP; neither
+resolves to a local path.
Kept in its own low-level module so both :mod:`deeptutor.knowledge.manager`
and the capability layer can import it without a cycle.
@@ -50,9 +57,17 @@ LINKED_KB_TYPE = "linked"
# working directory. Driven live via ``consult_subagent``; never indexed.
SUBAGENT_KB_TYPE = "subagent"
+# A connected external LightRAG server: a pointer (``server_url`` + optional
+# ``api_key``) to a standalone LightRAG instance the user runs. No path on disk
+# and no local index — retrieval is offloaded over HTTP to the server's
+# ``/query`` endpoint by the ``lightrag-server`` provider.
+LIGHTRAG_SERVER_KB_TYPE = "lightrag_server"
+
# Every pointer/connected KB type. Membership here is what makes the manager
# skip the index pipeline, the orphan prune and the embedding reconcile.
-CONNECTED_KB_TYPES = frozenset({OBSIDIAN_KB_TYPE, LINKED_KB_TYPE, SUBAGENT_KB_TYPE})
+CONNECTED_KB_TYPES = frozenset(
+ {OBSIDIAN_KB_TYPE, LINKED_KB_TYPE, SUBAGENT_KB_TYPE, LIGHTRAG_SERVER_KB_TYPE}
+)
def is_connected_kb(entry: Any) -> bool:
@@ -75,6 +90,7 @@ __all__ = [
"OBSIDIAN_KB_TYPE",
"LINKED_KB_TYPE",
"SUBAGENT_KB_TYPE",
+ "LIGHTRAG_SERVER_KB_TYPE",
"CONNECTED_KB_TYPES",
"is_connected_kb",
"external_root_of",
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index d6527dfe8..8b4d813d7 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -18,6 +18,7 @@ import sys
from typing import Any
from deeptutor.knowledge.kb_types import (
+ LIGHTRAG_SERVER_KB_TYPE,
LINKED_KB_TYPE,
OBSIDIAN_KB_TYPE,
SUBAGENT_KB_TYPE,
@@ -27,6 +28,7 @@ from deeptutor.knowledge.kb_types import (
from deeptutor.services.rag.factory import (
DEFAULT_PROVIDER,
KNOWN_PROVIDERS,
+ LIGHTRAG_SERVER_PROVIDER,
has_ready_provider_index,
normalize_provider_name,
provider_uses_embedding_versions,
@@ -835,6 +837,57 @@ class KnowledgeBaseManager:
self._save_config()
return entry
+ def register_lightrag_server_kb(
+ self,
+ name: str,
+ server_url: str,
+ *,
+ api_key: str = "",
+ search_mode: str = "",
+ description: str = "",
+ ) -> dict:
+ """Register a pointer to an external LightRAG server as a connected KB.
+
+ Like the other connected types this creates no folder under ``base_dir``
+ and runs no index pipeline: it records a ``type: lightrag_server`` entry
+ whose ``server_url`` (+ optional ``api_key``) the ``lightrag-server``
+ provider queries over HTTP. The server owns indexing entirely. Callers
+ should validate reachability with the probe helper first; this only
+ guards basic invariants. Raises ``ValueError`` on a missing name/URL or a
+ name clash.
+ """
+ name = (name or "").strip()
+ server_url = (server_url or "").strip().rstrip("/")
+ if not name:
+ raise ValueError("Knowledge base name is required.")
+ if not server_url:
+ raise ValueError("LightRAG server URL is required.")
+
+ self.config = self._load_config()
+ knowledge_bases = self.config.setdefault("knowledge_bases", {})
+ if name in knowledge_bases:
+ raise ValueError(f"A knowledge base named '{name}' already exists.")
+
+ now = datetime.now().isoformat()
+ entry: dict[str, Any] = {
+ "path": name,
+ "type": LIGHTRAG_SERVER_KB_TYPE,
+ "rag_provider": LIGHTRAG_SERVER_PROVIDER,
+ "server_url": server_url,
+ "api_key": (api_key or "").strip(),
+ "description": description or f"LightRAG server: {name}",
+ "status": "ready",
+ "needs_reindex": False,
+ "created_at": now,
+ "updated_at": now,
+ }
+ search_mode = (search_mode or "").strip().lower()
+ if search_mode:
+ entry["search_mode"] = search_mode
+ knowledge_bases[name] = entry
+ self._save_config()
+ return entry
+
def get_knowledge_base_path(self, name: str | None = None) -> Path:
"""Get path to a knowledge base.
@@ -977,6 +1030,9 @@ class KnowledgeBaseManager:
"type": kb_config.get("type"),
"vault_path": kb_config.get("vault_path"),
"external_path": kb_config.get("external_path"),
+ # LightRAG server pointer (the URL is safe to surface; the API
+ # key deliberately is not).
+ "server_url": kb_config.get("server_url"),
# Subagent connection fields (None for non-subagent KBs).
"agent_kind": kb_config.get("agent_kind"),
"cwd": kb_config.get("cwd"),
@@ -1105,6 +1161,10 @@ class KnowledgeBaseManager:
metadata["external_path"] = kb_config.get("external_path")
if kb_config.get("agent_kind"):
metadata["agent_kind"] = kb_config.get("agent_kind")
+ # The server URL is shown read-only in the UI; the API key never leaves
+ # the backend, so it is deliberately not surfaced here.
+ if kb_config.get("server_url"):
+ metadata["server_url"] = kb_config.get("server_url")
metadata.update(self._embedding_fields(kb_config))
diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.py
index 555aac201..929251fb6 100644
--- a/deeptutor/services/config/runtime_settings.py
+++ b/deeptutor/services/config/runtime_settings.py
@@ -75,14 +75,18 @@ DOCUMENT_PARSING_ENGINE_TEXT_ONLY = "text_only"
DOCUMENT_PARSING_ENGINE_MINERU = "mineru"
DOCUMENT_PARSING_ENGINE_DOCLING = "docling"
DOCUMENT_PARSING_ENGINE_MARKITDOWN = "markitdown"
+DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM = "pymupdf4llm"
_DOCUMENT_PARSING_ENGINES = frozenset(
{
DOCUMENT_PARSING_ENGINE_TEXT_ONLY,
DOCUMENT_PARSING_ENGINE_MINERU,
DOCUMENT_PARSING_ENGINE_DOCLING,
DOCUMENT_PARSING_ENGINE_MARKITDOWN,
+ DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM,
}
)
+# Image formats PyMuPDF4LLM can write extracted page images as.
+_PYMUPDF4LLM_IMAGE_FORMATS = frozenset({"png", "jpg", "jpeg", "webp"})
# Fresh installs default to the built-in text extractor so parsing works out of
# the box without optional parser packages or model weights.
# Migrated v1 installs keep MinerU (see ``_normalize_document_parsing``).
@@ -129,6 +133,16 @@ _DEFAULT_MARKITDOWN_ENGINE: dict[str, Any] = {
"enable_llm_image_description": False,
}
+# PyMuPDF4LLM engine slice. Pure-Python on top of PyMuPDF — no model downloads,
+# no CUDA, runs on low-end / GPU-less machines. Unlike text-only/markitdown it
+# can also extract embedded images and rendered vector graphics into the parse's
+# images/ dir. ``image_dpi`` is the render resolution for those images.
+_DEFAULT_PYMUPDF4LLM_ENGINE: dict[str, Any] = {
+ "write_images": True,
+ "image_format": "png",
+ "image_dpi": 150,
+}
+
# Built-in text-only engine slice. It deliberately has no knobs: it reuses
# DeepTutor's legacy text extractors for PDF / Office / text-like files.
_DEFAULT_TEXT_ONLY_ENGINE: dict[str, Any] = {}
@@ -145,6 +159,7 @@ DEFAULT_DOCUMENT_PARSING_SETTINGS: dict[str, Any] = {
DOCUMENT_PARSING_ENGINE_MINERU: _DEFAULT_MINERU_ENGINE,
DOCUMENT_PARSING_ENGINE_DOCLING: _DEFAULT_DOCLING_ENGINE,
DOCUMENT_PARSING_ENGINE_MARKITDOWN: _DEFAULT_MARKITDOWN_ENGINE,
+ DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM: _DEFAULT_PYMUPDF4LLM_ENGINE,
},
}
@@ -764,6 +779,9 @@ class RuntimeSettingsService:
DOCUMENT_PARSING_ENGINE_MARKITDOWN: self._normalize_markitdown_engine(
engines_in.get(DOCUMENT_PARSING_ENGINE_MARKITDOWN) or {}
),
+ DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM: self._normalize_pymupdf4llm_engine(
+ engines_in.get(DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM) or {}
+ ),
}
engine = _string(settings.get("engine")).lower().replace("-", "_").replace(" ", "_")
@@ -819,6 +837,16 @@ class RuntimeSettingsService:
),
}
+ def _normalize_pymupdf4llm_engine(self, settings: dict[str, Any]) -> dict[str, Any]:
+ image_format = _string(settings.get("image_format")).lower() or "png"
+ if image_format not in _PYMUPDF4LLM_IMAGE_FORMATS:
+ image_format = "png"
+ return {
+ "write_images": _coerce_bool(settings.get("write_images"), True),
+ "image_format": image_format,
+ "image_dpi": _coerce_clamped_int(settings.get("image_dpi"), 150, 72, 600),
+ }
+
def _normalize_text_only_engine(self, _settings: dict[str, Any]) -> dict[str, Any]:
return {}
@@ -942,6 +970,7 @@ __all__ = [
"DOCUMENT_PARSING_ENGINE_DOCLING",
"DOCUMENT_PARSING_ENGINE_MARKITDOWN",
"DOCUMENT_PARSING_ENGINE_MINERU",
+ "DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM",
"DOCUMENT_PARSING_ENGINE_TEXT_ONLY",
"MINERU_MODE_CLOUD",
"MINERU_MODE_LOCAL",
diff --git a/deeptutor/services/parsing/engines/_install.py b/deeptutor/services/parsing/engines/_install.py
new file mode 100644
index 000000000..12dc365ea
--- /dev/null
+++ b/deeptutor/services/parsing/engines/_install.py
@@ -0,0 +1,268 @@
+"""One-click background jobs for optional parser engines.
+
+The Document Parsing settings page runs two kinds of background job without the
+user dropping to a shell:
+
+* **install** — ``pip install`` an engine's optional PyPI package.
+* **models** — download an engine's model weights (e.g. Docling's layout/table
+ models via ``docling-tools models download``).
+
+Both mirror the MinerU model-download job (``mineru/models.py``): a single
+background subprocess with a cursor-based line log the UI starts, polls, and
+cancels. Commands come from fixed allow-lists (pip specs / downloader argv),
+never user input, so the subprocess argv can't be injected. Package installs use
+the bare package specs (the same strings as the ``[parse-*]`` extras) so pip
+never re-resolves DeepTutor itself; after a successful install we invalidate the
+import caches so the engine reports available in the same process (no restart).
+"""
+
+from __future__ import annotations
+
+import importlib
+import logging
+import os
+from pathlib import Path
+import shutil
+import subprocess # nosec B404 - argv from fixed allow-lists, never user input
+import sys
+import threading
+import time
+from typing import Any, Callable, Optional
+
+from ._versions import package_version
+
+logger = logging.getLogger(__name__)
+
+# Engine id -> pip requirement specifiers. Mirrors the optional extras in
+# pyproject.toml. Engines absent here (text_only built-in, mineru external
+# CLI/API) have no one-click install.
+ENGINE_PIP_SPECS: dict[str, list[str]] = {
+ # Pin <1.0: the 1.x line pulls onnxruntime + downloads a layout model and
+ # drops image extraction — keep the lightweight, image-capable pre-1.0 line.
+ "pymupdf4llm": ["pymupdf4llm>=0.0.17,<1.0"],
+ "markitdown": ["markitdown[pdf,docx,pptx,xlsx]>=0.0.1a2"],
+ "docling": ["docling>=2.0.0"],
+}
+
+# Engine id -> console-script argv that downloads its model weights. The script
+# is resolved next to the server's python first (same env), then on PATH.
+ENGINE_MODEL_DOWNLOADERS: dict[str, list[str]] = {
+ "docling": ["docling-tools", "models", "download"],
+}
+
+# Buffered log lines kept in memory; older lines are dropped (the cursor
+# protocol keeps clients consistent across trims).
+_MAX_LINES = 2000
+_LINE_MIN_INTERVAL = 0.2
+
+
+def installable_engines() -> frozenset[str]:
+ """Engine ids that support one-click pip install."""
+ return frozenset(ENGINE_PIP_SPECS)
+
+
+def model_downloadable_engines() -> frozenset[str]:
+ """Engine ids that support one-click model-weight download."""
+ return frozenset(ENGINE_MODEL_DOWNLOADERS)
+
+
+def resolve_model_downloader(engine: str) -> Optional[list[str]]:
+ """Resolve the model-download argv for ``engine``.
+
+ Locates the console script next to the server's python first (same env so it
+ matches the installed engine), then falls back to PATH. Returns ``None`` if
+ the engine has no downloader or the script isn't found.
+ """
+ parts = ENGINE_MODEL_DOWNLOADERS.get(engine)
+ if not parts:
+ return None
+ name = parts[0]
+ sibling = Path(sys.executable).parent / name
+ if sibling.is_file() and os.access(sibling, os.X_OK):
+ return [str(sibling), *parts[1:]]
+ found = shutil.which(name)
+ if found:
+ return [found, *parts[1:]]
+ return None
+
+
+def _invalidate_import_caches() -> None:
+ """Make a freshly installed package importable in this process and bust the
+ cached "" version so readiness flips without a server restart."""
+ try:
+ importlib.invalidate_caches()
+ package_version.cache_clear()
+ except Exception: # noqa: BLE001 - best effort
+ logger.exception("Post-install cache invalidation failed")
+
+
+class BackgroundJobManager:
+ """At most one background subprocess (install or model download), with a
+ cursor-based line log.
+
+ States: ``idle`` → ``running`` → ``done`` / ``failed`` / ``cancelled``.
+ ``status(cursor)`` returns lines after ``cursor`` plus ``next_cursor`` so the
+ UI can poll incrementally; ``kind`` (``install`` | ``models``) and ``engine``
+ tell the UI which job/card the log belongs to.
+ """
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._state = "idle"
+ self._kind = ""
+ self._engine = ""
+ self._lines: list[str] = []
+ self._base = 0
+ self._message = ""
+ self._process: subprocess.Popen | None = None
+ self._cancel_requested = False
+
+ def start_install(self, *, engine: str, specs: list[str]) -> dict[str, Any]:
+ cmd = [sys.executable, "-m", "pip", "install", "--no-input", *specs]
+ return self._launch(
+ kind="install",
+ engine=engine,
+ cmd=cmd,
+ env={"PIP_DISABLE_PIP_VERSION_CHECK": "1"},
+ on_success=_invalidate_import_caches,
+ )
+
+ def start_model_download(self, *, engine: str, cmd: list[str]) -> dict[str, Any]:
+ return self._launch(kind="models", engine=engine, cmd=cmd)
+
+ def status(self, cursor: int = 0) -> dict[str, Any]:
+ with self._lock:
+ start = max(int(cursor) - self._base, 0)
+ return {
+ "state": self._state,
+ "kind": self._kind,
+ "engine": self._engine,
+ "lines": list(self._lines[start:]),
+ "next_cursor": self._base + len(self._lines),
+ "message": self._message,
+ }
+
+ def cancel(self) -> dict[str, Any]:
+ with self._lock:
+ process = self._process
+ running = self._state == "running"
+ if running:
+ self._cancel_requested = True
+ if not (running and process):
+ return {"ok": False, "message": "No job is running."}
+ if process.poll() is None:
+ try:
+ process.terminate()
+ except Exception as exc: # noqa: BLE001
+ return {"ok": False, "message": f"Failed to cancel: {exc}"}
+ return {"ok": True, "message": ""}
+
+ # ------------------------------------------------------------------
+
+ def _launch(
+ self,
+ *,
+ kind: str,
+ engine: str,
+ cmd: list[str],
+ env: Optional[dict[str, str]] = None,
+ on_success: Optional[Callable[[], None]] = None,
+ ) -> dict[str, Any]:
+ with self._lock:
+ if self._state == "running":
+ return {
+ "ok": False,
+ "message": f"A {self._kind or 'job'} is already running ({self._engine}).",
+ }
+ try:
+ process = subprocess.Popen( # nosec B603 - argv from fixed allow-lists
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ shell=False,
+ env={**os.environ, **(env or {})},
+ )
+ except Exception as exc: # noqa: BLE001
+ self._state = "failed"
+ self._kind = kind
+ self._engine = engine
+ self._message = f"Failed to launch: {exc}"
+ return {"ok": False, "message": self._message}
+ self._state = "running"
+ self._kind = kind
+ self._engine = engine
+ self._lines = []
+ self._base = 0
+ self._message = ""
+ self._process = process
+ self._cancel_requested = False
+ thread = threading.Thread(
+ target=self._pump, args=(process, kind, engine, on_success), daemon=True
+ )
+ thread.start()
+ logger.info("Parser %s job started (%s): %s", kind, engine, " ".join(cmd))
+ return {"ok": True, "message": ""}
+
+ def _pump(
+ self,
+ process: subprocess.Popen,
+ kind: str,
+ engine: str,
+ on_success: Optional[Callable[[], None]],
+ ) -> None:
+ last_emit = 0.0
+ try:
+ assert process.stdout is not None
+ for raw_line in process.stdout:
+ line = raw_line.strip()
+ if not line:
+ continue
+ now = time.monotonic()
+ if now - last_emit < _LINE_MIN_INTERVAL:
+ continue
+ last_emit = now
+ self._append(line[:300])
+ except Exception:
+ logger.exception("Background job output pump failed")
+ returncode = process.wait()
+ with self._lock:
+ if self._cancel_requested:
+ self._state = "cancelled"
+ self._message = "Cancelled."
+ elif returncode == 0:
+ self._state = "done"
+ self._message = "Finished."
+ else:
+ self._state = "failed"
+ self._message = f"Exited with code {returncode}."
+ self._process = None
+ if returncode == 0 and not self._cancel_requested and on_success is not None:
+ on_success()
+ logger.info("Parser %s job finished (%s): %s", kind, engine, self._state)
+
+ def _append(self, line: str) -> None:
+ with self._lock:
+ self._lines.append(line)
+ overflow = len(self._lines) - _MAX_LINES
+ if overflow > 0:
+ del self._lines[:overflow]
+ self._base += overflow
+
+
+_manager = BackgroundJobManager()
+
+
+def get_background_job_manager() -> BackgroundJobManager:
+ return _manager
+
+
+__all__ = [
+ "ENGINE_MODEL_DOWNLOADERS",
+ "ENGINE_PIP_SPECS",
+ "BackgroundJobManager",
+ "get_background_job_manager",
+ "installable_engines",
+ "model_downloadable_engines",
+ "resolve_model_downloader",
+]
diff --git a/deeptutor/services/parsing/engines/docling/engine.py b/deeptutor/services/parsing/engines/docling/engine.py
index 4ba8f5b0d..643cf5788 100644
--- a/deeptutor/services/parsing/engines/docling/engine.py
+++ b/deeptutor/services/parsing/engines/docling/engine.py
@@ -27,14 +27,32 @@ _SUPPORTED = frozenset(
_MODEL_DIR_HINTS = ("docling", "ds4sd")
+def _dir_nonempty(path: Path) -> bool:
+ try:
+ return path.is_dir() and any(path.iterdir())
+ except Exception:
+ return False
+
+
+def docling_models_dir() -> Path:
+ """Docling's default model cache, where ``docling-tools models download``
+ writes (honors the ``DOCLING_CACHE_DIR`` override; default ~/.cache/docling).
+
+ Resolved without importing docling (heavy) so the readiness probe stays
+ cheap — it mirrors docling's own ``settings.cache_dir / "models"``."""
+ cache = os.environ.get("DOCLING_CACHE_DIR")
+ base = Path(cache).expanduser() if cache else Path.home() / ".cache" / "docling"
+ return base / "models"
+
+
def _docling_models_ready() -> bool:
"""Best-effort, fail-closed check for downloaded Docling models."""
artifacts = os.environ.get("DOCLING_ARTIFACTS_PATH")
- if (
- artifacts
- and Path(artifacts).expanduser().is_dir()
- and any(Path(artifacts).expanduser().iterdir())
- ):
+ if artifacts and _dir_nonempty(Path(artifacts).expanduser()):
+ return True
+ # The location `docling-tools models download` populates (and that docling
+ # auto-loads from at parse time).
+ if _dir_nonempty(docling_models_dir()):
return True
hf_home = os.environ.get("HF_HOME")
hub = (
@@ -89,7 +107,7 @@ class DoclingParser:
ready=False,
reason="models_missing",
message=(
- "Docling models aren't downloaded. Enable “Allow local model "
+ "Docling models aren't downloaded. Enable “Allow automatic model "
"download” in Settings → Document Parsing (or pre-fetch with "
"`docling-tools models download`), or switch to text-only / markitdown."
),
diff --git a/deeptutor/services/parsing/engines/factory.py b/deeptutor/services/parsing/engines/factory.py
index 8817437a0..8f7bc6ffa 100644
--- a/deeptutor/services/parsing/engines/factory.py
+++ b/deeptutor/services/parsing/engines/factory.py
@@ -14,6 +14,7 @@ from deeptutor.services.config.runtime_settings import (
DOCUMENT_PARSING_ENGINE_DOCLING,
DOCUMENT_PARSING_ENGINE_MARKITDOWN,
DOCUMENT_PARSING_ENGINE_MINERU,
+ DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM,
DOCUMENT_PARSING_ENGINE_TEXT_ONLY,
)
@@ -45,12 +46,19 @@ def _markitdown_class():
return MarkItDownParser
+def _pymupdf4llm_class():
+ from .pymupdf4llm.engine import PyMuPDF4LLMParser
+
+ return PyMuPDF4LLMParser
+
+
# name -> zero-arg loader returning the engine class.
_ENGINE_LOADERS: Dict[str, Callable[[], Any]] = {
DOCUMENT_PARSING_ENGINE_TEXT_ONLY: _text_only_class,
DOCUMENT_PARSING_ENGINE_MINERU: _mineru_class,
DOCUMENT_PARSING_ENGINE_DOCLING: _docling_class,
DOCUMENT_PARSING_ENGINE_MARKITDOWN: _markitdown_class,
+ DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM: _pymupdf4llm_class,
}
KNOWN_ENGINES = frozenset(_ENGINE_LOADERS)
@@ -89,6 +97,15 @@ _ENGINE_META: Dict[str, Dict[str, Any]] = {
),
"needs_local_models": False,
},
+ DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM: {
+ "name": "PyMuPDF4LLM",
+ "description": (
+ "Lightweight, no model downloads or CUDA — runs on low-end / GPU-less "
+ "machines. PDF/e-book → Markdown and can extract images. PDF and "
+ "e-book formats only."
+ ),
+ "needs_local_models": False,
+ },
}
diff --git a/deeptutor/services/parsing/engines/pymupdf4llm/__init__.py b/deeptutor/services/parsing/engines/pymupdf4llm/__init__.py
new file mode 100644
index 000000000..e4d78a0a3
--- /dev/null
+++ b/deeptutor/services/parsing/engines/pymupdf4llm/__init__.py
@@ -0,0 +1,8 @@
+"""PyMuPDF4LLM engine — lightweight, pure-Python, image-capable.
+
+Converts PDF / e-book formats to Markdown via PyMuPDF (fitz). No model
+downloads and no CUDA, so it runs on low-end / GPU-less machines. Unlike the
+text-only and markitdown engines it can also extract embedded images and
+rendered vector graphics into the parse's ``images/`` dir. Produces ``markdown``
+only (no structured ``content_list``).
+"""
diff --git a/deeptutor/services/parsing/engines/pymupdf4llm/config.py b/deeptutor/services/parsing/engines/pymupdf4llm/config.py
new file mode 100644
index 000000000..b95728252
--- /dev/null
+++ b/deeptutor/services/parsing/engines/pymupdf4llm/config.py
@@ -0,0 +1,36 @@
+"""PyMuPDF4LLM engine config (read-side adapter over the v2 settings slice)."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from deeptutor.services.config.runtime_settings import (
+ DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM,
+ load_document_parsing_settings,
+)
+
+
+@dataclass(frozen=True)
+class PyMuPDF4LLMConfig:
+ # Extract embedded images + rendered vector graphics into the images/ dir.
+ write_images: bool = True
+ # Output format for extracted images ("png" | "jpg" | "jpeg" | "webp").
+ image_format: str = "png"
+ # Render resolution (DPI) for extracted images.
+ image_dpi: int = 150
+
+
+def resolve_pymupdf4llm_config() -> PyMuPDF4LLMConfig:
+ slice_ = (
+ load_document_parsing_settings()
+ .get("engines", {})
+ .get(DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM, {})
+ )
+ return PyMuPDF4LLMConfig(
+ write_images=bool(slice_.get("write_images", True)),
+ image_format=str(slice_.get("image_format") or "png"),
+ image_dpi=int(slice_.get("image_dpi") or 150),
+ )
+
+
+__all__ = ["PyMuPDF4LLMConfig", "resolve_pymupdf4llm_config"]
diff --git a/deeptutor/services/parsing/engines/pymupdf4llm/engine.py b/deeptutor/services/parsing/engines/pymupdf4llm/engine.py
new file mode 100644
index 000000000..d08eb9214
--- /dev/null
+++ b/deeptutor/services/parsing/engines/pymupdf4llm/engine.py
@@ -0,0 +1,155 @@
+"""PyMuPDF4LLM engine adapter implementing the ``Parser`` protocol.
+
+A lightweight, pure-Python PDF/e-book → Markdown engine built on PyMuPDF (fitz):
+no CUDA, no model weights, suited to low-end / GPU-less machines. Unlike the
+text-only and markitdown engines it can also extract embedded images and
+rendered vector graphics, writing them into the parse's ``images/`` dir and
+rewriting the Markdown links to a portable ``images/<name>`` form (matching the
+MinerU/Docling asset convention the cache loader expects).
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import os
+from pathlib import Path
+import re
+from typing import Callable, Optional
+
+from ...base import ReadinessReport
+from ...signature import ParserSignature
+from ...types import ParserError
+from .._versions import package_version
+from .config import PyMuPDF4LLMConfig, resolve_pymupdf4llm_config
+
+# Document types PyMuPDF (fitz) opens and ``to_markdown`` handles. Kept to the
+# native document/e-book formats; bare image files go to other engines.
+_SUPPORTED = frozenset({".pdf", ".epub", ".xps", ".mobi", ".fb2", ".cbz"})
+
+# Markdown image links emitted by pymupdf4llm. We rewrite any link that points
+# at a file we actually extracted to a relative ``images/<name>`` so the cached
+# markdown stays valid no matter where the cache dir is moved to.
+_IMAGE_LINK_RE = re.compile(r"!\[([^\]]*)\]\(([^)]+)\)")
+
+
+class PyMuPDF4LLMParser:
+ """PDF/e-book → Markdown via pymupdf4llm (no models, optional image extraction)."""
+
+ name = "pymupdf4llm"
+ needs_local_models = False
+
+ @classmethod
+ def is_available(cls) -> bool:
+ return importlib.util.find_spec("pymupdf4llm") is not None
+
+ def resolve_config(self) -> PyMuPDF4LLMConfig:
+ return resolve_pymupdf4llm_config()
+
+ def supported_formats(self) -> frozenset[str]:
+ return _SUPPORTED
+
+ def signature(self, config: PyMuPDF4LLMConfig) -> ParserSignature:
+ return ParserSignature.build(
+ "pymupdf4llm",
+ package_version("pymupdf4llm"),
+ {
+ "write_images": config.write_images,
+ "image_format": config.image_format,
+ "image_dpi": config.image_dpi,
+ },
+ )
+
+ def is_ready(self, config: PyMuPDF4LLMConfig) -> ReadinessReport:
+ if not self.is_available():
+ return ReadinessReport(
+ ready=False,
+ reason="not_configured",
+ message="pymupdf4llm isn't installed (pip install deeptutor[parse-pymupdf4llm]).",
+ )
+ return ReadinessReport(ready=True)
+
+ def parse(
+ self,
+ source_path: Path,
+ workdir: Path,
+ *,
+ config: PyMuPDF4LLMConfig,
+ on_output: Optional[Callable[[str], None]] = None,
+ ) -> None:
+ to_markdown = self._resolve_to_markdown()
+
+ source_path = Path(source_path)
+ workdir = Path(workdir)
+ if on_output:
+ on_output(f"Converting {source_path.name} via PyMuPDF4LLM…")
+
+ images_dir = workdir / "images"
+ kwargs: dict[str, object] = {"show_progress": False}
+ if config.write_images:
+ images_dir.mkdir(parents=True, exist_ok=True)
+ kwargs.update(
+ write_images=True,
+ image_path=str(images_dir),
+ image_format=config.image_format,
+ dpi=config.image_dpi,
+ )
+
+ try:
+ markdown = to_markdown(str(source_path), **kwargs)
+ except Exception as exc: # noqa: BLE001 - surface as a parser error
+ raise ParserError(
+ f"PyMuPDF4LLM failed to convert {source_path.name}: {exc}"
+ )
+
+ if config.write_images:
+ markdown = self._portable_image_links(str(markdown), images_dir)
+ # Drop the images dir if nothing was actually extracted, so the
+ # cache loader doesn't report an empty asset_dir.
+ if images_dir.is_dir() and not any(images_dir.iterdir()):
+ images_dir.rmdir()
+
+ (workdir / f"{source_path.stem}.md").write_text(str(markdown), encoding="utf-8")
+
+ @staticmethod
+ def _resolve_to_markdown() -> Callable[..., object]:
+ """Return the classic pure-PyMuPDF Markdown converter.
+
+ pymupdf4llm 1.x defaults to an onnxruntime layout-AI path that downloads
+ a model on first use and (per its own docs) does NOT support image
+ extraction. We always bind the lightweight ``helpers.pymupdf_rag``
+ converter — the only path that extracts images and needs no model — so
+ the engine stays Pi-friendly regardless of the installed version. (Our
+ extra pins ``<1.0`` so onnxruntime is never even pulled.)
+ """
+ try:
+ from pymupdf4llm.helpers.pymupdf_rag import to_markdown
+
+ return to_markdown
+ except Exception: # noqa: BLE001 - fall back to the public entry point
+ import pymupdf4llm
+
+ return pymupdf4llm.to_markdown
+
+ @staticmethod
+ def _portable_image_links(markdown: str, images_dir: Path) -> str:
+ """Rewrite links pointing at extracted files to a relative ``images/<name>``.
+
+ pymupdf4llm embeds the ``image_path`` prefix (often absolute) in each
+ link; normalizing by basename is version-agnostic and keeps the cached
+ markdown portable.
+ """
+ names = {p.name for p in images_dir.iterdir()} if images_dir.is_dir() else set()
+ if not names:
+ return markdown
+
+ def _repl(match: re.Match[str]) -> str:
+ alt, target = match.group(1), match.group(2)
+ base = os.path.basename(target.replace("\\", "/"))
+ if base in names:
+ return f"![{alt}](images/{base})"
+ return match.group(0)
+
+ return _IMAGE_LINK_RE.sub(_repl, markdown)
+
+
+__all__ = ["PyMuPDF4LLMParser"]
diff --git a/deeptutor/services/rag/factory.py b/deeptutor/services/rag/factory.py
index 30bb887f2..c0897ac30 100644
--- a/deeptutor/services/rag/factory.py
+++ b/deeptutor/services/rag/factory.py
@@ -11,6 +11,9 @@ today:
* ``lightrag`` — graph + vector retrieval (HKUDS/LightRAG, multimodal
via RAG-Anything); optional dependency,
``pip install 'deeptutor[rag-lightrag]'``.
+* ``lightrag-server`` — retrieval offloaded to an external, standalone
+ LightRAG server the user runs. No local index: each
+ KB is a connection pointer queried over HTTP.
A KB is bound to one provider at creation time; later adds and retrieval always
go through that same pipeline (enforced upstream in the knowledge router).
@@ -25,11 +28,18 @@ DEFAULT_PROVIDER = "llamaindex"
PAGEINDEX_PROVIDER = "pageindex"
GRAPHRAG_PROVIDER = "graphrag"
LIGHTRAG_PROVIDER = "lightrag"
+LIGHTRAG_SERVER_PROVIDER = "lightrag-server"
# Providers the factory can instantiate. Unknown / legacy strings fall back to
# the default with a re-index hint upstream.
KNOWN_PROVIDERS = frozenset(
- {DEFAULT_PROVIDER, PAGEINDEX_PROVIDER, GRAPHRAG_PROVIDER, LIGHTRAG_PROVIDER}
+ {
+ DEFAULT_PROVIDER,
+ PAGEINDEX_PROVIDER,
+ GRAPHRAG_PROVIDER,
+ LIGHTRAG_PROVIDER,
+ LIGHTRAG_SERVER_PROVIDER,
+ }
)
# Cached pipeline instances keyed by (kb_base_dir, provider).
@@ -69,6 +79,7 @@ def version_matches_provider(entry: dict[str, Any], provider: Optional[str]) ->
PAGEINDEX_PROVIDER,
GRAPHRAG_PROVIDER,
LIGHTRAG_PROVIDER,
+ LIGHTRAG_SERVER_PROVIDER,
}
return entry_provider == resolved or signature == resolved
@@ -122,6 +133,13 @@ def _build_pipeline(provider: str, kb_base_dir: Optional[str], **kwargs: Any):
kwargs.setdefault("kb_base_dir", kb_base_dir)
return LightRagPipeline(**kwargs)
+ if provider == LIGHTRAG_SERVER_PROVIDER:
+ from .pipelines.lightrag_server.pipeline import LightRagServerPipeline
+
+ if kb_base_dir is not None:
+ kwargs.setdefault("kb_base_dir", kb_base_dir)
+ return LightRagServerPipeline(**kwargs)
+
from .pipelines.llamaindex.pipeline import LlamaIndexPipeline
if kb_base_dir is not None:
@@ -175,6 +193,14 @@ def list_pipelines() -> List[Dict[str, Any]]:
except Exception:
lightrag_ready, lightrag_modes, lightrag_default_mode = False, [], ""
+ try:
+ from .pipelines.lightrag_server import config as lightrag_server_config
+
+ lightrag_server_modes = list(lightrag_server_config.SUPPORTED_MODES)
+ lightrag_server_default_mode = lightrag_server_config.DEFAULT_MODE
+ except Exception:
+ lightrag_server_modes, lightrag_server_default_mode = [], ""
+
return [
{
"id": DEFAULT_PROVIDER,
@@ -208,6 +234,17 @@ def list_pipelines() -> List[Dict[str, Any]]:
"modes": lightrag_modes,
"default_mode": lightrag_default_mode,
},
+ {
+ "id": LIGHTRAG_SERVER_PROVIDER,
+ "name": "LightRAG Server",
+ "description": "Retrieval offloaded to an external, standalone LightRAG server you run. No local index — connect a KB to its URL and query it over HTTP (naive/local/global/hybrid/mix).",
+ # Always available: it's a thin HTTP client with no install or global
+ # credential. The endpoint is configured per-KB at connect time.
+ "configured": True,
+ "requires_api_key": False,
+ "modes": lightrag_server_modes,
+ "default_mode": lightrag_server_default_mode,
+ },
]
@@ -216,6 +253,7 @@ __all__ = [
"PAGEINDEX_PROVIDER",
"GRAPHRAG_PROVIDER",
"LIGHTRAG_PROVIDER",
+ "LIGHTRAG_SERVER_PROVIDER",
"KNOWN_PROVIDERS",
"get_pipeline",
"has_ready_provider_index",
diff --git a/deeptutor/services/rag/pipelines/lightrag_server/__init__.py b/deeptutor/services/rag/pipelines/lightrag_server/__init__.py
new file mode 100644
index 000000000..b36690e1b
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/lightrag_server/__init__.py
@@ -0,0 +1,15 @@
+"""Retrieval-only RAG pipeline backed by an external LightRAG server.
+
+A KB bound to the ``lightrag-server`` provider is a connection pointer to a
+standalone LightRAG server the user runs and indexed themselves. DeepTutor never
+indexes or stores anything locally: retrieval is offloaded to the server's
+``/query`` endpoint (context only — DeepTutor's chat LLM still writes the
+answer), and the endpoint is configured per-KB. See ``client`` for the wire and
+``probe`` for the connect-time health check.
+"""
+
+from __future__ import annotations
+
+from .pipeline import LightRagServerPipeline
+
+__all__ = ["LightRagServerPipeline"]
diff --git a/deeptutor/services/rag/pipelines/lightrag_server/client.py b/deeptutor/services/rag/pipelines/lightrag_server/client.py
new file mode 100644
index 000000000..74ec1936e
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/lightrag_server/client.py
@@ -0,0 +1,149 @@
+"""Thin async HTTP client for an external LightRAG server's REST API.
+
+We talk to the documented endpoints directly (``httpx`` only) — the calls map
+1:1 onto our retrieval-only contract:
+
+* ``POST /query`` with ``only_need_context=True`` — return the grounded context
+ the server retrieved, WITHOUT its own generation. DeepTutor's chat loop keeps
+ ownership of the answer; the server is used purely as a retriever.
+* ``GET /auth-status`` — reachability + whether the server requires an API key
+ (whitelisted on the server, so it answers without credentials).
+* ``GET /documents/pipeline_status`` — an auth-gated, side-effect-free call used
+ only to validate that a configured API key is accepted.
+
+Mirrors :class:`PageIndexClient`: a fresh :class:`httpx.AsyncClient` per call so
+the object is safe to construct once and reuse, and an injectable ``transport``
+so tests can stub the wire without a live server.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Optional
+
+import httpx
+
+from .config import LightRagServerConfig
+
+logger = logging.getLogger(__name__)
+
+
+class LightRagServerAPIError(RuntimeError):
+ """Raised when the LightRAG server returns an error or unexpected payload."""
+
+
+class LightRagServerClient:
+ """Stateless wrapper over an external LightRAG server's REST API."""
+
+ def __init__(
+ self,
+ config: LightRagServerConfig,
+ *,
+ timeout: float = 60.0,
+ transport: Optional[httpx.AsyncBaseTransport] = None,
+ ) -> None:
+ self._config = config
+ self._timeout = timeout
+ self._transport = transport
+
+ def _open(self) -> httpx.AsyncClient:
+ headers = {"Accept": "application/json"}
+ if self._config.api_key:
+ # LightRAG server authenticates with an ``X-API-Key`` header
+ # (its ``LIGHTRAG_API_KEY``); absent when the server runs open.
+ headers["X-API-Key"] = self._config.api_key
+ return httpx.AsyncClient(
+ base_url=self._config.base_url,
+ headers=headers,
+ timeout=self._timeout,
+ transport=self._transport,
+ )
+
+ @staticmethod
+ def _json(resp: httpx.Response) -> dict[str, Any]:
+ if resp.status_code >= 400:
+ raise LightRagServerAPIError(
+ f"LightRAG server returned {resp.status_code}: {resp.text[:300]}"
+ )
+ try:
+ data = resp.json()
+ except Exception as exc: # pragma: no cover - defensive
+ raise LightRagServerAPIError(
+ f"LightRAG server returned a non-JSON response: {exc}"
+ ) from exc
+ if not isinstance(data, dict):
+ raise LightRagServerAPIError(f"LightRAG server returned unexpected payload: {data!r}")
+ return data
+
+ # ----- retrieval ------------------------------------------------------
+
+ async def query_context(self, query: str, mode: str) -> dict[str, Any]:
+ """Retrieve grounded context for ``query`` without server-side generation.
+
+ Returns ``{"content": <context string>, "sources": [...]}``. ``sources``
+ are derived from the server's ``references`` list when present (one entry
+ per cited source file); an older server that omits references yields an
+ empty list rather than an error.
+ """
+ async with self._open() as client:
+ resp = await client.post(
+ "/query",
+ json={"query": query, "mode": mode, "only_need_context": True},
+ )
+ data = self._json(resp)
+ content = str(data.get("response") or "")
+ sources = _sources_from_references(data.get("references"))
+ return {"content": content, "sources": sources}
+
+ # ----- probing --------------------------------------------------------
+
+ async def auth_status(self) -> dict[str, Any]:
+ """Fetch ``/auth-status`` (no credentials) to probe reachability.
+
+ The presence of LightRAG-specific keys (``auth_configured`` /
+ ``core_version``) doubles as a "this really is a LightRAG server" signal.
+ """
+ async with self._open() as client:
+ resp = await client.get("/auth-status")
+ return self._json(resp)
+
+ async def verify_key(self) -> bool:
+ """Return whether the configured API key is accepted by the server.
+
+ Hits the auth-gated, read-only ``/documents/pipeline_status``: a 2xx
+ means the key (or open access) is valid; 401/403 means it was rejected.
+ Any other transport error propagates to the caller.
+ """
+ async with self._open() as client:
+ resp = await client.get("/documents/pipeline_status")
+ if resp.status_code in (401, 403):
+ return False
+ if resp.status_code >= 400:
+ raise LightRagServerAPIError(
+ f"LightRAG server returned {resp.status_code}: {resp.text[:300]}"
+ )
+ return True
+
+
+def _sources_from_references(references: Any) -> list[dict[str, Any]]:
+ """Map a LightRAG ``references`` list into DeepTutor's ``sources`` shape."""
+ if not isinstance(references, list):
+ return []
+ sources: list[dict[str, Any]] = []
+ for ref in references:
+ if not isinstance(ref, dict):
+ continue
+ file_path = str(ref.get("file_path") or "").strip()
+ ref_id = str(ref.get("reference_id") or "").strip()
+ if not file_path and not ref_id:
+ continue
+ source: dict[str, Any] = {}
+ if ref_id:
+ source["id"] = ref_id
+ if file_path:
+ source["file_path"] = file_path
+ sources.append(source)
+ return sources
+
+
+__all__ = ["LightRagServerClient", "LightRagServerAPIError"]
diff --git a/deeptutor/services/rag/pipelines/lightrag_server/config.py b/deeptutor/services/rag/pipelines/lightrag_server/config.py
new file mode 100644
index 000000000..e8fa7fe7a
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/lightrag_server/config.py
@@ -0,0 +1,68 @@
+"""Per-KB connection config and retrieval modes for the LightRAG Server engine.
+
+Unlike the hosted PageIndex engine (one global account key shared by every KB),
+each LightRAG Server KB points at its OWN server instance — a standalone LightRAG
+server's ``--workspace`` is fixed at startup, so one server instance = one
+workspace = one knowledge base. The endpoint (base URL + optional API key) is
+therefore stored per-KB in ``kb_config.json`` (the same place the KB's
+``search_mode`` lives), exactly like a ``linked`` KB stores its ``external_path``.
+
+This module is the single seam that reads that binding into a typed config; it
+holds no global state and imports no HTTP client (the client lives in
+``client.py``).
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+# LightRAG's ``/query`` retrieval modes. ``bypass`` is intentionally omitted: it
+# skips retrieval entirely, which is meaningless for a knowledge base. ``mix``
+# (knowledge-graph + vector + chunks) is the server's own default and the safest
+# general choice, matching the shared per-KB ``search_mode`` default.
+SUPPORTED_MODES = ("naive", "local", "global", "hybrid", "mix")
+DEFAULT_MODE = "mix"
+
+
+class LightRagServerNotConfiguredError(RuntimeError):
+ """Raised when a KB has no LightRAG server URL bound to it."""
+
+
+@dataclass(frozen=True)
+class LightRagServerConfig:
+ """A KB's resolved connection to an external LightRAG server."""
+
+ base_url: str
+ api_key: str
+
+
+def normalize_base_url(url: str | None) -> str:
+ """Trim and drop any trailing slash so endpoint paths join cleanly."""
+ return (url or "").strip().rstrip("/")
+
+
+def config_from_entry(entry: dict[str, Any]) -> LightRagServerConfig:
+ """Build a :class:`LightRagServerConfig` from a ``kb_config.json`` KB entry.
+
+ Raises :class:`LightRagServerNotConfiguredError` when no ``server_url`` is
+ present, so retrieval fails with a clear message instead of an opaque
+ connection error.
+ """
+ base_url = normalize_base_url(entry.get("server_url"))
+ if not base_url:
+ raise LightRagServerNotConfiguredError(
+ "This knowledge base is not connected to a LightRAG server "
+ "(no server URL configured). Re-create it with a valid server URL."
+ )
+ return LightRagServerConfig(base_url=base_url, api_key=str(entry.get("api_key") or "").strip())
+
+
+__all__ = [
+ "SUPPORTED_MODES",
+ "DEFAULT_MODE",
+ "LightRagServerNotConfiguredError",
+ "LightRagServerConfig",
+ "normalize_base_url",
+ "config_from_entry",
+]
diff --git a/deeptutor/services/rag/pipelines/lightrag_server/pipeline.py b/deeptutor/services/rag/pipelines/lightrag_server/pipeline.py
new file mode 100644
index 000000000..8e636f664
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/lightrag_server/pipeline.py
@@ -0,0 +1,120 @@
+"""Retrieval-only pipeline backed by an external LightRAG server.
+
+Implements the same contract as the other pipelines (see ``..base.RAGPipeline``)
+but owns no index: a ``lightrag-server`` KB is a connection pointer (``type:
+lightrag_server`` in ``kb_config.json``) to a standalone LightRAG server the user
+runs and indexed themselves. Only :meth:`search` does real work — it reads the
+KB's endpoint, asks the server for grounded context (no server-side generation),
+and shapes the result for the ``rag`` tool. Indexing is offloaded entirely to the
+server, so :meth:`initialize` / :meth:`add_documents` are not part of this
+engine's job and fail with a clear message; :meth:`delete` is a no-op because
+deleting the KB only drops DeepTutor's pointer (handled by the manager) and must
+never touch the user's server.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Dict, List, Optional
+
+from deeptutor.runtime.home import get_runtime_data_root
+from deeptutor.services.rag.provider_binding import load_kb_config_entry
+
+from ..modes import resolve_kb_mode
+from .config import (
+ DEFAULT_MODE,
+ SUPPORTED_MODES,
+ LightRagServerNotConfiguredError,
+ config_from_entry,
+)
+
+logger = logging.getLogger(__name__)
+
+PROVIDER = "lightrag-server"
+DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases")
+
+
+class LightRagServerPipeline:
+ """Query an external LightRAG server on behalf of a connected KB."""
+
+ def __init__(self, kb_base_dir: Optional[str] = None, *, client_factory=None, **_: Any) -> None:
+ self.logger = logging.getLogger(__name__)
+ self.kb_base_dir = kb_base_dir or DEFAULT_KB_BASE_DIR
+ # Injection seam for tests: (config) -> client. None uses the real client.
+ self._client_factory = client_factory
+
+ # ----- helpers --------------------------------------------------------
+
+ def _client(self, config):
+ if self._client_factory is not None:
+ return self._client_factory(config)
+ from .client import LightRagServerClient
+
+ return LightRagServerClient(config)
+
+ def _resolve_mode(self, kb_name: str, kwargs: dict[str, Any]) -> str:
+ return resolve_kb_mode(
+ self.kb_base_dir,
+ kb_name,
+ PROVIDER,
+ explicit=kwargs.get("mode"),
+ supported=SUPPORTED_MODES,
+ default=DEFAULT_MODE,
+ )
+
+ # ----- retrieval ------------------------------------------------------
+
+ async def search(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:
+ try:
+ config = config_from_entry(load_kb_config_entry(self.kb_base_dir, kb_name))
+ except LightRagServerNotConfiguredError as exc:
+ return self._error_result(query, exc, error_type="not_configured")
+
+ mode = self._resolve_mode(kb_name, kwargs)
+ try:
+ result = await self._client(config).query_context(query, mode)
+ except Exception as exc:
+ self.logger.error("LightRAG server search failed for '%s': %s", kb_name, exc)
+ return self._error_result(query, exc, error_type="retrieval_error")
+
+ content = result.get("content") or ""
+ return {
+ "query": query,
+ "answer": content,
+ "content": content,
+ "sources": result.get("sources") or [],
+ "provider": PROVIDER,
+ "mode": mode,
+ }
+
+ def _error_result(self, query: str, exc: Exception, *, error_type: str) -> Dict[str, Any]:
+ return {
+ "query": query,
+ "answer": str(exc),
+ "content": "",
+ "sources": [],
+ "provider": PROVIDER,
+ "error_type": error_type,
+ }
+
+ # ----- indexing (not applicable — owned by the external server) -------
+
+ async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
+ raise RuntimeError(
+ "LightRAG Server knowledge bases are indexed on the external server; "
+ "DeepTutor does not build or store their index. Add documents on the "
+ "LightRAG server directly."
+ )
+
+ async def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
+ return await self.initialize(kb_name, file_paths, **kwargs)
+
+ # ----- lifecycle ------------------------------------------------------
+
+ async def delete(self, kb_name: str, **kwargs) -> bool:
+ # The KB is only a pointer; the manager removes its config entry. Never
+ # touch the user's server. Nothing local to clean up here.
+ return True
+
+
+__all__ = ["LightRagServerPipeline", "PROVIDER"]
diff --git a/deeptutor/services/rag/pipelines/lightrag_server/probe.py b/deeptutor/services/rag/pipelines/lightrag_server/probe.py
new file mode 100644
index 000000000..88678b604
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/lightrag_server/probe.py
@@ -0,0 +1,110 @@
+"""Probe an external LightRAG server before connecting a KB to it.
+
+Connecting is cheap and reversible, but a typo'd URL or a wrong API key should
+fail loudly at connect time rather than silently at every later query. This
+module answers, in one round-trip pair, the questions the UI needs to confirm:
+
+1. **Reachable, and is it actually a LightRAG server?** ``GET /auth-status`` is
+ whitelisted on the server, so it answers without credentials; its LightRAG-
+ specific keys confirm we're talking to the right kind of server.
+2. **Does it require an API key, and is ours accepted?** When auth is enabled we
+ validate the key against the read-only ``GET /documents/pipeline_status``.
+
+Always returns a :class:`ServerProbe` (never raises); ``ok`` is the single
+boolean the caller gates on, with ``error`` explaining any failure.
+"""
+
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass
+from typing import Any, Optional
+
+from .client import LightRagServerClient
+from .config import LightRagServerConfig, normalize_base_url
+
+
+@dataclass
+class ServerProbe:
+ base_url: str
+ ok: bool = False
+ reachable: bool = False
+ auth_required: bool = False
+ auth_ok: bool = False
+ core_version: Optional[str] = None
+ api_version: Optional[str] = None
+ error: Optional[str] = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+async def probe_server(
+ server_url: str,
+ api_key: str = "",
+ *,
+ client_factory=None,
+) -> ServerProbe:
+ """Inspect ``server_url`` for a reachable, authorised LightRAG server.
+
+ ``client_factory`` (config → client) is an injection seam for tests; in
+ production it defaults to a real :class:`LightRagServerClient`.
+ """
+ base_url = normalize_base_url(server_url)
+ probe = ServerProbe(base_url=base_url)
+ if not base_url:
+ probe.error = "Server URL is required."
+ return probe
+ if not (base_url.startswith("http://") or base_url.startswith("https://")):
+ probe.error = "Server URL must start with http:// or https://."
+ return probe
+
+ config = LightRagServerConfig(base_url=base_url, api_key=(api_key or "").strip())
+ client = client_factory(config) if client_factory else LightRagServerClient(config)
+
+ try:
+ status = await client.auth_status()
+ except Exception as exc:
+ probe.error = f"Could not reach a LightRAG server at {base_url}: {exc}"
+ return probe
+
+ # ``auth_configured`` is LightRAG-specific; its absence means we reached
+ # something that isn't a LightRAG server.
+ if "auth_configured" not in status:
+ probe.error = f"{base_url} responded but does not look like a LightRAG server."
+ return probe
+
+ probe.reachable = True
+ probe.core_version = _opt_str(status.get("core_version"))
+ probe.api_version = _opt_str(status.get("api_version"))
+ probe.auth_required = bool(status.get("auth_configured"))
+
+ if not probe.auth_required:
+ # Open server — nothing to validate. A stray key is simply ignored.
+ probe.auth_ok = True
+ probe.ok = True
+ return probe
+
+ try:
+ probe.auth_ok = await client.verify_key()
+ except Exception as exc:
+ probe.error = f"Reached the server but could not validate the API key: {exc}"
+ return probe
+
+ if not probe.auth_ok:
+ probe.error = (
+ "This server requires an API key and the one provided was rejected."
+ if api_key
+ else "This server requires an API key. Provide one to connect."
+ )
+ return probe
+
+ probe.ok = True
+ return probe
+
+
+def _opt_str(value: Any) -> Optional[str]:
+ text = str(value).strip() if value is not None else ""
+ return text or None
+
+
+__all__ = ["ServerProbe", "probe_server"]
diff --git a/deeptutor/services/rag/pipelines/llamaindex/ingestion.py b/deeptutor/services/rag/pipelines/llamaindex/ingestion.py
index 3bcc1a2cf..56d6e0a8b 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/ingestion.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/ingestion.py
@@ -14,6 +14,8 @@ from llama_index.core.ingestion import IngestionPipeline
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.schema import BaseNode
+from . import vector_store
+
def build_ingestion_pipeline() -> IngestionPipeline:
"""Create the default DeepTutor ingestion pipeline.
@@ -80,9 +82,16 @@ def documents_to_nodes(documents: list[Any], *, show_progress: bool = True) -> l
def create_index_from_documents(
documents: list[Any], storage_dir: Path, *, show_progress: bool = True
) -> tuple[VectorStoreIndex, int]:
- """Create and persist a VectorStoreIndex from documents."""
+ """Create and persist a VectorStoreIndex from documents.
+
+ Uses a FAISS-backed store when available and all node embeddings share one
+ dimension; otherwise LlamaIndex's default SimpleVectorStore.
+ """
nodes = documents_to_nodes(documents, show_progress=show_progress)
- index = VectorStoreIndex(nodes=nodes, show_progress=show_progress)
+ storage_context = vector_store.storage_context_for_nodes(nodes)
+ index = VectorStoreIndex(
+ nodes=nodes, storage_context=storage_context, show_progress=show_progress
+ )
index.storage_context.persist(persist_dir=str(storage_dir))
return index, len(documents)
diff --git a/deeptutor/services/rag/pipelines/llamaindex/storage.py b/deeptutor/services/rag/pipelines/llamaindex/storage.py
index 74dc948b4..3d48758bc 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/storage.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/storage.py
@@ -2,14 +2,14 @@
from __future__ import annotations
+from collections import OrderedDict
from dataclasses import dataclass
import json
from pathlib import Path
import shutil
+import threading
from typing import Any
-from llama_index.core import StorageContext, load_index_from_storage
-
from deeptutor.services.embedding.validation import validate_embedding_batch
from deeptutor.services.rag.index_versioning import (
EmbeddingSignature,
@@ -18,7 +18,7 @@ from deeptutor.services.rag.index_versioning import (
resolve_storage_dir_for_write,
)
-from . import ingestion, retrievers
+from . import ingestion, retrievers, vector_store
@dataclass(frozen=True)
@@ -93,8 +93,7 @@ def create_index(documents: list[Any], storage_dir: Path, *, show_progress: bool
def insert_documents(existing_storage: Path, storage_dir: Path, documents: list[Any]) -> int:
- storage_context = StorageContext.from_defaults(persist_dir=str(existing_storage))
- index = load_index_from_storage(storage_context)
+ index = vector_store.load_index(existing_storage)
_validate_persisted_embeddings(index, existing_storage)
if hasattr(index, "insert_nodes"):
count = ingestion.insert_documents_into_index(index, documents, show_progress=True)
@@ -157,9 +156,16 @@ def _embedding_dict_from_payload(payload: Any) -> Any:
def _iter_file_embedding_dicts(storage_dir: Path):
- """Yield embedding dictionaries from persisted vector-store JSON files."""
+ """Yield embedding dictionaries from persisted SimpleVectorStore JSON files.
+
+ Binary FAISS indexes share the ``*vector_store.json`` filename but are not
+ JSON, so they are skipped (their vectors are validated at index build time).
+ """
for path in sorted(storage_dir.glob("*vector_store.json")):
try:
+ with open(path, "rb") as probe:
+ if probe.read(1)[:1] != b"{":
+ continue # binary FAISS index, not a JSON vector store
with open(path, encoding="utf-8") as handle:
payload = json.load(handle)
except Exception:
@@ -190,11 +196,63 @@ def validate_storage_embeddings(storage_dir: Path) -> None:
_validate_persisted_embeddings(None, storage_dir)
-def retrieve_nodes(storage_dir: Path, query: str, *, top_k: int = 5) -> list[Any]:
- storage_context = StorageContext.from_defaults(persist_dir=str(storage_dir))
- index = load_index_from_storage(storage_context)
+# Loaded indexes are cached per storage dir so repeated queries never re-read or
+# re-validate the (potentially large) persisted store. Entries are keyed by a
+# freshness token derived from the store files' mtimes, so a re-index or
+# incremental insert naturally invalidates the stale entry.
+_INDEX_CACHE: "OrderedDict[tuple[str, tuple[int, ...]], Any]" = OrderedDict()
+_INDEX_CACHE_LOCK = threading.Lock()
+_INDEX_CACHE_MAXSIZE = 8
+
+
+def _freshness_token(storage_dir: Path) -> tuple[int, ...]:
+ token: list[int] = []
+ for name in ("docstore.json", vector_store.DEFAULT_VECTOR_STORE_FILENAME):
+ try:
+ token.append((storage_dir / name).stat().st_mtime_ns)
+ except OSError:
+ token.append(0)
+ return tuple(token)
+
+
+def _load_validated_index(storage_dir: Path) -> Any:
+ """Load an index once and validate its embeddings (cache-miss path)."""
+ index = vector_store.load_index(storage_dir)
_validate_persisted_embeddings(index, storage_dir)
- retriever = retrievers.build_retriever(index, storage_dir, top_k=top_k)
+ return index
+
+
+def _cached_index(storage_dir: Path) -> Any:
+ key = (str(storage_dir.resolve()), _freshness_token(storage_dir))
+ with _INDEX_CACHE_LOCK:
+ cached = _INDEX_CACHE.get(key)
+ if cached is not None:
+ _INDEX_CACHE.move_to_end(key)
+ return cached
+
+ # Load outside the lock so a slow first load of one KB does not block other
+ # KBs' queries. A concurrent duplicate load is harmless (idempotent).
+ index = _load_validated_index(storage_dir)
+ with _INDEX_CACHE_LOCK:
+ # Drop any superseded entry for the same storage dir (older token).
+ for stale in [existing for existing in _INDEX_CACHE if existing[0] == key[0]]:
+ _INDEX_CACHE.pop(stale, None)
+ _INDEX_CACHE[key] = index
+ _INDEX_CACHE.move_to_end(key)
+ while len(_INDEX_CACHE) > _INDEX_CACHE_MAXSIZE:
+ _INDEX_CACHE.popitem(last=False)
+ return index
+
+
+def clear_index_cache() -> None:
+ """Drop all cached indexes (used by tests and after destructive edits)."""
+ with _INDEX_CACHE_LOCK:
+ _INDEX_CACHE.clear()
+
+
+def retrieve_nodes(storage_dir: Path, query: str, *, top_k: int = 5) -> list[Any]:
+ index = _cached_index(Path(storage_dir))
+ retriever = retrievers.build_retriever(index, Path(storage_dir), top_k=top_k)
return retriever.retrieve(query)
diff --git a/deeptutor/services/rag/pipelines/llamaindex/vector_store.py b/deeptutor/services/rag/pipelines/llamaindex/vector_store.py
new file mode 100644
index 000000000..a8e9bcdab
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/llamaindex/vector_store.py
@@ -0,0 +1,203 @@
+"""Vector-store backend selection for the LlamaIndex RAG pipeline.
+
+This module is the single seam between DeepTutor's LlamaIndex pipeline and the
+concrete vector store implementation. It exists so the rest of the pipeline
+(ingestion, storage, retrieval) never has to know *how* vectors are stored.
+
+Why it exists
+-------------
+LlamaIndex's built-in ``SimpleVectorStore`` keeps every embedding in a JSON
+document and performs a pure-Python, O(N) brute-force scan on each query. On a
+large knowledge base that is re-parsed and re-scanned per query, which pins a
+CPU core and makes retrieval take minutes (issue #552).
+
+This seam swaps in a FAISS index instead:
+
+* New (and re-indexed) knowledge bases are persisted as a binary FAISS index
+ (``IndexFlatIP``), loaded once and searched with vectorized BLAS.
+* Legacy ``SimpleVectorStore`` knowledge bases stay fully readable, so upgrading
+ never breaks an existing index. Re-indexing one rebuilds it as FAISS for the
+ full speed-up.
+
+FAISS is optional. When ``faiss`` / ``llama-index-vector-stores-faiss`` are not
+importable, every path falls back to ``SimpleVectorStore`` so retrieval keeps
+working (just without the speed-up).
+"""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import Any, Iterable, Optional
+
+from llama_index.core import StorageContext, load_index_from_storage
+from llama_index.core.vector_stores.simple import DEFAULT_VECTOR_STORE, NAMESPACE_SEP
+import numpy as np
+
+logger = logging.getLogger(__name__)
+
+BACKEND_FAISS = "faiss"
+BACKEND_SIMPLE = "simple"
+
+# The default vector store is always persisted under this filename, whether it
+# holds a SimpleVectorStore JSON document or a binary FAISS index. The first
+# byte disambiguates the two: "{" => JSON/simple, anything else => FAISS.
+DEFAULT_VECTOR_STORE_FILENAME = f"{DEFAULT_VECTOR_STORE}{NAMESPACE_SEP}vector_store.json"
+
+_COSINE_FAISS_CLS: Optional[type] = None
+
+
+def _faiss_modules() -> tuple[Any, Any]:
+ """Return ``(faiss, FaissVectorStore)`` or ``(None, None)`` when unavailable."""
+ try:
+ import faiss
+ from llama_index.vector_stores.faiss import FaissVectorStore
+ except Exception: # pragma: no cover - exercised only without faiss installed
+ return None, None
+ return faiss, FaissVectorStore
+
+
+def faiss_available() -> bool:
+ """True when both the FAISS library and its LlamaIndex integration import."""
+ faiss, faiss_store_cls = _faiss_modules()
+ return faiss is not None and faiss_store_cls is not None
+
+
+def _normalize(embedding: Any) -> list[float]:
+ """L2-normalize an embedding so inner product equals cosine similarity."""
+ vector = np.asarray(embedding, dtype="float32")
+ norm = float(np.linalg.norm(vector))
+ if norm > 0:
+ vector = vector / norm
+ return vector.tolist()
+
+
+def _cosine_faiss_cls() -> Optional[type]:
+ """Return a memoized FaissVectorStore subclass that ranks by cosine.
+
+ Stock ``FaissVectorStore`` normalizes neither on add nor on query, so an
+ ``IndexFlatIP`` would rank by raw dot product. Normalizing both sides makes
+ inner-product ranking identical to the cosine similarity SimpleVectorStore
+ used, preserving retrieval behaviour after the backend swap.
+ """
+ global _COSINE_FAISS_CLS
+ if _COSINE_FAISS_CLS is not None:
+ return _COSINE_FAISS_CLS
+
+ _, faiss_store_cls = _faiss_modules()
+ if faiss_store_cls is None:
+ return None
+
+ class _CosineFaissVectorStore(faiss_store_cls): # type: ignore[valid-type, misc]
+ """FAISS store that L2-normalizes vectors for cosine ranking."""
+
+ def add(self, nodes: list[Any], **kwargs: Any) -> list[str]:
+ for node in nodes:
+ node.embedding = _normalize(node.get_embedding())
+ return super().add(nodes, **kwargs)
+
+ def query(self, query: Any, **kwargs: Any) -> Any:
+ if getattr(query, "query_embedding", None) is not None:
+ query.query_embedding = _normalize(query.query_embedding)
+ return super().query(query, **kwargs)
+
+ _COSINE_FAISS_CLS = _CosineFaissVectorStore
+ return _COSINE_FAISS_CLS
+
+
+def _uniform_dimension(embeddings: Iterable[Any]) -> Optional[int]:
+ """Return the shared embedding dimension, or None if missing/ragged.
+
+ Mixed dimensions (e.g. text + multimodal image vectors) cannot live in a
+ single fixed-width FAISS index, so callers fall back to SimpleVectorStore.
+ """
+ dimension: Optional[int] = None
+ for embedding in embeddings:
+ if embedding is None:
+ return None
+ length = len(embedding)
+ if dimension is None:
+ dimension = length
+ elif length != dimension:
+ return None
+ return dimension if dimension and dimension > 0 else None
+
+
+def new_faiss_storage_context(dimension: int) -> Optional[StorageContext]:
+ """Return a StorageContext whose default store is a fresh cosine FAISS index.
+
+ Returns None when FAISS is unavailable or the dimension is invalid, so
+ callers fall back to the default SimpleVectorStore StorageContext.
+ """
+ faiss, _ = _faiss_modules()
+ cosine_cls = _cosine_faiss_cls()
+ if faiss is None or cosine_cls is None or dimension <= 0:
+ return None
+ store = cosine_cls(faiss_index=faiss.IndexFlatIP(dimension))
+ return StorageContext.from_defaults(vector_store=store)
+
+
+def storage_context_for_nodes(nodes: list[Any]) -> Optional[StorageContext]:
+ """Choose the write-time StorageContext for a set of embedded nodes.
+
+ Returns a FAISS-backed context when every node shares one embedding
+ dimension and FAISS is available; otherwise None (use the SimpleVectorStore
+ default). ``None`` keeps multimodal / mixed-dimension and faiss-less installs
+ on the original code path.
+ """
+ if not faiss_available():
+ return None
+ dimension = _uniform_dimension(getattr(node, "embedding", None) for node in nodes)
+ if dimension is None:
+ return None
+ return new_faiss_storage_context(dimension)
+
+
+def detect_backend(storage_dir: Path) -> str:
+ """Detect a persisted index's vector backend from its default store file."""
+ path = Path(storage_dir) / DEFAULT_VECTOR_STORE_FILENAME
+ try:
+ with open(path, "rb") as handle:
+ head = handle.read(1)
+ except OSError:
+ return BACKEND_SIMPLE
+ return BACKEND_SIMPLE if head[:1] == b"{" else BACKEND_FAISS
+
+
+def load_index(storage_dir: Path) -> Any:
+ """Load a persisted index for retrieval.
+
+ FAISS-persisted versions load their binary index directly. Legacy
+ SimpleVectorStore versions load unchanged and stay queryable; re-indexing
+ such a knowledge base rebuilds it as FAISS for the full speed-up.
+ """
+ storage_dir = Path(storage_dir)
+
+ if detect_backend(storage_dir) == BACKEND_FAISS:
+ cosine_cls = _cosine_faiss_cls()
+ if cosine_cls is None:
+ raise RuntimeError(
+ "This knowledge base was indexed with FAISS but the 'faiss-cpu' "
+ "package is not installed. Install it (pip install faiss-cpu) or "
+ "re-index the knowledge base to query it again."
+ )
+ vector_store = cosine_cls.from_persist_dir(str(storage_dir))
+ context = StorageContext.from_defaults(
+ persist_dir=str(storage_dir), vector_store=vector_store
+ )
+ return load_index_from_storage(context)
+
+ context = StorageContext.from_defaults(persist_dir=str(storage_dir))
+ return load_index_from_storage(context)
+
+
+__all__ = [
+ "BACKEND_FAISS",
+ "BACKEND_SIMPLE",
+ "DEFAULT_VECTOR_STORE_FILENAME",
+ "detect_backend",
+ "faiss_available",
+ "load_index",
+ "new_faiss_storage_context",
+ "storage_context_for_nodes",
+]
diff --git a/packaging/deeptutor-cli/pyproject.toml b/packaging/deeptutor-cli/pyproject.toml
index 25ca5a5db..a727c5a4b 100644
--- a/packaging/deeptutor-cli/pyproject.toml
+++ b/packaging/deeptutor-cli/pyproject.toml
@@ -32,6 +32,10 @@ dependencies = [
"oauth-cli-kit>=0.1.1",
"llama-index>=0.14.12",
"llama-index-retrievers-bm25>=0.7.1,<0.8.0",
+ # FAISS vector store: ANN retrieval replacing SimpleVectorStore brute force for
+ # large KBs (issue #552); imported lazily with SimpleVectorStore fallback.
+ "llama-index-vector-stores-faiss>=0.4.0,<1.0.0",
+ "faiss-cpu>=1.8.0,<2.0.0",
"PyMuPDF>=1.26.0",
"numpy>=1.24.0,<3.0.0",
"arxiv>=2.0.0",
diff --git a/pyproject.toml b/pyproject.toml
index 3c43fc494..1419c8503 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -38,6 +38,11 @@ dependencies = [
"oauth-cli-kit>=0.1.1",
"llama-index>=0.14.12",
"llama-index-retrievers-bm25>=0.7.1,<0.8.0",
+ # FAISS vector store: vectorized ANN retrieval that replaces SimpleVectorStore's
+ # brute-force per-query scan for large knowledge bases (issue #552). The
+ # pipeline imports it lazily and falls back to SimpleVectorStore if absent.
+ "llama-index-vector-stores-faiss>=0.4.0,<1.0.0",
+ "faiss-cpu>=1.8.0,<2.0.0",
"PyMuPDF>=1.26.0",
"numpy>=1.24.0,<3.0.0",
"arxiv>=2.0.0",
@@ -75,6 +80,11 @@ cli = [
# RAG (LlamaIndex)
"llama-index>=0.14.12",
"llama-index-retrievers-bm25>=0.7.1,<0.8.0",
+ # FAISS vector store: vectorized ANN retrieval that replaces SimpleVectorStore's
+ # brute-force per-query scan for large knowledge bases (issue #552). The
+ # pipeline imports it lazily and falls back to SimpleVectorStore if absent.
+ "llama-index-vector-stores-faiss>=0.4.0,<1.0.0",
+ "faiss-cpu>=1.8.0,<2.0.0",
"PyMuPDF>=1.26.0",
"numpy>=1.24.0,<3.0.0",
"arxiv>=2.0.0",
@@ -140,7 +150,17 @@ partners = [
# absent engine simply reports unavailable in Settings → Document Parsing.
parse-markitdown = ["markitdown[pdf,docx,pptx,xlsx]>=0.0.1a2"]
parse-docling = ["docling>=2.0.0"]
-parse = ["deeptutor[parse-markitdown]", "deeptutor[parse-docling]"]
+# PyMuPDF4LLM rides on PyMuPDF (already a core dep); the extra adds only the
+# thin Markdown layer, so it is the lightest image-capable engine. Pinned to the
+# pre-1.0 line on purpose: 1.x defaults to an onnxruntime layout-AI path that
+# pulls a heavy dep, downloads a model, and can't extract images — defeating the
+# "lightweight, runs on a Pi, extracts images" point of this engine.
+parse-pymupdf4llm = ["pymupdf4llm>=0.0.17,<1.0"]
+parse = [
+ "deeptutor[parse-markitdown]",
+ "deeptutor[parse-docling]",
+ "deeptutor[parse-pymupdf4llm]",
+]
# Legacy alias kept for one release: `pip install deeptutor[tutorbot]`.
tutorbot = ["deeptutor[partners]"]
diff --git a/requirements/cli.txt b/requirements/cli.txt
index 83cbef181..eb1636cd5 100644
--- a/requirements/cli.txt
+++ b/requirements/cli.txt
@@ -39,6 +39,10 @@ aiosqlite>=0.19.0
# --- RAG (LlamaIndex) ---
llama-index>=0.14.12
llama-index-retrievers-bm25>=0.7.1,<0.8.0
+# FAISS vector store: ANN retrieval replacing SimpleVectorStore brute force for
+# large KBs (issue #552); imported lazily with SimpleVectorStore fallback.
+llama-index-vector-stores-faiss>=0.4.0,<1.0.0
+faiss-cpu>=1.8.0,<2.0.0
PyMuPDF>=1.26.0
numpy>=1.24.0,<3.0.0
arxiv>=2.0.0
diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py
index b815f0fc5..296f0d2c4 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -64,6 +64,30 @@ class _FakeKBManager:
kb_dir.mkdir(parents=True, exist_ok=True)
return kb_dir
+ def register_lightrag_server_kb(
+ self,
+ name: str,
+ server_url: str,
+ *,
+ api_key: str = "",
+ search_mode: str = "",
+ description: str = "",
+ ) -> dict:
+ if name in self.config.get("knowledge_bases", {}):
+ raise ValueError(f"A knowledge base named '{name}' already exists.")
+ entry = {
+ "path": name,
+ "type": "lightrag_server",
+ "rag_provider": "lightrag-server",
+ "server_url": server_url,
+ "api_key": api_key,
+ "status": "ready",
+ }
+ if search_mode:
+ entry["search_mode"] = search_mode
+ self.config.setdefault("knowledge_bases", {})[name] = entry
+ return entry
+
class _FakeInitializer:
def __init__(self, kb_name: str, base_dir: str, **_kwargs) -> None:
@@ -110,15 +134,26 @@ def test_rag_providers_lists_llamaindex_and_pageindex() -> None:
assert response.status_code == 200
payload = response.json()
by_id = {p["id"]: p for p in payload["providers"]}
- assert set(by_id) == {"llamaindex", "pageindex", "graphrag", "lightrag"}
+ assert set(by_id) == {
+ "llamaindex",
+ "pageindex",
+ "graphrag",
+ "lightrag",
+ "lightrag-server",
+ }
# LlamaIndex works out of the box; PageIndex needs an API key; GraphRAG and
# LightRAG are optional local engines (no API key, configured = installed).
assert by_id["llamaindex"]["requires_api_key"] is False
assert by_id["pageindex"]["requires_api_key"] is True
assert by_id["graphrag"]["requires_api_key"] is False
assert by_id["lightrag"]["requires_api_key"] is False
+ # LightRAG Server is a thin HTTP client: always available, no API key gate
+ # (the per-KB endpoint is configured at connect time).
+ assert by_id["lightrag-server"]["requires_api_key"] is False
+ assert by_id["lightrag-server"]["configured"] is True
# Mode-aware engines advertise their retrieval modes; vector engines don't.
assert "hybrid" in by_id["lightrag"]["modes"]
+ assert "mix" in by_id["lightrag-server"]["modes"]
assert not by_id["llamaindex"].get("modes")
@@ -909,11 +944,13 @@ def test_rag_providers_marks_linkable() -> None:
with TestClient(_build_app()) as client:
providers = client.get("/api/v1/knowledge/rag-providers").json()["providers"]
by_id = {p["id"]: p for p in providers}
- # Self-contained local indexes can be linked in place; PageIndex (cloud) can't.
+ # Self-contained local indexes can be linked in place; PageIndex (cloud) and
+ # LightRAG Server (remote, no local folder) can't.
assert by_id["llamaindex"]["linkable"] is True
assert by_id["graphrag"]["linkable"] is True
assert by_id["lightrag"]["linkable"] is True
assert by_id["pageindex"]["linkable"] is False
+ assert by_id["lightrag-server"]["linkable"] is False
def test_probe_folder_endpoint_finds_ready_index(tmp_path: Path) -> None:
@@ -950,11 +987,81 @@ def test_probe_folder_endpoint_rejects_pageindex(tmp_path: Path) -> None:
assert payload["error"]
+def _patch_server_probe(monkeypatch, *, ok: bool, error: str | None = None) -> None:
+ """Stub the LightRAG server probe so router tests need no live server."""
+ from deeptutor.services.rag.pipelines.lightrag_server import probe as probe_module
+
+ async def _fake_probe(server_url: str, api_key: str = "", **_kwargs):
+ result = probe_module.ServerProbe(base_url=server_url.rstrip("/"))
+ result.ok = ok
+ result.reachable = ok
+ result.auth_required = bool(api_key)
+ result.auth_ok = ok
+ result.error = error
+ return result
+
+ monkeypatch.setattr(probe_module, "probe_server", _fake_probe)
+
+
+def test_probe_lightrag_server_endpoint_reports_verdict(monkeypatch) -> None:
+ _patch_server_probe(monkeypatch, ok=True)
+ with TestClient(_build_app()) as client:
+ response = client.post(
+ "/api/v1/knowledge/probe-lightrag-server",
+ json={"server_url": "http://localhost:9621", "api_key": "k"},
+ )
+ assert response.status_code == 200
+ payload = response.json()
+ assert payload["ok"] is True
+ assert payload["base_url"] == "http://localhost:9621"
+
+
+def test_connect_lightrag_server_registers_pointer(monkeypatch, tmp_path: Path) -> None:
+ manager = _FakeKBManager(tmp_path / "knowledge_bases")
+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)
+ _patch_server_probe(monkeypatch, ok=True)
+
+ with TestClient(_build_app()) as client:
+ response = client.post(
+ "/api/v1/knowledge/connect-lightrag-server",
+ json={
+ "name": "remote-kb",
+ "server_url": "http://localhost:9621/",
+ "api_key": "secret",
+ "search_mode": "MIX",
+ },
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["rag_provider"] == "lightrag-server"
+ entry = manager.config["knowledge_bases"]["remote-kb"]
+ assert entry["type"] == "lightrag_server"
+ assert entry["server_url"] == "http://localhost:9621"
+ assert entry["search_mode"] == "mix" # normalized + validated
+
+
+def test_connect_lightrag_server_rejects_unreachable(monkeypatch, tmp_path: Path) -> None:
+ manager = _FakeKBManager(tmp_path / "knowledge_bases")
+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)
+ _patch_server_probe(monkeypatch, ok=False, error="Could not reach a LightRAG server")
+
+ with TestClient(_build_app()) as client:
+ response = client.post(
+ "/api/v1/knowledge/connect-lightrag-server",
+ json={"name": "bad", "server_url": "http://nope:9621"},
+ )
+
+ assert response.status_code == 400
+ assert "LightRAG" in response.json()["detail"]
+ assert "bad" not in manager.config["knowledge_bases"]
+
+
def test_assert_not_connected_kb_blocks_connected_writes() -> None:
from fastapi import HTTPException
guard = knowledge_router_module._assert_not_connected_kb
- for kind in ("linked", "obsidian"):
+ for kind in ("linked", "obsidian", "lightrag_server"):
with pytest.raises(HTTPException) as excinfo:
guard("kb", {"type": kind})
assert excinfo.value.status_code == 409
diff --git a/tests/knowledge/test_lightrag_server_kb.py b/tests/knowledge/test_lightrag_server_kb.py
new file mode 100644
index 000000000..dded4fc44
--- /dev/null
+++ b/tests/knowledge/test_lightrag_server_kb.py
@@ -0,0 +1,106 @@
+"""Manager handling of LightRAG Server KBs (``type: lightrag_server`` pointers).
+
+A LightRAG Server KB is a connection pointer to an external server: no on-disk
+folder under ``base_dir``, no local index, and deleting it must only drop our
+pointer (never touch the user's server). The stored API key must never leak into
+surfaced metadata. Mirrors the linked/obsidian pointer guarantees.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from deeptutor.knowledge.kb_types import CONNECTED_KB_TYPES, LIGHTRAG_SERVER_KB_TYPE
+from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+
+def test_lightrag_server_is_a_connected_type() -> None:
+ assert LIGHTRAG_SERVER_KB_TYPE in CONNECTED_KB_TYPES
+
+
+def test_register_writes_pointer(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+
+ entry = manager.register_lightrag_server_kb(
+ "Remote",
+ "http://localhost:9621/",
+ api_key="secret",
+ search_mode="mix",
+ )
+
+ assert entry["type"] == LIGHTRAG_SERVER_KB_TYPE
+ assert entry["rag_provider"] == "lightrag-server"
+ assert entry["server_url"] == "http://localhost:9621" # trailing slash trimmed
+ assert entry["api_key"] == "secret"
+ assert entry["search_mode"] == "mix"
+ assert entry["status"] == "ready"
+ assert entry["needs_reindex"] is False
+ # No KB folder is created under base_dir.
+ assert not (manager.base_dir / "Remote").exists()
+
+
+def test_register_rejects_missing_url(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ with pytest.raises(ValueError):
+ manager.register_lightrag_server_kb("X", "")
+
+
+def test_register_rejects_name_clash(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ manager.register_lightrag_server_kb("Dup", "http://x:9621")
+ with pytest.raises(ValueError):
+ manager.register_lightrag_server_kb("Dup", "http://y:9621")
+
+
+def test_delete_drops_pointer(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ manager.register_lightrag_server_kb("Remote", "http://x:9621")
+
+ assert manager.delete_knowledge_base("Remote", confirm=True) is True
+ assert "Remote" not in manager.list_knowledge_bases()
+
+
+def test_entry_survives_orphan_prune(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ manager.register_lightrag_server_kb("Remote", "http://x:9621")
+
+ # No ``kbs/Remote`` directory exists, yet the pointer must not be pruned.
+ assert "Remote" in manager.list_knowledge_bases()
+
+
+def test_get_info_surfaces_url_but_hides_api_key(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ manager.register_lightrag_server_kb("Remote", "http://x:9621", api_key="secret")
+
+ info = manager.get_info("Remote")
+ assert info["status"] == "ready"
+ metadata = info["metadata"]
+ assert metadata["type"] == LIGHTRAG_SERVER_KB_TYPE
+ assert metadata["server_url"] == "http://x:9621"
+ # The API key must never be surfaced anywhere in the metadata.
+ assert "api_key" not in metadata
+ assert "secret" not in str(metadata)
+
+
+def test_get_metadata_hides_api_key(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ manager.register_lightrag_server_kb("Remote", "http://x:9621", api_key="secret")
+
+ meta = manager.get_metadata("Remote")
+ assert meta["type"] == LIGHTRAG_SERVER_KB_TYPE
+ assert meta["server_url"] == "http://x:9621"
+ assert "api_key" not in meta
+ assert "secret" not in str(meta)
+
+
+def test_reconcile_skips_server_entry(tmp_path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ manager.register_lightrag_server_kb("Remote", "http://x:9621")
+
+ # A fresh load runs the reconcile path; the pointer stays intact and is
+ # never flagged for reindex or given on-disk index versions.
+ reloaded = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ entry = reloaded.config["knowledge_bases"]["Remote"]
+ assert entry["type"] == LIGHTRAG_SERVER_KB_TYPE
+ assert entry.get("needs_reindex") is not True
+ assert "index_versions" not in entry
diff --git a/tests/services/config/test_runtime_settings.py b/tests/services/config/test_runtime_settings.py
index d9e38daf8..e6075bc2e 100644
--- a/tests/services/config/test_runtime_settings.py
+++ b/tests/services/config/test_runtime_settings.py
@@ -310,7 +310,13 @@ def test_document_parsing_v1_to_v2_migration(tmp_path: Path) -> None:
assert mineru["language"] == "ch"
assert mineru["allow_local_model_download"] is False
# All engines are always present after normalization.
- assert set(full["engines"]) == {"text_only", "mineru", "docling", "markitdown"}
+ assert set(full["engines"]) == {
+ "text_only",
+ "mineru",
+ "docling",
+ "markitdown",
+ "pymupdf4llm",
+ }
# Migration is persisted to the renamed file (v2, no top-level flat keys);
# the legacy mineru.json is gone.
assert not service.path_for("mineru").exists()
diff --git a/tests/services/parsing/test_engines.py b/tests/services/parsing/test_engines.py
index 9cbbfc690..414056e50 100644
--- a/tests/services/parsing/test_engines.py
+++ b/tests/services/parsing/test_engines.py
@@ -9,12 +9,24 @@ from deeptutor.services.parsing.types import ParserError
def test_known_engines() -> None:
- assert factory.KNOWN_ENGINES == {"text_only", "mineru", "docling", "markitdown"}
+ assert factory.KNOWN_ENGINES == {
+ "text_only",
+ "mineru",
+ "docling",
+ "markitdown",
+ "pymupdf4llm",
+ }
def test_list_engines_reports_metadata_and_availability() -> None:
engines = {entry["id"]: entry for entry in factory.list_engines()}
- assert set(engines) == {"text_only", "mineru", "docling", "markitdown"}
+ assert set(engines) == {
+ "text_only",
+ "mineru",
+ "docling",
+ "markitdown",
+ "pymupdf4llm",
+ }
assert engines["text_only"]["available"] is True
assert engines["text_only"]["needs_local_models"] is False
# MinerU is an external CLI / hosted API — the adapter is always available;
@@ -22,6 +34,7 @@ def test_list_engines_reports_metadata_and_availability() -> None:
assert engines["mineru"]["available"] is True
assert engines["mineru"]["needs_local_models"] is True
assert engines["markitdown"]["needs_local_models"] is False
+ assert engines["pymupdf4llm"]["needs_local_models"] is False
def test_get_parser_unknown_raises() -> None:
@@ -98,3 +111,145 @@ def test_mineru_local_model_download_gate(monkeypatch: pytest.MonkeyPatch) -> No
)
no_cli = rd.mineru_readiness(MinerUConfig(mode="local"))
assert no_cli.reason == "cli_missing"
+
+
+def test_pymupdf4llm_signature_tracks_image_knobs() -> None:
+ parser = factory.get_parser("pymupdf4llm")
+ from deeptutor.services.parsing.engines.pymupdf4llm.config import PyMuPDF4LLMConfig
+
+ base = parser.signature(
+ PyMuPDF4LLMConfig(write_images=True, image_format="png", image_dpi=150)
+ ).hash()
+ other_dpi = parser.signature(
+ PyMuPDF4LLMConfig(write_images=True, image_format="png", image_dpi=300)
+ ).hash()
+ no_images = parser.signature(PyMuPDF4LLMConfig(write_images=False)).hash()
+ assert base != other_dpi
+ assert base != no_images
+
+
+def test_pymupdf4llm_readiness_reflects_install() -> None:
+ parser = factory.get_parser("pymupdf4llm")
+ # Name lookup is case-insensitive (the metadata label is mixed-case).
+ assert type(factory.get_parser("PyMuPDF4LLM")) is type(parser)
+ report = parser.is_ready(parser.resolve_config())
+ if parser.is_available():
+ assert report.ready is True
+ else:
+ # Absent optional package → gated with a pip-install hint, not a crash.
+ assert report.reason == "not_configured"
+ assert "pymupdf4llm" in report.message
+
+
+def test_pymupdf4llm_parses_pdf_and_extracts_images(tmp_path) -> None:
+ pymupdf = pytest.importorskip("pymupdf")
+ pytest.importorskip("pymupdf4llm")
+ from deeptutor.services.parsing.engines.pymupdf4llm.config import PyMuPDF4LLMConfig
+
+ pdf = tmp_path / "doc.pdf"
+ doc = pymupdf.open()
+ page = doc.new_page()
+ page.insert_text((72, 72), "Hello DeepTutor via PyMuPDF4LLM")
+ pix = pymupdf.Pixmap(pymupdf.csRGB, pymupdf.IRect(0, 0, 120, 120))
+ pix.clear_with(128)
+ page.insert_image(pymupdf.Rect(100, 200, 320, 420), pixmap=pix)
+ doc.save(pdf)
+ doc.close()
+
+ parser = factory.get_parser("pymupdf4llm")
+ workdir = tmp_path / "parsed"
+ workdir.mkdir()
+ parser.parse(
+ pdf,
+ workdir,
+ config=PyMuPDF4LLMConfig(write_images=True, image_format="png", image_dpi=96),
+ )
+
+ md = (workdir / "doc.md").read_text(encoding="utf-8")
+ assert "DeepTutor" in md
+ images = workdir / "images"
+ assert images.is_dir()
+ extracted = list(images.glob("*.png"))
+ assert extracted, "expected at least one extracted image"
+ # Links are rewritten to the portable images/<name> form, not an abs path.
+ assert any(f"images/{p.name}" in md for p in extracted)
+ assert str(images) not in md
+
+
+def test_pymupdf4llm_no_images_leaves_no_asset_dir(tmp_path) -> None:
+ pymupdf = pytest.importorskip("pymupdf")
+ pytest.importorskip("pymupdf4llm")
+ from deeptutor.services.parsing.engines.pymupdf4llm.config import PyMuPDF4LLMConfig
+
+ pdf = tmp_path / "text.pdf"
+ doc = pymupdf.open()
+ page = doc.new_page()
+ page.insert_text((72, 72), "Text only, no figures here.")
+ doc.save(pdf)
+ doc.close()
+
+ parser = factory.get_parser("pymupdf4llm")
+ workdir = tmp_path / "parsed"
+ workdir.mkdir()
+ parser.parse(pdf, workdir, config=PyMuPDF4LLMConfig(write_images=True))
+
+ assert (workdir / "text.md").exists()
+ # An empty images/ dir is cleaned up so the cache loader sees no asset_dir.
+ assert not (workdir / "images").exists()
+
+
+def test_install_manager_spec_allowlist() -> None:
+ from deeptutor.services.parsing.engines._install import (
+ ENGINE_PIP_SPECS,
+ installable_engines,
+ )
+
+ # Only optional pip-backed engines are installable; built-in / external are not.
+ assert installable_engines() == {"pymupdf4llm", "markitdown", "docling"}
+ assert ENGINE_PIP_SPECS["pymupdf4llm"] == ["pymupdf4llm>=0.0.17,<1.0"]
+ assert "text_only" not in ENGINE_PIP_SPECS
+ assert "mineru" not in ENGINE_PIP_SPECS
+
+
+def test_model_download_allowlist() -> None:
+ from deeptutor.services.parsing.engines._install import (
+ ENGINE_MODEL_DOWNLOADERS,
+ model_downloadable_engines,
+ )
+
+ # Only Docling fetches model weights; the others need no models.
+ assert model_downloadable_engines() == {"docling"}
+ assert ENGINE_MODEL_DOWNLOADERS["docling"][0] == "docling-tools"
+ assert "pymupdf4llm" not in ENGINE_MODEL_DOWNLOADERS
+
+
+def test_resolve_model_downloader_unknown_engine() -> None:
+ from deeptutor.services.parsing.engines._install import resolve_model_downloader
+
+ assert resolve_model_downloader("pymupdf4llm") is None
+ assert resolve_model_downloader("nope") is None
+
+
+def test_background_job_manager_idle_status() -> None:
+ from deeptutor.services.parsing.engines._install import get_background_job_manager
+
+ status = get_background_job_manager().status(0)
+ assert status["state"] in {"idle", "running", "done", "failed", "cancelled"}
+ assert status["kind"] in {"", "install", "models"}
+ assert "engine" in status
+ assert isinstance(status["lines"], list)
+
+
+def test_docling_models_dir_honors_cache_env(monkeypatch, tmp_path) -> None:
+ from deeptutor.services.parsing.engines.docling import engine as docling_engine
+
+ monkeypatch.setenv("DOCLING_CACHE_DIR", str(tmp_path))
+ assert docling_engine.docling_models_dir() == tmp_path / "models"
+ # Empty cache → not ready; a populated models dir → detected as ready.
+ monkeypatch.delenv("DOCLING_ARTIFACTS_PATH", raising=False)
+ monkeypatch.setenv("HF_HOME", str(tmp_path / "nohub"))
+ assert docling_engine._docling_models_ready() is False
+ models = tmp_path / "models" / "layout"
+ models.mkdir(parents=True)
+ (models / "model.bin").write_bytes(b"x")
+ assert docling_engine._docling_models_ready() is True
diff --git a/tests/services/rag/test_lightrag_server_pipeline.py b/tests/services/rag/test_lightrag_server_pipeline.py
new file mode 100644
index 000000000..b594a63cf
--- /dev/null
+++ b/tests/services/rag/test_lightrag_server_pipeline.py
@@ -0,0 +1,266 @@
+"""Unit tests for the LightRAG Server (retrieval-only) RAG pipeline.
+
+The engine is a thin HTTP client over an external LightRAG server. We exercise:
+
+* the client wire shapes (``/query`` only_need_context, references→sources) against
+ an injected ``httpx.MockTransport`` — no network,
+* the connect-time probe verdict (reachable / auth-required / key accepted),
+* the pipeline's ``search`` (reads the per-KB endpoint from ``kb_config.json``,
+ shapes the result, and fails cleanly when unconfigured/unreachable),
+* factory routing and that indexing is refused (the server owns the index).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+
+import httpx
+
+from deeptutor.services.rag.factory import get_pipeline, normalize_provider_name
+from deeptutor.services.rag.pipelines.lightrag_server.client import LightRagServerClient
+from deeptutor.services.rag.pipelines.lightrag_server.config import (
+ DEFAULT_MODE,
+ LightRagServerConfig,
+ LightRagServerNotConfiguredError,
+ config_from_entry,
+)
+from deeptutor.services.rag.pipelines.lightrag_server.pipeline import LightRagServerPipeline
+from deeptutor.services.rag.pipelines.lightrag_server.probe import probe_server
+
+
+def _transport(*, auth_configured: bool = True, valid_key: str | None = "secret"):
+ """A MockTransport emulating a LightRAG server's relevant endpoints."""
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.path
+ if path == "/query":
+ body = json.loads(request.content)
+ assert body["only_need_context"] is True
+ return httpx.Response(
+ 200,
+ json={
+ "response": f"CONTEXT[{body['mode']}]",
+ "references": [
+ {"reference_id": "1", "file_path": "/docs/a.pdf"},
+ {"reference_id": "2", "file_path": "/docs/b.pdf"},
+ {"reference_id": "", "file_path": ""}, # dropped
+ ],
+ },
+ )
+ if path == "/auth-status":
+ return httpx.Response(
+ 200,
+ json={
+ "auth_configured": auth_configured,
+ "core_version": "1.2.3",
+ "api_version": "0150",
+ },
+ )
+ if path == "/documents/pipeline_status":
+ key = request.headers.get("X-API-Key")
+ ok = valid_key is None or key == valid_key
+ return httpx.Response(200 if ok else 403, json={})
+ return httpx.Response(404, json={})
+
+ return httpx.MockTransport(handler)
+
+
+def _client_factory(transport):
+ return lambda config: LightRagServerClient(config, transport=transport)
+
+
+# ----- config ------------------------------------------------------------
+
+
+def test_config_from_entry_requires_server_url() -> None:
+ cfg = config_from_entry({"server_url": "http://x:9621/", "api_key": "k"})
+ assert cfg.base_url == "http://x:9621" # trailing slash trimmed
+ assert cfg.api_key == "k"
+
+ try:
+ config_from_entry({"api_key": "k"})
+ except LightRagServerNotConfiguredError:
+ pass
+ else: # pragma: no cover - explicit failure
+ raise AssertionError("expected LightRagServerNotConfiguredError")
+
+
+# ----- client ------------------------------------------------------------
+
+
+def test_client_query_context_maps_references_to_sources() -> None:
+ client = LightRagServerClient(
+ LightRagServerConfig("http://x", "secret"), transport=_transport()
+ )
+ result = asyncio.run(client.query_context("what is AI?", "mix"))
+ assert result["content"] == "CONTEXT[mix]"
+ assert result["sources"] == [
+ {"id": "1", "file_path": "/docs/a.pdf"},
+ {"id": "2", "file_path": "/docs/b.pdf"},
+ ]
+
+
+def test_client_verify_key_true_and_false() -> None:
+ good = LightRagServerClient(
+ LightRagServerConfig("http://x", "secret"), transport=_transport()
+ )
+ bad = LightRagServerClient(
+ LightRagServerConfig("http://x", "wrong"), transport=_transport()
+ )
+ assert asyncio.run(good.verify_key()) is True
+ assert asyncio.run(bad.verify_key()) is False
+
+
+# ----- probe -------------------------------------------------------------
+
+
+def test_probe_ok_when_reachable_and_key_valid() -> None:
+ probe = asyncio.run(
+ probe_server("http://x:9621/", "secret", client_factory=_client_factory(_transport()))
+ )
+ assert probe.ok is True
+ assert probe.reachable is True
+ assert probe.auth_required is True
+ assert probe.auth_ok is True
+ assert probe.core_version == "1.2.3"
+ assert probe.base_url == "http://x:9621"
+
+
+def test_probe_rejects_bad_key() -> None:
+ probe = asyncio.run(
+ probe_server("http://x", "wrong", client_factory=_client_factory(_transport()))
+ )
+ assert probe.ok is False
+ assert probe.auth_ok is False
+ assert probe.error
+
+
+def test_probe_open_server_needs_no_key() -> None:
+ probe = asyncio.run(
+ probe_server(
+ "http://x",
+ "",
+ client_factory=_client_factory(_transport(auth_configured=False)),
+ )
+ )
+ assert probe.ok is True
+ assert probe.auth_required is False
+
+
+def test_probe_rejects_non_http_url() -> None:
+ probe = asyncio.run(probe_server("ftp://x"))
+ assert probe.ok is False
+ assert probe.reachable is False
+ assert probe.error
+
+
+def test_probe_unreachable_server_reports_error() -> None:
+ def boom(request: httpx.Request) -> httpx.Response:
+ raise httpx.ConnectError("refused", request=request)
+
+ probe = asyncio.run(
+ probe_server(
+ "http://x", "", client_factory=_client_factory(httpx.MockTransport(boom))
+ )
+ )
+ assert probe.ok is False
+ assert "Could not reach" in (probe.error or "")
+
+
+# ----- pipeline ----------------------------------------------------------
+
+
+def _kb_base(tmp_path: Path, entry: dict) -> str:
+ (tmp_path / "kb_config.json").write_text(
+ json.dumps({"knowledge_bases": {"remote": entry}}), encoding="utf-8"
+ )
+ return str(tmp_path)
+
+
+def test_search_returns_grounded_context(tmp_path: Path) -> None:
+ base = _kb_base(
+ tmp_path,
+ {
+ "type": "lightrag_server",
+ "rag_provider": "lightrag-server",
+ "server_url": "http://x",
+ "api_key": "secret",
+ "search_mode": "hybrid",
+ },
+ )
+ pipe = LightRagServerPipeline(kb_base_dir=base, client_factory=_client_factory(_transport()))
+ res = asyncio.run(pipe.search("q", "remote"))
+ assert res["provider"] == "lightrag-server"
+ assert res["mode"] == "hybrid" # per-KB search_mode wins
+ assert res["content"] == "CONTEXT[hybrid]"
+ assert res["answer"] == res["content"]
+ assert res["sources"][0]["file_path"] == "/docs/a.pdf"
+
+
+def test_search_defaults_mode_when_unset(tmp_path: Path) -> None:
+ base = _kb_base(
+ tmp_path,
+ {
+ "type": "lightrag_server",
+ "rag_provider": "lightrag-server",
+ "server_url": "http://x",
+ "api_key": "secret",
+ },
+ )
+ pipe = LightRagServerPipeline(kb_base_dir=base, client_factory=_client_factory(_transport()))
+ res = asyncio.run(pipe.search("q", "remote"))
+ assert res["mode"] == DEFAULT_MODE
+
+
+def test_search_not_configured_when_no_url(tmp_path: Path) -> None:
+ base = _kb_base(tmp_path, {"type": "lightrag_server", "rag_provider": "lightrag-server"})
+ pipe = LightRagServerPipeline(kb_base_dir=base, client_factory=_client_factory(_transport()))
+ res = asyncio.run(pipe.search("q", "remote"))
+ assert res["error_type"] == "not_configured"
+ assert res["content"] == ""
+
+
+def test_search_surfaces_retrieval_error(tmp_path: Path) -> None:
+ def boom(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(500, text="boom")
+
+ base = _kb_base(
+ tmp_path,
+ {
+ "type": "lightrag_server",
+ "rag_provider": "lightrag-server",
+ "server_url": "http://x",
+ },
+ )
+ pipe = LightRagServerPipeline(
+ kb_base_dir=base, client_factory=_client_factory(httpx.MockTransport(boom))
+ )
+ res = asyncio.run(pipe.search("q", "remote"))
+ assert res["error_type"] == "retrieval_error"
+
+
+def test_initialize_and_add_documents_are_refused(tmp_path: Path) -> None:
+ pipe = LightRagServerPipeline(kb_base_dir=str(tmp_path))
+ for coro in (pipe.initialize("kb", []), pipe.add_documents("kb", [])):
+ try:
+ asyncio.run(coro)
+ except RuntimeError as exc:
+ assert "external server" in str(exc)
+ else: # pragma: no cover - explicit failure
+ raise AssertionError("expected RuntimeError")
+
+
+def test_delete_is_noop_true(tmp_path: Path) -> None:
+ pipe = LightRagServerPipeline(kb_base_dir=str(tmp_path))
+ assert asyncio.run(pipe.delete("anything")) is True
+
+
+# ----- factory routing ---------------------------------------------------
+
+
+def test_factory_dispatches_lightrag_server(tmp_path: Path) -> None:
+ assert normalize_provider_name("lightrag-server") == "lightrag-server"
+ pipe = get_pipeline("lightrag-server", kb_base_dir=str(tmp_path))
+ assert type(pipe).__name__ == "LightRagServerPipeline"
diff --git a/tests/services/rag/test_llamaindex_embedding_failures.py b/tests/services/rag/test_llamaindex_embedding_failures.py
index 9c863ce24..84f1c2f1b 100644
--- a/tests/services/rag/test_llamaindex_embedding_failures.py
+++ b/tests/services/rag/test_llamaindex_embedding_failures.py
@@ -119,12 +119,7 @@ def test_retrieve_nodes_rejects_invalid_persisted_embeddings(
as_retriever=lambda similarity_top_k=5: _RetrieverShouldNotRun(),
)
- monkeypatch.setattr(
- storage_module.StorageContext,
- "from_defaults",
- lambda persist_dir: object(),
- )
- monkeypatch.setattr(storage_module, "load_index_from_storage", lambda _ctx: fake_index)
+ monkeypatch.setattr(storage_module.vector_store, "load_index", lambda _dir: fake_index)
with pytest.raises(ValueError, match="RAG index contains invalid embedding vectors"):
storage_module.retrieve_nodes(tmp_path, "what is this?")
@@ -163,12 +158,7 @@ def test_retrieve_nodes_checks_storage_context_vector_stores(
as_retriever=lambda similarity_top_k=5: _RetrieverShouldNotRun(),
)
- monkeypatch.setattr(
- storage_module.StorageContext,
- "from_defaults",
- lambda persist_dir: object(),
- )
- monkeypatch.setattr(storage_module, "load_index_from_storage", lambda _ctx: fake_index)
+ monkeypatch.setattr(storage_module.vector_store, "load_index", lambda _dir: fake_index)
with pytest.raises(ValueError, match="RAG index contains invalid embedding vectors"):
storage_module.retrieve_nodes(tmp_path, "what is this?")
diff --git a/tests/services/rag/test_llamaindex_faiss_vector_store.py b/tests/services/rag/test_llamaindex_faiss_vector_store.py
new file mode 100644
index 000000000..751efced8
--- /dev/null
+++ b/tests/services/rag/test_llamaindex_faiss_vector_store.py
@@ -0,0 +1,265 @@
+"""Tests for the FAISS-backed vector store seam (issue #552).
+
+These cover the behaviours plan B relies on: new indexes persist as FAISS,
+legacy SimpleVectorStore indexes are rebuilt in-memory without re-embedding,
+mixed-dimension/faiss-less installs fall back to SimpleVectorStore, and the
+retrieval path loads + validates an index only once (cached).
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+from llama_index.core import Settings, VectorStoreIndex
+from llama_index.core.embeddings import BaseEmbedding
+from llama_index.core.schema import ImageNode, TextNode
+import pytest
+
+from deeptutor.services.rag.pipelines.llamaindex import storage as storage_module
+from deeptutor.services.rag.pipelines.llamaindex import vector_store
+
+faiss = pytest.importorskip("faiss")
+pytest.importorskip("llama_index.vector_stores.faiss")
+
+_DIM = 8
+_VECTORS = {
+ "alpha": [1, 0, 0, 0, 0, 0, 0, 0],
+ "beta": [0, 1, 0, 0, 0, 0, 0, 0],
+ "gamma": [0.9, 0.1, 0, 0, 0, 0, 0, 0],
+ "delta": [0, 0, 1, 0, 0, 0, 0, 0],
+ # Query token chosen so it is not a substring of any node token (and vice
+ # versa); leans slightly toward gamma so cosine ranks gamma above alpha.
+ "probe": [0.8, 0.05, 0, 0, 0, 0, 0, 0],
+}
+
+
+class _FakeEmbed(BaseEmbedding):
+ """Deterministic embedding keyed by a substring of the text."""
+
+ def _vec(self, text: str) -> list[float]:
+ for key, vector in _VECTORS.items():
+ if key in text:
+ return [float(x) for x in vector]
+ return [0.0] * _DIM
+
+ def _get_text_embedding(self, text: str) -> list[float]:
+ return self._vec(text)
+
+ def _get_query_embedding(self, query: str) -> list[float]:
+ return self._vec(query)
+
+ async def _aget_query_embedding(self, query: str) -> list[float]:
+ return self._vec(query)
+
+ async def _aget_text_embedding(self, text: str) -> list[float]:
+ return self._vec(text)
+
+
[email protected](autouse=True)
+def _fake_embed_model() -> None:
+ Settings.embed_model = _FakeEmbed()
+ storage_module.clear_index_cache()
+ yield
+ storage_module.clear_index_cache()
+
+
+def _nodes() -> list[TextNode]:
+ nodes = []
+ for key in ("alpha", "beta", "gamma", "delta"):
+ node = TextNode(text=f"node {key}", id_=key)
+ node.embedding = [float(x) for x in _VECTORS[key]]
+ nodes.append(node)
+ return nodes
+
+
+def _persist_faiss_index(storage_dir: Path) -> None:
+ context = vector_store.new_faiss_storage_context(_DIM)
+ assert context is not None
+ index = VectorStoreIndex(nodes=_nodes(), storage_context=context)
+ context.persist(persist_dir=str(storage_dir))
+
+
+def _persist_simple_index(storage_dir: Path) -> None:
+ index = VectorStoreIndex(nodes=_nodes()) # default = SimpleVectorStore
+ index.storage_context.persist(persist_dir=str(storage_dir))
+
+
+def test_new_index_persists_faiss_and_ranks_by_cosine(tmp_path: Path) -> None:
+ _persist_faiss_index(tmp_path)
+
+ assert vector_store.detect_backend(tmp_path) == vector_store.BACKEND_FAISS
+ # The default store file holds a binary FAISS index, not JSON.
+ head = (tmp_path / vector_store.DEFAULT_VECTOR_STORE_FILENAME).read_bytes()[:1]
+ assert head != b"{"
+
+ index = vector_store.load_index(tmp_path)
+ results = index.as_retriever(similarity_top_k=2).retrieve("probe")
+ ids = [r.node.node_id for r in results]
+ # The probe vector aligns most with gamma then alpha under cosine.
+ assert ids == ["gamma", "alpha"]
+
+
+def test_legacy_simple_index_stays_readable_without_mutation(tmp_path: Path) -> None:
+ """An existing SimpleVectorStore KB keeps working after the FAISS upgrade."""
+ _persist_simple_index(tmp_path)
+ assert vector_store.detect_backend(tmp_path) == vector_store.BACKEND_SIMPLE
+
+ index = vector_store.load_index(tmp_path)
+ # Loaded as-is (not converted): the read path never rewrites the store.
+ assert "Faiss" not in type(index.vector_store).__name__
+ assert vector_store.detect_backend(tmp_path) == vector_store.BACKEND_SIMPLE
+
+ results = index.as_retriever(similarity_top_k=2).retrieve("probe")
+ assert [r.node.node_id for r in results] == ["gamma", "alpha"]
+
+
+def test_mixed_dimension_nodes_fall_back_to_simple() -> None:
+ text_node = TextNode(text="text", id_="t")
+ text_node.embedding = [0.1] * _DIM
+ other_node = TextNode(text="other", id_="o")
+ other_node.embedding = [0.2] * (_DIM * 2) # different dimension
+
+ assert vector_store.storage_context_for_nodes([text_node, other_node]) is None
+
+
+def _multimodal_nodes() -> list[object]:
+ """A text + image node sharing one dimension (single multimodal embedding).
+
+ DeepTutor embeds text and images with the *same* embedding client, so both
+ modalities produce same-dimension vectors and (in a plain VectorStoreIndex)
+ land in the ``default`` store together.
+ """
+ text_node = TextNode(text="node alpha", id_="text-1")
+ text_node.embedding = [float(x) for x in _VECTORS["alpha"]]
+ image_node = ImageNode(text="[Image] gamma.png", id_="image-1", image_path="/x/gamma.png")
+ image_node.embedding = [float(x) for x in _VECTORS["gamma"]]
+ return [text_node, image_node]
+
+
+def test_multimodal_nodes_indexed_and_retrieved_via_faiss(tmp_path: Path) -> None:
+ """Same-dimension text + image vectors are stored in (and served from) FAISS."""
+ nodes = _multimodal_nodes()
+ context = vector_store.storage_context_for_nodes(nodes)
+ assert context is not None, "uniform-dimension multimodal nodes should use FAISS"
+
+ VectorStoreIndex(nodes=nodes, storage_context=context)
+ context.persist(persist_dir=str(tmp_path))
+ assert vector_store.detect_backend(tmp_path) == vector_store.BACKEND_FAISS
+
+ index = vector_store.load_index(tmp_path)
+ results = index.as_retriever(similarity_top_k=2).retrieve("probe")
+ returned = {r.node.node_id: type(r.node).__name__ for r in results}
+ assert returned == {"text-1": "TextNode", "image-1": "ImageNode"}
+
+
+def test_legacy_multimodal_simple_index_stays_readable(tmp_path: Path) -> None:
+ """A legacy multimodal SimpleVectorStore (text + image in default) still serves both."""
+ VectorStoreIndex(nodes=_multimodal_nodes()).storage_context.persist(persist_dir=str(tmp_path))
+ assert vector_store.detect_backend(tmp_path) == vector_store.BACKEND_SIMPLE
+
+ index = vector_store.load_index(tmp_path)
+ results = index.as_retriever(similarity_top_k=2).retrieve("probe")
+ assert {r.node.node_id for r in results} == {"text-1", "image-1"}
+
+
+def test_uniform_dimension_nodes_select_faiss() -> None:
+ nodes = _nodes()
+ context = vector_store.storage_context_for_nodes(nodes)
+ assert context is not None
+ assert "Faiss" in type(context.vector_store).__name__
+
+
+def test_detect_backend_distinguishes_json_and_binary(tmp_path: Path) -> None:
+ simple_dir = tmp_path / "simple"
+ simple_dir.mkdir()
+ (simple_dir / vector_store.DEFAULT_VECTOR_STORE_FILENAME).write_text(
+ '{"embedding_dict": {}}', encoding="utf-8"
+ )
+ assert vector_store.detect_backend(simple_dir) == vector_store.BACKEND_SIMPLE
+
+ faiss_dir = tmp_path / "faiss"
+ faiss_dir.mkdir()
+ faiss.write_index(faiss.IndexFlatIP(_DIM), str(faiss_dir / vector_store.DEFAULT_VECTOR_STORE_FILENAME))
+ assert vector_store.detect_backend(faiss_dir) == vector_store.BACKEND_FAISS
+
+ # Missing file => assume simple (and never crash).
+ assert vector_store.detect_backend(tmp_path / "missing") == vector_store.BACKEND_SIMPLE
+
+
+def test_retrieve_nodes_caches_index_and_invalidates_on_change(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _persist_faiss_index(tmp_path)
+
+ load_calls: list[str] = []
+ real_load = vector_store.load_index
+
+ def _counting_load(storage_dir):
+ load_calls.append(str(storage_dir))
+ return real_load(storage_dir)
+
+ monkeypatch.setattr(storage_module.vector_store, "load_index", _counting_load)
+
+ first = storage_module.retrieve_nodes(tmp_path, "probe", top_k=2)
+ second = storage_module.retrieve_nodes(tmp_path, "probe", top_k=2)
+ assert first and second
+ assert len(load_calls) == 1, "second query must reuse the cached index"
+
+ # Touch the docstore so the freshness token changes -> cache invalidated.
+ docstore = tmp_path / "docstore.json"
+ future = docstore.stat().st_mtime_ns + 1_000_000_000
+ os.utime(docstore, ns=(future, future))
+
+ storage_module.retrieve_nodes(tmp_path, "probe", top_k=2)
+ assert len(load_calls) == 2, "a changed store must trigger a reload"
+
+
+def test_validation_skips_binary_faiss_files(tmp_path: Path) -> None:
+ """A persisted FAISS index must not trip the SimpleVectorStore validator."""
+ _persist_faiss_index(tmp_path)
+ # Should not raise despite the binary default__vector_store.json file.
+ storage_module.validate_storage_embeddings(tmp_path)
+
+
+def test_reindex_supersedes_legacy_simple_version_with_faiss(tmp_path: Path) -> None:
+ """Re-indexing a legacy KB writes a newer FAISS version that wins on read."""
+ from deeptutor.services.rag.index_versioning import (
+ EmbeddingSignature,
+ resolve_storage_dir_for_read,
+ write_version_meta,
+ )
+
+ kb_dir = tmp_path / "kb"
+ sig = EmbeddingSignature(
+ binding="b", model="m", dimension=_DIM, base_url="", api_version=""
+ )
+
+ # version-1: the pre-upgrade SimpleVectorStore index.
+ v1 = kb_dir / "version-1"
+ v1.mkdir(parents=True)
+ _persist_simple_index(v1)
+ write_version_meta(kb_dir, sig, storage_dir=v1)
+
+ # version-2: a re-index, persisted as FAISS (same embedding signature).
+ v2 = kb_dir / "version-2"
+ v2.mkdir()
+ _persist_faiss_index(v2)
+ write_version_meta(kb_dir, sig, storage_dir=v2)
+
+ resolved = resolve_storage_dir_for_read(kb_dir, sig)
+ assert resolved == v2
+ assert vector_store.detect_backend(resolved) == vector_store.BACKEND_FAISS
+
+
+def test_storage_create_index_persists_faiss_end_to_end(tmp_path: Path) -> None:
+ """The production create path (ingestion -> storage) persists a FAISS index."""
+ from llama_index.core import Document
+
+ storage_dir = tmp_path / "version-1"
+ storage_dir.mkdir()
+
+ count = storage_module.create_index([Document(text="node alpha", id_="d")], storage_dir)
+ assert count == 1
+ assert vector_store.detect_backend(storage_dir) == vector_store.BACKEND_FAISS
+ assert storage_module.retrieve_nodes(storage_dir, "probe", top_k=1)
diff --git a/tests/services/rag/test_llamaindex_storage_layout.py b/tests/services/rag/test_llamaindex_storage_layout.py
index bb98d7c1c..fd59f6ad7 100644
--- a/tests/services/rag/test_llamaindex_storage_layout.py
+++ b/tests/services/rag/test_llamaindex_storage_layout.py
@@ -44,11 +44,6 @@ async def test_incremental_add_migrates_matching_legacy_index_to_flat_version(
captured: dict[str, str] = {}
class _FakeStorageContext:
- @classmethod
- def from_defaults(cls, persist_dir: str):
- captured["load_dir"] = persist_dir
- return cls()
-
def persist(self, persist_dir: str) -> None:
captured["persist_dir"] = persist_dir
target = Path(persist_dir)
@@ -63,6 +58,10 @@ async def test_incremental_add_migrates_matching_legacy_index_to_flat_version(
def insert(self, document) -> None:
self.inserted.append(document)
+ def _fake_load_index(storage_dir) -> _FakeIndex:
+ captured["load_dir"] = str(storage_dir)
+ return _FakeIndex()
+
async def _verify_embedding_connectivity(self) -> None:
return None
@@ -76,12 +75,7 @@ async def test_incremental_add_migrates_matching_legacy_index_to_flat_version(
"_verify_embedding_connectivity",
_verify_embedding_connectivity,
)
- monkeypatch.setattr(storage_module, "StorageContext", _FakeStorageContext)
- monkeypatch.setattr(
- storage_module,
- "load_index_from_storage",
- lambda _storage_context: _FakeIndex(),
- )
+ monkeypatch.setattr(storage_module.vector_store, "load_index", _fake_load_index)
pipeline = LlamaIndexPipeline(
kb_base_dir=str(tmp_path),
diff --git a/tests/tools/test_rag_tool.py b/tests/tools/test_rag_tool.py
index 75fde3222..97ab28f89 100644
--- a/tests/tools/test_rag_tool.py
+++ b/tests/tools/test_rag_tool.py
@@ -46,6 +46,7 @@ class TestPipelineFactory:
"pageindex",
"graphrag",
"lightrag",
+ "lightrag-server",
}
def test_get_pipeline_returns_singleton(self) -> None:
@@ -80,6 +81,7 @@ class TestRAGServiceClassHelpers:
"pageindex",
"graphrag",
"lightrag",
+ "lightrag-server",
}
def test_has_provider_default_true(self) -> None:
diff --git a/web/app/(utility)/settings/document-parsing/page.tsx b/web/app/(utility)/settings/document-parsing/page.tsx
index 61c8a6d4b..335e45fa2 100644
--- a/web/app/(utility)/settings/document-parsing/page.tsx
+++ b/web/app/(utility)/settings/document-parsing/page.tsx
@@ -1,13 +1,15 @@
"use client";
-import { useCallback, useEffect, useState } from "react";
-import { CheckCircle2, Loader2, XCircle } from "lucide-react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { CheckCircle2, Download, Loader2, XCircle } from "lucide-react";
import { useTranslation } from "react-i18next";
import {
SettingRow,
SettingSection,
SettingsPageHeader,
+ nativeSelectClass,
+ selectOptionClass,
} from "@/components/settings/shared";
import { MinerUEngineSettings } from "@/components/settings/MinerUEngineSettings";
import { Toggle } from "@/components/settings/Toggle";
@@ -28,12 +30,14 @@ type DocumentParsingPayload = {
engines: Record<string, Record<string, unknown>>;
available_engines: EngineMeta[];
readiness: Record<string, Readiness>;
+ installable: string[];
mineru: { api_token_set: boolean; local_cli?: unknown };
};
-const INSTALL_HINT: Record<string, string> = {
+const PIP_HINT: Record<string, string> = {
docling: "pip install deeptutor[parse-docling]",
markitdown: "pip install deeptutor[parse-markitdown]",
+ pymupdf4llm: "pip install deeptutor[parse-pymupdf4llm]",
};
export default function DocumentParsingSettingsPage() {
@@ -175,11 +179,6 @@ export default function DocumentParsingSettingsPage() {
<p className="mt-1 text-[12px] text-[var(--muted-foreground)]">
{engine.description}
</p>
- {!engine.available && INSTALL_HINT[engine.id] && (
- <code className="mt-1 block font-mono text-[11px] text-[var(--muted-foreground)]">
- {INSTALL_HINT[engine.id]}
- </code>
- )}
</div>
</button>
);
@@ -200,6 +199,7 @@ export default function DocumentParsingSettingsPage() {
?.available ?? false
}
busy={busy}
+ onInstalled={load}
onSave={(patch) =>
putDocumentParsing({ engines: { docling: patch } })
}
@@ -214,11 +214,27 @@ export default function DocumentParsingSettingsPage() {
?.available ?? false
}
busy={busy}
+ onInstalled={load}
onSave={(patch) =>
putDocumentParsing({ engines: { markitdown: patch } })
}
/>
)}
+
+ {data.engine === "pymupdf4llm" && (
+ <PyMuPDF4LLMPanel
+ slice={data.engines.pymupdf4llm || {}}
+ available={
+ data.available_engines.find((e) => e.id === "pymupdf4llm")
+ ?.available ?? false
+ }
+ busy={busy}
+ onInstalled={load}
+ onSave={(patch) =>
+ putDocumentParsing({ engines: { pymupdf4llm: patch } })
+ }
+ />
+ )}
</>
)}
</div>
@@ -267,17 +283,44 @@ function ReadinessBadge({ readiness }: { readiness?: Readiness }) {
);
}
+// Full-width readiness line for engines whose "not ready" guidance is a
+// multi-sentence message (e.g. Docling's "models not downloaded" hint). A long
+// message must wrap full-width — it doesn't fit a SettingRow's compact,
+// non-shrinking control slot (which overflows and squeezes the title).
+function ReadinessNotice({ readiness }: { readiness?: Readiness }) {
+ const { t } = useTranslation();
+ if (!readiness) return null;
+ if (readiness.ready) {
+ return (
+ <div className="flex items-center gap-1.5 px-1 py-4 text-[12px] text-emerald-600 dark:text-emerald-400">
+ <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />
+ {t("Ready to parse.")}
+ </div>
+ );
+ }
+ return (
+ <div className="px-1 py-4">
+ <div className="flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-[12px] leading-relaxed text-amber-700 dark:text-amber-300">
+ <XCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ <span className="min-w-0">{readiness.message}</span>
+ </div>
+ </div>
+ );
+}
+
function DoclingPanel({
slice,
readiness,
available,
busy,
+ onInstalled,
onSave,
}: {
slice: Record<string, unknown>;
readiness?: Readiness;
available: boolean;
busy: boolean;
+ onInstalled: () => void;
onSave: (patch: Record<string, unknown>) => void;
}) {
const { t } = useTranslation();
@@ -287,13 +330,11 @@ function DoclingPanel({
if (!available) {
return (
- <SettingSection title={t("Docling")} description="">
- <SettingRow
- title={t("Docling isn't installed.")}
- description="pip install deeptutor[parse-docling]"
- control={null}
- />
- </SettingSection>
+ <NotInstalledSection
+ engineId="docling"
+ title={t("Docling")}
+ onInstalled={onInstalled}
+ />
);
}
@@ -304,10 +345,14 @@ function DoclingPanel({
"Structured conversion of PDF/Office/HTML/images. Downloads layout/table models on first run.",
)}
>
- <SettingRow
- title={t("Model status")}
- control={<ReadinessBadge readiness={readiness} />}
- />
+ <ReadinessNotice readiness={readiness} />
+ {readiness && !readiness.ready && (
+ <ModelDownloadRow
+ engineId="docling"
+ title={t("Docling")}
+ onDownloaded={onInstalled}
+ />
+ )}
<SettingRow
title={t("Allow automatic model download")}
description={t(
@@ -350,11 +395,13 @@ function MarkItDownPanel({
slice,
available,
busy,
+ onInstalled,
onSave,
}: {
slice: Record<string, unknown>;
available: boolean;
busy: boolean;
+ onInstalled: () => void;
onSave: (patch: Record<string, unknown>) => void;
}) {
const { t } = useTranslation();
@@ -362,13 +409,11 @@ function MarkItDownPanel({
if (!available) {
return (
- <SettingSection title={t("markitdown")} description="">
- <SettingRow
- title={t("markitdown isn't installed.")}
- description="pip install deeptutor[parse-markitdown]"
- control={null}
- />
- </SettingSection>
+ <NotInstalledSection
+ engineId="markitdown"
+ title={t("markitdown")}
+ onInstalled={onInstalled}
+ />
);
}
@@ -395,3 +440,389 @@ function MarkItDownPanel({
</SettingSection>
);
}
+
+const PYMUPDF4LLM_IMAGE_FORMATS = ["png", "jpg", "jpeg", "webp"];
+
+function PyMuPDF4LLMPanel({
+ slice,
+ available,
+ busy,
+ onInstalled,
+ onSave,
+}: {
+ slice: Record<string, unknown>;
+ available: boolean;
+ busy: boolean;
+ onInstalled: () => void;
+ onSave: (patch: Record<string, unknown>) => void;
+}) {
+ const { t } = useTranslation();
+ const writeImages = slice.write_images !== false;
+ const imageFormat =
+ typeof slice.image_format === "string" ? slice.image_format : "png";
+ const imageDpi = typeof slice.image_dpi === "number" ? slice.image_dpi : 150;
+
+ if (!available) {
+ return (
+ <NotInstalledSection
+ engineId="pymupdf4llm"
+ title={t("PyMuPDF4LLM")}
+ onInstalled={onInstalled}
+ />
+ );
+ }
+
+ return (
+ <SettingSection
+ title={t("PyMuPDF4LLM")}
+ description={t(
+ "Lightweight PDF/e-book → Markdown built on PyMuPDF. No model downloads or CUDA, so it runs on low-end machines.",
+ )}
+ >
+ <SettingRow
+ title={t("Extract images")}
+ description={t(
+ "Save embedded images and rendered vector graphics into the parse, referenced from the Markdown.",
+ )}
+ control={
+ <Toggle
+ checked={writeImages}
+ disabled={busy}
+ onChange={(v) => onSave({ write_images: v })}
+ />
+ }
+ />
+ {writeImages && (
+ <>
+ <SettingRow
+ title={t("Image format")}
+ control={
+ <select
+ className={`${nativeSelectClass} w-28`}
+ value={imageFormat}
+ disabled={busy}
+ onChange={(e) => onSave({ image_format: e.target.value })}
+ >
+ {PYMUPDF4LLM_IMAGE_FORMATS.map((f) => (
+ <option key={f} className={selectOptionClass} value={f}>
+ {f}
+ </option>
+ ))}
+ </select>
+ }
+ />
+ <SettingRow
+ title={t("Image resolution (DPI)")}
+ description={t("Higher is sharper but larger. 72–600.")}
+ control={
+ <input
+ type="number"
+ min={72}
+ max={600}
+ step={1}
+ value={imageDpi}
+ disabled={busy}
+ onChange={(e) => {
+ const v = Number(e.target.value);
+ if (Number.isFinite(v)) onSave({ image_dpi: v });
+ }}
+ className="w-24 rounded-lg border border-[var(--border)] bg-transparent px-2 py-1 text-[12px] text-[var(--foreground)]"
+ />
+ }
+ />
+ </>
+ )}
+ </SettingSection>
+ );
+}
+
+type JobKind = "install" | "models";
+
+type JobStatus = {
+ state: "running" | "done" | "failed" | "cancelled" | string;
+ kind: JobKind;
+ lines: string[];
+ message: string;
+};
+
+// Shared driver for the page's one-click background jobs (pip install / model
+// download). Mirrors the MinerU model-download UI: POST to start → poll a shared
+// cursor-based log filtered by `kind` → call onDone once on success. Only one
+// job runs server-side at a time, so the kind filter keeps each card's view to
+// its own job.
+function useBackgroundJob(
+ kind: JobKind,
+ startUrl: string,
+ engineId: string,
+ onDone: () => void,
+) {
+ const { t } = useTranslation();
+ const [job, setJob] = useState<JobStatus | null>(null);
+ const [starting, setStarting] = useState(false);
+ const cursor = useRef(0);
+ const notifiedDone = useRef(false);
+
+ useEffect(() => {
+ if (job?.state !== "running") return;
+ const timer = setInterval(async () => {
+ try {
+ const response = await apiFetch(
+ apiUrl(
+ `/api/v1/settings/document-parsing/job/status?cursor=${cursor.current}`,
+ ),
+ );
+ if (!response.ok) return;
+ const data = (await response.json()) as {
+ state?: string;
+ kind?: string;
+ lines?: string[];
+ next_cursor?: number;
+ message?: string;
+ };
+ // A different kind of job is running — leave our view alone.
+ if (data.kind && data.kind !== kind) return;
+ cursor.current = data.next_cursor ?? cursor.current;
+ setJob((current) =>
+ current
+ ? {
+ state: data.state || current.state,
+ kind,
+ lines: [...current.lines, ...(data.lines || [])].slice(-100),
+ message: data.message || "",
+ }
+ : current,
+ );
+ if (data.state === "done" && !notifiedDone.current) {
+ notifiedDone.current = true;
+ onDone();
+ }
+ } catch {
+ // transient network error — keep polling
+ }
+ }, 1000);
+ return () => clearInterval(timer);
+ }, [job?.state, kind, onDone]);
+
+ async function start() {
+ setStarting(true);
+ notifiedDone.current = false;
+ try {
+ const response = await apiFetch(apiUrl(startUrl), {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ engine: engineId }),
+ });
+ const data = (await response.json().catch(() => ({}))) as {
+ ok?: boolean;
+ message?: string;
+ detail?: string;
+ };
+ if (!response.ok || !data.ok) {
+ setJob({
+ state: "failed",
+ kind,
+ lines: [],
+ message: data.message || data.detail || t("Failed."),
+ });
+ return;
+ }
+ cursor.current = 0;
+ setJob({ state: "running", kind, lines: [], message: "" });
+ } finally {
+ setStarting(false);
+ }
+ }
+
+ async function cancel() {
+ try {
+ await apiFetch(apiUrl("/api/v1/settings/document-parsing/job/cancel"), {
+ method: "POST",
+ });
+ } catch {
+ // status polling surfaces the final state either way
+ }
+ }
+
+ return { job, starting, start, cancel };
+}
+
+// Status line + streamed log for a background job, shared by install / download.
+function JobLog({
+ job,
+ runningLabel,
+ doneLabel,
+}: {
+ job: JobStatus | null;
+ runningLabel: string;
+ doneLabel: string;
+}) {
+ if (!job) return null;
+ return (
+ <div className="px-1 pb-1">
+ <div
+ className={`mb-2 inline-flex items-center gap-1.5 text-[12px] ${
+ job.state === "done"
+ ? "text-emerald-600 dark:text-emerald-400"
+ : job.state === "running"
+ ? "text-[var(--muted-foreground)]"
+ : "text-red-600 dark:text-red-400"
+ }`}
+ >
+ {job.state === "running" ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : job.state === "done" ? (
+ <CheckCircle2 className="h-3.5 w-3.5" />
+ ) : (
+ <XCircle className="h-3.5 w-3.5" />
+ )}
+ {job.state === "running"
+ ? runningLabel
+ : job.state === "done"
+ ? doneLabel
+ : job.message || job.state}
+ </div>
+ {job.lines.length > 0 && (
+ <pre className="max-h-40 overflow-y-auto whitespace-pre-wrap rounded-lg border border-[var(--border)]/60 bg-[var(--card)] px-3 py-2 font-mono text-[11px] leading-relaxed text-[var(--muted-foreground)]">
+ {job.lines.join("\n")}
+ </pre>
+ )}
+ </div>
+ );
+}
+
+function JobButton({
+ running,
+ starting,
+ label,
+ onStart,
+ onCancel,
+}: {
+ running: boolean;
+ starting: boolean;
+ label: string;
+ onStart: () => void;
+ onCancel: () => void;
+}) {
+ const { t } = useTranslation();
+ if (running) {
+ return (
+ <button
+ type="button"
+ onClick={onCancel}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-opacity hover:opacity-80"
+ >
+ {t("Cancel")}
+ </button>
+ );
+ }
+ return (
+ <button
+ type="button"
+ onClick={onStart}
+ disabled={starting}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"
+ >
+ {starting ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <Download className="h-3 w-3" />
+ )}
+ {label}
+ </button>
+ );
+}
+
+// The active engine's panel when its optional package isn't installed: a clean
+// section with the pip hint and a one-click installer. Keeps install in ONE
+// place per engine; reloads on success so the engine flips to available.
+function NotInstalledSection({
+ engineId,
+ title,
+ onInstalled,
+}: {
+ engineId: string;
+ title: string;
+ onInstalled: () => void;
+}) {
+ const { t } = useTranslation();
+ const { job, starting, start, cancel } = useBackgroundJob(
+ "install",
+ "/api/v1/settings/document-parsing/install",
+ engineId,
+ onInstalled,
+ );
+
+ return (
+ <SettingSection
+ title={title}
+ description={t(
+ "Not installed yet. Install the package to use this engine — runs on the server, no terminal needed.",
+ )}
+ >
+ <SettingRow
+ title={t("Install package")}
+ description={PIP_HINT[engineId]}
+ control={
+ <JobButton
+ running={job?.state === "running"}
+ starting={starting}
+ label={t("Download & install")}
+ onStart={start}
+ onCancel={cancel}
+ />
+ }
+ />
+ <JobLog
+ job={job}
+ runningLabel={t("Installing {{name}}…", { name: title })}
+ doneLabel={t("Installed. Reloading…")}
+ />
+ </SettingSection>
+ );
+}
+
+// One-click model-weight download for an installed engine that still needs its
+// models (e.g. Docling). Mirrors MinerU's "Download models"; reloads readiness
+// on success so the gate clears.
+function ModelDownloadRow({
+ engineId,
+ title,
+ onDownloaded,
+}: {
+ engineId: string;
+ title: string;
+ onDownloaded: () => void;
+}) {
+ const { t } = useTranslation();
+ const { job, starting, start, cancel } = useBackgroundJob(
+ "models",
+ "/api/v1/settings/document-parsing/models/download",
+ engineId,
+ onDownloaded,
+ );
+
+ return (
+ <>
+ <SettingRow
+ title={t("Download models")}
+ description={t(
+ "Fetch the model weights onto the server now — no terminal needed.",
+ )}
+ control={
+ <JobButton
+ running={job?.state === "running"}
+ starting={starting}
+ label={t("Download models")}
+ onStart={start}
+ onCancel={cancel}
+ />
+ }
+ />
+ <JobLog
+ job={job}
+ runningLabel={t("Downloading {{name}} models…", { name: title })}
+ doneLabel={t("Downloaded. Reloading…")}
+ />
+ </>
+ );
+}
diff --git a/web/components/knowledge/CreateKbModal.tsx b/web/components/knowledge/CreateKbModal.tsx
index 594467d4d..38c58b737 100644
--- a/web/components/knowledge/CreateKbModal.tsx
+++ b/web/components/knowledge/CreateKbModal.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useState } from "react";
+import { useEffect, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import {
AlertTriangle,
@@ -10,11 +10,14 @@ import {
Link2,
Loader2,
Plus,
+ Server,
} from "lucide-react";
import Modal from "@/components/common/Modal";
import {
+ probeLightRagServer,
probeLinkedFolder,
type KnowledgeUploadPolicy,
+ type LightRagServerProbe,
type LinkedFolderProbe,
type RagProviderSummary,
} from "@/lib/knowledge-api";
@@ -23,8 +26,10 @@ import FileDropZone from "./FileDropZone";
const PAGEINDEX_FORMATS = [".pdf", ".md", ".markdown"];
const OBSIDIAN_SOURCE = "obsidian";
+const LIGHTRAG_SERVER_PROVIDER = "lightrag-server";
const EXAMPLE_INDEX_PATH = "/Users/you/knowledge_bases/my-kb";
const EXAMPLE_VAULT_PATH = "/Users/you/Documents/MyVault";
+const EXAMPLE_SERVER_URL = "http://localhost:9621";
type Mode = "new" | "link";
@@ -49,6 +54,13 @@ interface CreateKbModalProps {
name: string;
vaultPath: string;
}) => Promise<void>;
+ /** Connect an external LightRAG server (retrieval only, no local index). */
+ onConnectLightRagServer: (params: {
+ name: string;
+ serverUrl: string;
+ apiKey?: string;
+ mode?: string;
+ }) => Promise<void>;
/** Open the RAG pipeline settings (to add a missing API key). */
onConfigureProvider?: () => void;
/** Open straight into a given mode (e.g. "link" from the Obsidian card). */
@@ -65,6 +77,7 @@ export default function CreateKbModal({
onCreate,
onConnectLinkedFolder,
onConnectObsidian,
+ onConnectLightRagServer,
onConfigureProvider,
initialMode = "new",
initialSource,
@@ -79,6 +92,12 @@ export default function CreateKbModal({
const [folderPath, setFolderPath] = useState("");
const [probe, setProbe] = useState<LinkedFolderProbe | null>(null);
const [probing, setProbing] = useState(false);
+ // LightRAG Server engine (new mode): a connection instead of an upload.
+ const [serverUrl, setServerUrl] = useState("");
+ const [apiKey, setApiKey] = useState("");
+ const [serverMode, setServerMode] = useState("");
+ const [serverProbe, setServerProbe] = useState<LightRagServerProbe | null>(null);
+ const [serverProbing, setServerProbing] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -90,11 +109,16 @@ export default function CreateKbModal({
setName("");
setFiles([]);
setError(null);
- setProvider(providers[0]?.id || "llamaindex");
+ setProvider(initialSource || providers[0]?.id || "llamaindex");
setLinkSource(initialSource || firstLinkable || OBSIDIAN_SOURCE);
setFolderPath("");
setProbe(null);
setProbing(false);
+ setServerUrl("");
+ setApiKey("");
+ setServerMode("");
+ setServerProbe(null);
+ setServerProbing(false);
}, [isOpen, providers, firstLinkable, initialMode, initialSource]);
// A fresh path / source invalidates a stale probe verdict.
@@ -102,12 +126,21 @@ export default function CreateKbModal({
setProbe(null);
}, [folderPath, linkSource]);
+ // A fresh URL / key invalidates a stale server connection test.
+ useEffect(() => {
+ setServerProbe(null);
+ }, [serverUrl, apiKey]);
+
// ---- New mode (build a fresh index) ----------------------------------
const activeProvider = providers.find((p) => p.id === provider);
const providerNeedsKey =
!!activeProvider?.requires_api_key && activeProvider?.configured === false;
const providerUnavailable = activeProvider?.configured === false;
const isPageIndex = provider === "pageindex";
+ const isLightRagServer = provider === LIGHTRAG_SERVER_PROVIDER;
+ const serverModeOptions = activeProvider?.modes ?? [];
+ const effectiveServerMode =
+ serverMode || activeProvider?.default_mode || serverModeOptions[0] || "";
const policyForProvider: KnowledgeUploadPolicy = isPageIndex
? {
@@ -124,10 +157,16 @@ export default function CreateKbModal({
const trimmed = name.trim();
const trimmedPath = folderPath.trim();
+ const trimmedServerUrl = serverUrl.trim();
+
const canSubmit = (() => {
if (submitting) return false;
if (!trimmed) return false;
if (mode === "new") {
+ if (isLightRagServer) {
+ // The connection must pass the test before a KB is bound to it.
+ return !!trimmedServerUrl && !!serverProbe?.ok;
+ }
return !providerUnavailable && selection.validFiles.length > 0;
}
if (!trimmedPath) return false;
@@ -153,17 +192,43 @@ export default function CreateKbModal({
}
};
+ const handleTestServer = async () => {
+ if (!trimmedServerUrl || serverProbing) return;
+ setServerProbing(true);
+ setError(null);
+ try {
+ const result = await probeLightRagServer({
+ serverUrl: trimmedServerUrl,
+ apiKey: apiKey.trim(),
+ });
+ setServerProbe(result);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setServerProbing(false);
+ }
+ };
+
const handleSubmit = async () => {
if (!canSubmit) return;
setSubmitting(true);
setError(null);
try {
if (mode === "new") {
- await onCreate({
- name: trimmed,
- provider,
- files: selection.validFiles,
- });
+ if (isLightRagServer) {
+ await onConnectLightRagServer({
+ name: trimmed,
+ serverUrl: trimmedServerUrl,
+ apiKey: apiKey.trim(),
+ mode: effectiveServerMode,
+ });
+ } else {
+ await onCreate({
+ name: trimmed,
+ provider,
+ files: selection.validFiles,
+ });
+ }
} else if (linkIsObsidian) {
await onConnectObsidian({ name: trimmed, vaultPath: trimmedPath });
} else {
@@ -182,7 +247,13 @@ export default function CreateKbModal({
};
const submitLabel =
- mode === "new" ? t("Create") : linkIsObsidian ? t("Connect") : t("Link");
+ mode === "new"
+ ? isLightRagServer
+ ? t("Connect")
+ : t("Create")
+ : linkIsObsidian
+ ? t("Connect")
+ : t("Link");
return (
<Modal
@@ -211,7 +282,7 @@ export default function CreateKbModal({
>
{submitting ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : mode === "new" ? (
+ ) : mode === "new" && !isLightRagServer ? (
<Plus size={14} />
) : (
<Link2 size={14} />
@@ -257,6 +328,24 @@ export default function CreateKbModal({
files={files}
setFiles={setFiles}
policyForProvider={policyForProvider}
+ connectionForm={
+ isLightRagServer ? (
+ <LightRagServerFields
+ serverUrl={serverUrl}
+ setServerUrl={setServerUrl}
+ apiKey={apiKey}
+ setApiKey={setApiKey}
+ serverMode={effectiveServerMode}
+ setServerMode={setServerMode}
+ modeOptions={serverModeOptions}
+ submitting={submitting}
+ probing={serverProbing}
+ probe={serverProbe}
+ onTest={handleTestServer}
+ t={t}
+ />
+ ) : null
+ }
t={t}
/>
) : (
@@ -364,6 +453,7 @@ function NewModeFields({
files,
setFiles,
policyForProvider,
+ connectionForm,
t,
}: {
providers: RagProviderSummary[];
@@ -377,6 +467,8 @@ function NewModeFields({
files: File[];
setFiles: (files: File[]) => void;
policyForProvider: KnowledgeUploadPolicy;
+ /** When set, replaces the upload step (e.g. a server connection form). */
+ connectionForm?: ReactNode;
t: TFn;
}) {
return (
@@ -450,23 +542,166 @@ function NewModeFields({
)}
</div>
+ {connectionForm ?? (
+ <div>
+ <label className="mb-2 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
+ {t("Initial documents")}
+ {isPageIndex && (
+ <span className="ml-2 normal-case tracking-normal text-[var(--muted-foreground)]/80">
+ · {t("PDF and Markdown only")}
+ </span>
+ )}
+ </label>
+ <FileDropZone
+ files={files}
+ onChange={setFiles}
+ uploadPolicy={policyForProvider}
+ disabled={submitting}
+ />
+ </div>
+ )}
+ </>
+ );
+}
+
+function LightRagServerFields({
+ serverUrl,
+ setServerUrl,
+ apiKey,
+ setApiKey,
+ serverMode,
+ setServerMode,
+ modeOptions,
+ submitting,
+ probing,
+ probe,
+ onTest,
+ t,
+}: {
+ serverUrl: string;
+ setServerUrl: (value: string) => void;
+ apiKey: string;
+ setApiKey: (value: string) => void;
+ serverMode: string;
+ setServerMode: (value: string) => void;
+ modeOptions: string[];
+ submitting: boolean;
+ probing: boolean;
+ probe: LightRagServerProbe | null;
+ onTest: () => void;
+ t: TFn;
+}) {
+ return (
+ <div className="space-y-3">
<div>
- <label className="mb-2 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
- {t("Initial documents")}
- {isPageIndex && (
- <span className="ml-2 normal-case tracking-normal text-[var(--muted-foreground)]/80">
- · {t("PDF and Markdown only")}
- </span>
+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
+ {t("Server URL")}
+ </label>
+ <div className="flex gap-2">
+ <input
+ value={serverUrl}
+ onChange={(event) => setServerUrl(event.target.value)}
+ disabled={submitting}
+ placeholder={EXAMPLE_SERVER_URL}
+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"
+ />
+ <button
+ type="button"
+ onClick={onTest}
+ disabled={submitting || probing || serverUrl.trim().length === 0}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--ring)] disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ {probing ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Server className="h-3.5 w-3.5" />
+ )}
+ {t("Test connection")}
+ </button>
+ </div>
+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">
+ {t(
+ "The base URL of your running LightRAG server. Documents are indexed there — nothing is uploaded or copied.",
)}
+ </p>
+ </div>
+
+ <div>
+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
+ {t("API key")}
+ <span className="ml-2 normal-case tracking-normal text-[var(--muted-foreground)]/80">
+ · {t("optional")}
+ </span>
</label>
- <FileDropZone
- files={files}
- onChange={setFiles}
- uploadPolicy={policyForProvider}
+ <input
+ value={apiKey}
+ onChange={(event) => setApiKey(event.target.value)}
disabled={submitting}
+ type="password"
+ autoComplete="off"
+ placeholder={t("Only if your server requires one")}
+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"
/>
</div>
- </>
+
+ {modeOptions.length > 0 && (
+ <div>
+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
+ {t("Retrieval mode")}
+ </label>
+ <select
+ value={serverMode}
+ onChange={(event) => setServerMode(event.target.value)}
+ disabled={submitting}
+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"
+ >
+ {modeOptions.map((m) => (
+ <option key={m} value={m}>
+ {m}
+ </option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {probe && <ServerProbeVerdict probe={probe} t={t} />}
+ </div>
+ );
+}
+
+function ServerProbeVerdict({
+ probe,
+ t,
+}: {
+ probe: LightRagServerProbe;
+ t: TFn;
+}) {
+ if (!probe.ok) {
+ return (
+ <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">
+ <span className="flex items-center gap-1.5 font-medium">
+ <AlertTriangle className="h-3.5 w-3.5 shrink-0" />
+ {t("Could not connect")}
+ </span>
+ {probe.error && <p className="mt-1 leading-relaxed">{probe.error}</p>}
+ </div>
+ );
+ }
+ return (
+ <div className="space-y-1 rounded-lg border border-[var(--border)] bg-[var(--muted)]/40 px-3 py-2.5 text-[12px]">
+ <div className="flex items-center gap-1.5 font-medium text-emerald-700 dark:text-emerald-300">
+ <Check className="h-3.5 w-3.5 shrink-0" />
+ {t("Connected to LightRAG server")}
+ </div>
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11.5px] text-[var(--muted-foreground)]">
+ {probe.core_version && (
+ <span>{t("Core {{version}}", { version: probe.core_version })}</span>
+ )}
+ <span>
+ {probe.auth_required ? t("API key accepted") : t("Open access")}
+ </span>
+ </div>
+ </div>
);
}
diff --git a/web/components/knowledge/EngineDetail.tsx b/web/components/knowledge/EngineDetail.tsx
index 4b59bc232..1426d2dce 100644
--- a/web/components/knowledge/EngineDetail.tsx
+++ b/web/components/knowledge/EngineDetail.tsx
@@ -17,6 +17,7 @@ import {
Loader2,
Network,
RefreshCw,
+ Server,
Settings2,
ShieldCheck,
Workflow,
@@ -67,6 +68,7 @@ const ENGINE_ICONS: Record<string, LucideIcon> = {
pageindex: Cloud,
graphrag: Network,
lightrag: Workflow,
+ "lightrag-server": Server,
};
const INSTALL_HINTS: Record<string, string> = {
@@ -90,16 +92,25 @@ const MODE_DESCRIPTIONS: Record<string, string> = {
"lightrag:hybrid":
"Combines local and global retrieval — a solid general default.",
"lightrag:mix": "Fuses knowledge-graph and vector retrieval.",
+ "lightrag-server:naive": "Plain vector retrieval, without the knowledge graph.",
+ "lightrag-server:local": "Local context focused on the most relevant entities.",
+ "lightrag-server:global": "Theme-level retrieval over global relationships.",
+ "lightrag-server:hybrid":
+ "Combines local and global retrieval — a solid general default.",
+ "lightrag-server:mix":
+ "Fuses knowledge-graph and vector retrieval — the server's default.",
};
// Model kinds each engine needs (for the in-place pickers). "vision" isn't a
// catalog service — it rides on the active chat model — so LightRAG only lists
-// llm + embedding and shows a vision note under the chat picker.
+// llm + embedding and shows a vision note under the chat picker. LightRAG Server
+// owns its own models on the remote instance, so it needs none here.
const ENGINE_MODEL_KINDS: Record<string, ("llm" | "embedding")[]> = {
llamaindex: ["embedding"],
pageindex: [],
graphrag: ["llm", "embedding"],
lightrag: ["llm", "embedding"],
+ "lightrag-server": [],
};
const MODEL_KIND_LABEL: Record<string, string> = {
diff --git a/web/components/knowledge/KnowledgeHome.tsx b/web/components/knowledge/KnowledgeHome.tsx
index 7b79386aa..041d9f26a 100644
--- a/web/components/knowledge/KnowledgeHome.tsx
+++ b/web/components/knowledge/KnowledgeHome.tsx
@@ -13,6 +13,7 @@ import {
Network,
Plus,
Search,
+ Server,
Star,
Workflow,
type LucideIcon,
@@ -42,6 +43,7 @@ const ENGINE_ICONS: Record<string, LucideIcon> = {
pageindex: Cloud,
graphrag: Network,
lightrag: Workflow,
+ "lightrag-server": Server,
};
type EngineStatus = "ready" | "needs_key" | "unavailable";
diff --git a/web/components/knowledge/KnowledgePage.tsx b/web/components/knowledge/KnowledgePage.tsx
index 67b8db582..5b36112df 100644
--- a/web/components/knowledge/KnowledgePage.tsx
+++ b/web/components/knowledge/KnowledgePage.tsx
@@ -38,6 +38,7 @@ export default function KnowledgePage() {
deleteKb,
connectObsidian,
connectLinkedFolder,
+ connectLightRagServer,
} = useKnowledgeBases();
// Connected subagents are stored as ``type: subagent`` KBs so the chat
@@ -303,6 +304,7 @@ export default function KnowledgePage() {
onCreate={handleCreate}
onConnectLinkedFolder={connectLinkedFolder}
onConnectObsidian={connectObsidian}
+ onConnectLightRagServer={connectLightRagServer}
initialMode={createPreset?.mode}
initialSource={createPreset?.source}
onConfigureProvider={() => {
diff --git a/web/hooks/useKnowledgeBases.ts b/web/hooks/useKnowledgeBases.ts
index a7b607bc6..de6e3c617 100644
--- a/web/hooks/useKnowledgeBases.ts
+++ b/web/hooks/useKnowledgeBases.ts
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
+ connectLightRagServer as connectLightRagServerApi,
connectLinkedFolder as connectLinkedFolderApi,
connectObsidianVault as connectObsidianApi,
createKnowledgeBase as createKbApi,
@@ -320,6 +321,20 @@ export function useKnowledgeBases() {
[load],
);
+ const connectLightRagServer = useCallback(
+ async (params: {
+ name: string;
+ serverUrl: string;
+ apiKey?: string;
+ mode?: string;
+ }) => {
+ await connectLightRagServerApi(params);
+ invalidateKnowledgeCaches();
+ await load({ force: true, showSpinner: false });
+ },
+ [load],
+ );
+
return {
kbs: combinedKbs,
rawKbs: kbs,
@@ -342,6 +357,7 @@ export function useKnowledgeBases() {
deleteKb,
connectObsidian,
connectLinkedFolder,
+ connectLightRagServer,
};
}
diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.ts
index 716dca278..1e59b5d02 100644
--- a/web/lib/knowledge-api.ts
+++ b/web/lib/knowledge-api.ts
@@ -650,6 +650,76 @@ export async function connectLinkedFolder(payload: {
};
}
+export interface LightRagServerProbe {
+ /** Reachable, a LightRAG server, and (if required) the API key is accepted. */
+ ok: boolean;
+ base_url: string;
+ reachable: boolean;
+ auth_required: boolean;
+ auth_ok: boolean;
+ core_version: string | null;
+ api_version: string | null;
+ /** Set when the server can't be connected (unreachable, bad key, …). */
+ error: string | null;
+}
+
+export async function probeLightRagServer(payload: {
+ serverUrl: string;
+ apiKey?: string;
+}): Promise<LightRagServerProbe> {
+ const res = await apiFetch(
+ apiUrl("/api/v1/knowledge/probe-lightrag-server"),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ server_url: payload.serverUrl,
+ api_key: payload.apiKey ?? "",
+ }),
+ },
+ );
+ if (!res.ok) {
+ throw new Error(await readErrorDetail(res, "Failed to reach LightRAG server"));
+ }
+ return (await res.json()) as LightRagServerProbe;
+}
+
+export async function connectLightRagServer(payload: {
+ name: string;
+ serverUrl: string;
+ apiKey?: string;
+ mode?: string;
+}): Promise<{
+ status: string;
+ name: string;
+ server_url: string;
+ rag_provider: string;
+}> {
+ const res = await apiFetch(
+ apiUrl("/api/v1/knowledge/connect-lightrag-server"),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ name: payload.name,
+ server_url: payload.serverUrl,
+ api_key: payload.apiKey ?? "",
+ search_mode: payload.mode ?? "",
+ }),
+ },
+ );
+ if (!res.ok) {
+ throw new Error(await readErrorDetail(res, "Failed to connect LightRAG server"));
+ }
+ invalidateKnowledgeCaches();
+ return (await res.json()) as {
+ status: string;
+ name: string;
+ server_url: string;
+ rag_provider: string;
+ };
+}
+
export async function uploadKnowledgeBaseFiles(
name: string,
files: File[],
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 377fd91ed..b5c974df7 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -2656,5 +2656,13 @@
"Sign out": "Sign out",
"End your session on this device": "End your session on this device",
"Failed to load profile": "Failed to load profile",
- "Image is too large": "Image is too large"
+ "Image is too large": "Image is too large",
+ "Server URL": "Server URL",
+ "The base URL of your running LightRAG server. Documents are indexed there — nothing is uploaded or copied.": "The base URL of your running LightRAG server. Documents are indexed there — nothing is uploaded or copied.",
+ "Only if your server requires one": "Only if your server requires one",
+ "Could not connect": "Could not connect",
+ "Connected to LightRAG server": "Connected to LightRAG server",
+ "Core {{version}}": "Core {{version}}",
+ "API key accepted": "API key accepted",
+ "Open access": "Open access"
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index e76a705f6..2fcfb7e5b 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -2656,5 +2656,13 @@
"Sign out": "退出登录",
"End your session on this device": "结束此设备上的会话",
"Failed to load profile": "加载个人资料失败",
- "Image is too large": "图片过大"
+ "Image is too large": "图片过大",
+ "Server URL": "服务器地址",
+ "The base URL of your running LightRAG server. Documents are indexed there — nothing is uploaded or copied.": "你正在运行的 LightRAG 服务器的基础地址。文档在该服务器上建立索引——不会上传或复制任何内容。",
+ "Only if your server requires one": "仅当你的服务器需要时填写",
+ "Could not connect": "无法连接",
+ "Connected to LightRAG server": "已连接到 LightRAG 服务器",
+ "Core {{version}}": "内核 {{version}}",
+ "API key accepted": "API 密钥已通过",
+ "Open access": "开放访问"
}