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(proxy): surface provider 400 exhaustion as invalid request
Kair Wanga3c8838acc8a
diff --git a/server/src/__tests__/routes/proxy-error-redaction.test.ts b/server/src/__tests__/routes/proxy-error-redaction.test.tsindex 1751b99e..14a807d7 100644--- a/server/src/__tests__/routes/proxy-error-redaction.test.ts+++ b/server/src/__tests__/routes/proxy-error-redaction.test.ts@@ -101,4 +101,36 @@ describe('Provider error redaction', () => {expect(analyticsText).not.toContain(leakedUrl);expect(analyticsText).toContain('[redacted]');});++ it('returns invalid_request_error when provider API 400s exhaust a pinned route', async () => {+ const origFetch = global.fetch;++ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {+ const urlStr = typeof url === 'string' ? url : url.toString();+ if (urlStr.includes('api.groq.com/openai/v1/chat/completions')) {+ return {+ ok: false,+ status: 400,+ statusText: 'Bad Request',+ headers: new Headers(),+ json: () => Promise.resolve({+ error: {+ message: 'tool schema not supported',+ },+ }),+ } as any;+ }+ return origFetch(url, init);+ });++ const completion = await request(app, 'POST', '/v1/chat/completions', {+ model: 'groq/compound-mini',+ messages: [{ role: 'user', content: 'hello' }],+ }, authHeaders());++ expect(completion.status).toBe(400);+ expect(completion.body.error.type).toBe('invalid_request_error');+ expect(completion.body.error.message).toContain('rejected the request as invalid');+ expect(completion.body.error.message).toContain('Groq API error 400');+ });});diff --git a/server/src/__tests__/routes/proxy-retry.test.ts b/server/src/__tests__/routes/proxy-retry.test.tsindex a1825363..de550a2f 100644--- a/server/src/__tests__/routes/proxy-retry.test.ts+++ b/server/src/__tests__/routes/proxy-retry.test.ts@@ -1,5 +1,6 @@import { describe, it, expect } from 'vitest';import { isRetryableError, isPaymentRequiredError, isModelNotFoundError, isModelAccessForbiddenError } from '../../routes/proxy.js';+import { isProviderBadRequestError } from '../../lib/error-classify.js';describe('isModelAccessForbiddenError (403 model-not-on-tier, drives whole-model skip — issue #256)', () => {it('flags a 403 reaching the proxy by message or attached status', () => {@@ -88,6 +89,16 @@ describe('isRetryableError', () => {it('but a bare validation "400 Bad Request" (our own schema) is still NOT retryable', () => {expect(isRetryableError(new Error('400 Bad Request'))).toBe(false);});++ it('flags provider API 400s for invalid-request exhaustion reporting', () => {+ const err = Object.assign(+ new Error('Google API error 400: Invalid JSON payload received. Unknown name "x-google-enum-descriptions"'),+ { status: 400 },+ );+ expect(isProviderBadRequestError(err)).toBe(true);+ expect(isProviderBadRequestError(new Error('400 Bad Request'))).toBe(false);+ expect(isProviderBadRequestError(Object.assign(new Error('Bad Request'), { status: 400 }))).toBe(false);+ });});describe('403 model not on this key\'s tier fails over instead of 502 (issue #256)', () => {diff --git a/server/src/__tests__/routes/responses.test.ts b/server/src/__tests__/routes/responses.test.tsindex e124566e..db380229 100644--- a/server/src/__tests__/routes/responses.test.ts+++ b/server/src/__tests__/routes/responses.test.ts@@ -171,4 +171,27 @@ describe('POST /v1/responses (#96)', () => {const lastCall = mockRouteRequest.mock.calls.at(-1);expect(lastCall?.[4]).toBe(true);});++ it('non-stream: returns invalid_request_error when provider API 400s exhaust routing', async () => {+ mockRouteRequest.mockImplementation((_estimated, skipKeys) => {+ if (skipKeys?.size) {+ throw Object.assign(new Error('All models exhausted'), { status: 429 });+ }+ return fakeRoute({+ async chatCompletion() {+ throw Object.assign(+ new Error('Google API error 400: Invalid JSON payload received. Unknown name "x-google-enum-descriptions"'),+ { status: 400 },+ );+ },+ async *streamChatCompletion() { /* unused */ },+ });+ });++ const { status, text } = await post(app, '/v1/responses', { input: 'hi', stream: false }, key);+ const body = JSON.parse(text);+ expect(status).toBe(400);+ expect(body.error.type).toBe('invalid_request_error');+ expect(body.error.message).toContain('rejected the request as invalid');+ });});diff --git a/server/src/lib/error-classify.ts b/server/src/lib/error-classify.tsindex e1664851..9e0cad3b 100644--- a/server/src/lib/error-classify.ts+++ b/server/src/lib/error-classify.ts@@ -68,6 +68,15 @@ export function isRetryableError(err: any): boolean {|| msg.includes('unparseable inline tool-call dialect');}+// Provider-side 400s are retryable because another provider may accept the same+// request shape. If every routed provider rejects it, however, the client should+// see an invalid-request error rather than a misleading rate-limit exhaustion.+export function isProviderBadRequestError(err: any): boolean {+ const status = typeof err?.status === 'number' ? err.status : 0;+ const msg = (err?.message ?? '').toLowerCase();+ return (status === 0 || status === 400) && msg.includes('api error 400');+}+// 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.diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 708da15b..4d4a754c 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -14,7 +14,7 @@ import { sanitizeProviderErrorMessage } from '../lib/error-redaction.js';import { rescueInlineToolCalls, startsWithDialectMarker, couldBecomeDialectMarker, containsDialectMarker } from '../lib/tool-call-rescue.js';import { getContextHandoffMode, recordIncomingMessages, maybeInjectContextHandoff, recordSuccessfulModel, hasPriorModel, HANDOFF_MAX_TOKENS } from '../services/context-handoff.js';import { isFusionModel, runFusion, fusionConfigSchema, FusionError, FUSION_MODEL_ID } from '../services/fusion.js';-import { isRetryableError, isPaymentRequiredError, isModelNotFoundError, isModelAccessForbiddenError } from '../lib/error-classify.js';+import { isRetryableError, isPaymentRequiredError, isModelNotFoundError, isModelAccessForbiddenError, isProviderBadRequestError } from '../lib/error-classify.js';import { logRequest } from '../lib/request-log.js';import type { Platform } from '@freellmapi/shared/types.js';import { inferQuotaPoolKey, type QuotaObservationContext } from '../services/provider-quota.js';@@ -122,6 +122,23 @@ export function traceRouteEvent(console.log(parts.join(' '));}+export function exhaustedRetryError(lastError: any, maxRetries?: number) {+ const safeLastError = sanitizeProviderErrorMessage(lastError?.message);+ if (isProviderBadRequestError(lastError)) {+ return {+ status: 400,+ type: 'invalid_request_error',+ message: `All routed providers rejected the request as invalid. Last error: ${safeLastError}`,+ };+ }+ const scope = maxRetries == null ? 'All models rate-limited' : `All models rate-limited after ${maxRetries} attempts`;+ return {+ status: 429,+ type: 'rate_limit_error',+ message: `${scope}. Last error: ${safeLastError}`,+ };+}+// Sticky sessions: track which model served each "session"// Key: hash of first user message → model_db_id// This prevents model switching mid-conversation which causes hallucination@@ -698,10 +715,11 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {);} catch (err: any) {if (lastError) {- res.status(429).json({+ const error = exhaustedRetryError(lastError);+ res.status(error.status).json({error: {- message: `All models rate-limited. Last error: ${sanitizeProviderErrorMessage(lastError.message)}`,- type: 'rate_limit_error',+ message: error.message,+ type: error.type,},});} else {@@ -907,10 +925,11 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {}}- res.status(429).json({+ const error = exhaustedRetryError(lastError, MAX_RETRIES);+ res.status(error.status).json({error: {- message: `All models rate-limited after ${MAX_RETRIES} attempts. Last: ${sanitizeProviderErrorMessage(lastError?.message)}`,- type: 'rate_limit_error',+ message: error.message,+ type: error.type,},});});@@ -1322,11 +1341,11 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {} catch (err: any) {// No more models availableif (lastError) {- const safeLastError = sanitizeProviderErrorMessage(lastError.message);- res.status(429).json({+ const error = exhaustedRetryError(lastError);+ res.status(error.status).json({error: {- message: `All models rate-limited. Last error: ${safeLastError}`,- type: 'rate_limit_error',+ message: error.message,+ type: error.type,},});} else {@@ -1782,10 +1801,11 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {}// Exhausted all retries- res.status(429).json({+ const error = exhaustedRetryError(lastError, MAX_RETRIES);+ res.status(error.status).json({error: {- message: `All models rate-limited after ${MAX_RETRIES} attempts. Last: ${sanitizeProviderErrorMessage(lastError?.message)}`,- type: 'rate_limit_error',+ message: error.message,+ type: error.type,},});});diff --git a/server/src/routes/responses.ts b/server/src/routes/responses.tsindex e009e07f..7535425e 100644--- a/server/src/routes/responses.ts+++ b/server/src/routes/responses.ts@@ -26,6 +26,7 @@ import {getStickyModel,setStickyModel,traceRouteEvent,+ exhaustedRetryError,logRequest,} from './proxy.js';import { sanitizeProviderErrorMessage } from '../lib/error-redaction.js';@@ -382,11 +383,10 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {try {route = routeRequest(estimatedTotal, skipKeys.size > 0 ? skipKeys : undefined, preferredModel, false, wantsTools, skipModels.size > 0 ? skipModels : undefined);} catch (err: any) {- const status = lastError ? 429 : (err.status ?? 503);- const message = lastError- ? `All models rate-limited. Last error: ${sanitizeProviderErrorMessage(lastError.message)}`- : err.message;- const type = lastError ? 'rate_limit_error' : 'routing_error';+ const exhausted = lastError ? exhaustedRetryError(lastError) : null;+ const status = exhausted?.status ?? err.status ?? 503;+ const message = exhausted?.message ?? err.message;+ const type = exhausted?.type ?? 'routing_error';if (streamStarted) {sse('response.failed', { response: { id: responseId, object: 'response', status: 'failed', error: { message, type } } });res.end();@@ -782,13 +782,13 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {// (reachable since empty-completion failover can burn every attempt after// streamStarted) — close the SSE stream with a failed event instead of// writing JSON onto a committed event-stream response.- const exhaustedMsg = `All models rate-limited after ${MAX_RETRIES} attempts. Last: ${lastError?.message}`;+ const exhausted = exhaustedRetryError(lastError, MAX_RETRIES);if (streamStarted) {- sse('response.failed', { response: { id: responseId, object: 'response', status: 'failed', error: { message: exhaustedMsg, type: 'rate_limit_error' } } });+ sse('response.failed', { response: { id: responseId, object: 'response', status: 'failed', error: { message: exhausted.message, type: exhausted.type } } });res.end();return;}- res.status(429).json({- error: { message: exhaustedMsg, type: 'rate_limit_error' },+ res.status(exhausted.status).json({+ error: { message: exhausted.message, type: exhausted.type },});});