fix(providers): sum compound durations in 'try again in' retry hints

OpenAI-style 429 bodies report waits as Go durations such as 'try again in 1m30s'. The parser only read the first component, so the retry slept 60s instead of 90s and spent an attempt on a guaranteed second 429. Sum every h/m/s/ms component while keeping the existing precedence and single-unit formats.
This commit is contained in:
bob authored and Xubin Ren committed 2026-10-03 19:46:51 +08:00
1 parent d8c3b3cab5
commit 0848565067
2 files changed
+35

No files matched your search

+12
View File
@@ -1679,6 +1679,8 @@ class LLMProvider(ABC):
r"retry[_-]?after[\"'\s:=]+(\d+(?:\.\d+)?)",
)
for idx, pattern in enumerate(patterns):
if idx == 1 and (compound := cls._extract_compound_try_again_in(text)) is not None:
return compound
match = re.search(pattern, text)
if not match:
continue
@@ -1687,6 +1689,16 @@ class LLMProvider(ABC):
return cls._to_retry_seconds(value, unit)
return None
@classmethod
def _extract_compound_try_again_in(cls, text: str) -> float | None:
"""Sum Go-style durations such as OpenAI's ``try again in 1m30s``."""
match = re.search(r"try again in\s+((?:\d+(?:\.\d+)?(?:ms|h|m|s))+)(?![a-z])", text)
if not match:
return None
unit_seconds = {"ms": 0.001, "s": 1.0, "m": 60.0, "h": 3600.0}
parts = re.findall(r"(\d+(?:\.\d+)?)(ms|h|m|s)", match.group(1))
return max(0.1, sum(float(value) * unit_seconds[unit] for value, unit in parts))
@classmethod
def _to_retry_seconds(cls, value: float, unit: str | None = None) -> float:
normalized_unit = (unit or "s").lower()
+23
View File
@@ -621,6 +621,29 @@ def test_extract_retry_after_supports_common_provider_formats() -> None:
assert LLMProvider._extract_retry_after("retry-after: 20") == 20.0
@pytest.mark.parametrize(
("message", "expected"),
[
("Rate limit reached for gpt-x. Please try again in 1m30s.", 90.0),
("Please try again in 2m0.5s", 120.5),
("Please try again in 1h2m3s", 3723.0),
("Please try again in 6m0s. Visit https://example.com", 360.0),
("Please try again in 1.5s", 1.5),
("Please try again in 20ms", 0.1),
("Please try again in 30 seconds", 30.0),
("Please try again in 2 minutes", 120.0),
],
)
def test_extract_retry_after_sums_compound_durations(message: str, expected: float) -> None:
assert LLMProvider._extract_retry_after(message) == pytest.approx(expected)
def test_extract_retry_after_prefers_retry_after_over_try_again_in() -> None:
message = "retry after 5s; otherwise try again in 1m30s"
assert LLMProvider._extract_retry_after(message) == 5.0
def test_extract_retry_after_from_headers_supports_numeric_and_http_date() -> None:
assert LLMProvider._extract_retry_after_from_headers({"Retry-After": "20"}) == 20.0
assert LLMProvider._extract_retry_after_from_headers({"retry-after": "20"}) == 20.0