Skip to content

Commit 1b1430f

Browse files
committed
feat(agent-loop): Show auto-fallback as a chat message with quota type
When a 429 trips the auto-fallback, surface the model switch as a persistent chat message in addition to the existing 8s toast. The message names the primary model, the fallback target, the duration, and which quota tripped (tpm / rpm / tpd / rpd) when the 429 body identifies it. The quota type is parsed from the server body via a new `parse_limit_type` helper in the generic backend, plumbed through `Throttler.record_rate_limit(limit_type=...)` and stored per-model so the agent loop can read it back when arming the fallback. If the body wording isn't recognised, the parenthetical suffix is omitted and the message degrades to the generic form. Tests cover the regex helper (Albert wordings, empty body, unknown text, per-day-before-per-minute precedence, case-insensitivity) and the throttler round-trip (record/read, success clears, latest-wins, per-model isolation, backwards-compat for callers that omit the kwarg).
1 parent 7fd1967 commit 1b1430f

6 files changed

Lines changed: 215 additions & 11 deletions

File tree

‎albert_code/cli/textual_ui/app.py‎

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -890,20 +890,66 @@ async def _show_status(self) -> None:
890890
await self._mount_and_scroll(UserCommandMessage(status_text))
891891

892892
def _on_fallback_event(
893-
self, kind: str, message: str, remaining_seconds: float
893+
self,
894+
kind: str,
895+
message: str,
896+
remaining_seconds: float,
897+
limit_type: str | None = None,
894898
) -> None:
895-
"""Display a Textual toast when the auto-fallback toggles.
899+
"""Surface auto-fallback transitions both as a toast and in the chat.
896900
897901
`kind` is "activated" or "restored". `remaining_seconds` is the
898902
original fallback window length on activation, 0 on restore.
903+
`limit_type` is one of "tpm" / "rpm" / "tpd" / "rpd" or None when
904+
the 429 body didn't identify the quota.
899905
"""
900-
del remaining_seconds # informational, conveyed via `message`
901906
severity = "warning" if kind == "activated" else "information"
902907
title = (
903908
"Auto-fallback activated" if kind == "activated" else "Auto-fallback ended"
904909
)
905910
self.notify(message, title=title, severity=severity, timeout=8)
906911

912+
try:
913+
primary = self.config.get_active_model()
914+
except ValueError:
915+
return
916+
fallback_alias = primary.fallback_model or "(unknown)"
917+
918+
if kind == "activated":
919+
duration = max(1, int(remaining_seconds))
920+
quota_clause = self._format_limit_clause(limit_type)
921+
body = (
922+
f"## Auto-fallback activated (auto-fallback: ON)\n\n"
923+
f"Rate limit hit on `{primary.alias}`{quota_clause}. "
924+
f"Requests are redirected to `{fallback_alias}` for ~{duration}s, "
925+
f"then the primary model will be restored automatically."
926+
)
927+
else:
928+
body = (
929+
f"## Auto-fallback ended\n\nPrimary model `{primary.alias}` restored."
930+
)
931+
932+
self.run_worker(
933+
self._mount_and_scroll(UserCommandMessage(body)), exclusive=False
934+
)
935+
936+
@staticmethod
937+
def _format_limit_clause(limit_type: str | None) -> str:
938+
"""Render the parenthetical " (tpm: tokens per minute)" suffix for
939+
the fallback-activation chat message. Empty string when the 429
940+
body didn't identify the quota.
941+
"""
942+
labels = {
943+
"tpm": "tokens per minute",
944+
"rpm": "requests per minute",
945+
"tpd": "tokens per day",
946+
"rpd": "requests per day",
947+
}
948+
label = labels.get(limit_type or "")
949+
if not label:
950+
return ""
951+
return f" ({limit_type}: {label})"
952+
907953
def _refresh_model_label(self) -> None:
908954
"""Re-render the `#bottom-model` widget from the live config + agent_loop.
909955

