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(keys): multiple custom providers — one key row per endpoint, models bound via key_id (#212)
Tashfeen599c132891ec
diff --git a/server/src/__tests__/routes/custom-provider.test.ts b/server/src/__tests__/routes/custom-provider.test.tsindex 8f31345f..3b14e86e 100644--- a/server/src/__tests__/routes/custom-provider.test.ts+++ b/server/src/__tests__/routes/custom-provider.test.ts@@ -207,4 +207,74 @@ describe('POST /api/keys/custom (#117)', () => {expect(JSON.stringify(body)).toMatch(/not OpenAI-compatible/);expect(JSON.stringify(body)).not.toMatch(/Unexpected non-whitespace/);});++ // #212: adding a second custom provider used to overwrite the first one's+ // endpoint — one shared key row held THE base_url. Now each endpoint gets+ // its own key row and models bind to their endpoint via models.key_id.+ describe('multiple custom providers (#212)', () => {+ beforeAll(async () => {+ // Sweep custom state left by the tests above for a deterministic start.+ const db = getDb();+ db.prepare("DELETE FROM fallback_config WHERE model_db_id IN (SELECT id FROM models WHERE platform = 'custom')").run();+ db.prepare("DELETE FROM models WHERE platform = 'custom'").run();+ db.prepare("DELETE FROM api_keys WHERE platform = 'custom'").run();++ const a = await post(app, '/api/keys/custom', { baseUrl: 'http://127.0.0.1:11434/v1', model: 'llama3:8b', label: 'Ollama box' });+ const b = await post(app, '/api/keys/custom', { baseUrl: 'http://127.0.0.1:1234/v1', model: 'qwen3:4b', label: 'LM Studio' });+ expect(a.status).toBe(201);+ expect(b.status).toBe(201);+ });++ it('keeps a separate key row per endpoint instead of overwriting', () => {+ const db = getDb();+ const keys = db.prepare("SELECT id, base_url FROM api_keys WHERE platform = 'custom' ORDER BY id").all() as any[];+ expect(keys.length).toBe(2);+ expect(keys.map(k => k.base_url).sort()).toEqual(['http://127.0.0.1:11434/v1', 'http://127.0.0.1:1234/v1'].sort());+ });++ it('binds each model to its own endpoint key', () => {+ const db = getDb();+ const llama = db.prepare("SELECT m.key_id, k.base_url FROM models m JOIN api_keys k ON k.id = m.key_id WHERE m.platform = 'custom' AND m.model_id = 'llama3:8b'").get() as any;+ const qwen = db.prepare("SELECT m.key_id, k.base_url FROM models m JOIN api_keys k ON k.id = m.key_id WHERE m.platform = 'custom' AND m.model_id = 'qwen3:4b'").get() as any;+ expect(llama.base_url).toBe('http://127.0.0.1:11434/v1');+ expect(qwen.base_url).toBe('http://127.0.0.1:1234/v1');+ });++ it('routes each model through ITS endpoint, never the other one', () => {+ const db = getDb();+ const llamaId = (db.prepare("SELECT id FROM models WHERE platform = 'custom' AND model_id = 'llama3:8b'").get() as any).id;+ const qwenId = (db.prepare("SELECT id FROM models WHERE platform = 'custom' AND model_id = 'qwen3:4b'").get() as any).id;++ const llamaRoute = routeRequest(1000, undefined, llamaId);+ expect(llamaRoute.modelId).toBe('llama3:8b');+ expect((llamaRoute.provider as any).baseUrl).toBe('http://127.0.0.1:11434/v1');++ const qwenRoute = routeRequest(1000, undefined, qwenId);+ expect(qwenRoute.modelId).toBe('qwen3:4b');+ expect((qwenRoute.provider as any).baseUrl).toBe('http://127.0.0.1:1234/v1');+ });++ it('re-submitting an existing endpoint updates it instead of adding a third', async () => {+ const { status } = await post(app, '/api/keys/custom', { baseUrl: 'http://127.0.0.1:11434/v1', model: 'mistral:7b', label: 'Ollama box renamed' });+ expect(status).toBe(201);+ const db = getDb();+ expect((db.prepare("SELECT COUNT(*) AS n FROM api_keys WHERE platform = 'custom'").get() as any).n).toBe(2);+ const key = db.prepare("SELECT label FROM api_keys WHERE platform = 'custom' AND base_url = 'http://127.0.0.1:11434/v1'").get() as any;+ expect(key.label).toBe('Ollama box renamed');+ });++ it('deleting one endpoint removes only ITS models from catalog and chain', async () => {+ const db = getDb();+ const ollamaKey = db.prepare("SELECT id FROM api_keys WHERE platform = 'custom' AND base_url = 'http://127.0.0.1:11434/v1'").get() as any;++ const { status } = await del(app, `/api/keys/${ollamaKey.id}`);+ expect(status).toBe(200);++ const remainingModels = (db.prepare("SELECT model_id FROM models WHERE platform = 'custom'").all() as any[]).map(r => r.model_id);+ expect(remainingModels).toEqual(['qwen3:4b']); // llama3:8b + mistral:7b cascaded with their key+ const keys = db.prepare("SELECT base_url FROM api_keys WHERE platform = 'custom'").all() as any[];+ expect(keys.length).toBe(1);+ expect(keys[0].base_url).toBe('http://127.0.0.1:1234/v1');+ });+ });});diff --git a/server/src/db/index.ts b/server/src/db/index.tsindex 6460fb69..02f8275d 100644--- a/server/src/db/index.ts+++ b/server/src/db/index.ts@@ -173,6 +173,7 @@ function createTables(db: Database.Database) {ensureRequestKeyIdColumn(db);ensureApiKeysBaseUrlColumn(db);+ ensureModelsKeyIdColumn(db);ensureRequestTtfbColumn(db);}@@ -203,6 +204,23 @@ function ensureApiKeysBaseUrlColumn(db: Database.Database) {}}+// `key_id` binds a custom model to the api_keys row that carries ITS endpoint,+// so several custom providers can coexist (#212). NULL for built-in platforms+// (any key of the platform serves any of its models).+function ensureModelsKeyIdColumn(db: Database.Database) {+ const columns = db.prepare('PRAGMA table_info(models)').all() as { name: string }[];+ if (!columns.some(col => col.name === 'key_id')) {+ db.prepare('ALTER TABLE models ADD COLUMN key_id INTEGER').run();+ // Backfill: bind pre-existing custom models to the (single) legacy custom+ // endpoint key so they keep routing to the URL they were created for.+ db.prepare(`+ UPDATE models+ SET key_id = (SELECT id FROM api_keys WHERE platform = 'custom' ORDER BY id LIMIT 1)+ WHERE platform = 'custom' AND key_id IS NULL+ `).run();+ }+}+function seedModels(db: Database.Database) {const count = db.prepare('SELECT COUNT(*) as cnt FROM models').get() as { cnt: number };if (count.cnt > 0) return;diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 35c91c0f..bb8fe331 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -117,10 +117,13 @@ keysRouter.post('/', (req: Request, res: Response) => {});});-// ── Custom OpenAI-compatible provider (#117) ──────────────────────────────-// A single user-configured endpoint (llama.cpp / LM Studio / vLLM / Ollama /-// any OpenAI-compatible base_url). The endpoint lives on one 'custom' api_keys-// row; each call registers another model that routes through it.+// ── Custom OpenAI-compatible providers (#117, #212) ───────────────────────+// User-configured endpoints (llama.cpp / LM Studio / vLLM / Ollama / any+// OpenAI-compatible base_url). Each DISTINCT base_url gets its own 'custom'+// api_keys row, and every registered model binds to its endpoint's key via+// models.key_id — so several custom providers coexist without overwriting+// each other (#212). Re-submitting an existing base_url updates its key/label;+// re-registering an existing model id re-binds it to the submitted endpoint.const customProviderSchema = z.object({baseUrl: z.string().url('baseUrl must be a valid URL'),model: z.string().min(1, 'model is required'),@@ -145,14 +148,16 @@ keysRouter.post('/custom', (req: Request, res: Response) => {const db = getDb();const upsert = db.transaction(() => {- // One shared 'custom' key holds the endpoint URL. Reuse it across models;- // update its base_url/key when re-submitted.- const existing = db.prepare("SELECT id FROM api_keys WHERE platform = 'custom' LIMIT 1").get() as { id: number } | undefined;+ // One 'custom' key row PER ENDPOINT (matched on base_url). Re-submitting+ // the same endpoint updates its key/label; a new base_url gets its own+ // row instead of clobbering the previous provider. (#212)+ const existing = db.prepare("SELECT id FROM api_keys WHERE platform = 'custom' AND base_url = ? LIMIT 1")+ .get(baseUrl) as { id: number } | undefined;let keyId: number;if (existing) {const { encrypted, iv, authTag } = encrypt(rawKey);- db.prepare("UPDATE api_keys SET base_url = ?, encrypted_key = ?, iv = ?, auth_tag = ?, status = 'unknown', enabled = 1 WHERE id = ?")- .run(baseUrl, encrypted, iv, authTag, existing.id);+ db.prepare("UPDATE api_keys SET label = ?, encrypted_key = ?, iv = ?, auth_tag = ?, status = 'unknown', enabled = 1 WHERE id = ?")+ .run(label, encrypted, iv, authTag, existing.id);keyId = existing.id;} else {const { encrypted, iv, authTag } = encrypt(rawKey);@@ -163,14 +168,18 @@ keysRouter.post('/custom', (req: Request, res: Response) => {keyId = Number(r.lastInsertRowid);}- // Register the model (idempotent on platform+model_id). Custom models carry- // no rate limits and sort last in the intelligence preset (size_label tier).+ // Register the model bound to THIS endpoint's key. Custom models carry no+ // rate limits and sort last in the intelligence preset (size_label tier).+ // Re-registering an existing model id re-binds it (model ids are unique+ // per platform, so one id can't live on two endpoints at once).db.prepare(`- INSERT OR IGNORE INTO models+ 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)- VALUES ('custom', ?, ?, 50, 50, 'Custom', NULL, NULL, NULL, NULL, '', NULL, 1)- `).run(modelId, displayName);+ rpm_limit, rpd_limit, tpm_limit, tpd_limit, monthly_token_budget, context_window, enabled, key_id)+ VALUES ('custom', ?, ?, 50, 50, 'Custom', NULL, NULL, NULL, NULL, '', NULL, 1, ?)+ ON CONFLICT(platform, model_id)+ DO UPDATE SET display_name = excluded.display_name, key_id = excluded.key_id, enabled = 1+ `).run(modelId, displayName, keyId);const modelRow = db.prepare("SELECT id FROM models WHERE platform = 'custom' AND model_id = ?").get(modelId) as { id: number };@@ -215,11 +224,13 @@ keysRouter.delete('/:id', (req: Request, res: Response) => {const remove = db.transaction(() => {db.prepare('DELETE FROM api_keys WHERE id = ?').run(id);// Custom models exist only because POST /custom registered them alongside- // this endpoint key (#117) — they can't route without it. Built-in- // platforms keep their seeded catalog rows, but once the last custom key- // is gone, orphaned custom models would linger in the fallback chain- // forever (#189), so cascade them away.+ // their endpoint key (#117) — they can't route without it. Cascade away+ // the models bound to THIS endpoint (#212); other custom providers keep+ // theirs. Legacy rows (key_id NULL) are swept once no custom keys remain,+ // so they never linger in the fallback chain forever (#189).if (row.platform === 'custom') {+ db.prepare("DELETE FROM fallback_config WHERE model_db_id IN (SELECT id FROM models WHERE platform = 'custom' AND key_id = ?)").run(id);+ db.prepare("DELETE FROM models WHERE platform = 'custom' AND key_id = ?").run(id);const remaining = db.prepare("SELECT COUNT(*) AS n FROM api_keys WHERE platform = 'custom'").get() as { n: number };if (remaining.n === 0) {db.prepare("DELETE FROM fallback_config WHERE model_db_id IN (SELECT id FROM models WHERE platform = 'custom')").run();diff --git a/server/src/services/router.ts b/server/src/services/router.tsindex 5a96ceb3..f7f80e57 100644--- a/server/src/services/router.ts+++ b/server/src/services/router.ts@@ -40,6 +40,9 @@ interface ChainRow {supports_vision: number;supports_tools: number;context_window: number | null;+ // Custom models bind to the api_keys row carrying their endpoint (#212);+ // NULL for built-in platforms.+ key_id: number | null;}export interface RouteResult {@@ -356,7 +359,7 @@ export function routeRequest(estimatedTokens = 1000, skipKeys?: Set<string>, prem.platform, m.model_id, m.display_name, m.intelligence_rank,m.size_label, m.monthly_token_budget,m.rpm_limit, m.rpd_limit, m.tpm_limit, m.tpd_limit, m.supports_vision,- m.supports_tools, m.context_window+ m.supports_tools, m.context_window, m.key_idFROM fallback_config fcJOIN models m ON m.id = fc.model_db_id AND m.enabled = 1WHERE fc.enabled = 1@@ -423,6 +426,12 @@ export function routeRequest(estimatedTokens = 1000, skipKeys?: Set<string>, preconst key = keys[idx % keys.length];idx++;+ // A custom model belongs to exactly one endpoint: skip every custom key+ // except the one it was registered with. Without this, multiple custom+ // providers would round-robin each other's models onto the wrong+ // endpoint. (#212) Legacy rows (key_id NULL) keep the old any-key match.+ if (entry.platform === 'custom' && entry.key_id != null && key.id !== entry.key_id) continue;+const skipId = `${entry.platform}:${entry.model_id}:${key.id}`;if (skipKeys?.has(skipId)) continue;