Independent Auditing of AI Agents. Run by human or the agent itself, to answer the most crucial question in the AI Agent Economy. Is the agent doing what is supposed to do? With iFixAi you can have this answer in less than 120 seconds.
Python agent-evaluationaiai-alignmentai-evaluationai-governanceai-safetyclidiagnostic-tooleu-ai-acthallucination-detectioniso-42001llm-evaluationllm-securitynist-ai-rmfowasp-llmprompt-injectionpythonresponsible-airisk-assessmentrisk-management
fix(providers): distinguish exhausted quota from transient throttling (#197)
Rudy Mizrahi Celeklie5f78b6e877e
diff --git a/ifixai/providers/base.py b/ifixai/providers/base.pyindex d83e8dd..db63b93 100644--- a/ifixai/providers/base.py+++ b/ifixai/providers/base.py@@ -133,13 +133,11 @@ _FATAL_ERROR_MARKERS: tuple[str, ...] = (# The subset meaning the account itself is spent, not merely throttled. A 429# carrying any of these never clears on retry, so the run must stop and say so# rather than burn the whole budget on calls that cannot succeed.+# Bare quota/billing/credit words also appear in retryable per-minute limits._QUOTA_EXHAUSTED_MARKERS: tuple[str, ...] = (- "quota","insufficient_quota","insufficient credits",- "billing","payment required",- "credit",)@@ -147,6 +145,8 @@ def is_fatal_provider_error(exc: BaseException) -> bool:"""True when an error means the credential is rejected / out of quota."""if isinstance(exc, ProviderAuthError):return True+ if isinstance(exc, ProviderRateLimitError):+ return any(marker in exc.details.lower() for marker in _QUOTA_EXHAUSTED_MARKERS)# Transient by construction, so never a credential problem — and they must# be excluded by type, not by text. The markers below are matched as bare# substrings, and a truncation detail carries a character count: a reply cut@@ -154,13 +154,6 @@ def is_fatal_provider_error(exc: BaseException) -> bool:if isinstance(exc, TRANSIENT_PROVIDER_ERRORS):return Falsetext = str(exc).lower()- # Every provider maps HTTP 429 to ProviderRateLimitError whether it is a- # per-minute ceiling that clears in seconds or an exhausted account that- # never will, so the body is the only thing that separates them. Match the- # narrow account-dead markers, not the generic ones: "rate limit exceeded"- # contains "limit exceeded" and must stay retryable.- if isinstance(exc, ProviderRateLimitError):- return any(marker in text for marker in _QUOTA_EXHAUSTED_MARKERS)return any(marker in text for marker in _FATAL_ERROR_MARKERS)diff --git a/ifixai/providers/http.py b/ifixai/providers/http.pyindex c199d94..f36eb01 100644--- a/ifixai/providers/http.py+++ b/ifixai/providers/http.py@@ -16,6 +16,7 @@ from ifixai.providers.base import (ProviderRateLimitError,ProviderResponseError,ProviderTimeoutError,+ is_fatal_provider_error,raise_if_truncated,)from ifixai.providers.secrets import scrub_secrets@@ -134,6 +135,8 @@ class HttpProvider(ChatProvider):try:return await self._send_request(url, payload, headers, timeout, config)except ProviderRateLimitError as exc:+ if is_fatal_provider_error(exc):+ raiselast_error = excif attempt < config.max_retries:await asyncio.sleep(2**attempt)@@ -171,10 +174,11 @@ class HttpProvider(ChatProvider):details=f"HTTP {resp.status}: authentication failed",)if resp.status == 429:+ body = await resp.text()raise ProviderRateLimitError(provider="http",endpoint=endpoint,- details="HTTP 429: rate limited",+ details=f"HTTP 429: {scrub_secrets(body[:500])}",)if resp.status in RETRYABLE_HTTP_STATUS_CODES:body = await resp.text()diff --git a/ifixai/tests/providers/test_http_response_shapes.py b/ifixai/tests/providers/test_http_response_shapes.pyindex ddd60a4..f5d21ca 100644--- a/ifixai/tests/providers/test_http_response_shapes.py+++ b/ifixai/tests/providers/test_http_response_shapes.py@@ -64,6 +64,73 @@ async def test_malformed_retrieval_reply_reports_unavailable():await runner.cleanup()[email protected]("detail,fatal,attempts", [+ ("insufficient_quota", True, 1),+ ("insufficient credits", True, 1),+ ("payment required", True, 1),+ ("rate limit exceeded", False, 2),+ ("You exceeded your current quota, please check your plan and billing details", False, 2),+ ("Token rate limit exceeded. Retry after 60 seconds: https://aka.ms/oai/quotaincrease", False, 2),+ ("per-minute credit quota exceeded", False, 2),+])+async def test_http_429_preserves_quota_identity(monkeypatch, detail, fatal, attempts):+ from ifixai.providers.base import ProviderRateLimitError, is_fatal_provider_error++ seen = []+ async def chat(request):+ seen.append(await request.json())+ return aiohttp.web.json_response({"error": {"message": detail + " sk-" + "A" * 24}}, status=429)++ async def no_delay(_seconds):+ pass++ monkeypatch.setattr("ifixai.providers.http.asyncio.sleep", no_delay)+ app = aiohttp.web.Application()+ app.router.add_post("/v1/chat/completions", chat)+ runner = aiohttp.web.AppRunner(app)+ await runner.setup()+ site = aiohttp.web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ url = f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}/v1"+ provider = HttpProvider()+ try:+ with pytest.raises(ProviderRateLimitError) as caught:+ await provider.send_message([ChatMessage(content="hello")], ProviderConfig(provider="http", endpoint=url, max_retries=1))+ assert is_fatal_provider_error(caught.value) is fatal+ assert detail in caught.value.details+ assert "sk-" + "A" * 24 not in caught.value.details+ assert len(seen) == attempts+ finally:+ await provider.aclose()+ await runner.cleanup()++[email protected]("detail,fatal", [+ ("insufficient_quota", True), ("insufficient credits", True),+ ("payment required", True), ("billing limit reached", False),+ ("rate limit exceeded", False), ("HTTP 429, retry later", False),+ ("You exceeded your current quota, please check your plan and billing details", False),+ ("Token rate limit exceeded. Retry after 60 seconds: https://aka.ms/oai/quotaincrease", False),+ ("per-minute credit quota exceeded", False),+])+def test_shared_rate_limit_classifier_reaches_account_quota_check(detail, fatal):+ from ifixai.providers.base import (+ ProviderConnectionError,+ ProviderRateLimitError,+ is_fatal_provider_error,+ )+ assert is_fatal_provider_error(ProviderRateLimitError(details=detail)) is fatal+ assert not is_fatal_provider_error(ProviderConnectionError(details=detail))+++def test_quota_markers_in_provider_metadata_do_not_make_throttling_fatal():+ from ifixai.providers.base import ProviderRateLimitError, is_fatal_provider_error++ error = ProviderRateLimitError(provider="credit-proxy", endpoint="https://owned.invalid/quota", details="rate limit exceeded")+ assert not is_fatal_provider_error(error)++@pytest.mark.asyncio@pytest.mark.parametrize("status", [408, 500, 502, 503, 504, 400])async def test_http_gateway_failures_follow_retry_contract(monkeypatch, status):