Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(model-runtime): run Router attempts through one lifecycle and stop on cancel (#22819)

Arvin Xu8b3bd50e6b3a
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.abort.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.abort.test.ts
new file mode 100644
index 00000000000..d01201248c9
--- /dev/null
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.abort.test.ts
@@ -0,0 +1,81 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type {
+ EmbeddingsOptions,
+ EmbeddingsPayload,
+ GenerateObjectOptions,
+ GenerateObjectPayload,
+} from '../../types';
+import type { LobeRuntimeAI } from '../BaseAI';
+import { createRouterRuntime } from './createRuntime';
+
+const createAbortError = () =>
+ Object.assign(new Error('Request was aborted.'), { name: 'AbortError' });
+
+/** Every channel rejects with an abort error, as an SDK does once the request signal fires. */
+const createCancelledRuntime = () => {
+ const servedBy: string[] = [];
+ class MockRuntime implements LobeRuntimeAI {
+ constructor(private readonly options: { channel: string }) {}
+
+ async embeddings(
+ _payload: EmbeddingsPayload,
+ _options?: EmbeddingsOptions,
+ ): Promise<number[][]> {
+ servedBy.push(this.options.channel);
+ throw createAbortError();
+ }
+
+ async generateObject(_payload: GenerateObjectPayload, _options?: GenerateObjectOptions) {
+ servedBy.push(this.options.channel);
+ throw createAbortError();
+ }
+ }
+
+ const onRouteAttempt = vi.fn(async () => {});
+ const Runtime = createRouterRuntime({
+ id: 'test-router',
+ onRouteAttempt,
+ routers: [
+ {
+ apiType: 'openai',
+ models: ['model-x'],
+ options: [
+ { channel: 'channel-a', id: 'channel-a' },
+ { channel: 'channel-b', id: 'channel-b' },
+ ],
+ runtime: MockRuntime as any,
+ },
+ ],
+ });
+
+ return { onRouteAttempt, runtime: new Runtime({ apiKey: 'test' }), servedBy };
+};
+
+describe('createRouterRuntime cancelled requests', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it.each([
+ [
+ 'generateObject',
+ (runtime: any, signal: AbortSignal) =>
+ runtime.generateObject({ messages: [], model: 'model-x', schema: {} }, { signal }),
+ ],
+ [
+ 'embeddings',
+ (runtime: any, signal: AbortSignal) =>
+ runtime.embeddings({ input: 'hi', model: 'model-x' }, { signal }),
+ ],
+ ])('does not try another channel once %s is cancelled', async (_method, call) => {
+ const { onRouteAttempt, runtime, servedBy } = createCancelledRuntime();
+ const controller = new AbortController();
+ controller.abort();
+
+ await expect(call(runtime, controller.signal)).rejects.toMatchObject({ name: 'AbortError' });
+
+ expect(servedBy).toEqual(['channel-a']);
+ expect(onRouteAttempt).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.hookContract.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.hookContract.test.ts
new file mode 100644
index 00000000000..c2657489d94
--- /dev/null
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.hookContract.test.ts
@@ -0,0 +1,100 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { GenerateObjectOptions, GenerateObjectPayload } from '../../types';
+import type { LobeRuntimeAI } from '../BaseAI';
+import { createRouterRuntime } from './createRuntime';
+
+/**
+ * Cloud health handling runs from `onRouteAttempt` only when `completionPending` is
+ * absent, so non-chat methods must report each attempt exactly once without it.
+ */
+const createRuntime = (failingChannels: string[]) => {
+ class MockRuntime implements LobeRuntimeAI {
+ constructor(private readonly options: { channel: string }) {}
+
+ async generateObject(_payload: GenerateObjectPayload, _options?: GenerateObjectOptions) {
+ if (failingChannels.includes(this.options.channel)) throw new Error('channel failed');
+ return { servedBy: this.options.channel };
+ }
+ }
+
+ const hooks = {
+ onRouteAttempt: vi.fn(async () => {}),
+ onRouteSuccess: vi.fn(async () => {}),
+ scheduleRouteRequestSettled: vi.fn(),
+ };
+ const Runtime = createRouterRuntime({
+ id: 'test-router',
+ ...hooks,
+ routers: [
+ {
+ apiType: 'openai',
+ id: 'router-1',
+ models: ['model-x'],
+ options: [
+ { channel: 'channel-a', id: 'channel-a' },
+ { channel: 'channel-b', id: 'channel-b' },
+ ],
+ runtime: MockRuntime as any,
+ },
+ ],
+ });
+
+ return { hooks, runtime: new Runtime({ apiKey: 'test' }) };
+};
+
+const generate = (runtime: any) =>
+ runtime.generateObject({ messages: [], model: 'model-x', schema: {} });
+
+describe('createRouterRuntime non-chat hook contract', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('reports one committed attempt and one route success', async () => {
+ const { hooks, runtime } = createRuntime([]);
+
+ await expect(generate(runtime)).resolves.toEqual({ servedBy: 'channel-a' });
+
+ expect(hooks.onRouteAttempt).toHaveBeenCalledTimes(1);
+ const [attempt] = hooks.onRouteAttempt.mock.calls[0] as any[];
+ expect(attempt).toMatchObject({ channelId: 'channel-a', optionIndex: 0, success: true });
+ expect(attempt).not.toHaveProperty('completionPending');
+ expect(attempt).not.toHaveProperty('routeRequestManaged');
+
+ expect(hooks.onRouteSuccess).toHaveBeenCalledTimes(1);
+ expect(hooks.onRouteSuccess).toHaveBeenCalledWith(
+ expect.objectContaining({ channelId: 'channel-a', method: 'generateObject' }),
+ );
+ expect(hooks.scheduleRouteRequestSettled).not.toHaveBeenCalled();
+ });
+
+ it('reports each fallback attempt once with a shared request and distinct attempt ids', async () => {
+ const { hooks, runtime } = createRuntime(['channel-a']);
+
+ await expect(generate(runtime)).resolves.toEqual({ servedBy: 'channel-b' });
+
+ const attempts = hooks.onRouteAttempt.mock.calls.map(([result]) => result as any);
+ expect(attempts.map(({ channelId, success }) => ({ channelId, success }))).toEqual([
+ { channelId: 'channel-a', success: false },
+ { channelId: 'channel-b', success: true },
+ ]);
+ for (const attempt of attempts) expect(attempt).not.toHaveProperty('completionPending');
+ expect(attempts[0].requestId).toBe(attempts[1].requestId);
+ expect(attempts[0].attemptId).not.toBe(attempts[1].attemptId);
+
+ expect(hooks.onRouteSuccess).toHaveBeenCalledTimes(1);
+ expect(hooks.onRouteSuccess).toHaveBeenCalledWith(
+ expect.objectContaining({ channelId: 'channel-b', firstChannelId: 'channel-a' }),
+ );
+ });
+
+ it('never reports route success when every channel fails', async () => {
+ const { hooks, runtime } = createRuntime(['channel-a', 'channel-b']);
+
+ await expect(generate(runtime)).rejects.toThrow('channel failed');
+
+ expect(hooks.onRouteAttempt).toHaveBeenCalledTimes(2);
+ expect(hooks.onRouteSuccess).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index 7409edc045c..c73c267990b 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -1,7 +1,6 @@
/** @see https://github.com/lobehub/lobe-chat/discussions/6563 */
import type { ModelPricingContext } from '@lobechat/types';
import debug from 'debug';
-import { nanoid } from 'nanoid';
import type {
ASROptions,
@@ -25,13 +24,10 @@ import type {
VideoPollingRoute,
} from '../../types';
import { postProcessModelList } from '../../utils/postProcessModelList';
-import { shouldStopFallbackForError } from '../../utils/routeFallback';
import { getDurationMs } from '../../utils/timing';
import { createVideoWithCompletionMode } from '../../utils/videoCompletionMode';
import type { LobeRuntimeAI } from '../BaseAI';
import type { ApiType } from './apiTypes';
-import { attachRouteAttemptMetadata, validateRouteAttemptContext } from './attemptContext';
-import { classifyAttemptError } from './attemptErrors';
import { withAttemptUsage } from './attemptIdentity';
import { getChatAttemptObservation, observeChatAttempt } from './chatAttempt';
import { createChatAttemptFallbackCheck, resolveHoldReasoning } from './chatFallbackHooks';
@@ -39,7 +35,7 @@ import type { ChatStreamFallbackAttempt } from './chatStreamFallback';
import { createChatStreamFallbackResponse } from './chatStreamFallback';
import { runDecision } from './decisionRuntime';
import { createRuntimeFromOption } from './optionRuntime';
-import type { RouteAttemptResult, RouteAttemptStart } from './routeAttempt';
+import type { RouteAttemptStart } from './routeAttempt';
import { createRouteRequestTasks } from './routeRequestTasks';
import type {
CreateRouterRuntimeOptions,
@@ -47,6 +43,7 @@ import type {
RouterInstance,
Routers,
} from './routerOptions';
+import { createRouteRun } from './routeRun';
import {
normalizeRouterOptions,
resolveMatchedRouter,
@@ -143,85 +140,31 @@ export const createRouterRuntime = ({
options: ChatMethodOptions | undefined,
routeContext: RouteAttemptContext,
): Promise<Response> {
- const requestId = nanoid();
- const { metadata, toolsCount, user } = routeContext;
const { matchedRouter, routerOptions } = await selectRouteOptions(
this.deps,
payload.model,
routeContext,
);
- const firstChannelId = routerOptions[0]?.id;
- const weighted = routerOptions.some((option) => option.weight !== undefined);
const routeTasks = params.scheduleRouteRequestSettled
? await createRouteRequestTasks(params.scheduleRouteRequestSettled)
: undefined;
-
- const reportReturnedAttempt = (
- attempt: RouteAttemptStart,
- result: Partial<RouteAttemptResult> & Pick<RouteAttemptResult, 'durationMs' | 'success'>,
- ) => {
- if (!params.onRouteAttempt) return;
- try {
- const task = params.onRouteAttempt({ ...attempt, ...result } as RouteAttemptResult);
- if (routeTasks) routeTasks.track(task);
- else task.catch((error) => log('onRouteAttempt callback error: %O', error));
- } catch (error) {
- log('onRouteAttempt callback error: %O', error);
- }
- };
-
- const shouldContinueAfterRequestError = async (error: unknown, optionIndex: number) => {
- if (options?.signal?.aborted) return false;
- if (shouldStopFallbackForError(error)) return false;
-
- try {
- return !(await params.shouldStopFallback?.({
- error,
- metadata,
- model: payload.model,
- optionIndex,
- }));
- } catch (fallbackError) {
- log('shouldStopFallback callback error: %O', fallbackError);
- return true;
- }
- };
+ const run = createRouteRun({
+ deps: this.deps,
+ matchedRouter,
+ model: payload.model,
+ providerId: id,
+ reportRouteRequestManaged: true,
+ routeContext,
+ routerOptions,
+ routeTasks,
+ signal: options?.signal,
+ });
const holdReasoning = await resolveHoldReasoning(params.isImageOutputModel, payload.model);
const startAttempt = async (optionIndex: number): Promise<ChatStreamFallbackAttempt> => {
- const optionItem = routerOptions[optionIndex];
- const {
- channelId,
- id: resolvedApiType,
- remark,
- runtime,
- } = await createRuntimeFromOption(this.deps, matchedRouter, optionItem);
- const routeAttemptUserId = validateRouteAttemptContext(this.deps, {
- apiType: resolvedApiType,
- channelId,
- metadata,
- method: routeContext.method,
- model: payload.model,
- routerId: matchedRouter.id,
- toolsCount,
- user,
- });
- const attempt: RouteAttemptStart = {
- apiType: resolvedApiType,
- attemptId: nanoid(),
- channelId,
- metadata: metadata ? { ...metadata } : undefined,
- model: payload.model,
- optionIndex,
- providerId: id,
- remark,
- requestId,
- routeRequestManaged: Boolean(routeTasks),
- routerId: matchedRouter.id,
- startedAt: Date.now(),
- userId: routeAttemptUserId,
- };
+ const prepared = await run.prepareAttempt(optionIndex);
+ const { attempt, runtime } = prepared;
try {
const response = await observeChatAttempt(
@@ -237,24 +180,8 @@ export const createRouterRuntime = ({
{ deferCallbacks: true, holdReasoning },
);
const durationMs = Date.now() - attempt.startedAt;
- reportReturnedAttempt(attempt, {
- completionPending: true,
- durationMs,
- success: true,
- });
- attachRouteAttemptMetadata(this.deps, metadata, {
- apiType: resolvedApiType,
- attemptId: attempt.attemptId,
- channelId,
- completionPending: true,
- durationMs,
- optionIndex,
- providerId: id,
- requestId,
- routerId: matchedRouter.id,
- success: true,
- totalOptions: routerOptions.length,
- });
+ run.reportAttempt(attempt, { completionPending: true, durationMs, success: true });
+ run.attachSuccessMetadata(prepared, { completionPending: true, durationMs });
const observation = getChatAttemptObservation(response);
if (!observation) throw new Error('Missing chat attempt observation');
@@ -262,52 +189,23 @@ export const createRouterRuntime = ({
return {
index: optionIndex,
observation,
- onCompleted: async () => {
- if (!params.onRouteSuccess) return;
-
- try {
- /** Report failures here so the request tracker only waits for the handled task. */
- const task = Promise.resolve(
- params.onRouteSuccess({
- channelId,
- channelWeight: optionItem.weight,
- firstChannelId,
- method: routeContext.method,
- model: payload.model,
- routerId: matchedRouter.id,
- routeRequestManaged: Boolean(routeTasks),
- trackDeferredWork: routeTasks?.track,
- userId: routeAttemptUserId,
- weighted,
- }),
- ).catch((error) => {
- console.error('[RouterRuntime] onRouteSuccess callback failed:', error);
- });
- routeTasks?.track(task);
- await task;
- } catch (error) {
- // Affinity storage must not turn a successful upstream response into a fallback.
- console.error('[RouterRuntime] onRouteSuccess callback failed:', error);
- }
- },
+ onCompleted: () =>
+ run.notifyRouteSuccess(prepared, {
+ routeRequestManaged: Boolean(routeTasks),
+ trackDeferredWork: routeTasks?.track,
+ }),
reader: response.body?.getReader(),
response,
};
} catch (error) {
- const { nonRetryable, nonRetryableReason } = classifyAttemptError(error);
- reportReturnedAttempt(attempt, {
- // Defer cancellation health handling to the terminal outcome, which intentionally ignores it.
+ // Defer cancellation health handling to the terminal outcome, which intentionally ignores it.
+ run.reportFailure(prepared, error, {
completionPending: options?.signal?.aborted ?? false,
- durationMs: Date.now() - attempt.startedAt,
- error,
- nonRetryable,
- nonRetryableReason,
- success: false,
});
if (
optionIndex + 1 < routerOptions.length &&
- (await shouldContinueAfterRequestError(error, optionIndex))
+ (await run.shouldContinueAfterError(error, optionIndex))
) {
return startAttempt(optionIndex + 1);
}
@@ -328,22 +226,30 @@ export const createRouterRuntime = ({
}
}
+ /** Try channels in order; an attempt commits as soon as its method returns. */
private async runWithFallback<T>(
model: string,
requestHandler: (runtime: LobeRuntimeAI, attempt: RouteAttemptStart) => Promise<T>,
routeContext: RouteAttemptContext,
+ signal?: AbortSignal,
): Promise<T> {
const totalStartedAt = Date.now();
- const requestId = nanoid();
- const { metadata, toolsCount, user } = routeContext;
+ const { metadata } = routeContext;
const { matchedRouter, routerOptions } = await selectRouteOptions(
this.deps,
model,
routeContext,
);
const totalOptions = routerOptions.length;
- const firstChannelId = routerOptions[0]?.id;
- const weighted = routerOptions.some((option) => option.weight !== undefined);
+ const run = createRouteRun({
+ deps: this.deps,
+ matchedRouter,
+ model,
+ providerId: id,
+ routeContext,
+ routerOptions,
+ signal,
+ });
this.trace(
'runWithFallback start model=%s routerId=%s apiType=%s options=%d traceId=%s',
@@ -363,41 +269,11 @@ export const createRouterRuntime = ({
let lastError: unknown;
- for (const [index, optionItem] of routerOptions.entries()) {
+ for (let index = 0; index < totalOptions; index += 1) {
const attempt = index + 1;
const startTime = Date.now();
- const {
- channelId,
- id: resolvedApiType,
- remark,
- runtime,
- } = await createRuntimeFromOption(this.deps, matchedRouter, optionItem);
- const routeAttemptUserId = validateRouteAttemptContext(this.deps, {
- apiType: resolvedApiType,
- channelId,
- metadata,
- method: routeContext.method,
- model,
- routerId: matchedRouter.id,
- toolsCount,
- user,
- });
-
- const attemptContext: RouteAttemptStart = {
- apiType: resolvedApiType,
- attemptId: nanoid(),
- channelId,
- metadata: metadata ? { ...metadata } : undefined,
- model,
- optionIndex: index,
- providerId: id,
- remark,
- requestId,
- routerId: matchedRouter.id,
- // Exclude lazy runtime construction from provider performance measurements.
- startedAt: Date.now(),
- userId: routeAttemptUserId,
- };
+ const prepared = await run.prepareAttempt(index);
+ const { apiType: resolvedApiType, channelId, remark, runtime } = prepared;
try {
this.trace(
@@ -410,7 +286,7 @@ export const createRouterRuntime = ({
resolvedApiType,
metadata?.traceId,
);
- const result = await requestHandler(runtime, attemptContext);
+ const result = await requestHandler(runtime, prepared.attempt);
this.trace(
'attempt request success model=%s attempt=%d/%d routerId=%s channelId=%s apiType=%s durationMs=%d totalMs=%d traceId=%s',
model,
@@ -444,54 +320,13 @@ export const createRouterRuntime = ({
);
}
- if (params.onRouteSuccess) {
- try {
- await params.onRouteSuccess({
- channelId,
- channelWeight: optionItem.weight,
- firstChannelId,
- method: routeContext.method,
- model,
- routerId: matchedRouter.id,
- userId: routeAttemptUserId,
- weighted,
- });
- } catch (error) {
- // Affinity storage must not turn a successful upstream response into a fallback.
- console.error('[RouterRuntime] onRouteSuccess callback failed:', error);
- }
- }
-
- params
- .onRouteAttempt?.({
- ...attemptContext,
- apiType: resolvedApiType,
- channelId,
- durationMs: Date.now() - attemptContext.startedAt,
- metadata: attemptContext.metadata,
- model,
- optionIndex: index,
- providerId: id,
- remark,
- routerId: matchedRouter.id,
- success: true,
- userId: routeAttemptUserId,
- })
- .catch((e) => {
- log('onRouteAttempt callback error: %O', e);
- });
-
- attachRouteAttemptMetadata(this.deps, metadata, {
- apiType: resolvedApiType,
- attemptId: attemptContext.attemptId,
- channelId,
- durationMs: Date.now() - attemptContext.startedAt,
- optionIndex: index,
- providerId: id,
- requestId,
- routerId: matchedRouter.id,
+ await run.notifyRouteSuccess(prepared);
+ run.reportAttempt(prepared.attempt, {
+ durationMs: Date.now() - prepared.attempt.startedAt,
success: true,
- totalOptions,
+ });
+ run.attachSuccessMetadata(prepared, {
+ durationMs: Date.now() - prepared.attempt.startedAt,
});
return result;
@@ -510,64 +345,9 @@ export const createRouterRuntime = ({
metadata?.traceId,
);
- const { nonRetryable: shouldStopFallback, nonRetryableReason } =
- classifyAttemptError(error);
-
- params
- .onRouteAttempt?.({
- ...attemptContext,
- apiType: resolvedApiType,
- channelId,
- durationMs: Date.now() - attemptContext.startedAt,
- error,
- metadata: attemptContext.metadata,
- model,
- nonRetryable: shouldStopFallback,
- nonRetryableReason,
- optionIndex: index,
- providerId: id,
- remark,
- routerId: matchedRouter.id,
- success: false,
- userId: routeAttemptUserId,
- })
- .catch((e) => {
- log('onRouteAttempt callback error: %O', e);
- });
-
- if (shouldStopFallback) {
- throw error;
- }
-
- try {
- const shouldStopStartedAt = Date.now();
- const shouldStopFallback = await params.shouldStopFallback?.({
- error,
- metadata,
- model,
- optionIndex: index,
- });
-
- this.trace(
- 'shouldStopFallback done model=%s attempt=%d/%d durationMs=%d shouldStop=%s traceId=%s',
- model,
- attempt,
- totalOptions,
- getDurationMs(shouldStopStartedAt),
- shouldStopFallback,
- metadata?.traceId,
- );
+ run.reportFailure(prepared, error);
- if (shouldStopFallback) {
- throw error;
- }
- } catch (fallbackError) {
- if (fallbackError === error) {
- throw error;
- }
-
- log('shouldStopFallback callback error: %O', fallbackError);
- }
+ if (!(await run.shouldContinueAfterError(error, index))) throw error;
if (attempt < totalOptions) {
log(
@@ -669,6 +449,7 @@ export const createRouterRuntime = ({
toolsCount: payload.tools?.length ?? 0,
user: options?.user,
},
+ options?.signal,
);
} catch (e) {
if (params.chatCompletion?.handleError) {
@@ -770,6 +551,7 @@ export const createRouterRuntime = ({
toolsCount: payload.tools?.length ?? 0,
user: options?.user,
},
+ options?.signal,
);
}
@@ -783,6 +565,7 @@ export const createRouterRuntime = ({
pricingContext: options?.pricingContext,
user: options?.user,
},
+ options?.signal,
);
}
@@ -796,6 +579,7 @@ export const createRouterRuntime = ({
pricingContext: options?.pricingContext,
user: options?.user,
},
+ options?.signal,
);
}
@@ -804,6 +588,7 @@ export const createRouterRuntime = ({
payload.model,
(runtime, attempt) => runtime.transcribe!(payload, withAttemptUsage(options, attempt)),
{ metadata: options?.metadata, method: 'transcribe', user: options?.user },
+ options?.signal,
);
}
@@ -820,6 +605,7 @@ export const createRouterRuntime = ({
pricingContext: options?.pricingContext,
user: options?.user,
},
+ options?.signal,
);
}
};
diff --git a/packages/model-runtime/src/core/RouterRuntime/routeRequestTasks.ts b/packages/model-runtime/src/core/RouterRuntime/routeRequestTasks.ts
index 51bc2ff7f46..c0c24118fe8 100644
--- a/packages/model-runtime/src/core/RouterRuntime/routeRequestTasks.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/routeRequestTasks.ts
@@ -1,3 +1,5 @@
+export type RouteRequestTasks = NonNullable<Awaited<ReturnType<typeof createRouteRequestTasks>>>;
+
/** Keep request-scoped background work alive until the stream and its callbacks settle. */
export const createRouteRequestTasks = async (
schedule: (settled: Promise<void>) => void | Promise<void>,
diff --git a/packages/model-runtime/src/core/RouterRuntime/routeRun.ts b/packages/model-runtime/src/core/RouterRuntime/routeRun.ts
new file mode 100644
index 00000000000..b62a14abffc
--- /dev/null
+++ b/packages/model-runtime/src/core/RouterRuntime/routeRun.ts
@@ -0,0 +1,221 @@
+import debug from 'debug';
+import { nanoid } from 'nanoid';
+
+import { getDurationMs } from '../../utils/timing';
+import type { LobeRuntimeAI } from '../BaseAI';
+import type { ApiType } from './apiTypes';
+import { attachRouteAttemptMetadata, validateRouteAttemptContext } from './attemptContext';
+import { classifyAttemptError } from './attemptErrors';
+import { createRuntimeFromOption } from './optionRuntime';
+import type { RouteAttemptResult, RouteAttemptStart } from './routeAttempt';
+import type { RouteRequestTasks } from './routeRequestTasks';
+import type { RouterInstance, RouterOptionItem, RouteSuccessParams } from './routerOptions';
+import type { RouteAttemptContext, RouterRuntimeDeps } from './routeSelection';
+
+const log = debug('lobe-model-runtime:router-runtime');
+
+export interface PreparedRouteAttempt {
+ apiType: ApiType;
+ attempt: RouteAttemptStart;
+ channelId?: string;
+ optionItem: RouterOptionItem;
+ remark?: string;
+ runtime: LobeRuntimeAI;
+ userId?: string;
+}
+
+interface CreateRouteRunParams {
+ deps: RouterRuntimeDeps;
+ matchedRouter: RouterInstance;
+ model: string;
+ /** The router's own id, reported as `providerId` on every attempt. */
+ providerId: string;
+ /** Always report `routeRequestManaged` on attempts, `false` when no task tracks the request. */
+ reportRouteRequestManaged?: boolean;
+ routeContext: RouteAttemptContext;
+ routerOptions: RouterOptionItem[];
+ /** Request-scoped task tracking for hook work that must finish with the request. */
+ routeTasks?: RouteRequestTasks;
+ signal?: AbortSignal;
+}
+
+/**
+ * The lifecycle shared by every attempt of one routed request: preparing a channel's
+ * runtime, reporting the attempt, deciding whether a failure may fall back to the next
+ * channel, and reporting the route that served it. Callers decide when an attempt commits.
+ */
+export const createRouteRun = ({
+ deps,
+ matchedRouter,
+ model,
+ providerId,
+ reportRouteRequestManaged,
+ routeContext,
+ routerOptions,
+ routeTasks,
+ signal,
+}: CreateRouteRunParams) => {
+ const hooks = deps.params;
+ const requestId = nanoid();
+ const { metadata, toolsCount, user } = routeContext;
+ const firstChannelId = routerOptions[0]?.id;
+ const weighted = routerOptions.some((option) => option.weight !== undefined);
+
+ const prepareAttempt = async (optionIndex: number): Promise<PreparedRouteAttempt> => {
+ const optionItem = routerOptions[optionIndex];
+ const {
+ channelId,
+ id: apiType,
+ remark,
+ runtime,
+ } = await createRuntimeFromOption(deps, matchedRouter, optionItem);
+ const userId = validateRouteAttemptContext(deps, {
+ apiType,
+ channelId,
+ metadata,
+ method: routeContext.method,
+ model,
+ routerId: matchedRouter.id,
+ toolsCount,
+ user,
+ });
+ const attempt: RouteAttemptStart = {
+ apiType,
+ attemptId: nanoid(),
+ channelId,
+ metadata: metadata ? { ...metadata } : undefined,
+ model,
+ optionIndex,
+ providerId,
+ remark,
+ requestId,
+ ...(reportRouteRequestManaged ? { routeRequestManaged: Boolean(routeTasks) } : {}),
+ routerId: matchedRouter.id,
+ // Exclude lazy runtime construction from provider performance measurements.
+ startedAt: Date.now(),
+ userId,
+ };
+
+ return { apiType, attempt, channelId, optionItem, remark, runtime, userId };
+ };
+
+ const reportAttempt = (
+ attempt: RouteAttemptStart,
+ result: Partial<RouteAttemptResult> & Pick<RouteAttemptResult, 'durationMs' | 'success'>,
+ ) => {
+ if (!hooks.onRouteAttempt) return;
+ try {
+ const task = hooks.onRouteAttempt({ ...attempt, ...result } as RouteAttemptResult);
+ if (routeTasks) routeTasks.track(task);
+ else task.catch((error) => log('onRouteAttempt callback error: %O', error));
+ } catch (error) {
+ log('onRouteAttempt callback error: %O', error);
+ }
+ };
+
+ const reportFailure = (
+ { attempt }: PreparedRouteAttempt,
+ error: unknown,
+ { completionPending }: { completionPending?: boolean } = {},
+ ) => {
+ const { nonRetryable, nonRetryableReason } = classifyAttemptError(error);
+ reportAttempt(attempt, {
+ ...(completionPending === undefined ? {} : { completionPending }),
+ durationMs: Date.now() - attempt.startedAt,
+ error,
+ nonRetryable,
+ nonRetryableReason,
+ success: false,
+ });
+ };
+
+ /** Whether a failed attempt may hand the request to the next channel. */
+ const shouldContinueAfterError = async (error: unknown, optionIndex: number) => {
+ // A cancelled request must not be replayed on the remaining channels.
+ if (signal?.aborted) return false;
+ if (classifyAttemptError(error).nonRetryable) return false;
+
+ const startedAt = Date.now();
+ try {
+ const shouldStop = await hooks.shouldStopFallback?.({
+ error,
+ metadata,
+ model,
+ optionIndex,
+ });
+ deps.trace(
+ 'shouldStopFallback done model=%s attempt=%d/%d durationMs=%d shouldStop=%s traceId=%s',
+ model,
+ optionIndex + 1,
+ routerOptions.length,
+ getDurationMs(startedAt),
+ shouldStop,
+ metadata?.traceId,
+ );
+ return !shouldStop;
+ } catch (fallbackError) {
+ log('shouldStopFallback callback error: %O', fallbackError);
+ return true;
+ }
+ };
+
+ const attachSuccessMetadata = (
+ { apiType, attempt, channelId }: PreparedRouteAttempt,
+ { completionPending, durationMs }: { completionPending?: boolean; durationMs: number },
+ ) =>
+ attachRouteAttemptMetadata(deps, metadata, {
+ apiType,
+ attemptId: attempt.attemptId,
+ channelId,
+ ...(completionPending ? { completionPending } : {}),
+ durationMs,
+ optionIndex: attempt.optionIndex,
+ providerId,
+ requestId,
+ routerId: matchedRouter.id,
+ success: true,
+ totalOptions: routerOptions.length,
+ });
+
+ /** Report the channel that served the request. Never turns a success into a failure. */
+ const notifyRouteSuccess = async (
+ { channelId, optionItem, userId }: PreparedRouteAttempt,
+ extra: Pick<RouteSuccessParams, 'routeRequestManaged' | 'trackDeferredWork'> = {},
+ ) => {
+ if (!hooks.onRouteSuccess) return;
+
+ try {
+ /** Report failures here so the request tracker only waits for the handled task. */
+ const task = Promise.resolve(
+ hooks.onRouteSuccess({
+ channelId,
+ channelWeight: optionItem.weight,
+ firstChannelId,
+ method: routeContext.method,
+ model,
+ routerId: matchedRouter.id,
+ ...extra,
+ userId,
+ weighted,
+ }),
+ ).catch((error) => {
+ // Affinity storage must not turn a successful upstream response into a fallback.
+ console.error('[RouterRuntime] onRouteSuccess callback failed:', error);
+ });
+ routeTasks?.track(task);
+ await task;
+ } catch (error) {
+ console.error('[RouterRuntime] onRouteSuccess callback failed:', error);
+ }
+ };
+
+ return {
+ attachSuccessMetadata,
+ notifyRouteSuccess,
+ prepareAttempt,
+ reportAttempt,
+ reportFailure,
+ requestId,
+ shouldContinueAfterError,
+ };
+};