Skip to content

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

feat(lightrag): configure independent role models and pinned vision indexing

NoxsMedia446b3aab7eb9
diff --git a/README.md b/README.md
index 83cb76932..f8a9e5b4b 100644
--- a/README.md
+++ b/README.md
@@ -224,7 +224,7 @@ DeepTutor is an agent-native learning workspace that connects tutoring, problem
- **Connected learning context** — Knowledge bases, books, Co-Writer drafts, notebooks, question banks, personas, and Memory can be reused across the workflows that support them, subject to account grants and learning policies.
- **Immersive video learning** — paste a YouTube link for privacy-enhanced native playback, synchronized captions, timestamp-grounded tutoring, and resumable progress; administrators can switch playback to a self-hosted Invidious instance without rebuilding materials.
- **Subagents and Partners** — from Chat, consult a live agent harness (Claude Code, Codex, Antigravity, Kimi, opencode, MiMo, Hermes, OpenClaw, or DeepSeek) or a Partner, import past conversations, and run persistent IM companions on the same brain.
-- **Multi-engine knowledge** — versioned RAG libraries across LlamaIndex, PageIndex, GraphRAG, LightRAG, a remote LightRAG Server, a self-hosted WeKnora knowledge base, a Tencent IMA or MarginNote 4 library, or a linked Obsidian vault, with pluggable document parsing.
+- **Multi-engine knowledge** — versioned RAG libraries across LlamaIndex, PageIndex, GraphRAG, LightRAG, a remote LightRAG Server, a self-hosted WeKnora knowledge base, a Tencent IMA or MarginNote 4 library, or a linked Obsidian vault, with pluggable document parsing. See [native LightRAG role models](deeptutor/services/rag/pipelines/lightrag/README.md) for independent extraction, query and vision settings.
- **Extensible tools and skills** — built-in tools, MCP servers, CLI apps, image / video / voice generation models, and installable community skills from EduHub.
- **Inspectable memory** — L1 traces, L2 surface summaries, and L3 synthesis make personalization visible and editable; the Memory Graph links L2 facts to L1 evidence and L3 synthesis to contributing surfaces.
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index 63d74924c..11bd553b7 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -206,6 +206,12 @@ class SupportedFileTypesInfo(BaseModel):
allow_any_extension: bool = False
+from deeptutor.services.config.lightrag_roles import (
+ LightRagIndexingSelection,
+ LightRagRoleModels,
+)
+
+
class IndexingLLMSelectionRequest(BaseModel):
"""Secret-free catalog identity for an empty LightRAG knowledge base."""
@@ -249,17 +255,32 @@ def _mark_kb_queued_for_processing(
``stage`` must be a member of the frontend's ``LIVE_PROGRESS_STAGES`` set
(web/lib/knowledge-helpers.ts).
"""
- manager.update_kb_status(
- name=kb_name,
- status=status,
- progress={
- "stage": "starting",
- "message": message,
- "percent": 0,
- "task_id": task_id,
- "timestamp": datetime.now().isoformat(),
- },
+ from contextlib import nullcontext
+
+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import IndexingPolicyError
+ from deeptutor.services.rag.pipelines.lightrag.write_lock import write_ownership
+
+ entry = manager.config.get("knowledge_bases", {}).get(kb_name) or {}
+ ownership = (
+ write_ownership(Path(manager.base_dir) / kb_name)
+ if entry.get("rag_provider") == LIGHTRAG_PROVIDER
+ else nullcontext()
)
+ try:
+ with ownership:
+ manager.update_kb_status(
+ name=kb_name,
+ status=status,
+ progress={
+ "stage": "starting",
+ "message": message,
+ "percent": 0,
+ "task_id": task_id,
+ "timestamp": datetime.now().isoformat(),
+ },
+ )
+ except IndexingPolicyError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
def _save_zip_archive(
@@ -668,18 +689,42 @@ def _freeze_indexing_llm_form(raw: str):
"""Parse and resolve the optional LightRAG selection exactly once."""
from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (
IndexingPolicyError,
- freeze_snapshot,
+ freeze_roles,
)
try:
selection = json.loads(raw)
if not isinstance(selection, dict) or not selection:
raise ValueError("indexing_llm must be a non-empty JSON object.")
- return selection, freeze_snapshot(selection)
+ return selection, freeze_roles(selection)
except (json.JSONDecodeError, ValueError, PermissionError, IndexingPolicyError) as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+def _freeze_append_indexing(
+ kb_name: str, base_dir, provider: str, image_analysis: bool | None = None
+):
+ if provider != LIGHTRAG_PROVIDER:
+ return None
+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (
+ IndexingPolicyError,
+ bind_target,
+ resolve_write_snapshot,
+ with_image_analysis,
+ )
+
+ kb_dir = Path(base_dir) / kb_name
+ try:
+ return with_image_analysis(
+ bind_target(
+ resolve_write_snapshot(kb_dir, base_dir=str(base_dir), kb_name=kb_name), kb_dir
+ ),
+ image_analysis,
+ )
+ except (ValueError, PermissionError, IndexingPolicyError) as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+
+
def _freeze_default_indexing_llm():
"""Freeze the released LightRAG model default for one create or rebuild."""
from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (
@@ -1013,6 +1058,7 @@ async def run_upload_processing_task(
folder_id: str = None,
folder_root: str = None,
owner=None,
+ accepted_indexing_snapshot=None,
):
"""Background task for processing uploaded files.
@@ -1037,6 +1083,7 @@ async def run_upload_processing_task(
rag_provider=rag_provider,
folder_id=folder_id,
folder_root=folder_root,
+ accepted_indexing_snapshot=accepted_indexing_snapshot,
)
finally:
reset_current_user(token)
@@ -1065,6 +1112,7 @@ async def run_upload_processing_task(
base_dir=base_dir,
progress_tracker=progress_tracker,
rag_provider=rag_provider,
+ accepted_indexing_snapshot=accepted_indexing_snapshot,
)
# Staging blocks: a full-content hash per file, plus a copy for
@@ -1484,6 +1532,7 @@ async def update_graphrag_pipeline_config(payload: GraphRagConfigUpdate):
class LightRagConfigUpdate(BaseModel):
"""Partial update for LightRAG query + indexing knobs (omitted fields kept)."""
+ role_models: LightRagRoleModels | None = None
top_k: int | None = None
response_type: str | None = None
max_concurrent_files: int | None = None
@@ -1527,7 +1576,15 @@ async def get_lightrag_pipeline_config():
raise HTTPException(status_code=500, detail=str(e))
[email protected]("/knowledge-bases/rag-pipelines/lightrag/config")
[email protected]("/knowledge-bases/rag-pipelines/lightrag/model-options")
+async def get_lightrag_model_options():
+ """Return accessible catalog models with supported role capabilities."""
+ from deeptutor.services.rag.pipelines.lightrag.roles import model_options
+
+ return model_options()
+
+
[email protected]("/knowledge-bases/rag-pipelines/lightrag/config", dependencies=[Depends(require_admin)])
async def update_lightrag_pipeline_config(payload: LightRagConfigUpdate):
"""Persist LightRAG's knobs.
@@ -1542,11 +1599,24 @@ async def update_lightrag_pipeline_config(payload: LightRagConfigUpdate):
current = service.load_lightrag()
updates = payload.model_dump(exclude_none=True)
candidate = {**current, **updates}
- _validate_lightrag_llm_selection(
- str(candidate.get("llm_profile_id") or ""),
- str(candidate.get("llm_model_id") or ""),
- )
- return service.save_lightrag({**current, **updates})
+ if "role_models" in payload.model_fields_set and payload.role_models is None:
+ raise HTTPException(status_code=422, detail="Role models cannot be cleared.")
+ if candidate.get("role_models") is not None:
+ from deeptutor.services.rag.pipelines.lightrag.roles import validate_models
+
+ if {"llm_profile_id", "llm_model_id"} & payload.model_fields_set:
+ raise HTTPException(
+ status_code=422, detail="Use role_models for this configuration."
+ )
+ validate_models(LightRagRoleModels.model_validate(candidate["role_models"]))
+ else:
+ _validate_lightrag_llm_selection(
+ str(candidate.get("llm_profile_id") or ""),
+ str(candidate.get("llm_model_id") or ""),
+ )
+ return service.save_lightrag(candidate)
+ except (ValueError, PermissionError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
except HTTPException:
raise
except Exception as e:
@@ -2850,6 +2920,10 @@ async def upload_files(
rag_provider: str = Form(None),
rel_paths: list[str] = Form(None),
dest_subdir: str = Form(None),
+ image_analysis: bool | None = Form(
+ None,
+ description="Require image analysis with the pinned VLM; false skips images, omitted follows the pinned policy.",
+ ),
):
"""Upload files to a knowledge base and process them in background.
@@ -2882,6 +2956,9 @@ async def upload_files(
),
)
_assert_provider_ready(kb_provider)
+ accepted_snapshot = _freeze_append_indexing(
+ kb_name, kb_base_dir, kb_provider, image_analysis
+ )
_enforce_provider_formats(kb_provider, files)
allowed_extensions = (
set()
@@ -2914,6 +2991,7 @@ async def upload_files(
background_tasks.add_task(
run_upload_processing_task,
+ accepted_indexing_snapshot=accepted_snapshot,
kb_name=kb_name,
base_dir=str(kb_base_dir),
uploaded_file_paths=uploaded_file_paths,
@@ -2947,6 +3025,46 @@ async def create_knowledge_base(
search_mode: str = Form(""),
rel_paths: list[str] = Form(None),
indexing_llm: str = Form(""),
+):
+ from contextlib import nullcontext
+
+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import IndexingPolicyError
+ from deeptutor.services.rag.pipelines.lightrag.write_lock import write_ownership
+
+ try:
+ valid_name = validate_knowledge_base_name(name)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ ownership = (
+ write_ownership(_current_kb_base_dir() / valid_name)
+ if rag_provider == LIGHTRAG_PROVIDER
+ else nullcontext()
+ )
+ try:
+ with ownership:
+ return await _create_knowledge_base_owned(
+ background_tasks,
+ name,
+ files,
+ rag_provider,
+ pageindex_mode,
+ search_mode,
+ rel_paths,
+ indexing_llm,
+ )
+ except IndexingPolicyError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+
+
+async def _create_knowledge_base_owned(
+ background_tasks: BackgroundTasks,
+ name: str = Form(...),
+ files: list[UploadFile] = File(default=[]),
+ rag_provider: str = Form(DEFAULT_PROVIDER),
+ pageindex_mode: str = Form(""),
+ search_mode: str = Form(""),
+ rel_paths: list[str] = Form(None),
+ indexing_llm: str = Form(""),
):
"""Create a new knowledge base and initialize it with files."""
try:
@@ -3053,6 +3171,12 @@ async def create_knowledge_base(
)
initializer.create_directory_structure()
+ if indexing_snapshot is not None:
+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import bind_target
+
+ initializer.indexing_snapshot = bind_target(
+ indexing_snapshot, kb_base_dir / name, protect_contents=True
+ )
progress_tracker.task_id = task_id
manager = get_kb_manager()
@@ -3205,87 +3329,97 @@ async def run_reindex_task(
# rather than being swallowed into a generic wrapper. A False
# return is reserved for "no documents to index" — surface that
# specifically too.
+ def persist_terminal_state(candidate_root=None):
+ if candidate_root is None:
+ completed_at = datetime.now().isoformat()
+ metadata_file = kb_dir / "metadata.json"
+ try:
+ metadata = {}
+ if metadata_file.exists():
+ with open(metadata_file, encoding="utf-8") as handle:
+ loaded_metadata = json.load(handle)
+ if isinstance(loaded_metadata, dict):
+ metadata = loaded_metadata
+ metadata["last_updated"] = completed_at
+ metadata["last_indexed_at"] = completed_at
+ metadata["last_indexed_count"] = len(file_paths)
+ metadata["last_indexed_action"] = "reindex"
+ atomic_write_json(metadata_file, metadata)
+ except Exception:
+ raise
+
+ progress_tracker.update(
+ ProgressStage.COMPLETED,
+ "Re-index complete",
+ current=len(file_paths),
+ total=len(file_paths),
+ indexed_count=len(file_paths),
+ index_changed=True,
+ index_action="reindex",
+ publication_version=candidate_root.name if candidate_root else None,
+ )
+ try:
+ with open(progress_tracker.progress_file, encoding="utf-8") as handle:
+ persisted_progress = json.load(handle)
+ except Exception as progress_err:
+ raise RuntimeError(
+ f"Re-index terminal state was not persisted for '{kb_name}'."
+ ) from progress_err
+ expected_terminal_progress = {
+ "stage": ProgressStage.COMPLETED.value,
+ "task_id": task_id,
+ "progress_percent": 100,
+ "current": len(file_paths),
+ "total": len(file_paths),
+ "indexed_count": len(file_paths),
+ "index_changed": True,
+ "index_action": "reindex",
+ }
+ if not isinstance(persisted_progress, dict) or any(
+ persisted_progress.get(key) != value
+ for key, value in expected_terminal_progress.items()
+ ):
+ raise RuntimeError(
+ f"Re-index terminal state was not persisted for '{kb_name}'."
+ )
+ manager = KnowledgeBaseManager(base_dir=str(base_path))
+ # ProgressTracker persists through its own manager instance. Refresh
+ # this cached instance before clearing flags so stale processing
+ # state cannot overwrite the completed status it just wrote.
+ manager.config = manager._load_config()
+ # Clear the legacy mismatch / needs_reindex flags now that an
+ # index version matching the active config exists on disk.
+ kb_entry = manager.config.get("knowledge_bases", {}).get(kb_name) or {}
+ if kb_entry.get("status") != ("processing" if candidate_root else "ready"):
+ raise RuntimeError(
+ f"Re-index terminal state was not persisted for '{kb_name}'."
+ )
+ if candidate_root is not None:
+ return
+ mutated = False
+ if kb_entry.get("needs_reindex"):
+ kb_entry["needs_reindex"] = False
+ mutated = True
+ if kb_entry.get("embedding_mismatch"):
+ kb_entry.pop("embedding_mismatch", None)
+ mutated = True
+ if mutated:
+ manager._save_config()
+
success = await rag_service.initialize(
kb_name=kb_name,
file_paths=file_paths,
progress_callback=_on_progress,
indexing_snapshot=indexing_snapshot,
+ before_publish=persist_terminal_state
+ if signature_hash == LIGHTRAG_PROVIDER
+ else None,
)
if not success:
raise RuntimeError(f"Re-index found no valid documents to index in '{kb_name}'.")
index_published = signature_hash == LIGHTRAG_PROVIDER
- completed_at = datetime.now().isoformat()
- metadata_file = kb_dir / "metadata.json"
- try:
- metadata = {}
- if metadata_file.exists():
- with open(metadata_file, encoding="utf-8") as handle:
- loaded_metadata = json.load(handle)
- if isinstance(loaded_metadata, dict):
- metadata = loaded_metadata
- metadata["last_updated"] = completed_at
- metadata["last_indexed_at"] = completed_at
- metadata["last_indexed_count"] = len(file_paths)
- metadata["last_indexed_action"] = "reindex"
- atomic_write_json(metadata_file, metadata)
- except Exception as meta_err:
- logger.warning(
- "Failed to update re-index metadata for '%s': %s",
- kb_name,
- meta_err,
- )
-
- progress_tracker.update(
- ProgressStage.COMPLETED,
- "Re-index complete",
- current=len(file_paths),
- total=len(file_paths),
- indexed_count=len(file_paths),
- index_changed=True,
- index_action="reindex",
- )
- try:
- with open(progress_tracker.progress_file, encoding="utf-8") as handle:
- persisted_progress = json.load(handle)
- except Exception as progress_err:
- raise RuntimeError(
- f"Re-index terminal state was not persisted for '{kb_name}'."
- ) from progress_err
- expected_terminal_progress = {
- "stage": ProgressStage.COMPLETED.value,
- "task_id": task_id,
- "progress_percent": 100,
- "current": len(file_paths),
- "total": len(file_paths),
- "indexed_count": len(file_paths),
- "index_changed": True,
- "index_action": "reindex",
- }
- if not isinstance(persisted_progress, dict) or any(
- persisted_progress.get(key) != value
- for key, value in expected_terminal_progress.items()
- ):
- raise RuntimeError(f"Re-index terminal state was not persisted for '{kb_name}'.")
- manager = get_kb_manager()
- # ProgressTracker persists through its own manager instance. Refresh
- # this cached instance before clearing flags so stale processing
- # state cannot overwrite the completed status it just wrote.
- manager.config = manager._load_config()
- # Clear the legacy mismatch / needs_reindex flags now that an
- # index version matching the active config exists on disk.
- kb_entry = manager.config.get("knowledge_bases", {}).get(kb_name) or {}
- if kb_entry.get("status") != "ready":
- raise RuntimeError(f"Re-index terminal state was not persisted for '{kb_name}'.")
- mutated = False
- if kb_entry.get("needs_reindex"):
- kb_entry["needs_reindex"] = False
- mutated = True
- if kb_entry.get("embedding_mismatch"):
- kb_entry.pop("embedding_mismatch", None)
- mutated = True
- if mutated:
- manager._save_config()
+ persist_terminal_state()
_task_log(task_id, f"Re-index of '{kb_name}' complete", level="success")
task_manager.update_task_status(task_id, "completed")
@@ -3355,6 +3489,10 @@ async def reindex_knowledge_base(
)
kb_dir = kb_base_dir / kb_name
+ if indexing_snapshot is not None:
+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import bind_target
+
+ indexing_snapshot = bind_target(indexing_snapshot, kb_dir, protect_contents=True)
signature_hash = kb_provider
if provider_uses_embedding_versions(kb_provider):
from deeptutor.services.rag.embedding_signature import signature_from_embedding_config
@@ -3424,7 +3562,22 @@ async def reindex_knowledge_base(
@router.put("/knowledge-bases/{kb_name}/indexing-policy")
async def update_pending_indexing_policy(
kb_name: str,
- payload: IndexingLLMSelectionRequest,
+ payload: LightRagIndexingSelection | IndexingLLMSelectionRequest,
+):
+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import IndexingPolicyError
+ from deeptutor.services.rag.pipelines.lightrag.write_lock import write_ownership
+
+ _, resolved_name, base_dir = _writable_kb(kb_name)
+ try:
+ with write_ownership(base_dir / resolved_name):
+ return await _update_pending_indexing_policy_owned(kb_name, payload)
+ except IndexingPolicyError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+
+
+async def _update_pending_indexing_policy_owned(
+ kb_name: str,
+ payload: LightRagIndexingSelection | IndexingLLMSelectionRequest,
):
"""Change the pending model of an empty, unpublished LightRAG KB."""
manager, kb_name, kb_base_dir = _writable_kb(kb_name)
@@ -3504,7 +3657,9 @@ async def update_pending_indexing_policy(
)
kb_entry["pending_indexing_policy"] = policy
manager._save_config()
- return {"indexing_policy": policy}
+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import public_policy
+
+ return {"indexing_policy": public_policy(policy)}
@router.post("/knowledge-bases/{kb_name}/retry")
@@ -3948,8 +4103,10 @@ async def sync_folder(kb_name: str, folder_id: str, background_tasks: Background
)
# Add background task to process files
+ accepted_snapshot = _freeze_append_indexing(kb_name, kb_base_dir, kb_provider)
background_tasks.add_task(
run_upload_processing_task,
+ accepted_indexing_snapshot=accepted_snapshot,
kb_name=kb_name,
base_dir=str(kb_base_dir),
uploaded_file_paths=files_to_process,
diff --git a/deeptutor/knowledge/add_documents.py b/deeptutor/knowledge/add_documents.py
index 8212af3b9..d4554bb97 100644
--- a/deeptutor/knowledge/add_documents.py
+++ b/deeptutor/knowledge/add_documents.py
@@ -158,6 +158,7 @@ class DocumentAdder:
base_url: str | None = None,
progress_tracker=None,
rag_provider: str | None = None,
+ accepted_indexing_snapshot=None,
):
self.kb_name = kb_name
self.base_dir = Path(base_dir)
@@ -196,6 +197,20 @@ class DocumentAdder:
if not has_provider_index and not allows_lightrag_bootstrap:
raise ValueError(f"Knowledge base not initialized ({self.rag_provider}): {kb_name}")
+ self.accepted_indexing_snapshot = accepted_indexing_snapshot
+ if self.rag_provider == LIGHTRAG_PROVIDER and self.accepted_indexing_snapshot is None:
+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (
+ bind_target,
+ resolve_write_snapshot,
+ )
+
+ self.accepted_indexing_snapshot = bind_target(
+ resolve_write_snapshot(
+ self.kb_dir, base_dir=str(self.base_dir), kb_name=self.kb_name
+ ),
+ self.kb_dir,
+ )
+
self.api_key = api_key
self.base_url = base_url
self.progress_tracker = progress_tracker
@@ -308,6 +323,9 @@ class DocumentAdder:
if not new_files:
return DocumentIndexResult(processed_files=[], failures=[])
+ if self.rag_provider == LIGHTRAG_PROVIDER:
+ return await self._process_lightrag_batch(new_files)
+
rag_service = RAGService(kb_base_dir=str(self.base_dir), provider=self.rag_provider)
processed_files: list[Path] = []
failures: list[DocumentIndexFailure] = []
@@ -363,6 +381,60 @@ class DocumentAdder:
return DocumentIndexResult(processed_files=processed_files, failures=failures)
+ async def _process_lightrag_batch(self, files: List[Path]) -> DocumentIndexResult:
+ """Hold native write ownership across the entire accepted batch."""
+ from deeptutor.services.rag.pipelines.lightrag.pipeline import LightRagBatchError
+
+ def prepare_publication(root: Path) -> None:
+ from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker
+
+ tracker = self.progress_tracker or ProgressTracker(self.kb_name, self.base_dir)
+ tracker.update(
+ ProgressStage.COMPLETED,
+ message="Document indexing complete",
+ current=len(files),
+ total=len(files),
+ indexed_count=len(files),
+ index_changed=True,
+ index_action="upload",
+ publication_version=root.name,
+ )
+ tracker.verify_terminal(
+ current=len(files),
+ total=len(files),
+ indexed_count=len(files),
+ index_action="upload",
+ publication_version=root.name,
+ )
+
+ service = RAGService(kb_base_dir=str(self.base_dir), provider=LIGHTRAG_PROVIDER)
+ try:
+ success = await service.add_documents(
+ self.kb_name,
+ [str(path) for path in files],
+ accepted_indexing_snapshot=self.accepted_indexing_snapshot,
+ before_publish=prepare_publication,
+ )
+ if not success:
+ raise RuntimeError("LightRAG returned failure without details.")
+ processed = files
+ failures = []
+ except LightRagBatchError as exc:
+ processed = [path for path in files if path.name in exc.outcome.processed]
+ failures = [
+ DocumentIndexFailure(path, str(exc)) for path in files if path not in processed
+ ]
+ except Exception as exc:
+ return DocumentIndexResult([], [DocumentIndexFailure(path, str(exc)) for path in files])
+ for path in processed:
+ try:
+ await asyncio.to_thread(self._record_successful_hash, path)
+ except Exception:
+ logger.warning(
+ "Indexed document hash could not be recorded: %s", path.name, exc_info=True
+ )
+ return DocumentIndexResult(processed, failures)
+
def _record_successful_hash(self, file_path: Path) -> None:
file_hash = self._get_file_hash(file_path)
metadata = _read_metadata(self.metadata_file)
@@ -486,6 +558,7 @@ async def add_documents(
api_key: Optional[str] = None,
base_url: Optional[str] = None,
allow_duplicates: bool = False,
+ accepted_indexing_snapshot=None,
) -> int:
"""Convenience function used by CLI wrappers."""
from deeptutor.knowledge.manager import KnowledgeBaseManager
@@ -514,6 +587,7 @@ async def add_documents(
base_dir=base_dir,
api_key=api_key,
base_url=base_url,
+ accepted_indexing_snapshot=accepted_indexing_snapshot,
)
except ValueError as exc:
if "not initialized" not in str(exc).lower() or not source_files:
diff --git a/deeptutor/knowledge/initializer.py b/deeptutor/knowledge/initializer.py
index 33eb935b2..ed725e171 100644
--- a/deeptutor/knowledge/initializer.py
+++ b/deeptutor/knowledge/initializer.py
@@ -14,7 +14,7 @@ from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from deeptutor.multi_user.models import CurrentUser
- from deeptutor.services.rag.pipelines.lightrag.indexing_policy import IndexingLLMSnapshot
+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import IndexingPolicySnapshot
from deeptutor.knowledge.naming import validate_knowledge_base_name
from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker
@@ -38,7 +38,7 @@ class KnowledgeBaseInitializer:
base_url: str | None = None,
progress_tracker: ProgressTracker | None = None,
rag_provider: str | None = None,
- indexing_snapshot: IndexingLLMSnapshot | None = None,
+ indexing_snapshot: IndexingPolicySnapshot | None = None,
owner: CurrentUser | None = None,
):
self.kb_name = validate_knowledge_base_name(kb_name)
@@ -208,6 +208,26 @@ class KnowledgeBaseInitializer:
total=total,
)
+ def _prepare_publication(candidate_root: Path) -> None:
+ self._update_metadata_with_provider(provider)
+ self.progress_tracker.update(
+ ProgressStage.COMPLETED,
+ message_key="Knowledge base initialization complete!",
+ current=1,
+ total=1,
+ indexed_count=len(doc_files),
+ index_changed=True,
+ index_action="create",
+ publication_version=candidate_root.name,
+ )
+ self.progress_tracker.verify_terminal(
+ current=1,
+ total=1,
+ indexed_count=len(doc_files),
+ index_action="create",
+ publication_version=candidate_root.name,
+ )
+
try:
success = await rag_service.initialize(
kb_name=self.kb_name,
@@ -215,6 +235,7 @@ class KnowledgeBaseInitializer:
progress_callback=_on_progress,
image_progress_callback=_on_image_progress,
indexing_snapshot=self.indexing_snapshot,
+ before_publish=_prepare_publication if provider == "lightrag" else None,
)
if not success:
self.progress_tracker.update(
@@ -226,13 +247,14 @@ class KnowledgeBaseInitializer:
self.index_published = provider == "lightrag"
try:
- self._update_metadata_with_provider(provider)
- self.progress_tracker.update(
- ProgressStage.PROCESSING_DOCUMENTS,
- message_key="Documents processed successfully",
- current=len(doc_files),
- total=len(doc_files),
- )
+ if provider != "lightrag":
+ self._update_metadata_with_provider(provider)
+ self.progress_tracker.update(
+ ProgressStage.PROCESSING_DOCUMENTS,
+ message_key="Documents processed successfully",
+ current=len(doc_files),
+ total=len(doc_files),
+ )
except Exception:
if not self.index_published:
raise
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index a5e2c5cfe..57ba9fc77 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -1404,7 +1404,12 @@ class KnowledgeBaseManager:
indexing_policy = (
pending if isinstance(pending, dict) else {"policy": "legacy_unpinned"}
)
- metadata["indexing_policy"] = indexing_policy
+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import public_policy
+
+ metadata["indexing_policy"] = public_policy(indexing_policy)
+ for version in index_versions:
+ if isinstance(version.get("indexing_policy"), dict):
+ version["indexing_policy"] = public_policy(version["indexing_policy"])
metadata.update(self._embedding_fields(kb_config))
diff --git a/deeptutor/knowledge/progress_tracker.py b/deeptutor/knowledge/progress_tracker.py
index b93d69e4a..e163ce66c 100644
--- a/deeptutor/knowledge/progress_tracker.py
+++ b/deeptutor/knowledge/progress_tracker.py
@@ -47,6 +47,27 @@ class ProgressStage(Enum):
ERROR = "error" # Error
+def visible_progress(progress: dict, kb_dir: Path) -> dict:
+ """A prepared native terminal record is visible only after publication."""
+ version = progress.get("publication_version")
+ if progress.get("stage") != "completed" or not version:
+ return progress
+ from deeptutor.services.rag.pipelines.lightrag.storage import meta_is_native_published
+
+ if isinstance(version, str) and Path(version).name == version and version not in {".", ".."}:
+ if meta_is_native_published(kb_dir / version):
+ return progress
+ return {
+ **progress,
+ "stage": "processing_documents",
+ "message": "Finalizing index publication",
+ "message_key": "Finalizing index publication",
+ "message_params": {},
+ "progress_percent": 99,
+ "index_changed": False,
+ }
+
+
class ProgressTracker:
"""Progress tracker"""
@@ -93,12 +114,14 @@ class ProgressTracker:
def _save_progress(self, progress: dict):
"""Save progress to kb_config.json and local .progress.json file"""
# Save to kb_config.json (centralized config)
+ stored_progress = progress
try:
from deeptutor.knowledge.manager import KnowledgeBaseManager
manager = KnowledgeBaseManager(base_dir=str(self.base_dir))
- # Determine status based on stage
+ # A prepared completion remains processing until its version is published.
+ progress = visible_progress(progress, self.kb_dir)
stage = progress.get("stage", "")
if stage == "completed":
status = "ready"
@@ -144,7 +167,7 @@ class ProgressTracker:
# Persist the last seen progress snapshot so websocket subscribers and
# page reloads can recover the live state without relying on in-memory callbacks.
try:
- atomic_write_json(self.progress_file, progress)
+ atomic_write_json(self.progress_file, stored_progress)
except Exception as e:
_logger_instance().warning(
"Failed to persist progress snapshot for '%s': %s", self.kb_name, e
@@ -165,6 +188,7 @@ class ProgressTracker:
index_action: str | None = None,
message_key: str | None = None,
message_params: dict[str, object] | None = None,
+ publication_version: str | None = None,
):
"""Update progress.
@@ -205,6 +229,12 @@ class ProgressTracker:
if retryable is not None:
progress["retryable"] = retryable
+ if publication_version is not None:
+ progress["publication_version"] = publication_version
+ persisted_progress = progress
+ progress = visible_progress(progress, self.kb_dir)
+ message = str(progress["message"])
+
# Output to logger (terminal and log file)
try:
logger = _logger_instance()
@@ -238,7 +268,7 @@ class ProgressTracker:
if error:
fallback_logger.error("%s [ProgressTracker] Error: %s", prefix, error)
- self._save_progress(progress)
+ self._save_progress(persisted_progress)
if self.task_id:
try:
@@ -250,12 +280,53 @@ class ProgressTracker:
self._notify(progress)
+ def verify_terminal(
+ self,
+ *,
+ current: int,
+ total: int,
+ indexed_count: int,
+ index_action: str,
+ publication_version: str | None = None,
+ ) -> None:
+ """Fail publication if either required terminal persistence write was lost."""
+ expected = {
+ "stage": "completed",
+ "task_id": self.task_id,
+ "current": current,
+ "total": total,
+ "indexed_count": indexed_count,
+ "index_changed": True,
+ "index_action": index_action,
+ "progress_percent": 100,
+ }
+ if publication_version is not None:
+ expected["publication_version"] = publication_version
+ try:
+ with self.progress_file.open(encoding="utf-8") as handle:
+ persisted = json.load(handle)
+ if not isinstance(persisted, dict) or any(
+ persisted.get(key) != value for key, value in expected.items()
+ ):
+ raise ValueError("Terminal progress does not match this task.")
+ from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+ manager = KnowledgeBaseManager(base_dir=str(self.base_dir))
+ entry = manager.get_kb_entry(self.kb_name) or {}
+ expected_status = "processing" if publication_version else "ready"
+ if entry.get("status") != expected_status:
+ raise ValueError("Knowledge-base status was not persisted.")
+ if publication_version and (entry.get("progress") or {}).get("task_id") != self.task_id:
+ raise ValueError("Knowledge-base progress belongs to another task.")
+ except Exception as exc:
+ raise RuntimeError("Index terminal state was not persisted.") from exc
+
def get_progress(self) -> dict | None:
"""Get current progress"""
if self.progress_file.exists():
try:
with open(self.progress_file, encoding="utf-8") as f:
- return json.load(f)
+ return visible_progress(json.load(f), self.kb_dir)
except Exception as e:
_logger_instance().debug(f"Failed to read progress file for '{self.kb_name}': {e}")
diff --git a/deeptutor/multi_user/model_access.py b/deeptutor/multi_user/model_access.py
index ed95eb6d4..1a8d8bb4b 100644
--- a/deeptutor/multi_user/model_access.py
+++ b/deeptutor/multi_user/model_access.py
@@ -106,6 +106,11 @@ def redacted_model_access(user_id: str | None = None) -> dict[str, list[dict[str
"supported_reasoning_efforts": (model or {}).get(
"codex_supported_reasoning_levels"
),
+ **{
+ f"declared_{key}": value
+ for key, value in ((model or {}).get("capabilities") or {}).items()
+ if key in {"reasoning", "vision"} and type(value) is bool
+ },
"source": "admin",
"available": model is not None,
}
@@ -140,6 +145,7 @@ def allowed_llm_options() -> dict[str, Any]:
"provider": item.get("provider") or "",
"reasoning_effort": item.get("reasoning_effort"),
"supported_reasoning_efforts": item.get("supported_reasoning_efforts"),
+ **{key: item[key] for key in ("declared_reasoning", "declared_vision") if key in item},
"source": item.get("source") or "admin",
"is_active_default": (
item.get("profile_id") == active_profile_id
diff --git a/deeptutor/multi_user/personal_models.py b/deeptutor/multi_user/personal_models.py
index 7a9c57b3e..595a3e97f 100644
--- a/deeptutor/multi_user/personal_models.py
+++ b/deeptutor/multi_user/personal_models.py
@@ -113,6 +113,11 @@ def personal_llm_rows() -> list[dict[str, Any]]:
"provider": profile.get("binding") or "",
"reasoning_effort": model.get("reasoning_effort"),
"supported_reasoning_efforts": model.get("codex_supported_reasoning_levels"),
+ **{
+ f"declared_{key}": value
+ for key, value in (model.get("capabilities") or {}).items()
+ if key in {"reasoning", "vision"} and type(value) is bool
+ },
"source": "personal",
"available": True,
}
diff --git a/deeptutor/services/config/lightrag_roles.py b/deeptutor/services/config/lightrag_roles.py
new file mode 100644
index 000000000..ef7500afb
--- /dev/null
+++ b/deeptutor/services/config/lightrag_roles.py
@@ -0,0 +1,91 @@
+"""Credential-free configuration contracts for native LightRAG roles.
+
+Parsing these contracts never resolves a model or mutates the model catalog.
+Runtime resolution stays in the LightRAG adapter so settings can be loaded even
+when an optional provider is not installed.
+"""
+
+from __future__ import annotations
+
+from typing import Literal, Self
+
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+ReasoningEffort = Literal["none", "minimal", "low", "medium", "high", "xhigh", "max", "adaptive"]
+
+
+class LightRagModelSelection(BaseModel):
+ model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
+
+ profile_id: str = Field(min_length=1, max_length=128)
+ model_id: str = Field(min_length=1, max_length=128)
+ reasoning_effort: ReasoningEffort | None = None
+
+
+class LightRagRoleModel(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ mode: Literal["inherit", "model"] = "inherit"
+ selection: LightRagModelSelection | None = None
+ reasoning_effort: ReasoningEffort | None = None
+ max_async: int = Field(default=4, ge=1, le=32, strict=True)
+ timeout: int = Field(default=240, ge=1, le=3600, strict=True)
+
+ @model_validator(mode="after")
+ def check_selection(self) -> Self:
+ if (self.mode == "model") != (self.selection is not None):
+ raise ValueError("Only an explicit model role requires a model selection.")
+ if self.selection is not None and self.selection.reasoning_effort is not None:
+ raise ValueError("Set role reasoning_effort on the role, not its model selection.")
+ return self
+
+
+class LightRagVisionModel(LightRagRoleModel):
+ mode: Literal["disabled", "inherit", "model"] = "disabled"
+
+ @model_validator(mode="after")
+ def check_disabled(self) -> Self:
+ if self.mode == "disabled" and self.reasoning_effort is not None:
+ raise ValueError("A disabled vision role cannot override reasoning effort.")
+ return self
+
+
+class LightRagRoleModels(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ base: LightRagModelSelection
+ extract: LightRagRoleModel = Field(default_factory=LightRagRoleModel)
+ keyword: LightRagRoleModel = Field(default_factory=LightRagRoleModel)
+ query: LightRagRoleModel = Field(default_factory=LightRagRoleModel)
+ vlm: LightRagVisionModel = Field(default_factory=LightRagVisionModel)
+
+ def selection_for(self, role: str) -> LightRagModelSelection | None:
+ override = getattr(self, role)
+ if override.mode == "disabled":
+ return None
+ selected = override.selection or self.base
+ if override.reasoning_effort is not None:
+ selected = selected.model_copy(update={"reasoning_effort": override.reasoning_effort})
+ return selected
+
+
+class LightRagIndexingVision(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ mode: Literal["disabled", "enabled"] = "disabled"
+ selection: LightRagModelSelection | None = None
+
+ @model_validator(mode="after")
+ def check_selection(self) -> Self:
+ if (self.mode == "enabled") != (self.selection is not None):
+ raise ValueError("Only enabled vision indexing requires a model selection.")
+ return self
+
+
+class LightRagIndexingSelection(BaseModel):
+ """Resolved create/rebuild overrides, without mutable engine inheritance."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ extract: LightRagModelSelection
+ vlm: LightRagIndexingVision = Field(default_factory=LightRagIndexingVision)
diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.py
index 0ef52bd64..2ec8a6dca 100644
--- a/deeptutor/services/config/runtime_settings.py
+++ b/deeptutor/services/config/runtime_settings.py
@@ -613,6 +613,17 @@ class RuntimeSettingsService:
return payload
def load_lightrag(self) -> dict[str, Any]:
+ path = self.path_for("lightrag")
+ if path.exists():
+ # Invalid role settings must never become legacy chat-model fallback.
+ with path.open(encoding="utf-8") as handle:
+ loaded = json.load(handle)
+ if not isinstance(loaded, dict):
+ raise ValueError("LightRAG settings must be an object.")
+ normalized = self._normalize_lightrag({**DEFAULT_LIGHTRAG_SETTINGS, **loaded})
+ if normalized != loaded:
+ _atomic_write_json(path, normalized)
+ return normalized
return self._load_or_create("lightrag", DEFAULT_LIGHTRAG_SETTINGS, self._normalize_lightrag)
def save_lightrag(self, settings: dict[str, Any]) -> dict[str, Any]:
@@ -955,7 +966,17 @@ class RuntimeSettingsService:
}
def _normalize_lightrag(self, settings: dict[str, Any]) -> dict[str, Any]:
- return {
+ from .lightrag_roles import LightRagRoleModels
+
+ # Missing means a released, legacy setting. Never turn malformed new
+ # configuration back into a legacy model fallback.
+ role_models = settings.get("role_models")
+ roles = (
+ LightRagRoleModels.model_validate(role_models).model_dump()
+ if "role_models" in settings
+ else None
+ )
+ result = {
"version": 1,
"top_k": _coerce_clamped_int(settings.get("top_k"), 60, 1, 200),
"response_type": self._normalize_response_type(settings.get("response_type")),
@@ -971,6 +992,9 @@ class RuntimeSettingsService:
"llm_profile_id": _string(settings.get("llm_profile_id"))[:128],
"llm_model_id": _string(settings.get("llm_model_id"))[:128],
}
+ if roles is not None:
+ result["role_models"] = roles
+ return result
def _normalize_lightrag_server(self, settings: dict[str, Any]) -> dict[str, Any]:
return {
diff --git a/deeptutor/services/github_source/sync.py b/deeptutor/services/github_source/sync.py
index 6cc2839d9..62dec9245 100644
--- a/deeptutor/services/github_source/sync.py
+++ b/deeptutor/services/github_source/sync.py
@@ -135,6 +135,29 @@ def _filter_markdown_entries(entries, path_prefix, glob):
async def sync_source(kb_name, source, *, base_dir=DEFAULT_BASE_DIR, client=None):
+ from deeptutor.services.rag.provider_binding import resolve_bound_provider
+
+ accepted_indexing_snapshot = None
+ if resolve_bound_provider(base_dir, kb_name) == "lightrag":
+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (
+ bind_target,
+ resolve_write_snapshot,
+ )
+
+ kb_dir = Path(base_dir) / kb_name
+ try:
+ accepted_indexing_snapshot = bind_target(
+ resolve_write_snapshot(kb_dir, base_dir=str(base_dir), kb_name=kb_name), kb_dir
+ )
+ except Exception as exc:
+ error = redact_sync_error(exc)
+ _record_sync_failure(kb_name, source, base_dir, error)
+ return SyncResult(ok=False, error=error)
+ indexing_options = (
+ {"accepted_indexing_snapshot": accepted_indexing_snapshot}
+ if accepted_indexing_snapshot is not None
+ else {}
+ )
client = client or GitHubClient()
kb_dir = Path(base_dir) / kb_name
raw_dir = kb_dir / "raw"
@@ -163,7 +186,16 @@ async def sync_source(kb_name, source, *, base_dir=DEFAULT_BASE_DIR, client=None
try:
if not old_sha:
result = await _full_sync(
- client, kb_name, raw_dir, repo, branch, path_prefix, glob, latest_sha, base_dir
+ client,
+ kb_name,
+ raw_dir,
+ repo,
+ branch,
+ path_prefix,
+ glob,
+ latest_sha,
+ base_dir,
+ **indexing_options,
)
else:
result = await _incremental_sync(
@@ -177,6 +209,7 @@ async def sync_source(kb_name, source, *, base_dir=DEFAULT_BASE_DIR, client=None
old_sha,
latest_sha,
base_dir,
+ **indexing_options,
)
except GitHubAPIError as exc:
error = redact_sync_error(exc)
@@ -207,7 +240,17 @@ async def sync_source(kb_name, source, *, base_dir=DEFAULT_BASE_DIR, client=None
async def _full_sync(
- client, kb_name, raw_dir, repo, branch, path_prefix, glob, latest_sha, base_dir
+ client,
+ kb_name,
+ raw_dir,
+ repo,
+ branch,
+ path_prefix,
+ glob,
+ latest_sha,
+ base_dir,
+ *,
+ accepted_indexing_snapshot=None,
):
tree = await client.get_tree(repo, branch, path_prefix=path_prefix, glob=glob)
entries = _filter_markdown_entries(tree, path_prefix, glob)
@@ -222,12 +265,32 @@ async def _full_sync(
dest.write_bytes(content)
downloaded.append(str(dest))
if downloaded:
- await _index_files(kb_name, downloaded, base_dir)
+ await _index_files(
+ kb_name,
+ downloaded,
+ base_dir,
+ **(
+ {"accepted_indexing_snapshot": accepted_indexing_snapshot}
+ if accepted_indexing_snapshot is not None
+ else {}
+ ),
+ )
return SyncResult(ok=True, files_added=len(downloaded))
async def _incremental_sync(
- client, kb_name, raw_dir, repo, branch, path_prefix, glob, old_sha, new_sha, base_dir
+ client,
+ kb_name,
+ raw_dir,
+ repo,
+ branch,
+ path_prefix,
+ glob,
+ old_sha,
+ new_sha,
+ base_dir,
+ *,
+ accepted_indexing_snapshot=None,
):
all_changes = await client.compare_commits(repo, old_sha, new_sha)
changes = _filter_markdown_changes(all_changes, path_prefix, glob)
@@ -250,7 +313,16 @@ async def _incremental_sync(
dest.write_bytes(content)
downloaded.append(str(dest))
if downloaded:
- await _index_files(kb_name, downloaded, base_dir)
+ await _index_files(
+ kb_name,
+ downloaded,
+ base_dir,
+ **(
+ {"accepted_indexing_snapshot": accepted_indexing_snapshot}
+ if accepted_indexing_snapshot is not None
+ else {}
+ ),
+ )
removed_count = 0
for rel in removed:
target = _contained_dest(raw_dir, rel)
@@ -266,12 +338,20 @@ async def _incremental_sync(
return SyncResult(ok=True, files_added=len(downloaded), files_removed=removed_count)
-async def _index_files(kb_name, file_paths, base_dir):
+async def _index_files(kb_name, file_paths, base_dir, *, accepted_indexing_snapshot=None):
if not file_paths:
return 0
from deeptutor.knowledge.add_documents import add_documents
count = await add_documents(
- kb_name=kb_name, source_files=file_paths, base_dir=base_dir, allow_duplicates=False
+ kb_name=kb_name,
+ source_files=file_paths,
+ base_dir=base_dir,
+ allow_duplicates=False,
+ **(
+ {"accepted_indexing_snapshot": accepted_indexing_snapshot}
+ if accepted_indexing_snapshot is not None
+ else {}
+ ),
)
return count or 0
diff --git a/deeptutor/services/model_selection/llm.py b/deeptutor/services/model_selection/llm.py
index e3c5b318f..0ff27097e 100644
--- a/deeptutor/services/model_selection/llm.py
+++ b/deeptutor/services/model_selection/llm.py
@@ -145,6 +145,10 @@ def list_llm_options(catalog: dict[str, Any]) -> dict[str, Any]:
option["supported_reasoning_efforts"] = [
str(level).strip().lower() for level in supported_levels if str(level).strip()
]
+ declared = model.get("capabilities") or {}
+ for capability in ("reasoning", "vision"):
+ if type(declared.get(capability)) is bool:
+ option[f"declared_{capability}"] = declared[capability]
options.append(option)
return {
diff --git a/deeptutor/services/model_selection/reasoning.py b/deeptutor/services/model_selection/reasoning.py
new file mode 100644
index 000000000..d7afae050
--- /dev/null
+++ b/deeptutor/services/model_selection/reasoning.py
@@ -0,0 +1,93 @@
+"""Reasoning choices accepted by the existing catalog-selection call path.
+
+Managed catalog declarations take precedence over family defaults. Keep the
+family defaults aligned with web/lib/reasoning-effort.ts; LightRAG consumes the
+returned choices for both validation and its selectors.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from .llm import VALID_REASONING_EFFORTS
+
+
+def supported_reasoning_efforts(
+ binding: str, model: str, *, metadata: dict[str, Any] | None = None
+) -> list[str]:
+ metadata = metadata or {}
+ declared = metadata.get("codex_supported_reasoning_levels")
+ if isinstance(declared, list):
+ return [level for level in (*VALID_REASONING_EFFORTS, "adaptive") if level in declared]
+ capabilities = metadata.get("capabilities") or {}
+ if capabilities.get("reasoning") is False:
+ return []
+ provider = binding.lower().replace("-", "_")
+ provider = {
+ "azure": "azure_openai",
+ "azureopenai": "azure_openai",
+ "google": "gemini",
+ "google_genai": "gemini",
+ "claude": "anthropic",
+ "openai_compatible": "custom",
+ "anthropic_compatible": "custom_anthropic",
+ }.get(provider, provider)
+ name = model.lower()
+ levels: list[str] = []
+ if provider == "gemini" or "gemini" in name:
+ if "gemini-3" in name or "gemini-2.5-pro" in name:
+ levels = ["minimal", "low", "medium", "high"]
+ elif "gemini-2.5" in name:
+ levels = ["none", "low", "medium", "high"]
+ else:
+ levels = ["low", "medium", "high"]
+ elif provider in {"anthropic", "custom_anthropic"} or "claude" in name:
+ if any(
+ part in name
+ for part in ("opus-4-7", "opus-4-8", "opus-5", "sonnet-5", "fable-5", "mythos-5")
+ ):
+ levels = ["none", "adaptive"]
+ elif any(
+ part in name
+ for part in (
+ "claude-3-7",
+ "claude-4",
+ "claude-sonnet-4",
+ "claude-opus-4",
+ "claude-haiku-4",
+ )
+ ):
+ levels = ["none", "low", "medium", "high"]
+ elif provider == "custom":
+ levels = ["none", "low", "medium", "high"]
+ elif provider in {
+ "deepseek",
+ "volcengine",
+ "volcengine_coding_plan",
+ "byteplus",
+ "byteplus_coding_plan",
+ "dashscope",
+ "minimax",
+ }:
+ if provider == "minimax" or any(
+ part in name
+ for part in (
+ "deepseek-reasoner",
+ "deepseek-v4-pro",
+ "qwen3",
+ "qwen-3",
+ "qwq",
+ "qwen-plus",
+ )
+ ):
+ levels = ["minimal", "high"]
+ elif provider in {"openai", "azure_openai", "openai_codex", "github_copilot"}:
+ if "gpt-5.6-sol" in name:
+ levels = ["none", "low", "medium", "high", "xhigh", "max"]
+ elif "gpt-5" in name or "codex" in name:
+ levels = ["minimal", "low", "medium", "high", "xhigh"]
+ elif any(part in name for part in ("o1", "o3", "o4")):
+ levels = ["low", "medium", "high"]
+ if not levels and capabilities.get("reasoning") is True:
+ levels = ["none", "low", "medium", "high"]
+ return levels
diff --git a/deeptutor/services/rag/pipelines/lightrag/README.md b/deeptutor/services/rag/pipelines/lightrag/README.md
new file mode 100644
index 000000000..7454750fe
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/lightrag/README.md
@@ -0,0 +1,56 @@
+# LightRAG role models
+
+In Knowledge Center, open the native LightRAG engine and choose a base model.
+The saved base is independent of the chat model and the embedding model.
+Shared engine settings require administrator access when authentication is enabled.
+
+| Role | Used for | Available sources |
+| --- | --- | --- |
+| EXTRACT | Entity/relation extraction, structured tables and equations | Base or explicit model |
+| KEYWORD | Query keyword extraction | Base or explicit model |
+| QUERY | Answer generation | Base or explicit model |
+| VLM | Requested image analysis | Disabled, base or explicit vision model |
+
+New role configurations disable VLM by default. Inheriting the base for VLM
+requires a model that supports image inputs. Disabling VLM preserves text,
+table and equation processing. An explicit image-analysis request on a disabled
+index fails with full-rebuild guidance.
+
+Each enabled role can override supported reasoning effort. An unspecified value
+inherits the selected model's saved default; `none` explicitly disables reasoning
+where supported. Unsupported choices are rejected without substituting another
+model or reasoning level. Concurrency and timeout limits apply per role to
+subsequent tasks and do not require rebuilding. Accepted tasks keep their effective
+models, reasoning and limits while queued and running.
+
+## Creating, appending and rebuilding
+
+Creation and full rebuild dialogs prefill EXTRACT and VLM from engine settings.
+You may change both for that index. An empty, idle knowledge base also allows
+editing its pending selection before first publication.
+
+After publication, uploads and folder/GitHub sync use the index's pinned EXTRACT
+and VLM identities. Changing engine defaults does not change an existing index.
+Enabling, disabling or replacing VLM, or replacing EXTRACT or their reasoning
+configuration, requires a full rebuild. If a valid VLM was pinned before the first
+image, later image uploads can use it without another rebuild.
+
+The index details show pending or published model provenance, effective vision
+state and whether VLM was used. A failed or cancelled rebuild keeps the previous
+published index. A queued operation whose target changed fails before writing;
+resubmit it against the current index. Concurrent writers for one knowledge base
+are rejected, so wait for the active operation to finish before resubmitting.
+
+## Existing settings and indexes
+
+Legacy engine settings are prefilled from an accessible existing selection.
+Saving detaches the LightRAG base from chat. Missing or inaccessible selections
+must be replaced explicitly.
+
+Verifiable legacy single-model indexes retain their original model fingerprint
+and recorded vision state without a format-only rebuild. Unknown historical
+identity remains queryable but blocks incremental writes until a full rebuild.
+Malformed policies and models that have been deleted, changed identity or lost
+access cannot silently acquire current defaults. Credential rotation alone does
+not change the pinned identity; credentials are resolved privately for execution
+and are excluded from persisted index policy and public provenance.
diff --git a/deeptutor/services/rag/pipelines/lightrag/config.py b/deeptutor/services/rag/pipelines/lightrag/config.py
index 6f45e3365..568e5b16b 100644
--- a/deeptutor/services/rag/pipelines/lightrag/config.py
+++ b/deeptutor/services/rag/pipelines/lightrag/config.py
@@ -227,18 +227,24 @@ def lightrag_indexing_selection_from_settings() -> dict[str, str] | None:
def resolve_lightrag_query_llm_config():
- """Resolve the current LightRAG query model with the released fallback contract."""
+ """Resolve legacy settings, access-checking the active fallback as well."""
+ from deeptutor.multi_user.model_access import apply_allowed_llm_selection
from deeptutor.services.model_selection.runtime import resolve_llm_config_for_selection
- selection = lightrag_llm_selection_from_settings()
+ from .indexing_policy import _active_catalog_selection
+
+ selection = lightrag_llm_selection_from_settings() or _active_catalog_selection()
+ if selection is None:
+ raise LightRagNotConfiguredError("Choose an accessible LightRAG model in engine settings.")
+ apply_allowed_llm_selection(selection)
try:
return resolve_llm_config_for_selection(selection)
except ValueError:
- logger.warning(
- "LightRAG LLM selection %s no longer exists in the catalog; using the active model",
- selection,
- )
- return resolve_llm_config_for_selection(None)
+ fallback = _active_catalog_selection()
+ if fallback is None or fallback == selection:
+ raise
+ apply_allowed_llm_selection(fallback)
+ return resolve_llm_config_for_selection(fallback)
def build_llm_model_func(
diff --git a/deeptutor/services/rag/pipelines/lightrag/engine.py b/deeptutor/services/rag/pipelines/lightrag/engine.py
index 3b5f2cb85..0d4a7b0b6 100644
--- a/deeptutor/services/rag/pipelines/lightrag/engine.py
+++ b/deeptutor/services/rag/pipelines/lightrag/engine.py
@@ -19,7 +19,6 @@ from .config import (
indexing_kwargs_from_settings,
normalize_mode,
query_kwargs_from_settings,
- resolve_lightrag_query_llm_config,
)
from .ingress import IngressError, StagedDocument, pending_root
from .worker import OwnerLoopBridge
@@ -189,6 +188,7 @@ def build_rag(
io_bridge: OwnerLoopBridge | None = None,
enable_vlm: bool = False,
indexing_snapshot: Any | None = None,
+ query_roles: dict[str, Any] | None = None,
) -> Any:
"""Construct one exact-version, version-isolated LightRAG instance."""
_require_exact_version()
@@ -200,74 +200,58 @@ def build_rag(
if io_bridge is not None:
llm_adapter_kwargs["io_bridge"] = io_bridge
embedding_adapter_kwargs["io_bridge"] = io_bridge
- from .indexing_policy import cache_identity_for_config
-
- query_config = resolve_lightrag_query_llm_config()
- query_func = build_llm_model_func(
- **llm_adapter_kwargs,
- llm_config=query_config,
- )
- query_identity = cache_identity_for_config(query_config)
- query_metadata = {
- "binding": query_config.binding,
- "model": query_identity,
- }
+ from .indexing_policy import cache_identity, cache_identity_for_config
+ from .roles import resolve_query_roles
+
+ role_configs: dict[str, Any] = {}
+ if indexing_snapshot is None:
+ calls = query_roles if query_roles is not None else resolve_query_roles()
+ for role, call in calls.items():
+ role_configs[role] = RoleLLMConfig(
+ func=build_llm_model_func(
+ **llm_adapter_kwargs, llm_config=call.config, owner=call.owner
+ ),
+ metadata={
+ "binding": call.config.binding,
+ "model": cache_identity_for_config(call.config),
+ },
+ max_async=call.max_async,
+ timeout=call.timeout,
+ )
+ base = calls["query"]
+ base_config, base_owner = base.config, base.owner
+ base_identity = cache_identity_for_config(base_config)
+ else:
+ base = indexing_snapshot.extract
+ base_config, base_owner = base.config, base.owner
+ base_identity = cache_identity(base)
+ for role, snapshot in (("extract", base), ("vlm", indexing_snapshot.vlm)):
+ if snapshot is None or (role == "vlm" and not enable_vlm):
+ continue
+ builder = build_vision_model_func if role == "vlm" else build_llm_model_func
+ role_configs[role] = RoleLLMConfig(
+ func=builder(
+ **llm_adapter_kwargs, llm_config=snapshot.config, owner=snapshot.owner
+ ),
+ metadata={"binding": snapshot.config.binding, "model": cache_identity(snapshot)},
+ **indexing_snapshot.limits.get(role, {}),
+ )
+ if enable_vlm and (indexing_snapshot is None or indexing_snapshot.vlm is None):
+ raise LightRagContractError("Image analysis requires a pinned VLM; run a full re-index.")
constructor = {
"working_dir": str(Path(working_dir)),
"workspace": workspace_for(working_dir),
- "llm_model_func": query_func,
- "llm_model_name": query_identity,
+ "llm_model_func": build_llm_model_func(
+ **llm_adapter_kwargs, llm_config=base_config, owner=base_owner
+ ),
+ "llm_model_name": base_identity,
"embedding_func": build_embedding_func(**embedding_adapter_kwargs),
"auto_manage_storages_states": False,
"vlm_process_enable": bool(enable_vlm),
**indexing_kwargs_from_settings(),
**constructor_kwargs_from_settings(),
+ "role_llm_configs": role_configs,
}
- role_configs: dict[str, Any] = {
- "keyword": RoleLLMConfig(func=query_func, metadata=query_metadata),
- "query": RoleLLMConfig(func=query_func, metadata=query_metadata),
- }
- if indexing_snapshot is not None:
- from .indexing_policy import cache_identity
-
- snapshot_kwargs = {
- **llm_adapter_kwargs,
- "llm_config": indexing_snapshot.config,
- "owner": indexing_snapshot.owner,
- }
- metadata = {
- "binding": indexing_snapshot.config.binding,
- "model": cache_identity(indexing_snapshot),
- "host": indexing_snapshot.descriptor.get("endpoint"),
- }
- role_configs["extract"] = RoleLLMConfig(
- func=build_llm_model_func(**snapshot_kwargs), metadata=metadata
- )
- if enable_vlm:
- if indexing_snapshot is None:
- raise LightRagContractError(
- "LightRAG vision indexing requires a frozen indexing-model policy."
- )
- vision_kwargs = llm_adapter_kwargs
- metadata = None
- if indexing_snapshot is not None:
- from .indexing_policy import cache_identity
-
- vision_kwargs = {
- **llm_adapter_kwargs,
- "llm_config": indexing_snapshot.config,
- "owner": indexing_snapshot.owner,
- }
- metadata = {
- "binding": indexing_snapshot.config.binding,
- "model": cache_identity(indexing_snapshot),
- "host": indexing_snapshot.descriptor.get("endpoint"),
- }
- role_configs["vlm"] = RoleLLMConfig(
- func=build_vision_model_func(**vision_kwargs), metadata=metadata
- )
- if role_configs:
- constructor["role_llm_configs"] = role_configs
return _controlled_class()(**constructor)
diff --git a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py
index bbfa81284..5c2ae1815 100644
--- a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py
+++ b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from dataclasses import dataclass
+from dataclasses import dataclass, field, replace
import hashlib
import json
from pathlib import Path
@@ -152,8 +152,7 @@ def freeze_snapshot(
def pending_policy_for_selection(selection_value: Any) -> dict[str, Any]:
- snapshot = freeze_snapshot(selection_value, policy=POLICY_PENDING)
- return snapshot.persisted_policy()
+ return freeze_roles(selection_value, policy=POLICY_PENDING).persisted_policy()
def _active_catalog_selection() -> dict[str, str] | None:
@@ -168,7 +167,7 @@ def _active_catalog_selection() -> dict[str, str] | None:
return {"profile_id": profile_id, "model_id": model_id}
-def freeze_default_snapshot() -> IndexingLLMSnapshot:
+def _freeze_legacy_default_snapshot() -> IndexingLLMSnapshot:
"""Freeze the released LightRAG model, or the active model when it is unset."""
from .config import lightrag_indexing_selection_from_settings
@@ -187,9 +186,13 @@ def freeze_default_snapshot() -> IndexingLLMSnapshot:
)
-def snapshot_from_persisted(policy: dict[str, Any]) -> IndexingLLMSnapshot:
+def _single_snapshot_from_persisted(policy: dict[str, Any]) -> IndexingLLMSnapshot:
+ if type(policy.get("vision_available")) is not bool:
+ raise IndexingModelChangedError(
+ "The historical vision capability is unknown; run a full re-index."
+ )
selection = policy.get("selection")
- if selection is not None and not isinstance(selection, dict):
+ if not isinstance(selection, dict):
raise IndexingPolicyError("Pinned LightRAG metadata has an invalid model selection.")
snapshot = freeze_snapshot(selection, policy=POLICY_PINNED)
expected = str(policy.get("fingerprint") or "")
@@ -201,6 +204,283 @@ def snapshot_from_persisted(policy: dict[str, Any]) -> IndexingLLMSnapshot:
return snapshot
+@dataclass(frozen=True, slots=True)
+class IndexingPolicySnapshot:
+ extract: IndexingLLMSnapshot
+ vlm: IndexingLLMSnapshot | None
+ policy: str = POLICY_PINNED
+ limits: dict[str, dict[str, int]] = field(default_factory=dict)
+ legacy_policy: dict[str, Any] | None = None
+ target_version: str | None = None
+ target_bound: bool = False
+ target_policy: str | None = None
+ image_analysis: bool | None = None
+ target_revision: str | None = None
+
+ @property
+ def vision_available(self) -> bool:
+ return self.vlm is not None and self.vlm.vision_available
+
+ def persisted_policy(self) -> dict[str, Any]:
+ if self.legacy_policy is not None:
+ # Appending must not rewrite the old fingerprint as a v2 identity.
+ return dict(self.legacy_policy)
+ return {
+ "schema_version": 2,
+ "policy": self.policy,
+ "extract": self.extract.persisted_policy(),
+ "vlm": {
+ "mode": "enabled" if self.vlm else "disabled",
+ **({"snapshot": self.vlm.persisted_policy()} if self.vlm else {}),
+ },
+ }
+
+
+def _role_identity(snapshot: IndexingLLMSnapshot, *, vision: bool) -> dict[str, Any]:
+ config = snapshot.config
+ return {
+ **_canonical_identity(
+ snapshot.selection,
+ config,
+ vision_available=snapshot.vision_available if vision else None,
+ ),
+ "wire_api": config.wire_api,
+ "api_format": config.api_format,
+ "context_window": config.context_window,
+ }
+
+
+def _with_role_identity(snapshot: IndexingLLMSnapshot, *, vision: bool) -> IndexingLLMSnapshot:
+ snapshot = replace(
+ snapshot,
+ selection=replace(snapshot.selection, reasoning_effort=snapshot.config.reasoning_effort),
+ )
+ identity = _role_identity(snapshot, vision=vision)
+ return replace(snapshot, descriptor=identity, fingerprint=_fingerprint(identity))
+
+
+def _freeze_role(selection_value: Any, *, vision: bool = False) -> IndexingLLMSnapshot:
+ from deeptutor.services.config.lightrag_roles import LightRagModelSelection
+
+ from .roles import resolve_selection
+
+ if isinstance(selection_value, LLMSelection):
+ selection_value = selection_value.to_dict()
+ selected = LightRagModelSelection.model_validate(selection_value)
+ selection = LLMSelection(**selected.model_dump())
+ try:
+ config = resolve_selection(selection, vision=vision)
+ except (ValueError, PermissionError, LLMConfigError) as exc:
+ raise IndexingPolicyError(str(exc)) from exc
+ explicit_user = get_current_user_or_none()
+ if config.binding in OWNER_BOUND_BINDINGS and explicit_user is None:
+ raise IndexingPolicyError(
+ "Owner-bound indexing models require an explicit initiating user scope."
+ )
+ snapshot = IndexingLLMSnapshot(
+ config=config,
+ owner=explicit_user or get_current_user(),
+ policy=POLICY_PINNED,
+ selection=replace(selection, reasoning_effort=config.reasoning_effort),
+ descriptor={},
+ fingerprint=None,
+ vision_available=supports_vision(config.binding, config.model),
+ )
+ return _with_role_identity(snapshot, vision=vision)
+
+
+def freeze_roles(
+ selection_value: Any = None, *, policy: str = POLICY_PINNED
+) -> IndexingPolicySnapshot:
+ """Freeze create/rebuild choices; old request bodies still mean one model."""
+ from deeptutor.services.config import load_lightrag_settings
+ from deeptutor.services.config.lightrag_roles import LightRagIndexingSelection
+
+ from .roles import runtime_limits, settings_models
+
+ settings = load_lightrag_settings()
+ models = settings_models(settings)
+ limits = runtime_limits(settings)
+ if selection_value is None and models is not None:
+ extract_selection = models.selection_for("extract").model_dump()
+ vlm_selection = models.selection_for("vlm")
+ value = {
+ "extract": extract_selection,
+ "vlm": {"mode": "enabled", "selection": vlm_selection.model_dump()}
+ if vlm_selection
+ else {"mode": "disabled"},
+ }
+ elif (
+ selection_value is not None
+ and isinstance(selection_value, dict)
+ and "extract" in selection_value
+ ):
+ value = selection_value
+ else:
+ # Supported v1 settings and form producer: freeze the one known model,
+ # including its known vision capability, before constructing v2 roles.
+ single = (
+ freeze_snapshot(selection_value, policy=POLICY_PINNED)
+ if selection_value is not None
+ else _freeze_legacy_default_snapshot()
+ )
+ if single.selection is None:
+ raise IndexingPolicyError("Choose a catalog model before creating a LightRAG index.")
+ selected = single.selection.to_dict()
+ value = {
+ "extract": selected,
+ "vlm": {"mode": "enabled", "selection": selected}
+ if single.vision_available
+ else {"mode": "disabled"},
+ }
+ parsed = LightRagIndexingSelection.model_validate(value)
+ extract = _freeze_role(parsed.extract.model_dump())
+ vlm = (
+ _freeze_role(parsed.vlm.selection.model_dump(), vision=True)
+ if parsed.vlm.selection
+ else None
+ )
+ return IndexingPolicySnapshot(extract, vlm, policy=policy, limits=limits)
+
+
+def freeze_default_snapshot() -> IndexingPolicySnapshot:
+ return freeze_roles()
+
+
+def snapshot_from_persisted(policy: dict[str, Any]) -> IndexingPolicySnapshot:
+ from deeptutor.services.config import load_lightrag_settings
+
+ from .roles import runtime_limits
+
+ if not isinstance(policy, dict) or policy.get("policy") not in {POLICY_PINNED, POLICY_PENDING}:
+ raise IndexingModelChangedError(
+ "The index has no verified model policy; run a full re-index."
+ )
+ limits = runtime_limits(load_lightrag_settings())
+ if "schema_version" not in policy:
+ single = _single_snapshot_from_persisted(policy)
+ if policy["policy"] == POLICY_PENDING:
+ return IndexingPolicySnapshot(
+ _with_role_identity(single, vision=False),
+ _with_role_identity(single, vision=True) if single.vision_available else None,
+ policy=POLICY_PENDING,
+ limits=limits,
+ )
+ return IndexingPolicySnapshot(
+ single,
+ single if single.vision_available else None,
+ policy=policy["policy"],
+ limits=limits,
+ legacy_policy=dict(policy),
+ )
+ if type(policy["schema_version"]) is not int or policy["schema_version"] != 2:
+ raise IndexingPolicyError("Unsupported LightRAG indexing-policy version.")
+ vision = policy.get("vlm")
+ if not isinstance(vision, dict) or vision.get("mode") not in {"disabled", "enabled"}:
+ raise IndexingPolicyError("Invalid LightRAG vision policy.")
+ if vision["mode"] == "disabled" and "snapshot" in vision:
+ raise IndexingPolicyError("A disabled VLM cannot have an indexing snapshot.")
+
+ def restore(value: Any, *, vision: bool = False) -> IndexingLLMSnapshot:
+ if not isinstance(value, dict) or not isinstance(value.get("selection"), dict):
+ raise IndexingPolicyError("Invalid LightRAG role snapshot.")
+ result = _freeze_role(value["selection"], vision=vision)
+ if not value.get("fingerprint") or result.fingerprint != value["fingerprint"]:
+ raise IndexingModelChangedError("The pinned role model changed; run a full re-index.")
+ return result
+
+ return IndexingPolicySnapshot(
+ restore(policy.get("extract")),
+ restore(vision.get("snapshot"), vision=True) if vision["mode"] == "enabled" else None,
+ policy=policy["policy"],
+ limits=limits,
+ )
+
+
+def revalidate_snapshot(snapshot: IndexingPolicySnapshot) -> IndexingPolicySnapshot:
+ """Refresh credentials and permissions without changing frozen task settings."""
+ from deeptutor.multi_user.paths import user_context
+
+ with user_context(snapshot.extract.owner):
+ fresh = snapshot_from_persisted(snapshot.persisted_policy())
+ return replace(
+ fresh,
+ limits=snapshot.limits,
+ target_version=snapshot.target_version,
+ target_bound=snapshot.target_bound,
+ target_policy=snapshot.target_policy,
+ image_analysis=snapshot.image_analysis,
+ target_revision=snapshot.target_revision,
+ )
+
+
+def _target_policy_key(kb_dir: Path) -> str | None:
+ policy = effective_policy(kb_dir, base_dir=str(kb_dir.parent), kb_name=kb_dir.name)
+ return (
+ _fingerprint({key: value for key, value in policy.items() if key != "vlm_used"})
+ if policy is not None
+ else None
+ )
+
+
+def _content_revision(root: Path | None) -> str:
+ # Native document-status flushes are atomic. Track inode and nanosecond
+ # timestamps as well as size so a same-version append invalidates a queued rebuild.
+ revisions = {}
+ if root is not None:
+ for name in ("meta.json", "kv_store_doc_status.json"):
+ try:
+ stat = (root / name).stat()
+ revisions[name] = [stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns]
+ except FileNotFoundError:
+ revisions[name] = None
+ return _fingerprint(revisions)
+
+
+def bind_target(
+ snapshot: IndexingPolicySnapshot, kb_dir: Path, *, protect_contents: bool = False
+) -> IndexingPolicySnapshot:
+ from .storage import latest_published_root
+
+ target = latest_published_root(kb_dir)
+ return replace(
+ snapshot,
+ target_version=str(target) if target else None,
+ target_bound=True,
+ target_policy=_target_policy_key(kb_dir),
+ target_revision=_content_revision(target) if protect_contents else None,
+ )
+
+
+def validate_target(snapshot: IndexingPolicySnapshot, kb_dir: Path) -> None:
+ from .storage import latest_published_root
+
+ if not snapshot.target_bound:
+ return
+ target = latest_published_root(kb_dir)
+ if (
+ snapshot.target_version != (str(target) if target else None)
+ or snapshot.target_policy != _target_policy_key(kb_dir)
+ or (
+ snapshot.target_revision is not None
+ and snapshot.target_revision != _content_revision(target)
+ )
+ ):
+ raise IndexingPolicyError(
+ "The target index or pending policy changed while queued; resubmit this operation."
+ )
+
+
+def with_image_analysis(
+ snapshot: IndexingPolicySnapshot, requested: bool | None
+) -> IndexingPolicySnapshot:
+ if requested is True and not snapshot.vision_available:
+ raise IndexingModelChangedError(
+ "Image analysis is disabled for this index; run a full re-index with a VLM."
+ )
+ return replace(snapshot, image_analysis=requested)
+
+
def effective_policy(kb_dir: Path, *, base_dir: str, kb_name: str) -> dict[str, Any] | None:
"""Return published policy first, then pre-publication pending policy."""
from .storage import latest_published_root, read_published_policy
@@ -215,7 +495,9 @@ def effective_policy(kb_dir: Path, *, base_dir: str, kb_name: str) -> dict[str,
manager = KnowledgeBaseManager(base_dir=base_dir)
entry = manager.config.get("knowledge_bases", {}).get(kb_name) or {}
pending = entry.get("pending_indexing_policy")
- return pending if isinstance(pending, dict) else None
+ if pending is not None and not isinstance(pending, dict):
+ raise IndexingPolicyError("Invalid pending LightRAG indexing policy.")
+ return pending
def resolve_write_snapshot(
@@ -223,8 +505,8 @@ def resolve_write_snapshot(
*,
base_dir: str,
kb_name: str,
- explicit: IndexingLLMSnapshot | None = None,
-) -> IndexingLLMSnapshot:
+ explicit: IndexingPolicySnapshot | None = None,
+) -> IndexingPolicySnapshot:
if explicit is not None:
return explicit
policy = effective_policy(kb_dir, base_dir=base_dir, kb_name=kb_name)
@@ -253,11 +535,53 @@ def cache_identity(snapshot: IndexingLLMSnapshot) -> str:
def cache_identity_for_config(config: LLMConfig) -> str:
"""Return a credential-free cache identity for a resolved query model."""
- return _fingerprint(_canonical_identity(None, config))
+ return _fingerprint(
+ {
+ **_canonical_identity(None, config),
+ "wire_api": config.wire_api,
+ "api_format": config.api_format,
+ "context_window": config.context_window,
+ }
+ )
+
+
+def public_policy(policy: dict[str, Any]) -> dict[str, Any]:
+ """Expose provenance without private endpoint or owner metadata."""
+ result = {
+ key: policy[key]
+ for key in ("schema_version", "policy", "fingerprint", "vision_available", "vlm_used")
+ if key in policy
+ }
+ selection = policy.get("selection")
+ if isinstance(selection, dict):
+ result["selection"] = {
+ key: selection[key]
+ for key in ("profile_id", "model_id", "reasoning_effort")
+ if key in selection
+ }
+ descriptor = policy.get("descriptor")
+ if isinstance(descriptor, dict):
+ result["descriptor"] = {
+ key: descriptor[key]
+ for key in ("model", "binding", "provider_mode", "reasoning_effort", "vision_available")
+ if key in descriptor
+ }
+ if isinstance(policy.get("extract"), dict):
+ result["extract"] = public_policy(policy["extract"])
+ vlm = policy.get("vlm")
+ if isinstance(vlm, dict):
+ result["vlm"] = {"mode": vlm.get("mode")}
+ if isinstance(vlm.get("snapshot"), dict):
+ result["vlm"]["snapshot"] = public_policy(vlm["snapshot"])
+ return result
__all__ = [
"IndexingLLMSnapshot",
+ "IndexingPolicySnapshot",
+ "freeze_roles",
+ "bind_target",
+ "revalidate_snapshot",
"IndexingModelChangedError",
"IndexingPolicyError",
"POLICY_LEGACY",
diff --git a/deeptutor/services/rag/pipelines/lightrag/pipeline.py b/deeptutor/services/rag/pipelines/lightrag/pipeline.py
index 5818ce487..b9d0b525f 100644
--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py
+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py
@@ -20,8 +20,8 @@ from deeptutor.services.rag.kb_paths import resolve_kb_dir
from . import block_policy, engine, indexing_policy, ingress, storage
from . import config as lr_config
from .indexing_policy import (
- IndexingLLMSnapshot,
IndexingPolicyError,
+ IndexingPolicySnapshot,
effective_policy,
freeze_default_snapshot,
resolve_write_snapshot,
@@ -279,7 +279,7 @@ class LightRagPipeline:
working_dir: Path,
file_paths: List[str],
progress_callback: Callable[[int, int], Any] | None,
- snapshot: IndexingLLMSnapshot | None = None,
+ snapshot: IndexingPolicySnapshot | None = None,
) -> BatchOutcome:
if snapshot is None:
snapshot = freeze_default_snapshot()
@@ -289,7 +289,7 @@ class LightRagPipeline:
staged, preflight_failed = self._stage_documents(
working_dir,
file_paths,
- vision_available=snapshot.vision_available,
+ vision_available=snapshot.vision_available and snapshot.image_analysis is not False,
)
if not staged:
raise LightRagBatchError(
@@ -356,7 +356,10 @@ class LightRagPipeline:
ingress.remove_unaccepted(item)
outcome = await run_in_worker_loop(job)
- return replace(outcome, indexing_policy=snapshot.persisted_policy())
+ published_policy = snapshot.persisted_policy()
+ if published_policy.get("policy") == "pending_pinned":
+ published_policy["policy"] = "pinned"
+ return replace(outcome, indexing_policy=published_policy)
def _remove_zero_accepted_candidate(self, root_dir: Path) -> None:
if not root_dir.is_dir() or storage.has_any_doc_status(root_dir):
@@ -367,9 +370,26 @@ class LightRagPipeline:
shutil.rmtree(root_dir)
async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
+ from .write_lock import write_ownership
+
+ kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
+ with write_ownership(kb_dir):
+ snapshot = kwargs.get("indexing_snapshot") or kwargs.get("accepted_indexing_snapshot")
+ if snapshot is not None:
+ indexing_policy.validate_target(snapshot, kb_dir)
+ fresh = indexing_policy.revalidate_snapshot(snapshot)
+ key = (
+ "indexing_snapshot"
+ if kwargs.get("indexing_snapshot") is not None
+ else "accepted_indexing_snapshot"
+ )
+ kwargs[key] = fresh
+ return await self._initialize_owned(kb_name, file_paths, **kwargs)
+
+ async def _initialize_owned(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
self._ensure_available()
kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
- snapshot = kwargs.get("indexing_snapshot")
+ snapshot = kwargs.get("indexing_snapshot") or kwargs.get("accepted_indexing_snapshot")
if snapshot is None:
policy = effective_policy(
kb_dir,
@@ -380,6 +400,8 @@ class LightRagPipeline:
snapshot = indexing_policy.snapshot_from_persisted(policy)
else:
snapshot = freeze_default_snapshot()
+ if "image_analysis" in kwargs:
+ snapshot = indexing_policy.with_image_analysis(snapshot, kwargs["image_analysis"])
root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)
try:
outcome = await self._run_indexing(
@@ -389,6 +411,9 @@ class LightRagPipeline:
raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")
policy = dict(outcome.indexing_policy)
policy["vlm_used"] = outcome.vlm_used
+ before_publish = kwargs.get("before_publish")
+ if before_publish is not None:
+ before_publish(root_dir)
storage.write_meta(root_dir, indexing_policy=policy)
self._clear_pending_policy(kb_name)
return outcome.complete
@@ -403,27 +428,48 @@ class LightRagPipeline:
raise
async def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
+ from .write_lock import write_ownership
+
+ kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
+ with write_ownership(kb_dir):
+ if kwargs.get("indexing_snapshot") is not None and (
+ storage.latest_published_root(kb_dir) is not None or list_kb_versions(kb_dir)
+ ):
+ raise IndexingPolicyError(
+ "An explicit LightRAG indexing model cannot override an existing index; "
+ "run a full re-index."
+ )
+ snapshot = kwargs.get("indexing_snapshot") or kwargs.get("accepted_indexing_snapshot")
+ if snapshot is not None:
+ indexing_policy.validate_target(snapshot, kb_dir)
+ fresh = indexing_policy.revalidate_snapshot(snapshot)
+ key = (
+ "indexing_snapshot"
+ if kwargs.get("indexing_snapshot") is not None
+ else "accepted_indexing_snapshot"
+ )
+ kwargs[key] = fresh
+ return await self._add_documents_owned(kb_name, file_paths, **kwargs)
+
+ async def _add_documents_owned(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
self._ensure_available()
kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
existing = storage.latest_published_root(kb_dir)
versions = list_kb_versions(kb_dir)
explicit = kwargs.get("indexing_snapshot")
- if explicit is not None and (existing is not None or versions):
- raise IndexingPolicyError(
- "An explicit LightRAG indexing model cannot override an existing index; "
- "run a full re-index."
- )
if existing is None and versions:
raise LightRagNeedsReindexError(
"This LightRAG index is legacy, unpublished, or corrupt and must be rebuilt "
"before appending."
)
- snapshot = resolve_write_snapshot(
+ snapshot = kwargs.get("accepted_indexing_snapshot") or resolve_write_snapshot(
kb_dir,
base_dir=self.kb_base_dir,
kb_name=kb_name,
explicit=explicit,
)
+ if "image_analysis" in kwargs:
+ snapshot = indexing_policy.with_image_analysis(snapshot, kwargs["image_analysis"])
if existing is not None:
root_dir = existing
is_update = True
@@ -437,8 +483,12 @@ class LightRagPipeline:
if not storage.has_output(root_dir):
raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")
policy = dict(outcome.indexing_policy)
- policy["vlm_used"] = outcome.vlm_used
+ previous_policy = storage.read_published_policy(existing) or {}
+ policy["vlm_used"] = outcome.vlm_used or previous_policy.get("vlm_used") is True
if not is_update:
+ before_publish = kwargs.get("before_publish")
+ if before_publish is not None:
+ before_publish(root_dir)
storage.write_meta(root_dir, indexing_policy=policy)
self._clear_pending_policy(kb_name)
else:
@@ -494,8 +544,12 @@ class LightRagPipeline:
try:
self._ensure_available()
+ from .roles import resolve_query_roles
+
+ query_roles = resolve_query_roles()
+
async def job(io_bridge: OwnerLoopBridge):
- rag = engine.build_rag(root_dir, io_bridge=io_bridge)
+ rag = engine.build_rag(root_dir, io_bridge=io_bridge, query_roles=query_roles)
failed = True
try:
await engine.initialize(rag)
diff --git a/deeptutor/services/rag/pipelines/lightrag/roles.py b/deeptutor/services/rag/pipelines/lightrag/roles.py
new file mode 100644
index 000000000..7b312cfed
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/lightrag/roles.py
@@ -0,0 +1,116 @@
+"""Resolve native LightRAG role choices inside the initiating user's scope."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+from deeptutor.multi_user.context import get_current_user
+from deeptutor.multi_user.model_access import allowed_llm_options, apply_allowed_llm_selection
+from deeptutor.multi_user.models import CurrentUser
+from deeptutor.services.config.lightrag_roles import LightRagRoleModels
+from deeptutor.services.llm.capabilities import supports_vision
+from deeptutor.services.llm.config import LLMConfig
+from deeptutor.services.model_selection.llm import LLMSelection
+from deeptutor.services.model_selection.reasoning import supported_reasoning_efforts
+from deeptutor.services.model_selection.runtime import resolve_llm_config_for_selection
+
+ROLES = ("extract", "keyword", "query", "vlm")
+
+
+def model_options() -> dict[str, Any]:
+ """Access-filtered choices shared by the editor and runtime validator."""
+ result = allowed_llm_options()
+ options = []
+ for row in result["options"]:
+ levels = row.get("supported_reasoning_efforts")
+ metadata = {"codex_supported_reasoning_levels": levels} if levels is not None else {}
+ metadata["capabilities"] = {"reasoning": row.get("declared_reasoning")}
+ options.append(
+ {
+ **row,
+ "supported_reasoning_efforts": supported_reasoning_efforts(
+ row["provider"], row["model"], metadata=metadata
+ ),
+ "supports_vision": row.get(
+ "declared_vision", supports_vision(row["provider"], row["model"])
+ ),
+ }
+ )
+ return {**result, "options": options}
+
+
+def resolve_selection(selection: LLMSelection, *, vision: bool = False) -> LLMConfig:
+ apply_allowed_llm_selection(selection.to_dict())
+ config = resolve_llm_config_for_selection(selection)
+ if config.reasoning_effort is not None:
+ option = next(
+ (
+ item
+ for item in model_options()["options"]
+ if item["profile_id"] == selection.profile_id
+ and item["model_id"] == selection.model_id
+ ),
+ None,
+ )
+ if option is None or config.reasoning_effort not in option["supported_reasoning_efforts"]:
+ raise ValueError("The selected model does not support this reasoning effort.")
+ if vision and not supports_vision(config.binding, config.model):
+ raise ValueError("The selected VLM model does not support image inputs.")
+ return config
+
+
+def settings_models(settings: dict[str, Any]) -> LightRagRoleModels | None:
+ value = settings.get("role_models")
+ return LightRagRoleModels.model_validate(value) if "role_models" in settings else None
+
+
+def validate_models(models: LightRagRoleModels) -> None:
+ resolve_selection(LLMSelection(**models.base.model_dump()))
+ for role in ROLES:
+ selection = models.selection_for(role)
+ if selection is not None:
+ resolve_selection(LLMSelection(**selection.model_dump()), vision=role == "vlm")
+
+
+@dataclass(frozen=True)
+class RoleCall:
+ config: LLMConfig
+ owner: CurrentUser
+ max_async: int
+ timeout: int
+
+
+def runtime_limits(settings: dict[str, Any]) -> dict[str, dict[str, int]]:
+ models = settings_models(settings)
+ return {
+ role: {
+ "max_async": getattr(models, role).max_async
+ if models
+ else int(settings.get("llm_model_max_async", 4)),
+ "timeout": getattr(models, role).timeout if models else 240,
+ }
+ for role in ROLES
+ }
+
+
+def resolve_query_roles() -> dict[str, RoleCall]:
+ from deeptutor.services.config import load_lightrag_settings
+
+ from .config import resolve_lightrag_query_llm_config
+
+ settings = load_lightrag_settings()
+ models = settings_models(settings)
+ limits = runtime_limits(settings)
+ owner = get_current_user()
+ result = {}
+ # The legacy resolver is intentionally used only for old-format settings.
+ legacy = resolve_lightrag_query_llm_config() if models is None else None
+ for role in ("keyword", "query"):
+ config = (
+ legacy
+ if models is None
+ else resolve_selection(LLMSelection(**models.selection_for(role).model_dump()))
+ )
+ result[role] = RoleCall(config=config, owner=owner, **limits[role])
+ return result
diff --git a/deeptutor/services/rag/pipelines/lightrag/write_lock.py b/deeptutor/services/rag/pipelines/lightrag/write_lock.py
new file mode 100644
index 000000000..03c559d56
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/lightrag/write_lock.py
@@ -0,0 +1,47 @@
+"""One nonblocking writer per knowledge base, shared across worker processes."""
+
+from contextlib import contextmanager
+import hashlib
+import os
+from pathlib import Path
+
+from .indexing_policy import IndexingPolicyError
+
+
+@contextmanager
+def write_ownership(kb_dir: Path):
+ kb_dir = Path(kb_dir)
+ if kb_dir.is_symlink():
+ raise IndexingPolicyError("A writable knowledge-base directory cannot be a symbolic link.")
+ lock_dir = kb_dir.parent / ".lightrag-locks"
+ if lock_dir.is_symlink():
+ raise IndexingPolicyError("The indexing lock directory cannot be a symbolic link.")
+ lock_dir.mkdir(parents=True, exist_ok=True)
+ key = hashlib.sha256(str(kb_dir.resolve()).encode("utf-8")).hexdigest()
+ lock_path = lock_dir / f"{key}.lock"
+ if lock_path.is_symlink():
+ raise IndexingPolicyError("The indexing lock cannot be a symbolic link.")
+ descriptor = os.open(lock_path, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600)
+ with os.fdopen(descriptor, "r+b") as handle:
+ try:
+ if os.name == "nt":
+ import msvcrt
+
+ handle.seek(0)
+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError as exc:
+ raise IndexingPolicyError(
+ "Another indexing operation is active for this knowledge base; resubmit after it finishes."
+ ) from exc
+ try:
+ yield
+ finally:
+ if os.name == "nt":
+ handle.seek(0)
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
+ else:
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py
index 518a017bb..34f2ac6ad 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -2244,6 +2244,10 @@ def test_create_pageindex_oss_persists_optional_mode(monkeypatch, tmp_path: Path
def test_create_mode_aware_kb_persists_per_kb_search_mode(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(
+ "deeptutor.services.rag.pipelines.lightrag.indexing_policy.bind_target",
+ lambda snapshot, _kb_dir, **_kwargs: snapshot,
+ )
manager = _FakeKBManager(tmp_path / "knowledge_bases")
snapshot = SimpleNamespace(
persisted_policy=lambda: {
@@ -2289,6 +2293,10 @@ def test_create_mode_aware_kb_persists_per_kb_search_mode(monkeypatch, tmp_path:
def test_create_empty_lightrag_kb_persists_redacted_pending_policy(
monkeypatch, tmp_path: Path
) -> None:
+ monkeypatch.setattr(
+ "deeptutor.services.rag.pipelines.lightrag.indexing_policy.bind_target",
+ lambda snapshot, _kb_dir, **_kwargs: snapshot,
+ )
manager = _FakeKBManager(tmp_path / "knowledge_bases")
snapshot = SimpleNamespace(
persisted_policy=lambda: {
@@ -2434,6 +2442,10 @@ def test_reindex_passes_frozen_lightrag_snapshot_to_background_task(
"status": "ready",
}
(manager.base_dir / "kb" / "raw").mkdir(parents=True)
+ monkeypatch.setattr(
+ "deeptutor.services.rag.pipelines.lightrag.indexing_policy.bind_target",
+ lambda snapshot, _kb_dir, **_kwargs: snapshot,
+ )
snapshot = object()
captured: dict[str, object] = {}
@@ -2760,3 +2772,58 @@ def test_lightrag_config_validates_dedicated_llm_selection(monkeypatch, tmp_path
json={"llm_profile_id": "", "llm_model_id": ""},
)
assert cleared.status_code == 200
+
+
[email protected]("role, expected", [("user", 403), ("admin", 200)])
+def test_shared_lightrag_settings_require_admin_over_http(monkeypatch, tmp_path, role, expected):
+ auth = importlib.import_module("deeptutor.api.routers.auth")
+ service = RuntimeSettingsService(tmp_path, process_env={})
+ monkeypatch.setattr(config_module, "get_runtime_settings_service", lambda: service)
+ monkeypatch.setattr(auth, "AUTH_ENABLED", True)
+ app = _build_app()
+
+ async def authenticated():
+ return SimpleNamespace(role=role)
+
+ app.dependency_overrides[auth.require_auth] = authenticated
+ before = service.load_lightrag()
+ response = TestClient(app).put(
+ "/api/knowledge-bases/rag-pipelines/lightrag/config", json={"top_k": 31}
+ )
+ assert response.status_code == expected
+ assert service.load_lightrag()["top_k"] == (31 if role == "admin" else before["top_k"])
+
+
+def test_lightrag_role_settings_validate_before_save(monkeypatch, tmp_path):
+ from deeptutor.services.rag.pipelines.lightrag import roles
+
+ service = RuntimeSettingsService(tmp_path, process_env={})
+ monkeypatch.setattr(config_module, "get_runtime_settings_service", lambda: service)
+ observed = []
+
+ def validate(models):
+ observed.append(models)
+ if models.base.model_id == "deleted":
+ raise ValueError("Selected model is unavailable.")
+
+ monkeypatch.setattr(roles, "validate_models", validate)
+ client = TestClient(_build_app())
+ url = "/api/knowledge-bases/rag-pipelines/lightrag/config"
+ models = {
+ "base": {"profile_id": "public", "model_id": "ok"},
+ "query": {"mode": "inherit", "reasoning_effort": "adaptive"},
+ }
+ response = client.put(url, json={"role_models": models})
+ assert response.status_code == 200
+ before = client.get(url).json()
+ assert before["role_models"]["query"]["reasoning_effort"] == "adaptive"
+ assert before["role_models"]["vlm"]["mode"] == "disabled"
+ assert len(observed) == 1
+ for invalid in (
+ {"role_models": {**models, "base": {"profile_id": "public", "model_id": "deleted"}}},
+ {"role_models": {**models, "vlm": {"mode": "disabled", "selection": models["base"]}}},
+ {"role_models": None},
+ {"llm_profile_id": "other", "llm_model_id": "other"},
+ ):
+ assert client.put(url, json=invalid).status_code == 422
+ assert client.get(url).json() == before
diff --git a/tests/knowledge/test_document_adder_provider.py b/tests/knowledge/test_document_adder_provider.py
index 680ba25ca..702a8379f 100644
--- a/tests/knowledge/test_document_adder_provider.py
+++ b/tests/knowledge/test_document_adder_provider.py
@@ -140,7 +140,12 @@ def test_lightrag_hash_bookkeeping_failure_does_not_deny_published_success(
return True
monkeypatch.setattr("deeptutor.knowledge.add_documents.RAGService", _SuccessfulRagService)
- adder = DocumentAdder(kb_name="kb", base_dir=str(tmp_path), rag_provider="lightrag")
+ adder = DocumentAdder(
+ kb_name="kb",
+ base_dir=str(tmp_path),
+ rag_provider="lightrag",
+ accepted_indexing_snapshot=object(),
+ )
monkeypatch.setattr(
adder,
"_record_successful_hash",
diff --git a/tests/services/rag/test_lightrag_indexing_policy.py b/tests/services/rag/test_lightrag_indexing_policy.py
index bed6ae302..8f43e7f4e 100644
--- a/tests/services/rag/test_lightrag_indexing_policy.py
+++ b/tests/services/rag/test_lightrag_indexing_policy.py
@@ -172,7 +172,7 @@ def test_default_snapshot_prefers_released_lightrag_selection(monkeypatch) -> No
),
)
- assert indexing_policy.freeze_default_snapshot() is expected
+ assert indexing_policy._freeze_legacy_default_snapshot() is expected
assert calls == [(selection, indexing_policy.POLICY_PINNED, False)]
diff --git a/tests/services/rag/test_lightrag_pipeline.py b/tests/services/rag/test_lightrag_pipeline.py
index a1dc03be0..9e192a3f1 100644
--- a/tests/services/rag/test_lightrag_pipeline.py
+++ b/tests/services/rag/test_lightrag_pipeline.py
@@ -58,9 +58,18 @@ class _Bridge:
return await value if inspect.isawaitable(value) else value
[email protected](autouse=True)
+def _isolate_role_revalidation(monkeypatch):
+ # Lifecycle tests use synthetic policies; real catalog/access revalidation
+ # is covered by test_lightrag_roles and test_lightrag_indexing_policy.
+ monkeypatch.setattr(indexing_policy, "revalidate_snapshot", lambda snapshot: snapshot)
+
+
def _indexing_snapshot():
return types.SimpleNamespace(
vision_available=True,
+ image_analysis=None,
+ target_bound=False,
persisted_policy=lambda: {"policy": "pinned", "fingerprint": "a" * 64},
)
@@ -145,7 +154,7 @@ def test_query_model_resolver_falls_back_only_when_selected_entry_is_missing(
)
assert config.resolve_lightrag_query_llm_config() is fallback
- assert calls == [selection, None]
+ assert calls == [selection, indexing_policy._active_catalog_selection()]
def test_lightrag_llm_adapter_uses_explicit_snapshot_config(monkeypatch) -> None:
@@ -254,7 +263,13 @@ def test_build_rag_keeps_indexing_snapshot_out_of_embedding_kwargs(
monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)
monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)
query_config = types.SimpleNamespace(binding="openai")
- monkeypatch.setattr(engine, "resolve_lightrag_query_llm_config", lambda: query_config)
+ from deeptutor.services.rag.pipelines.lightrag import roles
+
+ monkeypatch.setattr(
+ roles,
+ "resolve_query_roles",
+ lambda: {role: roles.RoleCall(query_config, None, 4, 240) for role in ("keyword", "query")},
+ )
monkeypatch.setattr(indexing_policy, "cache_identity_for_config", lambda _config: "query-id")
llm_calls: list[dict[str, object]] = []
embedding_calls: list[object] = []
@@ -272,7 +287,7 @@ def test_build_rag_keeps_indexing_snapshot_out_of_embedding_kwargs(
rag = engine.build_rag(tmp_path)
- assert llm_calls == [{"llm_config": query_config}]
+ assert llm_calls == [{"llm_config": query_config, "owner": None}] * 3
assert embedding_calls == [None]
assert rag.kwargs["embedding_func"] == "embedding"
@@ -1218,6 +1233,8 @@ def test_public_initial_ingestion_retains_uncertain_ingress(
[str(source)],
indexing_snapshot=types.SimpleNamespace(
vision_available=True,
+ image_analysis=None,
+ target_bound=False,
persisted_policy=lambda: {"policy": "legacy_unpinned"},
),
)
diff --git a/tests/services/rag/test_lightrag_roles.py b/tests/services/rag/test_lightrag_roles.py
new file mode 100644
index 000000000..ea7aa0b92
--- /dev/null
+++ b/tests/services/rag/test_lightrag_roles.py
@@ -0,0 +1,641 @@
+"""Four-role calls, task freezing, legacy policies, and write ownership contracts."""
+
+from __future__ import annotations
+
+import asyncio
+from copy import deepcopy
+from dataclasses import replace
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+from pydantic import ValidationError
+import pytest
+
+from deeptutor.multi_user.context import reset_current_user, set_current_user
+from deeptutor.multi_user.models import CurrentUser, UserScope
+from deeptutor.services.config.lightrag_roles import LightRagRoleModels
+from deeptutor.services.llm.config import LLMConfig
+from deeptutor.services.model_selection.llm import LLMSelection
+from deeptutor.services.rag.pipelines.lightrag import engine, roles, storage
+from deeptutor.services.rag.pipelines.lightrag import indexing_policy as policy
+from deeptutor.services.rag.pipelines.lightrag.pipeline import BatchOutcome, LightRagPipeline
+from deeptutor.services.rag.pipelines.lightrag.write_lock import write_ownership
+
+
+def choice(number: int, effort: str | None = None) -> dict:
+ result = {"profile_id": f"p{number}", "model_id": f"m{number}"}
+ if effort is not None:
+ result["reasoning_effort"] = effort
+ return result
+
+
+def role_environment(tmp_path, monkeypatch):
+ user = CurrentUser(
+ id="role-user",
+ username="tester",
+ role="user",
+ scope=UserScope(kind="user", user_id="role-user", root=tmp_path / "owner"),
+ )
+ token = set_current_user(user)
+ models = LightRagRoleModels.model_validate(
+ {
+ "base": choice(0),
+ "extract": {
+ "mode": "inherit",
+ "reasoning_effort": "none",
+ "max_async": 2,
+ "timeout": 101,
+ },
+ "keyword": {
+ "mode": "model",
+ "selection": choice(1),
+ "reasoning_effort": "low",
+ "max_async": 3,
+ "timeout": 102,
+ },
+ "query": {
+ "mode": "model",
+ "selection": choice(2),
+ "reasoning_effort": "high",
+ "max_async": 4,
+ "timeout": 103,
+ },
+ "vlm": {
+ "mode": "model",
+ "selection": choice(3),
+ "reasoning_effort": "none",
+ "max_async": 5,
+ "timeout": 104,
+ },
+ }
+ )
+ state = {
+ "settings": {"role_models": models.model_dump()},
+ "allowed": {f"p{i}" for i in range(4)},
+ "configs": {
+ f"p{i}": LLMConfig(
+ model=f"model-{i}",
+ binding="custom",
+ provider_name="custom",
+ api_key="private-key",
+ base_url=f"https://name:password@provider-{i}.test/v1?key=private",
+ reasoning_effort="medium",
+ )
+ for i in range(4)
+ },
+ "vision": {f"model-{i}": i == 3 for i in range(4)},
+ }
+
+ def allowed(value):
+ if value["profile_id"] not in state["allowed"]:
+ raise PermissionError("Model access was revoked.")
+ return value
+
+ def resolve(value):
+ selection = LLMSelection.from_payload(value)
+ config = state["configs"][selection.profile_id]
+ return config.model_copy(
+ update={"reasoning_effort": selection.reasoning_effort or config.reasoning_effort}
+ )
+
+ def options():
+ return {
+ "active": choice(0),
+ "options": [
+ {
+ **choice(i),
+ "model": f"model-{i}",
+ "provider": "custom",
+ "model_name": f"Model {i}",
+ "profile_name": f"Provider {i}",
+ "is_active_default": i == 0,
+ "supported_reasoning_efforts": ["none", "low", "medium", "high"],
+ }
+ for i in range(4)
+ if f"p{i}" in state["allowed"]
+ ],
+ }
+
+ monkeypatch.setattr(
+ "deeptutor.services.config.load_lightrag_settings", lambda: deepcopy(state["settings"])
+ )
+ monkeypatch.setattr(roles, "allowed_llm_options", options)
+ monkeypatch.setattr(roles, "apply_allowed_llm_selection", allowed)
+ monkeypatch.setattr(roles, "resolve_llm_config_for_selection", resolve)
+ monkeypatch.setattr(
+ roles, "supports_vision", lambda _binding, model: state["vision"].get(model, False)
+ )
+ monkeypatch.setattr(policy, "apply_allowed_llm_selection", allowed)
+ monkeypatch.setattr(policy, "resolve_llm_config_for_selection", resolve)
+ monkeypatch.setattr(
+ policy, "supports_vision", lambda _binding, model: state["vision"].get(model, False)
+ )
+ monkeypatch.setattr(policy, "_active_catalog_selection", lambda: choice(0))
+ yield state
+ reset_current_user(token)
+
+
+def test_role_contract_distinguishes_inherit_explicit_disabled_and_none():
+ models = LightRagRoleModels.model_validate(
+ {"base": choice(0, "high"), "extract": {"reasoning_effort": "none"}}
+ )
+ assert models.selection_for("query").reasoning_effort == "high"
+ assert models.selection_for("extract").reasoning_effort == "none"
+ assert models.selection_for("vlm") is None
+ for invalid in (
+ {"base": choice(0), "query": {"mode": "disabled"}},
+ {"base": choice(0), "vlm": {"mode": "disabled", "selection": choice(3)}},
+ {"base": choice(0), "query": {"mode": "model"}},
+ {"base": choice(0), "query": {"mode": "inherit", "selection": choice(1)}},
+ {"base": choice(0), "query": {"max_async": 0}},
+ {"base": choice(0), "query": {"timeout": True}},
+ {"base": {**choice(0), "api_key": "private"}},
+ ):
+ with pytest.raises(ValidationError):
+ LightRagRoleModels.model_validate(invalid)
+
+
+def test_new_settings_do_not_fall_back_to_chat(role_environment, monkeypatch):
+ monkeypatch.setattr(
+ "deeptutor.services.rag.pipelines.lightrag.config.resolve_lightrag_query_llm_config",
+ lambda: pytest.fail("new settings must not resolve chat fallback"),
+ )
+ first = roles.resolve_query_roles()
+ assert first["keyword"].config.model == "model-1"
+ assert first["query"].config.model == "model-2"
+ role_environment["settings"]["role_models"]["query"] = {"mode": "inherit"}
+ role_environment["settings"]["role_models"]["base"] = choice(3)
+ second = roles.resolve_query_roles()
+ assert second["query"].config.model == "model-3"
+ assert first["query"].config.model == "model-2"
+ assert (first["query"].max_async, first["query"].timeout) == (4, 103)
+
+
+def test_all_four_native_roles_call_their_frozen_models(role_environment, monkeypatch, tmp_path):
+ pytest.importorskip("lightrag")
+ calls = []
+
+ def build(config, *, allow_multimodal):
+ async def complete(prompt, **kwargs):
+ calls.append((config.model, config.reasoning_effort, allow_multimodal, kwargs))
+ return config.model
+
+ return complete
+
+ monkeypatch.setattr("deeptutor.services.llm.client.build_model_func_for_config", build)
+ monkeypatch.setattr(engine, "_require_exact_version", lambda: None)
+ monkeypatch.setattr(engine, "_register_parser", lambda: None)
+ monkeypatch.setattr(engine, "_controlled_class", lambda: lambda **kwargs: kwargs)
+ monkeypatch.setattr(engine, "build_embedding_func", lambda **kwargs: "independent embedding")
+ monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)
+ monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)
+ snapshot = policy.freeze_roles()
+ queries = roles.resolve_query_roles()
+ indexed = engine.build_rag(tmp_path, indexing_snapshot=snapshot, enable_vlm=True)
+ queried = engine.build_rag(tmp_path, query_roles=queries)
+
+ async def exercise():
+ await indexed["role_llm_configs"]["extract"].func("extract")
+ await indexed["role_llm_configs"]["vlm"].func("vision", image_inputs=[{"base64": "image"}])
+ await queried["role_llm_configs"]["keyword"].func("keyword")
+ await queried["role_llm_configs"]["query"].func("query")
+
+ asyncio.run(exercise())
+ assert [(model, effort, vision) for model, effort, vision, _ in calls] == [
+ ("model-0", "none", False),
+ ("model-3", "none", True),
+ ("model-1", "low", False),
+ ("model-2", "high", False),
+ ]
+ assert all(kwargs["allow_image_fallback"] is False for *_, kwargs in calls)
+ all_roles = {**indexed["role_llm_configs"], **queried["role_llm_configs"]}
+ assert {name: (value.max_async, value.timeout) for name, value in all_roles.items()} == {
+ "extract": (2, 101),
+ "vlm": (5, 104),
+ "keyword": (3, 102),
+ "query": (4, 103),
+ }
+ assert len({value.metadata["model"] for value in all_roles.values()}) == 4
+
+
+def test_index_policy_freezes_defaults_and_limits_but_refreshes_credentials(role_environment):
+ snapshot = policy.freeze_roles()
+ persisted = snapshot.persisted_policy()
+ role_environment["settings"]["role_models"]["extract"]["max_async"] = 12
+ role_environment["settings"]["role_models"]["extract"]["timeout"] = 900
+ role_environment["settings"]["role_models"]["base"] = choice(2)
+ role_environment["configs"]["p0"].api_key = "rotated-secret"
+ fresh = policy.revalidate_snapshot(snapshot)
+ assert fresh.extract.config.api_key == "rotated-secret"
+ assert fresh.extract.config.model == "model-0"
+ assert fresh.limits["extract"] == {"max_async": 2, "timeout": 101}
+ assert fresh.persisted_policy() == persisted
+ assert policy.freeze_roles().extract.config.model == "model-2"
+ serialized = json.dumps(persisted)
+ for forbidden in ("private", "password", "api_key", "role-user"):
+ assert forbidden not in serialized
+ assert "endpoint" not in json.dumps(policy.public_policy(persisted))
+
+
+ "change", ["endpoint", "model", "wire_api", "context_window", "access", "vision"]
+)
+def test_invalid_pinned_identity_blocks_before_writes(role_environment, change):
+ snapshot = policy.freeze_roles()
+ if change == "endpoint":
+ role_environment["configs"]["p0"].effective_url = "https://other.test/v1"
+ elif change == "model":
+ role_environment["configs"]["p0"].model = "different"
+ elif change == "wire_api":
+ role_environment["configs"]["p0"].api_format = "openai_responses"
+ elif change == "context_window":
+ role_environment["configs"]["p0"].context_window = 100000
+ elif change == "access":
+ role_environment["allowed"].remove("p3")
+ else:
+ role_environment["vision"]["model-3"] = False
+ with pytest.raises(policy.IndexingPolicyError):
+ policy.revalidate_snapshot(snapshot)
+
+
+def test_unsupported_reasoning_and_nonvision_inheritance_fail(role_environment):
+ models = deepcopy(role_environment["settings"]["role_models"])
+ models["query"]["reasoning_effort"] = "max"
+ with pytest.raises(ValueError, match="reasoning"):
+ roles.validate_models(LightRagRoleModels.model_validate(models))
+ models["query"]["reasoning_effort"] = "high"
+ models["vlm"] = {"mode": "inherit"}
+ with pytest.raises(ValueError, match="image inputs"):
+ roles.validate_models(LightRagRoleModels.model_validate(models))
+
+
+def test_legacy_single_policy_keeps_its_original_algorithm_and_vision(role_environment):
+ legacy = policy.freeze_snapshot(choice(3, "none")).persisted_policy()
+ adapted = policy.snapshot_from_persisted(legacy)
+ assert adapted.vision_available
+ assert adapted.extract.fingerprint == legacy["fingerprint"]
+ assert adapted.vlm.fingerprint == legacy["fingerprint"]
+ assert adapted.persisted_policy() == legacy
+ assert "schema_version" not in adapted.persisted_policy()
+ del legacy["vision_available"]
+ with pytest.raises(policy.IndexingModelChangedError, match="historical vision"):
+ policy.snapshot_from_persisted(legacy)
+
+
+ "bad",
+ [
+ {},
+ {"policy": "legacy_unpinned"},
+ {"policy": "pinned", "schema_version": 99},
+ {"policy": "pinned", "schema_version": 2, "extract": {}, "vlm": {"mode": "enabled"}},
+ {
+ "policy": "pinned",
+ "schema_version": 2,
+ "extract": {},
+ "vlm": {"mode": "disabled", "snapshot": {}},
+ },
+ ],
+)
+def test_malformed_policies_never_acquire_current_defaults(role_environment, bad):
+ with pytest.raises(policy.IndexingPolicyError):
+ policy.snapshot_from_persisted(bad)
+
+
+def test_disabled_vlm_requires_rebuild_for_explicit_analysis(role_environment):
+ disabled = policy.freeze_roles({"extract": choice(0), "vlm": {"mode": "disabled"}})
+ assert not disabled.vision_available
+ assert policy.with_image_analysis(disabled, False).vlm is None
+ with pytest.raises(policy.IndexingModelChangedError, match="full re-index"):
+ policy.with_image_analysis(disabled, True)
+ enabled = policy.freeze_roles(
+ {"extract": choice(0), "vlm": {"mode": "enabled", "selection": choice(3)}}
+ )
+ assert policy.with_image_analysis(enabled, True).vision_available
+ assert (
+ policy.with_image_analysis(enabled, False).persisted_policy() == enabled.persisted_policy()
+ )
+
+
+def _published(path: Path, value: dict):
+ path.mkdir(parents=True, exist_ok=True)
+ (path / "kv_store_doc_status.json").write_text('{"doc": {"status": "processed"}}')
+ (path / "meta.json").write_text(
+ json.dumps(
+ {
+ "provider": "lightrag",
+ "signature": "lightrag",
+ "lightrag_adapter_schema": storage.ADAPTER_SCHEMA,
+ "parser_bridge_schema": 1,
+ "state": "published",
+ "indexing_policy": value,
+ }
+ )
+ )
+
+
+def test_stale_queued_target_is_rejected_before_graph_write(
+ role_environment, tmp_path, monkeypatch
+):
+ kb = tmp_path / "kb"
+ first = policy.freeze_roles()
+ _published(kb / "version-1", first.persisted_policy())
+ accepted = policy.bind_target(first, kb)
+ _published(kb / "version-2", first.persisted_policy())
+ pipeline = LightRagPipeline(str(tmp_path))
+ monkeypatch.setattr(
+ pipeline, "_run_indexing", lambda *_args: pytest.fail("stale job wrote graph")
+ )
+ with pytest.raises(policy.IndexingPolicyError, match="target index"):
+ asyncio.run(pipeline.add_documents("kb", ["doc.md"], accepted_indexing_snapshot=accepted))
+ assert storage.latest_published_root(kb) == kb / "version-2"
+
+
+def test_two_writers_cannot_own_one_knowledge_base(tmp_path):
+ kb = tmp_path / "kb"
+ with write_ownership(kb):
+ with pytest.raises(policy.IndexingPolicyError, match="Another indexing"):
+ with write_ownership(kb):
+ pytest.fail("both writers acquired ownership")
+ with write_ownership(kb):
+ pass
+
+
+def test_failed_terminal_persistence_does_not_publish_candidate(
+ role_environment, tmp_path, monkeypatch
+):
+ snapshot = policy.freeze_roles()
+ kb = tmp_path / "kb"
+ _published(kb / "version-1", snapshot.persisted_policy())
+ pipeline = LightRagPipeline(str(tmp_path))
+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)
+ monkeypatch.setattr(storage, "has_output", lambda _root: True)
+
+ async def indexed(root, *_args):
+ (root / "kv_store_doc_status.json").write_text('{"doc": {"status": "processed"}}')
+ return BatchOutcome(
+ 1, accepted=1, processed=("doc.md",), indexing_policy=snapshot.persisted_policy()
+ )
+
+ def fail_terminal(_root):
+ raise OSError("terminal persistence failed")
+
+ monkeypatch.setattr(pipeline, "_run_indexing", indexed)
+ with pytest.raises(OSError, match="terminal persistence"):
+ asyncio.run(
+ pipeline.initialize(
+ "kb", ["doc.md"], indexing_snapshot=snapshot, before_publish=fail_terminal
+ )
+ )
+ assert storage.latest_published_root(kb) == kb / "version-1"
+ assert not (kb / "version-2" / "meta.json").exists()
+
+
+def test_prepared_terminal_is_not_announced_or_read_as_completed(tmp_path, monkeypatch):
+ from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker
+
+ entry = {"status": "processing"}
+
+ class Manager:
+ def __init__(self, **_kwargs):
+ pass
+
+ def update_kb_status(self, *, status, progress, **_kwargs):
+ entry.update(status=status, progress=progress)
+
+ def get_kb_entry(self, _name):
+ return entry
+
+ monkeypatch.setattr("deeptutor.knowledge.manager.KnowledgeBaseManager", Manager)
+ monkeypatch.setattr(
+ "deeptutor.knowledge.progress_events.emit_task_progress", lambda *_args: None
+ )
+ tracker = ProgressTracker("kb", tmp_path)
+ tracker.task_id = "rebuild-1"
+ seen = []
+ tracker.set_callback(lambda progress: seen.append(progress["stage"]))
+ tracker.update(
+ ProgressStage.COMPLETED,
+ "Rebuild complete",
+ current=1,
+ total=1,
+ indexed_count=1,
+ index_changed=True,
+ index_action="reindex",
+ publication_version="version-2",
+ )
+ tracker.verify_terminal(
+ current=1, total=1, indexed_count=1, index_action="reindex", publication_version="version-2"
+ )
+ assert entry["status"] == "processing"
+ assert seen == ["processing_documents"]
+ assert tracker.get_progress()["stage"] == "processing_documents"
+ # A process interrupted here has a prepared record, not a published index.
+ _published(tmp_path / "kb" / "version-2", {"policy": "pinned"})
+ assert tracker.get_progress()["stage"] == "completed"
+
+
[email protected]("lost_write", ["progress_file", "kb_status"])
+def test_lost_terminal_write_is_detected_before_publication(tmp_path, monkeypatch, lost_write):
+ from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker
+
+ entry = {"status": "ready"}
+
+ class Manager:
+ def __init__(self, **_kwargs):
+ pass
+
+ def update_kb_status(self, *, status, progress, **_kwargs):
+ if lost_write == "kb_status":
+ raise OSError("status storage unavailable")
+ entry.update(status=status, progress=progress)
+
+ def get_kb_entry(self, _name):
+ return entry
+
+ monkeypatch.setattr("deeptutor.knowledge.manager.KnowledgeBaseManager", Manager)
+ if lost_write == "progress_file":
+
+ def fail(*_args):
+ raise OSError("progress storage unavailable")
+
+ monkeypatch.setattr("deeptutor.knowledge.progress_tracker.atomic_write_json", fail)
+ tracker = ProgressTracker("kb", tmp_path)
+ tracker.task_id = "new-task"
+ tracker.update(
+ ProgressStage.COMPLETED,
+ current=1,
+ total=1,
+ indexed_count=1,
+ index_changed=True,
+ index_action="reindex",
+ publication_version="version-2",
+ )
+ with pytest.raises(RuntimeError, match="terminal state was not persisted"):
+ tracker.verify_terminal(
+ current=1,
+ total=1,
+ indexed_count=1,
+ index_action="reindex",
+ publication_version="version-2",
+ )
+
+
+def test_concurrent_first_writers_do_not_publish_different_policies(
+ role_environment, tmp_path, monkeypatch
+):
+ snapshot = policy.bind_target(policy.freeze_roles(), tmp_path / "kb")
+ pipeline = LightRagPipeline(str(tmp_path))
+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)
+ monkeypatch.setattr(pipeline, "_clear_pending_policy", lambda _name: None)
+ monkeypatch.setattr(
+ storage, "write_meta", lambda root, *, indexing_policy: _published(root, indexing_policy)
+ )
+
+ async def exercise():
+ entered = asyncio.Event()
+ release = asyncio.Event()
+
+ async def indexed(root, *_args):
+ (root / "kv_store_doc_status.json").write_text('{"doc": {"status": "processed"}}')
+ entered.set()
+ await release.wait()
+ return BatchOutcome(
+ 1, accepted=1, processed=("doc.md",), indexing_policy=snapshot.persisted_policy()
+ )
+
+ monkeypatch.setattr(pipeline, "_run_indexing", indexed)
+ first = asyncio.create_task(
+ pipeline.add_documents("kb", ["doc.md"], accepted_indexing_snapshot=snapshot)
+ )
+ await entered.wait()
+ try:
+ with pytest.raises(policy.IndexingPolicyError, match="Another indexing"):
+ await pipeline.add_documents(
+ "kb", ["other.md"], accepted_indexing_snapshot=snapshot
+ )
+ finally:
+ release.set()
+ assert await first
+ with pytest.raises(policy.IndexingPolicyError, match="target index"):
+ await pipeline.add_documents("kb", ["other.md"], accepted_indexing_snapshot=snapshot)
+
+ asyncio.run(exercise())
+ published = storage.latest_published_root(tmp_path / "kb")
+ assert published.name == "version-1"
+ assert (
+ storage.read_published_policy(published)["extract"]["fingerprint"]
+ == snapshot.extract.fingerprint
+ )
+
+
+def test_pending_policy_change_invalidates_a_queued_first_write(role_environment, tmp_path):
+ from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+ kb = tmp_path / "kb"
+ kb.mkdir()
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))
+ original = policy.freeze_roles(policy=policy.POLICY_PENDING)
+ manager.config["knowledge_bases"]["kb"] = {
+ "path": "kb",
+ "rag_provider": "lightrag",
+ "pending_indexing_policy": original.persisted_policy(),
+ }
+ manager._save_config()
+ accepted = policy.bind_target(original, kb)
+ replacement = policy.freeze_roles(
+ {"extract": choice(1), "vlm": {"mode": "disabled"}}, policy=policy.POLICY_PENDING
+ )
+ manager.config["knowledge_bases"]["kb"]["pending_indexing_policy"] = (
+ replacement.persisted_policy()
+ )
+ manager._save_config()
+ with pytest.raises(policy.IndexingPolicyError, match="pending policy changed"):
+ policy.validate_target(accepted, kb)
+
+
+def test_queued_rebuild_rejects_same_version_append_but_append_remains_valid(
+ role_environment, tmp_path
+):
+ kb = tmp_path / "kb"
+ snapshot = policy.freeze_roles()
+ root = kb / "version-1"
+ _published(root, snapshot.persisted_policy())
+ rebuild = policy.bind_target(snapshot, kb, protect_contents=True)
+ append = policy.bind_target(snapshot, kb)
+ (root / "kv_store_doc_status.json").write_text(
+ '{"doc": {"status": "processed"}, "later": {"status": "processed"}}'
+ )
+ with pytest.raises(policy.IndexingPolicyError, match="target index"):
+ policy.validate_target(rebuild, kb)
+ policy.validate_target(append, kb)
+
+
+def test_disabled_vision_keeps_table_and_equation_processing(tmp_path, monkeypatch):
+ pipeline = LightRagPipeline(str(tmp_path))
+ from dataclasses import dataclass
+
+ from deeptutor.services.rag.pipelines.lightrag import ingress
+
+ @dataclass
+ class Staged:
+ process_options: str = "ite"
+
+ monkeypatch.setattr(
+ "deeptutor.services.parsing.get_parse_service",
+ lambda: SimpleNamespace(parse=lambda path: object()),
+ )
+ monkeypatch.setattr(ingress, "freeze_document", lambda *args: Staged())
+ disabled, failures = pipeline._stage_documents(tmp_path, ["doc.md"], vision_available=False)
+ enabled, _ = pipeline._stage_documents(tmp_path, ["doc.md"], vision_available=True)
+ assert not failures
+ assert disabled[0].process_options == "te"
+ assert enabled[0].process_options == "ite"
+
+
+async def test_github_sync_freezes_policy_before_download(role_environment, tmp_path, monkeypatch):
+ from deeptutor.services.github_source import sync
+
+ kb = tmp_path / "kb"
+ pinned = policy.freeze_roles()
+ _published(kb / "version-1", pinned.persisted_policy())
+ monkeypatch.setattr(
+ "deeptutor.services.rag.provider_binding.resolve_bound_provider", lambda *args: "lightrag"
+ )
+ recorded = []
+ monkeypatch.setattr(
+ "deeptutor.knowledge.manager.KnowledgeBaseManager",
+ lambda **kwargs: SimpleNamespace(
+ update_github_source_state=lambda **data: recorded.append(data)
+ ),
+ )
+ accepted = []
+
+ async def add_documents(**kwargs):
+ accepted.append(kwargs["accepted_indexing_snapshot"])
+ return 1
+
+ monkeypatch.setattr("deeptutor.knowledge.add_documents.add_documents", add_documents)
+
+ class Client:
+ async def get_latest_commit_sha(self, *args):
+ role_environment["settings"]["role_models"]["base"] = choice(2)
+ return "new-sha"
+
+ async def get_tree(self, *args, **kwargs):
+ return [SimpleNamespace(path="doc.md", type="blob")]
+
+ async def download_file(self, *args):
+ return b"test source"
+
+ result = await sync.sync_source(
+ "kb", {"id": "src", "repo": "owner/repo"}, base_dir=str(tmp_path), client=Client()
+ )
+ assert result.ok
+ assert accepted[0].extract.fingerprint == pinned.extract.fingerprint
+ assert accepted[0].vlm.fingerprint == pinned.vlm.fingerprint
+ assert accepted[0].target_bound
+ assert recorded[0]["last_synced_sha"] == "new-sha"
diff --git a/tests/services/rag/test_lightrag_settings_wiring.py b/tests/services/rag/test_lightrag_settings_wiring.py
index 4b9f7ad0d..22c011ce8 100644
--- a/tests/services/rag/test_lightrag_settings_wiring.py
+++ b/tests/services/rag/test_lightrag_settings_wiring.py
@@ -8,7 +8,7 @@ import types
import pytest
-from deeptutor.services.rag.pipelines.lightrag import engine
+from deeptutor.services.rag.pipelines.lightrag import engine, roles
pytestmark = pytest.mark.skipif(
importlib.util.find_spec("lightrag") is None,
@@ -28,7 +28,11 @@ def _stub_build(monkeypatch) -> None:
monkeypatch.setattr(engine, "_controlled_class", lambda: _NativeLightRag)
monkeypatch.setattr(engine, "build_llm_model_func", lambda **_kwargs: "llm")
monkeypatch.setattr(engine, "build_embedding_func", lambda **_kwargs: "embedding")
- monkeypatch.setattr(engine, "resolve_lightrag_query_llm_config", lambda: query_config)
+ monkeypatch.setattr(
+ roles,
+ "resolve_query_roles",
+ lambda: {role: roles.RoleCall(query_config, None, 4, 240) for role in ("keyword", "query")},
+ )
monkeypatch.setattr(
"deeptutor.services.rag.pipelines.lightrag.indexing_policy.cache_identity_for_config",
lambda _config: "query-fingerprint",
@@ -79,13 +83,17 @@ def test_global_dedicated_selection_drives_query_roles_not_embedding(
monkeypatch.setattr(engine, "build_llm_model_func", build_llm)
monkeypatch.setattr(engine, "build_embedding_func", build_embedding)
- monkeypatch.setattr(engine, "resolve_lightrag_query_llm_config", lambda: query_config)
+ monkeypatch.setattr(
+ roles,
+ "resolve_query_roles",
+ lambda: {role: roles.RoleCall(query_config, None, 4, 240) for role in ("keyword", "query")},
+ )
monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)
monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)
engine.build_rag(tmp_path)
- assert llm_calls == [{"llm_config": query_config}]
+ assert llm_calls == [{"llm_config": query_config, "owner": None}] * 3
assert embedding_calls == [{}]
@@ -105,14 +113,15 @@ def test_vlm_role_is_only_configured_when_enabled(monkeypatch, tmp_path: Path) -
lambda _snapshot: "snapshot-fingerprint",
)
- rag = engine.build_rag(tmp_path, enable_vlm=True, indexing_snapshot=snapshot)
+ pair = types.SimpleNamespace(extract=snapshot, vlm=snapshot, limits={})
+ rag = engine.build_rag(tmp_path, enable_vlm=True, indexing_snapshot=pair)
role = rag.kwargs["role_llm_configs"]["vlm"]
assert role.func == "vision"
assert rag.kwargs["vlm_process_enable"] is True
-def test_snapshot_routes_only_extract_and_vlm_while_query_base_stays_global(
+def test_indexing_uses_frozen_roles_without_resolving_query_models(
monkeypatch, tmp_path: Path
) -> None:
_stub_build(monkeypatch)
@@ -141,13 +150,13 @@ def test_snapshot_routes_only_extract_and_vlm_while_query_base_stays_global(
lambda _snapshot: "snapshot-fingerprint",
)
- rag = engine.build_rag(tmp_path, enable_vlm=True, indexing_snapshot=snapshot)
+ pair = types.SimpleNamespace(extract=snapshot, vlm=snapshot, limits={})
+ rag = engine.build_rag(tmp_path, enable_vlm=True, indexing_snapshot=pair)
assert "llm_config" in llm_calls[0]
assert llm_calls[1] == {"llm_config": snapshot.config, "owner": snapshot.owner}
assert vision_calls == [{"llm_config": snapshot.config, "owner": snapshot.owner}]
- assert rag.kwargs["llm_model_func"] == "llm-1"
- assert rag.kwargs["role_llm_configs"]["extract"].func == "llm-2"
+ assert rag.kwargs["llm_model_func"] == "llm-2"
+ assert rag.kwargs["role_llm_configs"]["extract"].func == "llm-1"
assert rag.kwargs["role_llm_configs"]["vlm"].func == "vision"
- assert rag.kwargs["role_llm_configs"]["keyword"].func == "llm-1"
- assert rag.kwargs["role_llm_configs"]["query"].func == "llm-1"
+ assert set(rag.kwargs["role_llm_configs"]) == {"extract", "vlm"}
diff --git a/web/components/knowledge/CreateKbModal.tsx b/web/components/knowledge/CreateKbModal.tsx
index 089750a9d..c94cc41b7 100644
--- a/web/components/knowledge/CreateKbModal.tsx
+++ b/web/components/knowledge/CreateKbModal.tsx
@@ -20,6 +20,7 @@ import { useLLMOptions } from "@/hooks/useLLMOptions";
import {
getGraphRagConfig,
getLightRagConfig,
+ getLightRagModelOptions,
getLightRagServerConfig,
getLlamaIndexConfig,
getPageIndexConfig,
@@ -30,7 +31,7 @@ import {
probeLinkedFolder,
probeWeKnora,
type KnowledgeUploadPolicy,
- type IndexingLLMSelection,
+ type LightRagIndexingSelection,
type LinkedFolderProbe,
type RagProviderSummary,
type WeKnoraProbe,
@@ -47,9 +48,10 @@ import {
import FileDropZone from "./FileDropZone";
import ImaConnectionFields from "./ImaConnectionFields";
import KnowledgeEngineIcon from "./KnowledgeEngineIcon";
-import IndexingModelSelector, {
- selectionFromLightRagDefault,
-} from "./IndexingModelSelector";
+import LightRagIndexingSelector, {
+ indexingSelectionFromDefaults,
+ isCompleteIndexingSelection,
+} from "./LightRagIndexingSelector";
const OBSIDIAN_SOURCE = "obsidian";
const MARGINNOTE4_SOURCE = "marginnote4";
@@ -72,7 +74,7 @@ interface CreateKbModalProps {
files: File[];
pageindexMode?: "flash" | "standard";
searchMode?: string;
- indexingLLM?: IndexingLLMSelection;
+ indexingLLM?: LightRagIndexingSelection;
}) => Promise<void>;
/** Link a pre-built engine index folder in place (no copy, no re-index). */
onConnectLinkedFolder: (params: {
@@ -164,9 +166,8 @@ export default function CreateKbModal({
const [weKnoraProbe, setWeKnoraProbe] = useState<WeKnoraProbe | null>(null);
const [weKnoraProbing, setWeKnoraProbing] = useState(false);
const [submitting, setSubmitting] = useState(false);
- const [indexingLLM, setIndexingLLM] = useState<IndexingLLMSelection | null>(
- null,
- );
+ const [indexingLLM, setIndexingLLM] =
+ useState<LightRagIndexingSelection | null>(null);
const [lightRagConfig, setLightRagConfig] = useState<Awaited<
ReturnType<typeof getLightRagConfig>
> | null>(null);
@@ -182,7 +183,7 @@ export default function CreateKbModal({
onError: setError,
active: linkIsIma,
});
- const llmCatalog = useLLMOptions();
+ const llmCatalog = useLLMOptions(getLightRagModelOptions);
const firstLinkable = providers.find((p) => p.linkable)?.id;
@@ -251,7 +252,7 @@ export default function CreateKbModal({
return;
}
setIndexingLLM(
- selectionFromLightRagDefault(
+ indexingSelectionFromDefaults(
llmCatalog.options,
lightRagConfig,
llmCatalog.activeDefault,
@@ -390,7 +391,8 @@ export default function CreateKbModal({
!!weKnoraProbe?.ok
);
}
- if (provider === "lightrag" && !indexingLLM) return false;
+ if (provider === "lightrag" && !isCompleteIndexingSelection(indexingLLM))
+ return false;
return !providerUnavailable;
}
if (linkIsIma) return imaConnection.canSubmit;
@@ -616,7 +618,7 @@ export default function CreateKbModal({
policyForProvider={policyForProvider}
indexingModelField={
provider === "lightrag" ? (
- <IndexingModelSelector
+ <LightRagIndexingSelector
options={llmCatalog.options}
selection={indexingLLM}
loading={llmCatalog.loading}
diff --git a/web/components/knowledge/IndexingModelSelector.tsx b/web/components/knowledge/IndexingModelSelector.tsx
index ae3b768be..4e5ce880b 100644
--- a/web/components/knowledge/IndexingModelSelector.tsx
+++ b/web/components/knowledge/IndexingModelSelector.tsx
@@ -19,6 +19,7 @@ const INDEXING_REASONING_EFFORTS = new Set([
"high",
"xhigh",
"max",
+ "adaptive",
]);
export function selectionFromLLMOption(
@@ -58,6 +59,8 @@ export function selectionFromLightRagDefault(
}
interface IndexingModelSelectorProps {
+ label?: string;
+ lockModel?: boolean;
options: LLMOption[];
selection: IndexingLLMSelection | null;
loading: boolean;
@@ -69,6 +72,8 @@ interface IndexingModelSelectorProps {
}
export default function IndexingModelSelector({
+ label = "Indexing model",
+ lockModel = false,
options,
selection,
loading,
@@ -86,7 +91,7 @@ export default function IndexingModelSelector({
);
const reasoningOptions = (
selected
- ? selected.supported_reasoning_efforts?.length
+ ? selected.supported_reasoning_efforts !== undefined
? reasoningEffortOptionsFromSupportedLevels(
selected.supported_reasoning_efforts,
)
@@ -129,11 +134,11 @@ export default function IndexingModelSelector({
<div className="space-y-3">
<label className="block">
<span className="mb-1.5 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
- {t("Indexing model")}
+ {t(label)}
</span>
<select
value={selected ? `${selected.profile_id}:${selected.model_id}` : ""}
- disabled={disabled}
+ disabled={disabled || lockModel}
onChange={(event) => {
const option = options.find(
(item) =>
@@ -157,11 +162,6 @@ export default function IndexingModelSelector({
</option>
))}
</select>
- <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">
- {t(
- "Defaults to the current LightRAG query model. Once published, incremental indexing keeps this selection.",
- )}
- </p>
</label>
{defaultUnavailable && !selection && (
@@ -179,30 +179,49 @@ export default function IndexingModelSelector({
</div>
)}
- {selected && reasoningOptions.length > 0 && (
- <label className="block">
- <span className="mb-1.5 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
- {t("Reasoning effort")}
- </span>
- <select
- value={selection?.reasoning_effort ?? ""}
- disabled={disabled}
- onChange={(event) =>
- onChange(selectionFromLLMOption(selected, event.target.value))
- }
- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] disabled:opacity-50"
- >
- {reasoningOptions.map((option) => (
- <option key={option.value || "auto"} value={option.value}>
- {t(option.label)}
- </option>
- ))}
- </select>
- <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">
- {t("Auto inherits the selected model's saved reasoning effort.")}
- </p>
- </label>
- )}
+ {selected &&
+ (reasoningOptions.length > 0 || selection?.reasoning_effort) && (
+ <label className="block">
+ <span className="mb-1.5 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">
+ {t("Reasoning effort")}
+ </span>
+ <select
+ aria-label={t("Reasoning effort")}
+ value={selection?.reasoning_effort ?? ""}
+ disabled={disabled}
+ onChange={(event) =>
+ onChange(selectionFromLLMOption(selected, event.target.value))
+ }
+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] disabled:opacity-50"
+ >
+ <option value="">{t("Model default / unspecified")}</option>
+ {selection?.reasoning_effort &&
+ !reasoningOptions.some(
+ (option) => option.value === selection.reasoning_effort,
+ ) && (
+ <option value={selection.reasoning_effort} disabled>
+ {t("Unsupported reasoning effort")}:{" "}
+ {selection.reasoning_effort}
+ </option>
+ )}
+ {reasoningOptions
+ .filter((option) => option.value)
+ .map((option) => (
+ <option key={option.value || "auto"} value={option.value}>
+ {t(option.label)}
+ </option>
+ ))}
+ </select>
+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">
+ {t("Effective reasoning")}:{" "}
+ {selection?.reasoning_effort ||
+ selected.reasoning_effort ||
+ t("Model default")}
+ .{" "}
+ {t("Auto inherits the selected model's saved reasoning effort.")}
+ </p>
+ </label>
+ )}
</div>
);
}
diff --git a/web/components/knowledge/KbIndexVersionsSection.tsx b/web/components/knowledge/KbIndexVersionsSection.tsx
index c4d9a33b9..0752f538d 100644
--- a/web/components/knowledge/KbIndexVersionsSection.tsx
+++ b/web/components/knowledge/KbIndexVersionsSection.tsx
@@ -22,56 +22,52 @@ import {
resolveKbStatus,
resolveProgressPercent,
type IndexVersion,
+ type LightRagIndexingPolicy,
type KnowledgeBase,
} from "@/lib/knowledge-helpers";
import type { TaskState } from "@/hooks/useKnowledgeProgress";
import ProcessLogs from "@/components/common/ProcessLogs";
import Modal from "@/components/common/Modal";
import { useLLMOptions } from "@/hooks/useLLMOptions";
-import { getLightRagConfig } from "@/features/knowledge/api/engines";
+import {
+ getLightRagConfig,
+ getLightRagModelOptions,
+} from "@/features/knowledge/api/engines";
import type { LLMOption } from "@/lib/llm-options";
import type {
- IndexingLLMSelection,
+ LightRagIndexingSelection,
LightRagConfig,
} from "@/features/knowledge/model/types";
import KbIndexFailureBanner from "./KbIndexFailureBanner";
-import IndexingModelSelector, {
- selectionFromLightRagDefault,
- selectionFromLLMOption,
-} from "./IndexingModelSelector";
+import LightRagIndexingSelector, {
+ indexingSelectionFromDefaults,
+ isCompleteIndexingSelection,
+ indexingSelectionFromPolicy,
+} from "./LightRagIndexingSelector";
import LightRagIndexingProvenance from "./LightRagIndexingProvenance";
export function selectionForLightRagModelDialog(
options: LLMOption[],
- config: Pick<LightRagConfig, "llm_profile_id" | "llm_model_id">,
- activeDefault: {
- profile_id?: string | null;
- model_id?: string | null;
- } | null,
- savedPending: IndexingLLMSelection | undefined,
+ config: Pick<
+ LightRagConfig,
+ "llm_profile_id" | "llm_model_id" | "role_models"
+ >,
+ activeDefault: import("@/lib/llm-options").LLMOptionsResponse["active"],
+ savedPending: LightRagIndexingPolicy | undefined,
preserveSavedPending: boolean,
-): IndexingLLMSelection | null {
- const savedOption = preserveSavedPending
- ? options.find(
- (option) =>
- option.profile_id === savedPending?.profile_id &&
- option.model_id === savedPending?.model_id,
- )
- : undefined;
- return savedOption
- ? selectionFromLLMOption(
- savedOption,
- savedPending?.reasoning_effort || "",
- )
- : selectionFromLightRagDefault(options, config, activeDefault);
+): LightRagIndexingSelection | null {
+ return (
+ (preserveSavedPending ? indexingSelectionFromPolicy(savedPending) : null) ??
+ indexingSelectionFromDefaults(options, config, activeDefault)
+ );
}
interface KbIndexVersionsSectionProps {
kb: KnowledgeBase;
task?: TaskState;
- onReindex: (indexingLLM?: IndexingLLMSelection) => Promise<void>;
+ onReindex: (indexingLLM?: LightRagIndexingSelection) => Promise<void>;
onUpdatePendingIndexingPolicy: (
- indexingLLM: IndexingLLMSelection,
+ indexingLLM: LightRagIndexingSelection,
) => Promise<void>;
}
@@ -84,16 +80,15 @@ export default function KbIndexVersionsSection({
const { t } = useTranslation();
const [submitting, setSubmitting] = useState(false);
const [modelDialogOpen, setModelDialogOpen] = useState(false);
- const [indexingLLM, setIndexingLLM] = useState<IndexingLLMSelection | null>(
- null,
- );
+ const [indexingLLM, setIndexingLLM] =
+ useState<LightRagIndexingSelection | null>(null);
const [dialogError, setDialogError] = useState<string | null>(null);
const [lightRagConfig, setLightRagConfig] = useState<LightRagConfig | null>(
null,
);
const [lightRagConfigLoaded, setLightRagConfigLoaded] = useState(false);
const [lightRagConfigError, setLightRagConfigError] = useState(false);
- const llmCatalog = useLLMOptions();
+ const llmCatalog = useLLMOptions(getLightRagModelOptions);
const provider = kb.statistics?.rag_provider || "llamaindex";
const isLightRag = provider === "lightrag";
const pageIndexProvider = !providerUsesEmbeddingMetadata(provider);
@@ -157,14 +152,14 @@ export default function KbIndexVersionsSection({
llmCatalog.options,
lightRagConfig,
llmCatalog.activeDefault,
- kb.metadata?.indexing_policy?.selection,
+ kb.metadata?.indexing_policy,
emptyPendingEligible,
),
);
}, [
emptyPendingEligible,
indexingLLM,
- kb.metadata?.indexing_policy?.selection,
+ kb.metadata?.indexing_policy,
llmCatalog.activeDefault,
llmCatalog.options,
lightRagConfig,
@@ -192,7 +187,7 @@ export default function KbIndexVersionsSection({
};
const handleModelSubmit = async () => {
- if (!indexingLLM) return;
+ if (!isCompleteIndexingSelection(indexingLLM)) return;
setSubmitting(true);
setDialogError(null);
try {
@@ -404,7 +399,7 @@ export default function KbIndexVersionsSection({
<button
type="button"
onClick={() => void handleModelSubmit()}
- disabled={submitting || !indexingLLM}
+ disabled={submitting || !isCompleteIndexingSelection(indexingLLM)}
className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:opacity-50"
>
{submitting && <Loader2 className="h-3 w-3 animate-spin" />}
@@ -425,7 +420,7 @@ export default function KbIndexVersionsSection({
"A full re-index publishes a new version and then makes this model the pinned identity for future incremental uploads.",
)}
</p>
- <IndexingModelSelector
+ <LightRagIndexingSelector
options={llmCatalog.options}
selection={indexingLLM}
loading={llmCatalog.loading}
@@ -492,11 +487,11 @@ function IndexVersionRow({
? t("Failed rebuild candidate")
: isBuildingLightRagCandidate
? t("Rebuild candidate in progress")
- : isLegacy
- ? t("Legacy index")
- : version.model
- ? version.model
- : (version.signature ?? t("Unknown"));
+ : isLegacy
+ ? t("Legacy index")
+ : version.model
+ ? version.model
+ : (version.signature ?? t("Unknown"));
const created = formatKnowledgeTimestamp(version.created_at);
diff --git a/web/components/knowledge/KnowledgeBaseDetail.tsx b/web/components/knowledge/KnowledgeBaseDetail.tsx
index 2390c7c43..ff091c3dd 100644
--- a/web/components/knowledge/KnowledgeBaseDetail.tsx
+++ b/web/components/knowledge/KnowledgeBaseDetail.tsx
@@ -17,7 +17,7 @@ import {
Upload,
} from "lucide-react";
import type {
- IndexingLLMSelection,
+ LightRagIndexingSelection,
KnowledgeUploadPolicy,
} from "@/features/knowledge/model/types";
import {
@@ -57,11 +57,11 @@ interface KnowledgeBaseDetailProps {
) => Promise<void>;
onReindex: (
kbName: string,
- indexingLLM?: IndexingLLMSelection,
+ indexingLLM?: LightRagIndexingSelection,
) => Promise<void>;
onUpdatePendingIndexingPolicy: (
kbName: string,
- indexingLLM: IndexingLLMSelection,
+ indexingLLM: LightRagIndexingSelection,
) => Promise<void>;
onRetry: (kbName: string) => Promise<void>;
onSetDefault: (kbName: string) => Promise<void>;
diff --git a/web/components/knowledge/KnowledgePage.tsx b/web/components/knowledge/KnowledgePage.tsx
index e58d6d890..029f16a9b 100644
--- a/web/components/knowledge/KnowledgePage.tsx
+++ b/web/components/knowledge/KnowledgePage.tsx
@@ -12,7 +12,7 @@ import {
decodeResourceSegment,
knowledgeBaseRoute,
} from "@/lib/resource-routes";
-import type { IndexingLLMSelection } from "@/features/knowledge/model/types";
+import type { LightRagIndexingSelection } from "@/features/knowledge/model/types";
const panelLoading = () => (
<div
@@ -31,7 +31,9 @@ const KnowledgeBaseDetail = dynamic(() => import("./KnowledgeBaseDetail"), {
});
const EngineDetail = dynamic(
() => import("@/features/knowledge/components/engines/EngineDetail"),
- { loading: panelLoading },
+ {
+ loading: panelLoading,
+ },
);
const CreateKbModal = dynamic(() => import("./CreateKbModal"));
@@ -250,7 +252,7 @@ export default function KnowledgePage() {
);
const handleReindex = useCallback(
- async (kbName: string, indexingLLM?: IndexingLLMSelection) => {
+ async (kbName: string, indexingLLM?: LightRagIndexingSelection) => {
try {
await reindex(kbName, indexingLLM);
} catch (err) {
@@ -262,7 +264,7 @@ export default function KnowledgePage() {
);
const handleUpdatePendingIndexingPolicy = useCallback(
- async (kbName: string, indexingLLM: IndexingLLMSelection) => {
+ async (kbName: string, indexingLLM: LightRagIndexingSelection) => {
try {
await updatePendingIndexingPolicy(kbName, indexingLLM);
} catch (err) {
diff --git a/web/components/knowledge/LightRagIndexingProvenance.tsx b/web/components/knowledge/LightRagIndexingProvenance.tsx
index 337320e68..234e208dc 100644
--- a/web/components/knowledge/LightRagIndexingProvenance.tsx
+++ b/web/components/knowledge/LightRagIndexingProvenance.tsx
@@ -22,10 +22,24 @@ export default function LightRagIndexingProvenance({
const resolved = policy ?? { policy: "legacy_unpinned" };
const pending = resolved.policy === "pending_pinned";
const pinned = resolved.policy === "pinned" || pending;
- const model = resolved.descriptor?.model;
- const binding = resolved.descriptor?.binding;
+ const extract = resolved.schema_version === 2 ? resolved.extract : resolved;
+ const visionEnabled =
+ resolved.schema_version === 2
+ ? resolved.vlm?.mode === "enabled"
+ ? true
+ : resolved.vlm?.mode === "disabled"
+ ? false
+ : undefined
+ : resolved.vision_available;
+ const vision =
+ resolved.schema_version === 2 ? resolved.vlm?.snapshot : resolved;
+ const visionLabel = [vision?.descriptor?.binding, vision?.descriptor?.model]
+ .filter(Boolean)
+ .join(" · ");
+ const model = extract?.descriptor?.model;
+ const binding = extract?.descriptor?.binding;
const modelLabel = [binding, model].filter(Boolean).join(" · ");
- const effort = resolved.descriptor?.reasoning_effort;
+ const effort = extract?.descriptor?.reasoning_effort;
const title = pending
? t("Pending pinned indexing model")
: pinned
@@ -49,26 +63,37 @@ export default function LightRagIndexingProvenance({
<p className="mt-0.5 text-[11px] text-[var(--muted-foreground)]">
{summary}
</p>
+ {visionEnabled === false && (
+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">
+ {t(
+ "Image analysis is disabled. Enable a VLM through a full rebuild.",
+ )}
+ </p>
+ )}
{compact && (
<p className="mt-1 text-[11px] font-medium text-[var(--foreground)]">
+ {"EXTRACT: "}
{modelLabel || t("Unverified historical indexing model")}
{` · ${t("Reasoning effort")}: ${effort || t("Model default")}`}
+ {` · VLM: ${visionEnabled === true ? visionLabel || t("Unknown") : visionEnabled === false ? t("Image analysis disabled") : t("Unknown")}`}
</p>
)}
{!compact && (
<dl className="mt-2 grid gap-x-4 gap-y-1 text-[11px] sm:grid-cols-2">
- <ProvenanceField label={t("Model")}>
+ <ProvenanceField label={t("EXTRACT model")}>
{modelLabel || t("Unverified historical indexing model")}
</ProvenanceField>
<ProvenanceField label={t("Reasoning effort")}>
{effort || t("Model default")}
</ProvenanceField>
- <ProvenanceField label={t("VLM capability")}>
- {typeof resolved.vision_available === "boolean"
- ? resolved.vision_available
- ? t("Available")
- : t("Unavailable")
- : t("Unknown")}
+ <ProvenanceField label={t("VLM model")}>
+ {visionEnabled === true
+ ? visionLabel || t("Unknown")
+ : visionEnabled === false
+ ? t("Image analysis disabled")
+ : t("Unknown")}
+ {visionEnabled === true &&
+ ` · ${t("Reasoning effort")}: ${vision?.descriptor?.reasoning_effort || t("Model default")}`}
{resolved.vlm_used === true
? ` · ${t("used for this version")}`
: resolved.vlm_used === false
diff --git a/web/components/knowledge/LightRagIndexingSelector.tsx b/web/components/knowledge/LightRagIndexingSelector.tsx
new file mode 100644
index 000000000..61a34505e
--- /dev/null
+++ b/web/components/knowledge/LightRagIndexingSelector.tsx
@@ -0,0 +1,167 @@
+"use client";
+
+import { useTranslation } from "react-i18next";
+import type {
+ LightRagConfig,
+ LightRagIndexingSelection,
+} from "@/features/knowledge/model/types";
+import type { LLMOption, LLMOptionsResponse } from "@/lib/llm-options";
+import type { LightRagIndexingPolicy } from "@/lib/knowledge-helpers";
+import IndexingModelSelector, {
+ selectionFromLightRagDefault,
+} from "./IndexingModelSelector";
+import { resolvedRole } from "./LightRagRoleModelsEditor";
+
+export function indexingSelectionFromDefaults(
+ options: LLMOption[],
+ config: Pick<
+ LightRagConfig,
+ "llm_profile_id" | "llm_model_id" | "role_models"
+ >,
+ active?: LLMOptionsResponse["active"],
+): LightRagIndexingSelection | null {
+ if (config.role_models) {
+ const extract = resolvedRole(config.role_models, "extract");
+ const vlm = resolvedRole(config.role_models, "vlm");
+ return extract
+ ? {
+ extract,
+ vlm: vlm ? { mode: "enabled", selection: vlm } : { mode: "disabled" },
+ }
+ : null;
+ }
+ const selected = selectionFromLightRagDefault(options, config, active);
+ if (!selected) return null;
+ const vision =
+ options.find(
+ (option) =>
+ option.profile_id === selected.profile_id &&
+ option.model_id === selected.model_id,
+ )?.supports_vision === true;
+ return {
+ extract: selected,
+ vlm: vision
+ ? { mode: "enabled", selection: selected }
+ : { mode: "disabled" },
+ };
+}
+
+export function indexingSelectionFromPolicy(
+ policy?: LightRagIndexingPolicy,
+): LightRagIndexingSelection | null {
+ if (policy?.schema_version === 2 && policy.extract?.selection && policy.vlm) {
+ const extract = policy.extract.selection;
+ if (policy.vlm.mode === "disabled")
+ return { extract, vlm: { mode: "disabled" } };
+ if (policy.vlm.mode === "enabled" && policy.vlm.snapshot?.selection)
+ return {
+ extract,
+ vlm: { mode: "enabled", selection: policy.vlm.snapshot.selection },
+ };
+ return null;
+ }
+ if (policy?.selection && typeof policy.vision_available === "boolean") {
+ return {
+ extract: policy.selection,
+ vlm: policy.vision_available
+ ? { mode: "enabled", selection: policy.selection }
+ : { mode: "disabled" },
+ };
+ }
+ return null;
+}
+
+export function isCompleteIndexingSelection(
+ value: LightRagIndexingSelection | null,
+): value is LightRagIndexingSelection {
+ return Boolean(
+ value?.extract.profile_id &&
+ value.extract.model_id &&
+ (value.vlm.mode === "disabled" ||
+ (value.vlm.selection?.profile_id && value.vlm.selection.model_id)),
+ );
+}
+
+export default function LightRagIndexingSelector({
+ options,
+ selection,
+ onChange,
+ ...state
+}: {
+ options: LLMOption[];
+ selection: LightRagIndexingSelection | null;
+ onChange: (value: LightRagIndexingSelection | null) => void;
+ loading: boolean;
+ error: boolean;
+ defaultUnavailable?: boolean;
+ defaultLoadError?: boolean;
+ disabled?: boolean;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className="space-y-4">
+ <p className="text-xs text-[var(--muted-foreground)]">
+ {t(
+ "Prefilled from the engine's EXTRACT and VLM settings. Changes here apply only to this new or rebuilt index.",
+ )}
+ </p>
+ <IndexingModelSelector
+ {...state}
+ label="EXTRACT model"
+ options={options}
+ selection={selection?.extract ?? null}
+ onChange={(extract) =>
+ onChange(
+ extract
+ ? { extract, vlm: selection?.vlm ?? { mode: "disabled" } }
+ : null,
+ )
+ }
+ />
+ {selection && (
+ <>
+ <label className="block text-xs">
+ {t("VLM image analysis")}
+ <select
+ aria-label={t("VLM image analysis")}
+ value={selection.vlm.mode}
+ disabled={state.disabled}
+ onChange={(event) => {
+ onChange({
+ ...selection,
+ vlm:
+ event.target.value === "enabled"
+ ? { mode: "enabled" }
+ : { mode: "disabled" },
+ });
+ }}
+ className="mt-1 w-full rounded-lg border border-[var(--border)] bg-[var(--background)] p-2"
+ >
+ <option value="disabled">{t("Image analysis disabled")}</option>
+ <option value="enabled">{t("Choose a vision model")}</option>
+ </select>
+ </label>
+ {selection.vlm.mode === "enabled" && (
+ <IndexingModelSelector
+ {...state}
+ label="VLM model"
+ options={options.filter((option) => option.supports_vision)}
+ selection={selection.vlm.selection ?? null}
+ onChange={(vlm) =>
+ onChange({
+ ...selection,
+ vlm: { mode: "enabled", ...(vlm ? { selection: vlm } : {}) },
+ })
+ }
+ />
+ )}
+ <p className="text-xs text-[var(--muted-foreground)]">
+ {t(
+ "After publication, enabling, disabling or replacing VLM requires a full rebuild. A VLM pinned now can process later image uploads.",
+ )}
+ </p>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/web/components/knowledge/LightRagRoleModelsEditor.tsx b/web/components/knowledge/LightRagRoleModelsEditor.tsx
new file mode 100644
index 000000000..b2fe00f22
--- /dev/null
+++ b/web/components/knowledge/LightRagRoleModelsEditor.tsx
@@ -0,0 +1,198 @@
+"use client";
+
+import { useTranslation } from "react-i18next";
+import type {
+ IndexingLLMSelection,
+ LightRagRoleModel,
+ LightRagRoleModels,
+} from "@/features/knowledge/model/types";
+import type { LLMOption } from "@/lib/llm-options";
+import IndexingModelSelector from "./IndexingModelSelector";
+
+export const inheritedRole = (): LightRagRoleModel => ({
+ mode: "inherit",
+ max_async: 4,
+ timeout: 240,
+});
+export const newRoleModels = (
+ base: IndexingLLMSelection,
+ vision = false,
+): LightRagRoleModels => ({
+ base,
+ extract: inheritedRole(),
+ keyword: inheritedRole(),
+ query: inheritedRole(),
+ vlm: { ...inheritedRole(), mode: vision ? "inherit" : "disabled" },
+});
+
+export function resolvedRole(
+ models: LightRagRoleModels,
+ role: "extract" | "keyword" | "query" | "vlm",
+): IndexingLLMSelection | null {
+ const value = models[role];
+ if (value.mode === "disabled") return null;
+ const selected = value.mode === "inherit" ? models.base : value.selection;
+ if (!selected) return null;
+ return {
+ ...selected,
+ ...(value.reasoning_effort
+ ? { reasoning_effort: value.reasoning_effort }
+ : {}),
+ };
+}
+
+export default function LightRagRoleModelsEditor({
+ models,
+ options,
+ loading,
+ error,
+ disabled,
+ onChange,
+}: {
+ models: LightRagRoleModels | null;
+ options: LLMOption[];
+ loading: boolean;
+ error: boolean;
+ disabled?: boolean;
+ onChange: (value: LightRagRoleModels) => void;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className="space-y-4">
+ <IndexingModelSelector
+ label="LightRAG base model"
+ options={options}
+ selection={models?.base ?? null}
+ loading={loading}
+ error={error}
+ disabled={disabled}
+ onChange={(base) => {
+ if (base)
+ onChange(models ? { ...models, base } : newRoleModels(base));
+ }}
+ />
+ {models &&
+ (["extract", "keyword", "query", "vlm"] as const).map((role) => {
+ const value = models[role];
+ const effective = resolvedRole(models, role);
+ const update = (patch: Partial<LightRagRoleModel>) =>
+ onChange({ ...models, [role]: { ...value, ...patch } });
+ return (
+ <fieldset
+ key={role}
+ className="space-y-3 rounded-lg border border-[var(--border)] p-3"
+ disabled={disabled}
+ >
+ <legend className="px-1 text-sm font-medium">
+ {role.toUpperCase()}
+ </legend>
+ <label className="block text-xs">
+ {t("Model source")}
+ <select
+ aria-label={`${role.toUpperCase()} ${t("Model source")}`}
+ value={value.mode}
+ className="mt-1 w-full rounded-lg border border-[var(--border)] bg-[var(--background)] p-2"
+ onChange={(event) => {
+ const mode = event.target
+ .value as LightRagRoleModel["mode"];
+ update({
+ mode,
+ selection:
+ mode === "model"
+ ? {
+ profile_id: models.base.profile_id,
+ model_id: models.base.model_id,
+ }
+ : null,
+ reasoning_effort: null,
+ });
+ }}
+ >
+ {role === "vlm" && (
+ <option value="disabled">
+ {t("Image analysis disabled")}
+ </option>
+ )}
+ <option value="inherit">
+ {t("Inherit LightRAG base model")}
+ </option>
+ <option value="model">{t("Choose a model")}</option>
+ </select>
+ </label>
+ {value.mode !== "disabled" && (
+ <IndexingModelSelector
+ label={`${role.toUpperCase()} ${t("effective model")}`}
+ options={
+ role === "vlm" && value.mode === "model"
+ ? options.filter((option) => option.supports_vision)
+ : options
+ }
+ selection={effective}
+ loading={loading}
+ error={error}
+ lockModel={value.mode === "inherit"}
+ onChange={(selection) => {
+ if (selection)
+ update({
+ selection:
+ value.mode === "model"
+ ? {
+ profile_id: selection.profile_id,
+ model_id: selection.model_id,
+ }
+ : null,
+ reasoning_effort: selection.reasoning_effort ?? null,
+ });
+ }}
+ />
+ )}
+ {role === "vlm" &&
+ value.mode !== "disabled" &&
+ !options.some(
+ (option) =>
+ option.profile_id === effective?.profile_id &&
+ option.model_id === effective?.model_id &&
+ option.supports_vision,
+ ) && (
+ <p className="text-xs text-red-600">
+ {t("The selected VLM model does not support image inputs.")}
+ </p>
+ )}
+ {value.mode !== "disabled" && (
+ <div className="grid grid-cols-2 gap-3">
+ <label className="text-xs">
+ {t("Concurrent LLM calls")}
+ <input
+ aria-label={`${role.toUpperCase()} ${t("Concurrent LLM calls")}`}
+ type="number"
+ min={1}
+ max={32}
+ value={value.max_async}
+ onChange={(event) =>
+ update({ max_async: Number(event.target.value) })
+ }
+ className="mt-1 w-full rounded border border-[var(--border)] bg-[var(--background)] p-2"
+ />
+ </label>
+ <label className="text-xs">
+ {t("Timeout (seconds)")}
+ <input
+ aria-label={`${role.toUpperCase()} ${t("Timeout (seconds)")}`}
+ type="number"
+ min={1}
+ max={3600}
+ value={value.timeout}
+ onChange={(event) =>
+ update({ timeout: Number(event.target.value) })
+ }
+ className="mt-1 w-full rounded border border-[var(--border)] bg-[var(--background)] p-2"
+ />
+ </label>
+ </div>
+ )}
+ </fieldset>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/web/contracts/generated/api.ts b/web/contracts/generated/api.ts
index 9abb3d082..a15e103d1 100644
--- a/web/contracts/generated/api.ts
+++ b/web/contracts/generated/api.ts
@@ -1534,10 +1534,7 @@ export interface paths {
*/
readonly get: operations["list_knowledge_bases_api_knowledge_bases_get"];
readonly put?: never;
- /**
- * Create Knowledge Base
- * @description Create a new knowledge base and initialize it with files.
- */
+ /** Create Knowledge Base */
readonly post: operations["create_knowledge_base_api_knowledge_bases_post"];
readonly delete?: never;
readonly options?: never;
@@ -1775,10 +1772,7 @@ export interface paths {
readonly cookie?: never;
};
readonly get?: never;
- /**
- * Update Pending Indexing Policy
- * @description Change the pending model of an empty, unpublished LightRAG KB.
- */
+ /** Update Pending Indexing Policy */
readonly put: operations["update_pending_indexing_policy_api_knowledge_bases__kb_name__indexing_policy_put"];
readonly post?: never;
readonly delete?: never;
@@ -2597,6 +2591,26 @@ export interface paths {
readonly patch?: never;
readonly trace?: never;
};
+ readonly "/api/knowledge-bases/rag-pipelines/lightrag/model-options": {
+ readonly parameters: {
+ readonly query?: never;
+ readonly header?: never;
+ readonly path?: never;
+ readonly cookie?: never;
+ };
+ /**
+ * Get Lightrag Model Options
+ * @description Return accessible catalog models with supported role capabilities.
+ */
+ readonly get: operations["get_lightrag_model_options_api_knowledge_bases_rag_pipelines_lightrag_model_options_get"];
+ readonly put?: never;
+ readonly post?: never;
+ readonly delete?: never;
+ readonly options?: never;
+ readonly head?: never;
+ readonly patch?: never;
+ readonly trace?: never;
+ };
readonly "/api/knowledge-bases/rag-pipelines/llamaindex/config": {
readonly parameters: {
readonly query?: never;
@@ -9312,6 +9326,11 @@ export interface components {
readonly dest_subdir?: string;
/** Files */
readonly files: readonly string[];
+ /**
+ * Image Analysis
+ * @description Require image analysis with the pinned VLM; false skips images, omitted follows the pinned policy.
+ */
+ readonly image_analysis?: boolean | null;
/** Rag Provider */
readonly rag_provider?: string;
/** Rel Paths */
@@ -10864,9 +10883,91 @@ export interface components {
readonly max_concurrent_files?: number | null;
/** Response Type */
readonly response_type?: string | null;
+ readonly role_models?: components["schemas"]["LightRagRoleModels"] | null;
/** Top K */
readonly top_k?: number | null;
};
+ /**
+ * LightRagIndexingSelection
+ * @description Resolved create/rebuild overrides, without mutable engine inheritance.
+ */
+ readonly LightRagIndexingSelection: {
+ readonly extract: components["schemas"]["LightRagModelSelection"];
+ readonly vlm?: components["schemas"]["LightRagIndexingVision"];
+ };
+ /** LightRagIndexingVision */
+ readonly LightRagIndexingVision: {
+ /**
+ * Mode
+ * @default disabled
+ * @enum {string}
+ */
+ readonly mode: "disabled" | "enabled";
+ readonly selection?:
+ components["schemas"]["LightRagModelSelection"] | null;
+ };
+ /** LightRagModelSelection */
+ readonly LightRagModelSelection: {
+ /** Model Id */
+ readonly model_id: string;
+ /** Profile Id */
+ readonly profile_id: string;
+ /** Reasoning Effort */
+ readonly reasoning_effort?:
+ | (
+ | "none"
+ | "minimal"
+ | "low"
+ | "medium"
+ | "high"
+ | "xhigh"
+ | "max"
+ | "adaptive"
+ )
+ | null;
+ };
+ /** LightRagRoleModel */
+ readonly LightRagRoleModel: {
+ /**
+ * Max Async
+ * @default 4
+ */
+ readonly max_async: number;
+ /**
+ * Mode
+ * @default inherit
+ * @enum {string}
+ */
+ readonly mode: "inherit" | "model";
+ /** Reasoning Effort */
+ readonly reasoning_effort?:
+ | (
+ | "none"
+ | "minimal"
+ | "low"
+ | "medium"
+ | "high"
+ | "xhigh"
+ | "max"
+ | "adaptive"
+ )
+ | null;
+ readonly selection?:
+ components["schemas"]["LightRagModelSelection"] | null;
+ /**
+ * Timeout
+ * @default 240
+ */
+ readonly timeout: number;
+ };
+ /** LightRagRoleModels */
+ readonly LightRagRoleModels: {
+ readonly base: components["schemas"]["LightRagModelSelection"];
+ readonly extract?: components["schemas"]["LightRagRoleModel"];
+ readonly keyword?: components["schemas"]["LightRagRoleModel"];
+ readonly query?: components["schemas"]["LightRagRoleModel"];
+ readonly vlm?: components["schemas"]["LightRagVisionModel"];
+ };
/**
* LightRagServerConfigUpdate
* @description Reusable LightRAG Server defaults (individual KBs may override them).
@@ -10877,6 +10978,40 @@ export interface components {
/** Server Url */
readonly server_url?: string | null;
};
+ /** LightRagVisionModel */
+ readonly LightRagVisionModel: {
+ /**
+ * Max Async
+ * @default 4
+ */
+ readonly max_async: number;
+ /**
+ * Mode
+ * @default disabled
+ * @enum {string}
+ */
+ readonly mode: "disabled" | "inherit" | "model";
+ /** Reasoning Effort */
+ readonly reasoning_effort?:
+ | (
+ | "none"
+ | "minimal"
+ | "low"
+ | "medium"
+ | "high"
+ | "xhigh"
+ | "max"
+ | "adaptive"
+ )
+ | null;
+ readonly selection?:
+ components["schemas"]["LightRagModelSelection"] | null;
+ /**
+ * Timeout
+ * @default 240
+ */
+ readonly timeout: number;
+ };
/**
* LinkedFolderInfo
* @description Response model for linked folder information.
@@ -13683,8 +13818,20 @@ export type SchemaLearningCaptureUpdateRequest =
components["schemas"]["LearningCaptureUpdateRequest"];
export type SchemaLightRagConfigUpdate =
components["schemas"]["LightRagConfigUpdate"];
+export type SchemaLightRagIndexingSelection =
+ components["schemas"]["LightRagIndexingSelection"];
+export type SchemaLightRagIndexingVision =
+ components["schemas"]["LightRagIndexingVision"];
+export type SchemaLightRagModelSelection =
+ components["schemas"]["LightRagModelSelection"];
+export type SchemaLightRagRoleModel =
+ components["schemas"]["LightRagRoleModel"];
+export type SchemaLightRagRoleModels =
+ components["schemas"]["LightRagRoleModels"];
export type SchemaLightRagServerConfigUpdate =
components["schemas"]["LightRagServerConfigUpdate"];
+export type SchemaLightRagVisionModel =
+ components["schemas"]["LightRagVisionModel"];
export type SchemaLinkedFolderInfo = components["schemas"]["LinkedFolderInfo"];
export type SchemaLinkFolderRequest =
components["schemas"]["LinkFolderRequest"];
@@ -17905,7 +18052,9 @@ export interface operations {
};
readonly requestBody: {
readonly content: {
- readonly "application/json": components["schemas"]["IndexingLLMSelectionRequest"];
+ readonly "application/json":
+ | components["schemas"]["LightRagIndexingSelection"]
+ | components["schemas"]["IndexingLLMSelectionRequest"];
};
};
readonly responses: {
@@ -19401,6 +19550,39 @@ export interface operations {
};
};
};
+ readonly get_lightrag_model_options_api_knowledge_bases_rag_pipelines_lightrag_model_options_get: {
+ readonly parameters: {
+ readonly query?: never;
+ readonly header?: {
+ readonly Authorization?: string | null;
+ };
+ readonly path?: never;
+ readonly cookie?: {
+ readonly dt_token?: string | null;
+ };
+ };
+ readonly requestBody?: never;
+ readonly responses: {
+ /** @description Successful Response */
+ readonly 200: {
+ headers: {
+ readonly [name: string]: unknown;
+ };
+ content: {
+ readonly "application/json": unknown;
+ };
+ };
+ /** @description Validation Error */
+ readonly 422: {
+ headers: {
+ readonly [name: string]: unknown;
+ };
+ content: {
+ readonly "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
readonly get_llamaindex_pipeline_config_api_knowledge_bases_rag_pipelines_llamaindex_config_get: {
readonly parameters: {
readonly query?: never;
diff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.json
index 05c5efeff..a277a5c7b 100644
--- a/web/contracts/schema/openapi.json
+++ b/web/contracts/schema/openapi.json
@@ -814,6 +814,18 @@
"title": "Files",
"type": "array"
},
+ "image_analysis": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Require image analysis with the pinned VLM; false skips images, omitted follows the pinned policy.",
+ "title": "Image Analysis"
+ },
"rag_provider": {
"title": "Rag Provider",
"type": "string"
@@ -4383,6 +4395,16 @@
],
"title": "Response Type"
},
+ "role_models": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/LightRagRoleModels"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"top_k": {
"anyOf": [
{
@@ -4398,6 +4420,179 @@
"title": "LightRagConfigUpdate",
"type": "object"
},
+ "LightRagIndexingSelection": {
+ "additionalProperties": false,
+ "description": "Resolved create/rebuild overrides, without mutable engine inheritance.",
+ "properties": {
+ "extract": {
+ "$ref": "#/components/schemas/LightRagModelSelection"
+ },
+ "vlm": {
+ "$ref": "#/components/schemas/LightRagIndexingVision"
+ }
+ },
+ "required": [
+ "extract"
+ ],
+ "title": "LightRagIndexingSelection",
+ "type": "object"
+ },
+ "LightRagIndexingVision": {
+ "additionalProperties": false,
+ "properties": {
+ "mode": {
+ "default": "disabled",
+ "enum": [
+ "disabled",
+ "enabled"
+ ],
+ "title": "Mode",
+ "type": "string"
+ },
+ "selection": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/LightRagModelSelection"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "title": "LightRagIndexingVision",
+ "type": "object"
+ },
+ "LightRagModelSelection": {
+ "additionalProperties": false,
+ "properties": {
+ "model_id": {
+ "maxLength": 128,
+ "minLength": 1,
+ "title": "Model Id",
+ "type": "string"
+ },
+ "profile_id": {
+ "maxLength": 128,
+ "minLength": 1,
+ "title": "Profile Id",
+ "type": "string"
+ },
+ "reasoning_effort": {
+ "anyOf": [
+ {
+ "enum": [
+ "none",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "adaptive"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Reasoning Effort"
+ }
+ },
+ "required": [
+ "profile_id",
+ "model_id"
+ ],
+ "title": "LightRagModelSelection",
+ "type": "object"
+ },
+ "LightRagRoleModel": {
+ "additionalProperties": false,
+ "properties": {
+ "max_async": {
+ "default": 4,
+ "maximum": 32.0,
+ "minimum": 1.0,
+ "title": "Max Async",
+ "type": "integer"
+ },
+ "mode": {
+ "default": "inherit",
+ "enum": [
+ "inherit",
+ "model"
+ ],
+ "title": "Mode",
+ "type": "string"
+ },
+ "reasoning_effort": {
+ "anyOf": [
+ {
+ "enum": [
+ "none",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "adaptive"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Reasoning Effort"
+ },
+ "selection": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/LightRagModelSelection"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "timeout": {
+ "default": 240,
+ "maximum": 3600.0,
+ "minimum": 1.0,
+ "title": "Timeout",
+ "type": "integer"
+ }
+ },
+ "title": "LightRagRoleModel",
+ "type": "object"
+ },
+ "LightRagRoleModels": {
+ "additionalProperties": false,
+ "properties": {
+ "base": {
+ "$ref": "#/components/schemas/LightRagModelSelection"
+ },
+ "extract": {
+ "$ref": "#/components/schemas/LightRagRoleModel"
+ },
+ "keyword": {
+ "$ref": "#/components/schemas/LightRagRoleModel"
+ },
+ "query": {
+ "$ref": "#/components/schemas/LightRagRoleModel"
+ },
+ "vlm": {
+ "$ref": "#/components/schemas/LightRagVisionModel"
+ }
+ },
+ "required": [
+ "base"
+ ],
+ "title": "LightRagRoleModels",
+ "type": "object"
+ },
"LightRagServerConfigUpdate": {
"description": "Reusable LightRAG Server defaults (individual KBs may override them).",
"properties": {
@@ -4427,6 +4622,68 @@
"title": "LightRagServerConfigUpdate",
"type": "object"
},
+ "LightRagVisionModel": {
+ "additionalProperties": false,
+ "properties": {
+ "max_async": {
+ "default": 4,
+ "maximum": 32.0,
+ "minimum": 1.0,
+ "title": "Max Async",
+ "type": "integer"
+ },
+ "mode": {
+ "default": "disabled",
+ "enum": [
+ "disabled",
+ "inherit",
+ "model"
+ ],
+ "title": "Mode",
+ "type": "string"
+ },
+ "reasoning_effort": {
+ "anyOf": [
+ {
+ "enum": [
+ "none",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "adaptive"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Reasoning Effort"
+ },
+ "selection": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/LightRagModelSelection"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "timeout": {
+ "default": 240,
+ "maximum": 3600.0,
+ "minimum": 1.0,
+ "title": "Timeout",
+ "type": "integer"
+ }
+ },
+ "title": "LightRagVisionModel",
+ "type": "object"
+ },
"LinkFolderRequest": {
"description": "Request model for linking a local folder to a KB.",
"properties": {
@@ -16991,7 +17248,6 @@
]
},
"post": {
- "description": "Create a new knowledge base and initialize it with files.",
"operationId": "create_knowledge_base_api_knowledge_bases_post",
"parameters": [
{
@@ -18900,6 +19156,70 @@
]
}
},
+ "/api/knowledge-bases/rag-pipelines/lightrag/model-options": {
+ "get": {
+ "description": "Return accessible catalog models with supported role capabilities.",
+ "operationId": "get_lightrag_model_options_api_knowledge_bases_rag_pipelines_lightrag_model_options_get",
+ "parameters": [
+ {
+ "in": "header",
+ "name": "Authorization",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Authorization"
+ }
+ },
+ {
+ "in": "cookie",
+ "name": "dt_token",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Dt Token"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "summary": "Get Lightrag Model Options",
+ "tags": [
+ "knowledge-bases"
+ ]
+ }
+ },
"/api/knowledge-bases/rag-pipelines/llamaindex/config": {
"get": {
"description": "Read the LlamaIndex engine's retrieval + chunking knobs.",
@@ -20633,7 +20953,6 @@
},
"/api/knowledge-bases/{kb_name}/indexing-policy": {
"put": {
- "description": "Change the pending model of an empty, unpublished LightRAG KB.",
"operationId": "update_pending_indexing_policy_api_knowledge_bases__kb_name__indexing_policy_put",
"parameters": [
{
@@ -20682,7 +21001,15 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/IndexingLLMSelectionRequest"
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/LightRagIndexingSelection"
+ },
+ {
+ "$ref": "#/components/schemas/IndexingLLMSelectionRequest"
+ }
+ ],
+ "title": "Payload"
}
}
},
diff --git a/web/features/knowledge/api/catalog.ts b/web/features/knowledge/api/catalog.ts
index f92d4c104..9e99933da 100644
--- a/web/features/knowledge/api/catalog.ts
+++ b/web/features/knowledge/api/catalog.ts
@@ -23,6 +23,7 @@ export {
export type {
IndexingLLMSelection,
+ LightRagIndexingSelection,
ImaKnowledgeBasePage,
ImaProbe,
KnowledgeBaseSummary,
diff --git a/web/features/knowledge/api/client.ts b/web/features/knowledge/api/client.ts
index 6fc015a69..e4383f4ff 100644
--- a/web/features/knowledge/api/client.ts
+++ b/web/features/knowledge/api/client.ts
@@ -90,7 +90,29 @@ export interface GraphRagConfig {
dynamic_community_selection: boolean;
}
+export interface LightRagRoleModel {
+ mode: "inherit" | "model" | "disabled";
+ selection?: IndexingLLMSelection | null;
+ reasoning_effort?: string | null;
+ max_async: number;
+ timeout: number;
+}
+
+export interface LightRagRoleModels {
+ base: IndexingLLMSelection;
+ extract: LightRagRoleModel;
+ keyword: LightRagRoleModel;
+ query: LightRagRoleModel;
+ vlm: LightRagRoleModel;
+}
+
+export interface LightRagIndexingSelection {
+ extract: IndexingLLMSelection;
+ vlm: { mode: "disabled" | "enabled"; selection?: IndexingLLMSelection };
+}
+
export interface LightRagConfig {
+ role_models?: LightRagRoleModels;
version: number;
top_k: number;
response_type: string;
@@ -477,6 +499,22 @@ export const updateGraphRagConfig = (
payload: Partial<Omit<GraphRagConfig, "version">>,
) => updateEngineConfig<GraphRagConfig>("graphrag", payload);
+export async function getLightRagModelOptions(): Promise<
+ import("@/lib/llm-options").LLMOptionsResponse
+> {
+ const res = await apiFetch(
+ apiUrl("/api/knowledge-bases/rag-pipelines/lightrag/model-options"),
+ {
+ cache: "no-store",
+ },
+ );
+ if (!res.ok)
+ throw new Error(
+ await readErrorDetail(res, "Failed to load LightRAG models"),
+ );
+ return res.json();
+}
+
export const getLightRagConfig = (options?: { force?: boolean }) =>
getEngineConfig<LightRagConfig>("lightrag", "lightrag-config", options);
export const updateLightRagConfig = (
@@ -689,7 +727,7 @@ export async function createKnowledgeBase(payload: {
files: File[];
pageindexMode?: "flash" | "standard";
searchMode?: string;
- indexingLLM?: IndexingLLMSelection;
+ indexingLLM?: IndexingLLMSelection | LightRagIndexingSelection;
}): Promise<KnowledgeTaskResponse> {
const form = new FormData();
form.append("name", payload.name);
@@ -1183,7 +1221,7 @@ export async function setDefaultKnowledgeBase(name: string): Promise<void> {
export async function reindexKnowledgeBase(
name: string,
- indexingLLM?: IndexingLLMSelection,
+ indexingLLM?: IndexingLLMSelection | LightRagIndexingSelection,
): Promise<KnowledgeTaskResponse> {
const request: RequestInit = { method: "POST" };
if (indexingLLM) {
@@ -1210,7 +1248,7 @@ export async function reindexKnowledgeBase(
export async function updatePendingIndexingPolicy(
name: string,
- indexingLLM: IndexingLLMSelection,
+ indexingLLM: IndexingLLMSelection | LightRagIndexingSelection,
): Promise<{ indexing_policy: Record<string, unknown> }> {
const res = await apiFetch(
apiUrl(`/api/knowledge-bases/${encodeURIComponent(name)}/indexing-policy`),
diff --git a/web/features/knowledge/api/engines.ts b/web/features/knowledge/api/engines.ts
index 55b3a6c40..2ffa57702 100644
--- a/web/features/knowledge/api/engines.ts
+++ b/web/features/knowledge/api/engines.ts
@@ -5,6 +5,7 @@ export {
getGraphRagConfig,
getImaConfig,
getLightRagConfig,
+ getLightRagModelOptions,
getLightRagServerConfig,
getLlamaIndexConfig,
getPageIndexConfig,
diff --git a/web/features/knowledge/components/engines/EngineDetail.tsx b/web/features/knowledge/components/engines/EngineDetail.tsx
index 6f827d62b..0867092b0 100644
--- a/web/features/knowledge/components/engines/EngineDetail.tsx
+++ b/web/features/knowledge/components/engines/EngineDetail.tsx
@@ -28,6 +28,7 @@ import {
getEnginePreflight,
getGraphRagConfig,
getLightRagConfig,
+ getLightRagModelOptions,
getLightRagServerConfig,
getImaConfig,
getLlamaIndexConfig,
@@ -62,6 +63,13 @@ import {
import { PageIndexConfigForm } from "@/components/knowledge/PageIndexSettingsModal";
import KnowledgeEngineIcon from "@/components/knowledge/KnowledgeEngineIcon";
+import { useAuthStatus } from "@/hooks/useAuthStatus";
+import { useLLMOptions } from "@/hooks/useLLMOptions";
+import LightRagRoleModelsEditor, {
+ newRoleModels,
+} from "@/components/knowledge/LightRagRoleModelsEditor";
+import { selectionFromLightRagDefault } from "@/components/knowledge/IndexingModelSelector";
+
export interface EngineDetailProps {
provider: RagProviderSummary;
kbs: KnowledgeBase[];
@@ -1050,45 +1058,37 @@ export function LightRagForm({
onError: (message: string) => void;
}) {
const { t } = useTranslation();
- const [modelOptions, setModelOptions] = useState<ModelOptionsByKind | null>(
- null,
- );
+ const catalog = useLLMOptions(getLightRagModelOptions);
+ const auth = useAuthStatus();
+ const canEdit = auth.statusAvailable && (!auth.enabled || auth.isAdmin);
const { form, setLoaded, setForm, saving, setSaving, dirty, patch } =
useEngineForm<LightRagConfig>(
() => getLightRagConfig({ force: true }),
onError,
);
- useEffect(() => {
- let cancelled = false;
- getEngineModelOptions(["llm"])
- .then((data) => !cancelled && setModelOptions(data))
- .catch(
- () =>
- !cancelled &&
- setModelOptions({
- llm: { active: { profile_id: null, model_id: null }, options: [] },
- }),
- );
- return () => {
- cancelled = true;
- };
- }, []);
-
if (!form) return <FormSkeleton />;
-
- const llmEntry = modelOptions?.llm;
- const selectedProfileId = form.llm_profile_id;
- const selectedModelId = form.llm_model_id;
- const selectedValue =
- selectedProfileId && selectedModelId
- ? `${selectedProfileId}::${selectedModelId}`
- : "";
- const selectedOption = llmEntry?.options.find(
- (option) => `${option.profile_id}::${option.model_id}` === selectedValue,
+ const legacyBase = selectionFromLightRagDefault(
+ catalog.options,
+ form,
+ catalog.activeDefault,
+ );
+ const legacyOption = catalog.options.find(
+ (option) =>
+ option.profile_id === legacyBase?.profile_id &&
+ option.model_id === legacyBase?.model_id,
);
+ const roleModels =
+ form.role_models ??
+ (legacyBase
+ ? newRoleModels(legacyBase, legacyOption?.supports_vision === true)
+ : null);
const save = async () => {
+ if (!roleModels) {
+ onError(t("Choose a LightRAG base model before saving."));
+ return;
+ }
setSaving(true);
try {
const next = await updateLightRagConfig({
@@ -1097,8 +1097,7 @@ export function LightRagForm({
max_concurrent_files: form.max_concurrent_files,
llm_model_max_async: form.llm_model_max_async,
entity_extract_max_gleaning: form.entity_extract_max_gleaning,
- llm_profile_id: form.llm_profile_id,
- llm_model_id: form.llm_model_id,
+ role_models: roleModels ?? undefined,
});
setLoaded(next);
setForm(next);
@@ -1111,7 +1110,15 @@ export function LightRagForm({
};
return (
- <div className="space-y-5 rounded-2xl border border-[var(--border)] p-4">
+ <fieldset
+ disabled={!canEdit || saving}
+ className="space-y-5 rounded-2xl border border-[var(--border)] p-4"
+ >
+ {!auth.loading && !canEdit && (
+ <p className="text-xs text-[var(--muted-foreground)]">
+ {t("Only administrators can change shared LightRAG engine settings.")}
+ </p>
+ )}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<NumberField
label={t("Results per query")}
@@ -1124,54 +1131,34 @@ export function LightRagForm({
value={form.response_type}
onChange={(v) => patch({ response_type: v })}
/>
- <label className="flex flex-col gap-1">
- <span className="text-[12px] font-medium text-[var(--foreground)]">
- {t("LightRAG query model")}
- </span>
- <select
- value={selectedValue}
- disabled={!llmEntry}
- onChange={(event) => {
- const [profileId, modelId] = event.target.value.split("::");
- patch({
- llm_profile_id: profileId || "",
- llm_model_id: modelId || "",
- });
- }}
- className="w-full cursor-pointer rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"
- >
- {!llmEntry ? (
- <option value="">{t("Loading models…")}</option>
- ) : (
- <>
- <option value="">{t("Use active chat model")}</option>
- {selectedValue && !selectedOption && (
- <option value={selectedValue}>
- {t("Selected model unavailable")}
- </option>
- )}
- {llmEntry.options.map((option) => (
- <option
- key={`${option.profile_id}::${option.model_id}`}
- value={`${option.profile_id}::${option.model_id}`}
- >
- {option.label}
- {option.model && option.model !== option.label
- ? ` · ${option.model}`
- : ""}
- </option>
- ))}
- </>
- )}
- </select>
- <span className="text-[11px] text-[var(--muted-foreground)]">
- {t(
- "Used for current LightRAG queries and as the default indexing model for new or fully rebuilt knowledge bases. Published indexes keep their pinned indexing model.",
- )}
- </span>
- </label>
</div>
+ {!form.role_models && (
+ <p className="text-xs text-[var(--muted-foreground)]">
+ {t(
+ "Legacy model settings are shown below. Saving fixes the LightRAG base selection independently of chat.",
+ )}
+ </p>
+ )}
+ <LightRagRoleModelsEditor
+ models={roleModels}
+ options={catalog.options}
+ loading={catalog.loading}
+ error={catalog.error}
+ disabled={saving}
+ onChange={(role_models) => patch({ role_models })}
+ />
+ <p className="text-xs text-[var(--muted-foreground)]">
+ {t(
+ "KEYWORD and QUERY apply to subsequent queries. EXTRACT and VLM apply to new or fully rebuilt indexes; published indexes keep their pinned models.",
+ )}
+ </p>
+ <p className="text-xs text-[var(--muted-foreground)]">
+ {t(
+ "Role concurrency and timeouts apply to subsequent tasks without rebuilding.",
+ )}
+ </p>
+
{/* Indexing knobs are a separate axis from the two above: they shape how
a knowledge base is built, so changing them only affects the next
build — the divider and note keep that from surprising anyone. */}
@@ -1193,14 +1180,6 @@ export function LightRagForm({
max={16}
onChange={(v) => patch({ max_concurrent_files: v })}
/>
- <NumberField
- label={t("Concurrent LLM calls")}
- hint={t("Lower this if your provider rate-limits you")}
- value={form.llm_model_max_async}
- min={1}
- max={32}
- onChange={(v) => patch({ llm_model_max_async: v })}
- />
<NumberField
label={t("Extra extraction passes")}
hint={t("Recovers missed entities; each pass costs another call")}
@@ -1212,8 +1191,12 @@ export function LightRagForm({
</div>
</div>
- <SaveButton dirty={dirty} saving={saving} onSave={() => void save()} />
- </div>
+ <SaveButton
+ dirty={dirty || (!form.role_models && roleModels !== null)}
+ saving={saving}
+ onSave={() => void save()}
+ />
+ </fieldset>
);
}
diff --git a/web/features/knowledge/model/types.ts b/web/features/knowledge/model/types.ts
index eb495bed3..81e4ba5d4 100644
--- a/web/features/knowledge/model/types.ts
+++ b/web/features/knowledge/model/types.ts
@@ -15,6 +15,9 @@ export type {
KnowledgeTaskResponse,
KnowledgeUploadPolicy,
LightRagConfig,
+ LightRagRoleModel,
+ LightRagRoleModels,
+ LightRagIndexingSelection,
LightRagServerConfig,
LightRagServerProbe,
LinkedFolderProbe,
diff --git a/web/hooks/useKnowledgeBases.ts b/web/hooks/useKnowledgeBases.ts
index 2b1912439..32065de5a 100644
--- a/web/hooks/useKnowledgeBases.ts
+++ b/web/hooks/useKnowledgeBases.ts
@@ -18,7 +18,7 @@ import {
updatePendingIndexingPolicy as updatePendingIndexingPolicyApi,
setDefaultKnowledgeBase as setDefaultKbApi,
type KnowledgeTaskResponse,
- type IndexingLLMSelection,
+ type LightRagIndexingSelection,
type KnowledgeUploadPolicy,
type RagProviderSummary,
} from "@/features/knowledge/api/catalog";
@@ -182,7 +182,7 @@ export function useKnowledgeBases() {
files: File[];
pageindexMode?: "flash" | "standard";
searchMode?: string;
- indexingLLM?: IndexingLLMSelection;
+ indexingLLM?: LightRagIndexingSelection;
}): Promise<KnowledgeTaskResponse> => {
const result = await createKbApi(params);
invalidateKnowledgeCaches();
@@ -262,7 +262,7 @@ export function useKnowledgeBases() {
const reindex = useCallback(
async (
kbName: string,
- indexingLLM?: IndexingLLMSelection,
+ indexingLLM?: LightRagIndexingSelection,
): Promise<KnowledgeTaskResponse> => {
const result = await reindexKbApi(kbName, indexingLLM);
if (result.noop) {
@@ -288,7 +288,7 @@ export function useKnowledgeBases() {
);
const updatePendingIndexingPolicy = useCallback(
- async (kbName: string, indexingLLM: IndexingLLMSelection) => {
+ async (kbName: string, indexingLLM: LightRagIndexingSelection) => {
await updatePendingIndexingPolicyApi(kbName, indexingLLM);
await load({ force: true, showSpinner: false });
},
diff --git a/web/hooks/useLLMOptions.ts b/web/hooks/useLLMOptions.ts
index 0ad5400f2..9465f5ae4 100644
--- a/web/hooks/useLLMOptions.ts
+++ b/web/hooks/useLLMOptions.ts
@@ -16,13 +16,13 @@ interface RefreshOptions {
}
/** Owns model-catalog loading independently from the chat page lifecycle. */
-export function useLLMOptions() {
+export function useLLMOptions(loader = listLLMOptions) {
const [state, dispatch] = useReducer(
reduceLLMOptionsState,
INITIAL_LLM_OPTIONS_STATE,
);
const latestRequestRef = useRef(0);
- const [loadOptions] = useState(() => createSingleFlight(listLLMOptions));
+ const [loadOptions] = useState(() => createSingleFlight(loader));
const mountedRef = useRef(true);
useEffect(() => {
diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.ts
index 121e0475f..111bd796a 100644
--- a/web/lib/knowledge-helpers.ts
+++ b/web/lib/knowledge-helpers.ts
@@ -106,6 +106,9 @@ export interface IndexVersion {
}
export interface LightRagIndexingPolicy {
+ schema_version?: number;
+ extract?: LightRagIndexingPolicy;
+ vlm?: { mode: "disabled" | "enabled"; snapshot?: LightRagIndexingPolicy };
policy: "pending_pinned" | "pinned" | "legacy_unpinned" | string;
selection?: {
profile_id: string;
@@ -124,11 +127,7 @@ export interface LightRagIndexingPolicy {
}
export type LightRagVersionDisplayState =
- | "published"
- | "building"
- | "failed"
- | "legacy"
- | "inactive";
+ "published" | "building" | "failed" | "legacy" | "inactive";
export function currentLightRagBuildCandidate(
versions: IndexVersion[],
diff --git a/web/lib/llm-options.ts b/web/lib/llm-options.ts
index 8a9c30c3a..e4cb86741 100644
--- a/web/lib/llm-options.ts
+++ b/web/lib/llm-options.ts
@@ -15,6 +15,7 @@ export interface LLMOption extends LLMSelection {
context_window?: number;
reasoning_effort?: string;
supported_reasoning_efforts?: string[];
+ supports_vision?: boolean;
is_active_default: boolean;
}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index ee807061f..7c1d36ee0 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -3993,5 +3993,26 @@
"readiness.detail.redis_unreachable": "Redis is unreachable",
"readiness.detail.redis_not_configured": "not configured",
"readiness.detail.multiple_workers_require_redis": "more than one backend worker needs Redis coordination",
- "readiness.detail.redis_available_but_memory_selected": "Redis is reachable — coordination could be switched to it"
+ "readiness.detail.redis_available_but_memory_selected": "Redis is reachable — coordination could be switched to it",
+ "After publication, enabling, disabling or replacing VLM requires a full rebuild. A VLM pinned now can process later image uploads.": "After publication, enabling, disabling or replacing VLM requires a full rebuild. A VLM pinned now can process later image uploads.",
+ "Choose a LightRAG base model before saving.": "Choose a LightRAG base model before saving.",
+ "Choose a vision model": "Choose a vision model",
+ "EXTRACT model": "EXTRACT model",
+ "Effective reasoning": "Effective reasoning",
+ "Image analysis disabled": "Image analysis disabled",
+ "Image analysis is disabled. Enable a VLM through a full rebuild.": "Image analysis is disabled. Enable a VLM through a full rebuild.",
+ "Inherit LightRAG base model": "Inherit LightRAG base model",
+ "KEYWORD and QUERY apply to subsequent queries. EXTRACT and VLM apply to new or fully rebuilt indexes; published indexes keep their pinned models.": "KEYWORD and QUERY apply to subsequent queries. EXTRACT and VLM apply to new or fully rebuilt indexes; published indexes keep their pinned models.",
+ "Legacy model settings are shown below. Saving fixes the LightRAG base selection independently of chat.": "Legacy model settings are shown below. Saving fixes the LightRAG base selection independently of chat.",
+ "LightRAG base model": "LightRAG base model",
+ "Model default / unspecified": "Model default / unspecified",
+ "Model source": "Model source",
+ "Only administrators can change shared LightRAG engine settings.": "Only administrators can change shared LightRAG engine settings.",
+ "Prefilled from the engine's EXTRACT and VLM settings. Changes here apply only to this new or rebuilt index.": "Prefilled from the engine's EXTRACT and VLM settings. Changes here apply only to this new or rebuilt index.",
+ "Role concurrency and timeouts apply to subsequent tasks without rebuilding.": "Role concurrency and timeouts apply to subsequent tasks without rebuilding.",
+ "The selected VLM model does not support image inputs.": "The selected VLM model does not support image inputs.",
+ "Unsupported reasoning effort": "Unsupported reasoning effort",
+ "VLM image analysis": "VLM image analysis",
+ "VLM model": "VLM model",
+ "effective model": "effective model"
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 974de84b9..35e955692 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -3993,5 +3993,26 @@
"readiness.detail.redis_unreachable": "Redis 连不上",
"readiness.detail.redis_not_configured": "未配置",
"readiness.detail.multiple_workers_require_redis": "多进程后端必须用 Redis 协调",
- "readiness.detail.redis_available_but_memory_selected": "Redis 可用,可以把轮次协调切到它"
+ "readiness.detail.redis_available_but_memory_selected": "Redis 可用,可以把轮次协调切到它",
+ "After publication, enabling, disabling or replacing VLM requires a full rebuild. A VLM pinned now can process later image uploads.": "发布后,启用、禁用或更换 VLM 均需完整重建。现在固定的 VLM 可以处理以后上传的图片。",
+ "Choose a LightRAG base model before saving.": "请先选择 LightRAG 基础模型再保存。",
+ "Choose a vision model": "选择视觉模型",
+ "EXTRACT model": "EXTRACT 模型",
+ "Effective reasoning": "实际推理强度",
+ "Image analysis disabled": "图片分析已禁用",
+ "Image analysis is disabled. Enable a VLM through a full rebuild.": "图片分析已禁用。请通过完整重建启用 VLM。",
+ "Inherit LightRAG base model": "继承 LightRAG 基础模型",
+ "KEYWORD and QUERY apply to subsequent queries. EXTRACT and VLM apply to new or fully rebuilt indexes; published indexes keep their pinned models.": "KEYWORD 和 QUERY 应用于后续查询。EXTRACT 和 VLM 应用于新建或完整重建的索引;已发布的索引保留固定的模型。",
+ "Legacy model settings are shown below. Saving fixes the LightRAG base selection independently of chat.": "下方显示旧版模型设置。保存后,LightRAG 基础模型将独立于聊天模型。",
+ "LightRAG base model": "LightRAG 基础模型",
+ "Model default / unspecified": "模型默认值 / 未指定",
+ "Model source": "模型来源",
+ "Only administrators can change shared LightRAG engine settings.": "只有管理员可以修改共享的 LightRAG 引擎设置。",
+ "Prefilled from the engine's EXTRACT and VLM settings. Changes here apply only to this new or rebuilt index.": "已从引擎的 EXTRACT 和 VLM 设置预填。此处修改仅应用于本次新建或重建的索引。",
+ "Role concurrency and timeouts apply to subsequent tasks without rebuilding.": "角色并发数和超时设置应用于后续任务,无需重建。",
+ "The selected VLM model does not support image inputs.": "所选 VLM 模型不支持图片输入。",
+ "Unsupported reasoning effort": "不支持的推理强度",
+ "VLM image analysis": "VLM 图片分析",
+ "VLM model": "VLM 模型",
+ "effective model": "实际模型"
}
diff --git a/web/tests/lightrag-indexing-model.test.ts b/web/tests/lightrag-indexing-model.test.ts
index 4625008e8..f9dc8dda6 100644
--- a/web/tests/lightrag-indexing-model.test.ts
+++ b/web/tests/lightrag-indexing-model.test.ts
@@ -194,16 +194,23 @@ test("late catalog loading preserves an empty knowledge base's saved pending mod
{ llm_profile_id: "current-profile", llm_model_id: "current-model" },
null,
{
- profile_id: "saved-profile",
- model_id: "saved-model",
- reasoning_effort: "none",
+ policy: "pending_pinned",
+ vision_available: false,
+ selection: {
+ profile_id: "saved-profile",
+ model_id: "saved-model",
+ reasoning_effort: "none",
+ },
},
true,
),
{
- profile_id: "saved-profile",
- model_id: "saved-model",
- reasoning_effort: "none",
+ extract: {
+ profile_id: "saved-profile",
+ model_id: "saved-model",
+ reasoning_effort: "none",
+ },
+ vlm: { mode: "disabled" },
},
);
});
diff --git a/web/tests/lightrag-role-models.spec.tsx b/web/tests/lightrag-role-models.spec.tsx
new file mode 100644
index 000000000..4ce599b5f
--- /dev/null
+++ b/web/tests/lightrag-role-models.spec.tsx
@@ -0,0 +1,216 @@
+import React, { useState } from "react";
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import LightRagRoleModelsEditor, {
+ newRoleModels,
+ resolvedRole,
+} from "@/components/knowledge/LightRagRoleModelsEditor";
+import LightRagIndexingSelector, {
+ indexingSelectionFromDefaults,
+ indexingSelectionFromPolicy,
+ isCompleteIndexingSelection,
+} from "@/components/knowledge/LightRagIndexingSelector";
+import type {
+ LightRagRoleModels,
+ LightRagIndexingSelection,
+} from "@/features/knowledge/model/types";
+import type { LLMOption } from "@/lib/llm-options";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (value: string) => value }),
+}));
+const textModel = { profile_id: "text", model_id: "small" };
+const visionModel = { profile_id: "vision", model_id: "large" };
+const options: LLMOption[] = [
+ {
+ ...textModel,
+ profile_name: "Text provider",
+ model_name: "Small",
+ model: "small",
+ provider: "custom",
+ supports_vision: false,
+ supported_reasoning_efforts: ["none", "low"],
+ is_active_default: true,
+ },
+ {
+ ...visionModel,
+ profile_name: "Vision provider",
+ model_name: "Large",
+ model: "large",
+ provider: "custom",
+ supports_vision: true,
+ supported_reasoning_efforts: ["none", "high"],
+ is_active_default: false,
+ },
+];
+function Editor({
+ initial = newRoleModels(textModel),
+}: {
+ initial?: LightRagRoleModels;
+}) {
+ const [models, setModels] = useState(initial);
+ return (
+ <>
+ <LightRagRoleModelsEditor
+ models={models}
+ options={options}
+ loading={false}
+ error={false}
+ onChange={setModels}
+ />
+ <output data-testid="models">{JSON.stringify(models)}</output>
+ </>
+ );
+}
+function state(): LightRagRoleModels {
+ return JSON.parse(screen.getByTestId("models").textContent ?? "{}");
+}
+
+describe("LightRAG role editor", () => {
+ it("keeps disabled, inherited, and explicit VLM choices distinct", () => {
+ render(<Editor />);
+ const vlm = within(screen.getByRole("group", { name: "VLM" }));
+ const mode = vlm.getByRole("combobox", { name: "VLM Model source" });
+ expect(state().vlm.mode).toBe("disabled");
+ fireEvent.change(mode, { target: { value: "inherit" } });
+ expect(
+ vlm.getByText("The selected VLM model does not support image inputs."),
+ ).toBeInTheDocument();
+ expect(state().vlm.selection).toBeNull();
+ fireEvent.change(mode, { target: { value: "model" } });
+ fireEvent.change(
+ vlm.getByRole("combobox", { name: "VLM effective model" }),
+ {
+ target: { value: "vision:large" },
+ },
+ );
+ expect(resolvedRole(state(), "vlm")).toEqual(visionModel);
+ fireEvent.change(mode, { target: { value: "disabled" } });
+ expect(resolvedRole(state(), "vlm")).toBeNull();
+ });
+ it("preserves explicit none and limits when the base model changes", () => {
+ render(<Editor />);
+ const extract = within(screen.getByRole("group", { name: "EXTRACT" }));
+ fireEvent.change(
+ extract.getByRole("combobox", { name: "Reasoning effort" }),
+ {
+ target: { value: "none" },
+ },
+ );
+ fireEvent.change(
+ extract.getByRole("spinbutton", { name: "EXTRACT Timeout (seconds)" }),
+ {
+ target: { value: "321" },
+ },
+ );
+ fireEvent.change(
+ screen.getByRole("combobox", { name: "LightRAG base model" }),
+ {
+ target: { value: "vision:large" },
+ },
+ );
+ expect(resolvedRole(state(), "extract")).toEqual({
+ ...visionModel,
+ reasoning_effort: "none",
+ });
+ expect(state().extract.timeout).toBe(321);
+ expect(state().vlm.mode).toBe("disabled");
+ });
+ it("shows an invalid saved effort without offering unsupported replacements", () => {
+ const initial = newRoleModels(textModel);
+ initial.extract.reasoning_effort = "high";
+ render(<Editor initial={initial} />);
+ const selector = within(
+ screen.getByRole("group", { name: "EXTRACT" }),
+ ).getByRole("combobox", {
+ name: "Reasoning effort",
+ });
+ expect(
+ within(selector).getByRole("option", {
+ name: "Unsupported reasoning effort: high",
+ }),
+ ).toBeDisabled();
+ expect(selector).toHaveValue("high");
+ expect(
+ within(selector).queryByRole("option", { name: "Max" }),
+ ).not.toBeInTheDocument();
+ });
+});
+it("prefills independent indexing roles and preserves a saved disabled policy", () => {
+ const roles = newRoleModels(textModel);
+ roles.vlm = {
+ mode: "model",
+ selection: visionModel,
+ reasoning_effort: "none",
+ max_async: 4,
+ timeout: 240,
+ };
+ expect(
+ indexingSelectionFromDefaults(
+ options,
+ { llm_profile_id: "old", llm_model_id: "old", role_models: roles },
+ visionModel,
+ ),
+ ).toEqual({
+ extract: textModel,
+ vlm: {
+ mode: "enabled",
+ selection: { ...visionModel, reasoning_effort: "none" },
+ },
+ });
+ expect(
+ indexingSelectionFromPolicy({
+ schema_version: 2,
+ policy: "pending_pinned",
+ extract: { policy: "pinned", selection: textModel },
+ vlm: { mode: "disabled" },
+ }),
+ ).toEqual({ extract: textModel, vlm: { mode: "disabled" } });
+});
+it("requires an explicit vision selection when enabling it in a rebuild draft", () => {
+ function Draft() {
+ const [selection, setSelection] =
+ useState<LightRagIndexingSelection | null>({
+ extract: textModel,
+ vlm: { mode: "disabled" },
+ });
+ return (
+ <>
+ <LightRagIndexingSelector
+ options={options}
+ selection={selection}
+ onChange={setSelection}
+ loading={false}
+ error={false}
+ />
+ <output data-testid="draft">{JSON.stringify(selection)}</output>
+ <button disabled={!isCompleteIndexingSelection(selection)}>
+ Submit
+ </button>
+ </>
+ );
+ }
+ render(<Draft />);
+ fireEvent.change(
+ screen.getByRole("combobox", { name: "VLM image analysis" }),
+ {
+ target: { value: "enabled" },
+ },
+ );
+ expect(
+ JSON.parse(screen.getByTestId("draft").textContent ?? "{}").vlm,
+ ).toEqual({
+ mode: "enabled",
+ });
+ expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
+ fireEvent.change(screen.getByRole("combobox", { name: "VLM model" }), {
+ target: { value: "vision:large" },
+ });
+ expect(
+ JSON.parse(screen.getByTestId("draft").textContent ?? "{}").vlm,
+ ).toEqual({
+ mode: "enabled",
+ selection: visionModel,
+ });
+ expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
+});