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.

♻️ refactor(model-runtime): organize OpenAI code by protocol (Chat Completions / Responses) (#22731)

Arvin Xucf1f576cd781
diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.ts
index 426386f7234..75c49137185 100644
--- a/packages/model-runtime/src/core/ModelRuntime.test.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts
@@ -938,6 +938,20 @@ describe('ModelRuntime', () => {
);
});
+ it('returns embeddings when onEmbeddingsFinal throws', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const onEmbeddingsFinal = vi.fn().mockRejectedValue(new Error('billing down'));
+ const { runtime, mockRuntimeAI } = createMockRuntime({ onEmbeddingsFinal });
+ mockRuntimeAI.embeddings.mockResolvedValue([[0.1]]);
+
+ await expect(runtime.embeddings({ input: 'hi', model: 'emb' })).resolves.toEqual([[0.1]]);
+ expect(consoleError).toHaveBeenCalledWith(
+ '[ModelRuntime] onEmbeddingsFinal hook error:',
+ expect.any(Error),
+ );
+ consoleError.mockRestore();
+ });
+
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/contextBuilders/openai.test.ts b/packages/model-runtime/src/core/contextBuilders/openai.test.ts
index be2e4d8c0ef..e3a4d74b757 100644
--- a/packages/model-runtime/src/core/contextBuilders/openai.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/openai.test.ts
@@ -1,17 +1,13 @@
-import { imageUrlToBase64 } from '../../utils/imageToBase64';
-import { videoUrlToBase64 } from '../../utils/videoToBase64';
import type OpenAI from 'openai';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import type { OpenAIChatMessage } from '../../types';
+import { imageUrlToBase64 } from '../../utils/imageToBase64';
import { clearReferenceImageCache } from '../../utils/referenceImageCache';
-import { serializeScopedSignature, type SignatureScope } from '../../utils/signatureScope';
import { parseDataUri } from '../../utils/uriParser';
+import { videoUrlToBase64 } from '../../utils/videoToBase64';
import {
convertImageUrlToFile,
convertMessageContent,
- convertOpenAIMessages,
- convertOpenAIResponseInputs,
type ExtendedChatCompletionContentPart,
} from './openai';
@@ -294,1335 +290,6 @@ describe('convertMessageContent', () => {
});
});
-describe('convertOpenAIMessages', () => {
- it('should restore thoughtSignature only for the exact scope', async () => {
- const scope: SignatureScope = { fingerprint: 'a'.repeat(32) };
- const foreignScope: SignatureScope = { fingerprint: 'b'.repeat(32) };
- const thoughtSignature = serializeScopedSignature(
- 'google-signature',
- scope,
- 'thought_signature',
- );
- const messages = [
- {
- content: '',
- role: 'assistant',
- tool_calls: [
- {
- function: { arguments: '{}', name: 'get_weather' },
- id: 'call_1',
- thoughtSignature,
- type: 'function',
- },
- ],
- },
- ] as any;
-
- const matching = await convertOpenAIMessages(messages, { thoughtSignatureScope: scope });
- const mismatching = await convertOpenAIMessages(messages, {
- thoughtSignatureScope: foreignScope,
- });
- const legacy = await convertOpenAIMessages(
- [
- {
- ...messages[0],
- tool_calls: [{ ...messages[0].tool_calls[0], thoughtSignature: 'legacy-signature' }],
- },
- ],
- { thoughtSignatureScope: scope },
- );
-
- expect((matching[0] as any).tool_calls[0].thoughtSignature).toBe('google-signature');
- expect((mismatching[0] as any).tool_calls[0].thoughtSignature).toBeUndefined();
- expect((legacy[0] as any).tool_calls[0].thoughtSignature).toBeUndefined();
- });
-
- it('should convert string content messages', async () => {
- const messages = [
- { role: 'user', content: 'Hello' },
- { role: 'assistant', content: 'Hi there' },
- ] as OpenAI.ChatCompletionMessageParam[];
-
- const result = await convertOpenAIMessages(messages);
-
- expect(result).toEqual(messages);
- });
-
- it('should convert array content messages', async () => {
- const messages = [
- {
- role: 'user',
- content: [
- { type: 'text', text: 'Hello' },
- { type: 'image_url', image_url: { url: 'https://example.com/image.jpg' } },
- ],
- },
- ] as OpenAI.ChatCompletionMessageParam[];
-
- vi.spyOn(Promise, 'all');
- vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
- vi.mocked(imageUrlToBase64).mockResolvedValue({
- base64: 'base64String',
- mimeType: 'image/jpeg',
- });
-
- process.env.LLM_VISION_IMAGE_USE_BASE64 = '1';
-
- const result = await convertOpenAIMessages(messages);
-
- expect(result).toEqual([
- {
- role: 'user',
- content: [
- { type: 'text', text: 'Hello' },
- {
- type: 'image_url',
- image_url: { url: 'data:image/jpeg;base64,base64String' },
- },
- ],
- },
- ]);
-
- expect(Promise.all).toHaveBeenCalledTimes(2); // 一次用于消息数组,一次用于内容数组
-
- process.env.LLM_VISION_IMAGE_USE_BASE64 = undefined;
- });
- it('should convert array content messages', async () => {
- const messages = [
- {
- role: 'user',
- content: [
- { type: 'text', text: 'Hello' },
- { type: 'image_url', image_url: { url: 'https://example.com/image.jpg' } },
- ],
- },
- ] as OpenAI.ChatCompletionMessageParam[];
-
- vi.spyOn(Promise, 'all');
- vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
- vi.mocked(imageUrlToBase64).mockResolvedValue({
- base64: 'base64String',
- mimeType: 'image/jpeg',
- });
-
- const result = await convertOpenAIMessages(messages);
-
- expect(result).toEqual(messages);
-
- expect(Promise.all).toHaveBeenCalledTimes(2); // 一次用于消息数组,一次用于内容数组
- });
-
- it('should filter out reasoning field from messages', async () => {
- const messages = [
- {
- role: 'assistant',
- content: 'Hello',
- reasoning: { content: 'some reasoning', duration: 100 },
- },
- { role: 'user', content: 'Hi' },
- ] as any;
-
- const result = await convertOpenAIMessages(messages);
-
- expect(result).toEqual([
- { role: 'assistant', content: 'Hello' },
- { role: 'user', content: 'Hi' },
- ]);
- // Ensure reasoning field is removed
- expect((result[0] as any).reasoning).toBeUndefined();
- });
-
- describe('reasoning passback for thinking families', () => {
- // Upstream rejects a thinking-mode turn that carries tool_calls without the
- // historical reasoning: "If thinking mode and tool_calls, `reasoning_content`
- // must be passed back to the API."
- const assistantTurn = {
- content: 'Calling a tool',
- reasoning: { content: 'step-by-step thinking' },
- role: 'assistant',
- tool_calls: [
- { function: { arguments: '{}', name: 'search' }, id: 'call-1', type: 'function' },
- ],
- } as any;
-
- it.each([['deepseek-v4-pro'], ['glm-5.3'], ['kimi-k3']])(
- 'echoes structured reasoning back for %s',
- async (model) => {
- const result = await convertOpenAIMessages([assistantTurn], { model });
-
- expect((result[0] as any).reasoning_content).toBe('step-by-step thinking');
- },
- );
-
- it('leaves unrelated models untouched', async () => {
- const result = await convertOpenAIMessages([assistantTurn], { model: 'gpt-5.6-sol' });
-
- expect((result[0] as any).reasoning_content).toBeUndefined();
- });
-
- it('keeps the empty placeholder scoped to DeepSeek thinking models', async () => {
- const withoutReasoning = { ...assistantTurn, reasoning: undefined };
-
- const deepseek = await convertOpenAIMessages([withoutReasoning], {
- model: 'deepseek-v4-pro',
- });
- const glm = await convertOpenAIMessages([withoutReasoning], { model: 'glm-5.3' });
-
- expect((deepseek[0] as any).reasoning_content).toBe('');
- expect((glm[0] as any).reasoning_content).toBeUndefined();
- });
- });
-
- it('should preserve reasoning_content field from messages (for DeepSeek compatibility)', async () => {
- const messages = [
- {
- role: 'assistant',
- content: 'Hello',
- reasoning_content: 'some reasoning content',
- },
- { role: 'user', content: 'Hi' },
- ] as any;
-
- const result = await convertOpenAIMessages(messages);
-
- expect(result).toEqual([
- { role: 'assistant', content: 'Hello', reasoning_content: 'some reasoning content' },
- { role: 'user', content: 'Hi' },
- ]);
- // Ensure reasoning_content field is preserved
- expect((result[0] as any).reasoning_content).toBe('some reasoning content');
- });
-
- it('should filter internal thinking content parts but preserve reasoning_content', async () => {
- const messages = [
- {
- role: 'assistant',
- content: [
- {
- signature: 'sig_123',
- thinking: 'internal reasoning',
- type: 'thinking',
- },
- {
- text: 'Visible answer',
- type: 'text',
- },
- ],
- reasoning_content: 'internal reasoning',
- },
- ] as any;
-
- const result = await convertOpenAIMessages(messages);
-
- expect(result).toEqual([
- {
- role: 'assistant',
- content: [{ text: 'Visible answer', type: 'text' }],
- reasoning_content: 'internal reasoning',
- },
- ]);
- });
-
- it('should filter out reasoning but preserve reasoning_content field', async () => {
- const messages = [
- {
- role: 'assistant',
- content: 'Hello',
- reasoning: { content: 'some reasoning', duration: 100 },
- reasoning_content: 'some reasoning content',
- },
- ] as any;
-
- const result = await convertOpenAIMessages(messages);
-
- expect(result).toEqual([
- { role: 'assistant', content: 'Hello', reasoning_content: 'some reasoning content' },
- ]);
- // Ensure reasoning object is removed but reasoning_content is preserved
- expect((result[0] as any).reasoning).toBeUndefined();
- expect((result[0] as any).reasoning_content).toBe('some reasoning content');
- });
-
- describe('tool messages with image parts', () => {
- it('should flatten the tool message to text and re-attach images as a user message', async () => {
- vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
-
- const messages = [
- {
- role: 'assistant',
- content: '',
- tool_calls: [
- { id: 'call_1', type: 'function', function: { name: 'readFile', arguments: '{}' } },
- ],
- },
- {
- role: 'tool',
- tool_call_id: 'call_1',
- content: [
- { type: 'text', text: '[Image: cat.png]' },
- { type: 'image_url', image_url: { url: 'https://files.example.com/cat.png' } },
- ],
- },
- { role: 'user', content: 'what do you see?' },
- ] as OpenAI.ChatCompletionMessageParam[];
-
- const result = await convertOpenAIMessages(messages);
-
- expect(result).toEqual([
- messages[0],
- // Tool message content must be text-only for the OpenAI API.
- { role: 'tool', tool_call_id: 'call_1', content: '[Image: cat.png]' },
- {
- role: 'user',
- content: [
- { type: 'text', text: 'Image output of tool call call_1:' },
- { type: 'image_url', image_url: { url: 'https://files.example.com/cat.png' } },
- ],
- },
- { role: 'user', content: 'what do you see?' },
- ]);
- });
-
- it('should keep the tool batch contiguous when multiple tool results carry images', async () => {
- vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
-
- const messages = [
- {
- role: 'assistant',
- content: '',
- tool_calls: [
- { id: 'call_1', type: 'function', function: { name: 'readFile', arguments: '{}' } },
- { id: 'call_2', type: 'function', function: { name: 'readFile', arguments: '{}' } },
- ],
- },
- {
- role: 'tool',
- tool_call_id: 'call_1',
- content: [{ type: 'image_url', image_url: { url: 'https://files.example.com/a.png' } }],
- },
- {
- role: 'tool',
- tool_call_id: 'call_2',
- content: 'plain text result',
- },
- ] as OpenAI.ChatCompletionMessageParam[];
-
- const result = await convertOpenAIMessages(messages);
-
- // No user message may interleave between the tool results of one batch.
- expect(result.map((m) => m.role)).toEqual(['assistant', 'tool', 'tool', 'user']);
- expect(result[1]).toEqual({
- role: 'tool',
- tool_call_id: 'call_1',
- content: '[Image output attached below]',
- });
- expect(result[2]).toEqual(messages[2]);
- expect(result[3]).toEqual({
- role: 'user',
- content: [
- { type: 'text', text: 'Image output of tool call call_1:' },
- { type: 'image_url', image_url: { url: 'https://files.example.com/a.png' } },
- ],
- });
- });
- });
-
- describe('DeepSeek reasoning_content compatibility', () => {
- it('should derive reasoning_content from reasoning.content for deepseek models', async () => {
- const messages = [
- {
- role: 'assistant',
- content: 'Answer with tool call',
- reasoning: { content: 'planned tool invocation', duration: 100 },
- tool_calls: [
- { id: 'call_1', type: 'function', function: { name: 'search', arguments: '{}' } },
- ],
- },
- ] as any;
-
- const result = await convertOpenAIMessages(messages, { model: 'deepseek-v4-flash' });
-
- expect((result[0] as any).reasoning_content).toBe('planned tool invocation');
- expect((result[0] as any).tool_calls).toHaveLength(1);
- expect((result[0] as any).reasoning).toBeUndefined();
- });
-
- it('should force empty reasoning_content for deepseek-v4 thinking-mode assistant messages without reasoning', async () => {
- const messages = [
- {
- role: 'assistant',
- content: '',
- tool_calls: [
- { id: 'call_1', type: 'function', function: { name: 'search', arguments: '{}' } },
- ],
- },
- ] as any;
-
- const result = await convertOpenAIMessages(messages, { model: 'deepseek-v4-pro' });
-
- expect((result[0] as any).reasoning_content).toBe('');
- });
-
- it('should force empty reasoning_content for deepseek-reasoner', async () => {
- const messages = [{ role: 'assistant', content: 'Hi' }] as any;
-
- const result = await convertOpenAIMessages(messages, { model: 'deepseek-reasoner' });
-
- expect((result[0] as any).reasoning_content).toBe('');
- });
-
- it('should match provider-prefixed deepseek model ids (e.g. Deepseek/deepseek-v4-pro)', async () => {
- const messages = [{ role: 'assistant', content: 'Hi' }] as any;
-
- const result = await convertOpenAIMessages(messages, {
- model: 'Deepseek/deepseek-v4-pro',
- });
-
- expect((result[0] as any).reasoning_content).toBe('');
- });
-
- it('should not force reasoning_content for non-thinking deepseek models', async () => {
- const messages = [{ role: 'assistant', content: 'Hi' }] as any;
-
- const result = await convertOpenAIMessages(messages, { model: 'deepseek-chat' });
-
- expect((result[0] as any).reasoning_content).toBeUndefined();
- });
-
- it('should leave non-deepseek models untouched', async () => {
- const messages = [
- {
- role: 'assistant',
- content: 'Hi',
- reasoning: { content: 'unrelated', duration: 10 },
- },
- ] as any;
-
- const result = await convertOpenAIMessages(messages, { model: 'gpt-4o-mini' });
-
- expect((result[0] as any).reasoning_content).toBeUndefined();
- expect((result[0] as any).reasoning).toBeUndefined();
- });
-
- it('should not touch non-assistant messages', async () => {
- const messages = [
- { role: 'user', content: 'hello' },
- { role: 'tool', content: '{}', tool_call_id: 'call_1' },
- ] as any;
-
- const result = await convertOpenAIMessages(messages, { model: 'deepseek-v4-flash' });
-
- expect((result[0] as any).reasoning_content).toBeUndefined();
- expect((result[1] as any).reasoning_content).toBeUndefined();
- });
-
- it('should preserve existing reasoning_content over reasoning.content', async () => {
- const messages = [
- {
- role: 'assistant',
- content: 'Hi',
- reasoning: { content: 'should be ignored', duration: 10 },
- reasoning_content: 'kept',
- },
- ] as any;
-
- const result = await convertOpenAIMessages(messages, { model: 'deepseek-v4-flash' });
-
- expect((result[0] as any).reasoning_content).toBe('kept');
- });
- });
-});
-
-describe('convertOpenAIResponseInputs', () => {
- it('should reject raw audio explicitly instead of dropping it from Responses input', async () => {
- const messages: OpenAIChatMessage[] = [
- {
- content: [
- {
- audio_url: { mimeType: 'audio/wav', url: 'https://files.example.com/voice.wav' },
- type: 'audio_url',
- },
- ],
- role: 'user',
- },
- ];
-
- await expect(convertOpenAIResponseInputs(messages)).rejects.toThrow(
- 'OpenAI raw audio input requires the Chat Completions API',
- );
- });
-
- it('应该正确转换普通文本消息', async () => {
- const messages: OpenAIChatMessage[] = [
- { role: 'user', content: 'Hello' },
- { role: 'assistant', content: 'Hi there!' },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- { role: 'user', content: 'Hello' },
- { role: 'assistant', content: 'Hi there!' },
- ]);
- });
-
- it('应该正确转换带有工具调用的消息', async () => {
- const messages: OpenAIChatMessage[] = [
- {
- role: 'assistant',
- content: '',
- tool_calls: [
- {
- id: 'call_123',
- type: 'function',
- function: {
- name: 'test_function',
- arguments: '{"key": "value"}',
- },
- },
- ],
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- {
- arguments: 'test_function',
- call_id: 'call_123',
- name: 'test_function',
- type: 'function_call',
- },
- ]);
- });
-
- it('应该正确转换工具响应消息', async () => {
- const messages: OpenAIChatMessage[] = [
- {
- role: 'tool',
- content: 'Function result',
- tool_call_id: 'call_123',
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- {
- call_id: 'call_123',
- output: 'Function result',
- type: 'function_call_output',
- },
- ]);
- });
-
- it('工具响应带图片时应保持 output 纯文本并追加 user 图片消息', async () => {
- vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
-
- const messages: OpenAIChatMessage[] = [
- {
- content: [
- { text: '[Image: cat.png]', type: 'text' },
- { image_url: { url: 'https://files.example.com/cat.png' }, type: 'image_url' },
- ] as any,
- role: 'tool',
- tool_call_id: 'call_123',
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- {
- call_id: 'call_123',
- // function_call_output.output is text-only — images must not land here.
- output: '[Image: cat.png]',
- type: 'function_call_output',
- },
- {
- content: [
- { text: 'Image output of tool call call_123:', type: 'input_text' },
- { image_url: 'https://files.example.com/cat.png', type: 'input_image' },
- ],
- role: 'user',
- type: 'message',
- },
- ]);
- });
-
- it('应该正确转换包含图片的消息', async () => {
- const messages: OpenAIChatMessage[] = [
- {
- role: 'user',
- content: [
- { type: 'text', text: 'Here is an image' },
- {
- type: 'image_url',
- image_url: {
- url: 'data:image/jpeg;base64,test123',
- },
- },
- ],
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- {
- role: 'user',
- content: [
- { type: 'input_text', text: 'Here is an image' },
- {
- type: 'input_image',
- image_url: 'data:image/jpeg;base64,test123',
- },
- ],
- },
- ]);
- });
-
- it('should preserve the requested image detail on input_image parts', async () => {
- const messages: OpenAIChatMessage[] = [
- {
- role: 'user',
- content: [
- { type: 'text', text: 'Inspect the circled area' },
- {
- type: 'image_url',
- image_url: { detail: 'high', url: 'data:image/png;base64,test123' },
- },
- ],
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- {
- role: 'user',
- content: [
- { type: 'input_text', text: 'Inspect the circled area' },
- { detail: 'high', image_url: 'data:image/png;base64,test123', type: 'input_image' },
- ],
- },
- ]);
- });
-
- it('应该正确转换包含视频的消息', async () => {
- const messages: OpenAIChatMessage[] = [
- {
- role: 'user',
- content: [
- { type: 'text', text: 'Here is a video' },
- {
- type: 'video_url',
- video_url: {
- url: 'data:video/mp4;base64,test123',
- },
- },
- ],
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- {
- role: 'user',
- content: [
- { type: 'input_text', text: 'Here is a video' },
- {
- type: 'input_video',
- video_url: 'data:video/mp4;base64,test123',
- },
- ],
- },
- ]);
- });
-
- it('应该正确转换包含图片和视频的混合消息', async () => {
- const messages: OpenAIChatMessage[] = [
- {
- role: 'user',
- content: [
- { type: 'text', text: 'Here is an image and a video' },
- {
- type: 'image_url',
- image_url: {
- url: 'data:image/jpeg;base64,test123',
- },
- },
- {
- type: 'video_url',
- video_url: {
- url: 'data:video/mp4;base64,test456',
- },
- },
- ],
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- {
- role: 'user',
- content: [
- { type: 'input_text', text: 'Here is an image and a video' },
- {
- type: 'input_image',
- image_url: 'data:image/jpeg;base64,test123',
- },
- {
- type: 'input_video',
- video_url: 'data:video/mp4;base64,test456',
- },
- ],
- },
- ]);
- });
-
- it('应该正确处理带有无效 video_url 的消息', async () => {
- const messages: OpenAIChatMessage[] = [
- {
- role: 'user',
- content: [
- { type: 'text', text: 'Here is a video' },
- {
- type: 'video_url',
- video_url: {
- url: '',
- },
- },
- ],
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- {
- role: 'user',
- content: [{ type: 'input_text', text: 'Here is a video' }],
- },
- ]);
- });
-
- it('应该正确处理混合类型的消息序列', async () => {
- const messages: OpenAIChatMessage[] = [
- { role: 'user', content: 'I need help with a function' },
- {
- role: 'assistant',
- content: '',
- tool_calls: [
- {
- id: 'call_456',
- type: 'function',
- function: {
- name: 'get_data',
- arguments: '{}',
- },
- },
- ],
- },
- {
- role: 'tool',
- content: '{"result": "success"}',
- tool_call_id: 'call_456',
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- { role: 'user', content: 'I need help with a function' },
- {
- arguments: 'get_data',
- call_id: 'call_456',
- name: 'get_data',
- type: 'function_call',
- },
- {
- call_id: 'call_456',
- output: '{"result": "success"}',
- type: 'function_call_output',
- },
- ]);
- });
-
- it('should filter orphan tool calls when strictToolPairing is enabled', async () => {
- const messages: OpenAIChatMessage[] = [
- { role: 'user', content: 'Use tools carefully' },
- {
- role: 'assistant',
- content: '',
- tool_calls: [
- {
- id: 'call_paired',
- type: 'function',
- function: {
- name: 'get_weather',
- arguments: '{"city":"Hangzhou"}',
- },
- },
- {
- id: 'call_orphan',
- type: 'function',
- function: {
- name: 'get_news',
- arguments: '{"topic":"AI"}',
- },
- },
- ],
- },
- {
- role: 'tool',
- content: '{"temp":22}',
- tool_call_id: 'call_paired',
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages, { strictToolPairing: true });
-
- expect(result).toEqual([
- { role: 'user', content: 'Use tools carefully' },
- {
- arguments: '{"city":"Hangzhou"}',
- call_id: 'call_paired',
- name: 'get_weather',
- type: 'function_call',
- },
- {
- call_id: 'call_paired',
- output: '{"temp":22}',
- type: 'function_call_output',
- },
- ]);
- });
-
- it('should drop assistant message with all orphaned tool_calls in strict mode', async () => {
- const messages: OpenAIChatMessage[] = [
- { role: 'user', content: 'Do something' },
- {
- role: 'assistant',
- content: '',
- tool_calls: [
- {
- id: 'call_orphan_1',
- type: 'function',
- function: { name: 'fn_a', arguments: '{}' },
- },
- {
- id: 'call_orphan_2',
- type: 'function',
- function: { name: 'fn_b', arguments: '{}' },
- },
- ],
- },
- { role: 'assistant', content: 'Final answer' },
- ];
-
- const result = await convertOpenAIResponseInputs(messages, { strictToolPairing: true });
-
- // The assistant message with all-orphaned tool_calls should produce no items,
- // NOT fall through to the default builder which would spread tool_calls back.
- expect(result).toEqual([
- { role: 'user', content: 'Do something' },
- { role: 'assistant', content: 'Final answer' },
- ]);
- });
-
- it('should extract reasoning.content into a separate reasoning item', async () => {
- const messages: OpenAIChatMessage[] = [
- { content: 'system prompts', role: 'system' },
- { content: '你好', role: 'user' },
- {
- content: 'hello',
- role: 'assistant',
- reasoning: { content: 'reasoning content', duration: 2706 },
- },
- { content: '杭州天气如何', role: 'user' },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- { content: 'system prompts', role: 'developer' },
- { content: '你好', role: 'user' },
- { summary: [{ text: 'reasoning content', type: 'summary_text' }], type: 'reasoning' },
- { content: 'hello', role: 'assistant' },
- { content: '杭州天气如何', role: 'user' },
- ]);
- });
-
- it('should replay encrypted reasoning from a persisted message for the exact scope', async () => {
- const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
- const messages: OpenAIChatMessage[] = [
- {
- content: 'hello',
- model: 'gpt-5.6-sol',
- provider: 'chatgpt',
- reasoning: {
- content: 'reasoning content',
- signature: serializeScopedSignature(
- 'encrypted-reasoning-content',
- reasoningSignatureScope,
- 'reasoning',
- ),
- },
- role: 'assistant',
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages, { reasoningSignatureScope });
-
- expect(result).toEqual([
- {
- encrypted_content: 'encrypted-reasoning-content',
- summary: [{ text: 'reasoning content', type: 'summary_text' }],
- type: 'reasoning',
- },
- { content: 'hello', role: 'assistant' },
- ]);
- });
-
- it('should preserve encrypted reasoning content without a visible summary', async () => {
- const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
- const messages: OpenAIChatMessage[] = [
- {
- content: 'hello',
- provider: 'chatgpt',
- reasoning: {
- signature: serializeScopedSignature(
- 'encrypted-reasoning-content',
- reasoningSignatureScope,
- 'reasoning',
- ),
- },
- role: 'assistant',
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages, { reasoningSignatureScope });
-
- expect(result).toEqual([
- {
- encrypted_content: 'encrypted-reasoning-content',
- summary: [],
- type: 'reasoning',
- },
- { content: 'hello', role: 'assistant' },
- ]);
- });
-
- it('should keep the visible summary but reject foreign and legacy encrypted reasoning', async () => {
- const sourceScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
- const targetScope: SignatureScope = { fingerprint: 'b'.repeat(32) };
- const baseMessage: OpenAIChatMessage = {
- content: 'hello',
- reasoning: {
- content: 'reasoning content',
- signature: serializeScopedSignature(
- 'encrypted-reasoning-content',
- sourceScope,
- 'reasoning',
- ),
- },
- role: 'assistant',
- };
-
- const foreignResult = await convertOpenAIResponseInputs([baseMessage], {
- reasoningSignatureScope: targetScope,
- });
- const legacyResult = await convertOpenAIResponseInputs(
- [{ ...baseMessage, reasoning: { ...baseMessage.reasoning, signature: 'legacy-signature' } }],
- { reasoningSignatureScope: sourceScope },
- );
-
- const expected = [
- { summary: [{ text: 'reasoning content', type: 'summary_text' }], type: 'reasoning' },
- { content: 'hello', role: 'assistant' },
- ];
- expect(foreignResult).toEqual(expected);
- expect(legacyResult).toEqual(expected);
- });
-
- it('should replay complete reasoning items in original order for the exact scope', async () => {
- const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
- const messages: OpenAIChatMessage[] = [
- {
- content: 'hello',
- provider: 'chatgpt',
- reasoning: {
- content: 'first summary',
- responseItems: [
- {
- encrypted_content: serializeScopedSignature(
- 'encrypted-part-1',
- reasoningSignatureScope,
- 'reasoning',
- ),
- id: 'rs_1',
- status: 'completed',
- summary: [{ text: 'first summary', type: 'summary_text' }],
- type: 'reasoning',
- },
- {
- encrypted_content: serializeScopedSignature(
- 'encrypted-part-2',
- reasoningSignatureScope,
- 'reasoning',
- ),
- id: 'rs_2',
- status: 'completed',
- summary: [],
- type: 'reasoning',
- },
- ],
- },
- role: 'assistant',
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages, { reasoningSignatureScope });
-
- expect(result).toEqual([
- {
- encrypted_content: 'encrypted-part-1',
- id: 'rs_1',
- status: 'completed',
- summary: [{ text: 'first summary', type: 'summary_text' }],
- type: 'reasoning',
- },
- {
- encrypted_content: 'encrypted-part-2',
- id: 'rs_2',
- status: 'completed',
- summary: [],
- type: 'reasoning',
- },
- { content: 'hello', role: 'assistant' },
- ]);
- });
-
- it('should replay hidden reasoning items that have no visible summary', async () => {
- const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
- const messages: OpenAIChatMessage[] = [
- {
- content: 'hello',
- provider: 'chatgpt',
- reasoning: {
- responseItems: [
- {
- encrypted_content: serializeScopedSignature(
- 'hidden-encrypted',
- reasoningSignatureScope,
- 'reasoning',
- ),
- id: 'rs_hidden',
- summary: [],
- type: 'reasoning',
- },
- ],
- },
- role: 'assistant',
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages, { reasoningSignatureScope });
-
- expect(result).toEqual([
- {
- encrypted_content: 'hidden-encrypted',
- id: 'rs_hidden',
- summary: [],
- type: 'reasoning',
- },
- { content: 'hello', role: 'assistant' },
- ]);
- });
-
- it('should fall back to the visible summary when any reasoning item is foreign-scoped', async () => {
- const sourceScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
- const targetScope: SignatureScope = { fingerprint: 'b'.repeat(32) };
- const messages: OpenAIChatMessage[] = [
- {
- content: 'hello',
- provider: 'chatgpt',
- reasoning: {
- content: 'visible summary',
- responseItems: [
- {
- encrypted_content: serializeScopedSignature(
- 'encrypted-part-1',
- sourceScope,
- 'reasoning',
- ),
- id: 'rs_1',
- summary: [{ text: 'visible summary', type: 'summary_text' }],
- type: 'reasoning',
- },
- ],
- signature: serializeScopedSignature('encrypted-part-1', sourceScope, 'reasoning'),
- },
- role: 'assistant',
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages, {
- reasoningSignatureScope: targetScope,
- });
-
- expect(result).toEqual([
- { summary: [{ text: 'visible summary', type: 'summary_text' }], type: 'reasoning' },
- { content: 'hello', role: 'assistant' },
- ]);
- });
-
- it('should strip item ids when replaying summary-only reasoning items', async () => {
- const messages: OpenAIChatMessage[] = [
- {
- content: 'hello',
- provider: 'chatgpt',
- reasoning: {
- content: 'summary only',
- responseItems: [
- {
- id: 'rs_summary_only',
- summary: [{ text: 'summary only', type: 'summary_text' }],
- type: 'reasoning',
- },
- ],
- },
- role: 'assistant',
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- { summary: [{ text: 'summary only', type: 'summary_text' }], type: 'reasoning' },
- { content: 'hello', role: 'assistant' },
- ]);
- });
-
- it('should preserve message order when earlier messages have async content (images)', async () => {
- const messages: OpenAIChatMessage[] = [
- { content: 'system prompts', role: 'system' },
- {
- content: [
- { type: 'text', text: 'describe this image' },
- { type: 'image_url', image_url: { url: 'data:image/jpeg;base64,abc123' } },
- ],
- role: 'user',
- },
- {
- content: 'The image shows a green car.',
- role: 'assistant',
- reasoning: { content: 'analyzing the image', duration: 3000 },
- },
- { content: '1 + 1 = ?', role: 'user' },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- { content: 'system prompts', role: 'developer' },
- {
- content: [
- { type: 'input_text', text: 'describe this image' },
- { type: 'input_image', image_url: 'data:image/jpeg;base64,abc123' },
- ],
- role: 'user',
- },
- { summary: [{ text: 'analyzing the image', type: 'summary_text' }], type: 'reasoning' },
- { content: 'The image shows a green car.', role: 'assistant' },
- { content: '1 + 1 = ?', role: 'user' },
- ]);
- });
-
- it('should handle openai and claude mixed message', async () => {
- // See: https://github.com/lobehub/lobehub/pull/12017
- const messages: OpenAIChatMessage[] = [
- {
- content: 'system prompts',
- role: 'system',
- },
- {
- content: '你是谁',
- role: 'user',
- },
- {
- content: [
- {
- signature: 'E',
- thinking: 'thoughts',
- type: 'thinking',
- },
- {
- text: '我是 Claude',
- type: 'text',
- },
- ],
- provider: 'anthropic',
- role: 'assistant',
- reasoning: {
- content: 'The user is asking',
- duration: 110,
- signature: 'E',
- },
- },
- ];
- const result = await convertOpenAIResponseInputs(messages, { provider: 'chatgpt' });
- expect(result).toEqual([
- { content: 'system prompts', role: 'developer' },
- { content: '你是谁', role: 'user' },
- {
- summary: [{ text: 'The user is asking', type: 'summary_text' }],
- type: 'reasoning',
- },
- {
- content: [{ text: '我是 Claude', type: 'output_text' }],
- role: 'assistant',
- },
- ]);
- });
-
- it('should drop assistant image content for Responses API input', async () => {
- const messages: OpenAIChatMessage[] = [
- {
- content: [
- {
- image_url: { url: 'data:image/jpeg;base64,abc123' },
- type: 'image_url',
- },
- ],
- role: 'assistant',
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([]);
- });
-
- it('should keep assistant text and drop unsupported assistant media for Responses API input', async () => {
- const messages: OpenAIChatMessage[] = [
- {
- content: [
- {
- text: 'Here is the generated image.',
- type: 'text',
- },
- {
- image_url: { url: 'data:image/jpeg;base64,abc123' },
- type: 'image_url',
- },
- {
- video_url: { url: 'data:video/mp4;base64,def456' },
- type: 'video_url',
- },
- ],
- role: 'assistant',
- },
- ];
-
- const result = await convertOpenAIResponseInputs(messages);
-
- expect(result).toEqual([
- {
- content: [{ text: 'Here is the generated image.', type: 'output_text' }],
- role: 'assistant',
- },
- ]);
- });
-
- it('should pass forceVideoBase64 to convertMessageContent in video_url branch', async () => {
- process.env.LLM_VISION_VIDEO_USE_BASE64 = undefined;
-
- const messages: OpenAIChatMessage[] = [
- {
- role: 'user',
- content: [
- { type: 'text', text: 'Here is a video' },
- {
- type: 'video_url',
- video_url: {
- url: 'https://example.com/video.mp4',
- },
- },
- ],
- },
- ];
-
- vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
- vi.mocked(videoUrlToBase64).mockResolvedValue({
- base64: 'forcedBase64',
- mimeType: 'video/mp4',
- });
-
- const result = await convertOpenAIResponseInputs(messages, { forceVideoBase64: true });
-
- expect(result).toEqual([
- {
- role: 'user',
- content: [
- { type: 'input_text', text: 'Here is a video' },
- {
- type: 'input_video',
- video_url: 'data:video/mp4;base64,forcedBase64',
- },
- ],
- },
- ]);
-
- expect(videoUrlToBase64).toHaveBeenCalledWith('https://example.com/video.mp4');
- });
-
- it('should pass forceImageBase64 to convertMessageContent in image_url branch', async () => {
- process.env.LLM_VISION_IMAGE_USE_BASE64 = undefined;
-
- const messages: OpenAIChatMessage[] = [
- {
- role: 'user',
- content: [
- { type: 'text', text: 'Here is an image' },
- {
- type: 'image_url',
- image_url: {
- url: 'https://example.com/image.jpg',
- },
- },
- ],
- },
- ];
-
- vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
- vi.mocked(imageUrlToBase64).mockResolvedValue({
- base64: 'forcedBase64',
- mimeType: 'image/jpeg',
- });
-
- const result = await convertOpenAIResponseInputs(messages, { forceImageBase64: true });
-
- expect(result).toEqual([
- {
- role: 'user',
- content: [
- { type: 'input_text', text: 'Here is an image' },
- {
- type: 'input_image',
- image_url: 'data:image/jpeg;base64,forcedBase64',
- },
- ],
- },
- ]);
-
- expect(imageUrlToBase64).toHaveBeenCalledWith('https://example.com/image.jpg');
- });
-});
-
describe('convertImageUrlToFile', () => {
beforeEach(() => {
vi.resetAllMocks();
diff --git a/packages/model-runtime/src/core/contextBuilders/openai.ts b/packages/model-runtime/src/core/contextBuilders/openai.ts
index 6abdb039603..7e8d8cdded0 100644
--- a/packages/model-runtime/src/core/contextBuilders/openai.ts
+++ b/packages/model-runtime/src/core/contextBuilders/openai.ts
@@ -1,20 +1,14 @@
-import { imageUrlToBase64 } from '../../utils/imageToBase64';
-import { videoUrlToBase64 } from '../../utils/videoToBase64';
import { Buffer } from 'buffer.js';
import type OpenAI from 'openai';
import { toFile } from 'openai';
import { disableStreamModels, systemToUserModels } from '../../providers/openai/modelId';
-import type {
- ChatStreamPayload,
- MessageToolCall,
- OpenAIChatMessage,
- UserMessageContentPart,
-} from '../../types';
-import { isDeepSeekThinkingEligibleModel } from '../../utils/modelParse';
+import type { ChatStreamPayload, OpenAIChatMessage, UserMessageContentPart } from '../../types';
+import { imageUrlToBase64 } from '../../utils/imageToBase64';
import { fetchReferenceImageBytes } from '../../utils/referenceImageCache';
-import { resolveScopedSignature, type SignatureScope } from '../../utils/signatureScope';
+import { type SignatureScope } from '../../utils/signatureScope';
import { parseDataUri } from '../../utils/uriParser';
+import { videoUrlToBase64 } from '../../utils/videoToBase64';
export type ExtendedChatCompletionContentPart = {
type: 'video_url';
@@ -23,7 +17,7 @@ export type ExtendedChatCompletionContentPart = {
};
};
-type ConvertMessageContentOptions = {
+export type ConvertMessageContentOptions = {
forceImageBase64?: boolean;
forceVideoBase64?: boolean;
model?: string;
@@ -34,27 +28,10 @@ type ConvertMessageContentOptions = {
thoughtSignatureScope?: SignatureScope;
};
-/**
- * Model families whose thinking mode requires the historical `reasoning_content`
- * to be echoed back when the assistant turn also carries `tool_calls`. Upstream
- * rejects the request outright otherwise:
- *
- * > If thinking mode and tool_calls, `reasoning_content` must be passed back to the API.
- *
- * Matched on the model id rather than the provider because these models are
- * mostly reached through OpenAI-compatible aggregators and user-configured
- * proxies, where the provider key says nothing about the underlying family.
- */
-const REASONING_PASSBACK_MODEL_KEYWORDS = ['deepseek', 'glm', 'kimi'] as const;
-
-const requiresReasoningPassback = (model: string | undefined) =>
- typeof model === 'string' &&
- REASONING_PASSBACK_MODEL_KEYWORDS.some((keyword) => model.toLowerCase().includes(keyword));
-
-type OpenAICompatibleContentPart =
+export type OpenAICompatibleContentPart =
ExtendedChatCompletionContentPart | OpenAI.ChatCompletionContentPart | UserMessageContentPart;
-type ConvertibleMessageContentPart =
+export type ConvertibleMessageContentPart =
| ExtendedChatCompletionContentPart
| OpenAI.ChatCompletionContentPart
| Extract<UserMessageContentPart, { type: 'audio_url' }>;
@@ -117,7 +94,7 @@ const convertAudioContent = async (
throw new TypeError(`Invalid audio URL: ${content.audio_url.url}`);
};
-const isInternalThinkingContentPart = (
+export const isInternalThinkingContentPart = (
content: OpenAICompatibleContentPart,
): content is Extract<UserMessageContentPart, { type: 'thinking' }> => content.type === 'thinking';
@@ -134,7 +111,7 @@ const isEmptyTextContentPart = (content: OpenAICompatibleContentPart) =>
* `content: null` is accepted. When nothing remains, use `null` for tool-call
* turns and `''` otherwise.
*/
-const filterOutgoingContentParts = (msg: any, parts: OpenAICompatibleContentPart[]) => {
+export const filterOutgoingContentParts = (msg: any, parts: OpenAICompatibleContentPart[]) => {
const filtered = parts.filter(
(c) =>
!isInternalThinkingContentPart(c) && (msg.role !== 'assistant' || !isEmptyTextContentPart(c)),
@@ -191,444 +168,6 @@ export const convertMessageContent = async (
return content;
};
-/**
- * OpenAI tool messages only accept text content — the Chat Completions API
- * rejects `image_url` parts inside a `role: 'tool'` message. When a tool
- * result carries images (e.g. builtin `readFile` on an image file), flatten
- * the tool message to text and re-attach the images as a `user` message
- * placed AFTER the contiguous tool-result batch: every tool message must
- * directly follow the assistant message holding its `tool_calls`, so nothing
- * may be interleaved inside the batch.
- */
-const extractToolMessageImages = (
- converted: OpenAI.ChatCompletionMessageParam[],
-): OpenAI.ChatCompletionMessageParam[] => {
- const output: OpenAI.ChatCompletionMessageParam[] = [];
- let pendingToolImages: { parts: OpenAI.ChatCompletionContentPart[]; toolCallId?: string }[] = [];
-
- const flushToolImages = () => {
- if (pendingToolImages.length === 0) return;
-
- const content = pendingToolImages.flatMap((pending) => [
- { text: `Image output of tool call ${pending.toolCallId}:`, type: 'text' as const },
- ...pending.parts,
- ]);
- output.push({ content, role: 'user' });
- pendingToolImages = [];
- };
-
- for (const message of converted) {
- if (message.role !== 'tool') flushToolImages();
-
- if (message.role === 'tool' && Array.isArray(message.content)) {
- const parts = message.content as any[];
- const imageParts = parts.filter((c) => c?.type === 'image_url' || c?.type === 'video_url');
- const text = parts
- .filter((c) => c?.type === 'text' && typeof c.text === 'string')
- .map((c) => c.text)
- .join('\n\n');
-
- if (imageParts.length > 0) {
- pendingToolImages.push({ parts: imageParts, toolCallId: message.tool_call_id });
- }
-
- output.push({
- ...message,
- content: text || (imageParts.length > 0 ? '[Image output attached below]' : ''),
- });
- continue;
- }
-
- output.push(message);
- }
-
- flushToolImages();
-
- return output;
-};
-
-export const convertOpenAIMessages = async (
- messages: OpenAI.ChatCompletionMessageParam[],
- options?: ConvertMessageContentOptions,
-) => {
- const converted = (await Promise.all(
- messages.map(async (message) => {
- const msg = message as any;
-
- // Explicitly map only valid ChatCompletionMessageParam fields
- // Exclude reasoning and reasoning_content fields as they should not be sent in requests
- const parts =
- typeof message.content === 'string'
- ? message.content
- : filterOutgoingContentParts(
- msg,
- (message.content || []) as OpenAICompatibleContentPart[],
- );
-
- const result: any = {
- content: Array.isArray(parts)
- ? await Promise.all(
- parts.map((c) => convertMessageContent(c as ConvertibleMessageContentPart, options)),
- )
- : parts,
- role: msg.role,
- };
-
- // Add optional fields if they exist
- if (msg.name !== undefined) result.name = msg.name;
- if (msg.tool_calls !== undefined) {
- result.tool_calls = msg.tool_calls.map((toolCall: MessageToolCall) => {
- if (!toolCall.thoughtSignature) return toolCall;
-
- const { thoughtSignature, ...rest } = toolCall;
- const resolvedSignature = resolveScopedSignature(
- thoughtSignature,
- options?.thoughtSignatureScope,
- 'thought_signature',
- );
-
- return resolvedSignature ? { ...rest, thoughtSignature: resolvedSignature } : rest;
- });
- }
- if (msg.tool_call_id !== undefined) result.tool_call_id = msg.tool_call_id;
- if (msg.function_call !== undefined) result.function_call = msg.function_call;
-
- // it's compatible for DeepSeek & Moonshot
- if (msg.reasoning_content !== undefined) result.reasoning_content = msg.reasoning_content;
- // MiniMax uses reasoning_details for historical thinking, so forward it unchanged
- if (msg.reasoning_details !== undefined) result.reasoning_details = msg.reasoning_details;
-
- // For passback-requiring families routed via any OpenAI-compatible runtime
- // (including custom user providers that bypass a dedicated handlePayload),
- // derive reasoning_content from the structured reasoning field on assistant
- // messages.
- if (msg.role === 'assistant' && requiresReasoningPassback(options?.model)) {
- if (result.reasoning_content === undefined && typeof msg.reasoning?.content === 'string') {
- result.reasoning_content = msg.reasoning.content;
- }
- // The empty placeholder stays DeepSeek-scoped. Echoing reasoning we
- // actually have is what upstream asks for; fabricating an empty thinking
- // block for a family we have not validated is a different, riskier change.
- if (
- result.reasoning_content === undefined &&
- isDeepSeekThinkingEligibleModel(options?.model)
- ) {
- result.reasoning_content = '';
- }
- }
-
- return result;
- }),
- )) as OpenAI.ChatCompletionMessageParam[];
-
- return extractToolMessageImages(converted);
-};
-
-export const convertOpenAIResponseInputs = async (
- messages: OpenAIChatMessage[],
- options?: ConvertMessageContentOptions,
-) => {
- const strictToolPairing = options?.strictToolPairing === true;
- // OpenAI Responses API rejects inputs that keep a function_call without its matching
- // function_call_output. Example from production:
- // "No tool output found for function call call_w5odMFjtXEYBBVyBUAQNMOh5."
- const validToolCallIds = new Set<string>();
- const pairedToolOutputIds = new Set<string>();
- const customToolCallIds = new Set<string>();
-
- for (const message of messages) {
- if (message.role === 'assistant' && message.tool_calls?.length) {
- message.tool_calls.forEach((tool) => {
- if (tool.id) validToolCallIds.add(tool.id);
- if (tool.id && tool.type === 'custom') customToolCallIds.add(tool.id);
- });
- }
- }
-
- for (const message of messages) {
- if (
- message.role === 'tool' &&
- message.tool_call_id &&
- validToolCallIds.has(message.tool_call_id)
- ) {
- pairedToolOutputIds.add(message.tool_call_id);
- }
- }
-
- const inputGroups = await Promise.all(
- messages.map(async (message) => {
- const items: OpenAI.Responses.ResponseInputItem[] = [];
- const reasoning = message.reasoning;
- if (message.responsesTools) {
- return [
- {
- type: 'additional_tools',
- role: 'developer',
- tools: message.responsesTools,
- } satisfies OpenAI.Responses.ResponseInputItem,
- ];
- }
-
- /**
- * Resolve persisted Responses reasoning items for stateless replay. Encrypted
- * items must all match the current signature scope — a single foreign-scope item
- * would make OpenAI reject the whole request, so fail closed to the legacy path.
- */
- const resolveResponseItems = (): OpenAI.Responses.ResponseReasoningItem[] | undefined => {
- const responseItems = reasoning?.responseItems;
- if (!responseItems?.length) return undefined;
-
- const resolved: OpenAI.Responses.ResponseReasoningItem[] = [];
- for (const item of responseItems) {
- if (item.encrypted_content) {
- const encryptedContent = resolveScopedSignature(
- item.encrypted_content,
- options?.reasoningSignatureScope,
- 'reasoning',
- );
- if (!encryptedContent) return undefined;
-
- resolved.push({
- ...item,
- encrypted_content: encryptedContent,
- } as OpenAI.Responses.ResponseReasoningItem);
- } else {
- /**
- * Without encrypted content the server cannot look the item up by id in a
- * stateless request, so drop the id and replay the visible summary only.
- */
- const { id: _id, ...rest } = item;
- resolved.push(rest as unknown as OpenAI.Responses.ResponseReasoningItem);
- }
- }
-
- return resolved;
- };
-
- const replayableResponseItems = resolveResponseItems();
-
- if (replayableResponseItems) {
- // Replay complete reasoning items verbatim and in original stream order.
- items.push(...replayableResponseItems);
- } else {
- const encryptedContent = resolveScopedSignature(
- reasoning?.signature,
- options?.reasoningSignatureScope,
- 'reasoning',
- );
-
- // Preserve encrypted reasoning state for stateless Responses API requests.
- if (reasoning?.content || encryptedContent) {
- items.push({
- encrypted_content: encryptedContent,
- summary: reasoning?.content ? [{ text: reasoning.content, type: 'summary_text' }] : [],
- type: 'reasoning',
- } as OpenAI.Responses.ResponseReasoningItem);
- }
- }
-
- // if message is assistant messages with tool calls , transform it to function type item
- if (message.role === 'assistant' && message.tool_calls && message.tool_calls?.length > 0) {
- const toolCalls = strictToolPairing
- ? message.tool_calls.filter((tool) => !!tool.id && pairedToolOutputIds.has(tool.id))
- : message.tool_calls;
-
- toolCalls.forEach((tool) => {
- const identity = {
- call_id: tool.id,
- name: tool.function.name,
- ...(tool.namespace ? { namespace: tool.namespace } : {}),
- };
- items.push(
- tool.type === 'custom'
- ? {
- ...identity,
- input: tool.function.arguments,
- type: 'custom_tool_call',
- }
- : {
- ...identity,
- arguments: strictToolPairing ? tool.function.arguments : tool.function.name,
- type: 'function_call',
- },
- );
- });
-
- return items;
- }
-
- if (message.role === 'tool') {
- if (
- strictToolPairing &&
- (!message.tool_call_id || !pairedToolOutputIds.has(message.tool_call_id))
- )
- return items;
-
- if (message.responsesOutput !== undefined) {
- items.push({
- call_id: message.tool_call_id!,
- output: message.responsesOutput,
- type: customToolCallIds.has(message.tool_call_id!)
- ? 'custom_tool_call_output'
- : 'function_call_output',
- });
- return items;
- }
-
- // `function_call_output.output` is text-only. When the tool result
- // carries images (e.g. builtin `readFile` on an image file), keep the
- // output textual and re-attach the images as a follow-up user message
- // item — Responses pairs outputs to calls by `call_id`, so a message
- // item between outputs is fine.
- let outputText = message.content as string;
- let imageParts: UserMessageContentPart[] = [];
-
- if (Array.isArray(message.content)) {
- const parts = message.content as any[];
- imageParts = parts.filter((c) => c?.type === 'image_url');
- outputText =
- parts
- .filter((c) => c?.type === 'text' && typeof c.text === 'string')
- .map((c) => c.text)
- .join('\n\n') || (imageParts.length > 0 ? '[Image output attached below]' : '');
- }
-
- items.push({
- call_id: message.tool_call_id,
- output: outputText,
- type: customToolCallIds.has(message.tool_call_id!)
- ? 'custom_tool_call_output'
- : 'function_call_output',
- } as OpenAI.Responses.ResponseInputItem);
-
- if (imageParts.length > 0) {
- const imageContent = (
- await Promise.all(
- imageParts.map(async (c) => {
- const image = await convertMessageContent(
- c as OpenAI.ChatCompletionContentPart,
- options,
- );
- const imageUrl = (image as OpenAI.ChatCompletionContentPartImage).image_url;
- if (!imageUrl?.url) return undefined;
- return {
- image_url: imageUrl.url,
- type: 'input_image' as const,
- ...(imageUrl.detail && { detail: imageUrl.detail }),
- };
- }),
- )
- ).filter((c) => !!c);
-
- if (imageContent.length > 0) {
- items.push({
- content: [
- {
- text: `Image output of tool call ${message.tool_call_id}:`,
- type: 'input_text' as const,
- },
- ...imageContent,
- ],
- role: 'user',
- type: 'message',
- } as OpenAI.Responses.ResponseInputItem);
- }
- }
-
- return items;
- }
-
- if (message.role === 'system') {
- items.push({ ...message, role: 'developer' } as OpenAI.Responses.ResponseInputItem);
- return items;
- }
-
- // default item
- // also need handle image
-
- const processedContent =
- typeof message.content === 'string'
- ? message.content
- : await Promise.all(
- (message.content || []).map(async (c) => {
- if (isInternalThinkingContentPart(c as OpenAICompatibleContentPart)) {
- return undefined;
- }
-
- if (c.type === 'text') {
- // if assistant message, set type to output_text
- // https://platform.openai.com/docs/guides/text
- if (message.role === 'assistant') {
- return { ...c, type: 'output_text' };
- }
- return { ...c, type: 'input_text' };
- }
-
- // Responses API only accepts output_text/refusal inside assistant history.
- // Multimodal parts are valid as model inputs, not as previous assistant outputs.
- if (message.role === 'assistant') {
- return undefined;
- }
-
- if (c.type === 'video_url') {
- const video = await convertMessageContent(c, options);
- if (!('video_url' in video) || !video.video_url?.url) {
- return undefined;
- }
- return {
- video_url: video.video_url.url,
- type: 'input_video',
- };
- }
- if (c.type === 'audio_url') {
- throw new TypeError('OpenAI raw audio input requires the Chat Completions API');
- }
- const image = await convertMessageContent(
- c as OpenAI.ChatCompletionContentPart,
- options,
- );
- const imageUrl = (image as OpenAI.ChatCompletionContentPartImage).image_url;
- if (!imageUrl?.url) {
- return undefined;
- }
- // Forward the requested detail level so callers that need full resolution
- // (e.g. inspecting small annotations on screenshots) are not downgraded to auto.
- return {
- image_url: imageUrl.url,
- type: 'input_image',
- ...(imageUrl.detail && { detail: imageUrl.detail }),
- };
- }),
- );
-
- const content =
- typeof processedContent === 'string'
- ? processedContent
- : processedContent.filter((m) => m !== undefined);
-
- if (message.role === 'assistant' && Array.isArray(content) && content.length === 0) {
- return items;
- }
-
- const {
- model: _model,
- provider: _provider,
- reasoning: _reasoning,
- ...responseMessage
- } = message;
- const item = {
- ...responseMessage,
- content,
- } as OpenAI.Responses.ResponseInputItem;
-
- items.push(item);
- return items;
- }),
- );
-
- return inputGroups.flat();
-};
-
export const pruneReasoningPayload = (payload: ChatStreamPayload) => {
const shouldStream = !disableStreamModels.has(payload.model);
const { stream_options, logprobs, top_logprobs, ...cleanedPayload } = payload as any;
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/apiMode.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/apiMode.ts
new file mode 100644
index 00000000000..de6d00de20b
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/apiMode.ts
@@ -0,0 +1,127 @@
+import debug from 'debug';
+
+import { isResponsesAPIModel } from '../../providers/openai/modelId';
+
+export interface ShouldUseResponsesAPIParams {
+ /** Context for logging (e.g., 'chat', 'generateObject', 'tool calling') */
+ context?: string;
+ /** Factory/instance level useResponse flag */
+ flagUseResponse?: boolean;
+ /** Factory/instance level model patterns for Responses API */
+ flagUseResponseModels?: Array<string | RegExp>;
+ /** The model ID to check */
+ model?: string;
+ /** Explicit responseApi flag */
+ responseApi?: boolean;
+ /** User-specified API mode (highest priority) */
+ userApiMode?: string;
+}
+
+/**
+ * Determine if should use Responses API based on various configuration options
+ * @returns true if should use Responses API, false otherwise
+ */
+export const shouldUseResponsesAPI = (
+ params: ShouldUseResponsesAPIParams,
+ logPrefix: string,
+): boolean => {
+ const {
+ model,
+ userApiMode,
+ responseApi,
+ flagUseResponse,
+ flagUseResponseModels,
+ context = 'operation',
+ } = params;
+
+ const log = debug(`${logPrefix}:shouldUseResponsesAPI`);
+
+ // Priority 0: Check built-in Responses API model rules FIRST (highest priority)
+ // These models MUST use Responses API regardless of user settings.
+ if (model && isResponsesAPIModel(model)) {
+ log('using Responses API: model %s matches built-in Responses API model rules', model);
+ return true;
+ }
+
+ // Priority 1: userApiMode is explicitly set to 'chatCompletion' (user disabled the switch)
+ if (userApiMode === 'chatCompletion') {
+ log('using Chat Completions API: userApiMode=%s', userApiMode);
+ return false;
+ }
+
+ // Priority 2: When user enables the switch (userApiMode === 'responses')
+ // Check if useResponseModels is configured - if so, only matching models use Responses API
+ // If useResponseModels is not configured, all models use Responses API
+ if (userApiMode === 'responses') {
+ if (model && flagUseResponseModels?.length) {
+ const matches = flagUseResponseModels.some((m: string | RegExp) =>
+ typeof m === 'string' ? model.includes(m) : (m as RegExp).test(model),
+ );
+ if (matches) {
+ log(
+ 'using Responses API: userApiMode=responses and model %s matches useResponseModels',
+ model,
+ );
+ return true;
+ }
+ log(
+ 'using Chat Completions API: userApiMode=responses but model %s does not match useResponseModels',
+ model,
+ );
+ return false;
+ }
+ // No useResponseModels configured, use Responses API for all models
+ log('using Responses API: userApiMode=responses (no useResponseModels filter)');
+ return true;
+ }
+
+ // Priority 3: Explicit responseApi flag
+ if (responseApi) {
+ log('using Responses API: explicit responseApi flag for %s', context);
+ return true;
+ }
+
+ // Priority 4: Factory/instance level useResponse flag
+ if (flagUseResponse) {
+ log('using Responses API: flagUseResponse=true for %s', context);
+ return true;
+ }
+
+ // Priority 5: Check if model matches useResponseModels patterns (without user switch)
+ if (model && flagUseResponseModels?.length) {
+ const matches = flagUseResponseModels.some((m: string | RegExp) =>
+ typeof m === 'string' ? model.includes(m) : (m as RegExp).test(model),
+ );
+ if (matches) {
+ log('using Responses API: model %s matches useResponseModels config', model);
+ return true;
+ }
+ }
+
+ log('using Chat Completions API for %s', context);
+ return false;
+};
+
+export const resolvePromptCacheKey = (
+ model: string | undefined,
+ user: string | undefined,
+ promptCacheKeyModels: Array<string | RegExp> | undefined,
+) => {
+ if (!user) return;
+
+ // Keep the default key at {userId}:{model}; {agentId/topicId} can be added later if a narrower cache bucket is needed.
+ if (model?.startsWith('gpt-') || /^o\d/.test(model || '') || model === 'chat-latest') {
+ return `lobe:${user}:${model}`;
+ }
+
+ const matchesProviderPromptCacheModel = promptCacheKeyModels?.some((item) => {
+ if (!model) return false;
+ if (typeof item === 'string') return model.includes(item);
+
+ item.lastIndex = 0;
+ return item.test(model);
+ });
+ if (matchesProviderPromptCacheModel) {
+ return `lobe:${user}:${model}`;
+ }
+};
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/context.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/context.ts
new file mode 100644
index 00000000000..3a7ec8512ff
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/context.ts
@@ -0,0 +1,41 @@
+import type OpenAI from 'openai';
+
+import type { ChatCompletionErrorPayload } from '../../types';
+import type { SignatureScope, SignatureScopeKind } from '../../utils/signatureScope';
+import type { ShouldUseResponsesAPIParams } from './apiMode';
+import type { ConstructorOptions, ResponseCreateParamsWithPromptCacheKey } from './factoryOptions';
+
+/**
+ * What the protocol modules read from a factory-built runtime. The runtime builds it per
+ * call, so its own members stay private and subclasses keep overriding `handleError`.
+ */
+export interface OpenAICompatibleRuntimeContext {
+ _options: ConstructorOptions;
+ baseURL: string;
+ client: OpenAI;
+ getMappedModelId: (model: string) => string;
+ getSignatureScope: (
+ model: string,
+ kind: SignatureScopeKind,
+ protocol: 'chat_completions' | 'responses',
+ ) => Promise<SignatureScope | undefined>;
+ handleError: (error: unknown) => ChatCompletionErrorPayload;
+ id: string;
+ /** The runtime itself, passed through to `customClient.createChatCompletionStream`. */
+ instance: unknown;
+ logPrefix: string;
+ prepareResponsesRequest: (
+ payload: ResponseCreateParamsWithPromptCacheKey,
+ logicalModel: string,
+ ) => { headers?: Record<string, string>; payload: ResponseCreateParamsWithPromptCacheKey };
+ resolvePromptCacheKeyParams: (
+ model?: string,
+ user?: string,
+ existingPromptCacheKey?: string,
+ ) => { prompt_cache_key?: string };
+ shouldUseResponsesAPI: (params: ShouldUseResponsesAPIParams) => boolean;
+ withMappedRequestModel: <TPayload extends { model?: string }>(
+ requestPayload: TPayload,
+ logicalModel: string,
+ ) => TPayload;
+}
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/errors.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/errors.ts
new file mode 100644
index 00000000000..633c12b042a
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/errors.ts
@@ -0,0 +1,191 @@
+import debug from 'debug';
+
+import { ErrorClassifier, refineErrorCode } from '../../errors';
+import type { ChatCompletionErrorPayload } from '../../types';
+import { AgentRuntimeErrorType } from '../../types/error';
+import { AgentRuntimeError } from '../../utils/createError';
+import { desensitizeUrl } from '../../utils/desensitizeUrl';
+import { handleOpenAIError } from '../../utils/handleOpenAIError';
+import { ContextExceededPreFlightError } from '../../utils/resolveSafeMaxTokens';
+import type { OpenAICompatibleRuntimeContext } from './context';
+import type { OpenAICompatibleFactoryOptions } from './factoryOptions';
+
+export const resolveErrorTypes = ({ errorType }: OpenAICompatibleFactoryOptions) => ({
+ bizError: errorType?.bizError || AgentRuntimeErrorType.ProviderBizError,
+ invalidAPIKey: errorType?.invalidAPIKey || AgentRuntimeErrorType.InvalidProviderAPIKey,
+});
+
+export const mapOpenAICompatibleError = (
+ runtime: OpenAICompatibleRuntimeContext,
+ factory: OpenAICompatibleFactoryOptions,
+ error: any,
+): ChatCompletionErrorPayload => {
+ const errorType = resolveErrorTypes(factory);
+ const log = debug(`${runtime.logPrefix}:error`);
+ log('handling error: %O', error);
+
+ let desensitizedEndpoint = runtime.baseURL;
+
+ // refs: https://github.com/lobehub/lobe-chat/issues/842
+ if (runtime.baseURL !== factory.baseURL) {
+ desensitizedEndpoint = desensitizeUrl(runtime.baseURL);
+ }
+
+ // Pre-flight context-window failures get a structured payload so the
+ // UI can offer fork / switch-model affordances instead of surfacing a
+ // raw provider 400. See .
+ if (error instanceof ContextExceededPreFlightError) {
+ log('pre-flight context exceeded: %s', error.message);
+ return AgentRuntimeError.chat({
+ endpoint: desensitizedEndpoint,
+ error: error.toPayload(),
+ errorType: AgentRuntimeErrorType.ExceededContextWindow,
+ message: error.message,
+ provider: runtime.id,
+ });
+ }
+
+ if (factory.chatCompletion?.handleError) {
+ log('using custom error handler');
+ const errorResult = factory.chatCompletion.handleError(error, runtime._options);
+
+ if (errorResult)
+ return AgentRuntimeError.chat({
+ ...errorResult,
+ provider: runtime.id,
+ } as ChatCompletionErrorPayload);
+ }
+
+ if ('status' in (error as any)) {
+ const status = (error as Response).status;
+ log('HTTP error with status: %d', status);
+
+ switch (status) {
+ case 401: {
+ log('invalid API key error');
+ return AgentRuntimeError.chat({
+ endpoint: desensitizedEndpoint,
+ error: error as any,
+ errorType: errorType.invalidAPIKey,
+ provider: runtime.id,
+ });
+ }
+
+ case 413: {
+ return AgentRuntimeError.chat({
+ endpoint: desensitizedEndpoint,
+ error: error as any,
+ errorType: AgentRuntimeErrorType.RequestBodyTooLarge,
+ provider: runtime.id,
+ });
+ }
+
+ default: {
+ break;
+ }
+ }
+ }
+
+ const { errorResult, RuntimeError, message } = handleOpenAIError(error);
+
+ log('error code: %s, message: %s', errorResult.code, errorResult.message);
+
+ switch (errorResult.code) {
+ case 'insufficient_quota': {
+ log('insufficient quota error');
+ return AgentRuntimeError.chat({
+ endpoint: desensitizedEndpoint,
+ error: errorResult,
+ errorType: AgentRuntimeErrorType.InsufficientQuota,
+ message,
+ provider: runtime.id,
+ });
+ }
+
+ case 'model_not_found': {
+ log('model not found error');
+ return AgentRuntimeError.chat({
+ endpoint: desensitizedEndpoint,
+ error: errorResult,
+ errorType: AgentRuntimeErrorType.ModelNotFound,
+ message,
+ provider: runtime.id,
+ });
+ }
+
+ // content too long
+ case 'context_length_exceeded':
+ case 'string_above_max_length': {
+ log('context length exceeded error');
+ return AgentRuntimeError.chat({
+ endpoint: desensitizedEndpoint,
+ error: errorResult,
+ errorType: AgentRuntimeErrorType.ExceededContextWindow,
+ message,
+ provider: runtime.id,
+ });
+ }
+ }
+
+ const errorMsg = errorResult.error?.message || errorResult.message;
+
+ if (ErrorClassifier.isAccountDeactivated(errorMsg)) {
+ log('account deactivated error detected from message');
+ return AgentRuntimeError.chat({
+ endpoint: desensitizedEndpoint,
+ error: errorResult,
+ errorType: AgentRuntimeErrorType.AccountDeactivated,
+ message,
+ provider: runtime.id,
+ });
+ }
+
+ if (ErrorClassifier.isInsufficientQuota(errorMsg)) {
+ log('insufficient quota error detected from message');
+ return AgentRuntimeError.chat({
+ endpoint: desensitizedEndpoint,
+ error: errorResult,
+ errorType: AgentRuntimeErrorType.InsufficientQuota,
+ message,
+ provider: runtime.id,
+ });
+ }
+
+ if (ErrorClassifier.isExceededContextWindow(errorMsg)) {
+ log('context length exceeded detected from message');
+ return AgentRuntimeError.chat({
+ endpoint: desensitizedEndpoint,
+ error: errorResult,
+ errorType: AgentRuntimeErrorType.ExceededContextWindow,
+ message,
+ provider: runtime.id,
+ });
+ }
+
+ if (ErrorClassifier.isRateLimitExceeded(errorMsg)) {
+ log('quota limit reached detected from message');
+ return AgentRuntimeError.chat({
+ endpoint: desensitizedEndpoint,
+ error: errorResult,
+ errorType: AgentRuntimeErrorType.RateLimitExceeded,
+ message,
+ provider: runtime.id,
+ });
+ }
+
+ const fallbackErrorType = RuntimeError || errorType.bizError;
+ const refinedErrorType = refineErrorCode({
+ errorType: String(fallbackErrorType),
+ message: typeof errorMsg === 'string' ? errorMsg : undefined,
+ provider: runtime.id,
+ });
+
+ log('returning generic error');
+ return AgentRuntimeError.chat({
+ endpoint: desensitizedEndpoint,
+ error: errorResult,
+ errorType: refinedErrorType ?? fallbackErrorType,
+ message,
+ provider: runtime.id,
+ });
+};
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/generateObject.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/generateObject.ts
new file mode 100644
index 00000000000..d1aa97c0e3e
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/generateObject.ts
@@ -0,0 +1,146 @@
+import debug from 'debug';
+
+import type { GenerateObjectOptions, GenerateObjectPayload } from '../../types';
+import { AgentRuntimeErrorType } from '../../types/error';
+import { getModelPricing } from '../../utils/getModelPricing';
+import { detectModelProvider } from '../../utils/modelParse';
+import {
+ generateObjectViaJsonSchema,
+ generateObjectViaToolCalling,
+ generateToolCallsViaChatCompletions,
+} from '../protocols/openaiChatCompletions/generateObject';
+import {
+ generateObjectViaResponses,
+ generateToolCallsViaResponses,
+} from '../protocols/openaiResponses/generateObject';
+import type { OpenAICompatibleRuntimeContext } from './context';
+import { resolveErrorTypes } from './errors';
+import type { OpenAICompatibleFactoryOptions } from './factoryOptions';
+import { StructuredOutputError } from './structuredOutput';
+
+type Runtime = OpenAICompatibleRuntimeContext;
+type Factory = OpenAICompatibleFactoryOptions;
+
+/** Factory-level Responses API routing control (supports instance override). */
+const shouldUseResponsesForGenerateObject = (
+ runtime: Runtime,
+ factory: Factory,
+ { model, responseApi }: GenerateObjectPayload,
+ context: string,
+) => {
+ const instanceGenerateObject = ((runtime._options as any).generateObject || {}) as {
+ useResponse?: boolean;
+ useResponseModels?: Array<string | RegExp>;
+ };
+ const flagUseResponse =
+ instanceGenerateObject.useResponse ??
+ (factory.generateObject ? factory.generateObject.useResponse : undefined);
+ const flagUseResponseModels =
+ instanceGenerateObject.useResponseModels ?? factory.generateObject?.useResponseModels;
+
+ return runtime.shouldUseResponsesAPI({
+ context,
+ flagUseResponse,
+ flagUseResponseModels,
+ model,
+ responseApi,
+ });
+};
+
+export const generateObject = async (
+ runtime: Runtime,
+ factory: Factory,
+ payload: GenerateObjectPayload,
+ options?: GenerateObjectOptions,
+) => {
+ const ErrorType = resolveErrorTypes(factory);
+ try {
+ const { schema, model, tools } = payload;
+
+ const log = debug(`${runtime.logPrefix}:generateObject`);
+ log(
+ 'generateObject called with model: %s, hasTools: %s, hasSchema: %s',
+ model,
+ !!tools,
+ !!schema,
+ );
+
+ const pricing = await getModelPricing(model, runtime.id, options?.pricingContext);
+ const usagePayload = { model, pricing, provider: runtime.id };
+
+ if (tools) {
+ log('using tools-based generation');
+ log('generateObjectWithTools called with model: %s, toolsCount: %d', model, tools.length);
+
+ return shouldUseResponsesForGenerateObject(runtime, factory, payload, 'tool calling')
+ ? await generateToolCallsViaResponses(runtime, factory, payload, options, usagePayload, log)
+ : await generateToolCallsViaChatCompletions(
+ runtime,
+ factory,
+ payload,
+ options,
+ usagePayload,
+ log,
+ );
+ }
+
+ if (!schema) throw new Error('tools or schema is required');
+
+ // Use tool calling fallback if configured, or when the model is known to
+ // reject `response_format: { type: 'json_schema' }`. The DeepSeek API only
+ // supports `json_object` and replies `400 This response_format type is
+ // unavailable now` to json_schema requests, so DeepSeek-family models served
+ // through generic OpenAI-compatible providers (aggregator gateways, custom
+ // endpoints) must simulate structured output via forced tool calling.
+ if (factory.generateObject?.useToolsCalling || detectModelProvider(model) === 'deepseek') {
+ log('using tool calling fallback for structured output');
+ return await generateObjectViaToolCalling(runtime, factory, payload, options, usagePayload);
+ }
+
+ const shouldUseResponses = shouldUseResponsesForGenerateObject(
+ runtime,
+ factory,
+ payload,
+ 'generateObject',
+ );
+
+ // Apply schema transformation if configured
+ const processedSchema = factory.generateObject?.handleSchema
+ ? { ...schema, schema: factory.generateObject.handleSchema(schema.schema) }
+ : schema;
+
+ return shouldUseResponses
+ ? await generateObjectViaResponses(
+ runtime,
+ factory,
+ payload,
+ processedSchema,
+ options,
+ usagePayload,
+ log,
+ )
+ : await generateObjectViaJsonSchema(
+ runtime,
+ factory,
+ payload,
+ processedSchema,
+ options,
+ usagePayload,
+ log,
+ );
+ } catch (error) {
+ // Provider HTTP normalization must not hide the structured-output recovery signal.
+ if (error instanceof StructuredOutputError) throw error;
+
+ const handledError = runtime.handleError(error);
+
+ if (
+ handledError.errorType === AgentRuntimeErrorType.AgentRuntimeError ||
+ handledError.errorType === ErrorType.bizError
+ ) {
+ throw error;
+ }
+
+ throw handledError;
+ }
+};
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/generateObjectReasoning.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/generateObjectReasoning.ts
deleted file mode 100644
index 0d643f34e77..00000000000
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/generateObjectReasoning.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-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.responsesInputs.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.responsesInputs.test.ts
new file mode 100644
index 00000000000..90ceb38efca
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.responsesInputs.test.ts
@@ -0,0 +1,88 @@
+// @vitest-environment node
+import { ModelProvider } from 'model-bank';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import * as responsesInputs from '../protocols/openaiResponses/inputs';
+import { createOpenAICompatibleRuntime } from './index';
+
+const closedResponseSource = {
+ toReadableStream: () =>
+ new ReadableStream({
+ start(controller) {
+ controller.close();
+ },
+ }),
+};
+
+describe('LobeOpenAICompatibleFactory Responses input conversion', () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it('should enable strictToolPairing when building Responses API input', async () => {
+ const LobeMockProviderUseResponses = createOpenAICompatibleRuntime({
+ baseURL: 'https://api.test.com/v1',
+ chatCompletion: {
+ useResponse: true,
+ },
+ provider: ModelProvider.OpenAI,
+ });
+
+ const inst = new LobeMockProviderUseResponses({ apiKey: 'test' });
+ const convertSpy = vi
+ .spyOn(responsesInputs, 'convertOpenAIResponseInputs')
+ .mockResolvedValue([{ role: 'user', content: 'mocked input' }] as any);
+
+ vi.spyOn(inst['client'].responses, 'create').mockResolvedValue(closedResponseSource as any);
+
+ try {
+ await inst.chat({
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'any-model',
+ temperature: 0,
+ });
+ } catch {
+ // Ignore stream mock limitations; we only care about input conversion options.
+ }
+
+ expect(convertSpy).toHaveBeenCalledWith(
+ [{ content: 'hi', role: 'user' }],
+ expect.objectContaining({
+ forceImageBase64: undefined,
+ forceVideoBase64: undefined,
+ strictToolPairing: true,
+ }),
+ );
+ convertSpy.mockRestore();
+ });
+
+ it('should bind encrypted reasoning to the ChatGPT subscription account', async () => {
+ const Runtime = createOpenAICompatibleRuntime({
+ baseURL: 'https://chatgpt.com/backend-api/codex',
+ chatCompletion: { useResponse: true },
+ provider: ModelProvider.ChatGPT,
+ });
+ const convertSpy = vi
+ .spyOn(responsesInputs, 'convertOpenAIResponseInputs')
+ .mockRejectedValue({ status: 400 });
+
+ for (const chatgptAccountId of ['account-a', 'account-b']) {
+ const inst = new Runtime({ apiKey: 'oauth-token', chatgptAccountId });
+ await expect(
+ inst.chat({
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'gpt-5.6-sol',
+ temperature: 0,
+ }),
+ ).rejects.toBeDefined();
+ }
+
+ const fingerprints = convertSpy.mock.calls.map(
+ ([, options]) => options?.reasoningSignatureScope?.fingerprint,
+ );
+ expect(fingerprints[0]).toMatch(/^[\da-f]{32}$/);
+ expect(fingerprints[1]).toMatch(/^[\da-f]{32}$/);
+ expect(fingerprints[0]).not.toBe(fingerprints[1]);
+ expect(fingerprints).not.toContain('account-a');
+ expect(fingerprints).not.toContain('account-b');
+ convertSpy.mockRestore();
+ });
+});
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
index 45df7a8a8aa..9f4a72e9090 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
@@ -1922,45 +1922,6 @@ describe('LobeOpenAICompatibleFactory', () => {
},
);
- it('should enable strictToolPairing when building Responses API input', async () => {
- const LobeMockProviderUseResponses = createOpenAICompatibleRuntime({
- baseURL: 'https://api.test.com/v1',
- chatCompletion: {
- useResponse: true,
- },
- provider: ModelProvider.OpenAI,
- });
-
- const inst = new LobeMockProviderUseResponses({ apiKey: 'test' });
- const convertSpy = vi
- .spyOn(openaiHelpers, 'convertOpenAIResponseInputs')
- .mockResolvedValue([{ role: 'user', content: 'mocked input' }] as any);
-
- vi.spyOn(inst['client'].responses, 'create').mockResolvedValue(
- createClosedResponseSource() as any,
- );
-
- try {
- await inst.chat({
- messages: [{ content: 'hi', role: 'user' }],
- model: 'any-model',
- temperature: 0,
- });
- } catch {
- // Ignore stream mock limitations; we only care about input conversion options.
- }
-
- expect(convertSpy).toHaveBeenCalledWith(
- [{ content: 'hi', role: 'user' }],
- expect.objectContaining({
- forceImageBase64: undefined,
- forceVideoBase64: undefined,
- strictToolPairing: true,
- }),
- );
- convertSpy.mockRestore();
- });
-
it('should replay encrypted reasoning scoped to the mapped upstream model', async () => {
const Runtime = createOpenAICompatibleRuntime({
baseURL: 'https://api.test.com/v1',
@@ -2003,38 +1964,6 @@ describe('LobeOpenAICompatibleFactory', () => {
});
});
- it('should bind encrypted reasoning to the ChatGPT subscription account', async () => {
- const Runtime = createOpenAICompatibleRuntime({
- baseURL: 'https://chatgpt.com/backend-api/codex',
- chatCompletion: { useResponse: true },
- provider: ModelProvider.ChatGPT,
- });
- const convertSpy = vi
- .spyOn(openaiHelpers, 'convertOpenAIResponseInputs')
- .mockRejectedValue({ status: 400 });
-
- for (const chatgptAccountId of ['account-a', 'account-b']) {
- const inst = new Runtime({ apiKey: 'oauth-token', chatgptAccountId });
- await expect(
- inst.chat({
- messages: [{ content: 'hi', role: 'user' }],
- model: 'gpt-5.6-sol',
- temperature: 0,
- }),
- ).rejects.toBeDefined();
- }
-
- const fingerprints = convertSpy.mock.calls.map(
- ([, options]) => options?.reasoningSignatureScope?.fingerprint,
- );
- expect(fingerprints[0]).toMatch(/^[\da-f]{32}$/);
- expect(fingerprints[1]).toMatch(/^[\da-f]{32}$/);
- expect(fingerprints[0]).not.toBe(fingerprints[1]);
- expect(fingerprints).not.toContain('account-a');
- expect(fingerprints).not.toContain('account-b');
- convertSpy.mockRestore();
- });
-
it('should keep OpenRouter OpenAI slugs on chat completions for provider payload normalization', async () => {
const LobeMockOpenRouter = createOpenAICompatibleRuntime({
baseURL: 'https://openrouter.ai/api/v1',
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index d14617a3a39..b6ff0eda0b2 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -1,20 +1,11 @@
-import type { ChatModelCard } from '@lobechat/types';
-import dayjs from 'dayjs';
-import utc from 'dayjs/plugin/utc';
import debug from 'debug';
-import type { AiModelType } from 'model-bank';
-import { LOBE_DEFAULT_MODEL_LIST } from 'model-bank';
import type OpenAI from 'openai';
-import type { Stream } from 'openai/streaming';
-import { ErrorClassifier, refineErrorCode } from '../../errors';
-import { isResponsesAPIModel } from '../../providers/openai/modelId';
import type {
ASROptions,
ASRPayload,
ASRResponse,
ChatCompletionErrorPayload,
- ChatCompletionTool,
ChatMethodOptions,
ChatStreamPayload,
Embeddings,
@@ -25,7 +16,6 @@ import type {
TextToSpeechOptions,
TextToSpeechPayload,
} from '../../types';
-import { AgentRuntimeErrorType } from '../../types/error';
import type { CreateImageMethodOptions, CreateImagePayload } from '../../types/image';
import type {
CreateVideoPayload,
@@ -34,22 +24,11 @@ import type {
PollVideoStatusResult,
VideoGenerationCapabilities,
} from '../../types/video';
-import { respondJsonAfterStream } from '../../utils/consumeStream';
import { AgentRuntimeError } from '../../utils/createError';
-import { debugPayload, debugResponse, debugStream } from '../../utils/debugStream';
-import { desensitizeUrl } from '../../utils/desensitizeUrl';
-import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';
import { getModelPricing } from '../../utils/getModelPricing';
-import { handleOpenAIError } from '../../utils/handleOpenAIError';
import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';
import { resolveMappedModelId, withMappedModelId } from '../../utils/modelIdMapping';
-import { detectModelProvider } from '../../utils/modelParse';
-import { postProcessModelList } from '../../utils/postProcessModelList';
-import {
- assertContextWithinWindow,
- ContextExceededPreFlightError,
-} from '../../utils/resolveSafeMaxTokens';
-import { StreamingResponse } from '../../utils/response';
+import { assertContextWithinWindow } from '../../utils/resolveSafeMaxTokens';
import {
createSignatureChannelId,
createSignatureScope,
@@ -58,54 +37,34 @@ import {
} from '../../utils/signatureScope';
import type { LobeRuntimeAI } from '../BaseAI';
import { normalizeToolsParameters } from '../contextBuilders/normalizeToolSchema';
-import { convertOpenAIMessages, convertOpenAIResponseInputs } from '../contextBuilders/openai';
-import { resolveModelSamplingParameters } from '../parameterResolver';
-import type { OpenAIStreamOptions } from '../streams';
-import { OpenAIResponsesStream, OpenAIStream } from '../streams';
-import { type ChatPayloadForTransformStream, readableFromAsyncIterable } from '../streams/protocol';
+import { chatViaChatCompletions } from '../protocols/openaiChatCompletions/chat';
+import { chatViaResponses } from '../protocols/openaiResponses/chat';
+import { convertOpenAITranscriptionUsage, convertOpenAIUsage } from '../usageConverters/openai';
import {
- convertOpenAIResponseUsage,
- convertOpenAITranscriptionUsage,
- convertOpenAIUsage,
-} from '../usageConverters/openai';
+ resolvePromptCacheKey,
+ shouldUseResponsesAPI,
+ type ShouldUseResponsesAPIParams,
+} from './apiMode';
import { OpenAICompatibleClient } from './client';
+import type { OpenAICompatibleRuntimeContext } from './context';
import { createOpenAICompatibleImage } from './createImage';
import { createOpenAICompatibleVideo, pollOpenAICompatibleVideoStatus } from './createVideo';
import { createDecision } from './decide';
+import { mapOpenAICompatibleError, resolveErrorTypes } from './errors';
import type {
- ChatCompletionCreateParamsWithPromptCacheKey,
ConstructorOptions,
LobeClientOptions,
OpenAICompatibleFactoryOptions,
- OpenAIExtraParams,
ResponseCreateParamsWithPromptCacheKey,
} from './factoryOptions';
-import {
- getGenerateObjectReasoningParams,
- getGenerateObjectResponsesReasoningParams,
-} from './generateObjectReasoning';
-import { transformResponseAPIToStream, transformResponseToStream } from './nonStreamToStream';
-import {
- initializeOpenAIDiagnostics,
- observeOpenAIChatCompletionStream,
- observeOpenAIResponsesStream,
- recordOpenAIChatCompletionResponse,
- recordOpenAIResponseMetadata,
- recordOpenAIResponsesResponse,
- resolveOpenAIResponseWithMetadata,
-} from './providerDiagnostics';
-import {
- convertChatCompletionToolToResponseTool,
- stripChatCompletionParameters,
-} from './responseTools';
-import {
- parseStructuredOutputText,
- parseStructuredToolArguments,
- StructuredOutputError,
-} from './structuredOutput';
+import { generateObject as runGenerateObject } from './generateObject';
+import { listOpenAICompatibleModels } from './models';
import { createOpenAICompatibleSpeech } from './textToSpeech';
export type { PollVideoStatusResult };
+export { isResponseFormatUnsupportedError } from '../protocols/openaiChatCompletions/generateObject';
+export * from '../protocols/openaiChatCompletions/nonStreamToStream';
+export * from '../protocols/openaiResponses/nonStreamToStream';
export * from './createVideo';
export type {
CreateImageOptions,
@@ -113,61 +72,28 @@ export type {
CustomClientOptions,
OpenAICompatibleFactoryOptions,
} from './factoryOptions';
-export * from './nonStreamToStream';
-
-/**
- * Detect provider 400/422 errors that reject `response_format: { type: 'json_schema' }`.
- * Known message variants from the DeepSeek family (official API and gateways proxying it):
- * - `This response_format type is unavailable now`
- * - `response_format.type \`json_schema\` is unavailable now`
- */
-export const isResponseFormatUnsupportedError = (error: unknown): boolean => {
- const err = error as { error?: { message?: unknown }; message?: unknown };
- const message = [err?.message, err?.error?.message]
- .filter((value): value is string => typeof value === 'string')
- .join('\n');
- if (!message) return false;
-
- return /(?:response_format|json_schema)[^]*?(?:unavailable|not +support)/i.test(message);
-};
-
-// the model contains the following keywords is not a chat model, so we should filter them out
-export const CHAT_MODELS_BLOCK_LIST = [
- 'embedding',
- 'davinci',
- 'curie',
- 'moderation',
- 'ada',
- 'babbage',
- 'tts',
- 'whisper',
- 'dall-e',
-];
-
-export const createOpenAICompatibleRuntime = <T extends Record<string, any> = any>({
- provider,
- baseURL: DEFAULT_BASE_URL,
- apiKey: DEFAULT_API_KEY,
- errorType,
- debug: debugParams,
- constructorOptions,
- chatCompletion,
- models,
- customClient,
- responses,
- promptCacheKeyModels,
- createImage: customCreateImage,
- createVideo: customCreateVideo,
- decide: decideConfig,
- videoGenerationCapabilities,
- handleCreateVideoWebhook: customHandleCreateVideoWebhook,
- handlePollVideoStatus: customHandlePollVideoStatus,
- generateObject: generateObjectConfig,
-}: OpenAICompatibleFactoryOptions<T>) => {
- const ErrorType = {
- bizError: errorType?.bizError || AgentRuntimeErrorType.ProviderBizError,
- invalidAPIKey: errorType?.invalidAPIKey || AgentRuntimeErrorType.InvalidProviderAPIKey,
- };
+export { CHAT_MODELS_BLOCK_LIST } from './models';
+
+export const createOpenAICompatibleRuntime = <T extends Record<string, any> = any>(
+ factory: OpenAICompatibleFactoryOptions<T>,
+) => {
+ const {
+ provider,
+ baseURL: DEFAULT_BASE_URL,
+ apiKey: DEFAULT_API_KEY,
+ constructorOptions,
+ chatCompletion,
+ customClient,
+ responses,
+ promptCacheKeyModels,
+ createImage: customCreateImage,
+ createVideo: customCreateVideo,
+ decide: decideConfig,
+ videoGenerationCapabilities,
+ handleCreateVideoWebhook: customHandleCreateVideoWebhook,
+ handlePollVideoStatus: customHandlePollVideoStatus,
+ } = factory;
+ const ErrorType = resolveErrorTypes(factory);
return class LobeOpenAICompatibleAI implements LobeRuntimeAI {
client!: OpenAI;
@@ -300,120 +226,34 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
);
}
- /**
- * Determine if should use Responses API based on various configuration options
- * @param params - Configuration parameters
- * @returns true if should use Responses API, false otherwise
- */
- private shouldUseResponsesAPI(params: {
- /** Context for logging (e.g., 'chat', 'generateObject', 'tool calling') */
- context?: string;
- /** Factory/instance level useResponse flag */
- flagUseResponse?: boolean;
- /** Factory/instance level model patterns for Responses API */
- flagUseResponseModels?: Array<string | RegExp>;
- /** The model ID to check */
- model?: string;
- /** Explicit responseApi flag */
- responseApi?: boolean;
- /** User-specified API mode (highest priority) */
- userApiMode?: string;
- }): boolean {
- const {
- model,
- userApiMode,
- responseApi,
- flagUseResponse,
- flagUseResponseModels,
- context = 'operation',
- } = params;
-
- const log = debug(`${this.logPrefix}:shouldUseResponsesAPI`);
-
- // Priority 0: Check built-in Responses API model rules FIRST (highest priority)
- // These models MUST use Responses API regardless of user settings.
- if (model && isResponsesAPIModel(model)) {
- log('using Responses API: model %s matches built-in Responses API model rules', model);
- return true;
- }
-
- // Priority 1: userApiMode is explicitly set to 'chatCompletion' (user disabled the switch)
- if (userApiMode === 'chatCompletion') {
- log('using Chat Completions API: userApiMode=%s', userApiMode);
- return false;
- }
-
- // Priority 2: When user enables the switch (userApiMode === 'responses')
- // Check if useResponseModels is configured - if so, only matching models use Responses API
- // If useResponseModels is not configured, all models use Responses API
- if (userApiMode === 'responses') {
- if (model && flagUseResponseModels?.length) {
- const matches = flagUseResponseModels.some((m: string | RegExp) =>
- typeof m === 'string' ? model.includes(m) : (m as RegExp).test(model),
- );
- if (matches) {
- log(
- 'using Responses API: userApiMode=responses and model %s matches useResponseModels',
- model,
- );
- return true;
- }
- log(
- 'using Chat Completions API: userApiMode=responses but model %s does not match useResponseModels',
- model,
- );
- return false;
- }
- // No useResponseModels configured, use Responses API for all models
- log('using Responses API: userApiMode=responses (no useResponseModels filter)');
- return true;
- }
-
- // Priority 3: Explicit responseApi flag
- if (responseApi) {
- log('using Responses API: explicit responseApi flag for %s', context);
- return true;
- }
-
- // Priority 4: Factory/instance level useResponse flag
- if (flagUseResponse) {
- log('using Responses API: flagUseResponse=true for %s', context);
- return true;
- }
-
- // Priority 5: Check if model matches useResponseModels patterns (without user switch)
- if (model && flagUseResponseModels?.length) {
- const matches = flagUseResponseModels.some((m: string | RegExp) =>
- typeof m === 'string' ? model.includes(m) : (m as RegExp).test(model),
- );
- if (matches) {
- log('using Responses API: model %s matches useResponseModels config', model);
- return true;
- }
- }
-
- log('using Chat Completions API for %s', context);
- return false;
- }
-
private resolvePromptCacheKey(model?: string, user?: string) {
- if (!user) return;
-
- // Keep the default key at {userId}:{model}; {agentId/topicId} can be added later if a narrower cache bucket is needed.
- if (model?.startsWith('gpt-') || /^o\d/.test(model || '') || model === 'chat-latest') {
- return `lobe:${user}:${model}`;
- }
+ return resolvePromptCacheKey(model, user, promptCacheKeyModels);
+ }
- const matchesProviderPromptCacheModel = promptCacheKeyModels?.some((item) => {
- if (!model) return false;
- if (typeof item === 'string') return model.includes(item);
+ private shouldUseResponsesAPI(params: ShouldUseResponsesAPIParams) {
+ return shouldUseResponsesAPI(params, this.logPrefix);
+ }
- item.lastIndex = 0;
- return item.test(model);
- });
- if (matchesProviderPromptCacheModel) {
- return `lobe:${user}:${model}`;
- }
+ /** What the protocol modules read; built per call so it always reflects current state. */
+ private get context(): OpenAICompatibleRuntimeContext {
+ return {
+ _options: this._options,
+ baseURL: this.baseURL,
+ client: this.client,
+ getMappedModelId: (model) => this.getMappedModelId(model),
+ getSignatureScope: (model, kind, protocol) => this.getSignatureScope(model, kind, protocol),
+ handleError: (error) => this.handleError(error),
+ id: this.id,
+ instance: this,
+ logPrefix: this.logPrefix,
+ prepareResponsesRequest: (payload, logicalModel) =>
+ this.prepareResponsesRequest(payload, logicalModel),
+ resolvePromptCacheKeyParams: (model, user, existing) =>
+ this.resolvePromptCacheKeyParams(model, user, existing),
+ shouldUseResponsesAPI: (params) => this.shouldUseResponsesAPI(params),
+ withMappedRequestModel: (payload, logicalModel) =>
+ this.withMappedRequestModel(payload, logicalModel),
+ };
}
private resolvePromptCacheKeyParams(
@@ -428,26 +268,56 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
return 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',
- ),
- });
- }
+ /**
+ * `handlePayload` receives `this._options` and may retarget `baseURL` for a
+ * specific model — Spark moves `spark-x2-flash` / `spark-x2` / `spark-x1.5`
+ * to `/agent/v1`, `/x2` and `/v2`. Re-point the cached client at that URL
+ * before the request, otherwise those models keep hitting the
+ * constructor's `/v1`.
+ */
+ private syncClientWithPayloadBaseURL() {
+ const computedBaseURL =
+ typeof this._options.baseURL === 'string' && this._options.baseURL
+ ? this._options.baseURL.trim()
+ : typeof DEFAULT_BASE_URL === 'string'
+ ? DEFAULT_BASE_URL
+ : undefined;
+ const targetBaseURL = computedBaseURL || this.baseURL;
+
+ if (targetBaseURL === this.baseURL) return;
+
+ const restOptions = {
+ ...(this._options as ConstructorOptions<T> & Record<string, any>),
+ } as Record<string, any>;
+ const optionApiKey = restOptions.apiKey;
+ delete restOptions.apiKey;
+ delete restOptions.baseURL;
+ delete restOptions.modelIdMapping;
+
+ const sanitizedApiKey = optionApiKey?.toString().trim() || DEFAULT_API_KEY;
+
+ const nextOptions = {
+ ...restOptions,
+ apiKey: sanitizedApiKey,
+ baseURL: targetBaseURL,
+ } as ConstructorOptions<T>;
+
+ const initOptions = {
+ apiKey: sanitizedApiKey,
+ baseURL: targetBaseURL,
+ ...constructorOptions,
+ ...restOptions,
+ } as ConstructorOptions<T> & Record<string, any>;
+
+ this._options = nextOptions;
- private handleGenerateObjectPayload(
- payload: GenerateObjectPayload,
- requestPayload: ChatCompletionCreateParamsWithPromptCacheKey,
- ) {
- return generateObjectConfig?.handlePayload
- ? generateObjectConfig.handlePayload(payload, requestPayload, this._options)
- : requestPayload;
+ if (customClient?.createClient) {
+ this.client = customClient.createClient(initOptions);
+ } else {
+ this.client = new OpenAICompatibleClient(initOptions);
+ }
+
+ this.baseURL = targetBaseURL;
}
async chat({ responseMode, ...payload }: ChatStreamPayload, options?: ChatMethodOptions) {
@@ -506,255 +376,27 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
} as OpenAI.ChatCompletionCreateParamsStreaming);
if ((handledPayload as any).apiMode === 'responses') {
- return await this.handleResponseAPIMode(processedPayload, options, payload.model);
- }
-
- // Sanitize temperature/top_p conflict for Claude 4+ models routed via OpenAI-compatible API.
- // normalizeTemperature is false here because OpenAI-compatible providers use the raw range.
- const postPayload = {
- ...handledPayload,
- ...resolveModelSamplingParameters(handledPayload.model, handledPayload, {
- normalizeTemperature: false,
- preferTemperature: true,
- }),
- };
-
- const computedBaseURL =
- typeof this._options.baseURL === 'string' && this._options.baseURL
- ? this._options.baseURL.trim()
- : typeof DEFAULT_BASE_URL === 'string'
- ? DEFAULT_BASE_URL
- : undefined;
- const targetBaseURL = computedBaseURL || this.baseURL;
-
- if (targetBaseURL !== this.baseURL) {
- const restOptions = {
- ...(this._options as ConstructorOptions<T> & Record<string, any>),
- } as Record<string, any>;
- const optionApiKey = restOptions.apiKey;
- delete restOptions.apiKey;
- delete restOptions.baseURL;
- delete restOptions.modelIdMapping;
-
- const sanitizedApiKey = optionApiKey?.toString().trim() || DEFAULT_API_KEY;
-
- const nextOptions = {
- ...restOptions,
- apiKey: sanitizedApiKey,
- baseURL: targetBaseURL,
- } as ConstructorOptions<T>;
-
- const initOptions = {
- apiKey: sanitizedApiKey,
- baseURL: targetBaseURL,
- ...constructorOptions,
- ...restOptions,
- } as ConstructorOptions<T> & Record<string, any>;
-
- this._options = nextOptions;
-
- if (customClient?.createClient) {
- this.client = customClient.createClient(initOptions);
- } else {
- this.client = new OpenAICompatibleClient(initOptions);
- }
-
- this.baseURL = targetBaseURL;
- }
-
- const requestModel =
- this.withMappedRequestModel({ model: postPayload.model }, payload.model).model ??
- payload.model;
- const thoughtSignatureScope = await this.getSignatureScope(
- requestModel,
- 'thought_signature',
- 'chat_completions',
- );
- const messages = await convertOpenAIMessages(postPayload.messages, {
- forceImageBase64: chatCompletion?.forceImageBase64,
- forceVideoBase64: chatCompletion?.forceVideoBase64,
- model: postPayload.model,
- supportsAudioInput: chatCompletion?.supportsAudioInput,
- thoughtSignatureScope,
- });
- const includeUsageRequested = Boolean(postPayload.stream && !chatCompletion?.excludeUsage);
-
- let response:
- | OpenAI.ChatCompletion
- | ReadableStream<OpenAI.Chat.Completions.ChatCompletionChunk>
- | Stream<OpenAI.Chat.Completions.ChatCompletionChunk>;
- let providerResponseDiagnostics;
-
- const streamOptions: OpenAIStreamOptions = {
- bizErrorTypeTransformer: chatCompletion?.handleStreamBizErrorType,
- callbacks: options?.callback,
- payload: {
- apiMode: 'chat_completions',
- includeUsageRequested,
- model: payload.model,
- pricing: await getModelPricing(payload.model, this.id, options?.pricingContext),
- provider: this.id,
- thoughtSignatureScope,
- },
- };
-
- if (customClient?.createChatCompletionStream) {
- log('using custom client for chat completion stream');
- // Apply sampling sanitization to processedPayload for the custom client path.
- // We use processedPayload (ChatStreamPayload type) here because
- // createChatCompletionStream expects ChatStreamPayload, not the OpenAI SDK format.
- // Strip LobeHub-internal fields that should never reach downstream APIs.
- const {
- apiMode: _apiMode,
- preserveThinking: _preserveThinking,
- ...cleanProcessedPayload
- } = processedPayload as any;
- const customRequestPayload = {
- ...cleanProcessedPayload,
- ...resolveModelSamplingParameters(cleanProcessedPayload.model, cleanProcessedPayload, {
- normalizeTemperature: false,
- preferTemperature: true,
- }),
- };
- const requestPayload = this.withMappedRequestModel(customRequestPayload, payload.model);
- providerResponseDiagnostics = initializeOpenAIDiagnostics({
- apiMode: 'chat_completions',
- diagnostics: options?.diagnostics,
- endpoint: desensitizeUrl(this.baseURL),
- payload: requestPayload,
- sentAt: Date.now(),
- });
-
- response = customClient.createChatCompletionStream(
- this.client,
- requestPayload,
- this,
- ) as any;
- recordOpenAIResponseMetadata(providerResponseDiagnostics, {});
- } else {
- // Remove LobeHub-internal fields before sending to downstream API.
- // `preserveThinking` is only consumed by Qwen/Zhipu handlePayload (which runs above)
- // and must not leak to other providers' APIs as an unknown parameter.
- const { apiMode: _, preserveThinking: _pt, ...cleanedPayload } = postPayload as any;
- const finalPayload = {
- ...cleanedPayload,
- messages,
- ...(chatCompletion?.noUserId ? {} : { user: options?.user }),
- ...this.resolvePromptCacheKeyParams(
- cleanedPayload.model,
- options?.user,
- cleanedPayload.prompt_cache_key,
- ),
- stream_options: includeUsageRequested ? { include_usage: true } : undefined,
- };
- const requestPayload = this.withMappedRequestModel(finalPayload, payload.model);
-
- log('sending chat completion request with %d messages', messages.length);
-
- if (debugParams?.chatCompletion?.()) {
- debugPayload(requestPayload);
- }
-
- providerResponseDiagnostics = initializeOpenAIDiagnostics({
- apiMode: 'chat_completions',
- diagnostics: options?.diagnostics,
- endpoint: desensitizeUrl(this.baseURL),
- payload: requestPayload,
- sentAt: Date.now(),
- });
- const responsePromise = this.client.chat.completions.create(requestPayload, {
- // https://github.com/lobehub/lobe-chat/pull/318
- headers: { Accept: '*/*', ...options?.requestHeaders },
- signal: options?.signal,
- });
- const responseWithMetadata = await resolveOpenAIResponseWithMetadata(responsePromise);
- response = responseWithMetadata.data as
- OpenAI.ChatCompletion | Stream<OpenAI.Chat.Completions.ChatCompletionChunk>;
- recordOpenAIResponseMetadata(providerResponseDiagnostics, {
- requestId: responseWithMetadata.request_id,
- response: responseWithMetadata.response,
- });
- }
-
- if (postPayload.stream) {
- log('processing streaming response');
- let prod = response as
- | ReadableStream<OpenAI.Chat.Completions.ChatCompletionChunk>
- | Stream<OpenAI.Chat.Completions.ChatCompletionChunk>;
-
- if (debugParams?.chatCompletion?.()) {
- const [productionStream, useForDebug] = prod.tee();
- prod = productionStream;
- const useForDebugStream =
- useForDebug instanceof ReadableStream ? useForDebug : useForDebug.toReadableStream();
-
- debugStream(useForDebugStream).catch(console.error);
- }
-
- if (providerResponseDiagnostics) {
- /** Observe provider-native chunks before the OpenAI protocol adapter transforms them. */
- const observedStream = observeOpenAIChatCompletionStream(
- prod,
- providerResponseDiagnostics,
- options?.signal,
- );
- prod =
- observedStream instanceof ReadableStream
- ? observedStream
- : readableFromAsyncIterable(observedStream, {
- model: payload.model,
- provider: this.id,
- });
- }
-
- return StreamingResponse(
- chatCompletion?.handleStream
- ? chatCompletion.handleStream(prod, {
- callbacks: streamOptions.callbacks,
- inputStartAt,
- payload: streamOptions.payload,
- })
- : OpenAIStream(prod, {
- ...streamOptions,
- inputStartAt,
- }),
- {
- headers: options?.headers,
- },
+ return await chatViaResponses(
+ this.context,
+ factory,
+ processedPayload,
+ options,
+ payload.model,
);
}
- if (debugParams?.chatCompletion?.()) {
- debugResponse(response);
- }
-
- await recordOpenAIChatCompletionResponse(
- providerResponseDiagnostics,
- response as OpenAI.ChatCompletion,
- options?.signal,
- );
-
- log('transforming non-streaming response to stream');
- // Snapshot first: provider transform handlers may rewrite the completion in place
- const jsonBody = responseMode === 'json' ? structuredClone(response) : undefined;
- const transformHandler =
- chatCompletion?.handleTransformResponseToStream || transformResponseToStream;
- const stream = transformHandler(response as unknown as OpenAI.ChatCompletion);
-
- const streamingResponse = StreamingResponse(
- chatCompletion?.handleStream
- ? chatCompletion.handleStream(stream, {
- callbacks: streamOptions.callbacks,
- inputStartAt,
- payload: streamOptions.payload,
- })
- : OpenAIStream(stream, { ...streamOptions, enableStreaming: false, inputStartAt }),
- {
- headers: options?.headers,
- },
- );
- if (jsonBody) return await respondJsonAfterStream(streamingResponse, jsonBody);
- return streamingResponse;
+ // `handlePayload` may have retargeted the base URL for this model.
+ this.syncClientWithPayloadBaseURL();
+
+ return await chatViaChatCompletions(this.context, factory, {
+ handledPayload,
+ inputStartAt,
+ log,
+ options,
+ payload,
+ processedPayload,
+ responseMode,
+ });
} catch (error) {
throw this.handleError(error);
}
@@ -840,280 +482,11 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
}
async models() {
- const log = debug(`${this.logPrefix}:models`);
- log('fetching available models');
-
- let resultModels: ChatModelCard[];
- if (typeof models === 'function') {
- log('using custom models function');
- resultModels = await models({ client: this.client, options: this._options });
- } else {
- log('fetching models from client API');
- const list = await this.client.models.list();
- resultModels = list.data
- .filter((model) => {
- return CHAT_MODELS_BLOCK_LIST.every(
- (keyword) => !model.id.toLowerCase().includes(keyword),
- );
- })
- .map((item) => {
- if (models?.transformModel) {
- return models.transformModel(item);
- }
-
- const toReleasedAt = () => {
- if (!item.created) return;
- dayjs.extend(utc);
-
- // guarantee item.created in Date String format
- if (
- typeof (item.created as any) === 'string' ||
- // or in milliseconds
- item.created.toFixed(0).length === 13
- ) {
- return dayjs.utc(item.created).format('YYYY-MM-DD');
- }
-
- // by default, the created time is in seconds
- return dayjs.utc(item.created * 1000).format('YYYY-MM-DD');
- };
-
- // TODO: should refactor after remove v1 user/modelList code
- const knownModel = LOBE_DEFAULT_MODEL_LIST.find((model) => model.id === item.id);
-
- if (knownModel) {
- const releasedAt = knownModel.releasedAt ?? toReleasedAt();
-
- return { ...knownModel, releasedAt };
- }
-
- return {
- id: item.id,
- releasedAt: toReleasedAt(),
- };
- })
-
- .filter(Boolean) as ChatModelCard[];
- }
-
- log('fetched %d models', resultModels.length);
-
- return await postProcessModelList(resultModels, (modelId) =>
- getModelPropertyWithFallback<AiModelType>(modelId, 'type'),
- );
- }
-
- /**
- * Simulate schema-based structured output through a forced tool call, for
- * providers that do not support `response_format: { type: 'json_schema' }`.
- * Returns the parsed schema object — the same shape as the json_schema path.
- */
- private async generateObjectViaToolCalling(
- payload: GenerateObjectPayload,
- options: GenerateObjectOptions | undefined,
- usagePayload: Parameters<typeof convertOpenAIUsage>[1],
- ) {
- const { schema, model } = payload;
-
- // Apply schema transformation if configured
- const processedSchema = generateObjectConfig?.handleSchema
- ? { ...schema!, schema: generateObjectConfig.handleSchema(schema!.schema) }
- : schema!;
-
- const tool: ChatCompletionTool = {
- function: {
- description:
- processedSchema.description ||
- 'Generate structured output according to the provided schema',
- name: processedSchema.name || 'structured_output',
- parameters: processedSchema.schema,
- },
- type: 'function',
- };
-
- const res = await this.client.chat.completions.create(
- this.withMappedRequestModel(
- this.handleGenerateObjectPayload(payload, {
- ...getGenerateObjectReasoningParams(payload),
- messages: await this.convertGenerateObjectMessages(payload),
- model,
- ...this.resolvePromptCacheKeyParams(model, options?.user),
- tool_choice: { function: { name: tool.function.name }, type: 'function' },
- tools: [tool],
- user: options?.user,
- }),
- payload.model,
- ) as OpenAI.ChatCompletionCreateParamsNonStreaming,
- { headers: options?.headers, signal: options?.signal },
- );
-
- if (res.usage) {
- await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
- }
-
- // Structural type keeps this compatible across openai SDK majors (v6
- // widened tool_calls to a function/custom union).
- const toolCalls = res.choices?.[0]?.message?.tool_calls as
- { function?: { arguments: string; name: string } }[] | undefined;
- const toolCall =
- toolCalls?.find((item) => item.function?.name === tool.function.name) ?? toolCalls?.[0];
-
- if (!toolCall?.function) throw new StructuredOutputError('no tool calls returned');
-
- return parseStructuredToolArguments(toolCall.function.arguments);
+ return listOpenAICompatibleModels(this.context, factory);
}
async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {
- try {
- const { messages, schema, model, responseApi, tools } = payload;
-
- const log = debug(`${this.logPrefix}:generateObject`);
- log(
- 'generateObject called with model: %s, hasTools: %s, hasSchema: %s',
- model,
- !!tools,
- !!schema,
- );
-
- const pricing = await getModelPricing(model, this.id, options?.pricingContext);
- const usagePayload = { model, pricing, provider: this.id };
-
- if (tools) {
- log('using tools-based generation');
- return await this.generateObjectWithTools(payload, options, usagePayload);
- }
-
- if (!schema) throw new Error('tools or schema is required');
-
- // Use tool calling fallback if configured, or when the model is known to
- // reject `response_format: { type: 'json_schema' }`. The DeepSeek API only
- // supports `json_object` and replies `400 This response_format type is
- // unavailable now` to json_schema requests, so DeepSeek-family models served
- // through generic OpenAI-compatible providers (aggregator gateways, custom
- // endpoints) must simulate structured output via forced tool calling.
- if (generateObjectConfig?.useToolsCalling || detectModelProvider(model) === 'deepseek') {
- log('using tool calling fallback for structured output');
- return await this.generateObjectViaToolCalling(payload, options, usagePayload);
- }
-
- // Factory-level Responses API routing control (supports instance override)
- const instanceGenerateObject = ((this._options as any).generateObject || {}) as {
- useResponse?: boolean;
- useResponseModels?: Array<string | RegExp>;
- };
- const flagUseResponse =
- instanceGenerateObject.useResponse ??
- (generateObjectConfig ? generateObjectConfig.useResponse : undefined);
- const flagUseResponseModels =
- instanceGenerateObject.useResponseModels ?? generateObjectConfig?.useResponseModels;
-
- const shouldUseResponses = this.shouldUseResponsesAPI({
- context: 'generateObject',
- flagUseResponse,
- flagUseResponseModels,
- model,
- responseApi,
- });
-
- // Apply schema transformation if configured
- const processedSchema = generateObjectConfig?.handleSchema
- ? { ...schema, schema: generateObjectConfig.handleSchema(schema.schema) }
- : schema;
-
- if (shouldUseResponses) {
- log('calling responses.create for structured output');
- // Chat Completions content parts are not valid Responses input: a `text` part must
- // become `input_text` and an `image_url` part `input_image`, or the API rejects the
- // whole request. String content survives untouched, which is why text-only callers
- // never hit this.
- const input = await convertOpenAIResponseInputs(messages as any, {
- forceImageBase64: chatCompletion?.forceImageBase64,
- forceVideoBase64: chatCompletion?.forceVideoBase64,
- provider: this.id,
- strictToolPairing: true,
- });
- const preparedRequest = this.prepareResponsesRequest(
- {
- input,
- model,
- ...getGenerateObjectResponsesReasoningParams(payload),
- ...this.resolvePromptCacheKeyParams(model, options?.user),
- text: { format: { strict: true, type: 'json_schema', ...processedSchema } },
- // Responses API replaced `user` with `safety_identifier`; some endpoints reject `user`
- safety_identifier: options?.user,
- } as any,
- model,
- );
- const res = await this.client!.responses.create(
- preparedRequest.payload as OpenAI.Responses.ResponseCreateParamsNonStreaming,
- {
- headers: preparedRequest.headers
- ? { ...options?.headers, ...preparedRequest.headers }
- : options?.headers,
- signal: options?.signal,
- },
- );
-
- if (res.usage) {
- await options?.onUsage?.(convertOpenAIResponseUsage(res.usage, usagePayload));
- }
-
- const text = res.output_text;
- log('received structured output from Responses API, length: %d', text?.length || 0);
- return parseStructuredOutputText(text);
- }
-
- log('calling chat.completions.create for structured output');
- let res: OpenAI.ChatCompletion;
- try {
- res = await this.client.chat.completions.create(
- this.withMappedRequestModel(
- this.handleGenerateObjectPayload(payload, {
- ...getGenerateObjectReasoningParams(payload),
- messages: await this.convertGenerateObjectMessages(payload),
- model,
- response_format: { json_schema: processedSchema, type: 'json_schema' },
- ...this.resolvePromptCacheKeyParams(model, options?.user),
- user: options?.user,
- }),
- model,
- ) as OpenAI.ChatCompletionCreateParamsNonStreaming,
- { headers: options?.headers, signal: options?.signal },
- );
- } catch (error) {
- // Gateways can serve json_schema-incapable upstreams under arbitrary
- // model ids (e.g. OpenCode Zen's `big-pickle` proxies DeepSeek), which
- // the model-id detection above cannot catch. Retry once via forced
- // tool calling when the upstream rejects the response_format type.
- if (!isResponseFormatUnsupportedError(error)) throw error;
-
- log('provider rejected json_schema response_format, retrying via tool calling');
- return await this.generateObjectViaToolCalling(payload, options, usagePayload);
- }
- if (res.usage) {
- await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
- }
-
- const text = res.choices?.[0]?.message?.content;
-
- log('received structured output from Chat Completions API, length: %d', text?.length || 0);
-
- return parseStructuredOutputText(text);
- } catch (error) {
- // Provider HTTP normalization must not hide the structured-output recovery signal.
- if (error instanceof StructuredOutputError) throw error;
-
- const handledError = this.handleError(error);
-
- if (
- handledError.errorType === AgentRuntimeErrorType.AgentRuntimeError ||
- handledError.errorType === ErrorType.bizError
- ) {
- throw error;
- }
-
- throw handledError;
- }
+ return runGenerateObject(this.context, factory, payload, options);
}
async embeddings(
@@ -1210,477 +583,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
}
protected handleError(error: any): ChatCompletionErrorPayload {
- const log = debug(`${this.logPrefix}:error`);
- log('handling error: %O', error);
-
- let desensitizedEndpoint = this.baseURL;
-
- // refs: https://github.com/lobehub/lobe-chat/issues/842
- if (this.baseURL !== DEFAULT_BASE_URL) {
- desensitizedEndpoint = desensitizeUrl(this.baseURL);
- }
-
- // Pre-flight context-window failures get a structured payload so the
- // UI can offer fork / switch-model affordances instead of surfacing a
- // raw provider 400. See .
- if (error instanceof ContextExceededPreFlightError) {
- log('pre-flight context exceeded: %s', error.message);
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: error.toPayload(),
- errorType: AgentRuntimeErrorType.ExceededContextWindow,
- message: error.message,
- provider: this.id,
- });
- }
-
- if (chatCompletion?.handleError) {
- log('using custom error handler');
- const errorResult = chatCompletion.handleError(error, this._options);
-
- if (errorResult)
- return AgentRuntimeError.chat({
- ...errorResult,
- provider: this.id,
- } as ChatCompletionErrorPayload);
- }
-
- if ('status' in (error as any)) {
- const status = (error as Response).status;
- log('HTTP error with status: %d', status);
-
- switch (status) {
- case 401: {
- log('invalid API key error');
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: error as any,
- errorType: ErrorType.invalidAPIKey,
- provider: this.id,
- });
- }
-
- case 413: {
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: error as any,
- errorType: AgentRuntimeErrorType.RequestBodyTooLarge,
- provider: this.id,
- });
- }
-
- default: {
- break;
- }
- }
- }
-
- const { errorResult, RuntimeError, message } = handleOpenAIError(error);
-
- log('error code: %s, message: %s', errorResult.code, errorResult.message);
-
- switch (errorResult.code) {
- case 'insufficient_quota': {
- log('insufficient quota error');
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: errorResult,
- errorType: AgentRuntimeErrorType.InsufficientQuota,
- message,
- provider: this.id,
- });
- }
-
- case 'model_not_found': {
- log('model not found error');
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: errorResult,
- errorType: AgentRuntimeErrorType.ModelNotFound,
- message,
- provider: this.id,
- });
- }
-
- // content too long
- case 'context_length_exceeded':
- case 'string_above_max_length': {
- log('context length exceeded error');
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: errorResult,
- errorType: AgentRuntimeErrorType.ExceededContextWindow,
- message,
- provider: this.id,
- });
- }
- }
-
- const errorMsg = errorResult.error?.message || errorResult.message;
-
- if (ErrorClassifier.isAccountDeactivated(errorMsg)) {
- log('account deactivated error detected from message');
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: errorResult,
- errorType: AgentRuntimeErrorType.AccountDeactivated,
- message,
- provider: this.id,
- });
- }
-
- if (ErrorClassifier.isInsufficientQuota(errorMsg)) {
- log('insufficient quota error detected from message');
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: errorResult,
- errorType: AgentRuntimeErrorType.InsufficientQuota,
- message,
- provider: this.id,
- });
- }
-
- if (ErrorClassifier.isExceededContextWindow(errorMsg)) {
- log('context length exceeded detected from message');
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: errorResult,
- errorType: AgentRuntimeErrorType.ExceededContextWindow,
- message,
- provider: this.id,
- });
- }
-
- if (ErrorClassifier.isRateLimitExceeded(errorMsg)) {
- log('quota limit reached detected from message');
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: errorResult,
- errorType: AgentRuntimeErrorType.RateLimitExceeded,
- message,
- provider: this.id,
- });
- }
-
- const fallbackErrorType = RuntimeError || ErrorType.bizError;
- const refinedErrorType = refineErrorCode({
- errorType: String(fallbackErrorType),
- message: typeof errorMsg === 'string' ? errorMsg : undefined,
- provider: this.id,
- });
-
- log('returning generic error');
- return AgentRuntimeError.chat({
- endpoint: desensitizedEndpoint,
- error: errorResult,
- errorType: refinedErrorType ?? fallbackErrorType,
- message,
- provider: this.id,
- });
- }
-
- private async handleResponseAPIMode(
- payload: ChatStreamPayload,
- options?: ChatMethodOptions,
- usageModel = payload.model,
- ): Promise<Response> {
- const log = debug(`${this.logPrefix}:handleResponseAPIMode`);
- log('handleResponseAPIMode called with model: %s', payload.model);
-
- const inputStartAt = Date.now();
-
- const {
- messages,
- reasoning_effort,
- tools,
- responsesTools,
- reasoning,
- responseMode,
- max_tokens,
- ...res
- } = responses?.handlePayload
- ? (responses.handlePayload(payload, this._options) as ChatStreamPayload)
- : payload;
- const requestModel =
- this.withMappedRequestModel({ model: res.model }, usageModel).model ?? usageModel;
- const reasoningSignatureScope = await this.getSignatureScope(
- requestModel,
- 'reasoning',
- 'responses',
- );
-
- const input = await convertOpenAIResponseInputs(messages as any, {
- forceImageBase64: chatCompletion?.forceImageBase64,
- forceVideoBase64: chatCompletion?.forceVideoBase64,
- provider: this.id,
- reasoningSignatureScope,
- strictToolPairing: true,
- });
-
- const isStreaming = payload.stream !== false;
- log(
- 'isStreaming: %s, hasTools: %s, hasReasoning: %s',
- isStreaming,
- !!tools,
- !!(reasoning || reasoning_effort),
- );
-
- const postPayload = {
- ...stripChatCompletionParameters(res),
- ...(reasoning || reasoning_effort
- ? {
- reasoning: {
- ...reasoning,
- ...(reasoning_effort && { effort: reasoning_effort }),
- },
- }
- : {}),
- input,
- ...(max_tokens && { max_output_tokens: max_tokens }),
- store: false,
- stream: isStreaming || undefined,
- tools: responsesTools ?? tools?.map(convertChatCompletionToolToResponseTool),
- ...this.resolvePromptCacheKeyParams(
- res.model,
- options?.user,
- (res as OpenAIExtraParams).prompt_cache_key,
- ),
- // Responses API replaced `user` with `safety_identifier`; some endpoints reject `user`
- safety_identifier: options?.user,
- // Sanitize sampling params for Responses API path
- ...resolveModelSamplingParameters(res.model, res, {
- normalizeTemperature: false,
- preferTemperature: true,
- }),
- } as ResponseCreateParamsWithPromptCacheKey;
- const preparedRequest = this.prepareResponsesRequest(postPayload, usageModel);
- const requestPayload = preparedRequest.payload;
- const providerResponseDiagnostics = initializeOpenAIDiagnostics({
- apiMode: 'responses',
- diagnostics: options?.diagnostics,
- endpoint: desensitizeUrl(this.baseURL),
- payload: requestPayload,
- sentAt: Date.now(),
- });
-
- if (debugParams?.responses?.()) {
- debugPayload(requestPayload);
- }
-
- log('sending responses.create request');
-
- const responsePromise = this.client.responses.create(requestPayload, {
- headers: {
- ...options?.requestHeaders,
- ...preparedRequest?.headers,
- },
- signal: options?.signal,
- });
- const responseWithMetadata = await resolveOpenAIResponseWithMetadata(responsePromise);
- const response = responseWithMetadata.data;
- recordOpenAIResponseMetadata(providerResponseDiagnostics, {
- requestId: responseWithMetadata.request_id,
- response: responseWithMetadata.response,
- });
-
- const streamOptions: OpenAIStreamOptions = {
- bizErrorTypeTransformer: chatCompletion?.handleStreamBizErrorType,
- callbacks: options?.callback,
- payload: {
- apiMode: 'responses',
- model: usageModel,
- pricing: await getModelPricing(usageModel, this.id, options?.pricingContext),
- provider: this.id,
- reasoningSignatureScope,
- },
- };
-
- if (isStreaming) {
- log('processing streaming Responses API response');
- let prod = response as
- | ReadableStream<OpenAI.Responses.ResponseStreamEvent>
- | Stream<OpenAI.Responses.ResponseStreamEvent>;
-
- if (debugParams?.responses?.()) {
- const [productionStream, useForDebug] = prod.tee();
- prod = productionStream;
- const useForDebugStream =
- useForDebug instanceof ReadableStream ? useForDebug : useForDebug.toReadableStream();
-
- debugStream(useForDebugStream).catch(console.error);
- }
-
- if (providerResponseDiagnostics) {
- /** Observe provider-native events before the Responses protocol adapter transforms them. */
- const observedStream = observeOpenAIResponsesStream(
- prod,
- providerResponseDiagnostics,
- options?.signal,
- );
- prod =
- observedStream instanceof ReadableStream
- ? observedStream
- : readableFromAsyncIterable(observedStream, {
- model: usageModel,
- provider: this.id,
- });
- }
-
- return StreamingResponse(OpenAIResponsesStream(prod, { ...streamOptions, inputStartAt }), {
- headers: options?.headers,
- });
- }
-
- log('processing non-streaming Responses API response');
-
- // Handle non-streaming response
- if (debugParams?.responses?.()) {
- debugResponse(response);
- }
-
- await recordOpenAIResponsesResponse(
- providerResponseDiagnostics,
- response as OpenAI.Responses.Response,
- options?.signal,
- );
-
- if (responseMode === 'json') {
- log('returning JSON response mode');
- return Response.json(response);
- }
-
- log('transforming non-streaming Responses API response to stream');
- const stream = transformResponseAPIToStream(response as OpenAI.Responses.Response);
-
- return StreamingResponse(
- OpenAIResponsesStream(stream, { ...streamOptions, enableStreaming: false, inputStartAt }),
- {
- headers: options?.headers,
- },
- );
- }
-
- private async generateObjectWithTools(
- payload: GenerateObjectPayload,
- options?: GenerateObjectOptions,
- usagePayload?: ChatPayloadForTransformStream,
- ) {
- const { messages, model, tools, responseApi } = payload;
- const log = debug(`${this.logPrefix}:generateObject`);
-
- log(
- 'generateObjectWithTools called with model: %s, toolsCount: %d',
- model,
- tools?.length || 0,
- );
-
- // Factory-level Responses API routing control (supports instance override)
- const instanceGenerateObject = ((this._options as any).generateObject || {}) as {
- useResponse?: boolean;
- useResponseModels?: Array<string | RegExp>;
- };
- const flagUseResponse =
- instanceGenerateObject.useResponse ??
- (generateObjectConfig ? generateObjectConfig.useResponse : undefined);
- const flagUseResponseModels =
- instanceGenerateObject.useResponseModels ?? generateObjectConfig?.useResponseModels;
-
- const shouldUseResponses = this.shouldUseResponsesAPI({
- context: 'tool calling',
- flagUseResponse,
- flagUseResponseModels,
- model,
- responseApi,
- });
- const requestModel = this.getMappedModelId(payload.model);
-
- if (shouldUseResponses) {
- log('calling responses.create for tool calling');
- const reasoningSignatureScope = await this.getSignatureScope(
- requestModel,
- 'reasoning',
- 'responses',
- );
- const input = await convertOpenAIResponseInputs(messages as any, {
- forceImageBase64: chatCompletion?.forceImageBase64,
- forceVideoBase64: chatCompletion?.forceVideoBase64,
- provider: this.id,
- reasoningSignatureScope,
- strictToolPairing: true,
- });
-
- const preparedRequest = this.prepareResponsesRequest(
- {
- input,
- model,
- ...this.resolvePromptCacheKeyParams(model, options?.user),
- tool_choice: 'required',
- tools: tools!.map(convertChatCompletionToolToResponseTool),
- // Responses API replaced `user` with `safety_identifier`; some endpoints reject `user`
- safety_identifier: options?.user,
- } as any,
- payload.model,
- );
- const res = await this.client.responses.create(
- preparedRequest.payload as OpenAI.Responses.ResponseCreateParamsNonStreaming,
- {
- headers: preparedRequest.headers
- ? { ...options?.headers, ...preparedRequest.headers }
- : options?.headers,
- signal: options?.signal,
- },
- );
-
- if (res.usage) {
- await options?.onUsage?.(convertOpenAIResponseUsage(res.usage, usagePayload));
- }
-
- const functionCalls = res.output?.filter((item) => item.type === 'function_call');
-
- log('received %d function calls from Responses API', functionCalls?.length || 0);
-
- if (!functionCalls?.length) throw new StructuredOutputError('no tool calls returned');
- return functionCalls.map((item) => ({
- arguments: parseStructuredToolArguments(item.arguments),
- name: item.name,
- }));
- }
-
- log('calling chat.completions.create for tool calling');
- const msgs = await this.convertGenerateObjectMessages(payload);
-
- const res = await this.client.chat.completions.create(
- this.withMappedRequestModel(
- this.handleGenerateObjectPayload(payload, {
- ...getGenerateObjectReasoningParams(payload),
- messages: msgs,
- model,
- ...this.resolvePromptCacheKeyParams(model, options?.user),
- tool_choice: 'required',
- tools,
- user: options?.user,
- }),
- payload.model,
- ) as OpenAI.ChatCompletionCreateParamsNonStreaming,
- { headers: options?.headers, signal: options?.signal },
- );
-
- if (res.usage) {
- await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
- }
-
- const toolCalls = res.choices?.[0]?.message?.tool_calls;
- if (!toolCalls?.length) throw new StructuredOutputError('no tool calls returned');
-
- return toolCalls.map((item) => {
- if (!('function' in item) || !item.function) {
- throw new StructuredOutputError('function tool call required');
- }
- return {
- arguments: parseStructuredToolArguments(item.function.arguments),
- name: item.function.name,
- };
- });
+ return mapOpenAICompatibleError(this.context, factory, error);
}
};
};
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/jsonResponseMode.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/jsonResponseMode.test.ts
index cccecc0db00..8fe69ab6dfc 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/jsonResponseMode.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/jsonResponseMode.test.ts
@@ -2,9 +2,9 @@
import type OpenAI from 'openai';
import { describe, expect, it, vi } from 'vitest';
+import { transformResponseToStream } from '../protocols/openaiChatCompletions/nonStreamToStream';
import type { OnFinishData } from '../streams/protocol';
import { createOpenAICompatibleRuntime } from './index';
-import { transformResponseToStream } from './nonStreamToStream';
vi.mock('@lobechat/business-model-bank/model-config', () => ({
loadModels: vi.fn().mockResolvedValue([]),
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/models.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/models.ts
new file mode 100644
index 00000000000..15865163bf8
--- /dev/null
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/models.ts
@@ -0,0 +1,90 @@
+import type { ChatModelCard } from '@lobechat/types';
+import dayjs from 'dayjs';
+import utc from 'dayjs/plugin/utc';
+import debug from 'debug';
+import type { AiModelType } from 'model-bank';
+import { LOBE_DEFAULT_MODEL_LIST } from 'model-bank';
+
+import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';
+import { postProcessModelList } from '../../utils/postProcessModelList';
+import type { OpenAICompatibleRuntimeContext } from './context';
+import type { OpenAICompatibleFactoryOptions } from './factoryOptions';
+
+// the model contains the following keywords is not a chat model, so we should filter them out
+export const CHAT_MODELS_BLOCK_LIST = [
+ 'embedding',
+ 'davinci',
+ 'curie',
+ 'moderation',
+ 'ada',
+ 'babbage',
+ 'tts',
+ 'whisper',
+ 'dall-e',
+];
+
+export const listOpenAICompatibleModels = async (
+ runtime: OpenAICompatibleRuntimeContext,
+ factory: OpenAICompatibleFactoryOptions,
+) => {
+ const { models } = factory;
+ const log = debug(`${runtime.logPrefix}:models`);
+ log('fetching available models');
+
+ let resultModels: ChatModelCard[];
+ if (typeof models === 'function') {
+ log('using custom models function');
+ resultModels = await models({ client: runtime.client, options: runtime._options });
+ } else {
+ log('fetching models from client API');
+ const list = await runtime.client.models.list();
+ resultModels = list.data
+ .filter((model) => {
+ return CHAT_MODELS_BLOCK_LIST.every((keyword) => !model.id.toLowerCase().includes(keyword));
+ })
+ .map((item) => {
+ if (models?.transformModel) {
+ return models.transformModel(item);
+ }
+
+ const toReleasedAt = () => {
+ if (!item.created) return;
+ dayjs.extend(utc);
+
+ // guarantee item.created in Date String format
+ if (
+ typeof (item.created as any) === 'string' ||
+ // or in milliseconds
+ item.created.toFixed(0).length === 13
+ ) {
+ return dayjs.utc(item.created).format('YYYY-MM-DD');
+ }
+
+ // by default, the created time is in seconds
+ return dayjs.utc(item.created * 1000).format('YYYY-MM-DD');
+ };
+
+ // TODO: should refactor after remove v1 user/modelList code
+ const knownModel = LOBE_DEFAULT_MODEL_LIST.find((model) => model.id === item.id);
+
+ if (knownModel) {
+ const releasedAt = knownModel.releasedAt ?? toReleasedAt();
+
+ return { ...knownModel, releasedAt };
+ }
+
+ return {
+ id: item.id,
+ releasedAt: toReleasedAt(),
+ };
+ })
+
+ .filter(Boolean) as ChatModelCard[];
+ }
+
+ log('fetched %d models', resultModels.length);
+
+ return await postProcessModelList(resultModels, (modelId) =>
+ getModelPropertyWithFallback<AiModelType>(modelId, 'type'),
+ );
+};
diff --git a/packages/model-runtime/src/core/protocols/openaiChatCompletions/chat.ts b/packages/model-runtime/src/core/protocols/openaiChatCompletions/chat.ts
new file mode 100644
index 00000000000..b71656f93dc
--- /dev/null
+++ b/packages/model-runtime/src/core/protocols/openaiChatCompletions/chat.ts
@@ -0,0 +1,256 @@
+import type debug from 'debug';
+import type OpenAI from 'openai';
+import type { Stream } from 'openai/streaming';
+
+import type { ChatMethodOptions, ChatStreamPayload } from '../../../types';
+import { respondJsonAfterStream } from '../../../utils/consumeStream';
+import { debugPayload, debugResponse, debugStream } from '../../../utils/debugStream';
+import { desensitizeUrl } from '../../../utils/desensitizeUrl';
+import { getModelPricing } from '../../../utils/getModelPricing';
+import { StreamingResponse } from '../../../utils/response';
+import type { OpenAICompatibleRuntimeContext } from '../../openaiCompatibleFactory/context';
+import type { OpenAICompatibleFactoryOptions } from '../../openaiCompatibleFactory/factoryOptions';
+import {
+ initializeOpenAIDiagnostics,
+ observeOpenAIChatCompletionStream,
+ recordOpenAIChatCompletionResponse,
+ recordOpenAIResponseMetadata,
+ resolveOpenAIResponseWithMetadata,
+} from '../../openaiCompatibleFactory/providerDiagnostics';
+import { resolveModelSamplingParameters } from '../../parameterResolver';
+import { readableFromAsyncIterable } from '../../streams/protocol';
+import { convertOpenAIMessages } from './messages';
+import { transformResponseToStream } from './nonStreamToStream';
+import type { OpenAIStreamOptions } from './stream';
+import { OpenAIStream } from './stream';
+
+export interface ChatCompletionsRequest {
+ handledPayload: OpenAI.ChatCompletionCreateParamsStreaming;
+ inputStartAt: number;
+ log: debug.Debugger;
+ options?: ChatMethodOptions;
+ payload: Omit<ChatStreamPayload, 'responseMode'>;
+ /** The payload before `chatCompletion.handlePayload`, used by custom stream clients. */
+ processedPayload: any;
+ responseMode?: ChatStreamPayload['responseMode'];
+}
+
+export const chatViaChatCompletions = async (
+ runtime: OpenAICompatibleRuntimeContext,
+ factory: OpenAICompatibleFactoryOptions,
+ {
+ handledPayload,
+ inputStartAt,
+ log,
+ options,
+ payload,
+ processedPayload,
+ responseMode,
+ }: ChatCompletionsRequest,
+): Promise<Response> => {
+ // Sanitize temperature/top_p conflict for Claude 4+ models routed via OpenAI-compatible API.
+ // normalizeTemperature is false here because OpenAI-compatible providers use the raw range.
+ const postPayload = {
+ ...handledPayload,
+ ...resolveModelSamplingParameters(handledPayload.model, handledPayload, {
+ normalizeTemperature: false,
+ preferTemperature: true,
+ }),
+ };
+
+ const requestModel =
+ runtime.withMappedRequestModel({ model: postPayload.model }, payload.model).model ??
+ payload.model;
+ const thoughtSignatureScope = await runtime.getSignatureScope(
+ requestModel,
+ 'thought_signature',
+ 'chat_completions',
+ );
+ const messages = await convertOpenAIMessages(postPayload.messages, {
+ forceImageBase64: factory.chatCompletion?.forceImageBase64,
+ forceVideoBase64: factory.chatCompletion?.forceVideoBase64,
+ model: postPayload.model,
+ supportsAudioInput: factory.chatCompletion?.supportsAudioInput,
+ thoughtSignatureScope,
+ });
+ const includeUsageRequested = Boolean(
+ postPayload.stream && !factory.chatCompletion?.excludeUsage,
+ );
+
+ let response:
+ | OpenAI.ChatCompletion
+ | ReadableStream<OpenAI.Chat.Completions.ChatCompletionChunk>
+ | Stream<OpenAI.Chat.Completions.ChatCompletionChunk>;
+ let providerResponseDiagnostics;
+
+ const streamOptions: OpenAIStreamOptions = {
+ bizErrorTypeTransformer: factory.chatCompletion?.handleStreamBizErrorType,
+ callbacks: options?.callback,
+ payload: {
+ apiMode: 'chat_completions',
+ includeUsageRequested,
+ model: payload.model,
+ pricing: await getModelPricing(payload.model, runtime.id, options?.pricingContext),
+ provider: runtime.id,
+ thoughtSignatureScope,
+ },
+ };
+
+ if (factory.customClient?.createChatCompletionStream) {
+ log('using custom client for chat completion stream');
+ // Apply sampling sanitization to processedPayload for the custom client path.
+ // We use processedPayload (ChatStreamPayload type) here because
+ // createChatCompletionStream expects ChatStreamPayload, not the OpenAI SDK format.
+ // Strip LobeHub-internal fields that should never reach downstream APIs.
+ const {
+ apiMode: _apiMode,
+ preserveThinking: _preserveThinking,
+ ...cleanProcessedPayload
+ } = processedPayload as any;
+ const customRequestPayload = {
+ ...cleanProcessedPayload,
+ ...resolveModelSamplingParameters(cleanProcessedPayload.model, cleanProcessedPayload, {
+ normalizeTemperature: false,
+ preferTemperature: true,
+ }),
+ };
+ const requestPayload = runtime.withMappedRequestModel(customRequestPayload, payload.model);
+ providerResponseDiagnostics = initializeOpenAIDiagnostics({
+ apiMode: 'chat_completions',
+ diagnostics: options?.diagnostics,
+ endpoint: desensitizeUrl(runtime.baseURL),
+ payload: requestPayload,
+ sentAt: Date.now(),
+ });
+
+ response = factory.customClient.createChatCompletionStream(
+ runtime.client,
+ requestPayload,
+ runtime.instance,
+ ) as any;
+ recordOpenAIResponseMetadata(providerResponseDiagnostics, {});
+ } else {
+ // Remove LobeHub-internal fields before sending to downstream API.
+ // `preserveThinking` is only consumed by Qwen/Zhipu handlePayload (which runs above)
+ // and must not leak to other providers' APIs as an unknown parameter.
+ const { apiMode: _, preserveThinking: _pt, ...cleanedPayload } = postPayload as any;
+ const finalPayload = {
+ ...cleanedPayload,
+ messages,
+ ...(factory.chatCompletion?.noUserId ? {} : { user: options?.user }),
+ ...runtime.resolvePromptCacheKeyParams(
+ cleanedPayload.model,
+ options?.user,
+ cleanedPayload.prompt_cache_key,
+ ),
+ stream_options: includeUsageRequested ? { include_usage: true } : undefined,
+ };
+ const requestPayload = runtime.withMappedRequestModel(finalPayload, payload.model);
+
+ log('sending chat completion request with %d messages', messages.length);
+
+ if (factory.debug?.chatCompletion?.()) {
+ debugPayload(requestPayload);
+ }
+
+ providerResponseDiagnostics = initializeOpenAIDiagnostics({
+ apiMode: 'chat_completions',
+ diagnostics: options?.diagnostics,
+ endpoint: desensitizeUrl(runtime.baseURL),
+ payload: requestPayload,
+ sentAt: Date.now(),
+ });
+ const responsePromise = runtime.client.chat.completions.create(requestPayload, {
+ // https://github.com/lobehub/lobe-chat/pull/318
+ headers: { Accept: '*/*', ...options?.requestHeaders },
+ signal: options?.signal,
+ });
+ const responseWithMetadata = await resolveOpenAIResponseWithMetadata(responsePromise);
+ response = responseWithMetadata.data as
+ OpenAI.ChatCompletion | Stream<OpenAI.Chat.Completions.ChatCompletionChunk>;
+ recordOpenAIResponseMetadata(providerResponseDiagnostics, {
+ requestId: responseWithMetadata.request_id,
+ response: responseWithMetadata.response,
+ });
+ }
+
+ if (postPayload.stream) {
+ log('processing streaming response');
+ let prod = response as
+ | ReadableStream<OpenAI.Chat.Completions.ChatCompletionChunk>
+ | Stream<OpenAI.Chat.Completions.ChatCompletionChunk>;
+
+ if (factory.debug?.chatCompletion?.()) {
+ const [productionStream, useForDebug] = prod.tee();
+ prod = productionStream;
+ const useForDebugStream =
+ useForDebug instanceof ReadableStream ? useForDebug : useForDebug.toReadableStream();
+
+ debugStream(useForDebugStream).catch(console.error);
+ }
+
+ if (providerResponseDiagnostics) {
+ /** Observe provider-native chunks before the OpenAI protocol adapter transforms them. */
+ const observedStream = observeOpenAIChatCompletionStream(
+ prod,
+ providerResponseDiagnostics,
+ options?.signal,
+ );
+ prod =
+ observedStream instanceof ReadableStream
+ ? observedStream
+ : readableFromAsyncIterable(observedStream, {
+ model: payload.model,
+ provider: runtime.id,
+ });
+ }
+
+ return StreamingResponse(
+ factory.chatCompletion?.handleStream
+ ? factory.chatCompletion.handleStream(prod, {
+ callbacks: streamOptions.callbacks,
+ inputStartAt,
+ payload: streamOptions.payload,
+ })
+ : OpenAIStream(prod, {
+ ...streamOptions,
+ inputStartAt,
+ }),
+ {
+ headers: options?.headers,
+ },
+ );
+ }
+
+ if (factory.debug?.chatCompletion?.()) {
+ debugResponse(response);
+ }
+
+ await recordOpenAIChatCompletionResponse(
+ providerResponseDiagnostics,
+ response as OpenAI.ChatCompletion,
+ options?.signal,
+ );
+
+ log('transforming non-streaming response to stream');
+ // Snapshot first: provider transform handlers may rewrite the completion in place
+ const jsonBody = responseMode === 'json' ? structuredClone(response) : undefined;
+ const transformHandler =
+ factory.chatCompletion?.handleTransformResponseToStream || transformResponseToStream;
+ const stream = transformHandler(response as unknown as OpenAI.ChatCompletion);
+
+ const streamingResponse = StreamingResponse(
+ factory.chatCompletion?.handleStream
+ ? factory.chatCompletion.handleStream(stream, {
+ callbacks: streamOptions.callbacks,
+ inputStartAt,
+ payload: streamOptions.payload,
+ })
+ : OpenAIStream(stream, { ...streamOptions, enableStreaming: false, inputStartAt }),
+ {
+ headers: options?.headers,
+ },
+ );
+ if (jsonBody) return await respondJsonAfterStream(streamingResponse, jsonBody);
+ return streamingResponse;
+};
diff --git a/packages/model-runtime/src/core/protocols/openaiChatCompletions/generateObject.ts b/packages/model-runtime/src/core/protocols/openaiChatCompletions/generateObject.ts
new file mode 100644
index 00000000000..0648fa4ace3
--- /dev/null
+++ b/packages/model-runtime/src/core/protocols/openaiChatCompletions/generateObject.ts
@@ -0,0 +1,236 @@
+import type { Debugger } from 'debug';
+import type OpenAI from 'openai';
+
+import type {
+ ChatCompletionTool,
+ GenerateObjectOptions,
+ GenerateObjectPayload,
+ GenerateObjectSchema,
+} from '../../../types';
+import type { OpenAICompatibleRuntimeContext } from '../../openaiCompatibleFactory/context';
+import type {
+ ChatCompletionCreateParamsWithPromptCacheKey,
+ OpenAICompatibleFactoryOptions,
+} from '../../openaiCompatibleFactory/factoryOptions';
+import {
+ parseStructuredOutputText,
+ parseStructuredToolArguments,
+ StructuredOutputError,
+} from '../../openaiCompatibleFactory/structuredOutput';
+import type { ChatPayloadForTransformStream } from '../../streams/protocol';
+import { convertOpenAIUsage } from '../../usageConverters/openai';
+import { convertOpenAIMessages } from './messages';
+
+type Runtime = OpenAICompatibleRuntimeContext;
+type Factory = OpenAICompatibleFactoryOptions;
+
+type GenerateObjectReasoningParams = Pick<GenerateObjectPayload, 'reasoning_effort' | 'thinking'>;
+export const getGenerateObjectReasoningParams = ({
+ reasoning_effort,
+ thinking,
+}: GenerateObjectReasoningParams) =>
+ reasoning_effort && thinking?.type !== 'disabled' ? { reasoning_effort } : {};
+
+/**
+ * Detect provider 400/422 errors that reject `response_format: { type: 'json_schema' }`.
+ * Known message variants from the DeepSeek family (official API and gateways proxying it):
+ * - `This response_format type is unavailable now`
+ * - `response_format.type \`json_schema\` is unavailable now`
+ */
+export const isResponseFormatUnsupportedError = (error: unknown): boolean => {
+ const err = error as { error?: { message?: unknown }; message?: unknown };
+ const message = [err?.message, err?.error?.message]
+ .filter((value): value is string => typeof value === 'string')
+ .join('\n');
+ if (!message) return false;
+
+ return /(?:response_format|json_schema)[^]*?(?:unavailable|not +support)/i.test(message);
+};
+
+const convertGenerateObjectMessages = async (
+ runtime: Runtime,
+ factory: Factory,
+ { messages, model }: GenerateObjectPayload,
+) => {
+ return convertOpenAIMessages(messages as any, {
+ forceImageBase64: factory.chatCompletion?.forceImageBase64,
+ forceVideoBase64: factory.chatCompletion?.forceVideoBase64,
+ model,
+ thoughtSignatureScope: await runtime.getSignatureScope(
+ runtime.getMappedModelId(model),
+ 'thought_signature',
+ 'chat_completions',
+ ),
+ });
+};
+
+const handleGenerateObjectPayload = (
+ runtime: Runtime,
+ factory: Factory,
+ payload: GenerateObjectPayload,
+ requestPayload: ChatCompletionCreateParamsWithPromptCacheKey,
+) => {
+ return factory.generateObject?.handlePayload
+ ? factory.generateObject.handlePayload(payload, requestPayload, runtime._options)
+ : requestPayload;
+};
+
+/**
+ * Simulate schema-based structured output through a forced tool call, for
+ * providers that do not support `response_format: { type: 'json_schema' }`.
+ * Returns the parsed schema object — the same shape as the json_schema path.
+ */
+export const generateObjectViaToolCalling = async (
+ runtime: Runtime,
+ factory: Factory,
+ payload: GenerateObjectPayload,
+ options: GenerateObjectOptions | undefined,
+ usagePayload: ChatPayloadForTransformStream,
+) => {
+ const { schema, model } = payload;
+
+ // Apply schema transformation if configured
+ const processedSchema = factory.generateObject?.handleSchema
+ ? { ...schema!, schema: factory.generateObject.handleSchema(schema!.schema) }
+ : schema!;
+
+ const tool: ChatCompletionTool = {
+ function: {
+ description:
+ processedSchema.description ||
+ 'Generate structured output according to the provided schema',
+ name: processedSchema.name || 'structured_output',
+ parameters: processedSchema.schema,
+ },
+ type: 'function',
+ };
+
+ const res = await runtime.client.chat.completions.create(
+ runtime.withMappedRequestModel(
+ handleGenerateObjectPayload(runtime, factory, payload, {
+ ...getGenerateObjectReasoningParams(payload),
+ messages: await convertGenerateObjectMessages(runtime, factory, payload),
+ model,
+ ...runtime.resolvePromptCacheKeyParams(model, options?.user),
+ tool_choice: { function: { name: tool.function.name }, type: 'function' },
+ tools: [tool],
+ user: options?.user,
+ }),
+ payload.model,
+ ) as OpenAI.ChatCompletionCreateParamsNonStreaming,
+ { headers: options?.headers, signal: options?.signal },
+ );
+
+ if (res.usage) {
+ await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
+ }
+
+ // Structural type keeps this compatible across openai SDK majors (v6
+ // widened tool_calls to a function/custom union).
+ const toolCalls = res.choices?.[0]?.message?.tool_calls as
+ { function?: { arguments: string; name: string } }[] | undefined;
+ const toolCall =
+ toolCalls?.find((item) => item.function?.name === tool.function.name) ?? toolCalls?.[0];
+
+ if (!toolCall?.function) throw new StructuredOutputError('no tool calls returned');
+
+ return parseStructuredToolArguments(toolCall.function.arguments);
+};
+
+/** Structured output through `response_format: { type: 'json_schema' }`. */
+export const generateObjectViaJsonSchema = async (
+ runtime: Runtime,
+ factory: Factory,
+ payload: GenerateObjectPayload,
+ processedSchema: GenerateObjectSchema,
+ options: GenerateObjectOptions | undefined,
+ usagePayload: ChatPayloadForTransformStream,
+ log: Debugger,
+) => {
+ const { model } = payload;
+
+ log('calling chat.completions.create for structured output');
+ let res: OpenAI.ChatCompletion;
+ try {
+ res = await runtime.client.chat.completions.create(
+ runtime.withMappedRequestModel(
+ handleGenerateObjectPayload(runtime, factory, payload, {
+ ...getGenerateObjectReasoningParams(payload),
+ messages: await convertGenerateObjectMessages(runtime, factory, payload),
+ model,
+ response_format: { json_schema: processedSchema, type: 'json_schema' },
+ ...runtime.resolvePromptCacheKeyParams(model, options?.user),
+ user: options?.user,
+ }),
+ model,
+ ) as OpenAI.ChatCompletionCreateParamsNonStreaming,
+ { headers: options?.headers, signal: options?.signal },
+ );
+ } catch (error) {
+ // Gateways can serve json_schema-incapable upstreams under arbitrary
+ // model ids (e.g. OpenCode Zen's `big-pickle` proxies DeepSeek), which
+ // the model-id detection above cannot catch. Retry once via forced
+ // tool calling when the upstream rejects the response_format type.
+ if (!isResponseFormatUnsupportedError(error)) throw error;
+
+ log('provider rejected json_schema response_format, retrying via tool calling');
+ return await generateObjectViaToolCalling(runtime, factory, payload, options, usagePayload);
+ }
+ if (res.usage) {
+ await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
+ }
+
+ const text = res.choices?.[0]?.message?.content;
+
+ log('received structured output from Chat Completions API, length: %d', text?.length || 0);
+
+ return parseStructuredOutputText(text);
+};
+
+/** Force the model to call one of `payload.tools` and return the parsed calls. */
+export const generateToolCallsViaChatCompletions = async (
+ runtime: Runtime,
+ factory: Factory,
+ payload: GenerateObjectPayload,
+ options: GenerateObjectOptions | undefined,
+ usagePayload: ChatPayloadForTransformStream | undefined,
+ log: Debugger,
+) => {
+ const { model, tools } = payload;
+
+ log('calling chat.completions.create for tool calling');
+ const msgs = await convertGenerateObjectMessages(runtime, factory, payload);
+
+ const res = await runtime.client.chat.completions.create(
+ runtime.withMappedRequestModel(
+ handleGenerateObjectPayload(runtime, factory, payload, {
+ ...getGenerateObjectReasoningParams(payload),
+ messages: msgs,
+ model,
+ ...runtime.resolvePromptCacheKeyParams(model, options?.user),
+ tool_choice: 'required',
+ tools,
+ user: options?.user,
+ }),
+ payload.model,
+ ) as OpenAI.ChatCompletionCreateParamsNonStreaming,
+ { headers: options?.headers, signal: options?.signal },
+ );
+
+ if (res.usage) {
+ await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
+ }
+
+ const toolCalls = res.choices?.[0]?.message?.tool_calls;
+ if (!toolCalls?.length) throw new StructuredOutputError('no tool calls returned');
+
+ return toolCalls.map((item) => {
+ if (!('function' in item) || !item.function) {
+ throw new StructuredOutputError('function tool call required');
+ }
+ return {
+ arguments: parseStructuredToolArguments(item.function.arguments),
+ name: item.function.name,
+ };
+ });
+};
diff --git a/packages/model-runtime/src/core/contextBuilders/openai.emptyTextParts.test.ts b/packages/model-runtime/src/core/protocols/openaiChatCompletions/messages.emptyTextParts.test.ts
similarity index 98%
rename from packages/model-runtime/src/core/contextBuilders/openai.emptyTextParts.test.ts
rename to packages/model-runtime/src/core/protocols/openaiChatCompletions/messages.emptyTextParts.test.ts
index 4c14a8f1bf0..96f75ad5f75 100644
--- a/packages/model-runtime/src/core/contextBuilders/openai.emptyTextParts.test.ts
+++ b/packages/model-runtime/src/core/protocols/openaiChatCompletions/messages.emptyTextParts.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { convertOpenAIMessages } from './openai';
+import { convertOpenAIMessages } from './messages';
/**
* Moonshot (official API and Novita) rejects `{ type: 'text', text: '' }` with 400
diff --git a/packages/model-runtime/src/core/protocols/openaiChatCompletions/messages.test.ts b/packages/model-runtime/src/core/protocols/openaiChatCompletions/messages.test.ts
new file mode 100644
index 00000000000..33dc3f3c724
--- /dev/null
+++ b/packages/model-runtime/src/core/protocols/openaiChatCompletions/messages.test.ts
@@ -0,0 +1,455 @@
+import type OpenAI from 'openai';
+import { describe, expect, it, vi } from 'vitest';
+
+import { imageUrlToBase64 } from '../../../utils/imageToBase64';
+import { serializeScopedSignature, type SignatureScope } from '../../../utils/signatureScope';
+import { parseDataUri } from '../../../utils/uriParser';
+import { convertOpenAIMessages } from './messages';
+
+// 模拟依赖
+vi.mock('../../../utils/imageToBase64', () => ({
+ imageUrlToBase64: vi.fn(),
+}));
+vi.mock('../../../utils/videoToBase64', () => ({
+ videoUrlToBase64: vi.fn(),
+}));
+vi.mock('../../../utils/uriParser');
+
+describe('convertOpenAIMessages', () => {
+ it('should restore thoughtSignature only for the exact scope', async () => {
+ const scope: SignatureScope = { fingerprint: 'a'.repeat(32) };
+ const foreignScope: SignatureScope = { fingerprint: 'b'.repeat(32) };
+ const thoughtSignature = serializeScopedSignature(
+ 'google-signature',
+ scope,
+ 'thought_signature',
+ );
+ const messages = [
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: { arguments: '{}', name: 'get_weather' },
+ id: 'call_1',
+ thoughtSignature,
+ type: 'function',
+ },
+ ],
+ },
+ ] as any;
+
+ const matching = await convertOpenAIMessages(messages, { thoughtSignatureScope: scope });
+ const mismatching = await convertOpenAIMessages(messages, {
+ thoughtSignatureScope: foreignScope,
+ });
+ const legacy = await convertOpenAIMessages(
+ [
+ {
+ ...messages[0],
+ tool_calls: [{ ...messages[0].tool_calls[0], thoughtSignature: 'legacy-signature' }],
+ },
+ ],
+ { thoughtSignatureScope: scope },
+ );
+
+ expect((matching[0] as any).tool_calls[0].thoughtSignature).toBe('google-signature');
+ expect((mismatching[0] as any).tool_calls[0].thoughtSignature).toBeUndefined();
+ expect((legacy[0] as any).tool_calls[0].thoughtSignature).toBeUndefined();
+ });
+
+ it('should convert string content messages', async () => {
+ const messages = [
+ { role: 'user', content: 'Hello' },
+ { role: 'assistant', content: 'Hi there' },
+ ] as OpenAI.ChatCompletionMessageParam[];
+
+ const result = await convertOpenAIMessages(messages);
+
+ expect(result).toEqual(messages);
+ });
+
+ it('should convert array content messages', async () => {
+ const messages = [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Hello' },
+ { type: 'image_url', image_url: { url: 'https://example.com/image.jpg' } },
+ ],
+ },
+ ] as OpenAI.ChatCompletionMessageParam[];
+
+ vi.spyOn(Promise, 'all');
+ vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
+ vi.mocked(imageUrlToBase64).mockResolvedValue({
+ base64: 'base64String',
+ mimeType: 'image/jpeg',
+ });
+
+ process.env.LLM_VISION_IMAGE_USE_BASE64 = '1';
+
+ const result = await convertOpenAIMessages(messages);
+
+ expect(result).toEqual([
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Hello' },
+ {
+ type: 'image_url',
+ image_url: { url: 'data:image/jpeg;base64,base64String' },
+ },
+ ],
+ },
+ ]);
+
+ expect(Promise.all).toHaveBeenCalledTimes(2); // 一次用于消息数组,一次用于内容数组
+
+ process.env.LLM_VISION_IMAGE_USE_BASE64 = undefined;
+ });
+ it('should convert array content messages', async () => {
+ const messages = [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Hello' },
+ { type: 'image_url', image_url: { url: 'https://example.com/image.jpg' } },
+ ],
+ },
+ ] as OpenAI.ChatCompletionMessageParam[];
+
+ vi.spyOn(Promise, 'all');
+ vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
+ vi.mocked(imageUrlToBase64).mockResolvedValue({
+ base64: 'base64String',
+ mimeType: 'image/jpeg',
+ });
+
+ const result = await convertOpenAIMessages(messages);
+
+ expect(result).toEqual(messages);
+
+ expect(Promise.all).toHaveBeenCalledTimes(2); // 一次用于消息数组,一次用于内容数组
+ });
+
+ it('should filter out reasoning field from messages', async () => {
+ const messages = [
+ {
+ role: 'assistant',
+ content: 'Hello',
+ reasoning: { content: 'some reasoning', duration: 100 },
+ },
+ { role: 'user', content: 'Hi' },
+ ] as any;
+
+ const result = await convertOpenAIMessages(messages);
+
+ expect(result).toEqual([
+ { role: 'assistant', content: 'Hello' },
+ { role: 'user', content: 'Hi' },
+ ]);
+ // Ensure reasoning field is removed
+ expect((result[0] as any).reasoning).toBeUndefined();
+ });
+
+ describe('reasoning passback for thinking families', () => {
+ // Upstream rejects a thinking-mode turn that carries tool_calls without the
+ // historical reasoning: "If thinking mode and tool_calls, `reasoning_content`
+ // must be passed back to the API."
+ const assistantTurn = {
+ content: 'Calling a tool',
+ reasoning: { content: 'step-by-step thinking' },
+ role: 'assistant',
+ tool_calls: [
+ { function: { arguments: '{}', name: 'search' }, id: 'call-1', type: 'function' },
+ ],
+ } as any;
+
+ it.each([['deepseek-v4-pro'], ['glm-5.3'], ['kimi-k3']])(
+ 'echoes structured reasoning back for %s',
+ async (model) => {
+ const result = await convertOpenAIMessages([assistantTurn], { model });
+
+ expect((result[0] as any).reasoning_content).toBe('step-by-step thinking');
+ },
+ );
+
+ it('leaves unrelated models untouched', async () => {
+ const result = await convertOpenAIMessages([assistantTurn], { model: 'gpt-5.6-sol' });
+
+ expect((result[0] as any).reasoning_content).toBeUndefined();
+ });
+
+ it('keeps the empty placeholder scoped to DeepSeek thinking models', async () => {
+ const withoutReasoning = { ...assistantTurn, reasoning: undefined };
+
+ const deepseek = await convertOpenAIMessages([withoutReasoning], {
+ model: 'deepseek-v4-pro',
+ });
+ const glm = await convertOpenAIMessages([withoutReasoning], { model: 'glm-5.3' });
+
+ expect((deepseek[0] as any).reasoning_content).toBe('');
+ expect((glm[0] as any).reasoning_content).toBeUndefined();
+ });
+ });
+
+ it('should preserve reasoning_content field from messages (for DeepSeek compatibility)', async () => {
+ const messages = [
+ {
+ role: 'assistant',
+ content: 'Hello',
+ reasoning_content: 'some reasoning content',
+ },
+ { role: 'user', content: 'Hi' },
+ ] as any;
+
+ const result = await convertOpenAIMessages(messages);
+
+ expect(result).toEqual([
+ { role: 'assistant', content: 'Hello', reasoning_content: 'some reasoning content' },
+ { role: 'user', content: 'Hi' },
+ ]);
+ // Ensure reasoning_content field is preserved
+ expect((result[0] as any).reasoning_content).toBe('some reasoning content');
+ });
+
+ it('should filter internal thinking content parts but preserve reasoning_content', async () => {
+ const messages = [
+ {
+ role: 'assistant',
+ content: [
+ {
+ signature: 'sig_123',
+ thinking: 'internal reasoning',
+ type: 'thinking',
+ },
+ {
+ text: 'Visible answer',
+ type: 'text',
+ },
+ ],
+ reasoning_content: 'internal reasoning',
+ },
+ ] as any;
+
+ const result = await convertOpenAIMessages(messages);
+
+ expect(result).toEqual([
+ {
+ role: 'assistant',
+ content: [{ text: 'Visible answer', type: 'text' }],
+ reasoning_content: 'internal reasoning',
+ },
+ ]);
+ });
+
+ it('should filter out reasoning but preserve reasoning_content field', async () => {
+ const messages = [
+ {
+ role: 'assistant',
+ content: 'Hello',
+ reasoning: { content: 'some reasoning', duration: 100 },
+ reasoning_content: 'some reasoning content',
+ },
+ ] as any;
+
+ const result = await convertOpenAIMessages(messages);
+
+ expect(result).toEqual([
+ { role: 'assistant', content: 'Hello', reasoning_content: 'some reasoning content' },
+ ]);
+ // Ensure reasoning object is removed but reasoning_content is preserved
+ expect((result[0] as any).reasoning).toBeUndefined();
+ expect((result[0] as any).reasoning_content).toBe('some reasoning content');
+ });
+
+ describe('tool messages with image parts', () => {
+ it('should flatten the tool message to text and re-attach images as a user message', async () => {
+ vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
+
+ const messages = [
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ { id: 'call_1', type: 'function', function: { name: 'readFile', arguments: '{}' } },
+ ],
+ },
+ {
+ role: 'tool',
+ tool_call_id: 'call_1',
+ content: [
+ { type: 'text', text: '[Image: cat.png]' },
+ { type: 'image_url', image_url: { url: 'https://files.example.com/cat.png' } },
+ ],
+ },
+ { role: 'user', content: 'what do you see?' },
+ ] as OpenAI.ChatCompletionMessageParam[];
+
+ const result = await convertOpenAIMessages(messages);
+
+ expect(result).toEqual([
+ messages[0],
+ // Tool message content must be text-only for the OpenAI API.
+ { role: 'tool', tool_call_id: 'call_1', content: '[Image: cat.png]' },
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Image output of tool call call_1:' },
+ { type: 'image_url', image_url: { url: 'https://files.example.com/cat.png' } },
+ ],
+ },
+ { role: 'user', content: 'what do you see?' },
+ ]);
+ });
+
+ it('should keep the tool batch contiguous when multiple tool results carry images', async () => {
+ vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
+
+ const messages = [
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ { id: 'call_1', type: 'function', function: { name: 'readFile', arguments: '{}' } },
+ { id: 'call_2', type: 'function', function: { name: 'readFile', arguments: '{}' } },
+ ],
+ },
+ {
+ role: 'tool',
+ tool_call_id: 'call_1',
+ content: [{ type: 'image_url', image_url: { url: 'https://files.example.com/a.png' } }],
+ },
+ {
+ role: 'tool',
+ tool_call_id: 'call_2',
+ content: 'plain text result',
+ },
+ ] as OpenAI.ChatCompletionMessageParam[];
+
+ const result = await convertOpenAIMessages(messages);
+
+ // No user message may interleave between the tool results of one batch.
+ expect(result.map((m) => m.role)).toEqual(['assistant', 'tool', 'tool', 'user']);
+ expect(result[1]).toEqual({
+ role: 'tool',
+ tool_call_id: 'call_1',
+ content: '[Image output attached below]',
+ });
+ expect(result[2]).toEqual(messages[2]);
+ expect(result[3]).toEqual({
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Image output of tool call call_1:' },
+ { type: 'image_url', image_url: { url: 'https://files.example.com/a.png' } },
+ ],
+ });
+ });
+ });
+
+ describe('DeepSeek reasoning_content compatibility', () => {
+ it('should derive reasoning_content from reasoning.content for deepseek models', async () => {
+ const messages = [
+ {
+ role: 'assistant',
+ content: 'Answer with tool call',
+ reasoning: { content: 'planned tool invocation', duration: 100 },
+ tool_calls: [
+ { id: 'call_1', type: 'function', function: { name: 'search', arguments: '{}' } },
+ ],
+ },
+ ] as any;
+
+ const result = await convertOpenAIMessages(messages, { model: 'deepseek-v4-flash' });
+
+ expect((result[0] as any).reasoning_content).toBe('planned tool invocation');
+ expect((result[0] as any).tool_calls).toHaveLength(1);
+ expect((result[0] as any).reasoning).toBeUndefined();
+ });
+
+ it('should force empty reasoning_content for deepseek-v4 thinking-mode assistant messages without reasoning', async () => {
+ const messages = [
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ { id: 'call_1', type: 'function', function: { name: 'search', arguments: '{}' } },
+ ],
+ },
+ ] as any;
+
+ const result = await convertOpenAIMessages(messages, { model: 'deepseek-v4-pro' });
+
+ expect((result[0] as any).reasoning_content).toBe('');
+ });
+
+ it('should force empty reasoning_content for deepseek-reasoner', async () => {
+ const messages = [{ role: 'assistant', content: 'Hi' }] as any;
+
+ const result = await convertOpenAIMessages(messages, { model: 'deepseek-reasoner' });
+
+ expect((result[0] as any).reasoning_content).toBe('');
+ });
+
+ it('should match provider-prefixed deepseek model ids (e.g. Deepseek/deepseek-v4-pro)', async () => {
+ const messages = [{ role: 'assistant', content: 'Hi' }] as any;
+
+ const result = await convertOpenAIMessages(messages, {
+ model: 'Deepseek/deepseek-v4-pro',
+ });
+
+ expect((result[0] as any).reasoning_content).toBe('');
+ });
+
+ it('should not force reasoning_content for non-thinking deepseek models', async () => {
+ const messages = [{ role: 'assistant', content: 'Hi' }] as any;
+
+ const result = await convertOpenAIMessages(messages, { model: 'deepseek-chat' });
+
+ expect((result[0] as any).reasoning_content).toBeUndefined();
+ });
+
+ it('should leave non-deepseek models untouched', async () => {
+ const messages = [
+ {
+ role: 'assistant',
+ content: 'Hi',
+ reasoning: { content: 'unrelated', duration: 10 },
+ },
+ ] as any;
+
+ const result = await convertOpenAIMessages(messages, { model: 'gpt-4o-mini' });
+
+ expect((result[0] as any).reasoning_content).toBeUndefined();
+ expect((result[0] as any).reasoning).toBeUndefined();
+ });
+
+ it('should not touch non-assistant messages', async () => {
+ const messages = [
+ { role: 'user', content: 'hello' },
+ { role: 'tool', content: '{}', tool_call_id: 'call_1' },
+ ] as any;
+
+ const result = await convertOpenAIMessages(messages, { model: 'deepseek-v4-flash' });
+
+ expect((result[0] as any).reasoning_content).toBeUndefined();
+ expect((result[1] as any).reasoning_content).toBeUndefined();
+ });
+
+ it('should preserve existing reasoning_content over reasoning.content', async () => {
+ const messages = [
+ {
+ role: 'assistant',
+ content: 'Hi',
+ reasoning: { content: 'should be ignored', duration: 10 },
+ reasoning_content: 'kept',
+ },
+ ] as any;
+
+ const result = await convertOpenAIMessages(messages, { model: 'deepseek-v4-flash' });
+
+ expect((result[0] as any).reasoning_content).toBe('kept');
+ });
+ });
+});
diff --git a/packages/model-runtime/src/core/protocols/openaiChatCompletions/messages.ts b/packages/model-runtime/src/core/protocols/openaiChatCompletions/messages.ts
new file mode 100644
index 00000000000..6cfc0f3d247
--- /dev/null
+++ b/packages/model-runtime/src/core/protocols/openaiChatCompletions/messages.ts
@@ -0,0 +1,162 @@
+import type OpenAI from 'openai';
+
+import type { MessageToolCall } from '../../../types';
+import { isDeepSeekThinkingEligibleModel } from '../../../utils/modelParse';
+import { resolveScopedSignature } from '../../../utils/signatureScope';
+import {
+ type ConvertibleMessageContentPart,
+ convertMessageContent,
+ type ConvertMessageContentOptions,
+ filterOutgoingContentParts,
+ type OpenAICompatibleContentPart,
+} from '../../contextBuilders/openai';
+
+/**
+ * Model families whose thinking mode requires the historical `reasoning_content`
+ * to be echoed back when the assistant turn also carries `tool_calls`. Upstream
+ * rejects the request outright otherwise:
+ *
+ * > If thinking mode and tool_calls, `reasoning_content` must be passed back to the API.
+ *
+ * Matched on the model id rather than the provider because these models are
+ * mostly reached through OpenAI-compatible aggregators and user-configured
+ * proxies, where the provider key says nothing about the underlying family.
+ */
+const REASONING_PASSBACK_MODEL_KEYWORDS = ['deepseek', 'glm', 'kimi'] as const;
+
+const requiresReasoningPassback = (model: string | undefined) =>
+ typeof model === 'string' &&
+ REASONING_PASSBACK_MODEL_KEYWORDS.some((keyword) => model.toLowerCase().includes(keyword));
+
+/**
+ * OpenAI tool messages only accept text content — the Chat Completions API
+ * rejects `image_url` parts inside a `role: 'tool'` message. When a tool
+ * result carries images (e.g. builtin `readFile` on an image file), flatten
+ * the tool message to text and re-attach the images as a `user` message
+ * placed AFTER the contiguous tool-result batch: every tool message must
+ * directly follow the assistant message holding its `tool_calls`, so nothing
+ * may be interleaved inside the batch.
+ */
+const extractToolMessageImages = (
+ converted: OpenAI.ChatCompletionMessageParam[],
+): OpenAI.ChatCompletionMessageParam[] => {
+ const output: OpenAI.ChatCompletionMessageParam[] = [];
+ let pendingToolImages: { parts: OpenAI.ChatCompletionContentPart[]; toolCallId?: string }[] = [];
+
+ const flushToolImages = () => {
+ if (pendingToolImages.length === 0) return;
+
+ const content = pendingToolImages.flatMap((pending) => [
+ { text: `Image output of tool call ${pending.toolCallId}:`, type: 'text' as const },
+ ...pending.parts,
+ ]);
+ output.push({ content, role: 'user' });
+ pendingToolImages = [];
+ };
+
+ for (const message of converted) {
+ if (message.role !== 'tool') flushToolImages();
+
+ if (message.role === 'tool' && Array.isArray(message.content)) {
+ const parts = message.content as any[];
+ const imageParts = parts.filter((c) => c?.type === 'image_url' || c?.type === 'video_url');
+ const text = parts
+ .filter((c) => c?.type === 'text' && typeof c.text === 'string')
+ .map((c) => c.text)
+ .join('\n\n');
+
+ if (imageParts.length > 0) {
+ pendingToolImages.push({ parts: imageParts, toolCallId: message.tool_call_id });
+ }
+
+ output.push({
+ ...message,
+ content: text || (imageParts.length > 0 ? '[Image output attached below]' : ''),
+ });
+ continue;
+ }
+
+ output.push(message);
+ }
+
+ flushToolImages();
+
+ return output;
+};
+
+export const convertOpenAIMessages = async (
+ messages: OpenAI.ChatCompletionMessageParam[],
+ options?: ConvertMessageContentOptions,
+) => {
+ const converted = (await Promise.all(
+ messages.map(async (message) => {
+ const msg = message as any;
+
+ // Explicitly map only valid ChatCompletionMessageParam fields
+ // Exclude reasoning and reasoning_content fields as they should not be sent in requests
+ const parts =
+ typeof message.content === 'string'
+ ? message.content
+ : filterOutgoingContentParts(
+ msg,
+ (message.content || []) as OpenAICompatibleContentPart[],
+ );
+
+ const result: any = {
+ content: Array.isArray(parts)
+ ? await Promise.all(
+ parts.map((c) => convertMessageContent(c as ConvertibleMessageContentPart, options)),
+ )
+ : parts,
+ role: msg.role,
+ };
+
+ // Add optional fields if they exist
+ if (msg.name !== undefined) result.name = msg.name;
+ if (msg.tool_calls !== undefined) {
+ result.tool_calls = msg.tool_calls.map((toolCall: MessageToolCall) => {
+ if (!toolCall.thoughtSignature) return toolCall;
+
+ const { thoughtSignature, ...rest } = toolCall;
+ const resolvedSignature = resolveScopedSignature(
+ thoughtSignature,
+ options?.thoughtSignatureScope,
+ 'thought_signature',
+ );
+
+ return resolvedSignature ? { ...rest, thoughtSignature: resolvedSignature } : rest;
+ });
+ }
+ if (msg.tool_call_id !== undefined) result.tool_call_id = msg.tool_call_id;
+ if (msg.function_call !== undefined) result.function_call = msg.function_call;
+
+ // it's compatible for DeepSeek & Moonshot
+ if (msg.reasoning_content !== undefined) result.reasoning_content = msg.reasoning_content;
+ // MiniMax uses reasoning_details for historical thinking, so forward it unchanged
+ if (msg.reasoning_details !== undefined) result.reasoning_details = msg.reasoning_details;
+
+ // For passback-requiring families routed via any OpenAI-compatible runtime
+ // (including custom user providers that bypass a dedicated handlePayload),
+ // derive reasoning_content from the structured reasoning field on assistant
+ // messages.
+ if (msg.role === 'assistant' && requiresReasoningPassback(options?.model)) {
+ if (result.reasoning_content === undefined && typeof msg.reasoning?.content === 'string') {
+ result.reasoning_content = msg.reasoning.content;
+ }
+ // The empty placeholder stays DeepSeek-scoped. Echoing reasoning we
+ // actually have is what upstream asks for; fabricating an empty thinking
+ // block for a family we have not validated is a different, riskier change.
+ if (
+ result.reasoning_content === undefined &&
+ isDeepSeekThinkingEligibleModel(options?.model)
+ ) {
+ result.reasoning_content = '';
+ }
+ }
+
+ return result;
+ }),
+ )) as OpenAI.ChatCompletionMessageParam[];
+
+ return extractToolMessageImages(converted);
+};
diff --git a/packages/model-runtime/src/core/protocols/openaiChatCompletions/nonStreamToStream.test.ts b/packages/model-runtime/src/core/protocols/openaiChatCompletions/nonStreamToStream.test.ts
new file mode 100644
index 00000000000..7256aefef96
--- /dev/null
+++ b/packages/model-runtime/src/core/protocols/openaiChatCompletions/nonStreamToStream.test.ts
@@ -0,0 +1,361 @@
+// @vitest-environment node
+import type OpenAI from 'openai';
+import { describe, expect, it } from 'vitest';
+
+import { 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([]);
+ });
+ });
+});
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts b/packages/model-runtime/src/core/protocols/openaiChatCompletions/nonStreamToStream.ts
similarity index 54%
rename from packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts
rename to packages/model-runtime/src/core/protocols/openaiChatCompletions/nonStreamToStream.ts
index af6734ddaff..25a61059c78 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts
+++ b/packages/model-runtime/src/core/protocols/openaiChatCompletions/nonStreamToStream.ts
@@ -88,74 +88,3 @@ export const transformResponseToStream = (data: OpenAI.ChatCompletion) =>
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, outputIndex) => {
- 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;
- }
- case 'reasoning': {
- if (output.encrypted_content) {
- controller.enqueue({
- item: output,
- output_index: outputIndex,
- sequence_number: outputIndex,
- type: 'response.output_item.done',
- } as OpenAI.Responses.ResponseOutputItemDoneEvent);
- }
- break;
- }
- /**
- * A completed tool call already carries its full arguments/input. The stream parser
- * reads them from `output_item.added`, so no argument deltas are needed; dropping
- * this item would turn a tool-call-only response into an empty completion.
- */
- case 'custom_tool_call':
- case 'function_call': {
- controller.enqueue({
- item: output,
- output_index: outputIndex,
- sequence_number: outputIndex,
- type: 'response.output_item.added',
- } as OpenAI.Responses.ResponseOutputItemAddedEvent);
- break;
- }
- }
- });
- }
-
- // Always send response.completed event
- controller.enqueue({
- response: data,
- sequence_number: 999,
- type: 'response.completed',
- } as OpenAI.Responses.ResponseStreamEvent);
-
- controller.close();
- },
- });
diff --git a/packages/model-runtime/src/core/streams/openai/openai.parallelToolCalls.test.ts b/packages/model-runtime/src/core/protocols/openaiChatCompletions/stream.parallelToolCalls.test.ts
similarity index 96%
rename from packages/model-runtime/src/core/streams/openai/openai.parallelToolCalls.test.ts
rename to packages/model-runtime/src/core/protocols/openaiChatCompletions/stream.parallelToolCalls.test.ts
index 556051596db..20f1ac4f8e7 100644
--- a/packages/model-runtime/src/core/streams/openai/openai.parallelToolCalls.test.ts
+++ b/packages/model-runtime/src/core/protocols/openaiChatCompletions/stream.parallelToolCalls.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from 'vitest';
import type { MessageToolCall } from '../../../types';
-import { createReadableStream, readStreamChunk } from '../utils';
-import { OpenAIStream } from './openai';
+import { createReadableStream, readStreamChunk } from '../../streams/utils';
+import { OpenAIStream } from './stream';
const toolChunk = (toolCall: Record<string, unknown>) => ({
choices: [{ delta: { tool_calls: [toolCall] }, index: 0 }],
diff --git a/packages/model-runtime/src/core/streams/openai/openai.test.ts b/packages/model-runtime/src/core/protocols/openaiChatCompletions/stream.test.ts
similarity index 99%
rename from packages/model-runtime/src/core/streams/openai/openai.test.ts
rename to packages/model-runtime/src/core/protocols/openaiChatCompletions/stream.test.ts
index 4731f93cbce..345f0e6054c 100644
--- a/packages/model-runtime/src/core/streams/openai/openai.test.ts
+++ b/packages/model-runtime/src/core/protocols/openaiChatCompletions/stream.test.ts
@@ -2,9 +2,9 @@ import { describe, expect, it, vi } from 'vitest';
import { AgentRuntimeErrorType } from '../../../types/error';
import { serializeScopedSignature, type SignatureScope } from '../../../utils/signatureScope';
-import { FIRST_CHUNK_ERROR_KEY } from '../protocol';
-import { createReadableStream, readStreamChunk } from '../utils';
-import { OpenAIStream } from './openai';
+import { FIRST_CHUNK_ERROR_KEY } from '../../streams/protocol';
+import { createReadableStream, readStreamChunk } from '../../streams/utils';
+import { OpenAIStream } from './stream';
describe('OpenAIStream', () => {
it('should transform OpenAI stream to protocol stream', async () => {
diff --git a/packages/model-runtime/src/core/streams/openai/openai.ts b/packages/model-runtime/src/core/protocols/openaiChatCompletions/stream.ts
similarity index 99%
rename from packages/model-runtime/src/core/streams/openai/openai.ts
rename to packages/model-runtime/src/core/protocols/openaiChatCompletions/stream.ts
index c744b703080..dadd996091b 100644
--- a/packages/model-runtime/src/core/streams/openai/openai.ts
+++ b/packages/model-runtime/src/core/protocols/openaiChatCompletions/stream.ts
@@ -7,27 +7,27 @@ import type { ILobeAgentRuntimeErrorType } from '../../../types/error';
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';
+} from '../../streams/events';
import type {
ChatPayloadForTransformStream,
StreamContext,
StreamProtocolChunk,
StreamProtocolToolCallChunk,
StreamToolCallChunkData,
-} from '../protocol';
+} from '../../streams/protocol';
import {
convertIterableToStream,
createFirstErrorHandleTransformer,
createTokenSpeedCalculator,
FIRST_CHUNK_ERROR_KEY,
generateToolCallId,
-} from '../protocol';
-import { recordProviderReportedCost } from '../providerReportedCost';
+} from '../../streams/protocol';
+import { recordProviderReportedCost } from '../../streams/providerReportedCost';
+import { convertOpenAIUsage } from '../../usageConverters';
/**
* Extended type for OpenAI tool calls that includes provider-specific extensions
diff --git a/packages/model-runtime/src/core/streams/openai/__snapshots__/responsesStream.test.ts.snap b/packages/model-runtime/src/core/protocols/openaiResponses/__snapshots__/stream.test.ts.snap
similarity index 100%
rename from packages/model-runtime/src/core/streams/openai/__snapshots__/responsesStream.test.ts.snap
rename to packages/model-runtime/src/core/protocols/openaiResponses/__snapshots__/stream.test.ts.snap
diff --git a/packages/model-runtime/src/core/protocols/openaiResponses/chat.ts b/packages/model-runtime/src/core/protocols/openaiResponses/chat.ts
new file mode 100644
index 00000000000..bdbe6a8e287
--- /dev/null
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/chat.ts
@@ -0,0 +1,212 @@
+import debug from 'debug';
+import type OpenAI from 'openai';
+import type { Stream } from 'openai/streaming';
+
+import type { ChatMethodOptions, ChatStreamPayload } from '../../../types';
+import { debugPayload, debugResponse, debugStream } from '../../../utils/debugStream';
+import { desensitizeUrl } from '../../../utils/desensitizeUrl';
+import { getModelPricing } from '../../../utils/getModelPricing';
+import { StreamingResponse } from '../../../utils/response';
+import type { OpenAICompatibleRuntimeContext } from '../../openaiCompatibleFactory/context';
+import type {
+ OpenAICompatibleFactoryOptions,
+ OpenAIExtraParams,
+ ResponseCreateParamsWithPromptCacheKey,
+} from '../../openaiCompatibleFactory/factoryOptions';
+import {
+ initializeOpenAIDiagnostics,
+ observeOpenAIResponsesStream,
+ recordOpenAIResponseMetadata,
+ recordOpenAIResponsesResponse,
+ resolveOpenAIResponseWithMetadata,
+} from '../../openaiCompatibleFactory/providerDiagnostics';
+import { resolveModelSamplingParameters } from '../../parameterResolver';
+import { readableFromAsyncIterable } from '../../streams/protocol';
+import type { OpenAIStreamOptions } from '../openaiChatCompletions/stream';
+import { convertOpenAIResponseInputs } from './inputs';
+import { transformResponseAPIToStream } from './nonStreamToStream';
+import { OpenAIResponsesStream } from './stream';
+import { convertChatCompletionToolToResponseTool, stripChatCompletionParameters } from './tools';
+
+export const chatViaResponses = async (
+ runtime: OpenAICompatibleRuntimeContext,
+ factory: OpenAICompatibleFactoryOptions,
+ payload: ChatStreamPayload,
+ options?: ChatMethodOptions,
+ usageModel = payload.model,
+): Promise<Response> => {
+ const log = debug(`${runtime.logPrefix}:handleResponseAPIMode`);
+ log('handleResponseAPIMode called with model: %s', payload.model);
+
+ const inputStartAt = Date.now();
+
+ const {
+ messages,
+ reasoning_effort,
+ tools,
+ responsesTools,
+ reasoning,
+ responseMode,
+ max_tokens,
+ ...res
+ } = factory.responses?.handlePayload
+ ? (factory.responses.handlePayload(payload, runtime._options) as ChatStreamPayload)
+ : payload;
+ const requestModel =
+ runtime.withMappedRequestModel({ model: res.model }, usageModel).model ?? usageModel;
+ const reasoningSignatureScope = await runtime.getSignatureScope(
+ requestModel,
+ 'reasoning',
+ 'responses',
+ );
+
+ const input = await convertOpenAIResponseInputs(messages as any, {
+ forceImageBase64: factory.chatCompletion?.forceImageBase64,
+ forceVideoBase64: factory.chatCompletion?.forceVideoBase64,
+ provider: runtime.id,
+ reasoningSignatureScope,
+ strictToolPairing: true,
+ });
+
+ const isStreaming = payload.stream !== false;
+ log(
+ 'isStreaming: %s, hasTools: %s, hasReasoning: %s',
+ isStreaming,
+ !!tools,
+ !!(reasoning || reasoning_effort),
+ );
+
+ const postPayload = {
+ ...stripChatCompletionParameters(res),
+ ...(reasoning || reasoning_effort
+ ? {
+ reasoning: {
+ ...reasoning,
+ ...(reasoning_effort && { effort: reasoning_effort }),
+ },
+ }
+ : {}),
+ input,
+ ...(max_tokens && { max_output_tokens: max_tokens }),
+ store: false,
+ stream: isStreaming || undefined,
+ tools: responsesTools ?? tools?.map(convertChatCompletionToolToResponseTool),
+ ...runtime.resolvePromptCacheKeyParams(
+ res.model,
+ options?.user,
+ (res as OpenAIExtraParams).prompt_cache_key,
+ ),
+ // Responses API replaced `user` with `safety_identifier`; some endpoints reject `user`
+ safety_identifier: options?.user,
+ // Sanitize sampling params for Responses API path
+ ...resolveModelSamplingParameters(res.model, res, {
+ normalizeTemperature: false,
+ preferTemperature: true,
+ }),
+ } as ResponseCreateParamsWithPromptCacheKey;
+ const preparedRequest = runtime.prepareResponsesRequest(postPayload, usageModel);
+ const requestPayload = preparedRequest.payload;
+ const providerResponseDiagnostics = initializeOpenAIDiagnostics({
+ apiMode: 'responses',
+ diagnostics: options?.diagnostics,
+ endpoint: desensitizeUrl(runtime.baseURL),
+ payload: requestPayload,
+ sentAt: Date.now(),
+ });
+
+ if (factory.debug?.responses?.()) {
+ debugPayload(requestPayload);
+ }
+
+ log('sending responses.create request');
+
+ const responsePromise = runtime.client.responses.create(requestPayload, {
+ headers: {
+ ...options?.requestHeaders,
+ ...preparedRequest?.headers,
+ },
+ signal: options?.signal,
+ });
+ const responseWithMetadata = await resolveOpenAIResponseWithMetadata(responsePromise);
+ const response = responseWithMetadata.data;
+ recordOpenAIResponseMetadata(providerResponseDiagnostics, {
+ requestId: responseWithMetadata.request_id,
+ response: responseWithMetadata.response,
+ });
+
+ const streamOptions: OpenAIStreamOptions = {
+ bizErrorTypeTransformer: factory.chatCompletion?.handleStreamBizErrorType,
+ callbacks: options?.callback,
+ payload: {
+ apiMode: 'responses',
+ model: usageModel,
+ pricing: await getModelPricing(usageModel, runtime.id, options?.pricingContext),
+ provider: runtime.id,
+ reasoningSignatureScope,
+ },
+ };
+
+ if (isStreaming) {
+ log('processing streaming Responses API response');
+ let prod = response as
+ | ReadableStream<OpenAI.Responses.ResponseStreamEvent>
+ | Stream<OpenAI.Responses.ResponseStreamEvent>;
+
+ if (factory.debug?.responses?.()) {
+ const [productionStream, useForDebug] = prod.tee();
+ prod = productionStream;
+ const useForDebugStream =
+ useForDebug instanceof ReadableStream ? useForDebug : useForDebug.toReadableStream();
+
+ debugStream(useForDebugStream).catch(console.error);
+ }
+
+ if (providerResponseDiagnostics) {
+ /** Observe provider-native events before the Responses protocol adapter transforms them. */
+ const observedStream = observeOpenAIResponsesStream(
+ prod,
+ providerResponseDiagnostics,
+ options?.signal,
+ );
+ prod =
+ observedStream instanceof ReadableStream
+ ? observedStream
+ : readableFromAsyncIterable(observedStream, {
+ model: usageModel,
+ provider: runtime.id,
+ });
+ }
+
+ return StreamingResponse(OpenAIResponsesStream(prod, { ...streamOptions, inputStartAt }), {
+ headers: options?.headers,
+ });
+ }
+
+ log('processing non-streaming Responses API response');
+
+ // Handle non-streaming response
+ if (factory.debug?.responses?.()) {
+ debugResponse(response);
+ }
+
+ await recordOpenAIResponsesResponse(
+ providerResponseDiagnostics,
+ response as OpenAI.Responses.Response,
+ options?.signal,
+ );
+
+ if (responseMode === 'json') {
+ log('returning JSON response mode');
+ return Response.json(response);
+ }
+
+ log('transforming non-streaming Responses API response to stream');
+ const stream = transformResponseAPIToStream(response as OpenAI.Responses.Response);
+
+ return StreamingResponse(
+ OpenAIResponsesStream(stream, { ...streamOptions, enableStreaming: false, inputStartAt }),
+ {
+ headers: options?.headers,
+ },
+ );
+};
diff --git a/packages/model-runtime/src/core/protocols/openaiResponses/generateObject.ts b/packages/model-runtime/src/core/protocols/openaiResponses/generateObject.ts
new file mode 100644
index 00000000000..749350857b3
--- /dev/null
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/generateObject.ts
@@ -0,0 +1,161 @@
+import type { Debugger } from 'debug';
+import type OpenAI from 'openai';
+
+import {
+ isGPTProResponsesModel,
+ supportsGPTResponsesReasoningEffortNone,
+} from '../../../providers/openai/modelId';
+import type {
+ GenerateObjectOptions,
+ GenerateObjectPayload,
+ GenerateObjectSchema,
+} from '../../../types';
+import type { OpenAICompatibleRuntimeContext } from '../../openaiCompatibleFactory/context';
+import type { OpenAICompatibleFactoryOptions } from '../../openaiCompatibleFactory/factoryOptions';
+import {
+ parseStructuredOutputText,
+ parseStructuredToolArguments,
+ StructuredOutputError,
+} from '../../openaiCompatibleFactory/structuredOutput';
+import type { ChatPayloadForTransformStream } from '../../streams/protocol';
+import { convertOpenAIResponseUsage } from '../../usageConverters/openai';
+import { convertOpenAIResponseInputs } from './inputs';
+import { convertChatCompletionToolToResponseTool } from './tools';
+
+type Runtime = OpenAICompatibleRuntimeContext;
+type Factory = OpenAICompatibleFactoryOptions;
+
+type GenerateObjectReasoningParams = Pick<GenerateObjectPayload, 'reasoning_effort' | 'thinking'>;
+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 } }
+ : {};
+};
+
+/** Structured output through `text.format: { type: 'json_schema' }`. */
+export const generateObjectViaResponses = async (
+ runtime: Runtime,
+ factory: Factory,
+ payload: GenerateObjectPayload,
+ processedSchema: GenerateObjectSchema,
+ options: GenerateObjectOptions | undefined,
+ usagePayload: ChatPayloadForTransformStream,
+ log: Debugger,
+) => {
+ const { messages, model } = payload;
+
+ log('calling responses.create for structured output');
+ // Chat Completions content parts are not valid Responses input: a `text` part must
+ // become `input_text` and an `image_url` part `input_image`, or the API rejects the
+ // whole request. String content survives untouched, which is why text-only callers
+ // never hit this.
+ const input = await convertOpenAIResponseInputs(messages as any, {
+ forceImageBase64: factory.chatCompletion?.forceImageBase64,
+ forceVideoBase64: factory.chatCompletion?.forceVideoBase64,
+ provider: runtime.id,
+ strictToolPairing: true,
+ });
+ const preparedRequest = runtime.prepareResponsesRequest(
+ {
+ input,
+ model,
+ ...getGenerateObjectResponsesReasoningParams(payload),
+ ...runtime.resolvePromptCacheKeyParams(model, options?.user),
+ text: { format: { strict: true, type: 'json_schema', ...processedSchema } },
+ // Responses API replaced `user` with `safety_identifier`; some endpoints reject `user`
+ safety_identifier: options?.user,
+ } as any,
+ model,
+ );
+ const res = await runtime.client!.responses.create(
+ preparedRequest.payload as OpenAI.Responses.ResponseCreateParamsNonStreaming,
+ {
+ headers: preparedRequest.headers
+ ? { ...options?.headers, ...preparedRequest.headers }
+ : options?.headers,
+ signal: options?.signal,
+ },
+ );
+
+ if (res.usage) {
+ await options?.onUsage?.(convertOpenAIResponseUsage(res.usage, usagePayload));
+ }
+
+ const text = res.output_text;
+ log('received structured output from Responses API, length: %d', text?.length || 0);
+ return parseStructuredOutputText(text);
+};
+
+/** Force the model to call one of `payload.tools` and return the parsed calls. */
+export const generateToolCallsViaResponses = async (
+ runtime: Runtime,
+ factory: Factory,
+ payload: GenerateObjectPayload,
+ options: GenerateObjectOptions | undefined,
+ usagePayload: ChatPayloadForTransformStream | undefined,
+ log: Debugger,
+) => {
+ const { messages, model, tools } = payload;
+
+ log('calling responses.create for tool calling');
+ const reasoningSignatureScope = await runtime.getSignatureScope(
+ runtime.getMappedModelId(payload.model),
+ 'reasoning',
+ 'responses',
+ );
+ const input = await convertOpenAIResponseInputs(messages as any, {
+ forceImageBase64: factory.chatCompletion?.forceImageBase64,
+ forceVideoBase64: factory.chatCompletion?.forceVideoBase64,
+ provider: runtime.id,
+ reasoningSignatureScope,
+ strictToolPairing: true,
+ });
+
+ const preparedRequest = runtime.prepareResponsesRequest(
+ {
+ input,
+ model,
+ ...runtime.resolvePromptCacheKeyParams(model, options?.user),
+ tool_choice: 'required',
+ tools: tools!.map(convertChatCompletionToolToResponseTool),
+ // Responses API replaced `user` with `safety_identifier`; some endpoints reject `user`
+ safety_identifier: options?.user,
+ } as any,
+ payload.model,
+ );
+ const res = await runtime.client.responses.create(
+ preparedRequest.payload as OpenAI.Responses.ResponseCreateParamsNonStreaming,
+ {
+ headers: preparedRequest.headers
+ ? { ...options?.headers, ...preparedRequest.headers }
+ : options?.headers,
+ signal: options?.signal,
+ },
+ );
+
+ if (res.usage) {
+ await options?.onUsage?.(convertOpenAIResponseUsage(res.usage, usagePayload));
+ }
+
+ const functionCalls = res.output?.filter((item) => item.type === 'function_call');
+
+ log('received %d function calls from Responses API', functionCalls?.length || 0);
+
+ if (!functionCalls?.length) throw new StructuredOutputError('no tool calls returned');
+ return functionCalls.map((item) => ({
+ arguments: parseStructuredToolArguments(item.arguments),
+ name: item.name,
+ }));
+};
diff --git a/packages/model-runtime/src/core/protocols/openaiResponses/inputs.test.ts b/packages/model-runtime/src/core/protocols/openaiResponses/inputs.test.ts
new file mode 100644
index 00000000000..0577d4c842a
--- /dev/null
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/inputs.test.ts
@@ -0,0 +1,907 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { OpenAIChatMessage } from '../../../types';
+import { imageUrlToBase64 } from '../../../utils/imageToBase64';
+import { serializeScopedSignature, type SignatureScope } from '../../../utils/signatureScope';
+import { parseDataUri } from '../../../utils/uriParser';
+import { videoUrlToBase64 } from '../../../utils/videoToBase64';
+import { convertOpenAIResponseInputs } from './inputs';
+
+// 模拟依赖
+vi.mock('../../../utils/imageToBase64', () => ({
+ imageUrlToBase64: vi.fn(),
+}));
+vi.mock('../../../utils/videoToBase64', () => ({
+ videoUrlToBase64: vi.fn(),
+}));
+vi.mock('../../../utils/uriParser');
+
+describe('convertOpenAIResponseInputs', () => {
+ it('should reject raw audio explicitly instead of dropping it from Responses input', async () => {
+ const messages: OpenAIChatMessage[] = [
+ {
+ content: [
+ {
+ audio_url: { mimeType: 'audio/wav', url: 'https://files.example.com/voice.wav' },
+ type: 'audio_url',
+ },
+ ],
+ role: 'user',
+ },
+ ];
+
+ await expect(convertOpenAIResponseInputs(messages)).rejects.toThrow(
+ 'OpenAI raw audio input requires the Chat Completions API',
+ );
+ });
+
+ it('应该正确转换普通文本消息', async () => {
+ const messages: OpenAIChatMessage[] = [
+ { role: 'user', content: 'Hello' },
+ { role: 'assistant', content: 'Hi there!' },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ { role: 'user', content: 'Hello' },
+ { role: 'assistant', content: 'Hi there!' },
+ ]);
+ });
+
+ it('应该正确转换带有工具调用的消息', async () => {
+ const messages: OpenAIChatMessage[] = [
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ {
+ id: 'call_123',
+ type: 'function',
+ function: {
+ name: 'test_function',
+ arguments: '{"key": "value"}',
+ },
+ },
+ ],
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ {
+ arguments: 'test_function',
+ call_id: 'call_123',
+ name: 'test_function',
+ type: 'function_call',
+ },
+ ]);
+ });
+
+ it('应该正确转换工具响应消息', async () => {
+ const messages: OpenAIChatMessage[] = [
+ {
+ role: 'tool',
+ content: 'Function result',
+ tool_call_id: 'call_123',
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ {
+ call_id: 'call_123',
+ output: 'Function result',
+ type: 'function_call_output',
+ },
+ ]);
+ });
+
+ it('工具响应带图片时应保持 output 纯文本并追加 user 图片消息', async () => {
+ vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
+
+ const messages: OpenAIChatMessage[] = [
+ {
+ content: [
+ { text: '[Image: cat.png]', type: 'text' },
+ { image_url: { url: 'https://files.example.com/cat.png' }, type: 'image_url' },
+ ] as any,
+ role: 'tool',
+ tool_call_id: 'call_123',
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ {
+ call_id: 'call_123',
+ // function_call_output.output is text-only — images must not land here.
+ output: '[Image: cat.png]',
+ type: 'function_call_output',
+ },
+ {
+ content: [
+ { text: 'Image output of tool call call_123:', type: 'input_text' },
+ { image_url: 'https://files.example.com/cat.png', type: 'input_image' },
+ ],
+ role: 'user',
+ type: 'message',
+ },
+ ]);
+ });
+
+ it('应该正确转换包含图片的消息', async () => {
+ const messages: OpenAIChatMessage[] = [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Here is an image' },
+ {
+ type: 'image_url',
+ image_url: {
+ url: 'data:image/jpeg;base64,test123',
+ },
+ },
+ ],
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ {
+ role: 'user',
+ content: [
+ { type: 'input_text', text: 'Here is an image' },
+ {
+ type: 'input_image',
+ image_url: 'data:image/jpeg;base64,test123',
+ },
+ ],
+ },
+ ]);
+ });
+
+ it('should preserve the requested image detail on input_image parts', async () => {
+ const messages: OpenAIChatMessage[] = [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Inspect the circled area' },
+ {
+ type: 'image_url',
+ image_url: { detail: 'high', url: 'data:image/png;base64,test123' },
+ },
+ ],
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ {
+ role: 'user',
+ content: [
+ { type: 'input_text', text: 'Inspect the circled area' },
+ { detail: 'high', image_url: 'data:image/png;base64,test123', type: 'input_image' },
+ ],
+ },
+ ]);
+ });
+
+ it('应该正确转换包含视频的消息', async () => {
+ const messages: OpenAIChatMessage[] = [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Here is a video' },
+ {
+ type: 'video_url',
+ video_url: {
+ url: 'data:video/mp4;base64,test123',
+ },
+ },
+ ],
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ {
+ role: 'user',
+ content: [
+ { type: 'input_text', text: 'Here is a video' },
+ {
+ type: 'input_video',
+ video_url: 'data:video/mp4;base64,test123',
+ },
+ ],
+ },
+ ]);
+ });
+
+ it('应该正确转换包含图片和视频的混合消息', async () => {
+ const messages: OpenAIChatMessage[] = [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Here is an image and a video' },
+ {
+ type: 'image_url',
+ image_url: {
+ url: 'data:image/jpeg;base64,test123',
+ },
+ },
+ {
+ type: 'video_url',
+ video_url: {
+ url: 'data:video/mp4;base64,test456',
+ },
+ },
+ ],
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ {
+ role: 'user',
+ content: [
+ { type: 'input_text', text: 'Here is an image and a video' },
+ {
+ type: 'input_image',
+ image_url: 'data:image/jpeg;base64,test123',
+ },
+ {
+ type: 'input_video',
+ video_url: 'data:video/mp4;base64,test456',
+ },
+ ],
+ },
+ ]);
+ });
+
+ it('应该正确处理带有无效 video_url 的消息', async () => {
+ const messages: OpenAIChatMessage[] = [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Here is a video' },
+ {
+ type: 'video_url',
+ video_url: {
+ url: '',
+ },
+ },
+ ],
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ {
+ role: 'user',
+ content: [{ type: 'input_text', text: 'Here is a video' }],
+ },
+ ]);
+ });
+
+ it('应该正确处理混合类型的消息序列', async () => {
+ const messages: OpenAIChatMessage[] = [
+ { role: 'user', content: 'I need help with a function' },
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ {
+ id: 'call_456',
+ type: 'function',
+ function: {
+ name: 'get_data',
+ arguments: '{}',
+ },
+ },
+ ],
+ },
+ {
+ role: 'tool',
+ content: '{"result": "success"}',
+ tool_call_id: 'call_456',
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ { role: 'user', content: 'I need help with a function' },
+ {
+ arguments: 'get_data',
+ call_id: 'call_456',
+ name: 'get_data',
+ type: 'function_call',
+ },
+ {
+ call_id: 'call_456',
+ output: '{"result": "success"}',
+ type: 'function_call_output',
+ },
+ ]);
+ });
+
+ it('should filter orphan tool calls when strictToolPairing is enabled', async () => {
+ const messages: OpenAIChatMessage[] = [
+ { role: 'user', content: 'Use tools carefully' },
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ {
+ id: 'call_paired',
+ type: 'function',
+ function: {
+ name: 'get_weather',
+ arguments: '{"city":"Hangzhou"}',
+ },
+ },
+ {
+ id: 'call_orphan',
+ type: 'function',
+ function: {
+ name: 'get_news',
+ arguments: '{"topic":"AI"}',
+ },
+ },
+ ],
+ },
+ {
+ role: 'tool',
+ content: '{"temp":22}',
+ tool_call_id: 'call_paired',
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages, { strictToolPairing: true });
+
+ expect(result).toEqual([
+ { role: 'user', content: 'Use tools carefully' },
+ {
+ arguments: '{"city":"Hangzhou"}',
+ call_id: 'call_paired',
+ name: 'get_weather',
+ type: 'function_call',
+ },
+ {
+ call_id: 'call_paired',
+ output: '{"temp":22}',
+ type: 'function_call_output',
+ },
+ ]);
+ });
+
+ it('should drop assistant message with all orphaned tool_calls in strict mode', async () => {
+ const messages: OpenAIChatMessage[] = [
+ { role: 'user', content: 'Do something' },
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ {
+ id: 'call_orphan_1',
+ type: 'function',
+ function: { name: 'fn_a', arguments: '{}' },
+ },
+ {
+ id: 'call_orphan_2',
+ type: 'function',
+ function: { name: 'fn_b', arguments: '{}' },
+ },
+ ],
+ },
+ { role: 'assistant', content: 'Final answer' },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages, { strictToolPairing: true });
+
+ // The assistant message with all-orphaned tool_calls should produce no items,
+ // NOT fall through to the default builder which would spread tool_calls back.
+ expect(result).toEqual([
+ { role: 'user', content: 'Do something' },
+ { role: 'assistant', content: 'Final answer' },
+ ]);
+ });
+
+ it('should extract reasoning.content into a separate reasoning item', async () => {
+ const messages: OpenAIChatMessage[] = [
+ { content: 'system prompts', role: 'system' },
+ { content: '你好', role: 'user' },
+ {
+ content: 'hello',
+ role: 'assistant',
+ reasoning: { content: 'reasoning content', duration: 2706 },
+ },
+ { content: '杭州天气如何', role: 'user' },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ { content: 'system prompts', role: 'developer' },
+ { content: '你好', role: 'user' },
+ { summary: [{ text: 'reasoning content', type: 'summary_text' }], type: 'reasoning' },
+ { content: 'hello', role: 'assistant' },
+ { content: '杭州天气如何', role: 'user' },
+ ]);
+ });
+
+ it('should replay encrypted reasoning from a persisted message for the exact scope', async () => {
+ const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
+ const messages: OpenAIChatMessage[] = [
+ {
+ content: 'hello',
+ model: 'gpt-5.6-sol',
+ provider: 'chatgpt',
+ reasoning: {
+ content: 'reasoning content',
+ signature: serializeScopedSignature(
+ 'encrypted-reasoning-content',
+ reasoningSignatureScope,
+ 'reasoning',
+ ),
+ },
+ role: 'assistant',
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages, { reasoningSignatureScope });
+
+ expect(result).toEqual([
+ {
+ encrypted_content: 'encrypted-reasoning-content',
+ summary: [{ text: 'reasoning content', type: 'summary_text' }],
+ type: 'reasoning',
+ },
+ { content: 'hello', role: 'assistant' },
+ ]);
+ });
+
+ it('should preserve encrypted reasoning content without a visible summary', async () => {
+ const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
+ const messages: OpenAIChatMessage[] = [
+ {
+ content: 'hello',
+ provider: 'chatgpt',
+ reasoning: {
+ signature: serializeScopedSignature(
+ 'encrypted-reasoning-content',
+ reasoningSignatureScope,
+ 'reasoning',
+ ),
+ },
+ role: 'assistant',
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages, { reasoningSignatureScope });
+
+ expect(result).toEqual([
+ {
+ encrypted_content: 'encrypted-reasoning-content',
+ summary: [],
+ type: 'reasoning',
+ },
+ { content: 'hello', role: 'assistant' },
+ ]);
+ });
+
+ it('should keep the visible summary but reject foreign and legacy encrypted reasoning', async () => {
+ const sourceScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
+ const targetScope: SignatureScope = { fingerprint: 'b'.repeat(32) };
+ const baseMessage: OpenAIChatMessage = {
+ content: 'hello',
+ reasoning: {
+ content: 'reasoning content',
+ signature: serializeScopedSignature(
+ 'encrypted-reasoning-content',
+ sourceScope,
+ 'reasoning',
+ ),
+ },
+ role: 'assistant',
+ };
+
+ const foreignResult = await convertOpenAIResponseInputs([baseMessage], {
+ reasoningSignatureScope: targetScope,
+ });
+ const legacyResult = await convertOpenAIResponseInputs(
+ [{ ...baseMessage, reasoning: { ...baseMessage.reasoning, signature: 'legacy-signature' } }],
+ { reasoningSignatureScope: sourceScope },
+ );
+
+ const expected = [
+ { summary: [{ text: 'reasoning content', type: 'summary_text' }], type: 'reasoning' },
+ { content: 'hello', role: 'assistant' },
+ ];
+ expect(foreignResult).toEqual(expected);
+ expect(legacyResult).toEqual(expected);
+ });
+
+ it('should replay complete reasoning items in original order for the exact scope', async () => {
+ const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
+ const messages: OpenAIChatMessage[] = [
+ {
+ content: 'hello',
+ provider: 'chatgpt',
+ reasoning: {
+ content: 'first summary',
+ responseItems: [
+ {
+ encrypted_content: serializeScopedSignature(
+ 'encrypted-part-1',
+ reasoningSignatureScope,
+ 'reasoning',
+ ),
+ id: 'rs_1',
+ status: 'completed',
+ summary: [{ text: 'first summary', type: 'summary_text' }],
+ type: 'reasoning',
+ },
+ {
+ encrypted_content: serializeScopedSignature(
+ 'encrypted-part-2',
+ reasoningSignatureScope,
+ 'reasoning',
+ ),
+ id: 'rs_2',
+ status: 'completed',
+ summary: [],
+ type: 'reasoning',
+ },
+ ],
+ },
+ role: 'assistant',
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages, { reasoningSignatureScope });
+
+ expect(result).toEqual([
+ {
+ encrypted_content: 'encrypted-part-1',
+ id: 'rs_1',
+ status: 'completed',
+ summary: [{ text: 'first summary', type: 'summary_text' }],
+ type: 'reasoning',
+ },
+ {
+ encrypted_content: 'encrypted-part-2',
+ id: 'rs_2',
+ status: 'completed',
+ summary: [],
+ type: 'reasoning',
+ },
+ { content: 'hello', role: 'assistant' },
+ ]);
+ });
+
+ it('should replay hidden reasoning items that have no visible summary', async () => {
+ const reasoningSignatureScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
+ const messages: OpenAIChatMessage[] = [
+ {
+ content: 'hello',
+ provider: 'chatgpt',
+ reasoning: {
+ responseItems: [
+ {
+ encrypted_content: serializeScopedSignature(
+ 'hidden-encrypted',
+ reasoningSignatureScope,
+ 'reasoning',
+ ),
+ id: 'rs_hidden',
+ summary: [],
+ type: 'reasoning',
+ },
+ ],
+ },
+ role: 'assistant',
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages, { reasoningSignatureScope });
+
+ expect(result).toEqual([
+ {
+ encrypted_content: 'hidden-encrypted',
+ id: 'rs_hidden',
+ summary: [],
+ type: 'reasoning',
+ },
+ { content: 'hello', role: 'assistant' },
+ ]);
+ });
+
+ it('should fall back to the visible summary when any reasoning item is foreign-scoped', async () => {
+ const sourceScope: SignatureScope = { fingerprint: 'a'.repeat(32) };
+ const targetScope: SignatureScope = { fingerprint: 'b'.repeat(32) };
+ const messages: OpenAIChatMessage[] = [
+ {
+ content: 'hello',
+ provider: 'chatgpt',
+ reasoning: {
+ content: 'visible summary',
+ responseItems: [
+ {
+ encrypted_content: serializeScopedSignature(
+ 'encrypted-part-1',
+ sourceScope,
+ 'reasoning',
+ ),
+ id: 'rs_1',
+ summary: [{ text: 'visible summary', type: 'summary_text' }],
+ type: 'reasoning',
+ },
+ ],
+ signature: serializeScopedSignature('encrypted-part-1', sourceScope, 'reasoning'),
+ },
+ role: 'assistant',
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages, {
+ reasoningSignatureScope: targetScope,
+ });
+
+ expect(result).toEqual([
+ { summary: [{ text: 'visible summary', type: 'summary_text' }], type: 'reasoning' },
+ { content: 'hello', role: 'assistant' },
+ ]);
+ });
+
+ it('should strip item ids when replaying summary-only reasoning items', async () => {
+ const messages: OpenAIChatMessage[] = [
+ {
+ content: 'hello',
+ provider: 'chatgpt',
+ reasoning: {
+ content: 'summary only',
+ responseItems: [
+ {
+ id: 'rs_summary_only',
+ summary: [{ text: 'summary only', type: 'summary_text' }],
+ type: 'reasoning',
+ },
+ ],
+ },
+ role: 'assistant',
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ { summary: [{ text: 'summary only', type: 'summary_text' }], type: 'reasoning' },
+ { content: 'hello', role: 'assistant' },
+ ]);
+ });
+
+ it('should preserve message order when earlier messages have async content (images)', async () => {
+ const messages: OpenAIChatMessage[] = [
+ { content: 'system prompts', role: 'system' },
+ {
+ content: [
+ { type: 'text', text: 'describe this image' },
+ { type: 'image_url', image_url: { url: 'data:image/jpeg;base64,abc123' } },
+ ],
+ role: 'user',
+ },
+ {
+ content: 'The image shows a green car.',
+ role: 'assistant',
+ reasoning: { content: 'analyzing the image', duration: 3000 },
+ },
+ { content: '1 + 1 = ?', role: 'user' },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ { content: 'system prompts', role: 'developer' },
+ {
+ content: [
+ { type: 'input_text', text: 'describe this image' },
+ { type: 'input_image', image_url: 'data:image/jpeg;base64,abc123' },
+ ],
+ role: 'user',
+ },
+ { summary: [{ text: 'analyzing the image', type: 'summary_text' }], type: 'reasoning' },
+ { content: 'The image shows a green car.', role: 'assistant' },
+ { content: '1 + 1 = ?', role: 'user' },
+ ]);
+ });
+
+ it('should handle openai and claude mixed message', async () => {
+ // See: https://github.com/lobehub/lobehub/pull/12017
+ const messages: OpenAIChatMessage[] = [
+ {
+ content: 'system prompts',
+ role: 'system',
+ },
+ {
+ content: '你是谁',
+ role: 'user',
+ },
+ {
+ content: [
+ {
+ signature: 'E',
+ thinking: 'thoughts',
+ type: 'thinking',
+ },
+ {
+ text: '我是 Claude',
+ type: 'text',
+ },
+ ],
+ provider: 'anthropic',
+ role: 'assistant',
+ reasoning: {
+ content: 'The user is asking',
+ duration: 110,
+ signature: 'E',
+ },
+ },
+ ];
+ const result = await convertOpenAIResponseInputs(messages, { provider: 'chatgpt' });
+ expect(result).toEqual([
+ { content: 'system prompts', role: 'developer' },
+ { content: '你是谁', role: 'user' },
+ {
+ summary: [{ text: 'The user is asking', type: 'summary_text' }],
+ type: 'reasoning',
+ },
+ {
+ content: [{ text: '我是 Claude', type: 'output_text' }],
+ role: 'assistant',
+ },
+ ]);
+ });
+
+ it('should drop assistant image content for Responses API input', async () => {
+ const messages: OpenAIChatMessage[] = [
+ {
+ content: [
+ {
+ image_url: { url: 'data:image/jpeg;base64,abc123' },
+ type: 'image_url',
+ },
+ ],
+ role: 'assistant',
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([]);
+ });
+
+ it('should keep assistant text and drop unsupported assistant media for Responses API input', async () => {
+ const messages: OpenAIChatMessage[] = [
+ {
+ content: [
+ {
+ text: 'Here is the generated image.',
+ type: 'text',
+ },
+ {
+ image_url: { url: 'data:image/jpeg;base64,abc123' },
+ type: 'image_url',
+ },
+ {
+ video_url: { url: 'data:video/mp4;base64,def456' },
+ type: 'video_url',
+ },
+ ],
+ role: 'assistant',
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages);
+
+ expect(result).toEqual([
+ {
+ content: [{ text: 'Here is the generated image.', type: 'output_text' }],
+ role: 'assistant',
+ },
+ ]);
+ });
+
+ it('should pass forceVideoBase64 to convertMessageContent in video_url branch', async () => {
+ process.env.LLM_VISION_VIDEO_USE_BASE64 = undefined;
+
+ const messages: OpenAIChatMessage[] = [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Here is a video' },
+ {
+ type: 'video_url',
+ video_url: {
+ url: 'https://example.com/video.mp4',
+ },
+ },
+ ],
+ },
+ ];
+
+ vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
+ vi.mocked(videoUrlToBase64).mockResolvedValue({
+ base64: 'forcedBase64',
+ mimeType: 'video/mp4',
+ });
+
+ const result = await convertOpenAIResponseInputs(messages, { forceVideoBase64: true });
+
+ expect(result).toEqual([
+ {
+ role: 'user',
+ content: [
+ { type: 'input_text', text: 'Here is a video' },
+ {
+ type: 'input_video',
+ video_url: 'data:video/mp4;base64,forcedBase64',
+ },
+ ],
+ },
+ ]);
+
+ expect(videoUrlToBase64).toHaveBeenCalledWith('https://example.com/video.mp4');
+ });
+
+ it('should pass forceImageBase64 to convertMessageContent in image_url branch', async () => {
+ process.env.LLM_VISION_IMAGE_USE_BASE64 = undefined;
+
+ const messages: OpenAIChatMessage[] = [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: 'Here is an image' },
+ {
+ type: 'image_url',
+ image_url: {
+ url: 'https://example.com/image.jpg',
+ },
+ },
+ ],
+ },
+ ];
+
+ vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });
+ vi.mocked(imageUrlToBase64).mockResolvedValue({
+ base64: 'forcedBase64',
+ mimeType: 'image/jpeg',
+ });
+
+ const result = await convertOpenAIResponseInputs(messages, { forceImageBase64: true });
+
+ expect(result).toEqual([
+ {
+ role: 'user',
+ content: [
+ { type: 'input_text', text: 'Here is an image' },
+ {
+ type: 'input_image',
+ image_url: 'data:image/jpeg;base64,forcedBase64',
+ },
+ ],
+ },
+ ]);
+
+ expect(imageUrlToBase64).toHaveBeenCalledWith('https://example.com/image.jpg');
+ });
+});
diff --git a/packages/model-runtime/src/core/contextBuilders/openai.responsesTools.test.ts b/packages/model-runtime/src/core/protocols/openaiResponses/inputs.tools.test.ts
similarity index 98%
rename from packages/model-runtime/src/core/contextBuilders/openai.responsesTools.test.ts
rename to packages/model-runtime/src/core/protocols/openaiResponses/inputs.tools.test.ts
index b3b60425e46..ec1144c701f 100644
--- a/packages/model-runtime/src/core/contextBuilders/openai.responsesTools.test.ts
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/inputs.tools.test.ts
@@ -1,7 +1,7 @@
import type OpenAI from 'openai';
import { describe, expect, it } from 'vitest';
-import { convertOpenAIResponseInputs } from './openai';
+import { convertOpenAIResponseInputs } from './inputs';
export const nativeTools: OpenAI.Responses.Tool[] = [
{
diff --git a/packages/model-runtime/src/core/protocols/openaiResponses/inputs.ts b/packages/model-runtime/src/core/protocols/openaiResponses/inputs.ts
new file mode 100644
index 00000000000..e082c6d04cc
--- /dev/null
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/inputs.ts
@@ -0,0 +1,315 @@
+import type OpenAI from 'openai';
+
+import type { OpenAIChatMessage, UserMessageContentPart } from '../../../types';
+import { resolveScopedSignature } from '../../../utils/signatureScope';
+import {
+ convertMessageContent,
+ type ConvertMessageContentOptions,
+ isInternalThinkingContentPart,
+ type OpenAICompatibleContentPart,
+} from '../../contextBuilders/openai';
+
+export const convertOpenAIResponseInputs = async (
+ messages: OpenAIChatMessage[],
+ options?: ConvertMessageContentOptions,
+) => {
+ const strictToolPairing = options?.strictToolPairing === true;
+ // OpenAI Responses API rejects inputs that keep a function_call without its matching
+ // function_call_output. Example from production:
+ // "No tool output found for function call call_w5odMFjtXEYBBVyBUAQNMOh5."
+ const validToolCallIds = new Set<string>();
+ const pairedToolOutputIds = new Set<string>();
+ const customToolCallIds = new Set<string>();
+
+ for (const message of messages) {
+ if (message.role === 'assistant' && message.tool_calls?.length) {
+ message.tool_calls.forEach((tool) => {
+ if (tool.id) validToolCallIds.add(tool.id);
+ if (tool.id && tool.type === 'custom') customToolCallIds.add(tool.id);
+ });
+ }
+ }
+
+ for (const message of messages) {
+ if (
+ message.role === 'tool' &&
+ message.tool_call_id &&
+ validToolCallIds.has(message.tool_call_id)
+ ) {
+ pairedToolOutputIds.add(message.tool_call_id);
+ }
+ }
+
+ const inputGroups = await Promise.all(
+ messages.map(async (message) => {
+ const items: OpenAI.Responses.ResponseInputItem[] = [];
+ const reasoning = message.reasoning;
+ if (message.responsesTools) {
+ return [
+ {
+ type: 'additional_tools',
+ role: 'developer',
+ tools: message.responsesTools,
+ } satisfies OpenAI.Responses.ResponseInputItem,
+ ];
+ }
+
+ /**
+ * Resolve persisted Responses reasoning items for stateless replay. Encrypted
+ * items must all match the current signature scope — a single foreign-scope item
+ * would make OpenAI reject the whole request, so fail closed to the legacy path.
+ */
+ const resolveResponseItems = (): OpenAI.Responses.ResponseReasoningItem[] | undefined => {
+ const responseItems = reasoning?.responseItems;
+ if (!responseItems?.length) return undefined;
+
+ const resolved: OpenAI.Responses.ResponseReasoningItem[] = [];
+ for (const item of responseItems) {
+ if (item.encrypted_content) {
+ const encryptedContent = resolveScopedSignature(
+ item.encrypted_content,
+ options?.reasoningSignatureScope,
+ 'reasoning',
+ );
+ if (!encryptedContent) return undefined;
+
+ resolved.push({
+ ...item,
+ encrypted_content: encryptedContent,
+ } as OpenAI.Responses.ResponseReasoningItem);
+ } else {
+ /**
+ * Without encrypted content the server cannot look the item up by id in a
+ * stateless request, so drop the id and replay the visible summary only.
+ */
+ const { id: _id, ...rest } = item;
+ resolved.push(rest as unknown as OpenAI.Responses.ResponseReasoningItem);
+ }
+ }
+
+ return resolved;
+ };
+
+ const replayableResponseItems = resolveResponseItems();
+
+ if (replayableResponseItems) {
+ // Replay complete reasoning items verbatim and in original stream order.
+ items.push(...replayableResponseItems);
+ } else {
+ const encryptedContent = resolveScopedSignature(
+ reasoning?.signature,
+ options?.reasoningSignatureScope,
+ 'reasoning',
+ );
+
+ // Preserve encrypted reasoning state for stateless Responses API requests.
+ if (reasoning?.content || encryptedContent) {
+ items.push({
+ encrypted_content: encryptedContent,
+ summary: reasoning?.content ? [{ text: reasoning.content, type: 'summary_text' }] : [],
+ type: 'reasoning',
+ } as OpenAI.Responses.ResponseReasoningItem);
+ }
+ }
+
+ // if message is assistant messages with tool calls , transform it to function type item
+ if (message.role === 'assistant' && message.tool_calls && message.tool_calls?.length > 0) {
+ const toolCalls = strictToolPairing
+ ? message.tool_calls.filter((tool) => !!tool.id && pairedToolOutputIds.has(tool.id))
+ : message.tool_calls;
+
+ toolCalls.forEach((tool) => {
+ const identity = {
+ call_id: tool.id,
+ name: tool.function.name,
+ ...(tool.namespace ? { namespace: tool.namespace } : {}),
+ };
+ items.push(
+ tool.type === 'custom'
+ ? {
+ ...identity,
+ input: tool.function.arguments,
+ type: 'custom_tool_call',
+ }
+ : {
+ ...identity,
+ arguments: strictToolPairing ? tool.function.arguments : tool.function.name,
+ type: 'function_call',
+ },
+ );
+ });
+
+ return items;
+ }
+
+ if (message.role === 'tool') {
+ if (
+ strictToolPairing &&
+ (!message.tool_call_id || !pairedToolOutputIds.has(message.tool_call_id))
+ )
+ return items;
+
+ if (message.responsesOutput !== undefined) {
+ items.push({
+ call_id: message.tool_call_id!,
+ output: message.responsesOutput,
+ type: customToolCallIds.has(message.tool_call_id!)
+ ? 'custom_tool_call_output'
+ : 'function_call_output',
+ });
+ return items;
+ }
+
+ // `function_call_output.output` is text-only. When the tool result
+ // carries images (e.g. builtin `readFile` on an image file), keep the
+ // output textual and re-attach the images as a follow-up user message
+ // item — Responses pairs outputs to calls by `call_id`, so a message
+ // item between outputs is fine.
+ let outputText = message.content as string;
+ let imageParts: UserMessageContentPart[] = [];
+
+ if (Array.isArray(message.content)) {
+ const parts = message.content as any[];
+ imageParts = parts.filter((c) => c?.type === 'image_url');
+ outputText =
+ parts
+ .filter((c) => c?.type === 'text' && typeof c.text === 'string')
+ .map((c) => c.text)
+ .join('\n\n') || (imageParts.length > 0 ? '[Image output attached below]' : '');
+ }
+
+ items.push({
+ call_id: message.tool_call_id,
+ output: outputText,
+ type: customToolCallIds.has(message.tool_call_id!)
+ ? 'custom_tool_call_output'
+ : 'function_call_output',
+ } as OpenAI.Responses.ResponseInputItem);
+
+ if (imageParts.length > 0) {
+ const imageContent = (
+ await Promise.all(
+ imageParts.map(async (c) => {
+ const image = await convertMessageContent(
+ c as OpenAI.ChatCompletionContentPart,
+ options,
+ );
+ const imageUrl = (image as OpenAI.ChatCompletionContentPartImage).image_url;
+ if (!imageUrl?.url) return undefined;
+ return {
+ image_url: imageUrl.url,
+ type: 'input_image' as const,
+ ...(imageUrl.detail && { detail: imageUrl.detail }),
+ };
+ }),
+ )
+ ).filter((c) => !!c);
+
+ if (imageContent.length > 0) {
+ items.push({
+ content: [
+ {
+ text: `Image output of tool call ${message.tool_call_id}:`,
+ type: 'input_text' as const,
+ },
+ ...imageContent,
+ ],
+ role: 'user',
+ type: 'message',
+ } as OpenAI.Responses.ResponseInputItem);
+ }
+ }
+
+ return items;
+ }
+
+ if (message.role === 'system') {
+ items.push({ ...message, role: 'developer' } as OpenAI.Responses.ResponseInputItem);
+ return items;
+ }
+
+ // default item
+ // also need handle image
+
+ const processedContent =
+ typeof message.content === 'string'
+ ? message.content
+ : await Promise.all(
+ (message.content || []).map(async (c) => {
+ if (isInternalThinkingContentPart(c as OpenAICompatibleContentPart)) {
+ return undefined;
+ }
+
+ if (c.type === 'text') {
+ // if assistant message, set type to output_text
+ // https://platform.openai.com/docs/guides/text
+ if (message.role === 'assistant') {
+ return { ...c, type: 'output_text' };
+ }
+ return { ...c, type: 'input_text' };
+ }
+
+ // Responses API only accepts output_text/refusal inside assistant history.
+ // Multimodal parts are valid as model inputs, not as previous assistant outputs.
+ if (message.role === 'assistant') {
+ return undefined;
+ }
+
+ if (c.type === 'video_url') {
+ const video = await convertMessageContent(c, options);
+ if (!('video_url' in video) || !video.video_url?.url) {
+ return undefined;
+ }
+ return {
+ video_url: video.video_url.url,
+ type: 'input_video',
+ };
+ }
+ if (c.type === 'audio_url') {
+ throw new TypeError('OpenAI raw audio input requires the Chat Completions API');
+ }
+ const image = await convertMessageContent(
+ c as OpenAI.ChatCompletionContentPart,
+ options,
+ );
+ const imageUrl = (image as OpenAI.ChatCompletionContentPartImage).image_url;
+ if (!imageUrl?.url) {
+ return undefined;
+ }
+ // Forward the requested detail level so callers that need full resolution
+ // (e.g. inspecting small annotations on screenshots) are not downgraded to auto.
+ return {
+ image_url: imageUrl.url,
+ type: 'input_image',
+ ...(imageUrl.detail && { detail: imageUrl.detail }),
+ };
+ }),
+ );
+
+ const content =
+ typeof processedContent === 'string'
+ ? processedContent
+ : processedContent.filter((m) => m !== undefined);
+
+ if (message.role === 'assistant' && Array.isArray(content) && content.length === 0) {
+ return items;
+ }
+
+ const {
+ model: _model,
+ provider: _provider,
+ reasoning: _reasoning,
+ ...responseMessage
+ } = message;
+ const item = {
+ ...responseMessage,
+ content,
+ } as OpenAI.Responses.ResponseInputItem;
+
+ items.push(item);
+ return items;
+ }),
+ );
+
+ return inputGroups.flat();
+};
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.ts b/packages/model-runtime/src/core/protocols/openaiResponses/nonStreamToStream.test.ts
similarity index 51%
rename from packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.ts
rename to packages/model-runtime/src/core/protocols/openaiResponses/nonStreamToStream.test.ts
index 2a48b8f4eaf..140f8f2d90f 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.test.ts
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/nonStreamToStream.test.ts
@@ -2,7 +2,7 @@
import type OpenAI from 'openai';
import { describe, expect, it } from 'vitest';
-import { transformResponseAPIToStream, transformResponseToStream } from './nonStreamToStream';
+import { transformResponseAPIToStream } from './nonStreamToStream';
const createInputOnlyUsage = () => ({
total_tokens: 5,
@@ -13,360 +13,6 @@ const createInputOnlyUsage = () => ({
});
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 = {
diff --git a/packages/model-runtime/src/core/protocols/openaiResponses/nonStreamToStream.ts b/packages/model-runtime/src/core/protocols/openaiResponses/nonStreamToStream.ts
new file mode 100644
index 00000000000..9de1c3e4986
--- /dev/null
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/nonStreamToStream.ts
@@ -0,0 +1,72 @@
+import type OpenAI from 'openai';
+
+/**
+ * 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, outputIndex) => {
+ 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;
+ }
+ case 'reasoning': {
+ if (output.encrypted_content) {
+ controller.enqueue({
+ item: output,
+ output_index: outputIndex,
+ sequence_number: outputIndex,
+ type: 'response.output_item.done',
+ } as OpenAI.Responses.ResponseOutputItemDoneEvent);
+ }
+ break;
+ }
+ /**
+ * A completed tool call already carries its full arguments/input. The stream parser
+ * reads them from `output_item.added`, so no argument deltas are needed; dropping
+ * this item would turn a tool-call-only response into an empty completion.
+ */
+ case 'custom_tool_call':
+ case 'function_call': {
+ controller.enqueue({
+ item: output,
+ output_index: outputIndex,
+ sequence_number: outputIndex,
+ type: 'response.output_item.added',
+ } as OpenAI.Responses.ResponseOutputItemAddedEvent);
+ break;
+ }
+ }
+ });
+ }
+
+ // Always send response.completed event
+ controller.enqueue({
+ response: data,
+ sequence_number: 999,
+ type: 'response.completed',
+ } as OpenAI.Responses.ResponseStreamEvent);
+
+ controller.close();
+ },
+ });
diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts b/packages/model-runtime/src/core/protocols/openaiResponses/stream.test.ts
similarity index 99%
rename from packages/model-runtime/src/core/streams/openai/responsesStream.test.ts
rename to packages/model-runtime/src/core/protocols/openaiResponses/stream.test.ts
index 7441043f927..abeaad03722 100644
--- a/packages/model-runtime/src/core/streams/openai/responsesStream.test.ts
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/stream.test.ts
@@ -2,9 +2,9 @@ import { describe, expect, it, vi } from 'vitest';
import { AgentRuntimeErrorType } from '../../../types/error';
import { serializeScopedSignature, type SignatureScope } from '../../../utils/signatureScope';
-import { FIRST_CHUNK_ERROR_KEY } from '../protocol';
-import { createReadableStream, readStreamChunk } from '../utils';
-import { OpenAIResponsesStream } from './responsesStream';
+import { FIRST_CHUNK_ERROR_KEY } from '../../streams/protocol';
+import { createReadableStream, readStreamChunk } from '../../streams/utils';
+import { OpenAIResponsesStream } from './stream';
const createdResponse = (id: string) => ({
type: 'response.created',
diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.tools.test.ts b/packages/model-runtime/src/core/protocols/openaiResponses/stream.tools.test.ts
similarity index 95%
rename from packages/model-runtime/src/core/streams/openai/responsesStream.tools.test.ts
rename to packages/model-runtime/src/core/protocols/openaiResponses/stream.tools.test.ts
index b82038e2142..1e653382a64 100644
--- a/packages/model-runtime/src/core/streams/openai/responsesStream.tools.test.ts
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/stream.tools.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
-import { createReadableStream } from '../utils';
-import { OpenAIResponsesStream } from './responsesStream';
+import { createReadableStream } from '../../streams/utils';
+import { OpenAIResponsesStream } from './stream';
describe('Responses custom tool streaming', () => {
it('keeps interleaved custom/function deltas attached to their own calls', async () => {
diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.ts b/packages/model-runtime/src/core/protocols/openaiResponses/stream.ts
similarity index 98%
rename from packages/model-runtime/src/core/streams/openai/responsesStream.ts
rename to packages/model-runtime/src/core/protocols/openaiResponses/stream.ts
index 54d8e58717f..c042fa11adf 100644
--- a/packages/model-runtime/src/core/streams/openai/responsesStream.ts
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/stream.ts
@@ -4,27 +4,27 @@ 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';
+} from '../../streams/events';
import type {
ChatPayloadForTransformStream,
StreamContext,
StreamProtocolChunk,
StreamProtocolToolCallChunk,
StreamToolCallChunkData,
-} from '../protocol';
+} from '../../streams/protocol';
import {
convertIterableToStream,
createFirstErrorHandleTransformer,
createTokenSpeedCalculator,
FIRST_CHUNK_ERROR_KEY,
-} from '../protocol';
-import { recordProviderReportedCost } from '../providerReportedCost';
-import type { OpenAIStreamOptions } from './openai';
+} from '../../streams/protocol';
+import { recordProviderReportedCost } from '../../streams/providerReportedCost';
+import { convertOpenAIResponseUsage } from '../../usageConverters';
+import type { OpenAIStreamOptions } from '../openaiChatCompletions/stream';
const toResponsesError = (error: { code?: string | null; message?: string | null }) =>
({
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/responseTools.ts b/packages/model-runtime/src/core/protocols/openaiResponses/tools.ts
similarity index 97%
rename from packages/model-runtime/src/core/openaiCompatibleFactory/responseTools.ts
rename to packages/model-runtime/src/core/protocols/openaiResponses/tools.ts
index bcf4b326247..0247acd50a1 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/responseTools.ts
+++ b/packages/model-runtime/src/core/protocols/openaiResponses/tools.ts
@@ -1,6 +1,6 @@
import type OpenAI from 'openai';
-import type { ChatCompletionTool, ChatStreamPayload } from '../../types';
+import type { ChatCompletionTool, ChatStreamPayload } from '../../../types';
export const convertChatCompletionToolToResponseTool = (
tool: ChatCompletionTool,
diff --git a/packages/model-runtime/src/core/streams/index.ts b/packages/model-runtime/src/core/streams/index.ts
index 6c4904042ab..a49ee2680ba 100644
--- a/packages/model-runtime/src/core/streams/index.ts
+++ b/packages/model-runtime/src/core/streams/index.ts
@@ -4,7 +4,6 @@ export * from './events';
export * from './google';
export * from './model';
export * from './ollama';
-export * from './openai';
export * from './protocol';
export * from './providerReportedCost';
export * from './qwen';
diff --git a/packages/model-runtime/src/core/streams/openai/index.ts b/packages/model-runtime/src/core/streams/openai/index.ts
deleted file mode 100644
index aa3c3902110..00000000000
--- a/packages/model-runtime/src/core/streams/openai/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export * from './openai';
-export * from './responsesStream';
diff --git a/packages/model-runtime/src/core/streams/providerReportedCost.test.ts b/packages/model-runtime/src/core/streams/providerReportedCost.test.ts
index 710eaed19ba..83b199fd503 100644
--- a/packages/model-runtime/src/core/streams/providerReportedCost.test.ts
+++ b/packages/model-runtime/src/core/streams/providerReportedCost.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, it, vi } from 'vitest';
+import { OpenAIStream } from '../protocols/openaiChatCompletions/stream';
+import { OpenAIResponsesStream } from '../protocols/openaiResponses/stream';
import { AnthropicStream } from './anthropic';
import { AWSBedrockClaudeStream } from './bedrock/claude';
-import { OpenAIStream } from './openai/openai';
-import { OpenAIResponsesStream } from './openai/responsesStream';
import { readProviderReportedCost } from './providerReportedCost';
const createStream = (chunks: unknown[]) =>
diff --git a/packages/model-runtime/src/providers/azureOpenai/index.test.ts b/packages/model-runtime/src/providers/azureOpenai/index.test.ts
index 5af6a99cc2a..0ed6a573e55 100644
--- a/packages/model-runtime/src/providers/azureOpenai/index.test.ts
+++ b/packages/model-runtime/src/providers/azureOpenai/index.test.ts
@@ -3,8 +3,9 @@ import OpenAI from 'openai';
import type { Mock } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import * as nonStreamToStreamModule from '../../core/openaiCompatibleFactory/nonStreamToStream';
-import * as streamsModule from '../../core/streams';
+import * as nonStreamToStreamModule from '../../core/protocols/openaiChatCompletions/nonStreamToStream';
+import * as chatCompletionsStreamModule from '../../core/protocols/openaiChatCompletions/stream';
+import * as responsesStreamModule from '../../core/protocols/openaiResponses/stream';
import { AgentRuntimeErrorType } from '../../types/error';
import * as debugStreamModule from '../../utils/debugStream';
import * as getModelPricingModule from '../../utils/getModelPricing';
@@ -92,7 +93,9 @@ describe('LobeAzureOpenAI', () => {
);
vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockStream);
vi.spyOn(getModelPricingModule, 'getModelPricing').mockResolvedValue(mockPricing as any);
- vi.spyOn(streamsModule, 'OpenAIResponsesStream').mockReturnValue(new ReadableStream());
+ vi.spyOn(responsesStreamModule, 'OpenAIResponsesStream').mockReturnValue(
+ new ReadableStream(),
+ );
await instance.chat({
enabledSearch: true,
@@ -119,7 +122,7 @@ describe('LobeAzureOpenAI', () => {
expect.arrayContaining([expect.objectContaining({ type: 'web_search' })]),
);
- expect(streamsModule.OpenAIResponsesStream).toHaveBeenCalledWith(
+ expect(responsesStreamModule.OpenAIResponsesStream).toHaveBeenCalledWith(
mockStream,
expect.objectContaining({
inputStartAt: expect.any(Number),
@@ -138,7 +141,9 @@ describe('LobeAzureOpenAI', () => {
vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockStream);
vi.spyOn(getModelPricingModule, 'getModelPricing').mockResolvedValue(undefined);
- vi.spyOn(streamsModule, 'OpenAIResponsesStream').mockReturnValue(new ReadableStream());
+ vi.spyOn(responsesStreamModule, 'OpenAIResponsesStream').mockReturnValue(
+ new ReadableStream(),
+ );
await instance.chat({
messages: [{ content: 'Review this migration.', role: 'user' }],
@@ -161,7 +166,9 @@ describe('LobeAzureOpenAI', () => {
const mockStream = new ReadableStream() as any;
vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockStream);
vi.spyOn(getModelPricingModule, 'getModelPricing').mockResolvedValue(undefined);
- vi.spyOn(streamsModule, 'OpenAIResponsesStream').mockReturnValue(new ReadableStream());
+ vi.spyOn(responsesStreamModule, 'OpenAIResponsesStream').mockReturnValue(
+ new ReadableStream(),
+ );
await instance.chat({
messages: [{ content: 'Review this migration.', role: 'system' }],
@@ -197,7 +204,9 @@ describe('LobeAzureOpenAI', () => {
);
vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockStream);
vi.spyOn(getModelPricingModule, 'getModelPricing').mockResolvedValue(mockPricing as any);
- vi.spyOn(streamsModule, 'OpenAIResponsesStream').mockReturnValue(new ReadableStream());
+ vi.spyOn(responsesStreamModule, 'OpenAIResponsesStream').mockReturnValue(
+ new ReadableStream(),
+ );
await instance.chat({
deploymentName: 'prod-gpt-54',
@@ -214,7 +223,7 @@ describe('LobeAzureOpenAI', () => {
expect(createCall.reasoning).toEqual({ summary: 'auto' });
expect(createCall.deploymentName).toBeUndefined();
- expect(streamsModule.OpenAIResponsesStream).toHaveBeenCalledWith(
+ expect(responsesStreamModule.OpenAIResponsesStream).toHaveBeenCalledWith(
mockStream,
expect.objectContaining({
payload: expect.objectContaining({
@@ -239,7 +248,7 @@ describe('LobeAzureOpenAI', () => {
vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(mockStream);
vi.spyOn(getModelPricingModule, 'getModelPricing').mockResolvedValue(mockPricing as any);
- vi.spyOn(streamsModule, 'OpenAIStream').mockReturnValue(new ReadableStream());
+ vi.spyOn(chatCompletionsStreamModule, 'OpenAIStream').mockReturnValue(new ReadableStream());
await instance.chat({
frequency_penalty: 0.4,
@@ -275,7 +284,7 @@ describe('LobeAzureOpenAI', () => {
'lobehub',
undefined,
);
- expect(streamsModule.OpenAIStream).toHaveBeenCalledWith(
+ expect(chatCompletionsStreamModule.OpenAIStream).toHaveBeenCalledWith(
mockStream,
expect.objectContaining({
inputStartAt: expect.any(Number),
@@ -293,7 +302,7 @@ describe('LobeAzureOpenAI', () => {
it('should handle multiple data chunks correctly', async () => {
const mockStream = new ReadableStream() as any;
vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(mockStream);
- vi.spyOn(streamsModule, 'OpenAIStream').mockReturnValue(
+ vi.spyOn(chatCompletionsStreamModule, 'OpenAIStream').mockReturnValue(
new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode('event: text\ndata: "你好!"\n\n'));
@@ -314,7 +323,7 @@ describe('LobeAzureOpenAI', () => {
});
expect(result).toBeInstanceOf(Response);
- expect(streamsModule.OpenAIStream).toHaveBeenCalledWith(
+ expect(chatCompletionsStreamModule.OpenAIStream).toHaveBeenCalledWith(
mockStream,
expect.objectContaining({
inputStartAt: expect.any(Number),
@@ -509,7 +518,7 @@ describe('LobeAzureOpenAI', () => {
process.env.DEBUG_AZURE_CHAT_COMPLETION = '1';
vi.spyOn(debugStreamModule, 'debugStream').mockImplementation(() => Promise.resolve());
- vi.spyOn(streamsModule, 'OpenAIStream').mockReturnValue(new ReadableStream());
+ vi.spyOn(chatCompletionsStreamModule, 'OpenAIStream').mockReturnValue(new ReadableStream());
// Act
await instance.chat({
diff --git a/packages/model-runtime/src/providers/azureai/index.ts b/packages/model-runtime/src/providers/azureai/index.ts
index f598da051bf..b4c663da8e3 100644
--- a/packages/model-runtime/src/providers/azureai/index.ts
+++ b/packages/model-runtime/src/providers/azureai/index.ts
@@ -8,6 +8,7 @@ import type OpenAI from 'openai';
import type { LobeRuntimeAI } from '../../core/BaseAI';
import { transformResponseToStream } from '../../core/openaiCompatibleFactory';
+import { OpenAIStream } from '../../core/protocols/openaiChatCompletions/stream';
import {
appendProviderResponseEvent,
appendRawProviderEvent,
@@ -16,7 +17,7 @@ import {
observeProviderReadableStream,
recordProviderError,
} from '../../core/providerDiagnostics';
-import { createSSEDataExtractor, OpenAIStream } from '../../core/streams';
+import { createSSEDataExtractor } from '../../core/streams';
import type { ChatMethodOptions, ChatStreamPayload } from '../../types';
import { AgentRuntimeErrorType } from '../../types/error';
import { AgentRuntimeError } from '../../utils/createError';
diff --git a/packages/model-runtime/src/providers/githubCopilot/index.test.ts b/packages/model-runtime/src/providers/githubCopilot/index.test.ts
index cc3ee67ef54..172ebf5e72a 100644
--- a/packages/model-runtime/src/providers/githubCopilot/index.test.ts
+++ b/packages/model-runtime/src/providers/githubCopilot/index.test.ts
@@ -1,7 +1,8 @@
// @vitest-environment node
import { afterEach, describe, expect, it, vi } from 'vitest';
-import * as openAIContextBuilders from '../../core/contextBuilders/openai';
+import * as chatCompletionsMessages from '../../core/protocols/openaiChatCompletions/messages';
+import * as responsesInputs from '../../core/protocols/openaiResponses/inputs';
import { isResponsesAPIModel } from '../openai/modelId';
import { LobeGithubCopilotAI } from './index';
@@ -22,7 +23,7 @@ describe('LobeGithubCopilotAI', () => {
describe('image payload conversion', () => {
it('should force image base64 conversion in responses mode', async () => {
const convertResponseInputsSpy = vi
- .spyOn(openAIContextBuilders, 'convertOpenAIResponseInputs')
+ .spyOn(responsesInputs, 'convertOpenAIResponseInputs')
.mockRejectedValue({ status: 400 });
const futureTime = Date.now() + 600_000;
@@ -50,7 +51,7 @@ describe('LobeGithubCopilotAI', () => {
it('should force image base64 conversion in chat completions mode', async () => {
const convertMessagesSpy = vi
- .spyOn(openAIContextBuilders, 'convertOpenAIMessages')
+ .spyOn(chatCompletionsMessages, 'convertOpenAIMessages')
.mockRejectedValue({ status: 400 });
const futureTime = Date.now() + 600_000;
@@ -77,7 +78,7 @@ describe('LobeGithubCopilotAI', () => {
it('should bind signature scopes to the Copilot account', async () => {
const convertMessagesSpy = vi
- .spyOn(openAIContextBuilders, 'convertOpenAIMessages')
+ .spyOn(chatCompletionsMessages, 'convertOpenAIMessages')
.mockRejectedValue({ status: 400 });
const futureTime = Date.now() + 600_000;
diff --git a/packages/model-runtime/src/providers/githubCopilot/index.ts b/packages/model-runtime/src/providers/githubCopilot/index.ts
index 793bf16d13d..6d19dc00b0c 100644
--- a/packages/model-runtime/src/providers/githubCopilot/index.ts
+++ b/packages/model-runtime/src/providers/githubCopilot/index.ts
@@ -5,13 +5,13 @@ import OpenAI from 'openai';
import { buildDefaultAnthropicPayload } from '../../core/anthropicCompatibleFactory';
import { type LobeRuntimeAI } from '../../core/BaseAI';
-import {
- convertOpenAIMessages,
- convertOpenAIResponseInputs,
- pruneReasoningPayload,
-} from '../../core/contextBuilders/openai';
+import { pruneReasoningPayload } from '../../core/contextBuilders/openai';
import { transformResponseAPIToStream } from '../../core/openaiCompatibleFactory';
-import { AnthropicStream, OpenAIResponsesStream, OpenAIStream } from '../../core/streams';
+import { convertOpenAIMessages } from '../../core/protocols/openaiChatCompletions/messages';
+import { OpenAIStream } from '../../core/protocols/openaiChatCompletions/stream';
+import { convertOpenAIResponseInputs } from '../../core/protocols/openaiResponses/inputs';
+import { OpenAIResponsesStream } from '../../core/protocols/openaiResponses/stream';
+import { AnthropicStream } from '../../core/streams';
import { type ChatMethodOptions, type ChatStreamPayload } from '../../types';
import { AgentRuntimeErrorType } from '../../types/error';
import { AgentRuntimeError } from '../../utils/createError';
diff --git a/packages/model-runtime/src/providers/spark/index.test.ts b/packages/model-runtime/src/providers/spark/index.test.ts
index 1bfa3ee4812..fc074be231f 100644
--- a/packages/model-runtime/src/providers/spark/index.test.ts
+++ b/packages/model-runtime/src/providers/spark/index.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { ModelProvider } from 'model-bank';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { testProvider } from '../../providerTestUtils';
import { LobeSparkAI, params } from './index';
@@ -309,4 +309,38 @@ describe('LobeSparkAI - custom features', () => {
expect(instance).toBeDefined();
});
});
+
+ describe('model-specific baseURL', () => {
+ it('should retarget the handlePayload options to the model endpoint', () => {
+ const options: Record<string, any> = {};
+
+ params.chatCompletion.handlePayload({ messages: [], model: 'spark-x2' } as any, options);
+
+ expect(options.baseURL).toBe('https://spark-api-open.xf-yun.com/x2');
+ });
+
+ it('should point the client at the retargeted endpoint before sending the request', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response('data: [DONE]\n\n', {
+ headers: { 'Content-Type': 'text/event-stream' },
+ status: 200,
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+
+ const instance = new LobeSparkAI({ apiKey: 'test-api-key' });
+
+ await instance
+ .chat({ messages: [{ content: 'hi', role: 'user' }], model: 'spark-x2' } as any)
+ .catch(() => undefined);
+
+ expect(fetchMock).toHaveBeenCalled();
+ expect(String(fetchMock.mock.calls[0][0])).toBe(
+ 'https://spark-api-open.xf-yun.com/x2/chat/completions',
+ );
+ expect(instance.baseURL).toBe('https://spark-api-open.xf-yun.com/x2');
+
+ vi.unstubAllGlobals();
+ });
+ });
});
diff --git a/packages/model-runtime/src/providers/zhipu/index.ts b/packages/model-runtime/src/providers/zhipu/index.ts
index 7fe699a3c4d..cef6ff40633 100644
--- a/packages/model-runtime/src/providers/zhipu/index.ts
+++ b/packages/model-runtime/src/providers/zhipu/index.ts
@@ -5,7 +5,7 @@ import {
type OpenAICompatibleFactoryOptions,
} from '../../core/openaiCompatibleFactory';
import { resolveParameters } from '../../core/parameterResolver';
-import { OpenAIStream } from '../../core/streams/openai';
+import { OpenAIStream } from '../../core/protocols/openaiChatCompletions/stream';
import { convertIterableToStream } from '../../core/streams/protocol';
import { getModelMaxOutputs } from '../../utils/getModelMaxOutputs';
import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';