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): enrich stream parse errors with provider/model context (#14636)

Arvin Xu0f9b6904fd4c
diff --git a/packages/model-runtime/src/core/streams/anthropic.ts b/packages/model-runtime/src/core/streams/anthropic.ts
index a22744508ac..97f8e89ff46 100644
--- a/packages/model-runtime/src/core/streams/anthropic.ts
+++ b/packages/model-runtime/src/core/streams/anthropic.ts
@@ -237,7 +237,9 @@ export const AnthropicStream = (
const streamStack: StreamContext = { id: '' };
const readableStream =
- stream instanceof ReadableStream ? stream : convertIterableToStream(stream);
+ stream instanceof ReadableStream
+ ? stream
+ : convertIterableToStream(stream, { model: payload?.model, provider: payload?.provider });
const transformWithPayload: typeof transformAnthropicStream = (chunk, ctx) =>
transformAnthropicStream(chunk, ctx, payload);
diff --git a/packages/model-runtime/src/core/streams/openai/openai.ts b/packages/model-runtime/src/core/streams/openai/openai.ts
index b4477e4871c..d5bd35b2c1f 100644
--- a/packages/model-runtime/src/core/streams/openai/openai.ts
+++ b/packages/model-runtime/src/core/streams/openai/openai.ts
@@ -629,7 +629,9 @@ export const OpenAIStream = (
transformOpenAIStream(chunk, streamContext, payload);
const readableStream =
- stream instanceof ReadableStream ? stream : convertIterableToStream(stream);
+ stream instanceof ReadableStream
+ ? stream
+ : convertIterableToStream(stream, { model: payload?.model, provider: payload?.provider });
return (
readableStream
diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.ts
index e1cfea1ee7f..311fac63807 100644
--- a/packages/model-runtime/src/core/streams/openai/responsesStream.ts
+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.ts
@@ -205,7 +205,9 @@ export const OpenAIResponsesStream = (
const streamStack: StreamContext = { id: '' };
const readableStream =
- stream instanceof ReadableStream ? stream : convertIterableToStream(stream);
+ stream instanceof ReadableStream
+ ? stream
+ : convertIterableToStream(stream, { model: payload?.model, provider: payload?.provider });
// use closure to pass payload to transformOpenAIStream
const transformWithPayload: typeof transformOpenAIStream = (chunk, streamContext) =>
diff --git a/packages/model-runtime/src/core/streams/protocol.test.ts b/packages/model-runtime/src/core/streams/protocol.test.ts
index 2865217eefa..43c92c1bf55 100644
--- a/packages/model-runtime/src/core/streams/protocol.test.ts
+++ b/packages/model-runtime/src/core/streams/protocol.test.ts
@@ -243,29 +243,138 @@ describe('createTokenSpeedCalculator', async () => {
});
describe('convertIterableToStream', () => {
- it('should surface errors from subsequent pulls as error chunks', async () => {
- async function* erroringStream() {
- yield 'first';
- throw new Error('rate limit');
- }
-
- const readable = convertIterableToStream(erroringStream()).pipeThrough(
- createFirstErrorHandleTransformer(),
- );
-
+ const drain = async (readable: ReadableStream<any>) => {
const reader = readable.getReader();
const chunks: any[] = [];
-
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
}
+ return chunks;
+ };
+
+ it('should surface errors from subsequent pulls as error chunks', async () => {
+ async function* erroringStream() {
+ yield 'first';
+ throw new Error('rate limit');
+ }
+
+ const chunks = await drain(
+ convertIterableToStream(erroringStream()).pipeThrough(createFirstErrorHandleTransformer()),
+ );
expect(chunks[0]).toBe('first');
expect(chunks[1][FIRST_CHUNK_ERROR_KEY]).toBe(true);
expect(chunks[1].message).toBe('rate limit');
});
+
+ it('should enrich error chunks with provider/model context', async () => {
+ async function* erroringStream() {
+ yield 'first';
+ throw new Error('connection reset');
+ }
+
+ const chunks = await drain(
+ convertIterableToStream(erroringStream(), {
+ model: 'deepseek-v4-flash',
+ provider: 'lobehub',
+ }).pipeThrough(createFirstErrorHandleTransformer(undefined, 'lobehub')),
+ );
+
+ expect(chunks[1].message).toBe('connection reset');
+ expect(chunks[1].provider).toBe('lobehub');
+ expect(chunks[1].model).toBe('deepseek-v4-flash');
+ });
+
+ it('should extract parse position from JSON SyntaxError messages', async () => {
+ async function* erroringStream() {
+ yield 'first';
+ // Reproduce the V8 JSON.parse SyntaxError shape that surfaces from the
+ // OpenAI SDK iterator when an upstream SSE chunk contains an illegal
+ // backslash escape β€” see LobeHub op_1778403331540 for a real instance.
+ throw new SyntaxError(
+ 'Bad escaped character in JSON at position 160050 (line 1 column 160051)',
+ );
+ }
+
+ const chunks = await drain(
+ convertIterableToStream(erroringStream(), { provider: 'lobehub' }).pipeThrough(
+ createFirstErrorHandleTransformer(undefined, 'lobehub'),
+ ),
+ );
+
+ expect(chunks[1].name).toBe('SyntaxError');
+ expect(chunks[1].parsePosition).toBe(160050);
+ });
+
+ it('should surface error.cause when present', async () => {
+ async function* erroringStream() {
+ yield 'first';
+ throw new Error('wrapper', { cause: new SyntaxError('inner parse failure') });
+ }
+
+ const chunks = await drain(
+ convertIterableToStream(erroringStream()).pipeThrough(createFirstErrorHandleTransformer()),
+ );
+
+ expect(chunks[1].causeName).toBe('SyntaxError');
+ expect(chunks[1].causeMessage).toBe('inner parse failure');
+ });
+
+ it('should extract parsePosition from a wrapped SyntaxError cause', async () => {
+ // Many provider SDKs rethrow JSON.parse failures wrapped in their own
+ // error class (e.g. APIError) β€” the outer name is no longer
+ // 'SyntaxError', so the offset has to be pulled from `cause`.
+ class APIError extends Error {
+ constructor(message: string, options?: { cause?: unknown }) {
+ super(message, options);
+ this.name = 'APIError';
+ }
+ }
+
+ async function* erroringStream() {
+ yield 'first';
+ throw new APIError('upstream failed', {
+ cause: new SyntaxError(
+ 'Bad escaped character in JSON at position 160050 (line 1 column 160051)',
+ ),
+ });
+ }
+
+ const chunks = await drain(
+ convertIterableToStream(erroringStream()).pipeThrough(createFirstErrorHandleTransformer()),
+ );
+
+ expect(chunks[1].name).toBe('APIError');
+ expect(chunks[1].causeName).toBe('SyntaxError');
+ expect(chunks[1].parsePosition).toBe(160050);
+ });
+
+ it('should not throw when cause contains BigInt or circular refs', async () => {
+ // structuredClone accepts both of these; JSON.stringify does not. If the
+ // outer stringify in buildStreamErrorPayload fails, the FIRST_CHUNK_ERROR
+ // chunk is never emitted and the stream silently dies β€” test that the
+ // diagnostic path stays intact.
+ const circular: Record<string, unknown> = { kind: 'detail' };
+ circular.self = circular;
+ const badCause = { big: 9_007_199_254_740_993n, ref: circular };
+
+ async function* erroringStream() {
+ yield 'first';
+ throw new Error('upstream blew up', { cause: badCause });
+ }
+
+ const chunks = await drain(
+ convertIterableToStream(erroringStream()).pipeThrough(createFirstErrorHandleTransformer()),
+ );
+
+ expect(chunks[1].message).toBe('upstream blew up');
+ // Cause is an object, not an Error, so it goes through `toJsonSafe`.
+ expect(chunks[1].cause).toBeDefined();
+ expect(chunks[1].cause.big).toBe('9007199254740993');
+ expect(chunks[1].cause.ref.self).toBe('[Circular]');
+ });
});
describe('createSSEProtocolTransformer', () => {
diff --git a/packages/model-runtime/src/core/streams/protocol.ts b/packages/model-runtime/src/core/streams/protocol.ts
index e52998a55d0..9ac281fe979 100644
--- a/packages/model-runtime/src/core/streams/protocol.ts
+++ b/packages/model-runtime/src/core/streams/protocol.ts
@@ -144,7 +144,121 @@ const chatStreamable = async function* <T>(stream: AsyncIterable<T>) {
const ERROR_CHUNK_PREFIX = '%FIRST_CHUNK_ERROR%: ';
-export function readableFromAsyncIterable<T>(iterable: AsyncIterable<T>) {
+/**
+ * Optional diagnostic context attached to errors that surface from the
+ * provider SDK iterator. Lets the FIRST_CHUNK_ERROR payload carry
+ * provider/model identifiers so log triage can correlate identical
+ * upstream failures across operations.
+ */
+export type StreamErrorContext = {
+ model?: string;
+ provider?: string;
+};
+
+/**
+ * Build the FIRST_CHUNK_ERROR payload string for a thrown error.
+ *
+ * Beyond `message`/`name`/`stack`, this surfaces:
+ * - `provider`/`model` from the caller, so error-log consumers know which
+ * upstream blew up without grepping for the operation
+ * - `causeMessage`/`causeName` when `error.cause` is set β€” many wrapped
+ * errors (e.g. APIError around a SyntaxError) bury the actionable detail
+ * in `cause` and the bare triplet drops it
+ * - `parsePosition` extracted from V8 JSON SyntaxError messages
+ * (e.g. `"Bad escaped character in JSON at position 160050"`) so we can
+ * group by failure offset and confirm the same chunk class is recurring.
+ * Walks both the outer error and any Error cause β€” SDKs commonly wrap
+ * the SyntaxError in an APIError, and the wrapped case is exactly the
+ * one this enrichment is meant to diagnose.
+ */
+const buildStreamErrorPayload = (error: Error, context?: StreamErrorContext): string => {
+ const payload: Record<string, unknown> = {
+ message: error.message,
+ name: error.name,
+ stack: error.stack,
+ };
+
+ if (context?.provider) payload.provider = context.provider;
+ if (context?.model) payload.model = context.model;
+
+ const cause = (error as { cause?: unknown }).cause;
+ const causeAsError = cause instanceof Error ? cause : undefined;
+
+ if (causeAsError) {
+ payload.causeName = causeAsError.name;
+ payload.causeMessage = causeAsError.message;
+ } else if (cause !== undefined && cause !== null) {
+ payload.cause = typeof cause === 'object' ? toJsonSafe(cause) : String(cause);
+ }
+
+ const parsePosition = extractParsePosition(error) ?? extractParsePosition(causeAsError);
+ if (parsePosition !== undefined) payload.parsePosition = parsePosition;
+
+ return ERROR_CHUNK_PREFIX + safeJsonStringify(payload);
+};
+
+/**
+ * Extract a JSON parse offset from V8's `SyntaxError` message format
+ * (`"... in JSON at position N (line ... column ...)"`). Accepts either a
+ * `SyntaxError` directly or any `Error` whose message still carries the
+ * `"JSON at position"` signature β€” wrapped errors routinely lose the
+ * `SyntaxError` name but preserve the offset in the message string.
+ */
+const extractParsePosition = (error: Error | undefined): number | undefined => {
+ if (!error) return undefined;
+ const isJsonParseError = error.name === 'SyntaxError' || /JSON at position/i.test(error.message);
+ if (!isJsonParseError) return undefined;
+ const match = /position\s+(\d+)/i.exec(error.message);
+ return match ? Number(match[1]) : undefined;
+};
+
+/**
+ * `JSON.stringify` with a replacer that handles `BigInt` and circular refs
+ * so the outer stringify in `buildStreamErrorPayload` never throws.
+ *
+ * If this throws, the FIRST_CHUNK_ERROR chunk never gets emitted and a
+ * diagnostic path turns into a hard stream failure β€” `safeJsonStringify`
+ * is the difference between "consumer sees a typed error" and "consumer
+ * sees the stream just stop".
+ */
+const safeJsonStringify = (value: unknown): string => {
+ const seen = new WeakSet<object>();
+ try {
+ return JSON.stringify(value, (_key, val) => {
+ if (typeof val === 'bigint') return val.toString();
+ if (typeof val === 'object' && val !== null) {
+ if (seen.has(val as object)) return '[Circular]';
+ seen.add(val as object);
+ }
+ return val;
+ });
+ } catch {
+ return JSON.stringify({
+ message: 'Failed to serialize error payload',
+ name: 'StreamErrorSerializationFailure',
+ });
+ }
+};
+
+/**
+ * Reduce an arbitrary cause object to a JSON-safe shape. `structuredClone`
+ * succeeds on values that `JSON.stringify` later chokes on (cycles, BigInt,
+ * functions in nested values), so the clone alone isn't enough β€” we run
+ * the result through `safeJsonStringify` and parse it back so consumers
+ * always receive plain JSON.
+ */
+const toJsonSafe = (cause: object): unknown => {
+ try {
+ return JSON.parse(safeJsonStringify(cause));
+ } catch {
+ return String(cause);
+ }
+};
+
+export function readableFromAsyncIterable<T>(
+ iterable: AsyncIterable<T>,
+ context?: StreamErrorContext,
+) {
const it = iterable[Symbol.asyncIterator]();
return new ReadableStream<T>({
async cancel(reason) {
@@ -157,12 +271,7 @@ export function readableFromAsyncIterable<T>(iterable: AsyncIterable<T>) {
if (done) controller.close();
else controller.enqueue(value);
} catch (e) {
- const error = e as Error;
-
- controller.enqueue(
- (ERROR_CHUNK_PREFIX +
- JSON.stringify({ message: error.message, name: error.name, stack: error.stack })) as T,
- );
+ controller.enqueue(buildStreamErrorPayload(e as Error, context) as T);
controller.close();
}
},
@@ -170,7 +279,10 @@ export function readableFromAsyncIterable<T>(iterable: AsyncIterable<T>) {
}
// make the response to the streamable format
-export const convertIterableToStream = <T>(stream: AsyncIterable<T>) => {
+export const convertIterableToStream = <T>(
+ stream: AsyncIterable<T>,
+ context?: StreamErrorContext,
+) => {
const iterable = chatStreamable(stream);
// copy from https://github.com/vercel/ai/blob/d3aa5486529e3d1a38b30e3972b4f4c63ea4ae9a/packages/ai/streams/ai-stream.ts#L284
@@ -187,12 +299,7 @@ export const convertIterableToStream = <T>(stream: AsyncIterable<T>) => {
if (done) controller.close();
else controller.enqueue(value);
} catch (e) {
- const error = e as Error;
-
- controller.enqueue(
- (ERROR_CHUNK_PREFIX +
- JSON.stringify({ message: error.message, name: error.name, stack: error.stack })) as T,
- );
+ controller.enqueue(buildStreamErrorPayload(e as Error, context) as T);
controller.close();
}
},
@@ -203,12 +310,7 @@ export const convertIterableToStream = <T>(stream: AsyncIterable<T>) => {
if (done) controller.close();
else controller.enqueue(value);
} catch (e) {
- const error = e as Error;
-
- controller.enqueue(
- (ERROR_CHUNK_PREFIX +
- JSON.stringify({ message: error.message, name: error.name, stack: error.stack })) as T,
- );
+ controller.enqueue(buildStreamErrorPayload(e as Error, context) as T);
controller.close();
}
},