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): keep provider message on plain stream chunk errors (#20209)

YuTengjing9d4db086e785
diff --git a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts
index 0a412262aff..5f106cc4ced 100644
--- a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.test.ts
@@ -350,6 +350,45 @@ describe('observeChatAttempt', () => {
}
});
+ it.each([
+ {
+ error: {
+ body: { message: 'The content was blocked for safety reasons.', provider: 'google' },
+ type: 'ProviderContentPolicyViolation',
+ },
+ expected: 'The content was blocked for safety reasons.',
+ },
+ {
+ error: { message: 'Internal error encountered.', name: 'Stream parsing error' },
+ expected: 'Internal error encountered.',
+ },
+ ])(
+ 'keeps the provider message when a plain error payload interrupts visible output',
+ async ({ error, expected }) => {
+ const finished = vi.fn();
+ const response = await observeChatAttempt(
+ async ({ callback }) => {
+ await callback?.onText?.('partial');
+ await callback?.onError?.(error);
+ await callback?.onFinal?.({ text: 'partial' });
+ return new Response('done');
+ },
+ undefined,
+ attempt,
+ true,
+ finished,
+ );
+ await response.text();
+
+ const streamError = finished.mock.calls[0][0].error;
+ expect(streamError).toMatchObject({
+ error: { cause: error, message: expected, name: 'StreamChunkError' },
+ message: expected,
+ name: 'StreamChunkError',
+ });
+ },
+ );
+
it.each([
{ expectedOutcome: 'completed', text: 'I cannot help with that.' },
{ expectedOutcome: 'empty', text: '' },
diff --git a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts
index 6f976a2ac3d..12876fa231c 100644
--- a/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/chatAttempt.ts
@@ -2,6 +2,7 @@ import type { ModelUsage } from '@lobechat/types';
import { AgentRuntimeErrorType } from '@lobechat/types';
import {
+ extractErrorMessage,
isEmptyModelCompletion,
isModelRefusalFinishReason,
ModelEmptyError,
@@ -29,13 +30,23 @@ export const getChatAttemptObservation = (response: Response): ChatAttemptObserv
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 }),
+/**
+ * Stream errors are often plain runtime payloads such as
+ * `{ type: 'ProviderContentPolicyViolation', body: { message } }`; `String()` would turn them
+ * into `[object Object]` and lose the provider reason in error logs (LOBE-14421).
+ */
+const streamErrorMessage = (error: unknown): string =>
+ (error instanceof Error ? error.message : extractErrorMessage(error)) ?? String(error);
+
+const createStreamChunkError = (error: unknown, provider: string) => {
+ const message = streamErrorMessage(error);
+
+ return Object.assign(
+ new Error(message, { cause: error }),
AgentRuntimeError.chat({
error: {
cause: error,
- message: error instanceof Error ? error.message : String(error),
+ message,
name: 'StreamChunkError',
},
errorType: AgentRuntimeErrorType.StreamChunkError,
@@ -43,6 +54,7 @@ const createStreamChunkError = (error: unknown, provider: string) =>
}),
{ name: 'StreamChunkError' },
);
+};
/**
* Observe the actual response body lifecycle. Terminal callbacks are delayed until
diff --git a/packages/model-runtime/src/errors/index.ts b/packages/model-runtime/src/errors/index.ts
index de6bf1a79d0..67af4437ca2 100644
--- a/packages/model-runtime/src/errors/index.ts
+++ b/packages/model-runtime/src/errors/index.ts
@@ -4,7 +4,7 @@ export { getRuntimeErrorI18nKey, type RuntimeErrorI18nKey } from './i18nKey';
export { isUserSideError, matchErrorPattern, type MatchInput, type MatchResult } from './match';
export { isEmptyModelCompletion, ModelEmptyError } from './modelEmptyCompletion';
export { isModelRefusalFinishReason, ModelRefusalError } from './modelRefusal';
-export { normalizeChatMessageError } from './normalizeChatMessageError';
+export { extractErrorMessage, normalizeChatMessageError } from './normalizeChatMessageError';
export { ERROR_PATTERNS, type ErrorPattern } from './patterns';
export { refineErrorCode, type RefineErrorInput } from './refine';
export {
diff --git a/packages/model-runtime/src/errors/normalizeChatMessageError.ts b/packages/model-runtime/src/errors/normalizeChatMessageError.ts
index 17f99fe70f3..6da9ec3cb0c 100644
--- a/packages/model-runtime/src/errors/normalizeChatMessageError.ts
+++ b/packages/model-runtime/src/errors/normalizeChatMessageError.ts
@@ -22,14 +22,18 @@ const extractProvider = (body: unknown): string | undefined => {
return typeof p === 'string' ? p : undefined;
};
-const extractMessage = (value: unknown, depth = 0): string | undefined => {
+/**
+ * Find the first human-readable message in an error value, walking the nested `error`,
+ * `_responseBody` and `body` layers that runtime payloads use.
+ */
+export const extractErrorMessage = (value: unknown, depth = 0): string | undefined => {
if (typeof value === 'string') return value.trim() ? value : undefined;
if (!isRecord(value) || depth > 5) return undefined;
if (typeof value.message === 'string' && value.message.trim() && value.message !== 'error') {
return value.message;
}
for (const nested of [value.error, value._responseBody, value.body]) {
- const message = extractMessage(nested, depth + 1);
+ const message = extractErrorMessage(nested, depth + 1);
if (message) return message;
}
};
@@ -197,9 +201,9 @@ export const normalizeChatMessageError = (error: unknown): ChatMessageError => {
};
const message =
(payload.message && payload.message !== 'error' ? payload.message : undefined) ??
- extractMessage(payload.body) ??
- extractMessage(payload._responseBody) ??
- extractMessage(payload.error) ??
+ extractErrorMessage(payload.body) ??
+ extractErrorMessage(payload._responseBody) ??
+ extractErrorMessage(payload.error) ??
String(payload.errorType);
return enrichWithSpec({
@@ -222,7 +226,7 @@ export const normalizeChatMessageError = (error: unknown): ChatMessageError => {
typeof (error as { type: unknown }).type === 'number')
) {
const formatted = error as ChatMessageError;
- const message = extractMessage(formatted);
+ const message = extractErrorMessage(formatted);
return enrichWithSpec({ ...formatted, ...(message ? { message } : {}) });
}
@@ -256,7 +260,7 @@ export const normalizeChatMessageError = (error: unknown): ChatMessageError => {
if (isRecord(error)) {
return enrichWithSpec({
body: error,
- message: extractMessage(error) ?? 'Agent runtime error',
+ message: extractErrorMessage(error) ?? 'Agent runtime error',
type:
typeof error.code === 'string'
? (getErrorCodeSpec(error.code)?.code ?? AgentRuntimeErrorType.AgentRuntimeError)