Skip to content

~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.

feat(errors): friendly runtime messages for OpenAI-compatible endpoints (#4027)

d 🔹8c59082c30f7
diff --git a/changelog.d/+3878-openai-compat-friendly-errors.feature.md b/changelog.d/+3878-openai-compat-friendly-errors.feature.md
new file mode 100644
index 0000000000..9beb1a2f7d
--- /dev/null
+++ b/changelog.d/+3878-openai-compat-friendly-errors.feature.md
@@ -0,0 +1 @@
+OpenAI-compatible runtime errors (LM Studio / vLLM / llama.cpp server / OpenRouter / custom endpoint) now surface a message that names the provider, configured base URL, and model. The existing `Error type: <code>` token convention is extended with seven `openai_*` codes (`openai_connection_refused`, `openai_timeout`, `openai_auth`, `openai_permission_denied`, `openai_model_not_found`, `openai_bad_request`, `openai_unknown`), and `ErrorReporter` maps each to the right `ErrorCategory`. The original exception text is preserved in a `Details:` suffix; userinfo embedded in a base URL (`https://u:key@host/v1`) is stripped before display.
diff --git a/pdm.lock b/pdm.lock
index 1001ccd213..6804d7d83d 100644
--- a/pdm.lock
+++ b/pdm.lock
@@ -5,7 +5,7 @@
groups = ["default", "dev", "mcp"]
strategy = ["inherit_metadata"]
lock_version = "4.5.0"
-content_hash = "sha256:c21fb2b8459e7aad9b2fa2160785c6c4c0114b557dbea2a7eaf68898e20689e6"
+content_hash = "sha256:63ab9cd74a01a92e437eb7257bfad6cc6e7cd7db822471b596083c4be01624af"
[[metadata.targets]]
requires_python = ">=3.12,<3.15"
diff --git a/pyproject.toml b/pyproject.toml
index 526fb49766..5bcd8147eb 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -26,6 +26,8 @@ dependencies = [
"langchain-ollama~=1.0",
"langchain-openai~=1.1",
"langchain-anthropic~=1.3",
+ "openai>=2", # direct dep: error_handling/openai_compat_errors.py imports exception classes
+ "httpx>=0.27", # direct dep: error_handling/openai_compat_errors.py imports ConnectError/ReadTimeout
"duckduckgo-search~=8.1",
"python-dateutil~=2.9",
"typing-extensions~=4.15",
diff --git a/src/local_deep_research/error_handling/error_reporter.py b/src/local_deep_research/error_handling/error_reporter.py
index e161ce813d..a31d7de904 100644
--- a/src/local_deep_research/error_handling/error_reporter.py
+++ b/src/local_deep_research/error_handling/error_reporter.py
@@ -41,6 +41,9 @@ class ErrorReporter:
r"127\.0\.0\.1.*Docker",
r"localhost.*1234.*Docker",
r"LM.*Studio.*Docker.*Mac",
+ # OpenAI-compatible endpoint tokens (#3878)
+ r"Error type: openai_connection_refused",
+ r"Error type: openai_timeout",
],
ErrorCategory.MODEL_ERROR: [
r"Model.*not found",
@@ -53,6 +56,12 @@ class ErrorReporter:
r"'<' not supported between",
r"No auth credentials found",
r"401.*API key",
+ # OpenAI-compatible endpoint tokens (#3878)
+ r"Error type: openai_auth",
+ r"Error type: openai_permission_denied",
+ r"Error type: openai_model_not_found",
+ r"Error type: openai_bad_request",
+ r"Error type: openai_unknown",
],
ErrorCategory.RATE_LIMIT_ERROR: [
r"429.*resource.*exhausted",
diff --git a/src/local_deep_research/error_handling/openai_compat_errors.py b/src/local_deep_research/error_handling/openai_compat_errors.py
new file mode 100644
index 0000000000..d6aefdfa77
--- /dev/null
+++ b/src/local_deep_research/error_handling/openai_compat_errors.py
@@ -0,0 +1,187 @@
+"""Friendly runtime-error rewriter for OpenAI-compatible LLM endpoints.
+
+When LM Studio, vLLM, llama.cpp server, OpenRouter, or any other OpenAI-compatible
+provider fails at request time, the underlying `openai.*` / `httpx.*` exception
+typically does not name the provider, configured base URL, or model in its
+message. This helper walks the cause chain to find the root SDK exception and
+produces a message that includes that context, while preserving the existing
+``Error type: <code>`` token convention used downstream in research_service.py
+and ErrorReporter.
+
+The helper deliberately does NOT introduce a new exception class -- the rest of
+the pipeline is string-based today and tokens are how Sites B and C
+communicate.
+"""
+
+from __future__ import annotations
+
+from urllib.parse import urlparse, urlunparse
+
+import httpx
+import openai
+
+
+def _strip_credentials(base_url: str | None) -> str:
+ """Return ``base_url`` with any userinfo (``user:password@``) removed.
+
+ Users sometimes embed an API key directly in the base URL (e.g.
+ ``https://user:key@host/v1``). We must never echo that back to the UI or
+ logs. Falsy / unparseable inputs are returned as ``"<unknown>"``.
+ """
+ if not base_url:
+ return "<unknown>"
+ try:
+ parsed = urlparse(base_url)
+ except Exception:
+ return "<unknown>"
+ if not parsed.netloc:
+ return base_url
+ host = parsed.hostname or ""
+ if parsed.port:
+ host = f"{host}:{parsed.port}"
+ return urlunparse(parsed._replace(netloc=host)) or "<unknown>"
+
+
+def _walk_cause(exc: BaseException) -> BaseException:
+ """Walk ``__cause__`` / ``__context__`` to find the deepest non-wrapper
+ exception, with a cycle guard.
+
+ LangChain often wraps the underlying ``openai.*`` exception in a generic
+ ``Exception`` or ``RuntimeError``; we need the original class to dispatch
+ on. If the walk doesn't find anything more specific, the original is
+ returned.
+ """
+ seen: set[int] = set()
+ cur: BaseException | None = exc
+ deepest: BaseException = exc
+ while cur is not None and id(cur) not in seen:
+ seen.add(id(cur))
+ deepest = cur
+ cur = cur.__cause__ or cur.__context__
+ return deepest
+
+
+_DOCKER_HINT = (
+ " (from inside Docker, localhost is the container itself -- use "
+ "host.docker.internal, the host IP, or run with --network=host to share "
+ "the host network namespace)"
+)
+
+
+def _dispatch(
+ root: BaseException, provider: str, base_url: str, model: str
+) -> tuple[str, str]:
+ """Map a root exception to ``(error_code_token, friendly_message)``.
+
+ Returns ``("openai_unknown", <generic message>)`` for any exception we don't
+ recognise; callers should still suffix the original ``exc!s`` so no detail
+ is lost.
+ """
+
+ def _is(cls_name: str) -> bool:
+ cls = getattr(openai, cls_name, None)
+ return cls is not None and isinstance(root, cls)
+
+ # Timeout family -- must be checked BEFORE APIConnectionError because
+ # openai.APITimeoutError subclasses APIConnectionError in openai>=1.x.
+ if _is("APITimeoutError") or isinstance(root, httpx.ReadTimeout):
+ return (
+ "openai_timeout",
+ f"{provider} at {base_url} did not respond in time. The server "
+ "may be loading a model or overloaded.",
+ )
+
+ # Connection-refused / network-unreachable family
+ if _is("APIConnectionError") or isinstance(root, httpx.ConnectError):
+ return (
+ "openai_connection_refused",
+ f"Cannot reach {provider} at {base_url}. Check that the server "
+ f"is running and the URL is correct.{_DOCKER_HINT}",
+ )
+
+ # Auth
+ if _is("AuthenticationError"):
+ return (
+ "openai_auth",
+ f"{provider} rejected the API key for {base_url}. Local servers "
+ "usually accept any non-empty key; remote providers need a valid "
+ "key.",
+ )
+
+ # Permission denied
+ if _is("PermissionDeniedError"):
+ return (
+ "openai_permission_denied",
+ f"{provider} denied access at {base_url} for model '{model}'.",
+ )
+
+ # Model not found (404 from OpenAI-compatible servers)
+ if _is("NotFoundError"):
+ return (
+ "openai_model_not_found",
+ f"{provider} at {base_url} does not have model '{model}'. Pick a "
+ f"model currently loaded in {provider}.",
+ )
+
+ # Bad request (400)
+ if _is("BadRequestError"):
+ return (
+ "openai_bad_request",
+ f"{provider} rejected the request to {base_url} for model "
+ f"'{model}'.",
+ )
+
+ # Any other openai SDK error
+ if _is("APIError"):
+ return (
+ "openai_unknown",
+ f"{provider} at {base_url} returned an error for model '{model}'.",
+ )
+
+ # Not an openai/httpx class we recognise -- caller should fall through.
+ return (
+ "openai_unknown",
+ f"{provider} at {base_url} returned an error for model '{model}'.",
+ )
+
+
+def is_openai_compat_runtime_error(exc: BaseException) -> bool:
+ """Return True iff ``exc`` (or any exception in its cause chain) is an
+ ``openai.*`` / ``httpx.*`` runtime error we can rewrite.
+
+ Used at Site B in research_service.py to decide whether to call
+ :func:`friendly_openai_compatible_error` instead of the existing
+ string-keyword branches.
+ """
+ root = _walk_cause(exc)
+ if isinstance(root, openai.APIError):
+ return True
+ if isinstance(root, (httpx.ConnectError, httpx.ReadTimeout)):
+ return True
+ return False
+
+
+def friendly_openai_compatible_error(
+ exc: BaseException,
+ *,
+ provider: str,
+ base_url: str | None,
+ model: str | None,
+) -> str:
+ """Build a user-facing error message for an OpenAI-compatible failure.
+
+ Returns a string of the form::
+
+ <friendly message> (Error type: <code>) | Details: <original exc>
+
+ where ``<code>`` is one of the ``openai_*`` tokens that Site C and
+ :class:`~local_deep_research.error_handling.error_reporter.ErrorReporter`
+ recognise. The original exception text is always preserved in the
+ ``Details:`` suffix so the user (and our logs) never lose information.
+ """
+ redacted = _strip_credentials(base_url)
+ model_repr = model or "<unspecified>"
+ provider_repr = provider or "<unknown provider>"
+ root = _walk_cause(exc)
+ code, friendly = _dispatch(root, provider_repr, redacted, model_repr)
+ return f"{friendly} (Error type: {code}) | Details: {exc!s}"
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 479d49a414..c373c60fd5 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -18,6 +18,10 @@ from ...constants import ResearchStatus
from ...database.models import ResearchHistory, ResearchStrategy
from ...database.session_context import get_user_db_session
from ...database.thread_local_session import thread_cleanup
+from ...error_handling.openai_compat_errors import (
+ friendly_openai_compatible_error,
+ is_openai_compat_runtime_error,
+)
from ...error_handling.report_generator import ErrorReportGenerator
from ...utilities.thread_context import set_search_context
from ...report_generator import IntegratedReportGenerator
@@ -733,6 +737,24 @@ def run_research_process(research_id, query, mode, **kwargs):
error_message = str(search_error)
error_type = "unknown"
+ # OpenAI-compatible runtime failures (LM Studio / vLLM / llama.cpp
+ # server / OpenRouter / custom endpoint) -- rewrite to a message
+ # that names the provider, base URL, and model (#3878).
+ if model_provider in {
+ "openai_endpoint",
+ "lmstudio",
+ "llamacpp",
+ "openai",
+ "openrouter",
+ } and is_openai_compat_runtime_error(search_error):
+ rewritten = friendly_openai_compatible_error(
+ search_error,
+ provider=model_provider,
+ base_url=custom_endpoint,
+ model=model,
+ )
+ raise RuntimeError(rewritten) from search_error
+
# Extract error details for common issues
if "status code: 503" in error_message:
error_message = "Ollama AI service is unavailable (HTTP 503). Please check that Ollama is running properly on your system."
@@ -1512,6 +1534,37 @@ def run_research_process(research_id, query, mode, **kwargs):
error_context = {
"solution": "Check API configuration and credentials."
}
+ # OpenAI-compatible runtime tokens (#3878). The friendly message
+ # built by friendly_openai_compatible_error() already names the
+ # provider, base URL, and model -- keep it as-is.
+ elif "Error type: openai_connection_refused" in user_friendly_error:
+ error_context = {
+ "solution": "Start your LLM server (LM Studio / vLLM / llama.cpp server) and verify the base URL in Settings -> LLM Providers."
+ }
+ elif "Error type: openai_timeout" in user_friendly_error:
+ error_context = {
+ "solution": "The server is reachable but slow -- it may be loading a model. Retry, or increase the request timeout."
+ }
+ elif "Error type: openai_auth" in user_friendly_error:
+ error_context = {
+ "solution": "Set or correct the API key for this provider in Settings -> LLM Providers. Local servers usually accept any non-empty key."
+ }
+ elif "Error type: openai_permission_denied" in user_friendly_error:
+ error_context = {
+ "solution": "Your API key is valid but lacks access to this model. Pick a model your account/server is permitted to use."
+ }
+ elif "Error type: openai_model_not_found" in user_friendly_error:
+ error_context = {
+ "solution": "The model id is not loaded on this server. Pick a currently-loaded model in the provider's UI/config."
+ }
+ elif "Error type: openai_bad_request" in user_friendly_error:
+ error_context = {
+ "solution": "The server rejected the request. Check the model id and any provider-specific parameters."
+ }
+ elif "Error type: openai_unknown" in user_friendly_error:
+ error_context = {
+ "solution": "Check the provider's logs for the full error and verify the base URL / model id."
+ }
# Generate enhanced error report for failed research
enhanced_report_content = None
diff --git a/tests/error_handling/test_openai_compat_errors.py b/tests/error_handling/test_openai_compat_errors.py
new file mode 100644
index 0000000000..a010dcc14d
--- /dev/null
+++ b/tests/error_handling/test_openai_compat_errors.py
@@ -0,0 +1,318 @@
+"""Tests for openai_compat_errors helper and its integration with
+``ErrorReporter`` (#3878).
+
+These tests construct ``openai`` / ``httpx`` exceptions directly (no network
+calls) and check that the rewritten messages and ``Error type: <code>`` tokens
+match the spec in the issue.
+"""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+from openai import (
+ APIConnectionError,
+ APITimeoutError,
+ AuthenticationError,
+ BadRequestError,
+ NotFoundError,
+ PermissionDeniedError,
+)
+
+from local_deep_research.error_handling.error_reporter import (
+ ErrorCategory,
+ ErrorReporter,
+)
+from local_deep_research.error_handling.openai_compat_errors import (
+ _strip_credentials,
+ _walk_cause,
+ friendly_openai_compatible_error,
+ is_openai_compat_runtime_error,
+)
+
+
+def _req(
+ url: str = "http://localhost:9999/v1/chat/completions",
+) -> httpx.Request:
+ return httpx.Request("POST", url)
+
+
+def _resp(status: int, body: dict | None = None) -> httpx.Response:
+ return httpx.Response(status, request=_req(), json=body or {})
+
+
+# ---------------------------------------------------------------------------
+# Acceptance criterion 4: redaction
+# ---------------------------------------------------------------------------
+
+
+class TestStripCredentials:
+ def test_strips_userinfo(self):
+ assert (
+ _strip_credentials("https://user:[email protected]/v1")
+ == "https://example.com/v1"
+ )
+
+ def test_strips_userinfo_keeps_port(self):
+ assert (
+ _strip_credentials("https://u:[email protected]:8443/v1")
+ == "https://example.com:8443/v1"
+ )
+
+ def test_no_userinfo_passes_through(self):
+ assert (
+ _strip_credentials("http://localhost:1234/v1")
+ == "http://localhost:1234/v1"
+ )
+
+ def test_empty_returns_unknown_marker(self):
+ assert _strip_credentials("") == "<unknown>"
+ assert _strip_credentials(None) == "<unknown>"
+
+
+# ---------------------------------------------------------------------------
+# Cause-chain walker
+# ---------------------------------------------------------------------------
+
+
+class TestWalkCause:
+ def test_returns_input_when_no_cause(self):
+ exc = RuntimeError("flat")
+ assert _walk_cause(exc) is exc
+
+ def test_walks_to_deepest(self):
+ root = APIConnectionError(message="conn", request=_req())
+ try:
+ try:
+ raise root
+ except Exception as e:
+ raise RuntimeError("middle") from e
+ except RuntimeError as e:
+ try:
+ raise ValueError("outer") from e
+ except ValueError as outer:
+ assert _walk_cause(outer) is root
+
+ def test_cycle_safe(self):
+ a = RuntimeError("a")
+ b = RuntimeError("b")
+ a.__cause__ = b
+ b.__cause__ = a
+ # Must terminate; the deepest reached before cycle is detected wins.
+ assert _walk_cause(a) in (a, b)
+
+
+# ---------------------------------------------------------------------------
+# Acceptance criterion 1: connection-refused naming
+# ---------------------------------------------------------------------------
+
+
+class TestConnectionRefused:
+ def test_openai_api_connection_error(self):
+ exc = APIConnectionError(message="conn", request=_req())
+ msg = friendly_openai_compatible_error(
+ exc,
+ provider="lmstudio",
+ base_url="http://localhost:9999/v1",
+ model="qwen2.5-7b",
+ )
+ assert "Cannot reach lmstudio at http://localhost:9999/v1" in msg
+ assert "Error type: openai_connection_refused" in msg
+ assert "Details:" in msg
+
+ def test_httpx_connect_error_through_langchain_wrapper(self):
+ root = httpx.ConnectError("All connection attempts failed")
+ try:
+ try:
+ raise root
+ except Exception as e:
+ raise RuntimeError("LangChain wrapped") from e
+ except RuntimeError as wrapped:
+ msg = friendly_openai_compatible_error(
+ wrapped,
+ provider="openai_endpoint",
+ base_url="http://localhost:1234/v1",
+ model="any-model",
+ )
+ assert "Cannot reach openai_endpoint at http://localhost:1234/v1" in msg
+ assert "Error type: openai_connection_refused" in msg
+
+
+# ---------------------------------------------------------------------------
+# Acceptance criterion 2: model-not-found naming
+# ---------------------------------------------------------------------------
+
+
+class TestModelNotFound:
+ def test_notfound_names_provider_url_model(self):
+ exc = NotFoundError(
+ message="model 'typo-model' does not exist",
+ response=_resp(404),
+ body=None,
+ )
+ msg = friendly_openai_compatible_error(
+ exc,
+ provider="lmstudio",
+ base_url="http://localhost:1234/v1",
+ model="typo-model",
+ )
+ assert "lmstudio at http://localhost:1234/v1" in msg
+ assert "'typo-model'" in msg
+ assert "Error type: openai_model_not_found" in msg
+
+
+# ---------------------------------------------------------------------------
+# Acceptance criterion 3: auth naming
+# ---------------------------------------------------------------------------
+
+
+class TestAuth:
+ def test_auth_names_provider_and_url(self):
+ exc = AuthenticationError(
+ message="invalid api key",
+ response=_resp(401),
+ body=None,
+ )
+ msg = friendly_openai_compatible_error(
+ exc,
+ provider="openai_endpoint",
+ base_url="https://api.openai.com/v1",
+ model="gpt-4o-mini",
+ )
+ assert "openai_endpoint rejected the API key" in msg
+ assert "https://api.openai.com/v1" in msg
+ assert "Error type: openai_auth" in msg
+
+
+# ---------------------------------------------------------------------------
+# Acceptance criterion 4: userinfo never leaks into the surfaced message
+# ---------------------------------------------------------------------------
+
+
+class TestNoCredentialLeak:
+ def test_userinfo_stripped_from_friendly_text(self):
+ exc = APIConnectionError(message="conn", request=_req())
+ leaked_key = "supersecretkey1234567890"
+ msg = friendly_openai_compatible_error(
+ exc,
+ provider="openai_endpoint",
+ base_url=f"https://u:{leaked_key}@hosted.example.com/v1",
+ model="m",
+ )
+ # The userinfo segment must NOT survive into the friendly portion of
+ # the message. We split on the Details: suffix because the original
+ # exception text is preserved there verbatim (and in practice does not
+ # carry the URL, but if a future exception did, we'd still want this
+ # test to guard the rewritten half).
+ friendly_half = msg.split("| Details:")[0]
+ assert leaked_key not in friendly_half
+ assert "u:" not in friendly_half
+
+
+# ---------------------------------------------------------------------------
+# Acceptance criterion 5: ErrorReporter category mapping
+# ---------------------------------------------------------------------------
+
+
+class TestErrorReporterCategorisation:
+ @pytest.fixture
+ def reporter(self) -> ErrorReporter:
+ return ErrorReporter()
+
+ @pytest.mark.parametrize(
+ ("token", "expected"),
+ [
+ ("openai_connection_refused", ErrorCategory.CONNECTION_ERROR),
+ ("openai_timeout", ErrorCategory.CONNECTION_ERROR),
+ ("openai_auth", ErrorCategory.MODEL_ERROR),
+ ("openai_permission_denied", ErrorCategory.MODEL_ERROR),
+ ("openai_model_not_found", ErrorCategory.MODEL_ERROR),
+ ("openai_bad_request", ErrorCategory.MODEL_ERROR),
+ ("openai_unknown", ErrorCategory.MODEL_ERROR),
+ ],
+ )
+ def test_token_to_category(
+ self, reporter: ErrorReporter, token: str, expected: ErrorCategory
+ ):
+ message = f"Some friendly text. (Error type: {token}) | Details: boom"
+ assert reporter.categorize_error(message) == expected
+
+
+# ---------------------------------------------------------------------------
+# Helper-detector
+# ---------------------------------------------------------------------------
+
+
+class TestIsOpenAICompatRuntimeError:
+ def test_yes_for_openai_class(self):
+ exc = APITimeoutError(request=_req())
+ assert is_openai_compat_runtime_error(exc) is True
+
+ def test_yes_for_wrapped_openai_class(self):
+ root = NotFoundError(message="missing", response=_resp(404), body=None)
+ try:
+ try:
+ raise root
+ except Exception as e:
+ raise RuntimeError("wrap") from e
+ except RuntimeError as wrapped:
+ assert is_openai_compat_runtime_error(wrapped) is True
+
+ def test_yes_for_httpx_connect_error(self):
+ assert (
+ is_openai_compat_runtime_error(httpx.ConnectError("nope")) is True
+ )
+
+ def test_no_for_unrelated_exception(self):
+ assert is_openai_compat_runtime_error(ValueError("unrelated")) is False
+
+
+# ---------------------------------------------------------------------------
+# Additional class coverage (the four non-AC tokens still need to round-trip)
+# ---------------------------------------------------------------------------
+
+
+class TestAdditionalDispatch:
+ def test_timeout(self):
+ exc = APITimeoutError(request=_req())
+ msg = friendly_openai_compatible_error(
+ exc,
+ provider="vllm",
+ base_url="http://localhost:8000/v1",
+ model="llama-3-8b",
+ )
+ assert "Error type: openai_timeout" in msg
+ assert "did not respond in time" in msg
+
+ def test_permission_denied(self):
+ exc = PermissionDeniedError(
+ message="forbidden", response=_resp(403), body=None
+ )
+ msg = friendly_openai_compatible_error(
+ exc,
+ provider="openai_endpoint",
+ base_url="https://api.example.com/v1",
+ model="gpt-4o",
+ )
+ assert "Error type: openai_permission_denied" in msg
+ assert "'gpt-4o'" in msg
+
+ def test_bad_request(self):
+ exc = BadRequestError(message="bad", response=_resp(400), body=None)
+ msg = friendly_openai_compatible_error(
+ exc,
+ provider="lmstudio",
+ base_url="http://localhost:1234/v1",
+ model="m",
+ )
+ assert "Error type: openai_bad_request" in msg
+
+ def test_falls_back_to_unknown_for_unrelated(self):
+ msg = friendly_openai_compatible_error(
+ ValueError("just a value error"),
+ provider="lmstudio",
+ base_url="http://localhost:1234/v1",
+ model="m",
+ )
+ assert "Error type: openai_unknown" in msg
+ assert "Details: just a value error" in msg