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(routing): learn per-model output ceilings instead of benching models that reject max_tokens (#1364)
Tashfeen26278add86b5
diff --git a/server/src/__tests__/lib/fallback-loop-size-skip.test.ts b/server/src/__tests__/lib/fallback-loop-size-skip.test.tsindex d794d219..a5a41fee 100644--- a/server/src/__tests__/lib/fallback-loop-size-skip.test.ts+++ b/server/src/__tests__/lib/fallback-loop-size-skip.test.ts@@ -19,6 +19,7 @@ import {resetModelFailureWindows,} from '../../lib/fallback-loop.js';import { isOnCooldown, resetKeyLocalityCache } from '../../services/ratelimit.js';+import { resetLearnedOutputCaps } from '../../lib/output-cap.js';import {setRoutingStrategy,clearAllPenalties,@@ -252,3 +253,26 @@ describe('request-too-large failures', () => {expect(isOnCooldown(PLATFORM, modelSmall.model_id, freshKey)).toBe(false);});});++describe('max_tokens above the model output ceiling', () => {+ const msg = 'Groq API error 400: `max_tokens` must be less than or equal to `65536`, the maximum value for `max_tokens` is less than the `context_window` for this model';++ it('retries the same route once the ceiling is learned, then rules the model out if it still rejects', () => {+ resetLearnedOutputCaps();+ const freshKey = insertKey('output-cap');+ resetKeyLocalityCache();+ const route = routeFor(modelSmall, freshKey);+ const routeKey = `${PLATFORM}:${modelSmall.model_id}:${freshKey}`;+ const state = newFallbackState();+ state.wantsTools = true;++ recordRetryableFailure(route, Object.assign(new Error(msg), { status: 400 }), state);+ expect(state.skipKeys.has(routeKey)).toBe(false);+ expect(state.skipModels.has(modelSmall.id)).toBe(false);+ expect(isOnCooldown(PLATFORM, modelSmall.model_id, freshKey)).toBe(false);++ recordRetryableFailure(route, Object.assign(new Error(msg), { status: 400 }), state);+ expect(state.skipModels.has(modelSmall.id)).toBe(true);+ expect(isOnCooldown(PLATFORM, modelSmall.model_id, freshKey)).toBe(false);+ });+});diff --git a/server/src/__tests__/lib/module-purity.test.ts b/server/src/__tests__/lib/module-purity.test.tsindex ebedc122..082304ae 100644--- a/server/src/__tests__/lib/module-purity.test.ts+++ b/server/src/__tests__/lib/module-purity.test.ts@@ -36,6 +36,8 @@ const PURE_MODULES = ['credential.ts','error-classify.ts','header-value.ts',+ // Learned output ceilings; the fallback loop and every route import it.+ 'output-cap.ts','provider-identity.ts','provider-size-parser.ts','retry-hint.ts',diff --git a/server/src/__tests__/lib/output-cap.test.ts b/server/src/__tests__/lib/output-cap.test.tsnew file mode 100644index 00000000..b2cc5901--- /dev/null+++ b/server/src/__tests__/lib/output-cap.test.ts@@ -0,0 +1,51 @@+import { describe, it, expect, beforeEach } from 'vitest';+import {+ learnOutputCapFromError,+ learnedOutputCap,+ parseMaxTokensCeiling,+ resetLearnedOutputCaps,+ routeOutputBudget,+} from '../../lib/output-cap.js';++// Live bodies, 2026-09-29, for Claude Code's max_tokens of 128000.+const OLLAMA = "Ollama Cloud API error 400: max_tokens (128000) exceeds model's maximum output tokens (65536) for model nemotron-3-ultra (ref: 3761884e-8e9b-4c46-8526-5de77ebe3c25)";+const GROQ = 'Groq API error 400: `max_tokens` must be less than or equal to `65536`, the maximum value for `max_tokens` is less than the `context_window` for this model';++beforeEach(() => resetLearnedOutputCaps());++describe('parseMaxTokensCeiling', () => {+ it('reads the ceiling from Ollama Cloud and Groq rejections', () => {+ expect(parseMaxTokensCeiling(OLLAMA)).toBe(65536);+ expect(parseMaxTokensCeiling(GROQ)).toBe(65536);+ expect(parseMaxTokensCeiling('max_completion_tokens must be at most 32768')).toBe(32768);+ });++ it('ignores context-window and unrelated errors', () => {+ expect(parseMaxTokensCeiling('Cloudflare API error 413: AiError: Ai: The estimated number of input and maximum output tokens (24092) exceeded this model context window limit (24000).')).toBeNull();+ expect(parseMaxTokensCeiling('Groq API error 413: Request too large for model `x` on tokens per minute (TPM): Limit 8000, Requested 17679')).toBeNull();+ expect(parseMaxTokensCeiling('max_tokens must be a positive integer')).toBeNull();+ });+});++describe('learned output caps', () => {+ const route = { platform: 'ollama', modelId: 'nemotron-3-ultra', contextWindow: 262144 };++ it('learns from a 400 and keeps the lowest reading', () => {+ expect(learnOutputCapFromError(route, Object.assign(new Error(OLLAMA), { status: 400 }))).toBe(65536);+ learnOutputCapFromError(route, Object.assign(new Error('max_tokens must be at most 32768'), { status: 400 }));+ expect(learnedOutputCap('ollama', 'nemotron-3-ultra')).toBe(32768);+ });++ it('does not learn from a non-400 status', () => {+ expect(learnOutputCapFromError(route, Object.assign(new Error(OLLAMA), { status: 503 }))).toBeNull();+ expect(learnedOutputCap('ollama', 'nemotron-3-ultra')).toBeUndefined();+ });++ it('lowers the route output budget to the learned cap', () => {+ expect(routeOutputBudget(route, 20000)).toBe(242144);+ learnOutputCapFromError(route, Object.assign(new Error(OLLAMA), { status: 400 }));+ expect(routeOutputBudget(route, 20000)).toBe(65536);+ expect(routeOutputBudget({ ...route, contextWindow: 50000 }, 20000)).toBe(30000);+ expect(routeOutputBudget({ ...route, contextWindow: null }, 20000)).toBe(65536);+ });+});diff --git a/server/src/__tests__/routes/output-cap-learning.test.ts b/server/src/__tests__/routes/output-cap-learning.test.tsnew file mode 100644index 00000000..bdcf2c51--- /dev/null+++ b/server/src/__tests__/routes/output-cap-learning.test.ts@@ -0,0 +1,59 @@+import { it, expect, vi } from 'vitest';+import { createApp } from '../../app.js';+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { resetLearnedOutputCaps } from '../../lib/output-cap.js';+import { getProvider } from '../../providers/index.js';+import { setRoutingStrategy } from '../../services/router.js';++// Claude Code sends max_tokens 128000. A model whose output ceiling is lower+// rejects it with a 400; the gateway must learn the ceiling, retry that model+// with max_tokens clamped, and keep clamping later requests, instead of+// benching it or booking it as a model without tool support.+it('/v1/messages learns an output ceiling from a max_tokens rejection and clamps later requests', async () => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:'); const db = getDb(); setRoutingStrategy('priority'); resetLearnedOutputCaps();+ db.prepare('UPDATE models SET enabled = 0').run();+ db.prepare('DELETE FROM profile_models').run();+ for (const index of [0, 1]) {+ const id = Number(db.prepare("INSERT INTO models(platform,model_id,display_name,intelligence_rank,speed_rank,size_label,context_window,enabled,supports_tools) VALUES ('groq',?,?,1,1,'Large',262144,1,1)")+ .run('cap-test-' + index, 'Cap test ' + index).lastInsertRowid);+ db.prepare('INSERT INTO profile_models(profile_id,model_db_id,priority,enabled) SELECT id,?,?,1 FROM profiles').run(id, index);+ }+ const { encrypted, iv, authTag } = encrypt('synthetic-key');+ db.prepare("INSERT INTO api_keys(platform,label,encrypted_key,iv,auth_tag,status,enabled) VALUES ('groq','test',?,?,?,'healthy',1)").run(encrypted, iv, authTag);+ const calls: { model: string; budget?: number }[] = [];+ const spy = vi.spyOn(getProvider('groq')!, 'chatCompletion').mockImplementation(async (_key, _messages, model, options) => {+ calls.push({ model, budget: options?.contextBudget });+ if (model === 'cap-test-0' && (options?.contextBudget ?? Infinity) > 65536) {+ throw Object.assign(new Error('Groq API error 400: `max_tokens` must be less than or equal to `65536`, the maximum value for `max_tokens` is less than the `context_window` for this model'), { status: 400 });+ }+ return { id: 'test', object: 'chat.completion', created: 1, model, choices: [{ index: 0, message: { role: 'assistant', content: 'ok' }, finish_reason: 'stop' }], usage: { prompt_tokens: 3, completion_tokens: 1, total_tokens: 4 } };+ });+ const server = createApp().listen(0, '127.0.0.1');+ if (!server.listening) await new Promise<void>(r => server.once('listening', r));+ const send = (text: string) => fetch('http://127.0.0.1:' + (server.address() as { port: number }).port + '/v1/messages', {+ method: 'POST',+ headers: { 'x-api-key': getUnifiedApiKey(), 'anthropic-version': '2023-06-01', 'Content-Type': 'application/json' },+ body: JSON.stringify({+ model: 'claude-opus-4-5', max_tokens: 128000,+ messages: [{ role: 'user', content: text }],+ tools: [{ name: 'noop', description: 'does nothing', input_schema: { type: 'object', properties: {} } }],+ }),+ });+ try {+ const first = await send('first request');+ expect(first.status).toBe(200);+ // Learned on the first rejection, then the same model retried, clamped.+ expect(calls.map(c => c.model)).toEqual(['cap-test-0', 'cap-test-0']);+ expect(calls[1].budget).toBe(65536);++ calls.length = 0;+ const second = await send('a different second request');+ expect(second.status).toBe(200);+ // Not benched: the priority-0 model is tried first again, now clamped.+ expect(calls).toHaveLength(1);+ expect(calls[0].model).toBe('cap-test-0');+ expect(calls[0].budget).toBe(65536);+ } finally { server.close(); spy.mockRestore(); }+});diff --git a/server/src/lib/fallback-loop.ts b/server/src/lib/fallback-loop.tsindex c437e6ee..49f0dc4d 100644--- a/server/src/lib/fallback-loop.ts+++ b/server/src/lib/fallback-loop.ts@@ -61,6 +61,7 @@ import { getRequestTrace, newRequestTrace, runWithRequestTrace, type AttemptOutcimport { logRequest, persistRequestAttempts } from './request-log.js';import { withKeyProxy } from './proxy.js';import { getEndpointTimeBudgetMs } from './ttfb-budget.js';+import { learnOutputCapFromError, learnedOutputCap } from './output-cap.js';// Every surface caps failover hops at the same number.export const FALLBACK_MAX_RETRIES = 20;@@ -509,6 +510,23 @@ export function recordRetryableFailure(route: RouteResult, err: any, state: FalllearnLimitFromError(route.modelDbId, err);return false;}+ // A max_tokens above this model's output ceiling (Claude Code asks for+ // 128000; Groq gpt-oss and Ollama Cloud's Nemotron stop at 65536) is the+ // request's shape, not the model's health and not missing tool support, so+ // it stays off the cooldown, penalty and tool-rejection books. A ceiling+ // learned just now makes the same route usable again at once (the next+ // attempt is clamped to it); one that was already applied and still got+ // rejected rules the model out for this request.+ const capBefore = learnedOutputCap(route.platform, route.modelId);+ const ceiling = learnOutputCapFromError(route, err);+ if (ceiling != null) {+ if (capBefore == null || ceiling < capBefore) {+ state.skipKeys.delete(`${route.platform}:${route.modelId}:${route.keyId}`);+ } else {+ state.skipModels.add(route.modelDbId);+ }+ return false;+ }if (consumeSkipBenchExemption(route, err)) return true;const decision = cooldownDecisionForError(route, err);setCooldown(route.platform, route.modelId, route.keyId, decision.durationMs, decision.source);diff --git a/server/src/lib/inbound-chat.ts b/server/src/lib/inbound-chat.tsindex bc2647fe..d5e70823 100644--- a/server/src/lib/inbound-chat.ts+++ b/server/src/lib/inbound-chat.ts@@ -32,6 +32,7 @@ import {import { routedViaValue } from './header-value.js';import { applyTokenBudget, tokenBudgetMessage } from './guardrails.js';import { contentToString, estimateInputTokens } from './content.js';+import { routeOutputBudget } from './output-cap.js';import { normalizeMessageImages } from './image-normalize.js';import { repairToolArguments, toolSchemaMap } from './tool-args.js';import { invalidToolArgumentsError, invalidToolCallReasons, isToolArgumentValidationEnabled } from './tool-validate.js';@@ -254,7 +255,7 @@ export async function runInboundChat(route.apiKey,input.messages,route.modelId,- options,+ { ...options, contextBudget: routeOutputBudget(route, estimatedInputTokens) },);const message = result.choices?.[0]?.message;let text = contentToString(message?.content ?? '');@@ -381,7 +382,7 @@ export async function runInboundChat(route.apiKey,input.messages,route.modelId,- options,+ { ...options, contextBudget: routeOutputBudget(route, estimatedInputTokens) },);for await (const chunk of stream) {if (clientGone) break;diff --git a/server/src/lib/output-cap.ts b/server/src/lib/output-cap.tsnew file mode 100644index 00000000..1358b9f9--- /dev/null+++ b/server/src/lib/output-cap.ts@@ -0,0 +1,72 @@+// Per-model output-token ceilings learned from provider rejections.+//+// Clients size max_tokens for the model they think they are talking to:+// Claude Code asks for 128000, Open WebUI for 65536. Several free models stop+// lower and reject the request outright instead of clamping it, observed live:+// - Ollama Cloud: "max_tokens (128000) exceeds model's maximum output tokens+// (65536) for model nemotron-3-ultra"+// - Groq: "`max_tokens` must be less than or equal to `65536`, the maximum+// value for `max_tokens` is less than the `context_window` for this model"+// The catalog has no output-limit column, so the ceiling is learned from the+// first rejection and applied to every later request on that model through the+// per-route output budget (resolveMaxTokens clamps max_tokens to it). A+// restart forgets the ceilings; the first request after it pays one failover+// hop to relearn each one.++const learned = new Map<string, number>();++const MAX_TOKENS_PARAM = /\b(max_tokens|max_completion_tokens|max_output_tokens|maxoutputtokens|max_new_tokens)\b/;+// The number that follows a ceiling phrase: "less than or equal to `65536`",+// "maximum output tokens (65536)", "at most 32768", "no more than 8192".+const CEILING = /(?:less than or equal to|at most|maximum output tokens|no (?:more|greater) than|cannot exceed|must not exceed)\W{0,4}(\d{3,7})/;++function capKey(platform: string, modelId: string): string {+ return `${platform}:${modelId}`;+}++/** The output ceiling a provider names when it rejects max_tokens as too+ * large, or null when the error is anything else. Both the parameter name and+ * a ceiling phrase must appear, so a context-window rejection that merely+ * mentions "maximum output tokens" (Cloudflare) never matches. */+export function parseMaxTokensCeiling(message: unknown): number | null {+ const msg = String(message ?? '').toLowerCase();+ if (!MAX_TOKENS_PARAM.test(msg)) return null;+ const match = CEILING.exec(msg);+ if (!match) return null;+ const ceiling = Number(match[1]);+ return Number.isFinite(ceiling) && ceiling > 0 ? ceiling : null;+}++/** Learn the ceiling from a max_tokens rejection. Returns it, or null when the+ * error is not one. The lowest reading wins. */+export function learnOutputCapFromError(route: { platform: string; modelId: string }, err: any): number | null {+ const status = typeof err?.status === 'number' ? err.status : 0;+ if (status !== 0 && status !== 400 && status !== 422) return null;+ const ceiling = parseMaxTokensCeiling(err?.message);+ if (ceiling == null) return null;+ const key = capKey(route.platform, route.modelId);+ const current = learned.get(key);+ learned.set(key, current == null ? ceiling : Math.min(current, ceiling));+ return ceiling;+}++export function learnedOutputCap(platform: string, modelId: string): number | undefined {+ return learned.get(capKey(platform, modelId));+}++/** The output budget for one route: what is left of its context window after+ * the input, lowered to any learned output ceiling. Adapters pass it to+ * resolveMaxTokens as `contextBudget`. */+export function routeOutputBudget(+ route: { platform: string; modelId: string; contextWindow?: number | null },+ estimatedInputTokens: number,+): number | undefined {+ const windowLeft = route.contextWindow != null ? route.contextWindow - estimatedInputTokens : undefined;+ const cap = learnedOutputCap(route.platform, route.modelId);+ if (cap == null) return windowLeft;+ return windowLeft == null ? cap : Math.min(windowLeft, cap);+}++export function resetLearnedOutputCaps(): void {+ learned.clear();+}diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.tsindex b12826e9..dab33a8f 100644--- a/server/src/routes/anthropic.ts+++ b/server/src/routes/anthropic.ts@@ -12,6 +12,7 @@ import type {import { routeRequest, resolveModelGroupCandidates, resolveRoutingChain, resolveStickyPreference, routingReserveTokens, type RouteResult, type ResolvedChain, type ChainRow } from '../services/router.js';import { getSetting, getUnifiedApiKey } from '../db/index.js';import { contentToString, estimateInputTokens } from '../lib/content.js';+import { routeOutputBudget } from '../lib/output-cap.js';import { resolveTaskType } from '../lib/task-type.js';import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';import { invalidToolArgumentsError, invalidToolCallReasons, isToolArgumentValidationEnabled } from '../lib/tool-validate.js';@@ -656,7 +657,7 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {return routeRequest(routingTotal, state.skipKeys.size > 0 ? state.skipKeys : undefined, preferredModel, hasImage, wantsTools, state.skipModels.size > 0 ? state.skipModels : undefined, groupChain ?? resolvedChain?.chain, false, state.skipPlatforms.size > 0 ? state.skipPlatforms : undefined, outputReserve, taskType);},dispatch: async (route, attempt, dispatchCtx) => {- const contextBudget = route.contextWindow != null ? route.contextWindow - estimatedInputTokens : undefined;+ const contextBudget = routeOutputBudget(route, estimatedInputTokens);const routeOptions = { ...dispatchOptions, contextBudget };if (stream) {try {diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 864454b5..1ab4a015 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -12,6 +12,7 @@ import multer from 'multer';import { getDb } from '../db/index.js';import { resolveAuth, prependSystemPrompt, type ResolvedAuth } from '../lib/system-prompt.js';import { contentToString, estimateInputTokens, messageHasImage, normalizeOutboundContent, sanitizeResponse, truncateMessagesForGithub } from '../lib/content.js';+import { routeOutputBudget } from '../lib/output-cap.js';import { resolveTaskType } from '../lib/task-type.js';import { normalizeMessageImages } from '../lib/image-normalize.js';import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';@@ -1192,7 +1193,7 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {);},dispatch: async (route, attempt, ctx) => {- const contextBudget = route.contextWindow != null ? route.contextWindow - estimatedInputTokens : undefined;+ const contextBudget = routeOutputBudget(route, estimatedInputTokens);traceRouteEvent('Proxy', {event: attempt === 0 ? 'start' : 'next',requestId: requestGroupId,@@ -2118,7 +2119,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {return routeRequest(routingEstimate, state.skipKeys.size > 0 ? state.skipKeys : undefined, preferredModel, hasImage, wantsTools, state.skipModels.size > 0 ? state.skipModels : undefined, groupChain ?? resolvedChain?.chain, samplingParams.response_format !== undefined, state.skipPlatforms.size > 0 ? state.skipPlatforms : undefined, outputReserve, taskType);},dispatch: async (route, attempt, ctx) => {- const contextBudget = route.contextWindow != null ? route.contextWindow - estimatedInputTokens : undefined;+ const contextBudget = routeOutputBudget(route, estimatedInputTokens);const modelKey = `${route.platform}:${route.modelId}`;traceRouteEvent('Proxy', {event: attempt === 0 ? 'start' : 'next',diff --git a/server/src/routes/responses.ts b/server/src/routes/responses.tsindex 8b7445cc..f39b1986 100644--- a/server/src/routes/responses.ts+++ b/server/src/routes/responses.ts@@ -14,6 +14,7 @@ import { getDb } from '../db/index.js';import { resolveAuth, prependSystemPrompt } from '../lib/system-prompt.js';import { isUnifyEnabled, getModelGroups, resolveRequestedIdForDispatch } from '../services/model-groups.js';import { contentToString, estimateInputTokens, messageHasImage } from '../lib/content.js';+import { routeOutputBudget } from '../lib/output-cap.js';import { resolveTaskType } from '../lib/task-type.js';import { normalizeMessageImages } from '../lib/image-normalize.js';import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';@@ -1138,7 +1139,7 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {return routeRequest(routingTotal, state.skipKeys.size > 0 ? state.skipKeys : undefined, preferredModel, hasImage, wantsTools, state.skipModels.size > 0 ? state.skipModels : undefined, groupChain ?? resolvedChain?.chain, completionOpts.response_format !== undefined, state.skipPlatforms.size > 0 ? state.skipPlatforms : undefined, outputReserve, taskType);},dispatch: async (route, attempt, ctx) => {- const contextBudget = route.contextWindow != null ? route.contextWindow - estimatedInputTokens : undefined;+ const contextBudget = routeOutputBudget(route, estimatedInputTokens);const routeOpts = contextBudget != null ? { ...dispatchOpts, contextBudget } : dispatchOpts;traceRouteEvent('Responses', {event: attempt === 0 ? 'start' : 'next',diff --git a/server/src/services/fusion.ts b/server/src/services/fusion.tsindex 83bab2f5..9ac52ccb 100644--- a/server/src/services/fusion.ts+++ b/server/src/services/fusion.ts@@ -18,6 +18,7 @@ import { contentToString, stripImagesFromMessages } from '../lib/content.js';import { sanitizeProviderErrorMessage } from '../lib/error-redaction.js';import { getSetting, setSetting } from '../db/index.js';import type { CompletionOptions } from '../providers/base.js';+import { routeOutputBudget } from '../lib/output-cap.js';// The virtual model id that triggers multi-model synthesis. Mirrors how// `auto` is a virtual id the router intercepts (see routes/proxy.ts).@@ -275,9 +276,7 @@ async function runModelCall(if (!route) break;const startedAt = Date.now();- const routeOpts = route.contextWindow != null- ? { ...options, contextBudget: route.contextWindow - estimatedTokens }- : options;+ const routeOpts = { ...options, contextBudget: routeOutputBudget(route, estimatedTokens) };try {const result = await route.provider.chatCompletion(route.apiKey, messages, route.modelId, routeOpts);const choice = result.choices?.[0];@@ -366,9 +365,7 @@ async function runJudgeStreaming(if (!route) break;const startedAt = Date.now();- const routeOpts = route.contextWindow != null- ? { ...options, contextBudget: route.contextWindow - estimatedTokens }- : options;+ const routeOpts = { ...options, contextBudget: routeOutputBudget(route, estimatedTokens) };let text = '';let started = false;try {