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): stop swallowing terminal stream events as empty completions (#19964)

Arvin Xu1648dd6e7a10
diff --git a/packages/model-runtime/src/core/streams/anthropic.test.ts b/packages/model-runtime/src/core/streams/anthropic.test.ts
index 63569303af5..fb861b69771 100644
--- a/packages/model-runtime/src/core/streams/anthropic.test.ts
+++ b/packages/model-runtime/src/core/streams/anthropic.test.ts
@@ -958,4 +958,50 @@ describe('AnthropicStream', () => {
expect.objectContaining({ error: expect.objectContaining({ message: 'terminated' }) }),
);
});
+
+ describe('relay-shaped failures', () => {
+ const collect = async (events: any[]) => {
+ const onCompletion = vi.fn();
+ const stream = new ReadableStream({
+ start(controller) {
+ for (const event of events) controller.enqueue(event);
+ controller.close();
+ },
+ });
+ const chunks: string[] = [];
+ const reader = AnthropicStream(stream, { callbacks: { onCompletion } }).getReader();
+ const decoder = new TextDecoder();
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(decoder.decode(value, { stream: true }));
+ }
+ return { chunks, completion: onCompletion.mock.calls[0]?.[0] };
+ };
+
+ it('surfaces an inline error event instead of an empty completion', async () => {
+ const { chunks, completion } = await collect([
+ {
+ message: { id: 'msg_1', usage: { input_tokens: 100, output_tokens: 1 } },
+ type: 'message_start',
+ },
+ { error: { message: 'Overloaded', type: 'overloaded_error' }, type: 'error' },
+ ]);
+
+ expect(chunks.some((c) => c.includes('event: error'))).toBe(true);
+ expect(completion.error).toMatchObject({ message: 'Overloaded' });
+ });
+
+ it('names an OpenAI-format answer on an Anthropic endpoint as a malformed response', async () => {
+ const { completion } = await collect([
+ {
+ choices: [{ delta: { content: 'Hello' }, finish_reason: null, index: 0 }],
+ id: 'chatcmpl_1',
+ object: 'chat.completion.chunk',
+ },
+ ]);
+
+ expect(completion.error).toMatchObject({ type: 'UpstreamMalformedResponse' });
+ });
+ });
});
diff --git a/packages/model-runtime/src/core/streams/anthropic.ts b/packages/model-runtime/src/core/streams/anthropic.ts
index b9dedccb604..ffe393a00c5 100644
--- a/packages/model-runtime/src/core/streams/anthropic.ts
+++ b/packages/model-runtime/src/core/streams/anthropic.ts
@@ -50,6 +50,39 @@ export const transformAnthropicStream = (
return { data: errorData, id: 'first_chunk_error', type: 'error' };
}
+ const raw = chunk as unknown as Record<string, unknown>;
+
+ /**
+ * Anthropic reports a mid-stream failure (e.g. `overloaded_error`) as an `error` event. The
+ * official SDK throws on the `event: error` line, but relays often forward the payload as a plain
+ * data frame, which reached the switch below as an unknown event and closed as an empty
+ * completion.
+ */
+ if (raw.type === 'error') {
+ const error = (raw.error ?? {}) as { message?: string; type?: string };
+ const errorData = {
+ body: raw,
+ message: error.message || error.type || 'The provider reported an error mid-stream.',
+ type: AgentRuntimeErrorType.ProviderBizError,
+ } satisfies ChatMessageError;
+ return { data: errorData, id: context.id, type: 'error' };
+ }
+
+ /**
+ * A relay that answers an Anthropic request in OpenAI chat-completions format produces no event
+ * this adapter understands, so the whole answer was dropped and reported as an empty completion.
+ * Name the protocol mismatch instead, so the user knows to fix the provider's API format.
+ */
+ if (Array.isArray(raw.choices) || raw.object === 'chat.completion.chunk') {
+ const errorData = {
+ body: raw,
+ message:
+ 'The provider answered an Anthropic-format request with OpenAI chat-completions chunks. Check that this provider is configured with the API format its endpoint actually serves.',
+ type: AgentRuntimeErrorType.UpstreamMalformedResponse,
+ } satisfies ChatMessageError;
+ return { data: errorData, id: context.id, type: 'error' };
+ }
+
// maybe need another structure to add support for multiple choices
switch (chunk.type) {
case 'message_start': {
diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts
index 1627a1d4210..d682c6a5a10 100644
--- a/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts
+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts
@@ -1574,4 +1574,73 @@ describe('OpenAIResponsesStream', () => {
expect(onCompletionMock).toHaveBeenCalledTimes(1);
});
});
+
+ describe('terminal failure events', () => {
+ const collect = async (events: any[]) => {
+ const onCompletion = vi.fn();
+ const protocolStream = OpenAIResponsesStream(createReadableStream(events), {
+ callbacks: { onCompletion },
+ });
+ const chunks = await readStreamChunk(protocolStream);
+ return { chunks, completion: onCompletion.mock.calls[0]?.[0] };
+ };
+
+ it('surfaces response.failed as an error carrying the upstream message', async () => {
+ const { chunks, completion } = await collect([
+ { type: 'response.created', response: { id: 'resp_failed', status: 'in_progress' } },
+ {
+ type: 'response.failed',
+ response: {
+ error: {
+ code: 'server_error',
+ message: 'The server had an error processing your request.',
+ },
+ id: 'resp_failed',
+ status: 'failed',
+ usage: null,
+ },
+ },
+ ]);
+
+ expect(chunks.some((c) => c.includes('event: error'))).toBe(true);
+ expect(completion.error).toMatchObject({
+ message: 'The server had an error processing your request.',
+ type: AgentRuntimeErrorType.ProviderBizError,
+ });
+ });
+
+ it('surfaces a bare error event as an error', async () => {
+ const { completion } = await collect([
+ { type: 'response.created', response: { id: 'resp_error', status: 'in_progress' } },
+ { type: 'error', code: 'rate_limit_exceeded', message: 'Rate limit reached', param: null },
+ ]);
+
+ expect(completion.error).toMatchObject({ message: 'Rate limit reached' });
+ });
+
+ it('reports usage and a length stop for response.incomplete', async () => {
+ const { completion } = await collect([
+ { type: 'response.created', response: { id: 'resp_incomplete', status: 'in_progress' } },
+ {
+ type: 'response.incomplete',
+ response: {
+ id: 'resp_incomplete',
+ incomplete_details: { reason: 'max_output_tokens' },
+ status: 'incomplete',
+ usage: {
+ input_tokens: 10,
+ input_tokens_details: { cached_tokens: 0 },
+ output_tokens: 500,
+ output_tokens_details: { reasoning_tokens: 500 },
+ total_tokens: 510,
+ },
+ },
+ },
+ ]);
+
+ expect(completion.error).toBeUndefined();
+ expect(completion.finishReason).toBe('length');
+ expect(completion.usage.totalOutputTokens).toBe(500);
+ });
+ });
});
diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.ts
index bc8169109d4..020254afd63 100644
--- a/packages/model-runtime/src/core/streams/openai/responsesStream.ts
+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.ts
@@ -22,6 +22,13 @@ import {
} from '../protocol';
import type { OpenAIStreamOptions } from './openai';
+const toResponsesError = (error: { code?: string | null; message?: string | null }) =>
+ ({
+ body: error,
+ message: error.message || error.code || 'The provider reported an error mid-stream.',
+ type: AgentRuntimeErrorType.ProviderBizError,
+ }) satisfies ChatMessageError;
+
const transformOpenAIStream = (
chunk:
| OpenAI.Responses.ResponseStreamEvent
@@ -230,6 +237,58 @@ const transformOpenAIStream = (
return { data: chunk, id: streamContext.id, type: 'data' };
}
+ /**
+ * Terminal failure events. Passing them through as plain `data` let the stream close
+ * normally with no content, no usage and no finish reason, so a failed or rate-limited
+ * response was reported as an empty completion — non-retryable, and without the
+ * upstream's own explanation.
+ */
+ case 'response.failed': {
+ const { error, usage } = chunk.response;
+ const failure = toResponsesError(
+ error ?? { message: 'The provider reported the response as failed.' },
+ );
+ const failureChunk = { data: failure, id: streamContext.id, type: 'error' } as const;
+ if (!usage) return failureChunk;
+
+ return [
+ {
+ data: convertOpenAIResponseUsage(usage, payload),
+ id: streamContext.id,
+ type: 'usage',
+ },
+ failureChunk,
+ ];
+ }
+
+ case 'error': {
+ return { data: toResponsesError(chunk), id: streamContext.id, type: 'error' };
+ }
+
+ /**
+ * An incomplete response is still billed. Surface its usage and reason so a turn that hit
+ * `max_output_tokens` during reasoning reads as a length stop rather than an unbilled drop.
+ */
+ case 'response.incomplete': {
+ const { incomplete_details, usage } = chunk.response;
+ const reason = incomplete_details?.reason;
+ const stopChunk = {
+ data: reason === 'max_output_tokens' ? 'length' : (reason ?? 'incomplete'),
+ id: streamContext.id,
+ type: 'stop',
+ } as const;
+ if (!usage) return stopChunk;
+
+ return [
+ {
+ data: convertOpenAIResponseUsage(usage, payload),
+ id: streamContext.id,
+ type: 'usage',
+ },
+ stopChunk,
+ ];
+ }
+
default: {
return { data: chunk, id: streamContext.id, type: 'data' };
}