Skip to content

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

fix(knowledge): harden GraphRAG model and embedding compatibility (#747)

Lan-zk3f1894e0c480
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index 1e8c636ac..a71cdeaac 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -39,6 +39,7 @@ from deeptutor.knowledge.kb_types import is_connected_kb, supports_local_raw_fil
from deeptutor.knowledge.manager import KnowledgeBaseManager
from deeptutor.knowledge.naming import validate_knowledge_base_name
from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker
+from deeptutor.logging import PROCESS_LOG_PRIVATE_ATTR
from deeptutor.multi_user.context import get_current_user
from deeptutor.multi_user.knowledge_access import (
assert_writable,
@@ -594,6 +595,28 @@ def _task_log(task_id: str, message: str, level: str = "info") -> None:
logger.info(f"[{task_id}] {message}")
+def _server_task_trace(task_id: str, trace: str) -> None:
+ """Keep a traceback in server logs while excluding it from browser streams."""
+ logger.error(
+ "[%s] Stack trace:\n%s",
+ task_id,
+ trace,
+ extra={PROCESS_LOG_PRIVATE_ATTR: True},
+ )
+
+
+def _exception_failure_metadata(exc: Exception) -> dict:
+ """Extract stable, user-facing failure metadata from a typed exception."""
+ metadata = {}
+ error_code = getattr(exc, "code", None)
+ retryable = getattr(exc, "retryable", None)
+ if isinstance(error_code, str) and error_code:
+ metadata["error_code"] = error_code
+ if isinstance(retryable, bool):
+ metadata["retryable"] = retryable
+ return metadata
+
+
def _validate_registered_provider(raw_provider: str | None) -> str:
"""Resolve a requested provider to a known engine.
@@ -637,6 +660,24 @@ def _assert_provider_ready(provider: str) -> None:
),
)
+ from deeptutor.services.rag.preflight import engine_preflight
+
+ report = engine_preflight(provider)
+ failed_checks = [
+ check
+ for check in report.get("checks", [])
+ if not check.get("optional") and not check.get("ok")
+ ]
+ if failed_checks:
+ failure_details = "; ".join(
+ str(check.get("detail") or check.get("label") or "Requirement not met")
+ for check in failed_checks
+ )
+ raise HTTPException(
+ status_code=409,
+ detail=f"GraphRAG preflight failed: {failure_details}",
+ )
+
if provider == LIGHTRAG_PROVIDER:
from deeptutor.services.rag.pipelines.lightrag.config import is_lightrag_available
@@ -820,9 +861,10 @@ async def run_initialization_task(initializer: KnowledgeBaseInitializer, task_id
error_msg = str(e)
trace = _tb.format_exc()
+ failure_metadata = _exception_failure_metadata(e)
_task_log(task_id, f"Initialization failed: {error_msg}", level="error")
- _task_log(task_id, f"Stack trace:\n{trace}", level="error")
+ _server_task_trace(task_id, trace)
task_manager.update_task_status(task_id, "error", error=error_msg)
@@ -835,6 +877,7 @@ async def run_initialization_task(initializer: KnowledgeBaseInitializer, task_id
"message": f"Initialization failed: {error_msg}",
"percent": 0,
"error": error_msg,
+ **failure_metadata,
"task_id": task_id,
"timestamp": datetime.now().isoformat(),
},
@@ -842,9 +885,12 @@ async def run_initialization_task(initializer: KnowledgeBaseInitializer, task_id
if initializer.progress_tracker:
initializer.progress_tracker.update(
- ProgressStage.ERROR, f"Initialization failed: {error_msg}", error=error_msg
+ ProgressStage.ERROR,
+ f"Initialization failed: {error_msg}",
+ error=error_msg,
+ **failure_metadata,
)
- task_stream_manager.emit_failed(task_id, error_msg, details=trace)
+ task_stream_manager.emit_failed(task_id, error_msg, **failure_metadata)
async def run_upload_processing_task(
@@ -986,15 +1032,19 @@ async def run_upload_processing_task(
error_msg = f"Upload processing failed (KB '{kb_name}'): {e}"
trace = _tb.format_exc()
+ failure_metadata = _exception_failure_metadata(e)
_task_log(task_id, error_msg, level="error")
- _task_log(task_id, f"Stack trace:\n{trace}", level="error")
+ _server_task_trace(task_id, trace)
task_manager.update_task_status(task_id, "error", error=error_msg)
progress_tracker.update(
- ProgressStage.ERROR, f"Processing failed: {error_msg}", error=error_msg
+ ProgressStage.ERROR,
+ f"Processing failed: {error_msg}",
+ error=error_msg,
+ **failure_metadata,
)
- task_stream_manager.emit_failed(task_id, error_msg, details=trace)
+ task_stream_manager.emit_failed(task_id, error_msg, **failure_metadata)
@router.get("/health")
@@ -1324,6 +1374,37 @@ async def get_rag_model_options(kinds: str = "llm,embedding"):
raise HTTPException(status_code=500, detail=str(e))
+class GraphRagModelCompatibilityRequest(BaseModel):
+ """Configured chat-model candidate to test without activating it."""
+
+ profile_id: str
+ model_id: str
+
+
+async def _probe_graphrag_model_compatibility(profile_id: str, model_id: str) -> dict:
+ """Resolve and probe a configured GraphRAG chat-model candidate."""
+ from deeptutor.services.rag.pipelines.graphrag.compatibility import (
+ probe_configured_completion_model,
+ )
+
+ return await probe_configured_completion_model(profile_id, model_id)
+
+
[email protected]("/rag-pipelines/graphrag/model-compatibility")
+async def test_graphrag_model_compatibility(payload: GraphRagModelCompatibilityRequest):
+ """Test GraphRAG structured output without changing the active chat model."""
+ try:
+ return await _probe_graphrag_model_compatibility(payload.profile_id, payload.model_id)
+ except ValueError as e:
+ raise HTTPException(status_code=400, detail=str(e)) from e
+ except Exception as e:
+ logger.exception("Unexpected error testing GraphRAG model compatibility")
+ raise HTTPException(
+ status_code=500,
+ detail="GraphRAG compatibility could not be tested because of an internal error.",
+ ) from e
+
+
class ActiveModelUpdate(BaseModel):
"""Switch the globally-active model for a kind (llm / embedding)."""
@@ -2569,18 +2650,20 @@ async def run_reindex_task(kb_name: str, base_dir: str, task_id: str, signature_
error_msg = str(e)
trace = _tb.format_exc()
+ failure_metadata = _exception_failure_metadata(e)
_task_log(task_id, f"Re-index failed: {error_msg}", level="error")
- _task_log(task_id, f"Stack trace:\n{trace}", level="error")
+ _server_task_trace(task_id, trace)
task_manager.update_task_status(task_id, "error", error=error_msg)
try:
ProgressTracker(kb_name, Path(base_dir)).update(
ProgressStage.ERROR,
f"Re-index failed: {error_msg}",
error=error_msg,
+ **failure_metadata,
)
except Exception:
pass
- task_stream_manager.emit_failed(task_id, error_msg, details=trace)
+ task_stream_manager.emit_failed(task_id, error_msg, **failure_metadata)
@router.post("/{kb_name}/reindex")
diff --git a/deeptutor/api/utils/task_log_stream.py b/deeptutor/api/utils/task_log_stream.py
index a49506de6..ab4696a84 100644
--- a/deeptutor/api/utils/task_log_stream.py
+++ b/deeptutor/api/utils/task_log_stream.py
@@ -10,6 +10,7 @@ import time
from typing import Any
from deeptutor.logging import (
+ PROCESS_LOG_PRIVATE_ATTR,
ProcessLogEvent,
bind_log_context,
capture_process_logs,
@@ -98,10 +99,22 @@ class KnowledgeTaskStreamManager:
def emit_complete(self, task_id: str, detail: str = "Task completed"):
self.emit(task_id, "complete", {"detail": detail, "task_id": task_id})
- def emit_failed(self, task_id: str, detail: str, *, details: str | None = None):
+ def emit_failed(
+ self,
+ task_id: str,
+ detail: str,
+ *,
+ details: str | None = None,
+ error_code: str | None = None,
+ retryable: bool | None = None,
+ ):
payload: dict[str, Any] = {"detail": detail, "task_id": task_id}
if details:
payload["details"] = details
+ if error_code:
+ payload["error_code"] = error_code
+ if retryable is not None:
+ payload["retryable"] = retryable
self.emit(task_id, "failed", payload)
def subscribe(
@@ -269,6 +282,8 @@ class _TaskScopedLogHandler(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
try:
+ if getattr(record, PROCESS_LOG_PRIVATE_ATTR, False):
+ return
context = current_log_context()
record_task_id = context.get("task_id")
if record_task_id and record_task_id != self._task_id:
diff --git a/deeptutor/knowledge/progress_tracker.py b/deeptutor/knowledge/progress_tracker.py
index 60ff406d3..a5b1ad7da 100644
--- a/deeptutor/knowledge/progress_tracker.py
+++ b/deeptutor/knowledge/progress_tracker.py
@@ -111,6 +111,8 @@ class ProgressTracker:
"total": progress.get("total", 0),
"file_name": progress.get("file_name"),
"error": progress.get("error"),
+ "error_code": progress.get("error_code"),
+ "retryable": progress.get("retryable"),
"timestamp": progress.get("timestamp"),
"task_id": progress.get("task_id"),
"indexed_count": progress.get("indexed_count"),
@@ -138,6 +140,8 @@ class ProgressTracker:
total: int = 0,
file_name: str = "",
error: str | None = None,
+ error_code: str | None = None,
+ retryable: bool | None = None,
indexed_count: int | None = None,
index_changed: bool | None = None,
index_action: str | None = None,
@@ -164,6 +168,10 @@ class ProgressTracker:
if error:
progress["error"] = error
progress["stage"] = ProgressStage.ERROR.value
+ if error_code:
+ progress["error_code"] = error_code
+ if retryable is not None:
+ progress["retryable"] = retryable
# Output to logger (terminal and log file)
try:
diff --git a/deeptutor/logging/__init__.py b/deeptutor/logging/__init__.py
index a1d07c50e..3c7761aaf 100644
--- a/deeptutor/logging/__init__.py
+++ b/deeptutor/logging/__init__.py
@@ -3,7 +3,7 @@
from .config import LoggingConfig, get_default_log_dir, get_global_log_level, load_logging_config
from .configure import configure_logging
from .context import LOG_CONTEXT_FIELDS, bind_log_context, current_log_context
-from .process_stream import ProcessLogEvent, capture_process_logs
+from .process_stream import PROCESS_LOG_PRIVATE_ATTR, ProcessLogEvent, capture_process_logs
from .stats import MODEL_PRICING, LLMCall, LLMStats, estimate_tokens, get_pricing
__all__ = [
@@ -12,6 +12,7 @@ __all__ = [
"configure_logging",
"bind_log_context",
"current_log_context",
+ "PROCESS_LOG_PRIVATE_ATTR",
"capture_process_logs",
"ProcessLogEvent",
"LLMStats",
diff --git a/deeptutor/logging/process_stream.py b/deeptutor/logging/process_stream.py
index 8a80ec719..ae6f4f432 100644
--- a/deeptutor/logging/process_stream.py
+++ b/deeptutor/logging/process_stream.py
@@ -13,6 +13,8 @@ from typing import Any
from .context import LOG_CONTEXT_FIELDS
from .formatters import ContextFilter
+PROCESS_LOG_PRIVATE_ATTR = "deeptutor_process_log_private"
+
@dataclass(frozen=True)
class ProcessLogEvent:
@@ -68,6 +70,8 @@ class ProcessLogHandler(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
try:
+ if getattr(record, PROCESS_LOG_PRIVATE_ATTR, False):
+ return
event = ProcessLogEvent.from_record(record)
if self._task_id and event.context.get("task_id") != self._task_id:
return
diff --git a/deeptutor/services/embedding/adapters/jina.py b/deeptutor/services/embedding/adapters/jina.py
index a10eb630c..310ffe6cf 100644
--- a/deeptutor/services/embedding/adapters/jina.py
+++ b/deeptutor/services/embedding/adapters/jina.py
@@ -5,6 +5,7 @@ from typing import Any, Dict
import httpx
+from deeptutor.services.embedding.request_options import should_send_embedding_dimensions
from deeptutor.services.llm.openai_http_client import disable_ssl_verify_enabled
from .base import BaseEmbeddingAdapter, EmbeddingRequest, EmbeddingResponse
@@ -36,20 +37,22 @@ class JinaEmbeddingAdapter(BaseEmbeddingAdapter):
def _should_send_dimensions(self, model_name: str | None, dim: int) -> bool:
"""Decide whether to attach `dimensions` (Matryoshka truncation)."""
- if self.send_dimensions is True:
- return True
- if self.send_dimensions is False:
- return False
+ decision = should_send_embedding_dimensions(
+ binding="jina",
+ model=model_name,
+ dimension=dim,
+ send_dimensions=self.send_dimensions,
+ )
+ if self.send_dimensions is not None or decision:
+ return decision
info = self.MODELS_INFO.get(model_name or "", {})
supported = info.get("dimensions") if isinstance(info, dict) else None
- if isinstance(supported, list) and dim in supported:
- return True
if isinstance(supported, list):
logger.warning(
f"Jina model '{model_name}' supports dims {supported} but {dim} requested; "
"dropping `dimensions` from payload."
)
- return False
+ return decision
def _supports_multimodal(self, model_name: str | None) -> bool:
info = self.MODELS_INFO.get(model_name or "")
diff --git a/deeptutor/services/embedding/adapters/openai_compatible.py b/deeptutor/services/embedding/adapters/openai_compatible.py
index 2e38e954e..778b532b4 100644
--- a/deeptutor/services/embedding/adapters/openai_compatible.py
+++ b/deeptutor/services/embedding/adapters/openai_compatible.py
@@ -6,6 +6,7 @@ from typing import Any, Dict
import httpx
+from deeptutor.services.embedding.request_options import should_send_embedding_dimensions
from deeptutor.services.llm.openai_http_client import disable_ssl_verify_enabled
from .base import (
@@ -127,18 +128,15 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
OpenAI-style ``dimensions`` parameter — OpenAI ``text-embedding-3*``,
Qwen3-Embedding, Qwen3-VL-Embedding.
"""
- if self.send_dimensions is True:
- return True
- if self.send_dimensions is False:
- return False
- if not model_name:
- return False
- lname = model_name.lower()
- if lname.startswith("text-embedding-3"):
- return True
- if "qwen3-embedding" in lname or "qwen3-vl-embedding" in lname:
- return True
- return False
+ return should_send_embedding_dimensions(
+ binding=None,
+ model=model_name,
+ # ``embed`` only calls this hook when a request dimension exists.
+ # Keep the historical one-argument override contract used by
+ # provider adapters such as Gemini.
+ dimension=self.dimensions or 1,
+ send_dimensions=self.send_dimensions,
+ )
async def embed(self, request: EmbeddingRequest) -> EmbeddingResponse:
import asyncio
diff --git a/deeptutor/services/embedding/adapters/openai_sdk.py b/deeptutor/services/embedding/adapters/openai_sdk.py
index 13ba3f166..881961435 100644
--- a/deeptutor/services/embedding/adapters/openai_sdk.py
+++ b/deeptutor/services/embedding/adapters/openai_sdk.py
@@ -12,6 +12,7 @@ from typing import Any, Dict
from openai import APIConnectionError, APIError, APIStatusError, AsyncOpenAI
+from deeptutor.services.embedding.request_options import should_send_embedding_dimensions
from deeptutor.services.llm.openai_http_client import openai_client_kwargs
from .base import (
@@ -33,18 +34,12 @@ class OpenAISDKEmbeddingAdapter(BaseEmbeddingAdapter):
Tri-state ``self.send_dimensions``: ``True`` always send, ``False``
never send, ``None`` auto by model family.
"""
- if self.send_dimensions is True:
- return True
- if self.send_dimensions is False:
- return False
- if not model_name:
- return False
- lname = model_name.lower()
- if lname.startswith("text-embedding-3"):
- return True
- if "qwen3-embedding" in lname or "qwen3-vl-embedding" in lname:
- return True
- return False
+ return should_send_embedding_dimensions(
+ binding=None,
+ model=model_name,
+ dimension=self.dimensions or 1,
+ send_dimensions=self.send_dimensions,
+ )
def _build_client(self) -> AsyncOpenAI:
# OpenRouter / custom gateways often don't validate the key, but the
diff --git a/deeptutor/services/embedding/request_options.py b/deeptutor/services/embedding/request_options.py
new file mode 100644
index 000000000..a4158d676
--- /dev/null
+++ b/deeptutor/services/embedding/request_options.py
@@ -0,0 +1,46 @@
+"""Shared request-option decisions for embedding transports."""
+
+from __future__ import annotations
+
+from deeptutor.services.config.embedding_endpoint import canonical_embedding_provider_name
+
+_JINA_VARIABLE_DIMENSIONS: dict[str, frozenset[int]] = {
+ "jina-embeddings-v3": frozenset({32, 64, 128, 256, 512, 768, 1024}),
+ "jina-embeddings-v4": frozenset({32, 64, 128, 256, 512, 768, 1024}),
+}
+
+
+def should_send_embedding_dimensions(
+ *,
+ binding: str | None,
+ model: str | None,
+ dimension: int | None,
+ send_dimensions: bool | None,
+) -> bool:
+ """Apply DeepTutor's tri-state ``dimensions`` request policy.
+
+ Explicit user choices always win. In automatic mode, Jina uses its known
+ Matryoshka dimensions while OpenAI-compatible transports use the model
+ families already supported by DeepTutor's regular embedding adapters.
+ """
+ if not dimension:
+ return False
+ if send_dimensions is True:
+ return True
+ if send_dimensions is False:
+ return False
+
+ provider = canonical_embedding_provider_name(binding)
+ model_name = str(model or "").strip()
+ if provider == "jina":
+ return dimension in _JINA_VARIABLE_DIMENSIONS.get(model_name, frozenset())
+
+ lowered = model_name.lower()
+ return (
+ lowered.startswith("text-embedding-3")
+ or "qwen3-embedding" in lowered
+ or "qwen3-vl-embedding" in lowered
+ )
+
+
+__all__ = ["should_send_embedding_dimensions"]
diff --git a/deeptutor/services/rag/pipelines/graphrag/compatibility.py b/deeptutor/services/rag/pipelines/graphrag/compatibility.py
new file mode 100644
index 000000000..f63dc0cb3
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/graphrag/compatibility.py
@@ -0,0 +1,42 @@
+"""Resolve and test GraphRAG completion-model candidates without activating them."""
+
+from __future__ import annotations
+
+from deeptutor.services.config import (
+ get_model_catalog_service,
+ resolve_llm_runtime_config,
+)
+
+from . import engine
+
+
+async def probe_configured_completion_model(profile_id: str, model_id: str) -> dict:
+ """Probe one configured model by ID while leaving the active catalog unchanged.
+
+ Args:
+ profile_id: Server-side model-catalog profile ID.
+ model_id: Server-side model ID within the selected profile.
+
+ Returns:
+ A secret-free GraphRAG compatibility result.
+
+ Raises:
+ ValueError: If the profile/model selection does not exist.
+ """
+ service = get_model_catalog_service()
+ llm_cfg = resolve_llm_runtime_config(
+ catalog=service.load(),
+ service=service,
+ llm_selection={"profile_id": profile_id, "model_id": model_id},
+ )
+ return await engine.probe_completion_model(llm_cfg)
+
+
+async def probe_active_completion_model() -> dict:
+ """Probe the globally active chat model without changing catalog state."""
+ service = get_model_catalog_service()
+ llm_cfg = resolve_llm_runtime_config(catalog=service.load(), service=service)
+ return await engine.probe_completion_model(llm_cfg)
+
+
+__all__ = ["probe_active_completion_model", "probe_configured_completion_model"]
diff --git a/deeptutor/services/rag/pipelines/graphrag/completion_adapter.py b/deeptutor/services/rag/pipelines/graphrag/completion_adapter.py
new file mode 100644
index 000000000..e2803caf8
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/graphrag/completion_adapter.py
@@ -0,0 +1,251 @@
+"""GraphRAG completion adapter with a strict JSON-object compatibility fallback."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+import json
+import threading
+from typing import Any
+from urllib.parse import urlparse
+
+from pydantic import BaseModel, ValidationError
+
+from .errors import (
+ MODEL_INCOMPATIBLE_MESSAGE,
+ MODEL_OUTPUT_TRUNCATED_MESSAGE,
+ GraphRagStructuredOutputError,
+ GraphRagStructuredOutputTruncatedError,
+ is_unsupported_schema_error,
+)
+from .provider import COMPLETION_TYPE
+
+_CAPABILITY_LOCK = threading.RLock()
+_JSON_OBJECT_CAPABILITIES: set[tuple[str, str, str]] = set()
+_ADAPTER_CLASS: type | None = None
+
+
+def _capability_key(model_config: Any) -> tuple[str, str, str]:
+ return (
+ str(getattr(model_config, "model_provider", "") or "").lower(),
+ str(getattr(model_config, "model", "") or "").lower(),
+ str(getattr(model_config, "api_base", "") or "").rstrip("/").lower(),
+ )
+
+
+def _uses_json_object(model_config: Any) -> bool:
+ with _CAPABILITY_LOCK:
+ return _capability_key(model_config) in _JSON_OBJECT_CAPABILITIES
+
+
+def _remember_json_object(model_config: Any) -> None:
+ with _CAPABILITY_LOCK:
+ _JSON_OBJECT_CAPABILITIES.add(_capability_key(model_config))
+
+
+def _uses_prompt_only_structured_output(model_config: Any) -> bool:
+ """Use the common messages contract for third-party Anthropic-compatible APIs.
+
+ LiteLLM implements Pydantic response formats on the Anthropic transport with
+ a forced synthetic tool. Third-party endpoints may implement Anthropic's
+ messages API without matching those tool semantics. A schema instruction
+ plus local Pydantic validation keeps the GraphRAG contract strict while
+ avoiding assumptions beyond the configured endpoint's base protocol.
+ """
+ provider = str(getattr(model_config, "model_provider", "") or "").lower()
+ if provider != "anthropic":
+ return False
+
+ api_base = str(getattr(model_config, "api_base", "") or "").strip()
+ if not api_base:
+ return False
+ parsed = urlparse(api_base if "://" in api_base else f"https://{api_base}")
+ hostname = (parsed.hostname or "").lower().rstrip(".")
+ return hostname != "api.anthropic.com" and not hostname.endswith(".anthropic.com")
+
+
+def clear_capability_cache() -> None:
+ """Clear process-local compatibility discoveries; intended for deterministic tests."""
+ with _CAPABILITY_LOCK:
+ _JSON_OBJECT_CAPABILITIES.clear()
+
+
+def _is_schema_model(response_format: Any) -> bool:
+ return isinstance(response_format, type) and issubclass(response_format, BaseModel)
+
+
+def _schema_instruction(response_format: type[BaseModel]) -> str:
+ schema = json.dumps(
+ response_format.model_json_schema(),
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ return (
+ "Return only one valid JSON object. Do not use Markdown fences or explanatory text. "
+ f"The JSON object must match this JSON schema exactly: {schema}"
+ )
+
+
+def _messages_with_schema(messages: Any, response_format: type[BaseModel]) -> Any:
+ instruction = _schema_instruction(response_format)
+ if isinstance(messages, str):
+ return f"{messages}\n\n{instruction}"
+ if not isinstance(messages, list):
+ return messages
+
+ copied = list(messages)
+ for index in range(len(copied) - 1, -1, -1):
+ message = copied[index]
+ if not isinstance(message, dict) or message.get("role") != "user":
+ continue
+ content = message.get("content")
+ if isinstance(content, str):
+ copied[index] = {**message, "content": f"{content}\n\n{instruction}"}
+ return copied
+ copied.append({"role": "user", "content": instruction})
+ return copied
+
+
+def _format_fallback_kwargs(kwargs: dict[str, Any], response_format: type[BaseModel]) -> dict:
+ fallback = dict(kwargs)
+ fallback["messages"] = _messages_with_schema(fallback["messages"], response_format)
+ fallback.pop("response_format", None)
+ return fallback
+
+
+def _format_response(response: Any, response_format: type[BaseModel]) -> Any:
+ from graphrag_llm.utils import structure_completion_response
+
+ try:
+ response.formatted_response = structure_completion_response(
+ response.content,
+ response_format,
+ )
+ except (json.JSONDecodeError, TypeError, ValidationError, ValueError) as error:
+ choices = getattr(response, "choices", None)
+ finish_reason = getattr(choices[0], "finish_reason", None) if choices else None
+ if finish_reason in {"length", "max_tokens"}:
+ raise GraphRagStructuredOutputTruncatedError(MODEL_OUTPUT_TRUNCATED_MESSAGE) from error
+ raise GraphRagStructuredOutputError(MODEL_INCOMPATIBLE_MESSAGE) from error
+ return response
+
+
+def _native_validation_error(error: BaseException) -> bool:
+ return isinstance(error, (json.JSONDecodeError, ValidationError))
+
+
+def _fallback_sync(instance: Any, kwargs: dict[str, Any], response_format: type[BaseModel]) -> Any:
+ fallback = _format_fallback_kwargs(kwargs, response_format)
+ if fallback.get("stream"):
+ raise ValueError("response_format is not supported for streaming completions.")
+ messages = fallback.pop("messages")
+ if isinstance(messages, str):
+ messages = [{"role": "user", "content": messages}]
+ request_metrics = fallback.pop("metrics", None) or {}
+ if not instance._track_metrics:
+ request_metrics = None
+ try:
+ response = instance._completion(
+ messages=messages,
+ metrics=request_metrics,
+ response_format_json_object=not _uses_prompt_only_structured_output(
+ instance._model_config
+ ),
+ **fallback,
+ )
+ return _format_response(response, response_format)
+ finally:
+ if request_metrics is not None:
+ instance._metrics_store.update_metrics(metrics=request_metrics)
+
+
+async def _fallback_async(
+ instance: Any,
+ kwargs: dict[str, Any],
+ response_format: type[BaseModel],
+) -> Any:
+ fallback = _format_fallback_kwargs(kwargs, response_format)
+ if fallback.get("stream"):
+ raise ValueError("response_format is not supported for streaming completions.")
+ messages = fallback.pop("messages")
+ if isinstance(messages, str):
+ messages = [{"role": "user", "content": messages}]
+ request_metrics = fallback.pop("metrics", None) or {}
+ if not instance._track_metrics:
+ request_metrics = None
+ try:
+ response = await instance._completion_async(
+ messages=messages,
+ metrics=request_metrics,
+ response_format_json_object=not _uses_prompt_only_structured_output(
+ instance._model_config
+ ),
+ **fallback,
+ )
+ return _format_response(response, response_format)
+ finally:
+ if request_metrics is not None:
+ instance._metrics_store.update_metrics(metrics=request_metrics)
+
+
+def _get_adapter_class() -> type:
+ global _ADAPTER_CLASS
+ with _CAPABILITY_LOCK:
+ if _ADAPTER_CLASS is not None:
+ return _ADAPTER_CLASS
+
+ from graphrag_llm.completion.lite_llm_completion import LiteLLMCompletion
+
+ class DeepTutorLiteLLMCompletion(LiteLLMCompletion):
+ """LiteLLM completion with a narrow GraphRAG structured-output fallback."""
+
+ def completion(self, /, **kwargs: Any) -> Any:
+ response_format = kwargs.get("response_format")
+ if not _is_schema_model(response_format):
+ return super().completion(**kwargs)
+ if _uses_prompt_only_structured_output(self._model_config):
+ return _fallback_sync(self, kwargs, response_format)
+ if _uses_json_object(self._model_config):
+ return _fallback_sync(self, kwargs, response_format)
+ try:
+ return super().completion(**kwargs)
+ except Exception as error:
+ explicit_unsupported = is_unsupported_schema_error(error)
+ if not explicit_unsupported and not _native_validation_error(error):
+ raise
+ formatted = _fallback_sync(self, kwargs, response_format)
+ if explicit_unsupported:
+ _remember_json_object(self._model_config)
+ return formatted
+
+ async def completion_async(self, /, **kwargs: Any) -> Any:
+ response_format = kwargs.get("response_format")
+ if not _is_schema_model(response_format):
+ return await super().completion_async(**kwargs)
+ if _uses_prompt_only_structured_output(self._model_config):
+ return await _fallback_async(self, kwargs, response_format)
+ if _uses_json_object(self._model_config):
+ return await _fallback_async(self, kwargs, response_format)
+ try:
+ return await super().completion_async(**kwargs)
+ except Exception as error:
+ explicit_unsupported = is_unsupported_schema_error(error)
+ if not explicit_unsupported and not _native_validation_error(error):
+ raise
+ formatted = await _fallback_async(self, kwargs, response_format)
+ if explicit_unsupported:
+ _remember_json_object(self._model_config)
+ return formatted
+
+ _ADAPTER_CLASS = DeepTutorLiteLLMCompletion
+ return _ADAPTER_CLASS
+
+
+def register_completion_adapter() -> None:
+ """Register DeepTutor's completion type through GraphRAG's public factory API."""
+ from graphrag_llm.completion import register_completion
+
+ initializer: Callable[..., Any] = _get_adapter_class()
+ register_completion(COMPLETION_TYPE, initializer, scope="singleton")
+
+
+__all__ = ["clear_capability_cache", "register_completion_adapter"]
diff --git a/deeptutor/services/rag/pipelines/graphrag/config.py b/deeptutor/services/rag/pipelines/graphrag/config.py
index 24ec3d811..baaca45ce 100644
--- a/deeptutor/services/rag/pipelines/graphrag/config.py
+++ b/deeptutor/services/rag/pipelines/graphrag/config.py
@@ -14,9 +14,8 @@ Decoupling notes:
model id, so the workflow/search sections pick it up automatically.
* Built-in prompts are used (every ``prompt`` field defaults to ``None`` in
GraphRAG), so we never scaffold prompt files.
-* GraphRAG talks to its models via LiteLLM with ``model_provider: openai`` + a
- custom ``api_base`` — which is exactly how DeepTutor reaches any
- OpenAI-compatible endpoint.
+* Completion calls use DeepTutor's registered GraphRAG compatibility adapter,
+ while embeddings retain GraphRAG's stock LiteLLM path.
This is the single spot to touch if GraphRAG's config schema shifts between
releases; pin the dependency to the 3.x line (see ``pyproject`` extra).
@@ -28,6 +27,18 @@ from dataclasses import dataclass
import logging
from pathlib import Path
from typing import Any
+from urllib.parse import urlsplit, urlunsplit
+
+from deeptutor.services.config.embedding_endpoint import canonical_embedding_provider_name
+from deeptutor.services.embedding.request_options import should_send_embedding_dimensions
+
+from .errors import GraphRagEmbeddingProviderUnsupportedError
+from .provider import (
+ COMPLETION_TYPE,
+ resolve_completion_call_args,
+ resolve_completion_model,
+ resolve_completion_provider,
+)
logger = logging.getLogger(__name__)
@@ -43,6 +54,25 @@ EMBEDDING_MODEL_ID = "default_embedding_model"
SUPPORTED_MODES = ("local", "global", "drift", "basic")
DEFAULT_MODE = "local"
+# GraphRAG's stock LiteLLM embedding client uses an OpenAI-style transport and
+# appends the ``/embeddings`` operation path to ``api_base``. DeepTutor stores a
+# complete operation URL for these bindings, so only this explicitly compatible
+# set can be translated safely. Native Cohere, Ollama, DashScope, and Azure
+# transports require separate provider adapters and must not be guessed here.
+OPENAI_COMPATIBLE_EMBEDDING_BINDINGS = frozenset(
+ {
+ "custom",
+ "custom_openai_sdk",
+ "gemini",
+ "jina",
+ "openai",
+ "openrouter",
+ "orcarouter",
+ "siliconflow",
+ "vllm",
+ }
+)
+
class GraphRagNotAvailableError(RuntimeError):
"""Raised when the optional ``graphrag`` dependency is not installed."""
@@ -75,6 +105,59 @@ def normalize_mode(mode: str | None) -> str:
return candidate if candidate in SUPPORTED_MODES else DEFAULT_MODE
+def graphrag_embedding_api_base(binding: str | None, endpoint: str | None) -> str:
+ """Translate a DeepTutor embedding endpoint into GraphRAG ``api_base``.
+
+ DeepTutor's public embedding contract stores and calls the complete
+ operation URL. GraphRAG's LiteLLM client expects the API root and appends
+ ``/embeddings`` itself. Strip exactly one terminal path segment only for
+ known OpenAI-compatible transports. Query-bearing URLs are left untouched
+ because the OpenAI SDK does not preserve operation semantics reliably when
+ query parameters are embedded in ``base_url``.
+
+ Args:
+ binding: Active DeepTutor embedding binding.
+ endpoint: Fully qualified endpoint saved in the model catalog.
+
+ Returns:
+ The API base GraphRAG should pass to LiteLLM.
+ """
+ value = str(endpoint or "").strip()
+ provider = canonical_embedding_provider_name(binding)
+ if not value or provider not in OPENAI_COMPATIBLE_EMBEDDING_BINDINGS:
+ return value
+
+ parsed = urlsplit(value)
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
+ return value
+ if parsed.query or parsed.fragment:
+ return value
+
+ path = parsed.path.rstrip("/")
+ if not path.endswith("/embeddings"):
+ return value
+
+ api_path = path[: -len("/embeddings")] or "/"
+ return urlunsplit(parsed._replace(path=api_path))
+
+
+def ensure_graphrag_embedding_transport(
+ binding: str | None,
+ endpoint: str | None,
+) -> None:
+ """Reject native embedding transports that GraphRAG cannot call safely."""
+ provider = canonical_embedding_provider_name(binding)
+ if provider not in OPENAI_COMPATIBLE_EMBEDDING_BINDINGS:
+ raise GraphRagEmbeddingProviderUnsupportedError()
+ # Gemini can use either DeepTutor's native ``batchEmbedContents`` adapter
+ # or its legacy OpenAI-compatible endpoint. GraphRAG only supports the
+ # latter; a provider name alone is no longer enough after Gemini 2 support.
+ if provider == "gemini" and not urlsplit(str(endpoint or "")).path.rstrip("/").endswith(
+ "/embeddings"
+ ):
+ raise GraphRagEmbeddingProviderUnsupportedError()
+
+
@dataclass(frozen=True)
class GraphRagQueryConfig:
"""Query-time knobs read from the persisted ``graphrag.json`` slice."""
@@ -99,9 +182,18 @@ def query_config_from_settings() -> GraphRagQueryConfig:
return GraphRagQueryConfig()
-def _model_entry(*, model: str, api_base: str | None, api_key: str | None) -> dict[str, Any]:
+def _embedding_model_entry(
+ *,
+ model: str,
+ api_base: str | None,
+ api_key: str | None,
+ binding: str | None,
+ dimension: int,
+ send_dimensions: bool | None,
+ extra_headers: dict[str, str] | None,
+) -> dict[str, Any]:
entry: dict[str, Any] = {
- "model_provider": "openai", # LiteLLM provider for any OpenAI-compatible API
+ "model_provider": "openai",
"model": model,
"auth_method": "api_key",
}
@@ -110,6 +202,37 @@ def _model_entry(*, model: str, api_base: str | None, api_key: str | None) -> di
# GraphRAG validates that a key is present for ``auth_method: api_key``; local
# OpenAI-compatible servers accept a placeholder.
entry["api_key"] = api_key or "sk-no-key-required"
+ call_args: dict[str, Any] = {}
+ if isinstance(extra_headers, dict) and extra_headers:
+ call_args["extra_headers"] = dict(extra_headers)
+ if should_send_embedding_dimensions(
+ binding=binding,
+ model=model,
+ dimension=dimension,
+ send_dimensions=send_dimensions,
+ ):
+ call_args["dimensions"] = dimension
+ if call_args:
+ entry["call_args"] = call_args
+ return entry
+
+
+def _completion_model_entry(llm_cfg: Any, *, api_base: str | None) -> dict[str, Any]:
+ entry: dict[str, Any] = {
+ "type": COMPLETION_TYPE,
+ "model_provider": resolve_completion_provider(llm_cfg),
+ "model": resolve_completion_model(llm_cfg),
+ "auth_method": "api_key",
+ "api_key": getattr(llm_cfg, "api_key", None) or "sk-no-key-required",
+ }
+ if api_base:
+ entry["api_base"] = api_base
+ api_version = getattr(llm_cfg, "api_version", None)
+ if api_version:
+ entry["api_version"] = api_version
+ call_args = resolve_completion_call_args(llm_cfg)
+ if call_args:
+ entry["call_args"] = call_args
return entry
@@ -148,24 +271,27 @@ def build_settings(*, llm_cfg: Any = None, embedding_cfg: Any = None) -> dict[st
"Settings → Catalog before creating a GraphRAG knowledge base."
)
+ embedding_binding = str(getattr(embedding_cfg, "binding", "") or "")
llm_base = getattr(llm_cfg, "effective_url", None) or getattr(llm_cfg, "base_url", None)
- embed_base = getattr(embedding_cfg, "effective_url", None) or getattr(
+ embed_endpoint = getattr(embedding_cfg, "effective_url", None) or getattr(
embedding_cfg, "base_url", None
)
+ ensure_graphrag_embedding_transport(embedding_binding, embed_endpoint)
+ embed_base = graphrag_embedding_api_base(embedding_binding, embed_endpoint)
return {
"completion_models": {
- COMPLETION_MODEL_ID: _model_entry(
- model=chat_model,
- api_base=llm_base,
- api_key=getattr(llm_cfg, "api_key", None),
- ),
+ COMPLETION_MODEL_ID: _completion_model_entry(llm_cfg, api_base=llm_base),
},
"embedding_models": {
- EMBEDDING_MODEL_ID: _model_entry(
+ EMBEDDING_MODEL_ID: _embedding_model_entry(
model=embed_model,
api_base=embed_base,
api_key=getattr(embedding_cfg, "api_key", None),
+ binding=embedding_binding,
+ dimension=embed_dim,
+ send_dimensions=getattr(embedding_cfg, "send_dimensions", None),
+ extra_headers=getattr(embedding_cfg, "extra_headers", None),
),
},
# Plain-text input: DeepTutor's ingestion writes parsed ``.txt`` files
@@ -192,31 +318,40 @@ def build_settings(*, llm_cfg: Any = None, embedding_cfg: Any = None) -> dict[st
}
-def write_settings(root_dir: Path, *, llm_cfg: Any = None, embedding_cfg: Any = None) -> Path:
- """Write ``settings.yaml`` into ``root_dir`` and return its path."""
+def write_settings_payload(root_dir: Path, settings: dict[str, Any]) -> Path:
+ """Write a previously-built settings snapshot into ``root_dir``."""
import yaml
root_dir = Path(root_dir)
root_dir.mkdir(parents=True, exist_ok=True)
- settings = build_settings(llm_cfg=llm_cfg, embedding_cfg=embedding_cfg)
path = root_dir / SETTINGS_FILENAME
with open(path, "w", encoding="utf-8") as handle:
yaml.safe_dump(settings, handle, sort_keys=False, allow_unicode=True)
return path
+def write_settings(root_dir: Path, *, llm_cfg: Any = None, embedding_cfg: Any = None) -> Path:
+ """Build and write ``settings.yaml`` into ``root_dir``."""
+ settings = build_settings(llm_cfg=llm_cfg, embedding_cfg=embedding_cfg)
+ return write_settings_payload(root_dir, settings)
+
+
__all__ = [
"SETTINGS_FILENAME",
"COMPLETION_MODEL_ID",
"EMBEDDING_MODEL_ID",
"SUPPORTED_MODES",
"DEFAULT_MODE",
+ "OPENAI_COMPATIBLE_EMBEDDING_BINDINGS",
"GraphRagNotAvailableError",
"GraphRagNotConfiguredError",
"GraphRagQueryConfig",
+ "ensure_graphrag_embedding_transport",
+ "graphrag_embedding_api_base",
"is_graphrag_available",
"normalize_mode",
"query_config_from_settings",
"build_settings",
"write_settings",
+ "write_settings_payload",
]
diff --git a/deeptutor/services/rag/pipelines/graphrag/engine.py b/deeptutor/services/rag/pipelines/graphrag/engine.py
index 11c67f32e..05b923001 100644
--- a/deeptutor/services/rag/pipelines/graphrag/engine.py
+++ b/deeptutor/services/rag/pipelines/graphrag/engine.py
@@ -17,7 +17,30 @@ import logging
from pathlib import Path
from typing import Any, TypeVar
-from .config import DEFAULT_MODE, normalize_mode, query_config_from_settings
+from .config import (
+ COMPLETION_MODEL_ID,
+ DEFAULT_MODE,
+ normalize_mode,
+ query_config_from_settings,
+)
+from .errors import (
+ EMBEDDING_RESPONSE_MESSAGE,
+ GraphRagEmbeddingDimensionError,
+ GraphRagEmbeddingProbeError,
+ GraphRagEmbeddingResponseError,
+ GraphRagModelIncompatibleError,
+ GraphRagStructuredOutputError,
+ GraphRagUnsupportedProviderError,
+ classify_embedding_error,
+ classify_model_error,
+)
+from .provider import (
+ COMPLETION_TYPE,
+ resolve_completion_call_args,
+ resolve_completion_model,
+ resolve_completion_provider,
+ resolve_persisted_completion_provider,
+)
logger = logging.getLogger(__name__)
@@ -26,6 +49,9 @@ logger = logging.getLogger(__name__)
# kept for tests / call sites that reference the defaults directly.
RESPONSE_TYPE = "Multiple Paragraphs"
DEFAULT_COMMUNITY_LEVEL = 2
+PROBE_MAX_TOKENS = 1024
+PROBE_TIMEOUT_SECONDS = 25
+EMBEDDING_PROBE_TEXT = "DeepTutor GraphRAG embedding compatibility test"
# Per-mode output tables the query API needs (mirrors graphrag.cli.query).
_OUTPUTS_BY_MODE: dict[str, tuple[list[str], list[str]]] = {
@@ -48,7 +74,15 @@ _T = TypeVar("_T")
def _load_config(root_dir: Path):
from graphrag.config.load_config import load_config
- return load_config(root_dir=Path(root_dir))
+ from .completion_adapter import register_completion_adapter
+
+ register_completion_adapter()
+ config = load_config(root_dir=Path(root_dir))
+ for model_config in config.completion_models.values():
+ if model_config.type in {"litellm", COMPLETION_TYPE}:
+ model_config.type = COMPLETION_TYPE
+ model_config.model_provider = resolve_persisted_completion_provider(model_config)
+ return config
async def _run_isolated(work: Callable[[], Awaitable[_T]]) -> _T:
@@ -81,20 +115,218 @@ async def _run_isolated(work: Callable[[], Awaitable[_T]]) -> _T:
return await asyncio.to_thread(_runner)
-async def build(root_dir: Path, *, is_update: bool = False) -> None:
+def _create_probe_completion(llm_cfg: Any):
+ """Create the same adapted completion client/schema used by community reports."""
+ from graphrag.index.operations.summarize_communities.community_reports_extractor import (
+ CommunityReportResponse,
+ )
+ from graphrag_llm.completion import create_completion
+ from graphrag_llm.config import ModelConfig
+
+ from .completion_adapter import register_completion_adapter
+
+ api_base = getattr(llm_cfg, "effective_url", None) or getattr(llm_cfg, "base_url", None)
+ call_args = resolve_completion_call_args(llm_cfg)
+ register_completion_adapter()
+ model_config = ModelConfig(
+ type=COMPLETION_TYPE,
+ model_provider=resolve_completion_provider(llm_cfg),
+ model=resolve_completion_model(llm_cfg),
+ api_base=api_base,
+ api_version=getattr(llm_cfg, "api_version", None),
+ api_key=getattr(llm_cfg, "api_key", None) or "sk-no-key-required",
+ auth_method="api_key",
+ call_args=call_args,
+ )
+ return create_completion(model_config), CommunityReportResponse
+
+
+def _create_configured_probe_completion(config: Any):
+ """Create a probe from a loaded settings snapshot used by real indexing."""
+ from graphrag.index.operations.summarize_communities.community_reports_extractor import (
+ CommunityReportResponse,
+ )
+ from graphrag_llm.completion import create_completion
+
+ return (
+ create_completion(config.completion_models[COMPLETION_MODEL_ID]),
+ CommunityReportResponse,
+ )
+
+
+async def _validate_probe_completion(completion: Any, response_model: type) -> None:
+ """Request and validate one minimal GraphRAG community-report response."""
+ response = await completion.completion_async(
+ messages=(
+ "Return one concise community report for a graph containing one topic named "
+ "'compatibility test'. Include a title, summary, one finding with summary and "
+ "explanation, a numeric rating, and a rating explanation."
+ ),
+ response_format=response_model,
+ max_tokens=PROBE_MAX_TOKENS,
+ stream=False,
+ timeout=PROBE_TIMEOUT_SECONDS,
+ )
+ if not isinstance(getattr(response, "formatted_response", None), response_model):
+ raise GraphRagStructuredOutputError("GraphRAG structured response validation failed.")
+
+
+async def _probe_completion_model_impl(llm_cfg: Any) -> None:
+ """Probe a resolved DeepTutor model through the GraphRAG adapter."""
+ await _validate_probe_completion(*_create_probe_completion(llm_cfg))
+
+
+def _failed_probe_result(llm_cfg: Any, error: Exception) -> dict[str, Any]:
+ """Classify a probe failure without returning provider messages or credentials."""
+ classified = classify_model_error(error)
+ if isinstance(
+ classified,
+ (GraphRagModelIncompatibleError, GraphRagUnsupportedProviderError),
+ ):
+ status = "incompatible"
+ compatible: bool | None = False
+ else:
+ status = "unverifiable"
+ compatible = None
+ if classified is not None:
+ return {
+ "status": status,
+ "compatible": compatible,
+ "code": classified.code,
+ "message": str(classified),
+ "model": str(getattr(llm_cfg, "model", "") or ""),
+ "binding": str(getattr(llm_cfg, "binding", "") or ""),
+ "retryable": classified.retryable,
+ }
+ return {
+ "status": "unverifiable",
+ "compatible": None,
+ "code": "graphrag_model_probe_failed",
+ "message": "GraphRAG compatibility could not be verified with this model.",
+ "model": str(getattr(llm_cfg, "model", "") or ""),
+ "binding": str(getattr(llm_cfg, "binding", "") or ""),
+ "retryable": False,
+ }
+
+
+async def probe_completion_model(llm_cfg: Any) -> dict[str, Any]:
+ """Test one completion config against GraphRAG's structured-output contract."""
+ try:
+ await _run_isolated(lambda: _probe_completion_model_impl(llm_cfg))
+ except Exception as error: # noqa: BLE001 - converted into a secret-free probe result
+ return _failed_probe_result(llm_cfg, error)
+ return {
+ "status": "compatible",
+ "compatible": True,
+ "code": "graphrag_model_compatible",
+ "message": "The model returned valid GraphRAG structured output.",
+ "model": str(getattr(llm_cfg, "model", "") or ""),
+ "binding": str(getattr(llm_cfg, "binding", "") or ""),
+ "retryable": False,
+ }
+
+
+def _create_probe_embedding(config: Any) -> tuple[Any, int]:
+ """Create GraphRAG's configured embedding client and expected vector size."""
+ from graphrag_llm.embedding import create_embedding
+
+ model_id = config.embed_text.embedding_model_id
+ model_config = config.embedding_models[model_id]
+ expected_dimension = int(config.vector_store.vector_size or 0)
+ return create_embedding(model_config), expected_dimension
+
+
+async def _probe_embedding_model_impl(config: Any) -> None:
+ """Run one bounded embedding request through GraphRAG's actual client."""
+ embedding, expected_dimension = _create_probe_embedding(config)
+ try:
+ response = await embedding.embedding_async(
+ input=[EMBEDDING_PROBE_TEXT],
+ timeout=PROBE_TIMEOUT_SECONDS,
+ )
+ except Exception as error: # noqa: BLE001 - classified into secret-free metadata
+ classified = classify_embedding_error(error)
+ if classified is not None:
+ raise classified from error
+ raise GraphRagEmbeddingProbeError() from error
+
+ vector = getattr(response, "first_embedding", None)
+ if not isinstance(vector, list) or not vector:
+ raise GraphRagEmbeddingResponseError(EMBEDDING_RESPONSE_MESSAGE)
+ if expected_dimension and len(vector) != expected_dimension:
+ raise GraphRagEmbeddingDimensionError(
+ configured=expected_dimension,
+ actual=len(vector),
+ )
+
+
+async def preflight_embedding(root_dir: Path) -> None:
+ """Validate one settings snapshot through GraphRAG's real embedding client."""
+ await _run_isolated(lambda: _preflight_embedding_impl(root_dir))
+
+
+async def preflight_completion(root_dir: Path) -> None:
+ """Validate the completion model from the exact persisted settings snapshot."""
+ try:
+ await _run_isolated(lambda: _preflight_completion_impl(root_dir))
+ except Exception as error:
+ classified = classify_model_error(error)
+ if classified is not None and classified is not error:
+ raise classified from error
+ raise
+
+
+async def _preflight_completion_impl(root_dir: Path) -> None:
+ config = _load_config(root_dir)
+ logger.info("GraphRAG: validating the active completion model before indexing")
+ await _validate_probe_completion(*_create_configured_probe_completion(config))
+
+
+async def _preflight_embedding_impl(root_dir: Path) -> None:
+ config = _load_config(root_dir)
+ logger.info("GraphRAG: validating the active embedding model before indexing")
+ await _probe_embedding_model_impl(config)
+
+
+async def build(
+ root_dir: Path,
+ *,
+ is_update: bool = False,
+ preflight_embedding_model: bool = True,
+) -> None:
"""Run the GraphRAG indexing pipeline rooted at ``root_dir``.
Raises on any failed workflow so the caller can surface an error and clean
up the (incomplete) version directory.
"""
- await _run_isolated(lambda: _build_impl(root_dir, is_update=is_update))
-
-
-async def _build_impl(root_dir: Path, *, is_update: bool) -> None:
+ try:
+ await _run_isolated(
+ lambda: _build_impl(
+ root_dir,
+ is_update=is_update,
+ preflight_embedding_model=preflight_embedding_model,
+ )
+ )
+ except Exception as error:
+ classified = classify_model_error(error)
+ if classified is not None and classified is not error:
+ raise classified from error
+ raise
+
+
+async def _build_impl(
+ root_dir: Path,
+ *,
+ is_update: bool,
+ preflight_embedding_model: bool,
+) -> None:
from graphrag.api import build_index
from graphrag.config.enums import IndexingMethod
config = _load_config(root_dir)
+ if preflight_embedding_model:
+ logger.info("GraphRAG: validating the active embedding model before indexing")
+ await _probe_embedding_model_impl(config)
logger.info("GraphRAG: building index at %s (update=%s)", root_dir, is_update)
results = await build_index(
config=config,
@@ -103,6 +335,17 @@ async def _build_impl(root_dir: Path, *, is_update: bool) -> None:
)
errors = [r for r in results if getattr(r, "error", None) is not None]
if errors:
+ for result in errors:
+ error = getattr(result, "error", None)
+ if isinstance(error, BaseException):
+ workflow = str(getattr(result, "workflow", "") or "").lower()
+ classified = (
+ classify_embedding_error(error)
+ if "embed" in workflow
+ else classify_model_error(error)
+ )
+ if classified is not None:
+ raise classified from error
detail = "; ".join(f"{r.workflow}: {r.error}" for r in errors[:3])
raise RuntimeError(f"GraphRAG indexing failed: {detail}")
@@ -131,7 +374,13 @@ async def search(root_dir: Path, query: str, mode: str | None = None) -> tuple[s
``context_data`` is normalised to a dict of record lists
(reports/entities/relationships/claims/sources) via GraphRAG's own helper.
"""
- return await _run_isolated(lambda: _search_impl(root_dir, query, mode))
+ try:
+ return await _run_isolated(lambda: _search_impl(root_dir, query, mode))
+ except Exception as error:
+ classified = classify_model_error(error)
+ if classified is not None and classified is not error:
+ raise classified from error
+ raise
async def _search_impl(root_dir: Path, query: str, mode: str | None) -> tuple[str, dict]:
@@ -195,4 +444,11 @@ async def _search_impl(root_dir: Path, query: str, mode: str | None) -> tuple[st
return str(response), context_data
-__all__ = ["build", "search", "RESPONSE_TYPE", "DEFAULT_COMMUNITY_LEVEL"]
+__all__ = [
+ "build",
+ "search",
+ "probe_completion_model",
+ "preflight_completion",
+ "RESPONSE_TYPE",
+ "DEFAULT_COMMUNITY_LEVEL",
+]
diff --git a/deeptutor/services/rag/pipelines/graphrag/errors.py b/deeptutor/services/rag/pipelines/graphrag/errors.py
new file mode 100644
index 000000000..bf1a81818
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/graphrag/errors.py
@@ -0,0 +1,328 @@
+"""Typed, secret-free GraphRAG pipeline errors for API and task reporting."""
+
+from __future__ import annotations
+
+from typing import ClassVar
+
+MODEL_INCOMPATIBLE_MESSAGE = (
+ "The model did not accept or return the structured output required by GraphRAG."
+)
+MODEL_AUTHENTICATION_MESSAGE = (
+ "GraphRAG compatibility could not be verified because the model credentials were rejected."
+)
+MODEL_RATE_LIMIT_MESSAGE = (
+ "GraphRAG compatibility could not be verified because the model provider is rate limiting "
+ "requests. Try again later."
+)
+MODEL_CONNECTION_MESSAGE = (
+ "GraphRAG compatibility could not be verified because the model provider could not be "
+ "reached. Try again later."
+)
+MODEL_OUTPUT_TRUNCATED_MESSAGE = (
+ "GraphRAG compatibility could not be verified because the model response reached its "
+ "output token limit. Try again."
+)
+EMBEDDING_AUTHENTICATION_MESSAGE = (
+ "GraphRAG could not use the active embedding model because its credentials were rejected."
+)
+EMBEDDING_RATE_LIMIT_MESSAGE = (
+ "GraphRAG could not use the active embedding model because the provider is rate limiting "
+ "requests. Try again later."
+)
+EMBEDDING_CONNECTION_MESSAGE = (
+ "GraphRAG could not reach the active embedding provider. Try again later."
+)
+EMBEDDING_ENDPOINT_MESSAGE = (
+ "The configured GraphRAG embedding model or endpoint was not found. Check the embedding "
+ "provider URL and model."
+)
+EMBEDDING_RESPONSE_MESSAGE = (
+ "The active embedding model did not accept or return the vector response required by GraphRAG."
+)
+EMBEDDING_PROVIDER_UNSUPPORTED_MESSAGE = (
+ "GraphRAG currently requires an OpenAI-compatible embedding endpoint. The active embedding "
+ "provider uses a native transport; choose its OpenAI-compatible endpoint or another "
+ "embedding profile."
+)
+
+
+class GraphRagPipelineError(RuntimeError):
+ """Base error carrying stable metadata for GraphRAG pipeline failures."""
+
+ code: ClassVar[str] = "graphrag_failed"
+ retryable: ClassVar[bool] = False
+
+
+class GraphRagModelError(GraphRagPipelineError):
+ """Base error carrying stable metadata for GraphRAG model failures."""
+
+ code: ClassVar[str] = "graphrag_model_failed"
+ retryable: ClassVar[bool] = False
+
+
+class GraphRagModelIncompatibleError(GraphRagModelError):
+ """Raised when a model cannot satisfy GraphRAG's structured-output contract."""
+
+ code = "graphrag_model_incompatible"
+
+
+class GraphRagStructuredOutputError(GraphRagModelIncompatibleError, ValueError):
+ """Raised when both native and fallback output fail strict schema validation."""
+
+
+class GraphRagStructuredOutputTruncatedError(GraphRagModelError, ValueError):
+ """Raised when strict validation fails because the provider truncated its response."""
+
+ code = "graphrag_model_output_truncated"
+ retryable = True
+
+ def __init__(self, _provider_detail: str | None = None) -> None:
+ """Discard provider response details and retain only the safe public message."""
+ super().__init__(MODEL_OUTPUT_TRUNCATED_MESSAGE)
+
+
+class GraphRagUnsupportedProviderError(GraphRagModelIncompatibleError):
+ """Raised when GraphRAG cannot use a provider's authentication transport."""
+
+ code = "graphrag_provider_unsupported"
+
+
+class GraphRagModelAuthenticationError(GraphRagModelError):
+ """Raised when the provider rejects the configured credentials."""
+
+ code = "graphrag_model_authentication_failed"
+
+
+class GraphRagModelRateLimitError(GraphRagModelError):
+ """Raised when compatibility cannot be checked because of provider throttling."""
+
+ code = "graphrag_model_rate_limited"
+ retryable = True
+
+
+class GraphRagModelConnectionError(GraphRagModelError):
+ """Raised when a transient provider or network failure prevents a model call."""
+
+ code = "graphrag_model_connection_failed"
+ retryable = True
+
+
+class GraphRagModelEndpointError(GraphRagModelError):
+ """Raised when the configured endpoint or model cannot be found."""
+
+ code = "graphrag_model_endpoint_failed"
+
+
+class GraphRagEmbeddingError(GraphRagPipelineError):
+ """Base error for GraphRAG embedding transport and response failures."""
+
+ code = "graphrag_embedding_failed"
+
+
+class GraphRagEmbeddingProviderUnsupportedError(GraphRagEmbeddingError):
+ """Raised before indexing when the active embedding transport is not supported."""
+
+ code = "graphrag_embedding_provider_unsupported"
+
+ def __init__(self) -> None:
+ super().__init__(EMBEDDING_PROVIDER_UNSUPPORTED_MESSAGE)
+
+
+class GraphRagEmbeddingAuthenticationError(GraphRagEmbeddingError):
+ """Raised when GraphRAG embedding credentials are rejected."""
+
+ code = "graphrag_embedding_authentication_failed"
+
+
+class GraphRagEmbeddingRateLimitError(GraphRagEmbeddingError):
+ """Raised when the embedding provider throttles the preflight or indexing call."""
+
+ code = "graphrag_embedding_rate_limited"
+ retryable = True
+
+
+class GraphRagEmbeddingConnectionError(GraphRagEmbeddingError):
+ """Raised when the GraphRAG embedding provider cannot be reached."""
+
+ code = "graphrag_embedding_connection_failed"
+ retryable = True
+
+
+class GraphRagEmbeddingEndpointError(GraphRagEmbeddingError):
+ """Raised when the GraphRAG embedding model or endpoint returns not found."""
+
+ code = "graphrag_embedding_endpoint_failed"
+
+
+class GraphRagEmbeddingResponseError(GraphRagEmbeddingError, ValueError):
+ """Raised when the embedding provider returns an unusable vector response."""
+
+ code = "graphrag_embedding_incompatible"
+
+
+class GraphRagEmbeddingProbeError(GraphRagEmbeddingError):
+ """Raised when an unexpected internal failure prevents embedding validation."""
+
+ code = "graphrag_embedding_probe_failed"
+
+ def __init__(self) -> None:
+ super().__init__(
+ "GraphRAG embedding compatibility could not be verified because of an internal error."
+ )
+
+
+class GraphRagEmbeddingDimensionError(GraphRagEmbeddingError, ValueError):
+ """Raised when the configured dimension differs from the provider response."""
+
+ code = "graphrag_embedding_dimension_mismatch"
+
+ def __init__(self, *, configured: int, actual: int) -> None:
+ super().__init__(
+ "The active embedding model returned "
+ f"{actual} dimensions, but DeepTutor is configured for {configured}. "
+ "Correct the embedding dimension before indexing with GraphRAG."
+ )
+
+
+_FORMAT_MARKERS = (
+ "response_format",
+ "response format",
+ "json_schema",
+ "json schema",
+ "structured output",
+)
+_UNSUPPORTED_MARKERS = (
+ "unavailable",
+ "unsupported",
+ "not supported",
+ "does not support",
+ "not available",
+ "not valid",
+ "must be",
+ "rejected",
+)
+
+
+def is_unsupported_schema_error(error: BaseException) -> bool:
+ """Return whether a provider explicitly rejected structured-output format support."""
+ if type(error).__name__ not in {
+ "BadRequestError",
+ "InvalidRequestError",
+ "UnsupportedParamsError",
+ "UnprocessableEntityError",
+ }:
+ return False
+ message = str(error).lower()
+ return any(marker in message for marker in _FORMAT_MARKERS) and any(
+ marker in message for marker in _UNSUPPORTED_MARKERS
+ )
+
+
+def _status_code(error: BaseException) -> int | None:
+ """Return a provider HTTP status without inspecting or exposing its body."""
+ value = getattr(error, "status_code", None)
+ if value is None:
+ value = getattr(error, "status", None)
+ return value if isinstance(value, int) else None
+
+
+def classify_embedding_error(error: BaseException) -> GraphRagPipelineError | None:
+ """Map embedding failures to stable, secret-free GraphRAG error metadata."""
+ if isinstance(error, GraphRagPipelineError):
+ return error
+
+ error_name = type(error).__name__
+ status_code = _status_code(error)
+ if error_name in {"AuthenticationError", "PermissionDeniedError"} or status_code in {
+ 401,
+ 403,
+ }:
+ return GraphRagEmbeddingAuthenticationError(EMBEDDING_AUTHENTICATION_MESSAGE)
+ if error_name == "RateLimitError" or status_code == 429:
+ return GraphRagEmbeddingRateLimitError(EMBEDDING_RATE_LIMIT_MESSAGE)
+ if error_name in {"NotFoundError"} or status_code == 404:
+ return GraphRagEmbeddingEndpointError(EMBEDDING_ENDPOINT_MESSAGE)
+ if error_name in {
+ "APIConnectionError",
+ "ConnectError",
+ "ConnectTimeout",
+ "ReadTimeout",
+ "ServiceUnavailableError",
+ "Timeout",
+ "TimeoutError",
+ } or (status_code is not None and status_code >= 500):
+ return GraphRagEmbeddingConnectionError(EMBEDDING_CONNECTION_MESSAGE)
+ if error_name in {
+ "BadRequestError",
+ "InvalidRequestError",
+ "UnprocessableEntityError",
+ "UnsupportedParamsError",
+ } or status_code in {400, 409, 422}:
+ return GraphRagEmbeddingResponseError(EMBEDDING_RESPONSE_MESSAGE)
+ return None
+
+
+def classify_model_error(error: BaseException) -> GraphRagPipelineError | None:
+ """Map known provider failures to stable GraphRAG errors without exposing details."""
+ if isinstance(error, GraphRagPipelineError):
+ return error
+ if is_unsupported_schema_error(error):
+ return GraphRagModelIncompatibleError(MODEL_INCOMPATIBLE_MESSAGE)
+
+ error_name = type(error).__name__
+ if error_name in {"AuthenticationError", "PermissionDeniedError"}:
+ return GraphRagModelAuthenticationError(MODEL_AUTHENTICATION_MESSAGE)
+ if error_name == "RateLimitError":
+ return GraphRagModelRateLimitError(MODEL_RATE_LIMIT_MESSAGE)
+ if error_name in {
+ "APIConnectionError",
+ "ServiceUnavailableError",
+ "Timeout",
+ "TimeoutError",
+ }:
+ return GraphRagModelConnectionError(MODEL_CONNECTION_MESSAGE)
+ if error_name in {"NotFoundError"} or getattr(error, "status_code", None) == 404:
+ return GraphRagModelEndpointError(
+ "The configured GraphRAG model or endpoint was not found. Check its provider URL."
+ )
+ status_code = _status_code(error)
+ if error_name == "APIError" and isinstance(status_code, int) and status_code >= 500:
+ return GraphRagModelConnectionError(MODEL_CONNECTION_MESSAGE)
+ return None
+
+
+__all__ = [
+ "EMBEDDING_AUTHENTICATION_MESSAGE",
+ "EMBEDDING_CONNECTION_MESSAGE",
+ "EMBEDDING_ENDPOINT_MESSAGE",
+ "EMBEDDING_PROVIDER_UNSUPPORTED_MESSAGE",
+ "EMBEDDING_RATE_LIMIT_MESSAGE",
+ "EMBEDDING_RESPONSE_MESSAGE",
+ "GraphRagEmbeddingAuthenticationError",
+ "GraphRagEmbeddingConnectionError",
+ "GraphRagEmbeddingDimensionError",
+ "GraphRagEmbeddingEndpointError",
+ "GraphRagEmbeddingError",
+ "GraphRagEmbeddingProviderUnsupportedError",
+ "GraphRagEmbeddingProbeError",
+ "GraphRagEmbeddingRateLimitError",
+ "GraphRagEmbeddingResponseError",
+ "GraphRagModelAuthenticationError",
+ "GraphRagModelConnectionError",
+ "GraphRagModelEndpointError",
+ "GraphRagModelError",
+ "GraphRagModelIncompatibleError",
+ "GraphRagModelRateLimitError",
+ "GraphRagPipelineError",
+ "GraphRagStructuredOutputError",
+ "GraphRagStructuredOutputTruncatedError",
+ "GraphRagUnsupportedProviderError",
+ "MODEL_AUTHENTICATION_MESSAGE",
+ "MODEL_CONNECTION_MESSAGE",
+ "MODEL_INCOMPATIBLE_MESSAGE",
+ "MODEL_OUTPUT_TRUNCATED_MESSAGE",
+ "MODEL_RATE_LIMIT_MESSAGE",
+ "classify_embedding_error",
+ "classify_model_error",
+ "is_unsupported_schema_error",
+]
diff --git a/deeptutor/services/rag/pipelines/graphrag/pipeline.py b/deeptutor/services/rag/pipelines/graphrag/pipeline.py
index e8a14c060..0192cc39e 100644
--- a/deeptutor/services/rag/pipelines/graphrag/pipeline.py
+++ b/deeptutor/services/rag/pipelines/graphrag/pipeline.py
@@ -15,9 +15,11 @@ from __future__ import annotations
import logging
from pathlib import Path
import shutil
+import tempfile
import traceback
from typing import Any, Dict, List, Optional
+from deeptutor.logging import PROCESS_LOG_PRIVATE_ATTR
from deeptutor.runtime.home import get_runtime_data_root
from deeptutor.services.rag.index_versioning import (
resolve_storage_dir_for_read,
@@ -68,6 +70,18 @@ class GraphRagPipeline:
except Exception as exc: # pragma: no cover - best-effort
self.logger.warning("Could not clean up failed version dir %s: %s", root_dir, exc)
+ async def _preflight_settings(self, settings: dict[str, Any]) -> None:
+ """Probe a settings snapshot without touching an existing KB version."""
+ from . import engine
+
+ with tempfile.TemporaryDirectory(prefix="deeptutor-graphrag-preflight-") as temp_dir:
+ probe_root = Path(temp_dir)
+ gr_config.write_settings_payload(probe_root, settings)
+ # Check the cheaper embedding request first so an invalid endpoint
+ # does not trigger a structured completion call unnecessarily.
+ await engine.preflight_embedding(probe_root)
+ await engine.preflight_completion(probe_root)
+
# ----- indexing -------------------------------------------------------
async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
@@ -90,7 +104,10 @@ class GraphRagPipeline:
return True
except Exception as exc:
self.logger.error("Failed to initialize GraphRAG KB: %s", exc)
- self.logger.error(traceback.format_exc())
+ self.logger.error(
+ traceback.format_exc(),
+ extra={PROCESS_LOG_PRIVATE_ATTR: True},
+ )
self._cleanup_failed_version_dir(root_dir)
raise
@@ -111,26 +128,49 @@ class GraphRagPipeline:
)
try:
# Refresh settings so a changed model/endpoint is picked up.
- gr_config.write_settings(root_dir)
+ settings = gr_config.build_settings()
+ if is_update:
+ # An update reuses the active version directory. Validate the
+ # exact settings snapshot first so a bad provider configuration
+ # cannot overwrite a working settings.yaml or add input files.
+ await self._preflight_settings(settings)
+ gr_config.write_settings_payload(root_dir, settings)
count = await ingestion.prepare_input(file_paths, root_dir)
if count == 0:
self.logger.warning("GraphRAG: no extractable documents to add for '%s'", kb_name)
return False
- await self._build(root_dir, is_update=is_update)
+ await self._build(
+ root_dir,
+ is_update=is_update,
+ preflight_embedding_model=not is_update,
+ )
storage.write_meta(root_dir)
self.logger.info("Added %d doc(s) to GraphRAG KB '%s'", count, kb_name)
return True
except Exception as exc:
self.logger.error("Failed to add documents to GraphRAG KB: %s", exc)
- self.logger.error(traceback.format_exc())
+ self.logger.error(
+ traceback.format_exc(),
+ extra={PROCESS_LOG_PRIVATE_ATTR: True},
+ )
if not is_update:
self._cleanup_failed_version_dir(root_dir)
raise
- async def _build(self, root_dir: Path, *, is_update: bool) -> None:
+ async def _build(
+ self,
+ root_dir: Path,
+ *,
+ is_update: bool,
+ preflight_embedding_model: bool = True,
+ ) -> None:
from . import engine
- await engine.build(root_dir, is_update=is_update)
+ await engine.build(
+ root_dir,
+ is_update=is_update,
+ preflight_embedding_model=preflight_embedding_model,
+ )
# ----- retrieval ------------------------------------------------------
@@ -160,7 +200,10 @@ class GraphRagPipeline:
return self._error_result(query, exc, error_type="not_configured")
except Exception as exc:
self.logger.error("GraphRAG search failed: %s", exc)
- self.logger.error(traceback.format_exc())
+ self.logger.error(
+ traceback.format_exc(),
+ extra={PROCESS_LOG_PRIVATE_ATTR: True},
+ )
return self._error_result(query, exc, error_type="retrieval_error")
return {
diff --git a/deeptutor/services/rag/pipelines/graphrag/provider.py b/deeptutor/services/rag/pipelines/graphrag/provider.py
new file mode 100644
index 000000000..aee600eba
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/graphrag/provider.py
@@ -0,0 +1,129 @@
+"""Resolve DeepTutor model bindings at the GraphRAG/LiteLLM boundary."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from deeptutor.services.llm.reasoning_params import build_openai_compatible_reasoning_kwargs
+from deeptutor.services.provider_registry import find_by_name, strip_provider_prefix
+
+from .errors import GraphRagUnsupportedProviderError
+
+COMPLETION_TYPE = "deeptutor_litellm"
+
+
+def _runtime_binding(llm_cfg: Any) -> str:
+ return str(
+ getattr(llm_cfg, "binding", None) or getattr(llm_cfg, "provider_name", None) or "openai"
+ ).strip()
+
+
+def resolve_completion_provider(llm_cfg: Any) -> str:
+ """Map a resolved DeepTutor provider to the narrow LiteLLM transport GraphRAG needs."""
+ binding = _runtime_binding(llm_cfg)
+ spec = find_by_name(binding)
+ if spec is None:
+ return "openai"
+ if spec.backend == "anthropic":
+ return "anthropic"
+ if spec.backend == "azure_openai":
+ return "azure"
+ if spec.backend in {"openai_codex", "github_copilot"} or spec.is_oauth:
+ raise GraphRagUnsupportedProviderError(
+ "GraphRAG cannot use this OAuth-only model provider. Choose an API-key profile."
+ )
+ if spec.backend == "openai_compat":
+ # DeepSeek's LiteLLM provider owns its parameter compatibility logic.
+ # Other DeepTutor OpenAI-compatible profiles already expose an OpenAI
+ # chat-completions endpoint and are safest on the generic transport.
+ return "deepseek" if spec.name == "deepseek" else "openai"
+ raise GraphRagUnsupportedProviderError(
+ "GraphRAG does not support the selected model provider transport."
+ )
+
+
+def resolve_completion_model(llm_cfg: Any) -> str:
+ """Return the model identifier expected by the selected LiteLLM transport."""
+ model = str(getattr(llm_cfg, "model", "") or "")
+ spec = find_by_name(_runtime_binding(llm_cfg))
+ return strip_provider_prefix(model, spec)
+
+
+def resolve_completion_call_args(llm_cfg: Any) -> dict[str, Any]:
+ """Return the request options shared by GraphRAG probes and indexing."""
+ call_args: dict[str, Any] = {}
+ extra_headers = getattr(llm_cfg, "extra_headers", None)
+ if isinstance(extra_headers, dict) and extra_headers:
+ call_args["extra_headers"] = dict(extra_headers)
+
+ binding = _runtime_binding(llm_cfg)
+ spec = find_by_name(binding)
+ reasoning_effort = getattr(llm_cfg, "reasoning_effort", None)
+ if spec is not None and spec.backend == "openai_compat":
+ call_args.update(
+ build_openai_compatible_reasoning_kwargs(
+ spec=spec,
+ binding=binding,
+ model=resolve_completion_model(llm_cfg),
+ reasoning_effort=reasoning_effort,
+ )
+ )
+ elif reasoning_effort:
+ # Preserve the existing GraphRAG behavior for Anthropic, Azure, and
+ # unknown transports; the OpenAI-compatible normalizer is not valid for
+ # those backends.
+ call_args["reasoning_effort"] = reasoning_effort
+ return call_args
+
+
+def resolve_persisted_completion_provider(model_config: Any) -> str:
+ """Recover a provider for old DeepTutor GraphRAG settings without rewriting them."""
+ current = str(getattr(model_config, "model_provider", "") or "openai")
+ if current != "openai":
+ return current
+
+ model = str(getattr(model_config, "model", "") or "")
+ api_base = str(getattr(model_config, "api_base", "") or "").rstrip("/")
+ try:
+ from deeptutor.services.config import (
+ get_model_catalog_service,
+ resolve_llm_runtime_config,
+ )
+
+ service = get_model_catalog_service()
+ catalog = service.load()
+ profiles = catalog.get("services", {}).get("llm", {}).get("profiles", [])
+ matches: list[tuple[str, str]] = []
+ for profile in profiles:
+ profile_base = str(profile.get("base_url") or "").rstrip("/")
+ if profile_base != api_base:
+ continue
+ for candidate in profile.get("models", []):
+ if str(candidate.get("model") or "") == model:
+ matches.append((str(profile.get("id") or ""), str(candidate.get("id") or "")))
+ if len(matches) == 1:
+ profile_id, model_id = matches[0]
+ resolved = resolve_llm_runtime_config(
+ catalog=catalog,
+ service=service,
+ llm_selection={"profile_id": profile_id, "model_id": model_id},
+ )
+ return resolve_completion_provider(resolved)
+ except GraphRagUnsupportedProviderError:
+ raise
+ except Exception:
+ # Old settings remain usable even when the catalog is unavailable.
+ pass
+
+ if "api.deepseek.com" in api_base.lower():
+ return "deepseek"
+ return current
+
+
+__all__ = [
+ "COMPLETION_TYPE",
+ "resolve_completion_call_args",
+ "resolve_completion_model",
+ "resolve_completion_provider",
+ "resolve_persisted_completion_provider",
+]
diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py
index c87650109..b651ff9b7 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -346,6 +346,75 @@ def test_supported_file_types_returns_upload_policy() -> None:
assert "image/png" in payload["accept"]
+def test_graphrag_model_compatibility_probes_candidate_without_switching(
+ monkeypatch,
+) -> None:
+ captured: dict[str, str] = {}
+
+ async def _probe(profile_id: str, model_id: str) -> dict:
+ captured.update({"profile_id": profile_id, "model_id": model_id})
+ return {
+ "status": "compatible",
+ "compatible": True,
+ "code": "graphrag_model_compatible",
+ "message": "The model returned valid GraphRAG structured output.",
+ "model": "gpt-4o-mini",
+ "binding": "openai",
+ "retryable": False,
+ }
+
+ monkeypatch.setattr(
+ knowledge_router_module,
+ "_probe_graphrag_model_compatibility",
+ _probe,
+ raising=False,
+ )
+
+ with TestClient(_build_app()) as client:
+ response = client.post(
+ "/api/v1/knowledge/rag-pipelines/graphrag/model-compatibility",
+ json={"profile_id": "profile-a", "model_id": "model-b"},
+ )
+
+ assert response.status_code == 200
+ assert captured == {"profile_id": "profile-a", "model_id": "model-b"}
+ assert response.json() == {
+ "status": "compatible",
+ "compatible": True,
+ "code": "graphrag_model_compatible",
+ "message": "The model returned valid GraphRAG structured output.",
+ "model": "gpt-4o-mini",
+ "binding": "openai",
+ "retryable": False,
+ }
+
+
+def test_graphrag_model_compatibility_hides_unexpected_provider_details(
+ monkeypatch,
+) -> None:
+ async def _probe(_profile_id: str, _model_id: str) -> dict:
+ raise RuntimeError("provider leaked sk-secret-must-not-reach-client")
+
+ monkeypatch.setattr(
+ knowledge_router_module,
+ "_probe_graphrag_model_compatibility",
+ _probe,
+ raising=False,
+ )
+
+ with TestClient(_build_app()) as client:
+ response = client.post(
+ "/api/v1/knowledge/rag-pipelines/graphrag/model-compatibility",
+ json={"profile_id": "profile-a", "model_id": "model-b"},
+ )
+
+ assert response.status_code == 500
+ assert response.json()["detail"] == (
+ "GraphRAG compatibility could not be tested because of an internal error."
+ )
+ assert "sk-secret" not in response.text
+
+
def test_create_kb_does_not_require_llm_precheck(monkeypatch, tmp_path: Path) -> None:
manager = _FakeKBManager(tmp_path / "knowledge_bases")
monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)
diff --git a/tests/knowledge/test_progress_tracker.py b/tests/knowledge/test_progress_tracker.py
index 16f4590b5..b9ce062b9 100644
--- a/tests/knowledge/test_progress_tracker.py
+++ b/tests/knowledge/test_progress_tracker.py
@@ -56,3 +56,26 @@ def test_progress_tracker_get_progress_falls_back_to_config(tmp_path) -> None:
"current": 3,
"total": 5,
}
+
+
+def test_progress_tracker_persists_structured_failure_metadata(tmp_path) -> None:
+ tracker = ProgressTracker("demo-kb", tmp_path)
+
+ tracker.update(
+ ProgressStage.ERROR,
+ "GraphRAG model is incompatible",
+ error="Choose a chat model that supports structured output.",
+ error_code="graphrag_model_incompatible",
+ retryable=False,
+ )
+
+ with open(tracker.progress_file, encoding="utf-8") as handle:
+ payload = json.load(handle)
+
+ assert payload["error_code"] == "graphrag_model_incompatible"
+ assert payload["retryable"] is False
+
+ status = KnowledgeBaseManager(base_dir=str(tmp_path)).get_kb_status("demo-kb")
+ assert status is not None
+ assert status["progress"]["error_code"] == "graphrag_model_incompatible"
+ assert status["progress"]["retryable"] is False
diff --git a/tests/logging/test_process_logs.py b/tests/logging/test_process_logs.py
index c2876702f..b7af73549 100644
--- a/tests/logging/test_process_logs.py
+++ b/tests/logging/test_process_logs.py
@@ -1,15 +1,25 @@
import logging
-from deeptutor.logging import ProcessLogEvent, bind_log_context, capture_process_logs
+from deeptutor.logging import (
+ PROCESS_LOG_PRIVATE_ATTR,
+ ProcessLogEvent,
+ bind_log_context,
+ capture_process_logs,
+)
def test_capture_process_logs_emits_structured_event_for_matching_task():
events: list[ProcessLogEvent] = []
logger = logging.getLogger("deeptutor.tests.process")
+ original_level = logger.level
+ logger.setLevel(logging.INFO)
- with bind_log_context(task_id="task-1", capability="knowledge", stage="indexing"):
- with capture_process_logs(events.append, task_id="task-1"):
- logger.info("Embedding batches: %s/%s", 2, 8)
+ try:
+ with bind_log_context(task_id="task-1", capability="knowledge", stage="indexing"):
+ with capture_process_logs(events.append, task_id="task-1"):
+ logger.info("Embedding batches: %s/%s", 2, 8)
+ finally:
+ logger.setLevel(original_level)
assert len(events) == 1
event = events[0].to_dict()
@@ -33,3 +43,17 @@ def test_capture_process_logs_filters_other_tasks():
logger.warning("wrong task")
assert events == []
+
+
+def test_capture_process_logs_excludes_server_only_diagnostics():
+ events: list[ProcessLogEvent] = []
+ logger = logging.getLogger("deeptutor.tests.process")
+
+ with bind_log_context(task_id="task-1", capability="knowledge"):
+ with capture_process_logs(events.append, task_id="task-1"):
+ logger.error(
+ "Stack trace contains sk-secret-must-not-leak",
+ extra={PROCESS_LOG_PRIVATE_ATTR: True},
+ )
+
+ assert events == []
diff --git a/tests/logging/test_task_log_stream.py b/tests/logging/test_task_log_stream.py
index 5770ba97e..d1c82d990 100644
--- a/tests/logging/test_task_log_stream.py
+++ b/tests/logging/test_task_log_stream.py
@@ -8,6 +8,7 @@ from deeptutor.api.utils.task_log_stream import (
capture_task_logs,
get_task_stream_manager,
)
+from deeptutor.logging import PROCESS_LOG_PRIVATE_ATTR
@pytest.mark.asyncio
@@ -31,6 +32,26 @@ async def test_knowledge_task_stream_emits_process_log_sse_event():
assert payload["context"]["task_id"] == "task-1"
+def test_knowledge_task_stream_emits_structured_failure_metadata():
+ manager = KnowledgeTaskStreamManager()
+ manager.ensure_task("task-failed")
+
+ manager.emit_failed(
+ "task-failed",
+ "Choose a compatible chat model.",
+ details="internal traceback",
+ error_code="graphrag_model_incompatible",
+ retryable=False,
+ )
+
+ event = list(manager._buffers["task-failed"])[-1]
+ assert event["event"] == "failed"
+ assert event["payload"]["detail"] == "Choose a compatible chat model."
+ assert event["payload"]["details"] == "internal traceback"
+ assert event["payload"]["error_code"] == "graphrag_model_incompatible"
+ assert event["payload"]["retryable"] is False
+
+
def test_capture_task_logs_forwards_lightrag_non_propagating_logger():
original_instance = KnowledgeTaskStreamManager._instance
lightrag_logger = logging.getLogger("lightrag")
@@ -97,6 +118,35 @@ def test_capture_task_logs_forwards_graphrag_propagating_logger_once():
assert len(matches) == 1
+def test_capture_task_logs_excludes_private_non_propagating_library_diagnostics():
+ original_instance = KnowledgeTaskStreamManager._instance
+ graphrag_logger = logging.getLogger("graphrag")
+ original_handlers = list(graphrag_logger.handlers)
+ original_propagate = graphrag_logger.propagate
+ original_level = graphrag_logger.level
+ try:
+ KnowledgeTaskStreamManager._instance = KnowledgeTaskStreamManager()
+ graphrag_logger.handlers = []
+ graphrag_logger.propagate = False
+ graphrag_logger.setLevel(logging.INFO)
+
+ with capture_task_logs("task-private"):
+ graphrag_logger.error(
+ "Stack trace contains sk-secret-must-not-leak",
+ extra={PROCESS_LOG_PRIVATE_ATTR: True},
+ )
+
+ manager = get_task_stream_manager()
+ events = list(manager._buffers["task-private"])
+ finally:
+ KnowledgeTaskStreamManager._instance = original_instance
+ graphrag_logger.handlers = original_handlers
+ graphrag_logger.propagate = original_propagate
+ graphrag_logger.setLevel(original_level)
+
+ assert events == []
+
+
def test_completed_task_buffers_are_bounded_and_restore_terminal_event():
manager = KnowledgeTaskStreamManager()
manager._MAX_RETAINED_TASKS = 3
diff --git a/tests/services/config/test_graphrag_lightrag_settings.py b/tests/services/config/test_graphrag_lightrag_settings.py
index b6725cf1a..d9dfdf85e 100644
--- a/tests/services/config/test_graphrag_lightrag_settings.py
+++ b/tests/services/config/test_graphrag_lightrag_settings.py
@@ -62,6 +62,21 @@ def test_preflight_shape_for_all_engines() -> None:
assert report["ok"] == required_ok
+def test_graphrag_static_preflight_does_not_guess_structured_output_support(
+ monkeypatch,
+) -> None:
+ from deeptutor.services.rag import preflight
+ from deeptutor.services.rag.pipelines.graphrag import config as graphrag_config
+
+ monkeypatch.setattr(graphrag_config, "is_graphrag_available", lambda: True)
+ monkeypatch.setattr(preflight, "_active_chat_model", lambda: ("deepseek-v4-flash", "deepseek"))
+ monkeypatch.setattr(preflight, "_active_embedding", lambda: ("text-embedding", 1024))
+
+ report = preflight.engine_preflight("graphrag")
+ assert all(check["key"] != "structured_output" for check in report["checks"])
+ assert report["ok"] is True
+
+
def test_preflight_unknown_provider_falls_back_to_default() -> None:
from deeptutor.services.rag.preflight import engine_preflight
diff --git a/tests/services/rag/test_graphrag_completion_adapter.py b/tests/services/rag/test_graphrag_completion_adapter.py
new file mode 100644
index 000000000..4ecfc6729
--- /dev/null
+++ b/tests/services/rag/test_graphrag_completion_adapter.py
@@ -0,0 +1,575 @@
+"""Regression tests for DeepTutor's GraphRAG completion compatibility seam."""
+
+from __future__ import annotations
+
+import asyncio
+from concurrent.futures import ThreadPoolExecutor
+import json
+from pathlib import Path
+import threading
+
+import pytest
+
+from deeptutor.services.rag.pipelines.graphrag import config as gr_config
+from deeptutor.services.rag.pipelines.graphrag import engine
+from deeptutor.services.rag.pipelines.graphrag.errors import (
+ GraphRagStructuredOutputError,
+ GraphRagStructuredOutputTruncatedError,
+ GraphRagUnsupportedProviderError,
+)
+
+
+class _Cfg:
+ def __init__(
+ self,
+ model: str,
+ url: str,
+ key: str,
+ *,
+ binding: str = "openai",
+ dim: int = 3072,
+ reasoning_effort: str | None = None,
+ ) -> None:
+ self.model = model
+ self.effective_url = url
+ self.base_url = None
+ self.api_key = key
+ self.api_version = None
+ self.extra_headers: dict[str, str] = {}
+ self.binding = binding
+ self.provider_name = binding
+ self.reasoning_effort = reasoning_effort
+ self.dim = dim
+
+
+def _load_completion(
+ tmp_path: Path,
+ *,
+ binding: str = "deepseek",
+ model: str = "deepseek-v4-flash",
+ url: str = "https://api.deepseek.com",
+):
+ from graphrag_llm.completion import create_completion
+
+ gr_config.write_settings(
+ tmp_path,
+ llm_cfg=_Cfg(
+ model,
+ url,
+ "sk-test",
+ binding=binding,
+ ),
+ embedding_cfg=_Cfg("embedding-model", "https://embedding.test/v1", "sk-test"),
+ )
+ loaded = engine._load_config(tmp_path)
+ return create_completion(loaded.get_completion_model_config(gr_config.COMPLETION_MODEL_ID))
+
+
+def _report_payload() -> dict:
+ return {
+ "title": "Compatibility",
+ "summary": "The adapter returned structured output.",
+ "findings": [{"summary": "Finding", "explanation": "Validated locally."}],
+ "rating": 8,
+ "rating_explanation": "The response matched the schema.",
+ }
+
+
+def _model_response(litellm, payload: dict | str, *, finish_reason: str = "stop"):
+ content = payload if isinstance(payload, str) else json.dumps(payload)
+ return litellm.ModelResponse(
+ model="deepseek-v4-flash",
+ choices=[
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": content},
+ "finish_reason": finish_reason,
+ }
+ ],
+ )
+
+
+def test_settings_route_deepseek_completion_without_changing_embedding() -> None:
+ settings = gr_config.build_settings(
+ llm_cfg=_Cfg(
+ "deepseek-v4-flash",
+ "https://api.deepseek.com",
+ "sk-test",
+ binding="deepseek",
+ ),
+ embedding_cfg=_Cfg(
+ "Qwen/Qwen3-Embedding-8B",
+ "https://api.siliconflow.cn/v1",
+ "sk-test",
+ binding="siliconflow",
+ dim=4096,
+ ),
+ )
+
+ completion = settings["completion_models"][gr_config.COMPLETION_MODEL_ID]
+ embedding = settings["embedding_models"][gr_config.EMBEDDING_MODEL_ID]
+ assert completion["type"] == "deeptutor_litellm"
+ assert completion["model_provider"] == "deepseek"
+ assert embedding.get("type", "litellm") == "litellm"
+ assert embedding["model_provider"] == "openai"
+
+
+def test_probe_completion_uses_same_reasoning_options_as_persisted_settings() -> None:
+ pytest.importorskip("graphrag")
+ cfg = _Cfg(
+ "deepseek-v4-pro",
+ "https://api.deepseek.com",
+ "sk-test",
+ binding="deepseek",
+ )
+
+ completion, _response_model = engine._create_probe_completion(cfg)
+ settings = gr_config.build_settings(
+ llm_cfg=cfg,
+ embedding_cfg=_Cfg("embedding-model", "https://embedding.test/v1", "sk-test"),
+ )
+
+ expected = settings["completion_models"][gr_config.COMPLETION_MODEL_ID]["call_args"]
+ assert completion._model_config.call_args == expected
+
+
+def test_real_graphrag_completion_falls_back_when_schema_type_is_unavailable(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ litellm = pytest.importorskip("litellm")
+ pytest.importorskip("graphrag")
+ from graphrag.index.operations.summarize_communities.community_reports_extractor import (
+ CommunityReportResponse,
+ )
+
+ from deeptutor.services.rag.pipelines.graphrag import completion_adapter
+
+ completion_adapter.clear_capability_cache()
+ completion = _load_completion(tmp_path)
+ calls: list[dict] = []
+
+ async def _acompletion(**kwargs):
+ calls.append(kwargs)
+ if len(calls) == 1:
+ raise litellm.BadRequestError(
+ message="This response_format type is unavailable now",
+ model="deepseek-v4-flash",
+ llm_provider="deepseek",
+ )
+ return _model_response(litellm, _report_payload())
+
+ monkeypatch.setattr(litellm, "acompletion", _acompletion)
+ response = asyncio.run(
+ completion.completion_async(
+ messages="Return one community report.",
+ response_format=CommunityReportResponse,
+ stream=False,
+ )
+ )
+
+ assert len(calls) == 2
+ assert calls[0]["response_format"] is CommunityReportResponse
+ assert calls[1]["response_format"] == {"type": "json_object"}
+ assert "json schema" in str(calls[1]["messages"]).lower()
+ assert isinstance(response.formatted_response, CommunityReportResponse)
+
+
+def test_custom_anthropic_endpoint_uses_prompt_only_structured_output(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ litellm = pytest.importorskip("litellm")
+ pytest.importorskip("graphrag")
+ from graphrag.index.operations.summarize_communities.community_reports_extractor import (
+ CommunityReportResponse,
+ )
+
+ completion = _load_completion(
+ tmp_path,
+ binding="anthropic",
+ model="third-party-model",
+ url="https://compatible-provider.example/v1",
+ )
+ calls: list[dict] = []
+
+ async def _acompletion(**kwargs):
+ calls.append(kwargs)
+ return _model_response(litellm, _report_payload())
+
+ monkeypatch.setattr(litellm, "acompletion", _acompletion)
+ response = asyncio.run(
+ completion.completion_async(
+ messages="Return one community report.",
+ response_format=CommunityReportResponse,
+ stream=False,
+ )
+ )
+
+ assert len(calls) == 1
+ assert "response_format" not in calls[0]
+ assert "json schema" in str(calls[0]["messages"]).lower()
+ assert isinstance(response.formatted_response, CommunityReportResponse)
+
+
+def test_official_anthropic_endpoint_keeps_native_structured_output(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ litellm = pytest.importorskip("litellm")
+ pytest.importorskip("graphrag")
+ from graphrag.index.operations.summarize_communities.community_reports_extractor import (
+ CommunityReportResponse,
+ )
+
+ completion = _load_completion(
+ tmp_path,
+ binding="anthropic",
+ model="claude-compatible-model",
+ url="https://api.anthropic.com",
+ )
+ calls: list[dict] = []
+
+ async def _acompletion(**kwargs):
+ calls.append(kwargs)
+ return _model_response(litellm, _report_payload())
+
+ monkeypatch.setattr(litellm, "acompletion", _acompletion)
+ response = asyncio.run(
+ completion.completion_async(
+ messages="Return one community report.",
+ response_format=CommunityReportResponse,
+ stream=False,
+ )
+ )
+
+ assert len(calls) == 1
+ assert calls[0]["response_format"] is CommunityReportResponse
+ assert "json schema" not in str(calls[0]["messages"]).lower()
+ assert isinstance(response.formatted_response, CommunityReportResponse)
+
+
+def test_unrelated_bad_request_is_not_retried(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ litellm = pytest.importorskip("litellm")
+ pytest.importorskip("graphrag")
+ from graphrag.index.operations.summarize_communities.community_reports_extractor import (
+ CommunityReportResponse,
+ )
+
+ from deeptutor.services.rag.pipelines.graphrag import completion_adapter
+
+ completion_adapter.clear_capability_cache()
+ completion = _load_completion(tmp_path)
+ calls = 0
+
+ async def _acompletion(**_kwargs):
+ nonlocal calls
+ calls += 1
+ raise litellm.BadRequestError(
+ message="Invalid temperature",
+ model="deepseek-v4-flash",
+ llm_provider="deepseek",
+ )
+
+ monkeypatch.setattr(litellm, "acompletion", _acompletion)
+ with pytest.raises(litellm.BadRequestError, match="Invalid temperature"):
+ asyncio.run(
+ completion.completion_async(
+ messages="Return one community report.",
+ response_format=CommunityReportResponse,
+ stream=False,
+ )
+ )
+
+ assert calls == 1
+
+
+def test_sync_completion_caches_explicit_json_object_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ litellm = pytest.importorskip("litellm")
+ from graphrag.index.operations.summarize_communities.community_reports_extractor import (
+ CommunityReportResponse,
+ )
+
+ from deeptutor.services.rag.pipelines.graphrag import completion_adapter
+
+ completion_adapter.clear_capability_cache()
+ completion = _load_completion(tmp_path)
+ calls: list[dict] = []
+
+ def _completion(**kwargs):
+ calls.append(kwargs)
+ if len(calls) == 1:
+ raise litellm.BadRequestError(
+ message="This response_format type is unavailable now",
+ model="deepseek-v4-flash",
+ llm_provider="deepseek",
+ )
+ return _model_response(litellm, _report_payload())
+
+ monkeypatch.setattr(litellm, "completion", _completion)
+ for _ in range(2):
+ response = completion.completion(
+ messages="Return one community report.",
+ response_format=CommunityReportResponse,
+ stream=False,
+ )
+ assert isinstance(response.formatted_response, CommunityReportResponse)
+
+ assert [call["response_format"] for call in calls] == [
+ CommunityReportResponse,
+ {"type": "json_object"},
+ {"type": "json_object"},
+ ]
+
+
+def test_authentication_failure_is_not_retried(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ litellm = pytest.importorskip("litellm")
+ from graphrag.index.operations.summarize_communities.community_reports_extractor import (
+ CommunityReportResponse,
+ )
+
+ from deeptutor.services.rag.pipelines.graphrag import completion_adapter
+
+ completion_adapter.clear_capability_cache()
+ completion = _load_completion(tmp_path)
+ calls = 0
+
+ class AuthenticationError(Exception):
+ pass
+
+ async def _acompletion(**_kwargs):
+ nonlocal calls
+ calls += 1
+ raise AuthenticationError("secret provider detail")
+
+ monkeypatch.setattr(litellm, "acompletion", _acompletion)
+ with pytest.raises(AuthenticationError):
+ asyncio.run(
+ completion.completion_async(
+ messages="Return one community report.",
+ response_format=CommunityReportResponse,
+ )
+ )
+ assert calls == 1
+
+
+def test_invalid_fallback_json_fails_strict_validation(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ litellm = pytest.importorskip("litellm")
+ from graphrag.index.operations.summarize_communities.community_reports_extractor import (
+ CommunityReportResponse,
+ )
+
+ from deeptutor.services.rag.pipelines.graphrag import completion_adapter
+
+ completion_adapter.clear_capability_cache()
+ completion = _load_completion(tmp_path)
+ calls = 0
+
+ async def _acompletion(**_kwargs):
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ raise litellm.BadRequestError(
+ message="This response_format type is unavailable now",
+ model="deepseek-v4-flash",
+ llm_provider="deepseek",
+ )
+ return _model_response(litellm, {"unexpected": "shape"})
+
+ monkeypatch.setattr(litellm, "acompletion", _acompletion)
+ with pytest.raises(GraphRagStructuredOutputError):
+ asyncio.run(
+ completion.completion_async(
+ messages="Return one community report.",
+ response_format=CommunityReportResponse,
+ )
+ )
+ assert calls == 2
+
+
+def test_truncated_fallback_is_unverifiable_instead_of_incompatible(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ litellm = pytest.importorskip("litellm")
+ from graphrag.index.operations.summarize_communities.community_reports_extractor import (
+ CommunityReportResponse,
+ )
+
+ from deeptutor.services.rag.pipelines.graphrag import completion_adapter
+
+ completion_adapter.clear_capability_cache()
+ completion = _load_completion(tmp_path)
+ calls = 0
+
+ async def _acompletion(**_kwargs):
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ raise litellm.BadRequestError(
+ message="This response_format type is unavailable now",
+ model="deepseek-v4-flash",
+ llm_provider="deepseek",
+ )
+ return _model_response(
+ litellm,
+ '{"title":"Compatibility","summary":"truncated',
+ finish_reason="length",
+ )
+
+ monkeypatch.setattr(litellm, "acompletion", _acompletion)
+ with pytest.raises(GraphRagStructuredOutputTruncatedError) as exc_info:
+ asyncio.run(
+ completion.completion_async(
+ messages="Return one community report.",
+ response_format=CommunityReportResponse,
+ )
+ )
+
+ assert exc_info.value.code == "graphrag_model_output_truncated"
+ assert exc_info.value.retryable is True
+ assert calls == 2
+
+
+def test_native_validation_failure_retries_once_without_caching(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ litellm = pytest.importorskip("litellm")
+ from graphrag.index.operations.summarize_communities.community_reports_extractor import (
+ CommunityReportResponse,
+ )
+
+ from deeptutor.services.rag.pipelines.graphrag import completion_adapter
+
+ completion_adapter.clear_capability_cache()
+ completion = _load_completion(tmp_path)
+ calls: list[dict] = []
+
+ async def _acompletion(**kwargs):
+ calls.append(kwargs)
+ if len(calls) == 1:
+ return _model_response(litellm, {"unexpected": "shape"})
+ return _model_response(litellm, _report_payload())
+
+ monkeypatch.setattr(litellm, "acompletion", _acompletion)
+ for _ in range(2):
+ response = asyncio.run(
+ completion.completion_async(
+ messages="Return one community report.",
+ response_format=CommunityReportResponse,
+ )
+ )
+ assert isinstance(response.formatted_response, CommunityReportResponse)
+
+ assert [call["response_format"] for call in calls] == [
+ CommunityReportResponse,
+ {"type": "json_object"},
+ CommunityReportResponse,
+ ]
+
+
+def test_old_settings_are_adapted_in_memory_without_rewrite(tmp_path: Path) -> None:
+ pytest.importorskip("graphrag")
+ import yaml
+
+ gr_config.write_settings(
+ tmp_path,
+ llm_cfg=_Cfg(
+ "deepseek-v4-flash",
+ "https://api.deepseek.com",
+ "sk-test",
+ binding="deepseek",
+ ),
+ embedding_cfg=_Cfg("embedding-model", "https://embedding.test/v1", "sk-test"),
+ )
+ settings_path = tmp_path / gr_config.SETTINGS_FILENAME
+ old_settings = yaml.safe_load(settings_path.read_text(encoding="utf-8"))
+ completion = old_settings["completion_models"][gr_config.COMPLETION_MODEL_ID]
+ completion.pop("type")
+ completion["model_provider"] = "openai"
+ settings_path.write_text(
+ yaml.safe_dump(old_settings, sort_keys=False),
+ encoding="utf-8",
+ )
+ before = settings_path.read_bytes()
+
+ loaded = engine._load_config(tmp_path)
+ loaded_completion = loaded.get_completion_model_config(gr_config.COMPLETION_MODEL_ID)
+
+ assert loaded_completion.type == "deeptutor_litellm"
+ assert loaded_completion.model_provider == "deepseek"
+ assert settings_path.read_bytes() == before
+
+
+def test_provider_resolution_uses_backend_contracts() -> None:
+ from deeptutor.services.rag.pipelines.graphrag.provider import (
+ resolve_completion_provider,
+ )
+
+ assert resolve_completion_provider(_Cfg("claude", "u", "k", binding="anthropic")) == (
+ "anthropic"
+ )
+ assert resolve_completion_provider(_Cfg("model", "u", "k", binding="custom")) == "openai"
+ with pytest.raises(GraphRagUnsupportedProviderError):
+ resolve_completion_provider(_Cfg("gpt", "u", "k", binding="openai_codex"))
+
+
+def test_cached_fallback_is_safe_under_concurrent_sync_calls(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ litellm = pytest.importorskip("litellm")
+ from graphrag.index.operations.summarize_communities.community_reports_extractor import (
+ CommunityReportResponse,
+ )
+
+ from deeptutor.services.rag.pipelines.graphrag import completion_adapter
+
+ completion_adapter.clear_capability_cache()
+ completion = _load_completion(tmp_path)
+ lock = threading.Lock()
+ calls: list[dict] = []
+
+ def _completion(**kwargs):
+ with lock:
+ calls.append(kwargs)
+ call_number = len(calls)
+ if call_number == 1:
+ raise litellm.BadRequestError(
+ message="This response_format type is unavailable now",
+ model="deepseek-v4-flash",
+ llm_provider="deepseek",
+ )
+ return _model_response(litellm, _report_payload())
+
+ monkeypatch.setattr(litellm, "completion", _completion)
+ completion.completion(
+ messages="Warm the capability cache.",
+ response_format=CommunityReportResponse,
+ )
+
+ def _call(_index: int):
+ return completion.completion(
+ messages="Return one community report.",
+ response_format=CommunityReportResponse,
+ )
+
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ responses = list(executor.map(_call, range(8)))
+
+ assert all(isinstance(item.formatted_response, CommunityReportResponse) for item in responses)
+ assert len(calls) == 10
+ assert all(call["response_format"] == {"type": "json_object"} for call in calls[1:])
diff --git a/tests/services/rag/test_graphrag_pipeline.py b/tests/services/rag/test_graphrag_pipeline.py
index 38594f2e3..eaaea1cae 100644
--- a/tests/services/rag/test_graphrag_pipeline.py
+++ b/tests/services/rag/test_graphrag_pipeline.py
@@ -24,6 +24,13 @@ from deeptutor.services.rag.factory import (
from deeptutor.services.rag.index_versioning import resolve_storage_dir_for_read
from deeptutor.services.rag.pipelines.graphrag import config as gr_config
from deeptutor.services.rag.pipelines.graphrag import engine, ingestion, storage
+from deeptutor.services.rag.pipelines.graphrag.errors import (
+ GraphRagEmbeddingDimensionError,
+ GraphRagEmbeddingEndpointError,
+ GraphRagEmbeddingProviderUnsupportedError,
+ GraphRagStructuredOutputTruncatedError,
+ classify_embedding_error,
+)
from deeptutor.services.rag.pipelines.graphrag.pipeline import GraphRagPipeline, _context_to_sources
# --------------------------------------------------------------------------- #
@@ -32,17 +39,17 @@ from deeptutor.services.rag.pipelines.graphrag.pipeline import GraphRagPipeline,
def test_factory_dispatches_graphrag_lazily(tmp_path) -> None:
+ imported_before = sys.modules.get("graphrag")
pipe = get_pipeline("graphrag", kb_base_dir=str(tmp_path))
assert type(pipe).__name__ == "GraphRagPipeline"
# Building the pipeline must NOT import the heavy optional dependency.
- assert "graphrag" not in sys.modules
+ assert sys.modules.get("graphrag") is imported_before
def test_list_pipelines_includes_graphrag() -> None:
entry = next(p for p in list_pipelines() if p["id"] == GRAPHRAG_PROVIDER)
assert entry["requires_api_key"] is False
- # Not installed in the test env.
- assert entry["configured"] is False
+ assert entry["configured"] is gr_config.is_graphrag_available()
def test_normalize_provider_keeps_graphrag() -> None:
@@ -67,12 +74,28 @@ def test_ragservice_routes_graphrag_from_metadata(tmp_path) -> None:
class _Cfg:
- def __init__(self, model, url, key, dim=3072):
+ def __init__(
+ self,
+ model,
+ url,
+ key,
+ dim=3072,
+ binding="openai",
+ *,
+ extra_headers=None,
+ reasoning_effort=None,
+ send_dimensions=None,
+ ):
self.model = model
self.effective_url = url
self.base_url = None
self.api_key = key
self.dim = dim
+ self.binding = binding
+ self.provider_name = binding
+ self.extra_headers = extra_headers or {}
+ self.reasoning_effort = reasoning_effort
+ self.send_dimensions = send_dimensions
def test_build_settings_bridges_models() -> None:
@@ -88,6 +111,7 @@ def test_build_settings_bridges_models() -> None:
chat = settings["completion_models"]["default_completion_model"]
emb = settings["embedding_models"]["default_embedding_model"]
assert chat == {
+ "type": "deeptutor_litellm",
"model_provider": "openai",
"model": "gpt-4o-mini",
"auth_method": "api_key",
@@ -100,6 +124,200 @@ def test_build_settings_bridges_models() -> None:
assert settings["vector_store"]["vector_size"] == 4096
+ ("binding", "model", "reasoning_effort", "expected"),
+ [
+ (
+ "deepseek",
+ "deepseek-v4-pro",
+ None,
+ {
+ "reasoning_effort": "high",
+ "extra_body": {"thinking": {"type": "enabled"}},
+ },
+ ),
+ (
+ "deepseek",
+ "deepseek-v4-flash",
+ None,
+ {"extra_body": {"thinking": {"type": "disabled"}}},
+ ),
+ (
+ "dashscope",
+ "qwen3-235b-a22b",
+ None,
+ {"extra_body": {"enable_thinking": True}},
+ ),
+ (
+ "custom",
+ "deepseek-v4-pro",
+ "minimal",
+ {"extra_body": {"thinking": {"type": "disabled"}}},
+ ),
+ ],
+)
+def test_build_settings_reuses_deeptutor_reasoning_request_options(
+ binding: str,
+ model: str,
+ reasoning_effort: str | None,
+ expected: dict,
+) -> None:
+ settings = gr_config.build_settings(
+ llm_cfg=_Cfg(
+ model,
+ "https://chat.test/v1",
+ "sk-llm",
+ binding=binding,
+ reasoning_effort=reasoning_effort,
+ extra_headers={"X-Route": "blue"},
+ ),
+ embedding_cfg=_Cfg("embedding-model", "https://emb.test/v1", "sk-emb"),
+ )
+
+ call_args = settings["completion_models"][gr_config.COMPLETION_MODEL_ID]["call_args"]
+ assert call_args == {"extra_headers": {"X-Route": "blue"}, **expected}
+
+
+ ("binding", "model", "send_dimensions", "expected_dimensions"),
+ [
+ ("openai", "text-embedding-3-large", None, 1536),
+ ("siliconflow", "Qwen/Qwen3-Embedding-8B", None, 4096),
+ ("custom", "vendor/opaque-embedding", True, 768),
+ ("openai", "text-embedding-3-large", False, None),
+ ("custom", "vendor/opaque-embedding", None, None),
+ ],
+)
+def test_build_settings_preserves_embedding_request_options(
+ binding: str,
+ model: str,
+ send_dimensions: bool | None,
+ expected_dimensions: int | None,
+) -> None:
+ dimension = expected_dimensions or (1536 if "text-embedding-3" in model else 768)
+ settings = gr_config.build_settings(
+ llm_cfg=_Cfg("gpt-4o-mini", "https://chat.test/v1", "sk-llm"),
+ embedding_cfg=_Cfg(
+ model,
+ "https://emb.test/v1/embeddings",
+ "sk-emb",
+ dim=dimension,
+ binding=binding,
+ send_dimensions=send_dimensions,
+ extra_headers={"X-Route": "blue"},
+ ),
+ )
+
+ entry = settings["embedding_models"][gr_config.EMBEDDING_MODEL_ID]
+ call_args = entry["call_args"]
+ assert call_args["extra_headers"] == {"X-Route": "blue"}
+ assert call_args.get("dimensions") == expected_dimensions
+
+
+ ("binding", "endpoint", "expected"),
+ [
+ ("openai", "https://api.openai.com/v1/embeddings", "https://api.openai.com/v1"),
+ (
+ "siliconflow",
+ "https://api.siliconflow.cn/v1/embeddings/",
+ "https://api.siliconflow.cn/v1",
+ ),
+ (
+ "gemini",
+ "https://generativelanguage.googleapis.com/v1beta/openai/embeddings",
+ "https://generativelanguage.googleapis.com/v1beta/openai",
+ ),
+ ("openrouter", "https://openrouter.ai/api/v1/embeddings", "https://openrouter.ai/api/v1"),
+ ("orcarouter", "https://api.orcarouter.ai/v1/embeddings", "https://api.orcarouter.ai/v1"),
+ ("vllm", "http://localhost:8000/v1/embeddings", "http://localhost:8000/v1"),
+ ("jina", "https://api.jina.ai/v1/embeddings", "https://api.jina.ai/v1"),
+ ("custom", "https://gateway.test/v1/embeddings", "https://gateway.test/v1"),
+ ("openai", "https://api.openai.com/v1", "https://api.openai.com/v1"),
+ ("custom", "https://gateway.test/embed", "https://gateway.test/embed"),
+ (
+ "custom",
+ "https://gateway.test/v1/embeddings?api-key=secret",
+ "https://gateway.test/v1/embeddings?api-key=secret",
+ ),
+ ],
+)
+def test_graphrag_embedding_api_base_only_normalizes_openai_compatible_operation_urls(
+ binding: str, endpoint: str, expected: str
+) -> None:
+ assert gr_config.graphrag_embedding_api_base(binding, endpoint) == expected
+
+
+ ("binding", "endpoint"),
+ [
+ ("cohere", "https://api.cohere.com/v2/embed"),
+ ("ollama", "http://localhost:11434/api/embed"),
+ (
+ "aliyun",
+ "https://dashscope.aliyuncs.com/api/v1/services/embeddings/"
+ "text-embedding/text-embedding",
+ ),
+ (
+ "azure_openai",
+ "https://example.openai.azure.com/openai/deployments/embed/embeddings"
+ "?api-version=2024-02-01",
+ ),
+ (
+ "gemini",
+ "https://generativelanguage.googleapis.com/v1beta/models/"
+ "gemini-embedding-2:batchEmbedContents",
+ ),
+ ],
+)
+def test_graphrag_settings_reject_native_embedding_transports_without_mutating_them(
+ binding: str, endpoint: str
+) -> None:
+ embedding_cfg = _Cfg("embedding-model", endpoint, "sk-emb", binding=binding)
+
+ with pytest.raises(GraphRagEmbeddingProviderUnsupportedError):
+ gr_config.build_settings(
+ llm_cfg=_Cfg("gpt-4o-mini", "https://api.example.com/v1", "sk-llm"),
+ embedding_cfg=embedding_cfg,
+ )
+
+ assert embedding_cfg.effective_url == endpoint
+
+
+def test_graphrag_settings_accept_gemini_openai_compatible_endpoint() -> None:
+ settings = gr_config.build_settings(
+ llm_cfg=_Cfg("gpt-4o-mini", "https://api.example.com/v1", "sk-llm"),
+ embedding_cfg=_Cfg(
+ "gemini-embedding-001",
+ "https://generativelanguage.googleapis.com/v1beta/openai/embeddings",
+ "sk-emb",
+ binding="gemini",
+ ),
+ )
+
+ embedding = settings["embedding_models"][gr_config.EMBEDDING_MODEL_ID]
+ assert embedding["api_base"] == ("https://generativelanguage.googleapis.com/v1beta/openai")
+
+
+def test_build_settings_normalizes_embedding_endpoint_only_in_graphrag_payload() -> None:
+ embedding_cfg = _Cfg(
+ "Qwen/Qwen3-Embedding-8B",
+ "https://api.siliconflow.cn/v1/embeddings",
+ "sk-emb",
+ dim=4096,
+ binding="siliconflow",
+ )
+
+ settings = gr_config.build_settings(
+ llm_cfg=_Cfg("gpt-4o-mini", "https://api.example.com/v1", "sk-llm"),
+ embedding_cfg=embedding_cfg,
+ )
+
+ emb = settings["embedding_models"]["default_embedding_model"]
+ assert emb["api_base"] == "https://api.siliconflow.cn/v1"
+ assert embedding_cfg.effective_url == "https://api.siliconflow.cn/v1/embeddings"
+
+
def test_build_settings_requires_models() -> None:
with pytest.raises(gr_config.GraphRagNotConfiguredError):
gr_config.build_settings(
@@ -116,6 +334,25 @@ def test_build_settings_requires_embedding_dimension() -> None:
)
+def test_build_settings_does_not_guess_compatibility_from_model_name(monkeypatch) -> None:
+ monkeypatch.setattr(
+ "deeptutor.services.llm.capabilities.supports_response_format",
+ lambda _binding, _model: False,
+ )
+
+ settings = gr_config.build_settings(
+ llm_cfg=_Cfg(
+ "deepseek-v4-flash",
+ "https://gateway.example.com/v1",
+ "sk-test",
+ binding="openrouter",
+ ),
+ embedding_cfg=_Cfg("embedding-model", "https://emb.test/v1", "sk-test"),
+ )
+
+ assert settings["completion_models"]["default_completion_model"]["model"] == "deepseek-v4-flash"
+
+
def test_local_api_key_placeholder_when_missing() -> None:
settings = gr_config.build_settings(
llm_cfg=_Cfg("m", "u", ""),
@@ -149,6 +386,361 @@ def test_engine_entry_points_run_on_a_private_loop() -> None:
assert seen["current"] is seen["running"]
+def test_compatibility_probe_resolves_candidate_without_mutating_active_model(
+ monkeypatch, tmp_path: Path
+) -> None:
+ from deeptutor.services.config.model_catalog import ModelCatalogService
+ from deeptutor.services.rag.pipelines.graphrag import compatibility
+
+ catalog = {
+ "version": 1,
+ "services": {
+ "llm": {
+ "active_profile_id": "profile-a",
+ "active_model_id": "model-a",
+ "profiles": [
+ {
+ "id": "profile-a",
+ "name": "OpenAI",
+ "binding": "openai",
+ "base_url": "https://api.openai.com/v1",
+ "api_key": "sk-test",
+ "api_version": "",
+ "extra_headers": {},
+ "models": [
+ {"id": "model-a", "name": "A", "model": "gpt-4o-mini"},
+ {"id": "model-b", "name": "B", "model": "gpt-4.1-mini"},
+ ],
+ }
+ ],
+ }
+ },
+ }
+ service = ModelCatalogService(tmp_path / "model_catalog.json")
+ service.save(catalog)
+ monkeypatch.setattr(compatibility, "get_model_catalog_service", lambda: service)
+
+ captured: dict[str, object] = {}
+
+ async def _probe(llm_cfg) -> dict:
+ captured["model"] = llm_cfg.model
+ captured["api_key"] = llm_cfg.api_key
+ return {
+ "status": "compatible",
+ "compatible": True,
+ "code": "graphrag_model_compatible",
+ "message": "The model returned valid GraphRAG structured output.",
+ "model": llm_cfg.model,
+ "binding": llm_cfg.binding,
+ "retryable": False,
+ }
+
+ monkeypatch.setattr(engine, "probe_completion_model", _probe, raising=False)
+
+ result = asyncio.run(compatibility.probe_configured_completion_model("profile-a", "model-b"))
+
+ assert result["compatible"] is True
+ assert captured == {"model": "gpt-4.1-mini", "api_key": "sk-test"}
+ persisted = service.load()
+ assert persisted["services"]["llm"]["active_model_id"] == "model-a"
+
+
+def test_completion_probe_requires_graphrag_structured_response(monkeypatch) -> None:
+ captured: dict[str, object] = {}
+
+ class _CommunityReportResponse:
+ pass
+
+ class _Response:
+ formatted_response = _CommunityReportResponse()
+
+ class _Completion:
+ async def completion_async(self, **kwargs):
+ captured.update(kwargs)
+ return _Response()
+
+ monkeypatch.setattr(
+ engine,
+ "_create_probe_completion",
+ lambda _cfg: (_Completion(), _CommunityReportResponse),
+ raising=False,
+ )
+
+ asyncio.run(
+ engine._probe_completion_model_impl(
+ _Cfg("gpt-4o-mini", "https://api.example.com/v1", "sk-test")
+ )
+ )
+
+ assert captured["response_format"] is _CommunityReportResponse
+ assert captured["stream"] is False
+ assert captured["max_tokens"] == 1024
+ assert captured["timeout"] == 25
+ assert "community report" in str(captured["messages"]).lower()
+
+
+def test_completion_probe_reports_compatible_after_isolated_validation(monkeypatch) -> None:
+ captured: dict[str, object] = {}
+
+ async def _impl(llm_cfg) -> None:
+ captured["model"] = llm_cfg.model
+
+ async def _isolated(work) -> None:
+ captured["isolated"] = True
+ await work()
+
+ monkeypatch.setattr(engine, "_probe_completion_model_impl", _impl)
+ monkeypatch.setattr(engine, "_run_isolated", _isolated)
+
+ result = asyncio.run(
+ engine.probe_completion_model(
+ _Cfg(
+ "gpt-4o-mini",
+ "https://api.openai.com/v1",
+ "sk-test",
+ binding="openai",
+ )
+ )
+ )
+
+ assert captured == {"isolated": True, "model": "gpt-4o-mini"}
+ assert result == {
+ "status": "compatible",
+ "compatible": True,
+ "code": "graphrag_model_compatible",
+ "message": "The model returned valid GraphRAG structured output.",
+ "model": "gpt-4o-mini",
+ "binding": "openai",
+ "retryable": False,
+ }
+
+
+def test_completion_probe_reports_unsupported_schema_as_incompatible(monkeypatch) -> None:
+ class UnsupportedParamsError(Exception):
+ pass
+
+ async def _isolated(_work) -> None:
+ raise UnsupportedParamsError("response_format rejected; sk-secret-must-not-leak")
+
+ monkeypatch.setattr(engine, "_run_isolated", _isolated)
+
+ result = asyncio.run(
+ engine.probe_completion_model(
+ _Cfg(
+ "candidate-model",
+ "https://api.example.com/v1",
+ "sk-secret-must-not-leak",
+ binding="custom",
+ )
+ )
+ )
+
+ assert result["status"] == "incompatible"
+ assert result["compatible"] is False
+ assert result["code"] == "graphrag_model_incompatible"
+ assert result["retryable"] is False
+ assert "sk-secret-must-not-leak" not in result["message"]
+
+
+def test_completion_probe_reports_auth_failure_as_unverifiable(monkeypatch) -> None:
+ class AuthenticationError(Exception):
+ pass
+
+ async def _isolated(_work) -> None:
+ raise AuthenticationError("invalid sk-secret-must-not-leak")
+
+ monkeypatch.setattr(engine, "_run_isolated", _isolated)
+
+ result = asyncio.run(
+ engine.probe_completion_model(
+ _Cfg("candidate-model", "https://api.example.com/v1", "sk-test")
+ )
+ )
+
+ assert result["status"] == "unverifiable"
+ assert result["compatible"] is None
+ assert result["code"] == "graphrag_model_authentication_failed"
+ assert result["retryable"] is False
+ assert "credentials" in result["message"].lower()
+ assert "sk-secret-must-not-leak" not in result["message"]
+
+
+def test_completion_probe_reports_truncated_output_as_unverifiable(monkeypatch) -> None:
+ async def _isolated(_work) -> None:
+ raise GraphRagStructuredOutputTruncatedError("secret response content")
+
+ monkeypatch.setattr(engine, "_run_isolated", _isolated)
+
+ result = asyncio.run(
+ engine.probe_completion_model(
+ _Cfg("candidate-model", "https://api.example.com/v1", "sk-test")
+ )
+ )
+
+ assert result["status"] == "unverifiable"
+ assert result["compatible"] is None
+ assert result["code"] == "graphrag_model_output_truncated"
+ assert result["retryable"] is True
+ assert "secret response content" not in result["message"]
+
+
+ ("error_name", "code"),
+ [
+ ("RateLimitError", "graphrag_model_rate_limited"),
+ ("APIConnectionError", "graphrag_model_connection_failed"),
+ ("Timeout", "graphrag_model_connection_failed"),
+ ("ServiceUnavailableError", "graphrag_model_connection_failed"),
+ ],
+)
+def test_completion_probe_marks_transient_failures_retryable(
+ monkeypatch, error_name: str, code: str
+) -> None:
+ error_type = type(error_name, (Exception,), {})
+
+ async def _isolated(_work) -> None:
+ raise error_type("temporary provider failure")
+
+ monkeypatch.setattr(engine, "_run_isolated", _isolated)
+
+ result = asyncio.run(
+ engine.probe_completion_model(
+ _Cfg("candidate-model", "https://api.example.com/v1", "sk-test")
+ )
+ )
+
+ assert result["status"] == "unverifiable"
+ assert result["compatible"] is None
+ assert result["code"] == code
+ assert result["retryable"] is True
+
+
+def test_embedding_preflight_uses_graphrag_client_and_checks_dimension(monkeypatch) -> None:
+ captured: dict[str, object] = {}
+
+ class _Response:
+ first_embedding = [0.1, 0.2, 0.3]
+
+ class _Embedding:
+ async def embedding_async(self, **kwargs):
+ captured.update(kwargs)
+ return _Response()
+
+ monkeypatch.setattr(
+ engine,
+ "_create_probe_embedding",
+ lambda _config: (_Embedding(), 3),
+ raising=False,
+ )
+
+ asyncio.run(engine._probe_embedding_model_impl(object()))
+
+ assert captured == {
+ "input": ["DeepTutor GraphRAG embedding compatibility test"],
+ "timeout": 25,
+ }
+
+
+def test_completion_preflight_uses_persisted_settings_client(monkeypatch, tmp_path) -> None:
+ captured: dict[str, object] = {}
+
+ class _CommunityReportResponse:
+ pass
+
+ class _Response:
+ formatted_response = _CommunityReportResponse()
+
+ class _Completion:
+ async def completion_async(self, **kwargs):
+ captured.update(kwargs)
+ return _Response()
+
+ monkeypatch.setattr(engine, "_load_config", lambda _root: object())
+ monkeypatch.setattr(
+ engine,
+ "_create_configured_probe_completion",
+ lambda _config: (_Completion(), _CommunityReportResponse),
+ )
+
+ asyncio.run(engine._preflight_completion_impl(tmp_path))
+
+ assert captured["response_format"] is _CommunityReportResponse
+ assert captured["stream"] is False
+
+
+def test_embedding_preflight_reports_dimension_mismatch_without_indexing(monkeypatch) -> None:
+ class _Response:
+ first_embedding = [0.1, 0.2]
+
+ class _Embedding:
+ async def embedding_async(self, **_kwargs):
+ return _Response()
+
+ monkeypatch.setattr(
+ engine,
+ "_create_probe_embedding",
+ lambda _config: (_Embedding(), 3),
+ raising=False,
+ )
+
+ with pytest.raises(GraphRagEmbeddingDimensionError) as exc_info:
+ asyncio.run(engine._probe_embedding_model_impl(object()))
+
+ assert exc_info.value.code == "graphrag_embedding_dimension_mismatch"
+ assert "returned 2 dimensions" in str(exc_info.value)
+ assert "configured for 3" in str(exc_info.value)
+
+
+def test_embedding_preflight_classifies_endpoint_error_without_leaking_provider_detail(
+ monkeypatch,
+) -> None:
+ class NotFoundError(Exception):
+ status_code = 404
+
+ class _Embedding:
+ async def embedding_async(self, **_kwargs):
+ raise NotFoundError("bad endpoint sk-secret-must-not-leak")
+
+ monkeypatch.setattr(
+ engine,
+ "_create_probe_embedding",
+ lambda _config: (_Embedding(), 3),
+ raising=False,
+ )
+
+ with pytest.raises(GraphRagEmbeddingEndpointError) as exc_info:
+ asyncio.run(engine._probe_embedding_model_impl(object()))
+
+ assert exc_info.value.code == "graphrag_embedding_endpoint_failed"
+ assert "embedding model or endpoint was not found" in str(exc_info.value)
+ assert "sk-secret-must-not-leak" not in str(exc_info.value)
+
+
+ ("error_name", "status_code", "expected_code", "retryable"),
+ [
+ ("AuthenticationError", 401, "graphrag_embedding_authentication_failed", False),
+ ("RateLimitError", 429, "graphrag_embedding_rate_limited", True),
+ ("APIConnectionError", None, "graphrag_embedding_connection_failed", True),
+ ("BadRequestError", 400, "graphrag_embedding_incompatible", False),
+ ],
+)
+def test_embedding_error_classification_is_typed_and_secret_free(
+ error_name: str,
+ status_code: int | None,
+ expected_code: str,
+ retryable: bool,
+) -> None:
+ error_type = type(error_name, (Exception,), {"status_code": status_code})
+
+ classified = classify_embedding_error(error_type("sk-secret-must-not-leak"))
+
+ assert classified is not None
+ assert classified.code == expected_code
+ assert classified.retryable is retryable
+ assert "sk-secret-must-not-leak" not in str(classified)
+
+
def test_write_settings_roundtrips(tmp_path) -> None:
import yaml
@@ -191,6 +783,31 @@ def test_write_settings_loads_and_builds_cache_via_real_graphrag(tmp_path) -> No
assert type(cache).__name__ == "JsonCache"
+def test_real_graphrag_model_config_preserves_embedding_request_options(tmp_path) -> None:
+ pytest.importorskip("graphrag")
+
+ gr_config.write_settings(
+ tmp_path,
+ llm_cfg=_Cfg("gpt-4o-mini", "https://chat.test/v1", "sk-llm"),
+ embedding_cfg=_Cfg(
+ "Qwen/Qwen3-Embedding-8B",
+ "https://emb.test/v1/embeddings",
+ "sk-emb",
+ dim=4096,
+ binding="siliconflow",
+ extra_headers={"X-Route": "blue"},
+ ),
+ )
+
+ loaded = engine._load_config(tmp_path)
+ model_config = loaded.embedding_models[gr_config.EMBEDDING_MODEL_ID]
+ assert model_config.api_base == "https://emb.test/v1"
+ assert model_config.call_args == {
+ "extra_headers": {"X-Route": "blue"},
+ "dimensions": 4096,
+ }
+
+
@pytest.mark.parametrize(
"given,expected",
[
@@ -207,7 +824,8 @@ def test_normalize_mode(given, expected) -> None:
assert gr_config.normalize_mode(given) == expected
-def test_is_graphrag_available_false_in_ci() -> None:
+def test_is_graphrag_available_reflects_dependency_lookup(monkeypatch) -> None:
+ monkeypatch.setattr("importlib.util.find_spec", lambda _name: None)
assert gr_config.is_graphrag_available() is False
@@ -306,14 +924,31 @@ def _force_available(monkeypatch, available: bool = True) -> None:
def _stub_build(monkeypatch) -> list[dict]:
calls: list[dict] = []
- async def fake_build(root_dir, *, is_update=False):
- calls.append({"root": str(root_dir), "is_update": is_update})
+ async def fake_build(
+ root_dir,
+ *,
+ is_update=False,
+ preflight_embedding_model=True,
+ ):
+ calls.append(
+ {
+ "root": str(root_dir),
+ "is_update": is_update,
+ "preflight_embedding_model": preflight_embedding_model,
+ }
+ )
out = storage.output_dir(Path(root_dir))
out.mkdir(parents=True, exist_ok=True)
(out / "entities.parquet").write_bytes(b"")
monkeypatch.setattr(engine, "build", fake_build)
+ async def fake_preflight(_root_dir):
+ return None
+
+ monkeypatch.setattr(engine, "preflight_completion", fake_preflight, raising=False)
+ monkeypatch.setattr(engine, "preflight_embedding", fake_preflight, raising=False)
+
# initialize() -> write_settings() resolves the active chat + embedding
# models from the catalog; CI has none configured, so pin fakes here so the
# settings.yaml write succeeds. The build_settings <-> catalog bridge itself
@@ -329,6 +964,25 @@ def _stub_build(monkeypatch) -> list[dict]:
return calls
+def test_incremental_preflight_checks_both_models_before_mutation(monkeypatch) -> None:
+ calls: list[str] = []
+
+ async def preflight_embedding(root_dir: Path) -> None:
+ assert (root_dir / gr_config.SETTINGS_FILENAME).exists()
+ calls.append("embedding")
+
+ async def preflight_completion(root_dir: Path) -> None:
+ assert (root_dir / gr_config.SETTINGS_FILENAME).exists()
+ calls.append("completion")
+
+ monkeypatch.setattr(engine, "preflight_embedding", preflight_embedding)
+ monkeypatch.setattr(engine, "preflight_completion", preflight_completion)
+
+ asyncio.run(GraphRagPipeline()._preflight_settings({"models": {}}))
+
+ assert calls == ["embedding", "completion"]
+
+
def test_initialize_requires_graphrag(tmp_path, monkeypatch) -> None:
_force_available(monkeypatch, False)
txt = tmp_path / "a.txt"
@@ -348,7 +1002,13 @@ def test_initialize_orchestrates_index(tmp_path, monkeypatch) -> None:
ok = asyncio.run(pipe.initialize("kb", [str(txt)]))
assert ok is True
- assert calls == [{"root": calls[0]["root"], "is_update": False}]
+ assert calls == [
+ {
+ "root": calls[0]["root"],
+ "is_update": False,
+ "preflight_embedding_model": True,
+ }
+ ]
root = Path(calls[0]["root"])
assert (root / gr_config.SETTINGS_FILENAME).exists()
assert list(storage.input_dir(root).glob("*.txt"))
@@ -383,6 +1043,44 @@ def test_add_documents_runs_update_when_indexed(tmp_path, monkeypatch) -> None:
assert ok is True
assert calls[-1]["is_update"] is True
+ assert calls[-1]["preflight_embedding_model"] is False
+
+
+def test_add_documents_preflight_failure_does_not_mutate_existing_index(
+ tmp_path, monkeypatch
+) -> None:
+ _force_available(monkeypatch, True)
+ _stub_build(monkeypatch)
+ pipe = GraphRagPipeline(kb_base_dir=str(tmp_path))
+
+ first = tmp_path / "a.txt"
+ first.write_text("existing graph content", encoding="utf-8")
+ asyncio.run(pipe.initialize("kb", [str(first)]))
+
+ kb_dir = tmp_path / "kb"
+ root = resolve_storage_dir_for_read(kb_dir, None)
+ assert root is not None
+ settings_before = (root / gr_config.SETTINGS_FILENAME).read_bytes()
+ input_before = {
+ path.name: path.read_bytes() for path in sorted(storage.input_dir(root).glob("*.txt"))
+ }
+
+ async def fail_preflight(_settings) -> None:
+ raise GraphRagEmbeddingEndpointError(
+ "The configured GraphRAG embedding model or endpoint was not found."
+ )
+
+ monkeypatch.setattr(pipe, "_preflight_settings", fail_preflight, raising=False)
+ second = tmp_path / "b.txt"
+ second.write_text("new graph content", encoding="utf-8")
+
+ with pytest.raises(GraphRagEmbeddingEndpointError):
+ asyncio.run(pipe.add_documents("kb", [str(second)]))
+
+ assert (root / gr_config.SETTINGS_FILENAME).read_bytes() == settings_before
+ assert {
+ path.name: path.read_bytes() for path in sorted(storage.input_dir(root).glob("*.txt"))
+ } == input_before
def test_search_needs_reindex_without_output(tmp_path) -> None:
@@ -483,6 +1181,12 @@ def test_context_to_sources_prefers_concrete_records() -> None:
# --------------------------------------------------------------------------- #
+def test_router_provider_preflight_does_not_require_a_model_probe() -> None:
+ from deeptutor.api.routers import knowledge
+
+ assert knowledge._assert_provider_ready("llamaindex") is None
+
+
def test_router_blocks_graphrag_when_unavailable(monkeypatch) -> None:
from fastapi import HTTPException
@@ -492,3 +1196,27 @@ def test_router_blocks_graphrag_when_unavailable(monkeypatch) -> None:
with pytest.raises(HTTPException) as exc:
knowledge._assert_provider_ready(GRAPHRAG_PROVIDER)
assert exc.value.status_code == 400
+
+
+def test_router_graphrag_readiness_does_not_make_a_paid_model_call(monkeypatch) -> None:
+ from deeptutor.api.routers import knowledge
+ from deeptutor.services.rag import preflight
+ from deeptutor.services.rag.pipelines.graphrag import compatibility
+
+ monkeypatch.setattr(gr_config, "is_graphrag_available", lambda: True)
+ monkeypatch.setattr(
+ preflight,
+ "engine_preflight",
+ lambda _provider: {"ok": True, "checks": []},
+ )
+
+ async def _unexpected_probe() -> dict:
+ raise AssertionError("readiness checks must not call the model provider")
+
+ monkeypatch.setattr(
+ compatibility,
+ "probe_active_completion_model",
+ _unexpected_probe,
+ )
+
+ assert knowledge._assert_provider_ready(GRAPHRAG_PROVIDER) is None
diff --git a/web/components/knowledge/EngineDetail.tsx b/web/components/knowledge/EngineDetail.tsx
index 05d8a3620..f2bc657c4 100644
--- a/web/components/knowledge/EngineDetail.tsx
+++ b/web/components/knowledge/EngineDetail.tsx
@@ -33,11 +33,13 @@ import {
getLlamaIndexConfig,
getPageIndexConfig,
setEngineActiveModel,
+ testGraphRagModelCompatibility,
updateGraphRagConfig,
updateLightRagConfig,
updateLlamaIndexConfig,
updatePageIndexConfig,
type EnginePreflight,
+ type GraphRagModelCompatibility,
type GraphRagConfig,
type LightRagConfig,
type LlamaIndexConfig,
@@ -45,6 +47,7 @@ import {
type PageIndexConfig,
type RagProviderSummary,
} from "@/lib/knowledge-api";
+import { canApplyGraphRagModelCandidate } from "@/lib/graphrag-model-compatibility";
import {
kbDocCount,
kbProvider,
@@ -934,10 +937,22 @@ function ModelsSection({
const [data, setData] = useState<ModelOptionsByKind | null>(null);
const [failed, setFailed] = useState(false);
const [busyKind, setBusyKind] = useState<string | null>(null);
+ const [testingKind, setTestingKind] = useState<string | null>(null);
+ const [draftSelections, setDraftSelections] = useState<
+ Record<string, string>
+ >({});
+ const [compatibility, setCompatibility] = useState<{
+ testedKey: string;
+ result: GraphRagModelCompatibility;
+ } | null>(null);
useEffect(() => {
if (kinds.length === 0) return;
let cancelled = false;
+ setData(null);
+ setFailed(false);
+ setDraftSelections({});
+ setCompatibility(null);
getEngineModelOptions(kinds)
.then((d) => !cancelled && setData(d))
.catch(() => !cancelled && setFailed(true));
@@ -961,6 +976,22 @@ function ModelsSection({
[onError],
);
+ const testCandidate = useCallback(
+ async (kind: string, candidateKey: string) => {
+ const [profileId, modelId] = candidateKey.split("::");
+ setTestingKind(kind);
+ try {
+ const result = await testGraphRagModelCompatibility(profileId, modelId);
+ setCompatibility({ testedKey: candidateKey, result });
+ } catch (err) {
+ onError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setTestingKind(null);
+ }
+ },
+ [onError],
+ );
+
if (kinds.length === 0) return null;
return (
@@ -986,8 +1017,20 @@ function ModelsSection({
<div className="space-y-4 rounded-2xl border border-[var(--border)] p-4">
{kinds.map((kind) => {
const entry = data[kind];
- const value = `${entry?.active.profile_id ?? ""}::${entry?.active.model_id ?? ""}`;
+ const activeKey = `${entry?.active.profile_id ?? ""}::${entry?.active.model_id ?? ""}`;
+ const value = draftSelections[kind] ?? activeKey;
const hasOptions = (entry?.options.length ?? 0) > 0;
+ const isGraphRagChat = providerId === "graphrag" && kind === "llm";
+ const visibleCompatibility =
+ isGraphRagChat && compatibility?.testedKey === value
+ ? compatibility.result
+ : null;
+ const canApply = canApplyGraphRagModelCandidate({
+ activeKey,
+ candidateKey: value,
+ testedKey: compatibility?.testedKey ?? null,
+ result: compatibility?.result ?? null,
+ });
return (
<div key={kind} className="flex flex-col gap-1">
<div className="flex items-center gap-2">
@@ -1001,9 +1044,18 @@ function ModelsSection({
{hasOptions ? (
<select
value={value}
- disabled={busyKind === kind}
+ disabled={busyKind === kind || testingKind === kind}
onChange={(e) => {
- const [pid, mid] = e.target.value.split("::");
+ const candidateKey = e.target.value;
+ if (isGraphRagChat) {
+ setDraftSelections((prev) => ({
+ ...prev,
+ [kind]: candidateKey,
+ }));
+ setCompatibility(null);
+ return;
+ }
+ const [pid, mid] = candidateKey.split("::");
void select(kind, pid, mid);
}}
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"
@@ -1027,6 +1079,85 @@ function ModelsSection({
<ExternalLink className="h-3 w-3" />
</Link>
)}
+ {hasOptions && isGraphRagChat && (
+ <div className="mt-1.5 space-y-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ onClick={() => void testCandidate(kind, value)}
+ disabled={testingKind === kind || busyKind === kind}
+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--ring)] disabled:opacity-50"
+ >
+ {testingKind === kind ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <ShieldCheck className="h-3.5 w-3.5" />
+ )}
+ {t(
+ testingKind === kind
+ ? "Testing compatibility…"
+ : "Test compatibility",
+ )}
+ </button>
+ {canApply && (
+ <button
+ type="button"
+ onClick={() => {
+ const [pid, mid] = value.split("::");
+ void select(kind, pid, mid);
+ }}
+ disabled={busyKind === kind}
+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-90 disabled:opacity-50"
+ >
+ {busyKind === kind ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Check className="h-3.5 w-3.5" />
+ )}
+ {t("Use this model")}
+ </button>
+ )}
+ </div>
+ <p className="text-[11px] leading-relaxed text-[var(--muted-foreground)]">
+ {t(
+ "Runs one small structured-output request and may incur provider charges. The global active chat model changes only after you choose Use this model.",
+ )}
+ </p>
+ {visibleCompatibility && (
+ <div
+ className={`flex items-start gap-2 rounded-lg border px-3 py-2 text-[11.5px] leading-relaxed ${
+ visibleCompatibility.status === "compatible"
+ ? "border-emerald-500/25 bg-emerald-500/5 text-emerald-700 dark:text-emerald-300"
+ : visibleCompatibility.status === "incompatible"
+ ? "border-red-500/25 bg-red-500/5 text-red-700 dark:text-red-300"
+ : "border-amber-500/25 bg-amber-500/5 text-amber-700 dark:text-amber-300"
+ }`}
+ >
+ {visibleCompatibility.status === "compatible" ? (
+ <CheckCircle2 className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ ) : visibleCompatibility.status === "incompatible" ? (
+ <XCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ ) : (
+ <CircleSlash className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ )}
+ <div>
+ <p className="font-medium">
+ {t(
+ visibleCompatibility.status === "compatible"
+ ? "Compatible with GraphRAG"
+ : visibleCompatibility.status === "incompatible"
+ ? "Incompatible with GraphRAG"
+ : "Compatibility could not be verified",
+ )}
+ </p>
+ <p className="mt-0.5 opacity-90">
+ {t(visibleCompatibility.message)}
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
{kind === "llm" && providerId === "lightrag" && (
<span className="text-[11px] text-[var(--muted-foreground)]">
{t(
diff --git a/web/components/knowledge/KbDocumentsSection.tsx b/web/components/knowledge/KbDocumentsSection.tsx
index 1fcdda774..5c469521a 100644
--- a/web/components/knowledge/KbDocumentsSection.tsx
+++ b/web/components/knowledge/KbDocumentsSection.tsx
@@ -16,6 +16,7 @@ import type { TaskState } from "@/hooks/useKnowledgeProgress";
import type { HistoryEntry } from "@/hooks/useKnowledgeHistory";
import ProcessLogs from "@/components/common/ProcessLogs";
import FileDropZone from "./FileDropZone";
+import KbIndexFailureBanner from "./KbIndexFailureBanner";
import KbUpdateHistory from "./KbUpdateHistory";
interface KbDocumentsSectionProps {
@@ -143,30 +144,28 @@ export default function KbDocumentsSection({
)}
{isError && !blockedReason && (
- <div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-[12px] text-amber-700 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-300">
- <span>
- {t(
- "The last indexing run failed. Remove the file(s) that failed in the Files tab, upload replacements below, or retry to rebuild from the current documents.",
- )}
- </span>
- {onRetry && (
- <button
- type="button"
- onClick={handleRetry}
- disabled={!canRetry || retrySubmitting}
- className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-amber-300 bg-amber-100 px-2 py-1 text-[11.5px] font-medium text-amber-800 transition-colors hover:bg-amber-200 disabled:opacity-50 dark:border-amber-800 dark:bg-amber-950/50 dark:text-amber-200"
- >
- {retrySubmitting || isRetryingHere ? (
- <Loader2 className="h-3 w-3 animate-spin" />
- ) : (
- <RefreshCw className="h-3 w-3" />
- )}
- {retrySubmitting || isRetryingHere
- ? t("Retrying…")
- : t("Retry indexing")}
- </button>
- )}
- </div>
+ <KbIndexFailureBanner
+ kb={kb}
+ action={
+ onRetry ? (
+ <button
+ type="button"
+ onClick={handleRetry}
+ disabled={!canRetry || retrySubmitting}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-red-300 bg-red-100 px-2 py-1 text-[11.5px] font-medium text-red-800 transition-colors hover:bg-red-200 disabled:opacity-50 dark:border-red-800 dark:bg-red-950/50 dark:text-red-200"
+ >
+ {retrySubmitting || isRetryingHere ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <RefreshCw className="h-3 w-3" />
+ )}
+ {retrySubmitting || isRetryingHere
+ ? t("Retrying…")
+ : t("Retry indexing")}
+ </button>
+ ) : undefined
+ }
+ />
)}
<FileDropZone
diff --git a/web/components/knowledge/KbIndexFailureBanner.tsx b/web/components/knowledge/KbIndexFailureBanner.tsx
new file mode 100644
index 000000000..33d1010c2
--- /dev/null
+++ b/web/components/knowledge/KbIndexFailureBanner.tsx
@@ -0,0 +1,50 @@
+"use client";
+
+import type { ReactNode } from "react";
+import Link from "next/link";
+import { AlertTriangle, Settings } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import {
+ resolveKnowledgeIndexFailure,
+ type KnowledgeBase,
+} from "@/lib/knowledge-helpers";
+
+interface KbIndexFailureBannerProps {
+ kb: KnowledgeBase;
+ action?: ReactNode;
+}
+
+export default function KbIndexFailureBanner({
+ kb,
+ action,
+}: KbIndexFailureBannerProps) {
+ const { t } = useTranslation();
+ const failure = resolveKnowledgeIndexFailure(kb);
+ if (!failure) return null;
+
+ return (
+ <div className="flex flex-wrap items-start justify-between gap-3 rounded-lg border border-red-200 bg-red-50/80 px-3 py-2 text-[12px] text-red-700 dark:border-red-900/60 dark:bg-red-950/20 dark:text-red-300">
+ <div className="flex min-w-0 flex-1 items-start gap-2">
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ <span className="break-words">
+ {failure.message ||
+ t(
+ "Indexing failed. Review the error details, update the configuration if needed, then retry.",
+ )}
+ </span>
+ </div>
+ <div className="flex shrink-0 flex-wrap items-center gap-2">
+ {failure.requiresModelChange && (
+ <Link
+ href={failure.settingsHref || "/settings/models"}
+ className="inline-flex items-center gap-1.5 rounded-md border border-red-300 bg-red-100 px-2 py-1 text-[11.5px] font-medium text-red-800 transition-colors hover:bg-red-200 dark:border-red-800 dark:bg-red-950/50 dark:text-red-200"
+ >
+ <Settings className="h-3 w-3" />
+ {t("Open model settings")}
+ </Link>
+ )}
+ {action}
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/knowledge/KbIndexVersionsSection.tsx b/web/components/knowledge/KbIndexVersionsSection.tsx
index 2441315da..0dd13545a 100644
--- a/web/components/knowledge/KbIndexVersionsSection.tsx
+++ b/web/components/knowledge/KbIndexVersionsSection.tsx
@@ -22,6 +22,7 @@ import {
} from "@/lib/knowledge-helpers";
import type { TaskState } from "@/hooks/useKnowledgeProgress";
import ProcessLogs from "@/components/common/ProcessLogs";
+import KbIndexFailureBanner from "./KbIndexFailureBanner";
interface KbIndexVersionsSectionProps {
kb: KnowledgeBase;
@@ -114,24 +115,13 @@ export default function KbIndexVersionsSection({
)}
</div>
- {(isError || needsReindex || mismatch) && (
- <div
- className={`flex items-start gap-2 rounded-lg border px-3 py-2 text-[12px] ${
- isError
- ? "border-red-200 bg-red-50/80 text-red-700 dark:border-red-900/60 dark:bg-red-950/20 dark:text-red-300"
- : "border-amber-200 bg-amber-50/80 text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/20 dark:text-amber-300"
- }`}
- >
- <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
- <span>
- {isError
- ? t(
- "Previous indexing failed. Retry will rebuild the index from the existing source documents.",
- )
- : t(
- "The active embedding configuration doesn't match any ready index version. Re-index to rebuild against the current embedding model.",
- )}
- </span>
+ {isError && <KbIndexFailureBanner kb={kb} />}
+
+ {!isError && (needsReindex || mismatch) && (
+ <div className="rounded-lg border border-amber-200 bg-amber-50/80 px-3 py-2 text-[12px] text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/20 dark:text-amber-300">
+ {t(
+ "The active embedding configuration doesn't match any ready index version. Re-index to rebuild against the current embedding model.",
+ )}
</div>
)}
diff --git a/web/hooks/useKnowledgeProgress.ts b/web/hooks/useKnowledgeProgress.ts
index 1069ca647..23ea5dfc1 100644
--- a/web/hooks/useKnowledgeProgress.ts
+++ b/web/hooks/useKnowledgeProgress.ts
@@ -2,7 +2,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { apiUrl, wsUrl } from "@/lib/api";
-import type { ProgressInfo } from "@/lib/knowledge-helpers";
+import { taskFailureMessage, type ProgressInfo } from "@/lib/knowledge-helpers";
export type TaskKind = "create" | "upload" | "reindex" | "retry";
@@ -13,6 +13,8 @@ export interface TaskState {
logs: string[];
executing: boolean;
error: string | null;
+ errorCode?: string;
+ retryable?: boolean;
}
interface UseKnowledgeProgressOptions {
@@ -216,25 +218,30 @@ export function useKnowledgeProgress(options?: UseKnowledgeProgressOptions) {
source.addEventListener("failed", (event) => {
settled = true;
let detail = "Task failed";
- let details: string | undefined;
+ let errorCode: string | undefined;
+ let retryable: boolean | undefined;
try {
const payload = JSON.parse((event as MessageEvent).data) as {
detail?: string;
details?: string;
+ error_code?: string;
+ retryable?: boolean;
};
- detail = payload.detail || detail;
- details = payload.details;
+ detail = taskFailureMessage(payload);
+ errorCode = payload.error_code;
+ retryable = payload.retryable;
} catch {
// ignore malformed failure event
}
- const composed = details ? `${detail}\n\n${details}` : detail;
setTasksByKb((prev) => {
const current = prev[kbName];
if (!current || current.taskId !== taskId) return prev;
const finalState = {
...current,
executing: false,
- error: composed,
+ error: detail,
+ errorCode,
+ retryable,
};
const startedAt =
startedAtRef.current[`${kbName}:${taskId}`] ?? Date.now();
diff --git a/web/lib/graphrag-model-compatibility.ts b/web/lib/graphrag-model-compatibility.ts
new file mode 100644
index 000000000..ee844c8f8
--- /dev/null
+++ b/web/lib/graphrag-model-compatibility.ts
@@ -0,0 +1,22 @@
+import type { GraphRagModelCompatibility } from "@/lib/knowledge-api";
+
+export interface GraphRagCandidateGate {
+ activeKey: string;
+ candidateKey: string;
+ testedKey: string | null;
+ result: GraphRagModelCompatibility | null;
+}
+
+/** A successful probe is valid only for the exact, not-yet-active candidate. */
+export function canApplyGraphRagModelCandidate({
+ activeKey,
+ candidateKey,
+ testedKey,
+ result,
+}: GraphRagCandidateGate): boolean {
+ return (
+ candidateKey !== activeKey &&
+ testedKey === candidateKey &&
+ result?.compatible === true
+ );
+}
diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.ts
index 3f3e383b6..a4dbce4d6 100644
--- a/web/lib/knowledge-api.ts
+++ b/web/lib/knowledge-api.ts
@@ -96,6 +96,16 @@ export interface ModelKindOptions {
options: ModelOption[];
}
+export interface GraphRagModelCompatibility {
+ status: "compatible" | "incompatible" | "unverifiable";
+ compatible: boolean | null;
+ code: string;
+ message: string;
+ model: string;
+ binding: string;
+ retryable: boolean;
+}
+
/** Map of service kind ("llm" | "embedding") → its options + active selection. */
export type ModelOptionsByKind = Record<string, ModelKindOptions>;
@@ -395,6 +405,26 @@ export async function getEngineModelOptions(
return (await res.json()) as ModelOptionsByKind;
}
+export async function testGraphRagModelCompatibility(
+ profileId: string,
+ modelId: string,
+): Promise<GraphRagModelCompatibility> {
+ const res = await apiFetch(
+ apiUrl("/api/v1/knowledge/rag-pipelines/graphrag/model-compatibility"),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ profile_id: profileId, model_id: modelId }),
+ },
+ );
+ if (!res.ok) {
+ throw new Error(
+ await readErrorDetail(res, "Failed to test GraphRAG compatibility"),
+ );
+ }
+ return (await res.json()) as GraphRagModelCompatibility;
+}
+
export async function setEngineActiveModel(
kind: string,
profileId: string,
diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.ts
index 158fd1833..df9f6f6c1 100644
--- a/web/lib/knowledge-helpers.ts
+++ b/web/lib/knowledge-helpers.ts
@@ -23,6 +23,17 @@ export interface ProgressInfo {
indexed_count?: number;
index_changed?: boolean;
index_action?: string;
+ error?: string;
+ error_code?: string;
+ retryable?: boolean;
+}
+
+export interface KnowledgeIndexFailure {
+ code?: string;
+ message?: string;
+ retryable?: boolean;
+ requiresModelChange: boolean;
+ settingsHref?: string;
}
export interface IndexVersion {
@@ -83,7 +94,10 @@ export interface KnowledgeBase {
}
export type ProviderConnectionStatus =
- "ready" | "per_kb" | "needs_key" | "unavailable";
+ | "ready"
+ | "per_kb"
+ | "needs_key"
+ | "unavailable";
export const providerConnectionStatus = (provider: {
id: string;
@@ -173,6 +187,58 @@ export const kbDocCount = (kb: KnowledgeBase): number | null => {
export const resolveKbStatus = (kb: KnowledgeBase): string =>
kb.status ?? kb.statistics?.status ?? "unknown";
+export const resolveKnowledgeIndexFailure = (
+ kb: KnowledgeBase,
+): KnowledgeIndexFailure | null => {
+ if (resolveKbStatus(kb) !== "error") return null;
+
+ const progress = kb.progress;
+ const storedProgress = kb.statistics?.progress;
+ const code =
+ progress?.error_code?.trim() ||
+ storedProgress?.error_code?.trim() ||
+ undefined;
+ const message =
+ progress?.error?.trim() ||
+ storedProgress?.error?.trim() ||
+ progress?.message?.trim() ||
+ storedProgress?.message?.trim() ||
+ undefined;
+
+ const embeddingConfigurationCodes = new Set([
+ "graphrag_embedding_authentication_failed",
+ "graphrag_embedding_dimension_mismatch",
+ "graphrag_embedding_endpoint_failed",
+ "graphrag_embedding_incompatible",
+ "graphrag_embedding_provider_unsupported",
+ ]);
+ const completionConfigurationCodes = new Set([
+ "graphrag_model_incompatible",
+ "graphrag_provider_unsupported",
+ "graphrag_model_authentication_failed",
+ "graphrag_model_endpoint_failed",
+ ]);
+ const requiresEmbeddingChange = embeddingConfigurationCodes.has(code ?? "");
+ const requiresCompletionChange = completionConfigurationCodes.has(code ?? "");
+
+ return {
+ code,
+ message,
+ retryable: progress?.retryable ?? storedProgress?.retryable,
+ requiresModelChange: requiresEmbeddingChange || requiresCompletionChange,
+ settingsHref: requiresEmbeddingChange
+ ? "/settings/embedding"
+ : requiresCompletionChange
+ ? "/settings/models"
+ : undefined,
+ };
+};
+
+export const taskFailureMessage = (payload: {
+ detail?: string;
+ details?: string;
+}): string => payload.detail?.trim() || "Task failed";
+
export const kbNeedsReindex = (kb: KnowledgeBase): boolean =>
Boolean(kb.statistics?.needs_reindex) ||
resolveKbStatus(kb) === "needs_reindex";
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 14d1990ba..65da72de2 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -2576,6 +2576,23 @@
"Global mode only": "Global mode only",
"Chat model": "Chat model",
"Embedding model": "Embedding model",
+ "Test compatibility": "Test compatibility",
+ "Testing compatibility…": "Testing compatibility…",
+ "Use this model": "Use this model",
+ "Runs one small structured-output request and may incur provider charges. The global active chat model changes only after you choose Use this model.": "Runs one small structured-output request and may incur provider charges. The global active chat model changes only after you choose Use this model.",
+ "Compatible with GraphRAG": "Compatible with GraphRAG",
+ "Incompatible with GraphRAG": "Incompatible with GraphRAG",
+ "Compatibility could not be verified": "Compatibility could not be verified",
+ "The model returned valid GraphRAG structured output.": "The model returned valid GraphRAG structured output.",
+ "The model did not accept or return the structured output required by GraphRAG.": "The model did not accept or return the structured output required by GraphRAG.",
+ "GraphRAG compatibility could not be verified because the model credentials were rejected.": "GraphRAG compatibility could not be verified because the model credentials were rejected.",
+ "GraphRAG compatibility could not be verified because the model provider is rate limiting requests. Try again later.": "GraphRAG compatibility could not be verified because the model provider is rate limiting requests. Try again later.",
+ "GraphRAG compatibility could not be verified because the model provider could not be reached. Try again later.": "GraphRAG compatibility could not be verified because the model provider could not be reached. Try again later.",
+ "GraphRAG compatibility could not be verified because the model response reached its output token limit. Try again.": "GraphRAG compatibility could not be verified because the model response reached its output token limit. Try again.",
+ "GraphRAG compatibility could not be verified with this model.": "GraphRAG compatibility could not be verified with this model.",
+ "The configured GraphRAG model or endpoint was not found. Check its provider URL.": "The configured GraphRAG model or endpoint was not found. Check its provider URL.",
+ "GraphRAG cannot use this OAuth-only model provider. Choose an API-key profile.": "GraphRAG cannot use this OAuth-only model provider. Choose an API-key profile.",
+ "GraphRAG does not support the selected model provider transport.": "GraphRAG does not support the selected model provider transport.",
"No models configured — open catalog": "No models configured — open catalog",
"Multimodal documents need a vision-capable chat model.": "Multimodal documents need a vision-capable chat model.",
"Requirements & environment": "Requirements & environment",
@@ -2961,6 +2978,8 @@
"Product names and logos are trademarks of their respective owners, shown for identification only.": "Product names and logos are trademarks of their respective owners, shown for identification only.",
"Needs authorization": "Needs authorization",
"Reauthorize": "Reauthorize",
+ "Indexing failed. Review the error details, update the configuration if needed, then retry.": "Indexing failed. Review the error details, update the configuration if needed, then retry.",
+ "Open model settings": "Open model settings",
"Frontend": "Frontend",
"Sandbox": "Sandbox",
"Supervisor": "Supervisor",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 366ca8095..1db8593ad 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -2576,6 +2576,23 @@
"Global mode only": "仅 global 模式",
"Chat model": "对话模型",
"Embedding model": "嵌入模型",
+ "Test compatibility": "测试兼容性",
+ "Testing compatibility…": "正在测试兼容性…",
+ "Use this model": "使用此模型",
+ "Runs one small structured-output request and may incur provider charges. The global active chat model changes only after you choose Use this model.": "测试会发送一次小型结构化输出请求,可能产生少量模型费用。只有点击“使用此模型”后,才会切换全局启用的对话模型。",
+ "Compatible with GraphRAG": "与 GraphRAG 兼容",
+ "Incompatible with GraphRAG": "与 GraphRAG 不兼容",
+ "Compatibility could not be verified": "暂时无法验证兼容性",
+ "The model returned valid GraphRAG structured output.": "模型成功返回了符合 GraphRAG 要求的结构化输出。",
+ "The model did not accept or return the structured output required by GraphRAG.": "模型不接受 GraphRAG 所需的结构化输出请求,或返回内容不符合要求。",
+ "GraphRAG compatibility could not be verified because the model credentials were rejected.": "模型凭据被拒绝,因此无法验证 GraphRAG 兼容性。",
+ "GraphRAG compatibility could not be verified because the model provider is rate limiting requests. Try again later.": "模型服务正在限流,因此无法验证 GraphRAG 兼容性。请稍后重试。",
+ "GraphRAG compatibility could not be verified because the model provider could not be reached. Try again later.": "暂时无法连接模型服务,因此无法验证 GraphRAG 兼容性。请稍后重试。",
+ "GraphRAG compatibility could not be verified because the model response reached its output token limit. Try again.": "模型响应达到输出长度限制,因此暂时无法验证 GraphRAG 兼容性。请重试。",
+ "GraphRAG compatibility could not be verified with this model.": "暂时无法验证此模型的 GraphRAG 兼容性。",
+ "The configured GraphRAG model or endpoint was not found. Check its provider URL.": "找不到为 GraphRAG 配置的模型或接口地址,请检查模型服务地址。",
+ "GraphRAG cannot use this OAuth-only model provider. Choose an API-key profile.": "GraphRAG 暂不支持此 OAuth 模型服务,请改用 API 密钥类型的模型配置。",
+ "GraphRAG does not support the selected model provider transport.": "GraphRAG 暂不支持所选模型服务的请求方式。",
"No models configured — open catalog": "未配置模型 — 打开模型目录",
"Multimodal documents need a vision-capable chat model.": "多模态文档需要支持视觉的对话模型。",
"Requirements & environment": "环境要求",
@@ -2961,6 +2978,8 @@
"Product names and logos are trademarks of their respective owners, shown for identification only.": "产品名称与标识为其各自所有者的商标,此处仅用于标识。",
"Needs authorization": "待授权",
"Reauthorize": "重新授权",
+ "Indexing failed. Review the error details, update the configuration if needed, then retry.": "索引失败。请查看错误详情,按需更新配置,然后重试。",
+ "Open model settings": "打开模型设置",
"Frontend": "前端",
"Sandbox": "沙箱",
"Supervisor": "主进程",
diff --git a/web/tests/graphrag-model-compatibility.test.ts b/web/tests/graphrag-model-compatibility.test.ts
new file mode 100644
index 000000000..85cc5f0da
--- /dev/null
+++ b/web/tests/graphrag-model-compatibility.test.ts
@@ -0,0 +1,87 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { testGraphRagModelCompatibility } from "../lib/knowledge-api";
+import { canApplyGraphRagModelCandidate } from "../lib/graphrag-model-compatibility";
+
+test("GraphRAG candidate probe sends catalog IDs without activating the model", async () => {
+ const originalFetch = globalThis.fetch;
+ let requestUrl = "";
+ let requestInit: RequestInit | undefined;
+ globalThis.fetch = async (input, init) => {
+ requestUrl = String(input);
+ requestInit = init;
+ return new Response(
+ JSON.stringify({
+ status: "compatible",
+ compatible: true,
+ code: "graphrag_model_compatible",
+ message: "The model returned valid GraphRAG structured output.",
+ model: "gpt-4o-mini",
+ binding: "openai",
+ retryable: false,
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ );
+ };
+
+ try {
+ const result = await testGraphRagModelCompatibility("profile-a", "model-b");
+
+ assert.equal(
+ requestUrl,
+ "/api/v1/knowledge/rag-pipelines/graphrag/model-compatibility",
+ );
+ assert.equal(requestInit?.method, "POST");
+ assert.deepEqual(JSON.parse(String(requestInit?.body)), {
+ profile_id: "profile-a",
+ model_id: "model-b",
+ });
+ assert.equal(result.status, "compatible");
+ assert.equal(result.compatible, true);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test("only the exact candidate that passed compatibility can be applied", () => {
+ const compatible = {
+ status: "compatible" as const,
+ compatible: true,
+ code: "graphrag_model_compatible",
+ message: "ok",
+ model: "gpt-4o-mini",
+ binding: "openai",
+ retryable: false,
+ };
+
+ assert.equal(
+ canApplyGraphRagModelCandidate({
+ activeKey: "profile-a::model-a",
+ candidateKey: "profile-a::model-b",
+ testedKey: "profile-a::model-b",
+ result: compatible,
+ }),
+ true,
+ );
+ assert.equal(
+ canApplyGraphRagModelCandidate({
+ activeKey: "profile-a::model-a",
+ candidateKey: "profile-a::model-c",
+ testedKey: "profile-a::model-b",
+ result: compatible,
+ }),
+ false,
+ "changing the dropdown must invalidate the previous probe",
+ );
+ assert.equal(
+ canApplyGraphRagModelCandidate({
+ activeKey: "profile-a::model-b",
+ candidateKey: "profile-a::model-b",
+ testedKey: "profile-a::model-b",
+ result: compatible,
+ }),
+ false,
+ "the already-active model does not need to be applied again",
+ );
+});
diff --git a/web/tests/knowledge-helpers.test.ts b/web/tests/knowledge-helpers.test.ts
index 199228a58..953360a43 100644
--- a/web/tests/knowledge-helpers.test.ts
+++ b/web/tests/knowledge-helpers.test.ts
@@ -3,6 +3,8 @@ import assert from "node:assert/strict";
import {
kbCanReindex,
+ resolveKnowledgeIndexFailure,
+ taskFailureMessage,
providerConnectionStatus,
type KnowledgeBase,
} from "../lib/knowledge-helpers";
@@ -55,6 +57,84 @@ test("kbCanReindex preserves mismatch and needs-reindex behavior", () => {
);
});
+test("resolveKnowledgeIndexFailure preserves actionable backend metadata", () => {
+ assert.deepEqual(
+ resolveKnowledgeIndexFailure(
+ kb({
+ status: "error",
+ progress: {
+ stage: "error",
+ error: "Choose a chat model that supports structured output.",
+ error_code: "graphrag_model_incompatible",
+ retryable: false,
+ },
+ }),
+ ),
+ {
+ code: "graphrag_model_incompatible",
+ message: "Choose a chat model that supports structured output.",
+ retryable: false,
+ requiresModelChange: true,
+ settingsHref: "/settings/models",
+ },
+ );
+});
+
+test("resolveKnowledgeIndexFailure distinguishes configuration from transient failures", () => {
+ const authentication = resolveKnowledgeIndexFailure(
+ kb({
+ status: "error",
+ progress: {
+ stage: "error",
+ error_code: "graphrag_model_authentication_failed",
+ retryable: false,
+ },
+ }),
+ );
+ const rateLimit = resolveKnowledgeIndexFailure(
+ kb({
+ status: "error",
+ progress: {
+ stage: "error",
+ error_code: "graphrag_model_rate_limited",
+ retryable: true,
+ },
+ }),
+ );
+
+ assert.equal(authentication?.requiresModelChange, true);
+ assert.equal(authentication?.settingsHref, "/settings/models");
+ assert.equal(rateLimit?.requiresModelChange, false);
+ assert.equal(rateLimit?.settingsHref, undefined);
+ assert.equal(rateLimit?.retryable, true);
+});
+
+test("resolveKnowledgeIndexFailure routes embedding configuration failures to embedding settings", () => {
+ const endpointFailure = resolveKnowledgeIndexFailure(
+ kb({
+ status: "error",
+ progress: {
+ stage: "error",
+ error_code: "graphrag_embedding_endpoint_failed",
+ retryable: false,
+ },
+ }),
+ );
+
+ assert.equal(endpointFailure?.requiresModelChange, true);
+ assert.equal(endpointFailure?.settingsHref, "/settings/embedding");
+});
+
+test("taskFailureMessage keeps trace details out of the primary error", () => {
+ assert.equal(
+ taskFailureMessage({
+ detail: "GraphRAG preflight failed.",
+ details: "Traceback: sensitive internal diagnostics",
+ }),
+ "GraphRAG preflight failed.",
+ );
+});
+
test("IMA is connected per knowledge base instead of globally ready", () => {
assert.equal(
providerConnectionStatus({ id: "ima", configured: true }),