:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): treat provider 412 billing suspension as quota exceeded (#106768)
Carlos Marchal8bc05730801e
diff --git a/products/ai_observability/backend/llm/providers/fireworks.py b/products/ai_observability/backend/llm/providers/fireworks.pyindex 586fc68d2235..c5719b73148f 100644--- a/products/ai_observability/backend/llm/providers/fireworks.py+++ b/products/ai_observability/backend/llm/providers/fireworks.py@@ -14,3 +14,6 @@ class FireworksAdapter(OpenAICompatibleByokAdapter):name = "fireworks"BASE_URL = FIREWORKS_BASE_URLPROVIDER_DISPLAY_NAME = "Fireworks"+ # Fireworks returns 412 when it suspends an account for billing. Other OpenAI-compatible+ # providers can send 412 for unrelated reasons, so only this adapter treats it as exhausted quota.+ QUOTA_EXHAUSTED_STATUS_CODES = OpenAICompatibleByokAdapter.QUOTA_EXHAUSTED_STATUS_CODES | {412}diff --git a/products/ai_observability/backend/llm/providers/openai.py b/products/ai_observability/backend/llm/providers/openai.pyindex 4893cdea6ab0..af254e839731 100644--- a/products/ai_observability/backend/llm/providers/openai.py+++ b/products/ai_observability/backend/llm/providers/openai.py@@ -4,7 +4,7 @@ import jsonimport uuidimport loggingfrom collections.abc import Generator-from typing import Any+from typing import Any, ClassVarfrom django.conf import settings@@ -113,6 +113,11 @@ class OpenAIAdapter:request_timeout: float = OpenAIConfig.TIMEOUTmax_retries: int = openai.DEFAULT_MAX_RETRIES+ # OpenRouter returns 402 when the key can't afford the requested max_tokens (or is out of+ # credits). Retrying never helps, so these map to the quota path and the workflow marks the+ # key errored and stops.+ QUOTA_EXHAUSTED_STATUS_CODES: ClassVar[frozenset[int]] = frozenset({402})+def _create_client(self,api_key: str,@@ -259,10 +264,7 @@ class OpenAIAdapter:# completion exists to carry a `content_filter` finish reason.if error.code == "content_filter":return ContentFilteredError(str(error))- # OpenRouter returns 402 when the key can't afford the requested- # max_tokens (or is out of credits). Retrying never helps — mirror- # the quota path so the workflow marks the key errored and stops.- if getattr(error, "status_code", None) == 402:+ if getattr(error, "status_code", None) in self.QUOTA_EXHAUSTED_STATUS_CODES:return QuotaExceededError(str(error))return Nonediff --git a/products/ai_observability/backend/llm/providers/test/test_fireworks.py b/products/ai_observability/backend/llm/providers/test/test_fireworks.pyindex 36e910537028..118ac5f048bc 100644--- a/products/ai_observability/backend/llm/providers/test/test_fireworks.py+++ b/products/ai_observability/backend/llm/providers/test/test_fireworks.py@@ -1,9 +1,12 @@import pytestfrom unittest.mock import MagicMock, patch+import httpximport openai+from products.ai_observability.backend.llm.errors import QuotaExceededErrorfrom products.ai_observability.backend.llm.providers.fireworks import FIREWORKS_BASE_URL, FireworksAdapter+from products.ai_observability.backend.llm.types import AnalyticsContext, CompletionRequestclass TestFireworksValidateKey:@@ -119,3 +122,27 @@ class TestFireworksDefaultKey:with pytest.raises(ValueError, match="BYOKEY-only"):adapter._get_default_api_key()+++class TestFireworksErrorMapping:+ def test_billing_suspension_412_is_mapped_to_quota_exceeded(self):+ message = "Account example-account is suspended."+ response = httpx.Response(+ status_code=412,+ request=httpx.Request("POST", f"{FIREWORKS_BASE_URL}/chat/completions"),+ json={"error": {"message": message}},+ )+ mock_client = MagicMock()+ mock_client.chat.completions.create.side_effect = openai.APIStatusError(+ message, response=response, body={"error": {"message": message}}+ )+ request = CompletionRequest(+ model="accounts/fireworks/models/llama-v3p3-70b-instruct",+ system="s",+ messages=[{"role": "user", "content": "hi"}],+ provider="fireworks",+ )++ with patch("products.ai_observability.backend.llm.providers.openai.openai.OpenAI", return_value=mock_client):+ with pytest.raises(QuotaExceededError, match="suspended"):+ FireworksAdapter().complete(request, api_key="fw-test-key", analytics=AnalyticsContext(capture=False))diff --git a/products/ai_observability/backend/llm/providers/test/test_openai_adapter.py b/products/ai_observability/backend/llm/providers/test/test_openai_adapter.pyindex a364e990a5df..6760865a2d88 100644--- a/products/ai_observability/backend/llm/providers/test/test_openai_adapter.py+++ b/products/ai_observability/backend/llm/providers/test/test_openai_adapter.py@@ -171,16 +171,21 @@ class TestOpenAIAdapterErrorMapping:request_no_structured_output, api_key="sk-test", analytics=AnalyticsContext(capture=False))- def test_non_402_status_error_is_not_swallowed(self, request_no_structured_output: CompletionRequest):+ @parameterized.expand([("server_error", 500), ("precondition_failed", 412)])+ def test_non_quota_status_error_is_not_swallowed(self, _name: str, status_code: int):adapter = OpenAIAdapter()mock_client = MagicMock()- mock_client.chat.completions.create.side_effect = _make_api_status_error(500, "server error")+ mock_client.chat.completions.create.side_effect = _make_api_status_error(status_code, "provider error")+ request = CompletionRequest(+ model="gpt-4.1",+ system="s",+ messages=[{"role": "user", "content": "hi"}],+ provider="openai",+ )with patch("products.ai_observability.backend.llm.providers.openai.openai.OpenAI", return_value=mock_client):with pytest.raises(openai.APIStatusError):- adapter.complete(- request_no_structured_output, api_key="sk-test", analytics=AnalyticsContext(capture=False)- )+ adapter.complete(request, api_key="sk-test", analytics=AnalyticsContext(capture=False))@parameterized.expand([