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(server): unified output-token cap setting to rescue excessive client max_tokens (#783)
suantea (asuan_suan)f3613ae344b6
diff --git a/server/src/__tests__/lib/unified-max-tokens.test.ts b/server/src/__tests__/lib/unified-max-tokens.test.tsnew file mode 100644index 00000000..d6f669a6--- /dev/null+++ b/server/src/__tests__/lib/unified-max-tokens.test.ts@@ -0,0 +1,97 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// The unified output-token cap: an operator-level ceiling on max_tokens that+// applies to every client. Open WebUI sends max_tokens=65536 by default, which+// 400s against free models whose output limit is 32768 — and the invalid value+// rides every failover hop, so the chain can't rescue the request.++// Mock the settings store so the cap can be driven deterministically, the same+// way guardrails.test.ts drives its knobs.+const settingStore = new Map<string, string>();+vi.mock('../../db/index.js', () => ({+ getSetting: (key: string) => settingStore.get(key),+}));++import {+ unifiedMaxTokensCap,+ resolveMaxTokens,+ defaultMaxTokensFor,+ UNIFIED_MAX_TOKENS_SETTING,+ UNIFIED_MAX_TOKENS_AUTO,+} from '../../lib/sampling-params.js';++beforeEach(() => {+ settingStore.clear();+});++describe('unifiedMaxTokensCap', () => {+ it('is disabled when the setting is unset', () => {+ expect(unifiedMaxTokensCap()).toBeNull();+ });++ it("is disabled for 'off', '0' and an empty value", () => {+ for (const raw of ['off', 'OFF', ' off ', '0', '', ' ']) {+ settingStore.set(UNIFIED_MAX_TOKENS_SETTING, raw);+ expect(unifiedMaxTokensCap()).toBeNull();+ }+ });++ it("resolves 'auto' to the auto ceiling, case- and space-insensitively", () => {+ for (const raw of ['auto', 'AUTO', ' Auto ']) {+ settingStore.set(UNIFIED_MAX_TOKENS_SETTING, raw);+ expect(unifiedMaxTokensCap()).toBe(UNIFIED_MAX_TOKENS_AUTO);+ }+ });++ it('uses an explicit positive integer verbatim', () => {+ settingStore.set(UNIFIED_MAX_TOKENS_SETTING, '4096');+ expect(unifiedMaxTokensCap()).toBe(4096);+ settingStore.set(UNIFIED_MAX_TOKENS_SETTING, ' 1 ');+ expect(unifiedMaxTokensCap()).toBe(1);+ });++ it('treats garbage as disabled so a bad value can never 400 requests', () => {+ for (const raw of ['banana', '-1', '1.5', 'NaN', 'Infinity', '32k', '{}']) {+ settingStore.set(UNIFIED_MAX_TOKENS_SETTING, raw);+ expect(unifiedMaxTokensCap()).toBeNull();+ }+ });+});++describe('resolveMaxTokens under the cap', () => {+ it('passes everything through untouched when the cap is disabled', () => {+ expect(resolveMaxTokens('groq', 65536)).toBe(65536);+ expect(resolveMaxTokens('groq', undefined)).toBeUndefined();+ expect(resolveMaxTokens('cloudflare', undefined)).toBe(defaultMaxTokensFor('cloudflare'));+ });++ it('lowers a requested value that exceeds the cap', () => {+ settingStore.set(UNIFIED_MAX_TOKENS_SETTING, 'auto');+ expect(resolveMaxTokens('groq', 65536)).toBe(UNIFIED_MAX_TOKENS_AUTO);+ settingStore.set(UNIFIED_MAX_TOKENS_SETTING, '4096');+ expect(resolveMaxTokens('groq', 65536)).toBe(4096);+ });++ it('leaves a requested value at or below the cap alone', () => {+ settingStore.set(UNIFIED_MAX_TOKENS_SETTING, '4096');+ expect(resolveMaxTokens('groq', 1024)).toBe(1024);+ expect(resolveMaxTokens('groq', 4096)).toBe(4096);+ });++ it('clamps the platform default when the client sent nothing', () => {+ const cfDefault = defaultMaxTokensFor('cloudflare')!;+ settingStore.set(UNIFIED_MAX_TOKENS_SETTING, String(cfDefault - 1));+ expect(resolveMaxTokens('cloudflare', undefined)).toBe(cfDefault - 1);+ });++ it('still sends nothing for a platform with no default and no client value', () => {+ settingStore.set(UNIFIED_MAX_TOKENS_SETTING, 'auto');+ expect(resolveMaxTokens('groq', undefined)).toBeUndefined();+ });++ it('never raises a value below the cap up to it', () => {+ settingStore.set(UNIFIED_MAX_TOKENS_SETTING, '100000');+ expect(resolveMaxTokens('cloudflare', undefined)).toBe(defaultMaxTokensFor('cloudflare'));+ expect(resolveMaxTokens('groq', 16)).toBe(16);+ });+});diff --git a/server/src/__tests__/providers/unified-max-tokens-cap.test.ts b/server/src/__tests__/providers/unified-max-tokens-cap.test.tsnew file mode 100644index 00000000..c4417e2e--- /dev/null+++ b/server/src/__tests__/providers/unified-max-tokens-cap.test.ts@@ -0,0 +1,191 @@+import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest';+import { initDb, setSetting } from '../../db/index.js';+import { OpenAICompatProvider } from '../../providers/openai-compat.js';+import { CloudflareProvider } from '../../providers/cloudflare.js';+import { CohereProvider } from '../../providers/cohere.js';+import { GoogleProvider } from '../../providers/google.js';+import { AIHordeProvider } from '../../providers/aihorde.js';+import {+ defaultMaxTokensFor,+ UNIFIED_MAX_TOKENS_SETTING,+ UNIFIED_MAX_TOKENS_AUTO,+} from '../../lib/sampling-params.js';++// The cap is only "unified" if EVERY adapter puts max_tokens on the wire+// through resolveMaxTokens(). These tests drive the real settings row and read+// the real outgoing request body for each adapter, so an adapter that goes back+// to reading options.max_tokens directly fails here.++const MESSAGES = [{ role: 'user' as const, content: 'Hi' }];+const CLIENT_ASKED = 65536; // Open WebUI's default++function openAiJsonResponse(): any {+ return {+ ok: true,+ status: 200,+ json: () => Promise.resolve({+ id: 'chatcmpl-1',+ object: 'chat.completion',+ created: 1,+ model: 'm',+ choices: [{ index: 0, message: { role: 'assistant', content: 'hi' }, finish_reason: 'stop' }],+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+ }),+ headers: new Headers(),+ };+}++function geminiJsonResponse(): any {+ return {+ ok: true,+ status: 200,+ json: () => Promise.resolve({+ candidates: [{ content: { parts: [{ text: 'hi' }] }, finishReason: 'STOP' }],+ usageMetadata: { promptTokenCount: 1, candidatesTokenCount: 1, totalTokenCount: 2 },+ }),+ headers: new Headers(),+ };+}++function hordeJsonResponse(): any {+ return {+ ok: true,+ status: 200,+ json: () => Promise.resolve({+ id: 'horde-1',+ object: 'chat.completion',+ created: 1,+ model: 'm',+ choices: [{ index: 0, message: { role: 'assistant', content: 'hi' }, finish_reason: 'stop' }],+ usage: { kudos: 2 },+ }),+ headers: new Headers(),+ };+}++/** Spy on fetch and hand back the parsed outgoing body. */+function captureBody(response: () => any): { body: () => any } {+ let captured: any = null;+ vi.spyOn(global, 'fetch').mockImplementation(async (_url, init) => {+ captured = JSON.parse((init as any).body);+ return response() as any;+ });+ return { body: () => captured };+}++/** One entry per adapter: fire a chat completion and report the max_tokens it+ * actually put on the wire. */+const ADAPTERS: Array<{+ name: string;+ send: (options?: Record<string, unknown>) => Promise<number | undefined>;+}> = [+ {+ name: 'openai-compat (groq)',+ send: async (options) => {+ const cap = captureBody(openAiJsonResponse);+ const p = new OpenAICompatProvider({ platform: 'groq', name: 'Groq', baseUrl: 'https://api.test.com/v1' });+ await p.chatCompletion('sk-test', MESSAGES, 'llama-3.3-70b', options as any);+ return cap.body().max_tokens;+ },+ },+ {+ name: 'cloudflare',+ send: async (options) => {+ const cap = captureBody(openAiJsonResponse);+ await new CloudflareProvider().chatCompletion('acct:token', MESSAGES, '@cf/openai/gpt-oss-120b', options as any);+ return cap.body().max_tokens;+ },+ },+ {+ name: 'cohere',+ send: async (options) => {+ const cap = captureBody(openAiJsonResponse);+ await new CohereProvider().chatCompletion('test-key', MESSAGES, 'command-a-03-2025', options as any);+ return cap.body().max_tokens;+ },+ },+ {+ name: 'google',+ send: async (options) => {+ const cap = captureBody(geminiJsonResponse);+ await new GoogleProvider().chatCompletion('test-key', MESSAGES, 'gemini-2.5-flash', options as any);+ return cap.body().generationConfig?.maxOutputTokens;+ },+ },+ {+ name: 'aihorde',+ send: async (options) => {+ const cap = captureBody(hordeJsonResponse);+ await new AIHordeProvider().chatCompletion('no-key', MESSAGES, 'm', options as any);+ return cap.body().max_tokens;+ },+ },+];++beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+});++beforeEach(() => {+ setSetting(UNIFIED_MAX_TOKENS_SETTING, 'off');+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('the unified cap reaches every adapter', () => {+ for (const adapter of ADAPTERS) {+ it(`${adapter.name} clamps an excessive client max_tokens`, async () => {+ setSetting(UNIFIED_MAX_TOKENS_SETTING, 'auto');+ expect(await adapter.send({ max_tokens: CLIENT_ASKED })).toBe(UNIFIED_MAX_TOKENS_AUTO);+ });++ it(`${adapter.name} honors an explicit integer cap`, async () => {+ setSetting(UNIFIED_MAX_TOKENS_SETTING, '4096');+ expect(await adapter.send({ max_tokens: CLIENT_ASKED })).toBe(4096);+ });++ it(`${adapter.name} leaves a value below the cap alone`, async () => {+ setSetting(UNIFIED_MAX_TOKENS_SETTING, '4096');+ expect(await adapter.send({ max_tokens: 512 })).toBe(512);+ });++ it(`${adapter.name} forwards the client value verbatim with the cap off`, async () => {+ expect(await adapter.send({ max_tokens: CLIENT_ASKED })).toBe(CLIENT_ASKED);+ });+ }+});++describe('the cap applies to values the client never sent', () => {+ it("clamps cloudflare's platform default (#553) when the cap is lower", async () => {+ const cfDefault = defaultMaxTokensFor('cloudflare')!;+ setSetting(UNIFIED_MAX_TOKENS_SETTING, String(cfDefault - 1));+ const cap = captureBody(openAiJsonResponse);+ await new CloudflareProvider().chatCompletion('acct:token', MESSAGES, '@cf/openai/gpt-oss-120b');+ expect(cap.body().max_tokens).toBe(cfDefault - 1);+ });++ it("clamps aihorde's own default", async () => {+ setSetting(UNIFIED_MAX_TOKENS_SETTING, '64');+ const cap = captureBody(hordeJsonResponse);+ await new AIHordeProvider().chatCompletion('no-key', MESSAGES, 'm');+ expect(cap.body().max_tokens).toBe(64);+ });++ it("never drops aihorde below the proxy's 16-token floor", async () => {+ setSetting(UNIFIED_MAX_TOKENS_SETTING, '4');+ const cap = captureBody(hordeJsonResponse);+ await new AIHordeProvider().chatCompletion('no-key', MESSAGES, 'm', { max_tokens: 1000 });+ expect(cap.body().max_tokens).toBe(16);+ });++ it('still omits max_tokens for a platform with no default', async () => {+ setSetting(UNIFIED_MAX_TOKENS_SETTING, 'auto');+ const cap = captureBody(openAiJsonResponse);+ const p = new OpenAICompatProvider({ platform: 'groq', name: 'Groq', baseUrl: 'https://api.test.com/v1' });+ await p.chatCompletion('sk-test', MESSAGES, 'llama-3.3-70b');+ expect(cap.body().max_tokens).toBeUndefined();+ });+});diff --git a/server/src/__tests__/routes/settings-output-limit.test.ts b/server/src/__tests__/routes/settings-output-limit.test.tsnew file mode 100644index 00000000..28739c56--- /dev/null+++ b/server/src/__tests__/routes/settings-output-limit.test.ts@@ -0,0 +1,101 @@+import { describe, it, expect, beforeAll } from 'vitest';+import type { Express } from 'express';+import { createApp } from '../../app.js';+import { initDb, getSetting, setSetting } from '../../db/index.js';+import { mintDashboardToken } from '../helpers/auth.js';+import { UNIFIED_MAX_TOKENS_SETTING, UNIFIED_MAX_TOKENS_AUTO } from '../../lib/sampling-params.js';++async function request(app: Express, method: string, path: string, body: any, token: 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,+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+ const raw = await res.text();+ server.close();+ let json: any = null;+ try { json = JSON.parse(raw); } catch {}+ return { status: res.status, body: json };+}++// GET/PUT /api/settings/output-limit is the only way to configure the unified+// output-token cap, so its contract is what a dashboard has to code against.+describe('/api/settings/output-limit', () => {+ let app: Express;+ let token: string;++ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ app = createApp();+ token = mintDashboardToken();+ });++ it("reports 'off' before anything is configured", async () => {+ const { status, body } = await request(app, 'GET', '/api/settings/output-limit', undefined, token);+ expect(status).toBe(200);+ expect(body).toEqual({ mode: 'off', effectiveCap: null, autoValue: UNIFIED_MAX_TOKENS_AUTO });+ });++ it("stores 'auto' and reports the auto ceiling", async () => {+ const put = await request(app, 'PUT', '/api/settings/output-limit', { mode: 'auto' }, token);+ expect(put.status).toBe(200);+ expect(put.body).toEqual({ mode: 'auto', effectiveCap: UNIFIED_MAX_TOKENS_AUTO, autoValue: UNIFIED_MAX_TOKENS_AUTO });+ expect(getSetting(UNIFIED_MAX_TOKENS_SETTING)).toBe('auto');++ const get = await request(app, 'GET', '/api/settings/output-limit', undefined, token);+ expect(get.body).toEqual(put.body);+ });++ it('stores an explicit integer and reports it as a number, not a string', async () => {+ const put = await request(app, 'PUT', '/api/settings/output-limit', { mode: 8192 }, token);+ expect(put.status).toBe(200);+ expect(put.body.mode).toBe(8192);+ expect(put.body.effectiveCap).toBe(8192);++ // A dashboard must be able to PUT back exactly what GET handed it.+ const get = await request(app, 'GET', '/api/settings/output-limit', undefined, token);+ expect(get.body).toEqual(put.body);+ const roundTrip = await request(app, 'PUT', '/api/settings/output-limit', { mode: get.body.mode }, token);+ expect(roundTrip.status).toBe(200);+ expect(roundTrip.body).toEqual(get.body);+ });++ it("'off' restores pass-through", async () => {+ await request(app, 'PUT', '/api/settings/output-limit', { mode: 'auto' }, token);+ const put = await request(app, 'PUT', '/api/settings/output-limit', { mode: 'off' }, token);+ expect(put.status).toBe(200);+ expect(put.body.mode).toBe('off');+ expect(put.body.effectiveCap).toBeNull();+ });++ const rejected: Array<[string, any]> = [+ ['an unknown mode string', { mode: 'unlimited' }],+ ['a numeric string', { mode: '8192' }],+ ['zero', { mode: 0 }],+ ['a negative integer', { mode: -1 }],+ ['a fractional value', { mode: 1.5 }],+ ['a missing mode', {}],+ ['a null mode', { mode: null }],+ ];++ for (const [label, payload] of rejected) {+ it(`rejects ${label} with a 400 and leaves the setting untouched`, async () => {+ await request(app, 'PUT', '/api/settings/output-limit', { mode: 4096 }, token);+ const { status, body } = await request(app, 'PUT', '/api/settings/output-limit', payload, token);+ expect(status).toBe(400);+ expect(body.error.type).toBe('invalid_request_error');+ expect(body.error.message).toMatch(/Invalid output limit/);+ expect(getSetting(UNIFIED_MAX_TOKENS_SETTING)).toBe('4096');+ });+ }++ it('reports a stored value it cannot parse as off, matching how it behaves', async () => {+ setSetting(UNIFIED_MAX_TOKENS_SETTING, 'banana');+ const { body } = await request(app, 'GET', '/api/settings/output-limit', undefined, token);+ expect(body.mode).toBe('off');+ expect(body.effectiveCap).toBeNull();+ });+});diff --git a/server/src/lib/sampling-params.ts b/server/src/lib/sampling-params.tsindex 0ded96e5..f436f664 100644--- a/server/src/lib/sampling-params.ts+++ b/server/src/lib/sampling-params.ts@@ -23,6 +23,7 @@import { z } from 'zod';import type { Platform } from '@freellmapi/shared/types.js';+import { getSetting } from '../db/index.js';// OpenAI's request-side reasoning knob. Wire values as of the current OpenAI// API: 'minimal'|'low'|'medium'|'high', plus 'none' (gpt-5.1). Forwarded@@ -214,8 +215,8 @@ export interface PlatformParamPolicy {// experience as a broken stream rather than as a truncation. A// client-supplied value always wins, larger or smaller. Applied by the// adapters through resolveMaxTokens(), so a platform added here only takes- // effect once its adapter routes max_tokens through that helper- // (openai-compat + cloudflare already do).+ // effect once its adapter routes max_tokens through that helper (they all+ // do).defaultMaxTokens?: number;}@@ -315,13 +316,56 @@ export function defaultMaxTokensFor(platform: string): number | undefined {/*** The max_tokens to put on the wire for one request: whatever the client asked- * for, or the platform's floor when the client asked for nothing (#553).- * Never clamps — a client-set value passes through untouched in both- * directions, and the gateway's own guardrails (token budget, routing reserve)- * have already had their say by the time an adapter calls this.+ * for, or the platform's floor when the client asked for nothing (#553), then+ * lowered to the unified output cap when the operator configured one. With the+ * cap off (the default) nothing is clamped — a client-set value passes through+ * untouched in both directions, and the gateway's own guardrails (token budget,+ * routing reserve) have already had their say by the time an adapter calls this.+ *+ * EVERY adapter must send max_tokens through here, or the cap is not unified:+ * openai-compat (and its subclasses), cloudflare, cohere, google and aihorde+ * all do.*/export function resolveMaxTokens(platform: string, requested: number | undefined): number | undefined {- return requested ?? defaultMaxTokensFor(platform);+ const resolved = requested ?? defaultMaxTokensFor(platform);+ if (resolved == null) return resolved;+ const cap = unifiedMaxTokensCap();+ return cap == null ? resolved : Math.min(resolved, cap);+}++// ── Unified output-token cap ─────────────────────────────────────────────────+// Optional operator-level ceiling on max_tokens for EVERY client. Aggressive+// clients (Open WebUI sends max_tokens=65536 by default) 400 against free+// models whose output limit is 32768 (CF qwen3-30b, zhipu glm), and without a+// ceiling the same invalid value rides every fallback candidate — the chain+// cannot rescue the request. The cap only LOWERS an+// excessive value; a client value at or below it is untouched, and clients that+// send nothing still get today's platform floor. 'off' (default) keeps the+// historical pass-through behaviour.+export const UNIFIED_MAX_TOKENS_SETTING = 'unified_max_tokens';+/** The ceiling 'auto' clamps to: the output limit of the largest common free+ * catalog models. */+export const UNIFIED_MAX_TOKENS_AUTO = 32768;++/** The configured unified output cap, or null when disabled ('off'/unset).+ * 'auto' resolves to UNIFIED_MAX_TOKENS_AUTO; an explicit integer is used+ * verbatim; anything else is treated as disabled so a bad value can't 400+ * requests. Reads the settings table on every call — cheap (better-sqlite3+ * sync read) and picks up dashboard changes without a restart, mirroring+ * guardrails.ts. */+export function unifiedMaxTokensCap(): number | null {+ let raw: string | undefined;+ try {+ raw = getSetting(UNIFIED_MAX_TOKENS_SETTING);+ } catch {+ return null; // DB not ready — never throw on the proxy hot path+ }+ if (!raw) return null;+ const value = raw.trim().toLowerCase();+ if (value === '' || value === 'off' || value === '0') return null;+ if (value === 'auto') return UNIFIED_MAX_TOKENS_AUTO;+ const n = Number(value);+ return Number.isInteger(n) && n > 0 ? n : null;}/** True when this platform's policy strips response_format before send — thediff --git a/server/src/providers/aihorde.ts b/server/src/providers/aihorde.tsindex 23120d2c..3dfb5b43 100644--- a/server/src/providers/aihorde.ts+++ b/server/src/providers/aihorde.ts@@ -8,6 +8,7 @@ import type {import { BaseProvider, providerHttpError, type CompletionOptions, type KeyValidationResult } from './base.js';import { recordQuotaObservationsFromResponse, type QuotaObservationContext } from '../services/provider-quota.js';import { providerTimeoutMs } from '../lib/provider-timeout.js';+import { resolveMaxTokens } from '../lib/sampling-params.js';/*** AI Horde — free, community-powered inference served by volunteer workers and@@ -86,8 +87,13 @@ export class AIHordeProvider extends BaseProvider {const body: Record<string, unknown> = {model: modelId,messages,- // Floor at 16 (proxy 422s below it); default when omitted.- max_tokens: Math.max(MIN_MAX_TOKENS, options?.max_tokens ?? DEFAULT_MAX_TOKENS),+ // Floor at 16 (proxy 422s below it); default when omitted. Our own+ // default goes through resolveMaxTokens too, so the unified output cap+ // applies to it as well — it can only ever lower what we send.+ max_tokens: Math.max(+ MIN_MAX_TOKENS,+ resolveMaxTokens(this.platform, options?.max_tokens ?? DEFAULT_MAX_TOKENS) ?? DEFAULT_MAX_TOKENS,+ ),};if (options?.temperature != null) body.temperature = options.temperature;if (options?.top_p != null) body.top_p = options.top_p;diff --git a/server/src/providers/cohere.ts b/server/src/providers/cohere.tsindex b134a232..f0f8a282 100644--- a/server/src/providers/cohere.ts+++ b/server/src/providers/cohere.ts@@ -5,7 +5,7 @@ import type {ChatToolDefinition,} from '@freellmapi/shared/types.js';import { BaseProvider, providerHttpError, type CompletionOptions, type KeyValidationResult } from './base.js';-import { extendedBodyParams } from '../lib/sampling-params.js';+import { extendedBodyParams, resolveMaxTokens } from '../lib/sampling-params.js';import { flattenMessageContent } from '../lib/content.js';import { recordQuotaObservationsFromResponse, type QuotaObservationContext } from '../services/provider-quota.js';import { stripSchemaKeys } from '../lib/tool-args.js';@@ -44,7 +44,7 @@ export class CohereProvider extends BaseProvider {model: modelId,messages: flattenMessageContent(messages),temperature: options?.temperature,- max_tokens: options?.max_tokens,+ max_tokens: resolveMaxTokens(this.platform, options?.max_tokens),top_p: options?.top_p,stop: options?.stop,tools: sanitizeCohereTools(options?.tools),@@ -92,7 +92,7 @@ export class CohereProvider extends BaseProvider {model: modelId,messages: flattenMessageContent(messages),temperature: options?.temperature,- max_tokens: options?.max_tokens,+ max_tokens: resolveMaxTokens(this.platform, options?.max_tokens),top_p: options?.top_p,stop: options?.stop,tools: sanitizeCohereTools(options?.tools),diff --git a/server/src/providers/google.ts b/server/src/providers/google.tsindex 3c10e28b..167b2e10 100644--- a/server/src/providers/google.ts+++ b/server/src/providers/google.ts@@ -13,6 +13,7 @@ import { proxyFetch } from '../lib/proxy.js';import { recordQuotaObservationsFromResponse, type QuotaObservationContext } from '../services/provider-quota.js';import { providerTimeoutMs, streamStallTimeoutMs } from '../lib/provider-timeout.js';import { sanitizeForGemini } from '../lib/gemini-wire.js';+import { resolveMaxTokens } from '../lib/sampling-params.js';export { sanitizeForGemini } from '../lib/gemini-wire.js';@@ -525,7 +526,7 @@ export class GoogleProvider extends BaseProvider {contents: request.contents,generationConfig: {temperature: options?.temperature,- maxOutputTokens: options?.max_tokens,+ maxOutputTokens: resolveMaxTokens(this.platform, options?.max_tokens),topP: options?.top_p,stopSequences: toGeminiStopSequences(options?.stop),...toGeminiExtendedConfig(options),@@ -608,7 +609,7 @@ export class GoogleProvider extends BaseProvider {contents: request.contents,generationConfig: {temperature: options?.temperature,- maxOutputTokens: options?.max_tokens,+ maxOutputTokens: resolveMaxTokens(this.platform, options?.max_tokens),topP: options?.top_p,stopSequences: toGeminiStopSequences(options?.stop),...toGeminiExtendedConfig(options),diff --git a/server/src/routes/settings.ts b/server/src/routes/settings.tsindex 54e08937..4a766fb4 100644--- a/server/src/routes/settings.ts+++ b/server/src/routes/settings.ts@@ -21,6 +21,11 @@ import {} from '../services/compression/config.js';import { z } from 'zod';import { getAppVersion } from '../lib/app-version.js';+import {+ UNIFIED_MAX_TOKENS_SETTING,+ UNIFIED_MAX_TOKENS_AUTO,+ unifiedMaxTokensCap,+} from '../lib/sampling-params.js';export const settingsRouter = Router();@@ -190,6 +195,49 @@ settingsRouter.delete('/url-tokens/:id', (req: Request, res: Response) => {res.status(204).end();});+// The unified output-token cap as the dashboard sees it. `mode` is exactly+// what PUT accepts back — 'off', 'auto', or the integer itself, never a+// stringified number — so a read/modify/write round trip can't 400 on its own+// output. A stored value that unifiedMaxTokensCap() doesn't understand is+// reported as 'off', which is how it actually behaves (effectiveCap null).+function outputLimitState(): { mode: 'off' | 'auto' | number; effectiveCap: number | null; autoValue: number } {+ const raw = (getSetting(UNIFIED_MAX_TOKENS_SETTING) ?? '').trim().toLowerCase();+ const effectiveCap = unifiedMaxTokensCap();+ const mode = raw === 'auto' ? 'auto' as const : (effectiveCap ?? 'off' as const);+ return { mode, effectiveCap, autoValue: UNIFIED_MAX_TOKENS_AUTO };+}++// Get the unified output-token cap ('off' = disabled, 'auto' = 32768, or an+// explicit integer). See lib/sampling-params.ts unifiedMaxTokensCap().+settingsRouter.get('/output-limit', (_req: Request, res: Response) => {+ res.json(outputLimitState());+});++const outputLimitPutSchema = z.object({+ mode: z.union([+ z.literal('off'),+ z.literal('auto'),+ z.number().int().min(1),+ ]),+});++// Update the unified output-token cap. 'off' restores pass-through behaviour;+// 'auto' clamps every request's max_tokens to UNIFIED_MAX_TOKENS_AUTO; an+// integer clamps to that value. Takes effect on the next request.+settingsRouter.put('/output-limit', (req: Request, res: Response) => {+ const parsed = outputLimitPutSchema.safeParse(req.body);+ if (!parsed.success) {+ const detail = parsed.error.errors+ .map(e => (e.path.length ? `${e.path.join('.')}: ${e.message}` : e.message))+ .slice(0, 5)+ .join(', ');+ res.status(400).json({ error: { message: `Invalid output limit: ${detail}`, type: 'invalid_request_error' } });+ return;+ }+ setSetting(UNIFIED_MAX_TOKENS_SETTING, String(parsed.data.mode));+ res.json(outputLimitState());+});+// Get the request guardrails (per-request token budget + failover circuit// breaker). Both default to 0 = disabled; see lib/guardrails.ts.settingsRouter.get('/guardrails', (_req: Request, res: Response) => {