Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(router): fail over on 402 Payment Required instead of hard 502 (#196)

Chong Jia Zhen2184e0f52f9e
diff --git a/server/src/__tests__/routes/proxy-retry.test.ts b/server/src/__tests__/routes/proxy-retry.test.ts
index e46d1c24..2eea16ac 100644
--- a/server/src/__tests__/routes/proxy-retry.test.ts
+++ b/server/src/__tests__/routes/proxy-retry.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { isRetryableError } from '../../routes/proxy.js';
+import { isRetryableError, isPaymentRequiredError } from '../../routes/proxy.js';
describe('isRetryableError', () => {
describe('413 Payload Too Large', () => {
@@ -53,6 +53,25 @@ describe('isRetryableError', () => {
});
});
+ describe('402 Payment Required out-of-credits fails over (graceful degradation)', () => {
+ it('treats a HuggingFace Router 402 as retryable (same model lives on other providers)', () => {
+ expect(isRetryableError(new Error('HuggingFace Router API error 402: Payment required'))).toBe(true);
+ });
+
+ it('catches common out-of-credits phrasings', () => {
+ expect(isRetryableError(new Error('Payment Required'))).toBe(true);
+ expect(isRetryableError(new Error('You exceeded your current quota: insufficient_quota'))).toBe(true);
+ expect(isRetryableError(new Error('Insufficient credit for this request'))).toBe(true);
+ expect(isRetryableError(new Error('Insufficient balance'))).toBe(true);
+ });
+
+ it('isPaymentRequiredError flags 402 (drives the long bench) but not a 429', () => {
+ expect(isPaymentRequiredError(new Error('HuggingFace Router API error 402: Payment required'))).toBe(true);
+ expect(isPaymentRequiredError(new Error('429 Too Many Requests'))).toBe(false);
+ expect(isPaymentRequiredError(new Error('503 Service Unavailable'))).toBe(false);
+ });
+ });
+
describe('existing categories still classify correctly', () => {
it('429 / rate limits are retryable', () => {
expect(isRetryableError(new Error('429 Too Many Requests'))).toBe(true);
diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.ts
index e15d9fde..9a7d81a2 100644
--- a/server/src/routes/proxy.ts
+++ b/server/src/routes/proxy.ts
@@ -4,7 +4,7 @@ import type { Request, Response } from 'express';
import { z } from 'zod';
import type { ChatMessage } from '@freellmapi/shared/types.js';
import { routeRequest, recordRateLimitHit, recordSuccess, hasEnabledVisionModel, hasEnabledToolsModel, type RouteResult } from '../services/router.js';
-import { recordRequest, recordTokens, setCooldown, getCooldownDurationForLimit } from '../services/ratelimit.js';
+import { recordRequest, recordTokens, setCooldown, getCooldownDurationForLimit, PAYMENT_REQUIRED_COOLDOWN_MS } from '../services/ratelimit.js';
import { pruneRequestAnalytics } from '../services/request-retention.js';
import { runEmbeddings, EmbeddingsError } from '../services/embeddings.js';
import { getDb, getUnifiedApiKey } from '../db/index.js';
@@ -238,7 +238,23 @@ export function isRetryableError(err: any): boolean {
// limits, unsupported params). The matching pattern is "api error 400"
// which comes from the OpenAI-compat provider's error formatting, not
// a bare "400" which is deliberately non-retryable for validation errors.
- || msg.includes('api error 400');
+ || msg.includes('api error 400')
+ // 402: this provider/key is out of credits (e.g. HuggingFace Router
+ // "API error 402: Payment required"). The SAME model often lives on another
+ // provider (Kimi K2.6 is on HF + Cloudflare + NVIDIA), so fail over instead
+ // of killing the workflow. Paired with a long cooldown (isPaymentRequiredError)
+ // so we don't re-hammer the broke key every retry.
+ || isPaymentRequiredError(err);
+}
+
+// A 402 Payment Required / out-of-credits error. Distinct from a transient 429:
+// it won't recover on the next window, so the caller benches the model+key with
+// PAYMENT_REQUIRED_COOLDOWN_MS (a full day) rather than the 90s transient cooldown.
+export function isPaymentRequiredError(err: any): boolean {
+ const msg = (err.message ?? '').toLowerCase();
+ return msg.includes('402') || msg.includes('payment required')
+ || msg.includes('insufficient_quota') || msg.includes('insufficient credit')
+ || msg.includes('insufficient balance');
}
// Pull the incremental text out of a streaming chunk for token counting.
@@ -599,10 +615,12 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
route.platform,
route.modelId,
route.keyId,
- getCooldownDurationForLimit(route.platform, route.modelId, route.keyId, {
- rpd: route.rpdLimit,
- tpd: route.tpdLimit,
- }),
+ isPaymentRequiredError(err)
+ ? PAYMENT_REQUIRED_COOLDOWN_MS
+ : getCooldownDurationForLimit(route.platform, route.modelId, route.keyId, {
+ rpd: route.rpdLimit,
+ tpd: route.tpdLimit,
+ }),
);
recordRateLimitHit(route.modelDbId);
lastError = err;
diff --git a/server/src/routes/responses.ts b/server/src/routes/responses.ts
index fc8c7cec..790825aa 100644
--- a/server/src/routes/responses.ts
+++ b/server/src/routes/responses.ts
@@ -9,12 +9,13 @@ import type {
ChatToolChoice,
} from '@freellmapi/shared/types.js';
import { routeRequest, recordRateLimitHit, recordSuccess, hasEnabledToolsModel, type RouteResult } from '../services/router.js';
-import { recordRequest, recordTokens, setCooldown, getCooldownDurationForLimit } from '../services/ratelimit.js';
+import { recordRequest, recordTokens, setCooldown, getCooldownDurationForLimit, PAYMENT_REQUIRED_COOLDOWN_MS } from '../services/ratelimit.js';
import { getUnifiedApiKey } from '../db/index.js';
import { contentToString } from '../lib/content.js';
import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';
import {
isRetryableError,
+ isPaymentRequiredError,
timingSafeStringEqual,
extractApiToken,
getStickyModel,
@@ -557,7 +558,9 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
if (isRetryableError(err)) {
skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);
- setCooldown(route.platform, route.modelId, route.keyId, getCooldownDurationForLimit(route.platform, route.modelId, route.keyId, { rpd: route.rpdLimit, tpd: route.tpdLimit }));
+ setCooldown(route.platform, route.modelId, route.keyId, isPaymentRequiredError(err)
+ ? PAYMENT_REQUIRED_COOLDOWN_MS
+ : getCooldownDurationForLimit(route.platform, route.modelId, route.keyId, { rpd: route.rpdLimit, tpd: route.tpdLimit }));
recordRateLimitHit(route.modelDbId);
lastError = err;
continue;
diff --git a/server/src/services/ratelimit.ts b/server/src/services/ratelimit.ts
index 0c4c778f..62344cb6 100644
--- a/server/src/services/ratelimit.ts
+++ b/server/src/services/ratelimit.ts
@@ -301,6 +301,13 @@ export function getNextCooldownDuration(platform: string, modelId: string, keyId
// Short cooldown for a transient (per-minute) 429 — recovers within ~one window.
const TRANSIENT_COOLDOWN_MS = 90 * 1000;
+// Long cooldown for a 402 Payment Required (provider/key out of credits). Unlike
+// a 429, this won't clear on the next minute/day window — it needs a top-up or
+// billing reset. Bench the model+key for a full day so the router fails over to
+// other providers instead of re-hammering a dead key every retry. Re-escalates
+// on the next 402 after expiry if still unpaid; a restart re-benches on first hit.
+export const PAYMENT_REQUIRED_COOLDOWN_MS = DAY;
+
// Decide how long to bench a model+key after an upstream 429. Escalate to the
// long quarantine (getNextCooldownDuration, up to 24h) ONLY when the model is
// genuinely at its DAILY limit (RPD or TPD) — that won't recover until the