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(proxy): expose 'auto' as a virtual model in /v1/models (#62, closes #50, credits @mybropro)
Tashfeen21215502a1d6
diff --git a/README.md b/README.mdindex 0ddca85e..020dbd1e 100644--- a/README.md+++ b/README.md@@ -297,6 +297,7 @@ PRs should include a test, keep the existing test suite green, and match the `.e<a href="https://github.com/jtbrennan-git"><img src="https://images.weserv.nl/?url=github.com/jtbrennan-git.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@jtbrennan-git" /></a><a href="https://github.com/praveenkumarpranjal"><img src="https://images.weserv.nl/?url=github.com/praveenkumarpranjal.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@praveenkumarpranjal" /></a><a href="https://github.com/nordbyte"><img src="https://images.weserv.nl/?url=github.com/nordbyte.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@nordbyte" /></a>+<a href="https://github.com/mybropro"><img src="https://images.weserv.nl/?url=github.com/mybropro.png&w=60&h=60&fit=cover&mask=circle" width="60" alt="@mybropro" /></a>## Terms of Service reviewdiff --git a/server/src/__tests__/routes/proxy-auto-model.test.ts b/server/src/__tests__/routes/proxy-auto-model.test.tsnew file mode 100644index 00000000..c878c721--- /dev/null+++ b/server/src/__tests__/routes/proxy-auto-model.test.ts@@ -0,0 +1,112 @@+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';++async function request(app: Express, method: string, path: string, body?: any, headers: Record<string, string> = {}) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const url = `http://127.0.0.1:${addr.port}${path}`;++ const res = await fetch(url, {+ method,+ headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...headers },+ body: body ? JSON.stringify(body) : undefined,+ });++ const data = await res.text();+ server.close();++ let json: any = null;+ try { json = JSON.parse(data); } catch {}++ return { status: res.status, body: json, headers: res.headers, raw: data };+}++function authHeaders() {+ return { Authorization: `Bearer ${getUnifiedApiKey()}` };+}++describe('Virtual "auto" model', () => {+ let app: Express;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ });++ beforeEach(async () => {+ const db = getDb();+ db.prepare('DELETE FROM api_keys').run();+ db.prepare('DELETE FROM requests').run();++ const addKey = await request(app, 'POST', '/api/keys', {+ platform: 'groq',+ key: 'gsk_auto_model_test',+ label: 'auto-model',+ });+ expect(addKey.status).toBe(201);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('lists "auto" as the first /v1/models entry', async () => {+ const { status, body } = await request(app, 'GET', '/v1/models');+ expect(status).toBe(200);+ expect(body.object).toBe('list');+ expect(body.data[0]).toMatchObject({+ id: 'auto',+ object: 'model',+ owned_by: 'freellmapi',+ });+ // Real catalog models still follow.+ expect(body.data.length).toBeGreaterThan(1);+ });++ it('treats model:"auto" as auto-route instead of a 400', 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: true,+ json: () => Promise.resolve({+ id: 'chatcmpl-auto',+ object: 'chat.completion',+ created: 123,+ model: 'openai/gpt-oss-120b',+ choices: [{+ index: 0,+ message: { role: 'assistant', content: 'routed via auto' },+ finish_reason: 'stop',+ }],+ usage: { prompt_tokens: 5, completion_tokens: 3, total_tokens: 8 },+ }),+ } as any;+ }+ return origFetch(url, init);+ });++ const { status, body } = await request(app, 'POST', '/v1/chat/completions', {+ model: 'auto',+ messages: [{ role: 'user', content: 'hello' }],+ }, authHeaders());++ expect(status).toBe(200);+ expect(body.choices[0].message.content).toBe('routed via auto');+ });++ it('still rejects an unknown model with model_not_found', async () => {+ const { status, body } = await request(app, 'POST', '/v1/chat/completions', {+ model: 'definitely-not-a-real-model',+ messages: [{ role: 'user', content: 'hello' }],+ }, authHeaders());++ expect(status).toBe(400);+ expect(body.error.code).toBe('model_not_found');+ });+});diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 35c91974..b6eb772f 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -9,6 +9,16 @@ import { getDb, getUnifiedApiKey } from '../db/index.js';export const proxyRouter = Router();+// Virtual "auto" model. Clients like Hermes require a non-empty `model` field+// on every request, but freellmapi's whole point is to pick the model itself.+// Requesting this id means "let the router decide" — identical to omitting+// `model` entirely.+const AUTO_MODEL_ID = 'auto';++function isAutoModel(modelId: string | undefined): boolean {+ return modelId === AUTO_MODEL_ID;+}+// Constant-time string comparison for the unified API key. Plain `===` leaks// length and per-character timing, which a network attacker could in principle// use to recover the key one byte at a time.@@ -77,14 +87,24 @@ proxyRouter.get('/models', (_req: Request, res: Response) => {const models = db.prepare('SELECT platform, model_id, display_name, context_window FROM models WHERE enabled = 1 ORDER BY intelligence_rank').all() as any[];res.json({object: 'list',- data: models.map(m => ({- id: m.model_id,- object: 'model',- created: 0,- owned_by: m.platform,- name: m.display_name,- context_window: m.context_window,- })),+ data: [+ {+ id: AUTO_MODEL_ID,+ object: 'model',+ created: 0,+ owned_by: 'freellmapi',+ name: 'Auto (router picks the best available model)',+ context_window: null,+ },+ ...models.map(m => ({+ id: m.model_id,+ object: 'model',+ created: 0,+ owned_by: m.platform,+ name: m.display_name,+ context_window: m.context_window,+ })),+ ],});});@@ -255,7 +275,10 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {// different model would be surprising to OpenAI-compatible clients.// Sticky-session is the fallback when no `model` field was sent at all.let preferredModel: number | undefined;- if (requestedModel) {+ if (isAutoModel(requestedModel)) {+ // Explicit "auto" → behave exactly like an omitted model field.+ preferredModel = getStickyModel(messages);+ } else if (requestedModel) {const db = getDb();const enabled = db.prepare('SELECT id FROM models WHERE model_id = ? AND enabled = 1').get(requestedModel) as { id: number } | undefined;if (enabled) {@@ -265,7 +288,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {const reason = disabled ? 'is disabled' : 'is not in the catalog';res.status(400).json({error: {- message: `Model '${requestedModel}' ${reason}. Omit the 'model' field to auto-route, or call /v1/models for the available list.`,+ message: `Model '${requestedModel}' ${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',},