~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
refactor(rag): categorize /test-embedding errors instead of guessing (#4208 follow-up) (#4220)
LearningCircuit958c1adde3e9
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex 3fe75de7a0..3ba78fef32 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -34,6 +34,7 @@ from typing import Optionalfrom ...constants import FILE_PATH_SENTINELS, FILE_PATH_TEXT_ONLYfrom ...security.decorators import require_json_body+from ...security.log_sanitizer import sanitize_error_messagefrom ...web.auth.decorators import login_requiredfrom ...web.utils.request_helpers import parse_bool_argfrom ...utilities.db_utils import get_settings_manager@@ -145,6 +146,75 @@ def get_rag_service()+# Module prefix for exceptions DEFINED inside LDR itself. An exception whose+# class lives under ``local_deep_research`` is something only we can fix, so we+# steer the user to file a bug instead of second-guessing their model choice.+#+# We deliberately do NOT treat bare builtins (KeyError/TypeError/RuntimeError/+# ...) as internal: ``type(exc).__module__`` is where the class is *defined*,+# not where it was *raised*, so a builtin tells us nothing about whether LDR or+# a provider/langchain frame produced it. On this path an OpenAI-compatible+# server that returns a malformed 200 body can surface a bare TypeError from+# langchain's response parser; telling the user to "report it on GitHub" for+# that is exactly the misleading guidance #4208 set out to remove.+_INTERNAL_MODULE_PREFIX = "local_deep_research"++# Module prefixes whose exceptions are upstream-provider errors (network,+# auth, model not found, etc.). Matched against ``type(exc).__module__``.+_UPSTREAM_MODULE_PREFIXES = (+ "openai",+ "httpx",+ "requests",+ "urllib3",+ "anthropic",+)+++def _module_matches(type_module: str, prefix: str) -> bool:+ """True if ``type_module`` is ``prefix`` itself or one of its submodules."""+ return type_module == prefix or type_module.startswith(f"{prefix}.")+++def _format_test_embedding_error(exc: Exception, model: str) -> str:+ """Build the user-facing error message for /api/rag/test-embedding.++ Categorizes the exception by the module its *class* is defined in so the+ UI distinguishes LDR-internal bugs (which the user can't fix and+ shouldn't be steered into changing their model over) from real+ upstream/provider errors. The previous implementation ran a keyword-match+ heuristic over every exception text — see #4208, where+ ``NoSettingsContextError`` surfaced as a misleading "try a dedicated+ embedding model" suggestion.++ The detail text is scrubbed with :func:`sanitize_error_message` first+ because an upstream error can echo an API key back in a URL or auth+ header, and this endpoint returns the detail to the browser.+ """+ raw_message = str(exc).strip() or type(exc).__name__+ detail = sanitize_error_message(raw_message)+ type_name = type(exc).__name__+ type_module = type(exc).__module__ or ""++ if _module_matches(type_module, _INTERNAL_MODULE_PREFIX):+ return (+ f"Embedding test failed for model '{model}' due to an "+ f"internal LDR error ({type_name}). This is a bug in LDR, "+ "not your configuration. Please report it on GitHub with "+ f"the server logs. Detail: {detail}"+ )++ if any(+ _module_matches(type_module, prefix)+ for prefix in _UPSTREAM_MODULE_PREFIXES+ ):+ return (+ f"Embedding test failed for model '{model}'. The provider "+ f"returned an error: {detail}"+ )++ return f"Embedding test failed for model '{model}': {detail}"++# Config API Routes@@ -440,42 +510,7 @@ def test_embedding():}), 400logger.exception("Error during testing embedding")- error_str = str(e).lower()-- # Detect common signs that an LLM was selected instead of an embedding model- llm_hints = [- "does not support",- "not an embedding",- "generate embedding",- "invalid model",- "not found",- "expected float",- "could not convert",- "list index out of range",- "object is not subscriptable",- "not iterable",- "json",- "chat",- "completion",- ]- is_likely_llm = any(hint in error_str for hint in llm_hints)-- if is_likely_llm:- user_message = (- f"Embedding test failed for model '{model}'. "- "This is most likely because an LLM (language model) was selected "- "instead of an embedding model. Please choose a dedicated embedding "- "model (e.g. nomic-embed-text, mxbai-embed-large, "- "all-MiniLM-L6-v2)."- )- else:- user_message = (- f"Embedding test failed for model '{model}'. "- "If you are unsure whether the selected model supports embeddings, "- "try a dedicated embedding model instead (e.g. nomic-embed-text, "- "mxbai-embed-large, all-MiniLM-L6-v2)."- )-+ user_message = _format_test_embedding_error(e, model)return jsonify({"success": False, "error": user_message}), 500diff --git a/tests/research_library/routes/test_rag_routes_coverage.py b/tests/research_library/routes/test_rag_routes_coverage.pyindex 42f4d53c6b..6ed8a27ce1 100644--- a/tests/research_library/routes/test_rag_routes_coverage.py+++ b/tests/research_library/routes/test_rag_routes_coverage.py@@ -445,7 +445,14 @@ class TestTestEmbedding:assert data["success"] is Trueassert data["dimension"] == 3- def test_error_llm_hint(self, app):+ def test_builtin_runtime_error_is_not_flagged_as_ldr_bug(self, app):+ """A bare builtin (RuntimeError/KeyError/TypeError/...) is NOT an+ LDR bug: ``type(exc).__module__`` is where the class is defined,+ not where it was raised, so a builtin can just as easily escape+ provider/langchain code. It must fall through to a verbatim+ message, not be labeled 'report it on GitHub'. Only exceptions+ whose class lives under ``local_deep_research`` are internal.+ See #4208 and the follow-up polish."""with _auth_client(app,extra_patches=[@@ -462,9 +469,14 @@ class TestTestEmbedding:assert resp.status_code == 500data = resp.get_json()assert data["success"] is False- assert "LLM" in data["error"]-- def test_error_generic(self, app):+ assert "internal LDR error" not in data["error"]+ assert "report it on GitHub" not in data["error"]+ # The real cause is still surfaced verbatim.+ assert "does not support embedding" in data["error"]++ def test_builtin_error_message_is_surfaced_verbatim(self, app):+ """A builtin error's original message is shown verbatim, with no+ 'try a dedicated embedding model' guessing."""with _auth_client(app,extra_patches=[@@ -481,7 +493,9 @@ class TestTestEmbedding:assert resp.status_code == 500data = resp.get_json()assert data["success"] is False- assert "dedicated embedding model" in data["error"]+ # No more "try a dedicated embedding model" guessing.+ assert "dedicated embedding model" not in data["error"]+ assert "network timeout" in data["error"]# ---------------------------------------------------------------------------diff --git a/tests/research_library/routes/test_rag_routes_deep_coverage.py b/tests/research_library/routes/test_rag_routes_deep_coverage.pyindex 00cef20f46..2b862154a5 100644--- a/tests/research_library/routes/test_rag_routes_deep_coverage.py+++ b/tests/research_library/routes/test_rag_routes_deep_coverage.py@@ -962,11 +962,17 @@ class TestCollectionUploadPageStorageSettings:# ----------------------------------------------------------------------------class TestTestEmbeddingErrorHints:- """Tests for LLM-hint detection in test_embedding error path."""+class TestTestEmbeddingErrorCategorization:+ """Tests for exception categorization in test_embedding error path.- def test_llm_hint_does_not_support(self, app):- """Error containing 'does not support' triggers LLM hint message."""+ Replaces the previous keyword-match heuristic which mis-categorized+ LDR-internal bugs (e.g. NoSettingsContextError → "try a dedicated+ embedding model"). See #4208 and the follow-up PR.+ """++ def test_value_error_falls_through_to_verbatim(self, app):+ """Generic ValueError is shown verbatim, with no "you picked an LLM"+ guess. Previously this exact message triggered an LLM-hint reply."""with _auth_client(app,extra_patches=[@@ -983,10 +989,12 @@ class TestTestEmbeddingErrorHints:)assert resp.status_code == 500data = resp.get_json()- assert "LLM (language model)" in data["error"]+ assert "LLM (language model)" not in data["error"]+ assert "model does not support embeddings" in data["error"]- def test_llm_hint_list_index_out_of_range(self, app):- """Error with 'list index out of range' triggers LLM hint."""+ def test_index_error_falls_through_to_verbatim(self, app):+ """IndexError is shown verbatim. Previously 'list index out of+ range' triggered a misleading LLM-hint message."""with _auth_client(app,extra_patches=[@@ -1003,10 +1011,12 @@ class TestTestEmbeddingErrorHints:)assert resp.status_code == 500data = resp.get_json()- assert "LLM (language model)" in data["error"]+ assert "LLM (language model)" not in data["error"]+ assert "list index out of range" in data["error"]- def test_generic_error_no_llm_hint(self, app):- """Error without LLM hints gives generic message."""+ def test_connection_error_falls_through_to_verbatim(self, app):+ """Generic ConnectionError shows the real reason. Previously the+ 'If you are unsure...' message hid the actual cause."""with _auth_client(app,extra_patches=[@@ -1023,7 +1033,162 @@ class TestTestEmbeddingErrorHints:)assert resp.status_code == 500data = resp.get_json()- assert "If you are unsure" in data["error"]+ assert "If you are unsure" not in data["error"]+ assert "connection refused" in data["error"]++ def test_internal_error_is_flagged_as_ldr_bug(self, app):+ """An exception whose class is defined inside ``local_deep_research``+ (e.g. NoSettingsContextError) must be presented as a bug to report,+ not steered into a model-choice suggestion. Regression for #4208."""+ from local_deep_research.config.thread_settings import (+ NoSettingsContextError,+ )++ with _auth_client(+ app,+ extra_patches=[+ patch(+ "local_deep_research.embeddings.embeddings_config.get_embedding_function",+ side_effect=NoSettingsContextError(+ "No settings context available in thread for key "+ "'embeddings.openai.dimensions'."+ ),+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/rag/test-embedding",+ json={"provider": "openai", "model": "some-model"},+ content_type="application/json",+ )+ assert resp.status_code == 500+ data = resp.get_json()+ assert "internal LDR error" in data["error"]+ assert "NoSettingsContextError" in data["error"]+ assert "report it on GitHub" in data["error"]++ def test_upstream_provider_error_passes_through(self, app):+ """Exceptions from upstream provider modules (openai, httpx,+ requests, ...) are shown as "provider returned an error: ..."+ with the original message preserved. Distinguishes user/config+ problems from LDR bugs."""++ class _FakeOpenAIError(Exception):+ pass++ _FakeOpenAIError.__module__ = "openai"++ with _auth_client(+ app,+ extra_patches=[+ patch(+ "local_deep_research.embeddings.embeddings_config.get_embedding_function",+ side_effect=_FakeOpenAIError(+ "404 model 'mystery-model' not found"+ ),+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/rag/test-embedding",+ json={"provider": "openai", "model": "mystery-model"},+ content_type="application/json",+ )+ assert resp.status_code == 500+ data = resp.get_json()+ assert "provider returned an error" in data["error"]+ assert "mystery-model" in data["error"]++ def test_upstream_subclass_of_builtin_is_provider_error(self, app):+ """A builtin SUBCLASS defined in an upstream module is a provider+ error, not an LDR bug: the subclass's __module__ is the upstream+ package (e.g. 'openai._response'), so _module_matches routes it to+ the provider branch even though it derives from KeyError. Guards the+ module-based categorization against builtin-subclass leakage."""++ class _FakeOpenAIKeyError(KeyError):+ pass++ _FakeOpenAIKeyError.__module__ = "openai._response"++ with _auth_client(+ app,+ extra_patches=[+ patch(+ "local_deep_research.embeddings.embeddings_config.get_embedding_function",+ side_effect=_FakeOpenAIKeyError("data"),+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/rag/test-embedding",+ json={"provider": "openai", "model": "some-model"},+ content_type="application/json",+ )+ assert resp.status_code == 500+ data = resp.get_json()+ assert "provider returned an error" in data["error"]+ assert "internal LDR error" not in data["error"]++ def test_builtin_keyerror_is_not_flagged_as_ldr_bug(self, app):+ """A bare builtin (KeyError) is NOT attributed to LDR. On this path a+ malformed-but-200 response from an OpenAI-compatible server can+ surface a builtin out of langchain's response parser, so builtins+ fall through to a verbatim message instead of 'report it on GitHub'.+ Only exceptions defined under ``local_deep_research`` are internal."""+ with _auth_client(+ app,+ extra_patches=[+ patch(+ "local_deep_research.embeddings.embeddings_config.get_embedding_function",+ side_effect=KeyError("embedding"),+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/rag/test-embedding",+ json={"provider": "openai", "model": "some-model"},+ content_type="application/json",+ )+ assert resp.status_code == 500+ data = resp.get_json()+ assert "internal LDR error" not in data["error"]+ assert "report it on GitHub" not in data["error"]++ def test_secret_in_error_message_is_redacted(self, app):+ """An upstream error that echoes an API key back must be scrubbed+ before it reaches the browser. The endpoint is @login_required, but+ the detail is sanitized as defense-in-depth so a leaked key is never+ reflected verbatim in the response."""++ class _FakeOpenAIError(Exception):+ pass++ _FakeOpenAIError.__module__ = "openai"++ leaked_key = "sk-proj-FAKEKEYFORTESTSONLY000000000000" # gitleaks:allow++ with _auth_client(+ app,+ extra_patches=[+ patch(+ "local_deep_research.embeddings.embeddings_config.get_embedding_function",+ side_effect=_FakeOpenAIError(+ f"Incorrect API key provided: {leaked_key}"+ ),+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/rag/test-embedding",+ json={"provider": "openai", "model": "some-model"},+ content_type="application/json",+ )+ assert resp.status_code == 500+ data = resp.get_json()+ assert leaked_key not in data["error"]+ assert "[REDACTED_KEY]" in data["error"]+ assert "provider returned an error" in data["error"]# ---------------------------------------------------------------------------