🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
⬆️ fix(model-runtime): upgrade openai SDK to v6 to drop node-fetch@2 (#16090)
Arvin Xu88a7e82ab8eb
diff --git a/package.json b/package.jsonindex ed9a7cded86..095f631f7bf 100644--- a/package.json+++ b/package.json@@ -392,7 +392,7 @@"ogl": "^1.0.11","oidc-provider": "^9.6.0","ollama": "^0.6.3",- "openai": "^4.104.0",+ "openai": "^6.42.0","openapi-fetch": "^0.14.1","partial-json": "^0.1.7","path-browserify-esm": "^1.0.6",diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.jsonindex 7ff32f8f19f..ead8a30fd82 100644--- a/packages/agent-runtime/package.json+++ b/packages/agent-runtime/package.json@@ -14,6 +14,6 @@"devDependencies": {"@lobechat/context-engine": "workspace:*","@lobechat/types": "workspace:*",- "openai": "^4.104.0"+ "openai": "^6.42.0"}}diff --git a/packages/model-runtime/package.json b/packages/model-runtime/package.jsonindex 9a73de4e2b0..9014b0d5fa4 100644--- a/packages/model-runtime/package.json+++ b/packages/model-runtime/package.json@@ -33,7 +33,7 @@"model-bank": "workspace:*","nanoid": "^5.1.6","ollama": "^0.6.2",- "openai": "^4.104.0",+ "openai": "^6.42.0","replicate": "^1.4.0","tokenx": "^1.3.0","type-fest": "^5.2.0",diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex bef0a411fd4..5cbee81c047 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -84,12 +84,15 @@ interface RouterInstance {runtime?: RuntimeClass;}-type ConstructorOptions<T extends Record<string, any> = any> = ClientOptions & T;+// OpenAI SDK v6 widened `apiKey` to `string | ApiKeySetter`; lobehub only ever+// passes a plain string, so narrow it back to keep `.trim()` / string assignments valid.+type LobeClientOptions = Omit<ClientOptions, 'apiKey'> & { apiKey?: string };+type ConstructorOptions<T extends Record<string, any> = any> = LobeClientOptions & T;type Routers =| RouterInstance[]| ((- options: ClientOptions & Record<string, any>,+ options: LobeClientOptions & Record<string, any>,runtimeContext: {model?: string;},@@ -199,7 +202,7 @@ export const createRouterRuntime = ({...params}: CreateRouterRuntimeOptions) => {return class UniformRuntime implements LobeRuntimeAI {- public _options: ClientOptions & Record<string, any>;+ public _options: LobeClientOptions & Record<string, any>;private _routers: Routers;private _params: any;private _id: string;@@ -213,7 +216,7 @@ export const createRouterRuntime = ({metadata.routeAttempt = routeAttempt;}- constructor(options: ClientOptions & Record<string, any> = {}) {+ constructor(options: LobeClientOptions & Record<string, any> = {}) {const startedAt = Date.now();this._options = {...options,diff --git a/packages/model-runtime/src/core/contextBuilders/anthropic.ts b/packages/model-runtime/src/core/contextBuilders/anthropic.tsindex 2bc2e958dba..d928761cf90 100644--- a/packages/model-runtime/src/core/contextBuilders/anthropic.ts+++ b/packages/model-runtime/src/core/contextBuilders/anthropic.ts@@ -460,17 +460,19 @@ export const buildAnthropicTools = () => {if (!tools) return;- return tools.map(- (tool, index): Anthropic.Tool => ({+ return tools.map((tool, index): Anthropic.Tool => {+ // OpenAI SDK v6 made `ChatCompletionTool` a function|custom union; lobehub only sends function tools.+ const { function: fn } = tool as OpenAI.ChatCompletionFunctionTool;+ return {cache_control:options.enabledContextCaching && index === tools.length - 1? { type: 'ephemeral' }: undefined,- description: tool.function.description,- input_schema: tool.function.parameters as Anthropic.Tool.InputSchema,- name: tool.function.name,- }),- );+ description: fn.description,+ input_schema: fn.parameters as Anthropic.Tool.InputSchema,+ name: fn.name,+ };+ });};export const buildSearchTool = (): Anthropic.WebSearchTool20250305 => {diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.tsindex 8c73340a4ed..ba33412d915 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts@@ -890,7 +890,7 @@ describe('LobeOpenAICompatibleFactory', () => {status: 400,},'Error message',- {},+ new Headers(),);vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);@@ -931,7 +931,7 @@ describe('LobeOpenAICompatibleFactory', () => {message: 'api is undefined',},};- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', new Headers());vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);@@ -960,7 +960,7 @@ describe('LobeOpenAICompatibleFactory', () => {const errorInfo = {cause: { message: 'api is undefined' },};- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', new Headers());instance = new LobeMockProvider({apiKey: 'test',@@ -1044,7 +1044,7 @@ describe('LobeOpenAICompatibleFactory', () => {status: 400,},'Error message',- {},+ new Headers(),);vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);@@ -1080,7 +1080,7 @@ describe('LobeOpenAICompatibleFactory', () => {status: 400,},'Error message',- {},+ new Headers(),);vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);@@ -1118,7 +1118,7 @@ describe('LobeOpenAICompatibleFactory', () => {status: 429,},'Error message',- {},+ new Headers(),);vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);@@ -2349,7 +2349,7 @@ describe('LobeOpenAICompatibleFactory', () => {status: 400,},'Error message',- {},+ new Headers(),);vi.spyOn(instance['client'].responses, 'create').mockRejectedValue(apiError);diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 7dbcc89df09..68ee873eda0 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -99,7 +99,10 @@ export const CHAT_MODELS_BLOCK_LIST = ['dall-e',];-type ConstructorOptions<T extends Record<string, any> = any> = ClientOptions & T;+// OpenAI SDK v6 widened `apiKey` to `string | ApiKeySetter`; lobehub only ever+// passes a plain string, so narrow it back to keep `.trim()` / string assignments valid.+type LobeClientOptions = Omit<ClientOptions, 'apiKey'> & { apiKey?: string };+type ConstructorOptions<T extends Record<string, any> = any> = LobeClientOptions & T;type OpenAIExtraParams = { prompt_cache_key?: string; safety_identifier?: string };type ChatCompletionCreateParamsWithPromptCacheKey = Omit<OpenAI.ChatCompletionCreateParamsNonStreaming,@@ -316,7 +319,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anbaseURL!: string;protected _options: ConstructorOptions<T>;- constructor(options: ClientOptions & Record<string, any> = {}) {+ constructor(options: LobeClientOptions & Record<string, any> = {}) {const _options = {...options,apiKey: options.apiKey?.trim() || DEFAULT_API_KEY,@@ -1541,10 +1544,14 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anlog('received %d tool calls from Chat Completions API', toolCalls?.length || 0);try {- const result = toolCalls.map((item) => ({- arguments: JSON.parse(item.function.arguments),- name: item.function.name,- }));+ const result = toolCalls.map((item) => {+ // OpenAI SDK v6 made tool calls a function|custom union; lobehub only emits function calls.+ const { function: fn } = item as OpenAI.ChatCompletionMessageFunctionToolCall;+ return {+ arguments: JSON.parse(fn.arguments),+ name: fn.name,+ };+ });log('successfully parsed tool calls: %O',result.map((r) => r.name),diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.tsindex 2350fbde56f..2651c399c0c 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/nonStreamToStream.ts@@ -36,12 +36,16 @@ export const transformResponseToStream = (data: OpenAI.ChatCompletion) =>content: choice.message.content,role: choice.message.role,tool_calls: choice.message.tool_calls?.map(- (tool, index): OpenAI.ChatCompletionChunk.Choice.Delta.ToolCall => ({- function: tool.function,- id: tool.id,- index,- type: tool.type,- }),+ (tool, index): OpenAI.ChatCompletionChunk.Choice.Delta.ToolCall => {+ // OpenAI SDK v6 made tool calls a function|custom union; lobehub only emits function calls.+ const fnTool = tool as OpenAI.ChatCompletionMessageFunctionToolCall;+ return {+ function: fnTool.function,+ id: fnTool.id,+ index,+ type: fnTool.type,+ };+ },),},finish_reason: null,diff --git a/packages/model-runtime/src/core/streams/openai/responsesStream.ts b/packages/model-runtime/src/core/streams/openai/responsesStream.tsindex 8aff9574334..8675ad2d87b 100644--- a/packages/model-runtime/src/core/streams/openai/responsesStream.ts+++ b/packages/model-runtime/src/core/streams/openai/responsesStream.ts@@ -132,7 +132,8 @@ const transformOpenAIStream = (}case 'response.output_text.annotation.added': {- const citations = chunk.annotation;+ // OpenAI SDK v6 types the annotation payload as `unknown`; narrow to the URL-citation shape we read.+ const citations = chunk.annotation as { title?: string; url?: string };if (streamContext.returnedCitationArray) {streamContext.returnedCitationArray.push({diff --git a/packages/model-runtime/src/core/streams/spark.ts b/packages/model-runtime/src/core/streams/spark.tsindex 0a81b253f89..f778d79081d 100644--- a/packages/model-runtime/src/core/streams/spark.ts+++ b/packages/model-runtime/src/core/streams/spark.ts@@ -35,12 +35,16 @@ export function transformSparkResponseToStream(data: OpenAI.ChatCompletion) {content: choice.message.content,role: choice.message.role,tool_calls: toolCallsArray.map(- (tool, index): OpenAI.ChatCompletionChunk.Choice.Delta.ToolCall => ({- function: tool.function,- id: tool.id,- index,- type: tool.type,- }),+ (tool, index): OpenAI.ChatCompletionChunk.Choice.Delta.ToolCall => {+ // OpenAI SDK v6 made tool calls a function|custom union; lobehub only emits function calls.+ const fnTool = tool as OpenAI.ChatCompletionMessageFunctionToolCall;+ return {+ function: fnTool.function,+ id: fnTool.id,+ index,+ type: fnTool.type,+ };+ },),},finish_reason: null,diff --git a/packages/model-runtime/src/providerTestUtils.test.ts b/packages/model-runtime/src/providerTestUtils.test.tsindex dc55fbf92a3..2f85164c736 100644--- a/packages/model-runtime/src/providerTestUtils.test.ts+++ b/packages/model-runtime/src/providerTestUtils.test.ts@@ -62,7 +62,7 @@ describe('testProvider', () => {status: 400,},'Test Error',- {},+ new Headers(),),),},diff --git a/packages/model-runtime/src/providerTestUtils.ts b/packages/model-runtime/src/providerTestUtils.tsindex ff38c33aa8e..dcbf5cb62c7 100644--- a/packages/model-runtime/src/providerTestUtils.ts+++ b/packages/model-runtime/src/providerTestUtils.ts@@ -138,7 +138,7 @@ export const testProvider = ({status: 400,},'Error message',- {},+ new Headers(),);if (test?.useResponsesAPI) {@@ -183,7 +183,7 @@ export const testProvider = ({message: 'api is undefined',},};- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', new Headers());if (test?.useResponsesAPI) {vi.mocked(instance['client'].responses.create).mockRejectedValue(apiError);@@ -216,7 +216,7 @@ export const testProvider = ({const errorInfo = {cause: { message: 'api is undefined' },};- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', new Headers());instance = new Runtime({apiKey: 'test',diff --git a/packages/model-runtime/src/providers/bfl/index.ts b/packages/model-runtime/src/providers/bfl/index.tsindex 377032c56e6..2ba6abe0ce9 100644--- a/packages/model-runtime/src/providers/bfl/index.ts+++ b/packages/model-runtime/src/providers/bfl/index.ts@@ -13,7 +13,8 @@ export class LobeBflAI implements LobeRuntimeAI {private apiKey: string;baseURL?: string;- constructor({ apiKey, baseURL }: ClientOptions = {}) {+ // OpenAI SDK v6 widened `apiKey` to `string | ApiKeySetter`; lobehub only uses the string form.+ constructor({ apiKey, baseURL }: Omit<ClientOptions, 'apiKey'> & { apiKey?: string } = {}) {if (!apiKey) throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey);this.apiKey = apiKey;diff --git a/packages/model-runtime/src/providers/fal/index.ts b/packages/model-runtime/src/providers/fal/index.tsindex d946095cad6..c659273773f 100644--- a/packages/model-runtime/src/providers/fal/index.ts+++ b/packages/model-runtime/src/providers/fal/index.ts@@ -15,7 +15,8 @@ const log = debug('lobe-image:fal');type FluxDevOutput = Awaited<ReturnType<typeof fal.subscribe<'fal-ai/flux/dev'>>>['data'];export class LobeFalAI implements LobeRuntimeAI {- constructor({ apiKey }: ClientOptions = {}) {+ // OpenAI SDK v6 widened `apiKey` to `string | ApiKeySetter`; lobehub only uses the string form.+ constructor({ apiKey }: Omit<ClientOptions, 'apiKey'> & { apiKey?: string } = {}) {if (!apiKey) throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey);fal.config({diff --git a/packages/model-runtime/src/providers/google/index.test.ts b/packages/model-runtime/src/providers/google/index.test.tsindex eb264878aaa..1b4de27ac36 100644--- a/packages/model-runtime/src/providers/google/index.test.ts+++ b/packages/model-runtime/src/providers/google/index.test.ts@@ -303,7 +303,7 @@ describe('LobeGoogleAI', () => {message: 'api is undefined',},};- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', new Headers());vi.spyOn(instance['client'].models, 'generateContentStream').mockRejectedValue(apiError);diff --git a/packages/model-runtime/src/providers/openai/index.test.ts b/packages/model-runtime/src/providers/openai/index.test.tsindex bf450b3b5fc..0bdefbf36d0 100644--- a/packages/model-runtime/src/providers/openai/index.test.ts+++ b/packages/model-runtime/src/providers/openai/index.test.ts@@ -71,7 +71,7 @@ describe('LobeOpenAI', () => {status: 400,},'Error message',- {},+ new Headers(),);vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);@@ -112,7 +112,7 @@ describe('LobeOpenAI', () => {message: 'api is undefined',},};- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', new Headers());vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);@@ -141,7 +141,7 @@ describe('LobeOpenAI', () => {const errorInfo = {cause: { message: 'api is undefined' },};- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', new Headers());instance = new LobeOpenAI({apiKey: 'test',diff --git a/packages/model-runtime/src/providers/siliconcloud/index.test.ts b/packages/model-runtime/src/providers/siliconcloud/index.test.tsindex 9f3dbfbe1ef..ab3cea50c13 100644--- a/packages/model-runtime/src/providers/siliconcloud/index.test.ts+++ b/packages/model-runtime/src/providers/siliconcloud/index.test.ts@@ -235,9 +235,7 @@ describe('LobeSiliconCloudAI - custom features', () => {message: 'Value error, current model does not support parameter `enable_thinking`.',},};- const apiError = new OpenAI.APIError(400, errorInfo, 'Request failed', {- status: 400,- } as any);+ const apiError = new OpenAI.APIError(400, errorInfo, 'Request failed', undefined);vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);diff --git a/packages/model-runtime/src/providers/taichu/index.test.ts b/packages/model-runtime/src/providers/taichu/index.test.tsindex 11558b8d0cb..675be6704e1 100644--- a/packages/model-runtime/src/providers/taichu/index.test.ts+++ b/packages/model-runtime/src/providers/taichu/index.test.ts@@ -48,7 +48,7 @@ describe('LobeTaichuAI', () => {message: 'api is undefined',},};- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', new Headers());const mockCreate = vi.spyOn(instance['client'].chat.completions, 'create')diff --git a/packages/model-runtime/src/utils/handleOpenAIError.test.ts b/packages/model-runtime/src/utils/handleOpenAIError.test.tsindex 7b7ead71b68..ef18a87d5a9 100644--- a/packages/model-runtime/src/utils/handleOpenAIError.test.ts+++ b/packages/model-runtime/src/utils/handleOpenAIError.test.ts@@ -11,7 +11,7 @@ describe('handleOpenAIError', () => {472,{ error: { message: 'API error', type: 'invalid_request' } },'test-message',- { status: 400 } as any,+ undefined,);const result = handleOpenAIError(apiError);@@ -25,9 +25,7 @@ describe('handleOpenAIError', () => {it('should handle OpenAI APIError with cause', () => {const cause = { message: 'Network error', code: 'ECONNRESET' };- const apiError = new OpenAI.APIError(472, null as any, 'test-message', {- status: 500,- } as any);+ const apiError = new OpenAI.APIError(472, null as any, 'test-message', undefined);(apiError as any).cause = cause;const result = handleOpenAIError(apiError);@@ -38,16 +36,13 @@ describe('handleOpenAIError', () => {});it('should handle OpenAI APIError without error or cause', () => {- const headers = { 'content-type': 'application/json' };- const apiError = new OpenAI.APIError(472, null as any, 'test-message', {- status: 401,- headers,- } as any);+ const headers = new Headers({ 'content-type': 'application/json' });+ const apiError = new OpenAI.APIError(472, null as any, 'test-message', headers);const result = handleOpenAIError(apiError);expect(result.errorResult).toEqual({- headers: { headers, status: 401 },+ headers: apiError.headers,status: 472,});expect(result.message).toBe(apiError.message);@@ -57,9 +52,7 @@ describe('handleOpenAIError', () => {it('should handle OpenAI APIError with both error and cause', () => {const errorObject = { message: 'API error', type: 'rate_limit' };const cause = { message: 'Rate limit exceeded' };- const apiError = new OpenAI.APIError(472, { error: errorObject }, 'test-message', {- status: 429,- } as any);+ const apiError = new OpenAI.APIError(472, { error: errorObject }, 'test-message', undefined);(apiError as any).cause = cause;const result = handleOpenAIError(apiError);