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(routing): try models that reject tool calls last for tool requests (#1230) (#1267)

Tashfeen47c3a451e882
diff --git a/server/src/__tests__/lib/fallback-loop-issue-1230.test.ts b/server/src/__tests__/lib/fallback-loop-issue-1230.test.ts
new file mode 100644
index 00000000..d85261be
--- /dev/null
+++ b/server/src/__tests__/lib/fallback-loop-issue-1230.test.ts
@@ -0,0 +1,202 @@
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
+
+// #1230: custom endpoints default to supports_tools = 1, so a relay model that
+// answers every tool-carrying request with a 400 stayed a first-class candidate
+// for tool requests. The only memory of the rejection was the 90s transient
+// cooldown, so auto mode re-walked the same dead chain on every tool request
+// until the operator disabled the models by hand. The loop now remembers those
+// rejections per model+endpoint so the router can try such models last for
+// tool requests, and only for tool requests.
+
+vi.mock('../../services/health.js', () => ({
+ checkKeyHealth: vi.fn(),
+ markKeyHealthyFromRequest: vi.fn(),
+}));
+
+import { initDb, getDb } from '../../db/index.js';
+import { encrypt } from '../../lib/crypto.js';
+import {
+ newFallbackState,
+ recordRetryableFailure,
+ recordUpstreamSuccess,
+ resetModelFailureWindows,
+ type FallbackState,
+} from '../../lib/fallback-loop.js';
+import {
+ isToolBenched,
+ resetToolCapability,
+ TOOL_BENCH_MS,
+ TOOL_REJECTION_LIMIT,
+ TOOL_REJECTION_WINDOW_MS,
+} from '../../lib/tool-capability.js';
+import { clearCooldownsForKey, resetKeyLocalityCache } from '../../services/ratelimit.js';
+import type { RouteResult } from '../../services/router.js';
+
+const PLATFORM = 'groq';
+let keyA = 0;
+let keyB = 0;
+let models: { id: number; model_id: string }[] = [];
+
+function insertKey(label: string): number {
+ const { encrypted, iv, authTag } = encrypt(`test-${label}`);
+ const info = getDb().prepare(`
+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)
+ VALUES (?, ?, ?, ?, ?, 'healthy', 1)
+ `).run(PLATFORM, label, encrypted, iv, authTag);
+ return Number(info.lastInsertRowid);
+}
+
+function routeFor(model: { id: number; model_id: string }, keyId: number, extra: Partial<RouteResult> = {}): RouteResult {
+ return {
+ provider: {} as any,
+ modelId: model.model_id,
+ modelDbId: model.id,
+ apiKey: 'k',
+ keyId,
+ platform: PLATFORM,
+ displayName: model.model_id,
+ rpdLimit: null,
+ tpdLimit: null,
+ endpointScope: '',
+ ...extra,
+ } as RouteResult;
+}
+
+// The shape every OpenAI-compatible adapter throws for an upstream 400.
+const BAD_REQUEST = () => Object.assign(
+ new Error('Custom API error 400: tools is not supported by this model'),
+ { status: 400 },
+);
+const CONTEXT_400 = () => Object.assign(
+ new Error("Custom API error 400: This model's maximum context length is 8192 tokens"),
+ { status: 400 },
+);
+
+function toolState(): FallbackState {
+ const state = newFallbackState();
+ state.wantsTools = true;
+ return state;
+}
+
+const benched = (m: { model_id: string }, scope = '') => isToolBenched(PLATFORM, m.model_id, scope);
+
+beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ const db = getDb();
+ db.prepare('DELETE FROM api_keys').run();
+ keyA = insertKey('key-a');
+ keyB = insertKey('key-b');
+ resetKeyLocalityCache();
+ models = db.prepare(
+ 'SELECT id, model_id FROM models WHERE platform = ? AND enabled = 1 ORDER BY id'
+ ).all(PLATFORM) as { id: number; model_id: string }[];
+ expect(models.length).toBeGreaterThanOrEqual(3);
+});
+
+beforeEach(() => {
+ clearCooldownsForKey(keyA);
+ clearCooldownsForKey(keyB);
+ resetModelFailureWindows();
+ resetToolCapability();
+});
+
+describe('tool-request rejections are remembered per model (#1230)', () => {
+ it('defers a model after the limit of DISTINCT tool requests it rejected', () => {
+ for (let i = 0; i < TOOL_REJECTION_LIMIT - 1; i++) {
+ recordRetryableFailure(routeFor(models[0], keyA), BAD_REQUEST(), toolState());
+ }
+ expect(benched(models[0])).toBe(false);
+ recordRetryableFailure(routeFor(models[0], keyA), BAD_REQUEST(), toolState());
+ expect(benched(models[0])).toBe(true);
+ // Only the model that rejected is affected.
+ expect(benched(models[1])).toBe(false);
+ });
+
+ it('counts one request once, however many keys of the model were tried', () => {
+ const state = toolState();
+ for (let i = 0; i < TOOL_REJECTION_LIMIT + 2; i++) {
+ recordRetryableFailure(routeFor(models[0], i % 2 ? keyA : keyB), BAD_REQUEST(), state);
+ }
+ expect(benched(models[0])).toBe(false);
+ });
+
+ it('ignores requests that carry no tools', () => {
+ for (let i = 0; i < TOOL_REJECTION_LIMIT + 2; i++) {
+ recordRetryableFailure(routeFor(models[0], keyA), BAD_REQUEST(), newFallbackState());
+ }
+ expect(benched(models[0])).toBe(false);
+ });
+
+ it('ignores 400s that are really another class (context too large)', () => {
+ for (let i = 0; i < TOOL_REJECTION_LIMIT + 2; i++) {
+ recordRetryableFailure(routeFor(models[0], keyA), CONTEXT_400(), toolState());
+ }
+ expect(benched(models[0])).toBe(false);
+ });
+
+ it('forgets rejections that fall outside the window', () => {
+ const t0 = 1_800_000_000_000;
+ for (let i = 0; i < TOOL_REJECTION_LIMIT - 1; i++) {
+ recordRetryableFailure(routeFor(models[0], keyA), BAD_REQUEST(), toolState(), t0);
+ }
+ recordRetryableFailure(routeFor(models[0], keyA), BAD_REQUEST(), toolState(), t0 + TOOL_REJECTION_WINDOW_MS + 1);
+ expect(isToolBenched(PLATFORM, models[0].model_id, '', t0 + TOOL_REJECTION_WINDOW_MS + 2)).toBe(false);
+ });
+
+ it('keeps two relays serving the same model id apart', () => {
+ const relayA = { platform: 'custom', endpointScope: 'https://relay-a.example/v1' };
+ for (let i = 0; i < TOOL_REJECTION_LIMIT; i++) {
+ recordRetryableFailure(routeFor(models[0], keyA, relayA), BAD_REQUEST(), toolState());
+ }
+ expect(isToolBenched('custom', models[0].model_id, 'https://relay-a.example/v1')).toBe(true);
+ expect(isToolBenched('custom', models[0].model_id, 'https://relay-b.example/v1')).toBe(false);
+ });
+
+ it('expires on its own', () => {
+ const t0 = 1_800_000_000_000;
+ for (let i = 0; i < TOOL_REJECTION_LIMIT; i++) {
+ recordRetryableFailure(routeFor(models[0], keyA), BAD_REQUEST(), toolState(), t0);
+ }
+ expect(isToolBenched(PLATFORM, models[0].model_id, '', t0 + TOOL_BENCH_MS - 1)).toBe(true);
+ expect(isToolBenched(PLATFORM, models[0].model_id, '', t0 + TOOL_BENCH_MS + 1)).toBe(false);
+ });
+});
+
+describe('a served tool request settles who was at fault (#1230)', () => {
+ it('defers the models that rejected the same request straight away', () => {
+ const state = toolState();
+ recordRetryableFailure(routeFor(models[0], keyA), BAD_REQUEST(), state);
+ recordRetryableFailure(routeFor(models[1], keyA), BAD_REQUEST(), state);
+ expect(benched(models[0])).toBe(false);
+ recordUpstreamSuccess(routeFor(models[2], keyA), 100, state);
+ expect(benched(models[0])).toBe(true);
+ expect(benched(models[1])).toBe(true);
+ expect(benched(models[2])).toBe(false);
+ });
+
+ it('clears a model that serves a tool request after all', () => {
+ for (let i = 0; i < TOOL_REJECTION_LIMIT; i++) {
+ recordRetryableFailure(routeFor(models[0], keyA), BAD_REQUEST(), toolState());
+ }
+ expect(benched(models[0])).toBe(true);
+ recordUpstreamSuccess(routeFor(models[0], keyA), 100, toolState());
+ expect(benched(models[0])).toBe(false);
+ });
+
+ it('a malformed tool request that every model rejects defers nothing on its own', () => {
+ // One broken client payload: every model 400s, nothing succeeds.
+ const state = toolState();
+ for (const m of models.slice(0, 3)) recordRetryableFailure(routeFor(m, keyA), BAD_REQUEST(), state);
+ expect(models.slice(0, 3).some(m => benched(m))).toBe(false);
+ });
+
+ it('a success without tools teaches nothing about tool support', () => {
+ for (let i = 0; i < TOOL_REJECTION_LIMIT; i++) {
+ recordRetryableFailure(routeFor(models[0], keyA), BAD_REQUEST(), toolState());
+ }
+ recordUpstreamSuccess(routeFor(models[0], keyA), 100, newFallbackState());
+ recordUpstreamSuccess(routeFor(models[0], keyA), 100);
+ expect(benched(models[0])).toBe(true);
+ });
+});
diff --git a/server/src/__tests__/routes/tool-rejection-e2e-1230.test.ts b/server/src/__tests__/routes/tool-rejection-e2e-1230.test.ts
new file mode 100644
index 00000000..4f509d61
--- /dev/null
+++ b/server/src/__tests__/routes/tool-rejection-e2e-1230.test.ts
@@ -0,0 +1,132 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import http from 'node:http';
+import type { AddressInfo } from 'node:net';
+import type { Express } from 'express';
+import { createApp } from '../../app.js';
+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';
+import { setRoutingStrategy, setExploreEnabled } from '../../services/router.js';
+import { resetToolCapability } from '../../lib/tool-capability.js';
+import { clearCooldownsForKey } from '../../services/ratelimit.js';
+import { mintDashboardToken } from '../helpers/auth.js';
+import { addToActiveChain } from '../helpers/chain.js';
+
+// #1230 end to end, against two REAL local relays. `bad` answers every request
+// that carries `tools` with a 400 (but serves plain chat); `good` serves
+// everything. Both are custom endpoints, so both default to supports_tools = 1
+// and `bad` sits first in the chain. Before the fix every tool request paid
+// for a rejected hop on `bad` first, forever.
+
+type Relay = { url: string; hits: { tools: number; plain: number }; close: () => Promise<void> };
+
+function startRelay(rejectTools: boolean): Promise<Relay> {
+ const hits = { tools: 0, plain: 0 };
+ const server = http.createServer((req, res) => {
+ let raw = '';
+ req.on('data', c => { raw += c; });
+ req.on('end', () => {
+ const body = raw ? JSON.parse(raw) : {};
+ const hasTools = Array.isArray(body.tools) && body.tools.length > 0;
+ if (hasTools) hits.tools++; else hits.plain++;
+ if (hasTools && rejectTools) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: { message: 'tools is not supported by this model', type: 'invalid_request_error' } }));
+ return;
+ }
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ id: 'chatcmpl-test', object: 'chat.completion', created: 1, model: body.model,
+ choices: [{ index: 0, finish_reason: 'stop', message: { role: 'assistant', content: 'OK' } }],
+ usage: { prompt_tokens: 5, completion_tokens: 1, total_tokens: 6 },
+ }));
+ });
+ });
+ return new Promise(resolve => server.listen(0, '127.0.0.1', () => {
+ const { port } = server.address() as AddressInfo;
+ resolve({ url: `http://127.0.0.1:${port}/v1`, hits, close: () => new Promise<void>(r => server.close(() => r())) });
+ }));
+}
+
+const TOOLS = [{ type: 'function', function: { name: 'get_time', description: 'now', parameters: { type: 'object', properties: {} } } }];
+
+describe('a relay that rejects tool calls stops costing every tool request a hop (#1230)', () => {
+ let app: Express;
+ let bad: Relay;
+ let good: Relay;
+ let dashToken = '';
+
+ async function call(path: string, body: unknown, token: string) {
+ const server = app.listen(0, '127.0.0.1');
+ if (!server.listening) await new Promise<void>(resolve => server.once('listening', () => resolve()));
+ const { port } = server.address() as AddressInfo;
+ const res = await fetch(`http://127.0.0.1:${port}${path}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
+ body: JSON.stringify(body),
+ });
+ const data = await res.json().catch(() => null) as any;
+ server.close();
+ return { status: res.status, body: data, routedVia: res.headers.get('x-routed-via') ?? '' };
+ }
+
+ // Every call is a NEW conversation with all cooldowns cleared, so neither the
+ // sticky-session pin nor the short transient bench on `bad` can explain where
+ // a request lands: only the chain order and the tool deferral can.
+ let turn = 0;
+ const chat = (withTools: boolean) => {
+ for (const k of getDb().prepare('SELECT id FROM api_keys').all() as { id: number }[]) clearCooldownsForKey(k.id);
+ return call('/v1/chat/completions', {
+ model: 'auto',
+ messages: [{ role: 'user', content: `question ${++turn}: what time is it?` }],
+ ...(withTools ? { tools: TOOLS } : {}),
+ }, getUnifiedApiKey());
+ };
+
+ beforeEach(async () => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ resetToolCapability();
+ app = createApp();
+ dashToken = mintDashboardToken();
+ bad = await startRelay(true);
+ good = await startRelay(false);
+ // Only the two relays are routable: no other platform has a key.
+ expect((await call('/api/keys/custom', { baseUrl: bad.url, model: 'bad-model', apiKey: 'k1', label: 'Bad relay' }, dashToken)).status).toBe(201);
+ expect((await call('/api/keys/custom', { baseUrl: good.url, model: 'good-model', apiKey: 'k2', label: 'Good relay' }, dashToken)).status).toBe(201);
+ setRoutingStrategy('priority');
+ setExploreEnabled(false);
+ const id = (m: string) => (getDb().prepare("SELECT id FROM models WHERE platform = 'custom' AND model_id = ?").get(m) as { id: number }).id;
+ getDb().prepare('UPDATE fallback_config SET priority = priority + 1000').run();
+ getDb().prepare('UPDATE profile_models SET priority = priority + 1000').run();
+ for (const [m, p] of [['bad-model', 1], ['good-model', 2]] as const) {
+ getDb().prepare('UPDATE fallback_config SET priority = ? WHERE model_db_id = ?').run(p, id(m));
+ addToActiveChain(id(m), p);
+ }
+ });
+
+ afterEach(async () => {
+ await bad.close();
+ await good.close();
+ resetToolCapability();
+ });
+
+ it('learns from one served tool request and skips the rejected hop afterwards', async () => {
+ // Request 1: bad is first, rejects with 400, good serves it.
+ const first = await chat(true);
+ expect(first.status).toBe(200);
+ expect(first.body.choices[0].message.content).toBe('OK');
+ expect(bad.hits.tools).toBe(1);
+ expect(good.hits.tools).toBe(1);
+
+ // Requests 2 and 3: good proved the request was fine, so bad is tried last
+ // and is never reached.
+ for (let i = 0; i < 2; i++) expect((await chat(true)).status).toBe(200);
+ expect(bad.hits.tools).toBe(1);
+ expect(good.hits.tools).toBe(3);
+
+ // Plain chat is untouched: bad is still first in line and serves it.
+ const plain = await chat(false);
+ expect(plain.status).toBe(200);
+ expect(bad.hits.plain).toBe(1);
+ expect(good.hits.plain).toBe(0);
+ });
+});
diff --git a/server/src/__tests__/services/router-bandit.test.ts b/server/src/__tests__/services/router-bandit.test.ts
index 560d13a0..2bd2f95e 100644
--- a/server/src/__tests__/services/router-bandit.test.ts
+++ b/server/src/__tests__/services/router-bandit.test.ts
@@ -10,6 +10,7 @@ import { resetModelWeightOverrides } from '../../services/model-weight-overrides
import * as ratelimit from '../../services/ratelimit.js';
import { getDb, initDb } from '../../db/index.js';
import { addToActiveChain } from '../helpers/chain.js';
+import { benchForTools, resetToolCapability, toolCapabilityKey } from '../../lib/tool-capability.js';
vi.mock('../../services/ratelimit.js', async () => {
const actual = await vi.importActual('../../services/ratelimit.js');
@@ -491,3 +492,61 @@ describe('bandit router', () => {
expect(shown(after.intelligence)).toBeGreaterThanOrEqual(shown(before.intelligence) + 2);
});
});
+
+// #1230: a model that keeps answering tool requests with a 400 is tried LAST
+// for tool requests. Soft preference only: it never empties the pool and it
+// never affects requests without tools.
+describe('tool-rejecting models are deferred for tool requests (#1230)', () => {
+ beforeEach(() => {
+ process.env.DEV_MODE = 'true';
+ process.env.NODE_ENV = 'test';
+ initDb(':memory:');
+ getDb().exec('DELETE FROM fallback_config; DELETE FROM api_keys; DELETE FROM models; DELETE FROM requests;');
+ vi.clearAllMocks();
+ (ratelimit.canMakeRequest as any).mockReturnValue(true);
+ (ratelimit.canUseTokens as any).mockReturnValue(true);
+ (ratelimit.isOnCooldown as any).mockReturnValue(false);
+ resetToolCapability();
+ setRoutingStrategy('priority');
+ setExploreEnabled(false);
+ });
+ afterEach(() => { resetToolCapability(); });
+
+ const seed = () => {
+ const first = addModel({ platform: 'google', modelId: 'first', name: 'First', intelligenceRank: 1, sizeLabel: 'Large', budget: '~1M', priority: 1 });
+ addModel({ platform: 'groq', modelId: 'second', name: 'Second', intelligenceRank: 2, sizeLabel: 'Large', budget: '~1M', priority: 2 });
+ return first;
+ };
+ const route = (requireTools: boolean, preferred?: number) => routeRequest(100, undefined, preferred, false, requireTools).modelId;
+
+ it('keeps the operator order until a model is benched', () => {
+ seed();
+ expect(route(true)).toBe('first');
+ });
+
+ it('tries the benched model last on a tool request', () => {
+ seed();
+ benchForTools(toolCapabilityKey('google', 'first', ''));
+ expect(route(true)).toBe('second');
+ });
+
+ it('leaves requests without tools alone', () => {
+ seed();
+ benchForTools(toolCapabilityKey('google', 'first', ''));
+ expect(route(false)).toBe('first');
+ });
+
+ it('still routes to a benched model when it is the only one left', () => {
+ seed();
+ benchForTools(toolCapabilityKey('google', 'first', ''));
+ benchForTools(toolCapabilityKey('groq', 'second', ''));
+ // Everything is deferred, so the original order is what remains.
+ expect(route(true)).toBe('first');
+ });
+
+ it('an explicit pin keeps its place', () => {
+ const first = seed();
+ benchForTools(toolCapabilityKey('google', 'first', ''));
+ expect(route(true, first)).toBe('first');
+ });
+});
diff --git a/server/src/lib/fallback-loop.ts b/server/src/lib/fallback-loop.ts
index 41e083ab..ec303d31 100644
--- a/server/src/lib/fallback-loop.ts
+++ b/server/src/lib/fallback-loop.ts
@@ -51,6 +51,7 @@ import {
isStreamTruncatedError,
} from './error-classify.js';
import { sanitizeProviderErrorMessage, summarizeAttemptError } from './error-redaction.js';
+import { benchForTools, clearToolRejections, noteToolRejection, toolCapabilityKey } from './tool-capability.js';
import { parseProviderReportedSize } from './provider-size-parser.js';
import { checkKeyHealth, markKeyHealthyFromRequest } from '../services/health.js';
import { noteModelRetirementSignal } from '../services/model-retirement.js';
@@ -212,6 +213,13 @@ export interface FallbackState {
// reading is the same request, not a smaller one.
observedTotalTokens?: number;
observedInputTokens?: number;
+ // The request carries `tools` (#1230). Set by the surface right after
+ // newFallbackState(); lets the failure/success paths learn which models
+ // reject tool calls in practice. Unset means "not a tool request".
+ wantsTools?: boolean;
+ // Models (tool-capability keys) that answered provider_bad_request to THIS
+ // tool request. Counted once per request however many keys were tried.
+ toolRejects?: Set<string>;
// Per-request tally of DISTINCT models that answered model_not_found, keyed
// by platform (#1218): a stale catalog misses on every sibling model in a
// row, and the per-model skip can't see the pattern. From
@@ -489,6 +497,20 @@ export function recordRetryableFailure(route: RouteResult, err: any, state: Fall
// cooldown ladder is already handling whatever that is.
truncationStreaks.delete(`${route.platform}:${route.modelId}:${route.keyId}`);
}
+ // A 400 "bad request" answer to a request that carries `tools` is how a
+ // model that does not really support tool calling shows up (#1230). The 90s
+ // transient cooldown above forgets it, so remember it per model+endpoint;
+ // after a few distinct requests the router tries that model last for tool
+ // requests (lib/tool-capability.ts). Only the final classification counts:
+ // context-too-large, model-not-found and degraded 400s are other problems.
+ if (state.wantsTools === true && classifyAttemptError(err) === 'provider_bad_request') {
+ const tk = toolCapabilityKey(route.platform, route.modelId, route.endpointScope);
+ const seen = (state.toolRejects ??= new Set<string>());
+ if (!seen.has(tk)) {
+ seen.add(tk);
+ noteToolRejection(tk, now);
+ }
+ }
// A suspended ACCOUNT fails every model behind the key identically. The
// per-route cooldown above benches only the model that happened to be
// tried, so the next request picks the platform's next model and pays the
@@ -572,7 +594,16 @@ export function recordAuthFailure(route: RouteResult, state: FallbackState): voi
* clear the model's 429 penalty. `rateLimitTokens` is whatever the surface metered
* (the provider's usage.total_tokens for non-stream, an estimate for stream).
*/
-export function recordUpstreamSuccess(route: RouteResult, rateLimitTokens: number): void {
+export function recordUpstreamSuccess(route: RouteResult, rateLimitTokens: number, state?: FallbackState): void {
+ // A tool-carrying request that was served proves two things (#1230): this
+ // model does handle tools, and the request itself was well-formed, so the
+ // models that answered it with a 400 earlier in this chain are the ones at
+ // fault. Defer those for tool requests without waiting for more evidence.
+ if (state?.wantsTools === true) {
+ const winner = toolCapabilityKey(route.platform, route.modelId, route.endpointScope);
+ clearToolRejections(winner);
+ for (const tk of state.toolRejects ?? []) if (tk !== winner) benchForTools(tk);
+ }
recordRequest(route.platform, route.modelId, route.keyId);
recordTokens(route.platform, route.modelId, route.keyId, rateLimitTokens);
recordSuccess(route.modelDbId);
diff --git a/server/src/lib/inbound-chat.ts b/server/src/lib/inbound-chat.ts
index 3995169c..d7692fb3 100644
--- a/server/src/lib/inbound-chat.ts
+++ b/server/src/lib/inbound-chat.ts
@@ -201,6 +201,8 @@ export async function runInboundChat(
const state = newFallbackState();
const attemptLog: AttemptRecord[] = [];
const wantsTools = (input.tools?.length ?? 0) > 0;
+ // Lets the failover loop learn which models reject tool calls (#1230).
+ state.wantsTools = wantsTools;
const imageRequest = hasImages(input.messages);
// Capped reserve (#470); threaded to the router separately because it is an
// exact count and must not be inflated by the context-window safety margin
@@ -335,7 +337,7 @@ export async function runInboundChat(
promptTokens,
completionTokens,
};
- recordUpstreamSuccess(route, result.usage?.total_tokens ?? promptTokens + completionTokens);
+ recordUpstreamSuccess(route, result.usage?.total_tokens ?? promptTokens + completionTokens, state);
if (pin.pinnedLabel == null) setStickyModel(input.messages, route.modelDbId, input.sessionId);
res.setHeader('X-Routed-Via', routedViaValue(route.platform, route.modelId));
setFallbackHeaders(res, attempt, attemptLog);
@@ -531,7 +533,7 @@ export async function runInboundChat(
completionTokens: outputTokens,
};
wire.finishStream(res, normalized);
- recordUpstreamSuccess(route, estimatedInputTokens + outputTokens);
+ recordUpstreamSuccess(route, estimatedInputTokens + outputTokens, state);
if (pin.pinnedLabel == null) setStickyModel(input.messages, route.modelDbId, input.sessionId);
logRequest(
route.platform,
diff --git a/server/src/lib/tool-capability.ts b/server/src/lib/tool-capability.ts
new file mode 100644
index 00000000..8851c8a8
--- /dev/null
+++ b/server/src/lib/tool-capability.ts
@@ -0,0 +1,73 @@
+// Observed tool-calling rejections (#1230).
+//
+// `models.supports_tools` is a declaration, and for custom endpoints it defaults
+// to 1 (migration 20260706_000002): a relay model that actually rejects every
+// request carrying `tools` with a 400 stays a first-class candidate for tool
+// requests, because the only memory of the rejection is the 90s transient
+// cooldown. Auto mode then walks the same dead chain on every tool request
+// until the operator disables the models by hand.
+//
+// This module remembers those rejections in memory and lets the router DEFER
+// such a model for tool-carrying requests only. It is a soft preference, never
+// a filter: a deferred model is still tried once everything else is exhausted,
+// plain chat requests are untouched, and nothing is written to the DB (the
+// `supports_tools` toggle stays the operator's). A client that sends a broken
+// tool schema gets a 400 from every model alike, which defers them all equally
+// and so changes nothing about their order.
+//
+// Keyed per model and per endpoint (`modelStatsKey`), not per key: tool support
+// is a property of the model behind one relay, and sibling keys share it.
+import { modelStatsKey } from './endpoint-scope.js';
+
+// Distinct REQUESTS (not hops) that must see the rejection before the model is
+// deferred: one odd request must not condemn a model.
+export const TOOL_REJECTION_LIMIT = 3;
+export const TOOL_REJECTION_WINDOW_MS = 60 * 60 * 1000;
+// Long enough to stop the per-request re-walk, short enough that a relay which
+// fixes its tool support comes back the same day without a restart.
+export const TOOL_BENCH_MS = 6 * 60 * 60 * 1000;
+
+const rejections = new Map<string, number[]>(); // statsKey -> rejection timestamps
+const benchedUntil = new Map<string, number>(); // statsKey -> expiry (ms)
+
+export function toolCapabilityKey(platform: string, modelId: string, endpointScope: string | null | undefined): string {
+ return modelStatsKey(platform, modelId, endpointScope);
+}
+
+/** Defer this model for tool requests right now (evidence is already conclusive). */
+export function benchForTools(key: string, now: number = Date.now()): void {
+ const already = (benchedUntil.get(key) ?? 0) > now;
+ benchedUntil.set(key, now + TOOL_BENCH_MS);
+ rejections.delete(key);
+ if (!already) {
+ console.warn(`[ToolCapability] ${key} keeps rejecting tool-calling requests; trying it last for tool requests for ${Math.round(TOOL_BENCH_MS / 3_600_000)}h`);
+ }
+}
+
+/** One tool-carrying request was rejected as a bad request by this model. */
+export function noteToolRejection(key: string, now: number = Date.now()): void {
+ const recent = (rejections.get(key) ?? []).filter(t => now - t < TOOL_REJECTION_WINDOW_MS);
+ recent.push(now);
+ if (recent.length >= TOOL_REJECTION_LIMIT) benchForTools(key, now);
+ else rejections.set(key, recent);
+}
+
+/** The model just served a tool-carrying request: it supports tools after all. */
+export function clearToolRejections(key: string): void {
+ rejections.delete(key);
+ benchedUntil.delete(key);
+}
+
+export function isToolBenched(platform: string, modelId: string, endpointScope: string | null | undefined, now: number = Date.now()): boolean {
+ const key = toolCapabilityKey(platform, modelId, endpointScope);
+ const until = benchedUntil.get(key);
+ if (until === undefined) return false;
+ if (until > now) return true;
+ benchedUntil.delete(key);
+ return false;
+}
+
+export function resetToolCapability(): void {
+ rejections.clear();
+ benchedUntil.clear();
+}
diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.ts
index a714e53c..63cd5029 100644
--- a/server/src/routes/anthropic.ts
+++ b/server/src/routes/anthropic.ts
@@ -21,7 +21,7 @@ import { convertDocumentBlock, documentRejectionMessage } from '../lib/anthropic
import { isClientAbortError, newClientAbortError, newHedgeAbortError, isUpstreamClassificationOutput } from '../lib/error-classify.js';
import { logRequest } from '../lib/request-log.js';
import { extractApiToken, timingSafeStringEqual, getStickyModel, setStickyModel } from './proxy.js';
-import { runFallbackLoop, newFallbackState, fallbackRoutingTokens, recordUpstreamSuccess, type ExhaustionBody, setFallbackHeaders, setExhaustionHeaders, type AttemptRecord } from '../lib/fallback-loop.js';
+import { runFallbackLoop, newFallbackState, fallbackRoutingTokens, recordUpstreamSuccess, type ExhaustionBody, setFallbackHeaders, setExhaustionHeaders, type AttemptRecord, type FallbackState } from '../lib/fallback-loop.js';
import { routedViaValue } from '../lib/header-value.js';
import { applyTokenBudget, tokenBudgetMessage } from '../lib/guardrails.js';
import { resolveAnthropicModel, claudeFamilyDiscoveryEntries } from '../services/anthropic-map.js';
@@ -620,6 +620,8 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {
// when every provider rejected the request, not always a 429), and applies the
// inline tool-call dialect rescue that the OpenAI/Responses surfaces carry.
const state = newFallbackState();
+ // Lets the failover loop learn which models reject tool calls (#1230).
+ state.wantsTools = wantsTools;
const attemptLog: AttemptRecord[] = [];
// Client-disconnect fan-out: the flag stops the loop before the NEXT
// attempt; the AbortController (threaded to the provider as
@@ -662,7 +664,7 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {
try {
await streamCompletion(res, route, messages, dispatchOptions, {
start, attempt, attemptLog, clientGone: () => clientGone, requestedModel, estimatedInputTokens, tools, pinnedModelId,
- sessionId, pinned: resolved.pinned, stickyScope, strategyKey, disarmHedge: dispatchCtx.disarmHedge,
+ sessionId, pinned: resolved.pinned, stickyScope, strategyKey, disarmHedge: dispatchCtx.disarmHedge, state,
});
return 'done';
} catch (err: any) {
@@ -739,7 +741,7 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {
const promptTokens = result.usage?.prompt_tokens ?? estimatedInputTokens;
const completionTokens = result.usage?.completion_tokens ?? Math.ceil((respText.length + respToolCalls.reduce((n, c) => n + c.function.arguments.length, 0)) / 4);
- recordUpstreamSuccess(route, result.usage?.total_tokens ?? promptTokens + completionTokens);
+ recordUpstreamSuccess(route, result.usage?.total_tokens ?? promptTokens + completionTokens, state);
// Remember this model for the rest of the auto-routed session. A pin used
// to make this a no-op (the pin fixed the model); a group pin still has a
// provider choice to remember, recorded under the group's own scope.
@@ -802,6 +804,8 @@ interface StreamCtx {
strategyKey?: string;
/** Cancel this attempt's time-budget hedge once the stream commits. */
disarmHedge: () => void;
+ /** The request's failover state, so a served tool request can be learned from (#1230). */
+ state: FallbackState;
}
// Consume the provider's OpenAI-style stream and re-emit it as the Anthropic
@@ -1055,7 +1059,7 @@ async function streamCompletion(
writeSse(res, 'message_stop', { type: 'message_stop' });
res.end();
- recordUpstreamSuccess(route, ctx.estimatedInputTokens + outputTokens);
+ recordUpstreamSuccess(route, ctx.estimatedInputTokens + outputTokens, ctx.state);
if (!ctx.pinned || ctx.stickyScope) setStickyModel(messages, route.modelDbId, ctx.sessionId, ctx.stickyScope ?? ctx.strategyKey);
logRequest(route.platform, route.modelId, route.keyId, 'success', ctx.estimatedInputTokens, outputTokens, Date.now() - ctx.start, null, null, ctx.pinnedModelId, null, 'http');
} catch (err: any) {
diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.ts
index f91b28d0..5c95bc55 100644
--- a/server/src/routes/proxy.ts
+++ b/server/src/routes/proxy.ts
@@ -2076,6 +2076,8 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
// context-handoff injection, group/unified-chain routing, and the OpenAI
// stream turn-integrity framing.
const state = newFallbackState();
+ // Lets the failover loop learn which models reject tool calls (#1230).
+ state.wantsTools = wantsTools;
const attemptLog: AttemptRecord[] = [];
// Fallback-v2 hedging: the loop aborts this controller (via abortInFlight)
// when the wall-clock retry budget expires mid-attempt, canceling the
@@ -2555,7 +2557,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
const inputTokens = upstreamUsage?.prompt_tokens ?? estimatedPromptTokens;
const outputTokens = upstreamUsage?.completion_tokens ?? totalOutputTokens;
const totalTokens = upstreamUsage?.total_tokens ?? (inputTokens + outputTokens);
- recordUpstreamSuccess(route, totalTokens);
+ recordUpstreamSuccess(route, totalTokens, state);
// Cache the freshly-generated SSE sequence so an identical later
// stream request is replayed without spending another free-tier
@@ -2762,7 +2764,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
const completionTokens = result.usage?.completion_tokens
?? Math.ceil((contentToString(respMsg?.content ?? '').length + completionReasoningText(result).length + respToolArgChars) / 4);
const totalTokens = result.usage?.total_tokens ?? (promptTokens + completionTokens);
- recordUpstreamSuccess(route, totalTokens);
+ recordUpstreamSuccess(route, totalTokens, state);
// #797: remember this turn's thinking trace so the next request from
// the same session can restore it (clients strip it on replay).
// normalizeChoices keeps reasoning_content on the message even when it
diff --git a/server/src/routes/responses.ts b/server/src/routes/responses.ts
index 7dfd961f..74b64f12 100644
--- a/server/src/routes/responses.ts
+++ b/server/src/routes/responses.ts
@@ -866,6 +866,8 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
const responseId = newId('resp');
const state = newFallbackState();
+ // Lets the failover loop learn which models reject tool calls (#1230).
+ state.wantsTools = wantsTools;
const attemptLog: AttemptRecord[] = [];
// Client-disconnect fan-out: the flag stops the loop before the NEXT
// attempt; the AbortController (threaded to the provider as
@@ -1423,7 +1425,7 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
sse('response.completed', { response: finalResponse });
res.end();
- recordUpstreamSuccess(route, estimatedInputTokens + totalOutputTokens);
+ recordUpstreamSuccess(route, estimatedInputTokens + totalOutputTokens, state);
setStickyModel(messages, route.modelDbId, sessionIdHeader, stickyStrategyKey);
traceRouteEvent('Responses', {
event: 'ok',
@@ -1548,7 +1550,7 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
// Usage fallback: a missing provider `usage` block used to record 0
// tokens against the rate-limit ledger; promptTokens/completionTokens
// above already carry the chars/4 estimate.
- recordUpstreamSuccess(route, result.usage?.total_tokens ?? (promptTokens + completionTokens));
+ recordUpstreamSuccess(route, result.usage?.total_tokens ?? (promptTokens + completionTokens), state);
setStickyModel(messages, route.modelDbId, sessionIdHeader, stickyStrategyKey);
res.setHeader('X-Routed-Via', routedViaValue(route.platform, route.modelId));
diff --git a/server/src/services/router.ts b/server/src/services/router.ts
index 7dba046a..2cc15d71 100644
--- a/server/src/services/router.ts
+++ b/server/src/services/router.ts
@@ -37,6 +37,7 @@ import { getActiveProfileId } from './profile-models.js';
import { customEndpointKeyIds } from './custom-endpoint.js';
import { isDegraded } from './degradation.js';
import { modelStatsKey, endpointScopeForBaseUrl } from '../lib/endpoint-scope.js';
+import { isToolBenched } from '../lib/tool-capability.js';
import { parseModelScope, scopeAllows } from '../lib/model-scope.js';
import { getKeyQuotaHeadroom, inferQuotaPoolKey } from './provider-quota.js';
import type { BaseProvider } from '../providers/base.js';
@@ -2006,6 +2007,9 @@ export function routeRequest(estimatedTokens = 1000, skipKeys?: Set<string>, pre
if (skipPlatforms?.has(e.platform)) return false;
if (requireVision && !e.supports_vision) return false;
if (requireTools && !e.supports_tools) return false;
+ // Never spend the exploration slot on a model that keeps rejecting tool
+ // requests (#1230); it stays reachable at the back of the main walk.
+ if (requireTools && isToolBenched(e.platform, e.model_id, e.endpoint_scope)) return false;
if (requireStructured && platformDropsResponseFormat(e.platform)) return false;
if (!fitsContextWindow(e.platform, e.context_window, estimatedTokens, exactOutputReserve)) return false;
if (e.tpm_limit != null && estimatedTokens > e.tpm_limit) return false;
@@ -2086,12 +2090,22 @@ export function routeRequest(estimatedTokens = 1000, skipKeys?: Set<string>, pre
// sweep margin-fitting models first; ones that only fit the advertised window
// stay eligible behind them. Worst case is one classified context_too_large
// hop instead of no route at all.
+ //
+ // Same soft treatment for models that keep answering tool requests with a 400
+ // (#1230, lib/tool-capability.ts): on a tool request they go to the very back
+ // instead of being excluded, so the worst case is the old order, never an
+ // empty pool. An explicit pin keeps its place: the client named that model.
const servingChain: ChainRow[] = [];
const marginDeferred: ChainRow[] = [];
+ const toolDeferred: ChainRow[] = [];
for (const e of routableChain) {
+ if (requireTools && e.model_db_id !== preferredModelDbId && isToolBenched(e.platform, e.model_id, e.endpoint_scope)) {
+ toolDeferred.push(e);
+ continue;
+ }
(fitsContextWindow(e.platform, e.context_window, estimatedTokens, exactOutputReserve) ? servingChain : marginDeferred).push(e);
}
- servingChain.push(...marginDeferred);
+ servingChain.push(...marginDeferred, ...toolDeferred);
for (const entry of servingChain) {
const label = `${entry.platform}/${entry.model_id}`;