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.

✨ feat: observe routed chat stream outcomes (#19729)

YuTengjinga406e840ecbd
diff --git a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts
new file mode 100644
index 00000000000..c8dbaffb908
--- /dev/null
+++ b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts
@@ -0,0 +1,324 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { ChatMethodOptions, ChatStreamCallbacks, OnFinishData } from '../../types';
+import { observeChatAttempt } from './chatAttempt';
+
+describe('observeChatAttempt', () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ const attempt = {
+ apiType: 'openai',
+ attemptId: 'attempt-1',
+ model: 'model',
+ optionIndex: 0,
+ providerId: 'test',
+ requestId: 'request-1',
+ startedAt: 1000,
+ };
+
+ it('shares completion metrics with final callbacks without including callback work', async () => {
+ let now = 1000;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ const completion = vi.fn((_data: OnFinishData) => {
+ now = 5000;
+ });
+ const final = vi.fn();
+ const finished = vi.fn();
+ const response = await observeChatAttempt(
+ async ({ callback }) => {
+ now = 1200;
+ await callback?.onText?.('first');
+ now = 2200;
+ await callback?.onText?.('last');
+ now = 2300;
+ const data = {
+ speed: { duration: 1000, latency: 1300, tps: 100, ttft: 200 },
+ text: 'firstlast',
+ usage: { cost: 0.001, totalOutputTokens: 100 },
+ };
+ await callback?.onCompletion?.(data);
+ await callback?.onFinal?.(data);
+ return new Response('done');
+ },
+ { callback: { onCompletion: completion, onFinal: final } },
+ attempt,
+ true,
+ finished,
+ );
+ await response.text();
+ expect(completion.mock.calls[0][0]).toEqual(final.mock.calls[0][0]);
+ expect(final.mock.calls[0][0]).toMatchObject({
+ routeAttempt: { attemptId: 'attempt-1', requestId: 'request-1' },
+ speed: { ttft: 200, duration: 1000, latency: 1300, tps: 100 },
+ });
+ expect(finished).toHaveBeenCalledTimes(1);
+ expect(finished.mock.calls[0][0].usage).toMatchObject({
+ cost: 0.001,
+ totalOutputTokens: 100,
+ });
+ });
+
+ it('retains reported input usage when the caller cancels before final usage', async () => {
+ let now = 1000;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ const finished = vi.fn();
+ const response = await observeChatAttempt(
+ async ({ callback }) => {
+ await callback?.onUsage?.({
+ totalInputTokens: 100,
+ inputCachedTokens: 0,
+ totalOutputTokens: 5,
+ });
+ await callback?.onThinking?.('reason');
+ now = 2000;
+ await callback?.onText?.('partial answer');
+ return new Response(new ReadableStream());
+ },
+ undefined,
+ attempt,
+ true,
+ finished,
+ );
+ await response.body!.cancel();
+ expect(finished.mock.calls[0][0]).toMatchObject({
+ outcome: 'cancelled',
+ usage: { totalInputTokens: 100, inputCachedTokens: 0 },
+ });
+ expect(finished.mock.calls[0][0].usage.totalOutputTokens).toBe(5);
+ expect(finished.mock.calls[0][0].speed).toBeUndefined();
+ });
+
+ it('leaves buffered response speed unknown and isolates observer failures', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const finished = vi.fn().mockRejectedValue(new Error('observer unavailable'));
+ const response = await observeChatAttempt(
+ async ({ callback }) => {
+ await callback?.onText?.('answer');
+ await callback?.onFinal?.({ text: 'answer', usage: { totalOutputTokens: 20 } });
+ return new Response('answer');
+ },
+ undefined,
+ attempt,
+ false,
+ finished,
+ );
+ expect(await response.text()).toBe('answer');
+ expect(finished.mock.calls[0][0].speed).toBeUndefined();
+ expect(finished).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not block response completion on a pending observer', async () => {
+ let releaseObserver!: () => void;
+ const finished = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ releaseObserver = resolve;
+ }),
+ );
+ const response = await observeChatAttempt(
+ async ({ callback }) => {
+ await callback?.onText?.('answer');
+ await callback?.onFinal?.({ text: 'answer' });
+ return new Response('answer');
+ },
+ undefined,
+ attempt,
+ true,
+ finished,
+ );
+ const responseText = response.text();
+
+ const outcome = await Promise.race([
+ responseText.then(() => 'completed'),
+ new Promise((resolve) => setTimeout(() => resolve('blocked'), 50)),
+ ]);
+ releaseObserver();
+
+ expect(outcome).toBe('completed');
+ await expect(responseText).resolves.toBe('answer');
+ expect(finished).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ [
+ 'content text',
+ async (callback?: ChatStreamCallbacks) => {
+ await callback?.onContentPart?.({ content: 'answer', partType: 'text' });
+ },
+ ],
+ [
+ 'reasoning text',
+ async (callback?: ChatStreamCallbacks) => {
+ await callback?.onReasoningPart?.({ content: 'reason', partType: 'text' });
+ },
+ ],
+ [
+ 'structured image',
+ async (callback?: ChatStreamCallbacks) => {
+ await callback?.onContentPart?.({
+ content: 'base64-image',
+ mimeType: 'image/png',
+ partType: 'image',
+ });
+ },
+ ],
+ ] as const)('counts %s as a non-empty completion', async (_label, emitPart) => {
+ const finished = vi.fn();
+ const response = await observeChatAttempt(
+ async ({ callback }) => {
+ await emitPart(callback);
+ await callback?.onFinal?.({ text: '' });
+ return new Response('');
+ },
+ undefined,
+ attempt,
+ true,
+ finished,
+ );
+
+ expect(await response.text()).toBe('');
+ expect(finished).toHaveBeenCalledWith(expect.objectContaining({ outcome: 'completed' }));
+ });
+
+ it('adds attempt identity without replacing provider performance', async () => {
+ let now = 1000;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ const finished = vi.fn();
+ const final = vi.fn();
+ const response = await observeChatAttempt(
+ async (options) => {
+ now = 1800;
+ await options.callback?.onFinal?.({
+ speed: { duration: 200, latency: 800, ttft: 300 },
+ text: 'answer',
+ });
+ return new Response('done');
+ },
+ { callback: { onFinal: final } },
+ attempt,
+ true,
+ finished,
+ );
+ await response.text();
+ expect(finished).toHaveBeenCalledTimes(1);
+ expect(finished.mock.calls[0][0]).toMatchObject({
+ ...attempt,
+ outcome: 'completed',
+ speed: { ttft: 300, duration: 200, latency: 800 },
+ });
+ expect(finished.mock.calls[0][0].speed.tps).toBeUndefined();
+ expect(final.mock.calls[0][0].routeAttempt).toEqual({
+ attemptId: 'attempt-1',
+ outcome: 'completed',
+ requestId: 'request-1',
+ });
+ });
+
+ it.each(['error', 'cancel'] as const)(
+ 'records a body %s even when onFinal never runs',
+ async (mode) => {
+ const finished = vi.fn();
+ const cancel = vi.fn();
+ const response = await observeChatAttempt(
+ async () =>
+ new Response(
+ new ReadableStream({
+ cancel,
+ pull(controller) {
+ if (mode === 'error') controller.error(new Error('disconnected'));
+ },
+ }),
+ ),
+ undefined,
+ attempt,
+ true,
+ finished,
+ );
+ if (mode === 'error') await expect(response.text()).rejects.toThrow('disconnected');
+ else await response.body!.cancel();
+ expect(finished).toHaveBeenCalledTimes(1);
+ expect(finished.mock.calls[0][0].outcome).toBe(
+ mode === 'error' ? 'interrupted' : 'cancelled',
+ );
+ if (mode === 'cancel') expect(cancel).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('synthesizes one final callback when the response body fails before provider final', async () => {
+ const upstreamError = new Error('disconnected');
+ const final = vi.fn();
+ const response = await observeChatAttempt(
+ async () =>
+ new Response(
+ new ReadableStream({
+ pull(controller) {
+ controller.error(upstreamError);
+ },
+ }),
+ ),
+ { callback: { onFinal: final } },
+ attempt,
+ true,
+ vi.fn(),
+ );
+
+ await expect(response.text()).rejects.toThrow('disconnected');
+ expect(final).toHaveBeenCalledTimes(1);
+ expect(final).toHaveBeenCalledWith(
+ expect.objectContaining({
+ error: upstreamError,
+ routeAttempt: expect.objectContaining({ outcome: 'interrupted' }),
+ text: '',
+ }),
+ );
+ });
+
+ it('does not turn an error event or abort into a successful completion', async () => {
+ for (const data of [
+ { error: { message: 'failed' }, text: '' },
+ { finishReason: 'abort', text: '' },
+ ]) {
+ const finished = vi.fn();
+ const response = await observeChatAttempt(
+ async ({ callback }) => {
+ await callback?.onFinal?.(data);
+ return new Response('done');
+ },
+ undefined,
+ attempt,
+ true,
+ finished,
+ );
+ await response.text();
+ expect(finished.mock.calls[0][0].outcome).toBe(data.error ? 'interrupted' : 'cancelled');
+ }
+ });
+
+ it('keeps concurrent attempt identities isolated even with shared options', async () => {
+ const finals: OnFinishData[] = [];
+ const options: ChatMethodOptions = {
+ callback: {
+ onFinal: (data) => {
+ finals.push(data);
+ },
+ },
+ };
+ const finished = vi.fn();
+ await Promise.all(
+ ['a', 'b'].map((attemptId) =>
+ observeChatAttempt(
+ async ({ callback }) => {
+ await callback?.onFinal?.({ text: attemptId });
+ return new Response('done');
+ },
+ options,
+ { ...attempt, attemptId },
+ true,
+ finished,
+ ).then((response) => response.text()),
+ ),
+ );
+ expect(finals.map((data) => data.routeAttempt?.attemptId)).toEqual(['a', 'b']);
+ expect(options.metadata).toBeUndefined();
+ });
+});
diff --git a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts
new file mode 100644
index 00000000000..00d6efe201a
--- /dev/null
+++ b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts
@@ -0,0 +1,402 @@
+import type { ModelUsage } from '@lobechat/types';
+import { AgentRuntimeErrorType } from '@lobechat/types';
+
+import { isEmptyModelCompletion, ModelEmptyError } from '../../errors';
+import type { ChatMethodOptions, ChatStreamCallbacks, OnFinishData } from '../../types';
+import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
+import { AgentRuntimeError } from '../../utils/createError';
+import type { RouteAttemptFinished, RouteAttemptOutcome, RouteAttemptStart } from './routeAttempt';
+
+export type { RouteAttemptFinished, RouteAttemptOutcome, RouteAttemptStart } from './routeAttempt';
+
+export interface ChatAttemptObservation {
+ commit: () => Promise<void>;
+ discard: () => void;
+ finished: Promise<RouteAttemptFinished>;
+ hasVisibleOutput: () => boolean;
+}
+
+const observations = new WeakMap<Response, ChatAttemptObservation>();
+
+export const getChatAttemptObservation = (response: Response): ChatAttemptObservation | undefined =>
+ observations.get(response);
+
+const getReasoningContent = (data: OnFinishData | undefined) =>
+ data?.thinking ?? data?.reasoning?.content ?? '';
+
+const createStreamChunkError = (error: unknown, provider: string) =>
+ Object.assign(
+ new Error(error instanceof Error ? error.message : String(error), { cause: error }),
+ AgentRuntimeError.chat({
+ error: {
+ cause: error,
+ message: error instanceof Error ? error.message : String(error),
+ name: 'StreamChunkError',
+ },
+ errorType: AgentRuntimeErrorType.StreamChunkError,
+ provider,
+ }),
+ { name: 'StreamChunkError' },
+ );
+
+/**
+ * Observe the actual response body lifecycle. Terminal callbacks are delayed until
+ * EOF so an upstream disconnect after `onFinal` cannot be reported as completed.
+ * Optional callback deferral lets the router discard an uncommitted attempt before
+ * switching to a fallback channel.
+ */
+export const observeChatAttempt = async (
+ request: (options: ChatMethodOptions) => Promise<Response>,
+ options: ChatMethodOptions | undefined,
+ attempt: RouteAttemptStart,
+ streaming: boolean,
+ onFinished: (result: RouteAttemptFinished) => Promise<void> | void,
+ observerOptions?: { deferCallbacks?: boolean },
+): Promise<Response> => {
+ const attemptDiagnostics: ModelRuntimeDiagnostics = {};
+ let committed = !observerOptions?.deferCallbacks;
+ let discarded = false;
+ let durationMs: number | undefined;
+ let finalResult: RouteAttemptFinished | undefined;
+ let observedUsage: ModelUsage | undefined;
+ let streamError: unknown;
+ let visibleOutput = false;
+ let imageCount = 0;
+ let toolCallCount = 0;
+ let grounding: unknown;
+ let content = '';
+ let reasoning = '';
+ let latestFinishData: OnFinishData | undefined;
+ let receivedFinalCallback = false;
+ const pendingCallbacks: Array<() => Promise<void>> = [];
+ const terminalCallbacks: Array<{
+ callback: ((data: OnFinishData) => Promise<void> | void) | undefined;
+ data: OnFinishData;
+ }> = [];
+ let resolveFinished!: (result: RouteAttemptFinished) => void;
+ const finished = new Promise<RouteAttemptFinished>((resolve) => {
+ resolveFinished = resolve;
+ });
+ const callback = options?.callback;
+
+ const publishAttemptDiagnostics = () => {
+ if (!options?.diagnostics) return;
+
+ options.diagnostics.providerRequest = attemptDiagnostics.providerRequest;
+ options.diagnostics.providerResponse = attemptDiagnostics.providerResponse;
+ };
+
+ const runOrBuffer = async (callbackTask: () => Promise<void>) => {
+ if (discarded) return;
+ if (committed) await callbackTask();
+ else pendingCallbacks.push(callbackTask);
+ };
+
+ const flushTerminalCallbacks = async () => {
+ if (!committed || discarded || !finalResult) return;
+
+ for (const terminal of terminalCallbacks.splice(0)) {
+ if (!terminal.callback) continue;
+ await terminal.callback({
+ ...terminal.data,
+ routeAttempt: {
+ attemptId: attempt.attemptId,
+ outcome: finalResult.outcome,
+ requestId: attempt.requestId,
+ },
+ speed: finalResult.speed ? { ...finalResult.speed } : undefined,
+ });
+ }
+ };
+
+ const commit = async () => {
+ if (discarded) return;
+ if (!committed) {
+ committed = true;
+ for (const callbackTask of pendingCallbacks.splice(0)) await callbackTask();
+ }
+ publishAttemptDiagnostics();
+ await flushTerminalCallbacks();
+ };
+
+ const discard = () => {
+ discarded = true;
+ pendingCallbacks.length = 0;
+ terminalCallbacks.length = 0;
+ };
+
+ const report = async (result: RouteAttemptFinished) => {
+ try {
+ await onFinished(result);
+ } catch (error) {
+ // Observability failures must never retry a provider call or suppress its output.
+ console.error('[RouterRuntime] Failed to report attempt completion:', error);
+ }
+ };
+
+ const finish = async (outcome: RouteAttemptOutcome, error?: unknown) => {
+ if (finalResult) return finalResult;
+
+ const finishData = latestFinishData;
+ const completedAt = Date.now();
+ const usage =
+ finishData?.usage || observedUsage ? { ...observedUsage, ...finishData?.usage } : undefined;
+ const finalError = error ?? streamError ?? finishData?.error;
+ if (outcome !== 'failed' && !receivedFinalCallback) {
+ terminalCallbacks.push({
+ callback: callback?.onFinal,
+ data: {
+ error: finalError,
+ finishReason: outcome === 'cancelled' ? 'abort' : finishData?.finishReason,
+ grounding: finishData?.grounding ?? grounding,
+ reasoning: finishData?.reasoning,
+ text: finishData?.text ?? content,
+ thinking: finishData?.thinking ?? reasoning,
+ toolsCalling: finishData?.toolsCalling,
+ usage,
+ usageMissingDiagnostics: finishData?.usageMissingDiagnostics,
+ },
+ });
+ }
+ finalResult = {
+ ...attempt,
+ completedAt,
+ diagnostics: attemptDiagnostics,
+ durationMs: durationMs ?? completedAt - attempt.startedAt,
+ error: finalError,
+ outcome,
+ speed: finishData?.speed
+ ? {
+ ...finishData.speed,
+ ...(outcome !== 'completed' && { tps: undefined }),
+ }
+ : undefined,
+ streaming,
+ success: outcome === 'completed',
+ usage,
+ };
+ options?.signal?.removeEventListener('abort', onAbort);
+ resolveFinished(finalResult);
+ void report(finalResult);
+ await flushTerminalCallbacks();
+ return finalResult;
+ };
+
+ const finishFromEOF = async () => {
+ if (finalResult) return finalResult;
+ if (options?.signal?.aborted || latestFinishData?.finishReason === 'abort') {
+ return finish('cancelled');
+ }
+ if (latestFinishData?.error || streamError) {
+ const error = streamError ?? latestFinishData?.error;
+ return finish(
+ 'interrupted',
+ visibleOutput ? createStreamChunkError(error, attempt.providerId) : error,
+ );
+ }
+ // JSON-mode responses do not emit stream callbacks; reaching body EOF is their terminal success.
+ if (!latestFinishData) return finish(streaming ? 'interrupted' : 'completed');
+
+ const finalContent = content || latestFinishData.text;
+ const finalReasoning = reasoning || getReasoningContent(latestFinishData);
+ const finalToolCallCount = Math.max(latestFinishData.toolsCalling?.length ?? 0, toolCallCount);
+ const empty = isEmptyModelCompletion({
+ content: finalContent,
+ hasGrounding: Boolean(latestFinishData.grounding ?? grounding),
+ imageCount,
+ outputTokens: latestFinishData.usage?.totalOutputTokens ?? observedUsage?.totalOutputTokens,
+ reasoning: finalReasoning,
+ toolCallCount: finalToolCallCount,
+ });
+
+ if (!empty) return finish('completed');
+
+ return finish(
+ 'empty',
+ new ModelEmptyError(undefined, {
+ contentLength: finalContent.length,
+ cost: latestFinishData.usage?.cost,
+ finishReason: latestFinishData.finishReason,
+ imageCount,
+ model: attempt.model,
+ outputTokens: latestFinishData.usage?.totalOutputTokens ?? observedUsage?.totalOutputTokens,
+ provider: attempt.providerId,
+ reasoningLength: finalReasoning.length,
+ toolCallCount: finalToolCallCount,
+ }),
+ );
+ };
+
+ const onAbort = () => {
+ void finish('cancelled');
+ };
+ options?.signal?.addEventListener('abort', onAbort, { once: true });
+
+ const terminalCallback = (
+ terminal: ((data: OnFinishData) => Promise<void> | void) | undefined,
+ data: OnFinishData,
+ ) => {
+ latestFinishData = data;
+ if (data.usage) observedUsage = { ...observedUsage, ...data.usage };
+ toolCallCount = Math.max(toolCallCount, data.toolsCalling?.length ?? 0);
+ grounding ??= data.grounding;
+ if (
+ data.text.trim() ||
+ getReasoningContent(data).trim() ||
+ (data.toolsCalling?.length ?? 0) > 0
+ ) {
+ visibleOutput = true;
+ }
+ terminalCallbacks.push({ callback: terminal, data });
+ };
+
+ const observedCallbacks: ChatStreamCallbacks = {
+ ...callback,
+ onBase64Image: async (data) => {
+ imageCount = Math.max(imageCount, data.images.length);
+ visibleOutput = true;
+ await runOrBuffer(async () => {
+ await callback?.onBase64Image?.(data);
+ });
+ },
+ onCompletion: async (data) => {
+ terminalCallback(callback?.onCompletion, data);
+ },
+ onContentPart: async (data) => {
+ if (data.partType === 'image') imageCount += 1;
+ else content += data.content;
+ if (data.partType === 'image' || data.content.trim()) visibleOutput = true;
+ await runOrBuffer(async () => {
+ await callback?.onContentPart?.(data);
+ });
+ },
+ onError: async (error) => {
+ streamError = error;
+ await runOrBuffer(async () => {
+ await callback?.onError?.(error);
+ });
+ },
+ onFinal: async (data) => {
+ receivedFinalCallback = true;
+ terminalCallback(callback?.onFinal, data);
+ },
+ onGrounding: async (data) => {
+ grounding = data;
+ await runOrBuffer(async () => {
+ await callback?.onGrounding?.(data);
+ });
+ },
+ onReasoningPart: async (data) => {
+ if (data.partType === 'image') imageCount += 1;
+ else reasoning += data.content;
+ if (data.partType === 'image' || data.content.trim()) visibleOutput = true;
+ await runOrBuffer(async () => {
+ await callback?.onReasoningPart?.(data);
+ });
+ },
+ onStart: async () => {
+ await runOrBuffer(async () => {
+ await callback?.onStart?.();
+ });
+ },
+ onText: async (text) => {
+ content += text;
+ if (text.trim()) visibleOutput = true;
+ await runOrBuffer(async () => {
+ await callback?.onText?.(text);
+ });
+ },
+ onThinking: async (text) => {
+ reasoning += text;
+ if (text.trim()) visibleOutput = true;
+ await runOrBuffer(async () => {
+ await callback?.onThinking?.(text);
+ });
+ },
+ onToolsCalling: async (data) => {
+ toolCallCount = Math.max(toolCallCount, data.toolsCalling.length, data.chunk.length);
+ if (toolCallCount > 0) visibleOutput = true;
+ await runOrBuffer(async () => {
+ await callback?.onToolsCalling?.(data);
+ });
+ },
+ onUsage: async (usage) => {
+ observedUsage = { ...observedUsage, ...usage };
+ await runOrBuffer(async () => {
+ await callback?.onUsage?.(usage);
+ });
+ },
+ };
+
+ try {
+ if (options?.signal?.aborted) options.signal.throwIfAborted();
+ const response = await request({
+ ...options,
+ callback: observedCallbacks,
+ diagnostics: attemptDiagnostics,
+ });
+ durationMs = Date.now() - attempt.startedAt;
+
+ const observation: ChatAttemptObservation = {
+ commit,
+ discard,
+ finished,
+ hasVisibleOutput: () => visibleOutput,
+ };
+ observations.set(response, observation);
+
+ if (!response.body) {
+ const result = await finishFromEOF();
+ if (result.outcome === 'empty' && !observerOptions?.deferCallbacks) throw result.error;
+ return response;
+ }
+
+ const reader = response.body.getReader();
+ const observedResponse = new Response(
+ new ReadableStream<Uint8Array>(
+ {
+ async cancel(reason) {
+ await finish('cancelled');
+ if (!observerOptions?.deferCallbacks) await commit();
+ await reader.cancel(reason);
+ },
+ async pull(controller) {
+ try {
+ const { done, value } = await reader.read();
+ if (!done) {
+ controller.enqueue(value);
+ return;
+ }
+
+ const result = await finishFromEOF();
+ if (!observerOptions?.deferCallbacks) await commit();
+ if (result.outcome === 'empty') controller.error(result.error);
+ else controller.close();
+ } catch (error) {
+ const result = await finish(
+ options?.signal?.aborted ? 'cancelled' : 'interrupted',
+ error,
+ );
+ if (!observerOptions?.deferCallbacks) await commit();
+ controller.error(
+ visibleOutput && result.outcome !== 'cancelled'
+ ? createStreamChunkError(error, attempt.providerId)
+ : error,
+ );
+ }
+ },
+ },
+ { highWaterMark: 0 },
+ ),
+ { headers: response.headers, status: response.status, statusText: response.statusText },
+ );
+ observations.set(observedResponse, observation);
+ return observedResponse;
+ } catch (error) {
+ durationMs = Date.now() - attempt.startedAt;
+ const result = await finish(options?.signal?.aborted ? 'cancelled' : 'failed', error);
+ if (observerOptions?.deferCallbacks) discard();
+ else await commit();
+ throw result.error ?? error;
+ }
+};
diff --git a/packages/model-runtime/src/core/RouterRuntime/chatStreamFallback.ts b/packages/model-runtime/src/core/RouterRuntime/chatStreamFallback.ts
new file mode 100644
index 00000000000..521ec5cdd34
--- /dev/null
+++ b/packages/model-runtime/src/core/RouterRuntime/chatStreamFallback.ts
@@ -0,0 +1,149 @@
+import type { ChatAttemptObservation } from './chatAttempt';
+import type { RouteAttemptFinished } from './routeAttempt';
+
+export interface ChatStreamFallbackAttempt {
+ index: number;
+ observation: ChatAttemptObservation;
+ onCompleted?: () => Promise<void>;
+ reader?: ReadableStreamDefaultReader<Uint8Array>;
+ response: Response;
+}
+
+interface CreateChatStreamFallbackResponseOptions {
+ shouldFallback: (result: RouteAttemptFinished) => Promise<boolean>;
+ startAttempt: (index: number) => Promise<ChatStreamFallbackAttempt>;
+ totalAttempts: number;
+}
+
+/**
+ * Keep response bytes and callbacks private until an attempt produces visible
+ * output. A terminal empty or interrupted attempt can then be discarded before
+ * starting the next route without mixing output from two providers.
+ */
+export const createChatStreamFallbackResponse = async ({
+ shouldFallback,
+ startAttempt,
+ totalAttempts,
+}: CreateChatStreamFallbackResponseOptions): Promise<Response> => {
+ let active = await startAttempt(0);
+ const initialResponse = active.response;
+ const responseHeaders = new Headers(initialResponse.headers);
+ responseHeaders.delete('content-length');
+ let bufferedChunks: Uint8Array[] = [];
+ let committed = false;
+
+ const flushBufferedChunks = (controller: ReadableStreamDefaultController<Uint8Array>) => {
+ for (const chunk of bufferedChunks) controller.enqueue(chunk);
+ bufferedChunks = [];
+ };
+
+ const activateNextAttempt = async () => {
+ active.observation.discard();
+ active = await startAttempt(active.index + 1);
+ bufferedChunks = [];
+ committed = false;
+ };
+
+ const shouldFallbackTerminalAttempt = async (result: RouteAttemptFinished) => {
+ if (
+ committed ||
+ active.observation.hasVisibleOutput() ||
+ active.index + 1 >= totalAttempts ||
+ (result.outcome !== 'empty' && result.outcome !== 'interrupted')
+ ) {
+ return false;
+ }
+
+ return shouldFallback(result);
+ };
+
+ const commitTerminalAttempt = async (result: RouteAttemptFinished) => {
+ await active.observation.commit();
+ if (result.outcome === 'completed') await active.onCompleted?.();
+ };
+
+ return new Response(
+ new ReadableStream<Uint8Array>(
+ {
+ async cancel(reason) {
+ await active.reader?.cancel(reason);
+ await active.observation.commit();
+ },
+ async pull(controller) {
+ while (true) {
+ if (!active.reader) {
+ const result = await active.observation.finished;
+ if (await shouldFallbackTerminalAttempt(result)) {
+ await activateNextAttempt();
+ continue;
+ }
+
+ await commitTerminalAttempt(result);
+ if (result.outcome === 'completed') controller.close();
+ else controller.error(result.error ?? new Error(`Chat attempt ${result.outcome}`));
+ return;
+ }
+
+ try {
+ const { done, value } = await active.reader.read();
+ if (!done) {
+ if (committed) {
+ controller.enqueue(value);
+ return;
+ }
+
+ bufferedChunks.push(value);
+ if (active.observation.hasVisibleOutput()) {
+ committed = true;
+ await active.observation.commit();
+ flushBufferedChunks(controller);
+ return;
+ }
+ continue;
+ }
+
+ const result = await active.observation.finished;
+ if (await shouldFallbackTerminalAttempt(result)) {
+ await activateNextAttempt();
+ continue;
+ }
+
+ await commitTerminalAttempt(result);
+ if (result.outcome === 'completed') {
+ flushBufferedChunks(controller);
+ controller.close();
+ } else {
+ controller.error(result.error ?? new Error(`Chat attempt ${result.outcome}`));
+ }
+ return;
+ } catch (error) {
+ // A deferred consumer callback can reject before EOF. Cancelling
+ // first lets the observer reach a terminal state without waiting
+ // forever inside the current pull.
+ try {
+ await active.reader.cancel(error);
+ } catch {
+ // The reader may already be errored and the observer terminal.
+ }
+ const result = await active.observation.finished;
+ if (await shouldFallbackTerminalAttempt(result)) {
+ await activateNextAttempt();
+ continue;
+ }
+
+ await commitTerminalAttempt(result);
+ controller.error(error);
+ return;
+ }
+ }
+ },
+ },
+ { highWaterMark: 0 },
+ ),
+ {
+ headers: responseHeaders,
+ status: initialResponse.status,
+ statusText: initialResponse.statusText,
+ },
+ );
+};
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
index 22f79c150e0..6adbb47a310 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
@@ -2,6 +2,8 @@ import { AgentRuntimeErrorType, RequestTrigger } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LobeVertexAI } from '../../providers/vertexai';
+import type { ChatMethodOptions, OnFinishData } from '../../types';
+import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
import { getRuntimeSignatureScopeSource } from '../../utils/signatureScope';
import type { LobeRuntimeAI } from '../BaseAI';
import { createRouterRuntime } from './createRuntime';
@@ -720,6 +722,504 @@ describe('createRouterRuntime', () => {
});
describe('fallback mechanism', () => {
+ const consumeResponse = async (response: Response) => {
+ const reader = response.body!.getReader();
+ let text = '';
+ const decoder = new TextDecoder();
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) return text + decoder.decode();
+ text += decoder.decode(value, { stream: true });
+ }
+ };
+
+ const createChatResponse = (
+ options: ChatMethodOptions | undefined,
+ config: {
+ bodyError?: unknown;
+ final?: OnFinishData;
+ image?: boolean;
+ text?: string;
+ thinking?: string;
+ toolCall?: boolean;
+ },
+ ) =>
+ new Response(
+ new ReadableStream({
+ async start(controller) {
+ if (config.text !== undefined) {
+ await options?.callback?.onText?.(config.text);
+ controller.enqueue(new TextEncoder().encode(config.text));
+ }
+ if (config.thinking !== undefined) {
+ await options?.callback?.onThinking?.(config.thinking);
+ controller.enqueue(new TextEncoder().encode(config.thinking));
+ }
+ if (config.image) {
+ const image = { data: 'data:image/png;base64,AA==', id: 'image-1' };
+ await options?.callback?.onBase64Image?.({ image, images: [image] });
+ controller.enqueue(new TextEncoder().encode('image'));
+ }
+ if (config.toolCall) {
+ const toolCall = {
+ function: { arguments: '{}', name: 'lookup' },
+ id: 'tool-1',
+ type: 'function' as const,
+ };
+ await options?.callback?.onToolsCalling?.({ chunk: [], toolsCalling: [toolCall] });
+ controller.enqueue(new TextEncoder().encode('tool-call'));
+ }
+ if (config.final) {
+ await options?.callback?.onCompletion?.(config.final);
+ await options?.callback?.onFinal?.(config.final);
+ }
+ if (config.bodyError) controller.error(config.bodyError);
+ else controller.close();
+ },
+ }),
+ );
+
+ it('follows the fallback policy after an empty completion and exposes one attempt', async () => {
+ const finished = vi.fn();
+ const onRouteSuccess = vi.fn();
+ const returned = vi.fn().mockResolvedValue(undefined);
+ const final = vi.fn();
+ let calls = 0;
+
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) => {
+ calls += 1;
+ options!.diagnostics!.providerRequest = {
+ apiMode: `attempt-${calls}`,
+ payload: { call: calls },
+ sentAt: calls,
+ };
+ if (calls === 1) {
+ const response = createChatResponse(options, {
+ final: {
+ finishReason: 'STOP',
+ text: '',
+ usage: { cost: 0, totalOutputTokens: 147 },
+ },
+ });
+ response.headers.set('content-length', '0');
+ return response;
+ }
+
+ return createChatResponse(options, {
+ final: { finishReason: 'STOP', text: 'answer', usage: { cost: 0.002 } },
+ text: 'answer',
+ });
+ };
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'lobehub',
+ onRouteAttempt: returned,
+ onRouteAttemptFinished: finished,
+ onRouteSuccess,
+ routers: [
+ {
+ apiType: 'openai',
+ id: 'router-a',
+ models: ['gpt-4'],
+ options: [{ id: 'channel-a' }, { id: 'channel-b' }],
+ runtime: MockRuntime,
+ },
+ ],
+ shouldFallbackChatAttempt: () => true,
+ });
+ const runtime = new Runtime({ userId: 'user-1' });
+ const diagnostics: ModelRuntimeDiagnostics = {};
+ const response = await runtime.chat(
+ { messages: [], model: 'gpt-4' },
+ {
+ callback: { onFinal: final },
+ diagnostics,
+ metadata: { trigger: RequestTrigger.Chat },
+ },
+ );
+
+ expect(await response.text()).toBe('answer');
+ expect(response.headers.get('content-length')).toBeNull();
+ expect(calls).toBe(2);
+ expect(final).toHaveBeenCalledTimes(1);
+ expect(final).toHaveBeenCalledWith(
+ expect.objectContaining({
+ routeAttempt: expect.objectContaining({ outcome: 'completed' }),
+ text: 'answer',
+ usage: expect.objectContaining({ cost: 0.002 }),
+ }),
+ );
+ expect(finished).toHaveBeenCalledTimes(2);
+ expect(finished.mock.calls.map(([result]) => result.outcome)).toEqual(['empty', 'completed']);
+ expect(finished.mock.calls.map(([result]) => result.success)).toEqual([false, true]);
+ expect(finished.mock.calls[0][0].requestId).toBe(finished.mock.calls[1][0].requestId);
+ expect(finished.mock.calls[0][0].attemptId).not.toBe(finished.mock.calls[1][0].attemptId);
+ expect(
+ finished.mock.calls.map(([result]) => result.diagnostics.providerRequest.apiMode),
+ ).toEqual(['attempt-1', 'attempt-2']);
+ expect(diagnostics.providerRequest?.apiMode).toBe('attempt-2');
+ expect(returned).toHaveBeenCalledWith(expect.objectContaining({ completionPending: true }));
+ expect(onRouteSuccess).toHaveBeenCalledOnce();
+ expect(onRouteSuccess).toHaveBeenCalledWith(
+ expect.objectContaining({
+ channelId: 'channel-b',
+ firstChannelId: 'channel-a',
+ model: 'gpt-4',
+ routerId: 'router-a',
+ }),
+ );
+ });
+
+ it('returns a non-streaming JSON response without retrying another route', async () => {
+ const finished = vi.fn();
+ const returned = vi.fn().mockResolvedValue(undefined);
+ let calls = 0;
+
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async () => {
+ calls += 1;
+ return Response.json({ id: 'response-1', output: 'answer' });
+ };
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttempt: returned,
+ onRouteAttemptFinished: finished,
+ routers: [
+ { apiType: 'openai', models: ['gpt-4'], options: [{}, {}], runtime: MockRuntime },
+ ],
+ shouldFallbackChatAttempt: () => true,
+ });
+ const response = await new Runtime().chat({
+ messages: [],
+ model: 'gpt-4',
+ responseMode: 'json',
+ stream: false,
+ });
+
+ await expect(response.json()).resolves.toEqual({ id: 'response-1', output: 'answer' });
+ expect(calls).toBe(1);
+ expect(finished).toHaveBeenCalledOnce();
+ expect(finished).toHaveBeenCalledWith(
+ expect.objectContaining({ outcome: 'completed', streaming: false, success: true }),
+ );
+ expect(returned).toHaveBeenCalledWith(
+ expect.objectContaining({ completionPending: true, success: true }),
+ );
+ });
+
+ it('falls back when the body is interrupted before any output', async () => {
+ let calls = 0;
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) => {
+ calls += 1;
+ return calls === 1
+ ? createChatResponse(options, { bodyError: new Error('disconnected') })
+ : createChatResponse(options, { final: { text: 'recovered' }, text: 'recovered' });
+ };
+ }
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttemptFinished: vi.fn(),
+ routers: [
+ { apiType: 'openai', models: ['gpt-4'], options: [{}, {}], runtime: MockRuntime },
+ ],
+ shouldFallbackChatAttempt: () => true,
+ });
+
+ const response = await new Runtime().chat({ messages: [], model: 'gpt-4' });
+
+ expect(await response.text()).toBe('recovered');
+ expect(calls).toBe(2);
+ });
+
+ it('surfaces a committed callback error without waiting for stream completion', async () => {
+ const callbackError = new Error('consumer callback failed');
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) =>
+ createChatResponse(options, { text: 'partial' });
+ }
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttemptFinished: vi.fn(),
+ routers: [
+ { apiType: 'openai', models: ['gpt-4'], options: [{}, {}], runtime: MockRuntime },
+ ],
+ shouldFallbackChatAttempt: () => true,
+ });
+ const response = await new Runtime().chat(
+ { messages: [], model: 'gpt-4' },
+ { callback: { onText: vi.fn().mockRejectedValue(callbackError) } },
+ );
+
+ const outcome = await Promise.race([
+ response.text().then(
+ () => 'completed',
+ (error) => error,
+ ),
+ new Promise((resolve) => setTimeout(() => resolve('timeout'), 100)),
+ ]);
+
+ expect(outcome).toBeInstanceOf(Error);
+ expect((outcome as Error).message).toContain(callbackError.message);
+ });
+
+ it.each([
+ ['text', { text: 'partial' }],
+ ['reasoning', { thinking: 'partial reasoning' }],
+ ['image', { image: true }],
+ ['tool call', { toolCall: true }],
+ ] as const)('does not replay after partial %s output', async (_label, partial) => {
+ const upstreamError = new Error('disconnected');
+ let calls = 0;
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) => {
+ calls += 1;
+ return createChatResponse(options, { ...partial, bodyError: upstreamError });
+ };
+ }
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttemptFinished: vi.fn(),
+ routers: [
+ { apiType: 'openai', models: ['gpt-4'], options: [{}, {}], runtime: MockRuntime },
+ ],
+ shouldFallbackChatAttempt: () => true,
+ });
+ const response = await new Runtime().chat({ messages: [], model: 'gpt-4' });
+
+ await expect(consumeResponse(response)).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.StreamChunkError,
+ });
+ expect(calls).toBe(1);
+ });
+
+ it('does not fallback after cancellation', async () => {
+ const cancelled = vi.fn();
+ const final = vi.fn();
+ const finished = vi.fn();
+ let calls = 0;
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async () => {
+ calls += 1;
+ return new Response(new ReadableStream({ cancel: cancelled }));
+ };
+ }
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttemptFinished: finished,
+ routers: [
+ { apiType: 'openai', models: ['gpt-4'], options: [{}, {}], runtime: MockRuntime },
+ ],
+ shouldFallbackChatAttempt: () => true,
+ });
+ const response = await new Runtime().chat(
+ { messages: [], model: 'gpt-4' },
+ { callback: { onFinal: final } },
+ );
+
+ await response.body!.cancel();
+
+ expect(calls).toBe(1);
+ expect(cancelled).toHaveBeenCalledTimes(1);
+ expect(finished).toHaveBeenCalledWith(expect.objectContaining({ outcome: 'cancelled' }));
+ expect(final).toHaveBeenCalledWith(
+ expect.objectContaining({
+ routeAttempt: expect.objectContaining({ outcome: 'cancelled' }),
+ }),
+ );
+ });
+
+ it('keeps a pre-response abort pending for terminal cancellation handling', async () => {
+ const controller = new AbortController();
+ const finished = vi.fn();
+ const returned = vi.fn().mockResolvedValue(undefined);
+ let calls = 0;
+
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) => {
+ calls += 1;
+ await new Promise<void>((_resolve, reject) => {
+ options?.signal?.addEventListener(
+ 'abort',
+ () => reject(new DOMException('The user aborted a request.', 'AbortError')),
+ { once: true },
+ );
+ });
+ return new Response();
+ };
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttempt: returned,
+ onRouteAttemptFinished: finished,
+ routers: [
+ { apiType: 'openai', models: ['gpt-4'], options: [{}, {}], runtime: MockRuntime },
+ ],
+ shouldFallbackChatAttempt: () => true,
+ });
+ const response = new Runtime().chat(
+ { messages: [], model: 'gpt-4' },
+ { signal: controller.signal },
+ );
+ await vi.waitFor(() => expect(calls).toBe(1));
+
+ controller.abort();
+
+ await expect(response).rejects.toMatchObject({ name: 'AbortError' });
+ expect(calls).toBe(1);
+ expect(finished).toHaveBeenCalledWith(expect.objectContaining({ outcome: 'cancelled' }));
+ expect(returned).toHaveBeenCalledWith(
+ expect.objectContaining({ completionPending: true, success: false }),
+ );
+ });
+
+ it('surfaces one terminal empty error after all routes return empty completions', async () => {
+ const final = vi.fn();
+ const finished = vi.fn();
+ let calls = 0;
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) => {
+ calls += 1;
+ return createChatResponse(options, {
+ final: { finishReason: 'STOP', text: '', usage: { cost: 0.001 } },
+ });
+ };
+ }
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttemptFinished: finished,
+ routers: [
+ { apiType: 'openai', models: ['gpt-4'], options: [{}, {}], runtime: MockRuntime },
+ ],
+ shouldFallbackChatAttempt: () => true,
+ });
+ const response = await new Runtime().chat(
+ { messages: [], model: 'gpt-4' },
+ { callback: { onFinal: final } },
+ );
+
+ await expect(consumeResponse(response)).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.ModelEmptyCompletion,
+ });
+ expect(calls).toBe(2);
+ expect(finished).toHaveBeenCalledTimes(2);
+ expect(final).toHaveBeenCalledTimes(1);
+ expect(final).toHaveBeenCalledWith(
+ expect.objectContaining({ routeAttempt: expect.objectContaining({ outcome: 'empty' }) }),
+ );
+ });
+
+ it('surfaces one terminal error after every route disconnects before output', async () => {
+ const final = vi.fn();
+ let calls = 0;
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) => {
+ calls += 1;
+ return createChatResponse(options, { bodyError: new Error(`disconnected-${calls}`) });
+ };
+ }
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttemptFinished: vi.fn(),
+ routers: [
+ { apiType: 'openai', models: ['gpt-4'], options: [{}, {}], runtime: MockRuntime },
+ ],
+ shouldFallbackChatAttempt: () => true,
+ });
+ const response = await new Runtime().chat(
+ { messages: [], model: 'gpt-4' },
+ { callback: { onFinal: final } },
+ );
+
+ await expect(consumeResponse(response)).rejects.toThrow('disconnected-2');
+ expect(calls).toBe(2);
+ expect(final).toHaveBeenCalledTimes(1);
+ expect(final).toHaveBeenCalledWith(
+ expect.objectContaining({
+ routeAttempt: expect.objectContaining({ outcome: 'interrupted' }),
+ }),
+ );
+ });
+
+ it('keeps stream-terminal fallback disabled unless the router opts in', async () => {
+ let calls = 0;
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) => {
+ calls += 1;
+ return createChatResponse(options, { final: { text: '' } });
+ };
+ }
+ const Runtime = createRouterRuntime({
+ id: 'byok-router',
+ onRouteAttemptFinished: vi.fn(),
+ routers: [
+ { apiType: 'openai', models: ['gpt-4'], options: [{}, {}], runtime: MockRuntime },
+ ],
+ });
+ const response = await new Runtime().chat({ messages: [], model: 'gpt-4' });
+
+ await expect(consumeResponse(response)).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.ModelEmptyCompletion,
+ });
+ expect(calls).toBe(1);
+ });
+
+ it('correlates fallback attempts and the successful completion without reusing request IDs', async () => {
+ const finished = vi.fn();
+ const returned = vi.fn().mockResolvedValue(undefined);
+ const final = vi.fn();
+ let calls = 0;
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) => {
+ if (++calls === 1) throw new Error('first channel failed');
+ await options?.callback?.onFinal?.({ text: 'answer' });
+ return new Response('answer');
+ };
+ }
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttempt: returned,
+ onRouteAttemptFinished: finished,
+ routers: [
+ { apiType: 'openai', models: ['gpt-4'], options: [{}, {}], runtime: MockRuntime },
+ ],
+ shouldFallbackChatAttempt: () => true,
+ });
+ const runtime = new Runtime();
+ const response = await runtime.chat(
+ { model: 'gpt-4', messages: [] },
+ { callback: { onFinal: final } },
+ );
+ await response.text();
+ expect(finished).toHaveBeenCalledTimes(2);
+ const first = finished.mock.calls[0][0];
+ const second = finished.mock.calls[1][0];
+ expect(first.outcome).toBe('failed');
+ expect(second.outcome).toBe('completed');
+ expect(returned.mock.calls[0][0]).toEqual(
+ expect.objectContaining({ completionPending: false, success: false }),
+ );
+ expect(returned.mock.calls[1][0]).toEqual(
+ expect.objectContaining({ completionPending: true, success: true }),
+ );
+ expect(first.requestId).toBe(second.requestId);
+ expect(first.attemptId).not.toBe(second.attemptId);
+ expect(final.mock.calls[0][0].routeAttempt).toEqual({
+ attemptId: second.attemptId,
+ outcome: 'completed',
+ requestId: second.requestId,
+ });
+ expect(returned.mock.calls[1][0].attemptId).toBe(second.attemptId);
+ const nextResponse = await runtime.chat({ model: 'gpt-4', messages: [] });
+ await nextResponse.text();
+ expect(finished.mock.calls[2][0].requestId).not.toBe(second.requestId);
+ });
+
it('should only use raw-audio-compatible routes for audio messages', async () => {
const attemptedRoutes: string[] = [];
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index f849732a07d..c282b14a1b7 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -10,6 +10,7 @@ import type {
import { AgentRuntimeErrorType } from '@lobechat/types';
import { createTimingHelpers, getDurationMs } from '@lobechat/utils';
import debug from 'debug';
+import { nanoid } from 'nanoid';
import type { ClientOptions } from 'openai';
import type OpenAI from 'openai';
import type { Stream } from 'openai/streaming';
@@ -51,6 +52,12 @@ import type {
CustomClientOptions,
} from '../openaiCompatibleFactory';
import type { ApiType, RuntimeClass } from './apiTypes';
+import { getChatAttemptObservation, observeChatAttempt } from './chatAttempt';
+import type { ChatStreamFallbackAttempt } from './chatStreamFallback';
+import { createChatStreamFallbackResponse } from './chatStreamFallback';
+import type { RouteAttemptFinished, RouteAttemptResult, RouteAttemptStart } from './routeAttempt';
+
+export type { RouteAttemptResult } from './routeAttempt';
const log = debug('lobe-model-runtime:router-runtime');
const { logger: timing } = createTimingHelpers('lobe-server:chat:lobehub:timing');
@@ -105,26 +112,10 @@ type Routers =
runtimeContext: RouterRuntimeRequestContext,
) => RouterInstance[] | Promise<RouterInstance[]>);
-export interface RouteAttemptResult {
- apiType: string;
- channelId?: string;
- durationMs: number;
- error?: unknown;
- metadata?: Record<string, unknown>;
- model: string;
- nonRetryable?: boolean;
- nonRetryableReason?: 'imageDecode';
- optionIndex: number;
- providerId: string;
- remark?: string;
- routerId?: string;
- success: boolean;
- userId?: string;
-}
-
interface RouteAttemptMetadata {
apiType: string;
channelId?: string;
+ completionPending?: boolean;
durationMs: number;
optionIndex: number;
providerId: string;
@@ -241,6 +232,7 @@ export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any>
transformModel?: (model: OpenAI.Model) => ChatModelCard;
};
onRouteAttempt?: (result: RouteAttemptResult) => Promise<void>;
+ onRouteAttemptFinished?: (result: RouteAttemptFinished) => Promise<void>;
/** Awaited before returning so a successful fallback can update routing affinity. */
onRouteSuccess?: (result: RouteSuccessParams) => void | Promise<void>;
responses?: {
@@ -250,6 +242,7 @@ export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any>
) => ChatStreamPayload;
};
routers: Routers;
+ shouldFallbackChatAttempt?: (result: RouteAttemptFinished) => boolean | Promise<boolean>;
shouldStopFallback?: (params: {
error: unknown;
metadata?: Record<string, unknown>;
@@ -632,12 +625,200 @@ export const createRouterRuntime = ({
};
}
+ /**
+ * Keep routed chat fallback open until the response body reaches a terminal
+ * outcome. Bytes and callbacks remain private until the first visible model
+ * output, preventing transparent replay after a partial answer or tool call.
+ */
+ private async runChatWithStreamFallback(
+ payload: ChatStreamPayload,
+ options: ChatMethodOptions | undefined,
+ routeContext: RouteAttemptContext,
+ ): Promise<Response> {
+ const requestId = nanoid();
+ const { allowedApiTypes, metadata, pricingContext, toolsCount, user } = routeContext;
+ const matchedRouter = await this.resolveMatchedRouter(payload.model, pricingContext);
+ const sortedRouterOptions = await this.applySortRouterOptions(
+ matchedRouter,
+ payload.model,
+ this.normalizeRouterOptions(matchedRouter),
+ routeContext,
+ );
+ const routerOptions = allowedApiTypes
+ ? sortedRouterOptions.filter((option) =>
+ allowedApiTypes.has(option.apiType ?? matchedRouter.apiType),
+ )
+ : sortedRouterOptions;
+
+ if (routerOptions.length === 0) {
+ throw new TypeError(
+ `No provider route supports raw audio input for model ${payload.model}`,
+ );
+ }
+ const firstChannelId = routerOptions[0]?.id;
+ const weighted = routerOptions.some((option) => option.weight !== undefined);
+
+ const reportReturnedAttempt = (
+ attempt: RouteAttemptStart,
+ result: Partial<RouteAttemptResult> & Pick<RouteAttemptResult, 'durationMs' | 'success'>,
+ ) => {
+ params.onRouteAttempt?.({ ...attempt, ...result } as RouteAttemptResult).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 startAttempt = async (optionIndex: number): Promise<ChatStreamFallbackAttempt> => {
+ const optionItem = routerOptions[optionIndex];
+ const {
+ channelId,
+ id: resolvedApiType,
+ remark,
+ runtime,
+ } = await this.createRuntimeFromOption(matchedRouter, optionItem);
+ const routeAttemptUserId = this.validateRouteAttemptContext({
+ 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,
+ routerId: matchedRouter.id,
+ startedAt: Date.now(),
+ userId: routeAttemptUserId,
+ };
+
+ try {
+ const response = await observeChatAttempt(
+ (attemptOptions) => runtime.chat!(payload, attemptOptions),
+ options,
+ attempt,
+ payload.stream !== false,
+ params.onRouteAttemptFinished!,
+ { deferCallbacks: true },
+ );
+ const durationMs = Date.now() - attempt.startedAt;
+ reportReturnedAttempt(attempt, {
+ completionPending: true,
+ durationMs,
+ success: true,
+ });
+ this.attachRouteAttemptMetadata(metadata, {
+ apiType: resolvedApiType,
+ channelId,
+ completionPending: true,
+ durationMs,
+ optionIndex,
+ providerId: id,
+ routerId: matchedRouter.id,
+ success: true,
+ totalOptions: routerOptions.length,
+ });
+
+ const observation = getChatAttemptObservation(response);
+ if (!observation) throw new Error('Missing chat attempt observation');
+
+ return {
+ index: optionIndex,
+ observation,
+ onCompleted: async () => {
+ if (!params.onRouteSuccess) return;
+
+ try {
+ await params.onRouteSuccess({
+ channelId,
+ channelWeight: optionItem.weight,
+ firstChannelId,
+ method: routeContext.method,
+ model: payload.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);
+ }
+ },
+ reader: response.body?.getReader(),
+ response,
+ };
+ } catch (error) {
+ const nonRetryable = shouldStopFallbackForError(error);
+ const nonRetryableReason =
+ nonRetryable && isImageDecodingRequestError(error)
+ ? ('imageDecode' as const)
+ : undefined;
+ reportReturnedAttempt(attempt, {
+ // Defer cancellation health handling to the terminal outcome, which intentionally ignores it.
+ completionPending: options?.signal?.aborted ?? false,
+ durationMs: Date.now() - attempt.startedAt,
+ error,
+ nonRetryable,
+ nonRetryableReason,
+ success: false,
+ });
+
+ if (
+ optionIndex + 1 < routerOptions.length &&
+ (await shouldContinueAfterRequestError(error, optionIndex))
+ ) {
+ return startAttempt(optionIndex + 1);
+ }
+ throw error;
+ }
+ };
+
+ return createChatStreamFallbackResponse({
+ shouldFallback: async (result) => {
+ try {
+ return Boolean(await params.shouldFallbackChatAttempt?.(result));
+ } catch (error) {
+ log('shouldFallbackChatAttempt callback error: %O', error);
+ return false;
+ }
+ },
+ startAttempt,
+ totalAttempts: routerOptions.length,
+ });
+ }
+
private async runWithFallback<T>(
model: string,
- requestHandler: (runtime: LobeRuntimeAI) => Promise<T>,
+ requestHandler: (runtime: LobeRuntimeAI, attempt: RouteAttemptStart) => Promise<T>,
routeContext: RouteAttemptContext,
): Promise<T> {
const totalStartedAt = Date.now();
+ const requestId = nanoid();
const { allowedApiTypes, metadata, pricingContext, toolsCount, user } = routeContext;
const matchedRouter = await this.resolveMatchedRouter(model, pricingContext);
const eligibleRouterOptions = this.normalizeRouterOptions(matchedRouter).filter(
@@ -697,6 +878,22 @@ export const createRouterRuntime = ({
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,
+ };
+
try {
if (this._id === 'lobehub') {
timing(
@@ -710,7 +907,7 @@ export const createRouterRuntime = ({
metadata?.traceId,
);
}
- const result = await requestHandler(runtime);
+ const result = await requestHandler(runtime, attemptContext);
if (this._id === 'lobehub') {
timing(
'attempt request success model=%s attempt=%d/%d routerId=%s channelId=%s apiType=%s durationMs=%d totalMs=%d traceId=%s',
@@ -766,10 +963,11 @@ export const createRouterRuntime = ({
params
.onRouteAttempt?.({
+ ...attemptContext,
apiType: resolvedApiType,
channelId,
- durationMs: Date.now() - startTime,
- metadata,
+ durationMs: Date.now() - attemptContext.startedAt,
+ metadata: attemptContext.metadata,
model,
optionIndex: index,
providerId: id,
@@ -785,7 +983,7 @@ export const createRouterRuntime = ({
this.attachRouteAttemptMetadata(metadata, {
apiType: resolvedApiType,
channelId,
- durationMs: Date.now() - startTime,
+ durationMs: Date.now() - attemptContext.startedAt,
optionIndex: index,
providerId: id,
routerId: matchedRouter.id,
@@ -819,11 +1017,12 @@ export const createRouterRuntime = ({
params
.onRouteAttempt?.({
+ ...attemptContext,
apiType: resolvedApiType,
channelId,
- durationMs: Date.now() - startTime,
+ durationMs: Date.now() - attemptContext.startedAt,
error,
- metadata,
+ metadata: attemptContext.metadata,
model,
nonRetryable: shouldStopFallback,
nonRetryableReason,
@@ -945,9 +1144,29 @@ export const createRouterRuntime = ({
try {
const containsRawAudio = hasRawAudioInput(payload);
+ if (params.onRouteAttemptFinished && params.shouldFallbackChatAttempt) {
+ return await this.runChatWithStreamFallback(payload, options, {
+ allowedApiTypes: containsRawAudio ? RAW_AUDIO_API_TYPES : undefined,
+ metadata: options?.metadata,
+ method: 'chat',
+ pricingContext: options?.pricingContext,
+ toolsCount: payload.tools?.length ?? 0,
+ user: options?.user,
+ });
+ }
+
return await this.runWithFallback(
payload.model,
- (runtime) => runtime.chat!(payload, options),
+ (runtime, attempt) =>
+ params.onRouteAttemptFinished
+ ? observeChatAttempt(
+ (attemptOptions) => runtime.chat!(payload, attemptOptions),
+ options,
+ attempt,
+ payload.stream !== false,
+ params.onRouteAttemptFinished,
+ )
+ : runtime.chat!(payload, options),
{
allowedApiTypes: containsRawAudio ? RAW_AUDIO_API_TYPES : undefined,
metadata: options?.metadata,
diff --git a/packages/model-runtime/src/core/RouterRuntime/index.ts b/packages/model-runtime/src/core/RouterRuntime/index.ts
index 8d6a410040e..3a8ccc63572 100644
--- a/packages/model-runtime/src/core/RouterRuntime/index.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/index.ts
@@ -6,5 +6,6 @@ export interface RuntimeItem {
runtime: LobeRuntimeAI;
}
-export type { CreateRouterRuntimeOptions, RouteAttemptResult, UniformRuntime } from './createRuntime';
+export type { CreateRouterRuntimeOptions, UniformRuntime } from './createRuntime';
export { createRouterRuntime } from './createRuntime';
+export type { RouteAttemptFinished, RouteAttemptResult } from './routeAttempt';
diff --git a/packages/model-runtime/src/core/RouterRuntime/routeAttempt.ts b/packages/model-runtime/src/core/RouterRuntime/routeAttempt.ts
new file mode 100644
index 00000000000..0c38001443a
--- /dev/null
+++ b/packages/model-runtime/src/core/RouterRuntime/routeAttempt.ts
@@ -0,0 +1,47 @@
+import type { ModelPerformance, ModelUsage } from '@lobechat/types';
+
+import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
+
+export interface RouteAttemptResult {
+ apiType: string;
+ attemptId?: string;
+ channelId?: string;
+ completionPending?: boolean;
+ durationMs: number;
+ error?: unknown;
+ metadata?: Record<string, unknown>;
+ model: string;
+ nonRetryable?: boolean;
+ nonRetryableReason?: 'imageDecode';
+ optionIndex: number;
+ providerId: string;
+ remark?: string;
+ requestId?: string;
+ routerId?: string;
+ startedAt?: number;
+ success: boolean;
+ userId?: string;
+}
+
+export interface RouteAttemptStart extends Omit<
+ RouteAttemptResult,
+ 'completionPending' | 'durationMs' | 'success'
+> {
+ attemptId: string;
+ requestId: string;
+ startedAt: number;
+}
+
+export type RouteAttemptOutcome = 'completed' | 'empty' | 'interrupted' | 'cancelled' | 'failed';
+
+export interface RouteAttemptFinished extends RouteAttemptResult {
+ attemptId: string;
+ completedAt: number;
+ diagnostics: ModelRuntimeDiagnostics;
+ outcome: RouteAttemptOutcome;
+ requestId: string;
+ speed?: ModelPerformance;
+ startedAt: number;
+ streaming: boolean;
+ usage?: ModelUsage;
+}
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
index 6fba2f65072..7be887da164 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
@@ -788,7 +788,7 @@ describe('LobeOpenAICompatibleFactory', () => {
'data: {"inputTextTokens":5,"outputTextTokens":5,"totalInputTokens":5,"totalOutputTokens":5,"totalTokens":10}\n\n',
'id: output_speed\n',
'event: speed\n',
- expect.stringMatching(/^data: \{.*"tps":.*,"ttft":.*\}\n\n$/), // tps ttft should be calculated with elapsed time
+ 'data: {"latency":10}\n\n',
'id: a\n',
'event: stop\n',
'data: "stop"\n\n',
@@ -864,7 +864,7 @@ describe('LobeOpenAICompatibleFactory', () => {
'data: {"inputTextTokens":5,"outputTextTokens":5,"totalInputTokens":5,"totalOutputTokens":5,"totalTokens":10}\n\n',
'id: output_speed\n',
'event: speed\n',
- expect.stringMatching(/^data: \{.*"tps":.*,"ttft":.*\}\n\n$/), // tps ttft should be calculated with elapsed time
+ 'data: {"latency":10}\n\n',
'id: a\n',
'event: stop\n',
'data: "stop"\n\n',
diff --git a/packages/model-runtime/src/core/streams/anthropic.test.ts b/packages/model-runtime/src/core/streams/anthropic.test.ts
index 2c290c03327..3d16d7ffd01 100644
--- a/packages/model-runtime/src/core/streams/anthropic.test.ts
+++ b/packages/model-runtime/src/core/streams/anthropic.test.ts
@@ -623,7 +623,7 @@ describe('AnthropicStream', () => {
'data: "end_turn"\n',
'id: msg_01MNsLe7n1uVLtu6W8rCFujD',
'event: usage',
- 'data: {"inputCacheMissTokens":46,"totalInputTokens":46,"totalOutputTokens":365,"totalTokens":411}\n',
+ 'data: {"inputCacheMissTokens":46,"inputCachedTokens":0,"totalInputTokens":46,"totalOutputTokens":365,"totalTokens":411}\n',
'id: msg_01MNsLe7n1uVLtu6W8rCFujD',
'event: stop',
'data: "message_stop"\n',
@@ -783,7 +783,7 @@ describe('AnthropicStream', () => {
'data: "end_turn"\n',
'id: msg_019q32esPvu3TftzZnL6JPys',
'event: usage',
- 'data: {"inputCacheMissTokens":92,"totalInputTokens":92,"totalOutputTokens":263,"totalTokens":355}\n',
+ 'data: {"inputCacheMissTokens":92,"inputCachedTokens":0,"totalInputTokens":92,"totalOutputTokens":263,"totalTokens":355}\n',
'id: msg_019q32esPvu3TftzZnL6JPys',
'event: stop',
'data: "message_stop"\n',
diff --git a/packages/model-runtime/src/core/streams/openai/openai.test.ts b/packages/model-runtime/src/core/streams/openai/openai.test.ts
index 9f73df46859..5364fa6b480 100644
--- a/packages/model-runtime/src/core/streams/openai/openai.test.ts
+++ b/packages/model-runtime/src/core/streams/openai/openai.test.ts
@@ -629,7 +629,7 @@ describe('OpenAIStream', () => {
`data: "stop"\n`,
'id: chatcmpl-B7CcnaeK3jqWBMOhxg7SSKFwlk7dC',
'event: usage',
- `data: {"inputAudioTokens":0,"inputCacheMissTokens":1646,"inputTextTokens":1646,"outputTextTokens":11,"totalInputTokens":1646,"totalOutputTokens":11,"totalTokens":1657}\n`,
+ `data: {"inputAudioTokens":0,"inputCacheMissTokens":1646,"inputCachedTokens":0,"inputTextTokens":1646,"outputTextTokens":11,"totalInputTokens":1646,"totalOutputTokens":11,"totalTokens":1657}\n`,
].map((i) => `${i}\n`),
);
});
@@ -731,7 +731,7 @@ describe('OpenAIStream', () => {
`data: {"delta":{},"id":"chatcmpl-c1f6a6a6-fcf8-463a-96bf-cf634d3e98a5","index":0}\n`,
'id: chatcmpl-c1f6a6a6-fcf8-463a-96bf-cf634d3e98a5',
'event: usage',
- `data: {"inputAudioTokens":0,"inputCacheMissTokens":1797,"inputTextTokens":1797,"outputTextTokens":1720,"totalInputTokens":1797,"totalOutputTokens":1720,"totalTokens":3517}\n`,
+ `data: {"inputAudioTokens":0,"inputCacheMissTokens":1797,"inputCachedTokens":0,"inputTextTokens":1797,"outputTextTokens":1720,"totalInputTokens":1797,"totalOutputTokens":1720,"totalTokens":3517}\n`,
].map((i) => `${i}\n`),
);
});
@@ -1715,7 +1715,7 @@ describe('OpenAIStream', () => {
`data: "这是最终答案。"\n`,
'id: 1',
'event: usage',
- `data: {"inputCacheMissTokens":10,"inputTextTokens":10,"outputReasoningTokens":20,"outputTextTokens":30,"totalInputTokens":10,"totalOutputTokens":50,"totalTokens":60}\n`,
+ `data: {"inputCacheMissTokens":10,"inputCachedTokens":0,"inputTextTokens":10,"outputReasoningTokens":20,"outputTextTokens":30,"totalInputTokens":10,"totalOutputTokens":50,"totalTokens":60}\n`,
].map((i) => `${i}\n`),
);
});
@@ -1996,7 +1996,7 @@ describe('OpenAIStream', () => {
`data: "帮助。"\n`,
'id: 1',
'event: usage',
- `data: {"inputCacheMissTokens":6,"inputTextTokens":6,"outputReasoningTokens":70,"outputTextTokens":34,"totalInputTokens":6,"totalOutputTokens":104,"totalTokens":110}\n`,
+ `data: {"inputCacheMissTokens":6,"inputCachedTokens":0,"inputTextTokens":6,"outputReasoningTokens":70,"outputTextTokens":34,"totalInputTokens":6,"totalOutputTokens":104,"totalTokens":110}\n`,
].map((i) => `${i}\n`),
);
});
@@ -2215,7 +2215,7 @@ describe('OpenAIStream', () => {
`data: "帮助。"\n`,
'id: 1',
'event: usage',
- `data: {"inputCacheMissTokens":6,"inputTextTokens":6,"outputReasoningTokens":70,"outputTextTokens":34,"totalInputTokens":6,"totalOutputTokens":104,"totalTokens":110}\n`,
+ `data: {"inputCacheMissTokens":6,"inputCachedTokens":0,"inputTextTokens":6,"outputReasoningTokens":70,"outputTextTokens":34,"totalInputTokens":6,"totalOutputTokens":104,"totalTokens":110}\n`,
].map((i) => `${i}\n`),
);
});
@@ -2484,7 +2484,7 @@ describe('OpenAIStream', () => {
`data: "帮助。"\n`,
'id: 1',
'event: usage',
- `data: {"inputCacheMissTokens":6,"inputTextTokens":6,"outputReasoningTokens":70,"outputTextTokens":34,"totalInputTokens":6,"totalOutputTokens":104,"totalTokens":110}\n`,
+ `data: {"inputCacheMissTokens":6,"inputCachedTokens":0,"inputTextTokens":6,"outputReasoningTokens":70,"outputTextTokens":34,"totalInputTokens":6,"totalOutputTokens":104,"totalTokens":110}\n`,
].map((i) => `${i}\n`),
);
});
@@ -2685,7 +2685,7 @@ describe('OpenAIStream', () => {
`data: "帮助。"\n`,
'id: 1',
'event: usage',
- `data: {"inputCacheMissTokens":6,"inputTextTokens":6,"outputReasoningTokens":70,"outputTextTokens":34,"totalInputTokens":6,"totalOutputTokens":104,"totalTokens":110}\n`,
+ `data: {"inputCacheMissTokens":6,"inputCachedTokens":0,"inputTextTokens":6,"outputReasoningTokens":70,"outputTextTokens":34,"totalInputTokens":6,"totalOutputTokens":104,"totalTokens":110}\n`,
].map((i) => `${i}\n`),
);
});
@@ -2886,7 +2886,7 @@ describe('OpenAIStream', () => {
`data: "帮助。"\n`,
'id: 1',
'event: usage',
- `data: {"inputCacheMissTokens":6,"inputTextTokens":6,"outputReasoningTokens":70,"outputTextTokens":34,"totalInputTokens":6,"totalOutputTokens":104,"totalTokens":110}\n`,
+ `data: {"inputCacheMissTokens":6,"inputCachedTokens":0,"inputTextTokens":6,"outputReasoningTokens":70,"outputTextTokens":34,"totalInputTokens":6,"totalOutputTokens":104,"totalTokens":110}\n`,
].map((i) => `${i}\n`),
);
});
diff --git a/packages/model-runtime/src/core/streams/protocol.test.ts b/packages/model-runtime/src/core/streams/protocol.test.ts
index 959a0a766cf..2822d660b23 100644
--- a/packages/model-runtime/src/core/streams/protocol.test.ts
+++ b/packages/model-runtime/src/core/streams/protocol.test.ts
@@ -1,5 +1,6 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { StreamProtocolChunk } from './protocol';
import {
ABORT_CHUNK,
convertIterableToStream,
@@ -12,6 +13,8 @@ import {
readableFromAsyncIterable,
} from './protocol';
+afterEach(() => vi.restoreAllMocks());
+
describe('createSSEDataExtractor', () => {
// Helper function to convert string to Uint8Array
const stringToUint8Array = (str: string): Uint8Array => {
@@ -199,6 +202,39 @@ describe('createTokenSpeedCalculator', async () => {
expect(speedChunk.data.ttft).not.toBeNaN();
});
+ it('measures effective output and excludes trailing usage delivery from generation speed', async () => {
+ let now = 1000;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ const transformer = createTokenSpeedCalculator((chunk) => chunk, { inputStartAt: 1000 });
+ const writer = transformer.writable.getWriter();
+ const reader = transformer.readable.getReader();
+ const results: StreamProtocolChunk[] = [];
+ const readResult = (async () => {
+ while (true) {
+ const result = await reader.read();
+ if (result.done) return;
+ results.push(result.value);
+ }
+ })();
+
+ for (const [at, chunk] of [
+ [1100, { data: '', type: 'text' }],
+ [1200, { data: 'reason', type: 'reasoning' }],
+ [2200, { data: 'answer', type: 'text' }],
+ [3200, { data: { totalOutputTokens: 100 }, type: 'usage' }],
+ ] as const) {
+ now = at;
+ await writer.write(chunk);
+ }
+ await writer.close();
+ await readResult;
+
+ expect(results.at(-1)).toMatchObject({
+ data: { duration: 1000, latency: 2200, tps: 100, ttft: 200 },
+ type: 'speed',
+ });
+ });
+
it('should not calculate token speed if no usage', async () => {
const chunks = [
{ data: '', id: 'chatcmpl-BKO1bogylHvMaYfETjTAzrCguYwZy', type: 'text' },
diff --git a/packages/model-runtime/src/core/streams/protocol.ts b/packages/model-runtime/src/core/streams/protocol.ts
index 349e5dfb43d..e9b288b9963 100644
--- a/packages/model-runtime/src/core/streams/protocol.ts
+++ b/packages/model-runtime/src/core/streams/protocol.ts
@@ -720,6 +720,30 @@ export const createSSEDataExtractor = () =>
export const TOKEN_SPEED_CHUNK_ID = 'output_speed';
+const hasEffectiveOutput = (chunk: StreamProtocolChunk): boolean => {
+ switch (chunk.type) {
+ case 'base64_image':
+ case 'reasoning':
+ case 'text': {
+ return Boolean(chunk.data);
+ }
+ case 'content_part':
+ case 'reasoning_part': {
+ return Boolean((chunk.data as StreamPartChunkData | undefined)?.content);
+ }
+ case 'tool_calls': {
+ return (
+ (chunk.data as StreamToolCallChunkData[] | undefined)?.some(
+ (tool) => tool.function?.name || tool.function?.arguments,
+ ) ?? false
+ );
+ }
+ default: {
+ return false;
+ }
+ }
+};
+
/**
* Create a middleware to calculate the token generate speed
* @requires createSSEProtocolTransformer
@@ -733,44 +757,34 @@ export const createTokenSpeedCalculator = (
}: { enableStreaming?: boolean; inputStartAt?: number; streamStack?: StreamContext } = {},
) => {
let outputStartAt: number | undefined;
+ let outputEndAt: number | undefined;
const process = (chunk: StreamProtocolChunk) => {
const result = [chunk];
- // Set outputStartAt when receiving the first content chunk (for TTFT calculation)
- // - text/reasoning: standard text output events
- // - content_part/reasoning_part: multimodal output events used by Gemini 3+ models
- // which emit structured parts instead of plain text events
- // - tool_calls: function calling output events
- if (
- !outputStartAt &&
- (chunk.type === 'text' ||
- chunk.type === 'reasoning' ||
- chunk.type === 'content_part' ||
- chunk.type === 'reasoning_part' ||
- chunk.type === 'tool_calls')
- ) {
- outputStartAt = Date.now();
+ if (hasEffectiveOutput(chunk)) {
+ const now = Date.now();
+ outputStartAt ??= now;
+ outputEndAt = now;
}
- // if the chunk is the stop chunk, set as output finish
- if (inputStartAt && outputStartAt && chunk.type === 'usage') {
+ if (inputStartAt !== undefined && outputStartAt !== undefined && chunk.type === 'usage') {
// TPS should always include all generated tokens (including reasoning tokens)
// because it measures generation speed, not just visible content
const usage = chunk.data as ModelUsage;
const outputTokens = usage?.totalOutputTokens ?? 0;
const now = Date.now();
- const elapsed = now - (enableStreaming ? outputStartAt : inputStartAt);
- const duration = now - outputStartAt;
- const latency = now - inputStartAt;
- const ttft = outputStartAt - inputStartAt;
- const tps = elapsed === 0 ? undefined : (outputTokens / elapsed) * 1000;
+ const duration = (outputEndAt ?? outputStartAt) - outputStartAt;
+ const tps =
+ enableStreaming && duration > 0 && outputTokens > 1
+ ? (outputTokens / duration) * 1000
+ : undefined;
result.push({
data: {
- duration,
- latency,
+ duration: enableStreaming ? duration : undefined,
+ latency: now - inputStartAt,
tps,
- ttft,
+ ttft: enableStreaming ? outputStartAt - inputStartAt : undefined,
} as ModelPerformance,
id: TOKEN_SPEED_CHUNK_ID,
type: 'speed',
diff --git a/packages/model-runtime/src/core/usageConverters/anthropic.test.ts b/packages/model-runtime/src/core/usageConverters/anthropic.test.ts
index a56cc6e0ec1..6a0fbd2a06e 100644
--- a/packages/model-runtime/src/core/usageConverters/anthropic.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/anthropic.test.ts
@@ -1,9 +1,16 @@
import type Anthropic from '@anthropic-ai/sdk';
import { describe, expect, it } from 'vitest';
-import { convertAnthropicUsage } from './anthropic';
+import { buildAnthropicInitialUsage, convertAnthropicUsage } from './anthropic';
describe('convertAnthropicUsage', () => {
+ it('preserves an explicit zero cache read without inventing a missing value', () => {
+ const usage = { input_tokens: 100, output_tokens: 10 } as Anthropic.Messages.Usage;
+ expect(buildAnthropicInitialUsage(usage)?.inputCachedTokens).toBeUndefined();
+ expect(
+ buildAnthropicInitialUsage({ ...usage, cache_read_input_tokens: 0 })?.inputCachedTokens,
+ ).toBe(0);
+ });
it('should convert message_start usage with cache information', () => {
const event = {
type: 'message_start',
diff --git a/packages/model-runtime/src/core/usageConverters/anthropic.ts b/packages/model-runtime/src/core/usageConverters/anthropic.ts
index e68c6e7fb9a..6f1169c3660 100644
--- a/packages/model-runtime/src/core/usageConverters/anthropic.ts
+++ b/packages/model-runtime/src/core/usageConverters/anthropic.ts
@@ -22,7 +22,7 @@ export const buildAnthropicInitialUsage = (
return {
inputCacheMissTokens: usage.input_tokens,
- inputCachedTokens: usage.cache_read_input_tokens || undefined,
+ inputCachedTokens: usage.cache_read_input_tokens ?? undefined,
inputWriteCacheTokens: usage.cache_creation_input_tokens || undefined,
totalInputTokens,
totalOutputTokens,
diff --git a/packages/model-runtime/src/core/usageConverters/openai.test.ts b/packages/model-runtime/src/core/usageConverters/openai.test.ts
index 75a2c814073..6a6a841edc0 100644
--- a/packages/model-runtime/src/core/usageConverters/openai.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/openai.test.ts
@@ -5,6 +5,18 @@ import { describe, expect, it } from 'vitest';
import { convertOpenAIImageUsage, convertOpenAIResponseUsage, convertOpenAIUsage } from './openai';
describe('convertUsage', () => {
+ it('distinguishes an explicit zero cache read from missing cache usage', () => {
+ const usage = { prompt_tokens: 100, completion_tokens: 10, total_tokens: 110 };
+ expect(convertOpenAIUsage(usage).inputCachedTokens).toBeUndefined();
+ expect(
+ convertOpenAIUsage({ ...usage, prompt_tokens_details: { cached_tokens: 0 } })
+ .inputCachedTokens,
+ ).toBe(0);
+ expect(
+ convertOpenAIUsage({ ...usage, prompt_cache_hit_tokens: 0 } as typeof usage)
+ .inputCachedTokens,
+ ).toBe(0);
+ });
it('should convert basic OpenAI usage data correctly', () => {
// Arrange
const openaiUsage: OpenAI.Completions.CompletionUsage = {
@@ -118,6 +130,7 @@ describe('convertUsage', () => {
expect(result).toEqual({
inputTextTokens: 2000,
inputWriteCacheTokens: 1500,
+ inputCachedTokens: 0,
// uncached 1× bucket must not include writes (2000 - 0 - 1500)
inputCacheMissTokens: 500,
totalInputTokens: 2000,
@@ -125,7 +138,7 @@ describe('convertUsage', () => {
outputTextTokens: 100,
totalTokens: 2100,
});
- expect(result).not.toHaveProperty('inputCachedTokens');
+ expect(result.inputCachedTokens).toBe(0);
});
it('should split miss / read / write when both cache hit and write are present', () => {
@@ -539,6 +552,7 @@ describe('convertUsage', () => {
expect(result).toEqual({
inputTextTokens: 100,
inputCacheMissTokens: 100, // 100 - 0
+ inputCachedTokens: 0,
totalInputTokens: 100,
totalOutputTokens: 200,
outputImageTokens: 60,
diff --git a/packages/model-runtime/src/core/usageConverters/openai.ts b/packages/model-runtime/src/core/usageConverters/openai.ts
index 9af9b5fa111..c803c3bcc52 100644
--- a/packages/model-runtime/src/core/usageConverters/openai.ts
+++ b/packages/model-runtime/src/core/usageConverters/openai.ts
@@ -19,7 +19,10 @@ const shouldKeepUsageValue = (key: string, value: unknown) => {
if (value !== 0) return true;
- return key === 'inputAudioTokens' || key === 'inputCacheMissTokens';
+ // Explicit zero cache reads distinguish a cache miss from unavailable telemetry.
+ return (
+ key === 'inputAudioTokens' || key === 'inputCacheMissTokens' || key === 'inputCachedTokens'
+ );
};
/**
@@ -78,7 +81,7 @@ export const convertOpenAIUsage = (
const totalInputTokens = inputCitationTokens + (usage.prompt_tokens || 0);
const cachedTokens =
- (usage as any).prompt_cache_hit_tokens || usage.prompt_tokens_details?.cached_tokens;
+ (usage as any).prompt_cache_hit_tokens ?? usage.prompt_tokens_details?.cached_tokens;
// OpenAI reports aggregate cached prompt tokens, but does not identify how many cached tokens
// are audio. Do not infer inputCachedAudioTokens from overlapping aggregate counters; callers
// can handle the unavailable modality split without receiving fabricated usage.
@@ -144,7 +147,7 @@ export const convertOpenAIResponseUsage = (
): ModelUsage => {
// 1. Extract and default primary values
const totalInputTokens = usage.input_tokens || 0;
- const inputCachedTokens = usage.input_tokens_details?.cached_tokens || 0;
+ const inputCachedTokens = usage.input_tokens_details?.cached_tokens;
const inputWriteCacheTokens = readCacheWriteTokens(usage.input_tokens_details);
const totalOutputTokens = usage.output_tokens || 0;
@@ -155,11 +158,12 @@ export const convertOpenAIResponseUsage = (
// 2. Calculate derived values.
// Exclude cache writes from the uncached bucket so textInput (1×) and
// textInput_cacheWrite (1.25×) do not both bill the same tokens.
- const inputCacheMissTokens = resolveOpenAIInputCacheMissTokens({
- inputCachedTokens,
- inputWriteCacheTokens,
- totalInputTokens,
- })!;
+ const inputCacheMissTokens =
+ resolveOpenAIInputCacheMissTokens({
+ inputCachedTokens,
+ inputWriteCacheTokens,
+ totalInputTokens,
+ }) ?? totalInputTokens;
// For ResponseUsage, inputTextTokens is effectively totalInputTokens as no further breakdown is given.
const inputTextTokens = totalInputTokens;
diff --git a/packages/model-runtime/src/errors/modelEmptyCompletion.ts b/packages/model-runtime/src/errors/modelEmptyCompletion.ts
index 80fa9069071..cd429a8521c 100644
--- a/packages/model-runtime/src/errors/modelEmptyCompletion.ts
+++ b/packages/model-runtime/src/errors/modelEmptyCompletion.ts
@@ -21,8 +21,8 @@ export interface ModelEmptyCompletionDiagnostics {
* does not make an otherwise blank turn visible to the user.
*
* The `errorType` tags this as the terminal `ModelEmptyCompletion` provider
- * error. Callers surface it immediately so the user can decide whether another
- * potentially billable request should be made.
+ * error. Ordinary callers surface it immediately. A managed router may instead
+ * authorize route fallback while the attempt is still buffered and uncommitted.
*/
export class ModelEmptyError extends Error {
readonly errorType = AgentRuntimeErrorType.ModelEmptyCompletion;
diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.ts
index cf548f8614a..e295949ca2b 100644
--- a/packages/model-runtime/src/types/chat.ts
+++ b/packages/model-runtime/src/types/chat.ts
@@ -274,6 +274,12 @@ export interface OnFinishData {
finishReason?: string;
grounding?: any;
reasoning?: ModelReasoning;
+ /** Stable identities and terminal outcome for the provider attempt producing this result. */
+ routeAttempt?: {
+ attemptId: string;
+ outcome?: 'completed' | 'empty' | 'interrupted' | 'cancelled' | 'failed';
+ requestId: string;
+ };
speed?: ModelPerformance;
text: string;
thinking?: string;