DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(llm): say why a self-hosted model endpoint refused the connection
Bingxi Zhao (Frank)a531e650f763
diff --git a/deeptutor/agents/loop/agent_loop.py b/deeptutor/agents/loop/agent_loop.pyindex 797ca9a7d..b953ef7a2 100644--- a/deeptutor/agents/loop/agent_loop.py+++ b/deeptutor/agents/loop/agent_loop.py@@ -61,6 +61,7 @@ from deeptutor.services.llm.request_compat import (is_transient_transport_error,logged_error_text,)+from deeptutor.services.llm.utils import unreachable_endpoint_hintfrom deeptutor.services.session.provider_response_state import (normalize_provider_response_state,)@@ -1039,6 +1040,16 @@ class AgentLoop:else "Unable to reach the model provider. Please retry."),)+ if not partial_response:+ # "Please retry" is the whole story for a cloud endpoint and+ # none of it for a self-hosted one, where the connection was+ # refused because nothing is listening — or because the+ # container's own ``localhost`` is not the host running+ # Ollama. Say which, instead of leaving the reader a bare+ # ``ConnectError`` in the server log.+ hint = unreachable_endpoint_hint(self.pipeline.base_url)+ if hint:+ message = f"{message} {hint}"raise LLMProviderTransportError(message,partial_response=partial_response,diff --git a/deeptutor/services/llm/utils.py b/deeptutor/services/llm/utils.pyindex 35b7c90d5..432d14260 100644--- a/deeptutor/services/llm/utils.py+++ b/deeptutor/services/llm/utils.py@@ -10,6 +10,7 @@ from __future__ import annotationsfrom collections.abc import Mapping, Sequenceimport ipaddressimport os+from pathlib import Pathimport refrom urllib.parse import urlparse@@ -98,6 +99,43 @@ def is_local_llm_server(base_url: str, allow_private: bool | None = None) -> booreturn any(port in base_url_lower for port in LOCAL_PORTS)+def unreachable_endpoint_hint(base_url: str | None) -> str:+ """One sentence naming the likely cause of a failed connection, or ``""``.++ "Unable to reach the model provider" is the whole story for a cloud+ endpoint, and no story at all for a self-hosted one: the two ways a local+ Ollama / LM Studio / vLLM base URL fails are that nothing is listening on+ it, or that DeepTutor is in a container where ``localhost`` resolves to the+ container itself rather than the host running the model. Both are the+ user's to fix, and neither is guessable from a bare ``ConnectError`` —+ which is what the traceback in the report showed and all it showed.+ """+ if not base_url or not is_local_llm_server(base_url):+ return ""++ parsed = urlparse(base_url if "://" in base_url else f"http://{base_url}")+ hostname = (parsed.hostname or "").lower()+ port = f":{parsed.port}" if parsed.port else ""+ loopback = hostname in {"localhost", "127.0.0.1", "0.0.0.0"} # nosec B104++ if loopback and running_in_container():+ return (+ f"DeepTutor is running in a container, where {hostname}{port} is the container "+ "itself — not the machine serving the model. Point the provider's Base URL at "+ f"host.docker.internal{port} (start the container with "+ "--add-host=host.docker.internal:host-gateway on Linux)."+ )+ return (+ f"Nothing accepted a connection on {hostname}{port}. Start the local model server "+ "(for Ollama: `ollama serve`) or correct the Base URL in Settings › Models."+ )+++def running_in_container() -> bool:+ """Whether this process is inside a Docker/Podman container."""+ return any(Path(marker).exists() for marker in ("/.dockerenv", "/run/.containerenv"))++def _needs_v1_suffix(base_url: str) -> bool:"""Return True when base_url should receive a /v1 suffix."""return any(port in base_url for port in V1_SUFFIX_PORTS) and not base_url.endswith("/v1")@@ -316,6 +354,8 @@ def build_auth_headers(api_key: str | None, binding: str | None = None) -> dict[__all__ = ["sanitize_url","is_local_llm_server",+ "running_in_container",+ "unreachable_endpoint_hint","build_chat_url","build_completion_url","build_auth_headers",diff --git a/tests/services/llm/test_unreachable_endpoint_hint.py b/tests/services/llm/test_unreachable_endpoint_hint.pynew file mode 100644index 000000000..31567c357--- /dev/null+++ b/tests/services/llm/test_unreachable_endpoint_hint.py@@ -0,0 +1,50 @@+"""A refused connection to a self-hosted model must name its own cause.++"Unable to reach the model provider. Please retry." plus an ``httpcore+.ConnectError`` traceback is everything a local-Ollama user was told, and it+does not distinguish "the server is not running" from "you are in a container,+where localhost is the container".+"""++from __future__ import annotations++import pytest++from deeptutor.services.llm import utils as llm_utils+from deeptutor.services.llm.utils import unreachable_endpoint_hint+++ "base_url",+ ["https://api.openai.com/v1", "https://api.deepseek.com", "", None],+)+def test_cloud_and_missing_endpoints_get_no_hint(base_url: str | None) -> None:+ assert unreachable_endpoint_hint(base_url) == ""+++def test_local_endpoint_outside_a_container_points_at_the_server(monkeypatch) -> None:+ monkeypatch.setattr(llm_utils, "running_in_container", lambda: False)++ hint = unreachable_endpoint_hint("http://localhost:11434/v1")++ assert "localhost:11434" in hint+ assert "ollama serve" in hint+ assert "host.docker.internal" not in hint+++def test_loopback_inside_a_container_points_at_the_host(monkeypatch) -> None:+ monkeypatch.setattr(llm_utils, "running_in_container", lambda: True)++ hint = unreachable_endpoint_hint("http://127.0.0.1:11434/v1")++ assert "host.docker.internal:11434" in hint+++def test_a_host_gateway_url_is_not_told_to_use_the_gateway(monkeypatch) -> None:+ """Already on ``host.docker.internal``: the container advice is wrong here."""+ monkeypatch.setattr(llm_utils, "running_in_container", lambda: True)++ hint = unreachable_endpoint_hint("http://host.docker.internal:11434/v1")++ assert "host.docker.internal:11434" in hint+ assert "container itself" not in hint