DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(lightrag): type role modes and document public contracts
NoxsMediaee5cd8e1cec1
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 8947b2502..cfc9c0276 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -16,8 +16,12 @@ from pathlib import Pathimport reimport shutilimport traceback+from typing import TYPE_CHECKING, Anyfrom uuid import uuid4+if TYPE_CHECKING:+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import IndexingPolicySnapshot+from fastapi import (APIRouter,BackgroundTasks,@@ -702,8 +706,8 @@ def _freeze_indexing_llm_form(raw: str):def _freeze_append_indexing(- kb_name: str, base_dir, provider: str, image_analysis: bool | None = None-):+ kb_name: str, base_dir: str | Path, provider: str, image_analysis: bool | None = None+) -> "IndexingPolicySnapshot | None":if provider != LIGHTRAG_PROVIDER:return Nonefrom deeptutor.services.rag.pipelines.lightrag.indexing_policy import (@@ -1576,8 +1580,8 @@ async def get_lightrag_pipeline_config():raise HTTPException(status_code=500, detail=str(e))[email protected]("/knowledge-bases/rag-pipelines/lightrag/model-options")-async def get_lightrag_model_options():[email protected]("/knowledge-bases/rag-pipelines/lightrag/model-options", response_model=None)+async def get_lightrag_model_options() -> dict[str, Any]:"""Return accessible catalog models with supported role capabilities."""from deeptutor.services.rag.pipelines.lightrag.roles import model_options@@ -3070,7 +3074,7 @@ async def _create_knowledge_base_owned(search_mode: str = Form(""),rel_paths: list[str] = Form(None),indexing_llm: str = Form(""),-):+) -> dict[str, Any]:"""Create a new knowledge base and initialize it with files."""try:try:@@ -3583,7 +3587,7 @@ async def update_pending_indexing_policy(async def _update_pending_indexing_policy_owned(kb_name: str,payload: LightRagIndexingSelection | IndexingLLMSelectionRequest,-):+) -> dict[str, Any]:"""Change the pending model of an empty, unpublished LightRAG KB."""manager, kb_name, kb_base_dir = _writable_kb(kb_name)kb_entry = _load_kb_entry_or_404(manager, kb_name)diff --git a/deeptutor/services/config/lightrag_roles.py b/deeptutor/services/config/lightrag_roles.pyindex ef7500afb..b912f70d7 100644--- a/deeptutor/services/config/lightrag_roles.py+++ b/deeptutor/services/config/lightrag_roles.py@@ -15,6 +15,8 @@ ReasoningEffort = Literal["none", "minimal", "low", "medium", "high", "xhigh", "class LightRagModelSelection(BaseModel):+ """Identify a catalog model and its optional reasoning selection."""+model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)profile_id: str = Field(min_length=1, max_length=128)@@ -22,10 +24,12 @@ class LightRagModelSelection(BaseModel):reasoning_effort: ReasoningEffort | None = None-class LightRagRoleModel(BaseModel):+class _LightRagRoleSettings(BaseModel):+ """Share selection validation and execution limits across role kinds."""+model_config = ConfigDict(extra="forbid")- mode: Literal["inherit", "model"] = "inherit"+ mode: Literal["disabled", "inherit", "model"] = "inherit"selection: LightRagModelSelection | None = Nonereasoning_effort: ReasoningEffort | None = Nonemax_async: int = Field(default=4, ge=1, le=32, strict=True)@@ -33,6 +37,7 @@ class LightRagRoleModel(BaseModel):@model_validator(mode="after")def check_selection(self) -> Self:+ """Reject missing explicit selections and misplaced reasoning overrides."""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:@@ -40,17 +45,28 @@ class LightRagRoleModel(BaseModel):return self-class LightRagVisionModel(LightRagRoleModel):+class LightRagRoleModel(_LightRagRoleSettings):+ """Configure a text role through base inheritance or an explicit model."""++ mode: Literal["inherit", "model"] = "inherit"+++class LightRagVisionModel(_LightRagRoleSettings):+ """Configure disabled, inherited, or explicit vision model execution."""+mode: Literal["disabled", "inherit", "model"] = "disabled"@model_validator(mode="after")def check_disabled(self) -> Self:+ """Reject reasoning overrides when vision execution is disabled."""if self.mode == "disabled" and self.reasoning_effort is not None:raise ValueError("A disabled vision role cannot override reasoning effort.")return selfclass LightRagRoleModels(BaseModel):+ """Group the independent base model and its four role overrides."""+model_config = ConfigDict(extra="forbid")base: LightRagModelSelection@@ -60,6 +76,7 @@ class LightRagRoleModels(BaseModel):vlm: LightRagVisionModel = Field(default_factory=LightRagVisionModel)def selection_for(self, role: str) -> LightRagModelSelection | None:+ """Return the effective role selection, or None for a disabled role."""override = getattr(self, role)if override.mode == "disabled":return None@@ -70,6 +87,8 @@ class LightRagRoleModels(BaseModel):class LightRagIndexingVision(BaseModel):+ """Represent an explicitly enabled or disabled indexing vision model."""+model_config = ConfigDict(extra="forbid")mode: Literal["disabled", "enabled"] = "disabled"@@ -77,6 +96,7 @@ class LightRagIndexingVision(BaseModel):@model_validator(mode="after")def check_selection(self) -> Self:+ """Require a model selection exactly when indexing vision is enabled."""if (self.mode == "enabled") != (self.selection is not None):raise ValueError("Only enabled vision indexing requires a model selection.")return selfdiff --git a/deeptutor/services/model_selection/reasoning.py b/deeptutor/services/model_selection/reasoning.pyindex e0d058f9d..b450090db 100644--- a/deeptutor/services/model_selection/reasoning.py+++ b/deeptutor/services/model_selection/reasoning.py@@ -16,6 +16,7 @@ from deeptutor.services.provider_registry import find_by_namedef supported_reasoning_efforts(binding: str, model: str, *, metadata: dict[str, Any] | None = None) -> list[str]:+ """Return supported reasoning choices, preferring managed catalog metadata."""metadata = metadata or {}declared = metadata.get("codex_supported_reasoning_levels")capabilities = metadata.get("capabilities") or {}diff --git a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.pyindex de2554ef5..46f7f51d1 100644--- a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py+++ b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py@@ -206,6 +206,8 @@ def _single_snapshot_from_persisted(policy: dict[str, Any]) -> IndexingLLMSnapsh@dataclass(frozen=True, slots=True)class IndexingPolicySnapshot:+ """Freeze role identities, runtime limits, and accepted indexing target state."""+extract: IndexingLLMSnapshotvlm: IndexingLLMSnapshot | Nonepolicy: str = POLICY_PINNED@@ -219,9 +221,11 @@ class IndexingPolicySnapshot:@propertydef vision_available(self) -> bool:+ """Return whether the pinned vision model supports image inputs."""return self.vlm is not None and self.vlm.vision_availabledef persisted_policy(self) -> dict[str, Any]:+ """Serialize role identities while preserving an existing legacy policy."""if self.legacy_policy is not None:# Appending must not rewrite the old fingerprint as a v2 identity.return dict(self.legacy_policy)@@ -448,6 +452,7 @@ def _content_revision(root: Path | None) -> str:def bind_target(snapshot: IndexingPolicySnapshot, kb_dir: Path, *, protect_contents: bool = False) -> IndexingPolicySnapshot:+ """Bind a snapshot to the current index and optionally its content revision."""from .storage import latest_published_roottarget = latest_published_root(kb_dir)@@ -461,6 +466,7 @@ def bind_target(def validate_target(snapshot: IndexingPolicySnapshot, kb_dir: Path) -> None:+ """Reject a queued write if its bound index, policy, or revision changed."""from .storage import latest_published_rootif not snapshot.target_bound:@@ -482,6 +488,7 @@ def validate_target(snapshot: IndexingPolicySnapshot, kb_dir: Path) -> None:def with_image_analysis(snapshot: IndexingPolicySnapshot, requested: bool | None) -> IndexingPolicySnapshot:+ """Record the requested image mode, rejecting unavailable pinned vision."""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."diff --git a/deeptutor/services/rag/pipelines/lightrag/roles.py b/deeptutor/services/rag/pipelines/lightrag/roles.pyindex a2e641197..c4649a741 100644--- a/deeptutor/services/rag/pipelines/lightrag/roles.py+++ b/deeptutor/services/rag/pipelines/lightrag/roles.py@@ -41,6 +41,7 @@ def model_options() -> dict[str, Any]:def resolve_selection(selection: LLMSelection, *, vision: bool = False) -> LLMConfig:+ """Resolve an accessible model and validate its reasoning and vision support."""apply_allowed_llm_selection(selection.to_dict())config = resolve_llm_config_for_selection(selection)if config.reasoning_effort is not None:@@ -61,11 +62,13 @@ def resolve_selection(selection: LLMSelection, *, vision: bool = False) -> LLMCodef settings_models(settings: dict[str, Any]) -> LightRagRoleModels | None:+ """Parse configured role models, returning None for legacy settings."""value = settings.get("role_models")return LightRagRoleModels.model_validate(value) if "role_models" in settings else Nonedef validate_models(models: LightRagRoleModels) -> None:+ """Validate access and capabilities for the base and all enabled roles."""resolve_selection(LLMSelection(**models.base.model_dump()))for role in ROLES:selection = models.selection_for(role)@@ -75,6 +78,8 @@ def validate_models(models: LightRagRoleModels) -> None:@dataclass(frozen=True)class RoleCall:+ """Carry a resolved role model, initiating user, and execution limits."""+config: LLMConfigowner: CurrentUsermax_async: int@@ -82,6 +87,7 @@ class RoleCall:def runtime_limits(settings: dict[str, Any]) -> dict[str, dict[str, int]]:+ """Resolve per-role concurrency and timeouts, including legacy defaults."""models = settings_models(settings)return {role: {@@ -95,6 +101,7 @@ def runtime_limits(settings: dict[str, Any]) -> dict[str, dict[str, int]]:def resolve_query_roles() -> dict[str, RoleCall]:+ """Resolve keyword and query models within the initiating user scope."""from deeptutor.services.config import load_lightrag_settingsfrom .config import resolve_lightrag_query_llm_configdiff --git a/deeptutor/services/rag/pipelines/lightrag/write_lock.py b/deeptutor/services/rag/pipelines/lightrag/write_lock.pyindex 03c559d56..bd2c43f72 100644--- a/deeptutor/services/rag/pipelines/lightrag/write_lock.py+++ b/deeptutor/services/rag/pipelines/lightrag/write_lock.py@@ -1,5 +1,6 @@"""One nonblocking writer per knowledge base, shared across worker processes."""+from collections.abc import Iteratorfrom contextlib import contextmanagerimport hashlibimport os@@ -9,7 +10,14 @@ from .indexing_policy import IndexingPolicyError@contextmanager-def write_ownership(kb_dir: Path):+def write_ownership(kb_dir: Path) -> Iterator[None]:+ """Hold exclusive nonblocking write ownership for a knowledge base.++ Yields:+ None while the cross-process indexing lock is held.++ Raises:+ IndexingPolicyError: The target uses a symlink or another writer owns it."""kb_dir = Path(kb_dir)if kb_dir.is_symlink():raise IndexingPolicyError("A writable knowledge-base directory cannot be a symbolic link.")diff --git a/web/contracts/generated/api.ts b/web/contracts/generated/api.tsindex a15e103d1..261c4d343 100644--- a/web/contracts/generated/api.ts+++ b/web/contracts/generated/api.ts@@ -10895,7 +10895,10 @@ export interface components {readonly extract: components["schemas"]["LightRagModelSelection"];readonly vlm?: components["schemas"]["LightRagIndexingVision"];};- /** LightRagIndexingVision */+ /**+ * LightRagIndexingVision+ * @description Represent an explicitly enabled or disabled indexing vision model.+ */readonly LightRagIndexingVision: {/*** Mode@@ -10906,7 +10909,10 @@ export interface components {readonly selection?:components["schemas"]["LightRagModelSelection"] | null;};- /** LightRagModelSelection */+ /**+ * LightRagModelSelection+ * @description Identify a catalog model and its optional reasoning selection.+ */readonly LightRagModelSelection: {/** Model Id */readonly model_id: string;@@ -10926,7 +10932,10 @@ export interface components {)| null;};- /** LightRagRoleModel */+ /**+ * LightRagRoleModel+ * @description Configure a text role through base inheritance or an explicit model.+ */readonly LightRagRoleModel: {/*** Max Async@@ -10960,7 +10969,10 @@ export interface components {*/readonly timeout: number;};- /** LightRagRoleModels */+ /**+ * LightRagRoleModels+ * @description Group the independent base model and its four role overrides.+ */readonly LightRagRoleModels: {readonly base: components["schemas"]["LightRagModelSelection"];readonly extract?: components["schemas"]["LightRagRoleModel"];@@ -10978,7 +10990,10 @@ export interface components {/** Server Url */readonly server_url?: string | null;};- /** LightRagVisionModel */+ /**+ * LightRagVisionModel+ * @description Configure disabled, inherited, or explicit vision model execution.+ */readonly LightRagVisionModel: {/*** Max Asyncdiff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.jsonindex a277a5c7b..1d53cdf41 100644--- a/web/contracts/schema/openapi.json+++ b/web/contracts/schema/openapi.json@@ -4439,6 +4439,7 @@},"LightRagIndexingVision": {"additionalProperties": false,+ "description": "Represent an explicitly enabled or disabled indexing vision model.","properties": {"mode": {"default": "disabled",@@ -4465,6 +4466,7 @@},"LightRagModelSelection": {"additionalProperties": false,+ "description": "Identify a catalog model and its optional reasoning selection.","properties": {"model_id": {"maxLength": 128,@@ -4509,6 +4511,7 @@},"LightRagRoleModel": {"additionalProperties": false,+ "description": "Configure a text role through base inheritance or an explicit model.","properties": {"max_async": {"default": 4,@@ -4570,6 +4573,7 @@},"LightRagRoleModels": {"additionalProperties": false,+ "description": "Group the independent base model and its four role overrides.","properties": {"base": {"$ref": "#/components/schemas/LightRagModelSelection"@@ -4624,6 +4628,7 @@},"LightRagVisionModel": {"additionalProperties": false,+ "description": "Configure disabled, inherited, or explicit vision model execution.","properties": {"max_async": {"default": 4,