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: fix non stream mode in OpenAI Response API (#9360)

Arvin Xu1c61b21133ff
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index ce07bac531e..fe5b7011047 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -34,6 +34,9 @@ import { StreamingResponse } from '../../utils/response';
import { LobeRuntimeAI } from '../BaseAI';
import { OpenAIResponsesStream, OpenAIStream, OpenAIStreamOptions } from '../streams';
import { createOpenAICompatibleImage } from './createImage';
+import { transformResponseAPIToStream, transformResponseToStream } from './nonStreamToStream';
+
+export * from './nonStreamToStream';
// the model contains the following keywords is not a chat model, so we should filter them out
export const CHAT_MODELS_BLOCK_LIST = [
@@ -117,92 +120,6 @@ interface OpenAICompatibleFactoryOptions<T extends Record<string, any> = any> {
};
}
-/**
- * make the OpenAI response data as a stream
- */
-export function transformResponseToStream(data: OpenAI.ChatCompletion) {
- return new ReadableStream({
- start(controller) {
- const choices = data.choices || [];
- const first = choices[0];
- // 兼容:非流式里 DeepSeek 等会把“深度思考”放在 message.reasoning_content
- const message: any = first?.message ?? {};
- const reasoningText =
- typeof message.reasoning_content === 'string' && message.reasoning_content.length > 0
- ? message.reasoning_content
- : null;
- if (reasoningText) {
- controller.enqueue({
- choices: [
- {
- delta: { content: null, reasoning_content: reasoningText, role: 'assistant' },
- finish_reason: null,
- index: first?.index ?? 0,
- logprobs: first?.logprobs ?? null,
- },
- ],
- created: data.created,
- id: data.id,
- model: data.model,
- object: 'chat.completion.chunk',
- } as unknown as OpenAI.ChatCompletionChunk);
- }
- const chunk: OpenAI.ChatCompletionChunk = {
- choices: choices.map((choice: OpenAI.ChatCompletion.Choice) => ({
- delta: {
- content: choice.message.content,
- role: choice.message.role,
- tool_calls: choice.message.tool_calls?.map(
- (tool, index): OpenAI.ChatCompletionChunk.Choice.Delta.ToolCall => ({
- function: tool.function,
- id: tool.id,
- index,
- type: tool.type,
- }),
- ),
- },
- finish_reason: null,
- index: choice.index,
- logprobs: choice.logprobs,
- })),
- created: data.created,
- id: data.id,
- model: data.model,
- object: 'chat.completion.chunk',
- };
-
- controller.enqueue(chunk);
- if (data.usage) {
- controller.enqueue({
- choices: [],
- created: data.created,
- id: data.id,
- model: data.model,
- object: 'chat.completion.chunk',
- usage: data.usage,
- } as unknown as OpenAI.ChatCompletionChunk);
- }
- controller.enqueue({
- choices: choices.map((choice: OpenAI.ChatCompletion.Choice) => ({
- delta: {
- content: null,
- role: choice.message.role,
- },
- finish_reason: choice.finish_reason,
- index: choice.index,
- logprobs: choice.logprobs,
- })),
- created: data.created,
- id: data.id,
- model: data.model,
- object: 'chat.completion.chunk',
- system_fingerprint: data.system_fingerprint,
- } as OpenAI.ChatCompletionChunk);
- controller.close();
- },
- });
-}
-
export const createOpenAICompatibleRuntime = <T extends Record<string, any> = any>({
provider,
baseURL: DEFAULT_BASE_URL,
@@ -544,9 +461,10 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
): Promise<Response> {
const inputStartAt = Date.now();
- const { messages, reasoning_effort, tools, reasoning, ...res } = responses?.handlePayload
- ? (responses?.handlePayload(payload, this._options) as ChatStreamPayload)
- : payload;
+ const { messages, reasoning_effort, tools, reasoning, responseMode, ...res } =
+ responses?.handlePayload
+ ? (responses?.handlePayload(payload, this._options) as ChatStreamPayload)
+ : payload;
// remove penalty params
delete res.apiMode;
@@ -555,6 +473,8 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
const input = await convertOpenAIResponseInputs(messages as any);
+ const isStreaming = payload.stream !== false;
+
const postPayload = {
...res,
...(reasoning || reasoning_effort
@@ -567,8 +487,9 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
: {}),
input,
store: false,
+ stream: !isStreaming ? undefined : isStreaming,
tools: tools?.map((tool) => this.convertChatCompletionToolToResponseTool(tool)),
- } as OpenAI.Responses.ResponseCreateParamsStreaming;
+ } as OpenAI.Responses.ResponseCreateParamsStreaming | OpenAI.Responses.ResponseCreateParams;
if (debug?.responses?.()) {
console.log('[requestPayload]');
@@ -580,24 +501,43 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
signal: options?.signal,
});
- const [prod, useForDebug] = response.tee();
-
- if (debug?.responses?.()) {
- const useForDebugStream =
- useForDebug instanceof ReadableStream ? useForDebug : useForDebug.toReadableStream();
-
- debugStream(useForDebugStream).catch(console.error);
- }
-
const streamOptions: OpenAIStreamOptions = {
bizErrorTypeTransformer: chatCompletion?.handleStreamBizErrorType,
callbacks: options?.callback,
provider: this.id,
};
- return StreamingResponse(OpenAIResponsesStream(prod, { ...streamOptions, inputStartAt }), {
- headers: options?.headers,
- });
+ if (isStreaming) {
+ const stream = response as Stream<OpenAI.Responses.ResponseStreamEvent>;
+ const [prod, useForDebug] = stream.tee();
+
+ if (debug?.responses?.()) {
+ const useForDebugStream =
+ useForDebug instanceof ReadableStream ? useForDebug : useForDebug.toReadableStream();
+
+ debugStream(useForDebugStream).catch(console.error);
+ }
+
+ return StreamingResponse(OpenAIResponsesStream(prod, { ...streamOptions, inputStartAt }), {
+ headers: options?.headers,
+ });
+ }
+
+ // Handle non-streaming response
+ if (debug?.responses?.()) {
+ debugResponse(response);
+ }
+
+ if (responseMode === 'json') return Response.json(response);
+
+ const stream = transformResponseAPIToStream(response as OpenAI.Responses.Response);
+
+ return StreamingResponse(
+ OpenAIResponsesStream(stream, { ...streamOptions, enableStreaming: false, inputStartAt }),
+ {
+ headers: options?.headers,
+ },
+ );
}
private convertChatCompletionToolToResponseTool = (tool: ChatCompletionTool) => {
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.ts
new file mode 100644
index 00000000000..138a4e78d92
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.ts
@@ -0,0 +1,656 @@
+// @vitest-environment node
+import OpenAI from 'openai';
+import { describe, expect, it } from 'vitest';
+
+import { transformResponseAPIToStream, transformResponseToStream } from './nonStreamToStream';
+
+describe('nonStreamToStream', () => {
+ describe('transformResponseToStream', () => {
+ it('should transform ChatCompletion to stream events correctly', async () => {
+ const mockResponse: OpenAI.ChatCompletion = {
+ id: 'chatcmpl-123',
+ object: 'chat.completion',
+ created: 1677652288,
+ model: 'gpt-3.5-turbo',
+ choices: [
+ {
+ index: 0,
+ message: {
+ role: 'assistant',
+ content: 'Hello! How can I help you today?',
+ refusal: null,
+ },
+ finish_reason: 'stop',
+ logprobs: null,
+ },
+ ],
+ usage: {
+ prompt_tokens: 13,
+ completion_tokens: 7,
+ total_tokens: 20,
+ },
+ };
+
+ const stream = transformResponseToStream(mockResponse);
+ const reader = stream.getReader();
+ const chunks: OpenAI.ChatCompletionChunk[] = [];
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ }
+
+ expect(chunks).toEqual([
+ // First chunk: content chunk
+ {
+ choices: [
+ {
+ delta: {
+ content: 'Hello! How can I help you today?',
+ role: 'assistant',
+ tool_calls: undefined,
+ },
+ finish_reason: null,
+ index: 0,
+ logprobs: null,
+ },
+ ],
+ created: 1677652288,
+ id: 'chatcmpl-123',
+ model: 'gpt-3.5-turbo',
+ object: 'chat.completion.chunk',
+ },
+ // Second chunk: usage chunk
+ {
+ choices: [],
+ created: 1677652288,
+ id: 'chatcmpl-123',
+ model: 'gpt-3.5-turbo',
+ object: 'chat.completion.chunk',
+ usage: {
+ prompt_tokens: 13,
+ completion_tokens: 7,
+ total_tokens: 20,
+ },
+ },
+ // Third chunk: finish chunk
+ {
+ choices: [
+ {
+ delta: {
+ content: null,
+ role: 'assistant',
+ },
+ finish_reason: 'stop',
+ index: 0,
+ logprobs: null,
+ },
+ ],
+ created: 1677652288,
+ id: 'chatcmpl-123',
+ model: 'gpt-3.5-turbo',
+ object: 'chat.completion.chunk',
+ system_fingerprint: undefined,
+ },
+ ]);
+ });
+
+ it('should transform ChatCompletion with reasoning_content to stream events correctly', async () => {
+ const mockResponse: unknown = {
+ id: 'chatcmpl-reasoning-123',
+ object: 'chat.completion',
+ created: 1677652288,
+ model: 'deepseek-reasoner',
+ choices: [
+ {
+ index: 0,
+ message: {
+ role: 'assistant',
+ content: 'The answer is 42.',
+ reasoning_content: 'Let me think about this step by step...',
+ },
+ finish_reason: 'stop',
+ logprobs: null,
+ },
+ ],
+ usage: {
+ prompt_tokens: 13,
+ completion_tokens: 7,
+ total_tokens: 20,
+ },
+ };
+
+ const stream = transformResponseToStream(mockResponse as OpenAI.ChatCompletion);
+ const reader = stream.getReader();
+ const chunks: OpenAI.ChatCompletionChunk[] = [];
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ }
+
+ expect(chunks).toEqual([
+ // First chunk: reasoning chunk
+ {
+ choices: [
+ {
+ delta: {
+ content: null,
+ reasoning_content: 'Let me think about this step by step...',
+ role: 'assistant',
+ },
+ finish_reason: null,
+ index: 0,
+ logprobs: null,
+ },
+ ],
+ created: 1677652288,
+ id: 'chatcmpl-reasoning-123',
+ model: 'deepseek-reasoner',
+ object: 'chat.completion.chunk',
+ },
+ // Second chunk: content chunk
+ {
+ choices: [
+ {
+ delta: {
+ content: 'The answer is 42.',
+ role: 'assistant',
+ tool_calls: undefined,
+ },
+ finish_reason: null,
+ index: 0,
+ logprobs: null,
+ },
+ ],
+ created: 1677652288,
+ id: 'chatcmpl-reasoning-123',
+ model: 'deepseek-reasoner',
+ object: 'chat.completion.chunk',
+ },
+ // Third chunk: usage chunk
+ {
+ choices: [],
+ created: 1677652288,
+ id: 'chatcmpl-reasoning-123',
+ model: 'deepseek-reasoner',
+ object: 'chat.completion.chunk',
+ usage: {
+ prompt_tokens: 13,
+ completion_tokens: 7,
+ total_tokens: 20,
+ },
+ },
+ // Fourth chunk: finish chunk
+ {
+ choices: [
+ {
+ delta: {
+ content: null,
+ role: 'assistant',
+ },
+ finish_reason: 'stop',
+ index: 0,
+ logprobs: null,
+ },
+ ],
+ created: 1677652288,
+ id: 'chatcmpl-reasoning-123',
+ model: 'deepseek-reasoner',
+ object: 'chat.completion.chunk',
+ system_fingerprint: undefined,
+ },
+ ]);
+ });
+
+ it('should transform ChatCompletion with tool_calls to stream events correctly', async () => {
+ const mockResponse: OpenAI.ChatCompletion = {
+ id: 'chatcmpl-tool-123',
+ object: 'chat.completion',
+ created: 1677652288,
+ model: 'gpt-4',
+ choices: [
+ {
+ index: 0,
+ message: {
+ role: 'assistant',
+ content: 'I need to check the weather for you.',
+ refusal: null,
+ tool_calls: [
+ {
+ id: 'call_abc123',
+ type: 'function',
+ function: {
+ name: 'get_weather',
+ arguments: '{"location": "New York"}',
+ },
+ },
+ ],
+ },
+ finish_reason: 'tool_calls',
+ logprobs: null,
+ },
+ ],
+ usage: {
+ prompt_tokens: 13,
+ completion_tokens: 7,
+ total_tokens: 20,
+ },
+ };
+
+ const stream = transformResponseToStream(mockResponse);
+ const reader = stream.getReader();
+ const chunks: OpenAI.ChatCompletionChunk[] = [];
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ }
+
+ expect(chunks).toEqual([
+ // First chunk: content and tool_calls chunk
+ {
+ choices: [
+ {
+ delta: {
+ content: 'I need to check the weather for you.',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ name: 'get_weather',
+ arguments: '{"location": "New York"}',
+ },
+ id: 'call_abc123',
+ index: 0,
+ type: 'function',
+ },
+ ],
+ },
+ finish_reason: null,
+ index: 0,
+ logprobs: null,
+ },
+ ],
+ created: 1677652288,
+ id: 'chatcmpl-tool-123',
+ model: 'gpt-4',
+ object: 'chat.completion.chunk',
+ },
+ // Second chunk: usage chunk
+ {
+ choices: [],
+ created: 1677652288,
+ id: 'chatcmpl-tool-123',
+ model: 'gpt-4',
+ object: 'chat.completion.chunk',
+ usage: {
+ prompt_tokens: 13,
+ completion_tokens: 7,
+ total_tokens: 20,
+ },
+ },
+ // Third chunk: finish chunk
+ {
+ choices: [
+ {
+ delta: {
+ content: null,
+ role: 'assistant',
+ },
+ finish_reason: 'tool_calls',
+ index: 0,
+ logprobs: null,
+ },
+ ],
+ created: 1677652288,
+ id: 'chatcmpl-tool-123',
+ model: 'gpt-4',
+ object: 'chat.completion.chunk',
+ system_fingerprint: undefined,
+ },
+ ]);
+ });
+
+ it('should handle empty choices array', async () => {
+ const mockResponse: OpenAI.ChatCompletion = {
+ id: 'chatcmpl-empty-123',
+ object: 'chat.completion',
+ created: 1677652288,
+ model: 'gpt-3.5-turbo',
+ choices: [],
+ usage: {
+ prompt_tokens: 13,
+ completion_tokens: 0,
+ total_tokens: 13,
+ },
+ };
+
+ const stream = transformResponseToStream(mockResponse);
+ const reader = stream.getReader();
+ const chunks: OpenAI.ChatCompletionChunk[] = [];
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ }
+
+ expect(chunks).toHaveLength(3);
+
+ // Verify all chunks have empty choices array structure
+ expect(chunks[0].choices).toEqual([]);
+ expect(chunks[1]).toEqual({
+ choices: [],
+ created: 1677652288,
+ id: 'chatcmpl-empty-123',
+ model: 'gpt-3.5-turbo',
+ object: 'chat.completion.chunk',
+ usage: {
+ prompt_tokens: 13,
+ completion_tokens: 0,
+ total_tokens: 13,
+ },
+ });
+ expect(chunks[2].choices).toEqual([]);
+ });
+ });
+
+ describe('transformResponseAPIToStream', () => {
+ it('should transform Response API with text output to stream events correctly', async () => {
+ const mockResponse: OpenAI.Responses.Response = {
+ id: 'resp_abc123',
+ object: 'response',
+ status: 'completed',
+ status_details: null,
+ output: [
+ {
+ id: 'msg_001',
+ object: 'realtime.item',
+ type: 'message',
+ status: 'completed',
+ role: 'assistant',
+ content: [
+ {
+ type: 'output_text',
+ text: 'Hello! How can I help you today?',
+ } as any,
+ ],
+ },
+ ],
+ usage: {
+ total_tokens: 20,
+ input_tokens: 13,
+ output_tokens: 7,
+ input_tokens_details: { audio_tokens: 0, cache_read_tokens: 0 },
+ output_tokens_details: { audio_tokens: 0, reasoning_tokens: 0 },
+ },
+ created: 1677652288,
+ created_at: 1677652288,
+ model: 'gpt-4o-realtime-preview',
+ } as any;
+
+ const stream = transformResponseAPIToStream(mockResponse);
+ const reader = stream.getReader();
+ const events: OpenAI.Responses.ResponseStreamEvent[] = [];
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ events.push(value);
+ }
+
+ expect(events).toEqual([
+ // First event: response.output_text.delta
+ {
+ delta: 'Hello! How can I help you today?',
+ type: 'response.output_text.delta',
+ },
+ // Second event: response.completed
+ {
+ response: mockResponse,
+ sequence_number: 999,
+ type: 'response.completed',
+ },
+ ]);
+ });
+
+ it('should handle Response API without message output', async () => {
+ const mockResponse: OpenAI.Responses.Response = {
+ id: 'resp_no_message',
+ object: 'response',
+ status: 'completed',
+ status_details: null,
+ output: [
+ {
+ id: 'audio_001',
+ object: 'realtime.item',
+ type: 'message' as any,
+ status: 'completed',
+ // Missing content property
+ },
+ ],
+ usage: {
+ total_tokens: 5,
+ input_tokens: 5,
+ output_tokens: 0,
+ input_tokens_details: { audio_tokens: 0, cache_read_tokens: 0 },
+ output_tokens_details: { audio_tokens: 0, reasoning_tokens: 0 },
+ },
+ created: 1677652288,
+ created_at: 1677652288,
+ model: 'gpt-4o-realtime-preview',
+ } as any;
+
+ const stream = transformResponseAPIToStream(mockResponse);
+ const reader = stream.getReader();
+ const events: OpenAI.Responses.ResponseStreamEvent[] = [];
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ events.push(value);
+ }
+
+ // Should only produce response.completed event, no text deltas
+ expect(events).toEqual([
+ {
+ response: mockResponse,
+ sequence_number: 999,
+ type: 'response.completed',
+ },
+ ]);
+ });
+
+ it('should handle Response API with message but no text content', async () => {
+ const mockResponse: OpenAI.Responses.Response = {
+ id: 'resp_no_text',
+ object: 'response',
+ status: 'completed',
+ status_details: null,
+ output: [
+ {
+ id: 'msg_no_text',
+ object: 'realtime.item',
+ type: 'message',
+ status: 'completed',
+ role: 'assistant',
+ content: [
+ {
+ type: 'output_text' as any,
+ audio: 'base64encodedaudio',
+ // No text property
+ },
+ ],
+ },
+ ],
+ usage: {
+ total_tokens: 5,
+ input_tokens: 5,
+ output_tokens: 0,
+ input_tokens_details: { audio_tokens: 0, cache_read_tokens: 0 },
+ output_tokens_details: { audio_tokens: 0, reasoning_tokens: 0 },
+ },
+ created: 1677652288,
+ created_at: 1677652288,
+ model: 'gpt-4o-realtime-preview',
+ } as any;
+
+ const stream = transformResponseAPIToStream(mockResponse);
+ const reader = stream.getReader();
+ const events: OpenAI.Responses.ResponseStreamEvent[] = [];
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ events.push(value);
+ }
+
+ // Should only produce response.completed event because message has no text content
+ expect(events).toEqual([
+ {
+ response: mockResponse,
+ sequence_number: 999,
+ type: 'response.completed',
+ },
+ ]);
+ });
+
+ it('should handle Response API with message id missing', async () => {
+ const mockResponse: OpenAI.Responses.Response = {
+ id: 'resp_missing_id',
+ object: 'response',
+ status: 'completed',
+ status_details: null,
+ output: [
+ {
+ // id is missing
+ object: 'realtime.item',
+ type: 'message',
+ status: 'completed',
+ role: 'assistant',
+ content: [
+ {
+ type: 'output_text',
+ text: 'Response without message ID',
+ } as any,
+ ],
+ },
+ ],
+ usage: {
+ total_tokens: 15,
+ input_tokens: 10,
+ output_tokens: 5,
+ input_tokens_details: { audio_tokens: 0, cache_read_tokens: 0 },
+ output_tokens_details: { audio_tokens: 0, reasoning_tokens: 0 },
+ },
+ created: 1677652288,
+ created_at: 1677652288,
+ model: 'gpt-4o-realtime-preview',
+ } as any;
+
+ const stream = transformResponseAPIToStream(mockResponse);
+ const reader = stream.getReader();
+ const events: OpenAI.Responses.ResponseStreamEvent[] = [];
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ events.push(value);
+ }
+
+ expect(events).toEqual([
+ {
+ delta: 'Response without message ID',
+ type: 'response.output_text.delta',
+ },
+ {
+ response: mockResponse,
+ sequence_number: 999,
+ type: 'response.completed',
+ },
+ ]);
+ });
+
+ it('should handle empty output array', async () => {
+ const mockResponse: OpenAI.Responses.Response = {
+ id: 'resp_empty_output',
+ object: 'response',
+ status: 'completed',
+ status_details: null,
+ output: [],
+ usage: {
+ total_tokens: 5,
+ input_tokens: 5,
+ output_tokens: 0,
+ input_tokens_details: { audio_tokens: 0, cache_read_tokens: 0 },
+ output_tokens_details: { audio_tokens: 0, reasoning_tokens: 0 },
+ },
+ created: 1677652288,
+ created_at: 1677652288,
+ model: 'gpt-4o-realtime-preview',
+ } as any;
+
+ const stream = transformResponseAPIToStream(mockResponse);
+ const reader = stream.getReader();
+ const events: OpenAI.Responses.ResponseStreamEvent[] = [];
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ events.push(value);
+ }
+
+ // Should only produce response.completed event even with empty output
+ expect(events).toEqual([
+ {
+ response: mockResponse,
+ sequence_number: 999,
+ type: 'response.completed',
+ },
+ ]);
+ });
+
+ it('should handle missing output field', async () => {
+ const mockResponse: Partial<OpenAI.Responses.Response> = {
+ id: 'resp_no_output',
+ object: 'response',
+ status: 'completed',
+ status_details: null,
+ // output field is missing
+ usage: {
+ total_tokens: 5,
+ input_tokens: 5,
+ output_tokens: 0,
+ input_tokens_details: { audio_tokens: 0, cache_read_tokens: 0 },
+ output_tokens_details: { audio_tokens: 0, reasoning_tokens: 0 },
+ },
+ created: 1677652288,
+ created_at: 1677652288,
+ model: 'gpt-4o-realtime-preview',
+ } as any;
+
+ const stream = transformResponseAPIToStream(mockResponse as OpenAI.Responses.Response);
+ const reader = stream.getReader();
+ const events: OpenAI.Responses.ResponseStreamEvent[] = [];
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ events.push(value);
+ }
+
+ // Should only produce response.completed event since output is missing
+ expect(events).toEqual([
+ {
+ response: mockResponse,
+ sequence_number: 999,
+ type: 'response.completed',
+ },
+ ]);
+ });
+ });
+});
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts
new file mode 100644
index 00000000000..033b9d13026
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts
@@ -0,0 +1,131 @@
+import OpenAI from 'openai';
+
+/**
+ * make the OpenAI response data as a stream
+ */
+export const transformResponseToStream = (data: OpenAI.ChatCompletion) =>
+ new ReadableStream({
+ start(controller) {
+ const choices = data.choices || [];
+ const first = choices[0];
+ // 兼容:非流式里 DeepSeek 等会把“深度思考”放在 message.reasoning_content
+ const message: any = first?.message ?? {};
+ const reasoningText =
+ typeof message.reasoning_content === 'string' && message.reasoning_content.length > 0
+ ? message.reasoning_content
+ : null;
+ if (reasoningText) {
+ controller.enqueue({
+ choices: [
+ {
+ delta: { content: null, reasoning_content: reasoningText, role: 'assistant' },
+ finish_reason: null,
+ index: first?.index ?? 0,
+ logprobs: first?.logprobs ?? null,
+ },
+ ],
+ created: data.created,
+ id: data.id,
+ model: data.model,
+ object: 'chat.completion.chunk',
+ } as unknown as OpenAI.ChatCompletionChunk);
+ }
+ const chunk: OpenAI.ChatCompletionChunk = {
+ choices: choices.map((choice: OpenAI.ChatCompletion.Choice) => ({
+ delta: {
+ content: choice.message.content,
+ role: choice.message.role,
+ tool_calls: choice.message.tool_calls?.map(
+ (tool, index): OpenAI.ChatCompletionChunk.Choice.Delta.ToolCall => ({
+ function: tool.function,
+ id: tool.id,
+ index,
+ type: tool.type,
+ }),
+ ),
+ },
+ finish_reason: null,
+ index: choice.index,
+ logprobs: choice.logprobs,
+ })),
+ created: data.created,
+ id: data.id,
+ model: data.model,
+ object: 'chat.completion.chunk',
+ };
+
+ controller.enqueue(chunk);
+ if (data.usage) {
+ controller.enqueue({
+ choices: [],
+ created: data.created,
+ id: data.id,
+ model: data.model,
+ object: 'chat.completion.chunk',
+ usage: data.usage,
+ } as unknown as OpenAI.ChatCompletionChunk);
+ }
+ controller.enqueue({
+ choices: choices.map((choice: OpenAI.ChatCompletion.Choice) => ({
+ delta: {
+ content: null,
+ role: choice.message.role,
+ },
+ finish_reason: choice.finish_reason,
+ index: choice.index,
+ logprobs: choice.logprobs,
+ })),
+ created: data.created,
+ id: data.id,
+ model: data.model,
+ object: 'chat.completion.chunk',
+ system_fingerprint: data.system_fingerprint,
+ } as OpenAI.ChatCompletionChunk);
+ controller.close();
+ },
+ });
+
+/**
+ * transform the OpenAI Response API data to stream format for non-streaming responses
+ */
+export const transformResponseAPIToStream = (data: OpenAI.Responses.Response) =>
+ new ReadableStream({
+ start(controller) {
+ // Check if output exists and is an array
+ if (data.output && Array.isArray(data.output)) {
+ data.output.forEach((output) => {
+ switch (output.type) {
+ case 'message': {
+ // Check if content exists and is an array
+ if (output.content && Array.isArray(output.content)) {
+ output.content.forEach((content) => {
+ switch (content.type) {
+ case 'output_text': {
+ // Only emit delta if text exists
+ if (content.text) {
+ controller.enqueue({
+ delta: content.text,
+ type: 'response.output_text.delta',
+ });
+ }
+ break;
+ }
+ }
+ });
+ }
+ break;
+ }
+ }
+ });
+ }
+
+ // Always send response.completed event
+ controller.enqueue({
+ response: data,
+ sequence_number: 999,
+ type: 'response.completed',
+ } as OpenAI.Responses.ResponseStreamEvent);
+
+ controller.close();
+ },
+ });