‎albert_code/core/agent_loop.py‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,9 @@ def __init__(
216216
self.entrypoint_metadata = entrypoint_metadata
217217
self.session_id = str(uuid4())
218218
self._current_user_message_id: str | None = None
219-
self._fallback_observer: Callable[[str, str, float], None] | None = None
219+
self._fallback_observer: (
220+
Callable[[str, str, float, str | None], None] | None
221+
) = None
220222
self._last_resolved_model_alias: str | None = None
221223

222224
self.telemetry_client = TelemetryClient(config_getter=lambda: self.config)
@@ -288,23 +290,28 @@ def _select_backend(self) -> BackendLike:
288290
return BACKEND_FACTORY[provider.backend](provider=provider, timeout=timeout)
289291

290292
def set_fallback_observer(
291-
self, observer: Callable[[str, str, float], None] | None
293+
self, observer: Callable[[str, str, float, str | None], None] | None
292294
) -> None:
293295
"""Register a callback notified on auto-fallback transitions.
294296
295-
Called with (event_kind, message, remaining_seconds) where
296-
`event_kind` is "activated" or "restored".
297+
Called with (event_kind, message, remaining_seconds, limit_type)
298+
where `event_kind` is "activated" or "restored" and `limit_type`
299+
is one of "tpm" / "rpm" / "tpd" / "rpd" or None.
297300
"""
298301
self._fallback_observer = observer
299302

300303
def _notify_fallback(
301-
self, kind: str, message: str, remaining_seconds: float
304+
self,
305+
kind: str,
306+
message: str,
307+
remaining_seconds: float,
308+
limit_type: str | None = None,
302309
) -> None:
303310
observer = getattr(self, "_fallback_observer", None)
304311
if observer is None:
305312
return
306313
try:
307-
observer(kind, message, remaining_seconds)
314+
observer(kind, message, remaining_seconds, limit_type)
308315
except Exception:
309316
logger.debug("Fallback observer raised", exc_info=True)
310317

@@ -353,6 +360,7 @@ def _resolve_model_with_fallback(self) -> ModelConfig:
353360
f"Auto-fallback: {primary.alias} -> {candidate.alias} "
354361
f"for ~{int(remaining)}s",
355362
remaining,
363+
throttler.last_limit_type(primary.alias),
356364
)
357365
self._last_resolved_model_alias = candidate.alias
358366
return candidate

‎albert_code/core/llm/backend/generic.py‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,30 @@ def _partial_tag_suffix_length(text: str, tag: str) -> int:
455455
_BODY_PER_DAY_RE = re.compile(
456456
r"(input\s+)?tokens?\s+per\s+day|requests?\s+per\s+day", re.IGNORECASE
457457
)
458+
_BODY_TPM_RE = re.compile(r"(input\s+)?tokens?\s+per\s+minute", re.IGNORECASE)
459+
_BODY_TPD_RE = re.compile(r"(input\s+)?tokens?\s+per\s+day", re.IGNORECASE)
460+
_BODY_RPD_RE = re.compile(r"requests?\s+per\s+day", re.IGNORECASE)
461+
462+
463+
def parse_limit_type(body: str) -> str | None:
464+
"""Detect which Albert quota the 429 body refers to.
465+
466+
Returns one of "tpm", "rpm", "tpd", "rpd", or None when no quota
467+
keyword is recognised. Order matters: per-day patterns are tested
468+
before per-minute so "tokens per day" doesn't match the tpm regex.
469+
"""
470+
if not body:
471+
return None
472+
head = body[:500]
473+
if _BODY_TPD_RE.search(head):
474+
return "tpd"
475+
if _BODY_RPD_RE.search(head):
476+
return "rpd"
477+
if _BODY_TPM_RE.search(head):
478+
return "tpm"
479+
if _BODY_RPM_RE.search(head):
480+
return "rpm"
481+
return None
458482

459483

