~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
fix(errors): stop the cause walk at the exception that names the failure (#6235)
Ehsan529a0e4301b1
diff --git a/changelog.d/5888.bugfix.md b/changelog.d/5888.bugfix.mdnew file mode 100644index 0000000000..217763e63f--- /dev/null+++ b/changelog.d/5888.bugfix.md@@ -0,0 +1 @@+Failures from OpenAI-compatible endpoints are named again instead of arriving as a generic unknown error. The cause-chain walk ran to the end of the chain, past the `openai` exception that carries the failure kind and down to the `ConnectionRefusedError` or `TimeoutError` beneath it, so a refused connection, a read timeout and a rejected API key all reported `openai_unknown` and the friendly rewriter never ran. The walk now stops at the first exception it can classify, and transport errors are matched against `httpx2` as well as `httpx`, which is what `openai` 3.x raises.diff --git a/src/local_deep_research/error_handling/openai_compat_errors.py b/src/local_deep_research/error_handling/openai_compat_errors.pyindex 3ad497f63f..d0f90528f9 100644--- a/src/local_deep_research/error_handling/openai_compat_errors.py+++ b/src/local_deep_research/error_handling/openai_compat_errors.py@@ -15,6 +15,7 @@ communicate.from __future__ import annotations+from types import ModuleTypefrom urllib.parse import urlparse, urlunparseimport httpx@@ -22,6 +23,19 @@ import openaifrom ..security.log_sanitizer import sanitize_error_message+# openai 3.x makes its requests through httpx2, so its transport errors are+# httpx2 classes and are unrelated to the httpx ones imported above. openai 2.x+# does not pull httpx2 in, so the import has to stay optional.+_TRANSPORT_MODULES: tuple[ModuleType, ...] = (httpx,)+try:+ import httpx2+except ImportError:+ pass+else:+ _TRANSPORT_MODULES += (httpx2,)+_CONNECT_ERRORS = tuple(m.ConnectError for m in _TRANSPORT_MODULES)+_READ_TIMEOUTS = tuple(m.ReadTimeout for m in _TRANSPORT_MODULES)+def _strip_credentials(base_url: str | None) -> str:"""Return ``base_url`` with any userinfo (``user:password@``) removed.@@ -51,20 +65,31 @@ def _strip_credentials(base_url: str | None) -> str:return urlunparse(parsed._replace(netloc=host)) or "<unknown>"+def _is_dispatchable(exc: BaseException) -> bool:+ """Return True when :func:`_dispatch` has a branch for ``exc``."""+ return isinstance(exc, (openai.APIError, *_CONNECT_ERRORS, *_READ_TIMEOUTS))++def _walk_cause(exc: BaseException) -> BaseException:- """Walk ``__cause__`` / ``__context__`` to find the deepest non-wrapper- exception, with a cycle guard.+ """Walk ``__cause__`` / ``__context__`` for the outermost exception+ :func:`_dispatch` recognises, 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.+ on. The walk stops there rather than running to the end of the chain,+ because the SDK re-raises from its transport library and the transport+ re-raises from ``httpcore`` or a bare ``OSError``: a refused connection+ ends in ``ConnectionRefusedError``, which names no provider and no failure+ kind. If nothing in the chain is recognised the deepest exception is+ returned, as before."""seen: set[int] = set()cur: BaseException | None = excdeepest: BaseException = excwhile cur is not None and id(cur) not in seen:seen.add(id(cur))+ if _is_dispatchable(cur):+ return curdeepest = curcur = cur.__cause__ or cur.__context__return deepest@@ -93,7 +118,7 @@ def _dispatch(# Timeout family -- must be checked BEFORE APIConnectionError because# openai.APITimeoutError subclasses APIConnectionError in openai>=1.x.- if _is("APITimeoutError") or isinstance(root, httpx.ReadTimeout):+ if _is("APITimeoutError") or isinstance(root, _READ_TIMEOUTS):return ("openai_timeout",f"{provider} at {base_url} did not respond in time. The server "@@ -101,7 +126,7 @@ def _dispatch()# Connection-refused / network-unreachable family- if _is("APIConnectionError") or isinstance(root, httpx.ConnectError):+ if _is("APIConnectionError") or isinstance(root, _CONNECT_ERRORS):return ("openai_connection_refused",f"Cannot reach {provider} at {base_url}. Check that the server "@@ -166,18 +191,13 @@ def _dispatch(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.+ ``openai.*`` or transport 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 existingstring-keyword branches."""- root = _walk_cause(exc)- if isinstance(root, openai.APIError):- return True- if isinstance(root, (httpx.ConnectError, httpx.ReadTimeout)):- return True- return False+ return _is_dispatchable(_walk_cause(exc))def friendly_openai_compatible_error(diff --git a/tests/error_handling/test_openai_compat_errors.py b/tests/error_handling/test_openai_compat_errors.pyindex 9caf3e8d72..8447d64c50 100644--- a/tests/error_handling/test_openai_compat_errors.py+++ b/tests/error_handling/test_openai_compat_errors.py@@ -8,7 +8,10 @@ match the spec in the issue.from __future__ import annotations+import sys+import httpx+import openaiimport pytestfrom openai import (APIConnectionError,@@ -479,3 +482,122 @@ class TestRateLimitErrorDispatch:assert (reporter.categorize_error(message) == ErrorCategory.RATE_LIMIT_ERROR)+++# ---------------------------------------------------------------------------+# #5888: the walk overshot the SDK exception, and the transport package moved+# ---------------------------------------------------------------------------+++def _chain(*excs: BaseException) -> BaseException:+ """Link ``excs`` outermost-first through ``__cause__``, return the head."""+ for outer, inner in zip(excs, excs[1:]):+ outer.__cause__ = inner+ return excs[0]+++def _sdk_transport_module():+ """Return the HTTP package the installed ``openai`` sends requests through.++ Read off the public ``DefaultHttpxClient`` so this stays independent of the+ module under test: ``openai`` 2.x subclasses ``httpx.Client`` and 3.x+ subclasses ``httpx2.Client``.+ """+ for base in openai.DefaultHttpxClient.__mro__[1:]:+ module = sys.modules.get(base.__module__.split(".")[0])+ if module is not None and hasattr(module, "ConnectError"):+ return module+ raise AssertionError("could not identify the openai transport package")+++class TestWalkCauseStopsAtTheSDKException:+ """The SDK re-raises transport failures and the transport re-raises from+ ``httpcore`` or a bare ``OSError``, so the end of a real cause chain names+ neither the provider nor the failure kind. The chains below are the ones+ observed driving ``openai.OpenAI`` against a refused port, a socket that+ accepts and never answers, and an endpoint returning 401.++ Mutation: drop the ``_is_dispatchable`` check from the walk and every test+ here reports ``openai_unknown``.+ """++ def test_connection_refused_names_the_provider(self):+ exc = _chain(+ APIConnectionError(message="Connection error.", request=_req()),+ httpx.ConnectError("All connection attempts failed"),+ ConnectionRefusedError(111, "Connection refused"),+ )+ msg = friendly_openai_compatible_error(+ exc,+ provider="lmstudio",+ base_url="http://localhost:1234/v1",+ model="qwen3-8b",+ )+ assert "Error type: openai_connection_refused" in msg+ assert "Cannot reach lmstudio" in msg++ def test_read_timeout_reports_the_timeout_token(self):+ exc = _chain(+ APITimeoutError(request=_req()),+ httpx.ReadTimeout("timed out"),+ TimeoutError("timed out"),+ )+ 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_auth_failure_survives_its_transport_wrapper(self):+ exc = _chain(+ AuthenticationError(+ message="bad key", response=_resp(401), body=None+ ),+ httpx.HTTPStatusError("401", request=_req(), response=_resp(401)),+ )+ msg = friendly_openai_compatible_error(+ exc,+ provider="openrouter",+ base_url="https://openrouter.ai/api/v1",+ model="gpt-4o",+ )+ assert "Error type: openai_auth" in msg+ assert "rejected the API key" in msg++ def test_detector_sees_the_wrapped_sdk_error(self):+ exc = _chain(+ APIConnectionError(message="Connection error.", request=_req()),+ httpx.ConnectError("All connection attempts failed"),+ ConnectionRefusedError(111, "Connection refused"),+ )+ assert is_openai_compat_runtime_error(exc) is True+++class TestTransportPackageOfTheInstalledSDK:+ """``openai`` 3.x moved from ``httpx`` to ``httpx2``, so the transport+ exceptions it raises are not instances of the ``httpx`` classes this+ module imports, and both packages can be installed side by side.++ Mutation: match ``httpx.ConnectError`` alone and both tests fail under+ ``openai`` 3.x while still passing under 2.x.+ """++ def test_connect_error_is_recognised(self):+ transport = _sdk_transport_module()+ assert (+ is_openai_compat_runtime_error(transport.ConnectError("nope"))+ is True+ )++ def test_read_timeout_reports_the_timeout_token(self):+ transport = _sdk_transport_module()+ msg = friendly_openai_compatible_error(+ transport.ReadTimeout("slow"),+ provider="llamacpp",+ base_url="http://localhost:8080/v1",+ model="mistral",+ )+ assert "Error type: openai_timeout" in msg