Skip to content

The agent that grows with you

fix(agent): timeout summary follows only the cause chain and names the real provider key

Tekniumc41de4d95f79
diff --git a/agent/api_error_summary.py b/agent/api_error_summary.py
index 4b57d961cbc..ec945a73e1f 100644
--- a/agent/api_error_summary.py
+++ b/agent/api_error_summary.py
@@ -4,6 +4,7 @@ Entitlement-failure detection, xAI subscription decoration, structured-detail co
redaction of provider error payloads.
Extracted from ``run_agent.py``; every method resolves through ``AIAgent``'s MRO unchanged.
"""
+import functools
import json
import re
from typing import Any, Dict, Optional
@@ -73,6 +74,22 @@ def _http_prefix(error: Exception) -> str:
return f"HTTP {status_code}: " if status_code else ""
+class _BindsAgentProvider:
+ """Static-style method that also receives ``provider=<agent.provider>`` when called on an agent.
+
+ Class access (``ApiErrorSummaryMixin._summarize_api_error(err)``) returns the plain function, and
+ callers keep the one-argument call shape, so one-argument stubs set on an instance still work.
+ """
+
+ def __init__(self, func):
+ self._func = func
+
+ def __get__(self, obj, objtype=None):
+ if obj is None:
+ return self._func
+ return functools.partial(self._func, provider=getattr(obj, "provider", None))
+
+
class ApiErrorSummaryMixin:
"""Provider error -> user/log-safe summary (see module docstring)."""
@@ -151,8 +168,8 @@ class ApiErrorSummaryMixin:
return ""
return str(value)
- @staticmethod
- def _summarize_api_error(error: Exception) -> str:
+ @_BindsAgentProvider
+ def _summarize_api_error(error: Exception, provider: Optional[str] = None) -> str:
"""Extract a human-readable one-liner from an API error.
Cloudflare HTML pages → ``<title>``; network/DNS failures (even SDK-wrapped) → offline hint;
@@ -172,7 +189,7 @@ class ApiErrorSummaryMixin:
current = current.__cause__ or current.__context__
from agent.timeout_error_summary import summarize_timeout_error
- timeout_summary = summarize_timeout_error(error)
+ timeout_summary = summarize_timeout_error(error, provider)
if timeout_summary is not None:
return timeout_summary
diff --git a/agent/timeout_error_summary.py b/agent/timeout_error_summary.py
index 9b116cd7dc0..04cd659d350 100644
--- a/agent/timeout_error_summary.py
+++ b/agent/timeout_error_summary.py
@@ -5,7 +5,9 @@ text: ``Request timed out.`` (openai ``APITimeoutError``) or ``timed out`` (a
raw httpx ``ReadTimeout`` mid-stream). Neither says whether a connection was
ever made, nor which setting to raise. The openai SDK wraps EVERY httpx
timeout, connect included, in ``APITimeoutError``, so the phase is read from
-the most specific exception in the ``__cause__``/``__context__`` chain.
+the most specific timeout in the explicit ``__cause__`` chain. ``__context__``
+is not followed: an HTTP error raised while a timeout was being handled is a
+different failure and keeps its own summary.
"""
from __future__ import annotations
@@ -17,9 +19,11 @@ _CONNECT_TIMEOUT_TYPES = frozenset({"ConnectTimeout", "ConnectTimeoutError"})
# The request was sent (or a stream was open) but no bytes arrived in time.
# ``APITimeoutError`` without a transport cause also lands here.
_READ_TIMEOUT_TYPES = frozenset({
- "ReadTimeout", "WriteTimeout", "PoolTimeout", "TimeoutException", "ReadTimeoutError",
- "APITimeoutError",
+ "ReadTimeout", "TimeoutException", "ReadTimeoutError", "APITimeoutError",
})
+# Waiting for a pooled connection or while uploading the request: the provider
+# never got to answer, so neither hint applies and the existing summary stays.
+_OTHER_TIMEOUT_TYPES = frozenset({"PoolTimeout", "WriteTimeout"})
def _timeout_phase(error: BaseException) -> Optional[str]:
@@ -32,13 +36,16 @@ def _timeout_phase(error: BaseException) -> Optional[str]:
name = type(current).__name__
if name in _CONNECT_TIMEOUT_TYPES:
return "connect"
- if name in _READ_TIMEOUT_TYPES:
- phase = "read"
- current = current.__cause__ or current.__context__
+ if name in _OTHER_TIMEOUT_TYPES:
+ return None
+ if name not in _READ_TIMEOUT_TYPES:
+ break
+ phase = "read"
+ current = current.__cause__
return phase
-def summarize_timeout_error(error: BaseException) -> Optional[str]:
+def summarize_timeout_error(error: BaseException, provider: Optional[str] = None) -> Optional[str]:
"""Timeout summary naming the phase and the setting to change, or ``None``
for any other error (the caller's existing summary handling then applies).
@@ -50,6 +57,7 @@ def summarize_timeout_error(error: BaseException) -> Optional[str]:
return ("Connection to the provider timed out before it was established "
"(check the base_url and network path)")
if phase == "read":
+ key = provider.strip() if isinstance(provider, str) and provider.strip() else "<provider>"
return ("Request timed out waiting for the provider to respond (if the model needs "
- "longer, raise providers.<provider>.request_timeout_seconds in config.yaml)")
+ f"longer, raise providers.{key}.request_timeout_seconds in config.yaml)")
return None
diff --git a/tests/agent/test_timeout_error_summary.py b/tests/agent/test_timeout_error_summary.py
index 38f98a640ad..4f6f7ddd214 100644
--- a/tests/agent/test_timeout_error_summary.py
+++ b/tests/agent/test_timeout_error_summary.py
@@ -31,3 +31,29 @@ def test_sdk_wrapped_timeouts_name_the_phase():
def test_non_timeout_errors_keep_their_summary():
assert ApiErrorSummaryMixin._summarize_api_error(RuntimeError("upstream exploded")) == "upstream exploded"
+
+
+def test_pool_and_write_timeouts_get_no_provider_response_hint():
+ for cause in (httpx.PoolTimeout("timed out"), httpx.WriteTimeout("timed out", request=_REQ)):
+ assert ApiErrorSummaryMixin._summarize_api_error(_sdk_timeout(cause)) == "Request timed out."
+
+
+def test_error_raised_while_handling_a_timeout_keeps_its_own_summary():
+ # __context__ is not a cause: a 401 raised inside ``except ReadTimeout`` is an auth failure.
+ resp = httpx.Response(401, request=_REQ, json={"error": {"message": "Invalid API key"}})
+ try:
+ try:
+ raise httpx.ReadTimeout("timed out", request=_REQ)
+ except httpx.ReadTimeout:
+ raise openai.AuthenticationError("Error code: 401", response=resp, body={"error": {"message": "Invalid API key"}})
+ except openai.AuthenticationError as exc:
+ assert ApiErrorSummaryMixin._summarize_api_error(exc) == "HTTP 401: Invalid API key"
+
+
+def test_read_timeout_hint_names_the_agents_provider_key():
+ class _Agent(ApiErrorSummaryMixin):
+ provider = "openrouter"
+
+ error = _sdk_timeout(httpx.ReadTimeout("timed out", request=_REQ))
+ assert "providers.openrouter.request_timeout_seconds" in _Agent()._summarize_api_error(error)
+ assert "providers.<provider>.request_timeout_seconds" in ApiErrorSummaryMixin._summarize_api_error(error)