460484
def _parse_retry_after_from_body(body: str) -> float | None:
@@ -871,8 +895,12 @@ async def _handle_429(
871895
body_text = ""
872896
logger.warning("429 body: %s", body_text[:300] if body_text else "(empty)")
873897

898+
limit_type = parse_limit_type(body_text)
899+
874900
if is_terminal_rate_limit(body_text):
875-
get_throttler(self._provider).record_rate_limit(model_alias=model_alias)
901+
get_throttler(self._provider).record_rate_limit(
902+
model_alias=model_alias, limit_type=limit_type
903+
)
876904
save_terminal_quota_event(
877905
model_name=model_name or model_alias or "unknown",
878906
reason="daily-quota",
@@ -890,7 +918,9 @@ async def _handle_429(
890918
retry_after = _parse_retry_after_from_body(body_text)
891919
throttler = get_throttler(self._provider)
892920
throttler.record_rate_limit(
893-
model_alias=model_alias, retry_after_seconds=retry_after
921+
model_alias=model_alias,
922+
retry_after_seconds=retry_after,
923+
limit_type=limit_type,
894924
)
895925
# If this 429 just armed the auto-fallback for this model, retrying
896926
# the same primary is wasteful: the next agent turn will switch to

‎albert_code/core/llm/throttling.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,11 @@ def __init__(
135135
self._consecutive_429_per_model: dict[str, int] = {}
136136
# primary_alias -> fallback active until (monotonic seconds, 0 if inactive)
137137
self._fallback_until: dict[str, float] = {}
138+
# primary_alias -> last detected limit type ("tpm" / "rpm" / "tpd"
139+
# / "rpd"). Set by record_rate_limit when the 429 body identifies
140+
# the quota that tripped, read by the agent loop when arming the
141+
# auto-fallback so the chat message can name the limit.
142+
self._last_limit_type_per_model: dict[str, str] = {}
138143
# Pre-call debounce: timestamp of the last acquired slot, used to
139144
# enforce a minimum 60/rpm + epsilon spacing between calls (Simon
140145
# Roux's AlbertCode does the same in api.py:_wait_for_slot).
@@ -255,6 +260,7 @@ def record_rate_limit(
255260
*,
256261
model_alias: str | None = None,
257262
retry_after_seconds: float | None = None,
263+
limit_type: str | None = None,
258264
) -> None:
259265
"""Called when the upstream returned 429.
260266
@@ -265,6 +271,10 @@ def record_rate_limit(
265271
If `retry_after_seconds` is provided, future `acquire()` calls will
266272
also wait for that block to expire (in addition to rolling-window
267273
and debounce constraints).
274+
275+
If `limit_type` is provided (one of "tpm" / "rpm" / "tpd" / "rpd"),
276+
it is stored per model so the agent loop can surface which quota
277+
tripped when arming the auto-fallback.
268278
"""
269279
self._rate_limit_events.add(1)
270280
recent = self._rate_limit_events.total()
@@ -278,6 +288,15 @@ def record_rate_limit(
278288
self._consecutive_429_per_model[model_alias] = (
279289
self._consecutive_429_per_model.get(model_alias, 0) + 1
280290
)
291+
if limit_type is not None:
292+
self._last_limit_type_per_model[model_alias] = limit_type
293+
294+
def last_limit_type(self, model_alias: str) -> str | None:
295+
"""Return the last detected quota type for `model_alias`, or None.
296+
297+
Cleared by `clear_consecutive_429` after a successful call.
298+
"""
299+
return self._last_limit_type_per_model.get(model_alias)
281300

282301
def usage_snapshot(self, *, model_name: str | None = None) -> UsageSnapshot:
283302
"""Live counters for the /rpm slash command.
@@ -350,6 +369,7 @@ def record_success(self, *, model_alias: str | None = None) -> None:
350369
if model_alias is None:
351370
return
352371
self._consecutive_429_per_model.pop(model_alias, None)
372+
self._last_limit_type_per_model.pop(model_alias, None)
353373

354374
def is_fallback_trigger_reached(self, model_alias: str | None) -> bool:
355375
"""Pure getter: True if `model_alias` has accumulated enough
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from __future__ import annotations
2+
3+
import pytest
4+
5+
from albert_code.core.llm.backend.generic import parse_limit_type
6+
7+
8+
class TestParseLimitType:
9+
"""`parse_limit_type` extracts the quota family from a 429 body so the
10+
auto-fallback chat message can name which limit tripped. The function
11+
is regex-based and fragile by nature: this suite locks in the wordings
12+
Albert is known to use, plus the precedence rules that prevent
13+
"tokens per day" from being mis-classified as `tpm`.
14+
"""
15+
16+
@pytest.mark.parametrize(
17+
("body", "expected"),
18+
[
19+
("Server: 128000 input tokens per minute exceeded (remaining: 0).", "tpm"),
20+
("Server: 50 requests per minute exceeded (remaining: 0).", "rpm"),
21+
("Server: 2460000 input tokens per day exceeded (remaining: 0).", "tpd"),
22+
("Server: 5000 requests per day exceeded (remaining: 0).", "rpd"),
23+
],
24+
)
25+
def test_recognises_albert_wordings(self, body: str, expected: str) -> None:
26+
assert parse_limit_type(body) == expected
27+
28+
def test_returns_none_on_empty_body(self) -> None:
29+
assert parse_limit_type("") is None
30+
31+
def test_returns_none_when_no_quota_keyword(self) -> None:
32+
# If Albert ever changes the wording, the fallback chat message
33+
# will still render correctly - just without the "(tpm: ...)"
34+
# suffix - rather than crashing.
35+
assert parse_limit_type("Quota exceeded.") is None
36+
assert parse_limit_type("HTTP 429 Too Many Requests") is None
37+
38+
def test_per_day_takes_precedence_over_per_minute(self) -> None:
39+
# The substring "tokens per minute" doesn't appear in "tokens per
40+
# day", but the order of checks matters if both keywords coexist
41+
# in a future composite message. Lock in tpd-before-tpm.
42+
body = (
43+
"Daily and per-minute limits: 1000 tokens per day, 100 tokens per minute."
44+
)
45+
assert parse_limit_type(body) == "tpd"
46+
47+
def test_case_insensitive(self) -> None:
48+
assert parse_limit_type("TOKENS PER MINUTE EXCEEDED") == "tpm"
49+
assert parse_limit_type("Requests Per Day Exceeded") == "rpd"

‎tests/core/test_throttling.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,3 +253,54 @@ def test_fallback_remaining_seconds(self) -> None:
253253
assert throttler.fallback_remaining_seconds("albert-code") == pytest.approx(
254254
40.0
255255
)
256+
257+
258+
class TestThrottlerLimitType:
259+
"""`record_rate_limit` accepts an optional `limit_type` ("tpm" / "rpm"
260+
/ "tpd" / "rpd") so the agent loop can name the tripped quota when
261+
arming the auto-fallback. This suite locks in storage, retrieval, and
262+
cleanup semantics.
263+
"""
264+
265+
@pytest.fixture(autouse=True)
266+
def _reset(self) -> None:
267+
reset_throttlers_for_tests()
268+
269+
def test_record_then_read_back(self) -> None:
270+
throttler = Throttler(_make_provider(), clock=FakeClock())
271+
throttler.record_rate_limit(model_alias="albert-code", limit_type="tpm")
272+
assert throttler.last_limit_type("albert-code") == "tpm"
273+
274+
def test_unknown_alias_returns_none(self) -> None:
275+
throttler = Throttler(_make_provider(), clock=FakeClock())
276+
assert throttler.last_limit_type("never-seen") is None
277+
278+
def test_omitting_limit_type_does_not_store(self) -> None:
279+
# Backward compat: existing call sites that don't pass limit_type
280+
# must not poison the dict (would surface as a stale type from a
281+
# previous 429 in the worst case, but here it stays None).
282+
throttler = Throttler(_make_provider(), clock=FakeClock())
283+
throttler.record_rate_limit(model_alias="albert-code")
284+
assert throttler.last_limit_type("albert-code") is None
285+
286+
def test_record_success_clears_limit_type(self) -> None:
287+
throttler = Throttler(_make_provider(), clock=FakeClock())
288+
throttler.record_rate_limit(model_alias="albert-code", limit_type="tpd")
289+
throttler.record_success(model_alias="albert-code")
290+
assert throttler.last_limit_type("albert-code") is None
291+
292+
def test_latest_value_wins(self) -> None:
293+
# Two consecutive 429 with different quota types - the agent loop
294+
# arms the fallback after the second; the user should see the
295+
# most recent quota that tripped.
296+
throttler = Throttler(_make_provider(), clock=FakeClock())
297+
throttler.record_rate_limit(model_alias="albert-code", limit_type="tpm")
298+
throttler.record_rate_limit(model_alias="albert-code", limit_type="rpm")
299+
assert throttler.last_limit_type("albert-code") == "rpm"
300+
301+
def test_per_model_isolation(self) -> None:
302+
throttler = Throttler(_make_provider(), clock=FakeClock())
303+
throttler.record_rate_limit(model_alias="albert-code", limit_type="tpm")
304+
throttler.record_rate_limit(model_alias="albert-large", limit_type="rpd")
305+
assert throttler.last_limit_type("albert-code") == "tpm"
306+
assert throttler.last_limit_type("albert-large") == "rpd"

0 commit comments

Comments
 (0)