🤯 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
✨ feat(runtime): map provider model IDs (#16128)
YuTengjinge1ff69bfbe21
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex 5cbee81c047..1c80f247fe3 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -36,6 +36,7 @@ import type {} from '../../types';import { AgentRuntimeError } from '../../utils/createError';import { isNonRetryableRequestError } from '../../utils/isNonRetryableRequestError';+import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';import { postProcessModelList } from '../../utils/postProcessModelList';import { safeParseJSON } from '../../utils/safeParseJSON';import type { LobeRuntimeAI } from '../BaseAI';@@ -57,6 +58,7 @@ interface ProviderIniOptions extends Record<string, any> {baseURL?: string;baseURLOrAccountID?: string;dangerouslyAllowBrowser?: boolean;+ modelIdMapping?: Record<string, string>;region?: string;sdkType?: string;sessionToken?: string;@@ -383,7 +385,7 @@ export const createRouterRuntime = ({if (resolvedApiType === 'vertexai') {const { apiKey, googleAuthOptions, project, location, ...restOptions } = finalOptions;const credentials = safeParseJSON<Record<string, any>>(apiKey);- const vertexOptions: GoogleGenAIOptions = {+ const vertexOptions: GoogleGenAIOptions & ModelIdMappingOptions = {...(restOptions as GoogleGenAIOptions),vertexai: true,};diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.tsindex 0eac7369cab..2a77586ea99 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts@@ -11,6 +11,7 @@ const log = debug('lobe-model-runtime:anthropic:generate-object');export interface AnthropicGenerateObjectConfig {maxTokens?: number;+ requestModel?: string;requestParams?: Pick<Anthropic.MessageCreateParamsNonStreaming, 'output_config' | 'thinking'>;schemaToolChoice?: 'any' | 'tool';schemaToolStrict?: boolean;@@ -148,11 +149,14 @@ export const createAnthropicGenerateObject = async (payload,config,);+ const finalRequestParams = config?.requestModel+ ? { ...requestParams, model: config.requestModel }+ : requestParams;try {- log('calling Anthropic API with max_tokens: %d', requestParams.max_tokens);+ log('calling Anthropic API with max_tokens: %d', finalRequestParams.max_tokens);- const response = await client.messages.create(requestParams, { signal: options?.signal });+ const response = await client.messages.create(finalRequestParams, { signal: options?.signal });log('received response with %d content blocks', response.content.length);log('response: %O', response);diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.tsindex 91e153a3522..eb66551a750 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts@@ -17,6 +17,10 @@ vi.mock('@lobechat/const', () => ({CURRENT_VERSION: '1.0.0-test',}));+vi.mock('@lobechat/business-model-bank/model-config', () => ({+ loadModels: vi.fn().mockResolvedValue([]),+}));+const MockedAnthropic = vi.mocked(Anthropic);const originalAnthropicClientTimeout = process.env.ANTHROPIC_CLIENT_TIMEOUT;@@ -157,4 +161,99 @@ describe('createAnthropicCompatibleRuntime', () => {);expect(runtime.baseURL).toBe('https://aihubmix.com');});++ it('should send mapped model id to Anthropic Messages API', async () => {+ const messagesCreate = vi.fn().mockResolvedValue({ content: [] });+ const getPricingOptions = vi.fn(() => undefined);+ const handlePayload = vi.fn((payload) => ({+ max_tokens: 1024,+ messages: [],+ model: payload.model,+ }));+ const createClient = vi.fn((options) => ({+ baseURL: options.baseURL,+ messages: { create: messagesCreate },+ }));+ const Runtime = createAnthropicCompatibleRuntime({+ chatCompletion: {+ getPricingOptions,+ handlePayload,+ },+ customClient: {+ createClient: (options) => createClient(options) as unknown as Anthropic,+ },+ provider: 'test-provider',+ });+ const runtime = new Runtime({+ apiKey: 'test-key',+ modelIdMapping: { 'logical-model': 'upstream-model' },+ });++ await runtime.chat({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'logical-model',+ responseMode: 'json',+ stream: false,+ } as any);++ expect(messagesCreate).toHaveBeenCalledWith(+ expect.objectContaining({+ model: 'upstream-model',+ }),+ expect.anything(),+ );+ expect(handlePayload).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'logical-model' }),+ expect.anything(),+ );+ expect(getPricingOptions).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'logical-model' }),+ expect.objectContaining({ model: 'logical-model' }),+ );+ expect(createClient.mock.calls[0][0]).not.toHaveProperty('modelIdMapping');+ });++ it('should keep logical model for generateObject and pass mapped id as request config', async () => {+ const generateObject = vi.fn().mockResolvedValue({ ok: true });+ const Runtime = createAnthropicCompatibleRuntime({+ chatCompletion: {+ handlePayload: (payload) => ({+ max_tokens: 1024,+ messages: [],+ model: payload.model,+ }),+ },+ customClient: {+ createClient: () =>+ ({+ baseURL: 'https://aihubmix.com',+ messages: { create: vi.fn() },+ }) as unknown as Anthropic,+ },+ generateObject,+ provider: 'test-provider',+ });+ const runtime = new Runtime({+ apiKey: 'test-key',+ modelIdMapping: { 'logical-model': 'upstream-model' },+ });++ const result = await runtime.generateObject({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'logical-model',+ schema: {+ name: 'result',+ schema: { properties: {}, type: 'object' },+ },+ });++ expect(generateObject).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ model: 'logical-model' }),+ undefined,+ undefined,+ expect.objectContaining({ requestModel: 'upstream-model' }),+ );+ expect(result).toEqual({ ok: true });+ });});diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.tsindex ea544b2f8f6..009c18dcaab 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts@@ -21,6 +21,8 @@ import { AgentRuntimeError } from '../../utils/createError';import { debugStream } from '../../utils/debugStream';import { desensitizeUrl } from '../../utils/desensitizeUrl';import { getModelPricing } from '../../utils/getModelPricing';+import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';+import { resolveMappedModelId } from '../../utils/modelIdMapping';import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';import { StreamingResponse } from '../../utils/response';import type { LobeRuntimeAI } from '../BaseAI';@@ -32,12 +34,17 @@ import {import { resolveModelSamplingParameters } from '../parameterResolver';import { AnthropicStream, type AnthropicStreamOptions } from '../streams';import { type ComputeChatCostOptions } from '../usageConverters/utils/computeChatCost';-import { createAnthropicGenerateObject } from './generateObject';+import {+ type AnthropicGenerateObjectConfig,+ createAnthropicGenerateObject,+} from './generateObject';import { handleAnthropicError } from './handleAnthropicError';import { resolveCacheTTL } from './resolveCacheTTL';import { resolveMaxTokens } from './resolveMaxTokens';-type ConstructorOptions<T extends Record<string, any> = any> = ClientOptions & T;+type ConstructorOptions<T extends Record<string, any> = any> = ClientOptions &+ ModelIdMappingOptions &+ T;type AnthropicTools = Anthropic.Tool | Anthropic.WebSearchTool20250305;@@ -109,6 +116,7 @@ export interface AnthropicCompatibleFactoryOptions<T extends Record<string, any>payload: GenerateObjectPayload,options?: GenerateObjectOptions,pricing?: Pricing,+ config?: AnthropicGenerateObjectConfig,) => Promise<any>;models?: (params: {apiKey?: string;@@ -451,21 +459,28 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =private id: string;private logPrefix: string;+ private modelIdMappingOptions: ModelIdMappingOptions = {};baseURL!: string;protected _options: ConstructorOptions<T>;constructor(options: ClientOptions & Record<string, any> = {}) {- const apiKey = typeof options.apiKey === 'string' ? options.apiKey.trim() : options.apiKey;+ const { modelIdMapping, ...inputOptions } = options as ClientOptions &+ Record<string, any> &+ ModelIdMappingOptions;+ const apiKey =+ typeof inputOptions.apiKey === 'string' ? inputOptions.apiKey.trim() : inputOptions.apiKey;const inputBaseURL =- typeof options.baseURL === 'string' ? options.baseURL.trim() : options.baseURL;+ typeof inputOptions.baseURL === 'string'+ ? inputOptions.baseURL.trim()+ : inputOptions.baseURL;// Anthropic SDK appends `/v1/messages`; normalize gateway URLs that already// include that SDK-managed path segment before constructing any client.const baseURL = normalizeAnthropicCompatibleBaseURL(inputBaseURL);const defaultBaseURL = normalizeAnthropicCompatibleBaseURL(DEFAULT_BASE_URL);const resolvedOptions = {- ...options,+ ...inputOptions,apiKey: apiKey || DEFAULT_API_KEY,baseURL: baseURL || defaultBaseURL,};@@ -475,6 +490,7 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =...rest} = resolvedOptions;this._options = resolvedOptions as ConstructorOptions<T>;+ this.modelIdMappingOptions = { modelIdMapping };if (!finalApiKey) throw AgentRuntimeError.createError(ErrorType.invalidAPIKey);@@ -497,6 +513,20 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =this.logPrefix = `lobe-model-runtime:${this.id}`;}+ private withMappedRequestModel<TPayload extends { model?: string }>(+ requestPayload: TPayload,+ logicalModel: string,+ ): TPayload {+ if (!requestPayload.model) return requestPayload;++ const mappedModel = resolveMappedModelId(logicalModel, this.modelIdMappingOptions);+ if (requestPayload.model !== logicalModel || mappedModel === requestPayload.model) {+ return requestPayload;+ }++ return { ...requestPayload, model: mappedModel };+ }+async chat(payload: ChatStreamPayload, options?: ChatMethodOptions) {try {if (!chatCompletion?.handlePayload) {@@ -511,17 +541,18 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =const postPayload = await chatCompletion.handlePayload(payload, this._options);const shouldStream = postPayload.stream ?? payload.stream ?? true;const finalPayload = { ...postPayload, stream: shouldStream };+ const requestPayload = this.withMappedRequestModel(finalPayload, payload.model);if (debugParams?.chatCompletion?.()) {// eslint-disable-next-line no-consoleconsole.log('[requestPayload]');// eslint-disable-next-line no-console- console.log(JSON.stringify(finalPayload), '\n');+ console.log(JSON.stringify(requestPayload), '\n');}const response = await this.client.messages.create({- ...finalPayload,+ ...requestPayload,metadata: options?.user ? { user_id: options.user } : undefined,},{@@ -664,7 +695,9 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =try {const pricing = await getModelPricing(payload.model, this.id);- return await generateObject(this.client, payload, options, pricing);+ return await generateObject(this.client, payload, options, pricing, {+ requestModel: resolveMappedModelId(payload.model, this.modelIdMappingOptions),+ });} catch (error) {throw this.handleError(error);}diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.test.tsindex ca4e68c32af..ad157ab129f 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.test.ts@@ -9,6 +9,9 @@ import { createOpenAICompatibleImage } from './createImage';// Mock the console to avoid polluting test outputvi.spyOn(console, 'error').mockImplementation(() => {});+vi.mock('@lobechat/business-model-bank/model-config', () => ({+ loadModels: vi.fn().mockResolvedValue([]),+}));// Polyfill File for Node environmentif (typeof File === 'undefined') {@@ -530,6 +533,45 @@ describe('createOpenAICompatibleImage', () => {expect(mockClient.images.edit).not.toHaveBeenCalled();});+ it('should route by logical image model while sending mapped model id', async () => {+ const mockChatResponse = {+ choices: [+ {+ message: {+ images: [+ {+ image_url: {+ url: 'data:image/png;base64,mappedChatModelResult',+ },+ },+ ],+ },+ },+ ],+ };++ vi.mocked(mockClient.chat.completions.create).mockResolvedValue(mockChatResponse as any);++ const payload: CreateImagePayload = {+ model: 'logical-model:image',+ params: {+ prompt: 'Test mapped routing',+ },+ };++ const result = await createOpenAICompatibleImage(mockClient, payload, 'test-provider', {+ requestModel: 'upstream-model',+ routingModel: 'logical-model:image',+ });++ expect(result.imageUrl).toBe('data:image/png;base64,mappedChatModelResult');+ expect(mockClient.chat.completions.create).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'upstream-model' }),+ );+ expect(mockClient.images.generate).not.toHaveBeenCalled();+ expect(mockClient.images.edit).not.toHaveBeenCalled();+ });+it('should route to image mode when model does not end with :image', async () => {const mockImageResponse = {data: [@@ -567,7 +609,7 @@ describe('createOpenAICompatibleImage', () => {};// Mock fetch for image download- const mockArrayBuffer = new Uint8Array([0xFF, 0xD8, 0xFF, 0xE0]).buffer;+ const mockArrayBuffer = new Uint8Array([0xff, 0xd8, 0xff, 0xe0]).buffer;global.fetch = vi.fn().mockResolvedValue({ok: true,arrayBuffer: async () => mockArrayBuffer,diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.tsindex df7315ee419..173baa5430a 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/createImage.ts@@ -12,6 +12,12 @@ import { convertOpenAIImageUsage } from '../usageConverters/openai';const log = createDebug('lobe-image:openai-compatible');+interface CreateOpenAICompatibleImageOptions {+ pricingModel?: string;+ requestModel?: string;+ routingModel?: string;+}+/*** Generate images using traditional OpenAI images API (DALL-E, etc.)*/@@ -19,10 +25,13 @@ async function generateByImageMode(client: OpenAI,payload: CreateImagePayload,provider: string,+ imageOptions?: CreateOpenAICompatibleImageOptions,): Promise<CreateImageResponse> {const { model, params } = payload;+ const requestModel = imageOptions?.requestModel ?? model;+ const routingModel = imageOptions?.routingModel ?? model;- log('Creating image with model: %s and params: %O', model, params);+ log('Creating image with model: %s and params: %O', requestModel, params);// Map parameter names, mapping imageUrls to imageconst paramsMap = new Map<RuntimeImageGenParamsValue, string>([@@ -68,18 +77,18 @@ async function generateByImageMode(// https://developers.openai.com/cookbook/examples/multimodal/image-gen-models-prompting-guide// Match the gpt-image-1 family (including dated snapshots like// `gpt-image-1-2025-04-15` and the `.5` variant), but exclude the mini tier.- const isGptImage1Family = /^gpt-image-1(?:$|[-.])/.test(model);- const supportsInputFidelity = isImageEdit && isGptImage1Family && !model.includes('mini');+ const isGptImage1Family = /^gpt-image-1(?:$|[-.])/.test(routingModel);+ const supportsInputFidelity = isImageEdit && isGptImage1Family && !routingModel.includes('mini');const defaultInput = {n: 1,- ...(model.includes('dall-e') ? { response_format: 'b64_json' } : {}),+ ...(routingModel.includes('dall-e') ? { response_format: 'b64_json' } : {}),// https://platform.openai.com/docs/api-reference/images/createEdit#images_createedit-input_fidelity...(supportsInputFidelity ? { input_fidelity: 'high' } : {}),};const options = cleanObject({- model,+ model: requestModel,...defaultInput,...userInput,});@@ -126,7 +135,10 @@ async function generateByImageMode(imageUrl,...(img.usage? {- modelUsage: convertOpenAIImageUsage(img.usage, await getModelPricing(model, provider)),+ modelUsage: convertOpenAIImageUsage(+ img.usage,+ await getModelPricing(imageOptions?.pricingModel ?? routingModel, provider),+ ),}: {}),};@@ -158,9 +170,10 @@ async function processImageUrlForChat(imageUrl: string): Promise<string> {async function generateByChatModel(client: OpenAI,payload: CreateImagePayload,+ requestModel?: string,): Promise<CreateImageResponse> {const { model, params } = payload;- const actualModel = model.replace(':image', ''); // Remove :image suffix+ const actualModel = (requestModel ?? model).replace(':image', ''); // Remove :image suffixlog('Creating image via chat API with model: %s and params: %O', actualModel, params);@@ -232,14 +245,16 @@ export async function createOpenAICompatibleImage(client: OpenAI,payload: CreateImagePayload,provider: string,+ options?: CreateOpenAICompatibleImageOptions,): Promise<CreateImageResponse> {const { model } = payload;+ const routingModel = options?.routingModel ?? model;// Check if it's a chat model for image generation (via :image suffix)- if (model.endsWith(':image')) {- return await generateByChatModel(client, payload);+ if (routingModel.endsWith(':image')) {+ return await generateByChatModel(client, payload, options?.requestModel);}// Default to traditional images API- return await generateByImageMode(client, payload, provider);+ return await generateByImageMode(client, payload, provider, options);}diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.tsindex be9aa2aa6ef..7e5d5593f4d 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/createVideo.ts@@ -6,6 +6,7 @@ import type {CreateVideoResponse,PollVideoStatusResult,} from '../../types/video';+import { resolveMappedModelId } from '../../utils/modelIdMapping';import type { CreateVideoOptions } from '../openaiCompatibleFactory';const log = createDebug('lobe-video:openai-compatible');@@ -127,15 +128,16 @@ export async function createOpenAICompatibleVideo(options: CreateVideoOptions,): Promise<CreateVideoResponse> {const { model, params } = payload;+ const requestModel = resolveMappedModelId(model, options);const { prompt, imageUrl, size, duration } = params;- log('Creating video with OpenAI-compatible API - model: %s, params: %O', model, params);+ log('Creating video with OpenAI-compatible API - model: %s, params: %O', requestModel, params);const baseURL = options.baseURL || 'https://api.openai.com/v1';// Build request body compatible with OpenAI Soraconst body: Record<string, unknown> = {- model,+ model: requestModel,prompt,};diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.tsindex ba33412d915..0f01c2e61ae 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts@@ -133,6 +133,43 @@ describe('LobeOpenAICompatibleFactory', () => {expect(result).toBeInstanceOf(Response);});+ it('should keep logical model for provider payload handling while sending mapped model id', async () => {+ const handlePayload = vi.fn(+ (payload: ChatStreamPayload): OpenAI.ChatCompletionCreateParamsStreaming => ({+ messages: payload.messages as OpenAI.ChatCompletionCreateParamsStreaming['messages'],+ model: payload.model,+ stream: true,+ }),+ );+ const Runtime = createOpenAICompatibleRuntime({+ baseURL: defaultBaseURL,+ chatCompletion: { handlePayload },+ provider: 'mapped-provider',+ });+ const runtime = new Runtime({+ apiKey: 'test',+ modelIdMapping: { 'logical-model': 'upstream-model' },+ });+ vi.spyOn(runtime['client'].chat.completions, 'create').mockResolvedValue(+ new ReadableStream() as any,+ );++ await runtime.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'logical-model',+ temperature: 0,+ });++ expect(handlePayload).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'logical-model' }),+ expect.anything(),+ );+ expect(runtime['client'].chat.completions.create).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'upstream-model' }),+ expect.anything(),+ );+ });+describe('streaming response', () => {it('should handle multiple data chunks correctly', async () => {const mockStream = new ReadableStream({@@ -1659,6 +1696,42 @@ describe('LobeOpenAICompatibleFactory', () => {});});+ it('should route mapped logical image-chat models through chat completions', async () => {+ const mappedInstance = new LobeMockProvider({+ apiKey: 'test',+ modelIdMapping: { 'logical-image-model:image': 'upstream-image-model' },+ });+ vi.spyOn(mappedInstance['client'].chat.completions, 'create').mockResolvedValue({+ choices: [+ {+ message: {+ images: [+ {+ image_url: {+ url: 'data:image/png;base64,mapped-chat-image',+ },+ },+ ],+ },+ },+ ],+ } as any);+ vi.spyOn(mappedInstance['client'].images, 'generate').mockResolvedValue({} as any);++ const result = await (mappedInstance as any).createImage({+ model: 'logical-image-model:image',+ params: {+ prompt: 'A beautiful sunset',+ },+ });++ expect(mappedInstance['client'].chat.completions.create).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'upstream-image-model' }),+ );+ expect(mappedInstance['client'].images.generate).not.toHaveBeenCalled();+ expect(result).toEqual({ imageUrl: 'data:image/png;base64,mapped-chat-image' });+ });+it('should handle size auto parameter correctly', async () => {const mockResponse = {data: [{ b64_json: 'mock-base64-data' }],@@ -2079,6 +2152,43 @@ describe('LobeOpenAICompatibleFactory', () => {expect(result).toEqual({ age: 30, name: 'John' });});+ it('should choose generateObject API by logical model while sending mapped model id', async () => {+ const Runtime = createOpenAICompatibleRuntime({+ baseURL: defaultBaseURL,+ generateObject: {+ useResponseModels: ['logical-response-model'],+ },+ provider: 'mapped-provider',+ });+ const runtime = new Runtime({+ apiKey: 'test',+ modelIdMapping: { 'logical-response-model': 'upstream-response-model' },+ });+ vi.spyOn(runtime['client'].responses, 'create').mockResolvedValue({+ output_text: '{"ok":true}',+ } as any);+ vi.spyOn(runtime['client'].chat.completions, 'create').mockResolvedValue({} as any);++ const result = await runtime.generateObject({+ messages: [{ content: 'Generate JSON', role: 'user' }],+ model: 'logical-response-model',+ schema: {+ name: 'result',+ schema: {+ properties: { ok: { type: 'boolean' } },+ type: 'object',+ },+ },+ });++ expect(runtime['client'].responses.create).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'upstream-response-model' }),+ expect.anything(),+ );+ expect(runtime['client'].chat.completions.create).not.toHaveBeenCalled();+ expect(result).toEqual({ ok: true });+ });+it('should map disabled thinking to no reasoning effort for GPT-5.4 Responses generateObject', async () => {const mockResponse = {output_text: '{"name": "John", "age": 30}',diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 68ee873eda0..2891ce84777 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -47,6 +47,8 @@ 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 {@@ -102,7 +104,9 @@ export const CHAT_MODELS_BLOCK_LIST = [// 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 ConstructorOptions<T extends Record<string, any> = any> = LobeClientOptions &+ ModelIdMappingOptions &+ T;type OpenAIExtraParams = { prompt_cache_key?: string; safety_identifier?: string };type ChatCompletionCreateParamsWithPromptCacheKey = Omit<OpenAI.ChatCompletionCreateParamsNonStreaming,@@ -116,10 +120,11 @@ type ResponseCreateParamsWithPromptCacheKey = (| OpenAI.Responses.ResponseCreateParams) &OpenAIExtraParams;-export type CreateImageOptions = Omit<ClientOptions, 'apiKey'> & {- apiKey: string;- provider: string;-};+export type CreateImageOptions = Omit<ClientOptions, 'apiKey'> &+ ModelIdMappingOptions & {+ apiKey: string;+ provider: string;+ };const getGenerateObjectReasoningParams = ({reasoning_effort,@@ -149,10 +154,11 @@ const getGenerateObjectResponsesReasoningParams = ({: {};};-export type CreateVideoOptions = Omit<ClientOptions, 'apiKey'> & {- apiKey: string;- provider: string;-};+export type CreateVideoOptions = Omit<ClientOptions, 'apiKey'> &+ ModelIdMappingOptions & {+ apiKey: string;+ provider: string;+ };export interface CustomClientOptions<T extends Record<string, any> = any> {createChatCompletionStream?: (@@ -315,18 +321,23 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anprivate id: string;private logPrefix: string;+ private modelIdMappingOptions: ModelIdMappingOptions = {};baseURL!: string;protected _options: ConstructorOptions<T>;constructor(options: LobeClientOptions & Record<string, any> = {}) {+ const { modelIdMapping, ...inputOptions } = options as LobeClientOptions &+ Record<string, any> &+ ModelIdMappingOptions;const _options = {- ...options,- apiKey: options.apiKey?.trim() || DEFAULT_API_KEY,- baseURL: options.baseURL?.trim() || DEFAULT_BASE_URL,+ ...inputOptions,+ apiKey: inputOptions.apiKey?.trim() || DEFAULT_API_KEY,+ baseURL: inputOptions.baseURL?.trim() || DEFAULT_BASE_URL,};const { apiKey, baseURL = DEFAULT_BASE_URL, ...res } = _options;this._options = _options as ConstructorOptions<T>;+ this.modelIdMappingOptions = { modelIdMapping };if (!apiKey) throw AgentRuntimeError.createError(ErrorType?.invalidAPIKey);@@ -345,6 +356,24 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anthis.logPrefix = `lobe-model-runtime:${this.id}`;}+ protected getMappedModelId(model: string) {+ return resolveMappedModelId(model, this.modelIdMappingOptions);+ }++ private withMappedRequestModel<TPayload extends { model?: string }>(+ requestPayload: TPayload,+ logicalModel: string,+ ): TPayload {+ if (!requestPayload.model) return requestPayload;++ const mappedModel = this.getMappedModelId(logicalModel);+ if (requestPayload.model !== logicalModel || mappedModel === requestPayload.model) {+ return requestPayload;+ }++ return { ...requestPayload, model: mappedModel };+ }+/*** Determine if should use Responses API based on various configuration options* @param params - Configuration parameters@@ -521,7 +550,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an} as OpenAI.ChatCompletionCreateParamsStreaming);if ((handledPayload as any).apiMode === 'responses') {- return await this.handleResponseAPIMode(processedPayload, options);+ return await this.handleResponseAPIMode(processedPayload, options, payload.model);}// Sanitize temperature/top_p conflict for Claude 4+ models routed via OpenAI-compatible API.@@ -549,6 +578,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anconst optionApiKey = restOptions.apiKey;delete restOptions.apiKey;delete restOptions.baseURL;+ delete restOptions.modelIdMapping;const sanitizedApiKey = optionApiKey?.toString().trim() || DEFAULT_API_KEY;@@ -608,19 +638,17 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anpreserveThinking: _preserveThinking,...cleanProcessedPayload} = processedPayload as any;+ const customRequestPayload = {+ ...cleanProcessedPayload,+ ...resolveModelSamplingParameters(cleanProcessedPayload.model, cleanProcessedPayload, {+ normalizeTemperature: false,+ preferTemperature: true,+ }),+ };+response = customClient.createChatCompletionStream(this.client,- {- ...cleanProcessedPayload,- ...resolveModelSamplingParameters(- cleanProcessedPayload.model,- cleanProcessedPayload,- {- normalizeTemperature: false,- preferTemperature: true,- },- ),- },+ this.withMappedRequestModel(customRequestPayload, payload.model),this,) as any;} else {@@ -639,6 +667,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an),stream_options: includeUsageRequested ? { include_usage: true } : undefined,};+ const requestPayload = this.withMappedRequestModel(finalPayload, payload.model);log('sending chat completion request with %d messages', messages.length);@@ -646,10 +675,10 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an// eslint-disable-next-line no-consoleconsole.log('[requestPayload]');// eslint-disable-next-line no-console- console.log(JSON.stringify(finalPayload), '\n');+ console.log(JSON.stringify(requestPayload), '\n');}- response = (await this.client.chat.completions.create(finalPayload, {+ response = (await this.client.chat.completions.create(requestPayload, {// https://github.com/lobehub/lobe-chat/pull/318headers: { Accept: '*/*', ...options?.requestHeaders },signal: options?.signal,@@ -724,13 +753,18 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anreturn customCreateImage(payload, {...this._options,apiKey: this._options.apiKey!,+ modelIdMapping: this.modelIdMappingOptions.modelIdMapping,provider,});}log('using default createOpenAICompatibleImage');// Use the new createOpenAICompatibleImage function- return createOpenAICompatibleImage(this.client, payload, this.id);+ return createOpenAICompatibleImage(this.client, payload, this.id, {+ pricingModel: payload.model,+ requestModel: resolveMappedModelId(payload.model, this.modelIdMappingOptions),+ routingModel: payload.model,+ });}async createVideo(payload: CreateVideoPayload) {@@ -741,6 +775,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anreturn customCreateVideo(payload, {...this._options,apiKey: this._options.apiKey!,+ modelIdMapping: this.modelIdMappingOptions.modelIdMapping,provider,});}@@ -750,6 +785,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an...this._options,apiKey: this._options.apiKey!,baseURL: this._options.baseURL || '',+ modelIdMapping: this.modelIdMappingOptions.modelIdMapping,provider,});}@@ -879,15 +915,18 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an};const res = await this.client.chat.completions.create(- this.handleGenerateObjectPayload(payload, {- ...getGenerateObjectReasoningParams(payload),- messages,- model,- ...this.resolvePromptCacheKeyParams(model, options?.user),- tool_choice: { function: { name: tool.function.name }, type: 'function' },- tools: [tool],- user: options?.user,- }) as OpenAI.ChatCompletionCreateParamsNonStreaming,+ this.withMappedRequestModel(+ this.handleGenerateObjectPayload(payload, {+ ...getGenerateObjectReasoningParams(payload),+ messages,+ 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 },);@@ -978,15 +1017,18 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anif (shouldUseResponses) {log('calling responses.create for structured output');const res = await this.client!.responses.create(- {- input: messages,+ this.withMappedRequestModel(+ {+ input: messages,+ 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,- ...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,+ ),{ headers: options?.headers, signal: options?.signal },);@@ -1011,14 +1053,17 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anlet res: OpenAI.ChatCompletion;try {res = await this.client.chat.completions.create(- this.handleGenerateObjectPayload(payload, {- ...getGenerateObjectReasoningParams(payload),- messages,+ this.withMappedRequestModel(+ this.handleGenerateObjectPayload(payload, {+ ...getGenerateObjectReasoningParams(payload),+ messages,+ model,+ response_format: { json_schema: processedSchema, type: 'json_schema' },+ ...this.resolvePromptCacheKeyParams(model, options?.user),+ user: options?.user,+ }),model,- response_format: { json_schema: processedSchema, type: 'json_schema' },- ...this.resolvePromptCacheKeyParams(model, options?.user),- user: options?.user,- }) as OpenAI.ChatCompletionCreateParamsNonStreaming,+ ) as OpenAI.ChatCompletionCreateParamsNonStreaming,{ headers: options?.headers, signal: options?.signal },);} catch (error) {@@ -1067,6 +1112,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anoptions?: EmbeddingsOptions,): Promise<Embeddings[]> {const log = debug(`${this.logPrefix}:embeddings`);+ const requestPayload = withMappedModelId(payload, this.modelIdMappingOptions);log('embeddings called with model: %s, input items: %d',payload.model,@@ -1075,7 +1121,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = antry {const res = await this.client.embeddings.create(- { ...payload, encoding_format: 'float', user: options?.user },+ { ...requestPayload, encoding_format: 'float', user: options?.user },{ headers: options?.headers, signal: options?.signal },);@@ -1099,6 +1145,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anasync textToSpeech(payload: TextToSpeechPayload, options?: TextToSpeechOptions) {const log = debug(`${this.logPrefix}:textToSpeech`);+ const requestPayload = withMappedModelId(payload, this.modelIdMappingOptions);log('textToSpeech called with input length: %d, voice: %s',payload.input?.length || 0,@@ -1106,7 +1153,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an);try {- const mp3 = await this.client.audio.speech.create(payload as any, {+ const mp3 = await this.client.audio.speech.create(requestPayload as any, {headers: options?.headers,signal: options?.signal,});@@ -1121,6 +1168,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anasync transcribe(payload: ASRPayload, options?: ASROptions): Promise<ASRResponse> {const log = debug(`${this.logPrefix}:transcribe`);const { file, fileName, model, language, prompt, responseFormat, temperature } = payload;+ const requestModel = withMappedModelId(payload, this.modelIdMappingOptions).model;log('transcribe called with model: %s, audio size: %d bytes', model, file?.size || 0);try {@@ -1133,7 +1181,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an{file: uploadFile,language,- model,+ model: requestModel,prompt,response_format: responseFormat,temperature,@@ -1308,6 +1356,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anprivate 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);@@ -1367,17 +1416,18 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anpreferTemperature: true,}),} as ResponseCreateParamsWithPromptCacheKey;+ const requestPayload = this.withMappedRequestModel(postPayload, usageModel);if (debugParams?.responses?.()) {// eslint-disable-next-line no-consoleconsole.log('[requestPayload]');// eslint-disable-next-line no-console- console.log(JSON.stringify(postPayload), '\n');+ console.log(JSON.stringify(requestPayload), '\n');}log('sending responses.create request');- const response = await this.client.responses.create(postPayload, {+ const response = await this.client.responses.create(requestPayload, {headers: options?.requestHeaders,signal: options?.signal,});@@ -1387,8 +1437,8 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = ancallbacks: options?.callback,payload: {apiMode: 'responses',- model: payload.model,- pricing: await getModelPricing(payload.model, this.id),+ model: usageModel,+ pricing: await getModelPricing(usageModel, this.id),provider: this.id,},};@@ -1481,15 +1531,18 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an});const res = await this.client.responses.create(- {- input,- model,- ...this.resolvePromptCacheKeyParams(model, options?.user),- tool_choice: 'required',- tools: tools!.map((tool) => this.convertChatCompletionToolToResponseTool(tool)),- // Responses API replaced `user` with `safety_identifier`; some endpoints reject `user`- safety_identifier: options?.user,- } as any,+ this.withMappedRequestModel(+ {+ input,+ model,+ ...this.resolvePromptCacheKeyParams(model, options?.user),+ tool_choice: 'required',+ tools: tools!.map((tool) => this.convertChatCompletionToolToResponseTool(tool)),+ // Responses API replaced `user` with `safety_identifier`; some endpoints reject `user`+ safety_identifier: options?.user,+ } as any,+ payload.model,+ ),{ headers: options?.headers, signal: options?.signal },);@@ -1523,15 +1576,18 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anconst msgs = messages;const res = await this.client.chat.completions.create(- this.handleGenerateObjectPayload(payload, {- ...getGenerateObjectReasoningParams(payload),- messages: msgs,- model,- ...this.resolvePromptCacheKeyParams(model, options?.user),- tool_choice: 'required',- tools,- user: options?.user,- }) as OpenAI.ChatCompletionCreateParamsNonStreaming,+ 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 },);diff --git a/packages/model-runtime/src/providers/azureOpenai/index.test.ts b/packages/model-runtime/src/providers/azureOpenai/index.test.tsindex 3625b8a506f..fc7ce96bcc2 100644--- a/packages/model-runtime/src/providers/azureOpenai/index.test.ts+++ b/packages/model-runtime/src/providers/azureOpenai/index.test.ts@@ -445,6 +445,30 @@ describe('LobeAzureOpenAI', () => {expect(res).toEqual({ imageUrl: url });});+ it('should use mapped model id for image generation requests', async () => {+ instance = new LobeAzureOpenAI({+ apiKey: 'test_key',+ baseURL: 'https://test.openai.azure.com/',+ modelIdMapping: { 'gpt-image-1': 'azure-image-deployment' },+ });+ const editSpy = vi+ .spyOn(instance['client'].images, 'edit')+ .mockResolvedValue({ data: [{ url: 'https://example.com/mapped.png' }] } as any);+ const helpers = await import('../../core/contextBuilders/openai');+ vi.spyOn(helpers, 'convertImageUrlToFile').mockResolvedValue({} as any);++ await instance.createImage({+ model: 'gpt-image-1',+ params: { imageUrl: 'https://example.com/source.png', prompt: 'mapped cat' },+ });++ expect(vi.mocked(editSpy).mock.calls[0][0]).toMatchObject({+ input_fidelity: 'high',+ model: 'azure-image-deployment',+ prompt: 'mapped cat',+ });+ });+it('should parse string JSON response from images.generate', async () => {const url = 'https://example.com/str.png';const payload = JSON.stringify({ data: [{ url }] });diff --git a/packages/model-runtime/src/providers/azureOpenai/index.ts b/packages/model-runtime/src/providers/azureOpenai/index.tsindex d803d6ff2ad..e4cf0b5a699 100644--- a/packages/model-runtime/src/providers/azureOpenai/index.ts+++ b/packages/model-runtime/src/providers/azureOpenai/index.ts@@ -70,7 +70,7 @@ const normalizeAzureBaseURL = (value?: string) => {const maskSensitiveUrl = (url: string) => {const regex = /^(https:\/\/)([^.]+)(\.(?:openai\.azure\.com|cognitiveservices\.azure\.com).*)$/;- return url.replace(regex, (match, protocol, subdomain, rest) => `${protocol}***${rest}`);+ return url.replace(regex, (_match, protocol, _subdomain, rest) => `${protocol}***${rest}`);};const BaseAzureOpenAI = createOpenAICompatibleRuntime({@@ -210,7 +210,8 @@ export class LobeAzureOpenAI extends BaseAzureOpenAI {async createImage(payload: CreateImagePayload) {const { model, params } = payload;- azureImageLogger('Creating image with model: %s and params: %O', model, params);+ const requestModel = this.getMappedModelId(model);+ azureImageLogger('Creating image with model: %s and params: %O', requestModel, params);try {const userInput: Record<string, any> = { ...params };@@ -244,7 +245,7 @@ export class LobeAzureOpenAI extends BaseAzureOpenAI {const shouldUseInputFidelity = isImageEdit && supportsImageInputFidelity(model);const azureImageOptions: Record<string, any> = {- model,+ model: requestModel,n: 1,...(shouldUseInputFidelity ? { input_fidelity: 'high' } : {}),...userInput,diff --git a/packages/model-runtime/src/providers/deepseek/generateObject.ts b/packages/model-runtime/src/providers/deepseek/generateObject.tsindex b58fb554e5e..4ffc7f49c66 100644--- a/packages/model-runtime/src/providers/deepseek/generateObject.ts+++ b/packages/model-runtime/src/providers/deepseek/generateObject.ts@@ -21,6 +21,7 @@ export const createDeepSeekAnthropicGenerateObject = async (payload: GenerateObjectPayload,options?: GenerateObjectOptions,pricing?: Pricing,+ config?: AnthropicGenerateObjectConfig,) => {// DeepSeek's Anthropic-compatible endpoint rejects named schema tool_choice// while thinking is active, but accepts `{ type: "any" }`. V4 models may@@ -51,6 +52,7 @@ export const createDeepSeekAnthropicGenerateObject = async (} as Anthropic;return createAnthropicGenerateObject(sanitizedClient, payload, options, pricing, {+ requestModel: config?.requestModel,requestParams,schemaToolChoice: thinkingDisabled ? 'tool' : 'any',});diff --git a/packages/model-runtime/src/providers/fal/index.test.ts b/packages/model-runtime/src/providers/fal/index.test.tsindex 212631cfd5d..764c1eb956d 100644--- a/packages/model-runtime/src/providers/fal/index.test.ts+++ b/packages/model-runtime/src/providers/fal/index.test.ts@@ -105,6 +105,32 @@ describe('LobeFalAI', () => {});});+ it('should use mapped model id for fal endpoint requests', async () => {+ const mappedInstance = new LobeFalAI({+ apiKey: 'test-api-key',+ modelIdMapping: { 'logical-fal-image': 'fal-ai/upstream/image-model' },+ });+ mockFal.subscribe.mockResolvedValue({+ data: {+ images: [{ url: 'https://example.com/mapped.jpg' }],+ },+ requestId: 'test-request-id',+ } as any);++ await mappedInstance.createImage({+ model: 'logical-fal-image',+ params: { prompt: 'A mapped image' },+ });++ expect(mockFal.subscribe).toHaveBeenCalledWith('fal-ai/upstream/image-model', {+ input: {+ enable_safety_checker: false,+ num_images: 1,+ prompt: 'A mapped image',+ },+ });+ });+it('should map standard parameters to fal-specific parameters', async () => {// Arrangeconst mockImageResponse = {diff --git a/packages/model-runtime/src/providers/fal/index.ts b/packages/model-runtime/src/providers/fal/index.tsindex c659273773f..e7e648a9375 100644--- a/packages/model-runtime/src/providers/fal/index.ts+++ b/packages/model-runtime/src/providers/fal/index.ts@@ -8,6 +8,8 @@ import type { LobeRuntimeAI } from '../../core/BaseAI';import { AgentRuntimeErrorType } from '../../types/error';import type { CreateImagePayload, CreateImageResponse } from '../../types/image';import { AgentRuntimeError } from '../../utils/createError';+import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';+import { resolveMappedModelId } from '../../utils/modelIdMapping';// Create debug loggerconst log = debug('lobe-image:fal');@@ -15,19 +17,26 @@ const log = debug('lobe-image:fal');type FluxDevOutput = Awaited<ReturnType<typeof fal.subscribe<'fal-ai/flux/dev'>>>['data'];export class LobeFalAI implements LobeRuntimeAI {+ private readonly modelIdMappingOptions: ModelIdMappingOptions;+// OpenAI SDK v6 widened `apiKey` to `string | ApiKeySetter`; lobehub only uses the string form.- constructor({ apiKey }: Omit<ClientOptions, 'apiKey'> & { apiKey?: string } = {}) {+ constructor({+ apiKey,+ modelIdMapping,+ }: Omit<ClientOptions, 'apiKey'> & { apiKey?: string } & ModelIdMappingOptions = {}) {if (!apiKey) throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey);fal.config({credentials: apiKey,});+ this.modelIdMappingOptions = { modelIdMapping };log('FalAI initialized with apiKey: %s', apiKey ? '*****' : 'Not set');}async createImage(payload: CreateImagePayload): Promise<CreateImageResponse> {const { model, params } = payload;- log('Creating image with model: %s and params: %O', model, params);+ const requestModel = resolveMappedModelId(model, this.modelIdMappingOptions);+ log('Creating image with model: %s and params: %O', requestModel, params);const paramsMap = new Map<RuntimeImageGenParamsValue, string>([['steps', 'num_inference_steps'],@@ -65,12 +74,12 @@ export class LobeFalAI implements LobeRuntimeAI {}const modelsAcceleratedByDefault = new Set<string>(['flux/krea']);- if (modelsAcceleratedByDefault.has(model)) {+ if (modelsAcceleratedByDefault.has(requestModel)) {defaultInput['acceleration'] = 'high';}// Ensure model has fal-ai/ prefix- let endpoint = model.startsWith('fal-ai/') ? model : `fal-ai/${model}`;+ let endpoint = requestModel.startsWith('fal-ai/') ? requestModel : `fal-ai/${requestModel}`;const hasImageUrls = (params.imageUrls?.length ?? 0) > 0;if (['fal-ai/bytedance/seedream/v', 'fal-ai/hunyuan-image/v'].some((m) => endpoint.startsWith(m))diff --git a/packages/model-runtime/src/providers/google/createImage.ts b/packages/model-runtime/src/providers/google/createImage.tsindex 0d94cfa4eac..400c0006467 100644--- a/packages/model-runtime/src/providers/google/createImage.ts+++ b/packages/model-runtime/src/providers/google/createImage.ts@@ -83,6 +83,11 @@ interface GoogleImageErrorMetadata {reasonCode?: string;}+interface GoogleImageOptions {+ pricingModel?: string;+ routingModel?: string;+}+// Keep raw provider responses available to upstream error handlers without// exposing text-only no-image responses through JSON serialization.const attachNonSerializableProviderResponse = <T extends object>(@@ -286,6 +291,7 @@ async function generateImageByChatModel(client: GoogleGenAI,payload: CreateImagePayload,provider: string,+ options?: Pick<GoogleImageOptions, 'pricingModel'>,): Promise<CreateImageResponse> {const { model, params } = payload;const actualModel = model.replace(':image', '');@@ -349,7 +355,7 @@ async function generateImageByChatModel(const imageResponse = extractImageFromResponse(response);if (response.usageMetadata) {- const pricing = await getModelPricing(model, provider);+ const pricing = await getModelPricing(options?.pricingModel ?? model, provider);imageResponse.modelUsage = convertGoogleAIUsage(response.usageMetadata, pricing);}@@ -363,13 +369,14 @@ export async function createGoogleImage(client: GoogleGenAI,provider: string,payload: CreateImagePayload,+ options?: GoogleImageOptions,): Promise<CreateImageResponse> {try {- const { model } = payload;+ const routingModel = options?.routingModel ?? payload.model;// Handle Gemini 2.5 Flash Image models that use generateContent- if (model.endsWith(':image')) {- return await generateImageByChatModel(client, payload, provider);+ if (routingModel.endsWith(':image')) {+ return await generateImageByChatModel(client, payload, provider, options);}// Handle traditional Imagen models that use generateImagesdiff --git a/packages/model-runtime/src/providers/google/index.test.ts b/packages/model-runtime/src/providers/google/index.test.tsindex 1b4de27ac36..ade95a94ae3 100644--- a/packages/model-runtime/src/providers/google/index.test.ts+++ b/packages/model-runtime/src/providers/google/index.test.ts@@ -61,6 +61,28 @@ describe('LobeGoogleAI', () => {// Assertexpect(result).toBeInstanceOf(Response);});++ it('should use mapped model id for upstream chat requests while keeping pricing on logical model', async () => {+ const mappedInstance = new LobeGoogleAI({+ apiKey: 'test',+ modelIdMapping: { 'gemini-logical': 'gemini-upstream' },+ });+ const mockStreamData = createEmptyAsyncGenerator<GenerateContentResponse>();+ vi.spyOn(mappedInstance['client'].models, 'generateContentStream').mockResolvedValue(+ mockStreamData,+ );++ await mappedInstance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gemini-logical',+ temperature: 0,+ });++ const callArgs = (mappedInstance['client'].models.generateContentStream as any).mock.calls[0];+ expect(callArgs[0].model).toBe('gemini-upstream');+ expect(getModelPricingMock).toHaveBeenCalledWith('gemini-logical', provider);+ });+it('should handle text messages correctly', async () => {// Mock Google AI SDK's generateContentStream method to return a successful response streamconst mockStream = new ReadableStream({@@ -1075,6 +1097,70 @@ describe('buildGoogleToolsWithSearch', () => {});});+describe('modelIdMapping', () => {+ it('should use mapped model id for upstream chat-image requests while keeping logical model usage pricing', async () => {+ const mappedInstance = new LobeGoogleAI({+ apiKey: 'test',+ modelIdMapping: { 'gemini-logical:image': 'gemini-upstream-image' },+ });+ const generateContentMock = vi+ .spyOn(mappedInstance['client'].models, 'generateContent')+ .mockResolvedValue({+ candidates: [+ {+ content: {+ parts: [{ inlineData: { data: 'image-base64', mimeType: 'image/png' } }],+ },+ },+ ],+ usageMetadata: {+ candidatesTokenCount: 1,+ promptTokenCount: 1,+ totalTokenCount: 2,+ },+ } as any);++ const result = await mappedInstance.createImage!({+ model: 'gemini-logical:image',+ params: { prompt: 'Create a sunset' },+ });++ expect(result.imageUrl).toBe('data:image/png;base64,image-base64');+ expect(generateContentMock.mock.calls[0][0].model).toBe('gemini-upstream-image');+ expect(getModelPricingMock).toHaveBeenCalledWith('gemini-logical:image', provider);+ });++ it('should use mapped model id for upstream generateObject requests while keeping pricing on logical model', async () => {+ const mappedInstance = new LobeGoogleAI({+ apiKey: 'test',+ modelIdMapping: { 'gemini-logical': 'gemini-upstream' },+ });+ const generateContentMock = vi+ .spyOn(mappedInstance['client'].models, 'generateContent')+ .mockResolvedValue({ text: '{"ok":true}' } as any);++ const result = await mappedInstance.generateObject(+ {+ messages: [{ content: 'Return JSON', role: 'user' }],+ model: 'gemini-logical',+ schema: {+ name: 'result',+ schema: {+ properties: { ok: { type: 'boolean' } },+ required: ['ok'],+ type: 'object',+ },+ },+ } as any,+ {},+ );++ expect(result).toEqual({ ok: true });+ expect(generateContentMock.mock.calls[0][0].model).toBe('gemini-upstream');+ expect(getModelPricingMock).toHaveBeenCalledWith('gemini-logical', provider);+ });+});+describe('models', () => {it('should pass API Key via x-goog-api-key header instead of URL parameter', async () => {const mockFetch = vi.fn().mockResolvedValue({diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.tsindex 20e29fefd8f..9d05170ac2c 100644--- a/packages/model-runtime/src/providers/google/index.ts+++ b/packages/model-runtime/src/providers/google/index.ts@@ -28,6 +28,8 @@ import { AgentRuntimeError } from '../../utils/createError';import { debugStream } from '../../utils/debugStream';import { getModelPricing } from '../../utils/getModelPricing';import { parseGoogleErrorMessage } from '../../utils/googleErrorParser';+import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';+import { withMappedModelId } from '../../utils/modelIdMapping';import { StreamingResponse } from '../../utils/response';import { createGoogleImage } from './createImage';import { createGoogleVideo, pollGoogleVideoOperation } from './createVideo';@@ -86,7 +88,7 @@ function getThreshold(model: string): HarmBlockThreshold {const DEFAULT_BASE_URL = 'https://generativelanguage.googleapis.com';-interface LobeGoogleAIParams {+interface LobeGoogleAIParams extends ModelIdMappingOptions {apiKey?: string;baseURL?: string;client?: GoogleGenAI;@@ -112,6 +114,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {baseURL?: string;apiKey?: string;provider: string;+ private readonly modelIdMappingOptions: ModelIdMappingOptions;constructor({apiKey,@@ -120,6 +123,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {isVertexAi,id,defaultHeaders,+ modelIdMapping,}: LobeGoogleAIParams = {}) {if (!apiKey) throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey);@@ -131,6 +135,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {this.client = client ?? new GoogleGenAI({ apiKey, httpOptions });this.baseURL = client ? undefined : baseURL || DEFAULT_BASE_URL;this.isVertexAi = isVertexAi || false;+ this.modelIdMappingOptions = { modelIdMapping };this.provider = id || (isVertexAi ? 'vertexai' : 'google');}@@ -214,8 +219,9 @@ export class LobeGoogleAI implements LobeRuntimeAI {};const inputStartAt = Date.now();+ const requestPayload = withMappedModelId(payload, this.modelIdMappingOptions);- const finalPayload = { config, contents, model };+ const finalPayload = { config, contents, model: requestPayload.model };const key = this.isVertexAi? 'DEBUG_VERTEX_AI_CHAT_COMPLETION': 'DEBUG_GOOGLE_CHAT_COMPLETION';@@ -270,11 +276,20 @@ export class LobeGoogleAI implements LobeRuntimeAI {* @see https://ai.google.dev/gemini-api/docs/image-generation#imagen*/async createImage(payload: CreateImagePayload): Promise<CreateImageResponse> {- return createGoogleImage(this.client, this.provider, payload);+ const requestPayload = withMappedModelId(payload, this.modelIdMappingOptions);++ return createGoogleImage(this.client, this.provider, requestPayload, {+ pricingModel: payload.model,+ routingModel: payload.model,+ });}async createVideo(payload: CreateVideoPayload): Promise<CreateVideoResponse> {- return createGoogleVideo(this.client, this.provider, payload);+ return createGoogleVideo(+ this.client,+ this.provider,+ withMappedModelId(payload, this.modelIdMappingOptions),+ );}/**@@ -283,7 +298,11 @@ export class LobeGoogleAI implements LobeRuntimeAI {*/async transcribe(payload: ASRPayload, options?: ASROptions): Promise<ASRResponse> {try {- return await createGoogleTranscription(this.client, payload, options);+ return await createGoogleTranscription(+ this.client,+ withMappedModelId(payload, this.modelIdMappingOptions),+ options,+ );} catch (e) {const err = e as Error;@@ -316,12 +335,13 @@ export class LobeGoogleAI implements LobeRuntimeAI {// Convert OpenAI messages to Google formatconst contents = await buildGoogleMessages(payload.messages, { model: payload.model });const pricing = await getModelPricing(payload.model, this.provider);+ const requestPayload = withMappedModelId(payload, this.modelIdMappingOptions);// Handle tools-based structured outputif (payload.tools && payload.tools.length > 0) {return createGoogleGenerateObjectWithTools(this.client,- { contents, model: payload.model, tools: payload.tools },+ { contents, model: requestPayload.model, tools: payload.tools },options,pricing,);@@ -331,7 +351,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {if (payload.schema) {return createGoogleGenerateObject(this.client,- { contents, model: payload.model, schema: payload.schema },+ { contents, model: requestPayload.model, schema: payload.schema },options,pricing,);diff --git a/packages/model-runtime/src/providers/minimax/createImage.ts b/packages/model-runtime/src/providers/minimax/createImage.tsindex f2f3e10704d..354ba7ca71b 100644--- a/packages/model-runtime/src/providers/minimax/createImage.ts+++ b/packages/model-runtime/src/providers/minimax/createImage.ts@@ -3,6 +3,7 @@ import createDebug from 'debug';import type { CreateImageOptions } from '../../core/openaiCompatibleFactory';import type { CreateImagePayload, CreateImageResponse } from '../../types/image';import { AgentRuntimeError } from '../../utils/createError';+import { resolveMappedModelId } from '../../utils/modelIdMapping';const log = createDebug('lobe-image:minimax');@@ -30,13 +31,14 @@ export async function createMiniMaxImage(): Promise<CreateImageResponse> {const { apiKey, baseURL, provider } = options;const { model, params } = payload;+ const requestModel = resolveMappedModelId(model, options);try {const endpoint = `${baseURL}/image_generation`;const requestBody: Record<string, unknown> = {aspect_ratio: params.aspectRatio,- model,+ model: requestModel,n: 1,prompt: params.prompt,aigc_watermark: params.watermark ?? false,diff --git a/packages/model-runtime/src/providers/minimax/createVideo.ts b/packages/model-runtime/src/providers/minimax/createVideo.tsindex bdb69f311da..beff6ef65f5 100644--- a/packages/model-runtime/src/providers/minimax/createVideo.ts+++ b/packages/model-runtime/src/providers/minimax/createVideo.ts@@ -2,6 +2,7 @@ import createDebug from 'debug';import type { CreateVideoOptions } from '../../core/openaiCompatibleFactory';import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';+import { resolveMappedModelId } from '../../utils/modelIdMapping';const log = createDebug('lobe-video:minimax');@@ -136,12 +137,13 @@ export async function createMiniMaxVideo(options: CreateVideoOptions,): Promise<CreateVideoResponse> {const { model, params } = payload;+ const requestModel = resolveMappedModelId(model, options);const { prompt, imageUrl, endImageUrl, duration, resolution } = params;const baseURL = options.baseURL || 'https://api.minimaxi.com/v1';const body: Record<string, unknown> = {- model,+ model: requestModel,prompt,aigc_watermark: params.watermark ?? false,prompt_optimizer: params.promptExtend ?? false,diff --git a/packages/model-runtime/src/providers/minimax/index.test.ts b/packages/model-runtime/src/providers/minimax/index.test.tsindex d9fc93dddd6..3a779279f38 100644--- a/packages/model-runtime/src/providers/minimax/index.test.ts+++ b/packages/model-runtime/src/providers/minimax/index.test.ts@@ -140,6 +140,58 @@ describe('LobeMinimaxAI', () => {'Unsupported MiniMax sdkType: invalid',);});++ it('should pass modelIdMapping to the OpenAI-compatible runtime', async () => {+ const modelIdMapping = { 'minimax-public': 'MiniMax-M3' };+ const chatSpy = vi+ .spyOn(LobeMinimaxOpenAI.prototype as any, 'chat')+ .mockResolvedValue(new Response());++ try {+ const runtime = new LobeMinimaxAI({+ apiKey: 'test',+ modelIdMapping,+ sdkType: 'openai',+ });++ await runtime.chat({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'minimax-public',+ });++ expect((chatSpy.mock.contexts[0] as any).modelIdMappingOptions.modelIdMapping).toEqual(+ modelIdMapping,+ );+ } finally {+ chatSpy.mockRestore();+ }+ });++ it('should pass modelIdMapping to the Anthropic-compatible runtime', async () => {+ const modelIdMapping = { 'minimax-public': 'MiniMax-M3' };+ const chatSpy = vi+ .spyOn(LobeMinimaxAnthropicAI.prototype as any, 'chat')+ .mockResolvedValue(new Response());++ try {+ const runtime = new LobeMinimaxAI({+ apiKey: 'test',+ modelIdMapping,+ sdkType: 'anthropic',+ });++ await runtime.chat({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'minimax-public',+ });++ expect((chatSpy.mock.contexts[0] as any).modelIdMappingOptions.modelIdMapping).toEqual(+ modelIdMapping,+ );+ } finally {+ chatSpy.mockRestore();+ }+ });});});@@ -152,6 +204,55 @@ describe('LobeMinimaxAnthropicAI', () => {expect((runtime as any).baseURL).toEqual(anthropicBaseURL);});});++ it('should derive Anthropic params from logical model while sending mapped model id', async () => {+ const runtime = new LobeMinimaxAnthropicAI({+ apiKey: 'test',+ modelIdMapping: { 'MiniMax-M3': 'upstream-minimax-m3' },+ });+ const createSpy = vi+ .spyOn((runtime as any).client.messages, 'create')+ .mockResolvedValue({ content: [] } as any);++ await runtime.chat({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'MiniMax-M3',+ responseMode: 'json',+ stream: false,+ } as any);++ expect(createSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ max_tokens: 524_288,+ model: 'upstream-minimax-m3',+ }),+ expect.anything(),+ );+ });+});++describe('LobeMinimaxOpenAI', () => {+ it('should keep MiniMax-M3 payload handling on logical model while sending mapped model id', async () => {+ const runtime = new LobeMinimaxOpenAI({+ apiKey: 'test',+ modelIdMapping: { 'MiniMax-M3': 'upstream-minimax-m3' },+ });+ const createSpy = vi+ .spyOn(runtime['client'].chat.completions, 'create')+ .mockResolvedValue(new ReadableStream() as any);++ await runtime.chat({+ messages: [{ content: 'hi', role: 'user' }],+ model: 'MiniMax-M3',+ thinking: { type: 'disabled' },+ } as any);++ const requestPayload = createSpy.mock.calls[0][0] as any;+ expect(requestPayload.model).toBe('upstream-minimax-m3');+ expect(requestPayload).toHaveProperty('max_completion_tokens');+ expect(requestPayload).not.toHaveProperty('max_tokens');+ expect(requestPayload.thinking).toEqual({ type: 'disabled' });+ });});describe('LobeMinimaxAI - handlePayload', () => {diff --git a/packages/model-runtime/src/providers/vertexai/index.test.ts b/packages/model-runtime/src/providers/vertexai/index.test.tsindex e5fbd0bd9a5..40d9fc837a8 100644--- a/packages/model-runtime/src/providers/vertexai/index.test.ts+++ b/packages/model-runtime/src/providers/vertexai/index.test.ts@@ -1,7 +1,9 @@// @vitest-environment node-import { describe, expect, it, vi } from 'vitest';+import { GoogleGenAI } from '@google/genai';+import { afterEach, describe, expect, it, vi } from 'vitest';import { AgentRuntimeErrorType } from '../../types/error';+import { LobeGoogleAI } from '../google';import { LobeVertexAI } from './index';// Mock dependencies@@ -26,6 +28,10 @@ vi.mock('../google', () => ({}));describe('LobeVertexAI', () => {+ afterEach(() => {+ vi.clearAllMocks();+ });+describe('initFromVertexAI', () => {it('should create LobeVertexAI instance with default location', () => {const instance = LobeVertexAI.initFromVertexAI();@@ -40,6 +46,23 @@ describe('LobeVertexAI', () => {expect(instance).toBeDefined();});+ it('should pass modelIdMapping to LobeGoogleAI without passing it to GoogleGenAI', () => {+ LobeVertexAI.initFromVertexAI({+ location: 'us-central1',+ modelIdMapping: { 'logical-gemini': 'vertex-upstream' },+ project: 'test-project',+ });++ const googleGenAIOptions = vi.mocked(GoogleGenAI).mock.calls.at(-1)?.[0] as any;+ const lobeGoogleAIOptions = vi.mocked(LobeGoogleAI).mock.calls.at(-1)?.[0] as any;++ expect(googleGenAIOptions.modelIdMapping).toBeUndefined();+ expect(lobeGoogleAIOptions).toMatchObject({+ isVertexAi: true,+ modelIdMapping: { 'logical-gemini': 'vertex-upstream' },+ });+ });+it('should throw InvalidVertexCredentials error when IllegalArgumentError occurs', () => {try {LobeVertexAI.initFromVertexAI({diff --git a/packages/model-runtime/src/providers/vertexai/index.ts b/packages/model-runtime/src/providers/vertexai/index.tsindex 5a158e71bde..36e13973697 100644--- a/packages/model-runtime/src/providers/vertexai/index.ts+++ b/packages/model-runtime/src/providers/vertexai/index.ts@@ -3,20 +3,28 @@ import { GoogleGenAI } from '@google/genai';import { AgentRuntimeErrorType } from '../../types/error';import { AgentRuntimeError } from '../../utils/createError';+import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';import { LobeGoogleAI } from '../google';const DEFAULT_VERTEXAI_LOCATION = 'global';+type VertexAIInitOptions = GoogleGenAIOptions & ModelIdMappingOptions;export class LobeVertexAI extends LobeGoogleAI {- static initFromVertexAI(params?: GoogleGenAIOptions) {+ static initFromVertexAI(params?: VertexAIInitOptions) {try {+ const { modelIdMapping, ...googleOptions } = params ?? {};const client = new GoogleGenAI({- ...params,- location: params?.location ?? DEFAULT_VERTEXAI_LOCATION, // @google/genai throws an error if location is not provided+ ...googleOptions,+ location: googleOptions.location ?? DEFAULT_VERTEXAI_LOCATION, // @google/genai throws an error if location is not providedvertexai: true,});- return new LobeGoogleAI({ apiKey: 'avoid-error', client, isVertexAi: true });+ return new LobeGoogleAI({+ apiKey: 'avoid-error',+ client,+ isVertexAi: true,+ modelIdMapping,+ });} catch (e) {const err = e as Error;diff --git a/packages/model-runtime/src/providers/zhipu/createImage.ts b/packages/model-runtime/src/providers/zhipu/createImage.tsindex cad55a7b5a0..66686da6466 100644--- a/packages/model-runtime/src/providers/zhipu/createImage.ts+++ b/packages/model-runtime/src/providers/zhipu/createImage.ts@@ -4,6 +4,7 @@ import type { CreateImageOptions } from '../../core/openaiCompatibleFactory';import type { CreateImagePayload, CreateImageResponse } from '../../types/image';import type { TaskResult } from '../../utils/asyncifyPolling';import { asyncifyPolling } from '../../utils/asyncifyPolling';+import { resolveMappedModelId } from '../../utils/modelIdMapping';const log = createDebug('lobe-image:zhipu');@@ -101,14 +102,15 @@ export async function createZhipuImage(options: CreateImageOptions,): Promise<CreateImageResponse> {const { model, params } = payload;+ const requestModel = resolveMappedModelId(model, options);const { prompt, resolution, size, watermark, width, height } = params;- log('Creating image with Zhipu API - model: %s, params: %O', model, params);+ log('Creating image with Zhipu API - model: %s, params: %O', requestModel, params);const baseURL = options.baseURL || 'https://open.bigmodel.cn/api/paas/v4';const body: Record<string, unknown> = {- model,+ model: requestModel,prompt,...(resolution && { quality: resolution }),};diff --git a/packages/model-runtime/src/providers/zhipu/createVideo.ts b/packages/model-runtime/src/providers/zhipu/createVideo.tsindex 3fe27309a29..9a43a0eae3f 100644--- a/packages/model-runtime/src/providers/zhipu/createVideo.ts+++ b/packages/model-runtime/src/providers/zhipu/createVideo.ts@@ -6,6 +6,7 @@ import type {CreateVideoResponse,PollVideoStatusResult,} from '../../types/video';+import { resolveMappedModelId } from '../../utils/modelIdMapping';const log = createDebug('lobe-video:zhipu');@@ -90,6 +91,7 @@ export async function createZhipuVideo(options: CreateVideoOptions,): Promise<CreateVideoResponse> {const { model, params } = payload;+ const requestModel = resolveMappedModelId(model, options);const {prompt,imageUrl,@@ -103,13 +105,13 @@ export async function createZhipuVideo(watermark,} = params;- log('Creating video with Zhipu API - model: %s, params: %O', model, params);+ log('Creating video with Zhipu API - model: %s, params: %O', requestModel, params);const baseURL = options.baseURL || 'https://open.bigmodel.cn/api/paas/v4';// Build request body based on Zhipu CogVideoX API formatconst body: Record<string, unknown> = {- model,+ model: requestModel,prompt,};diff --git a/packages/model-runtime/src/providers/zhipu/index.test.ts b/packages/model-runtime/src/providers/zhipu/index.test.tsindex a3b91c4a508..230e958c961 100644--- a/packages/model-runtime/src/providers/zhipu/index.test.ts+++ b/packages/model-runtime/src/providers/zhipu/index.test.ts@@ -16,6 +16,10 @@ testProvider({},});+vi.mock('@lobechat/business-model-bank/model-config', () => ({+ loadModels: vi.fn().mockResolvedValue([]),+}));+// Mock the console.error to avoid polluting test outputvi.spyOn(console, 'error').mockImplementation(() => {});@@ -51,6 +55,32 @@ describe('LobeZhipuAI - custom features', () => {});describe('handlePayload', () => {+ it('should send mapped model id when modelIdMapping is configured', async () => {+ const mappedInstance = new LobeZhipuAI({+ apiKey: 'test',+ modelIdMapping: { 'glm-4-alltools': 'upstream-glm-deployment' },+ });+ vi.spyOn(mappedInstance['client'].chat.completions, 'create').mockResolvedValue(+ new ReadableStream() as any,+ );++ await mappedInstance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'glm-4-alltools',+ temperature: 2,+ top_p: 2,+ });++ expect(mappedInstance['client'].chat.completions.create).toHaveBeenCalledWith(+ expect.objectContaining({+ model: 'upstream-glm-deployment',+ temperature: 0.99,+ top_p: 0.99,+ }),+ expect.anything(),+ );+ });+describe('Web Search Feature', () => {it('should add web_search tool when enabledSearch is true', async () => {await instance.chat({diff --git a/packages/model-runtime/src/utils/modelIdMapping.ts b/packages/model-runtime/src/utils/modelIdMapping.tsnew file mode 100644index 00000000000..358a2c2ebbd--- /dev/null+++ b/packages/model-runtime/src/utils/modelIdMapping.ts@@ -0,0 +1,15 @@+export interface ModelIdMappingOptions {+ modelIdMapping?: Record<string, string>;+}++export const resolveMappedModelId = (model: string, options?: ModelIdMappingOptions) =>+ options?.modelIdMapping?.[model] ?? model;++export const withMappedModelId = <T extends { model: string }>(+ payload: T,+ options?: ModelIdMappingOptions,+): T => {+ const model = resolveMappedModelId(payload.model, options);++ return model === payload.model ? payload : { ...payload, model };+};