Skip to content

🙌 OpenHands: AI-Driven Development

fix(enterprise): avoid rotating keys on LiteLLM non-auth errors (#15267)

Saurya Velagapudi96f902a9ac14
diff --git a/enterprise/storage/lite_llm_manager.py b/enterprise/storage/lite_llm_manager.py
index 8bd2a28390..0ff0273710 100644
--- a/enterprise/storage/lite_llm_manager.py
+++ b/enterprise/storage/lite_llm_manager.py
@@ -1377,12 +1377,34 @@ class LiteLlmManager:
user_id: The user ID for logging purposes
Returns:
- True if the key is verified as valid, False if verification fails or key is invalid.
- Returns False on network errors/timeouts to ensure we don't return potentially invalid keys.
+ True if the key is verified as valid or verification is inconclusive.
+ False only when LiteLLM explicitly reports an auth failure.
"""
if not (LITE_LLM_API_URL and key):
return False
+ def _extract_error_message(response: httpx.Response) -> str:
+ try:
+ message = response.text or ''
+ except Exception:
+ message = ''
+ if message:
+ return message
+ try:
+ payload = response.json()
+ except Exception:
+ return ''
+ if isinstance(payload, dict):
+ for field in ('detail', 'error', 'message'):
+ value = payload.get(field)
+ if isinstance(value, str):
+ return value
+ return ''
+
+ def _is_budget_exceeded(message: str) -> bool:
+ lower = message.lower()
+ return 'budget' in lower and 'exceeded' in lower
+
try:
async with httpx.AsyncClient(
verify=httpx_verify_option(),
@@ -1405,30 +1427,49 @@ class LiteLlmManager:
)
return True
- # All other status codes (401, 403, 500, etc.) are treated as invalid
- # This includes authentication errors and server errors
+ if response.status_code in (401, 403):
+ logger.warning(
+ 'Key verification failed - invalid credentials',
+ extra={
+ 'user_id': user_id,
+ 'status_code': response.status_code,
+ 'key_prefix': key[:10] + '...' if len(key) > 10 else key,
+ },
+ )
+ return False
+
+ error_message = _extract_error_message(response)
+ if response.status_code == 400 and _is_budget_exceeded(error_message):
+ logger.info(
+ 'Key verification blocked by budget exceeded - preserving key',
+ extra={
+ 'user_id': user_id,
+ 'status_code': response.status_code,
+ 'key_prefix': key[:10] + '...' if len(key) > 10 else key,
+ },
+ )
+ return True
+
logger.warning(
- 'Key verification failed - treating as invalid',
+ 'Key verification inconclusive - preserving key',
extra={
'user_id': user_id,
'status_code': response.status_code,
'key_prefix': key[:10] + '...' if len(key) > 10 else key,
},
)
- return False
+ return True
except (httpx.TimeoutException, Exception) as e:
- # Any exception (timeout, network error, etc.) means we can't verify
- # Return False to trigger regeneration rather than returning potentially invalid key
logger.warning(
- 'Key verification error - treating as invalid to ensure key validity',
+ 'Key verification error - preserving key',
extra={
'user_id': user_id,
'error': str(e),
'error_type': type(e).__name__,
},
)
- return False
+ return True
@staticmethod
async def _get_key_info(
@@ -1469,7 +1510,7 @@ class LiteLlmManager:
async def _get_all_keys_for_user(
client: httpx.AsyncClient,
keycloak_user_id: str,
- ) -> list[dict]:
+ ) -> list[dict] | None:
"""Get all keys for a user from LiteLLM.
Returns a list of key info dictionaries containing:
@@ -1481,31 +1522,61 @@ class LiteLlmManager:
- team_id: the team the key belongs to
- metadata: any metadata associated with the key
- Returns an empty list if no keys found or on error.
+ Returns None when the LiteLLM request fails so callers can skip
+ invalidation on transient errors.
"""
if LITE_LLM_API_KEY is None or LITE_LLM_API_URL is None:
logger.warning('LiteLLM API configuration not found')
- return []
+ return None
try:
response = await client.get(
f'{LITE_LLM_API_URL}/user/info?user_id={keycloak_user_id}',
headers={'x-goog-api-key': LITE_LLM_API_KEY},
)
- response.raise_for_status()
- user_json = response.json()
- # The user/info endpoint returns keys in the 'keys' field
- return user_json.get('keys', [])
except Exception as e:
logger.warning(
- 'LiteLlmManager:_get_all_keys_for_user:error',
+ 'LiteLlmManager:_get_all_keys_for_user:request_error',
extra={
'user_id': keycloak_user_id,
'error': str(e),
},
)
+ return None
+
+ if response.status_code == 404:
+ logger.info(
+ 'LiteLlmManager:_get_all_keys_for_user:not_found',
+ extra={'user_id': keycloak_user_id},
+ )
return []
+ if not response.is_success:
+ logger.warning(
+ 'LiteLlmManager:_get_all_keys_for_user:request_failed',
+ extra={
+ 'user_id': keycloak_user_id,
+ 'status_code': response.status_code,
+ 'text': response.text,
+ },
+ )
+ return None
+
+ try:
+ user_json = response.json()
+ except Exception as e:
+ logger.warning(
+ 'LiteLlmManager:_get_all_keys_for_user:parse_failed',
+ extra={
+ 'user_id': keycloak_user_id,
+ 'error': str(e),
+ },
+ )
+ return None
+
+ # The user/info endpoint returns keys in the 'keys' field
+ return user_json.get('keys', [])
+
@staticmethod
async def _verify_existing_key(
client: httpx.AsyncClient,
@@ -1525,6 +1596,15 @@ class LiteLlmManager:
"""
found = False
keys = await LiteLlmManager._get_all_keys_for_user(client, keycloak_user_id)
+ if keys is None:
+ logger.warning(
+ 'LiteLlmManager:_verify_existing_key:skip_invalidation',
+ extra={
+ 'user_id': keycloak_user_id,
+ 'org_id': org_id,
+ },
+ )
+ return True
for key_info in keys:
metadata = key_info.get('metadata') or {}
team_id = key_info.get('team_id')
diff --git a/enterprise/tests/unit/server/routes/test_api_keys.py b/enterprise/tests/unit/server/routes/test_api_keys.py
index 1f5b6f57eb..8c6b5fa8be 100644
--- a/enterprise/tests/unit/server/routes/test_api_keys.py
+++ b/enterprise/tests/unit/server/routes/test_api_keys.py
@@ -116,14 +116,37 @@ class TestVerifyByorKeyInLitellm:
@pytest.mark.asyncio
@patch('storage.lite_llm_manager.LITE_LLM_API_URL', 'https://litellm.example.com')
@patch('storage.lite_llm_manager.httpx.AsyncClient')
- async def test_verify_server_error_returns_false(self, mock_client_class):
- """Test that a server error (500) returns False to ensure key validity."""
+ async def test_verify_budget_exceeded_returns_true(self, mock_client_class):
+ """Test that budget exceeded responses preserve the key."""
+ # Arrange
+ byor_key = 'sk-budget-key-123'
+ user_id = 'user-123'
+ mock_response = MagicMock()
+ mock_response.status_code = 400
+ mock_response.text = 'Budget has been exceeded!'
+ mock_client = AsyncMock()
+ mock_client.__aenter__.return_value = mock_client
+ mock_client.__aexit__.return_value = None
+ mock_client.get.return_value = mock_response
+ mock_client_class.return_value = mock_client
+
+ # Act
+ result = await LiteLlmManager.verify_key(byor_key, user_id)
+
+ # Assert
+ assert result is True
+
+ @pytest.mark.asyncio
+ @patch('storage.lite_llm_manager.LITE_LLM_API_URL', 'https://litellm.example.com')
+ @patch('storage.lite_llm_manager.httpx.AsyncClient')
+ async def test_verify_server_error_returns_true(self, mock_client_class):
+ """Test that a server error (500) preserves the key."""
# Arrange
byor_key = 'sk-key-123'
user_id = 'user-123'
mock_response = MagicMock()
mock_response.status_code = 500
- mock_response.is_success = False
+ mock_response.text = 'Internal Server Error'
mock_client = AsyncMock()
mock_client.__aenter__.return_value = mock_client
mock_client.__aexit__.return_value = None
@@ -134,13 +157,13 @@ class TestVerifyByorKeyInLitellm:
result = await LiteLlmManager.verify_key(byor_key, user_id)
# Assert
- assert result is False
+ assert result is True
@pytest.mark.asyncio
@patch('storage.lite_llm_manager.LITE_LLM_API_URL', 'https://litellm.example.com')
@patch('storage.lite_llm_manager.httpx.AsyncClient')
- async def test_verify_timeout_returns_false(self, mock_client_class):
- """Test that a timeout returns False to ensure key validity."""
+ async def test_verify_timeout_returns_true(self, mock_client_class):
+ """Test that a timeout preserves the key."""
# Arrange
byor_key = 'sk-key-123'
user_id = 'user-123'
@@ -154,13 +177,13 @@ class TestVerifyByorKeyInLitellm:
result = await LiteLlmManager.verify_key(byor_key, user_id)
# Assert
- assert result is False
+ assert result is True
@pytest.mark.asyncio
@patch('storage.lite_llm_manager.LITE_LLM_API_URL', 'https://litellm.example.com')
@patch('storage.lite_llm_manager.httpx.AsyncClient')
- async def test_verify_network_error_returns_false(self, mock_client_class):
- """Test that a network error returns False to ensure key validity."""
+ async def test_verify_network_error_returns_true(self, mock_client_class):
+ """Test that a network error preserves the key."""
# Arrange
byor_key = 'sk-key-123'
user_id = 'user-123'
@@ -174,7 +197,7 @@ class TestVerifyByorKeyInLitellm:
result = await LiteLlmManager.verify_key(byor_key, user_id)
# Assert
- assert result is False
+ assert result is True
@pytest.mark.asyncio
@patch('storage.lite_llm_manager.LITE_LLM_API_URL', None)
diff --git a/enterprise/tests/unit/test_lite_llm_manager.py b/enterprise/tests/unit/test_lite_llm_manager.py
index c198e3fd61..449c8902d4 100644
--- a/enterprise/tests/unit/test_lite_llm_manager.py
+++ b/enterprise/tests/unit/test_lite_llm_manager.py
@@ -2521,7 +2521,7 @@ class TestGetAllKeysForUser:
result = await LiteLlmManager._get_all_keys_for_user(
mock_client, 'test-user-id'
)
- assert result == []
+ assert result is None
mock_client.get.assert_not_called()
@pytest.mark.asyncio
@@ -2587,7 +2587,7 @@ class TestGetAllKeysForUser:
@pytest.mark.asyncio
async def test_get_all_keys_api_error(self):
- """Test _get_all_keys_for_user handles API errors gracefully."""
+ """Test _get_all_keys_for_user skips invalidation on API errors."""
mock_client = AsyncMock(spec=httpx.AsyncClient)
mock_client.get.side_effect = Exception('API Error')
@@ -2596,7 +2596,7 @@ class TestGetAllKeysForUser:
result = await LiteLlmManager._get_all_keys_for_user(
mock_client, 'test-user-id'
)
- assert result == []
+ assert result is None
class TestVerifyExistingKey:
@@ -2767,6 +2767,25 @@ class TestVerifyExistingKey:
)
assert result is False
+ @pytest.mark.asyncio
+ async def test_verify_existing_key_skips_on_litellm_error(self):
+ """Test _verify_existing_key preserves key when LiteLLM lookup fails."""
+ mock_client = AsyncMock(spec=httpx.AsyncClient)
+
+ with patch.object(
+ LiteLlmManager, '_get_all_keys_for_user', new_callable=AsyncMock
+ ) as mock_get_keys:
+ mock_get_keys.return_value = None
+
+ result = await LiteLlmManager._verify_existing_key(
+ mock_client,
+ 'some-key-value',
+ 'test-user-id',
+ 'test-org',
+ openhands_type=True,
+ )
+ assert result is True
+
@pytest.mark.asyncio
async def test_verify_existing_key_handles_none_key_name(self):
"""Test _verify_existing_key handles None key_name gracefully."""
diff --git a/frontend/__tests__/conversation-websocket-handler.test.tsx b/frontend/__tests__/conversation-websocket-handler.test.tsx
index c57c9530d5..ec9db50e81 100644
--- a/frontend/__tests__/conversation-websocket-handler.test.tsx
+++ b/frontend/__tests__/conversation-websocket-handler.test.tsx
@@ -468,7 +468,7 @@ describe("Conversation WebSocket Handler", () => {
await waitFor(() => {
expect(screen.getByTestId("error-message")).toHaveTextContent(
- "STATUS$ERROR_LLM_OUT_OF_CREDITS",
+ "STATUS$ERROR_BUDGET_LIMIT_REACHED",
);
});
});
diff --git a/frontend/__tests__/utils/error-handler.test.ts b/frontend/__tests__/utils/error-handler.test.ts
index 00bbed4d9f..07a8ec8106 100644
--- a/frontend/__tests__/utils/error-handler.test.ts
+++ b/frontend/__tests__/utils/error-handler.test.ts
@@ -3,7 +3,7 @@ import {
trackError,
showErrorToast,
showChatError,
- isBudgetOrCreditError,
+ classifyBudgetOrCreditError,
} from "#/utils/error-handler";
import * as Actions from "#/services/actions";
import * as CustomToast from "#/utils/custom-toast-handlers";
@@ -87,30 +87,30 @@ describe("Error Handler", () => {
});
});
- describe("isBudgetOrCreditError", () => {
- it("identifies OpenHands budget and credit limit errors", () => {
+ describe("classifyBudgetOrCreditError", () => {
+ it("classifies OpenHands budget and credit limit errors", () => {
expect(
- isBudgetOrCreditError(
+ classifyBudgetOrCreditError(
"Budget has been exceeded! Current cost: 18.51, Max budget: 18.24",
),
- ).toBe(true);
- expect(isBudgetOrCreditError("OpenHands Credits are exhausted")).toBe(
- true,
- );
- expect(isBudgetOrCreditError("Credit limit reached")).toBe(true);
+ ).toBe("budget");
+ expect(
+ classifyBudgetOrCreditError("OpenHands Credits are exhausted"),
+ ).toBe("credit");
+ expect(classifyBudgetOrCreditError("Credit limit reached")).toBe("credit");
});
- it("does not rewrite provider-side credit messages as OpenHands billing errors", () => {
+ it("ignores provider-side credit messages", () => {
expect(
- isBudgetOrCreditError(
+ classifyBudgetOrCreditError(
"OpenrouterException - This model requires provider credits. Check your OpenRouter account.",
),
- ).toBe(false);
+ ).toBeNull();
expect(
- isBudgetOrCreditError(
+ classifyBudgetOrCreditError(
"Provider returned insufficient credits for minimax/minimax-m2.5:free",
),
- ).toBe(false);
+ ).toBeNull();
});
});
});
diff --git a/frontend/src/contexts/conversation-websocket-context.tsx b/frontend/src/contexts/conversation-websocket-context.tsx
index 071836a56a..17875f95be 100644
--- a/frontend/src/contexts/conversation-websocket-context.tsx
+++ b/frontend/src/contexts/conversation-websocket-context.tsx
@@ -49,7 +49,7 @@ import type {
import EventService from "#/api/event-service/event-service.api";
import PendingMessageService from "#/api/pending-message-service/pending-message-service.api";
import { useConversationStore } from "#/stores/conversation-store";
-import { isBudgetOrCreditError, trackError } from "#/utils/error-handler";
+import { classifyBudgetOrCreditError, trackError } from "#/utils/error-handler";
import { useReadConversationFile } from "#/hooks/mutation/use-read-conversation-file";
import useMetricsStore from "#/stores/metrics-store";
import { I18nKey } from "#/i18n/declaration";
@@ -77,6 +77,17 @@ const ConversationWebSocketContext = createContext<
ConversationWebSocketContextType | undefined
>(undefined);
+const getBudgetErrorMessageKey = (errorMessage: string) => {
+ const errorType = classifyBudgetOrCreditError(errorMessage);
+ if (errorType === "credit") {
+ return I18nKey.STATUS$ERROR_LLM_OUT_OF_CREDITS;
+ }
+ if (errorType === "budget") {
+ return I18nKey.STATUS$ERROR_BUDGET_LIMIT_REACHED;
+ }
+ return null;
+};
+
export function ConversationWebSocketProvider({
children,
conversationId,
@@ -145,7 +156,8 @@ export function ConversationWebSocketProvider({
(event: { source?: string }) => {
const currentError = useErrorMessageStore.getState().errorMessage;
const isBudgetError =
- currentError === I18nKey.STATUS$ERROR_LLM_OUT_OF_CREDITS;
+ currentError === I18nKey.STATUS$ERROR_LLM_OUT_OF_CREDITS ||
+ currentError === I18nKey.STATUS$ERROR_BUDGET_LIMIT_REACHED;
const isAgentEvent = event.source === "agent";
// Budget errors persist until agent proves LLM is working
@@ -398,8 +410,9 @@ export function ConversationWebSocketProvider({
errorCode: errorEvent.code,
},
});
- if (isBudgetOrCreditError(errorEvent.detail)) {
- setErrorMessage(I18nKey.STATUS$ERROR_LLM_OUT_OF_CREDITS);
+ const budgetErrorKey = getBudgetErrorMessageKey(errorEvent.detail);
+ if (budgetErrorKey) {
+ setErrorMessage(budgetErrorKey);
} else {
setErrorMessage(errorEvent.detail);
}
@@ -419,8 +432,9 @@ export function ConversationWebSocketProvider({
},
});
// Use friendly i18n message for budget/credit errors instead of raw error
- if (isBudgetOrCreditError(event.error)) {
- setErrorMessage(I18nKey.STATUS$ERROR_LLM_OUT_OF_CREDITS);
+ const budgetErrorKey = getBudgetErrorMessageKey(event.error);
+ if (budgetErrorKey) {
+ setErrorMessage(budgetErrorKey);
} else {
setErrorMessage(event.error);
}
@@ -592,8 +606,9 @@ export function ConversationWebSocketProvider({
errorCode: errorEvent.code,
},
});
- if (isBudgetOrCreditError(errorEvent.detail)) {
- setErrorMessage(I18nKey.STATUS$ERROR_LLM_OUT_OF_CREDITS);
+ const budgetErrorKey = getBudgetErrorMessageKey(errorEvent.detail);
+ if (budgetErrorKey) {
+ setErrorMessage(budgetErrorKey);
} else {
setErrorMessage(errorEvent.detail);
}
@@ -613,8 +628,9 @@ export function ConversationWebSocketProvider({
},
});
// Use friendly i18n message for budget/credit errors instead of raw error
- if (isBudgetOrCreditError(event.error)) {
- setErrorMessage(I18nKey.STATUS$ERROR_LLM_OUT_OF_CREDITS);
+ const budgetErrorKey = getBudgetErrorMessageKey(event.error);
+ if (budgetErrorKey) {
+ setErrorMessage(budgetErrorKey);
} else {
setErrorMessage(event.error);
}
@@ -780,7 +796,13 @@ export function ConversationWebSocketProvider({
setMainConnectionState("CLOSED");
// Only show error message if we've previously connected successfully
if (hasConnectedRefMain.current) {
- setErrorMessage("Failed to connect to server");
+ const currentError = useErrorMessageStore.getState().errorMessage;
+ if (
+ currentError !== I18nKey.STATUS$ERROR_LLM_OUT_OF_CREDITS &&
+ currentError !== I18nKey.STATUS$ERROR_BUDGET_LIMIT_REACHED
+ ) {
+ setErrorMessage("Failed to connect to server");
+ }
}
},
onMessage: handleMainMessage,
@@ -847,7 +869,13 @@ export function ConversationWebSocketProvider({
setPlanningConnectionState("CLOSED");
// Only show error message if we've previously connected successfully
if (hasConnectedRefPlanning.current) {
- setErrorMessage("Failed to connect to server");
+ const currentError = useErrorMessageStore.getState().errorMessage;
+ if (
+ currentError !== I18nKey.STATUS$ERROR_LLM_OUT_OF_CREDITS &&
+ currentError !== I18nKey.STATUS$ERROR_BUDGET_LIMIT_REACHED
+ ) {
+ setErrorMessage("Failed to connect to server");
+ }
}
},
onMessage: handlePlanningMessage,
diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.ts
index 6fa5158acf..1f5efab22d 100644
--- a/frontend/src/i18n/declaration.ts
+++ b/frontend/src/i18n/declaration.ts
@@ -759,6 +759,7 @@ export enum I18nKey {
STATUS$ERROR_LLM_SERVICE_UNAVAILABLE = "STATUS$ERROR_LLM_SERVICE_UNAVAILABLE",
STATUS$ERROR_LLM_INTERNAL_SERVER_ERROR = "STATUS$ERROR_LLM_INTERNAL_SERVER_ERROR",
STATUS$ERROR_LLM_OUT_OF_CREDITS = "STATUS$ERROR_LLM_OUT_OF_CREDITS",
+ STATUS$ERROR_BUDGET_LIMIT_REACHED = "STATUS$ERROR_BUDGET_LIMIT_REACHED",
STATUS$ERROR_LLM_CONTENT_POLICY_VIOLATION = "STATUS$ERROR_LLM_CONTENT_POLICY_VIOLATION",
STATUS$ERROR = "STATUS$ERROR",
STATUS$ERROR_RUNTIME_DISCONNECTED = "STATUS$ERROR_RUNTIME_DISCONNECTED",
diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.json
index 4b2299fa80..267f5370a4 100644
--- a/frontend/src/i18n/translation.json
+++ b/frontend/src/i18n/translation.json
@@ -12902,6 +12902,23 @@
"uk": "У вас закінчилися кредити OpenHands. <a>Додати кошти</a>",
"ca": "No teniu crèdits d'OpenHands. <a>Afegiu fons</a>"
},
+ "STATUS$ERROR_BUDGET_LIMIT_REACHED": {
+ "en": "The organization's budget or the budget associated with your user account has been reached. Please contact your OpenHands Enterprise administrator to request an override.",
+ "ja": "組織の予算、またはあなたのユーザーアカウントに関連付けられた予算に達しました。オーバーライドを依頼するには OpenHands Enterprise 管理者に連絡してください。",
+ "zh-CN": "组织预算或与您的用户账户关联的预算已达到上限。请联系您的 OpenHands Enterprise 管理员申请超额额度。",
+ "zh-TW": "組織預算或與您的使用者帳戶關聯的預算已達上限。請聯絡您的 OpenHands Enterprise 管理員申請覆寫。",
+ "ko-KR": "조직 예산 또는 사용자 계정에 연결된 예산 한도에 도달했습니다. 예산 상향(override)을 요청하려면 OpenHands Enterprise 관리자에게 문의하세요.",
+ "no": "Organisasjonens budsjett eller budsjettet knyttet til brukerkontoen din er nådd. Kontakt OpenHands Enterprise-administratoren for å be om en overstyring.",
+ "it": "È stato raggiunto il budget dell'organizzazione o quello associato al tuo account utente. Contatta l'amministratore OpenHands Enterprise per richiedere un override.",
+ "pt": "O orçamento da organização ou o orçamento associado à sua conta de usuário foi atingido. Entre em contato com o administrador do OpenHands Enterprise para solicitar uma exceção.",
+ "es": "Se alcanzó el presupuesto de la organización o el presupuesto asociado a tu cuenta de usuario. Ponte en contacto con el administrador de OpenHands Enterprise para solicitar una excepción.",
+ "ar": "تم الوصول إلى ميزانية المؤسسة أو الميزانية المرتبطة بحساب المستخدم الخاص بك. يرجى التواصل مع مسؤول OpenHands Enterprise لطلب استثناء.",
+ "fr": "Le budget de l’organisation ou celui associé à votre compte utilisateur a été atteint. Veuillez contacter l’administrateur OpenHands Enterprise pour demander une dérogation.",
+ "tr": "Kuruluşun bütçesine veya kullanıcı hesabınızla ilişkili bütçeye ulaşıldı. İstisna (override) istemek için OpenHands Enterprise yöneticinizle iletişime geçin.",
+ "de": "Das Budget der Organisation oder das mit Ihrem Benutzerkonto verknüpfte Budget wurde erreicht. Bitte wenden Sie sich an Ihren OpenHands Enterprise-Administrator, um eine Ausnahme zu beantragen.",
+ "uk": "Досягнуто бюджету організації або бюджету, пов’язаного з вашим обліковим записом. Будь ласка, зверніться до адміністратора OpenHands Enterprise, щоб запросити виняток.",
+ "ca": "S'ha assolit el pressupost de l'organització o el pressupost associat al vostre compte d'usuari. Poseu-vos en contacte amb l'administrador d'OpenHands Enterprise per sol·licitar una excepció."
+ },
"STATUS$ERROR_LLM_CONTENT_POLICY_VIOLATION": {
"en": "Content policy violation. The output was blocked by content filtering policy.",
"ja": "コンテンツポリシー違反。出力はコンテンツフィルタリングポリシーによってブロックされました。",
diff --git a/frontend/src/utils/error-handler.ts b/frontend/src/utils/error-handler.ts
index 28a8e13f7d..f47033ea82 100644
--- a/frontend/src/utils/error-handler.ts
+++ b/frontend/src/utils/error-handler.ts
@@ -42,14 +42,25 @@ export function showChatError({
* Provider-side errors can also mention "credits"; those should stay as raw
* provider errors instead of being rewritten as OpenHands billing failures.
*/
-export function isBudgetOrCreditError(errorMessage: string): boolean {
+export type BudgetErrorType = "budget" | "credit" | null;
+
+export function classifyBudgetOrCreditError(
+ errorMessage: string,
+): BudgetErrorType {
const lowerCaseError = errorMessage.toLowerCase();
- const isBudgetLimitError =
- lowerCaseError.includes("budget") &&
- /(exceed|exceeded|limit|max budget|spent)/.test(lowerCaseError);
const isOpenHandsCreditError =
/openhands\s+credits?/.test(lowerCaseError) ||
lowerCaseError.includes("credit limit reached");
+ if (isOpenHandsCreditError) {
+ return "credit";
+ }
+
+ const isBudgetLimitError =
+ lowerCaseError.includes("budget") &&
+ /(exceed|exceeded|limit|max budget|spent)/.test(lowerCaseError);
+ if (isBudgetLimitError) {
+ return "budget";
+ }
- return isBudgetLimitError || isOpenHandsCreditError;
+ return null;
}