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

fix: clamp reasoning params per provider instead of 400-ing (#638)

Tashfeen8270d7d69d1a
diff --git a/server/src/__tests__/lib/sampling-params.test.ts b/server/src/__tests__/lib/sampling-params.test.ts
index 3ee4e956..0c1b23c6 100644
--- a/server/src/__tests__/lib/sampling-params.test.ts
+++ b/server/src/__tests__/lib/sampling-params.test.ts
@@ -4,7 +4,9 @@ import {
extendedBodyParams,
supportedParametersFor,
supportedParametersForPlatforms,
+ normalizeReasoningEffort,
EXTENDED_SAMPLING_KEYS,
+ REASONING_EFFORTS,
} from '../../lib/sampling-params.js';
describe('pickSamplingParams', () => {
@@ -151,6 +153,51 @@ describe('reasoning_effort (request-side reasoning control)', () => {
});
});
+describe('reasoning_effort normalization (#619 — off-scale values must not 400)', () => {
+ it('passes supported values through untouched, case/whitespace tolerant', () => {
+ for (const effort of REASONING_EFFORTS) {
+ expect(normalizeReasoningEffort(effort)).toBe(effort);
+ }
+ expect(normalizeReasoningEffort(' High ')).toBe('high');
+ });
+
+ it("clamps 'max' and its spellings to the top of the scale", () => {
+ for (const alias of ['max', 'maximum', 'MAX', 'highest', 'ultra', 'xhigh', 'x-high']) {
+ expect(normalizeReasoningEffort(alias)).toBe('high');
+ }
+ });
+
+ it('clamps the other off-scale spellings to their nearest supported value', () => {
+ expect(normalizeReasoningEffort('mid')).toBe('medium');
+ expect(normalizeReasoningEffort('balanced')).toBe('medium');
+ expect(normalizeReasoningEffort('min')).toBe('minimal');
+ expect(normalizeReasoningEffort('lowest')).toBe('minimal');
+ expect(normalizeReasoningEffort('off')).toBe('none');
+ expect(normalizeReasoningEffort('disabled')).toBe('none');
+ });
+
+ it("drops model-managed modes and anything unrecognizable instead of failing", () => {
+ for (const value of ['auto', 'adaptive', 'default', 'wat', '', 7, null, undefined, {}]) {
+ expect(normalizeReasoningEffort(value)).toBeUndefined();
+ }
+ });
+
+ it('pickSamplingParams clamps rather than forwarding an off-scale value', () => {
+ expect(pickSamplingParams({ reasoning_effort: 'max' })).toEqual({ reasoning_effort: 'high' });
+ expect(pickSamplingParams({ reasoning: { effort: 'max' } })).toEqual({ reasoning_effort: 'high' });
+ expect(pickSamplingParams({ reasoning_effort: 'adaptive' })).toEqual({});
+ expect(pickSamplingParams({ reasoning_effort: 'nonsense', seed: 3 })).toEqual({ seed: 3 });
+ });
+
+ it('per-platform clamping: github takes only low/medium/high', () => {
+ expect(extendedBodyParams('github', { reasoning_effort: 'none' }).reasoning_effort).toBe('low');
+ expect(extendedBodyParams('github', { reasoning_effort: 'minimal' }).reasoning_effort).toBe('low');
+ expect(extendedBodyParams('github', { reasoning_effort: 'medium' }).reasoning_effort).toBe('medium');
+ // Platforms without a restriction still get the value verbatim.
+ expect(extendedBodyParams('groq', { reasoning_effort: 'none' }).reasoning_effort).toBe('none');
+ });
+});
+
describe('live-sweep policy findings (2026-07-11 demo-box validation)', () => {
it('kilo: response_format dropped (gateway 400s on it), seed still forwarded', () => {
const body = extendedBodyParams('kilo', { seed: 7, response_format: { type: 'json_object' } });
diff --git a/server/src/__tests__/routes/reasoning-control.test.ts b/server/src/__tests__/routes/reasoning-control.test.ts
index da0f0d89..c8204562 100644
--- a/server/src/__tests__/routes/reasoning-control.test.ts
+++ b/server/src/__tests__/routes/reasoning-control.test.ts
@@ -159,13 +159,24 @@ describe('request-side reasoning control (end-to-end)', () => {
expect(JSON.stringify(captured.body)).not.toContain('reasoning');
});
- it('rejects an unknown effort value with a 400 instead of forwarding garbage', async () => {
- const { status, body } = await request(app, '/v1/chat/completions', {
- model: 'auto', reasoning_effort: 'maximum',
+ it("clamps an off-scale effort to the nearest supported one instead of 400-ing (#619)", async () => {
+ const captured = mockJson(textCompletion('ok'));
+ const { status } = await request(app, '/v1/chat/completions', {
+ model: 'auto', reasoning_effort: 'max',
+ messages: [{ role: 'user', content: 'hi' }],
+ }, openaiHeaders());
+ expect(status).toBe(200);
+ expect(captured.body.reasoning_effort).toBe('high');
+ });
+
+ it('drops an unrecognizable effort and completes on the provider default', async () => {
+ const captured = mockJson(textCompletion('ok'));
+ const { status } = await request(app, '/v1/chat/completions', {
+ model: 'auto', reasoning_effort: 'turbo-plus',
messages: [{ role: 'user', content: 'hi' }],
}, openaiHeaders());
- expect(status).toBe(400);
- expect(body.error.type).toBe('invalid_request_error');
+ expect(status).toBe(200);
+ expect(captured.body).not.toHaveProperty('reasoning_effort');
});
it('non-streaming: inline <think> is extracted into reasoning_content in the response', async () => {
@@ -237,6 +248,26 @@ describe('Anthropic surface: thinking knob + thinking blocks', () => {
expect(effortFromAnthropicThinking({ type: 'enabled', budget_tokens: 32000 })).toBe('high');
});
+ it("accepts thinking types outside the enabled/disabled enum (#632)", () => {
+ // 'adaptive' means the model manages its own budget — no knob forwarded.
+ expect(effortFromAnthropicThinking({ type: 'adaptive' })).toBeUndefined();
+ expect(effortFromAnthropicThinking({ type: 'auto' })).toBeUndefined();
+ // An explicit budget still wins, whatever the mode is called.
+ expect(effortFromAnthropicThinking({ type: 'adaptive', budget_tokens: 32000 })).toBe('high');
+ expect(effortFromAnthropicThinking({ type: 'off' })).toBe('none');
+ });
+
+ it("a thinking:{type:'adaptive'} request completes instead of 400-ing (#632)", async () => {
+ const captured = mockJson(textCompletion('done'));
+ const { status } = await request(app, '/v1/messages', {
+ model: 'claude-sonnet-4-5', max_tokens: 64,
+ thinking: { type: 'adaptive' },
+ messages: [{ role: 'user', content: 'hi' }],
+ }, anthropicHeaders());
+ expect(status).toBe(200);
+ expect(captured.body).not.toHaveProperty('reasoning_effort');
+ });
+
it('forwards the mapped effort to the provider', async () => {
const captured = mockJson(textCompletion('done'));
const { status } = await request(app, '/v1/messages', {
diff --git a/server/src/lib/sampling-params.ts b/server/src/lib/sampling-params.ts
index 89951093..4358b306 100644
--- a/server/src/lib/sampling-params.ts
+++ b/server/src/lib/sampling-params.ts
@@ -31,6 +31,57 @@ import type { Platform } from '@freellmapi/shared/types.js';
export const REASONING_EFFORTS = ['none', 'minimal', 'low', 'medium', 'high'] as const;
export type ReasoningEffort = typeof REASONING_EFFORTS[number];
+// Effort spellings clients actually send that aren't on OpenAI's scale, mapped
+// to the nearest value we do support (#619: a strict enum turned a client's
+// `reasoning_effort: 'max'` into a 400 from our own edge — a knob nobody asked
+// to be fatal). Values that mean "let the model decide" ('auto', 'adaptive',
+// 'default') are deliberately absent: they resolve to undefined below, i.e.
+// nothing is forwarded and the provider default stands — same rule
+// effortFromGeminiThinking applies to a -1 thinking budget.
+const EFFORT_ALIASES: Readonly<Record<string, ReasoningEffort>> = {
+ max: 'high', maximum: 'high', highest: 'high', ultra: 'high', xhigh: 'high', 'x-high': 'high',
+ mid: 'medium', moderate: 'medium', balanced: 'medium', normal: 'medium', standard: 'medium',
+ min: 'minimal', minimum: 'minimal', lowest: 'minimal', xlow: 'minimal', 'x-low': 'minimal',
+ off: 'none', disabled: 'none', disable: 'none',
+};
+
+/**
+ * Coerce a client-supplied effort value onto our scale: supported values pass
+ * through, known aliases clamp to the nearest supported one, and anything
+ * else (unknown word, wrong type, "auto") yields undefined — the knob is
+ * dropped and the provider's own default applies. Never throws, so a bad
+ * effort can't fail a request. Exported for tests.
+ */
+export function normalizeReasoningEffort(value: unknown): ReasoningEffort | undefined {
+ if (typeof value !== 'string') return undefined;
+ const key = value.trim().toLowerCase();
+ if ((REASONING_EFFORTS as readonly string[]).includes(key)) return key as ReasoningEffort;
+ return EFFORT_ALIASES[key];
+}
+
+/**
+ * Clamp an effort to the nearest value a platform actually accepts, walking
+ * the ordered scale outward from the requested one (ties go to the stronger
+ * value, so 'medium' on a low/high platform becomes 'high'). Returns
+ * undefined only when the platform accepts nothing.
+ */
+function clampEffortTo(effort: ReasoningEffort, supported: readonly ReasoningEffort[]): ReasoningEffort | undefined {
+ if (supported.includes(effort)) return effort;
+ const want = REASONING_EFFORTS.indexOf(effort);
+ let best: ReasoningEffort | undefined;
+ let bestDistance = Infinity;
+ for (const candidate of supported) {
+ const distance = Math.abs(REASONING_EFFORTS.indexOf(candidate) - want);
+ if (distance < bestDistance
+ || (distance === bestDistance && best !== undefined
+ && REASONING_EFFORTS.indexOf(candidate) > REASONING_EFFORTS.indexOf(best))) {
+ best = candidate;
+ bestDistance = distance;
+ }
+ }
+ return best;
+}
+
// Every field is `.nullable()` because real clients serialize their whole
// request struct and send explicit nulls for unset knobs (#200); null is
// treated as absent and never forwarded.
@@ -52,13 +103,16 @@ export const samplingParamSchemaFields = {
schema: z.record(z.string(), z.unknown()).optional(),
}).passthrough().optional(),
}).passthrough().nullable().optional(),
- reasoning_effort: z.enum(REASONING_EFFORTS).nullable().optional(),
+ // Accepted as free-form and normalized by pickSamplingParams rather than
+ // validated against the enum: clients invent effort values ('max', 'xhigh')
+ // and rejecting them made an advisory knob fatal (#619).
+ reasoning_effort: z.unknown().optional(),
// Object-form alias some clients send (OpenRouter-style chat clients, and
// the Responses API's native shape): `reasoning: { effort }`. Resolved into
// reasoning_effort by pickSamplingParams; the wrapper object itself is never
// forwarded. Extra keys (summary, max_tokens…) are tolerated and ignored.
reasoning: z.object({
- effort: z.enum(REASONING_EFFORTS).nullable().optional(),
+ effort: z.unknown().optional(),
}).passthrough().nullable().optional(),
// OpenAI's newer alias for max_tokens; surfaces resolve it into max_tokens
// themselves (it is not a forwarded param of its own).
@@ -115,15 +169,19 @@ export function pickSamplingParams(body: ParsedSamplingBody): ExtendedSamplingOp
const value = body[key];
if (value === undefined || value === null) continue;
if (key === 'response_format' && (value as { type?: string }).type === 'text') continue;
+ if (key === 'reasoning_effort') {
+ const effort = normalizeReasoningEffort(value);
+ if (effort === undefined) continue;
+ out[key] = effort;
+ continue;
+ }
out[key] = value;
}
// Object-form fallback: `reasoning: { effort }` fills reasoning_effort only
// when the flat field wasn't sent (the explicit flat form wins on conflict).
if (out.reasoning_effort === undefined) {
- const effort = body.reasoning?.effort;
- if (typeof effort === 'string' && (REASONING_EFFORTS as readonly string[]).includes(effort)) {
- out.reasoning_effort = effort;
- }
+ const effort = normalizeReasoningEffort(body.reasoning?.effort);
+ if (effort !== undefined) out.reasoning_effort = effort;
}
return out as ExtendedSamplingOptions;
}
@@ -145,6 +203,11 @@ export interface PlatformParamPolicy {
// are 'text' and 'json_schema'."). Upgrade json_object to a permissive
// json_schema on the wire instead of dropping structured output entirely.
jsonObjectToSchema?: boolean;
+ // The effort values this platform's API accepts, when it accepts fewer than
+ // the full scale. A request outside the set is clamped to the nearest
+ // supported value instead of being forwarded into a 400 (#619). Omitted =
+ // forward whatever the client asked for.
+ reasoningEfforts?: readonly ReasoningEffort[];
}
// Keyed by Platform (not string) so a typo'd platform id fails tsc instead of
@@ -162,8 +225,10 @@ export const PLATFORM_PARAM_POLICIES: Partial<Record<Platform, PlatformParamPoli
// rejects requests that include them.
groq: { drop: ['logprobs', 'top_logprobs', 'logit_bias'] },
// GitHub Models sits on Azure OpenAI, which 400s "Unrecognized request
- // argument" for knobs outside the OpenAI set.
- github: { drop: ['top_k', 'min_p', 'repetition_penalty'] },
+ // argument" for knobs outside the OpenAI set. Its reasoning_effort enum is
+ // the older low/medium/high one, so 'none'/'minimal' are clamped rather
+ // than sent.
+ github: { drop: ['top_k', 'min_p', 'repetition_penalty'], reasoningEfforts: ['low', 'medium', 'high'] },
// Gemini's generationConfig has no equivalents for these; the adapter
// translates the rest natively (topK, seed, penalties, responseSchema, and
// reasoning_effort → thinkingConfig — see toGeminiExtendedConfig).
@@ -214,6 +279,10 @@ export function extendedBodyParams(platform: string, options: ExtendedSamplingOp
&& (value as { type?: string }).type === 'json_object') {
value = ANY_OBJECT_SCHEMA;
}
+ if (key === 'reasoning_effort' && policy?.reasoningEfforts) {
+ value = clampEffortTo(value as ReasoningEffort, policy.reasoningEfforts);
+ if (value === undefined) continue;
+ }
out[policy?.rename?.[key] ?? key] = value;
}
return out;
diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.ts
index a81abc18..23589e02 100644
--- a/server/src/routes/anthropic.ts
+++ b/server/src/routes/anthropic.ts
@@ -93,8 +93,11 @@ const messagesSchema = z.object({
// reasoning_effort (see effortFromAnthropicThinking) so providers with
// request-side reasoning control receive it; platforms without support have
// it stripped by the policy in lib/sampling-params.ts.
+ // `type` is a free string, not the enabled/disabled enum: Anthropic keeps
+ // adding modes (Claude Code sends 'adaptive') and validating the enum here
+ // turned a knob we only use as a hint into a hard 400 (#632).
thinking: z.object({
- type: z.enum(['enabled', 'disabled']).optional(),
+ type: z.string().optional(),
budget_tokens: z.number().int().optional(),
}).passthrough().nullable().optional(),
}).passthrough();
@@ -108,8 +111,13 @@ export function effortFromAnthropicThinking(
thinking: { type?: string; budget_tokens?: number } | null | undefined,
): ReasoningEffort | undefined {
if (!thinking) return undefined;
- if (thinking.type === 'disabled') return 'none';
+ const type = thinking.type?.trim().toLowerCase();
+ if (type === 'disabled' || type === 'off' || type === 'none') return 'none';
const budget = thinking.budget_tokens;
+ // Model-managed modes ('adaptive', 'auto') without an explicit budget mean
+ // "you decide how much" — forward no knob at all and let the provider
+ // default stand, same as a -1 Gemini thinking budget.
+ if (budget == null && (type === 'adaptive' || type === 'auto')) return undefined;
if (budget == null) return 'medium';
if (budget < 4096) return 'low';
if (budget < 16384) return 'medium';