Skip to content

Commit 67cadb8

Browse files
committed
Throttle Albert API: per-model documented limits, debounce, fail-fast on daily quota
- Distinguish daily quota (rpd/tpd) from transient (rpm/tpm) 429s. On daily quota (e.g. "2460000 input tokens per day exceeded"), raise TerminalRateLimitError immediately instead of burning 3 retries that all return 429. - Surface Albert's 429 body in the TUI message ("Daily quota exhausted on X. Server: ...") instead of a generic "rate limit exceeded". - Log the 429 body in _handle_429 for diagnostic visibility. - Per-model documented limits (DOCUMENTED_MODEL_LIMITS) used by the throttler instead of the max-across-routers, which incorrectly picked the embeddings router (500 rpm) for chat models like Qwen3-Coder (50 rpm). Throttler.acquire and usage_snapshot accept model_name. - Pre-call debounce: enforce 60/rpm + 0.05s minimum spacing between two acquires (Simon Roux's _wait_for_slot pattern). Plus _blocked_until for Retry-After-driven backoff. - New /rpm slash command: live RPM/TPM gauge for the active model with bar, debounce, active backoff, and limit source (documented vs guessed). - /limits now also shows the documented EXP/PROD tier for the active model alongside live /v1/me/info per-router data. - Fail-fast on the next 429 once the auto-fallback trigger is reached (is_fallback_trigger_reached): stop wasting retries on a primary the agent loop will replace at the next turn. - Skip auto-continue when the assistant returned an empty response (no content, no tool_calls). Avoids the observed pattern of 15+ requests at 20k input tokens each producing 0 output tokens. - Reset throttler singletons between tests to avoid state leakage.
1 parent 3ff24ad commit 67cadb8

10 files changed

Lines changed: 499 additions & 35 deletions

File tree

‎README.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,15 @@ Les documents techniques détaillés sont dans le dossier [`docs/`](docs/) :
100100

101101
## Remerciements
102102

103-
Ce fork s'inspire du projet [AlbertCode](https://github.com/XenocodeRCE/AlbertCode) de **Simon Roux** pour plusieurs idées clés liées à l'API Albert : auto-fallback de modèle sur 429 répétés, jauge RPM, mode plan-first avec checkpoints, snapshots Git automatiques avant édition. Les implémentations dans ce fork sont indépendantes mais doivent beaucoup à ses choix de conception.
103+
Ce fork s'inspire du projet [AlbertCode](https://github.com/XenocodeRCE/AlbertCode) de **Simon Roux** pour plusieurs idées clés liées à l'API Albert :
104+
105+
- **Auto-fallback de modèle sur 429 répétés** : après deux 429 consécutifs sur le modèle principal, bascule automatique vers un modèle de secours pendant 60 s puis retour.
106+
- **Jauge RPM live** : commande slash `/rpm` qui affiche la consommation `requêtes/limite (%) [###···]` du modèle actif sur une fenêtre glissante de 60 s.
107+
- **Debounce global pré-appel** : un délai minimum `60/rpm + 0.05 s` est imposé entre deux appels HTTP, pour éviter les rafales qui déclenchent les 429 (vu dans `_wait_for_slot` côté collègue).
108+
- **Lecture du `Retry-After` dans le corps de réponse** : quand Albert renvoie un message texte du type `"Limit exceeded: 50 requests per minute"`, ce délai est extrait et respecté avant le retry.
109+
- **Table statique des paliers documentés EXP / PROD** par modèle, affichée dans `/limits` à côté du fetch live de `/v1/me/info` : utile pour repérer si le compte est sur le palier expérimental ou production sans appel API supplémentaire.
110+
111+
Les implémentations dans ce fork sont indépendantes mais doivent beaucoup à ses choix de conception.
104112

105113
## Bibliothèques utilisées
106114

