π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(model-runtime): keep stream payloads intact and move callbacks to typed events (#22620)
Arvin Xuabf174542e52
diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.tsindex e879482820b..426386f7234 100644--- a/packages/model-runtime/src/core/ModelRuntime.test.ts+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts@@ -925,6 +925,19 @@ describe('ModelRuntime', () => {);});+ it('fires onEmbeddingsFinal when the provider reports no usage', async () => {+ const onEmbeddingsFinal = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({ onEmbeddingsFinal });+ mockRuntimeAI.embeddings.mockResolvedValue([[0.1]]);++ await runtime.embeddings({ input: 'hi', model: 'emb' });++ expect(onEmbeddingsFinal).toHaveBeenCalledWith(+ { latencyMs: expect.any(Number), routeAttempt: undefined, usage: undefined },+ expect.anything(),+ );+ });+it('passes the route attempt to onTranscribeFinal', async () => {const onTranscribeFinal = vi.fn();const { runtime, mockRuntimeAI } = createMockRuntime({ onTranscribeFinal });diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.tsindex d304ccceeeb..8fdea05738c 100644--- a/packages/model-runtime/src/core/ModelRuntime.ts+++ b/packages/model-runtime/src/core/ModelRuntime.ts@@ -579,25 +579,33 @@ export class ModelRuntime {const startTime = Date.now();+ let usage: ModelUsage | undefined;+ let routeAttempt: UsageReportContext['routeAttempt'];const finalOptions = this._hooks?.onEmbeddingsFinal? {...hookOptions,- onUsage: async (usage: ModelUsage, context?: UsageReportContext) => {- await hookOptions?.onUsage?.(usage, context);- try {- const latencyMs = Date.now() - startTime;- await this._hooks!.onEmbeddingsFinal!(- { latencyMs, routeAttempt: context?.routeAttempt, usage },- { options, payload },- );- } catch (e) {- console.error('[ModelRuntime] onEmbeddingsFinal hook error:', e);- }+ onUsage: async (reported: ModelUsage, context?: UsageReportContext) => {+ usage = reported;+ routeAttempt = context?.routeAttempt;+ await hookOptions?.onUsage?.(reported, context);},}: hookOptions;- return await this._runtime.embeddings?.(payload, finalOptions);+ const result = await this._runtime.embeddings?.(payload, finalOptions);++ if (this._hooks?.onEmbeddingsFinal) {+ try {+ await this._hooks.onEmbeddingsFinal(+ { latencyMs: Date.now() - startTime, routeAttempt, usage },+ { options, payload },+ );+ } catch (e) {+ console.error('[ModelRuntime] onEmbeddingsFinal hook error:', e);+ }+ }++ return result;} catch (error) {if (this._hooks?.onEmbeddingsError) {await this._hooks.onEmbeddingsError(error as ChatCompletionErrorPayload, {diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.routeOrder.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.routeOrder.test.tsnew file mode 100644index 00000000000..94671e065cb--- /dev/null+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.routeOrder.test.ts@@ -0,0 +1,56 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { LobeRuntimeAI } from '../BaseAI';+import { createRouterRuntime } from './createRuntime';++const audioPayload = {+ messages: [+ {+ content: [+ {+ audio_url: { mimeType: 'audio/wav', url: 'https://example.com/voice.wav' },+ type: 'audio_url' as const,+ },+ ],+ role: 'user' as const,+ },+ ],+ model: 'audio-model',+};++describe('routed chat option eligibility', () => {+ afterEach(() => vi.restoreAllMocks());++ it('sorts only eligible options on the stream-fallback path', async () => {+ class EmptyRuntime implements LobeRuntimeAI {+ chat = vi.fn(async () => new Response(null));+ }+ const sortRouterOptions = vi.fn(({ options }) => options);+ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ onRouteAttemptFinished: vi.fn(),+ routers: [+ {+ apiType: 'openai',+ models: ['audio-model'],+ options: [+ { apiKey: 'anthropic-key', apiType: 'anthropic', id: 'anthropic' },+ { apiKey: 'openai-key', apiType: 'openai', id: 'openai' },+ { apiKey: 'google-key', apiType: 'google', id: 'google' },+ ],+ runtime: EmptyRuntime as any,+ },+ ],+ shouldFallbackChatAttempt: vi.fn(async () => false),+ sortRouterOptions,+ });++ await new Runtime().chat(audioPayload).catch(() => undefined);++ expect(sortRouterOptions).toHaveBeenCalledTimes(1);+ expect(sortRouterOptions.mock.calls[0][0].options.map((option: any) => option.id)).toEqual([+ 'openai',+ 'google',+ ]);+ });+});diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex ed08b806622..aadf4ca8e93 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -474,23 +474,21 @@ export const createRouterRuntime = ({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 eligibleRouterOptions = this.normalizeRouterOptions(matchedRouter).filter(+ (option) =>+ !allowedApiTypes || allowedApiTypes.has(option.apiType ?? matchedRouter.apiType),);- const routerOptions = allowedApiTypes- ? sortedRouterOptions.filter((option) =>- allowedApiTypes.has(option.apiType ?? matchedRouter.apiType),- )- : sortedRouterOptions;-- if (routerOptions.length === 0) {+ if (eligibleRouterOptions.length === 0) {throw new TypeError(`No provider route supports raw audio input for model ${payload.model}`,);}+ const routerOptions = await this.applySortRouterOptions(+ matchedRouter,+ payload.model,+ eligibleRouterOptions,+ routeContext,+ );const firstChannelId = routerOptions[0]?.id;const weighted = routerOptions.some((option) => option.weight !== undefined);const routeTasks = params.scheduleRouteRequestSettleddiff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/generateObject.messages.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/generateObject.messages.test.tsnew file mode 100644index 00000000000..8b644c244bb--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/generateObject.messages.test.ts@@ -0,0 +1,89 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';++import * as imageToBase64 from '../../utils/imageToBase64';+import { createOpenAICompatibleRuntime } from './index';++vi.mock('../../utils/getModelPricing', () => ({+ getModelPricing: vi.fn().mockResolvedValue(undefined),+}));++const remoteImageUrl = 'https://example.com/image.jpg';+const inlinedImageUrl = 'data:image/jpeg;base64,forced';++const Runtime = createOpenAICompatibleRuntime({+ baseURL: 'https://api.test.com/v1',+ chatCompletion: { forceImageBase64: true },+ provider: 'testprovider',+});++const payload = {+ messages: [+ {+ content: [+ { text: 'Describe it', type: 'text' as const },+ { image_url: { url: remoteImageUrl }, type: 'image_url' as const },+ ],+ role: 'user' as const,+ },+ ],+ model: 'gpt-anything',+ schema: {+ name: 'answer',+ schema: { properties: { title: { type: 'string' } }, type: 'object' as const },+ },+};++const sentImageUrl = (create: ReturnType<typeof vi.spyOn>) =>+ (create.mock.calls[0][0] as any).messages[0].content[1].image_url.url;++describe('generateObject message conversion', () => {+ afterEach(() => vi.restoreAllMocks());++ const mockImage = () =>+ vi+ .spyOn(imageToBase64, 'imageUrlToBase64')+ .mockResolvedValue({ base64: 'forced', mimeType: 'image/jpeg' });++ it('applies forceImageBase64 on the json_schema path', async () => {+ mockImage();+ const runtime = new Runtime({ apiKey: 'test' });+ const create = vi.spyOn(runtime.client.chat.completions, 'create').mockResolvedValue({+ choices: [{ message: { content: '{"title":"ok"}' } }],+ } as any);++ await expect(runtime.generateObject(payload)).resolves.toEqual({ title: 'ok' });++ expect(sentImageUrl(create as any)).toBe(inlinedImageUrl);+ });++ it('applies forceImageBase64 on the forced tool-calling path', async () => {+ mockImage();+ const ToolRuntime = createOpenAICompatibleRuntime({+ baseURL: 'https://api.test.com/v1',+ chatCompletion: { forceImageBase64: true },+ generateObject: { useToolsCalling: true },+ provider: 'testprovider',+ });+ const runtime = new ToolRuntime({ apiKey: 'test' });+ const create = vi.spyOn(runtime.client.chat.completions, 'create').mockResolvedValue({+ choices: [+ {+ message: {+ tool_calls: [+ {+ function: { arguments: '{"title":"ok"}', name: 'answer' },+ id: '1',+ type: 'function',+ },+ ],+ },+ },+ ],+ } as any);++ await expect(runtime.generateObject(payload)).resolves.toEqual({ title: 'ok' });++ expect(sentImageUrl(create as any)).toBe(inlinedImageUrl);+ });+});diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/generateObjectReasoning.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/generateObjectReasoning.tsnew file mode 100644index 00000000000..0d643f34e77--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/generateObjectReasoning.ts@@ -0,0 +1,30 @@+import {+ isGPTProResponsesModel,+ supportsGPTResponsesReasoningEffortNone,+} from '../../providers/openai/modelId';+import type { GenerateObjectPayload } from '../../types';++type GenerateObjectReasoningParams = Pick<GenerateObjectPayload, 'reasoning_effort' | 'thinking'>;+export const getGenerateObjectReasoningParams = ({+ reasoning_effort,+ thinking,+}: GenerateObjectReasoningParams) =>+ reasoning_effort && thinking?.type !== 'disabled' ? { reasoning_effort } : {};++export const getGenerateObjectResponsesReasoningParams = ({+ model,+ reasoning_effort,+ thinking,+}: GenerateObjectReasoningParams & { model: string }) => {+ if (isGPTProResponsesModel(model)) {+ return reasoning_effort && reasoning_effort !== 'max' ? { reasoning: { effort: 'high' } } : {};+ }++ if (thinking?.type === 'disabled') {+ return supportsGPTResponsesReasoningEffortNone(model) ? { reasoning: { effort: 'none' } } : {};+ }++ return reasoning_effort && reasoning_effort !== 'max'+ ? { reasoning: { effort: reasoning_effort } }+ : {};+};diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 57025680a5b..d14617a3a39 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -8,11 +8,7 @@ import type OpenAI from 'openai';import type { Stream } from 'openai/streaming';import { ErrorClassifier, refineErrorCode } from '../../errors';-import {- isGPTProResponsesModel,- isResponsesAPIModel,- supportsGPTResponsesReasoningEffortNone,-} from '../../providers/openai/modelId';+import { isResponsesAPIModel } from '../../providers/openai/modelId';import type {ASROptions,ASRPayload,@@ -84,6 +80,10 @@ import type {OpenAIExtraParams,ResponseCreateParamsWithPromptCacheKey,} from './factoryOptions';+import {+ getGenerateObjectReasoningParams,+ getGenerateObjectResponsesReasoningParams,+} from './generateObjectReasoning';import { transformResponseAPIToStream, transformResponseToStream } from './nonStreamToStream';import {initializeOpenAIDiagnostics,@@ -144,35 +144,6 @@ export const CHAT_MODELS_BLOCK_LIST = ['dall-e',];-type GenerateObjectReasoningParams = Pick<GenerateObjectPayload, 'reasoning_effort' | 'thinking'>;-const getGenerateObjectReasoningParams = ({- reasoning_effort,- thinking,-}: GenerateObjectReasoningParams) => ({- // `thinking` is a Lobe runtime abstraction, not a generic OpenAI-compatible API field.- // Use it here only to suppress `reasoning_effort`; providers that support thinking- // must translate it via `generateObject.handlePayload`.- ...(reasoning_effort && thinking?.type !== 'disabled' ? { reasoning_effort } : {}),-});--const getGenerateObjectResponsesReasoningParams = ({- model,- reasoning_effort,- thinking,-}: GenerateObjectReasoningParams & { model: string }) => {- if (isGPTProResponsesModel(model)) {- return reasoning_effort && reasoning_effort !== 'max' ? { reasoning: { effort: 'high' } } : {};- }-- if (thinking?.type === 'disabled') {- return supportsGPTResponsesReasoningEffortNone(model) ? { reasoning: { effort: 'none' } } : {};- }-- return reasoning_effort && reasoning_effort !== 'max'- ? { reasoning: { effort: reasoning_effort } }- : {};-};-export const createOpenAICompatibleRuntime = <T extends Record<string, any> = any>({provider,baseURL: DEFAULT_BASE_URL,@@ -457,6 +428,19 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anreturn promptCacheKey ? { prompt_cache_key: promptCacheKey } : {};}+ private async convertGenerateObjectMessages({ messages, model }: GenerateObjectPayload) {+ return convertOpenAIMessages(messages as any, {+ forceImageBase64: chatCompletion?.forceImageBase64,+ forceVideoBase64: chatCompletion?.forceVideoBase64,+ model,+ thoughtSignatureScope: await this.getSignatureScope(+ this.getMappedModelId(model),+ 'thought_signature',+ 'chat_completions',+ ),+ });+ }+private handleGenerateObjectPayload(payload: GenerateObjectPayload,requestPayload: ChatCompletionCreateParamsWithPromptCacheKey,@@ -929,7 +913,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anoptions: GenerateObjectOptions | undefined,usagePayload: Parameters<typeof convertOpenAIUsage>[1],) {- const { messages, schema, model } = payload;+ const { schema, model } = payload;// Apply schema transformation if configuredconst processedSchema = generateObjectConfig?.handleSchema@@ -951,7 +935,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anthis.withMappedRequestModel(this.handleGenerateObjectPayload(payload, {...getGenerateObjectReasoningParams(payload),- messages,+ messages: await this.convertGenerateObjectMessages(payload),model,...this.resolvePromptCacheKeyParams(model, options?.user),tool_choice: { function: { name: tool.function.name }, type: 'function' },@@ -1086,7 +1070,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anthis.withMappedRequestModel(this.handleGenerateObjectPayload(payload, {...getGenerateObjectReasoningParams(payload),- messages,+ messages: await this.convertGenerateObjectMessages(payload),model,response_format: { json_schema: processedSchema, type: 'json_schema' },...this.resolvePromptCacheKeyParams(model, options?.user),@@ -1415,7 +1399,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anmax_tokens,...res} = responses?.handlePayload- ? (responses?.handlePayload(payload, this._options) as ChatStreamPayload)+ ? (responses.handlePayload(payload, this._options) as ChatStreamPayload): payload;const requestModel =this.withMappedRequestModel({ model: res.model }, usageModel).model ?? usageModel;@@ -1663,17 +1647,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an}log('calling chat.completions.create for tool calling');- const thoughtSignatureScope = await this.getSignatureScope(- requestModel,- 'thought_signature',- 'chat_completions',- );- const msgs = await convertOpenAIMessages(messages as any, {- forceImageBase64: chatCompletion?.forceImageBase64,- forceVideoBase64: chatCompletion?.forceVideoBase64,- model,- thoughtSignatureScope,- });+ const msgs = await this.convertGenerateObjectMessages(payload);const res = await this.client.chat.completions.create(this.withMappedRequestModel(diff --git a/packages/model-runtime/src/core/streams/anthropic.ts b/packages/model-runtime/src/core/streams/anthropic.tsindex f3408f2f121..d5550ededa0 100644--- a/packages/model-runtime/src/core/streams/anthropic.ts+++ b/packages/model-runtime/src/core/streams/anthropic.ts@@ -5,6 +5,11 @@ import type { ChatCitationItem, ChatMessageError } from '@lobechat/types';import type { ChatStreamCallbacks } from '../../types';import { AgentRuntimeErrorType } from '../../types/error';import { convertAnthropicUsage } from '../usageConverters';+import {+ createEventCallbacksTransformer,+ createModelEventTransformer,+ createSSEEncoder,+} from './events';import type {ChatPayloadForTransformStream,StreamContext,@@ -14,9 +19,7 @@ import type {} from './protocol';import {convertIterableToStream,- createCallbacksTransformer,createFirstErrorHandleTransformer,- createSSEProtocolTransformer,createTokenSpeedCalculator,FIRST_CHUNK_ERROR_KEY,} from './protocol';@@ -344,7 +347,8 @@ export const AnthropicStream = (* connection mid-response without either; without this flag the truncated output was* treated as a normal completion, so half-written tool arguments got executed.*/- createSSEProtocolTransformer((c) => c, streamStack, { requireTerminalEvent: true }),+ createModelEventTransformer((c) => c, streamStack, { requireTerminalEvent: true }),)- .pipeThrough(createCallbacksTransformer(callbacks, { streamStack }));+ .pipeThrough(createEventCallbacksTransformer(callbacks, { streamStack }))+ .pipeThrough(createSSEEncoder());};diff --git a/packages/model-runtime/src/core/streams/bedrock/claude.ts b/packages/model-runtime/src/core/streams/bedrock/claude.tsindex b86fd2dd976..e84ef3c77fb 100644--- a/packages/model-runtime/src/core/streams/bedrock/claude.ts+++ b/packages/model-runtime/src/core/streams/bedrock/claude.ts@@ -3,12 +3,13 @@ import type { InvokeModelWithResponseStreamResponse } from '@aws-sdk/client-bedrimport type { ChatStreamCallbacks } from '../../../types';import { nanoid } from '../../../utils/uuid';import { transformAnthropicStream } from '../anthropic';-import type { StreamContext } from '../protocol';import {- createCallbacksTransformer,- createSSEProtocolTransformer,- createTokenSpeedCalculator,-} from '../protocol';+ createEventCallbacksTransformer,+ createModelEventTransformer,+ createSSEEncoder,+} from '../events';+import type { StreamContext } from '../protocol';+import { createTokenSpeedCalculator } from '../protocol';import { createBedrockStream } from './common';export const AWSBedrockClaudeStream = (@@ -38,7 +39,8 @@ export const AWSBedrockClaudeStream = ().pipeThrough(// Same Messages event contract as `AnthropicStream`: closing without a terminal event is a truncation.- createSSEProtocolTransformer((c) => c, streamStack, { requireTerminalEvent: true }),+ createModelEventTransformer((c) => c, streamStack, { requireTerminalEvent: true }),)- .pipeThrough(createCallbacksTransformer(options?.callbacks, { streamStack }));+ .pipeThrough(createEventCallbacksTransformer(options?.callbacks, { streamStack }))+ .pipeThrough(createSSEEncoder());};diff --git a/packages/model-runtime/src/core/streams/bedrock/llama.ts b/packages/model-runtime/src/core/streams/bedrock/llama.tsindex f869fdfb681..d9d063a04d8 100644--- a/packages/model-runtime/src/core/streams/bedrock/llama.ts+++ b/packages/model-runtime/src/core/streams/bedrock/llama.ts@@ -2,8 +2,12 @@ import type { InvokeModelWithResponseStreamResponse } from '@aws-sdk/client-bedrimport type { ChatStreamCallbacks } from '../../../types';import { nanoid } from '../../../utils/uuid';+import {+ createEventCallbacksTransformer,+ createModelEventTransformer,+ createSSEEncoder,+} from '../events';import type { StreamContext, StreamProtocolChunk } from '../protocol';-import { createCallbacksTransformer, createSSEProtocolTransformer } from '../protocol';import { createBedrockStream } from './common';interface AmazonBedrockInvocationMetrics {@@ -41,6 +45,7 @@ export const AWSBedrockLlamaStream = (const stream = res instanceof ReadableStream ? res : createBedrockStream(res);return stream- .pipeThrough(createSSEProtocolTransformer(transformLlamaStream, streamStack))- .pipeThrough(createCallbacksTransformer(cb));+ .pipeThrough(createModelEventTransformer(transformLlamaStream, streamStack))+ .pipeThrough(createEventCallbacksTransformer(cb))+ .pipeThrough(createSSEEncoder());};diff --git a/packages/model-runtime/src/core/streams/events.test.ts b/packages/model-runtime/src/core/streams/events.test.tsnew file mode 100644index 00000000000..d99fe85f9f0--- /dev/null+++ b/packages/model-runtime/src/core/streams/events.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it, vi } from 'vitest';++import type { ModelStreamEvent } from './events';+import {+ createEventCallbacksTransformer,+ createModelEventTransformer,+ createSSEEncoder,+} from './events';++const passThrough = (chunk: ModelStreamEvent) => chunk;++const readBytes = async (stream: ReadableStream<Uint8Array>) => {+ const decoder = new TextDecoder();+ const output: string[] = [];+ const reader = stream.getReader();+ for (let next = await reader.read(); !next.done; next = await reader.read()) {+ output.push(decoder.decode(next.value));+ }+ return output;+};++const streamOf = (chunks: ModelStreamEvent[]) =>+ new ReadableStream<ModelStreamEvent>({+ start(controller) {+ for (const chunk of chunks) controller.enqueue(chunk);+ controller.close();+ },+ });++describe('model stream event pipeline', () => {+ it('encodes each event as id, event and data SSE lines', async () => {+ const output = await readBytes(+ streamOf([{ data: 'hello', id: '1', type: 'text' }])+ .pipeThrough(createModelEventTransformer(passThrough))+ .pipeThrough(createSSEEncoder()),+ );++ expect(output).toEqual(['id: 1\n', 'event: text\n', 'data: "hello"\n\n']);+ });++ it('does not add an error when a terminal event arrived', async () => {+ const output = await readBytes(+ streamOf([{ data: 'end_turn', id: 'ok', type: 'stop' }])+ .pipeThrough(+ createModelEventTransformer(passThrough, { id: 's' }, { requireTerminalEvent: true }),+ )+ .pipeThrough(createSSEEncoder()),+ );++ expect(output).toEqual(['id: ok\n', 'event: stop\n', 'data: "end_turn"\n\n']);+ });++ it('closes an interrupted stream with an error that callbacks also see', async () => {+ const onError = vi.fn();+ const onFinal = vi.fn();+ const data = {+ body: { name: 'Stream parsing error', reason: 'unexpected_end' },+ message: 'Stream ended unexpectedly',+ name: 'Stream parsing error',+ type: 'ProviderStreamInterrupted',+ };++ const output = await readBytes(+ streamOf([{ data: 'partial', id: '1', type: 'text' }])+ .pipeThrough(+ createModelEventTransformer(passThrough, { id: 's' }, { requireTerminalEvent: true }),+ )+ .pipeThrough(createEventCallbacksTransformer({ onError, onFinal }))+ .pipeThrough(createSSEEncoder()),+ );++ expect(output.slice(-3)).toEqual([+ 'id: s\n',+ 'event: error\n',+ `data: ${JSON.stringify(data)}\n\n`,+ ]);+ expect(onError).toHaveBeenCalledWith(data);+ expect(onFinal).toHaveBeenCalledWith(expect.objectContaining({ error: data, text: 'partial' }));+ });++ it('delivers payloads containing SSE markers intact', async () => {+ const onText = vi.fn();+ const text = 'event: x\ndata: y';++ const output = await readBytes(+ streamOf([{ data: text, id: '1', type: 'text' }])+ .pipeThrough(createEventCallbacksTransformer({ onText }))+ .pipeThrough(createSSEEncoder()),+ );++ expect(onText).toHaveBeenCalledWith(text);+ expect(output[2]).toBe(`data: ${JSON.stringify(text)}\n\n`);+ });++ it('forwards the event before a slow callback resolves', async () => {+ let release!: () => void;+ const pending = new Promise<void>((resolve) => (release = resolve));+ const reader = streamOf([{ data: 'hi', id: '1', type: 'text' }])+ .pipeThrough(createEventCallbacksTransformer({ onText: () => pending }))+ .getReader();++ await expect(reader.read()).resolves.toMatchObject({+ value: { data: 'hi', type: 'text' },+ });++ release();+ });+});diff --git a/packages/model-runtime/src/core/streams/events.ts b/packages/model-runtime/src/core/streams/events.tsnew file mode 100644index 00000000000..549cec02070--- /dev/null+++ b/packages/model-runtime/src/core/streams/events.ts@@ -0,0 +1,310 @@+import type { ModelPerformance, ModelReasoningResponseItem, ModelUsage } from '@lobechat/types';++import { parseToolCalls } from '../../helpers';+import type { ChatStreamCallbacks, OnFinishData } from '../../types';+import { AgentRuntimeErrorType } from '../../types/error';+import { nanoid } from '../../utils/uuid';+import type {+ StreamContext,+ StreamPartChunkData,+ StreamProtocolChunk,+ StreamToolCallChunkData,+} from './protocol';++export interface ModelStreamEventDataMap {+ base64_image: string | { image: { data: string; id: string } };+ content_part: StreamPartChunkData;+ data: unknown;+ error: unknown;+ flagged_reasoning_signature: unknown;+ grounding: unknown;+ reasoning: string;+ reasoning_part: StreamPartChunkData;+ reasoning_response_item: ModelReasoningResponseItem;+ reasoning_signature: string;+ speed: ModelPerformance;+ stop: unknown;+ text: string;+ tool_calls: StreamToolCallChunkData[];+ usage: ModelUsage;+}++/**+ * The provider-neutral chat stream contract. SSE is only its wire encoding, applied once+ * at the end of a pipeline by `createSSEEncoder`.+ */+export type ModelStreamEvent = {+ [Type in keyof ModelStreamEventDataMap]: {+ data: ModelStreamEventDataMap[Type];+ id?: string;+ type: Type;+ };+}[keyof ModelStreamEventDataMap];++/** Accumulates a stream's events and fires the chat callbacks for each of them. */+export const createStreamCallbackDispatcher = (+ cb: ChatStreamCallbacks | undefined,+ options?: { streamStack?: StreamContext },+) => {+ let aggregatedText = '';+ let aggregatedThinking: string | undefined = undefined;+ let reasoningSignature: string | undefined;+ const reasoningResponseItems: ModelReasoningResponseItem[] = [];+ let usage: ModelUsage | undefined;+ let speed: ModelPerformance | undefined;+ let grounding: any;+ let toolsCalling: any;+ let streamError: any;+ let finishReason: string | undefined;+ // Track base64 images for accumulation+ const base64Images: Array<{ data: string; id: string }> = [];++ const callbacks = cb || {};++ const finish = async (): Promise<void> => {+ /**+ * Non-streaming Responses conversion emits reasoning items without summary+ * deltas, so derive visible thinking text from the item summaries whenever+ * nothing was streamed β otherwise the summary would persist but never render.+ */+ const responseItemsThinking = reasoningResponseItems+ .flatMap(({ summary }) => summary ?? [])+ .map(({ text }) => text)+ .filter(Boolean)+ .join('\n');+ const reasoningContent = aggregatedThinking || responseItemsThinking || undefined;++ const data: OnFinishData = {+ error: streamError,+ finishReason,+ grounding,+ speed,+ text: aggregatedText,+ thinking: reasoningContent,+ toolsCalling,+ usage,+ };+ if (reasoningContent || reasoningSignature || reasoningResponseItems.length > 0) {+ data.reasoning = {+ content: reasoningContent,+ responseItems: reasoningResponseItems.length > 0 ? reasoningResponseItems : undefined,+ signature: reasoningSignature,+ };+ }+ const usageMissingDiagnostics = usage+ ? undefined+ : options?.streamStack?.usageMissingDiagnostics;+ if (usageMissingDiagnostics) data.usageMissingDiagnostics = usageMissingDiagnostics;+ const { pricingOptions, providerReportedCost } = options?.streamStack ?? {};+ if (providerReportedCost !== undefined) data.providerReportedCost = providerReportedCost;+ if (pricingOptions) data.pricingOptions = pricingOptions;++ if (callbacks.onCompletion) {+ await callbacks.onCompletion(data);+ }++ if (callbacks.onFinal) {+ await callbacks.onFinal(data);+ }+ };++ const dispatch = async (event: ModelStreamEvent): Promise<void> => {+ const data = event.data as any;++ if (!data) return;++ switch (event.type) {+ case 'text': {+ aggregatedText += data;+ await callbacks.onText?.(data);+ break;+ }++ case 'reasoning': {+ if (!aggregatedThinking) {+ aggregatedThinking = '';+ }++ aggregatedThinking += data;+ await callbacks.onThinking?.(data);+ break;+ }++ case 'reasoning_signature': {+ if (typeof data === 'string') reasoningSignature = data;+ break;+ }++ case 'reasoning_response_item': {+ reasoningResponseItems.push(data as ModelReasoningResponseItem);+ break;+ }++ case 'base64_image': {+ // Real providers (google/openai image streams) serialize `data` as a+ // raw data-URI string; wrap it into an image item, mirroring+ // fetch-sse's client-side parser so both paths share one contract.+ // Tolerate the legacy `{ image, images }` object shape too, so any+ // existing consumer keeps working.+ const image =+ typeof data === 'string'+ ? { data, id: `tmp_img_${nanoid()}` }+ : (data as { image: { data: string; id: string } }).image;+ base64Images.push(image);+ await callbacks.onBase64Image?.({+ image,+ images: base64Images,+ });+ break;+ }++ case 'content_part': {+ // data format: StreamPartChunkData+ const partData = data as StreamPartChunkData;+ await callbacks.onContentPart?.({+ content: partData.content,+ mimeType: partData.mimeType,+ partType: partData.partType,+ thoughtSignature: partData.thoughtSignature,+ });+ break;+ }++ case 'reasoning_part': {+ // data format: StreamPartChunkData+ const partData = data as StreamPartChunkData;+ await callbacks.onReasoningPart?.({+ content: partData.content,+ mimeType: partData.mimeType,+ partType: partData.partType,+ thoughtSignature: partData.thoughtSignature,+ });+ break;+ }++ case 'usage': {+ usage = data;+ await callbacks.onUsage?.(data);+ break;+ }++ case 'speed': {+ speed = data;+ break;+ }++ case 'grounding': {+ grounding = data;+ await callbacks.onGrounding?.(data);+ break;+ }++ case 'tool_calls': {+ if (!toolsCalling) toolsCalling = [];+ toolsCalling = parseToolCalls(toolsCalling, data);++ await callbacks.onToolsCalling?.({ chunk: data, toolsCalling });+ break;+ }++ case 'stop': {+ // Provider's terminal finishReason (e.g. Google's RECITATION / MAX_TOKENS,+ // OpenAI's length, Anthropic's end_turn). Capture so downstream consumers+ // can detect soft interrupts where content is empty but tokens were billed.+ //+ // Some providers emit multiple stop chunks per stream β Anthropic sends+ // `message_delta` (carrying the real `stop_reason` like `end_turn` /+ // `max_tokens` / `tool_use`) followed by a `message_stop` sentinel.+ // Keep the FIRST non-empty value so the meaningful reason is not+ // clobbered by the trailing sentinel.+ if (typeof data === 'string' && data && !finishReason) {+ finishReason = data;+ }+ break;+ }++ case 'error': {+ streamError = data;+ await callbacks.onError?.(data);+ break;+ }+ }+ };++ return { dispatch, finish, start: async () => callbacks.onStart?.() };+};++/**+ * Convert provider chunks into model stream events, closing with an error event when+ * `requireTerminalEvent` is set and the upstream ended without one.+ */+export const createModelEventTransformer = (+ transformer: (chunk: any, stack: StreamContext) => StreamProtocolChunk | StreamProtocolChunk[],+ streamStack?: StreamContext,+ options?: { requireTerminalEvent?: boolean },+) => {+ let hasTerminalEvent = false;++ return new TransformStream<any, ModelStreamEvent>({+ flush(controller) {+ if (!options?.requireTerminalEvent || hasTerminalEvent) return;++ // The provider cut the response short; no chunk failed to parse, so this is not a+ // `StreamChunkError`.+ controller.enqueue({+ data: {+ body: { name: 'Stream parsing error', reason: 'unexpected_end' },+ message: 'Stream ended unexpectedly',+ name: 'Stream parsing error',+ type: AgentRuntimeErrorType.ProviderStreamInterrupted,+ },+ id: streamStack?.id || 'stream_end',+ type: 'error',+ });+ },+ transform: (chunk, controller) => {+ const result = transformer(chunk, streamStack || { id: '' });++ for (const event of Array.isArray(result) ? result : [result]) {+ controller.enqueue(event as ModelStreamEvent);++ // mark terminal when receiving any of these events+ if (event.type === 'stop' || event.type === 'usage' || event.type === 'error') {+ hasTerminalEvent = true;+ }+ }+ },+ });+};++/** Fires chat callbacks for each event, forwarding the event before its callback resolves. */+export const createEventCallbacksTransformer = (+ cb: ChatStreamCallbacks | undefined,+ options?: { streamStack?: StreamContext },+) => {+ const dispatcher = createStreamCallbackDispatcher(cb, options);++ return new TransformStream<ModelStreamEvent, ModelStreamEvent>({+ flush: () => dispatcher.finish(),+ start: async () => {+ await dispatcher.start();+ },+ transform: async (event, controller) => {+ controller.enqueue(event);+ await dispatcher.dispatch(event);+ },+ });+};++/** Encode model stream events as the SSE bytes sent to clients. */+export const createSSEEncoder = () => {+ const textEncoder = new TextEncoder();++ return new TransformStream<ModelStreamEvent, Uint8Array>({+ transform: ({ data, id, type }, controller) => {+ controller.enqueue(textEncoder.encode(`id: ${id}\n`));+ controller.enqueue(textEncoder.encode(`event: ${type}\n`));+ controller.enqueue(textEncoder.encode(`data: ${JSON.stringify(data)}\n\n`));+ },+ });+};diff --git a/packages/model-runtime/src/core/streams/google/index.ts b/packages/model-runtime/src/core/streams/google/index.tsindex e0054fd57a0..ee9144bbe0b 100644--- a/packages/model-runtime/src/core/streams/google/index.ts+++ b/packages/model-runtime/src/core/streams/google/index.ts@@ -6,6 +6,11 @@ import { AgentRuntimeErrorType } from '../../../types/error';import { serializeScopedSignature } from '../../../utils/signatureScope';import { nanoid } from '../../../utils/uuid';import { convertGoogleAIUsage } from '../../usageConverters/google-ai';+import {+ createEventCallbacksTransformer,+ createModelEventTransformer,+ createSSEEncoder,+} from '../events';import type {ChatPayloadForTransformStream,StreamContext,@@ -13,12 +18,7 @@ import type {StreamProtocolChunk,StreamToolCallChunkData,} from '../protocol';-import {- createCallbacksTransformer,- createSSEProtocolTransformer,- createTokenSpeedCalculator,- generateToolCallId,-} from '../protocol';+import { createTokenSpeedCalculator, generateToolCallId } from '../protocol';import { GOOGLE_AI_BLOCK_REASON } from './const';export const LOBE_ERROR_KEY = '__lobe_error';@@ -419,8 +419,7 @@ export const GoogleGenerativeAIStream = (streamStack,}),)- .pipeThrough(- createSSEProtocolTransformer((c) => c, streamStack, { requireTerminalEvent: true }),- )- .pipeThrough(createCallbacksTransformer(callbacks, { streamStack }));+ .pipeThrough(createModelEventTransformer((c) => c, streamStack, { requireTerminalEvent: true }))+ .pipeThrough(createEventCallbacksTransformer(callbacks, { streamStack }))+ .pipeThrough(createSSEEncoder());};diff --git a/packages/model-runtime/src/core/streams/index.ts b/packages/model-runtime/src/core/streams/index.tsindex 4449b227dc2..6c4904042ab 100644--- a/packages/model-runtime/src/core/streams/index.ts+++ b/packages/model-runtime/src/core/streams/index.ts@@ -1,5 +1,6 @@export * from './anthropic';export * from './bedrock';+export * from './events';export * from './google';export * from './model';export * from './ollama';diff --git a/packages/model-runtime/src/core/streams/ollama.ts b/packages/model-runtime/src/core/streams/ollama.tsindex ea0ce7e51af..9e594204788 100644--- a/packages/model-runtime/src/core/streams/ollama.ts+++ b/packages/model-runtime/src/core/streams/ollama.ts@@ -2,12 +2,13 @@ import type { ChatResponse } from 'ollama/browser';import type { ChatStreamCallbacks } from '../../types';import { nanoid } from '../../utils/uuid';-import type { StreamContext, StreamProtocolChunk } from './protocol';import {- createCallbacksTransformer,- createSSEProtocolTransformer,- generateToolCallId,-} from './protocol';+ createEventCallbacksTransformer,+ createModelEventTransformer,+ createSSEEncoder,+} from './events';+import type { StreamContext, StreamProtocolChunk } from './protocol';+import { generateToolCallId } from './protocol';const transformOllamaStream = (chunk: ChatResponse, stack: StreamContext): StreamProtocolChunk => {if (chunk.message.thinking) {@@ -57,6 +58,7 @@ export const OllamaStream = (const streamStack: StreamContext = { id: 'chat_' + nanoid() };return res- .pipeThrough(createSSEProtocolTransformer(transformOllamaStream, streamStack))- .pipeThrough(createCallbacksTransformer(cb));+ .pipeThrough(createModelEventTransformer(transformOllamaStream, streamStack))+ .pipeThrough(createEventCallbacksTransformer(cb))+ .pipeThrough(createSSEEncoder());};diff --git a/packages/model-runtime/src/core/streams/openai/openai.ts b/packages/model-runtime/src/core/streams/openai/openai.tsindex 94d60d96fc6..78cfa4a9df2 100644--- a/packages/model-runtime/src/core/streams/openai/openai.ts+++ b/packages/model-runtime/src/core/streams/openai/openai.ts@@ -8,6 +8,11 @@ import { AgentRuntimeErrorType } from '../../../types/error';import { isErrorCausedByContentFilter } from '../../../utils/isErrorCausedByContentFilter';import { serializeScopedSignature } from '../../../utils/signatureScope';import { convertOpenAIUsage } from '../../usageConverters';+import {+ createEventCallbacksTransformer,+ createModelEventTransformer,+ createSSEEncoder,+} from '../events';import type {ChatPayloadForTransformStream,StreamContext,@@ -17,9 +22,7 @@ import type {} from '../protocol';import {convertIterableToStream,- createCallbacksTransformer,createFirstErrorHandleTransformer,- createSSEProtocolTransformer,createTokenSpeedCalculator,FIRST_CHUNK_ERROR_KEY,generateToolCallId,@@ -757,7 +760,8 @@ export const OpenAIStream = (streamStack,}),)- .pipeThrough(createSSEProtocolTransformer((c) => c, streamStack))- .pipeThrough(createCallbacksTransformer(callbacks, { streamStack }))+ .pipeThrough(createModelEventTransformer((c) => c, streamStack))+ .pipeThrough(createEventCallbacksTransformer(callbacks, { streamStack }))+ .pipeThrough(createSSEEncoder()));};diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.tsindex 610f9cf3488..54d8e58717f 100644--- a/packages/model-runtime/src/core/streams/openai/responsesStream.ts+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.ts@@ -5,6 +5,11 @@ import type { Stream } from 'openai/streaming';import { AgentRuntimeErrorType } from '../../../types/error';import { serializeScopedSignature } from '../../../utils/signatureScope';import { convertOpenAIResponseUsage } from '../../usageConverters';+import {+ createEventCallbacksTransformer,+ createModelEventTransformer,+ createSSEEncoder,+} from '../events';import type {ChatPayloadForTransformStream,StreamContext,@@ -14,9 +19,7 @@ import type {} from '../protocol';import {convertIterableToStream,- createCallbacksTransformer,createFirstErrorHandleTransformer,- createSSEProtocolTransformer,createTokenSpeedCalculator,FIRST_CHUNK_ERROR_KEY,} from '../protocol';@@ -370,7 +373,8 @@ export const OpenAIResponsesStream = (streamStack,}),)- .pipeThrough(createSSEProtocolTransformer((c) => c, streamStack))- .pipeThrough(createCallbacksTransformer(callbacks, { streamStack }))+ .pipeThrough(createModelEventTransformer((c) => c, streamStack))+ .pipeThrough(createEventCallbacksTransformer(callbacks, { streamStack }))+ .pipeThrough(createSSEEncoder()));};diff --git a/packages/model-runtime/src/core/streams/protocol.callbacks.test.ts b/packages/model-runtime/src/core/streams/protocol.callbacks.test.tsnew file mode 100644index 00000000000..55545319839--- /dev/null+++ b/packages/model-runtime/src/core/streams/protocol.callbacks.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it, vi } from 'vitest';++import { createCallbacksTransformer } from './protocol';++const runChunks = async (+ chunks: string[],+ callbacks: Parameters<typeof createCallbacksTransformer>[0],+) => {+ const stream = new ReadableStream<string>({+ start(controller) {+ for (const chunk of chunks) controller.enqueue(chunk);+ controller.close();+ },+ }).pipeThrough(createCallbacksTransformer(callbacks));++ const reader = stream.getReader();+ while (!(await reader.read()).done);+};++const sse = (type: string, data: unknown) => [+ `event: ${type}\n`,+ `data: ${JSON.stringify(data)}\n\n`,+];++describe('createCallbacksTransformer payloads containing the SSE field marker', () => {+ it('keeps text that contains `data:`', async () => {+ const onText = vi.fn();+ const onCompletion = vi.fn();+ const text = 'the metadata: field is required';++ await runChunks(sse('text', text), { onCompletion, onText });++ expect(onText).toHaveBeenCalledWith(text);+ expect(onCompletion).toHaveBeenCalledWith(expect.objectContaining({ text }));+ });++ it('keeps reasoning that contains `data:`', async () => {+ const onThinking = vi.fn();+ const thinking = 'check the data: it looks wrong';++ await runChunks(sse('reasoning', thinking), { onThinking });++ expect(onThinking).toHaveBeenCalledWith(thinking);+ });++ it('keeps tool call arguments that contain a data URI', async () => {+ const onToolsCalling = vi.fn();+ const args = JSON.stringify({ url: 'data:image/png;base64,AAAA' });++ await runChunks(+ sse('tool_calls', [+ { function: { arguments: args, name: 'view' }, id: 'call_1', index: 0, type: 'function' },+ ]),+ { onToolsCalling },+ );++ expect(onToolsCalling).toHaveBeenCalledTimes(1);+ expect(onToolsCalling.mock.calls[0][0].toolsCalling[0].function.arguments).toBe(args);+ });+});diff --git a/packages/model-runtime/src/core/streams/protocol.test.ts b/packages/model-runtime/src/core/streams/protocol.test.tsindex 880781eb12b..3e3d6c34884 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 { afterEach, describe, expect, it, vi } from 'vitest';+import { createModelEventTransformer, createSSEEncoder } from './events';import type { StreamProtocolChunk } from './protocol';import {ABORT_CHUNK,@@ -7,7 +8,6 @@ import {createCallbacksTransformer,createFirstErrorHandleTransformer,createSSEDataExtractor,- createSSEProtocolTransformer,createTokenSpeedCalculator,FIRST_CHUNK_ERROR_KEY,readableFromAsyncIterable,@@ -551,7 +551,8 @@ describe('convertIterableToStream', () => {const identity = (chunk: any) => ({ data: chunk, id: 'msg_1', type: 'data' as const });const readable = convertIterableToStream(abortingStream()).pipeThrough(createTokenSpeedCalculator(identity))- .pipeThrough(createSSEProtocolTransformer((c) => c));+ .pipeThrough(createModelEventTransformer((c) => c))+ .pipeThrough(createSSEEncoder());const reader = readable.getReader();const chunks: string[] = [];@@ -559,7 +560,7 @@ describe('convertIterableToStream', () => {while (true) {const { done, value } = await reader.read();if (done) break;- chunks.push(value as string);+ chunks.push(new TextDecoder().decode(value));}// Last 3 chunks should be the stop:abort SSE event@@ -612,83 +613,6 @@ describe('readableFromAsyncIterable', () => {});});-describe('createSSEProtocolTransformer', () => {- const processChunk = async (transformer: TransformStream, chunk: any) => {- const results: any[] = [];- const readable = new ReadableStream({- start(controller) {- controller.enqueue(chunk);- controller.close();- },- });-- const writable = new WritableStream({- write(chunk) {- results.push(chunk);- },- });-- await readable.pipeThrough(transformer).pipeTo(writable);-- return results;- };-- it('should convert chunk into SSE formatted lines without enforcing terminal (default)', async () => {- const transformerFn = (chunk: any) => ({ type: 'text', id: chunk.id, data: chunk.data });- const transformer = createSSEProtocolTransformer(transformerFn as any);-- const input = { id: '1', data: 'hello' };- const results = await processChunk(transformer, input);-- // Should only output the text event, no injected error on flush (default not enforced)- expect(results).toEqual([`id: 1\n`, `event: text\n`, `data: ${JSON.stringify('hello')}\n\n`]);- });-- it('should not emit flush error if a terminal event was received (enforced)', async () => {- const transformerFn = (chunk: any) => ({ type: 'stop', id: chunk.id, data: chunk.data });- const transformer = createSSEProtocolTransformer(- transformerFn as any,- { id: 'stream_ok' },- { requireTerminalEvent: true },- );-- const input = { id: 'ok', data: 'bye' };- const results = await processChunk(transformer, input);-- // Only the stop event lines should be present (no extra error event from flush)- expect(results).toEqual([`id: ok\n`, `event: stop\n`, `data: ${JSON.stringify('bye')}\n\n`]);- });-- it('should emit an error event on flush when no terminal event received (enforced)', async () => {- const transformerFn = (chunk: any) => ({ type: 'text', id: chunk.id, data: chunk.data });- const streamStack = { id: 'stream_missing_term' } as any;- const transformer = createSSEProtocolTransformer(transformerFn as any, streamStack, {- requireTerminalEvent: true,- });-- const input = { id: '1', data: 'partial' };- const results = await processChunk(transformer, input);-- // original 3 lines + 3 lines from flush error- expect(results).toHaveLength(6);-- // last three lines should be the injected error event- const lastThree = results.slice(-3);- const expectedData = {- body: { name: 'Stream parsing error', reason: 'unexpected_end' },- message: 'Stream ended unexpectedly',- name: 'Stream parsing error',- type: 'ProviderStreamInterrupted',- };-- expect(lastThree).toEqual([- `id: ${streamStack.id}\n`,- `event: error\n`,- `data: ${JSON.stringify(expectedData)}\n\n`,- ]);- });-});-describe('createCallbacksTransformer', () => {// Helper function to process chunks through transformerconst processChunks = async (@@ -1432,7 +1356,7 @@ describe('createCallbacksTransformer', () => {it('should surface first-chunk error via onError callback', async () => {// Simulates the full chain: provider throws β ERROR_CHUNK_PREFIX β FIRST_CHUNK_ERROR_KEY- // β transformOpenAIStream returns { type: 'error' } β createSSEProtocolTransformer+ // β transformOpenAIStream returns { type: 'error' } β createModelEventTransformer// β createCallbacksTransformer should handle 'error' in switchconst onError = vi.fn();const onCompletion = vi.fn();diff --git a/packages/model-runtime/src/core/streams/protocol.ts b/packages/model-runtime/src/core/streams/protocol.tsindex a7b888a5f5d..d098f18d356 100644--- a/packages/model-runtime/src/core/streams/protocol.ts+++ b/packages/model-runtime/src/core/streams/protocol.ts@@ -1,18 +1,14 @@-import type {- ChatCitationItem,- ModelPerformance,- ModelReasoningResponseItem,- ModelUsage,-} from '@lobechat/types';+import type { ChatCitationItem, ModelPerformance, ModelUsage } from '@lobechat/types';import type { Pricing } from 'model-bank';-import { parseToolCalls } from '../../helpers';-import type { ChatStreamCallbacks, OnFinishData, UsageMissingDiagnostics } from '../../types';+import type { ChatStreamCallbacks, UsageMissingDiagnostics } from '../../types';import { AgentRuntimeErrorType } from '../../types/error';import { safeParseJSON } from '../../utils/safeParseJSON';import type { SignatureScope } from '../../utils/signatureScope';import { nanoid } from '../../utils/uuid';import type { ComputeChatCostOptions } from '../usageConverters/utils/computeChatCost';+import type { ModelStreamEvent } from './events';+import { createStreamCallbackDispatcher } from './events';export type ChatPayloadForTransformStream = {apiMode?: UsageMissingDiagnostics['apiMode'];@@ -376,264 +372,35 @@ export const convertIterableToStream = <T>(};/**- * Create a transformer to convert the response into an SSE format+ * Fire callbacks for a stream that is already SSE text. Pipelines built from model events+ * should use `createEventCallbacksTransformer` instead.*/-export const createSSEProtocolTransformer = (- transformer: (chunk: any, stack: StreamContext) => StreamProtocolChunk | StreamProtocolChunk[],- streamStack?: StreamContext,- options?: { requireTerminalEvent?: boolean },-) => {- let hasTerminalEvent = false;- const requireTerminalEvent = Boolean(options?.requireTerminalEvent);-- return new TransformStream({- flush(controller) {- // If the upstream closes without sending a terminal event, emit a final error event.- // The provider cut the response short; no chunk failed to parse, so this is not a- // `StreamChunkError`.- if (requireTerminalEvent && !hasTerminalEvent) {- const id = streamStack?.id || 'stream_end';- const data = {- body: { name: 'Stream parsing error', reason: 'unexpected_end' },- message: 'Stream ended unexpectedly',- name: 'Stream parsing error',- type: AgentRuntimeErrorType.ProviderStreamInterrupted,- };- controller.enqueue(`id: ${id}\n`);- controller.enqueue(`event: error\n`);- controller.enqueue(`data: ${JSON.stringify(data)}\n\n`);- }- },- transform: (chunk, controller) => {- const result = transformer(chunk, streamStack || { id: '' });-- const buffers = Array.isArray(result) ? result : [result];-- buffers.forEach(({ type, id, data }) => {- controller.enqueue(`id: ${id}\n`);- controller.enqueue(`event: ${type}\n`);- controller.enqueue(`data: ${JSON.stringify(data)}\n\n`);-- // mark terminal when receiving any of these events- if (type === 'stop' || type === 'usage' || type === 'error') hasTerminalEvent = true;- });- },- });-};-export function createCallbacksTransformer(cb: ChatStreamCallbacks | undefined,options?: { streamStack?: StreamContext },) {const textEncoder = new TextEncoder();- let aggregatedText = '';- let aggregatedThinking: string | undefined = undefined;- let reasoningSignature: string | undefined;- const reasoningResponseItems: ModelReasoningResponseItem[] = [];- let usage: ModelUsage | undefined;- let speed: ModelPerformance | undefined;- let grounding: any;- let toolsCalling: any;- let streamError: any;- let finishReason: string | undefined;- // Track base64 images for accumulation- const base64Images: Array<{ data: string; id: string }> = [];-+ const dispatcher = createStreamCallbackDispatcher(cb, options);let currentType = '' as unknown as StreamProtocolChunk['type'];- const callbacks = cb || {};return new TransformStream<string, Uint8Array>({- async flush(): Promise<void> {- /**- * Non-streaming Responses conversion emits reasoning items without summary- * deltas, so derive visible thinking text from the item summaries whenever- * nothing was streamed β otherwise the summary would persist but never render.- */- const responseItemsThinking = reasoningResponseItems- .flatMap(({ summary }) => summary ?? [])- .map(({ text }) => text)- .filter(Boolean)- .join('\n');- const reasoningContent = aggregatedThinking || responseItemsThinking || undefined;-- const data: OnFinishData = {- error: streamError,- finishReason,- grounding,- speed,- text: aggregatedText,- thinking: reasoningContent,- toolsCalling,- usage,- };- if (reasoningContent || reasoningSignature || reasoningResponseItems.length > 0) {- data.reasoning = {- content: reasoningContent,- responseItems: reasoningResponseItems.length > 0 ? reasoningResponseItems : undefined,- signature: reasoningSignature,- };- }- const usageMissingDiagnostics = usage- ? undefined- : options?.streamStack?.usageMissingDiagnostics;- if (usageMissingDiagnostics) data.usageMissingDiagnostics = usageMissingDiagnostics;- const { pricingOptions, providerReportedCost } = options?.streamStack ?? {};- if (providerReportedCost !== undefined) data.providerReportedCost = providerReportedCost;- if (pricingOptions) data.pricingOptions = pricingOptions;-- if (callbacks.onCompletion) {- await callbacks.onCompletion(data);- }-- if (callbacks.onFinal) {- await callbacks.onFinal(data);- }- },+ flush: () => dispatcher.finish(),async start(): Promise<void> {- if (callbacks.onStart) await callbacks.onStart();+ await dispatcher.start();},async transform(chunk: string, controller): Promise<void> {controller.enqueue(textEncoder.encode(chunk));- // track the type of the chunkif (chunk.startsWith('event:')) {currentType = chunk.split('event:')[1].trim() as unknown as StreamProtocolChunk['type'];- }- // if the message is a data chunk, handle the callback- else if (chunk.startsWith('data:')) {- // `base64_image` payloads are raw data-URIs (`data:image/png;base64,...`)- // and `reasoning_response_item` payloads carry arbitrary model-authored- // summary text β both can contain `data:` themselves, which the legacy- // `split('data:')[1]` corrupts (it splits on the embedded marker too).- // Strip only the leading field marker for those types; every other event- // type keeps the original split path unchanged for compatibility.- const content =- currentType === 'base64_image' || currentType === 'reasoning_response_item'- ? chunk.slice('data:'.length).trim()- : chunk.split('data:')[1].trim();-- const data = safeParseJSON(content) as any;-- if (!data) return;-- switch (currentType) {- case 'text': {- aggregatedText += data;- await callbacks.onText?.(data);- break;- }-- case 'reasoning': {- if (!aggregatedThinking) {- aggregatedThinking = '';- }-- aggregatedThinking += data;- await callbacks.onThinking?.(data);- break;- }-- case 'reasoning_signature': {- if (typeof data === 'string') reasoningSignature = data;- break;- }-- case 'reasoning_response_item': {- reasoningResponseItems.push(data as ModelReasoningResponseItem);- break;- }-- case 'base64_image': {- // Real providers (google/openai image streams) serialize `data` as a- // raw data-URI string; wrap it into an image item, mirroring- // fetch-sse's client-side parser so both paths share one contract.- // Tolerate the legacy `{ image, images }` object shape too, so any- // existing consumer keeps working.- const image =- typeof data === 'string'- ? { data, id: `tmp_img_${nanoid()}` }- : (data as { image: { data: string; id: string } }).image;- base64Images.push(image);- await callbacks.onBase64Image?.({- image,- images: base64Images,- });- break;- }-- case 'content_part': {- // data format: StreamPartChunkData- const partData = data as StreamPartChunkData;- await callbacks.onContentPart?.({- content: partData.content,- mimeType: partData.mimeType,- partType: partData.partType,- thoughtSignature: partData.thoughtSignature,- });- break;- }-- case 'reasoning_part': {- // data format: StreamPartChunkData- const partData = data as StreamPartChunkData;- await callbacks.onReasoningPart?.({- content: partData.content,- mimeType: partData.mimeType,- partType: partData.partType,- thoughtSignature: partData.thoughtSignature,- });- break;- }-- case 'usage': {- usage = data;- await callbacks.onUsage?.(data);- break;- }-- case 'speed': {- speed = data;- break;- }-- case 'grounding': {- grounding = data;- await callbacks.onGrounding?.(data);- break;- }-- case 'tool_calls': {- if (!toolsCalling) toolsCalling = [];- toolsCalling = parseToolCalls(toolsCalling, data);+ } else if (chunk.startsWith('data:')) {+ // Strip only the leading field marker: any payload can contain `data:` itself+ // (model text, tool arguments, data URIs).+ const data = safeParseJSON(chunk.slice('data:'.length).trim());- await callbacks.onToolsCalling?.({ chunk: data, toolsCalling });- break;- }-- case 'stop': {- // Provider's terminal finishReason (e.g. Google's RECITATION / MAX_TOKENS,- // OpenAI's length, Anthropic's end_turn). Capture so downstream consumers- // can detect soft interrupts where content is empty but tokens were billed.- //- // Some providers emit multiple stop chunks per stream β Anthropic sends- // `message_delta` (carrying the real `stop_reason` like `end_turn` /- // `max_tokens` / `tool_use`) followed by a `message_stop` sentinel.- // Keep the FIRST non-empty value so the meaningful reason is not- // clobbered by the trailing sentinel.- if (typeof data === 'string' && data && !finishReason) {- finishReason = data;- }- break;- }-- case 'error': {- streamError = data;- await callbacks.onError?.(data);- break;- }- }+ await dispatcher.dispatch({ data, type: currentType } as ModelStreamEvent);}},});@@ -730,7 +497,7 @@ const hasEffectiveOutput = (chunk: StreamProtocolChunk): boolean => {/*** Create a middleware to calculate the token generate speed- * @requires createSSEProtocolTransformer+ * @requires createSSEEncoder*/export const createTokenSpeedCalculator = (transformer: (chunk: any, stack: StreamContext) => StreamProtocolChunk | StreamProtocolChunk[],diff --git a/packages/model-runtime/src/core/streams/qwen.ts b/packages/model-runtime/src/core/streams/qwen.tsindex 7e49a27aa41..58e592a03d0 100644--- a/packages/model-runtime/src/core/streams/qwen.ts+++ b/packages/model-runtime/src/core/streams/qwen.ts@@ -7,6 +7,11 @@ import type { Stream } from 'openai/streaming';import type { ChatStreamCallbacks } from '../../types';import { convertOpenAIUsage } from '../usageConverters';+import {+ createEventCallbacksTransformer,+ createModelEventTransformer,+ createSSEEncoder,+} from './events';import type {ChatPayloadForTransformStream,StreamContext,@@ -16,8 +21,6 @@ import type {} from './protocol';import {convertIterableToStream,- createCallbacksTransformer,- createSSEProtocolTransformer,createTokenSpeedCalculator,generateToolCallId,} from './protocol';@@ -219,6 +222,7 @@ export const QwenAIStream = (streamStack: streamContext,}),)- .pipeThrough(createSSEProtocolTransformer((c) => c, streamContext))- .pipeThrough(createCallbacksTransformer(callbacks, { streamStack: streamContext }));+ .pipeThrough(createModelEventTransformer((c) => c, streamContext))+ .pipeThrough(createEventCallbacksTransformer(callbacks, { streamStack: streamContext }))+ .pipeThrough(createSSEEncoder());};diff --git a/packages/model-runtime/src/core/streams/spark.ts b/packages/model-runtime/src/core/streams/spark.tsindex ca8465c92f5..bbc124d339c 100644--- a/packages/model-runtime/src/core/streams/spark.ts+++ b/packages/model-runtime/src/core/streams/spark.ts@@ -3,18 +3,18 @@ import type { Stream } from 'openai/streaming';import type { ChatStreamCallbacks } from '../../types';import { convertOpenAIUsage } from '../usageConverters';+import {+ createEventCallbacksTransformer,+ createModelEventTransformer,+ createSSEEncoder,+} from './events';import type {ChatPayloadForTransformStream,StreamContext,StreamProtocolChunk,StreamProtocolToolCallChunk,} from './protocol';-import {- convertIterableToStream,- createCallbacksTransformer,- createSSEProtocolTransformer,- generateToolCallId,-} from './protocol';+import { convertIterableToStream, generateToolCallId } from './protocol';import { setOpenAIChatCompletionUsageMissingDiagnostics } from './usageMissingDiagnostics';export function transformSparkResponseToStream(data: OpenAI.ChatCompletion) {@@ -236,6 +236,7 @@ export const SparkAIStream = (transformSparkStream(chunk, streamContext, payload);return readableStream- .pipeThrough(createSSEProtocolTransformer(transformWithPayload, streamContext))- .pipeThrough(createCallbacksTransformer(callbacks, { streamStack: streamContext }));+ .pipeThrough(createModelEventTransformer(transformWithPayload, streamContext))+ .pipeThrough(createEventCallbacksTransformer(callbacks, { streamStack: streamContext }))+ .pipeThrough(createSSEEncoder());};