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

Fail over to the same model on another provider for /v1/messages (#1000)

Tashfeen59db45472e60
diff --git a/README.md b/README.md
index 0da93f6a..9818ce61 100644
--- a/README.md
+++ b/README.md
@@ -348,6 +348,8 @@ Contributors very welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for the dev lo
<a href="https://github.com/VinhPhamAI"><img src="https://images.weserv.nl/?url=github.com/VinhPhamAI.png&w=40&h=40&fit=cover&mask=circle" width="40" alt="@VinhPhamAI" /></a>
<a href="https://github.com/deadc"><img src="https://images.weserv.nl/?url=github.com/deadc.png&w=40&h=40&fit=cover&mask=circle" width="40" alt="@deadc" /></a>
<a href="https://github.com/zhangyu1324"><img src="https://images.weserv.nl/?url=github.com/zhangyu1324.png&w=40&h=40&fit=cover&mask=circle" width="40" alt="@zhangyu1324" /></a>
+<a href="https://github.com/kentpan"><img src="https://images.weserv.nl/?url=github.com/kentpan.png&w=40&h=40&fit=cover&mask=circle" width="40" alt="@kentpan" /></a>
+<a href="https://github.com/stephenzwj"><img src="https://images.weserv.nl/?url=github.com/stephenzwj.png&w=40&h=40&fit=cover&mask=circle" width="40" alt="@stephenzwj" /></a>
<a href="https://github.com/chongjiazhen"><img src="https://images.weserv.nl/?url=github.com/chongjiazhen.png&w=40&h=40&fit=cover&mask=circle" width="40" alt="@chongjiazhen" /></a>
<a href="https://github.com/vjsai"><img src="https://images.weserv.nl/?url=github.com/vjsai.png&w=40&h=40&fit=cover&mask=circle" width="40" alt="@vjsai" /></a>
<a href="https://github.com/long2ice"><img src="https://images.weserv.nl/?url=github.com/long2ice.png&w=40&h=40&fit=cover&mask=circle" width="40" alt="@long2ice" /></a>
diff --git a/server/src/__tests__/routes/anthropic.test.ts b/server/src/__tests__/routes/anthropic.test.ts
index 6f6de7cc..f7c449a0 100644
--- a/server/src/__tests__/routes/anthropic.test.ts
+++ b/server/src/__tests__/routes/anthropic.test.ts
@@ -2,6 +2,9 @@ import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vite
import type { Express } from 'express';
import { createApp } from '../../app.js';
import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';
+import { encrypt } from '../../lib/crypto.js';
+import { setUnifyEnabled, setUnifyOverrides } from '../../services/model-groups.js';
+import { getRoutingStrategy, setRoutingStrategy, type RoutingStrategy } from '../../services/router.js';
import { mintDashboardToken } from '../helpers/auth.js';
// Anthropic-compatible Messages API (`POST /v1/messages`). These tests drive
@@ -508,4 +511,150 @@ describe('Anthropic-compatible /v1/messages', () => {
expect(status).toBe(200);
expect(body.map).toEqual({ default: 'auto', opus: 'auto', sonnet: 'auto', haiku: 'auto' });
});
+
+ // ── Same-model cross-provider failover (#932) ────────────────────────────
+ // Reported by stephenzwj: a pinned /v1/messages request preferred exactly ONE
+ // catalog row, so when that provider rate-limited, the fallback loop walked
+ // the rest of the chain and answered with a DIFFERENT model. Every other
+ // surface already routes a pinned id over its unified model group as a strict
+ // chain; these tests hold /v1/messages to the same contract.
+ describe('same-model cross-provider failover (#932)', () => {
+ const SHARED = 'shared-fallback-model';
+ const UNRELATED = 'unrelated-test-model';
+ let enabledBefore: number[] = [];
+ let addedIds: number[] = [];
+ let strategyBefore: RoutingStrategy;
+
+ // A catalog row + its fallback_config entry, returning the model db id.
+ function addModel(platform: string, modelId: string, displayName: string, priority: number): number {
+ const db = getDb();
+ const info = db.prepare(`
+ INSERT INTO models (platform, model_id, display_name, intelligence_rank, speed_rank, size_label,
+ rpm_limit, rpd_limit, tpm_limit, tpd_limit, monthly_token_budget, context_window, enabled, supports_vision)
+ VALUES (?, ?, ?, 5, 5, 'Large', 100, NULL, NULL, NULL, '~10M', 131072, 1, 0)
+ `).run(platform, modelId, displayName);
+ const id = Number(info.lastInsertRowid);
+ db.prepare('INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, 1)').run(id, priority);
+ return id;
+ }
+
+ function addKey(platform: string): void {
+ const { encrypted, iv, authTag } = encrypt(`test-key-${platform}`);
+ getDb().prepare(`
+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)
+ VALUES (?, ?, ?, ?, ?, 'healthy', 1)
+ `).run(platform, `${platform}-key`, encrypted, iv, authTag);
+ }
+
+ beforeEach(() => {
+ const db = getDb();
+ strategyBefore = getRoutingStrategy();
+ setRoutingStrategy('priority');
+ setUnifyEnabled(true);
+ setUnifyOverrides({ merges: [], splits: [] });
+ // Isolate the catalog: only the three rows below can be routed to, so
+ // "served by an unrelated model" is unambiguous.
+ enabledBefore = (db.prepare('SELECT id FROM models WHERE enabled = 1').all() as { id: number }[]).map(r => r.id);
+ db.prepare('UPDATE models SET enabled = 0').run();
+ addedIds = [
+ // The SAME model_id served by two platforms. Groq is tried first
+ // (priority 10 < 20) and is the one that fails.
+ addModel('groq', SHARED, 'Shared Fallback Model', 10),
+ addModel('cerebras', SHARED, 'Shared Fallback Model', 20),
+ // A different model on the healthy platform, with the BEST priority in
+ // the catalog — before the fix this is what answered the request.
+ addModel('cerebras', UNRELATED, 'Unrelated Test Model', 1),
+ ];
+ addKey('cerebras'); // the groq key is created by the outer beforeEach
+ });
+
+ afterEach(() => {
+ const db = getDb();
+ for (const id of addedIds) {
+ db.prepare('DELETE FROM fallback_config WHERE model_db_id = ?').run(id);
+ db.prepare('DELETE FROM models WHERE id = ?').run(id);
+ }
+ if (enabledBefore.length) {
+ db.prepare(`UPDATE models SET enabled = 1 WHERE id IN (${enabledBefore.map(() => '?').join(',')})`).run(...enabledBefore);
+ }
+ setRoutingStrategy(strategyBefore);
+ });
+
+ // Records every upstream the router actually dispatched to, as
+ // "platform/model_id", and rate-limits Groq.
+ function mockTwoPlatforms(seen: string[]) {
+ const orig = global.fetch;
+ vi.spyOn(global, 'fetch').mockImplementation(async (url: any, init?: any) => {
+ const u = String(url);
+ const sent = init?.body ? JSON.parse(String(init.body)) : {};
+ if (u.includes('api.groq.com')) {
+ seen.push(`groq/${sent.model}`);
+ return new Response(JSON.stringify({ error: { message: 'rate limited' } }), { status: 429 });
+ }
+ if (u.includes('api.cerebras.ai')) {
+ seen.push(`cerebras/${sent.model}`);
+ return new Response(JSON.stringify({
+ id: 'chatcmpl-c', object: 'chat.completion', created: 1, model: sent.model,
+ choices: [{ index: 0, message: { role: 'assistant', content: `answer from cerebras ${sent.model}` }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 3, completion_tokens: 4, total_tokens: 7 },
+ }), { status: 200, headers: { 'Content-Type': 'application/json' } });
+ }
+ return orig(url, init);
+ });
+ }
+
+ it('falls over to the SAME model on the second provider, never to an unrelated one', async () => {
+ const seen: string[] = [];
+ mockTwoPlatforms(seen);
+
+ const { status, body, headers } = await request(app, '/v1/messages', {
+ model: SHARED, max_tokens: 64, messages: [{ role: 'user', content: 'hi' }],
+ }, anthropicHeaders());
+
+ expect(status).toBe(200);
+ // Same model, second provider — not the better-priority unrelated model.
+ expect(headers.get('x-routed-via')).toBe(`cerebras/${SHARED}`);
+ expect(body.content[0].text).toBe(`answer from cerebras ${SHARED}`);
+ expect(seen).toEqual([`groq/${SHARED}`, `cerebras/${SHARED}`]);
+ expect(seen.some(s => s.includes(UNRELATED))).toBe(false);
+ });
+
+ it('never leaves the pinned model even when every provider for it fails', async () => {
+ const orig = global.fetch;
+ const seen: string[] = [];
+ vi.spyOn(global, 'fetch').mockImplementation(async (url: any, init?: any) => {
+ const u = String(url);
+ const sent = init?.body ? JSON.parse(String(init.body)) : {};
+ if (u.includes('api.groq.com') || u.includes('api.cerebras.ai')) {
+ seen.push(`${u.includes('api.groq.com') ? 'groq' : 'cerebras'}/${sent.model}`);
+ return new Response(JSON.stringify({ error: { message: 'rate limited' } }), { status: 429 });
+ }
+ return orig(url, init);
+ });
+
+ const { status } = await request(app, '/v1/messages', {
+ model: SHARED, max_tokens: 64, messages: [{ role: 'user', content: 'hi' }],
+ }, anthropicHeaders());
+
+ expect(status).toBeGreaterThanOrEqual(400);
+ expect(seen.every(s => s.endsWith(`/${SHARED}`))).toBe(true);
+ expect(seen.some(s => s.includes(UNRELATED))).toBe(false);
+ });
+
+ it('leaves an auto-routed Claude alias on the full chain', async () => {
+ // opus/sonnet/haiku/default all map to 'auto' by default, so nothing is
+ // pinned and the router is free to pick any model — including the
+ // unrelated one, which is exactly the pre-existing behaviour.
+ const seen: string[] = [];
+ mockTwoPlatforms(seen);
+
+ const { status, headers } = await request(app, '/v1/messages', {
+ model: 'claude-sonnet-4-5', max_tokens: 64, messages: [{ role: 'user', content: 'hi' }],
+ }, anthropicHeaders());
+
+ expect(status).toBe(200);
+ expect(headers.get('x-routed-via')).toBe(`cerebras/${UNRELATED}`);
+ });
+ });
+
});
diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.ts
index 38bd7ba1..c41a778f 100644
--- a/server/src/routes/anthropic.ts
+++ b/server/src/routes/anthropic.ts
@@ -9,7 +9,7 @@ import type {
ChatToolChoice,
ChatContentBlock,
} from '@freellmapi/shared/types.js';
-import { routeRequest, resolveStickyPreference, routingReserveTokens, type RouteResult } from '../services/router.js';
+import { routeRequest, resolveModelGroupCandidates, resolveStickyPreference, routingReserveTokens, type RouteResult, type ChainRow } from '../services/router.js';
import { getSetting, getUnifiedApiKey } from '../db/index.js';
import { contentToString } from '../lib/content.js';
import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';
@@ -24,6 +24,7 @@ import { runFallbackLoop, newFallbackState, recordUpstreamSuccess, type Exhausti
import { routedViaValue } from '../lib/header-value.js';
import { applyTokenBudget, tokenBudgetMessage } from '../lib/guardrails.js';
import { resolveAnthropicModel, claudeFamilyDiscoveryEntries } from '../services/anthropic-map.js';
+import { isUnifyEnabled, getModelGroups, resolveRequestedIdForDispatch } from '../services/model-groups.js';
import type { ReasoningEffort } from '../lib/sampling-params.js';
import { buildModelListing } from '../services/model-listing.js';
import { compressRequest, formatCompressionHeader } from '../services/compression/pipeline.js';
@@ -534,8 +535,48 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {
// model so it doesn't flap between free providers mid-conversation.
const rawSession = req.headers['x-claude-code-session-id'] ?? req.headers['x-session-id'];
const sessionId = Array.isArray(rawSession) ? rawSession[0] : rawSession;
+
+ // Same-model cross-provider failover (#932). A pin resolves to ONE catalog
+ // row, and until now that row was the only thing the request preferred: when
+ // its provider failed, the loop walked the rest of the catalog and answered
+ // with a completely different model. The OpenAI, Responses and inbound-chat
+ // surfaces already avoid that by routing a pinned id over its unified model
+ // group as a STRICT chain (#335) — every provider serving the same logical
+ // model, and nothing else. Build the identical chain here so /v1/messages
+ // behaves the same.
+ //
+ // Only the pinned paths change. A Claude family alias mapped to 'auto' (the
+ // default for opus/sonnet/haiku/default) resolves to no model at all and
+ // keeps auto-routing over the full chain exactly as before.
+ let groupChain: ChainRow[] | undefined;
+ // Sticky scope for a group-pinned request: bucket by the pinned catalog id so
+ // the session prefers its last successful provider of THIS model without
+ // leaking affinity across groups. Undefined for auto (the global scope).
+ let stickyScope: string | undefined;
+ if (resolved.modelId) {
+ const dispatch = isUnifyEnabled() ? resolveRequestedIdForDispatch(resolved.modelId, getModelGroups()) : null;
+ const members = dispatch?.memberDbIds ?? null;
+ if (members && members.length > 0) {
+ const chain = resolveModelGroupCandidates(members, dispatch!.demotedDbIds);
+ // An empty chain would mean the pinned row is no longer routable at all;
+ // this surface is lenient, so leave the legacy single-row pin in place
+ // rather than failing the request.
+ if (chain.length > 0) {
+ groupChain = chain;
+ stickyScope = resolved.modelId;
+ }
+ }
+ }
+
let preferredModel = resolved.preferredModelDbId;
- if (preferredModel == null) preferredModel = resolveStickyPreference(getStickyModel(messages, sessionId));
+ if (groupChain) {
+ // The strict chain already fixes the model; the only preference left is
+ // which member served this session last. Passing a non-member would make
+ // routeRequest splice an off-group model into the chain and break the pin.
+ const sticky = getStickyModel(messages, sessionId, stickyScope);
+ preferredModel = (sticky != null && groupChain.some(r => r.model_db_id === sticky)) ? sticky : undefined;
+ }
+ if (preferredModel == null && !groupChain) preferredModel = resolveStickyPreference(getStickyModel(messages, sessionId));
// Thin adapter over the shared fallback loop (lib/fallback-loop.ts): the
// cooldown/skip/penalty/exhaustion machinery is shared, only the Anthropic
@@ -572,13 +613,13 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {
attemptLog,
clientGone: () => clientGone,
abortInFlight: () => hedgeAbort.abort(newHedgeAbortError()),
- route: () => routeRequest(estimatedTotal, state.skipKeys.size > 0 ? state.skipKeys : undefined, preferredModel, hasImage, wantsTools, state.skipModels.size > 0 ? state.skipModels : undefined, undefined, false, state.skipPlatforms.size > 0 ? state.skipPlatforms : undefined, outputReserve),
+ route: () => routeRequest(estimatedTotal, state.skipKeys.size > 0 ? state.skipKeys : undefined, preferredModel, hasImage, wantsTools, state.skipModels.size > 0 ? state.skipModels : undefined, groupChain, false, state.skipPlatforms.size > 0 ? state.skipPlatforms : undefined, outputReserve),
dispatch: async (route, attempt, dispatchCtx) => {
if (stream) {
try {
await streamCompletion(res, route, messages, dispatchOptions, {
start, attempt, attemptLog, clientGone: () => clientGone, requestedModel, estimatedInputTokens, tools, pinnedModelId,
- sessionId, pinned: resolved.pinned, disarmHedge: dispatchCtx.disarmHedge,
+ sessionId, pinned: resolved.pinned, stickyScope, disarmHedge: dispatchCtx.disarmHedge,
});
return 'done';
} catch (err: any) {
@@ -656,9 +697,10 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {
const completionTokens = result.usage?.completion_tokens ?? Math.ceil((respText.length + respToolCalls.reduce((n, c) => n + c.function.arguments.length, 0)) / 4);
recordUpstreamSuccess(route, result.usage?.total_tokens ?? promptTokens + completionTokens);
- // Remember this model for the rest of the auto-routed session (no-op for
- // a pinned request — the pin already fixes the model).
- if (!resolved.pinned) setStickyModel(messages, route.modelDbId, sessionId);
+ // Remember this model for the rest of the auto-routed session. A pin used
+ // to make this a no-op (the pin fixed the model); a group pin still has a
+ // provider choice to remember, recorded under the group's own scope.
+ if (!resolved.pinned || stickyScope) setStickyModel(messages, route.modelDbId, sessionId, stickyScope);
const anthropicResponse: AnthropicMessageResponse = {
id: newMessageId(),
@@ -711,6 +753,8 @@ interface StreamCtx {
pinnedModelId: string | null;
sessionId?: string;
pinned: boolean;
+ // Sticky bucket for a group-pinned request; undefined for auto routing.
+ stickyScope?: string;
/** Cancel this attempt's time-budget hedge once the stream commits. */
disarmHedge: () => void;
}
@@ -967,7 +1011,7 @@ async function streamCompletion(
res.end();
recordUpstreamSuccess(route, ctx.estimatedInputTokens + outputTokens);
- if (!ctx.pinned) setStickyModel(messages, route.modelDbId, ctx.sessionId);
+ if (!ctx.pinned || ctx.stickyScope) setStickyModel(messages, route.modelDbId, ctx.sessionId, ctx.stickyScope);
logRequest(route.platform, route.modelId, route.keyId, 'success', ctx.estimatedInputTokens, outputTokens, Date.now() - ctx.start, null, null, ctx.pinnedModelId);
} catch (err: any) {
if (err instanceof StreamAlreadyStarted) throw err;
diff --git a/server/src/services/anthropic-map.ts b/server/src/services/anthropic-map.ts
index c4d389d9..75f35c8e 100644
--- a/server/src/services/anthropic-map.ts
+++ b/server/src/services/anthropic-map.ts
@@ -76,6 +76,11 @@ export function classifyClaudeFamily(model?: string): ClaudeFamily | null {
export interface ResolvedAnthropicModel {
// The catalog model db id to pin, or undefined to auto-route.
preferredModelDbId?: number;
+ // The catalog model_id that db id belongs to, when one was pinned. Callers
+ // widen this into the model's cross-provider group so a failure fails over to
+ // the SAME model on another provider (the strict chain /v1/chat/completions
+ // and /v1/responses already build) instead of to an unrelated model.
+ modelId?: string;
// True when we resolved to a specific model (for analytics/pinned labels).
pinned: boolean;
}
@@ -85,24 +90,34 @@ export interface ResolvedAnthropicModel {
// "auto-route" (the default for every family unless the operator pinned one).
export function resolveAnthropicModel(model?: string): ResolvedAnthropicModel {
const db = getDb();
- const lookupEnabled = (modelId: string): number | undefined => {
- const row = db.prepare('SELECT id FROM models WHERE model_id = ? AND enabled = 1').get(modelId) as { id: number } | undefined;
- return row?.id;
- };
+ // A model_id can exist on several platforms at once (the same open-weights
+ // model relayed by two providers). The row we pin is only the head hint —
+ // the caller routes over the whole group — but an arbitrary SQLite row order
+ // made the head flap between providers run to run, so pick deterministically:
+ // chain priority first (ascending, as everywhere else), then insertion order.
+ const lookupEnabled = (modelId: string): { id: number; model_id: string } | undefined =>
+ db.prepare(`
+ SELECT m.id as id, m.model_id as model_id
+ FROM models m
+ LEFT JOIN fallback_config fc ON fc.model_db_id = m.id
+ WHERE m.model_id = ? AND m.enabled = 1
+ ORDER BY COALESCE(fc.priority, 0) ASC, m.id ASC
+ LIMIT 1
+ `).get(modelId) as { id: number; model_id: string } | undefined;
const family = classifyClaudeFamily(model);
if (family) {
const target = getClaudeModelMap()[family];
if (!target || target === 'auto') return { pinned: false };
- const id = lookupEnabled(target);
+ const row = lookupEnabled(target);
// A pinned-but-now-disabled/removed target degrades gracefully to auto.
- return id != null ? { preferredModelDbId: id, pinned: true } : { pinned: false };
+ return row ? { preferredModelDbId: row.id, modelId: row.model_id, pinned: true } : { pinned: false };
}
// Not a Claude alias: treat as a concrete catalog model id and pin it if it
// exists and is enabled; otherwise auto-route (lenient, like the OpenAI route).
- const id = lookupEnabled((model ?? '').trim());
- return id != null ? { preferredModelDbId: id, pinned: true } : { pinned: false };
+ const row = lookupEnabled((model ?? '').trim());
+ return row ? { preferredModelDbId: row.id, modelId: row.model_id, pinned: true } : { pinned: false };
}
// The canonical Claude id this gateway answers to for each family, and the