Skip to content

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

fix: recover model catalog and provider transport (#888)

Bingxi Zhaof12d6a8a1fb7
diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.py
index cd83bfba5..39cd7bb44 100644
--- a/deeptutor/agents/chat/agent_loop.py
+++ b/deeptutor/agents/chat/agent_loop.py
@@ -27,6 +27,7 @@ tells the frontend how to render that round's text.
from __future__ import annotations
+import asyncio
from contextlib import suppress
from dataclasses import dataclass, field
import logging
@@ -42,13 +43,14 @@ from deeptutor.core.agentic.usage import message_content_chars, record_streamed_
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_id
-from deeptutor.services.llm import clean_thinking_tags
+from deeptutor.services.llm import LLMProviderTransportError, clean_thinking_tags
from deeptutor.services.llm.capabilities import threads_session_id
from deeptutor.services.llm.multimodal import should_degrade_to_text, strip_image_parts_inplace
from deeptutor.services.llm.request_compat import (
is_image_input_unsupported,
is_stream_options_unsupported,
is_tool_schema_unsupported,
+ is_transient_transport_error,
)
if TYPE_CHECKING: # pragma: no cover
@@ -65,6 +67,11 @@ LOOP_STAGE = "responding"
# still request tools, making the total upper bound ``exploration + 4``.
MAX_SETTLEMENT_ROUNDS = 3
_TRUNCATED_FINISH_REASONS = frozenset({"length", "max_tokens", "max_output_tokens"})
+# The SDK already retries failures that happen before response headers. These
+# short outer retries also cover SSE connections that fail before yielding any
+# user-visible output. Once output is visible, replay is unsafe because it can
+# duplicate prose or tool calls.
+_PROVIDER_RETRY_DELAYS = (0.5, 1.5)
_THINK_OPEN_RE = re.compile(r"<\s*think(?:ing)?\b[^>]*>", re.IGNORECASE)
_THINK_CLOSE_RE = re.compile(r"<\s*/\s*think(?:ing)?\s*>", re.IGNORECASE)
@@ -631,99 +638,169 @@ class AgentLoop:
carried = self._last_request.tool_schemas
self._last_request = LLMRequestSnapshot(messages=list(messages), tool_schemas=carried)
- # Providers (esp. Gemini OpenAI-compat) may attach ``usage`` to more
- # than one stream chunk. Keep the latest frame; it is recorded once
- # after the stream via ``record_streamed_usage``.
- usage_seen: Any = None
- text_parts: list[str] = []
- tool_acc: dict[int, dict[str, str]] = {}
- output_chars = 0
- finish_reason = ""
- think_filter = InlineThinkFilter()
- # DeepSeek's Anthropic-compatible endpoint can interleave user-facing
- # prose and DSML tool calls in one content stream. Strip only the DSML
- # blocks incrementally; the raw chunks stay in ``text_parts`` for the
- # post-stream parser and the surrounding prose remains visible.
- dsml_filter = DSMLStreamFilter()
- answer_content_emitted = False
- visible_text_parts: list[str] = []
chunk_meta = merge_trace_metadata(trace_meta, {"trace_kind": "llm_chunk"})
- async def _emit_segments(segments: list[tuple[str, str]]) -> None:
- nonlocal answer_content_emitted
- for kind, segment in segments:
- if kind == "content":
- visible_text_parts.append(segment)
- if segment.strip():
- answer_content_emitted = True
- await self.stream.content(
- segment, source="chat", stage=stage, metadata=chunk_meta
+ for attempt in range(len(_PROVIDER_RETRY_DELAYS) + 1):
+ # Providers (esp. Gemini OpenAI-compat) may attach ``usage`` to
+ # more than one stream chunk. Keep the latest frame and record it
+ # once, only after a successful attempt.
+ usage_seen: Any = None
+ text_parts: list[str] = []
+ tool_acc: dict[int, dict[str, str]] = {}
+ output_chars = 0
+ finish_reason = ""
+ think_filter = InlineThinkFilter()
+ # DeepSeek's Anthropic-compatible endpoint can interleave
+ # user-facing prose and DSML calls in one content stream.
+ dsml_filter = DSMLStreamFilter()
+ answer_content_emitted = False
+ visible_text_parts: list[str] = []
+ output_emitted = False
+
+ async def _emit_segments(segments: list[tuple[str, str]]) -> None:
+ nonlocal answer_content_emitted, output_emitted
+ for kind, segment in segments:
+ output_emitted = True
+ if kind == "content":
+ visible_text_parts.append(segment)
+ if segment.strip():
+ answer_content_emitted = True
+ await self.stream.content(
+ segment, source="chat", stage=stage, metadata=chunk_meta
+ )
+ else:
+ await self.stream.thinking(
+ segment, source="chat", stage=stage, metadata=chunk_meta
+ )
+
+ response_stream = None
+ try:
+ response_stream = await self._create_response_stream(kwargs, trace_meta, stage)
+ async for chunk in response_stream:
+ usage = getattr(chunk, "usage", None)
+ if usage is not None:
+ usage_seen = usage
+ choices = getattr(chunk, "choices", None) or []
+ if not choices:
+ continue
+ choice = choices[0]
+ if getattr(choice, "finish_reason", None):
+ finish_reason = str(choice.finish_reason)
+ delta = getattr(choice, "delta", None)
+ if delta is None:
+ continue
+
+ reasoning_text = getattr(delta, "reasoning_content", None) or getattr(
+ delta,
+ "reasoning",
+ None,
)
- else:
- await self.stream.thinking(
- segment, source="chat", stage=stage, metadata=chunk_meta
+ if reasoning_text:
+ output_chars += len(reasoning_text)
+ output_emitted = True
+ await self.stream.thinking(
+ reasoning_text, source="chat", stage=stage, metadata=chunk_meta
+ )
+
+ content = getattr(delta, "content", None)
+ if content:
+ output_chars += len(content)
+ text_parts.append(content)
+ # Every round's text streams to the user; inline
+ # <think> segments remain trace-only while DSML markup
+ # and its argument payload never enter either channel.
+ visible_content = dsml_filter.feed(content)
+ if visible_content:
+ await _emit_segments(think_filter.feed(visible_content))
+
+ for tc_delta in getattr(delta, "tool_calls", None) or []:
+ index = int(getattr(tc_delta, "index", 0) or 0)
+ acc = tool_acc.setdefault(
+ index,
+ {"id": "", "name": "", "arguments": ""},
+ )
+ tcid = getattr(tc_delta, "id", None)
+ if tcid:
+ acc["id"] += str(tcid)
+ fn = getattr(tc_delta, "function", None)
+ if fn is None:
+ continue
+ name = getattr(fn, "name", None)
+ arguments = getattr(fn, "arguments", None)
+ if name:
+ acc["name"] += str(name)
+ output_chars += len(str(name))
+ if arguments:
+ acc["arguments"] += str(arguments)
+ output_chars += len(str(arguments))
+ except Exception as exc:
+ if not is_transient_transport_error(exc):
+ raise
+ can_retry = not output_emitted and attempt < len(_PROVIDER_RETRY_DELAYS)
+ if can_retry:
+ logger.warning(
+ "provider stream failed before output (attempt %d/%d); retrying: %s",
+ attempt + 1,
+ len(_PROVIDER_RETRY_DELAYS) + 1,
+ exc,
)
-
- response_stream = await self._create_response_stream(kwargs, trace_meta, stage)
- try:
- async for chunk in response_stream:
- usage = getattr(chunk, "usage", None)
- if usage is not None:
- usage_seen = usage
- choices = getattr(chunk, "choices", None) or []
- if not choices:
- continue
- choice = choices[0]
- if getattr(choice, "finish_reason", None):
- finish_reason = str(choice.finish_reason)
- delta = getattr(choice, "delta", None)
- if delta is None:
+ await self.stream.progress(
+ self.pipeline._t(
+ "notices.provider_retry",
+ default="The model provider connection was interrupted; retrying.",
+ ),
+ source="chat",
+ stage=stage,
+ metadata=merge_trace_metadata(
+ trace_meta,
+ {
+ "trace_kind": "warning",
+ "error_code": "provider_transport",
+ "retry_attempt": attempt + 1,
+ },
+ ),
+ )
+ await asyncio.sleep(_PROVIDER_RETRY_DELAYS[attempt])
continue
- reasoning_text = getattr(delta, "reasoning_content", None) or getattr(
- delta,
- "reasoning",
- None,
+ partial_response = output_emitted
+ await self.stream.progress(
+ "",
+ source="chat",
+ stage=stage,
+ metadata=merge_trace_metadata(
+ trace_meta,
+ {
+ "trace_kind": "call_status",
+ "call_state": "failed",
+ "error_code": "provider_transport",
+ "retryable": True,
+ "partial_response": partial_response,
+ },
+ ),
)
- if reasoning_text:
- output_chars += len(reasoning_text)
- await self.stream.thinking(
- reasoning_text, source="chat", stage=stage, metadata=chunk_meta
- )
-
- content = getattr(delta, "content", None)
- if content:
- output_chars += len(content)
- text_parts.append(content)
- # Every round's text streams to the user; inline <think>
- # segments remain trace-only while DSML markup and its
- # argument payload never enter either visible channel.
- visible_content = dsml_filter.feed(content)
- if visible_content:
- await _emit_segments(think_filter.feed(visible_content))
-
- for tc_delta in getattr(delta, "tool_calls", None) or []:
- index = int(getattr(tc_delta, "index", 0) or 0)
- acc = tool_acc.setdefault(index, {"id": "", "name": "", "arguments": ""})
- tcid = getattr(tc_delta, "id", None)
- if tcid:
- acc["id"] += str(tcid)
- fn = getattr(tc_delta, "function", None)
- if fn is None:
- continue
- name = getattr(fn, "name", None)
- arguments = getattr(fn, "arguments", None)
- if name:
- acc["name"] += str(name)
- output_chars += len(str(name))
- if arguments:
- acc["arguments"] += str(arguments)
- output_chars += len(str(arguments))
- finally:
- close = getattr(response_stream, "close", None)
- if callable(close):
- with suppress(Exception):
- await close()
+ message = self.pipeline._t(
+ (
+ "notices.provider_stream_interrupted"
+ if partial_response
+ else "notices.provider_unavailable"
+ ),
+ default=(
+ "The model provider interrupted this response. Please retry."
+ if partial_response
+ else "Unable to reach the model provider. Please retry."
+ ),
+ )
+ raise LLMProviderTransportError(
+ message,
+ partial_response=partial_response,
+ ) from exc
+ finally:
+ close = getattr(response_stream, "close", None)
+ if callable(close):
+ with suppress(Exception):
+ await close()
+ break
dsml_tail = dsml_filter.flush()
if dsml_tail:
diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
index 6a850597c..49b28b329 100644
--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
@@ -117,6 +117,9 @@ notices:
loop_settlement: "Exploration budget reached; completing required follow-up before the final answer."
output_truncated: "The model output reached its token limit; asked it to continue."
loop_error_finish: "A step failed; answering with what has been gathered."
+ provider_retry: "The model provider connection was interrupted; retrying."
+ provider_unavailable: "Unable to reach the model provider. Please retry."
+ provider_stream_interrupted: "The model provider interrupted this response. Please retry."
context_window_guard: "Trimmed older tool results to keep this turn within the model's context window."
tool_schema_fallback: "Provider rejected native tool schemas; retrying without tools."
image_fallback: "Model does not support image input; retrying without images."
diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
index e2d6eb6de..d6044952a 100644
--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
@@ -86,6 +86,9 @@ notices:
loop_settlement: "探索轮次预算已用尽;正在完成必要收尾,然后给出最终回答。"
output_truncated: "模型输出达到 token 上限,已要求其继续完成回答。"
loop_error_finish: "某一步执行失败,将基于已收集的材料作答。"
+ provider_retry: "模型服务连接中断,正在重试。"
+ provider_unavailable: "无法连接模型服务,请重试。"
+ provider_stream_interrupted: "模型服务中断了本次回答,请重试。"
context_window_guard: "已裁剪较旧的工具结果,以确保本轮在模型上下文窗口内。"
tool_schema_fallback: "服务方拒绝了原生工具 schema;将不带工具重试。"
image_fallback: "当前模型不支持图片输入;将去除图片后重试。"
diff --git a/deeptutor/runtime/orchestrator.py b/deeptutor/runtime/orchestrator.py
index de97242d8..710fe5c30 100644
--- a/deeptutor/runtime/orchestrator.py
+++ b/deeptutor/runtime/orchestrator.py
@@ -87,10 +87,23 @@ class ChatOrchestrator:
except Exception as exc:
status = "failed"
logger.error("Capability %s failed: %s", cap_name, exc, exc_info=True)
+ error_metadata: dict[str, Any] = {
+ "turn_terminal": True,
+ "status": status,
+ }
+ error_code = getattr(exc, "error_code", None)
+ if isinstance(error_code, str) and error_code:
+ error_metadata["error_code"] = error_code
+ retryable = getattr(exc, "retryable", None)
+ if isinstance(retryable, bool):
+ error_metadata["retryable"] = retryable
+ partial_response = getattr(exc, "partial_response", None)
+ if isinstance(partial_response, bool):
+ error_metadata["partial_response"] = partial_response
await bus.error(
str(exc),
source=cap_name,
- metadata={"turn_terminal": True, "status": status},
+ metadata=error_metadata,
)
finally:
await bus.emit(
diff --git a/deeptutor/services/llm/__init__.py b/deeptutor/services/llm/__init__.py
index d6306bd10..853916f6e 100644
--- a/deeptutor/services/llm/__init__.py
+++ b/deeptutor/services/llm/__init__.py
@@ -78,6 +78,7 @@ from .exceptions import (
LLMError,
LLMModelNotFoundError,
LLMProviderError,
+ LLMProviderTransportError,
LLMRateLimitError,
LLMTimeoutError,
)
@@ -133,6 +134,7 @@ __all__ = [
"LLMError",
"LLMConfigError",
"LLMProviderError",
+ "LLMProviderTransportError",
"LLMAPIError",
"LLMTimeoutError",
"LLMRateLimitError",
diff --git a/deeptutor/services/llm/exceptions.py b/deeptutor/services/llm/exceptions.py
index 541b05290..fb63c186b 100644
--- a/deeptutor/services/llm/exceptions.py
+++ b/deeptutor/services/llm/exceptions.py
@@ -41,6 +41,17 @@ class LLMProviderError(LLMError):
pass
+class LLMProviderTransportError(LLMProviderError):
+ """A retryable provider connection or response-stream failure."""
+
+ error_code = "provider_transport"
+ retryable = True
+
+ def __init__(self, message: str, *, partial_response: bool = False):
+ super().__init__(message)
+ self.partial_response = partial_response
+
+
class LLMCircuitBreakerError(LLMError):
"""Raised when circuit breaker blocks LLM execution."""
@@ -148,6 +159,7 @@ __all__ = [
"LLMError",
"LLMConfigError",
"LLMProviderError",
+ "LLMProviderTransportError",
"LLMCircuitBreakerError",
"LLMAPIError",
"LLMTimeoutError",
diff --git a/deeptutor/services/llm/request_compat.py b/deeptutor/services/llm/request_compat.py
index 3ac08ac0a..087ff302f 100644
--- a/deeptutor/services/llm/request_compat.py
+++ b/deeptutor/services/llm/request_compat.py
@@ -2,6 +2,28 @@
from __future__ import annotations
+import httpx
+
+from .exceptions import LLMTimeoutError
+
+
+def _exception_chain(exc: Exception):
+ """Yield an exception and its wrapped causes without looping forever."""
+ pending = [exc]
+ seen: set[int] = set()
+ while pending:
+ current = pending.pop()
+ if id(current) in seen:
+ continue
+ seen.add(id(current))
+ yield current
+ nested = getattr(current, "exceptions", ())
+ if isinstance(nested, tuple):
+ pending.extend(item for item in nested if isinstance(item, Exception))
+ cause = current.__cause__ or current.__context__
+ if isinstance(cause, Exception):
+ pending.append(cause)
+
def error_text(exc: Exception) -> str:
"""Return the best available lowercase provider error body."""
@@ -70,9 +92,44 @@ def is_image_input_unsupported(exc: Exception) -> bool:
)
+def is_transient_transport_error(exc: Exception) -> bool:
+ """Return whether retrying can recover a provider transport failure.
+
+ Authentication, rate-limit, HTTP-status and response-shape errors are
+ intentionally excluded. OpenAI-compatible clients wrap httpx/httpcore
+ failures, so the complete exception chain is inspected.
+ """
+ for current in _exception_chain(exc):
+ if isinstance(
+ current,
+ (httpx.TransportError, LLMTimeoutError, TimeoutError, ConnectionError),
+ ):
+ return True
+ error_type = type(current)
+ module = error_type.__module__
+ name = error_type.__name__
+ if module.startswith("openai") and name in {
+ "APIConnectionError",
+ "APITimeoutError",
+ }:
+ return True
+ if module.startswith("httpcore") and name in {
+ "ConnectError",
+ "ConnectTimeout",
+ "ReadError",
+ "ReadTimeout",
+ "RemoteProtocolError",
+ "WriteError",
+ "WriteTimeout",
+ }:
+ return True
+ return False
+
+
__all__ = [
"error_text",
"is_image_input_unsupported",
"is_stream_options_unsupported",
+ "is_transient_transport_error",
"is_tool_schema_unsupported",
]
diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.py
index dced255af..41e9b247e 100644
--- a/tests/agents/chat/test_agent_loop.py
+++ b/tests/agents/chat/test_agent_loop.py
@@ -5,8 +5,10 @@ import json
from types import SimpleNamespace
from typing import Any
+import httpx
import pytest
+from deeptutor.agents.chat import agent_loop as agent_loop_mod
from deeptutor.agents.chat.agent_loop import InlineThinkFilter
from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
from deeptutor.capabilities.explore_context import explorer as explorer_mod
@@ -15,6 +17,7 @@ from deeptutor.core.context import Attachment, UnifiedContext
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.tool_protocol import ToolResult
+from deeptutor.services.llm import LLMProviderTransportError
async def _collect_bus_events(bus: StreamBus) -> tuple[list[StreamEvent], asyncio.Task[Any]]:
@@ -720,11 +723,11 @@ async def test_dsml_container_schema_survives_native_tool_fallback(
@pytest.mark.asyncio
-async def test_midloop_llm_failure_salvages_turn_with_forced_finish(
+async def test_midloop_transport_failure_retries_current_round(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """A mid-loop LLM failure (e.g. a timeout) after useful work must not nuke
- the turn — it is salvaged with a forced finish, not propagated."""
+ """A transport failure before the next round emits output retries that
+ round without discarding the useful tool work already in context."""
class _FailingThenFinishClient:
def __init__(self) -> None:
@@ -773,31 +776,35 @@ async def test_midloop_llm_failure_salvages_turn_with_forced_finish(
UnifiedContext(session_id="s1", user_message="Look up", enabled_tools=["web_search"]),
)
- # 1 tool round + 1 failed round + 1 forced-finish call = 3 create() calls.
+ # 1 tool round + 1 failed attempt + 1 retry = 3 create() calls.
assert client.call_count == 3
# The turn produced an answer instead of failing.
result = _result(events)
assert result.metadata["response"] == "Best-effort answer."
- # The forced-finish warning explains the salvage.
+ # The retry is explicit in the trace, and no forced-finish path was needed.
progress = [
e.content
for e in events
- if e.type == StreamEventType.PROGRESS and "A step failed" in str(e.content or "")
+ if e.type == StreamEventType.PROGRESS
+ and e.metadata.get("error_code") == "provider_transport"
]
- assert progress, "expected the loop_error_finish notice to be emitted"
+ assert progress == ["The model provider connection was interrupted; retrying."]
@pytest.mark.asyncio
-async def test_first_round_llm_failure_propagates(
+async def test_first_round_transport_failure_retries_then_becomes_structured_error(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """A failure on the very first round (no work gathered yet) has nothing to
- salvage and propagates so the orchestrator surfaces the error."""
+ """An unavailable provider gets bounded retries and a safe UI error."""
class _AlwaysFailClient:
def __init__(self) -> None:
+ self.call_count = 0
+ parent = self
+
class _Completions:
async def create(self, **kwargs):
+ parent.call_count += 1
raise TimeoutError("Request timed out.")
class _Chat:
@@ -806,14 +813,16 @@ async def test_first_round_llm_failure_propagates(
self.chat = _Chat()
+ client = _AlwaysFailClient()
pipeline = AgenticChatPipeline(language="en")
pipeline.registry = _Registry()
+ monkeypatch.setattr(agent_loop_mod, "_PROVIDER_RETRY_DELAYS", (0, 0))
monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["web_search"])
- monkeypatch.setattr(pipeline, "_build_openai_client", lambda: _AlwaysFailClient())
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
bus = StreamBus()
_events, consumer = await _collect_bus_events(bus)
- with pytest.raises(TimeoutError):
+ with pytest.raises(LLMProviderTransportError) as raised:
await pipeline.run(
UnifiedContext(session_id="s1", user_message="x", enabled_tools=["web_search"]),
bus,
@@ -821,6 +830,97 @@ async def test_first_round_llm_failure_propagates(
await bus.close()
await consumer
+ assert client.call_count == 3
+ assert raised.value.error_code == "provider_transport"
+ assert raised.value.retryable is True
+ assert raised.value.partial_response is False
+ assert str(raised.value) == "Unable to reach the model provider. Please retry."
+
+
+async def test_transport_failure_before_output_recovers_without_duplicate_content(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class _RecoveringClient:
+ def __init__(self) -> None:
+ self.call_count = 0
+ parent = self
+
+ class _Completions:
+ async def create(self, **kwargs):
+ parent.call_count += 1
+ if parent.call_count == 1:
+ raise httpx.ConnectTimeout("provider handshake timed out")
+ return _async_llm_stream([_llm_chunk(content="Recovered.")])
+
+ self.chat = SimpleNamespace(completions=_Completions())
+
+ client = _RecoveringClient()
+ pipeline = AgenticChatPipeline(language="en")
+ pipeline.registry = _Registry()
+ monkeypatch.setattr(agent_loop_mod, "_PROVIDER_RETRY_DELAYS", (0, 0))
+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: [])
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+
+ events = await _run(pipeline, UnifiedContext(session_id="s1", user_message="Hi"))
+
+ assert client.call_count == 2
+ assert _contents(events) == ["Recovered."]
+ retry_events = [
+ event
+ for event in events
+ if event.type == StreamEventType.PROGRESS
+ and event.metadata.get("error_code") == "provider_transport"
+ ]
+ assert len(retry_events) == 1
+ assert retry_events[0].metadata["retry_attempt"] == 1
+
+
+async def test_midstream_transport_failure_is_not_replayed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def _interrupted_stream():
+ yield _llm_chunk(content="Partial answer.")
+ raise httpx.ReadError("peer closed the SSE stream")
+
+ class _InterruptedClient:
+ def __init__(self) -> None:
+ self.call_count = 0
+ parent = self
+
+ class _Completions:
+ async def create(self, **kwargs):
+ parent.call_count += 1
+ return _interrupted_stream()
+
+ self.chat = SimpleNamespace(completions=_Completions())
+
+ client = _InterruptedClient()
+ pipeline = AgenticChatPipeline(language="en")
+ pipeline.registry = _Registry()
+ monkeypatch.setattr(agent_loop_mod, "_PROVIDER_RETRY_DELAYS", (0, 0))
+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: [])
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+
+ bus = StreamBus()
+ events, consumer = await _collect_bus_events(bus)
+ with pytest.raises(LLMProviderTransportError) as raised:
+ await pipeline.run(UnifiedContext(session_id="s1", user_message="Hi"), bus)
+ await bus.close()
+ await consumer
+
+ assert client.call_count == 1
+ assert _contents(events) == ["Partial answer."]
+ assert raised.value.partial_response is True
+ failed_call = next(
+ event
+ for event in events
+ if event.type == StreamEventType.PROGRESS and event.metadata.get("call_state") == "failed"
+ )
+ assert failed_call.metadata["error_code"] == "provider_transport"
+ assert failed_call.metadata["partial_response"] is True
+
@pytest.mark.asyncio
async def test_context_checkpoint_folds_completed_tool_rounds(
diff --git a/tests/runtime/test_orchestrator.py b/tests/runtime/test_orchestrator.py
index 5f75c224a..687820241 100644
--- a/tests/runtime/test_orchestrator.py
+++ b/tests/runtime/test_orchestrator.py
@@ -171,6 +171,34 @@ class TestOrchestratorErrorHandling:
assert len(done_events) == 1
assert done_events[0].metadata["status"] == "failed"
+ @pytest.mark.asyncio
+ async def test_capability_exception_preserves_safe_error_metadata(self) -> None:
+ class _StructuredError(RuntimeError):
+ error_code = "provider_transport"
+ retryable = True
+ partial_response = False
+
+ class _StructuredFailingCapability:
+ async def run(self, _context, _bus) -> None:
+ raise _StructuredError("Unable to reach the model provider. Please retry.")
+
+ orch = _make_orchestrator({"fail": _StructuredFailingCapability()})
+ events = [
+ event
+ async for event in orch.handle(
+ UnifiedContext(user_message="boom", active_capability="fail")
+ )
+ ]
+
+ error = next(event for event in events if event.type == StreamEventType.ERROR)
+ assert error.metadata == {
+ "turn_terminal": True,
+ "status": "failed",
+ "error_code": "provider_transport",
+ "retryable": True,
+ "partial_response": False,
+ }
+
# ---------------------------------------------------------------------------
# Session ID management
diff --git a/tests/services/llm/test_request_compat.py b/tests/services/llm/test_request_compat.py
index 9f1b34374..05e2b3bab 100644
--- a/tests/services/llm/test_request_compat.py
+++ b/tests/services/llm/test_request_compat.py
@@ -1,10 +1,13 @@
from __future__ import annotations
+import httpx
+
from deeptutor.services.llm.request_compat import (
error_text,
is_image_input_unsupported,
is_stream_options_unsupported,
is_tool_schema_unsupported,
+ is_transient_transport_error,
)
@@ -34,3 +37,18 @@ def test_request_compatibility_classifiers_ignore_unrelated_errors() -> None:
assert not is_stream_options_unsupported(error)
assert not is_tool_schema_unsupported(error)
assert not is_image_input_unsupported(error)
+
+
+def test_transient_transport_classifier_walks_wrapped_causes() -> None:
+ try:
+ try:
+ raise httpx.ReadError("peer closed the stream")
+ except httpx.ReadError as cause:
+ raise RuntimeError("provider request failed") from cause
+ except RuntimeError as error:
+ assert is_transient_transport_error(error)
+
+
+def test_transient_transport_classifier_excludes_provider_rejections() -> None:
+ assert not is_transient_transport_error(RuntimeError("401 invalid API key"))
+ assert not is_transient_transport_error(RuntimeError("429 rate limit exceeded"))
diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
index 272735736..c90df730c 100644
--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
@@ -2098,6 +2098,9 @@ export default function ChatPage() {
llmSelection={state.llmSelection}
llmOptionsLoading={llmOptionsLoading}
llmOptionsError={llmOptionsError}
+ onRefreshLLMOptions={() =>
+ void refreshLLMOptions({ force: true })
+ }
contextBudget={contextBudget}
selectedBookReferences={selectedBookReferences}
selectedNotebookRecords={selectedNotebookRecords}
diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx
index 7b1f85c51..35bc0537b 100644
--- a/web/components/chat/home/ChatComposer.tsx
+++ b/web/components/chat/home/ChatComposer.tsx
@@ -196,6 +196,7 @@ export default memo(function ChatComposer({
llmSelection,
llmOptionsLoading,
llmOptionsError,
+ onRefreshLLMOptions,
contextBudget = null,
selectedNotebookRecords,
selectedBookReferences,
@@ -276,6 +277,7 @@ export default memo(function ChatComposer({
llmSelection: LLMSelection | null;
llmOptionsLoading: boolean;
llmOptionsError: boolean;
+ onRefreshLLMOptions?: () => void;
/**
* Context-window breakdown measured on the last turn that reported one.
* Omitted by surfaces that don't track it (quiz follow-up) and null until
@@ -1070,6 +1072,7 @@ export default memo(function ChatComposer({
loading={llmOptionsLoading}
error={llmOptionsError}
onChange={onSelectLLM}
+ onRefresh={onRefreshLLMOptions}
/>
{contextBudget ? (
<ContextBudgetChip budget={contextBudget} />
diff --git a/web/components/chat/home/ModelSelector.tsx b/web/components/chat/home/ModelSelector.tsx
index 6c0dd4b8d..ed1828ee0 100644
--- a/web/components/chat/home/ModelSelector.tsx
+++ b/web/components/chat/home/ModelSelector.tsx
@@ -113,6 +113,7 @@ export default function ModelSelector({
helperText,
placement = "top",
onChange,
+ onRefresh,
}: {
options: LLMOption[];
activeDefault: LLMSelection | null;
@@ -125,6 +126,7 @@ export default function ModelSelector({
helperText?: string;
placement?: "top" | "bottom";
onChange: (selection: LLMSelection | null) => void;
+ onRefresh?: () => void;
}) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
@@ -158,12 +160,15 @@ export default function ModelSelector({
const defaultLabel = systemDefaultLabel || t("System default");
const defaultDetail =
systemDefaultDetail || t("Use the active default model from Settings");
+ const canRefresh = error && Boolean(onRefresh);
const disabled =
- loading || error || (options.length === 0 && !allowSystemDefault);
+ loading || (!canRefresh && (error || (options.length === 0 && !allowSystemDefault)));
const label = loading
? t("Loading models")
: error
- ? t("Models unavailable")
+ ? canRefresh
+ ? t("Refresh models")
+ : t("Models unavailable")
: allowSystemDefault && !selectedSelection
? defaultLabel
: // Official model ID, consistent with the dropdown rows.
@@ -182,8 +187,16 @@ export default function ModelSelector({
<button
type="button"
disabled={disabled}
- onClick={() => setOpen((current) => !current)}
- aria-label={t("Select model")}
+ onClick={() => {
+ if (canRefresh) {
+ setOpen(false);
+ onRefresh?.();
+ return;
+ }
+ setOpen((current) => !current);
+ }}
+ aria-label={canRefresh ? t("Refresh models") : t("Select model")}
+ title={canRefresh ? t("Refresh models") : undefined}
aria-expanded={open}
{...lingerProps}
className={`inline-flex h-8 shrink-0 items-center rounded-lg px-2 text-[14px] font-medium transition-[background-color,color,transform] duration-150 active:scale-[0.97] ${
diff --git a/web/lib/llm-options.ts b/web/lib/llm-options.ts
index 22d66fe3c..504733114 100644
--- a/web/lib/llm-options.ts
+++ b/web/lib/llm-options.ts
@@ -3,6 +3,7 @@ import { invalidateClientCache, withClientCache } from "@/lib/client-cache";
import type { LLMSelection } from "@/lib/unified-ws";
const LLM_OPTIONS_CACHE_KEY = "llm-options:list";
+const DEFAULT_LLM_OPTIONS_TIMEOUT_MS = 30_000;
export interface LLMOption extends LLMSelection {
profile_name: string;
@@ -40,21 +41,32 @@ export function sameLLMSelection(
* ``invalidateLLMOptionsCache``; pass ``force`` to bypass the cache. */
export async function listLLMOptions(options?: {
force?: boolean;
+ timeoutMs?: number;
}): Promise<LLMOptionsResponse> {
return withClientCache<LLMOptionsResponse>(
LLM_OPTIONS_CACHE_KEY,
async () => {
- const response = await apiFetch(apiUrl("/api/v1/settings/llm-options"), {
- cache: "no-store",
- });
- if (!response.ok) {
- throw new Error(`Failed to load LLM options: ${response.status}`);
+ const controller = new AbortController();
+ const timeout = setTimeout(
+ () => controller.abort(),
+ options?.timeoutMs ?? DEFAULT_LLM_OPTIONS_TIMEOUT_MS,
+ );
+ try {
+ const response = await apiFetch(apiUrl("/api/v1/settings/llm-options"), {
+ cache: "no-store",
+ signal: controller.signal,
+ });
+ if (!response.ok) {
+ throw new Error(`Failed to load LLM options: ${response.status}`);
+ }
+ const data = (await response.json()) as LLMOptionsResponse;
+ return {
+ active: data.active ?? null,
+ options: Array.isArray(data.options) ? data.options : [],
+ };
+ } finally {
+ clearTimeout(timeout);
}
- const data = (await response.json()) as LLMOptionsResponse;
- return {
- active: data.active ?? null,
- options: Array.isArray(data.options) ? data.options : [],
- };
},
{ force: options?.force },
);
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 65da72de2..1ecf87ac8 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -51,6 +51,7 @@
"Tools": "Tools",
"Loading models": "Loading models",
"Models unavailable": "Models unavailable",
+ "Refresh models": "Refresh models",
"Select model": "Select model",
"Choose model": "Choose model",
"Choose a model": "Choose a model",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 1db8593ad..97afeee0e 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -51,6 +51,7 @@
"Tools": "工具",
"Loading models": "模型加载中",
"Models unavailable": "模型不可用",
+ "Refresh models": "重新加载模型",
"Select model": "选择模型",
"Choose model": "选择模型",
"Choose a model": "请选择模型",
diff --git a/web/tests/llm-options-transport.test.ts b/web/tests/llm-options-transport.test.ts
new file mode 100644
index 000000000..738f614a0
--- /dev/null
+++ b/web/tests/llm-options-transport.test.ts
@@ -0,0 +1,45 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ invalidateLLMOptionsCache,
+ listLLMOptions,
+} from "../lib/llm-options";
+
+test("a timed-out model catalog request can be retried", async () => {
+ const originalFetch = globalThis.fetch;
+ (globalThis as { window?: unknown }).window = {
+ setTimeout,
+ clearTimeout,
+ location: { pathname: "/home", href: "" },
+ };
+ let calls = 0;
+ globalThis.fetch = async (_input, init) => {
+ calls += 1;
+ if (calls === 1) {
+ return new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => {
+ reject(new DOMException("The operation was aborted", "AbortError"));
+ });
+ });
+ }
+ return new Response(JSON.stringify({ active: null, options: [] }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ };
+
+ try {
+ await assert.rejects(
+ listLLMOptions({ force: true, timeoutMs: 5 }),
+ (error: unknown) => error instanceof DOMException && error.name === "AbortError",
+ );
+ const result = await listLLMOptions({ force: true, timeoutMs: 50 });
+ assert.deepEqual(result, { active: null, options: [] });
+ assert.equal(calls, 2);
+ } finally {
+ invalidateLLMOptionsCache();
+ globalThis.fetch = originalFetch;
+ delete (globalThis as { window?: unknown }).window;
+ }
+});