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

feat(custom): register multiple models per endpoint in one submit (#281) (#300)

Tashfeen888d653137dd
diff --git a/client/src/pages/KeysPage.tsx b/client/src/pages/KeysPage.tsx
index 4ceaed01..671a30a4 100644
--- a/client/src/pages/KeysPage.tsx
+++ b/client/src/pages/KeysPage.tsx
@@ -3,6 +3,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { apiFetch } from '@/lib/api'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
+import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
@@ -268,6 +269,16 @@ function ProxySettingsSection() {
)
}
+// Split a free-text model field on commas / newlines into a clean id list,
+// dropping blanks and duplicates so one endpoint can take several models. (#281)
+function parseModelList(raw: string): string[] {
+ const seen = new Set<string>()
+ return raw
+ .split(/[\n,]+/)
+ .map(s => s.trim())
+ .filter(s => s.length > 0 && !seen.has(s) && seen.add(s))
+}
+
function CustomProviderSection() {
const queryClient = useQueryClient()
const [baseUrl, setBaseUrl] = useState('')
@@ -275,8 +286,11 @@ function CustomProviderSection() {
const [displayName, setDisplayName] = useState('')
const [apiKey, setApiKey] = useState('')
+ const models = parseModelList(model)
+ const multiple = models.length > 1
+
const addCustom = useMutation({
- mutationFn: (body: { baseUrl: string; model: string; displayName?: string; apiKey?: string }) =>
+ mutationFn: (body: { baseUrl: string; models: string[]; displayName?: string; apiKey?: string }) =>
apiFetch('/api/keys/custom', { method: 'POST', body: JSON.stringify(body) }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['keys'] })
@@ -290,8 +304,15 @@ function CustomProviderSection() {
const submit = (e: React.FormEvent) => {
e.preventDefault()
- if (!baseUrl || !model) return
- addCustom.mutate({ baseUrl, model, displayName: displayName || undefined, apiKey: apiKey || undefined })
+ if (!baseUrl || models.length === 0) return
+ // A single display name only makes sense for a lone model; with several
+ // ids the server names each model after its own id.
+ addCustom.mutate({
+ baseUrl,
+ models,
+ displayName: !multiple ? (displayName || undefined) : undefined,
+ apiKey: apiKey || undefined,
+ })
}
return (
@@ -299,8 +320,8 @@ function CustomProviderSection() {
<h2 className="text-sm font-medium mb-1">Add a custom OpenAI-compatible model</h2>
<p className="text-xs text-muted-foreground mb-3">
Point at any OpenAI-compatible endpoint: llama.cpp, LM Studio, vLLM, a local Ollama, or a remote
- gateway. Add each model you want routed; they all share the one endpoint. The API key is optional
- (most local servers don't need one).
+ gateway. List one model per line (or comma-separated) to add several at once; they all share the
+ one endpoint. The API key is optional (most local servers don't need one).
</p>
<form onSubmit={submit} className="flex flex-wrap items-end gap-3 rounded-3xl border p-4 bg-card">
<div className="space-y-1.5 flex-1 min-w-[240px]">
@@ -313,12 +334,13 @@ function CustomProviderSection() {
/>
</div>
<div className="space-y-1.5">
- <Label className="text-xs">Model</Label>
- <Input
+ <Label className="text-xs">Models</Label>
+ <Textarea
value={model}
onChange={e => setModel(e.target.value)}
- placeholder="qwen3:4b"
- className="w-[180px] font-mono text-xs"
+ placeholder={'qwen3:4b\nllama3:8b'}
+ rows={2}
+ className="w-[200px] font-mono text-xs"
/>
</div>
<div className="space-y-1.5">
@@ -326,7 +348,8 @@ function CustomProviderSection() {
<Input
value={displayName}
onChange={e => setDisplayName(e.target.value)}
- placeholder="optional"
+ placeholder={multiple ? 'per-model' : 'optional'}
+ disabled={multiple}
className="w-[150px]"
/>
</div>
@@ -340,8 +363,8 @@ function CustomProviderSection() {
className="w-[150px] font-mono text-xs"
/>
</div>
- <Button type="submit" size="sm" disabled={!baseUrl || !model || addCustom.isPending}>
- {addCustom.isPending ? 'Adding…' : 'Add model'}
+ <Button type="submit" size="sm" disabled={!baseUrl || models.length === 0 || addCustom.isPending}>
+ {addCustom.isPending ? 'Adding…' : multiple ? `Add ${models.length} models` : 'Add model'}
</Button>
</form>
{addCustom.isError && (
diff --git a/server/src/__tests__/routes/custom-provider.test.ts b/server/src/__tests__/routes/custom-provider.test.ts
index 3b14e86e..25a535f9 100644
--- a/server/src/__tests__/routes/custom-provider.test.ts
+++ b/server/src/__tests__/routes/custom-provider.test.ts
@@ -277,4 +277,53 @@ describe('POST /api/keys/custom (#117)', () => {
expect(keys[0].base_url).toBe('http://127.0.0.1:1234/v1');
});
});
+
+ // #281: one submit can bind several model ids to a single endpoint, instead
+ // of forcing one POST per model.
+ describe('multiple models per endpoint (#281)', () => {
+ beforeAll(() => {
+ 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();
+ });
+
+ it('registers every model in the models array against one endpoint key', async () => {
+ const { status, body } = await post(app, '/api/keys/custom', {
+ baseUrl: 'http://127.0.0.1:9999/v1',
+ models: ['gemma3:1b', { model: 'phi4:14b', displayName: 'Phi 4' }],
+ label: 'Multi box',
+ });
+ expect(status).toBe(201);
+ // Back-compat fields echo the first model; `models` carries the full set.
+ expect(body.model).toBe('gemma3:1b');
+ expect(body.models).toHaveLength(2);
+ expect(body.models.map((m: any) => m.model).sort()).toEqual(['gemma3:1b', 'phi4:14b']);
+ expect(body.models.find((m: any) => m.model === 'phi4:14b').displayName).toBe('Phi 4');
+
+ const db = getDb();
+ const keys = db.prepare("SELECT id FROM api_keys WHERE platform = 'custom' AND base_url = 'http://127.0.0.1:9999/v1'").all();
+ expect(keys.length).toBe(1); // one endpoint, one key
+ const models = db.prepare("SELECT model_id FROM models WHERE platform = 'custom' AND key_id = ?").all((keys[0] as any).id) as any[];
+ expect(models.map(m => m.model_id).sort()).toEqual(['gemma3:1b', 'phi4:14b']);
+ for (const m of body.models) {
+ expect(db.prepare('SELECT 1 FROM fallback_config WHERE model_db_id = ?').get(m.modelDbId)).toBeDefined();
+ }
+ });
+
+ it('dedupes repeated ids and ignores blanks', async () => {
+ const { status, body } = await post(app, '/api/keys/custom', {
+ baseUrl: 'http://127.0.0.1:9999/v1',
+ models: ['dupe:1', 'dupe:1', ' '],
+ });
+ expect(status).toBe(201);
+ expect(body.models).toHaveLength(1);
+ expect(body.models[0].model).toBe('dupe:1');
+ });
+
+ it('rejects a submit with neither model nor models', async () => {
+ const { status } = await post(app, '/api/keys/custom', { baseUrl: 'http://127.0.0.1:9999/v1' });
+ expect(status).toBe(400);
+ });
+ });
});
diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.ts
index b7d336e8..00b8ec45 100644
--- a/server/src/routes/keys.ts
+++ b/server/src/routes/keys.ts
@@ -125,13 +125,24 @@ keysRouter.post('/', (req: Request, res: Response) => {
// 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.
+// A model can be given as a bare id ("qwen3:4b") or as {model, displayName}.
+// `model`/`displayName` (singular) stay supported for older clients; `models`
+// (plural) lets one submit bind several model ids to the same endpoint. (#281)
+const modelEntrySchema = z.union([
+ z.string().min(1),
+ z.object({ model: z.string().min(1), displayName: z.string().optional() }),
+]);
const customProviderSchema = z.object({
baseUrl: z.string().url('baseUrl must be a valid URL'),
- model: z.string().min(1, 'model is required'),
+ model: z.string().optional(),
+ models: z.array(modelEntrySchema).optional(),
displayName: z.string().optional(),
apiKey: z.string().optional(),
label: z.string().optional(),
-});
+}).refine(
+ d => (d.model && d.model.trim().length > 0) || (d.models && d.models.length > 0),
+ { message: 'model or models is required' },
+);
keysRouter.post('/custom', (req: Request, res: Response) => {
const parsed = customProviderSchema.safeParse(req.body);
@@ -141,12 +152,32 @@ keysRouter.post('/custom', (req: Request, res: Response) => {
}
const baseUrl = parsed.data.baseUrl.trim().replace(/\/+$/, '');
- const modelId = parsed.data.model.trim();
- const displayName = (parsed.data.displayName ?? modelId).trim();
// Local servers often need no key; keep a sentinel so there's always a bearer.
const rawKey = parsed.data.apiKey?.trim() || 'no-key';
const label = parsed.data.label ?? 'Custom';
+ // Flatten singular + plural inputs into one list, dedupe by model id, drop
+ // blanks. The singular `displayName` only applies to a lone `model` (it can't
+ // sensibly fan out across many ids).
+ const entries: { modelId: string; displayName: string }[] = [];
+ const seen = new Set<string>();
+ const addEntry = (rawId: string, rawDisplay?: string) => {
+ const modelId = rawId.trim();
+ if (!modelId || seen.has(modelId)) return;
+ seen.add(modelId);
+ entries.push({ modelId, displayName: (rawDisplay?.trim() || modelId) });
+ };
+ if (parsed.data.model?.trim()) addEntry(parsed.data.model, parsed.data.displayName);
+ for (const m of parsed.data.models ?? []) {
+ if (typeof m === 'string') addEntry(m);
+ else addEntry(m.model, m.displayName);
+ }
+
+ if (entries.length === 0) {
+ res.status(400).json({ error: { message: 'model or models is required' } });
+ return;
+ }
+
const db = getDb();
const upsert = db.transaction(() => {
// One 'custom' key row PER ENDPOINT (matched on base_url). Re-submitting
@@ -169,40 +200,49 @@ keysRouter.post('/custom', (req: Request, res: Response) => {
keyId = Number(r.lastInsertRowid);
}
- // 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 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, 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 };
-
- // Append to the fallback chain if not already present.
- const inChain = db.prepare('SELECT 1 FROM fallback_config WHERE model_db_id = ?').get(modelRow.id);
- if (!inChain) {
- const max = db.prepare('SELECT COALESCE(MAX(priority), 0) AS m FROM fallback_config').get() as { m: number };
- db.prepare('INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, 1)').run(modelRow.id, max.m + 1);
+ const registered: { modelDbId: number; model: string; displayName: string }[] = [];
+ for (const { modelId, displayName } of entries) {
+ // Register each 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 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, 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 };
+
+ // Append to the fallback chain if not already present.
+ const inChain = db.prepare('SELECT 1 FROM fallback_config WHERE model_db_id = ?').get(modelRow.id);
+ if (!inChain) {
+ const max = db.prepare('SELECT COALESCE(MAX(priority), 0) AS m FROM fallback_config').get() as { m: number };
+ db.prepare('INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, 1)').run(modelRow.id, max.m + 1);
+ }
+
+ registered.push({ modelDbId: modelRow.id, model: modelId, displayName });
}
- return { keyId, modelDbId: modelRow.id };
+ return { keyId, registered };
});
- const { keyId, modelDbId } = upsert();
+ const { keyId, registered } = upsert();
+ // `model`/`displayName`/`modelDbId` echo the first model for older clients;
+ // `models` carries the full set registered in this call.
+ const first = registered[0]!;
res.status(201).json({
success: true,
keyId,
- modelDbId,
+ modelDbId: first.modelDbId,
platform: 'custom',
baseUrl,
- model: modelId,
- displayName,
+ model: first.model,
+ displayName: first.displayName,
+ models: registered,
maskedKey: maskKey(rawKey),
});
});