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(proxy): serve the listed Claude aliases on the OpenAI-wire routes (#1613)

Tashfeen19eb7e1c3bd5
diff --git a/server/src/__tests__/routes/claude-alias-openai-routes.test.ts b/server/src/__tests__/routes/claude-alias-openai-routes.test.ts
new file mode 100644
index 00000000..593af100
--- /dev/null
+++ b/server/src/__tests__/routes/claude-alias-openai-routes.test.ts
@@ -0,0 +1,166 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+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 { setRoutingStrategy } from '../../services/router.js';
+import { setClaudeModelMap } from '../../services/anthropic-map.js';
+import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';
+
+let app: Express;
+let dashToken = '';
+
+async function request(method: string, path: string, body?: any, headers: Record<string, string> = {}) {
+ const server = app.listen(0, '127.0.0.1');
+ if (!server.listening) await new Promise<void>(resolve => server.once('listening', () => resolve()));
+ const addr = server.address() as any;
+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {
+ method,
+ headers: {
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
+ ...(isGatedApiPath(path) && !('Authorization' in headers) ? { Authorization: `Bearer ${dashToken}` } : {}),
+ ...headers,
+ },
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ const text = await res.text();
+ server.close();
+ let json: any = null;
+ try { json = JSON.parse(text); } catch { /* SSE / non-JSON */ }
+ return { status: res.status, body: json, text };
+}
+
+function authHeaders() {
+ return { Authorization: `Bearer ${getUnifiedApiKey()}` };
+}
+
+function activeProfileId(): number | null {
+ const row = getDb().prepare("SELECT value FROM settings WHERE key = 'active_profile_id'").get() as { value: string } | undefined;
+ return row ? Number(row.value) : null;
+}
+
+function addKey(platform: string): void {
+ const secret = encrypt(`${platform}-claude-alias-key`);
+ getDb().prepare(`
+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)
+ VALUES (?, 'claude-alias', ?, ?, ?, 'healthy', 1)
+ `).run(platform, secret.encrypted, secret.iv, secret.authTag);
+}
+
+// A two-model catalog at fixed priorities: with the 'priority' strategy the
+// routed model is fully deterministic, so "which model served" is a clean
+// assertion. Unique model ids also make each model its own unify group, so an
+// explicit request resolves to exactly one row.
+function addModel(modelId: string, priority: number, sizeLabel = 'Small'): number {
+ const db = getDb();
+ const inserted = 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, supports_tools
+ )
+ VALUES ('groq', ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, '~1M', 128000, 1, 0, 1)
+ `).run(modelId, `Alias ${modelId}`, priority, priority, sizeLabel);
+ const id = Number(inserted.lastInsertRowid);
+ db.prepare('INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, 1)').run(id, priority);
+ const profileId = activeProfileId();
+ if (profileId != null) {
+ db.prepare('INSERT INTO profile_models (profile_id, model_db_id, priority, enabled) VALUES (?, ?, ?, 1)')
+ .run(profileId, id, priority);
+ }
+ return id;
+}
+
+function mockUpstream() {
+ const origFetch = global.fetch;
+ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {
+ const u = typeof url === 'string' ? url : url.toString();
+ if (u.includes('api.groq.com')) {
+ return {
+ ok: true,
+ status: 200,
+ headers: new Headers(),
+ json: () => Promise.resolve({
+ id: 'chatcmpl-x', object: 'chat.completion', created: 1, model: 'default',
+ choices: [{ index: 0, message: { role: 'assistant', content: 'ok' }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 2, completion_tokens: 1, total_tokens: 3 },
+ }),
+ } as any;
+ }
+ return origFetch(url, init);
+ });
+}
+
+function lastServedModel(): string {
+ const row = getDb().prepare('SELECT model_id FROM requests ORDER BY id DESC LIMIT 1').get() as { model_id: string } | undefined;
+ return row?.model_id ?? '';
+}
+
+
+// GET /v1/models lists claude-opus/sonnet/haiku-4-5 on the OpenAI-shaped
+// listing too (#880), so OpenAI-wire clients pick them. These routes used to
+// answer 404 model_not_found; they now resolve the listed ids through the same
+// Claude family map /v1/messages uses.
+beforeEach(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ app = createApp();
+ dashToken = mintDashboardToken();
+ setRoutingStrategy('priority');
+ const db = getDb();
+ db.prepare('DELETE FROM api_keys').run();
+ db.prepare('DELETE FROM profile_models').run();
+ db.prepare('DELETE FROM fallback_config').run();
+ db.prepare('DELETE FROM models').run();
+ addKey('groq');
+ addModel('alpha-model', 1, 'Small');
+ addModel('beta-model', 2, 'Large');
+ mockUpstream();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+const surfaces: [string, string, (model: string) => Record<string, unknown>][] = [
+ ['chat completions', '/v1/chat/completions', model => ({ model, messages: [{ role: 'user', content: 'hi' }] })],
+ ['completions', '/v1/completions', model => ({ model, prompt: 'hi' })],
+ ['responses', '/v1/responses', model => ({ model, input: 'hi' })],
+];
+
+describe.each(surfaces)('Claude aliases on %s', (_name, path, body) => {
+ it('auto-routes an alias mapped to auto (the default)', async () => {
+ const res = await request('POST', path, body('claude-sonnet-4-5'), authHeaders());
+ expect(res.status).toBe(200);
+ expect(lastServedModel()).toBe('alpha-model');
+ });
+
+ it('serves the catalog model the family is pinned to', async () => {
+ setClaudeModelMap({ sonnet: 'beta-model' });
+ const res = await request('POST', path, body('claude-sonnet-4-5'), authHeaders());
+ expect(res.status).toBe(200);
+ expect(lastServedModel()).toBe('beta-model');
+ });
+
+ it('stays inside the tier pool for a tier selector', async () => {
+ setClaudeModelMap({ haiku: 'tier:mid' });
+ const res = await request('POST', path, body('claude-haiku-4-5'), authHeaders());
+ expect(res.status).toBe(200);
+ // Priority order would pick alpha-model (Small); tier:mid is Large only.
+ expect(lastServedModel()).toBe('beta-model');
+ });
+
+ it('lets a real catalog row with the alias id win', async () => {
+ addModel('claude-opus-4-5', 3);
+ setClaudeModelMap({ opus: 'alpha-model' });
+ const res = await request('POST', path, body('claude-opus-4-5'), authHeaders());
+ expect(res.status).toBe(200);
+ expect(lastServedModel()).toBe('claude-opus-4-5');
+ });
+
+ it('still rejects a Claude-looking id that is not listed', async () => {
+ const res = await request('POST', path, body('claude-3-opus-20240229'), authHeaders());
+ expect([400, 404]).toContain(res.status);
+ expect(res.body?.error?.code).toBe('model_not_found');
+ });
+});
diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.ts
index bfbcef75..b7410144 100644
--- a/server/src/routes/proxy.ts
+++ b/server/src/routes/proxy.ts
@@ -38,7 +38,7 @@ import type { Platform } from '@freellmapi/shared/types.js';
import { inferQuotaPoolKey, type QuotaObservationContext } from '../services/provider-quota.js';
import { isUnifyEnabled, getModelGroups, resolveRequestedIdForDispatch } from '../services/model-groups.js';
import { buildModelListing, type NormalizedModel } from '../services/model-listing.js';
-import { claudeFamilyDiscoveryEntries } from '../services/anthropic-map.js';
+import { claudeFamilyDiscoveryEntries, resolveListedClaudeAlias } from '../services/anthropic-map.js';
import { compressRequest, formatCompressionHeader } from '../services/compression/pipeline.js';
import { applyDecisionRouting, routingStrategyHeader } from '../services/routing-decision.js';
@@ -1304,8 +1304,12 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
return;
}
- const { model: requestedModel, prompt, suffix, temperature, top_p, stream } = parsed.data;
- const requestedModelLabel = requestedModel ?? 'auto';
+ const { model: clientModel, prompt, suffix, temperature, top_p, stream } = parsed.data;
+ const requestedModelLabel = clientModel ?? 'auto';
+ // Claude alias from GET /v1/models → the Claude family map, as on /v1/chat/completions.
+ const claudeAlias = resolveListedClaudeAlias(clientModel);
+ const requestedModel = claudeAlias?.kind === 'model' ? claudeAlias.modelId : claudeAlias ? 'auto' : clientModel;
+ const aliasTierChain = claudeAlias?.kind === 'tier' ? resolveModelGroupCandidates(claudeAlias.dbIds) : [];
const max_tokens = parsed.data.max_tokens != null && parsed.data.max_tokens > 0
? parsed.data.max_tokens : 128;
const stop = providerSafeStop(parsed.data.stop);
@@ -1337,9 +1341,9 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
}
let preferredModel: number | undefined;
- let groupChain: ChainRow[] | undefined;
+ let groupChain: ChainRow[] | undefined = aliasTierChain.length > 0 ? aliasTierChain : undefined;
- if (!isAutoModel(requestedModel) && requestedModel) {
+ if (!groupChain && !isAutoModel(requestedModel) && requestedModel) {
const db = getDb();
const resolved = isUnifyEnabled() ? resolveRequestedIdForDispatch(requestedModel, getModelGroups()) : null;
const members = resolved?.memberDbIds ?? null;
@@ -1727,8 +1731,13 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
return;
}
- const { model: requestedModel, temperature, top_p, stream } = parsed.data;
- const requestedModelLabel = requestedModel ?? 'auto';
+ const { model: clientModel, temperature, top_p, stream } = parsed.data;
+ const requestedModelLabel = clientModel ?? 'auto';
+ // A Claude alias from GET /v1/models routes through the Claude family map
+ // (a pinned model, auto, or a tier pool), the same as on /v1/messages.
+ const claudeAlias = resolveListedClaudeAlias(clientModel);
+ const requestedModel = claudeAlias?.kind === 'model' ? claudeAlias.modelId : claudeAlias ? 'auto' : clientModel;
+ const aliasTierChain = claudeAlias?.kind === 'tier' ? resolveModelGroupCandidates(claudeAlias.dbIds) : [];
// Agent-tolerant knob normalization (#200): max_tokens <= 0 means "no
// limit" in several clients → unset; tool_choice 'any' is OpenAI's
// 'required'; tool definitions get their 'function' type re-defaulted.
@@ -2256,7 +2265,14 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
// successful provider without leaking stickiness across groups.
let stickyStrategyKey: string | undefined = strategyKey;
- if (isAutoModel(requestedModel)) {
+ if (aliasTierChain.length > 0) {
+ // A tier-mapped Claude alias routes STRICTLY over its tier's pool. An
+ // empty tier falls through to plain auto, as on /v1/messages.
+ groupChain = aliasTierChain;
+ stickyStrategyKey = `tier:${aliasTierChain[0]!.model_db_id}`;
+ const sticky = getStickyModel(messages, sessionIdHeader, stickyStrategyKey);
+ preferredModel = (sticky != null && groupChain.some(r => r.model_db_id === sticky)) ? sticky : undefined;
+ } else if (isAutoModel(requestedModel)) {
preferredModel = resolveStickyPreference(getStickyModel(messages, sessionIdHeader, strategyKey), resolvedChain?.chain);
} else if (requestedModel) {
const db = getDb();
diff --git a/server/src/routes/responses.ts b/server/src/routes/responses.ts
index e2ea372c..6e86ed0c 100644
--- a/server/src/routes/responses.ts
+++ b/server/src/routes/responses.ts
@@ -49,6 +49,7 @@ import {
type FusionResult,
} from '../services/fusion.js';
import { applyDecisionRouting, routingStrategyHeader } from '../services/routing-decision.js';
+import { resolveListedClaudeAlias } from '../services/anthropic-map.js';
export const responsesRouter = Router();
@@ -810,6 +811,12 @@ export async function handleResponses(req: Request, res: Response): Promise<void
?? req.headers['x-session-id'];
const sessionIdHeader = Array.isArray(rawSessionId) ? rawSessionId[0] : rawSessionId;
const requestedModelLabel = reqData.model ?? 'auto';
+ // What routing acts on. Usually the id the client sent; a Claude alias from
+ // GET /v1/models routes through the Claude family map instead (a pinned
+ // model, auto, or a tier pool), the same as on /v1/messages.
+ const claudeAlias = resolveListedClaudeAlias(reqData.model);
+ const routedModel = claudeAlias?.kind === 'model' ? claudeAlias.modelId : claudeAlias ? 'auto' : requestedModelLabel;
+ const aliasTierChain = claudeAlias?.kind === 'tier' ? resolveModelGroupCandidates(claudeAlias.dbIds) : [];
// Explicit `model` field pins routing. If the catalog has no enabled row
// matching the requested id, return 400 — silently auto-routing to a
@@ -823,9 +830,15 @@ export async function handleResponses(req: Request, res: Response): Promise<void
// stays on the unscoped key so existing session affinity is unchanged.
let stickyStrategyKey: string | undefined;
- if (isAutoModel(requestedModelLabel)) {
+ if (aliasTierChain.length > 0) {
+ // Strict over the tier's pool; an empty tier falls through to plain auto.
+ groupChain = aliasTierChain;
+ stickyStrategyKey = `tier:${aliasTierChain[0]!.model_db_id}`;
+ const sticky = getStickyModel(messages, sessionIdHeader, stickyStrategyKey);
+ preferredModel = (sticky != null && groupChain.some(r => r.model_db_id === sticky)) ? sticky : undefined;
+ } else if (isAutoModel(routedModel)) {
try {
- resolvedChain = resolveRoutingChain(requestedModelLabel);
+ resolvedChain = resolveRoutingChain(routedModel);
} catch (err: any) {
if (err?.status === 400) {
res.status(400).json({
@@ -840,12 +853,12 @@ export async function handleResponses(req: Request, res: Response): Promise<void
getStickyModel(messages, sessionIdHeader, stickyStrategyKey),
resolvedChain.chain,
);
- } else if (isFusionModel(requestedModelLabel)) {
+ } else if (isFusionModel(routedModel)) {
// Fusion is a virtual model, not a row in the catalog. Its panel and
// judge each resolve through the normal router inside runFusion below.
} else {
const db = getDb();
- const resolved = isUnifyEnabled() ? resolveRequestedIdForDispatch(requestedModelLabel, getModelGroups()) : null;
+ const resolved = isUnifyEnabled() ? resolveRequestedIdForDispatch(routedModel, getModelGroups()) : null;
const members = resolved?.memberDbIds ?? null;
if (members && members.length > 0) {
groupChain = resolveModelGroupCandidates(members, resolved!.demotedDbIds);
@@ -855,25 +868,25 @@ export async function handleResponses(req: Request, res: Response): Promise<void
const reason = anyEnabled ? 'has no providers with an enabled key' : 'is disabled';
res.status(400).json({
error: {
- message: `Model '${requestedModelLabel}' ${reason}. Use 'auto' (or omit the 'model' field) to auto-route, or call /v1/models for the available list.`,
+ message: `Model '${routedModel}' ${reason}. Use 'auto' (or omit the 'model' field) to auto-route, or call /v1/models for the available list.`,
type: 'invalid_request_error',
code: 'model_not_found',
},
});
return;
}
- const sticky = getStickyModel(messages, sessionIdHeader, requestedModelLabel);
+ const sticky = getStickyModel(messages, sessionIdHeader, routedModel);
preferredModel = (sticky != null && groupChain.some(r => r.model_db_id === sticky)) ? sticky : undefined;
} else {
- const enabled = db.prepare('SELECT id FROM models WHERE model_id = ? AND enabled = 1').get(requestedModelLabel) as { id: number } | undefined;
+ const enabled = db.prepare('SELECT id FROM models WHERE model_id = ? AND enabled = 1').get(routedModel) as { id: number } | undefined;
if (enabled) {
preferredModel = enabled.id;
} else {
- const disabled = db.prepare('SELECT id FROM models WHERE model_id = ?').get(requestedModelLabel) as { id: number } | undefined;
+ const disabled = db.prepare('SELECT id FROM models WHERE model_id = ?').get(routedModel) as { id: number } | undefined;
const reason = disabled ? 'is disabled' : 'is not in the catalog';
res.status(400).json({
error: {
- message: `Model '${requestedModelLabel}' ${reason}. Use 'auto' (or omit the 'model' field) to auto-route, or call /v1/models for the available list.`,
+ message: `Model '${routedModel}' ${reason}. Use 'auto' (or omit the 'model' field) to auto-route, or call /v1/models for the available list.`,
type: 'invalid_request_error',
code: 'model_not_found',
},
@@ -930,7 +943,7 @@ export async function handleResponses(req: Request, res: Response): Promise<void
// virtual id before normal model dispatch; do the same here after the common
// Responses translation/guardrails so Codex and other Responses clients can
// opt into the exact same panel + judge behavior.
- if (isFusionModel(requestedModelLabel)) {
+ if (isFusionModel(routedModel)) {
const fusionConfig = reqData.fusion ?? {};
const fusionOptions = { ...dispatchOpts };
@@ -1166,7 +1179,7 @@ export async function handleResponses(req: Request, res: Response): Promise<void
// model picks which preset (Smartest / Fastest / Balanced / Most reliable)
// this turn routes with. Skipped when the client pinned a model or the
// conversation is sticky to one. Any doubt routes as Balanced.
- const routingPick = await applyDecisionRouting(messages, { pinned: !isAutoModel(requestedModelLabel) || preferredModel != null, signal: clientAbort.signal });
+ const routingPick = await applyDecisionRouting(messages, { pinned: !isAutoModel(routedModel) || preferredModel != null, signal: clientAbort.signal });
if (routingPick && !res.headersSent) res.setHeader('X-FreeLLM-Routing-Strategy', routingStrategyHeader(routingPick));
await runFallbackLoop({
diff --git a/server/src/services/anthropic-map.ts b/server/src/services/anthropic-map.ts
index 13607afc..6d656326 100644
--- a/server/src/services/anthropic-map.ts
+++ b/server/src/services/anthropic-map.ts
@@ -191,6 +191,29 @@ export const CLAUDE_FAMILY_ALIASES: { id: string; family: ClaudeFamily; label: s
{ id: 'claude-haiku-4-5', family: 'haiku', label: 'Haiku' },
];
+/** What an OpenAI-wire route should dispatch a listed Claude alias to. */
+export type ClaudeAliasDispatch =
+ | { kind: 'model'; modelId: string }
+ | { kind: 'auto' }
+ | { kind: 'tier'; dbIds: number[] };
+
+// GET /v1/models lists CLAUDE_FAMILY_ALIASES on the OpenAI-shaped listing too
+// (#880), so OpenAI-wire clients (agents seeded from that listing, ZCode,
+// Continue...) pick them, and /v1/chat/completions, /v1/completions and
+// /v1/responses used to answer 404 model_not_found. Resolve exactly the listed
+// ids through the same family map /v1/messages uses. Returns null for anything
+// else, including an alias id that is also a real catalog row (the listing
+// hides the alias then, and the catalog row wins).
+export function resolveListedClaudeAlias(model?: string): ClaudeAliasDispatch | null {
+ const id = (model ?? '').trim().toLowerCase();
+ if (!CLAUDE_FAMILY_ALIASES.some(alias => alias.id === id)) return null;
+ if (getDb().prepare('SELECT 1 FROM models WHERE model_id = ? LIMIT 1').get(model!.trim())) return null;
+ const resolved = resolveAnthropicModel(id);
+ if (resolved.modelId) return { kind: 'model', modelId: resolved.modelId };
+ if (resolved.tierDbIds?.length) return { kind: 'tier', dbIds: resolved.tierDbIds };
+ return { kind: 'auto' };
+}
+
// Discovery entries for the family aliases, named after where each one routes:
// the pinned catalog model when the operator pinned one, otherwise the router.
export function claudeFamilyDiscoveryEntries(): { id: string; displayName: string }[] {