The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(image_gen): a gateway 429 is reported as a rate limit and retried once, not as a missing model
teknium1884b8d980f79
diff --git a/plugins/video_gen/fal/__init__.py b/plugins/video_gen/fal/__init__.pyindex 2dbd0e9f46d..a97eb548161 100644--- a/plugins/video_gen/fal/__init__.py+++ b/plugins/video_gen/fal/__init__.py@@ -270,10 +270,15 @@ def _submit_fal_video_request(endpoint: str, arguments: Dict[str, Any]):managed_gateway = _resolve_managed_fal_video_gateway()if managed_gateway is None:return client.submit(endpoint, arguments=arguments, headers=headers)+ from tools.fal_common import (+ _extract_http_status, _managed_fal_billing_error, submit_managed_fal_with_rate_limit_retry,+ )try:- return _get_managed_fal_video_client(managed_gateway).submit(endpoint, arguments=arguments, headers=headers)+ return submit_managed_fal_with_rate_limit_retry(+ lambda request_headers: _get_managed_fal_video_client(managed_gateway).submit(+ endpoint, arguments=arguments, headers=request_headers),+ what="video endpoint", name=endpoint)except Exception as exc:- from tools.fal_common import _extract_http_status, _managed_fal_billing_errorstatus = _extract_http_status(exc)if status is not None and 400 <= status < 500:billing = _managed_fal_billing_error(exc, "endpoint")diff --git a/tests/tools/test_image_generation.py b/tests/tools/test_image_generation.pyindex ddc6bfd556a..4971b92183a 100644--- a/tests/tools/test_image_generation.py+++ b/tests/tools/test_image_generation.py@@ -563,6 +563,42 @@ class TestManagedGatewayErrorTranslation:with pytest.raises(ConnectionError):image_tool._submit_fal_request("fal-ai/flux-2-pro", {"prompt": "x"})+ @staticmethod+ def _rate_limited(retry_after):+ return _MockHttpxError(429, "Too Many Requests", payload={"error": {+ "code": "RATE_LIMIT_EXCEEDED", "message": "Rate limit exceeded.", "retryAfter": retry_after}})++ def test_short_429_is_retried_once_under_a_fresh_idempotency_key(self, image_tool, monkeypatch):+ """A gateway 429 with a short retryAfter is waited out and resubmitted once (new key)."""+ from unittest.mock import MagicMock++ monkeypatch.setattr(image_tool, "_resolve_managed_fal_gateway", lambda: MagicMock())+ mock_managed_client = MagicMock()+ mock_managed_client.submit.side_effect = [self._rate_limited(1), "handle"]+ monkeypatch.setattr(image_tool, "_get_managed_fal_client", lambda gw: mock_managed_client)++ assert image_tool._submit_fal_request("fal-ai/gpt-image-2", {"prompt": "x"}) == "handle"++ keys = [call.kwargs["headers"]["x-idempotency-key"] for call in mock_managed_client.submit.call_args_list]+ assert len(keys) == 2 and keys[0] != keys[1]++ def test_long_429_is_reported_as_a_rate_limit_not_a_missing_model(self, image_tool, monkeypatch):+ """A 429 beyond the retry cap names the rate limit; agents must not be told to switch models."""+ from unittest.mock import MagicMock++ monkeypatch.setattr(image_tool, "_resolve_managed_fal_gateway", lambda: MagicMock())+ mock_managed_client = MagicMock()+ mock_managed_client.submit.side_effect = self._rate_limited(120)+ monkeypatch.setattr(image_tool, "_get_managed_fal_client", lambda gw: mock_managed_client)++ with pytest.raises(ValueError) as exc_info:+ image_tool._submit_fal_request("fal-ai/gpt-image-2", {"prompt": "x"})++ msg = str(exc_info.value)+ assert "rate-limited" in msg and "retry after 120s" in msg+ assert "may not yet be enabled" not in msg+ assert mock_managed_client.submit.call_count == 1+class TestKreaModelNormalization:"""Native ``krea-2-*`` detection for managed Krea routing."""diff --git a/tools/fal_common.py b/tools/fal_common.pyindex d1918a019dc..d4f90937aa0 100644--- a/tools/fal_common.py+++ b/tools/fal_common.py@@ -8,9 +8,14 @@ here would silently defeat ``monkeypatch.setattr(image_tool, "_managed_fal_clienfrom __future__ import annotations-from typing import Any, Dict, Optional, Union+import time+import uuid+from typing import Any, Callable, Dict, Optional, Unionfrom urllib.parse import urlencode+# A 429 whose Retry-After is longer than this is reported, not waited out inside a tool call.+MANAGED_FAL_RATE_LIMIT_RETRY_CAP_SECONDS = 30.0+def import_fal_client() -> Any:"""Import ``fal_client`` (via ``lazy_deps`` when available); raises ImportError if unavailable.@@ -74,6 +79,61 @@ def _managed_fal_billing_error(exc: BaseException, what: str) -> Optional[str]:)+def _managed_fal_retry_after_seconds(exc: BaseException) -> Optional[float]:+ """Seconds the managed gateway asked us to wait after a 429: the ``Retry-After`` header,+ else the body's ``error.retryAfter``; None when the status is not 429 or neither is present."""+ response = getattr(exc, "response", None)+ if response is None or _extract_http_status(exc) != 429:+ return None+ headers = getattr(response, "headers", None)+ raw = headers.get("Retry-After") if headers is not None and hasattr(headers, "get") else None+ if raw is None:+ try:+ error = response.json().get("error")+ except Exception: # noqa: BLE001 — a non-JSON 429 body simply has no hint+ return None+ raw = error.get("retryAfter") if isinstance(error, dict) else None+ try:+ return float(raw) if raw is not None else None+ except (TypeError, ValueError):+ return None+++def _managed_fal_rate_limit_message(what: str, name: str, retry_after: Optional[float]) -> str:+ hint = f"retry after {retry_after:g}s" if retry_after is not None else "no Retry-After given"+ return (+ f"Nous Subscription gateway rate-limited {what} '{name}' (HTTP 429; {hint}). "+ "The model is enabled — retry later instead of switching models or setting FAL_KEY."+ )+++def submit_managed_fal_with_rate_limit_retry(+ submit: Callable[[Dict[str, str]], Any], *, what: str, name: str,+):+ """Call ``submit(headers)`` with a fresh ``x-idempotency-key``; on a 429 whose Retry-After+ fits the cap, wait it out (interrupt-aware) and resubmit ONCE under a new key.++ A second 429, or one with an unknown/too-long Retry-After, raises ValueError naming the+ rate limit — it must never fall through to the callers' "model may not be enabled" 4xx text,+ which sends agents off to switch models. Every other exception propagates untouched.+ """+ from tools.interrupt import is_interrupted+ for attempt in (1, 2):+ try:+ return submit({"x-idempotency-key": str(uuid.uuid4())})+ except Exception as exc:+ if _extract_http_status(exc) != 429:+ raise+ retry_after = _managed_fal_retry_after_seconds(exc)+ if attempt == 2 or retry_after is None or retry_after > MANAGED_FAL_RATE_LIMIT_RETRY_CAP_SECONDS:+ raise ValueError(_managed_fal_rate_limit_message(what, name, retry_after)) from exc+ deadline = time.monotonic() + retry_after+ while time.monotonic() < deadline:+ if is_interrupted():+ raise ValueError(_managed_fal_rate_limit_message(what, name, retry_after)) from exc+ time.sleep(min(0.5, max(0.0, deadline - time.monotonic())))++def _require(value: Any, what: str) -> Any:if value is None:raise RuntimeError(f"{what} is required for managed FAL gateway mode")diff --git a/tools/image_generation_tool.py b/tools/image_generation_tool.pyindex 6d00b89fcd2..6c7d6841189 100644--- a/tools/image_generation_tool.py+++ b/tools/image_generation_tool.py@@ -31,7 +31,7 @@ def _load_fal_client() -> Any:from tools.debug_helpers import DebugSessionfrom tools.fal_common import (_ManagedFalSyncClient, _extract_http_status, _managed_fal_billing_error,- _normalize_fal_queue_url_format,+ _normalize_fal_queue_url_format, submit_managed_fal_with_rate_limit_retry,)from tools.image_generation_catalog import (DEFAULT_ASPECT_RATIO, DEFAULT_MODEL, FAL_MODELS, UPSCALER_CREATIVITY, UPSCALER_DEFAULT_PROMPT,@@ -127,8 +127,10 @@ def _submit_fal_request(model: str, arguments: Dict[str, Any]):if managed_gateway is None:return fal_client.submit(model, arguments=arguments, headers=request_headers)try:- return _get_managed_fal_client(managed_gateway).submit(- model, arguments=arguments, headers=request_headers)+ return submit_managed_fal_with_rate_limit_retry(+ lambda headers: _get_managed_fal_client(managed_gateway).submit(+ model, arguments=arguments, headers=headers),+ what="image model", name=model)except Exception as exc:# A managed-gateway 4xx usually means the portal doesn't proxy this model# (allowlist miss, billing gate): give remediation instead of a raw httpx error.