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): fall back image-output chat before the final image (#21424)

YuTengjinge153a036602f
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/formatErrorEventData.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/formatErrorEventData.test.ts
index 23e5021d6d5..24642e58c37 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/formatErrorEventData.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/formatErrorEventData.test.ts
@@ -175,6 +175,23 @@ describe('formatErrorEventData', () => {
});
});
+ it('keeps the provider and trace id of a provider stream error in the event body', () => {
+ const err = Object.assign(new Error('got status: RESOURCE_EXHAUSTED'), {
+ _responseBody: { traceId: 'trace-1' },
+ error: { message: 'got status: RESOURCE_EXHAUSTED', name: 'StreamChunkError' },
+ errorType: AgentRuntimeErrorType.StreamChunkError,
+ provider: 'lobehub',
+ });
+
+ const out = formatErrorEventData(err, 'llm_execution');
+
+ expect(out).toMatchObject({
+ body: { provider: 'lobehub', traceId: 'trace-1' },
+ error: 'got status: RESOURCE_EXHAUSTED',
+ errorType: AgentRuntimeErrorType.StreamChunkError,
+ });
+ });
+
it('preserves a custom errorType even when no .cause PG info exists', () => {
const err = Object.assign(new Error('rate limited'), {
errorType: 'ProviderRateLimited',
diff --git a/apps/server/src/modules/AgentRuntime/formatErrorEventData.ts b/apps/server/src/modules/AgentRuntime/formatErrorEventData.ts
index dc2fe6e8d89..2bcdb301e2d 100644
--- a/apps/server/src/modules/AgentRuntime/formatErrorEventData.ts
+++ b/apps/server/src/modules/AgentRuntime/formatErrorEventData.ts
@@ -34,12 +34,17 @@ export const formatErrorEventData = (error: unknown, phase: string) => {
const rawPayloadErrorType = payload?.errorType ?? payload?.type;
const payloadErrorType = isErrorType(rawPayloadErrorType) ? rawPayloadErrorType : undefined;
/**
- * Runtime completion errors carry their provider/model diagnostics on the Error instance.
- * Keep that body so the client can persist it and render provider-specific error UI;
- * other Error instances keep the flat shape.
+ * Runtime completion errors and provider chat errors thrown as Error instances (e.g. a
+ * `StreamChunkError` raised while consuming the model stream) carry their provider,
+ * diagnostics, and trace id on the instance. Keep that body so the client can persist it
+ * and render provider-specific error UI; other Error instances keep the flat shape.
*/
const isRuntimeCompletionError =
- error instanceof ModelEmptyError || error instanceof ModelRefusalError;
+ error instanceof ModelEmptyError ||
+ error instanceof ModelRefusalError ||
+ (error instanceof Error &&
+ payloadErrorType !== undefined &&
+ pickNonEmptyString(payload?.provider) !== undefined);
const structuredError = isRuntimeCompletionError
? formatErrorForState(error)
: error instanceof Error || payloadErrorType === undefined
diff --git a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts
index 29ab6d73891..374f87d876d 100644
--- a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts
@@ -68,8 +68,17 @@ export const observeChatAttempt = async (
attempt: RouteAttemptStart,
streaming: boolean,
onFinished: (result: RouteAttemptFinished) => Promise<void> | void,
- observerOptions?: { deferCallbacks?: boolean },
+ observerOptions?: {
+ deferCallbacks?: boolean;
+ /**
+ * Image-output models stream thinking text and interim thought images long before the
+ * final image. Treat that reasoning as provisional so an upstream failure before the
+ * deliverable can still fall back instead of committing a stream with nothing usable.
+ */
+ holdReasoning?: boolean;
+ },
): Promise<Response> => {
+ const reasoningIsVisible = !observerOptions?.holdReasoning;
const attemptDiagnostics: ModelRuntimeDiagnostics = {};
let committed = !observerOptions?.deferCallbacks;
let discarded = false;
@@ -79,6 +88,8 @@ export const observeChatAttempt = async (
let streamError: unknown;
let visibleOutput = false;
let imageCount = 0;
+ /** Images in response content, excluding interim thought images streamed as reasoning. */
+ let deliverableImageCount = 0;
let toolCallCount = 0;
let grounding: unknown;
let content = '';
@@ -223,12 +234,16 @@ export const observeChatAttempt = async (
* Provider-internal reasoning alone must not turn a blank refusal into a success.
*/
const isRefusal = isModelRefusalFinishReason(latestFinishData.finishReason);
+ /**
+ * Held reasoning is provisional, so a clean finish with only thinking and thought images
+ * (e.g. `MAX_TOKENS` before the final image) is empty and can still fall back.
+ */
const empty = isEmptyModelCompletion({
content: finalContent,
hasGrounding: Boolean(latestFinishData.grounding ?? grounding),
- imageCount,
+ imageCount: reasoningIsVisible ? imageCount : deliverableImageCount,
outputTokens: latestFinishData.usage?.totalOutputTokens ?? observedUsage?.totalOutputTokens,
- reasoning: isRefusal ? '' : finalReasoning,
+ reasoning: isRefusal || !reasoningIsVisible ? '' : finalReasoning,
toolCallCount: finalToolCallCount,
});
@@ -275,7 +290,7 @@ export const observeChatAttempt = async (
grounding ??= data.grounding;
if (
data.text.trim() ||
- getReasoningContent(data).trim() ||
+ (reasoningIsVisible && getReasoningContent(data).trim()) ||
(data.toolsCalling?.length ?? 0) > 0
) {
visibleOutput = true;
@@ -287,6 +302,7 @@ export const observeChatAttempt = async (
...callback,
onBase64Image: async (data) => {
imageCount = Math.max(imageCount, data.images.length);
+ deliverableImageCount = Math.max(deliverableImageCount, data.images.length);
visibleOutput = true;
await runOrBuffer(async () => {
await callback?.onBase64Image?.(data);
@@ -296,8 +312,10 @@ export const observeChatAttempt = async (
terminalCallback(callback?.onCompletion, data);
},
onContentPart: async (data) => {
- if (data.partType === 'image') imageCount += 1;
- else content += data.content;
+ if (data.partType === 'image') {
+ imageCount += 1;
+ deliverableImageCount += 1;
+ } else content += data.content;
if (data.partType === 'image' || data.content.trim()) visibleOutput = true;
await runOrBuffer(async () => {
await callback?.onContentPart?.(data);
@@ -322,7 +340,9 @@ export const observeChatAttempt = async (
onReasoningPart: async (data) => {
if (data.partType === 'image') imageCount += 1;
else reasoning += data.content;
- if (data.partType === 'image' || data.content.trim()) visibleOutput = true;
+ if (reasoningIsVisible && (data.partType === 'image' || data.content.trim())) {
+ visibleOutput = true;
+ }
await runOrBuffer(async () => {
await callback?.onReasoningPart?.(data);
});
@@ -341,7 +361,7 @@ export const observeChatAttempt = async (
},
onThinking: async (text) => {
reasoning += text;
- if (text.trim()) visibleOutput = true;
+ if (reasoningIsVisible && text.trim()) visibleOutput = true;
await runOrBuffer(async () => {
await callback?.onThinking?.(text);
});
diff --git a/packages/model-runtime/src/core/RouterRuntime/chatFallbackHooks.ts b/packages/model-runtime/src/core/RouterRuntime/chatFallbackHooks.ts
new file mode 100644
index 00000000000..9f46148c075
--- /dev/null
+++ b/packages/model-runtime/src/core/RouterRuntime/chatFallbackHooks.ts
@@ -0,0 +1,34 @@
+import debug from 'debug';
+
+import type { RouteAttemptFinished } from './routeAttempt';
+import type { CreateRouterRuntimeOptions } from './routerOptions';
+
+const log = debug('lobe-model-runtime:router-runtime');
+
+/**
+ * Image-output models hold their reasoning until the final image so a failure before it can
+ * still fall back. An unknown capability keeps the regular commit rule rather than failing.
+ */
+export const resolveHoldReasoning = async (
+ isImageOutputModel: CreateRouterRuntimeOptions['isImageOutputModel'],
+ model: string,
+): Promise<boolean> => {
+ try {
+ return Boolean(await isImageOutputModel?.(model));
+ } catch (error) {
+ console.error('[RouterRuntime] isImageOutputModel callback failed:', error);
+ return false;
+ }
+};
+
+/** A failing policy callback must not restart a provider call, so it resolves to no fallback. */
+export const createChatAttemptFallbackCheck =
+ (shouldFallbackChatAttempt: CreateRouterRuntimeOptions['shouldFallbackChatAttempt']) =>
+ async (result: RouteAttemptFinished): Promise<boolean> => {
+ try {
+ return Boolean(await shouldFallbackChatAttempt?.(result));
+ } catch (error) {
+ log('shouldFallbackChatAttempt callback error: %O', error);
+ return false;
+ }
+ };
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.imageOutput.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.imageOutput.test.ts
new file mode 100644
index 00000000000..f364b24bdaa
--- /dev/null
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.imageOutput.test.ts
@@ -0,0 +1,239 @@
+import { AgentRuntimeErrorType, RequestTrigger } from '@lobechat/types';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { ChatMethodOptions } from '../../types';
+import type { LobeRuntimeAI } from '../BaseAI';
+import { createRouterRuntime } from './createRuntime';
+
+const encoder = new TextEncoder();
+
+const quotaError = {
+ body: { message: 'got status: RESOURCE_EXHAUSTED', provider: 'google' },
+ message: 'got status: RESOURCE_EXHAUSTED',
+ name: 'Stream parsing error',
+ type: AgentRuntimeErrorType.QuotaLimitReached,
+};
+
+/**
+ * Mirrors a Gemini image-output stream: thinking text and an interim thought image arrive
+ * long before the final image, and an upstream 429 can end the stream in between.
+ */
+const createImageModelResponse = (
+ options: ChatMethodOptions | undefined,
+ config: { ending?: 'error' | 'image' | 'max-tokens'; label: string },
+) =>
+ new Response(
+ new ReadableStream({
+ async start(controller) {
+ await options?.callback?.onReasoningPart?.({
+ content: `${config.label} thinking`,
+ partType: 'text',
+ });
+ controller.enqueue(encoder.encode(`${config.label}:thinking;`));
+ await options?.callback?.onReasoningPart?.({
+ content: 'AA==',
+ mimeType: 'image/png',
+ partType: 'image',
+ });
+ controller.enqueue(encoder.encode(`${config.label}:thought-image;`));
+
+ if (config.ending === 'image') {
+ await options?.callback?.onContentPart?.({
+ content: 'AA==',
+ mimeType: 'image/png',
+ partType: 'image',
+ });
+ controller.enqueue(encoder.encode(`${config.label}:image;`));
+ const final = { finishReason: 'STOP', text: '', thinking: `${config.label} thinking` };
+ await options?.callback?.onCompletion?.(final);
+ await options?.callback?.onFinal?.(final);
+ } else if (config.ending === 'max-tokens') {
+ const final = {
+ finishReason: 'MAX_TOKENS',
+ text: '',
+ thinking: `${config.label} thinking`,
+ };
+ await options?.callback?.onCompletion?.(final);
+ await options?.callback?.onFinal?.(final);
+ } else {
+ await options?.callback?.onError?.(quotaError);
+ controller.enqueue(encoder.encode(`${config.label}:error;`));
+ const final = { error: quotaError, text: '', thinking: `${config.label} thinking` };
+ await options?.callback?.onCompletion?.(final);
+ await options?.callback?.onFinal?.(final);
+ }
+ controller.close();
+ },
+ }),
+ );
+
+/** `Response.text()` in happy-dom hides the stream error behind an EncodingError. */
+const readStreamError = async (response: Response) => {
+ const reader = response.body!.getReader();
+ try {
+ while (!(await reader.read()).done);
+ } catch (error) {
+ return error;
+ }
+};
+
+const createRuntime = (
+ isImageOutputModel: (model: string) => boolean | Promise<boolean>,
+ firstEnding: 'error' | 'max-tokens' = 'error',
+) => {
+ let calls = 0;
+
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) => {
+ calls += 1;
+ return createImageModelResponse(options, {
+ ending: calls > 1 ? 'image' : firstEnding,
+ label: `attempt-${calls}`,
+ });
+ };
+ }
+
+ const finished = vi.fn();
+ const Runtime = createRouterRuntime({
+ id: 'lobehub',
+ isImageOutputModel,
+ onRouteAttemptFinished: finished,
+ routers: [
+ {
+ apiType: 'google',
+ id: 'image-router',
+ models: ['gemini-nano-banana-2.1'],
+ options: [{ id: 'channel-a' }, { id: 'channel-b' }],
+ runtime: MockRuntime,
+ },
+ ],
+ shouldFallbackChatAttempt: () => true,
+ });
+
+ return { finished, getCalls: () => calls, runtime: new Runtime({ userId: 'user-1' }) };
+};
+
+describe('createRouterRuntime image-output stream fallback', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('falls back when an image-output attempt fails after only reasoning was streamed', async () => {
+ const isImageOutputModel = vi.fn().mockResolvedValue(true);
+ const { finished, getCalls, runtime } = createRuntime(isImageOutputModel);
+ const onReasoningPart = vi.fn();
+ const onContentPart = vi.fn();
+ const onError = vi.fn();
+
+ const response = await runtime.chat(
+ { messages: [], model: 'gemini-nano-banana-2.1' },
+ {
+ callback: { onContentPart, onError, onReasoningPart },
+ metadata: { trigger: RequestTrigger.Chat },
+ },
+ );
+
+ expect(await response.text()).toBe(
+ 'attempt-2:thinking;attempt-2:thought-image;attempt-2:image;',
+ );
+ expect(getCalls()).toBe(2);
+ expect(isImageOutputModel).toHaveBeenCalledWith('gemini-nano-banana-2.1');
+ expect(onReasoningPart.mock.calls.map(([part]) => part.content)).toEqual([
+ 'attempt-2 thinking',
+ 'AA==',
+ ]);
+ expect(onContentPart).toHaveBeenCalledOnce();
+ expect(onError).not.toHaveBeenCalled();
+ expect(finished.mock.calls.map(([result]) => result.outcome)).toEqual([
+ 'interrupted',
+ 'completed',
+ ]);
+ // The failed channel keeps the upstream error type so health checks and fallback
+ // policy see the 429 instead of a generic partial-output StreamChunkError.
+ expect(finished.mock.calls[0][0]).toMatchObject({
+ channelId: 'channel-a',
+ error: { type: AgentRuntimeErrorType.QuotaLimitReached },
+ success: false,
+ });
+ });
+
+ it('falls back when an image-output attempt ends cleanly with only reasoning', async () => {
+ const { finished, getCalls, runtime } = createRuntime(() => true, 'max-tokens');
+ const onReasoningPart = vi.fn();
+
+ const response = await runtime.chat(
+ { messages: [], model: 'gemini-nano-banana-2.1' },
+ { callback: { onReasoningPart }, metadata: { trigger: RequestTrigger.Chat } },
+ );
+
+ expect(await response.text()).toBe(
+ 'attempt-2:thinking;attempt-2:thought-image;attempt-2:image;',
+ );
+ expect(getCalls()).toBe(2);
+ expect(onReasoningPart.mock.calls.map(([part]) => part.content)).toEqual([
+ 'attempt-2 thinking',
+ 'AA==',
+ ]);
+ expect(finished.mock.calls.map(([result]) => result.outcome)).toEqual(['empty', 'completed']);
+ });
+
+ it('keeps reasoning committing output for models without image output', async () => {
+ const { finished, getCalls, runtime } = createRuntime(() => false);
+ const onError = vi.fn();
+
+ const response = await runtime.chat(
+ { messages: [], model: 'gemini-nano-banana-2.1' },
+ { callback: { onError }, metadata: { trigger: RequestTrigger.Chat } },
+ );
+
+ expect(await readStreamError(response)).toMatchObject({ name: 'StreamChunkError' });
+ expect(getCalls()).toBe(1);
+ expect(onError).toHaveBeenCalledOnce();
+ expect(finished.mock.calls.map(([result]) => result.outcome)).toEqual(['interrupted']);
+ });
+
+ it('does not fall back when the policy hook rejects the interrupted image attempt', async () => {
+ let calls = 0;
+ class MockRuntime implements LobeRuntimeAI {
+ chat = async (_payload: unknown, options?: ChatMethodOptions) => {
+ calls += 1;
+ return createImageModelResponse(options, { label: `attempt-${calls}` });
+ };
+ }
+ const shouldFallbackChatAttempt = vi.fn().mockResolvedValue(false);
+ const Runtime = createRouterRuntime({
+ id: 'lobehub',
+ isImageOutputModel: () => true,
+ onRouteAttemptFinished: vi.fn(),
+ routers: [
+ {
+ apiType: 'google',
+ models: ['gemini-nano-banana-2.1'],
+ options: [{ id: 'channel-a' }, { id: 'channel-b' }],
+ runtime: MockRuntime,
+ },
+ ],
+ shouldFallbackChatAttempt,
+ });
+
+ const response = await new Runtime().chat({ messages: [], model: 'gemini-nano-banana-2.1' });
+
+ expect(await readStreamError(response)).toMatchObject({
+ type: AgentRuntimeErrorType.QuotaLimitReached,
+ });
+ expect(calls).toBe(1);
+ expect(shouldFallbackChatAttempt).toHaveBeenCalledOnce();
+ });
+
+ it('treats a failing image-output hook as a regular model', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const { getCalls, runtime } = createRuntime(() => {
+ throw new Error('model config unavailable');
+ });
+
+ const response = await runtime.chat({ messages: [], model: 'gemini-nano-banana-2.1' });
+
+ expect(await readStreamError(response)).toMatchObject({ name: 'StreamChunkError' });
+ expect(getCalls()).toBe(1);
+ });
+});
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index 1fc145273b5..df22bb63f19 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -39,6 +39,7 @@ import { createVideoWithCompletionMode } from '../../utils/videoCompletionMode';
import type { LobeRuntimeAI } from '../BaseAI';
import type { ApiType } from './apiTypes';
import { getChatAttemptObservation, observeChatAttempt } from './chatAttempt';
+import { createChatAttemptFallbackCheck, resolveHoldReasoning } from './chatFallbackHooks';
import type { ChatStreamFallbackAttempt } from './chatStreamFallback';
import { createChatStreamFallbackResponse } from './chatStreamFallback';
import type { RouteAttemptResult, RouteAttemptStart } from './routeAttempt';
@@ -534,6 +535,8 @@ export const createRouterRuntime = ({
}
};
+ const holdReasoning = await resolveHoldReasoning(params.isImageOutputModel, payload.model);
+
const startAttempt = async (optionIndex: number): Promise<ChatStreamFallbackAttempt> => {
const optionItem = routerOptions[optionIndex];
const {
@@ -579,7 +582,7 @@ export const createRouterRuntime = ({
if (routeTasks) routeTasks.track(Promise.resolve(task));
else return task;
},
- { deferCallbacks: true },
+ { deferCallbacks: true, holdReasoning },
);
const durationMs = Date.now() - attempt.startedAt;
reportReturnedAttempt(attempt, {
@@ -665,14 +668,7 @@ export const createRouterRuntime = ({
try {
return await createChatStreamFallbackResponse({
onSettled: routeTasks?.settle,
- shouldFallback: async (result) => {
- try {
- return Boolean(await params.shouldFallbackChatAttempt?.(result));
- } catch (error) {
- log('shouldFallbackChatAttempt callback error: %O', error);
- return false;
- }
- },
+ shouldFallback: createChatAttemptFallbackCheck(params.shouldFallbackChatAttempt),
startAttempt,
totalAttempts: routerOptions.length,
});
diff --git a/packages/model-runtime/src/core/RouterRuntime/routerOptions.ts b/packages/model-runtime/src/core/RouterRuntime/routerOptions.ts
index b8926fc8d0f..f09d4bdf5dc 100644
--- a/packages/model-runtime/src/core/RouterRuntime/routerOptions.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/routerOptions.ts
@@ -154,6 +154,11 @@ export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any>
options: CreateVideoOptions,
) => Promise<HandleCreateVideoWebhookResult>;
id: string;
+ /**
+ * Whether a chat model's deliverable is an image. Its reasoning then stays provisional
+ * during streamed fallback, so a channel failing before the final image falls back.
+ */
+ isImageOutputModel?: (model: string) => boolean | Promise<boolean>;
models?:
| ((params: { client: OpenAI; options?: ConstructorOptions<T> }) => Promise<ChatModelCard[]>)
| {
diff --git a/packages/model-runtime/src/errors/normalizeChatMessageError.test.ts b/packages/model-runtime/src/errors/normalizeChatMessageError.test.ts
index 68161cd5e47..2939a0656b0 100644
--- a/packages/model-runtime/src/errors/normalizeChatMessageError.test.ts
+++ b/packages/model-runtime/src/errors/normalizeChatMessageError.test.ts
@@ -77,6 +77,19 @@ describe('normalizeChatMessageError', () => {
expect(result.body).toMatchObject({ ...providerBody, traceId: 'trace-1' });
});
+ it('keeps hook display fields on a typed stream error payload', () => {
+ const providerBody = { code: 500, message: 'Internal error', provider: 'lobehub' };
+ const result = normalizeChatMessageError({
+ _responseBody: { traceId: 'trace-1' },
+ body: providerBody,
+ message: 'Internal error',
+ type: 'ProviderBizError',
+ });
+
+ expect(result.body).toEqual({ ...providerBody, traceId: 'trace-1' });
+ expect(result).not.toHaveProperty('_responseBody');
+ });
+
it('keeps hook display fields on a plain Error', () => {
const error = Object.assign(new TypeError('terminated'), {
_responseBody: { traceId: 'trace-1' },
diff --git a/packages/model-runtime/src/errors/normalizeChatMessageError.ts b/packages/model-runtime/src/errors/normalizeChatMessageError.ts
index 6da9ec3cb0c..2a7a86a9681 100644
--- a/packages/model-runtime/src/errors/normalizeChatMessageError.ts
+++ b/packages/model-runtime/src/errors/normalizeChatMessageError.ts
@@ -225,9 +225,21 @@ export const normalizeChatMessageError = (error: unknown): ChatMessageError => {
(typeof (error as { type: unknown }).type === 'string' ||
typeof (error as { type: unknown }).type === 'number')
) {
- const formatted = error as ChatMessageError;
+ const { _responseBody: responseBody, ...formatted } = error as ChatMessageError & {
+ _responseBody?: unknown;
+ };
const message = extractErrorMessage(formatted);
- return enrichWithSpec({ ...formatted, ...(message ? { message } : {}) });
+ // Error hooks attach display fields such as `traceId` through `_responseBody`, including on
+ // a typed provider stream error that fails a router's last channel mid-stream.
+ const body =
+ isRecord(responseBody) && responseBody !== formatted.body
+ ? { ...(isRecord(formatted.body) ? formatted.body : {}), ...responseBody }
+ : formatted.body;
+ return enrichWithSpec({
+ ...formatted,
+ ...(body === undefined ? {} : { body }),
+ ...(message ? { message } : {}),
+ });
}
if (error instanceof Error) {