‎albert_code/cli/commands.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,11 @@ def __init__(self, excluded_commands: list[str] | None = None) -> None:
6767
description="Display Albert API quotas (rpm/rpd/tpm/tpd)",
6868
handler="_show_limits",
6969
),
70+
"rpm": Command(
71+
aliases=frozenset(["/rpm"]),
72+
description="Live RPM/TPM gauge for the active model",
73+
handler="_show_rpm",
74+
),
7075
"fallback": Command(
7176
aliases=frozenset(["/fallback"]),
7277
description="Toggle auto-fallback on repeated 429",

‎albert_code/cli/textual_ui/app.py‎

Lines changed: 121 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -723,10 +723,25 @@ async def _handle_agent_loop_turn(self, prompt: str) -> None:
723723

724724
message = str(e)
725725
if isinstance(e, RateLimitError):
726-
message = (
727-
"Rate limits exceeded. Please wait a moment before trying again. "
728-
"Use /limits to inspect your Albert quotas."
729-
)
726+
lines: list[str] = []
727+
if e.is_terminal:
728+
lines.append(
729+
f"Daily quota exhausted on `{e.model}` ({e.provider})."
730+
)
731+
else:
732+
lines.append(
733+
f"Rate limit exceeded on `{e.model}` ({e.provider})."
734+
)
735+
if e.detail:
736+
lines.append(f"Server: {e.detail}")
737+
if e.is_terminal:
738+
lines.append(
739+
"This won't recover by retrying. Try a different model "
740+
"(`/config`) or wait until the daily counter resets."
741+
)
742+
else:
743+
lines.append("Use /limits to inspect your Albert quotas.")
744+
message = " ".join(lines)
730745

731746
await self._mount_and_scroll(
732747
ErrorMessage(message, collapsed=self._tools_collapsed)
@@ -944,6 +959,7 @@ async def _toggle_fallback(self) -> None:
944959
async def _show_limits(self) -> None:
945960
"""Display Albert API quotas (rpm/rpd/tpm/tpd) for the active provider."""
946961
from albert_code.core.llm.quota import (
962+
documented_limits_for,
947963
fetch_albert_quotas_detailed,
948964
group_limits_by_router,
949965
is_albert_provider,
@@ -985,7 +1001,7 @@ async def _show_limits(self) -> None:
9851001
if not info.limits:
9861002
lines.append("_No quota information returned._")
9871003
else:
988-
lines.append("### Limits per router")
1004+
lines.append("### Limits per router (live, /v1/me/info)")
9891005
lines.append("")
9901006
lines.append("| Router | rpm | rpd | tpm | tpd |")
9911007
lines.append("|---:|---:|---:|---:|---:|")
@@ -997,6 +1013,92 @@ async def _show_limits(self) -> None:
9971013
tpm = _format_quota_value(vals, "tpm")
9981014
tpd = _format_quota_value(vals, "tpd")
9991015
lines.append(f"| {router_id} | {rpm} | {rpd} | {tpm} | {tpd} |")
1016+
lines.append("")
1017+
lines.append(
1018+
"_Albert does not expose the model -> router mapping; "
1019+
"compare with the documented tier below._"
1020+
)
1021+
1022+
documented = documented_limits_for(active_model.name)
1023+
if documented is not None:
1024+
lines.append("")
1025+
lines.append(
1026+
f"### Documented tier for `{active_model.name}`"
1027+
)
1028+
lines.append("")
1029+
lines.append("| Tier | rpm | rpd | tpm | tpd |")
1030+
lines.append("|:---|---:|---:|---:|---:|")
1031+
for label, tier in (("EXP", documented.exp), ("PROD", documented.prod)):
1032+
lines.append(
1033+
f"| {label} "
1034+
f"| {_format_doc_value(tier.rpm)} "
1035+
f"| {_format_doc_value(tier.rpd)} "
1036+
f"| {_format_doc_value(tier.tpm)} "
1037+
f"| {_format_doc_value(tier.tpd)} |"
1038+
)
1039+
lines.append("")
1040+
lines.append(
1041+
"_Source: https://albert.sites.beta.gouv.fr/prices/_"
1042+
)
1043+
1044+
await self._mount_and_scroll(UserCommandMessage("\n".join(lines)))
1045+
1046+
async def _show_rpm(self) -> None:
1047+
"""Live RPM/TPM gauge for the active model (rolling 60s window)."""
1048+
from albert_code.core.llm.quota import is_albert_provider
1049+
from albert_code.core.llm.throttling import get_throttler
1050+
1051+
active_model = self.config.get_active_model()
1052+
provider = self.config.get_provider_for_model(active_model)
1053+
1054+
if not is_albert_provider(provider):
1055+
await self._mount_and_scroll(
1056+
UserCommandMessage(
1057+
f"## RPM gauge\n\nThe active provider `{provider.name}` "
1058+
"is not Albert. The gauge is only meaningful for Albert."
1059+
)
1060+
)
1061+
return
1062+
1063+
throttler = get_throttler(provider)
1064+
# Make sure quotas are fetched at least once.
1065+
await throttler.acquire(model_name=active_model.name)
1066+
snap = throttler.usage_snapshot(model_name=active_model.name)
1067+
1068+
rpm_used = int(snap["rpm_used"] or 0)
1069+
rpm_limit = snap["rpm_limit"]
1070+
tpm_used = int(snap["tpm_used"] or 0)
1071+
tpm_limit = snap["tpm_limit"]
1072+
debounce = float(snap["debounce_seconds"] or 0.0)
1073+
blocked = float(snap["blocked_for"] or 0.0)
1074+
window = int(snap["window_seconds"] or 60)
1075+
limit_source = str(snap.get("limit_source") or "unknown")
1076+
1077+
lines: list[str] = [
1078+
"## RPM gauge",
1079+
"",
1080+
f"- **Model**: `{active_model.name}`",
1081+
f"- **Window**: rolling {window}s",
1082+
f"- **Limit source**: {limit_source}",
1083+
"",
1084+
f"- **Requests**: {_format_gauge(rpm_used, rpm_limit)}",
1085+
f"- **Tokens**: {_format_gauge(tpm_used, tpm_limit)}",
1086+
]
1087+
if debounce > 0.0:
1088+
lines.append(
1089+
f"- **Debounce**: {debounce:.2f}s minimum between calls"
1090+
)
1091+
if blocked > 0.0:
1092+
lines.append(
1093+
f"- **Backoff active**: {blocked:.1f}s remaining (Retry-After)"
1094+
)
1095+
1096+
if rpm_limit is None:
1097+
lines.append("")
1098+
lines.append(
1099+
"_Note: no documented tier for this model and no live "
1100+
"limit available. See /limits for the raw per-router data._"
1101+
)
10001102

10011103
await self._mount_and_scroll(UserCommandMessage("\n".join(lines)))
10021104

@@ -1725,6 +1827,20 @@ def _format_quota_value(vals: dict[str, int | None], key: str) -> str:
17251827
return "∞" if value is None else f"{value:,}"
17261828

17271829

1830+
def _format_doc_value(value: int | None) -> str:
1831+
return "∞" if value is None else f"{value:,}"
1832+
1833+
1834+
def _format_gauge(used: int, limit: int | None, *, width: int = 20) -> str:
1835+
"""Format a numeric gauge as `used/limit (pct%) [###···]`."""
1836+
if limit is None or limit <= 0:
1837+
return f"{used:,} (limit unknown)"
1838+
pct = min(100.0, used / limit * 100.0)
1839+
filled = int(round(pct / 100.0 * width))
1840+
bar = "#" * filled + "·" * (width - filled)
1841+
return f"{used:,}/{limit:,} ({pct:.0f}%) `[{bar}]`"
1842+
1843+
17281844
def _print_session_resume_message(session_id: str | None) -> None:
17291845
if not session_id:
17301846
return

‎albert_code/core/agent_loop.py‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from enum import StrEnum, auto
66
from http import HTTPStatus
77
import json
8+
import re
89
from pathlib import Path
910
from threading import Thread
1011
import time
@@ -144,6 +145,20 @@ def _should_raise_rate_limit_error(e: Exception) -> bool:
144145
return isinstance(e, BackendError) and e.status == HTTPStatus.TOO_MANY_REQUESTS
145146

146147

148+
_PER_DAY_HINT = re.compile(r"per\s+day", re.IGNORECASE)
149+
150+
151+
def _build_rate_limit_error(
152+
e: Exception, provider_name: str, model_name: str
153+
) -> RateLimitError:
154+
parsed = e.parsed_error if isinstance(e, BackendError) else None
155+
detail = (parsed or "").strip() or None
156+
is_terminal = bool(detail and _PER_DAY_HINT.search(detail))
157+
return RateLimitError(
158+
provider_name, model_name, detail=detail, is_terminal=is_terminal
159+
)
160+
161+
147162
class AgentLoop:
148163
def __init__(
149164
self,
@@ -588,13 +603,27 @@ def _should_auto_continue(self, last_message: LLMMessage, count: int) -> bool:
588603
589604
Returns True only if:
590605
- the agent ended its turn cleanly (assistant message, no tool call),
606+
- the assistant actually produced content (not an empty response),
591607
- the auto-continue budget for this user input is not exhausted,
592608
- the todo list still has pending or in-progress steps.
609+
610+
Empty assistant responses are excluded: the model failed to emit
611+
anything (often a server-side hiccup or token-budget edge case);
612+
retrying with another nudge wastes another full-context API call
613+
for the same null result.
593614
"""
594615
if count >= self._MAX_AUTO_CONTINUE_PER_USER_INPUT:
595616
return False
596617
if last_message.role != Role.assistant:
597618
return False
619+
has_content = bool((last_message.content or "").strip())
620+
has_tool_calls = bool(last_message.tool_calls)
621+
if not has_content and not has_tool_calls:
622+
logger.warning(
623+
"Skipping auto-continue: assistant returned empty response "
624+
"(no content, no tool calls). Avoiding wasted retry."
625+
)
626+
return False
598627
unfinished = [
599628
t
600629
for t in self._snapshot_todos()
@@ -889,7 +918,9 @@ async def _chat(self, max_tokens: int | None = None) -> LLMChunk:
889918

890919
except Exception as e:
891920
if _should_raise_rate_limit_error(e):
892-
raise RateLimitError(provider.name, active_model.name) from e
921+
raise _build_rate_limit_error(
922+
e, provider.name, active_model.name
923+
) from e
893924

894925
raise RuntimeError(
895926
f"API error from {provider.name} (model: {active_model.name}): {e}"
@@ -938,7 +969,9 @@ async def _chat_streaming(
938969

939970
except Exception as e:
940971
if _should_raise_rate_limit_error(e):
941-
raise RateLimitError(provider.name, active_model.name) from e
972+
raise _build_rate_limit_error(
973+
e, provider.name, active_model.name
974+
) from e
942975

943976
raise RuntimeError(
944977
f"API error from {provider.name} (model: {active_model.name}): {e}"

0 commit comments

Comments
 (0)