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

refactor(gateway): unify the four provider fallback loops, fix drift (#482 base) (#483)

Tashfeen940986c88b64
diff --git a/server/src/__tests__/routes/anthropic-fallback-convergence.test.ts b/server/src/__tests__/routes/anthropic-fallback-convergence.test.ts
new file mode 100644
index 00000000..397923c8
--- /dev/null
+++ b/server/src/__tests__/routes/anthropic-fallback-convergence.test.ts
@@ -0,0 +1,200 @@
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
+
+// Characterization tests for the drifts the shared fallback loop
+// (lib/fallback-loop.ts) converged on the Anthropic /v1/messages surface:
+// - drift #3: exhaustion now uses the shared body — a 400 invalid_request_error
+// when every routed provider rejected the request as invalid, not always a
+// 429 rate_limit_error, and the message matches the other surfaces.
+// - drift #4: the inline tool-call dialect rescue (a model that serialized its
+// tool call as TEXT) now runs here too, on both the non-stream and stream
+// paths, translated to Anthropic tool_use blocks.
+// - drift #1: streaming commit is held until the first meaningful content, so a
+// dialect turn that opens the stream but turns out unparseable fails over.
+
+const { mockRouteRequest } = vi.hoisted(() => ({ mockRouteRequest: vi.fn() }));
+vi.mock('../../services/router.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../services/router.js')>();
+ return { ...actual, routeRequest: mockRouteRequest };
+});
+
+import type { Express } from 'express';
+import { createApp } from '../../app.js';
+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';
+
+function fakeRoute(provider: any) {
+ return {
+ provider, modelId: 'fake-model', modelDbId: 9999, apiKey: 'k', keyId: 1,
+ platform: 'fake', displayName: 'Fake Model', rpdLimit: null, tpdLimit: null,
+ };
+}
+
+function jsonProvider(response: any) {
+ return { async chatCompletion() { return response; }, async *streamChatCompletion(): AsyncGenerator<any> { /* unused */ } };
+}
+
+function streamProvider(gen: () => AsyncGenerator<any>) {
+ return { async chatCompletion() { throw new Error('nope'); }, streamChatCompletion: gen };
+}
+
+async function post(app: Express, body: any, key: string) {
+ const server = app.listen(0);
+ const addr = server.address() as any;
+ const res = await fetch(`http://127.0.0.1:${addr.port}/v1/messages`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'x-api-key': key, 'anthropic-version': '2023-06-01' },
+ body: JSON.stringify(body),
+ });
+ const text = await res.text();
+ server.close();
+ let json: any = null;
+ try { json = JSON.parse(text); } catch { /* SSE */ }
+ return { status: res.status, text, body: json };
+}
+
+function sseEvents(text: string): Array<{ event: string; data: any }> {
+ const events: Array<{ event: string; data: any }> = [];
+ for (const block of text.split('\n\n')) {
+ let event: string | null = null;
+ let data: string | null = null;
+ for (const line of block.split('\n')) {
+ if (line.startsWith('event: ')) event = line.slice(7).trim();
+ else if (line.startsWith('data: ')) data = line.slice(6);
+ }
+ if (event && data) { try { events.push({ event, data: JSON.parse(data) }); } catch { /* ignore */ } }
+ }
+ return events;
+}
+
+const chunk = (delta: any, finish: string | null = null) => ({
+ id: 'c1', object: 'chat.completion.chunk', created: 1, model: 'm', choices: [{ index: 0, delta, finish_reason: finish }],
+});
+
+const WEATHER_TOOL = {
+ name: 'get_weather', description: 'Get current weather',
+ input_schema: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] },
+};
+
+describe('/v1/messages shared-loop convergence', () => {
+ let app: Express;
+ let key: string;
+
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ app = createApp();
+ key = getUnifiedApiKey();
+ });
+
+ beforeEach(() => {
+ mockRouteRequest.mockReset();
+ getDb().prepare('DELETE FROM rate_limit_cooldowns').run();
+ });
+
+ it('exhaustion returns a 400 invalid_request_error when every provider rejected the request (drift #3)', async () => {
+ mockRouteRequest.mockImplementation((_estimated: number, skipKeys?: Set<string>) => {
+ if (skipKeys?.size) throw Object.assign(new Error('All models exhausted'), { status: 429 });
+ return fakeRoute({
+ async chatCompletion() {
+ throw Object.assign(new Error('Google API error 400: Invalid JSON payload received. Unknown name "x-google-enum-descriptions"'), { status: 400 });
+ },
+ async *streamChatCompletion(): AsyncGenerator<any> { /* unused */ },
+ });
+ });
+
+ const { status, body } = await post(app, { model: 'claude-sonnet-4-5', max_tokens: 64, messages: [{ role: 'user', content: 'hi' }] }, key);
+ expect(status).toBe(400); // was always 429 before the convergence
+ expect(body.type).toBe('error');
+ expect(body.error.type).toBe('invalid_request_error');
+ expect(body.error.message).toContain('rejected the request as invalid');
+ });
+
+ it('exhaustion returns a 429 rate_limit_error (Anthropic-shaped) when every provider is rate-limited', async () => {
+ mockRouteRequest.mockImplementation((_estimated: number, skipKeys?: Set<string>) => {
+ if (skipKeys?.size) throw Object.assign(new Error('All models exhausted'), { status: 429 });
+ return fakeRoute({
+ async chatCompletion() { throw Object.assign(new Error('Groq API error 429: rate limit'), { status: 429 }); },
+ async *streamChatCompletion(): AsyncGenerator<any> { /* unused */ },
+ });
+ });
+
+ const { status, body } = await post(app, { model: 'claude-sonnet-4-5', max_tokens: 64, messages: [{ role: 'user', content: 'hi' }] }, key);
+ expect(status).toBe(429);
+ expect(body.type).toBe('error');
+ expect(body.error.type).toBe('rate_limit_error');
+ });
+
+ it('non-stream: rescues an inline tool-call dialect into an Anthropic tool_use block (drift #4)', async () => {
+ mockRouteRequest.mockReturnValue(fakeRoute(jsonProvider({
+ id: 'c', object: 'chat.completion', created: 0, model: 'fake-model',
+ choices: [{ index: 0, message: { role: 'assistant', content: '<function=get_weather{"city": "Paris"}</function>' }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 5, completion_tokens: 9, total_tokens: 14 },
+ })));
+
+ const { status, body } = await post(app, {
+ model: 'claude-sonnet-4-5', max_tokens: 64,
+ messages: [{ role: 'user', content: 'weather in Paris?' }],
+ tools: [WEATHER_TOOL],
+ }, key);
+
+ expect(status).toBe(200);
+ expect(body.stop_reason).toBe('tool_use');
+ const toolUse = body.content.find((b: any) => b.type === 'tool_use');
+ expect(toolUse).toMatchObject({ type: 'tool_use', name: 'get_weather', input: { city: 'Paris' } });
+ // The raw dialect text is not leaked as a text block.
+ expect(body.content.some((b: any) => b.type === 'text' && b.text.includes('<function='))).toBe(false);
+ });
+
+ it('stream: rescues a streamed inline dialect into a tool_use block (drift #4 + #1 hold window)', async () => {
+ mockRouteRequest.mockReturnValue(fakeRoute(streamProvider(async function* () {
+ yield chunk({ role: 'assistant' });
+ yield chunk({ content: '<function=get_weather{"city":' });
+ yield chunk({ content: ' "Berlin"}</function>' });
+ yield chunk({}, 'stop');
+ })));
+
+ const { status, text } = await post(app, {
+ model: 'claude-sonnet-4-5', max_tokens: 64, stream: true,
+ messages: [{ role: 'user', content: 'weather?' }],
+ tools: [WEATHER_TOOL],
+ }, key);
+
+ expect(status).toBe(200);
+ const events = sseEvents(text);
+ const toolStart = events.find(e => e.event === 'content_block_start' && e.data.content_block?.type === 'tool_use');
+ expect(toolStart!.data.content_block).toMatchObject({ type: 'tool_use', name: 'get_weather' });
+ const jsonDelta = events.filter(e => e.event === 'content_block_delta' && e.data.delta?.type === 'input_json_delta').map(e => e.data.delta.partial_json).join('');
+ expect(JSON.parse(jsonDelta)).toEqual({ city: 'Berlin' });
+ const msgDelta = events.find(e => e.event === 'message_delta');
+ expect(msgDelta!.data.delta.stop_reason).toBe('tool_use');
+ // The raw dialect never reached the client as a text_delta.
+ expect(text).not.toContain('<function=');
+ });
+
+ it('stream: an unparseable dialect that opens the stream fails over invisibly (drift #1)', async () => {
+ mockRouteRequest
+ .mockReturnValueOnce(fakeRoute(streamProvider(async function* () {
+ yield chunk({ role: 'assistant' });
+ // Detected-but-unparseable dialect (degraded id token) — must not commit.
+ yield chunk({ content: '<|tool_call_begin|> chatcmpl-tool-bde5 <|tool_call_argument_begin|> {"city": "X"}' });
+ yield chunk({}, 'stop');
+ })))
+ .mockReturnValueOnce(fakeRoute(streamProvider(async function* () {
+ yield chunk({ role: 'assistant', content: 'Recovered by the next model.' });
+ yield chunk({}, 'stop');
+ })));
+
+ const { status, text } = await post(app, {
+ model: 'claude-sonnet-4-5', max_tokens: 64, stream: true,
+ messages: [{ role: 'user', content: 'hi' }],
+ tools: [WEATHER_TOOL],
+ }, key);
+
+ expect(status).toBe(200);
+ const events = sseEvents(text);
+ // Exactly one message_start — the first (unparseable) attempt never committed.
+ expect(events.filter(e => e.event === 'message_start')).toHaveLength(1);
+ const deltas = events.filter(e => e.event === 'content_block_delta' && e.data.delta?.type === 'text_delta').map(e => e.data.delta.text).join('');
+ expect(deltas).toBe('Recovered by the next model.');
+ expect(text).not.toContain('<|tool_call_begin|>');
+ });
+});
diff --git a/server/src/__tests__/routes/responses-fallback-convergence.test.ts b/server/src/__tests__/routes/responses-fallback-convergence.test.ts
new file mode 100644
index 00000000..83d75c96
--- /dev/null
+++ b/server/src/__tests__/routes/responses-fallback-convergence.test.ts
@@ -0,0 +1,141 @@
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
+
+// Characterization tests for the drifts the shared fallback loop
+// (lib/fallback-loop.ts) converged on the /v1/responses surface:
+// - drift #2: a provider Retry-After is now honored, and a 403 model-not-on-tier
+// is day-benched (MODEL_FORBIDDEN_COOLDOWN_MS), instead of the old flat 90s
+// transient cooldown that fell through here before.
+// - drift #1: the SSE skeleton commits on the first MEANINGFUL content, not the
+// first raw chunk — so a role-only chunk followed by an error fails over
+// invisibly on the same connection instead of dead-ending as response.failed.
+
+// Mock only routeRequest so we can script the provider + exhaustion precisely;
+// the rest of the router (recordRateLimitHit / hasOtherUsableKey) and the whole
+// ratelimit module (setCooldown persistence) stay real.
+const { mockRouteRequest } = vi.hoisted(() => ({ mockRouteRequest: vi.fn() }));
+vi.mock('../../services/router.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../services/router.js')>();
+ return { ...actual, routeRequest: mockRouteRequest };
+});
+
+import type { Express } from 'express';
+import { createApp } from '../../app.js';
+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+function fakeRoute(provider: any) {
+ return {
+ provider, modelId: 'fake-model', modelDbId: 9999, apiKey: 'k', keyId: 1,
+ platform: 'fake', displayName: 'Fake Model', rpdLimit: null, tpdLimit: null,
+ };
+}
+
+function throwingProvider(err: any) {
+ return {
+ async chatCompletion() { throw err; },
+ async *streamChatCompletion(): AsyncGenerator<any> { throw err; },
+ };
+}
+
+async function post(app: Express, path: string, body: any, key: string) {
+ const server = app.listen(0);
+ const addr = server.address() as any;
+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
+ body: JSON.stringify(body),
+ });
+ const text = await res.text();
+ server.close();
+ return { status: res.status, text };
+}
+
+function cooldownExpiry(): number | null {
+ const row = getDb().prepare(
+ "SELECT expires_at_ms FROM rate_limit_cooldowns WHERE platform = 'fake' AND model_id = 'fake-model' AND key_id = 1",
+ ).get() as { expires_at_ms: number } | undefined;
+ return row?.expires_at_ms ?? null;
+}
+
+describe('/v1/responses shared-loop convergence', () => {
+ let app: Express;
+ let key: string;
+
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ app = createApp();
+ key = getUnifiedApiKey();
+ });
+
+ beforeEach(() => {
+ mockRouteRequest.mockReset();
+ getDb().prepare('DELETE FROM rate_limit_cooldowns').run();
+ getDb().prepare('DELETE FROM rate_limit_usage').run();
+ });
+
+ it('honors a provider Retry-After on the cooldown (drift #2 — was ignored on /v1/responses)', async () => {
+ const retryAfterMs = 5 * 60 * 1000; // 5 minutes, well over the 90s transient floor
+ const err = Object.assign(new Error('Groq API error 429: rate limit'), { status: 429, retryAfterMs });
+ mockRouteRequest.mockImplementation((_estimated: number, skipKeys?: Set<string>) => {
+ if (skipKeys?.size) throw Object.assign(new Error('All models exhausted'), { status: 429 });
+ return fakeRoute(throwingProvider(err));
+ });
+
+ const before = Date.now();
+ const { status } = await post(app, '/v1/responses', { input: 'hi', stream: false }, key);
+ expect(status).toBe(429); // exhausted after the single scripted model failed over
+
+ const expiry = cooldownExpiry();
+ expect(expiry).not.toBeNull();
+ const benchMs = expiry! - before;
+ // Retry-After (5 min) is honored: benched well beyond the 90s transient and
+ // well short of the day-long payment/forbidden bench.
+ expect(benchMs).toBeGreaterThan(4 * 60 * 1000);
+ expect(benchMs).toBeLessThan(10 * 60 * 1000);
+ });
+
+ it('day-benches a 403 model-not-on-tier (drift #2 — fell through to 90s transient before)', async () => {
+ const err = Object.assign(new Error('GitHub Models API error 403: Model not available on your plan'), { status: 403 });
+ mockRouteRequest.mockImplementation((_estimated: number, skipKeys?: Set<string>) => {
+ if (skipKeys?.size) throw Object.assign(new Error('All models exhausted'), { status: 429 });
+ return fakeRoute(throwingProvider(err));
+ });
+
+ const before = Date.now();
+ const { status } = await post(app, '/v1/responses', { input: 'hi', stream: false }, key);
+ expect(status).toBe(429);
+
+ const expiry = cooldownExpiry();
+ expect(expiry).not.toBeNull();
+ // MODEL_FORBIDDEN_COOLDOWN_MS is a full day; assert at least ~23h out (would
+ // have been ~90s before the convergence).
+ expect(expiry! - before).toBeGreaterThan(DAY_MS - 60 * 60 * 1000);
+ });
+
+ it('streams over a role-only chunk then an error, failing over invisibly (drift #1 commit point)', async () => {
+ async function* roleThenError(): AsyncGenerator<any> {
+ // A role preamble is NOT meaningful content — the skeleton must stay held.
+ yield { id: 'c', object: 'chat.completion.chunk', created: 0, model: 'fake-model', choices: [{ index: 0, delta: { role: 'assistant' }, finish_reason: null }] };
+ throw Object.assign(new Error('OpenRouter API error 503: Provider returned error'), { status: 503 });
+ }
+ async function* good(): AsyncGenerator<any> {
+ yield { id: 'c', object: 'chat.completion.chunk', created: 0, model: 'fake-model', choices: [{ index: 0, delta: { role: 'assistant', content: 'recovered ' }, finish_reason: null }] };
+ yield { id: 'c', object: 'chat.completion.chunk', created: 0, model: 'fake-model', choices: [{ index: 0, delta: { content: 'answer' }, finish_reason: 'stop' }] };
+ }
+ const streamGood = vi.fn(good);
+ mockRouteRequest
+ .mockReturnValueOnce(fakeRoute({ async chatCompletion() { throw new Error('nope'); }, streamChatCompletion: roleThenError }))
+ .mockReturnValueOnce(fakeRoute({ async chatCompletion() { throw new Error('nope'); }, streamChatCompletion: streamGood }));
+
+ const { status, text } = await post(app, '/v1/responses', { input: 'hi', stream: true }, key);
+ expect(status).toBe(200);
+ // The pre-content failure produced no committed bytes: no response.failed,
+ // the second model's answer completes the same connection.
+ expect(text).not.toContain('response.failed');
+ expect(text).toContain('response.completed');
+ expect(text).toContain('recovered answer');
+ expect(streamGood).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/src/lib/fallback-loop.ts b/server/src/lib/fallback-loop.ts
new file mode 100644
index 00000000..b5bc0c9b
--- /dev/null
+++ b/server/src/lib/fallback-loop.ts
@@ -0,0 +1,238 @@
+// One shared provider retry/fallback loop for every OpenAI-, Responses- and
+// Anthropic-shaped chat surface (routes/proxy.ts legacy /completions and
+// /chat/completions, routes/responses.ts, routes/anthropic.ts). Each surface
+// used to carry its own ~150-line copy of the attempt loop, and the copies had
+// drifted (a 403 that was benched for a day on three surfaces but only 90s on
+// /v1/responses; an exhaustion body that returned a 400 for a provider-invalid
+// request on three surfaces but always 429 on /v1/messages; a Retry-After that
+// was honored everywhere except /v1/responses). This module is the single
+// source of truth for the parts that MUST behave identically — cooldown
+// selection, per-key failure bookkeeping, exhaustion status — while each
+// surface keeps its own request/stream translation as a thin `dispatch` adapter.
+//
+// Pure control-flow + accounting: no Express, no wire-format knowledge. The
+// per-surface bytes (SSE framing, error-body shape, context handoff, group
+// routing) live in the caller's hooks, so this stays reviewable as unification.
+
+import type { RouteResult } from '../services/router.js';
+import { recordRateLimitHit, recordSuccess, hasOtherUsableKey } from '../services/router.js';
+import {
+ recordRequest,
+ recordTokens,
+ setCooldown,
+ getCooldownDurationForLimit,
+ PAYMENT_REQUIRED_COOLDOWN_MS,
+ MODEL_FORBIDDEN_COOLDOWN_MS,
+ learnLimitFromError,
+} from '../services/ratelimit.js';
+import {
+ isRetryableError,
+ isPaymentRequiredError,
+ isModelNotFoundError,
+ isModelAccessForbiddenError,
+ isProviderBadRequestError,
+} from './error-classify.js';
+import { sanitizeProviderErrorMessage } from './error-redaction.js';
+
+// Every surface caps failover hops at the same number.
+export const FALLBACK_MAX_RETRIES = 20;
+
+// Mutable per-request skip state threaded through the loop and mutated by
+// recordRetryableFailure. skipKeys entries are "platform:modelId:keyId";
+// skipModels holds model_db_ids ruled out for the rest of this request.
+export interface FallbackState {
+ skipKeys: Set<string>;
+ skipModels: Set<number>;
+}
+
+export function newFallbackState(): FallbackState {
+ return { skipKeys: new Set<string>(), skipModels: new Set<number>() };
+}
+
+/**
+ * The one true cooldown-duration selection after a retryable upstream failure:
+ * - 402 out-of-credits → a full day (PAYMENT_REQUIRED_COOLDOWN_MS)
+ * - 403 model-not-on-tier → a full day (MODEL_FORBIDDEN_COOLDOWN_MS), because a
+ * tier/subscription gate won't clear on the next minute window (issue #256)
+ * - anything else → the transient/daily escalation ladder, honoring the
+ * provider's Retry-After as a floor (getCooldownDurationForLimit).
+ *
+ * Convergence: /v1/responses previously skipped BOTH the 403 day-bench (it fell
+ * through to the 90s transient) AND the Retry-After floor. Now every surface
+ * benches identically.
+ */
+export function cooldownForError(route: RouteResult, err: any): number {
+ if (isPaymentRequiredError(err)) return PAYMENT_REQUIRED_COOLDOWN_MS;
+ if (isModelAccessForbiddenError(err)) return MODEL_FORBIDDEN_COOLDOWN_MS;
+ return getCooldownDurationForLimit(
+ route.platform,
+ route.modelId,
+ route.keyId,
+ { rpd: route.rpdLimit, tpd: route.tpdLimit },
+ err?.retryAfterMs,
+ );
+}
+
+/**
+ * Apply the full per-key failure bookkeeping shared by every surface after a
+ * retryable failure:
+ * - rule out the WHOLE model for the rest of the request on a 404 (removed
+ * upstream) or 403 (off this key's tier) — a sibling key would fail it the
+ * same way (PR #111 / issue #256);
+ * - bench this model+key via cooldownForError;
+ * - demote the model in the scorer ONLY when the failure exhausted it — i.e.
+ * no sibling key can still serve it (#454 gate). skipKeys already contains
+ * the just-failed key here, preserving #479's "count budget across keys"
+ * semantics: hasOtherUsableKey excludes both the failed key and skipKeys;
+ * - learn a provider-reported ceiling (e.g. a Groq 413 "TPM: Limit 30000")
+ * from the error body so the next pre-check fails over before the 413.
+ *
+ * Callers add the just-failed key to skipKeys via this function (do not pre-add).
+ */
+export function recordRetryableFailure(route: RouteResult, err: any, state: FallbackState): void {
+ if (isModelNotFoundError(err) || isModelAccessForbiddenError(err)) {
+ state.skipModels.add(route.modelDbId);
+ }
+ state.skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);
+ setCooldown(route.platform, route.modelId, route.keyId, cooldownForError(route, err));
+ // Model-level penalty only when no sibling key can still serve (#454).
+ if (!hasOtherUsableKey(route.modelDbId, route.keyId, state.skipKeys)) {
+ recordRateLimitHit(route.modelDbId);
+ }
+ learnLimitFromError(route.modelDbId, err);
+}
+
+/**
+ * The success-side accounting every surface runs after a completed attempt:
+ * count the request + its tokens against the model+key's rate-limit windows and
+ * 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 {
+ recordRequest(route.platform, route.modelId, route.keyId);
+ recordTokens(route.platform, route.modelId, route.keyId, rateLimitTokens);
+ recordSuccess(route.modelDbId);
+}
+
+export interface ExhaustionBody {
+ status: number;
+ type: string;
+ message: string;
+}
+
+/**
+ * The shared exhaustion response body. A request every routed provider rejected
+ * as invalid (isProviderBadRequestError) is a client error → 400
+ * invalid_request_error, not a misleading rate-limit exhaustion; otherwise 429
+ * rate_limit_error. The two `type` strings are valid error types on the OpenAI,
+ * Responses AND Anthropic surfaces, so all four call sites render this directly.
+ *
+ * Convergence: /v1/messages used to hand-roll a fixed 429 here, losing the 400
+ * branch. (Moved out of routes/proxy.ts, which re-exports it for compatibility.)
+ */
+export function exhaustedRetryError(lastError: any, maxRetries?: number): ExhaustionBody {
+ const safeLastError = sanitizeProviderErrorMessage(lastError?.message);
+ if (isProviderBadRequestError(lastError)) {
+ return {
+ status: 400,
+ type: 'invalid_request_error',
+ message: `All routed providers rejected the request as invalid. Last error: ${safeLastError}`,
+ };
+ }
+ const scope = maxRetries == null
+ ? 'All models rate-limited'
+ : `All models rate-limited after ${maxRetries} attempts`;
+ return {
+ status: 429,
+ type: 'rate_limit_error',
+ message: `${scope}. Last error: ${safeLastError}`,
+ };
+}
+
+// What a surface's dispatch() returns to signal the response is finished and the
+// loop must stop:
+// 'done' — the attempt succeeded and the full response was sent.
+// 'committed' — a stream already flushed real bytes to the client, then hit a
+// mid-stream error the surface surfaced honestly; no failover is
+// possible, so stop without recording another retry.
+export type DispatchOutcome = 'done' | 'committed';
+
+export interface FallbackHooks {
+ // Defaults to FALLBACK_MAX_RETRIES.
+ maxRetries?: number;
+ // Skip state; recordRetryableFailure (called by the loop) mutates it, and the
+ // surface's route() reads it to exclude failed keys/models.
+ state: FallbackState;
+
+ /**
+ * Pick a route for this attempt. Reads state.skipKeys / state.skipModels.
+ * Throws the router's RouteError when the pool is exhausted before any
+ * upstream is tried (caught by the loop → onRoutingExhausted).
+ */
+ route(attempt: number): RouteResult;
+
+ /**
+ * Run one attempt against the chosen route. Return 'done' on success or
+ * 'committed' when a stream already sent bytes and handled its own mid-stream
+ * error. THROW a (possibly synthetic) provider error — an upstream HTTP error,
+ * or an "empty completion" / "unparseable inline tool-call dialect" Error the
+ * classifier already treats as retryable — to trigger failover; a
+ * non-retryable throw becomes onFatal. A pre-commit failure MUST throw (not
+ * return 'committed') so the loop can fail over invisibly.
+ */
+ dispatch(route: RouteResult, attempt: number): Promise<DispatchOutcome>;
+
+ /** Trace + log a per-attempt failure (per-surface scope + logRequest args). */
+ logFailure(route: RouteResult, err: any, attempt: number): void;
+
+ /** Render a non-retryable provider error (per-surface body/status). */
+ onFatal(route: RouteResult, err: any): void;
+
+ /**
+ * Render exhaustion when route() threw. `lastError` is the last upstream error
+ * if any attempt ran, else null (routing gave up before trying anything).
+ */
+ onRoutingExhausted(lastError: any, routeErr: any): void;
+
+ /** Render exhaustion after all attempts were tried and failed. */
+ onExhausted(lastError: any): void;
+}
+
+/**
+ * The shared attempt loop. Owns iteration, the routeRequest-exhaustion path, the
+ * retryable-vs-fatal classification, the per-failure bookkeeping
+ * (recordRetryableFailure), and the final exhaustion path. Everything
+ * surface-specific — request translation, stream framing, error-body shape,
+ * context handoff, group routing — lives in the hooks.
+ */
+export async function runFallbackLoop(hooks: FallbackHooks): Promise<void> {
+ const maxRetries = hooks.maxRetries ?? FALLBACK_MAX_RETRIES;
+ let lastError: any = null;
+
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
+ let route: RouteResult;
+ try {
+ route = hooks.route(attempt);
+ } catch (routeErr) {
+ hooks.onRoutingExhausted(lastError, routeErr);
+ return;
+ }
+
+ try {
+ // 'done' or 'committed' — either way the response is finished.
+ await hooks.dispatch(route, attempt);
+ return;
+ } catch (err: any) {
+ hooks.logFailure(route, err, attempt);
+ if (isRetryableError(err)) {
+ recordRetryableFailure(route, err, hooks.state);
+ lastError = err;
+ continue;
+ }
+ hooks.onFatal(route, err);
+ return;
+ }
+ }
+
+ hooks.onExhausted(lastError);
+}
diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.ts
index aaf64503..68a1bda4 100644
--- a/server/src/routes/anthropic.ts
+++ b/server/src/routes/anthropic.ts
@@ -10,18 +10,15 @@ import type {
ChatContent,
ChatContentBlock,
} from '@freellmapi/shared/types.js';
-import { routeRequest, recordRateLimitHit, recordSuccess, hasOtherUsableKey, routingReserveTokens, type RouteResult } from '../services/router.js';
-import {
- recordRequest, recordTokens, setCooldown, getCooldownDurationForLimit,
- PAYMENT_REQUIRED_COOLDOWN_MS, MODEL_FORBIDDEN_COOLDOWN_MS, learnLimitFromError,
-} from '../services/ratelimit.js';
+import { routeRequest, routingReserveTokens, type RouteResult } from '../services/router.js';
import { getUnifiedApiKey } from '../db/index.js';
import { contentToString } from '../lib/content.js';
import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';
+import { rescueInlineToolCalls, startsWithDialectMarker, couldBecomeDialectMarker, containsDialectMarker } from '../lib/tool-call-rescue.js';
import { sanitizeProviderErrorMessage } from '../lib/error-redaction.js';
-import { isRetryableError, isPaymentRequiredError, isModelNotFoundError, isModelAccessForbiddenError } from '../lib/error-classify.js';
import { logRequest } from '../lib/request-log.js';
import { extractApiToken, timingSafeStringEqual, getStickyModel, setStickyModel } from './proxy.js';
+import { runFallbackLoop, newFallbackState, recordUpstreamSuccess, exhaustedRetryError } from '../lib/fallback-loop.js';
import { resolveAnthropicModel } from '../services/anthropic-map.js';
import { buildModelListing } from '../services/model-listing.js';
@@ -324,14 +321,19 @@ function writeSse(res: Response, event: string, data: unknown): void {
res.write(`data: ${JSON.stringify(data)}\n\n`);
}
-// ── Routing (shared loop, trimmed for the translation layer) ────────────────
-// Returns the routed result + the converted (internal) response for the
-// non-streaming path. Streaming is handled inline so we can translate chunks
-// as they arrive. Mirrors the OpenAI route's cooldown/skip/analytics handling.
-function cooldownFor(route: RouteResult, err: any): number {
- if (isPaymentRequiredError(err)) return PAYMENT_REQUIRED_COOLDOWN_MS;
- if (isModelAccessForbiddenError(err)) return MODEL_FORBIDDEN_COOLDOWN_MS;
- return getCooldownDurationForLimit(route.platform, route.modelId, route.keyId, { rpd: route.rpdLimit, tpd: route.tpdLimit }, err?.retryAfterMs);
+// Convert rescued inline tool calls (parsed out of a model that serialized its
+// tool call as TEXT) into OpenAI-shaped tool_calls, so toAnthropicContent /
+// the streaming tool_use emitter render them as Anthropic tool_use blocks —
+// the same rescue /chat/completions and /v1/responses already apply (#231).
+function rescuedToToolCalls(
+ calls: Array<{ name: string; arguments: string }>,
+ schemas: Map<string, unknown>,
+): ChatToolCall[] {
+ return calls.map((c, i) => ({
+ id: `toolu_${crypto.randomBytes(8).toString('hex')}_rescued_${i + 1}`,
+ type: 'function' as const,
+ function: { name: c.name, arguments: repairToolArguments(c.arguments, schemas.get(c.name) as any) },
+ }));
}
anthropicRouter.post('/messages', async (req: Request, res: Response) => {
@@ -377,47 +379,64 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {
let preferredModel = resolved.preferredModelDbId;
if (preferredModel == null) preferredModel = getStickyModel(messages, sessionId);
- const skipKeys = new Set<string>();
- const skipModels = new Set<number>();
- let lastError: any = null;
-
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
- let route: RouteResult;
- try {
- route = routeRequest(estimatedTotal, skipKeys.size > 0 ? skipKeys : undefined, preferredModel, hasImage, wantsTools, skipModels.size > 0 ? skipModels : undefined);
- } catch (err: any) {
- if (lastError) {
- sendError(res, 429, 'rate_limit_error', `All models rate-limited. Last error: ${sanitizeProviderErrorMessage(lastError.message)}`);
- } else {
- sendError(res, err?.status ?? 503, 'api_error', err?.message ?? 'No model available to route this request');
- }
- return;
- }
-
- try {
+ // Thin adapter over the shared fallback loop (lib/fallback-loop.ts): the
+ // cooldown/skip/penalty/exhaustion machinery is shared, only the Anthropic
+ // request/stream translation lives here. This converged three drifts on this
+ // surface: it now honors a provider Retry-After and day-benches a 403 (via the
+ // shared cooldown), returns a shared exhaustion body (a 400 invalid_request
+ // 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();
+
+ await runFallbackLoop({
+ maxRetries: MAX_RETRIES,
+ state,
+ route: () => routeRequest(estimatedTotal, state.skipKeys.size > 0 ? state.skipKeys : undefined, preferredModel, hasImage, wantsTools, state.skipModels.size > 0 ? state.skipModels : undefined),
+ dispatch: async (route, attempt) => {
if (stream) {
- await streamCompletion(res, route, messages, completionOptions, {
- start, attempt, requestedModel, estimatedInputTokens, tools, pinnedModelId,
- sessionId, pinned: resolved.pinned,
- });
- return;
+ try {
+ await streamCompletion(res, route, messages, completionOptions, {
+ start, attempt, requestedModel, estimatedInputTokens, tools, pinnedModelId,
+ sessionId, pinned: resolved.pinned,
+ });
+ return 'done';
+ } catch (err: any) {
+ // The stream already committed (message_start sent) and surfaced its
+ // own error event; stop without failover or a second response.
+ if (err instanceof StreamAlreadyStarted) return 'committed';
+ throw err;
+ }
}
const result = await route.provider.chatCompletion(route.apiKey, messages, route.modelId, completionOptions);
const respMsg = result.choices?.[0]?.message;
const respText = contentToString(respMsg?.content ?? '');
- const respToolCalls = respMsg?.tool_calls ?? [];
+ let respToolCalls = respMsg?.tool_calls ?? [];
- // Empty completion → fail over, exactly like the OpenAI route.
+ // Empty completion → fail over via the shared loop, exactly like the
+ // OpenAI route.
if (!respText && respToolCalls.length === 0) {
- logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, Date.now() - start, 'empty completion (no content, no tool_calls)', null, pinnedModelId);
- skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);
- setCooldown(route.platform, route.modelId, route.keyId, cooldownFor(route, {}));
- // Only demote the whole model when no sibling key can still serve; the
- // per-key cooldown already isolates this key's failure (#454).
- if (!hasOtherUsableKey(route.modelDbId, route.keyId, skipKeys)) recordRateLimitHit(route.modelDbId);
- lastError = new Error(`empty completion from ${route.displayName}`);
- continue;
+ throw new Error(`empty completion from ${route.displayName}`);
+ }
+
+ // Inline tool-call dialect rescue (#231): a tool-bearing request answered
+ // with the call serialized as TEXT → re-parse it into structured tool_use
+ // so Claude Code's agent loop keeps working; a detected-but-unparseable
+ // dialect is a dead turn and fails over like an empty completion. Same
+ // rescue /chat/completions and /v1/responses already apply.
+ if (wantsTools && respMsg && respToolCalls.length === 0 && respText) {
+ const rescue = rescueInlineToolCalls(respText, new Set((tools ?? []).map(t => t.function.name)));
+ if (rescue.detected) {
+ if (!rescue.calls) {
+ throw new Error(`unparseable inline tool-call dialect from ${route.displayName}: ${respText.slice(0, 120)}`);
+ }
+ const schemas = toolSchemaMap(tools);
+ respMsg.tool_calls = rescuedToToolCalls(rescue.calls, schemas);
+ respMsg.content = rescue.cleanText.length > 0 ? rescue.cleanText : null;
+ if (result.choices?.[0]) result.choices[0].finish_reason = 'tool_calls';
+ respToolCalls = respMsg.tool_calls;
+ console.log(`[Anthropic] Rescued ${rescue.calls.length} inline tool call(s) from ${route.displayName} into tool_use`);
+ }
}
// Repair double-encoded tool arguments against the request schemas, so
@@ -434,9 +453,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);
- recordRequest(route.platform, route.modelId, route.keyId);
- recordTokens(route.platform, route.modelId, route.keyId, result.usage?.total_tokens ?? promptTokens + completionTokens);
- recordSuccess(route.modelDbId);
+ recordUpstreamSuccess(route, result.usage?.total_tokens ?? promptTokens + completionTokens);
// Remember this model for the rest of the auto-routed session (no-op for
// a pinned request — the pin already fixes the model).
if (!resolved.pinned) setStickyModel(messages, route.modelDbId, sessionId);
@@ -456,32 +473,27 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {
if (attempt > 0) res.setHeader('X-Fallback-Attempts', String(attempt));
logRequest(route.platform, route.modelId, route.keyId, 'success', promptTokens, completionTokens, Date.now() - start, null, null, pinnedModelId);
res.json(anthropicResponse);
- return;
- } catch (err: any) {
- const safeError = sanitizeProviderErrorMessage(err.message);
- logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, Date.now() - start, safeError, null, pinnedModelId);
-
- // A stream that already sent its `message_start` cannot fail over — the
- // helper finished the SSE response itself. Bubble back without retrying.
- if (err instanceof StreamAlreadyStarted) return;
-
- if (isRetryableError(err)) {
- if (isModelNotFoundError(err) || isModelAccessForbiddenError(err)) skipModels.add(route.modelDbId);
- skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);
- setCooldown(route.platform, route.modelId, route.keyId, cooldownFor(route, err));
- // Model-level penalty only when no sibling key can still serve (#454).
- if (!hasOtherUsableKey(route.modelDbId, route.keyId, skipKeys)) recordRateLimitHit(route.modelDbId);
- learnLimitFromError(route.modelDbId, err);
- lastError = err;
- continue;
+ return 'done';
+ },
+ logFailure: (route, err) => {
+ logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, Date.now() - start, sanitizeProviderErrorMessage(err.message), null, pinnedModelId);
+ },
+ onFatal: (route, err) => {
+ sendError(res, 502, 'api_error', `Provider error (${route.displayName}): ${sanitizeProviderErrorMessage(err.message)}`);
+ },
+ onRoutingExhausted: (lastError, routeErr) => {
+ if (lastError) {
+ const e = exhaustedRetryError(lastError);
+ sendError(res, e.status, e.type, e.message);
+ } else {
+ sendError(res, routeErr?.status ?? 503, 'api_error', routeErr?.message ?? 'No model available to route this request');
}
-
- sendError(res, 502, 'api_error', `Provider error (${route.displayName}): ${safeError}`);
- return;
- }
- }
-
- sendError(res, 429, 'rate_limit_error', `All models rate-limited after ${MAX_RETRIES} attempts. Last: ${sanitizeProviderErrorMessage(lastError?.message)}`);
+ },
+ onExhausted: (lastError) => {
+ const e = exhaustedRetryError(lastError, MAX_RETRIES);
+ sendError(res, e.status, e.type, e.message);
+ },
+ });
});
// Thrown by streamCompletion once the SSE response is underway, so the outer
@@ -515,7 +527,7 @@ async function streamCompletion(
options: any,
ctx: StreamCtx,
): Promise<void> {
- let messageStarted = false; // doubles as "headers + message_start sent"
+ let messageStarted = false; // doubles as "headers + message_start sent" = committed
let textBlockOpen = false;
let textBlockIndex = -1;
let nextIndex = 0;
@@ -523,6 +535,16 @@ async function streamCompletion(
let upstreamFinish: string | null = null;
const toolAcc = new Map<number, { id?: string; name: string; args: string }>();
+ // Inline-dialect hold window (#231): the first text is held until it either
+ // matches a tool-call dialect marker (held to the end and rescued into
+ // tool_use blocks) or provably cannot (flushed and streamed normally). This is
+ // also the commit point convergence — message_start is not sent until the
+ // first MEANINGFUL content, so a stream that opens with a dialect marker and
+ // then turns out unparseable fails over invisibly (previously this surface
+ // committed on the first non-empty text and had no dialect rescue at all).
+ let dialectMode: 'undecided' | 'passthrough' | 'dialect' = 'undecided';
+ let heldText = '';
+
const ensureMessageStart = () => {
if (messageStarted) return;
res.setHeader('Content-Type', 'text/event-stream');
@@ -541,6 +563,18 @@ async function streamCompletion(
messageStarted = true;
};
+ // Commit (if needed), open the text block (if needed), and stream `text`.
+ const emitText = (text: string) => {
+ ensureMessageStart();
+ if (!textBlockOpen) {
+ textBlockIndex = nextIndex++;
+ writeSse(res, 'content_block_start', { type: 'content_block_start', index: textBlockIndex, content_block: { type: 'text', text: '' } });
+ textBlockOpen = true;
+ }
+ writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: textBlockIndex, delta: { type: 'text_delta', text } });
+ outputChars += text.length;
+ };
+
try {
const gen = route.provider.streamChatCompletion(route.apiKey, messages, route.modelId, options);
@@ -575,14 +609,22 @@ async function streamCompletion(
const text = typeof choice.delta?.content === 'string' ? choice.delta.content : '';
if (text.length === 0) continue;
- ensureMessageStart();
- if (!textBlockOpen) {
- textBlockIndex = nextIndex++;
- writeSse(res, 'content_block_start', { type: 'content_block_start', index: textBlockIndex, content_block: { type: 'text', text: '' } });
- textBlockOpen = true;
+ if (dialectMode === 'passthrough') {
+ emitText(text);
+ } else {
+ heldText += text;
+ if (dialectMode === 'undecided') {
+ const probe = heldText.trimStart();
+ if (startsWithDialectMarker(probe)) {
+ dialectMode = 'dialect';
+ } else if (!couldBecomeDialectMarker(probe) || heldText.length > 256) {
+ dialectMode = 'passthrough';
+ emitText(heldText);
+ heldText = '';
+ }
+ }
+ // else: still a strict prefix of a marker — keep holding.
}
- writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: textBlockIndex, delta: { type: 'text_delta', text } });
- outputChars += text.length;
}
// Assemble buffered tool calls: synthesize missing ids, repair args against
@@ -598,6 +640,32 @@ async function streamCompletion(
}))
.filter(c => { try { JSON.parse(c.arguments); return c.name.length > 0; } catch { return false; } });
+ // Resolve the dialect hold window now the full text is known. Held text was
+ // never emitted, so a dead dialect turn can still fail over (nothing has been
+ // committed). A rescued dialect becomes tool_use blocks; leftover clean text
+ // is emitted as a text block first.
+ if (heldText.length > 0) {
+ const rescue = (dialectMode === 'dialect' || containsDialectMarker(heldText))
+ ? rescueInlineToolCalls(heldText, new Set((ctx.tools ?? []).map(t => t.function.name)))
+ : { detected: false as const, calls: null, cleanText: heldText };
+ if (rescue.detected && !rescue.calls) {
+ throw new Error(`unparseable inline tool-call dialect from ${route.displayName}: ${heldText.slice(0, 120)}`);
+ }
+ if (rescue.detected && rescue.calls) {
+ if (rescue.cleanText.length > 0) emitText(rescue.cleanText);
+ for (const c of rescue.calls) {
+ const repaired = repairToolArguments(c.arguments, schemas.get(c.name));
+ if (c.name.length === 0) continue;
+ try { JSON.parse(repaired); } catch { continue; }
+ completedCalls.push({ id: `toolu_${crypto.randomBytes(8).toString('hex')}_rescued_${++synthetic}`, name: c.name, arguments: repaired });
+ }
+ console.log(`[Anthropic] Rescued ${rescue.calls.length} inline tool call(s) from ${route.displayName} into tool_use`);
+ } else {
+ emitText(heldText);
+ }
+ heldText = '';
+ }
+
// Nothing usable came out — fail over (message_start was never sent, so the
// client never saw this attempt).
if (!messageStarted && completedCalls.length === 0) {
@@ -621,9 +689,7 @@ async function streamCompletion(
writeSse(res, 'message_stop', { type: 'message_stop' });
res.end();
- recordRequest(route.platform, route.modelId, route.keyId);
- recordTokens(route.platform, route.modelId, route.keyId, ctx.estimatedInputTokens + outputTokens);
- recordSuccess(route.modelDbId);
+ recordUpstreamSuccess(route, ctx.estimatedInputTokens + outputTokens);
if (!ctx.pinned) setStickyModel(messages, route.modelDbId, ctx.sessionId);
logRequest(route.platform, route.modelId, route.keyId, 'success', ctx.estimatedInputTokens, outputTokens, Date.now() - ctx.start, null, null, ctx.pinnedModelId);
} catch (err: any) {
diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.ts
index 6c4dc739..d79bc500 100644
--- a/server/src/routes/proxy.ts
+++ b/server/src/routes/proxy.ts
@@ -14,9 +14,10 @@ import { sanitizeProviderErrorMessage } from '../lib/error-redaction.js';
import { rescueInlineToolCalls, startsWithDialectMarker, couldBecomeDialectMarker, containsDialectMarker } from '../lib/tool-call-rescue.js';
import { getContextHandoffMode, recordIncomingMessages, maybeInjectContextHandoff, recordSuccessfulModel, hasPriorModel, HANDOFF_MAX_TOKENS } from '../services/context-handoff.js';
import { isFusionModel, runFusion, fusionConfigSchema, FusionError, FUSION_MODEL_ID } from '../services/fusion.js';
-import { isRetryableError, isPaymentRequiredError, isModelNotFoundError, isModelAccessForbiddenError, isProviderBadRequestError } from '../lib/error-classify.js';
+import { isRetryableError, isPaymentRequiredError, isModelNotFoundError, isModelAccessForbiddenError } from '../lib/error-classify.js';
import { logRequest } from '../lib/request-log.js';
import { parseCacheDirective, cacheActive, isCacheableTemperature, computeCacheKey, getCachedResponse, storeCachedResponse } from '../services/cache.js';
+import { runFallbackLoop, newFallbackState, recordUpstreamSuccess, exhaustedRetryError } from '../lib/fallback-loop.js';
import type { Platform } from '@freellmapi/shared/types.js';
import { inferQuotaPoolKey, type QuotaObservationContext } from '../services/provider-quota.js';
import { isUnifyEnabled, getModelGroups, resolveRequestedIdToMembers } from '../services/model-groups.js';
@@ -123,22 +124,10 @@ export function traceRouteEvent(
console.log(parts.join(' '));
}
-export function exhaustedRetryError(lastError: any, maxRetries?: number) {
- const safeLastError = sanitizeProviderErrorMessage(lastError?.message);
- if (isProviderBadRequestError(lastError)) {
- return {
- status: 400,
- type: 'invalid_request_error',
- message: `All routed providers rejected the request as invalid. Last error: ${safeLastError}`,
- };
- }
- const scope = maxRetries == null ? 'All models rate-limited' : `All models rate-limited after ${maxRetries} attempts`;
- return {
- status: 429,
- type: 'rate_limit_error',
- message: `${scope}. Last error: ${safeLastError}`,
- };
-}
+// exhaustedRetryError moved to lib/fallback-loop.ts (the shared retry loop needs
+// it and importing it back from a route would be a cycle). Re-exported here for
+// existing importers (routes/responses.ts, proxy-retry.test.ts historically).
+export { exhaustedRetryError };
// Sticky sessions: track which model served each "session"
// Key: hash of first user message → model_db_id
@@ -711,55 +700,33 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
}
const pinnedModelId = requestedModel && !isAutoModel(requestedModel) ? requestedModel : null;
- const skipKeys = new Set<string>();
- const skipModels = new Set<number>();
- let lastError: any = null;
-
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
- let route: RouteResult;
- try {
- route = routeRequest(
- estimatedTotal,
- skipKeys.size > 0 ? skipKeys : undefined,
- preferredModel,
- false,
- false,
- skipModels.size > 0 ? skipModels : undefined,
- groupChain ?? resolvedChain?.chain,
- );
- } catch (err: any) {
- if (lastError) {
- const error = exhaustedRetryError(lastError);
- res.status(error.status).json({
- error: {
- message: error.message,
- type: error.type,
- },
- });
- } else {
- const disposition: string[] = Array.isArray(err.diagnostics) ? err.diagnostics : [];
- console.warn(
- `[Proxy] legacy completions routing exhausted (no upstream tried) req=${shortRequestId(requestGroupId)} ` +
- `requested=${requestedModelLabel} candidates=${disposition.length}` +
- (disposition.length ? `:\n ${disposition.join('\n ')}` : ''),
- );
- res.status(err.status ?? 503).json({
- error: { message: err.message, type: 'routing_error' },
- });
- }
- return;
- }
-
- traceRouteEvent('Proxy', {
- event: attempt === 0 ? 'start' : 'next',
- requestId: requestGroupId,
- attempt,
- platform: route.platform,
- model: route.modelId,
- requestedModel: attempt === 0 ? requestedModelLabel : undefined,
- });
+ const state = newFallbackState();
+
+ // Legacy /completions is a thin adapter over the shared fallback loop
+ // (lib/fallback-loop.ts): the cooldown/skip/penalty/exhaustion machinery is
+ // shared; only the text_completion request/stream translation lives here.
+ await runFallbackLoop({
+ maxRetries: MAX_RETRIES,
+ state,
+ route: () => routeRequest(
+ estimatedTotal,
+ state.skipKeys.size > 0 ? state.skipKeys : undefined,
+ preferredModel,
+ false,
+ false,
+ state.skipModels.size > 0 ? state.skipModels : undefined,
+ groupChain ?? resolvedChain?.chain,
+ ),
+ dispatch: async (route, attempt) => {
+ traceRouteEvent('Proxy', {
+ event: attempt === 0 ? 'start' : 'next',
+ requestId: requestGroupId,
+ attempt,
+ platform: route.platform,
+ model: route.modelId,
+ requestedModel: attempt === 0 ? requestedModelLabel : undefined,
+ });
- try {
if (stream) {
let totalOutputTokens = 0;
let headerSent = false;
@@ -794,6 +761,8 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
if (text.length > 0) sawText = true;
totalOutputTokens += Math.ceil(text.length / 4);
const frame = legacyCompletionChunk(route, chunk, text);
+ // Commit point: hold headers until the first real text, so a stream
+ // that dies before producing any fails over invisibly.
if (!headerSent && !sawText) {
buffered.push(frame);
continue;
@@ -810,9 +779,7 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
res.write('data: [DONE]\n\n');
res.end();
- recordRequest(route.platform, route.modelId, route.keyId);
- recordTokens(route.platform, route.modelId, route.keyId, estimatedInputTokens + totalOutputTokens);
- recordSuccess(route.modelDbId);
+ recordUpstreamSuccess(route, estimatedInputTokens + totalOutputTokens);
traceRouteEvent('Proxy', {
event: 'ok',
requestId: requestGroupId,
@@ -824,7 +791,7 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
outputTokens: totalOutputTokens,
});
logRequest(route.platform, route.modelId, route.keyId, 'success', estimatedInputTokens, totalOutputTokens, Date.now() - start, null, ttfbMs, pinnedModelId);
- return;
+ return 'done';
} catch (streamErr: any) {
if (headerSent) {
console.error(`[Proxy] Mid-stream legacy completion error from ${route.displayName}:`, streamErr.message);
@@ -841,59 +808,58 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
error: sanitizeProviderErrorMessage(streamErr.message),
});
logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, totalOutputTokens, Date.now() - start, sanitizeProviderErrorMessage(streamErr.message), ttfbMs, pinnedModelId);
- return;
+ return 'committed';
}
throw streamErr;
}
- } else {
- const result = await route.provider.chatCompletion(
- route.apiKey,
- messages,
- route.modelId,
- { temperature, max_tokens, top_p, stop },
- quotaContextForRoute(route, 'chat/completions'),
- );
+ }
- const text = completionTextFromChat(result);
- if (!text) {
- throw new Error(`empty completion from ${route.displayName}`);
- }
+ const result = await route.provider.chatCompletion(
+ route.apiKey,
+ messages,
+ route.modelId,
+ { temperature, max_tokens, top_p, stop },
+ quotaContextForRoute(route, 'chat/completions'),
+ );
- const totalTokens = result.usage?.total_tokens ?? 0;
- recordRequest(route.platform, route.modelId, route.keyId);
- recordTokens(route.platform, route.modelId, route.keyId, totalTokens);
- recordSuccess(route.modelDbId);
+ const text = completionTextFromChat(result);
+ if (!text) {
+ throw new Error(`empty completion from ${route.displayName}`);
+ }
- res.setHeader('X-Routed-Via', `${route.platform}/${route.modelId}`);
- if (attempt > 0) res.setHeader('X-Fallback-Attempts', String(attempt));
- res.json({
- id: completionIdFromChat(result.id),
- object: 'text_completion',
- created: result.created ?? Math.floor(Date.now() / 1000),
- model: route.modelId,
- choices: [{
- text,
- index: result.choices?.[0]?.index ?? 0,
- logprobs: null,
- finish_reason: result.choices?.[0]?.finish_reason ?? 'stop',
- }],
- usage: result.usage,
- });
+ const totalTokens = result.usage?.total_tokens ?? 0;
+ recordUpstreamSuccess(route, totalTokens);
- traceRouteEvent('Proxy', {
- event: 'ok',
- requestId: requestGroupId,
- attempt,
- platform: route.platform,
- model: route.modelId,
- latencyMs: Date.now() - start,
- inputTokens: result.usage?.prompt_tokens ?? 0,
- outputTokens: result.usage?.completion_tokens ?? 0,
- });
- logRequest(route.platform, route.modelId, route.keyId, 'success', result.usage?.prompt_tokens ?? 0, result.usage?.completion_tokens ?? 0, Date.now() - start, null, null, pinnedModelId);
- return;
- }
- } catch (err: any) {
+ res.setHeader('X-Routed-Via', `${route.platform}/${route.modelId}`);
+ if (attempt > 0) res.setHeader('X-Fallback-Attempts', String(attempt));
+ res.json({
+ id: completionIdFromChat(result.id),
+ object: 'text_completion',
+ created: result.created ?? Math.floor(Date.now() / 1000),
+ model: route.modelId,
+ choices: [{
+ text,
+ index: result.choices?.[0]?.index ?? 0,
+ logprobs: null,
+ finish_reason: result.choices?.[0]?.finish_reason ?? 'stop',
+ }],
+ usage: result.usage,
+ });
+
+ traceRouteEvent('Proxy', {
+ event: 'ok',
+ requestId: requestGroupId,
+ attempt,
+ platform: route.platform,
+ model: route.modelId,
+ latencyMs: Date.now() - start,
+ inputTokens: result.usage?.prompt_tokens ?? 0,
+ outputTokens: result.usage?.completion_tokens ?? 0,
+ });
+ logRequest(route.platform, route.modelId, route.keyId, 'success', result.usage?.prompt_tokens ?? 0, result.usage?.completion_tokens ?? 0, Date.now() - start, null, null, pinnedModelId);
+ return 'done';
+ },
+ logFailure: (route, err, attempt) => {
const latency = Date.now() - start;
const safeError = sanitizeProviderErrorMessage(err.message);
traceRouteEvent('Proxy', {
@@ -906,48 +872,32 @@ proxyRouter.post('/completions', async (req: Request, res: Response) => {
error: safeError,
});
logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, latency, safeError, null, pinnedModelId);
-
- if (isRetryableError(err)) {
- if (isModelNotFoundError(err) || isModelAccessForbiddenError(err)) skipModels.add(route.modelDbId);
- skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);
- setCooldown(
- route.platform,
- route.modelId,
- route.keyId,
- isPaymentRequiredError(err)
- ? PAYMENT_REQUIRED_COOLDOWN_MS
- : isModelAccessForbiddenError(err)
- ? MODEL_FORBIDDEN_COOLDOWN_MS
- : getCooldownDurationForLimit(route.platform, route.modelId, route.keyId, {
- rpd: route.rpdLimit,
- tpd: route.tpdLimit,
- }, err.retryAfterMs),
- );
- // Only demote the whole model when this 429 exhausted it. If another
- // enabled, non-cooldown key can still serve, the per-key cooldown alone
- // isolates the failure; a model-level penalty would wrongly sink a
- // model that's healthy on its other keys (#454).
- if (!hasOtherUsableKey(route.modelDbId, route.keyId, skipKeys)) recordRateLimitHit(route.modelDbId);
- learnLimitFromError(route.modelDbId, err);
- lastError = err;
- continue;
- }
-
+ },
+ onFatal: (route, err) => {
res.status(502).json({
error: {
- message: `Provider error (${route.displayName}): ${safeError}`,
+ message: `Provider error (${route.displayName}): ${sanitizeProviderErrorMessage(err.message)}`,
type: 'provider_error',
},
});
- return;
- }
- }
-
- const error = exhaustedRetryError(lastError, MAX_RETRIES);
- res.status(error.status).json({
- error: {
- message: error.message,
- type: error.type,
+ },
+ onRoutingExhausted: (lastError, routeErr) => {
+ if (lastError) {
+ const error = exhaustedRetryError(lastError);
+ res.status(error.status).json({ error: { message: error.message, type: error.type } });
+ } else {
+ const disposition: string[] = Array.isArray(routeErr.diagnostics) ? routeErr.diagnostics : [];
+ console.warn(
+ `[Proxy] legacy completions routing exhausted (no upstream tried) req=${shortRequestId(requestGroupId)} ` +
+ `requested=${requestedModelLabel} candidates=${disposition.length}` +
+ (disposition.length ? `:\n ${disposition.join('\n ')}` : ''),
+ );
+ res.status(routeErr.status ?? 503).json({ error: { message: routeErr.message, type: 'routing_error' } });
+ }
+ },
+ onExhausted: (lastError) => {
+ const error = exhaustedRetryError(lastError, MAX_RETRIES);
+ res.status(error.status).json({ error: { message: error.message, type: error.type } });
},
});
});
@@ -1385,14 +1335,18 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
// traffic and failover overrides are visible.
const pinnedModelId = requestedModel && !isAutoModel(requestedModel) ? requestedModel : null;
- // Retry loop: on 429/rate limit, skip that model+key and try the next one
- const skipKeys = new Set<string>();
- const skipModels = new Set<number>();
- let lastError: any = null;
-
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
- let route: RouteResult;
- try {
+ // Retry loop: on 429/rate limit, skip that model+key and try the next one.
+ // The attempt iteration, cooldown/skip/penalty bookkeeping, and exhaustion
+ // rendering are the shared fallback loop (lib/fallback-loop.ts). What stays
+ // here is /chat/completions-specific: the response-cache MISS store, the
+ // context-handoff injection, group/unified-chain routing, and the OpenAI
+ // stream turn-integrity framing.
+ const state = newFallbackState();
+
+ await runFallbackLoop({
+ maxRetries: MAX_RETRIES,
+ state,
+ route: () => {
// When a handoff could fire this turn, pad the token estimate so the router's
// context-window and TPM checks account for the extra system message overhead.
// We don't know the selected model key until after routeRequest() returns, so
@@ -1400,35 +1354,9 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
// model is on record). Turns where injection can't happen — every turn 1, and
// sessions that never switched — pay no headroom tax.
const routingEstimate = handoffPossible ? estimatedTotal + HANDOFF_MAX_TOKENS : estimatedTotal;
- route = routeRequest(routingEstimate, skipKeys.size > 0 ? skipKeys : undefined, preferredModel, hasImage, wantsTools, skipModels.size > 0 ? skipModels : undefined, groupChain ?? resolvedChain?.chain);
- } catch (err: any) {
- // No more models available
- if (lastError) {
- const error = exhaustedRetryError(lastError);
- res.status(error.status).json({
- error: {
- message: error.message,
- type: error.type,
- },
- });
- } else {
- // Synchronous exhaustion: the router rejected every candidate before any
- // upstream was tried, so this is the ONLY place the per-model disposition
- // is recorded. Without it a routing_error 429 is opaque — you can't tell a
- // genuinely dry pool from cooldowns/quota/context narrowing (issue _1).
- const disposition: string[] = Array.isArray(err.diagnostics) ? err.diagnostics : [];
- console.warn(
- `[Proxy] routing exhausted (no upstream tried) req=${shortRequestId(requestGroupId)} ` +
- `requested=${requestedModelLabel} candidates=${disposition.length}` +
- (disposition.length ? `:\n ${disposition.join('\n ')}` : ''),
- );
- res.status(err.status ?? 503).json({
- error: { message: err.message, type: 'routing_error' },
- });
- }
- return;
- }
-
+ return routeRequest(routingEstimate, state.skipKeys.size > 0 ? state.skipKeys : undefined, preferredModel, hasImage, wantsTools, state.skipModels.size > 0 ? state.skipModels : undefined, groupChain ?? resolvedChain?.chain);
+ },
+ dispatch: async (route, attempt) => {
const modelKey = `${route.platform}:${route.modelId}`;
traceRouteEvent('Proxy', {
event: attempt === 0 ? 'start' : 'next',
@@ -1451,7 +1379,6 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
injectedHandoffTokens = handoff.injectedTokens;
}
- try {
if (stream) {
// — Stream turn-integrity (#231 audit) —
// The old loop forwarded upstream chunks verbatim and called any
@@ -1536,7 +1463,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
error: sanitizeProviderErrorMessage(String(msg)),
});
logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, totalOutputTokens, Date.now() - start, `in-band error frame: ${sanitizeProviderErrorMessage(String(msg))}`, ttfbMs, pinnedModelId);
- return;
+ return 'committed';
}
if (anyChunk.id) lastMeta = { id: anyChunk.id, model: anyChunk.model, created: anyChunk.created };
@@ -1660,9 +1587,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
res.write('data: [DONE]\n\n');
res.end();
- recordRequest(route.platform, route.modelId, route.keyId);
- recordTokens(route.platform, route.modelId, route.keyId, estimatedInputTokens + injectedHandoffTokens + totalOutputTokens);
- recordSuccess(route.modelDbId);
+ recordUpstreamSuccess(route, estimatedInputTokens + injectedHandoffTokens + totalOutputTokens);
setStickyModel(messages, route.modelDbId, sessionIdHeader, stickyStrategyKey);
if (handoffMode !== 'off' && sessionKey) recordSuccessfulModel({ sessionKey, modelKey });
traceRouteEvent('Proxy', {
@@ -1676,7 +1601,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
outputTokens: totalOutputTokens,
});
logRequest(route.platform, route.modelId, route.keyId, 'success', estimatedInputTokens + injectedHandoffTokens, totalOutputTokens, Date.now() - start, null, ttfbMs, pinnedModelId);
- return;
+ return 'done';
} catch (streamErr: any) {
if (headerSent) {
// Mid-stream error after real payload reached the client — finish
@@ -1695,12 +1620,12 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
error: sanitizeProviderErrorMessage(streamErr.message),
});
logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, totalOutputTokens, Date.now() - start, sanitizeProviderErrorMessage(streamErr.message), ttfbMs, pinnedModelId);
- return;
+ return 'committed';
}
- // Headers never sent — bubble to the outer retry handler, which
- // cooldowns this model+key and tries the next one. Covers upstream
- // HTTP errors, in-band error frames, abrupt EOF, stalls, empty
- // completions, and unparseable dialect turns alike.
+ // Headers never sent — bubble to the shared loop, which cooldowns this
+ // model+key and tries the next one. Covers upstream HTTP errors, in-band
+ // error frames, abrupt EOF, stalls, empty completions, and unparseable
+ // dialect turns alike.
throw streamErr;
}
} else {
@@ -1712,26 +1637,13 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
// Empty completion (no text, no tool calls) → fail over rather than
// return a transport-level "success" the caller can't act on. Mirrors
- // the zero-chunk streaming case above.
+ // the zero-chunk streaming case above. Throwing hands it to the shared
+ // loop, which classifies "empty completion" as retryable and applies the
+ // same cooldown/skip/penalty bookkeeping as every other failure.
const respMsg = result.choices?.[0]?.message;
const respText = contentToString(respMsg?.content ?? '');
if (!respText && (respMsg?.tool_calls?.length ?? 0) === 0) {
- traceRouteEvent('Proxy', {
- event: 'fail',
- requestId: requestGroupId,
- attempt,
- platform: route.platform,
- model: route.modelId,
- latencyMs: Date.now() - start,
- error: 'empty completion',
- });
- logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, Date.now() - start, 'empty completion (no content, no tool_calls)', null, pinnedModelId);
- skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);
- setCooldown(route.platform, route.modelId, route.keyId, getCooldownDurationForLimit(route.platform, route.modelId, route.keyId, { rpd: route.rpdLimit, tpd: route.tpdLimit }));
- // Model-level penalty only when no sibling key can still serve (#454).
- if (!hasOtherUsableKey(route.modelDbId, route.keyId, skipKeys)) recordRateLimitHit(route.modelDbId);
- lastError = new Error(`empty completion from ${route.displayName}`);
- continue;
+ throw new Error(`empty completion from ${route.displayName}`);
}
// Inline tool-call dialect rescue (#231 audit): a tool-bearing
@@ -1759,9 +1671,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
}
const totalTokens = result.usage?.total_tokens ?? 0;
- recordRequest(route.platform, route.modelId, route.keyId);
- recordTokens(route.platform, route.modelId, route.keyId, totalTokens);
- recordSuccess(route.modelDbId);
+ recordUpstreamSuccess(route, totalTokens);
// Use stickyStrategyKey (not the global strategyKey) so a group-pinned
// request writes its sticky entry under the SAME key the next turn reads
// from (set to the requested model id at the top of the loop). Matches the
@@ -1815,9 +1725,10 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
outputTokens: result.usage?.completion_tokens ?? 0,
});
logRequest(route.platform, route.modelId, route.keyId, 'success', result.usage?.prompt_tokens ?? 0, result.usage?.completion_tokens ?? 0, Date.now() - start, null, null, pinnedModelId);
- return;
+ return 'done';
}
- } catch (err: any) {
+ },
+ logFailure: (route, err, attempt) => {
const latency = Date.now() - start;
const safeError = sanitizeProviderErrorMessage(err.message);
traceRouteEvent('Proxy', {
@@ -1830,64 +1741,38 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
error: safeError,
});
logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, latency, safeError, null, pinnedModelId);
-
- if (isRetryableError(err)) {
- // Model-level 404 (removed/deprecated upstream): rule the whole model
- // out for the rest of this request — its other keys would 404 the same
- // way. The per-key cooldown below still applies, so cross-request
- // behavior (#66/#76) is unchanged. (PR #111, credits @barbotkonv.)
- // 404 (removed upstream) and 403 (model off-limits to this key's tier)
- // both rule the model out: a sibling key on the same platform would
- // fail it identically, so skip it for the rest of this request.
- if (isModelNotFoundError(err) || isModelAccessForbiddenError(err)) skipModels.add(route.modelDbId);
-
- // Put this model+key on cooldown and try the next one
- const skipId = `${route.platform}:${route.modelId}:${route.keyId}`;
- skipKeys.add(skipId);
- setCooldown(
- route.platform,
- route.modelId,
- route.keyId,
- isPaymentRequiredError(err)
- ? PAYMENT_REQUIRED_COOLDOWN_MS
- // A 403 won't clear on the next window (it's a tier/subscription gate,
- // not a transient limit), so bench this model+key for a day like a 402
- // instead of re-trying it every request. See issue #256.
- : isModelAccessForbiddenError(err)
- ? MODEL_FORBIDDEN_COOLDOWN_MS
- : getCooldownDurationForLimit(route.platform, route.modelId, route.keyId, {
- rpd: route.rpdLimit,
- tpd: route.tpdLimit,
- }, err.retryAfterMs),
- );
- // Model-level penalty only when no sibling key can still serve (#454).
- if (!hasOtherUsableKey(route.modelDbId, route.keyId, skipKeys)) recordRateLimitHit(route.modelDbId);
- // Self-correct the catalog: if the provider reported its real ceiling in
- // the error body (e.g. a Groq 413 "tokens per minute (TPM): Limit 30000"),
- // persist it so the next request's pre-check fails over BEFORE the 413
- // instead of re-discovering it. No-op for errors with no parseable limit.
- learnLimitFromError(route.modelDbId, err);
- lastError = err;
- continue;
- }
-
- // Non-retryable error (auth, 4xx, etc.): don't retry
+ },
+ onFatal: (route, err) => {
+ // Non-retryable error (auth, bare 4xx, etc.): don't retry.
res.status(502).json({
error: {
- message: `Provider error (${route.displayName}): ${safeError}`,
+ message: `Provider error (${route.displayName}): ${sanitizeProviderErrorMessage(err.message)}`,
type: 'provider_error',
},
});
- return;
- }
- }
-
- // Exhausted all retries
- const error = exhaustedRetryError(lastError, MAX_RETRIES);
- res.status(error.status).json({
- error: {
- message: error.message,
- type: error.type,
+ },
+ onRoutingExhausted: (lastError, routeErr) => {
+ // No more models available.
+ if (lastError) {
+ const error = exhaustedRetryError(lastError);
+ res.status(error.status).json({ error: { message: error.message, type: error.type } });
+ } else {
+ // Synchronous exhaustion: the router rejected every candidate before any
+ // upstream was tried, so this is the ONLY place the per-model disposition
+ // is recorded. Without it a routing_error 429 is opaque — you can't tell a
+ // genuinely dry pool from cooldowns/quota/context narrowing (issue _1).
+ const disposition: string[] = Array.isArray(routeErr.diagnostics) ? routeErr.diagnostics : [];
+ console.warn(
+ `[Proxy] routing exhausted (no upstream tried) req=${shortRequestId(requestGroupId)} ` +
+ `requested=${requestedModelLabel} candidates=${disposition.length}` +
+ (disposition.length ? `:\n ${disposition.join('\n ')}` : ''),
+ );
+ res.status(routeErr.status ?? 503).json({ error: { message: routeErr.message, type: 'routing_error' } });
+ }
+ },
+ onExhausted: (lastError) => {
+ const error = exhaustedRetryError(lastError, MAX_RETRIES);
+ res.status(error.status).json({ error: { message: error.message, type: error.type } });
},
});
});
diff --git a/server/src/routes/responses.ts b/server/src/routes/responses.ts
index 64aa8a1c..70e5fbad 100644
--- a/server/src/routes/responses.ts
+++ b/server/src/routes/responses.ts
@@ -9,26 +9,21 @@ import type {
ChatToolChoice,
Platform,
} from '@freellmapi/shared/types.js';
-import { routeRequest, recordRateLimitHit, recordSuccess, hasEnabledToolsModel, hasOtherUsableKey, routingReserveTokens, type RouteResult } from '../services/router.js';
-import { recordRequest, recordTokens, setCooldown, getCooldownDurationForLimit, PAYMENT_REQUIRED_COOLDOWN_MS, learnLimitFromError } from '../services/ratelimit.js';
+import { routeRequest, hasEnabledToolsModel, routingReserveTokens, type RouteResult } from '../services/router.js';
import { getUnifiedApiKey } from '../db/index.js';
import { contentToString } from '../lib/content.js';
import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';
import { rescueInlineToolCalls, startsWithDialectMarker, couldBecomeDialectMarker, containsDialectMarker } from '../lib/tool-call-rescue.js';
import {
- isRetryableError,
- isPaymentRequiredError,
- isModelNotFoundError,
- isModelAccessForbiddenError,
timingSafeStringEqual,
extractApiToken,
getRequestGroupId,
getStickyModel,
setStickyModel,
traceRouteEvent,
- exhaustedRetryError,
logRequest,
} from './proxy.js';
+import { runFallbackLoop, newFallbackState, recordUpstreamSuccess, exhaustedRetryError } from '../lib/fallback-loop.js';
import { sanitizeProviderErrorMessage } from '../lib/error-redaction.js';
import { inferQuotaPoolKey, type QuotaObservationContext } from '../services/provider-quota.js';
@@ -41,13 +36,16 @@ export const responsesRouter = Router();
// is rejected — so the existing /v1/chat/completions endpoint isn't reachable
// from Codex (see issue #96). This endpoint accepts a Responses-shaped request,
// translates it to the internal chat-message format, runs it through the SAME
-// router/retry machinery as the proxy, and translates the result back into the
-// Responses object / SSE event stream that Codex expects.
+// shared fallback loop as the proxy (lib/fallback-loop.ts), and translates the
+// result back into the Responses object / SSE event stream Codex expects.
//
-// Deliberately self-contained: it duplicates the proxy's retry loop rather than
-// refactoring that battle-tested handler, so the production /chat/completions
-// path is untouched. Shared, side-effect-free helpers (routing, rate-limit
-// bookkeeping, sticky sessions, logging) are imported, not re-implemented.
+// A thin adapter: the cooldown/skip/penalty/exhaustion machinery is shared, and
+// only the Responses request/stream translation lives here. This is what fixed
+// the drift where /v1/responses ignored a provider Retry-After and under-benched
+// a 403 (both are now handled identically to /chat/completions by the shared
+// loop) and committed the SSE skeleton on the first raw chunk (the commit point
+// is now held until the first meaningful content, so a pre-content failure fails
+// over invisibly).
// ─────────────────────────────────────────────────────────────────────────
const MAX_RETRIES = 20;
@@ -368,11 +366,13 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
}
const responseId = newId('resp');
- const skipKeys = new Set<string>();
- const skipModels = new Set<number>();
- let lastError: any = null;
+ const state = newFallbackState();
- // Stream bookkeeping (used only when stream === true).
+ // Stream bookkeeping (used only when stream === true). `streamStarted` is the
+ // commit flag: true once the response.created/in_progress skeleton has left,
+ // after which failover is no longer possible. seq/streamStarted span attempts
+ // so the SSE sequence numbers stay monotonic and a committed stream can't be
+ // re-committed by a later attempt.
let seq = 0;
let streamStarted = false;
const sse = (event: string, payload: Record<string, unknown>) => {
@@ -380,25 +380,11 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
res.write(`data: ${JSON.stringify({ type: event, sequence_number: seq++, ...payload })}\n\n`);
};
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
- let route: RouteResult;
- try {
- route = routeRequest(estimatedTotal, skipKeys.size > 0 ? skipKeys : undefined, preferredModel, false, wantsTools, skipModels.size > 0 ? skipModels : undefined);
- } catch (err: any) {
- const exhausted = lastError ? exhaustedRetryError(lastError) : null;
- const status = exhausted?.status ?? err.status ?? 503;
- const message = exhausted?.message ?? err.message;
- const type = exhausted?.type ?? 'routing_error';
- if (streamStarted) {
- sse('response.failed', { response: { id: responseId, object: 'response', status: 'failed', error: { message, type } } });
- res.end();
- } else {
- res.status(status).json({ error: { message, type } });
- }
- return;
- }
-
- try {
+ await runFallbackLoop({
+ maxRetries: MAX_RETRIES,
+ state,
+ route: () => routeRequest(estimatedTotal, state.skipKeys.size > 0 ? state.skipKeys : undefined, preferredModel, false, wantsTools, state.skipModels.size > 0 ? state.skipModels : undefined),
+ dispatch: async (route, attempt) => {
traceRouteEvent('Responses', {
event: attempt === 0 ? 'start' : 'next',
requestId: requestGroupId,
@@ -422,8 +408,31 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
let dialectMode: 'undecided' | 'passthrough' | 'dialect' = 'undecided';
let heldText = '';
+ // Commit point: headers + the response.created/in_progress skeleton go
+ // out only when the first MEANINGFUL output item is about to be emitted
+ // (converged with /chat/completions — responses previously committed on
+ // the first raw chunk, even a role-only one). Until then a connect-time
+ // error, an empty completion, or an unparseable dialect turn fails over
+ // on the same connection with no bytes on the wire. Idempotent.
+ const commit = () => {
+ if (streamStarted) return;
+ res.setHeader('Content-Type', 'text/event-stream');
+ res.setHeader('Cache-Control', 'no-cache');
+ res.setHeader('Connection', 'keep-alive');
+ res.setHeader('X-Routed-Via', `${route.platform}/${route.modelId}`);
+ if (attempt > 0) res.setHeader('X-Fallback-Attempts', String(attempt));
+ const skeleton = {
+ id: responseId, object: 'response', created_at: nowUnix(),
+ status: 'in_progress', model: route.modelId, output: [], output_text: '',
+ };
+ sse('response.created', { response: skeleton });
+ sse('response.in_progress', { response: skeleton });
+ streamStarted = true;
+ };
+
// Open the text output item and stream `text` as its first delta.
const openTextItem = (text: string) => {
+ commit();
msgItemId = newId('msg');
sse('response.output_item.added', {
output_index: outputIndex,
@@ -439,310 +448,260 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
}
};
- const gen = route.provider.streamChatCompletion(
- route.apiKey,
- messages,
- route.modelId,
- completionOpts,
- quotaContextForRoute(route, 'responses'),
- );
-
- for await (const chunk of gen) {
- // In-band upstream error frame ({"error":...} inside a 200 SSE
- // stream — observed live from Groq). Throw before the lazy header
- // block so a first-frame error keeps streamStarted=false and takes
- // the normal failover path in the catch below.
- const anyChunk = chunk as Record<string, any>;
- if (anyChunk.error && !anyChunk.choices) {
- throw new Error(`in-band provider error from ${route.displayName}: ${anyChunk.error.message ?? 'provider error'}`);
- }
- // LAZY header set — headers + the response.created/in_progress
- // skeleton go out only once the provider actually streams a chunk.
- // Sending them before the provider call (the previous behavior)
- // committed the SSE response, so a provider error AT STREAM OPEN —
- // e.g. OpenRouter 503ing a large-context request — was misclassified
- // as mid-stream and returned to the client with NO failover and NO
- // cooldown; the next request then hit the same broken model again
- // (observed: 17 consecutive 503s to the same model while the rest of
- // the chain sat idle). With lazy headers a connect-time error
- // bubbles to the catch with streamStarted=false and takes the normal
- // retry path. Mirrors the proxy's streaming handler.
- if (!streamStarted) {
- res.setHeader('Content-Type', 'text/event-stream');
- res.setHeader('Cache-Control', 'no-cache');
- res.setHeader('Connection', 'keep-alive');
- res.setHeader('X-Routed-Via', `${route.platform}/${route.modelId}`);
- if (attempt > 0) res.setHeader('X-Fallback-Attempts', String(attempt));
- const skeleton = {
- id: responseId, object: 'response', created_at: nowUnix(),
- status: 'in_progress', model: route.modelId, output: [], output_text: '',
- };
- sse('response.created', { response: skeleton });
- sse('response.in_progress', { response: skeleton });
- streamStarted = true;
- }
+ try {
+ const gen = route.provider.streamChatCompletion(
+ route.apiKey,
+ messages,
+ route.modelId,
+ completionOpts,
+ quotaContextForRoute(route, 'responses'),
+ );
+
+ for await (const chunk of gen) {
+ // In-band upstream error frame ({"error":...} inside a 200 SSE
+ // stream — observed live from Groq). Throwing hands it to the catch
+ // below: pre-commit it fails over, post-commit it surfaces
+ // response.failed.
+ const anyChunk = chunk as Record<string, any>;
+ if (anyChunk.error && !anyChunk.choices) {
+ throw new Error(`in-band provider error from ${route.displayName}: ${anyChunk.error.message ?? 'provider error'}`);
+ }
- const delta = chunk.choices?.[0]?.delta;
- if (!delta) continue;
+ const delta = chunk.choices?.[0]?.delta;
+ if (!delta) continue;
+
+ // Text deltas → output_text events on a single message item, after
+ // the dialect hold window has decided the text is real prose.
+ const text = delta.content ?? '';
+ if (text) {
+ totalOutputTokens += Math.ceil(text.length / 4);
+ if (dialectMode === 'passthrough') {
+ if (msgItemId === null) openTextItem('');
+ sse('response.output_text.delta', {
+ item_id: msgItemId, output_index: 0, content_index: 0, delta: text,
+ });
+ msgText += text;
+ } else {
+ heldText += text;
+ if (dialectMode === 'undecided') {
+ const probe = heldText.trimStart();
+ if (startsWithDialectMarker(probe)) {
+ dialectMode = 'dialect';
+ } else if (!couldBecomeDialectMarker(probe) || heldText.length > 256) {
+ dialectMode = 'passthrough';
+ openTextItem(heldText);
+ heldText = '';
+ }
+ }
+ }
+ }
- // Text deltas → output_text events on a single message item, after
- // the dialect hold window has decided the text is real prose.
- const text = delta.content ?? '';
- if (text) {
- totalOutputTokens += Math.ceil(text.length / 4);
- if (dialectMode === 'passthrough') {
- if (msgItemId === null) openTextItem('');
- sse('response.output_text.delta', {
- item_id: msgItemId, output_index: 0, content_index: 0, delta: text,
- });
- msgText += text;
- } else {
- heldText += text;
- if (dialectMode === 'undecided') {
- const probe = heldText.trimStart();
- if (startsWithDialectMarker(probe)) {
- dialectMode = 'dialect';
- } else if (!couldBecomeDialectMarker(probe) || heldText.length > 256) {
- dialectMode = 'passthrough';
- openTextItem(heldText);
- heldText = '';
+ // Tool-call deltas → function_call item + argument deltas.
+ for (const tc of delta.tool_calls ?? []) {
+ const idx = (tc as any).index ?? 0;
+ let acc = toolAcc.get(idx);
+ if (!acc) {
+ // First time we see this tool call: open a new output item.
+ commit();
+ if (msgItemId !== null && msgText.length > 0) {
+ // close the text item (always output index 0) before starting a function_call item
+ sse('response.output_text.done', { item_id: msgItemId, output_index: 0, content_index: 0, text: msgText });
+ sse('response.content_part.done', { item_id: msgItemId, output_index: 0, content_index: 0, part: { type: 'output_text', text: msgText, annotations: [] } });
+ sse('response.output_item.done', { output_index: 0, item: { id: msgItemId, type: 'message', status: 'completed', role: 'assistant', content: [{ type: 'output_text', text: msgText, annotations: [] }] } });
+ msgItemId = null;
}
+ outputIndex = toolAcc.size + (msgText.length > 0 ? 1 : 0);
+ acc = { outputIndex, itemId: newId('fc'), callId: tc.id || newId('call'), name: tc.function?.name ?? '', args: '' };
+ toolAcc.set(idx, acc);
+ sse('response.output_item.added', {
+ output_index: acc.outputIndex,
+ item: { id: acc.itemId, type: 'function_call', status: 'in_progress', call_id: acc.callId, name: acc.name, arguments: '' },
+ });
+ }
+ const argFrag = tc.function?.arguments ?? '';
+ if (tc.function?.name && !acc.name) acc.name = tc.function.name;
+ if (argFrag) {
+ acc.args += argFrag;
+ sse('response.function_call_arguments.delta', { item_id: acc.itemId, output_index: acc.outputIndex, delta: argFrag });
}
}
}
- // Tool-call deltas → function_call item + argument deltas.
- for (const tc of delta.tool_calls ?? []) {
- const idx = (tc as any).index ?? 0;
- let acc = toolAcc.get(idx);
- if (!acc) {
- // First time we see this tool call: open a new output item.
- if (msgItemId !== null && msgText.length > 0) {
- // close the text item (always output index 0) before starting a function_call item
- sse('response.output_text.done', { item_id: msgItemId, output_index: 0, content_index: 0, text: msgText });
- sse('response.content_part.done', { item_id: msgItemId, output_index: 0, content_index: 0, part: { type: 'output_text', text: msgText, annotations: [] } });
- sse('response.output_item.done', { output_index: 0, item: { id: msgItemId, type: 'message', status: 'completed', role: 'assistant', content: [{ type: 'output_text', text: msgText, annotations: [] }] } });
- msgItemId = null;
- }
- outputIndex = toolAcc.size + (msgText.length > 0 ? 1 : 0);
- acc = { outputIndex, itemId: newId('fc'), callId: tc.id || newId('call'), name: tc.function?.name ?? '', args: '' };
- toolAcc.set(idx, acc);
- sse('response.output_item.added', {
- output_index: acc.outputIndex,
- item: { id: acc.itemId, type: 'function_call', status: 'in_progress', call_id: acc.callId, name: acc.name, arguments: '' },
- });
+ // Resolve the dialect hold window now that the full text is known.
+ // Held text was never emitted, so a dead dialect turn can still fail
+ // over on the same SSE stream (nothing has been committed yet).
+ if (heldText.length > 0) {
+ const rescue = (dialectMode === 'dialect' || containsDialectMarker(heldText))
+ ? rescueInlineToolCalls(heldText, new Set((tools ?? []).map(t => t.function.name)))
+ : { detected: false as const, calls: null, cleanText: heldText };
+ if (rescue.detected && !rescue.calls) {
+ // Unparseable dialect turn: throw so the shared loop cooldowns this
+ // model+key and fails over (streamStarted is still false).
+ throw new Error(`unparseable inline tool-call dialect from ${route.displayName}: ${heldText.slice(0, 120)}`);
}
- const argFrag = tc.function?.arguments ?? '';
- if (tc.function?.name && !acc.name) acc.name = tc.function.name;
- if (argFrag) {
- acc.args += argFrag;
- sse('response.function_call_arguments.delta', { item_id: acc.itemId, output_index: acc.outputIndex, delta: argFrag });
+ if (rescue.detected && rescue.calls) {
+ // Rescued calls become function_call items, exactly as if the
+ // provider had streamed them structurally.
+ console.log(`[Responses] Rescued ${rescue.calls.length} inline tool call(s) from ${route.displayName}`);
+ if (rescue.cleanText.length > 0 && msgItemId === null) openTextItem(rescue.cleanText);
+ let rescuedIdx = 0;
+ for (const c of rescue.calls) {
+ const idx = 1000 + rescuedIdx++; // synthetic accumulator keys, past any provider index
+ commit();
+ const acc = {
+ outputIndex: toolAcc.size + (msgText.length > 0 ? 1 : 0),
+ itemId: newId('fc'), callId: newId('call'), name: c.name, args: c.arguments,
+ };
+ toolAcc.set(idx, acc);
+ sse('response.output_item.added', {
+ output_index: acc.outputIndex,
+ item: { id: acc.itemId, type: 'function_call', status: 'in_progress', call_id: acc.callId, name: acc.name, arguments: '' },
+ });
+ }
+ } else if (msgItemId === null) {
+ // Plain short answer that never left the hold window (e.g. "Hi").
+ openTextItem(heldText);
}
+ heldText = '';
}
- }
- // Resolve the dialect hold window now that the full text is known.
- // Held text was never emitted, so a dead dialect turn can still fail
- // over on the same SSE stream (only the skeleton events are out).
- if (heldText.length > 0) {
- const rescue = (dialectMode === 'dialect' || containsDialectMarker(heldText))
- ? rescueInlineToolCalls(heldText, new Set((tools ?? []).map(t => t.function.name)))
- : { detected: false as const, calls: null, cleanText: heldText };
- if (rescue.detected && !rescue.calls) {
- traceRouteEvent('Responses', {
- event: 'fail',
- requestId: requestGroupId,
- attempt,
- platform: route.platform,
- model: route.modelId,
- latencyMs: Date.now() - start,
- error: 'unparseable inline tool-call dialect',
- });
- logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, Date.now() - start, `unparseable inline tool-call dialect: ${heldText.slice(0, 120)}`);
- skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);
- setCooldown(route.platform, route.modelId, route.keyId, getCooldownDurationForLimit(route.platform, route.modelId, route.keyId, { rpd: route.rpdLimit, tpd: route.tpdLimit }));
- // Only demote the whole model when no sibling key can still serve;
- // the per-key cooldown already isolates this key's failure (#454).
- if (!hasOtherUsableKey(route.modelDbId, route.keyId, skipKeys)) recordRateLimitHit(route.modelDbId);
- lastError = new Error(`unparseable inline tool-call dialect from ${route.displayName}`);
- continue;
+ // Empty completion — the provider returned 200 with no text AND no
+ // tool calls. Seen in production from nemotron-3-super on ~65k-token
+ // contexts: transport-level "success", zero usable output. Nothing has
+ // been committed yet (the skeleton is lazy), so throwing lets the
+ // shared loop fail over to the next model on the same SSE connection.
+ if (msgText.length === 0 && toolAcc.size === 0) {
+ throw new Error(`empty completion from ${route.displayName}`);
}
- if (rescue.detected && rescue.calls) {
- // Rescued calls become function_call items, exactly as if the
- // provider had streamed them structurally.
- console.log(`[Responses] Rescued ${rescue.calls.length} inline tool call(s) from ${route.displayName}`);
- if (rescue.cleanText.length > 0 && msgItemId === null) openTextItem(rescue.cleanText);
- let rescuedIdx = 0;
- for (const c of rescue.calls) {
- const idx = 1000 + rescuedIdx++; // synthetic accumulator keys, past any provider index
- const acc = {
- outputIndex: toolAcc.size + (msgText.length > 0 ? 1 : 0),
- itemId: newId('fc'), callId: newId('call'), name: c.name, args: c.arguments,
- };
- toolAcc.set(idx, acc);
- sse('response.output_item.added', {
- output_index: acc.outputIndex,
- item: { id: acc.itemId, type: 'function_call', status: 'in_progress', call_id: acc.callId, name: acc.name, arguments: '' },
- });
- }
- } else if (msgItemId === null) {
- // Plain short answer that never left the hold window (e.g. "Hi").
- openTextItem(heldText);
+
+ // Finalize any open text item.
+ if (msgItemId !== null) {
+ sse('response.output_text.done', { item_id: msgItemId, output_index: 0, content_index: 0, text: msgText });
+ sse('response.content_part.done', { item_id: msgItemId, output_index: 0, content_index: 0, part: { type: 'output_text', text: msgText, annotations: [] } });
+ sse('response.output_item.done', { output_index: 0, item: { id: msgItemId, type: 'message', status: 'completed', role: 'assistant', content: [{ type: 'output_text', text: msgText, annotations: [] }] } });
+ }
+ // Finalize tool-call items. Arguments are repaired against the tool's
+ // parameter schema at this point (after the full string accumulated):
+ // models like GLM double-encode nested arrays/objects as strings, and
+ // Codex hard-rejects the call ("invalid type: string, expected a
+ // sequence"). Clients consume the *.done events / final response for
+ // arguments, so repairing here covers the streamed path too.
+ const finalToolCalls: ChatToolCall[] = [];
+ for (const acc of toolAcc.values()) {
+ const repairedArgs = repairToolArguments(acc.args, toolSchemas.get(acc.name));
+ sse('response.function_call_arguments.done', { item_id: acc.itemId, output_index: acc.outputIndex, arguments: repairedArgs });
+ sse('response.output_item.done', { output_index: acc.outputIndex, item: { id: acc.itemId, type: 'function_call', status: 'completed', call_id: acc.callId, name: acc.name, arguments: repairedArgs } });
+ finalToolCalls.push({ id: acc.callId, type: 'function', function: { name: acc.name, arguments: repairedArgs } });
}
- heldText = '';
- }
- // Empty completion — the provider returned 200 with no text AND no
- // tool calls. Seen in production from nemotron-3-super on ~65k-token
- // contexts: transport-level "success", zero usable output, so the
- // agent client records a successful run it can't act on and its issue
- // dead-ends. Nothing substantive has been emitted yet (output_item
- // events only fire on the first delta; only the created/in_progress
- // skeletons are out), so it's safe to fail over to the next model on
- // the same SSE stream.
- if (msgText.length === 0 && toolAcc.size === 0) {
+ const finalResponse = buildResponseObject({
+ id: responseId, model: route.modelId, text: msgText,
+ toolCalls: finalToolCalls, promptTokens: estimatedInputTokens, completionTokens: totalOutputTokens,
+ });
+ sse('response.completed', { response: finalResponse });
+ res.end();
+
+ recordUpstreamSuccess(route, estimatedInputTokens + totalOutputTokens);
+ setStickyModel(messages, route.modelDbId, sessionIdHeader);
traceRouteEvent('Responses', {
- event: 'fail',
+ event: 'ok',
requestId: requestGroupId,
attempt,
platform: route.platform,
model: route.modelId,
latencyMs: Date.now() - start,
- error: 'empty completion',
+ inputTokens: estimatedInputTokens,
+ outputTokens: totalOutputTokens,
});
- logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, Date.now() - start, 'empty completion (no content, no tool_calls)');
- skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);
- setCooldown(route.platform, route.modelId, route.keyId, getCooldownDurationForLimit(route.platform, route.modelId, route.keyId, { rpd: route.rpdLimit, tpd: route.tpdLimit }));
- // Model-level penalty only when no sibling key can still serve (#454).
- if (!hasOtherUsableKey(route.modelDbId, route.keyId, skipKeys)) recordRateLimitHit(route.modelDbId);
- lastError = new Error(`empty completion from ${route.displayName}`);
- continue;
+ logRequest(route.platform, route.modelId, route.keyId, 'success', estimatedInputTokens, totalOutputTokens, Date.now() - start, null);
+ return 'done';
+ } catch (streamErr: any) {
+ // A committed stream can't fail over (bytes already sent) — surface a
+ // response.failed event honestly and stop. A pre-commit failure throws
+ // through to the shared loop for cooldown + failover.
+ if (streamStarted) {
+ const safe = sanitizeProviderErrorMessage(streamErr.message);
+ traceRouteEvent('Responses', {
+ event: 'fail',
+ requestId: requestGroupId,
+ attempt,
+ platform: route.platform,
+ model: route.modelId,
+ latencyMs: Date.now() - start,
+ error: safe,
+ });
+ logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, Date.now() - start, safe);
+ sse('response.failed', { response: { id: responseId, object: 'response', status: 'failed', error: { message: `Provider error (${route.displayName}): stream interrupted`, type: 'stream_error' } } });
+ res.end();
+ return 'committed';
+ }
+ throw streamErr;
}
+ }
- // Finalize any open text item.
- if (msgItemId !== null) {
- sse('response.output_text.done', { item_id: msgItemId, output_index: 0, content_index: 0, text: msgText });
- sse('response.content_part.done', { item_id: msgItemId, output_index: 0, content_index: 0, part: { type: 'output_text', text: msgText, annotations: [] } });
- sse('response.output_item.done', { output_index: 0, item: { id: msgItemId, type: 'message', status: 'completed', role: 'assistant', content: [{ type: 'output_text', text: msgText, annotations: [] }] } });
- }
- // Finalize tool-call items. Arguments are repaired against the tool's
- // parameter schema at this point (after the full string accumulated):
- // models like GLM double-encode nested arrays/objects as strings, and
- // Codex hard-rejects the call ("invalid type: string, expected a
- // sequence"). Clients consume the *.done events / final response for
- // arguments, so repairing here covers the streamed path too.
- const finalToolCalls: ChatToolCall[] = [];
- for (const acc of toolAcc.values()) {
- const repairedArgs = repairToolArguments(acc.args, toolSchemas.get(acc.name));
- sse('response.function_call_arguments.done', { item_id: acc.itemId, output_index: acc.outputIndex, arguments: repairedArgs });
- sse('response.output_item.done', { output_index: acc.outputIndex, item: { id: acc.itemId, type: 'function_call', status: 'completed', call_id: acc.callId, name: acc.name, arguments: repairedArgs } });
- finalToolCalls.push({ id: acc.callId, type: 'function', function: { name: acc.name, arguments: repairedArgs } });
+ const result = await route.provider.chatCompletion(
+ route.apiKey,
+ messages,
+ route.modelId,
+ completionOpts,
+ quotaContextForRoute(route, 'responses'),
+ );
+
+ const msg = result.choices[0]?.message;
+ let text = contentToString(msg?.content ?? '');
+ let toolCalls = (msg?.tool_calls ?? []).map((tc) => ({
+ ...tc,
+ function: { ...tc.function, arguments: repairToolArguments(tc.function.arguments, toolSchemas.get(tc.function.name)) },
+ }));
+
+ // Inline tool-call dialect rescue (#231) — see /chat/completions.
+ if (wantsTools && toolCalls.length === 0 && text) {
+ const rescue = rescueInlineToolCalls(text, new Set((tools ?? []).map(t => t.function.name)));
+ if (rescue.detected) {
+ if (!rescue.calls) {
+ throw new Error(`unparseable inline tool-call dialect from ${route.displayName}: ${text.slice(0, 120)}`);
+ }
+ console.log(`[Responses] Rescued ${rescue.calls.length} inline tool call(s) from ${route.displayName}`);
+ toolCalls = rescue.calls.map((c, i) => ({
+ id: `call_rescued_${i + 1}`,
+ type: 'function' as const,
+ function: { name: c.name, arguments: repairToolArguments(c.arguments, toolSchemas.get(c.name)) },
+ }));
+ text = rescue.cleanText;
}
+ }
+ const promptTokens = result.usage?.prompt_tokens ?? estimatedInputTokens;
+ const completionTokens = result.usage?.completion_tokens ?? Math.ceil(text.length / 4);
- const finalResponse = buildResponseObject({
- id: responseId, model: route.modelId, text: msgText,
- toolCalls: finalToolCalls, promptTokens: estimatedInputTokens, completionTokens: totalOutputTokens,
- });
- sse('response.completed', { response: finalResponse });
- res.end();
+ // Empty completion → fail over via the shared loop (see the streaming path).
+ if (!text && toolCalls.length === 0) {
+ throw new Error(`empty completion from ${route.displayName}`);
+ }
- recordRequest(route.platform, route.modelId, route.keyId);
- recordTokens(route.platform, route.modelId, route.keyId, estimatedInputTokens + totalOutputTokens);
- recordSuccess(route.modelDbId);
- setStickyModel(messages, route.modelDbId, sessionIdHeader);
- traceRouteEvent('Responses', {
- event: 'ok',
- requestId: requestGroupId,
- attempt,
- platform: route.platform,
- model: route.modelId,
- latencyMs: Date.now() - start,
- inputTokens: estimatedInputTokens,
- outputTokens: totalOutputTokens,
- });
- logRequest(route.platform, route.modelId, route.keyId, 'success', estimatedInputTokens, totalOutputTokens, Date.now() - start, null);
- return;
- } else {
- const result = await route.provider.chatCompletion(
- route.apiKey,
- messages,
- route.modelId,
- completionOpts,
- quotaContextForRoute(route, 'responses'),
- );
-
- const msg = result.choices[0]?.message;
- let text = contentToString(msg?.content ?? '');
- let toolCalls = (msg?.tool_calls ?? []).map((tc) => ({
- ...tc,
- function: { ...tc.function, arguments: repairToolArguments(tc.function.arguments, toolSchemas.get(tc.function.name)) },
- }));
-
- // Inline tool-call dialect rescue (#231) — see /chat/completions.
- if (wantsTools && toolCalls.length === 0 && text) {
- const rescue = rescueInlineToolCalls(text, new Set((tools ?? []).map(t => t.function.name)));
- if (rescue.detected) {
- if (!rescue.calls) {
- throw new Error(`unparseable inline tool-call dialect from ${route.displayName}: ${text.slice(0, 120)}`);
- }
- console.log(`[Responses] Rescued ${rescue.calls.length} inline tool call(s) from ${route.displayName}`);
- toolCalls = rescue.calls.map((c, i) => ({
- id: `call_rescued_${i + 1}`,
- type: 'function' as const,
- function: { name: c.name, arguments: repairToolArguments(c.arguments, toolSchemas.get(c.name)) },
- }));
- text = rescue.cleanText;
- }
- }
- const promptTokens = result.usage?.prompt_tokens ?? estimatedInputTokens;
- const completionTokens = result.usage?.completion_tokens ?? Math.ceil(text.length / 4);
+ recordUpstreamSuccess(route, result.usage?.total_tokens ?? 0);
+ setStickyModel(messages, route.modelDbId, sessionIdHeader);
- // Empty completion → fail over (see the streaming-path comment above).
- if (!text && toolCalls.length === 0) {
- traceRouteEvent('Responses', {
- event: 'fail',
- requestId: requestGroupId,
- attempt,
- platform: route.platform,
- model: route.modelId,
- latencyMs: Date.now() - start,
- error: 'empty completion',
- });
- logRequest(route.platform, route.modelId, route.keyId, 'error', promptTokens, 0, Date.now() - start, 'empty completion (no content, no tool_calls)');
- skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);
- setCooldown(route.platform, route.modelId, route.keyId, getCooldownDurationForLimit(route.platform, route.modelId, route.keyId, { rpd: route.rpdLimit, tpd: route.tpdLimit }));
- // Model-level penalty only when no sibling key can still serve (#454).
- if (!hasOtherUsableKey(route.modelDbId, route.keyId, skipKeys)) recordRateLimitHit(route.modelDbId);
- lastError = new Error(`empty completion from ${route.displayName}`);
- continue;
- }
+ res.setHeader('X-Routed-Via', `${route.platform}/${route.modelId}`);
+ if (attempt > 0) res.setHeader('X-Fallback-Attempts', String(attempt));
+ res.json(buildResponseObject({
+ id: responseId, model: route.modelId, text, toolCalls,
+ promptTokens, completionTokens,
+ }));
- recordRequest(route.platform, route.modelId, route.keyId);
- recordTokens(route.platform, route.modelId, route.keyId, result.usage?.total_tokens ?? 0);
- recordSuccess(route.modelDbId);
- setStickyModel(messages, route.modelDbId, sessionIdHeader);
-
- res.setHeader('X-Routed-Via', `${route.platform}/${route.modelId}`);
- if (attempt > 0) res.setHeader('X-Fallback-Attempts', String(attempt));
- res.json(buildResponseObject({
- id: responseId, model: route.modelId, text, toolCalls,
- promptTokens, completionTokens,
- }));
-
- traceRouteEvent('Responses', {
- event: 'ok',
- requestId: requestGroupId,
- attempt,
- platform: route.platform,
- model: route.modelId,
- latencyMs: Date.now() - start,
- inputTokens: promptTokens,
- outputTokens: completionTokens,
- });
- logRequest(route.platform, route.modelId, route.keyId, 'success', promptTokens, completionTokens, Date.now() - start, null);
- return;
- }
- } catch (err: any) {
+ traceRouteEvent('Responses', {
+ event: 'ok',
+ requestId: requestGroupId,
+ attempt,
+ platform: route.platform,
+ model: route.modelId,
+ latencyMs: Date.now() - start,
+ inputTokens: promptTokens,
+ outputTokens: completionTokens,
+ });
+ logRequest(route.platform, route.modelId, route.keyId, 'success', promptTokens, completionTokens, Date.now() - start, null);
+ return 'done';
+ },
+ logFailure: (route, err, attempt) => {
const latency = Date.now() - start;
const safeError = sanitizeProviderErrorMessage(err.message);
traceRouteEvent('Responses', {
@@ -755,47 +714,32 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
error: safeError,
});
logRequest(route.platform, route.modelId, route.keyId, 'error', estimatedInputTokens, 0, latency, safeError);
-
- // Mid-stream failures can't be retried (bytes already sent) — close cleanly.
- if (stream && streamStarted) {
- sse('response.failed', { response: { id: responseId, object: 'response', status: 'failed', error: { message: `Provider error (${route.displayName}): stream interrupted`, type: 'stream_error' } } });
+ },
+ onFatal: (route, err) => {
+ res.status(502).json({ error: { message: `Provider error (${route.displayName}): ${sanitizeProviderErrorMessage(err.message)}`, type: 'provider_error' } });
+ },
+ onRoutingExhausted: (lastError, routeErr) => {
+ const exhausted = lastError ? exhaustedRetryError(lastError) : null;
+ const status = exhausted?.status ?? routeErr.status ?? 503;
+ const message = exhausted?.message ?? routeErr.message;
+ const type = exhausted?.type ?? 'routing_error';
+ if (streamStarted) {
+ sse('response.failed', { response: { id: responseId, object: 'response', status: 'failed', error: { message, type } } });
res.end();
- return;
+ } else {
+ res.status(status).json({ error: { message, type } });
}
-
- if (isRetryableError(err)) {
- // Model-level 404: rule out the whole model for this request — its
- // other keys would 404 the same way. (PR #111, credits @barbotkonv.)
- if (isModelNotFoundError(err) || isModelAccessForbiddenError(err)) skipModels.add(route.modelDbId);
- skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);
- setCooldown(route.platform, route.modelId, route.keyId, isPaymentRequiredError(err)
- ? PAYMENT_REQUIRED_COOLDOWN_MS
- : getCooldownDurationForLimit(route.platform, route.modelId, route.keyId, { rpd: route.rpdLimit, tpd: route.tpdLimit }));
- // Model-level penalty only when no sibling key can still serve (#454).
- if (!hasOtherUsableKey(route.modelDbId, route.keyId, skipKeys)) recordRateLimitHit(route.modelDbId);
- // Learn a provider-reported ceiling (e.g. a 413 TPM limit) so the next
- // request's pre-check fails over before the 413. Mirrors the chat path.
- learnLimitFromError(route.modelDbId, err);
- lastError = err;
- continue;
+ },
+ onExhausted: (lastError) => {
+ // The streaming skeleton may already be on the wire — close the SSE stream
+ // with a failed event instead of writing JSON onto a committed response.
+ const exhausted = exhaustedRetryError(lastError, MAX_RETRIES);
+ if (streamStarted) {
+ sse('response.failed', { response: { id: responseId, object: 'response', status: 'failed', error: { message: exhausted.message, type: exhausted.type } } });
+ res.end();
+ } else {
+ res.status(exhausted.status).json({ error: { message: exhausted.message, type: exhausted.type } });
}
-
- res.status(502).json({ error: { message: `Provider error (${route.displayName}): ${safeError}`, type: 'provider_error' } });
- return;
- }
- }
-
- // Exhausted all retries. The streaming skeleton may already be on the wire
- // (reachable since empty-completion failover can burn every attempt after
- // streamStarted) — close the SSE stream with a failed event instead of
- // writing JSON onto a committed event-stream response.
- const exhausted = exhaustedRetryError(lastError, MAX_RETRIES);
- if (streamStarted) {
- sse('response.failed', { response: { id: responseId, object: 'response', status: 'failed', error: { message: exhausted.message, type: exhausted.type } } });
- res.end();
- return;
- }
- res.status(exhausted.status).json({
- error: { message: exhausted.message, type: exhausted.type },
+ },
});
});