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(fallback): stop the digits 402 in a token count benching a whole provider, let ACLIDE errors fail over (#1282)

Tashfeenb882473c3a23
diff --git a/server/src/__tests__/providers/aclide.test.ts b/server/src/__tests__/providers/aclide.test.ts
index 290c910b..ab77ce0c 100644
--- a/server/src/__tests__/providers/aclide.test.ts
+++ b/server/src/__tests__/providers/aclide.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { AclideProvider } from '../../providers/aclide.js';
import { getProvider } from '../../providers/index.js';
import { AUTH_JSON_PROVIDER_MAP, detectPlatform } from '../../lib/key-parser.js';
+import { isRetryableError } from '../../lib/error-classify.js';
const model = 'z-ai/glm-4.7-flashx';
const messages = [{ role: 'user' as const, content: 'Say OK' }];
@@ -135,4 +136,24 @@ describe('ACLIDE Responses adapter', () => {
await expect(new AclideProvider().chatCompletion('k', [{ role: 'user', content: [{ type: 'input_audio', input_audio: {} }] }], model)).rejects.toThrow('content block');
expect(fetch).not.toHaveBeenCalled();
});
+
+ // #1277 follow-up: these used to be fatal, so one ACLIDE hop ended the chain.
+ it('words a 400 so the chain fails over instead of ending', async () => {
+ vi.spyOn(global, 'fetch').mockResolvedValue(json({ error: { message: 'invalid parameter temperature' } }, 400));
+ const err = await new AclideProvider().chatCompletion('k', messages, model).catch((e: unknown) => e);
+ expect(err).toMatchObject({ status: 400 });
+ expect((err as Error).message).toContain('ACLIDE API error 400:');
+ expect((err as Error).message).toContain('invalid parameter temperature');
+ expect(isRetryableError(err)).toBe(true);
+ });
+
+ it('lets another provider serve a request shape it cannot express', async () => {
+ const provider = new AclideProvider();
+ const audio = await provider.chatCompletion('k', [{ role: 'user', content: [{ type: 'input_audio', input_audio: {} }] }], model).catch((e: unknown) => e);
+ const tool = await provider.chatCompletion('k', [{ role: 'tool', content: 'x' }], model).catch((e: unknown) => e);
+ for (const err of [audio, tool]) {
+ expect(err).toMatchObject({ status: 422 });
+ expect(isRetryableError(err)).toBe(true);
+ }
+ });
});
diff --git a/server/src/__tests__/routes/proxy-retry.test.ts b/server/src/__tests__/routes/proxy-retry.test.ts
index 49ecf0a4..1bf885b4 100644
--- a/server/src/__tests__/routes/proxy-retry.test.ts
+++ b/server/src/__tests__/routes/proxy-retry.test.ts
@@ -211,6 +211,31 @@ describe('isRetryableError', () => {
expect(isPaymentRequiredError(new Error('429 Too Many Requests'))).toBe(false);
expect(isPaymentRequiredError(new Error('503 Service Unavailable'))).toBe(false);
});
+
+ // #1277 follow-up: the digits 402 inside a token count or id are not a
+ // status. The 402 bench takes the key off every model of the platform for
+ // a day, so these false positives emptied whole providers.
+ it('isPaymentRequiredError ignores 402 inside other numbers and under another status', () => {
+ for (const message of [
+ 'groq API error 413: Request too large. Limit 30000, Requested 34026',
+ 'openrouter API error 429: rate limit, 14023 tokens used',
+ 'provider API error 500: upstream request id 8f402ab',
+ 'ACLIDE API error 400: max_tokens 402 is below the minimum',
+ 'timeout after 4.402s',
+ ]) {
+ expect(isPaymentRequiredError(new Error(message)), message).toBe(false);
+ }
+ expect(isPaymentRequiredError(Object.assign(new Error('Requested 402 tokens'), { status: 413 }))).toBe(false);
+ });
+
+ it('isPaymentRequiredError still catches every real out-of-credits shape', () => {
+ expect(isPaymentRequiredError(new Error('402 Payment Required'))).toBe(true);
+ expect(isPaymentRequiredError(new Error('upstream returned 402'))).toBe(true);
+ expect(isPaymentRequiredError(Object.assign(new Error('no credits left'), { status: 402 }))).toBe(true);
+ expect(isPaymentRequiredError(new Error('Pollinations API error 402: insufficient credit'))).toBe(true);
+ expect(isPaymentRequiredError(new Error('provider API error 429: insufficient balance (1008)'))).toBe(true);
+ expect(isPaymentRequiredError(new Error('openai API error 429: insufficient_quota'))).toBe(true);
+ });
});
describe('410 Gone & un-enumerated upstream statuses fail over instead of 502 (#337/#339)', () => {
diff --git a/server/src/lib/error-classify.ts b/server/src/lib/error-classify.ts
index cf645938..8d96c70d 100644
--- a/server/src/lib/error-classify.ts
+++ b/server/src/lib/error-classify.ts
@@ -485,11 +485,26 @@ export function isContextTooLargeError(err: any): boolean {
// 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.
+//
+// The digits 402 only count as the STATUS. A bare `includes('402')` also
+// matched token counts and request ids ("Limit 30000, Requested 34026",
+// "14023 tokens used"), and since the 402 bench covers the key on every model
+// of the platform for a day (#1239), one unlucky number took a whole provider
+// out. So: an error that states another status is never a 402 by its digits,
+// and otherwise 402 has to stand alone rather than sit inside a longer number.
+const STATED_STATUS = /\bapi error (\d{3})\b|\(http (\d{3})\)/;
+const STANDALONE_402 = /(?<![\w.])402(?![\w.])/;
+
export function isPaymentRequiredError(err: any): boolean {
- const msg = (err.message ?? '').toLowerCase();
- return msg.includes('402') || msg.includes('payment required')
+ const msg = String(err?.message ?? '').toLowerCase();
+ if (msg.includes('payment required')
|| msg.includes('insufficient_quota') || msg.includes('insufficient credit')
- || msg.includes('insufficient balance');
+ || msg.includes('insufficient balance')) return true;
+
+ const stated = msg.match(STATED_STATUS);
+ const status = typeof err?.status === 'number' ? err.status : Number(stated?.[1] ?? stated?.[2]);
+ if (Number.isFinite(status)) return status === 402;
+ return STANDALONE_402.test(msg);
}
// "model 'x' does not exist" / "model \"x\" does not exist" / "model x does not
diff --git a/server/src/providers/aclide.ts b/server/src/providers/aclide.ts
index 777450b8..581ab511 100644
--- a/server/src/providers/aclide.ts
+++ b/server/src/providers/aclide.ts
@@ -37,6 +37,13 @@ function upstreamError(message: string): Error {
return Object.assign(new Error(`ACLIDE ${message}`), { status: 502 });
}
+// A request this adapter cannot express is ACLIDE's limit, not the caller's
+// mistake: stamped 422 so the chain moves on to a provider that can serve it
+// instead of ending at the first hop.
+function unsupportedRequest(message: string): Error {
+ return Object.assign(new Error(`ACLIDE ${message}`), { status: 422 });
+}
+
/** ACLIDE exposes Responses, NOT Chat Completions. Streaming clients receive
* buffered compatibility chunks after a terminal response, as with Sail.
* No model rows are seeded here: the signed catalog owns the release gate. */
@@ -52,7 +59,7 @@ export class AclideProvider extends BaseProvider {
const input: Record<string, unknown>[] = [];
for (const message of messages) {
if (message.role === 'tool') {
- if (!message.tool_call_id) throw new Error('ACLIDE tool messages require tool_call_id');
+ if (!message.tool_call_id) throw unsupportedRequest('tool messages require tool_call_id');
input.push({ type: 'function_call_output', call_id: message.tool_call_id, output: contentToString(message.content) });
continue;
}
@@ -67,7 +74,7 @@ export class AclideProvider extends BaseProvider {
if (typeof image?.url === 'string') return { type: 'input_image', image_url: image.url, ...(image.detail ? { detail: image.detail } : {}) };
}
// Never silently erase media the caller relied on.
- throw new Error(`ACLIDE does not support this content block: ${part.type ?? 'unknown'}`);
+ throw unsupportedRequest(`does not support this content block: ${part.type ?? 'unknown'}`);
});
}
if (contentToString(message.content) || !message.tool_calls?.length || Array.isArray(content) && content.length) {
@@ -123,7 +130,9 @@ export class AclideProvider extends BaseProvider {
const body = await res.text();
let detail: unknown = body;
try { detail = JSON.parse(body); } catch { /* Keep non-JSON diagnostics. */ }
- throw providerHttpError(res, `ACLIDE error (HTTP ${res.status})`, detail);
+ // The shared "<name> API error <status>: <text>" wording is what the
+ // failover classifier reads; without it a 400 ended the whole chain.
+ throw providerHttpError(res, `ACLIDE API error ${res.status}: ${body.slice(0, 500)}`, detail);
}
const response = await res.json() as AclideResponse;
if (response.model !== modelId) throw upstreamError('returned a different or missing model identity');