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(router): keep tool-bearing requests on models that emit structured tool_calls (#190)
Tashfeen3ad5b9b639b2
diff --git a/client/src/pages/FallbackPage.tsx b/client/src/pages/FallbackPage.tsxindex 95e96020..0ac7285b 100644--- a/client/src/pages/FallbackPage.tsx+++ b/client/src/pages/FallbackPage.tsx@@ -40,6 +40,7 @@ interface FallbackEntry {rpdLimit: number | nullmonthlyTokenBudget: stringsupportsVision: boolean+ supportsTools: booleankeyCount: number}@@ -254,6 +255,14 @@ function RowContent({Vision</span>)}+ {row.supportsTools && (+ <span+ title="Emits structured tool calls — eligible for tool-bearing requests"+ className="text-[10px] rounded-full px-1.5 py-0.5 bg-violet-600/15 text-violet-700 dark:bg-violet-400/15 dark:text-violet-400"+ >+ Tools+ </span>+ )}{(row.penalty ?? 0) > 0 && (<span className="text-[10px] text-amber-600 dark:text-amber-400">−{row.penalty} penalty</span>)}diff --git a/server/src/__tests__/routes/proxy-tools-routing.test.ts b/server/src/__tests__/routes/proxy-tools-routing.test.tsnew file mode 100644index 00000000..52a087b9--- /dev/null+++ b/server/src/__tests__/routes/proxy-tools-routing.test.ts@@ -0,0 +1,150 @@+import { describe, it, expect, beforeAll } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';+import { routeRequest, setRoutingStrategy } from '../../services/router.js';+import { encrypt } from '../../lib/crypto.js';++async function post(app: Express, path: string, body: any, key: string) {+ const server = app.listen(0);+ const addr = server.address() as any;+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },+ body: JSON.stringify(body),+ });+ const text = await res.text();+ server.close();+ let json: any = null;+ try { json = JSON.parse(text); } catch {}+ return { status: res.status, body: json };+}++const WEATHER_TOOL = {+ type: 'function',+ function: {+ name: 'get_weather',+ description: 'Get the weather for a city',+ parameters: { type: 'object', properties: { city: { type: 'string' } } },+ },+};++const TOOLS_CHAT = {+ messages: [{ role: 'user', content: 'what is the weather in Berlin?' }],+ tools: [WEATHER_TOOL],+};++const TOOLS_RESPONSES = {+ input: 'what is the weather in Berlin?',+ tools: [{+ type: 'function',+ name: 'get_weather',+ description: 'Get the weather for a city',+ parameters: { type: 'object', properties: { city: { type: 'string' } } },+ }],+};++describe('Tools-aware routing', () => {+ let app: Express;+ let key: string;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ key = getUnifiedApiKey();+ });++ it('flags tool-capable families and leaves the known-bad ones unflagged', () => {+ const db = getDb();+ const flag = (modelId: string) =>+ (db.prepare('SELECT supports_tools FROM models WHERE model_id = ?').get(modelId) as { supports_tools: number } | undefined)?.supports_tools;++ // Verified tool-callers from the live benchmark stay eligible.+ expect(flag('openai/gpt-oss-120b')).toBe(1);+ expect(flag('gemini-2.5-flash')).toBe(1);+ expect(flag('llama-3.3-70b-versatile')).toBe(1);++ // hermes-3 emits tool calls as text — must NOT ride the llama-3 rule.+ const hermes = db.prepare("SELECT supports_tools FROM models WHERE model_id LIKE '%hermes-3%'").all() as { supports_tools: number }[];+ for (const h of hermes) expect(h.supports_tools).toBe(0);++ // gemma must NOT ride the gemini rule.+ const gemma = db.prepare("SELECT supports_tools FROM models WHERE LOWER(model_id) LIKE '%gemma%'").all() as { supports_tools: number }[];+ for (const g of gemma) expect(g.supports_tools).toBe(0);++ // Sanity: the flag splits the catalog (some 1s, some 0s).+ const on = (db.prepare('SELECT COUNT(*) c FROM models WHERE supports_tools = 1').get() as { c: number }).c;+ const off = (db.prepare('SELECT COUNT(*) c FROM models WHERE supports_tools = 0').get() as { c: number }).c;+ expect(on).toBeGreaterThanOrEqual(5);+ expect(off).toBeGreaterThan(0);+ });++ it('routeRequest skips non-tool models when requireTools is set', () => {+ const db = getDb();+ setRoutingStrategy('priority');++ // One key for google, whose catalog holds both a non-tool model (gemma)+ // and tool-capable ones (gemini). Put gemma at the top of the chain.+ const { encrypted, iv, authTag } = encrypt('test-google-key');+ db.prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)+ VALUES ('google', 'test', ?, ?, ?, 'healthy', 1)+ `).run(encrypted, iv, authTag);++ const gemma = db.prepare("SELECT id FROM models WHERE platform = 'google' AND LOWER(model_id) LIKE '%gemma%' AND enabled = 1").get() as { id: number } | undefined;+ expect(gemma).toBeDefined();+ db.prepare('UPDATE fallback_config SET priority = 0, enabled = 1 WHERE model_db_id = ?').run(gemma!.id);++ // Plain request takes the chain head: gemma.+ const plain = routeRequest(1000);+ expect(plain.modelId.toLowerCase()).toContain('gemma');++ // Tool-bearing request must skip past gemma to a tool-capable model.+ const tooled = routeRequest(1000, undefined, undefined, false, true);+ expect(tooled.modelId.toLowerCase()).not.toContain('gemma');+ const flag = db.prepare('SELECT supports_tools FROM models WHERE id = ?').get(tooled.modelDbId) as { supports_tools: number };+ expect(flag.supports_tools).toBe(1);++ db.prepare('DELETE FROM api_keys').run();+ });++ it('lets a tool request through routing when a tool-capable model is enabled (no 422)', async () => {+ // No provider keys exist, so routing exhausts → 429/503. The point: it is+ // NOT the 422 "no tools model" error, proving the precheck passed.+ const { status, body } = await post(app, '/v1/chat/completions', TOOLS_CHAT, key);+ expect(status).not.toBe(422);+ expect(body?.error?.code).not.toBe('no_tools_model');+ });++ it('rejects a tool request with a clear 422 when no tool-capable model is enabled', async () => {+ getDb().prepare('UPDATE models SET enabled = 0 WHERE supports_tools = 1').run();++ const { status, body } = await post(app, '/v1/chat/completions', TOOLS_CHAT, key);+ expect(status).toBe(422);+ expect(body.error.code).toBe('no_tools_model');+ expect(body.error.type).toBe('invalid_request_error');++ getDb().prepare('UPDATE models SET enabled = 1 WHERE supports_tools = 1').run();+ });++ it('applies the same gate on /v1/responses (Codex path)', async () => {+ getDb().prepare('UPDATE models SET enabled = 0 WHERE supports_tools = 1').run();++ const { status, body } = await post(app, '/v1/responses', TOOLS_RESPONSES, key);+ expect(status).toBe(422);+ expect(body.error.code).toBe('no_tools_model');++ getDb().prepare('UPDATE models SET enabled = 1 WHERE supports_tools = 1').run();+ });++ it('does not apply the tools gate to a plain chat request', async () => {+ getDb().prepare('UPDATE models SET enabled = 0 WHERE supports_tools = 1').run();+ const { status, body } = await post(app, '/v1/chat/completions', {+ messages: [{ role: 'user', content: 'hello' }],+ }, key);+ expect(status).not.toBe(422);+ expect(body?.error?.code).not.toBe('no_tools_model');+ getDb().prepare('UPDATE models SET enabled = 1 WHERE supports_tools = 1').run();+ });+});diff --git a/server/src/db/index.ts b/server/src/db/index.tsindex 0a70bae1..689ed5b9 100644--- a/server/src/db/index.ts+++ b/server/src/db/index.ts@@ -56,6 +56,7 @@ export function initDb(dbPath?: string): Database.Database {migrateModelsV19Gemma4(db);migrateModelsV20KiloFree(db);migrateModelsV21PruneDead(db);+ migrateModelsV22Tools(db);ensureUnifiedKey(db);console.log(`Database initialized at ${resolvedPath}`);@@ -1624,6 +1625,71 @@ function migrateModelsV21PruneDead(db: Database.Database) {apply();}+// ── V22: tools-aware routing (2026-06-04) ──+// Adds the supports_tools column and flags the models that reliably emit+// STRUCTURED tool_calls. Motivation: an OpenAI-compatible agent client+// (Paperclip/Codex via /v1/responses) sent tool-bearing requests that the+// chain cascaded down to models with no real function-calling support —+// nemotron-3-nano answered 72 requests averaging ~38 output tokens, and the+// tool call leaked into chat text as literal `</tool_call>` XML, so the agent+// harness never saw a status update and every issue dead-ended in manual+// recovery. The router now keeps tool-bearing requests on this flagged subset+// (see routeRequest's requireTools).+//+// Rule-based by model family rather than a hardcoded id list, same reasoning+// as V16Vision: the catalog churns through migrations and LIKE rules survive+// renames. A family is flagged only when (a) it has native, documented+// function calling AND (b) we've seen structured tool_calls from it through+// this gateway (the 2026-06-01 live tool-calling benchmark, V4's probe pass,+// or production traffic). Conservative on purpose: a false negative just+// narrows the pool, while a false positive reproduces the silent-garbage+// failure above. Deliberately NOT flagged: gemma (weak at tools — V4),+// nemotron nano/9b (the incident model), poolside laguna (returns ~2 tokens),+// hermes-3 (emits tool calls as text — V4), groq compound (built-in tools+// only, rejects user functions), r1-distills, and the small/stealth/unknown+// tail (granite, lfm, stepfun, big-pickle, mimo, owl-alpha, cogito,+// pollinations). Idempotent — reset-then-set, safe on fresh seeds and+// upgrades alike.+function migrateModelsV22Tools(db: Database.Database) {+ const columns = db.prepare('PRAGMA table_info(models)').all() as { name: string }[];+ if (!columns.some(col => col.name === 'supports_tools')) {+ db.prepare('ALTER TABLE models ADD COLUMN supports_tools INTEGER NOT NULL DEFAULT 0').run();+ }+ const apply = db.transaction(() => {+ // Reset first so a de-flagged model doesn't keep a stale flag across re-runs.+ db.prepare('UPDATE models SET supports_tools = 0').run();+ db.prepare(`+ UPDATE models SET supports_tools = 1+ WHERE (+ LOWER(model_id) LIKE '%gpt-oss%' -- groq/OR/cerebras/CF/sambanova/ollama; incl. safeguard (tool-tuned)+ OR ((LOWER(model_id) LIKE '%llama-3%' OR LOWER(model_id) LIKE '%llama-4%')+ AND LOWER(model_id) NOT LIKE '%hermes%') -- Llama 3.x/4 native tools; hermes-3-llama emits text tool calls+ OR LOWER(model_id) LIKE '%gemini-%' -- every Gemini; gemma intentionally NOT matched+ OR LOWER(model_id) LIKE '%glm-%' -- GLM 4.5+/5.x are agentic-tuned (zai/zhipu/CF/ollama)+ OR LOWER(model_id) LIKE '%qwen3%'+ OR LOWER(model_id) LIKE '%qwen-3%' -- Qwen3 incl. coder/next variants+ OR LOWER(model_id) LIKE '%deepseek-v%' -- V3.x/V4 function calling; excludes r1-distill+ OR LOWER(model_id) LIKE '%kimi-k2%' -- K2 family is tool-native+ OR LOWER(model_id) LIKE '%minimax-m2%' -- M2.x is agent-focused+ OR LOWER(model_id) LIKE '%mistral-large%' -- Mistral API function calling (whole family)+ OR LOWER(model_id) LIKE '%mistral-medium%'+ OR LOWER(model_id) LIKE '%mistral-small%'+ OR LOWER(model_id) LIKE '%magistral%'+ OR LOWER(model_id) LIKE '%codestral%'+ OR LOWER(model_id) LIKE '%devstral%'+ OR LOWER(model_id) LIKE '%ministral%'+ OR LOWER(model_id) LIKE '%command-a%' -- Cohere native tool use (benchmarked top-20)+ OR LOWER(model_id) LIKE '%command-r%'+ OR LOWER(model_id) LIKE '%gpt-4o%' -- GitHub's OpenAI models+ OR LOWER(model_id) LIKE '%gpt-4.1%'+ OR LOWER(model_id) LIKE '%gpt-5%'+ OR LOWER(model_id) LIKE '%nemotron-3-super%' -- benchmarked #8 with real tool calls; nano stays excluded+ )+ `).run();+ });+ apply();+}+/** Append any models not yet in the fallback chain, lowest priority, ordered by* intelligence_rank. Shared by the recent model migrations (V18–V20). */function backfillFallback(db: Database.Database) {diff --git a/server/src/routes/fallback.ts b/server/src/routes/fallback.tsindex 678d5c9b..dbe162e5 100644--- a/server/src/routes/fallback.ts+++ b/server/src/routes/fallback.ts@@ -38,7 +38,7 @@ fallbackRouter.get('/', (_req: Request, res: Response) => {SELECT fc.model_db_id, fc.priority, fc.enabled,m.platform, m.model_id, m.display_name, m.intelligence_rank,m.speed_rank, m.size_label, m.rpm_limit, m.rpd_limit,- m.monthly_token_budget, m.supports_vision+ m.monthly_token_budget, m.supports_vision, m.supports_toolsFROM fallback_config fcJOIN models m ON m.id = fc.model_db_idORDER BY fc.priority ASC@@ -75,6 +75,7 @@ fallbackRouter.get('/', (_req: Request, res: Response) => {rpdLimit: r.rpd_limit,monthlyTokenBudget: r.monthly_token_budget,supportsVision: r.supports_vision === 1,+ supportsTools: r.supports_tools === 1,keyCount: keyCountMap.get(r.platform) ?? 0,};}));diff --git a/server/src/routes/models.ts b/server/src/routes/models.tsindex 9a381152..91c921ba 100644--- a/server/src/routes/models.ts+++ b/server/src/routes/models.ts@@ -41,6 +41,7 @@ modelsRouter.get('/', (_req: Request, res: Response) => {contextWindow: m.context_window,enabled: m.enabled === 1,supportsVision: m.supports_vision === 1,+ supportsTools: m.supports_tools === 1,priority: m.priority,fallbackEnabled: m.fallback_enabled === 1,hasProvider: hasProvider(m.platform),diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 11711bad..6b286b3b 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -3,7 +3,7 @@ import { Router } from 'express';import type { Request, Response } from 'express';import { z } from 'zod';import type { ChatMessage } from '@freellmapi/shared/types.js';-import { routeRequest, recordRateLimitHit, recordSuccess, hasEnabledVisionModel, type RouteResult } from '../services/router.js';+import { routeRequest, recordRateLimitHit, recordSuccess, hasEnabledVisionModel, hasEnabledToolsModel, type RouteResult } from '../services/router.js';import { recordRequest, recordTokens, setCooldown, getCooldownDurationForLimit } from '../services/ratelimit.js';import { pruneRequestAnalytics } from '../services/request-retention.js';import { getDb, getUnifiedApiKey } from '../db/index.js';@@ -414,6 +414,23 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {n + (Array.isArray(m.content) ? m.content.filter(b => (b as { type?: string })?.type === 'image_url' || (b as { type?: string })?.type === 'image').length : 0), 0);const estimatedTotal = estimatedInputTokens + imageCount * IMAGE_TOKEN_ESTIMATE + (max_tokens ?? 1000);+ // Tool-bearing requests must route to a model that emits STRUCTURED+ // tool_calls. A model without real function-calling support serializes the+ // call into its text answer — the request "succeeds" but the client's tool+ // loop sees nothing, which is strictly worse than an error. Same up-front+ // gate pattern as vision above.+ const wantsTools = (tools?.length ?? 0) > 0;+ if (wantsTools && !hasEnabledToolsModel()) {+ res.status(422).json({+ error: {+ message: 'This request includes tools, but no tool-capable model is enabled. Enable a tool-calling model (e.g. GPT-OSS 120B, Gemini 3.5 Flash, GLM-4.7) in the Fallback Chain.',+ type: 'invalid_request_error',+ code: 'no_tools_model',+ },+ });+ return;+ }+// Explicit `model` field pins routing. If the catalog has no enabled row// matching the requested id, return 400 — silently auto-routing to a// different model would be surprising to OpenAI-compatible clients.@@ -450,7 +467,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {let route: RouteResult;try {- route = routeRequest(estimatedTotal, skipKeys.size > 0 ? skipKeys : undefined, preferredModel, hasImage);+ route = routeRequest(estimatedTotal, skipKeys.size > 0 ? skipKeys : undefined, preferredModel, hasImage, wantsTools);} catch (err: any) {// No more models availableif (lastError) {diff --git a/server/src/routes/responses.ts b/server/src/routes/responses.tsindex 81c66ce1..38776953 100644--- a/server/src/routes/responses.ts+++ b/server/src/routes/responses.ts@@ -8,7 +8,7 @@ import type {ChatToolDefinition,ChatToolChoice,} from '@freellmapi/shared/types.js';-import { routeRequest, recordRateLimitHit, recordSuccess, type RouteResult } from '../services/router.js';+import { routeRequest, recordRateLimitHit, recordSuccess, hasEnabledToolsModel, type RouteResult } from '../services/router.js';import { recordRequest, recordTokens, setCooldown, getCooldownDurationForLimit } from '../services/ratelimit.js';import { getUnifiedApiKey } from '../db/index.js';import { contentToString } from '../lib/content.js';@@ -313,6 +313,22 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {const estimatedTotal = estimatedInputTokens + (reqData.max_output_tokens ?? 1000);const preferredModel = getStickyModel(messages);+ // Tool-bearing requests (the normal case for Codex/agent clients on this+ // endpoint) must stay on models that emit structured tool_calls — a model+ // that serializes the call into text strands the agent harness with a+ // "successful" run it can't act on. Mirrors the /chat/completions gate.+ const wantsTools = (tools?.length ?? 0) > 0;+ if (wantsTools && !hasEnabledToolsModel()) {+ res.status(422).json({+ error: {+ message: 'This request includes tools, but no tool-capable model is enabled. Enable a tool-calling model (e.g. GPT-OSS 120B, Gemini 3.5 Flash, GLM-4.7) in the Fallback Chain.',+ type: 'invalid_request_error',+ code: 'no_tools_model',+ },+ });+ return;+ }+const responseId = newId('resp');const skipKeys = new Set<string>();let lastError: any = null;@@ -328,7 +344,7 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {let route: RouteResult;try {- route = routeRequest(estimatedTotal, skipKeys.size > 0 ? skipKeys : undefined, preferredModel);+ route = routeRequest(estimatedTotal, skipKeys.size > 0 ? skipKeys : undefined, preferredModel, false, wantsTools);} catch (err: any) {const status = lastError ? 429 : (err.status ?? 503);const message = lastErrordiff --git a/server/src/services/router.ts b/server/src/services/router.tsindex 10257d77..d1334476 100644--- a/server/src/services/router.ts+++ b/server/src/services/router.ts@@ -38,6 +38,7 @@ interface ChainRow {tpm_limit: number | null;tpd_limit: number | null;supports_vision: number;+ supports_tools: number;context_window: number | null;}@@ -340,8 +341,9 @@ function orderChain(chain: ChainRow[], strategy: RoutingStrategy): ChainRow[] {* @param skipKeys - set of "platform:modelId:keyId" to skip (failed on this request)* @param preferredModelDbId - try this model first (sticky session)* @param requireVision - only consider models that accept image input (#118)+ * @param requireTools - only consider models that emit structured tool_calls*/-export function routeRequest(estimatedTokens = 1000, skipKeys?: Set<string>, preferredModelDbId?: number, requireVision = false): RouteResult {+export function routeRequest(estimatedTokens = 1000, skipKeys?: Set<string>, preferredModelDbId?: number, requireVision = false, requireTools = false): RouteResult {const db = getDb();const strategy = getRoutingStrategy();@@ -353,7 +355,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.context_window+ m.supports_tools, m.context_windowFROM fallback_config fcJOIN models m ON m.id = fc.model_db_id AND m.enabled = 1WHERE fc.enabled = 1@@ -375,6 +377,13 @@ export function routeRequest(estimatedTokens = 1000, skipKeys?: Set<string>, pre// which is correct: don't pin an image turn to a model that can't see it.if (requireVision && !entry.supports_vision) continue;+ // Tool-bearing requests skip models that can't emit structured tool_calls.+ // A model that "answers" a tool request with the call serialized as text+ // looks successful at the transport level while the client's harness sees+ // nothing — worse than a failover. Applies to sticky models too, same+ // reasoning as vision above.+ if (requireTools && !entry.supports_tools) continue;+// Context-aware routing: skip a model whose context window can't hold the// request, so a large prompt never selects a small-context model and burns// a failover hop on a 413 "request too large" (#167). Only enforced when we@@ -503,7 +512,7 @@ export function getRoutingScores(): { strategy: RoutingStrategy; weights: Routinm.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.context_window+ m.supports_tools, m.context_windowFROM fallback_config fcJOIN models m ON m.id = fc.model_db_idWHERE m.enabled = 1@@ -551,3 +560,17 @@ export function hasEnabledVisionModel(): boolean {`).get() as { cnt: number };return row.cnt > 0;}++// Whether at least one tool-capable model is enabled in the fallback chain.+// Same role as hasEnabledVisionModel: a clear up-front error for tool-bearing+// requests beats routing them to a model that mangles the tool call.+export function hasEnabledToolsModel(): boolean {+ const db = getDb();+ const row = db.prepare(`+ SELECT COUNT(*) as cnt+ FROM fallback_config fc+ JOIN models m ON m.id = fc.model_db_id+ WHERE fc.enabled = 1 AND m.enabled = 1 AND m.supports_tools = 1+ `).get() as { cnt: number };+ return row.cnt > 0;+}diff --git a/shared/types.ts b/shared/types.tsindex 064d795d..cdbfc53f 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -45,6 +45,7 @@ export interface Model {contextWindow: number | null;enabled: boolean;supportsVision: boolean;+ supportsTools: boolean;}export type KeyStatus = 'healthy' | 'rate_limited' | 'invalid' | 'error' | 'unknown';