Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: optimize newapi pricing queries and model batch update (#15656)

sxjeruf46a8ab60f87
diff --git a/packages/database/src/models/__tests__/aiModel.test.ts b/packages/database/src/models/__tests__/aiModel.test.ts
index acec43b29fa..a758848e405 100644
--- a/packages/database/src/models/__tests__/aiModel.test.ts
+++ b/packages/database/src/models/__tests__/aiModel.test.ts
@@ -279,8 +279,8 @@ describe('AiModelModel', () => {
});
describe('batchUpdateAiModels', () => {
- it('should insert new models and update existing ones', async () => {
- // Create an initial model
+ it('should insert new models and preserve existing user-editable fields on conflict', async () => {
+ // Create an initial model — displayName set by user
await aiProviderModel.create({
id: 'existing-model',
providerId: 'openai',
@@ -290,10 +290,12 @@ describe('AiModelModel', () => {
const models = [
{
id: 'existing-model',
+ // Provider sends a new displayName, but DB-first COALESCE keeps 'Old Name'
displayName: 'Updated Name',
},
{
id: 'new-model',
+ // No existing row — incoming value is used
displayName: 'New Model',
},
] as AiProviderModelListItem[];
@@ -302,10 +304,92 @@ describe('AiModelModel', () => {
const allModels = await aiProviderModel.query();
expect(allModels).toHaveLength(2);
+ // Existing non-null displayName is preserved (DB-first)
expect(allModels.find((m) => m.id === 'existing-model')?.displayName).toBe('Old Name');
+ // New model has no previous value → incoming value fills it
expect(allModels.find((m) => m.id === 'new-model')?.displayName).toBe('New Model');
});
+ it('should fill NULL user-editable fields from incoming data', async () => {
+ // Create a model with no displayName, contextWindowTokens, abilities, parameters, or type override
+ await serverDB.insert(aiModels).values({
+ id: 'bare-model',
+ providerId: 'openai',
+ userId,
+ // displayName intentionally left NULL
+ });
+
+ const models = [
+ {
+ id: 'bare-model',
+ displayName: 'Filled Name',
+ contextWindowTokens: 8192,
+ type: 'chat',
+ },
+ ] as AiProviderModelListItem[];
+
+ await aiProviderModel.batchUpdateAiModels('openai', models);
+
+ const allModels = await aiProviderModel.query();
+ const model = allModels.find((m) => m.id === 'bare-model');
+ // NULL slots are filled by the incoming provider data
+ expect(model?.displayName).toBe('Filled Name');
+ expect(model?.contextWindowTokens).toBe(8192);
+ expect(model?.type).toBe('chat');
+ });
+
+ it('should not overwrite existing displayName with null/undefined when updating', async () => {
+ // Create an initial model with displayName
+ await aiProviderModel.create({
+ id: 'existing-model',
+ providerId: 'openai',
+ displayName: 'Old Name',
+ });
+
+ const models = [
+ {
+ id: 'existing-model',
+ enabled: false,
+ type: 'chat' as const,
+ // displayName is missing/undefined
+ },
+ ] as AiProviderModelListItem[];
+
+ await aiProviderModel.batchUpdateAiModels('openai', models);
+
+ const allModels = await aiProviderModel.query();
+ const model = allModels.find((m) => m.id === 'existing-model');
+ // displayName is preserved (DB-first) because it was already set
+ expect(model?.displayName).toBe('Old Name');
+ });
+
+ it('should not overwrite existing abilities/parameters with empty defaults when omitted in sparse update', async () => {
+ // Create an initial model with abilities and parameters
+ await aiProviderModel.create({
+ id: 'existing-model',
+ providerId: 'openai',
+ abilities: { functionCall: true },
+ parameters: { temperature: 0.5 },
+ });
+
+ const models = [
+ {
+ id: 'existing-model',
+ enabled: false,
+ type: 'chat' as const,
+ // abilities and parameters are omitted in the payload
+ displayName: 'Updated Name',
+ },
+ ] as AiProviderModelListItem[];
+
+ await aiProviderModel.batchUpdateAiModels('openai', models);
+
+ const allModels = await aiProviderModel.query();
+ const model = allModels.find((m) => m.id === 'existing-model');
+ expect(model?.abilities).toEqual({ functionCall: true });
+ expect(model?.parameters).toEqual({ temperature: 0.5 });
+ });
+
it('should return empty array when models array is empty', async () => {
const result = await aiProviderModel.batchUpdateAiModels('openai', []);
expect(result).toEqual([]);
@@ -329,6 +413,391 @@ describe('AiModelModel', () => {
expect(result.releasedAt).toBe('2025-01-01');
});
+
+ it('should update abilities when remote provides new capabilities for existing model with empty abilities', async () => {
+ // 1. Historical model with empty abilities
+ await serverDB.insert(aiModels).values({
+ id: 'old-model',
+ providerId: 'openai',
+ userId,
+ abilities: {}, // Empty capabilities
+ source: 'remote',
+ });
+
+ // 2. Remote returns same model with new capabilities
+ const models = [
+ {
+ id: 'old-model',
+ enabled: false,
+ type: 'chat' as const,
+ abilities: { functionCall: true, reasoning: true },
+ },
+ ] as AiProviderModelListItem[];
+
+ await aiProviderModel.batchUpdateAiModels('openai', models);
+
+ // 3. Verify abilities are updated
+ const updated = await aiProviderModel.findById('old-model');
+ expect(updated?.abilities).toEqual({
+ functionCall: true,
+ reasoning: true,
+ });
+ });
+
+ it('should update type when remote corrects model type', async () => {
+ // 1. Existing model with wrong type
+ await serverDB.insert(aiModels).values({
+ id: 'image-model',
+ providerId: 'openai',
+ userId,
+ type: 'chat', // Wrong type
+ source: 'remote',
+ });
+
+ // 2. Remote provides correct type
+ const models = [
+ {
+ id: 'image-model',
+ enabled: false,
+ type: 'image' as const, // Correct type
+ },
+ ] as AiProviderModelListItem[];
+
+ await aiProviderModel.batchUpdateAiModels('openai', models);
+
+ // 3. Verify type is updated
+ const updated = await aiProviderModel.findById('image-model');
+ expect(updated?.type).toBe('image');
+ });
+
+ it('should update parameters when remote provides new parameters for existing model', async () => {
+ // 1. Existing model with empty parameters
+ await serverDB.insert(aiModels).values({
+ id: 'param-model',
+ providerId: 'openai',
+ userId,
+ parameters: {}, // Empty parameters
+ source: 'remote',
+ });
+
+ // 2. Remote provides parameters
+ const models = [
+ {
+ id: 'param-model',
+ enabled: false,
+ type: 'chat' as const,
+ parameters: {
+ max_tokens: { default: 4096 },
+ temperature: { default: 0.7, max: 2, min: 0, step: 0.1 },
+ } as any,
+ },
+ ] as AiProviderModelListItem[];
+
+ await aiProviderModel.batchUpdateAiModels('openai', models);
+
+ // 3. Verify parameters are updated
+ const updated = await aiProviderModel.findById('param-model');
+ expect(updated?.parameters).toEqual({
+ max_tokens: { default: 4096 },
+ temperature: { default: 0.7, max: 2, min: 0, step: 0.1 },
+ });
+ });
+
+ it('should update pricing from remote data', async () => {
+ // 1. Existing model with old pricing
+ await serverDB.insert(aiModels).values({
+ id: 'pricing-model',
+ providerId: 'openai',
+ userId,
+ pricing: {
+ currency: 'USD',
+ units: [
+ { name: 'input', rate: 10, strategy: 'fixed', unit: 'token' },
+ { name: 'output', rate: 30, strategy: 'fixed', unit: 'token' },
+ ],
+ } as any,
+ source: 'remote',
+ });
+
+ // 2. Remote provides updated pricing
+ const models = [
+ {
+ id: 'pricing-model',
+ enabled: false,
+ type: 'chat' as const,
+ pricing: {
+ currency: 'USD',
+ units: [
+ { name: 'input', rate: 5, strategy: 'fixed', unit: 'token' },
+ { name: 'output', rate: 15, strategy: 'fixed', unit: 'token' },
+ ],
+ } as any,
+ },
+ ] as any as AiProviderModelListItem[];
+
+ await aiProviderModel.batchUpdateAiModels('openai', models);
+
+ // 3. Verify pricing is updated
+ const updated = await aiProviderModel.findById('pricing-model');
+ expect(updated?.pricing).toEqual({
+ currency: 'USD',
+ units: [
+ { name: 'input', rate: 5, strategy: 'fixed', unit: 'token' },
+ { name: 'output', rate: 15, strategy: 'fixed', unit: 'token' },
+ ],
+ });
+ });
+
+ it('should NOT overwrite existing type when remote payload omits type field', async () => {
+ // 1. Existing remote model with type='image'
+ await serverDB.insert(aiModels).values({
+ id: 'image-model',
+ providerId: 'openai',
+ userId,
+ type: 'image',
+ source: 'remote',
+ });
+
+ // 2. Remote payload omits type (caller does not include type field)
+ // excluded.type will be 'chat' (schema default), but SQL condition filters it out
+ const models = [
+ {
+ id: 'image-model',
+ enabled: false,
+ // type is omitted - no type field at all
+ },
+ ] as AiProviderModelListItem[];
+
+ await aiProviderModel.batchUpdateAiModels('openai', models);
+
+ // 3. Verify type is preserved (not overwritten by default 'chat')
+ const updated = await aiProviderModel.findById('image-model');
+ expect(updated?.type).toBe('image');
+ });
+
+ it('should update type from non-chat to another non-chat when remote provides it', async () => {
+ // 1. Existing remote model with type='image'
+ await serverDB.insert(aiModels).values({
+ id: 'multimodal-model',
+ providerId: 'openai',
+ userId,
+ type: 'image',
+ source: 'remote',
+ });
+
+ // 2. Remote reclassifies it as 'video'
+ const models = [
+ {
+ id: 'multimodal-model',
+ enabled: false,
+ type: 'video' as const,
+ },
+ ] as AiProviderModelListItem[];
+
+ await aiProviderModel.batchUpdateAiModels('openai', models);
+
+ // 3. Verify type is updated
+ const updated = await aiProviderModel.findById('multimodal-model');
+ expect(updated?.type).toBe('video');
+ });
+
+ it('should NOT overwrite existing abilities when remote payload has empty abilities', async () => {
+ // 1. Existing remote model with abilities
+ await serverDB.insert(aiModels).values({
+ id: 'capable-model',
+ providerId: 'openai',
+ userId,
+ abilities: { functionCall: true, reasoning: true },
+ source: 'remote',
+ });
+
+ // 2. Remote payload provides empty abilities object (all fields undefined)
+ const models = [
+ {
+ id: 'capable-model',
+ enabled: false,
+ type: 'chat' as const,
+ abilities: {}, // Empty object - no real capabilities
+ },
+ ] as AiProviderModelListItem[];
+
+ await aiProviderModel.batchUpdateAiModels('openai', models);
+
+ // 3. Verify abilities are preserved
+ const updated = await aiProviderModel.findById('capable-model');
+ expect(updated?.abilities).toEqual({ functionCall: true, reasoning: true });
+ });
+
+ it('should update custom models with remote provider-sourced data while preserving user-editable fields', async () => {
+ // 1. User-created custom model (e.g., user added model ID before provider officially supported it)
+ await serverDB.insert(aiModels).values({
+ id: 'custom-model',
+ providerId: 'openai',
+ userId,
+ displayName: 'My Custom Model',
+ abilities: { functionCall: true },
+ type: 'chat',
+ pricing: {
+ currency: 'USD',
+ units: [
+ { name: 'input', rate: 10, strategy: 'fixed', unit: 'token' },
+ { name: 'output', rate: 20, strategy: 'fixed', unit: 'token' },
+ ],
+ } as any,
+ source: 'custom',
+ });
+
+ // 2. Remote provides different data for same model id (provider now officially supports it)
+ const models = [
+ {
+ id: 'custom-model',
+ enabled: false,
+ displayName: 'Remote Name',
+ abilities: { vision: true },
+ type: 'image' as const,
+ pricing: {
+ currency: 'USD',
+ units: [
+ { name: 'input', rate: 5, strategy: 'fixed', unit: 'token' },
+ { name: 'output', rate: 10, strategy: 'fixed', unit: 'token' },
+ ],
+ } as any,
+ },
+ ] as any as AiProviderModelListItem[];
+
+ await aiProviderModel.batchUpdateAiModels('openai', models);
+
+ // 3. Verify: provider-sourced fields updated, user-editable fields preserved
+ const updated = await aiProviderModel.findById('custom-model');
+ expect(updated?.displayName).toBe('My Custom Model'); // User-editable: preserved
+ expect(updated?.abilities).toEqual({ vision: true }); // Provider-sourced: updated
+ expect(updated?.type).toBe('image'); // Provider-sourced: updated
+ expect(updated?.pricing).toEqual({
+ currency: 'USD',
+ units: [
+ { name: 'input', rate: 5, strategy: 'fixed', unit: 'token' },
+ { name: 'output', rate: 10, strategy: 'fixed', unit: 'token' },
+ ],
+ }); // Provider-sourced: updated
+ expect(updated?.source).toBe('custom'); // Source: preserved
+ });
+
+ it('should update both remote and custom models in same batch', async () => {
+ // 1. Create both remote and custom models
+ await serverDB.insert(aiModels).values([
+ {
+ id: 'remote-model',
+ providerId: 'openai',
+ userId,
+ abilities: {},
+ source: 'remote',
+ },
+ {
+ id: 'custom-model',
+ providerId: 'openai',
+ userId,
+ abilities: { functionCall: true },
+ source: 'custom',
+ },
+ ]);
+
+ // 2. Remote provides updates for both
+ const models = [
+ {
+ id: 'remote-model',
+ enabled: false,
+ type: 'chat' as const,
+ abilities: { vision: true },
+ },
+ {
+ id: 'custom-model',
+ enabled: false,
+ type: 'chat' as const,
+ abilities: { reasoning: true },
+ },
+ ] as AiProviderModelListItem[];
+
+ await aiProviderModel.batchUpdateAiModels('openai', models);
+
+ // 3. Verify: both models updated with remote provider-sourced data
+ const remoteModel = await aiProviderModel.findById('remote-model');
+ const customModel = await aiProviderModel.findById('custom-model');
+
+ expect(remoteModel?.abilities).toEqual({ vision: true });
+ expect(customModel?.abilities).toEqual({ reasoning: true }); // Now updated from remote
+ });
+
+ it('should NOT update builtin models with remote provider-sourced data', async () => {
+ // 1. Builtin model with existing data
+ await serverDB.insert(aiModels).values({
+ id: 'gpt-4',
+ providerId: 'openai',
+ userId,
+ displayName: 'GPT-4',
+ abilities: { functionCall: true, vision: true },
+ type: 'chat',
+ contextWindowTokens: 128000,
+ pricing: {
+ currency: 'USD',
+ units: [
+ { name: 'input', rate: 10, strategy: 'fixed', unit: 'token' },
+ { name: 'output', rate: 30, strategy: 'fixed', unit: 'token' },
+ ],
+ } as any,
+ parameters: { temperature: 1 },
+ releasedAt: '2023-03-14',
+ description: 'Built-in model description',
+ source: 'builtin',
+ });
+
+ // 2. Remote provides different data for same model id
+ const models = [
+ {
+ id: 'gpt-4',
+ enabled: false,
+ displayName: 'Remote GPT-4',
+ abilities: { reasoning: true }, // Different abilities
+ type: 'image' as const, // Different type
+ contextWindowTokens: 8192, // Different context window
+ pricing: {
+ currency: 'USD',
+ units: [
+ { name: 'input', rate: 5, strategy: 'fixed', unit: 'token' },
+ { name: 'output', rate: 15, strategy: 'fixed', unit: 'token' },
+ ],
+ } as any, // Different pricing
+ parameters: { temperature: 0.5 }, // Different parameters
+ releasedAt: '2024-01-01', // Different release date
+ description: 'Remote model description', // Different description
+ },
+ ] as any as AiProviderModelListItem[];
+
+ await aiProviderModel.batchUpdateAiModels('openai', models);
+
+ // 3. Verify: builtin model is protected from remote updates
+ const updated = await aiProviderModel.findById('gpt-4');
+
+ // Provider-sourced fields should NOT be updated
+ expect(updated?.abilities).toEqual({ functionCall: true, vision: true }); // Preserved
+ expect(updated?.type).toBe('chat'); // Preserved
+ expect(updated?.contextWindowTokens).toBe(128000); // Preserved
+ expect(updated?.pricing).toEqual({
+ currency: 'USD',
+ units: [
+ { name: 'input', rate: 10, strategy: 'fixed', unit: 'token' },
+ { name: 'output', rate: 30, strategy: 'fixed', unit: 'token' },
+ ],
+ }); // Preserved
+ expect(updated?.parameters).toEqual({ temperature: 1 }); // Preserved
+ expect(updated?.releasedAt).toBe('2023-03-14'); // Preserved
+ expect(updated?.description).toBe('Built-in model description'); // Preserved
+
+ // User-editable fields still use DB-first COALESCE
+ expect(updated?.displayName).toBe('GPT-4'); // Preserved (user-editable)
+
+ // Source is never overwritten
+ expect(updated?.source).toBe('builtin');
+ });
});
describe('batchToggleAiModels', () => {
diff --git a/packages/database/src/models/aiModel.ts b/packages/database/src/models/aiModel.ts
index a55baa66aa2..6a46eafbe0b 100644
--- a/packages/database/src/models/aiModel.ts
+++ b/packages/database/src/models/aiModel.ts
@@ -131,6 +131,7 @@ export class AiModelModel {
id: aiModels.id,
parameters: aiModels.parameters,
providerId: aiModels.providerId,
+ pricing: aiModels.pricing,
releasedAt: aiModels.releasedAt,
settings: aiModels.settings,
sort: aiModels.sort,
@@ -205,22 +206,141 @@ export class AiModelModel {
return [];
}
- const records = models.map(({ id, ...model }) => ({
- ...model,
- id,
- providerId,
- releasedAt: this.normalizeReleasedAt(model.releasedAt),
- type: normalizeAiModelType(model.type),
- updatedAt: new Date(),
- userId: this.userId,
- }));
+ type BatchAiModelInput = Omit<AiProviderModelListItem, 'id'> &
+ Partial<Pick<AiModelSelectItem, 'description' | 'organization' | 'sort'>>;
+
+ const records = models.map(({ id, ...model }) => {
+ const input = model as BatchAiModelInput;
+ const record: typeof aiModels.$inferInsert = {
+ id,
+ providerId,
+ updatedAt: new Date(),
+ userId: this.userId,
+ };
+
+ // Only include fields that have meaningful values
+ // Normalize releasedAt if present
+ if (input.releasedAt !== undefined && input.releasedAt !== null) {
+ record.releasedAt = this.normalizeReleasedAt(input.releasedAt);
+ }
+
+ // Only include abilities if it has at least one truthy capability
+ const hasAnyAbility = input.abilities && Object.values(input.abilities).some((v) => v);
+ if (hasAnyAbility) {
+ record.abilities = input.abilities;
+ } else if (input.abilities !== undefined) {
+ // Mark as explicitly absent to distinguish from "not provided"
+ record.abilities = null;
+ }
+
+ // Only include parameters if it has at least one key with non-null value
+ const hasAnyParameter =
+ input.parameters &&
+ Object.keys(input.parameters).length > 0 &&
+ Object.values(input.parameters).some((v) => v !== null && v !== undefined);
+ if (hasAnyParameter) {
+ record.parameters = input.parameters;
+ } else if (input.parameters !== undefined) {
+ // Mark as explicitly absent
+ record.parameters = null;
+ }
+
+ // Include type if explicitly provided
+ // When type is undefined, omit it to use schema default ('chat')
+ // This means we can't distinguish "remote explicitly said chat" vs "remote didn't provide type"
+ // Trade-off: remote models with type != 'chat' won't be updated back to 'chat' via batch update
+ if (input.type !== undefined) {
+ record.type = normalizeAiModelType(input.type);
+ }
+
+ // Include other provider-sourced fields if present
+ if (input.contextWindowTokens !== undefined && input.contextWindowTokens !== null) {
+ record.contextWindowTokens = input.contextWindowTokens;
+ }
+ if (input.pricing !== undefined && input.pricing !== null) {
+ record.pricing = input.pricing;
+ }
+
+ // Include user-editable fields if present
+ if (input.displayName !== undefined && input.displayName !== null) {
+ record.displayName = input.displayName;
+ }
+
+ // Include other fields from model
+ if (input.config !== undefined) record.config = input.config;
+ if (input.enabled !== undefined) record.enabled = input.enabled;
+ if (input.settings !== undefined) record.settings = input.settings;
+ if (input.source !== undefined) record.source = input.source;
+
+ // Include optional internal fields if present via wider caller payloads.
+ if (input.description !== undefined) record.description = input.description;
+ if (input.organization !== undefined) record.organization = input.organization;
+ if (input.sort !== undefined) record.sort = input.sort;
+
+ return record;
+ });
return this.db
.insert(aiModels)
.values(records)
- .onConflictDoNothing({
+ .onConflictDoUpdate({
+ set: {
+ // User-editable fields: keep existing DB value; only fill when NULL
+ displayName: sql`COALESCE(ai_models.display_name, excluded.display_name)`,
+ // Provider-sourced fields: allow remote data to update remote/custom/new models
+ // For custom models, users can add a model ID before the provider supports it;
+ // when the provider later adds that model, we should fill in pricing/abilities/etc.
+ // Only builtin models are fully protected from remote updates.
+ // Only update if excluded value is not NULL (meaning it was explicitly provided and valid)
+ // Note: empty objects {} may come from schema defaults when field was omitted in payload
+ abilities: sql`CASE
+ WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL)
+ AND excluded.abilities IS NOT NULL
+ AND excluded.abilities != '{}'::jsonb
+ THEN excluded.abilities
+ ELSE ai_models.abilities
+ END`,
+ contextWindowTokens: sql`CASE
+ WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL) AND excluded.context_window_tokens IS NOT NULL
+ THEN excluded.context_window_tokens
+ ELSE ai_models.context_window_tokens
+ END`,
+ description: sql`CASE
+ WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL) AND excluded.description IS NOT NULL
+ THEN excluded.description
+ ELSE ai_models.description
+ END`,
+ parameters: sql`CASE
+ WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL)
+ AND excluded.parameters IS NOT NULL
+ AND excluded.parameters != '{}'::jsonb
+ THEN excluded.parameters
+ ELSE ai_models.parameters
+ END`,
+ pricing: sql`CASE
+ WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL) AND excluded.pricing IS NOT NULL
+ THEN excluded.pricing
+ ELSE ai_models.pricing
+ END`,
+ releasedAt: sql`CASE
+ WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL) AND excluded.released_at IS NOT NULL
+ THEN excluded.released_at
+ ELSE ai_models.released_at
+ END`,
+ type: sql`CASE
+ WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL) AND excluded.type IS NOT NULL AND excluded.type != 'chat'
+ THEN excluded.type
+ WHEN ai_models.source = 'builtin' AND excluded.type IS NOT NULL
+ THEN COALESCE(ai_models.type, excluded.type)
+ ELSE ai_models.type
+ END`,
+ // source marks model origin (remote/custom/builtin); once set, never overwrite
+ source: sql`COALESCE(ai_models.source, excluded.source)`,
+ updatedAt: sql`excluded.updated_at`,
+ // Note: enabled is intentionally omitted to preserve user toggle state
+ },
target: [aiModels.id, aiModels.userId, aiModels.providerId],
- where: isNull(aiModels.workspaceId),
+ targetWhere: isNull(aiModels.workspaceId),
})
.returning();
};
diff --git a/packages/database/src/repositories/aiInfra/__tests__/getEnabledModels.test.ts b/packages/database/src/repositories/aiInfra/__tests__/getEnabledModels.test.ts
index 0fdb8cb7eeb..863fef9fac6 100644
--- a/packages/database/src/repositories/aiInfra/__tests__/getEnabledModels.test.ts
+++ b/packages/database/src/repositories/aiInfra/__tests__/getEnabledModels.test.ts
@@ -976,5 +976,117 @@ describe('AiInfraRepos', () => {
// custom-model should still be included as appended user model
expect(result.find((m) => m.id === 'custom-model')).toBeDefined();
});
+
+ it('should merge user pricing over builtin pricing', async () => {
+ const mockProviders = [
+ { enabled: true, id: 'openai', name: 'OpenAI', source: 'builtin' as const },
+ ];
+
+ const mockAllModels = [
+ {
+ id: 'gpt-4',
+ providerId: 'openai',
+ enabled: true,
+ type: 'chat' as const,
+ abilities: {},
+ pricing: {
+ units: [{ name: 'textInput', rate: 10, strategy: 'fixed', unit: 'millionTokens' }],
+ },
+ },
+ ] as EnabledAiModel[];
+
+ vi.spyOn(repo, 'getAiProviderList').mockResolvedValue(mockProviders);
+ vi.spyOn(repo.aiModelModel, 'getAllModels').mockResolvedValue(mockAllModels);
+ vi.spyOn(repo as any, 'fetchBuiltinModels').mockResolvedValue([
+ {
+ id: 'gpt-4',
+ enabled: true,
+ type: 'chat' as const,
+ abilities: {},
+ pricing: {
+ units: [{ name: 'textInput', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' }],
+ },
+ },
+ ]);
+
+ const result = await repo.getEnabledModels();
+ const merged = result.find((m) => m.id === 'gpt-4');
+ expect(merged).toBeDefined();
+ expect(merged?.pricing).toEqual({
+ units: [{ name: 'textInput', rate: 10, strategy: 'fixed', unit: 'millionTokens' }],
+ });
+ });
+
+ it('should fallback to builtin pricing if user pricing is undefined', async () => {
+ const mockProviders = [
+ { enabled: true, id: 'openai', name: 'OpenAI', source: 'builtin' as const },
+ ];
+
+ const mockAllModels = [
+ {
+ id: 'gpt-4',
+ providerId: 'openai',
+ enabled: true,
+ type: 'chat' as const,
+ abilities: {},
+ },
+ ] as EnabledAiModel[];
+
+ vi.spyOn(repo, 'getAiProviderList').mockResolvedValue(mockProviders);
+ vi.spyOn(repo.aiModelModel, 'getAllModels').mockResolvedValue(mockAllModels);
+ vi.spyOn(repo as any, 'fetchBuiltinModels').mockResolvedValue([
+ {
+ id: 'gpt-4',
+ enabled: true,
+ type: 'chat' as const,
+ abilities: {},
+ pricing: {
+ units: [{ name: 'textInput', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' }],
+ },
+ },
+ ]);
+
+ const result = await repo.getEnabledModels();
+ const merged = result.find((m) => m.id === 'gpt-4');
+ expect(merged).toBeDefined();
+ expect(merged?.pricing).toEqual({
+ units: [{ name: 'textInput', rate: 2.5, strategy: 'fixed', unit: 'millionTokens' }],
+ });
+ });
+
+ it('should retain pricing for appended user-only models', async () => {
+ const mockProviders = [
+ {
+ enabled: true,
+ id: 'custom-provider',
+ name: 'Custom Provider',
+ source: 'custom' as const,
+ },
+ ];
+
+ const mockAllModels = [
+ {
+ id: 'newapi-model',
+ providerId: 'custom-provider',
+ enabled: true,
+ type: 'chat' as const,
+ abilities: {},
+ pricing: {
+ units: [{ name: 'textInput', rate: 0.15, strategy: 'fixed', unit: 'millionTokens' }],
+ },
+ },
+ ] as EnabledAiModel[];
+
+ vi.spyOn(repo, 'getAiProviderList').mockResolvedValue(mockProviders);
+ vi.spyOn(repo.aiModelModel, 'getAllModels').mockResolvedValue(mockAllModels);
+ vi.spyOn(repo as any, 'fetchBuiltinModels').mockResolvedValue([]);
+
+ const result = await repo.getEnabledModels();
+ const merged = result.find((m) => m.id === 'newapi-model');
+ expect(merged).toBeDefined();
+ expect(merged?.pricing).toEqual({
+ units: [{ name: 'textInput', rate: 0.15, strategy: 'fixed', unit: 'millionTokens' }],
+ });
+ });
});
});
diff --git a/packages/database/src/repositories/aiInfra/index.ts b/packages/database/src/repositories/aiInfra/index.ts
index 61dcad1bd05..6e618106b1c 100644
--- a/packages/database/src/repositories/aiInfra/index.ts
+++ b/packages/database/src/repositories/aiInfra/index.ts
@@ -225,6 +225,7 @@ export class AiInfraRepos {
displayName: user?.displayName || item.displayName,
enabled: typeof user.enabled === 'boolean' ? user.enabled : item.enabled,
id: item.id,
+ pricing: user.pricing || item.pricing,
providerId: provider.id,
settings: isEmpty(user.settings)
? item.settings
diff --git a/packages/model-bank/src/aiModels/minimax.ts b/packages/model-bank/src/aiModels/minimax.ts
index 3505aa9a17a..22be9d18ef5 100644
--- a/packages/model-bank/src/aiModels/minimax.ts
+++ b/packages/model-bank/src/aiModels/minimax.ts
@@ -28,8 +28,8 @@ const minimaxChatModels: AIChatModelCard[] = [
name: 'textInput',
strategy: 'tiered',
tiers: [
- { rate: 4.2, upTo: 512_000 },
- { rate: 8.4, upTo: 'infinity' },
+ { rate: 2.1, upTo: 512_000 },
+ { rate: 4.2, upTo: 'infinity' },
],
unit: 'millionTokens',
},
@@ -37,8 +37,8 @@ const minimaxChatModels: AIChatModelCard[] = [
name: 'textOutput',
strategy: 'tiered',
tiers: [
- { rate: 16.8, upTo: 512_000 },
- { rate: 33.6, upTo: 'infinity' },
+ { rate: 8.4, upTo: 512_000 },
+ { rate: 16.8, upTo: 'infinity' },
],
unit: 'millionTokens',
},
@@ -46,12 +46,11 @@ const minimaxChatModels: AIChatModelCard[] = [
name: 'textInput_cacheRead',
strategy: 'tiered',
tiers: [
- { rate: 0.84, upTo: 512_000 },
- { rate: 1.68, upTo: 'infinity' },
+ { rate: 0.42, upTo: 512_000 },
+ { rate: 0.84, upTo: 'infinity' },
],
unit: 'millionTokens',
},
- { name: 'textInput_cacheWrite', rate: 2.625, strategy: 'fixed', unit: 'millionTokens' },
],
},
releasedAt: '2026-06-01',
diff --git a/packages/model-bank/src/aiModels/modelscope.ts b/packages/model-bank/src/aiModels/modelscope.ts
index a4cdaef5e7d..d4d1d4174a6 100644
--- a/packages/model-bank/src/aiModels/modelscope.ts
+++ b/packages/model-bank/src/aiModels/modelscope.ts
@@ -65,20 +65,6 @@ const modelscopeChatModels: AIChatModelCard[] = [
id: 'deepseek-ai/DeepSeek-V3.1',
type: 'chat',
},
- {
- abilities: {
- functionCall: true,
- reasoning: true,
- },
- contextWindowTokens: 131_072,
- description:
- 'DeepSeek R1 leverages additional compute and post-training algorithmic optimizations to deepen reasoning. It performs strongly across benchmarks in math, programming, and general logic, approaching leaders like o3 and Gemini 2.5 Pro.',
- displayName: 'DeepSeek R1 0528',
- family: 'deepseek',
- generation: 'deepseek-r1',
- id: 'deepseek-ai/DeepSeek-R1-0528',
- type: 'chat',
- },
{
abilities: {
functionCall: true,
diff --git a/packages/model-bank/src/aiModels/ollamacloud.ts b/packages/model-bank/src/aiModels/ollamacloud.ts
index b016c6a0a45..ca92a58f040 100644
--- a/packages/model-bank/src/aiModels/ollamacloud.ts
+++ b/packages/model-bank/src/aiModels/ollamacloud.ts
@@ -1,6 +1,50 @@
import { type AIChatModelCard } from '../types/aiModel';
const ollamaCloudModels: AIChatModelCard[] = [
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
+ },
+ contextWindowTokens: 1_000_000,
+ description: 'GLM-5.2 is Z.ai’s flagship model for the era of long-horizon tasks.',
+ displayName: 'GLM-5.2',
+ enabled: true,
+ family: 'glm',
+ generation: 'glm-5.2',
+ id: 'glm-5.2',
+ type: 'chat',
+ },
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
+ vision: true,
+ },
+ contextWindowTokens: 262_144,
+ description:
+ "Kimi K2.7 Code is Moonshot AI's coding-focused agentic model built upon Kimi K2.6, with substantial improvements on real-world long-horizon coding tasks and roughly 30% lower thinking-token usage.",
+ displayName: 'Kimi K2.7 Code',
+ enabled: true,
+ family: 'kimi',
+ generation: 'kimi-k2.7',
+ id: 'kimi-k2.7-code',
+ type: 'chat',
+ },
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
+ vision: true,
+ },
+ contextWindowTokens: 512_000,
+ description: 'MiniMax M3: Coding & Agentic Frontier. 1M context window. Native Multimodality.',
+ displayName: 'MiniMax M3',
+ family: 'minimax',
+ generation: 'minimax-m3',
+ id: 'minimax-m3',
+ type: 'chat',
+ },
{
abilities: {
functionCall: true,
@@ -11,7 +55,6 @@ const ollamaCloudModels: AIChatModelCard[] = [
description:
'Kimi K2.6 is an open-source, native multimodal agentic model that advances practical capabilities in long-horizon coding, coding-driven design, proactive autonomous execution, and swarm-based task orchestration.',
displayName: 'Kimi K2.6',
- enabled: true,
family: 'kimi',
generation: 'kimi-k2.6',
id: 'kimi-k2.6',
@@ -26,7 +69,6 @@ const ollamaCloudModels: AIChatModelCard[] = [
description:
'GLM-5.1 is our next-generation flagship model for agentic engineering, with significantly stronger coding capabilities than its predecessor. It achieves state-of-the-art performance on SWE-Bench Pro and leads GLM-5 by a wide margin.',
displayName: 'GLM-5.1',
- enabled: true,
family: 'glm',
generation: 'glm-5.1',
id: 'glm-5.1',
@@ -55,7 +97,6 @@ const ollamaCloudModels: AIChatModelCard[] = [
description:
'MiniMax M2.7 is an efficient large language model built specifically for coding and agent workflows.',
displayName: 'MiniMax M2.7',
- enabled: true,
family: 'minimax',
generation: 'minimax-m2.7',
id: 'minimax-m2.7',
@@ -103,20 +144,6 @@ const ollamaCloudModels: AIChatModelCard[] = [
id: 'minimax-m2.5',
type: 'chat',
},
- {
- abilities: {
- functionCall: true,
- reasoning: true,
- },
- contextWindowTokens: 262_144,
- description:
- 'K2 long thinking model supports 256k contexts, supports multi-step tool calling and thinking, and is good at solving more complex problems.',
- displayName: 'Kimi K2 Thinking',
- family: 'kimi',
- generation: 'kimi-k2',
- id: 'kimi-k2-thinking',
- type: 'chat',
- },
{
abilities: {
functionCall: true,
@@ -158,18 +185,6 @@ const ollamaCloudModels: AIChatModelCard[] = [
id: 'devstral-2:123b',
type: 'chat',
},
- {
- abilities: {
- functionCall: true,
- reasoning: true,
- },
- contextWindowTokens: 163_840,
- description:
- 'Cogito v2.1 671B is a US open-source LLM free for commercial use, with performance rivaling top models, higher token reasoning efficiency, a 128k long context, and strong overall capability.',
- displayName: 'Cogito v2.1 671B',
- id: 'cogito-2.1:671b',
- type: 'chat',
- },
{
abilities: {
functionCall: true,
@@ -199,20 +214,6 @@ const ollamaCloudModels: AIChatModelCard[] = [
id: 'minimax-m2.1',
type: 'chat',
},
- {
- abilities: {
- functionCall: true,
- reasoning: true,
- },
- contextWindowTokens: 204_800,
- description:
- 'MiniMax M2 is an efficient large language model built specifically for coding and agent workflows.',
- displayName: 'MiniMax M2',
- family: 'minimax',
- generation: 'minimax-m2',
- id: 'minimax-m2',
- type: 'chat',
- },
{
abilities: {
functionCall: true,
@@ -227,20 +228,6 @@ const ollamaCloudModels: AIChatModelCard[] = [
id: 'glm-4.7',
type: 'chat',
},
- {
- abilities: {
- functionCall: true,
- reasoning: true,
- },
- contextWindowTokens: 200_000,
- description:
- "Zhipu's flagship model GLM-4.6 (355B) fully surpasses its predecessors in advanced coding, long-text processing, reasoning, and agent capabilities. It particularly aligns with Claude Sonnet 4 in programming ability, becoming China's top Coding model.",
- displayName: 'GLM-4.6',
- family: 'glm',
- generation: 'glm-4.6',
- id: 'glm-4.6',
- type: 'chat',
- },
{
abilities: {
functionCall: true,
@@ -287,20 +274,6 @@ const ollamaCloudModels: AIChatModelCard[] = [
releasedAt: '2025-08-05',
type: 'chat',
},
- {
- abilities: {
- functionCall: true,
- reasoning: true,
- },
- contextWindowTokens: 131_072,
- description:
- 'Kimi K2 is a large MoE LLM from Moonshot AI with 1T total parameters and 32B active per forward pass. It is optimized for agent capabilities including advanced tool use, reasoning, and code synthesis.',
- displayName: 'Kimi K2',
- family: 'kimi',
- generation: 'kimi-k2',
- id: 'kimi-k2:1t',
- type: 'chat',
- },
{
abilities: {
functionCall: true,
@@ -313,31 +286,6 @@ const ollamaCloudModels: AIChatModelCard[] = [
id: 'qwen3-coder:480b',
type: 'chat',
},
- {
- abilities: {
- functionCall: true,
- vision: true,
- },
- contextWindowTokens: 262_144,
- displayName: 'Qwen3 VL 235B Instruct',
- family: 'qwen',
- generation: 'qwen3',
- id: 'qwen3-vl:235b-instruct',
- type: 'chat',
- },
- {
- abilities: {
- functionCall: true,
- reasoning: true,
- vision: true,
- },
- contextWindowTokens: 262_144,
- displayName: 'Qwen3 VL 235B',
- family: 'qwen',
- generation: 'qwen3',
- id: 'qwen3-vl:235b',
- type: 'chat',
- },
{
abilities: {
functionCall: true,
diff --git a/packages/model-bank/src/aiModels/openrouter.ts b/packages/model-bank/src/aiModels/openrouter.ts
index 51bdea445d1..4d010c4fe09 100644
--- a/packages/model-bank/src/aiModels/openrouter.ts
+++ b/packages/model-bank/src/aiModels/openrouter.ts
@@ -197,25 +197,6 @@ const openrouterChatModels: AIChatModelCard[] = [
},
type: 'chat',
},
- {
- abilities: {
- reasoning: true,
- },
- contextWindowTokens: 32_000,
- description:
- 'GLM-4-32B-0414 is a 32B bilingual (Chinese/English) open-weights model optimized for code generation, function calling, and agent tasks. It is pretrained on 15T high-quality and reasoning-heavy data and further refined with human preference alignment, rejection sampling, and RL. It excels at complex reasoning, artifact generation, and structured output, reaching GPT-4o and DeepSeek-V3-0324-level performance on multiple benchmarks.',
- displayName: 'GLM 4 32B',
- family: 'glm',
- generation: 'glm-4',
- id: 'thudm/glm-4-32b',
- pricing: {
- units: [
- { name: 'textInput', rate: 0.24, strategy: 'fixed', unit: 'millionTokens' },
- { name: 'textOutput', rate: 0.24, strategy: 'fixed', unit: 'millionTokens' },
- ],
- },
- type: 'chat',
- },
{
abilities: {
functionCall: true,
diff --git a/packages/model-bank/src/aiModels/qwen.ts b/packages/model-bank/src/aiModels/qwen.ts
index b7f2c45289e..26bb471f90e 100644
--- a/packages/model-bank/src/aiModels/qwen.ts
+++ b/packages/model-bank/src/aiModels/qwen.ts
@@ -410,6 +410,33 @@ const qwenChatModels: AIChatModelCard[] = [
},
type: 'chat',
},
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
+ },
+ contextWindowTokens: 1_000_000,
+ description:
+ 'The GLM series is a hybrid reasoning model from Zhipu AI built for agents, with thinking and non-thinking modes. GLM-5.2 is Zhipu’s flagship model for the era of long-horizon tasks, supporting 1M tokens context and optimized for long-horizon planning, complex coding, and agent execution.',
+ displayName: 'GLM-5.2',
+ family: 'glm',
+ generation: 'glm-5.2',
+ id: 'glm-5.2',
+ maxOutput: 131_072,
+ pricing: {
+ currency: 'CNY',
+ units: [
+ { name: 'textInput_cacheRead', rate: 2, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textInput', rate: 8, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 28, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ },
+ releasedAt: '2026-06-17',
+ settings: {
+ extendParams: ['enableReasoning', 'reasoningBudgetToken'],
+ },
+ type: 'chat',
+ },
{
abilities: {
functionCall: true,
diff --git a/packages/model-bank/src/aiModels/siliconcloud.ts b/packages/model-bank/src/aiModels/siliconcloud.ts
index 79036a4d0cf..2244b64646d 100644
--- a/packages/model-bank/src/aiModels/siliconcloud.ts
+++ b/packages/model-bank/src/aiModels/siliconcloud.ts
@@ -6,6 +6,59 @@ import {
// https://siliconflow.cn/zh-cn/models
const siliconcloudChatModels: AIChatModelCard[] = [
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
+ },
+ contextWindowTokens: 1_048_576,
+ description:
+ "GLM-5.2 is Z.ai's latest flagship model designed for long-horizon task scenarios, offering significant improvements in long-horizon task capabilities compared to GLM-5.1. This 753B MoE model supports a stable 1M-token context window, features stronger programming capabilities, and supports multiple thinking effort levels for a flexible balance between performance and latency.",
+ displayName: 'GLM-5.2',
+ family: 'glm',
+ generation: 'glm-5.2',
+ id: 'zai-org/GLM-5.2',
+ pricing: {
+ currency: 'CNY',
+ units: [
+ { name: 'textInput_cacheRead', rate: 2, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textInput', rate: 8, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 28, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ },
+ releasedAt: '2026-06-17',
+ settings: {
+ extendParams: ['deepseekV4ReasoningEffort', 'reasoningBudgetToken'],
+ },
+ type: 'chat',
+ },
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
+ vision: true,
+ },
+ contextWindowTokens: 262_144,
+ description:
+ 'Kimi K2.7 Code is an agentic model designed for code tasks from Moonshot AI. Built on Kimi K2.6, it shows significant improvements in real-world long-horizon coding tasks, enhancing end-to-end task completion capabilities in complex software engineering workflows while reducing thinking token usage by about 30% compared to Kimi K2.6.',
+ displayName: 'Kimi-K2.7-Code',
+ family: 'kimi',
+ generation: 'kimi-k2.7',
+ id: 'moonshotai/Kimi-K2.7-Code',
+ pricing: {
+ currency: 'CNY',
+ units: [
+ { name: 'textInput_cacheRead', rate: 1.3, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textInput', rate: 6.5, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 27, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ },
+ releasedAt: '2026-06-12',
+ settings: {
+ extendParams: ['enableReasoning', 'reasoningBudgetToken'],
+ },
+ type: 'chat',
+ },
{
abilities: {
functionCall: true,
@@ -30,7 +83,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
},
releasedAt: '2026-04-24',
settings: {
- extendParams: ['enableReasoning', 'reasoningBudgetToken'],
+ extendParams: ['deepseekV4ReasoningEffort', 'reasoningBudgetToken'],
},
type: 'chat',
},
@@ -58,7 +111,7 @@ const siliconcloudChatModels: AIChatModelCard[] = [
},
releasedAt: '2026-04-24',
settings: {
- extendParams: ['enableReasoning', 'reasoningBudgetToken'],
+ extendParams: ['deepseekV4ReasoningEffort', 'reasoningBudgetToken'],
},
type: 'chat',
},
diff --git a/packages/model-bank/src/types/aiModel.ts b/packages/model-bank/src/types/aiModel.ts
index fcaacb5eabd..b19779deb86 100644
--- a/packages/model-bank/src/types/aiModel.ts
+++ b/packages/model-bank/src/types/aiModel.ts
@@ -592,6 +592,7 @@ export interface EnabledAiModel {
id: string;
knowledgeCutoff?: string;
parameters?: ModelParamsSchema;
+ pricing?: Pricing;
providerId: string;
releasedAt?: string;
settings?: AiModelSettings;
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
index 0288bd2bb06..573425871e8 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
@@ -316,6 +316,9 @@ describe('createRouterRuntime', () => {
expect(models).toHaveBeenCalledWith({
client: { provider: 'openai-compatible' },
+ options: expect.objectContaining({
+ baseURL: 'https://api.example.com/v1',
+ }),
});
});
});
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index ae0da1ea717..5a67c6f20f8 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -176,7 +176,7 @@ export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any>
) => Promise<HandleCreateVideoWebhookResult>;
id: string;
models?:
- | ((params: { client: OpenAI }) => Promise<ChatModelCard[]>)
+ | ((params: { client: OpenAI; options?: ConstructorOptions<T> }) => Promise<ChatModelCard[]>)
| {
transformModel?: (model: OpenAI.Model) => ChatModelCard;
};
@@ -686,7 +686,10 @@ export const createRouterRuntime = ({
typeof modelsOption === 'function' && // Use the same baseURL-matched runtime as chat routing for provider model discovery.
'client' in runtime
) {
- const modelList = await modelsOption({ client: (runtime as any).client });
+ const modelList = await modelsOption({
+ client: (runtime as any).client,
+ options: this._options,
+ });
return await postProcessModelList(modelList);
}
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index da9a4f8574a..9fb8ed6d46f 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -291,7 +291,7 @@ export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> =
options: CreateVideoOptions,
) => Promise<PollVideoStatusResult>;
models?:
- | ((params: { client: OpenAI }) => Promise<ChatModelCard[]>)
+ | ((params: { client: OpenAI; options?: ConstructorOptions<T> }) => Promise<ChatModelCard[]>)
| {
transformModel?: (model: OpenAI.Model) => ChatModelCard;
};
@@ -863,7 +863,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
let resultModels: ChatModelCard[];
if (typeof models === 'function') {
log('using custom models function');
- resultModels = await models({ client: this.client });
+ resultModels = await models({ client: this.client, options: this._options });
} else {
log('fetching models from client API');
const list = await this.client.models.list();
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
index 061473347a5..099ab428db7 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
@@ -829,18 +829,18 @@ describe('computeChatPricing', () => {
const input1 = result1?.breakdown.find((item) => item.unit.name === 'textInput');
expect(input1?.quantity).toBe(100_000);
- expect(input1?.credits).toBe(58_989); // Math.ceil((100,000 * 4.2) / 7.12)
- expect(input1?.segments).toEqual([{ quantity: 100_000, rate: 4.2, credits: 420_000 }]);
+ expect(input1?.credits).toBe(29_495); // Math.ceil((100,000 * 2.1) / 7.12)
+ expect(input1?.segments).toEqual([{ quantity: 100_000, rate: 2.1, credits: 210_000 }]);
const cached1 = result1?.breakdown.find((item) => item.unit.name === 'textInput_cacheRead');
expect(cached1?.quantity).toBe(20_000);
- expect(cached1?.credits).toBe(2_360); // Math.ceil((20,000 * 0.84) / 7.12)
- expect(cached1?.segments).toEqual([{ quantity: 20_000, rate: 0.84, credits: 16_800 }]);
+ expect(cached1?.credits).toBe(1_180); // Math.ceil((20,000 * 0.42) / 7.12)
+ expect(cached1?.segments).toEqual([{ quantity: 20_000, rate: 0.42, credits: 8_400 }]);
const output1 = result1?.breakdown.find((item) => item.unit.name === 'textOutput');
expect(output1?.quantity).toBe(10_000);
- expect(output1?.credits).toBe(23_596); // Math.ceil((10,000 * 16.8) / 7.12)
- expect(output1?.segments).toEqual([{ quantity: 10_000, rate: 16.8, credits: 168_000 }]);
+ expect(output1?.credits).toBe(11_798); // Math.ceil((10,000 * 8.4) / 7.12)
+ expect(output1?.segments).toEqual([{ quantity: 10_000, rate: 8.4, credits: 84_000 }]);
// Higher tier test (> 512,000 tokens)
const usage2: ModelTokensUsage = {
@@ -859,18 +859,18 @@ describe('computeChatPricing', () => {
const input2 = result2?.breakdown.find((item) => item.unit.name === 'textInput');
expect(input2?.quantity).toBe(500_000);
- expect(input2?.credits).toBe(589_888); // Math.ceil((500,000 * 8.4) / 7.12)
- expect(input2?.segments).toEqual([{ quantity: 500_000, rate: 8.4, credits: 4_200_000 }]);
+ expect(input2?.credits).toBe(294_944); // Math.ceil((500,000 * 4.2) / 7.12)
+ expect(input2?.segments).toEqual([{ quantity: 500_000, rate: 4.2, credits: 2_100_000 }]);
const cached2 = result2?.breakdown.find((item) => item.unit.name === 'textInput_cacheRead');
expect(cached2?.quantity).toBe(100_000);
- expect(cached2?.credits).toBe(23_596); // Math.ceil((100,000 * 1.68) / 7.12)
- expect(cached2?.segments).toEqual([{ quantity: 100_000, rate: 1.68, credits: 168_000 }]);
+ expect(cached2?.credits).toBe(11_798); // Math.ceil((100,000 * 0.84) / 7.12)
+ expect(cached2?.segments).toEqual([{ quantity: 100_000, rate: 0.84, credits: 84_000 }]);
const output2 = result2?.breakdown.find((item) => item.unit.name === 'textOutput');
expect(output2?.quantity).toBe(50_000);
- expect(output2?.credits).toBe(235_956); // Math.ceil((50,000 * 33.6) / 7.12)
- expect(output2?.segments).toEqual([{ quantity: 50_000, rate: 33.6, credits: 1_680_000 }]);
+ expect(output2?.credits).toBe(117_978); // Math.ceil((50,000 * 16.8) / 7.12)
+ expect(output2?.segments).toEqual([{ quantity: 50_000, rate: 16.8, credits: 840_000 }]);
});
});
diff --git a/packages/model-runtime/src/providers/newapi/index.test.ts b/packages/model-runtime/src/providers/newapi/index.test.ts
index f54b1be5bd6..25a40b2d3c0 100644
--- a/packages/model-runtime/src/providers/newapi/index.test.ts
+++ b/packages/model-runtime/src/providers/newapi/index.test.ts
@@ -1079,6 +1079,115 @@ describe('NewAPI Runtime - 100% Branch Coverage', () => {
expect(result[0].pricing).toBeUndefined();
});
+ it('should use dedicated proxy route when running in browser', async () => {
+ // Mock browser environment
+ const originalWindow = global.window;
+ const originalDocument = global.document;
+ global.window = {} as any;
+ global.document = {} as any;
+
+ try {
+ const mockClient = {
+ apiKey: 'test-key',
+ baseURL: 'https://api.newapi.com/v1',
+ models: {
+ list: vi.fn().mockResolvedValue({
+ data: [
+ {
+ created: 123,
+ id: 'test-model',
+ object: 'model',
+ owned_by: 'openai',
+ },
+ ],
+ }),
+ },
+ };
+
+ mockFetch.mockResolvedValue({
+ json: async () => ({
+ data: [
+ {
+ completion_ratio: 1.5,
+ enable_groups: ['default'],
+ model_name: 'test-model',
+ model_price: 10,
+ quota_type: 0,
+ },
+ ],
+ success: true,
+ }),
+ ok: true,
+ });
+
+ mockProcessMultiProviderModelList.mockImplementation((models) => models);
+
+ const result = await params.models({ client: mockClient as any });
+
+ expect(mockFetch).toHaveBeenCalledWith('/webapi/models/newapi/pricing');
+ expect(result[0].pricing).toBeDefined();
+ } finally {
+ global.window = originalWindow;
+ global.document = originalDocument;
+ }
+ });
+
+ it('should use custom provider pricing proxy route when running in browser', async () => {
+ // Mock browser environment
+ const originalWindow = global.window;
+ const originalDocument = global.document;
+ global.window = {} as any;
+ global.document = {} as any;
+
+ try {
+ const mockClient = {
+ apiKey: 'test-key',
+ baseURL: 'https://api.newapi.com/v1',
+ models: {
+ list: vi.fn().mockResolvedValue({
+ data: [
+ {
+ created: 123,
+ id: 'custom-model',
+ object: 'model',
+ owned_by: 'openai',
+ },
+ ],
+ }),
+ },
+ };
+
+ mockFetch.mockResolvedValue({
+ json: async () => ({
+ data: [
+ {
+ completion_ratio: 1.5,
+ enable_groups: ['default'],
+ model_name: 'custom-model',
+ model_price: 10,
+ quota_type: 0,
+ },
+ ],
+ success: true,
+ }),
+ ok: true,
+ });
+
+ mockProcessMultiProviderModelList.mockImplementation((models) => models);
+
+ const result = await params.models({
+ client: mockClient as any,
+ options: { providerId: 'custom-router' },
+ });
+
+ expect(mockFetch).toHaveBeenCalledWith('/webapi/models/custom-router/pricing');
+ expect(result[0].pricing).toBeDefined();
+ } finally {
+ global.window = originalWindow;
+ global.document = originalDocument;
+ }
+ });
+
it('should handle pricing data with success=false', async () => {
const mockClient = {
apiKey: 'test-key',
diff --git a/packages/model-runtime/src/providers/newapi/index.ts b/packages/model-runtime/src/providers/newapi/index.ts
index 29e6b8fd49e..90abfd2ec69 100644
--- a/packages/model-runtime/src/providers/newapi/index.ts
+++ b/packages/model-runtime/src/providers/newapi/index.ts
@@ -27,17 +27,40 @@ export interface NewAPIPricing {
supported_endpoint_types?: string[];
}
+const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined';
+
const fetchPricing = async (
pricingUrl: string,
apiKey: string,
+ providerId = ModelProvider.NewAPI,
): Promise<NewAPIPricing[] | null> => {
try {
- const res = await fetch(pricingUrl, {
- headers: {
- Accept: 'application/json; charset=utf-8',
- Authorization: `Bearer ${apiKey}`,
- },
- });
+ let res: Response;
+ if (isBrowser()) {
+ res = await fetch(`/webapi/models/${encodeURIComponent(providerId)}/pricing`);
+ } else {
+ const fetchWithAuth = async (useAuth: boolean) => {
+ const headers: Record<string, string> = {
+ Accept: 'application/json; charset=utf-8',
+ };
+ if (useAuth && apiKey) {
+ headers.Authorization = `Bearer ${apiKey}`;
+ }
+ return fetch(pricingUrl, { headers });
+ };
+
+ let usedAuth = true;
+ try {
+ res = await fetchWithAuth(true);
+ } catch {
+ usedAuth = false;
+ res = await fetchWithAuth(false);
+ }
+
+ if (!res.ok && usedAuth) {
+ res = await fetchWithAuth(false);
+ }
+ }
if (!res.ok) return null;
@@ -56,7 +79,10 @@ export const params = {
'X-Client': 'LobeHub',
},
id: ModelProvider.NewAPI,
- models: async ({ client: openAIClient }) => {
+ models: async ({ client: openAIClient, options }) => {
+ const providerId =
+ typeof options?.providerId === 'string' ? options.providerId : ModelProvider.NewAPI;
+
// Get base URL (remove trailing API version paths like /v1, /v1beta, etc.)
const baseURL = openAIClient.baseURL.replace(/\/v\d+[a-z]*\/?$/, '');
@@ -69,7 +95,11 @@ export const params = {
// Try to get pricing information to enrich model details
const pricingMap: Map<string, NewAPIPricing> = new Map();
- const pricingList = await fetchPricing(`${baseURL}/api/pricing`, openAIClient.apiKey || '');
+ const pricingList = await fetchPricing(
+ `${baseURL}/api/pricing`,
+ openAIClient.apiKey || '',
+ providerId,
+ );
if (Array.isArray(pricingList)) {
pricingList.forEach((pricing) => {
pricingMap.set(pricing.model_name, pricing);
diff --git a/packages/model-runtime/src/providers/siliconcloud/index.test.ts b/packages/model-runtime/src/providers/siliconcloud/index.test.ts
index ab3cea50c13..dd1a058edf0 100644
--- a/packages/model-runtime/src/providers/siliconcloud/index.test.ts
+++ b/packages/model-runtime/src/providers/siliconcloud/index.test.ts
@@ -170,6 +170,32 @@ describe('LobeSiliconCloudAI - custom features', () => {
expect(calledPayload.enable_thinking).toBeUndefined();
expect(calledPayload.thinking_budget).toBe(2048);
});
+
+ it('should forward reasoning_effort when thinking is not explicitly disabled', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'deepseek-ai/DeepSeek-V4-Flash',
+ reasoning_effort: 'medium',
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.reasoning_effort).toBe('medium');
+ });
+
+ it('should not send reasoning_effort when thinking is explicitly disabled', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'deepseek-ai/DeepSeek-V4-Flash',
+ thinking: {
+ type: 'disabled',
+ },
+ reasoning_effort: 'high',
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.reasoning_effort).toBeUndefined();
+ expect(calledPayload.enable_thinking).toBe(false);
+ });
});
describe('handleError', () => {
diff --git a/packages/model-runtime/src/providers/siliconcloud/index.ts b/packages/model-runtime/src/providers/siliconcloud/index.ts
index 7413a7cc0e3..34d79524923 100644
--- a/packages/model-runtime/src/providers/siliconcloud/index.ts
+++ b/packages/model-runtime/src/providers/siliconcloud/index.ts
@@ -69,7 +69,8 @@ export const params = {
return {
error: status,
errorType: AgentRuntimeErrorType.ProviderBizError,
- message: 'Please check if your API Key balance is sufficient, or if you are using an unverified API Key to access models that require verification.',
+ message:
+ 'Please check if your API Key balance is sufficient, or if you are using an unverified API Key to access models that require verification.',
};
}
@@ -93,7 +94,7 @@ export const params = {
return { error };
},
handlePayload: (payload) => {
- const { max_tokens, model, thinking, ...rest } = payload;
+ const { max_tokens, model, thinking, reasoning_effort, ...rest } = payload;
const thinkingBudget =
thinking?.budget_tokens === 0 ? 1 : thinking?.budget_tokens || undefined;
@@ -104,6 +105,8 @@ export const params = {
model,
};
+ const thinkingExplicitlyDisabled = thinking?.type === 'disabled';
+
if (thinking) {
// Only set enable_thinking if type is explicitly provided
if (typeof thinking.type !== 'undefined') {
@@ -113,6 +116,13 @@ export const params = {
result.thinking_budget = Math.min(Math.max(thinkingBudget, 128), 32_768);
}
}
+
+ // SiliconCloud supports reasoning_effort for deepseek-ai/DeepSeek-V4-Flash.
+ // It should not be sent when thinking is explicitly disabled.
+ if (!thinkingExplicitlyDisabled && reasoning_effort) {
+ result.reasoning_effort = reasoning_effort;
+ }
+
return result;
},
},
diff --git a/packages/model-runtime/src/utils/modelExtendParams.test.ts b/packages/model-runtime/src/utils/modelExtendParams.test.ts
index 2ac0c8e1247..99694c5c4cb 100644
--- a/packages/model-runtime/src/utils/modelExtendParams.test.ts
+++ b/packages/model-runtime/src/utils/modelExtendParams.test.ts
@@ -86,6 +86,23 @@ describe('applyModelExtendParams', () => {
expect(result.reasoning_effort).toBe('max');
});
+
+ it('preserves thinking budget when deepseekV4ReasoningEffort is set', () => {
+ const result = applyModelExtendParams({
+ chatConfig: chatConfig({
+ deepseekV4ReasoningEffort: 'high',
+ reasoningBudgetToken: 2048,
+ }),
+ extendParams: ['deepseekV4ReasoningEffort', 'reasoningBudgetToken'],
+ model: 'deepseek-v4-pro',
+ });
+
+ expect(result.reasoning_effort).toBe('high');
+ expect(result.thinking).toEqual({
+ budget_tokens: 2048,
+ type: 'enabled',
+ });
+ });
});
describe('resolveDefaultThinkingLevelForModel', () => {
diff --git a/packages/model-runtime/src/utils/modelExtendParams.ts b/packages/model-runtime/src/utils/modelExtendParams.ts
index 028a9141141..9e5c7ea6415 100644
--- a/packages/model-runtime/src/utils/modelExtendParams.ts
+++ b/packages/model-runtime/src/utils/modelExtendParams.ts
@@ -241,11 +241,13 @@ export const applyModelExtendParams = (ctx: ApplyModelExtendParamsContext): Mode
if (deepseekV4ReasoningEffort === 'none') {
delete extendParams.reasoning_effort;
extendParams.thinking = {
+ ...extendParams.thinking,
type: 'disabled',
};
} else {
extendParams.reasoning_effort = deepseekV4ReasoningEffort;
extendParams.thinking = {
+ ...extendParams.thinking,
type: 'enabled',
};
}
diff --git a/src/app/(backend)/webapi/models/[provider]/pricing/route.test.ts b/src/app/(backend)/webapi/models/[provider]/pricing/route.test.ts
new file mode 100644
index 00000000000..f03c7d2496c
--- /dev/null
+++ b/src/app/(backend)/webapi/models/[provider]/pricing/route.test.ts
@@ -0,0 +1,212 @@
+// @vitest-environment node
+import { ChatErrorType } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { auth } from '@/auth';
+import { AiProviderModel } from '@/database/models/aiProvider';
+
+import { GET } from './route';
+
+vi.mock('@/app/(backend)/middleware/auth/utils', () => ({
+ checkAuthMethod: vi.fn(),
+}));
+
+vi.mock('@/auth', () => ({
+ auth: {
+ api: {
+ getSession: vi.fn().mockResolvedValue(null),
+ },
+ },
+}));
+
+vi.mock('@/database/models/aiProvider', () => {
+ const mockGetAiProviderById = vi.fn();
+ return {
+ AiProviderModel: vi.fn().mockImplementation(() => ({
+ getAiProviderById: mockGetAiProviderById,
+ })),
+ };
+});
+
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: {
+ getUserKeyVaults: vi.fn(),
+ },
+}));
+
+const mockSsrfSafeFetch = vi.fn();
+vi.mock('@lobechat/ssrf-safe-fetch', () => ({
+ ssrfSafeFetch: (...args: any[]) => mockSsrfSafeFetch(...args),
+}));
+
+let request: Request;
+
+beforeEach(() => {
+ request = new Request(new URL('https://test.com'), {
+ method: 'GET',
+ });
+
+ // Default: valid session
+ vi.mocked(auth.api.getSession).mockResolvedValue({
+ session: {} as any,
+ user: { id: 'test-user-id' } as any,
+ });
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('GET /webapi/models/[provider]/pricing', () => {
+ it('should return ContentNotFound if provider config is missing', async () => {
+ const mockParams = Promise.resolve({ provider: 'newapi' });
+ const mockModelInstance = new AiProviderModel({} as any, 'test-user-id');
+ vi.mocked(mockModelInstance.getAiProviderById).mockResolvedValue(undefined);
+
+ const response = await GET(request, { params: mockParams });
+ const responseBody = await response.json();
+
+ expect(response.status).toBe(404);
+ expect(responseBody.errorType).toBe(ChatErrorType.ContentNotFound);
+ });
+
+ it('should return BadRequest if baseURL is missing', async () => {
+ const mockParams = Promise.resolve({ provider: 'newapi' });
+ const mockModelInstance = new AiProviderModel({} as any, 'test-user-id');
+ vi.mocked(mockModelInstance.getAiProviderById).mockResolvedValue({
+ keyVaults: {
+ apiKey: 'test-key',
+ },
+ } as any);
+
+ const response = await GET(request, { params: mockParams });
+ const responseBody = await response.json();
+
+ expect(response.status).toBe(400);
+ expect(responseBody.errorType).toBe(ChatErrorType.BadRequest);
+ });
+
+ it('should fetch pricing successfully', async () => {
+ const mockParams = Promise.resolve({ provider: 'newapi' });
+ const mockModelInstance = new AiProviderModel({} as any, 'test-user-id');
+ vi.mocked(mockModelInstance.getAiProviderById).mockResolvedValue({
+ keyVaults: {
+ apiKey: 'test-key',
+ baseURL: 'https://newapi.test.com/v1',
+ },
+ } as any);
+
+ mockSsrfSafeFetch.mockResolvedValue({
+ json: async () => ({ success: true, data: [{ model_name: 'test' }] }),
+ ok: true,
+ });
+
+ const response = await GET(request, { params: mockParams });
+ const responseBody = await response.json();
+
+ expect(response.status).toBe(200);
+ expect(responseBody).toEqual({ success: true, data: [{ model_name: 'test' }] });
+ expect(mockSsrfSafeFetch).toHaveBeenCalledWith(
+ 'https://newapi.test.com/api/pricing',
+ expect.any(Object),
+ );
+ });
+
+ it('should fetch pricing from the requested custom provider config', async () => {
+ const mockParams = Promise.resolve({ provider: 'custom-router' });
+ const mockModelInstance = new AiProviderModel({} as any, 'test-user-id');
+ vi.mocked(mockModelInstance.getAiProviderById).mockResolvedValue({
+ keyVaults: {
+ apiKey: 'custom-key',
+ baseURL: 'https://custom-newapi.test.com/v1',
+ },
+ } as any);
+
+ mockSsrfSafeFetch.mockResolvedValue({
+ json: async () => ({ success: true, data: [{ model_name: 'custom-model' }] }),
+ ok: true,
+ });
+
+ const response = await GET(request, { params: mockParams });
+ const responseBody = await response.json();
+
+ expect(response.status).toBe(200);
+ expect(responseBody).toEqual({ success: true, data: [{ model_name: 'custom-model' }] });
+ expect(mockModelInstance.getAiProviderById).toHaveBeenCalledWith(
+ 'custom-router',
+ expect.any(Function),
+ );
+ expect(mockSsrfSafeFetch).toHaveBeenCalledWith(
+ 'https://custom-newapi.test.com/api/pricing',
+ expect.any(Object),
+ );
+ });
+
+ it('should fallback to fetch without auth if fetch with auth fails', async () => {
+ const mockParams = Promise.resolve({ provider: 'newapi' });
+ const mockModelInstance = new AiProviderModel({} as any, 'test-user-id');
+ vi.mocked(mockModelInstance.getAiProviderById).mockResolvedValue({
+ keyVaults: {
+ apiKey: 'test-key',
+ baseURL: 'https://newapi.test.com/v1',
+ },
+ } as any);
+
+ mockSsrfSafeFetch.mockRejectedValueOnce(new Error('Auth fetch failed')).mockResolvedValueOnce({
+ json: async () => ({ success: true, data: [{ model_name: 'test' }] }),
+ ok: true,
+ });
+
+ const response = await GET(request, { params: mockParams });
+ const responseBody = await response.json();
+
+ expect(response.status).toBe(200);
+ expect(responseBody).toEqual({ success: true, data: [{ model_name: 'test' }] });
+ expect(mockSsrfSafeFetch).toHaveBeenCalledTimes(2);
+ });
+
+ it('should return BadGateway if external api call fails', async () => {
+ const mockParams = Promise.resolve({ provider: 'newapi' });
+ const mockModelInstance = new AiProviderModel({} as any, 'test-user-id');
+ vi.mocked(mockModelInstance.getAiProviderById).mockResolvedValue({
+ keyVaults: {
+ apiKey: 'test-key',
+ baseURL: 'https://newapi.test.com/v1',
+ },
+ } as any);
+
+ mockSsrfSafeFetch.mockResolvedValue({
+ ok: false,
+ statusText: 'Bad Gateway',
+ });
+
+ const response = await GET(request, { params: mockParams });
+ const responseBody = await response.json();
+
+ expect(response.status).toBe(502);
+ expect(responseBody.errorType).toBe(ChatErrorType.BadGateway);
+ });
+
+ it('should return InternalServerError if SSRF protection blocks the request', async () => {
+ const mockParams = Promise.resolve({ provider: 'newapi' });
+ const mockModelInstance = new AiProviderModel({} as any, 'test-user-id');
+ vi.mocked(mockModelInstance.getAiProviderById).mockResolvedValue({
+ keyVaults: {
+ apiKey: 'test-key',
+ baseURL: 'http://192.168.1.1/v1',
+ },
+ } as any);
+
+ mockSsrfSafeFetch.mockRejectedValue(
+ new Error(
+ 'SSRF blocked: http://192.168.1.1 is not allowed. See: https://lobehub.com/docs/self-hosting/environment-variables/basic#ssrf-allow-private-ip-address',
+ ),
+ );
+
+ const response = await GET(request, { params: mockParams });
+ const responseBody = await response.json();
+
+ expect(response.status).toBe(500);
+ expect(responseBody.errorType).toBe(ChatErrorType.InternalServerError);
+ });
+});
diff --git a/src/app/(backend)/webapi/models/[provider]/pricing/route.ts b/src/app/(backend)/webapi/models/[provider]/pricing/route.ts
new file mode 100644
index 00000000000..706032e9f3d
--- /dev/null
+++ b/src/app/(backend)/webapi/models/[provider]/pricing/route.ts
@@ -0,0 +1,93 @@
+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
+import { ChatErrorType } from '@lobechat/types';
+import debug from 'debug';
+import { NextResponse } from 'next/server';
+
+import { checkAuth } from '@/app/(backend)/middleware/auth';
+import { AiProviderModel } from '@/database/models/aiProvider';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { createErrorResponse } from '@/utils/errorResponse';
+
+const log = debug('lobe-server:models:pricing');
+
+interface NewApiPricingKeyVaults {
+ apiKey?: string;
+ baseURL?: string;
+}
+
+export const GET = checkAuth(async (req, { params, userId, serverDB }) => {
+ const provider = (await params).provider;
+
+ if (!provider) {
+ return createErrorResponse(ChatErrorType.BadRequest, {
+ message: 'Provider is required.',
+ });
+ }
+
+ try {
+ // 1. Get user's provider configuration from database
+ const aiProviderModel = new AiProviderModel(serverDB, userId);
+ const providerConfig = await aiProviderModel.getAiProviderById(
+ provider,
+ KeyVaultsGateKeeper.getUserKeyVaults,
+ );
+
+ if (!providerConfig) {
+ return createErrorResponse(ChatErrorType.ContentNotFound, {
+ message: 'Provider configuration not found.',
+ });
+ }
+
+ const keyVaults = (providerConfig.keyVaults || {}) as NewApiPricingKeyVaults;
+ const baseURL = keyVaults.baseURL;
+ const apiKey = keyVaults.apiKey;
+
+ if (!baseURL) {
+ return createErrorResponse(ChatErrorType.BadRequest, {
+ message: 'Provider baseURL not configured.',
+ });
+ }
+
+ // Remove trailing API version paths like /v1, /v1beta, etc.
+ const cleanBaseURL = baseURL.replace(/\/v\d+[a-z]*\/?$/, '');
+ const pricingUrl = `${cleanBaseURL}/api/pricing`;
+
+ const headers: Record<string, string> = {
+ Accept: 'application/json; charset=utf-8',
+ };
+
+ const fetchWithAuth = async (useAuth: boolean) => {
+ const currentHeaders = { ...headers };
+ if (useAuth && apiKey) {
+ currentHeaders.Authorization = `Bearer ${apiKey}`;
+ }
+ return ssrfSafeFetch(pricingUrl, { headers: currentHeaders });
+ };
+
+ let res: Response;
+ let usedAuth = true;
+ try {
+ res = await fetchWithAuth(true);
+ } catch {
+ usedAuth = false;
+ res = await fetchWithAuth(false);
+ }
+
+ if (!res.ok && usedAuth) {
+ res = await fetchWithAuth(false);
+ }
+
+ if (!res.ok) {
+ return createErrorResponse(ChatErrorType.BadGateway, {
+ message: `Failed to fetch pricing from provider: ${res.statusText}`,
+ });
+ }
+
+ const body = await res.json();
+ return NextResponse.json(body);
+ } catch (e) {
+ log(`Route: [${provider}] pricing error: %O`, e);
+ const error = e instanceof Error ? { message: e.message, name: e.name } : e;
+ return createErrorResponse(ChatErrorType.InternalServerError, { error });
+ }
+});
diff --git a/src/services/__tests__/_url.test.ts b/src/services/__tests__/_url.test.ts
index dad2721dd56..1d56bd69ea8 100644
--- a/src/services/__tests__/_url.test.ts
+++ b/src/services/__tests__/_url.test.ts
@@ -14,6 +14,7 @@ describe('API_ENDPOINTS', () => {
expect(API_ENDPOINTS.chat('openai')).toBe('/webapi/chat/openai');
expect(API_ENDPOINTS.models('anthropic')).toBe('/webapi/models/anthropic');
expect(API_ENDPOINTS.modelPull('azure')).toBe('/webapi/models/azure/pull');
+ expect(API_ENDPOINTS.pricing('newapi')).toBe('/webapi/models/newapi/pricing');
expect(API_ENDPOINTS.tts('openai')).toBe('/webapi/tts/openai');
});
});
diff --git a/src/services/_url.ts b/src/services/_url.ts
index 575c032f4b9..d7c263bd9da 100644
--- a/src/services/_url.ts
+++ b/src/services/_url.ts
@@ -10,6 +10,7 @@ export const API_ENDPOINTS = {
// models
models: (provider: string) => `/webapi/models/${provider}`,
modelPull: (provider: string) => `/webapi/models/${provider}/pull`,
+ pricing: (provider: string) => `/webapi/models/${provider}/pricing`,
// TTS
tts: (provider: string) => `/webapi/tts/${provider}`,
diff --git a/src/services/chat/mecha/clientModelRuntime.test.ts b/src/services/chat/mecha/clientModelRuntime.test.ts
index 87d3b818546..6adefc75736 100644
--- a/src/services/chat/mecha/clientModelRuntime.test.ts
+++ b/src/services/chat/mecha/clientModelRuntime.test.ts
@@ -74,6 +74,7 @@ const mockProviderKeyVaults = async (provider: string, keyVaults: any) => {
...state.aiProviderRuntimeConfig,
[provider]: {
keyVaults,
+ settings: {},
},
},
}));
@@ -121,6 +122,28 @@ describe('ModelRuntimeOnClient', () => {
expect(runtime['_runtime'].baseURL).toBe('user-openai-endpoint');
});
+ it('custom router provider: passes actual provider id to runtime options', async () => {
+ await mockProviderKeyVaults('custom-router', {
+ apiKey: 'custom-router-key',
+ baseURL: 'https://custom-router.test.com/v1',
+ });
+
+ const initializeSpy = vi.spyOn(ModelRuntime, 'initializeWithProvider');
+
+ await initializeWithClientStore({
+ payload: {},
+ provider: 'custom-router',
+ runtimeProvider: 'router',
+ });
+
+ expect(initializeSpy).toHaveBeenCalledWith(
+ 'router',
+ expect.objectContaining({
+ providerId: 'custom-router',
+ }),
+ );
+ });
+
it('Azure provider: with apiKey and endpoint', async () => {
await mockProviderKeyVaults(ModelProvider.Azure, {
apiKey: 'user-azure-key',
diff --git a/src/services/chat/mecha/clientModelRuntime.ts b/src/services/chat/mecha/clientModelRuntime.ts
index 15c81d6b4f9..7b47824ddef 100644
--- a/src/services/chat/mecha/clientModelRuntime.ts
+++ b/src/services/chat/mecha/clientModelRuntime.ts
@@ -41,5 +41,6 @@ export const initializeWithClientStore = ({
...commonOptions,
...providerAuthPayload,
...payload,
+ providerId: provider,
});
};
diff --git a/src/store/aiInfra/slices/aiModel/action.test.ts b/src/store/aiInfra/slices/aiModel/action.test.ts
index e01018b0f5d..7f39d8a792b 100644
--- a/src/store/aiInfra/slices/aiModel/action.test.ts
+++ b/src/store/aiInfra/slices/aiModel/action.test.ts
@@ -264,6 +264,72 @@ describe('AiModelAction', () => {
source: 'remote',
type: 'image',
});
+ });
+
+ it('should preserve enabled status of existing models when fetching', async () => {
+ const mockRemoteModels = [
+ {
+ displayName: 'Remote Model 1',
+ id: 'remote-1',
+ enabled: true,
+ type: 'chat',
+ },
+ {
+ displayName: 'Remote Model 2',
+ id: 'remote-2',
+ enabled: false,
+ type: 'chat',
+ },
+ ];
+
+ act(() => {
+ useStore.setState({
+ aiProviderModelList: [
+ {
+ id: 'remote-1',
+ enabled: false,
+ type: 'chat',
+ },
+ {
+ id: 'remote-2',
+ enabled: true,
+ type: 'chat',
+ },
+ ],
+ });
+ });
+
+ const { result } = renderHook(() => useStore());
+ const batchUpdateSpy = vi
+ .spyOn(result.current, 'batchUpdateAiModels')
+ .mockResolvedValue(undefined);
+ const refreshSpy = vi
+ .spyOn(result.current, 'refreshAiModelList')
+ .mockResolvedValue(undefined);
+
+ vi.doMock('@/services/models', () => ({
+ modelsService: {
+ getModels: vi.fn().mockResolvedValue(mockRemoteModels),
+ },
+ }));
+
+ await act(async () => {
+ await result.current.fetchRemoteModelList('test-provider');
+ });
+
+ await waitFor(() => {
+ expect(batchUpdateSpy).toHaveBeenCalled();
+ });
+
+ const batchUpdateArg = batchUpdateSpy.mock.calls[0][0];
+ expect(batchUpdateArg[0]).toMatchObject({
+ id: 'remote-1',
+ enabled: false,
+ });
+ expect(batchUpdateArg[1]).toMatchObject({
+ id: 'remote-2',
+ enabled: true,
+ });
expect(refreshSpy).toHaveBeenCalled();
});
diff --git a/src/store/aiInfra/slices/aiModel/action.ts b/src/store/aiInfra/slices/aiModel/action.ts
index 9a2454c46a0..7d625c816aa 100644
--- a/src/store/aiInfra/slices/aiModel/action.ts
+++ b/src/store/aiInfra/slices/aiModel/action.ts
@@ -63,22 +63,48 @@ export class AiModelActionImpl {
const data = await modelsService.getModels(providerId);
if (data) {
+ const currentEnabledState = new Map(
+ this.#get().aiProviderModelList.map(({ enabled, id }) => [id, enabled]),
+ );
await this.#get().batchUpdateAiModels(
- data.map((model) => ({
- ...model,
- abilities: {
- files: model.files,
- functionCall: model.functionCall,
- imageOutput: model.imageOutput,
- reasoning: model.reasoning,
- search: model.search,
- video: model.video,
- vision: model.vision,
- },
- enabled: model.enabled || false,
- source: 'remote',
- type: model.type || 'chat',
- })),
+ data.map((model) => {
+ const result: any = {
+ ...model,
+ enabled: currentEnabledState.get(model.id) ?? model.enabled ?? false,
+ source: 'remote',
+ };
+
+ // Only include abilities if at least one capability is truthy
+ const hasAnyAbility =
+ model.files ||
+ model.functionCall ||
+ model.imageOutput ||
+ model.reasoning ||
+ model.search ||
+ model.video ||
+ model.vision;
+
+ if (hasAnyAbility) {
+ result.abilities = {
+ files: model.files,
+ functionCall: model.functionCall,
+ imageOutput: model.imageOutput,
+ reasoning: model.reasoning,
+ search: model.search,
+ video: model.video,
+ vision: model.vision,
+ };
+ }
+
+ // Always include type to enable remote updates
+ // The SQL layer will preserve non-chat types when remote sends 'chat'
+ // This allows correcting misclassified models (e.g., image → video)
+ if (model.type) {
+ result.type = model.type;
+ }
+
+ return result;
+ }),
);
await this.#get().refreshAiModelList();
diff --git a/src/store/aiInfra/slices/aiModel/selectors.test.ts b/src/store/aiInfra/slices/aiModel/selectors.test.ts
index fc1edebb2e1..3a790c41d0c 100644
--- a/src/store/aiInfra/slices/aiModel/selectors.test.ts
+++ b/src/store/aiInfra/slices/aiModel/selectors.test.ts
@@ -267,4 +267,61 @@ describe('aiModelSelectors', () => {
).toBeUndefined();
});
});
+
+ describe('getModelCard', () => {
+ it('should find model in enabledAiModels first', () => {
+ const state: AIProviderStoreState = {
+ ...mockState,
+ enabledAiModels: [
+ {
+ id: 'test-model',
+ providerId: 'provider-a',
+ displayName: 'Enabled Model A',
+ abilities: {},
+ type: 'chat',
+ pricing: {
+ units: [{ name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' }],
+ },
+ },
+ ],
+ builtinAiModelList: [
+ {
+ id: 'test-model',
+ providerId: 'provider-a',
+ displayName: 'Builtin Model A',
+ abilities: {},
+ type: 'chat',
+ },
+ ],
+ };
+ const result = aiModelSelectors.getModelCard('test-model', 'provider-a')(state);
+ expect(result).toBeDefined();
+ expect(result?.displayName).toBe('Enabled Model A');
+ expect((result?.pricing?.units?.[0] as any)?.rate).toBe(1);
+ });
+
+ it('should fallback to builtinAiModelList if not in enabledAiModels', () => {
+ const state: AIProviderStoreState = {
+ ...mockState,
+ enabledAiModels: [],
+ builtinAiModelList: [
+ {
+ id: 'test-model',
+ providerId: 'provider-a',
+ displayName: 'Builtin Model A',
+ abilities: {},
+ type: 'chat',
+ },
+ ],
+ };
+ const result = aiModelSelectors.getModelCard('test-model', 'provider-a')(state);
+ expect(result).toBeDefined();
+ expect(result?.displayName).toBe('Builtin Model A');
+ });
+
+ it('should return undefined if model is not found in either list', () => {
+ const result = aiModelSelectors.getModelCard('non-existent', 'provider-a')(mockState);
+ expect(result).toBeUndefined();
+ });
+ });
});
diff --git a/src/store/aiInfra/slices/aiModel/selectors.ts b/src/store/aiInfra/slices/aiModel/selectors.ts
index 3d41cb5974c..16f8a3d569e 100644
--- a/src/store/aiInfra/slices/aiModel/selectors.ts
+++ b/src/store/aiInfra/slices/aiModel/selectors.ts
@@ -27,7 +27,9 @@ const totalAiProviderModelList = (s: AIProviderStoreState) => s.aiProviderModelL
const isEmptyAiProviderModelList = (s: AIProviderStoreState) => totalAiProviderModelList(s) === 0;
const getModelCard = (model: string, provider: string) => (s: AIProviderStoreState) =>
- s.builtinAiModelList.find((item) => item.id === model && item.providerId === provider);
+ s.enabledAiModels?.find(
+ (item) => item.id === model && (provider ? item.providerId === provider : true),
+ ) || s.builtinAiModelList.find((item) => item.id === model && item.providerId === provider);
const hasRemoteModels = (s: AIProviderStoreState) =>
s.aiProviderModelList.some((m) => m.source === AiModelSourceEnum.Remote);