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.

💄 style: modelParse support to get model settings params & Customize extendParams UI (#11185)

sxjeru94e985ad7fa9
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 0d9367931f1..48d4d9e6784 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -63,6 +63,7 @@
"extendParams.reasoningEffort.title": "推理强度",
"extendParams.textVerbosity.title": "输出详细程度",
"extendParams.thinking.title": "深度思考开关",
+ "extendParams.thinkingBudget.title": "思考预算",
"extendParams.thinkingLevel.title": "思考水平",
"extendParams.title": "模型扩展功能",
"extendParams.urlContext.desc": "开启后会自动解析网页链接,提取网页内容作为上下文",
diff --git a/locales/zh-CN/modelProvider.json b/locales/zh-CN/modelProvider.json
index ee6ec81f920..060833b183d 100644
--- a/locales/zh-CN/modelProvider.json
+++ b/locales/zh-CN/modelProvider.json
@@ -194,6 +194,26 @@
"providerModels.item.modelConfig.deployName.title": "模型部署名称",
"providerModels.item.modelConfig.displayName.placeholder": "请输入模型的展示名称,例如 ChatGPT、GPT-4 等",
"providerModels.item.modelConfig.displayName.title": "模型展示名称",
+ "providerModels.item.modelConfig.extendParams.extra": "根据模型支持的能力选择扩展参数,将鼠标悬停在选项上可预览配置。错误配置可能导致请求失败。",
+ "providerModels.item.modelConfig.extendParams.options.disableContextCaching.hint": "适用于 Claude 系列,可降低成本并加快响应速度。",
+ "providerModels.item.modelConfig.extendParams.options.enableReasoning.hint": "适用于 Claude、DeepSeek 等推理模型,开启深度推理能力。",
+ "providerModels.item.modelConfig.extendParams.options.gpt5ReasoningEffort.hint": "适用于 GPT-5 系列,控制推理力度。",
+ "providerModels.item.modelConfig.extendParams.options.gpt5_1ReasoningEffort.hint": "适用于 GPT-5.1 系列,控制推理力度。",
+ "providerModels.item.modelConfig.extendParams.options.gpt5_2ProReasoningEffort.hint": "适用于 GPT-5.2 Pro 系列,控制推理力度。",
+ "providerModels.item.modelConfig.extendParams.options.gpt5_2ReasoningEffort.hint": "适用于 GPT-5.2 系列,控制推理力度。",
+ "providerModels.item.modelConfig.extendParams.options.imageAspectRatio.hint": "适用于 Gemini 生图模型,控制生成图像的纵横比。",
+ "providerModels.item.modelConfig.extendParams.options.imageResolution.hint": "适用于 Gemini 3 生图模型,控制生成图像的分辨率。",
+ "providerModels.item.modelConfig.extendParams.options.reasoningBudgetToken.hint": "适用于 Claude、Qwen3 等模型,控制推理 token 预算。",
+ "providerModels.item.modelConfig.extendParams.options.reasoningEffort.hint": "适用于 OpenAI 等支持推理的模型,控制推理强度。",
+ "providerModels.item.modelConfig.extendParams.options.textVerbosity.hint": "适用于 GPT-5 系列,控制输出详尽程度。",
+ "providerModels.item.modelConfig.extendParams.options.thinking.hint": "适用于部分豆包系列,允许模型自行决定是否思考。",
+ "providerModels.item.modelConfig.extendParams.options.thinkingBudget.hint": "适用于 Gemini 系列,控制思考预算。",
+ "providerModels.item.modelConfig.extendParams.options.thinkingLevel.hint": "适用于 Gemini 3 Flash Preview 模型,控制思考深度。",
+ "providerModels.item.modelConfig.extendParams.options.thinkingLevel2.hint": "适用于 Gemini 3 Pro Preview 模型,控制思考深度。",
+ "providerModels.item.modelConfig.extendParams.options.urlContext.hint": "适用于 Gemini 系列,支持 URL 上下文输入。",
+ "providerModels.item.modelConfig.extendParams.placeholder": "选择需要启用的扩展参数",
+ "providerModels.item.modelConfig.extendParams.previewFallback": "暂不支持预览",
+ "providerModels.item.modelConfig.extendParams.title": "扩展功能参数",
"providerModels.item.modelConfig.files.extra": "当前文件上传实现仅为一种 Hack 方案,仅限自行尝试。完整文件上传能力请等待后续实现",
"providerModels.item.modelConfig.files.title": "支持文件上传",
"providerModels.item.modelConfig.functionCall.extra": "此配置将仅开启模型使用技能的能力,进而可以为模型添加技能。但是否支持真正使用技能完全取决于模型本身,请自行测试的可用性",
diff --git a/packages/database/src/models/aiModel.ts b/packages/database/src/models/aiModel.ts
index 4620c220e85..339a0ea4c99 100644
--- a/packages/database/src/models/aiModel.ts
+++ b/packages/database/src/models/aiModel.ts
@@ -78,6 +78,7 @@ export class AiModelModel {
parameters: aiModels.parameters,
pricing: aiModels.pricing,
releasedAt: aiModels.releasedAt,
+ settings: aiModels.settings,
source: aiModels.source,
type: aiModels.type,
})
@@ -105,6 +106,7 @@ export class AiModelModel {
parameters: aiModels.parameters,
providerId: aiModels.providerId,
releasedAt: aiModels.releasedAt,
+ settings: aiModels.settings,
sort: aiModels.sort,
source: aiModels.source,
type: aiModels.type,
diff --git a/packages/database/src/repositories/aiInfra/index.test.ts b/packages/database/src/repositories/aiInfra/index.test.ts
index de23f31079b..8316a051e05 100644
--- a/packages/database/src/repositories/aiInfra/index.test.ts
+++ b/packages/database/src/repositories/aiInfra/index.test.ts
@@ -4,7 +4,7 @@ import type {
AiProviderRuntimeConfig,
EnabledProvider,
} from '@lobechat/types';
-import { AiProviderModelListItem, EnabledAiModel } from 'model-bank';
+import { AiProviderModelListItem, EnabledAiModel, ExtendParamsType } from 'model-bank';
import { DEFAULT_MODEL_PROVIDER_LIST } from 'model-bank/modelProviders';
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -801,6 +801,46 @@ describe('AiInfraRepos', () => {
expect(merged?.settings).toEqual({ searchImpl: 'tool', searchProvider: 'google' });
});
+ it('should merge builtin settings with user-provided extend params', async () => {
+ const mockProviders = [
+ { enabled: true, id: 'openai', name: 'OpenAI', source: 'builtin' as const },
+ ];
+
+ const userModel: EnabledAiModel = {
+ abilities: {},
+ id: 'gpt-4',
+ providerId: 'openai',
+ enabled: true,
+ type: 'chat',
+ settings: { extendParams: ['reasoningEffort'] as ExtendParamsType[] },
+ };
+
+ const builtinModel = {
+ id: 'gpt-4',
+ enabled: true,
+ type: 'chat' as const,
+ settings: {
+ extendParams: ['thinking'] as ExtendParamsType[],
+ searchImpl: 'params',
+ searchProvider: 'builtin-provider',
+ },
+ };
+
+ vi.spyOn(repo, 'getAiProviderList').mockResolvedValue(mockProviders);
+ vi.spyOn(repo.aiModelModel, 'getAllModels').mockResolvedValue([userModel]);
+ vi.spyOn(repo as any, 'fetchBuiltinModels').mockResolvedValue([builtinModel]);
+
+ const result = await repo.getEnabledModels();
+
+ const merged = result.find((m) => m.id === 'gpt-4');
+ expect(merged).toBeDefined();
+ expect(merged?.settings).toEqual({
+ extendParams: ['reasoningEffort'],
+ searchImpl: 'params',
+ searchProvider: 'builtin-provider',
+ });
+ });
+
it('should have no settings when both user and builtin have no settings', async () => {
const mockProviders = [
{ enabled: true, id: 'openai', name: 'OpenAI', source: 'builtin' as const },
diff --git a/packages/database/src/repositories/aiInfra/index.ts b/packages/database/src/repositories/aiInfra/index.ts
index e04989b89a5..5d686288ab2 100644
--- a/packages/database/src/repositories/aiInfra/index.ts
+++ b/packages/database/src/repositories/aiInfra/index.ts
@@ -226,7 +226,9 @@ export class AiInfraRepos {
enabled: typeof user.enabled === 'boolean' ? user.enabled : item.enabled,
id: item.id,
providerId: provider.id,
- settings: user.settings || item.settings,
+ settings: isEmpty(user.settings)
+ ? item.settings
+ : merge(item.settings || {}, user.settings || {}),
sort: user.sort || undefined,
type: user.type || item.type,
};
diff --git a/packages/model-runtime/src/providers/openrouter/index.test.ts b/packages/model-runtime/src/providers/openrouter/index.test.ts
index be5bb53b042..d62dbd6471a 100644
--- a/packages/model-runtime/src/providers/openrouter/index.test.ts
+++ b/packages/model-runtime/src/providers/openrouter/index.test.ts
@@ -162,14 +162,14 @@ describe('LobeOpenRouterAI - custom features', () => {
);
});
- it('should add empty reasoning object when thinking is not enabled', async () => {
+ it('should not add reasoning object when thinking is not enabled', async () => {
await instance.chat({
messages: [{ content: 'Hello', role: 'user' }],
model: 'openai/gpt-4',
});
expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
- expect.objectContaining({ reasoning: {} }),
+ expect.not.objectContaining({ reasoning: expect.anything() }),
expect.anything(),
);
});
@@ -204,22 +204,6 @@ describe('LobeOpenRouterAI - custom features', () => {
);
});
- it('should cap reasoning tokens to max_tokens - 1 when budget exceeds max_tokens', async () => {
- await instance.chat({
- messages: [{ content: 'Think about this', role: 'user' }],
- model: 'openai/gpt-4',
- max_tokens: 1000,
- thinking: { type: 'enabled', budget_tokens: 2000 },
- });
-
- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
- expect.objectContaining({
- reasoning: { max_tokens: 999 }, // min(2000, 1000 - 1) = 999
- }),
- expect.anything(),
- );
- });
-
it('should use model maxOutput when no max_tokens provided', async () => {
// Mock OpenRouterModels to have a specific maxOutput
const { openrouter } = await import('model-bank');
@@ -241,21 +225,6 @@ describe('LobeOpenRouterAI - custom features', () => {
}
});
- it('should use default 32000 when no max_tokens or model maxOutput available', async () => {
- await instance.chat({
- messages: [{ content: 'Think about this', role: 'user' }],
- model: 'unknown/model-without-config',
- thinking: { type: 'enabled', budget_tokens: 50000 },
- });
-
- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
- expect.objectContaining({
- reasoning: { max_tokens: 31999 }, // min(50000, 32000 - 1) = 31999
- }),
- expect.anything(),
- );
- });
-
it('should combine enabledSearch and thinking features', async () => {
await instance.chat({
messages: [{ content: 'Search and think', role: 'user' }],
@@ -302,12 +271,12 @@ describe('LobeOpenRouterAI - custom features', () => {
});
expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
- expect.objectContaining({ reasoning: {} }),
+ expect.objectContaining({ reasoning: { enabled: false } }),
expect.anything(),
);
});
- it('should handle undefined thinking', async () => {
+ it('should not add reasoning when thinking is undefined', async () => {
await instance.chat({
messages: [{ content: 'Hello', role: 'user' }],
model: 'openai/gpt-4',
@@ -315,23 +284,7 @@ describe('LobeOpenRouterAI - custom features', () => {
});
expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
- expect.objectContaining({ reasoning: {} }),
- expect.anything(),
- );
- });
-
- it('should cap reasoning tokens to 1 when max_tokens is 2', async () => {
- await instance.chat({
- messages: [{ content: 'Think about this', role: 'user' }],
- model: 'openai/gpt-4',
- max_tokens: 2,
- thinking: { type: 'enabled', budget_tokens: 2000 },
- });
-
- expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
- expect.objectContaining({
- reasoning: { max_tokens: 1 }, // min(2000, 2 - 1) = 1
- }),
+ expect.not.objectContaining({ reasoning: expect.anything() }),
expect.anything(),
);
});
@@ -351,7 +304,7 @@ describe('LobeOpenRouterAI - custom features', () => {
);
});
- it('should handle 0 budget_tokens (falsy, falls back to 1024)', async () => {
+ it('should handle 0 budget_tokens (passes directly)', async () => {
await instance.chat({
messages: [{ content: 'Think about this', role: 'user' }],
model: 'openai/gpt-4',
@@ -360,7 +313,7 @@ describe('LobeOpenRouterAI - custom features', () => {
expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
expect.objectContaining({
- reasoning: { max_tokens: 1024 }, // 0 is falsy, falls back to 1024
+ reasoning: { max_tokens: 0 }, // 0 is passed directly
}),
expect.anything(),
);
@@ -1092,7 +1045,8 @@ describe('LobeOpenRouterAI - custom features', () => {
const models = await params.models();
const nullMaxOutputModel = models.find((m) => m.id === 'null-maxoutput/model');
- expect(nullMaxOutputModel?.maxOutput).toBeUndefined();
+ // When top_provider.max_completion_tokens is null, falls back to model.context_length
+ expect(nullMaxOutputModel?.maxOutput).toBe(8192);
});
it('should format releasedAt from created timestamp', async () => {
diff --git a/packages/model-runtime/src/providers/openrouter/index.ts b/packages/model-runtime/src/providers/openrouter/index.ts
index 415f3ab286c..048bc81a13e 100644
--- a/packages/model-runtime/src/providers/openrouter/index.ts
+++ b/packages/model-runtime/src/providers/openrouter/index.ts
@@ -1,4 +1,4 @@
-import { ModelProvider, openrouter as OpenRouterModels } from 'model-bank';
+import { ModelProvider } from 'model-bank';
import {
OpenAICompatibleFactoryOptions,
@@ -16,34 +16,27 @@ export const params = {
baseURL: 'https://openrouter.ai/api/v1',
chatCompletion: {
handlePayload: (payload) => {
- const { thinking, model, max_tokens } = payload;
-
- let reasoning: OpenRouterReasoning = {};
-
- if (thinking?.type === 'enabled') {
- const modelConfig = OpenRouterModels.find((m) => m.id === model);
- const defaultMaxOutput = modelConfig?.maxOutput;
-
- // 配置优先级:用户设置 > 模型配置 > 硬编码默认值
- const getMaxTokens = () => {
- if (max_tokens) return max_tokens;
- if (defaultMaxOutput) return defaultMaxOutput;
- return undefined;
- };
-
- const maxTokens = getMaxTokens() || 32_000; // Claude Opus 4 has minimum maxOutput
-
- reasoning = {
- max_tokens: thinking?.budget_tokens
- ? Math.min(thinking.budget_tokens, maxTokens - 1)
- : 1024,
- };
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { reasoning_effort, thinking, reasoning: _reasoning, ...rest } = payload;
+
+ let reasoning: OpenRouterReasoning | undefined;
+
+ if (thinking?.type || thinking?.budget_tokens !== undefined || reasoning_effort) {
+ if (thinking?.type === 'disabled') {
+ reasoning = { enabled: false };
+ } else if (thinking?.budget_tokens !== undefined) {
+ reasoning = {
+ max_tokens: thinking?.budget_tokens,
+ };
+ } else if (reasoning_effort) {
+ reasoning = { effort: reasoning_effort };
+ }
}
return {
- ...payload,
+ ...rest,
model: payload.enabledSearch ? `${payload.model}:online` : payload.model,
- reasoning,
+ ...(reasoning && { reasoning }),
stream: payload.stream ?? true,
} as any;
},
@@ -104,6 +97,8 @@ export const params = {
displayName += ' (free)';
}
+ const hasReasoning = supported_parameters.includes('reasoning');
+
return {
contextWindowTokens: top_provider.context_length || model.context_length,
description: model.description,
@@ -113,16 +108,41 @@ export const params = {
maxOutput:
typeof top_provider.max_completion_tokens === 'number'
? top_provider.max_completion_tokens
- : undefined,
+ : typeof model.context_length === 'number'
+ ? model.context_length
+ : undefined,
pricing: {
cachedInput: cachedInputPrice,
input: inputPrice,
output: outputPrice,
writeCacheInput: writeCacheInputPrice,
},
- reasoning: supported_parameters.includes('reasoning'),
+ reasoning: hasReasoning,
releasedAt: new Date(model.created * 1000).toISOString().split('T')[0],
vision: inputModalities.includes('image'),
+ // Merge all applicable extendParams for settings
+ ...(() => {
+ const extendParams: string[] = [];
+ if (model.description && model.description.includes('`reasoning` `enabled`')) {
+ extendParams.push('enableReasoning');
+ }
+ if (hasReasoning && model.id.includes('gpt-5')) {
+ extendParams.push('gpt5ReasoningEffort');
+ }
+ if (hasReasoning && model.id.includes('openai') && !model.id.includes('gpt-5')) {
+ extendParams.push('reasoningEffort');
+ }
+ if (hasReasoning && model.id.includes('claude')) {
+ extendParams.push('enableReasoning', 'reasoningBudgetToken');
+ }
+ if (model.id.includes('claude') && writeCacheInputPrice && writeCacheInputPrice !== 0) {
+ extendParams.push('disableContextCaching');
+ }
+ if (hasReasoning && model.id.includes('gemini-2.5')) {
+ extendParams.push('reasoningBudgetToken');
+ }
+ return extendParams.length > 0 ? { settings: { extendParams } } : {};
+ })(),
};
});
diff --git a/packages/model-runtime/src/providers/openrouter/type.ts b/packages/model-runtime/src/providers/openrouter/type.ts
index cbccdba1c84..4d2de6ddab7 100644
--- a/packages/model-runtime/src/providers/openrouter/type.ts
+++ b/packages/model-runtime/src/providers/openrouter/type.ts
@@ -3,57 +3,45 @@ interface ModelPricing {
image?: string;
input_cache_read?: string;
input_cache_write?: string;
+ internal_reasoning?: string;
prompt: string;
request?: string;
web_search?: string;
- internal_reasoning?: string;
}
interface TopProvider {
context_length: number;
- max_completion_tokens: number | null;
is_moderated: boolean;
+ max_completion_tokens: number | null;
}
interface Architecture {
- modality: string;
input_modalities: string[];
+ instruct_type: string | null;
+ modality: string;
output_modalities: string[];
tokenizer: string;
- instruct_type: string | null;
}
export interface OpenRouterModelCard {
- id: string;
+ architecture: Architecture;
canonical_slug: string;
- hugging_face_id?: string;
- name: string;
+ context_length: number;
created: number;
+ default_parameters?: any | null;
description?: string;
- context_length: number;
- architecture: Architecture;
- pricing: ModelPricing;
- top_provider: TopProvider;
+ hugging_face_id?: string;
+ id: string;
+ name: string;
per_request_limits?: any | null;
+ pricing: ModelPricing;
supported_parameters: string[];
- default_parameters?: any | null;
-}
-
-interface OpenRouterOpenAIReasoning {
- effort: 'high' | 'medium' | 'low';
- exclude?: boolean;
-}
-
-interface OpenRouterAnthropicReasoning {
- exclude?: boolean;
- max_tokens: number;
+ top_provider: TopProvider;
}
-interface OpenRouterCommonReasoning {
+export interface OpenRouterReasoning {
+ effort?: 'high' | 'medium' | 'low' | 'minimal';
+ enabled?: boolean;
exclude?: boolean;
+ max_tokens?: number;
}
-
-export type OpenRouterReasoning =
- | OpenRouterOpenAIReasoning
- | OpenRouterAnthropicReasoning
- | OpenRouterCommonReasoning;
diff --git a/packages/model-runtime/src/providers/vercelaigateway/index.test.ts b/packages/model-runtime/src/providers/vercelaigateway/index.test.ts
index 959091f2890..5b00062712e 100644
--- a/packages/model-runtime/src/providers/vercelaigateway/index.test.ts
+++ b/packages/model-runtime/src/providers/vercelaigateway/index.test.ts
@@ -71,7 +71,7 @@ describe('LobeVercelAIGatewayAI - custom features', () => {
it('should add reasoning_effort to providerOptions.openai', async () => {
await instance.chat({
messages: [{ content: 'Hello', role: 'user' }],
- model: 'o1-preview',
+ model: 'openai/o1-preview',
reasoning_effort: 'high',
});
@@ -83,7 +83,7 @@ describe('LobeVercelAIGatewayAI - custom features', () => {
it('should handle both reasoning_effort and verbosity', async () => {
await instance.chat({
messages: [{ content: 'Hello', role: 'user' }],
- model: 'o1-preview',
+ model: 'openai/o1-preview',
reasoning_effort: 'medium',
verbosity: 'low',
});
@@ -96,7 +96,7 @@ describe('LobeVercelAIGatewayAI - custom features', () => {
it('should handle verbosity without reasoning_effort', async () => {
await instance.chat({
messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4o',
+ model: 'openai/gpt-4o',
verbosity: 'high',
});
@@ -119,13 +119,13 @@ describe('LobeVercelAIGatewayAI - custom features', () => {
await instance.chat({
max_tokens: 1000,
messages: [{ content: 'Hello', role: 'user' }],
- model: 'o1-preview',
+ model: 'openai/o1-preview',
reasoning_effort: 'high',
temperature: 0.7,
});
const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
- expect(calledPayload.model).toBe('o1-preview');
+ expect(calledPayload.model).toBe('openai/o1-preview');
expect(calledPayload.temperature).toBe(0.7);
expect(calledPayload.max_tokens).toBe(1000);
expect(calledPayload.reasoning_effort).toBeUndefined();
@@ -138,7 +138,7 @@ describe('LobeVercelAIGatewayAI - custom features', () => {
vi.clearAllMocks();
await instance.chat({
messages: [{ content: 'Hello', role: 'user' }],
- model: 'o1-preview',
+ model: 'openai/o1-preview',
reasoning_effort: effort,
} as any);
diff --git a/packages/model-runtime/src/providers/vercelaigateway/index.ts b/packages/model-runtime/src/providers/vercelaigateway/index.ts
index 80f27708eb1..cccc4086724 100644
--- a/packages/model-runtime/src/providers/vercelaigateway/index.ts
+++ b/packages/model-runtime/src/providers/vercelaigateway/index.ts
@@ -23,6 +23,11 @@ export interface VercelAIGatewayModelCard {
type?: string;
}
+export interface VercelAIGatewayReasoning {
+ enabled?: boolean;
+ max_tokens?: number;
+}
+
export const formatPrice = (price?: string | number) => {
if (price === undefined || price === null) return undefined;
const n = typeof price === 'number' ? price : Number(price);
@@ -35,23 +40,41 @@ export const params = {
baseURL: 'https://ai-gateway.vercel.sh/v1',
chatCompletion: {
handlePayload: (payload) => {
- const { model, reasoning_effort, verbosity, ...rest } = payload;
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { reasoning_effort, thinking, reasoning: _reasoning, verbosity, ...rest } = payload;
- const providerOptions: any = {};
- if (reasoning_effort || verbosity) {
- providerOptions.openai = {};
- if (reasoning_effort) {
- providerOptions.openai.reasoningEffort = reasoning_effort;
- providerOptions.openai.reasoningSummary = 'auto';
- }
- if (verbosity) {
- providerOptions.openai.textVerbosity = verbosity;
+ let reasoning: VercelAIGatewayReasoning | undefined;
+
+ if (thinking?.type || thinking?.budget_tokens !== undefined || reasoning_effort) {
+ if (thinking?.type === 'disabled') {
+ reasoning = { enabled: false };
+ } else if (thinking?.budget_tokens !== undefined) {
+ reasoning = {
+ enabled: true,
+ max_tokens: thinking?.budget_tokens,
+ };
+ } else if (reasoning_effort) {
+ reasoning = { enabled: true };
}
}
+ const providerOptions: any = {};
+ if ((verbosity || reasoning) && payload.model.includes('openai')) {
+ providerOptions.openai = {
+ ...(reasoning_effort && {
+ reasoningEffort: reasoning_effort,
+ reasoningSummary: 'auto',
+ }),
+ ...(verbosity && {
+ textVerbosity: verbosity,
+ }),
+ };
+ }
+
return {
...rest,
- model,
+ model: payload.model,
+ ...(reasoning && { reasoning }),
providerOptions,
} as any;
},
@@ -99,6 +122,26 @@ export const params = {
reasoning: tags.includes('reasoning') || false,
type: m.type === 'embedding' ? 'embedding' : 'chat',
vision: tags.includes('vision') || false,
+ // Merge all applicable extendParams for settings
+ ...(() => {
+ const extendParams: string[] = [];
+ if (tags.includes('reasoning') && m.id.includes('gpt-5')) {
+ extendParams.push('gpt5ReasoningEffort', 'textVerbosity');
+ }
+ if (tags.includes('reasoning') && m.id.includes('openai') && !m.id.includes('gpt-5')) {
+ extendParams.push('reasoningEffort', 'textVerbosity');
+ }
+ if (tags.includes('reasoning') && m.id.includes('claude')) {
+ extendParams.push('enableReasoning', 'reasoningBudgetToken');
+ }
+ if (m.id.includes('claude') && writeCacheInputPrice && writeCacheInputPrice !== 0) {
+ extendParams.push('disableContextCaching');
+ }
+ if (tags.includes('reasoning') && m.id.includes('gemini-2.5')) {
+ extendParams.push('reasoningBudgetToken');
+ }
+ return extendParams.length > 0 ? { settings: { extendParams } } : {};
+ })(),
} as any;
});
diff --git a/packages/model-runtime/src/utils/modelParse.test.ts b/packages/model-runtime/src/utils/modelParse.test.ts
index a48f7826671..bf0b1d9d532 100644
--- a/packages/model-runtime/src/utils/modelParse.test.ts
+++ b/packages/model-runtime/src/utils/modelParse.test.ts
@@ -94,6 +94,16 @@ const mockDefaultModelList: (Partial<ChatModelCard> & { id: string })[] = [
enabled: false,
id: 'model-known-disabled',
},
+ {
+ displayName: 'Known Model With Settings',
+ enabled: true,
+ id: 'model-known-settings',
+ settings: {
+ extendParams: ['enableReasoning'],
+ searchImpl: 'params',
+ searchProvider: 'builtin',
+ },
+ },
];
// Mock the import
@@ -242,7 +252,11 @@ describe('modelParse', () => {
describe('search and imageOutput (processModelList)', () => {
it('openai: default search keywords should make "*-search" models support search', async () => {
// openai config does not define searchKeywords, so DEFAULT_SEARCH_KEYWORDS ['-search'] applies
- const out = await processModelList([{ id: 'gpt-4o-search' }], MODEL_LIST_CONFIGS.openai, 'openai');
+ const out = await processModelList(
+ [{ id: 'gpt-4o-search' }],
+ MODEL_LIST_CONFIGS.openai,
+ 'openai',
+ );
expect(out).toHaveLength(1);
expect(out[0].search).toBe(true);
});
@@ -276,7 +290,11 @@ describe('modelParse', () => {
});
it('google: gemini-* without "-image-" should not infer imageOutput and get search=true via known google model', async () => {
- const out = await processModelList([{ id: 'gemini-2.5-pro' }], MODEL_LIST_CONFIGS.google, 'google');
+ const out = await processModelList(
+ [{ id: 'gemini-2.5-pro' }],
+ MODEL_LIST_CONFIGS.google,
+ 'google',
+ );
expect(out).toHaveLength(1);
expect(out[0].displayName).toBe('Gemini 2.5 Pro');
expect(out[0].search).toBe(true);
@@ -354,6 +372,36 @@ describe('modelParse', () => {
expect(result.find((m) => m.id === 'model-known-disabled')!.enabled).toBe(false);
expect(result.find((m) => m.id === 'unknown-model-for-enabled-test')!.enabled).toBe(false);
});
+
+ it('should include settings from known model when remote data does not provide them', async () => {
+ const modelList = [{ id: 'model-known-settings' }];
+ const result = await processModelList(modelList, config);
+
+ const settings = result[0].settings;
+ expect(settings).toBeDefined();
+ expect(settings?.extendParams).toEqual(['enableReasoning']);
+ expect(settings?.searchImpl).toBe('params');
+ expect(settings?.searchProvider).toBe('builtin');
+ });
+
+ it('should merge extendParams from known and remote models while preserving uniqueness', async () => {
+ const modelList = [
+ {
+ id: 'model-known-settings',
+ settings: {
+ extendParams: ['reasoningBudgetToken', 'enableReasoning'],
+ searchImpl: 'tool',
+ },
+ },
+ ];
+
+ const result = await processModelList(modelList, config);
+ const settings = result[0].settings;
+
+ expect(settings?.extendParams).toEqual(['enableReasoning', 'reasoningBudgetToken']);
+ expect(settings?.searchImpl).toBe('tool');
+ expect(settings?.searchProvider).toBe('builtin');
+ });
});
});
@@ -497,7 +545,7 @@ describe('modelParse', () => {
});
it('default search keywords should make "*-search" models support search', async () => {
- const out = await processMultiProviderModelList([{ id: 'gpt-4o-search'}]);
+ const out = await processMultiProviderModelList([{ id: 'gpt-4o-search' }]);
expect(out).toHaveLength(1);
expect(out[0].search).toBe(true);
});
@@ -674,6 +722,140 @@ describe('modelParse', () => {
expect(glm.vision).toBe(true);
});
+ it('should include known extendParams for OpenAI and Google providers regardless of providerid', async () => {
+ const mockModule = await import('model-bank');
+ mockModule.LOBE_DEFAULT_MODEL_LIST.push(
+ {
+ id: 'gpt-openai-extend-restricted',
+ displayName: 'OpenAI Extend Restricted',
+ settings: {
+ extendParams: ['openaiParam'],
+ },
+ } as any,
+ {
+ id: 'gemini-extend-restricted',
+ displayName: 'Gemini Extend Restricted',
+ settings: {
+ extendParams: ['thinkingBudget', 'urlContext'],
+ },
+ } as any,
+ );
+
+ const modelList = [
+ { id: 'gpt-openai-extend-restricted' },
+ { id: 'gemini-extend-restricted' },
+ ];
+
+ const result = await processMultiProviderModelList(modelList, 'vercelaigateway');
+
+ const openaiModel = result.find((m) => m.id === 'gpt-openai-extend-restricted');
+ const googleModel = result.find((m) => m.id === 'gemini-extend-restricted');
+
+ // Both OpenAI and Google providers always include known extendParams
+ expect(openaiModel?.settings?.extendParams).toEqual(['openaiParam']);
+ expect(googleModel?.settings?.extendParams).toEqual(['thinkingBudget', 'urlContext']);
+ });
+
+ it('should allow known extendParams for non-OpenAI providers when provider is aihubmix', async () => {
+ const mockModule = await import('model-bank');
+ mockModule.LOBE_DEFAULT_MODEL_LIST.push({
+ id: 'gemini-extend-aihubmix',
+ displayName: 'Gemini Extend Aihubmix',
+ settings: {
+ extendParams: ['thinkingBudget', 'urlContext'],
+ },
+ } as any);
+
+ const modelList = [{ id: 'gemini-extend-aihubmix' }];
+
+ const result = await processMultiProviderModelList(modelList, 'aihubmix');
+
+ const googleModel = result.find((m) => m.id === 'gemini-extend-aihubmix');
+
+ expect(googleModel?.settings?.extendParams).toEqual(['thinkingBudget', 'urlContext']);
+ });
+
+ it('should omit search settings when provider is neither aihubmix nor newapi', async () => {
+ const mockModule = await import('model-bank');
+ const initialLength = mockModule.LOBE_DEFAULT_MODEL_LIST.length;
+ mockModule.LOBE_DEFAULT_MODEL_LIST.push({
+ id: 'search-settings-model',
+ displayName: 'Search Settings Model',
+ settings: {
+ searchImpl: 'params',
+ searchProvider: 'builtin',
+ },
+ } as any);
+
+ try {
+ const result = await processMultiProviderModelList(
+ [{ id: 'search-settings-model' }],
+ 'vercelaigateway',
+ );
+
+ const model = result.find((m) => m.id === 'search-settings-model');
+
+ expect(model?.settings?.searchImpl).toBeUndefined();
+ expect(model?.settings?.searchProvider).toBeUndefined();
+ } finally {
+ mockModule.LOBE_DEFAULT_MODEL_LIST.splice(initialLength);
+ }
+ });
+
+ it('should include search settings when provider is aihubmix', async () => {
+ const mockModule = await import('model-bank');
+ const initialLength = mockModule.LOBE_DEFAULT_MODEL_LIST.length;
+ mockModule.LOBE_DEFAULT_MODEL_LIST.push({
+ id: 'search-settings-aihubmix',
+ displayName: 'Search Settings Aihubmix',
+ settings: {
+ searchImpl: 'params',
+ searchProvider: 'builtin',
+ },
+ } as any);
+
+ try {
+ const result = await processMultiProviderModelList(
+ [{ id: 'search-settings-aihubmix' }],
+ 'aihubmix',
+ );
+
+ const model = result.find((m) => m.id === 'search-settings-aihubmix');
+
+ expect(model?.settings?.searchImpl).toBe('params');
+ expect(model?.settings?.searchProvider).toBe('builtin');
+ } finally {
+ mockModule.LOBE_DEFAULT_MODEL_LIST.splice(initialLength);
+ }
+ });
+
+ it('should include search settings when provider is newapi', async () => {
+ const mockModule = await import('model-bank');
+ const initialLength = mockModule.LOBE_DEFAULT_MODEL_LIST.length;
+ mockModule.LOBE_DEFAULT_MODEL_LIST.push({
+ id: 'search-settings-newapi',
+ displayName: 'Search Settings NewAPI',
+ settings: {
+ searchImpl: 'params',
+ searchProvider: 'builtin',
+ },
+ } as any);
+
+ try {
+ const result = await processMultiProviderModelList(
+ [{ id: 'search-settings-newapi' }],
+ 'newapi',
+ );
+
+ const model = result.find((m) => m.id === 'search-settings-newapi');
+
+ expect(model?.settings?.searchImpl).toBe('params');
+ expect(model?.settings?.searchProvider).toBe('builtin');
+ } finally {
+ mockModule.LOBE_DEFAULT_MODEL_LIST.splice(initialLength);
+ }
+ });
+
it('should correctly handle models with excluded keywords in different providers', async () => {
// OpenAI excludes 'audio', other providers don't have excluded keywords
const modelList = [
diff --git a/packages/model-runtime/src/utils/modelParse.ts b/packages/model-runtime/src/utils/modelParse.ts
index 9875d6ff22f..5437fa1a41e 100644
--- a/packages/model-runtime/src/utils/modelParse.ts
+++ b/packages/model-runtime/src/utils/modelParse.ts
@@ -1,5 +1,6 @@
import type { ChatModelCard } from '@lobechat/types';
import { AIBaseModelCard } from 'model-bank';
+import type { AiModelSettings, ExtendParamsType } from 'model-bank';
import type { ModelProviderKey } from '../types';
@@ -344,6 +345,75 @@ const processDisplayName = (displayName: string): string => {
return displayName;
};
+const mergeExtendParams = (
+ modelExtendParams?: ReadonlyArray<ExtendParamsType>,
+ knownExtendParams?: ReadonlyArray<ExtendParamsType>,
+ options?: { includeKnownExtendParams?: boolean },
+): ExtendParamsType[] | undefined => {
+ const includeKnown = options?.includeKnownExtendParams ?? true;
+
+ const combined = [
+ ...(includeKnown ? (knownExtendParams ?? []) : []),
+ ...(modelExtendParams ?? []),
+ ];
+
+ if (combined.length === 0) return undefined;
+
+ return Array.from(new Set(combined));
+};
+
+const mergeSettings = (
+ modelSettings?: AiModelSettings,
+ knownSettings?: AiModelSettings,
+ options?: { includeKnownExtendParams?: boolean; includeSearchSettings?: boolean },
+): AiModelSettings | undefined => {
+ if (!modelSettings && !knownSettings) return undefined;
+
+ const merged: AiModelSettings = {};
+
+ if (knownSettings) {
+ Object.assign(merged, knownSettings);
+ }
+
+ if (modelSettings) {
+ Object.assign(merged, modelSettings);
+ }
+
+ const extendParams = mergeExtendParams(
+ modelSettings?.extendParams,
+ knownSettings?.extendParams,
+ options,
+ );
+ if (extendParams) {
+ merged.extendParams = extendParams;
+ } else {
+ delete merged.extendParams;
+ }
+
+ const includeSearchSettings = options?.includeSearchSettings ?? true;
+
+ if (includeSearchSettings) {
+ const searchImpl = modelSettings?.searchImpl ?? knownSettings?.searchImpl;
+ if (searchImpl) {
+ merged.searchImpl = searchImpl;
+ } else {
+ delete merged.searchImpl;
+ }
+
+ const searchProvider = modelSettings?.searchProvider ?? knownSettings?.searchProvider;
+ if (searchProvider) {
+ merged.searchProvider = searchProvider;
+ } else {
+ delete merged.searchProvider;
+ }
+ } else {
+ delete merged.searchImpl;
+ delete merged.searchProvider;
+ }
+
+ return Object.keys(merged).length > 0 ? merged : undefined;
+};
+
/**
* Get the local configuration of the model provider
* @param provider Model provider
@@ -389,6 +459,7 @@ const processModelCard = (
model: { [key: string]: any; id: string },
config: ModelProcessorConfig,
knownModel?: any,
+ options?: { includeKnownExtendParams?: boolean; includeSearchSettings?: boolean },
): ChatModelCard | undefined => {
const {
functionCallKeywords = [],
@@ -421,6 +492,8 @@ const processModelCard = (
return undefined;
}
+ const mergedSettings = mergeSettings(model.settings, knownModel?.settings, options);
+
const formatPricing = (pricing?: {
cachedInput?: number;
input?: number;
@@ -510,6 +583,7 @@ const processModelCard = (
...(modelType === 'image' && {
parameters: model.parameters ?? knownModel?.parameters,
}),
+ ...(mergedSettings ? { settings: mergedSettings } : {}),
video:
model.video ??
knownModel?.abilities?.video ??
@@ -606,13 +680,46 @@ export const processMultiProviderModelList = async (
);
}
+ const includeKnownExtendParams =
+ providerid === 'aihubmix' ||
+ providerid === 'newapi' ||
+ detectedProvider === 'openai' ||
+ detectedProvider === 'google';
+ const includeSearchSettings = providerid === 'aihubmix' || providerid === 'newapi';
+
// If providerid is provided and has local configuration, try to get the model's enabled status from it
const providerLocalModelConfig = getModelLocalEnableConfig(
providerLocalConfig as any[],
model,
);
- const processedModel = processModelCard(model, config, knownModel);
+ const processedModel = processModelCard(model, config, knownModel, {
+ includeKnownExtendParams,
+ includeSearchSettings,
+ });
+
+ if (processedModel && includeSearchSettings && providerLocalModelConfig?.settings) {
+ const localSettings = providerLocalModelConfig.settings as AiModelSettings | undefined;
+ const searchImpl = localSettings?.searchImpl;
+ const searchProvider = localSettings?.searchProvider;
+
+ if (searchImpl || searchProvider) {
+ const updatedSettings: AiModelSettings = processedModel.settings
+ ? { ...processedModel.settings }
+ : ({} as AiModelSettings);
+
+ if (searchImpl) {
+ updatedSettings.searchImpl = searchImpl;
+ }
+
+ if (searchProvider) {
+ updatedSettings.searchProvider = searchProvider;
+ }
+
+ processedModel.settings =
+ Object.keys(updatedSettings).length > 0 ? updatedSettings : undefined;
+ }
+ }
// If model is found in local configuration, use its enabled status
if (
diff --git a/packages/types/src/llm.ts b/packages/types/src/llm.ts
index c9126c7ca23..7fc09821929 100644
--- a/packages/types/src/llm.ts
+++ b/packages/types/src/llm.ts
@@ -1,4 +1,4 @@
-import { AiModelType, ModelParamsSchema, Pricing } from 'model-bank';
+import { AiModelSettings, AiModelType, ModelParamsSchema, Pricing } from 'model-bank';
import { ReactNode } from 'react';
import { AiProviderSettings } from './aiProvider';
@@ -64,6 +64,8 @@ export interface ChatModelCard {
*/
search?: boolean;
+ settings?: AiModelSettings;
+
type?: AiModelType;
/**
diff --git a/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/ExtendParamsSelect.tsx b/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/ExtendParamsSelect.tsx
new file mode 100644
index 00000000000..69cfd20e1da
--- /dev/null
+++ b/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/ExtendParamsSelect.tsx
@@ -0,0 +1,398 @@
+import { Flexbox } from '@lobehub/ui';
+import { Popover, Select, Space, Switch, Tag, Typography, theme } from 'antd';
+import type { ExtendParamsType } from 'model-bank';
+import { memo, useMemo } from 'react';
+import type { ReactNode } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+
+import GPT5ReasoningEffortSlider from '@/features/ChatInput/ActionBar/Model/GPT5ReasoningEffortSlider';
+import GPT51ReasoningEffortSlider from '@/features/ChatInput/ActionBar/Model/GPT51ReasoningEffortSlider';
+import GPT52ProReasoningEffortSlider from '@/features/ChatInput/ActionBar/Model/GPT52ProReasoningEffortSlider';
+import GPT52ReasoningEffortSlider from '@/features/ChatInput/ActionBar/Model/GPT52ReasoningEffortSlider';
+import ImageAspectRatioSelect from '@/features/ChatInput/ActionBar/Model/ImageAspectRatioSelect';
+import ImageResolutionSlider from '@/features/ChatInput/ActionBar/Model/ImageResolutionSlider';
+import ReasoningEffortSlider from '@/features/ChatInput/ActionBar/Model/ReasoningEffortSlider';
+import ReasoningTokenSlider from '@/features/ChatInput/ActionBar/Model/ReasoningTokenSlider';
+import TextVerbositySlider from '@/features/ChatInput/ActionBar/Model/TextVerbositySlider';
+import ThinkingBudgetSlider from '@/features/ChatInput/ActionBar/Model/ThinkingBudgetSlider';
+import ThinkingLevel2Slider from '@/features/ChatInput/ActionBar/Model/ThinkingLevel2Slider';
+import ThinkingLevelSlider from '@/features/ChatInput/ActionBar/Model/ThinkingLevelSlider';
+import ThinkingSlider from '@/features/ChatInput/ActionBar/Model/ThinkingSlider';
+
+type ExtendParamsOption = {
+ hintKey: string;
+ key: ExtendParamsType;
+};
+
+const EXTEND_PARAMS_OPTIONS: ExtendParamsOption[] = [
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.disableContextCaching.hint',
+ key: 'disableContextCaching',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.enableReasoning.hint',
+ key: 'enableReasoning',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.reasoningBudgetToken.hint',
+ key: 'reasoningBudgetToken',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.reasoningEffort.hint',
+ key: 'reasoningEffort',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.gpt5ReasoningEffort.hint',
+ key: 'gpt5ReasoningEffort',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.gpt5_1ReasoningEffort.hint',
+ key: 'gpt5_1ReasoningEffort',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.gpt5_2ReasoningEffort.hint',
+ key: 'gpt5_2ReasoningEffort',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.gpt5_2ProReasoningEffort.hint',
+ key: 'gpt5_2ProReasoningEffort',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.textVerbosity.hint',
+ key: 'textVerbosity',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.thinking.hint',
+ key: 'thinking',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.thinkingBudget.hint',
+ key: 'thinkingBudget',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.thinkingLevel.hint',
+ key: 'thinkingLevel',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.thinkingLevel2.hint',
+ key: 'thinkingLevel2',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.urlContext.hint',
+ key: 'urlContext',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.imageAspectRatio.hint',
+ key: 'imageAspectRatio',
+ },
+ {
+ hintKey: 'providerModels.item.modelConfig.extendParams.options.imageResolution.hint',
+ key: 'imageResolution',
+ },
+];
+
+// Map variant keys to their base i18n title key (synced with ControlsForm.tsx)
+// This allows reusing existing i18n translations instead of adding new ones
+const TITLE_KEY_ALIASES: Partial<Record<ExtendParamsType, ExtendParamsType>> = {
+ gpt5ReasoningEffort: 'reasoningEffort',
+ gpt5_1ReasoningEffort: 'reasoningEffort',
+ gpt5_2ProReasoningEffort: 'reasoningEffort',
+ gpt5_2ReasoningEffort: 'reasoningEffort',
+ thinkingLevel2: 'thinkingLevel',
+};
+
+type PreviewMeta = {
+ labelOverride?: string;
+ labelSuffix?: string;
+ previewWidth?: number;
+ tag?: string;
+};
+
+const PREVIEW_META: Partial<Record<ExtendParamsType, PreviewMeta>> = {
+ disableContextCaching: { labelSuffix: ' (Claude)', previewWidth: 400 },
+ enableReasoning: { previewWidth: 300, tag: 'thinking.type' },
+ gpt5ReasoningEffort: { previewWidth: 300, tag: 'reasoning_effort' },
+ gpt5_1ReasoningEffort: { labelSuffix: ' (GPT-5.1)', previewWidth: 300, tag: 'reasoning_effort' },
+ gpt5_2ProReasoningEffort: {
+ labelSuffix: ' (GPT-5.2 Pro)',
+ previewWidth: 300,
+ tag: 'reasoning_effort',
+ },
+ gpt5_2ReasoningEffort: { labelSuffix: ' (GPT-5.2)', previewWidth: 300, tag: 'reasoning_effort' },
+ imageAspectRatio: { labelSuffix: '', previewWidth: 350, tag: 'aspect_ratio' },
+ imageResolution: { labelSuffix: '', previewWidth: 250, tag: 'resolution' },
+ reasoningBudgetToken: { previewWidth: 350, tag: 'thinking.budget_tokens' },
+ reasoningEffort: { previewWidth: 250, tag: 'reasoning_effort' },
+ textVerbosity: { labelSuffix: '', previewWidth: 250, tag: 'text_verbosity' },
+ thinking: { labelSuffix: ' (Doubao)', previewWidth: 300, tag: 'thinking.type' },
+ thinkingBudget: { labelSuffix: ' (Gemini)', previewWidth: 500, tag: 'thinkingBudget' },
+ thinkingLevel: { labelSuffix: ' (Gemini 3)', previewWidth: 280, tag: 'thinkingLevel' },
+ thinkingLevel2: { labelSuffix: ' (Gemini 3)', previewWidth: 200, tag: 'thinkingLevel' },
+ urlContext: { labelSuffix: ' (Gemini)', previewWidth: 400, tag: 'urlContext' },
+};
+
+type ExtendParamsDefinition = {
+ desc?: ReactNode;
+ hint: string;
+ key: ExtendParamsType;
+ label: string;
+ parameterTag?: string;
+ preview?: ReactNode;
+ previewWidth?: number;
+};
+
+interface ExtendParamsSelectProps {
+ onChange?: (value: ExtendParamsType[] | undefined) => void;
+ value?: ExtendParamsType[];
+}
+
+const PreviewContent = ({
+ desc,
+ hint,
+ label,
+ preview,
+ previewFallback,
+ parameterTag,
+ previewWidth,
+}: {
+ desc?: ReactNode;
+ hint: string;
+ label: string;
+ parameterTag?: string;
+ preview?: ReactNode;
+ previewFallback: string;
+ previewWidth?: number;
+}) => {
+ const { token } = theme.useToken();
+ const containerStyle = previewWidth
+ ? { minWidth: previewWidth, width: previewWidth }
+ : { minWidth: 240 };
+
+ return (
+ <Flexbox gap={12} style={containerStyle}>
+ <Typography.Text style={{ whiteSpace: 'normal' }} type={'secondary'}>
+ {hint}
+ </Typography.Text>
+ <Flexbox gap={12}>
+ <Flexbox
+ gap={8}
+ style={{
+ background: token.colorBgElevated,
+ border: `1px solid ${token.colorBorderSecondary}`,
+ borderRadius: 10,
+ padding: 12,
+ width: previewWidth,
+ }}
+ >
+ <Flexbox align={'center'} gap={8} horizontal>
+ <Typography.Text strong>{label}</Typography.Text>
+ {parameterTag ? <Tag color={'cyan'}>{parameterTag}</Tag> : null}
+ </Flexbox>
+ {desc ? (
+ <Typography.Text style={{ fontSize: 12, whiteSpace: 'normal' }} type={'secondary'}>
+ {desc}
+ </Typography.Text>
+ ) : null}
+ {preview ? (
+ <div style={{ pointerEvents: 'none', width: '100%' }}>{preview}</div>
+ ) : (
+ <Typography.Text type={'secondary'}>{previewFallback}</Typography.Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+};
+
+const ExtendParamsSelect = memo<ExtendParamsSelectProps>(({ value, onChange }) => {
+ const { t } = useTranslation('modelProvider');
+ const { t: tChat } = useTranslation('chat');
+
+ // Preview controls use controlled mode with default values (no store access)
+ const previewControls = useMemo<Partial<Record<ExtendParamsType, ReactNode>>>(
+ () => ({
+ disableContextCaching: <Switch checked disabled />,
+ enableReasoning: <Switch checked disabled />,
+ gpt5ReasoningEffort: <GPT5ReasoningEffortSlider value="medium" />,
+ gpt5_1ReasoningEffort: <GPT51ReasoningEffortSlider value="none" />,
+ gpt5_2ProReasoningEffort: <GPT52ProReasoningEffortSlider value="medium" />,
+ gpt5_2ReasoningEffort: <GPT52ReasoningEffortSlider value="none" />,
+ imageAspectRatio: <ImageAspectRatioSelect value="1:1" />,
+ imageResolution: <ImageResolutionSlider value="1K" />,
+ reasoningBudgetToken: <ReasoningTokenSlider defaultValue={1 * 1024} />,
+ reasoningEffort: <ReasoningEffortSlider value="medium" />,
+ textVerbosity: <TextVerbositySlider value="medium" />,
+ thinking: <ThinkingSlider value="auto" />,
+ thinkingBudget: <ThinkingBudgetSlider defaultValue={2 * 1024} />,
+ thinkingLevel: <ThinkingLevelSlider value="high" />,
+ thinkingLevel2: <ThinkingLevel2Slider value="high" />,
+ urlContext: <Switch checked disabled />,
+ }),
+ [],
+ );
+
+ const descOverrides: Partial<Record<ExtendParamsType, ReactNode>> = {
+ disableContextCaching: (() => {
+ const original = tChat('extendParams.disableContextCaching.desc', { defaultValue: '' });
+
+ const sanitized = original.replace(/(<\d>.*?<\/\d>)/u, '');
+
+ return (
+ sanitized || (
+ <Trans i18nKey={'extendParams.disableContextCaching.desc'} ns={'chat'}>
+ 单条对话生成成本最高可降低 90%,响应速度提升 4 倍。开启后将自动禁用历史消息数限制
+ </Trans>
+ )
+ );
+ })(),
+ enableReasoning: (() => {
+ const original = tChat('extendParams.enableReasoning.desc', { defaultValue: '' });
+
+ const sanitized = original.replace(/(<\d>.*?<\/\d>)/u, '');
+
+ return (
+ sanitized || (
+ <Trans i18nKey={'extendParams.enableReasoning.desc'} ns={'chat'}>
+ 基于 Claude Thinking 机制限制,开启后将自动禁用历史消息数限制
+ </Trans>
+ )
+ );
+ })(),
+ };
+
+ const previewFallback = String(
+ t('providerModels.item.modelConfig.extendParams.previewFallback', {
+ defaultValue: 'Preview unavailable',
+ }),
+ );
+
+ const definitions = useMemo<ExtendParamsDefinition[]>(() => {
+ return EXTEND_PARAMS_OPTIONS.map((item) => {
+ const descKey = `extendParams.${item.key}.desc`;
+ const rawDesc = tChat(descKey as any, { defaultValue: '' });
+ const normalizedDesc =
+ typeof rawDesc === 'string' && rawDesc !== '' && rawDesc !== descKey ? rawDesc : undefined;
+ const desc = descOverrides[item.key] ?? normalizedDesc;
+ const meta = PREVIEW_META[item.key];
+ // Use alias key for title if available (synced with ControlsForm.tsx)
+ const titleKey = TITLE_KEY_ALIASES[item.key] ?? item.key;
+ const baseLabel = String(
+ tChat(`extendParams.${titleKey}.title` as any, { defaultValue: item.key }),
+ );
+
+ const label = meta?.labelOverride
+ ? meta.labelOverride
+ : meta?.labelSuffix
+ ? `${baseLabel}${meta.labelSuffix}`
+ : baseLabel;
+
+ return {
+ desc,
+ hint: String(t(item.hintKey as any)),
+ key: item.key,
+ label,
+ parameterTag: meta?.tag,
+ preview: previewControls[item.key],
+ previewWidth: meta?.previewWidth,
+ };
+ });
+ }, [previewControls, t, tChat]);
+
+ const definitionMap = useMemo(() => {
+ return new Map(definitions.map((item) => [item.key, item]));
+ }, [definitions]);
+
+ const options = useMemo(
+ () =>
+ definitions.map((item) => ({
+ label: item.label,
+ value: item.key,
+ })),
+ [definitions],
+ );
+
+ const placeholder = String(t('providerModels.item.modelConfig.extendParams.placeholder'));
+ const handleChange = (val: ExtendParamsType[]) => {
+ if (!Array.isArray(val) || val.length === 0) {
+ onChange?.(undefined);
+ return;
+ }
+
+ const filtered = val.filter((item) => definitionMap.has(item));
+ onChange?.(filtered.length ? filtered : undefined);
+ };
+
+ return (
+ <Flexbox gap={8}>
+ <Select
+ allowClear
+ mode={'multiple'}
+ onChange={(val) => handleChange(val as ExtendParamsType[])}
+ optionRender={(option) => {
+ const def = definitionMap.get(option.value as ExtendParamsType);
+ if (!def) return option.label;
+
+ return (
+ <Popover
+ content={
+ <PreviewContent
+ desc={def.desc}
+ hint={def.hint}
+ label={def.label}
+ parameterTag={def.parameterTag}
+ preview={def.preview}
+ previewFallback={previewFallback}
+ previewWidth={def.previewWidth}
+ />
+ }
+ placement={'right'}
+ >
+ <Flexbox gap={4}>
+ <Typography.Text>{def.label}</Typography.Text>
+ <Typography.Text style={{ fontSize: 12 }} type={'secondary'}>
+ {def.hint}
+ </Typography.Text>
+ </Flexbox>
+ </Popover>
+ );
+ }}
+ options={options}
+ placeholder={placeholder}
+ popupMatchSelectWidth={false}
+ style={{ width: '100%' }}
+ value={value}
+ />
+ {value && value.length > 0 && (
+ <Space size={[8, 8]} wrap>
+ {value.map((key) => {
+ const def = definitionMap.get(key);
+ if (!def) return null;
+ return (
+ <Popover
+ content={
+ <PreviewContent
+ desc={def.desc}
+ hint={def.hint}
+ label={def.label}
+ parameterTag={def.parameterTag}
+ preview={def.preview}
+ previewFallback={previewFallback}
+ previewWidth={def.previewWidth}
+ />
+ }
+ key={key}
+ placement={'top'}
+ >
+ <Tag bordered={false} color={'processing'}>
+ {def.label}
+ </Tag>
+ </Popover>
+ );
+ })}
+ </Space>
+ )}
+ </Flexbox>
+ );
+});
+
+export default ExtendParamsSelect;
diff --git a/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/Form.tsx b/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/Form.tsx
index 5b86bed4f0d..b3556d0fa61 100644
--- a/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/Form.tsx
+++ b/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/Form.tsx
@@ -1,5 +1,5 @@
-import { Input , Checkbox } from '@lobehub/ui';
-import { Form, type FormInstance, Select } from 'antd';
+import { Input } from '@lobehub/ui';
+import { Checkbox, Form, type FormInstance, Select } from 'antd';
import { type AiModelType } from 'model-bank';
import { memo, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -8,6 +8,8 @@ import MaxTokenSlider from '@/components/MaxTokenSlider';
import { useIsMobile } from '@/hooks/useIsMobile';
import { type ChatModelCard } from '@/types/llm';
+import ExtendParamsSelect from './ExtendParamsSelect';
+
interface ModelConfigFormProps {
idEditable?: boolean;
initialValues?: ChatModelCard;
@@ -102,6 +104,13 @@ const ModelConfigForm = memo<ModelConfigFormProps>(
>
<MaxTokenSlider />
</Form.Item>
+ <Form.Item
+ extra={t('providerModels.item.modelConfig.extendParams.extra')}
+ label={t('providerModels.item.modelConfig.extendParams.title')}
+ name={['settings', 'extendParams']}
+ >
+ <ExtendParamsSelect />
+ </Form.Item>
<Form.Item
extra={t('providerModels.item.modelConfig.functionCall.extra')}
label={t('providerModels.item.modelConfig.functionCall.title')}
diff --git a/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/__tests__/ExtendParamsSelect.test.tsx b/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/__tests__/ExtendParamsSelect.test.tsx
new file mode 100644
index 00000000000..6426617414d
--- /dev/null
+++ b/src/app/[variants]/(main)/settings/provider/features/ModelList/CreateNewModelModal/__tests__/ExtendParamsSelect.test.tsx
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest';
+
+// Import the constant directly for testing
+// We'll need to test the TITLE_KEY_ALIASES logic
+
+describe('ExtendParamsSelect', () => {
+ describe('TITLE_KEY_ALIASES mapping', () => {
+ // This mapping should be synced with ControlsForm.tsx
+ const TITLE_KEY_ALIASES: Record<string, string> = {
+ gpt5ReasoningEffort: 'reasoningEffort',
+ gpt5_1ReasoningEffort: 'reasoningEffort',
+ gpt5_2ProReasoningEffort: 'reasoningEffort',
+ gpt5_2ReasoningEffort: 'reasoningEffort',
+ thinkingLevel2: 'thinkingLevel',
+ };
+
+ it('should map GPT5 variants to reasoningEffort', () => {
+ expect(TITLE_KEY_ALIASES['gpt5ReasoningEffort']).toBe('reasoningEffort');
+ expect(TITLE_KEY_ALIASES['gpt5_1ReasoningEffort']).toBe('reasoningEffort');
+ expect(TITLE_KEY_ALIASES['gpt5_2ReasoningEffort']).toBe('reasoningEffort');
+ expect(TITLE_KEY_ALIASES['gpt5_2ProReasoningEffort']).toBe('reasoningEffort');
+ });
+
+ it('should map thinkingLevel2 to thinkingLevel', () => {
+ expect(TITLE_KEY_ALIASES['thinkingLevel2']).toBe('thinkingLevel');
+ });
+
+ it('should return undefined for keys without aliases', () => {
+ expect(TITLE_KEY_ALIASES['reasoningEffort']).toBeUndefined();
+ expect(TITLE_KEY_ALIASES['thinkingLevel']).toBeUndefined();
+ expect(TITLE_KEY_ALIASES['thinking']).toBeUndefined();
+ });
+ });
+
+ describe('title key resolution logic', () => {
+ const TITLE_KEY_ALIASES: Record<string, string> = {
+ gpt5ReasoningEffort: 'reasoningEffort',
+ gpt5_1ReasoningEffort: 'reasoningEffort',
+ gpt5_2ProReasoningEffort: 'reasoningEffort',
+ gpt5_2ReasoningEffort: 'reasoningEffort',
+ thinkingLevel2: 'thinkingLevel',
+ };
+
+ const getTitleKey = (key: string): string => {
+ return TITLE_KEY_ALIASES[key] ?? key;
+ };
+
+ it('should return the alias key when available', () => {
+ expect(getTitleKey('gpt5ReasoningEffort')).toBe('reasoningEffort');
+ expect(getTitleKey('thinkingLevel2')).toBe('thinkingLevel');
+ });
+
+ it('should return the original key when no alias exists', () => {
+ expect(getTitleKey('reasoningEffort')).toBe('reasoningEffort');
+ expect(getTitleKey('thinking')).toBe('thinking');
+ expect(getTitleKey('textVerbosity')).toBe('textVerbosity');
+ });
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/Model/ControlsForm.tsx b/src/features/ChatInput/ActionBar/Model/ControlsForm.tsx
index f4b62b01bc5..79a8f50eb85 100644
--- a/src/features/ChatInput/ActionBar/Model/ControlsForm.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ControlsForm.tsx
@@ -178,7 +178,7 @@ const ControlsForm = memo(() => {
},
{
children: <ThinkingBudgetSlider />,
- label: t('extendParams.reasoningBudgetToken.title'),
+ label: t('extendParams.thinkingBudget.title'),
layout: 'vertical',
minWidth: 460,
name: 'thinkingBudget',
diff --git a/src/features/ChatInput/ActionBar/Model/GPT51ReasoningEffortSlider.tsx b/src/features/ChatInput/ActionBar/Model/GPT51ReasoningEffortSlider.tsx
index d193090164e..cb168625700 100644
--- a/src/features/ChatInput/ActionBar/Model/GPT51ReasoningEffortSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/GPT51ReasoningEffortSlider.tsx
@@ -1,60 +1,15 @@
-import { Flexbox } from '@lobehub/ui';
-import { Slider } from 'antd';
-import { memo, useCallback } from 'react';
+import { type CreatedLevelSliderProps, createLevelSliderComponent } from './createLevelSlider';
-import { useAgentStore } from '@/store/agent';
-import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+const GPT51_REASONING_EFFORT_LEVELS = ['none', 'low', 'medium', 'high'] as const;
+type GPT51ReasoningEffort = (typeof GPT51_REASONING_EFFORT_LEVELS)[number];
-import { useAgentId } from '../../hooks/useAgentId';
-import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+export type GPT51ReasoningEffortSliderProps = CreatedLevelSliderProps<GPT51ReasoningEffort>;
-const GPT51ReasoningEffortSlider = memo(() => {
- const agentId = useAgentId();
- const { updateAgentChatConfig } = useUpdateAgentConfig();
- const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
-
- const gpt5_1ReasoningEffort = config.gpt5_1ReasoningEffort || 'none'; // Default to 'none' if not set
-
- const marks = {
- 0: 'none',
- 1: 'low',
- 2: 'medium',
- 3: 'high',
- };
-
- const effortValues = ['none', 'low', 'medium', 'high'];
- const indexValue = effortValues.indexOf(gpt5_1ReasoningEffort);
- const currentValue = indexValue === -1 ? 0 : indexValue;
-
- const updateGPT51ReasoningEffort = useCallback(
- (value: number) => {
- const effort = effortValues[value] as 'none' | 'low' | 'medium' | 'high';
- updateAgentChatConfig({ gpt5_1ReasoningEffort: effort });
- },
- [updateAgentChatConfig],
- );
-
- return (
- <Flexbox
- align={'center'}
- gap={12}
- horizontal
- paddingInline={'0 20px'}
- style={{ minWidth: 200, width: '100%' }}
- >
- <Flexbox flex={1}>
- <Slider
- marks={marks}
- max={3}
- min={0}
- onChange={updateGPT51ReasoningEffort}
- step={1}
- tooltip={{ open: false }}
- value={currentValue}
- />
- </Flexbox>
- </Flexbox>
- );
+const GPT51ReasoningEffortSlider = createLevelSliderComponent<GPT51ReasoningEffort>({
+ configKey: 'gpt5_1ReasoningEffort',
+ defaultValue: 'none',
+ levels: GPT51_REASONING_EFFORT_LEVELS,
+ style: { minWidth: 200 },
});
export default GPT51ReasoningEffortSlider;
diff --git a/src/features/ChatInput/ActionBar/Model/GPT52ProReasoningEffortSlider.tsx b/src/features/ChatInput/ActionBar/Model/GPT52ProReasoningEffortSlider.tsx
index 89772e8b92d..7ae87cf2f53 100644
--- a/src/features/ChatInput/ActionBar/Model/GPT52ProReasoningEffortSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/GPT52ProReasoningEffortSlider.tsx
@@ -1,59 +1,15 @@
-import { Flexbox } from '@lobehub/ui';
-import { Slider } from 'antd';
-import { memo, useCallback } from 'react';
+import { type CreatedLevelSliderProps, createLevelSliderComponent } from './createLevelSlider';
-import { useAgentStore } from '@/store/agent';
-import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+const GPT52_PRO_REASONING_EFFORT_LEVELS = ['medium', 'high', 'xhigh'] as const;
+type GPT52ProReasoningEffort = (typeof GPT52_PRO_REASONING_EFFORT_LEVELS)[number];
-import { useAgentId } from '../../hooks/useAgentId';
-import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+export type GPT52ProReasoningEffortSliderProps = CreatedLevelSliderProps<GPT52ProReasoningEffort>;
-const GPT52ProReasoningEffortSlider = memo(() => {
- const agentId = useAgentId();
- const { updateAgentChatConfig } = useUpdateAgentConfig();
- const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
-
- const gpt5_2ProReasoningEffort = config.gpt5_2ProReasoningEffort || 'medium';
-
- const marks = {
- 0: 'medium',
- 1: 'high',
- 2: 'xhigh',
- };
-
- const effortValues = ['medium', 'high', 'xhigh'];
- const indexValue = effortValues.indexOf(gpt5_2ProReasoningEffort);
- const currentValue = indexValue === -1 ? 0 : indexValue;
-
- const updateGPT52ProReasoningEffort = useCallback(
- (value: number) => {
- const effort = effortValues[value] as 'medium' | 'high' | 'xhigh';
- updateAgentChatConfig({ gpt5_2ProReasoningEffort: effort });
- },
- [updateAgentChatConfig],
- );
-
- return (
- <Flexbox
- align={'center'}
- gap={12}
- horizontal
- paddingInline={'0 20px'}
- style={{ minWidth: 160, width: '100%' }}
- >
- <Flexbox flex={1}>
- <Slider
- marks={marks}
- max={2}
- min={0}
- onChange={updateGPT52ProReasoningEffort}
- step={1}
- tooltip={{ open: false }}
- value={currentValue}
- />
- </Flexbox>
- </Flexbox>
- );
+const GPT52ProReasoningEffortSlider = createLevelSliderComponent<GPT52ProReasoningEffort>({
+ configKey: 'gpt5_2ProReasoningEffort',
+ defaultValue: 'medium',
+ levels: GPT52_PRO_REASONING_EFFORT_LEVELS,
+ style: { minWidth: 160 },
});
export default GPT52ProReasoningEffortSlider;
diff --git a/src/features/ChatInput/ActionBar/Model/GPT52ReasoningEffortSlider.tsx b/src/features/ChatInput/ActionBar/Model/GPT52ReasoningEffortSlider.tsx
index 0240b057189..da63c5862ab 100644
--- a/src/features/ChatInput/ActionBar/Model/GPT52ReasoningEffortSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/GPT52ReasoningEffortSlider.tsx
@@ -1,61 +1,15 @@
-import { Flexbox } from '@lobehub/ui';
-import { Slider } from 'antd';
-import { memo, useCallback } from 'react';
+import { type CreatedLevelSliderProps, createLevelSliderComponent } from './createLevelSlider';
-import { useAgentStore } from '@/store/agent';
-import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+const GPT52_REASONING_EFFORT_LEVELS = ['none', 'low', 'medium', 'high', 'xhigh'] as const;
+type GPT52ReasoningEffort = (typeof GPT52_REASONING_EFFORT_LEVELS)[number];
-import { useAgentId } from '../../hooks/useAgentId';
-import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+export type GPT52ReasoningEffortSliderProps = CreatedLevelSliderProps<GPT52ReasoningEffort>;
-const GPT52ReasoningEffortSlider = memo(() => {
- const agentId = useAgentId();
- const { updateAgentChatConfig } = useUpdateAgentConfig();
- const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
-
- const gpt5_2ReasoningEffort = config.gpt5_2ReasoningEffort || 'none';
-
- const marks = {
- 0: 'none',
- 1: 'low',
- 2: 'medium',
- 3: 'high',
- 4: 'xhigh',
- };
-
- const effortValues = ['none', 'low', 'medium', 'high', 'xhigh'];
- const indexValue = effortValues.indexOf(gpt5_2ReasoningEffort);
- const currentValue = indexValue === -1 ? 0 : indexValue;
-
- const updateGPT52ReasoningEffort = useCallback(
- (value: number) => {
- const effort = effortValues[value] as 'none' | 'low' | 'medium' | 'high' | 'xhigh';
- updateAgentChatConfig({ gpt5_2ReasoningEffort: effort });
- },
- [updateAgentChatConfig],
- );
-
- return (
- <Flexbox
- align={'center'}
- gap={12}
- horizontal
- paddingInline={'0 20px'}
- style={{ minWidth: 230, width: '100%' }}
- >
- <Flexbox flex={1}>
- <Slider
- marks={marks}
- max={4}
- min={0}
- onChange={updateGPT52ReasoningEffort}
- step={1}
- tooltip={{ open: false }}
- value={currentValue}
- />
- </Flexbox>
- </Flexbox>
- );
+const GPT52ReasoningEffortSlider = createLevelSliderComponent<GPT52ReasoningEffort>({
+ configKey: 'gpt5_2ReasoningEffort',
+ defaultValue: 'none',
+ levels: GPT52_REASONING_EFFORT_LEVELS,
+ style: { minWidth: 230 },
});
export default GPT52ReasoningEffortSlider;
diff --git a/src/features/ChatInput/ActionBar/Model/GPT5ReasoningEffortSlider.tsx b/src/features/ChatInput/ActionBar/Model/GPT5ReasoningEffortSlider.tsx
index 95b86684b7c..481561a2f06 100644
--- a/src/features/ChatInput/ActionBar/Model/GPT5ReasoningEffortSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/GPT5ReasoningEffortSlider.tsx
@@ -1,60 +1,15 @@
-import { Flexbox } from '@lobehub/ui';
-import { Slider } from 'antd';
-import { memo, useCallback } from 'react';
+import { type CreatedLevelSliderProps, createLevelSliderComponent } from './createLevelSlider';
-import { useAgentStore } from '@/store/agent';
-import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+const GPT5_REASONING_EFFORT_LEVELS = ['minimal', 'low', 'medium', 'high'] as const;
+type GPT5ReasoningEffort = (typeof GPT5_REASONING_EFFORT_LEVELS)[number];
-import { useAgentId } from '../../hooks/useAgentId';
-import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+export type GPT5ReasoningEffortSliderProps = CreatedLevelSliderProps<GPT5ReasoningEffort>;
-const GPT5ReasoningEffortSlider = memo(() => {
- const agentId = useAgentId();
- const { updateAgentChatConfig } = useUpdateAgentConfig();
- const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
-
- const gpt5ReasoningEffort = config.gpt5ReasoningEffort || 'medium'; // Default to 'medium' if not set
-
- const marks = {
- 0: 'minimal',
- 1: 'low',
- 2: 'medium',
- 3: 'high',
- };
-
- const effortValues = ['minimal', 'low', 'medium', 'high'];
- const indexValue = effortValues.indexOf(gpt5ReasoningEffort);
- const currentValue = indexValue === -1 ? 2 : indexValue;
-
- const updateGPT5ReasoningEffort = useCallback(
- (value: number) => {
- const effort = effortValues[value] as 'minimal' | 'low' | 'medium' | 'high';
- updateAgentChatConfig({ gpt5ReasoningEffort: effort });
- },
- [updateAgentChatConfig],
- );
-
- return (
- <Flexbox
- align={'center'}
- gap={12}
- horizontal
- paddingInline={'0 20px'}
- style={{ minWidth: 200, width: '100%' }}
- >
- <Flexbox flex={1}>
- <Slider
- marks={marks}
- max={3}
- min={0}
- onChange={updateGPT5ReasoningEffort}
- step={1}
- tooltip={{ open: false }}
- value={currentValue}
- />
- </Flexbox>
- </Flexbox>
- );
+const GPT5ReasoningEffortSlider = createLevelSliderComponent<GPT5ReasoningEffort>({
+ configKey: 'gpt5ReasoningEffort',
+ defaultValue: 'medium',
+ levels: GPT5_REASONING_EFFORT_LEVELS,
+ style: { minWidth: 200 },
});
export default GPT5ReasoningEffortSlider;
diff --git a/src/features/ChatInput/ActionBar/Model/ImageAspectRatioSelect.tsx b/src/features/ChatInput/ActionBar/Model/ImageAspectRatioSelect.tsx
index 69f65fe7881..5b7cf364632 100644
--- a/src/features/ChatInput/ActionBar/Model/ImageAspectRatioSelect.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ImageAspectRatioSelect.tsx
@@ -1,5 +1,5 @@
import { Select } from 'antd';
-import { memo, useCallback, useMemo } from 'react';
+import { memo, useMemo } from 'react';
import { useAgentStore } from '@/store/agent';
import { chatConfigByIdSelectors } from '@/store/agent/selectors';
@@ -18,15 +18,21 @@ const NANO_BANANA_ASPECT_RATIOS = [
'9:16', // 768x1376 / 1536x2752 / 3072x5504
'16:9', // 1376x768 / 2752x1536 / 5504x3072
'21:9', // 1584x672 / 3168x1344 / 6336x2688
-];
+] as const;
-const ImageAspectRatioSelect = memo(() => {
- const agentId = useAgentId();
- const { updateAgentChatConfig } = useUpdateAgentConfig();
- const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
+type AspectRatio = (typeof NANO_BANANA_ASPECT_RATIOS)[number];
- const imageAspectRatio = config.imageAspectRatio || '1:1';
+export interface ImageAspectRatioSelectProps {
+ defaultValue?: AspectRatio;
+ onChange?: (value: AspectRatio) => void;
+ value?: AspectRatio;
+}
+// Inner pure UI component - no store hooks, safe for preview
+const ImageAspectRatioSelectInner = memo<{
+ onChange: (_value: AspectRatio) => void;
+ value: AspectRatio;
+}>(({ value, onChange }) => {
const options = useMemo(
() =>
NANO_BANANA_ASPECT_RATIOS.map((ratio) => ({
@@ -36,21 +42,49 @@ const ImageAspectRatioSelect = memo(() => {
[],
);
- const updateAspectRatio = useCallback(
- (value: string) => {
- updateAgentChatConfig({ imageAspectRatio: value });
- },
- [updateAgentChatConfig],
- );
-
return (
<Select
- onChange={updateAspectRatio}
+ onChange={(v: string) => onChange(v as AspectRatio)}
options={options}
style={{ height: 32, marginRight: 10, width: 75 }}
- value={imageAspectRatio}
+ value={value}
/>
);
});
+// Store-connected component - uses agent store hooks
+const ImageAspectRatioSelectWithStore = memo<{ defaultValue: AspectRatio }>(({ defaultValue }) => {
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
+
+ const storeValue = (config.imageAspectRatio as AspectRatio) || defaultValue;
+
+ const handleChange = (ratio: AspectRatio) => {
+ updateAgentChatConfig({ imageAspectRatio: ratio });
+ };
+
+ return <ImageAspectRatioSelectInner onChange={handleChange} value={storeValue} />;
+});
+
+// Main exported component - chooses between controlled and store mode
+const ImageAspectRatioSelect = memo<ImageAspectRatioSelectProps>(
+ ({ value: controlledValue, onChange: controlledOnChange, defaultValue = '1:1' }) => {
+ const isControlled = controlledValue !== undefined || controlledOnChange !== undefined;
+
+ if (isControlled) {
+ // Controlled mode: use props only, no store access
+ return (
+ <ImageAspectRatioSelectInner
+ onChange={controlledOnChange ?? (() => {})}
+ value={controlledValue ?? defaultValue}
+ />
+ );
+ }
+
+ // Uncontrolled mode: use store
+ return <ImageAspectRatioSelectWithStore defaultValue={defaultValue} />;
+ },
+);
+
export default ImageAspectRatioSelect;
diff --git a/src/features/ChatInput/ActionBar/Model/ImageResolutionSlider.tsx b/src/features/ChatInput/ActionBar/Model/ImageResolutionSlider.tsx
index e7a290b41b0..d4cd9c108f0 100644
--- a/src/features/ChatInput/ActionBar/Model/ImageResolutionSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ImageResolutionSlider.tsx
@@ -1,61 +1,15 @@
-import { Flexbox } from '@lobehub/ui';
-import { Slider } from 'antd';
-import { memo, useCallback } from 'react';
-
-import { useAgentStore } from '@/store/agent';
-import { chatConfigByIdSelectors } from '@/store/agent/selectors';
-
-import { useAgentId } from '../../hooks/useAgentId';
-import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+import { type CreatedLevelSliderProps, createLevelSliderComponent } from './createLevelSlider';
const IMAGE_RESOLUTIONS = ['1K', '2K', '4K'] as const;
type ImageResolution = (typeof IMAGE_RESOLUTIONS)[number];
-const ImageResolutionSlider = memo(() => {
- const agentId = useAgentId();
- const { updateAgentChatConfig } = useUpdateAgentConfig();
- const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
-
- const imageResolution = (config.imageResolution as ImageResolution) || '1K';
-
- const marks = {
- 0: '1K',
- 1: '2K',
- 2: '4K',
- };
-
- const indexValue = IMAGE_RESOLUTIONS.indexOf(imageResolution);
- const currentValue = indexValue === -1 ? 0 : indexValue;
-
- const updateResolution = useCallback(
- (value: number) => {
- const resolution = IMAGE_RESOLUTIONS[value];
- updateAgentChatConfig({ imageResolution: resolution });
- },
- [updateAgentChatConfig],
- );
+export type ImageResolutionSliderProps = CreatedLevelSliderProps<ImageResolution>;
- return (
- <Flexbox
- align={'center'}
- gap={12}
- horizontal
- paddingInline={'0 20px'}
- style={{ minWidth: 150, width: '100%' }}
- >
- <Flexbox flex={1}>
- <Slider
- marks={marks}
- max={2}
- min={0}
- onChange={updateResolution}
- step={1}
- tooltip={{ open: false }}
- value={currentValue}
- />
- </Flexbox>
- </Flexbox>
- );
+const ImageResolutionSlider = createLevelSliderComponent<ImageResolution>({
+ configKey: 'imageResolution',
+ defaultValue: '1K',
+ levels: IMAGE_RESOLUTIONS,
+ style: { minWidth: 150 },
});
export default ImageResolutionSlider;
diff --git a/src/features/ChatInput/ActionBar/Model/LevelSlider.tsx b/src/features/ChatInput/ActionBar/Model/LevelSlider.tsx
new file mode 100644
index 00000000000..69bd53ece31
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Model/LevelSlider.tsx
@@ -0,0 +1,92 @@
+import { Flexbox } from '@lobehub/ui';
+import { Slider } from 'antd';
+import { type SliderSingleProps } from 'antd/es/slider';
+import { type CSSProperties, memo, useMemo } from 'react';
+import useMergeState from 'use-merge-value';
+
+export interface LevelSliderProps<T extends string = string> {
+ /**
+ * Default value when uncontrolled
+ */
+ defaultValue?: T;
+ /**
+ * Ordered array of level values (left to right on slider)
+ */
+ levels: readonly T[];
+ /**
+ * Optional custom marks. If not provided, uses level values as marks.
+ */
+ marks?: SliderSingleProps['marks'];
+ /**
+ * Callback when value changes
+ */
+ onChange?: (value: T) => void;
+ /**
+ * Style for the slider container
+ */
+ style?: CSSProperties;
+ /**
+ * Controlled value
+ */
+ value?: T;
+}
+
+function LevelSlider<T extends string = string>({
+ levels,
+ value,
+ defaultValue,
+ onChange,
+ marks: customMarks,
+ style,
+}: LevelSliderProps<T>) {
+ const defaultLevel = defaultValue ?? levels[Math.floor(levels.length / 2)];
+
+ const [currentLevel, setCurrentLevel] = useMergeState<T>(defaultLevel, {
+ defaultValue,
+ onChange,
+ value,
+ });
+
+ const marks = useMemo(() => {
+ if (customMarks) return customMarks;
+ const result: SliderSingleProps['marks'] = {};
+ levels.forEach((level, index) => {
+ result[index] = level;
+ });
+ return result;
+ }, [customMarks, levels]);
+
+ const currentIndex = levels.indexOf(currentLevel);
+ const sliderValue = currentIndex === -1 ? Math.floor(levels.length / 2) : currentIndex;
+
+ const handleChange = (index: number) => {
+ const newLevel = levels[index];
+ if (newLevel !== undefined) {
+ setCurrentLevel(newLevel);
+ }
+ };
+
+ return (
+ <Flexbox
+ align={'center'}
+ gap={12}
+ horizontal
+ paddingInline={'0 20px'}
+ style={{ minWidth: 200, width: '100%', ...style }}
+ >
+ <Flexbox flex={1}>
+ <Slider
+ marks={marks}
+ max={levels.length - 1}
+ min={0}
+ onChange={handleChange}
+ step={1}
+ tooltip={{ open: false }}
+ value={sliderValue}
+ />
+ </Flexbox>
+ </Flexbox>
+ );
+}
+
+export default memo(LevelSlider) as typeof LevelSlider;
diff --git a/src/features/ChatInput/ActionBar/Model/ReasoningEffortSlider.tsx b/src/features/ChatInput/ActionBar/Model/ReasoningEffortSlider.tsx
index 1b8a7297cbd..bc7437161b3 100644
--- a/src/features/ChatInput/ActionBar/Model/ReasoningEffortSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ReasoningEffortSlider.tsx
@@ -1,59 +1,15 @@
-import { Flexbox } from '@lobehub/ui';
-import { Slider } from 'antd';
-import { memo, useCallback } from 'react';
+import { type CreatedLevelSliderProps, createLevelSliderComponent } from './createLevelSlider';
-import { useAgentStore } from '@/store/agent';
-import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+const REASONING_EFFORT_LEVELS = ['low', 'medium', 'high'] as const;
+type ReasoningEffort = (typeof REASONING_EFFORT_LEVELS)[number];
-import { useAgentId } from '../../hooks/useAgentId';
-import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+export type ReasoningEffortSliderProps = CreatedLevelSliderProps<ReasoningEffort>;
-const ReasoningEffortSlider = memo(() => {
- const agentId = useAgentId();
- const { updateAgentChatConfig } = useUpdateAgentConfig();
- const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
-
- const reasoningEffort = config.reasoningEffort || 'medium'; // Default to 'medium' if not set
-
- const marks = {
- 0: 'low',
- 1: 'medium',
- 2: 'high',
- };
-
- const effortValues = ['low', 'medium', 'high'];
- const indexValue = effortValues.indexOf(reasoningEffort);
- const currentValue = indexValue === -1 ? 1 : indexValue;
-
- const updateReasoningEffort = useCallback(
- (value: number) => {
- const effort = effortValues[value] as 'low' | 'medium' | 'high';
- updateAgentChatConfig({ reasoningEffort: effort });
- },
- [updateAgentChatConfig],
- );
-
- return (
- <Flexbox
- align={'center'}
- gap={12}
- horizontal
- paddingInline={'0 20px'}
- style={{ minWidth: 200, width: '100%' }}
- >
- <Flexbox flex={1}>
- <Slider
- marks={marks}
- max={2}
- min={0}
- onChange={updateReasoningEffort}
- step={1}
- tooltip={{ open: false }}
- value={currentValue}
- />
- </Flexbox>
- </Flexbox>
- );
+const ReasoningEffortSlider = createLevelSliderComponent<ReasoningEffort>({
+ configKey: 'reasoningEffort',
+ defaultValue: 'medium',
+ levels: REASONING_EFFORT_LEVELS,
+ style: { minWidth: 200 },
});
export default ReasoningEffortSlider;
diff --git a/src/features/ChatInput/ActionBar/Model/TextVerbositySlider.tsx b/src/features/ChatInput/ActionBar/Model/TextVerbositySlider.tsx
index d76430e0459..db65589d928 100644
--- a/src/features/ChatInput/ActionBar/Model/TextVerbositySlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/TextVerbositySlider.tsx
@@ -1,59 +1,15 @@
-import { Flexbox } from '@lobehub/ui';
-import { Slider } from 'antd';
-import { memo, useCallback } from 'react';
+import { type CreatedLevelSliderProps, createLevelSliderComponent } from './createLevelSlider';
-import { useAgentStore } from '@/store/agent';
-import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+const TEXT_VERBOSITY_LEVELS = ['low', 'medium', 'high'] as const;
+type TextVerbosity = (typeof TEXT_VERBOSITY_LEVELS)[number];
-import { useAgentId } from '../../hooks/useAgentId';
-import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+export type TextVerbositySliderProps = CreatedLevelSliderProps<TextVerbosity>;
-const TextVerbositySlider = memo(() => {
- const agentId = useAgentId();
- const { updateAgentChatConfig } = useUpdateAgentConfig();
- const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
-
- const textVerbosity = config.textVerbosity || 'medium'; // Default to 'medium' if not set
-
- const marks = {
- 0: 'low',
- 1: 'medium',
- 2: 'high',
- };
-
- const verbosityValues = ['low', 'medium', 'high'];
- const indexValue = verbosityValues.indexOf(textVerbosity);
- const currentValue = indexValue === -1 ? 1 : indexValue;
-
- const updateTextVerbosity = useCallback(
- (value: number) => {
- const verbosity = verbosityValues[value] as 'low' | 'medium' | 'high';
- updateAgentChatConfig({ textVerbosity: verbosity });
- },
- [updateAgentChatConfig],
- );
-
- return (
- <Flexbox
- align={'center'}
- gap={12}
- horizontal
- paddingInline={'0 20px'}
- style={{ minWidth: 160, width: '100%' }}
- >
- <Flexbox flex={1}>
- <Slider
- marks={marks}
- max={2}
- min={0}
- onChange={updateTextVerbosity}
- step={1}
- tooltip={{ open: false }}
- value={currentValue}
- />
- </Flexbox>
- </Flexbox>
- );
+const TextVerbositySlider = createLevelSliderComponent<TextVerbosity>({
+ configKey: 'textVerbosity',
+ defaultValue: 'medium',
+ levels: TEXT_VERBOSITY_LEVELS,
+ style: { minWidth: 160 },
});
export default TextVerbositySlider;
diff --git a/src/features/ChatInput/ActionBar/Model/ThinkingLevel2Slider.tsx b/src/features/ChatInput/ActionBar/Model/ThinkingLevel2Slider.tsx
index 8cb4ffebe4a..5315e225de8 100644
--- a/src/features/ChatInput/ActionBar/Model/ThinkingLevel2Slider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ThinkingLevel2Slider.tsx
@@ -1,58 +1,15 @@
-import { Flexbox } from '@lobehub/ui';
-import { Slider } from 'antd';
-import { memo, useCallback } from 'react';
+import { type CreatedLevelSliderProps, createLevelSliderComponent } from './createLevelSlider';
-import { useAgentStore } from '@/store/agent';
-import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+const THINKING_LEVELS_2 = ['low', 'high'] as const;
+type ThinkingLevel2 = (typeof THINKING_LEVELS_2)[number];
-import { useAgentId } from '../../hooks/useAgentId';
-import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+export type ThinkingLevel2SliderProps = CreatedLevelSliderProps<ThinkingLevel2>;
-const ThinkingLevel2Slider = memo(() => {
- const agentId = useAgentId();
- const { updateAgentChatConfig } = useUpdateAgentConfig();
- const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
-
- const thinkingLevel = config.thinkingLevel || 'high'; // Default to 'high' if not set
-
- const marks = {
- 0: 'low',
- 1: 'high',
- };
-
- const levelValues = ['low', 'high'];
- const indexValue = levelValues.indexOf(thinkingLevel as any);
- const currentValue = indexValue === -1 ? 1 : indexValue;
-
- const updateThinkingLevel = useCallback(
- (value: number) => {
- const level = levelValues[value] as 'low' | 'high';
- updateAgentChatConfig({ thinkingLevel: level });
- },
- [updateAgentChatConfig],
- );
-
- return (
- <Flexbox
- align={'center'}
- gap={12}
- horizontal
- paddingInline={'0 20px'}
- style={{ minWidth: 110, width: '100%' }}
- >
- <Flexbox flex={1}>
- <Slider
- marks={marks}
- max={1}
- min={0}
- onChange={updateThinkingLevel}
- step={1}
- tooltip={{ open: false }}
- value={currentValue}
- />
- </Flexbox>
- </Flexbox>
- );
+const ThinkingLevel2Slider = createLevelSliderComponent<ThinkingLevel2>({
+ configKey: 'thinkingLevel',
+ defaultValue: 'high',
+ levels: THINKING_LEVELS_2,
+ style: { minWidth: 110 },
});
export default ThinkingLevel2Slider;
diff --git a/src/features/ChatInput/ActionBar/Model/ThinkingLevelSlider.tsx b/src/features/ChatInput/ActionBar/Model/ThinkingLevelSlider.tsx
index 67b9d89c6d9..53c3b959f7b 100644
--- a/src/features/ChatInput/ActionBar/Model/ThinkingLevelSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ThinkingLevelSlider.tsx
@@ -1,60 +1,15 @@
-import { Flexbox } from '@lobehub/ui';
-import { Slider } from 'antd';
-import { memo, useCallback } from 'react';
+import { type CreatedLevelSliderProps, createLevelSliderComponent } from './createLevelSlider';
-import { useAgentStore } from '@/store/agent';
-import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+const THINKING_LEVELS = ['minimal', 'low', 'medium', 'high'] as const;
+type ThinkingLevel = (typeof THINKING_LEVELS)[number];
-import { useAgentId } from '../../hooks/useAgentId';
-import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+export type ThinkingLevelSliderProps = CreatedLevelSliderProps<ThinkingLevel>;
-const ThinkingLevelSlider = memo(() => {
- const agentId = useAgentId();
- const { updateAgentChatConfig } = useUpdateAgentConfig();
- const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
-
- const thinkingLevel = config.thinkingLevel || 'high'; // Default to 'high' if not set
-
- const marks = {
- 0: 'minimal',
- 1: 'low',
- 2: 'medium',
- 3: 'high',
- };
-
- const levelValues = ['minimal', 'low', 'medium', 'high'];
- const indexValue = levelValues.indexOf(thinkingLevel as any);
- const currentValue = indexValue === -1 ? 3 : indexValue;
-
- const updateThinkingLevel = useCallback(
- (value: number) => {
- const level = levelValues[value] as 'minimal' | 'low' | 'medium' | 'high';
- updateAgentChatConfig({ thinkingLevel: level });
- },
- [updateAgentChatConfig],
- );
-
- return (
- <Flexbox
- align={'center'}
- gap={12}
- horizontal
- paddingInline={'0 20px'}
- style={{ minWidth: 200, width: '100%' }}
- >
- <Flexbox flex={1}>
- <Slider
- marks={marks}
- max={3}
- min={0}
- onChange={updateThinkingLevel}
- step={1}
- tooltip={{ open: false }}
- value={currentValue}
- />
- </Flexbox>
- </Flexbox>
- );
+const ThinkingLevelSlider = createLevelSliderComponent<ThinkingLevel>({
+ configKey: 'thinkingLevel',
+ defaultValue: 'high',
+ levels: THINKING_LEVELS,
+ style: { minWidth: 200 },
});
export default ThinkingLevelSlider;
diff --git a/src/features/ChatInput/ActionBar/Model/ThinkingSlider.tsx b/src/features/ChatInput/ActionBar/Model/ThinkingSlider.tsx
index f79907a206a..74743d8e769 100644
--- a/src/features/ChatInput/ActionBar/Model/ThinkingSlider.tsx
+++ b/src/features/ChatInput/ActionBar/Model/ThinkingSlider.tsx
@@ -1,59 +1,23 @@
-import { Flexbox } from '@lobehub/ui';
-import { Slider } from 'antd';
-import { memo, useCallback } from 'react';
-
-import { useAgentStore } from '@/store/agent';
-import { chatConfigByIdSelectors } from '@/store/agent/selectors';
-
-import { useAgentId } from '../../hooks/useAgentId';
-import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
-
-const ThinkingSlider = memo(() => {
- const agentId = useAgentId();
- const { updateAgentChatConfig } = useUpdateAgentConfig();
- const config = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
-
- const thinking = config.thinking || 'auto'; // Default to 'auto' if not set
-
- const marks = {
- 0: 'OFF',
- 1: 'Auto',
- 2: 'ON',
- };
-
- const thinkingValues = ['disabled', 'auto', 'enabled'];
- const indexValue = thinkingValues.indexOf(thinking);
- const currentValue = indexValue === -1 ? 1 : indexValue;
-
- const updateThinking = useCallback(
- (value: number) => {
- const thinkingMode = thinkingValues[value] as 'disabled' | 'auto' | 'enabled';
- updateAgentChatConfig({ thinking: thinkingMode });
- },
- [updateAgentChatConfig],
- );
-
- return (
- <Flexbox
- align={'center'}
- gap={12}
- horizontal
- paddingInline={'0 20px'}
- style={{ minWidth: 200, width: '100%' }}
- >
- <Flexbox flex={1}>
- <Slider
- marks={marks}
- max={2}
- min={0}
- onChange={updateThinking}
- step={1}
- tooltip={{ open: false }}
- value={currentValue}
- />
- </Flexbox>
- </Flexbox>
- );
+import { type CreatedLevelSliderProps, createLevelSliderComponent } from './createLevelSlider';
+
+const THINKING_MODES = ['disabled', 'auto', 'enabled'] as const;
+type ThinkingMode = (typeof THINKING_MODES)[number];
+
+// Display marks for the slider
+const THINKING_MARKS = {
+ 0: 'OFF',
+ 1: 'Auto',
+ 2: 'ON',
+};
+
+export type ThinkingSliderProps = CreatedLevelSliderProps<ThinkingMode>;
+
+const ThinkingSlider = createLevelSliderComponent<ThinkingMode>({
+ configKey: 'thinking',
+ defaultValue: 'auto',
+ levels: THINKING_MODES,
+ marks: THINKING_MARKS,
+ style: { minWidth: 200 },
});
export default ThinkingSlider;
diff --git a/src/features/ChatInput/ActionBar/Model/__tests__/createLevelSlider.test.tsx b/src/features/ChatInput/ActionBar/Model/__tests__/createLevelSlider.test.tsx
new file mode 100644
index 00000000000..85b92cebde1
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Model/__tests__/createLevelSlider.test.tsx
@@ -0,0 +1,126 @@
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createLevelSliderComponent } from '../createLevelSlider';
+
+// Mock the store hooks - they should NOT be called in controlled mode
+vi.mock('@/store/agent', () => ({
+ useAgentStore: vi.fn(() => {
+ throw new Error('useAgentStore should not be called in controlled mode');
+ }),
+}));
+
+vi.mock('../../../hooks/useAgentId', () => ({
+ useAgentId: vi.fn(() => {
+ throw new Error('useAgentId should not be called in controlled mode');
+ }),
+}));
+
+vi.mock('../../../hooks/useUpdateAgentConfig', () => ({
+ useUpdateAgentConfig: vi.fn(() => {
+ throw new Error('useUpdateAgentConfig should not be called in controlled mode');
+ }),
+}));
+
+const TEST_LEVELS = ['low', 'medium', 'high'] as const;
+type TestLevel = (typeof TEST_LEVELS)[number];
+
+describe('createLevelSliderComponent', () => {
+ describe('controlled mode (with value prop)', () => {
+ it('should NOT call store hooks when value prop is provided', () => {
+ const TestSlider = createLevelSliderComponent<TestLevel>({
+ configKey: 'reasoningEffort',
+ defaultValue: 'medium',
+ levels: TEST_LEVELS,
+ });
+
+ // This should NOT throw - if it throws, it means store hooks were called
+ expect(() => {
+ render(<TestSlider value="high" />);
+ }).not.toThrow();
+ });
+
+ it('should NOT call store hooks when onChange prop is provided', () => {
+ const TestSlider = createLevelSliderComponent<TestLevel>({
+ configKey: 'reasoningEffort',
+ defaultValue: 'medium',
+ levels: TEST_LEVELS,
+ });
+
+ const mockOnChange = vi.fn();
+
+ // This should NOT throw - if it throws, it means store hooks were called
+ expect(() => {
+ render(<TestSlider onChange={mockOnChange} />);
+ }).not.toThrow();
+ });
+
+ it('should render with the controlled value', () => {
+ const TestSlider = createLevelSliderComponent<TestLevel>({
+ configKey: 'reasoningEffort',
+ defaultValue: 'medium',
+ levels: TEST_LEVELS,
+ });
+
+ render(<TestSlider value="high" />);
+
+ // The slider should show the marks
+ expect(screen.getByText('low')).toBeInTheDocument();
+ expect(screen.getByText('medium')).toBeInTheDocument();
+ expect(screen.getByText('high')).toBeInTheDocument();
+ });
+
+ it('should use defaultValue when value is not provided but onChange is', () => {
+ const TestSlider = createLevelSliderComponent<TestLevel>({
+ configKey: 'reasoningEffort',
+ defaultValue: 'medium',
+ levels: TEST_LEVELS,
+ });
+
+ const mockOnChange = vi.fn();
+
+ // Should not throw and should render
+ expect(() => {
+ render(<TestSlider onChange={mockOnChange} />);
+ }).not.toThrow();
+ });
+ });
+
+ describe('factory configuration', () => {
+ it('should create slider with custom marks', () => {
+ const customMarks = {
+ 0: 'OFF',
+ 1: 'Auto',
+ 2: 'ON',
+ };
+
+ const TestSlider = createLevelSliderComponent<TestLevel>({
+ configKey: 'thinking',
+ defaultValue: 'medium',
+ levels: TEST_LEVELS,
+ marks: customMarks,
+ });
+
+ render(<TestSlider value="medium" />);
+
+ expect(screen.getByText('OFF')).toBeInTheDocument();
+ expect(screen.getByText('Auto')).toBeInTheDocument();
+ expect(screen.getByText('ON')).toBeInTheDocument();
+ });
+
+ it('should apply custom style', () => {
+ const TestSlider = createLevelSliderComponent<TestLevel>({
+ configKey: 'reasoningEffort',
+ defaultValue: 'medium',
+ levels: TEST_LEVELS,
+ style: { minWidth: 300 },
+ });
+
+ const { container } = render(<TestSlider value="medium" />);
+
+ // The outer Flexbox should have the custom style merged
+ const flexbox = container.firstChild as HTMLElement;
+ expect(flexbox).toHaveStyle({ minWidth: '300px' });
+ });
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/Model/createLevelSlider.tsx b/src/features/ChatInput/ActionBar/Model/createLevelSlider.tsx
new file mode 100644
index 00000000000..80252710d24
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Model/createLevelSlider.tsx
@@ -0,0 +1,105 @@
+'use client';
+
+import { type LobeAgentChatConfig } from '@lobechat/types';
+import { type SliderSingleProps } from 'antd/es/slider';
+import { type CSSProperties, memo } from 'react';
+
+import { useAgentStore } from '@/store/agent';
+import { chatConfigByIdSelectors } from '@/store/agent/selectors';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+import LevelSlider from './LevelSlider';
+
+export interface LevelSliderConfig<T extends string> {
+ /**
+ * The key in LobeAgentChatConfig to read/write
+ */
+ configKey: keyof LobeAgentChatConfig;
+ /**
+ * Default value when no value is provided
+ */
+ defaultValue: T;
+ /**
+ * Ordered array of level values (left to right on slider)
+ */
+ levels: readonly T[];
+ /**
+ * Optional custom marks for the slider
+ */
+ marks?: SliderSingleProps['marks'];
+ /**
+ * Optional style for the slider container
+ */
+ style?: CSSProperties;
+}
+
+export interface CreatedLevelSliderProps<T extends string> {
+ defaultValue?: T;
+ onChange?: (value: T) => void;
+ value?: T;
+}
+
+/**
+ * Factory function to create a level slider component that supports both
+ * controlled mode (for previews without store access) and uncontrolled mode
+ * (reading/writing to agent store).
+ */
+export function createLevelSliderComponent<T extends string>(config: LevelSliderConfig<T>) {
+ const { levels, configKey, defaultValue, marks, style } = config;
+
+ // Inner pure UI component - no store hooks, safe for preview
+ const LevelSliderInner = memo<{
+ defaultValue: T;
+ onChange: (_v: T) => void;
+ value: T;
+ }>(({ value, onChange, defaultValue: dv }) => (
+ <LevelSlider<T>
+ defaultValue={dv}
+ levels={levels}
+ marks={marks}
+ onChange={onChange}
+ style={style}
+ value={value}
+ />
+ ));
+
+ // Store-connected component - uses agent store hooks
+ const LevelSliderWithStore = memo<{ defaultValue: T }>(({ defaultValue: dv }) => {
+ const agentId = useAgentId();
+ const { updateAgentChatConfig } = useUpdateAgentConfig();
+ const agentConfig = useAgentStore((s) => chatConfigByIdSelectors.getChatConfigById(agentId)(s));
+
+ const storeValue = (agentConfig[configKey] as T) || dv;
+
+ const handleChange = (newValue: T) => {
+ updateAgentChatConfig({ [configKey]: newValue });
+ };
+
+ return <LevelSliderInner defaultValue={dv} onChange={handleChange} value={storeValue} />;
+ });
+
+ // Main exported component - chooses between controlled and store mode
+ const CreatedLevelSlider = memo<CreatedLevelSliderProps<T>>(
+ ({ value: controlledValue, onChange: controlledOnChange, defaultValue: propDefaultValue }) => {
+ const dv = propDefaultValue ?? defaultValue;
+ const isControlled = controlledValue !== undefined || controlledOnChange !== undefined;
+
+ if (isControlled) {
+ // Controlled mode: use props only, no store access
+ return (
+ <LevelSliderInner
+ defaultValue={dv}
+ onChange={controlledOnChange ?? (() => {})}
+ value={controlledValue ?? dv}
+ />
+ );
+ }
+
+ // Uncontrolled mode: use store
+ return <LevelSliderWithStore defaultValue={dv} />;
+ },
+ );
+
+ return CreatedLevelSlider;
+}
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index ef2fa0fde29..4ae6e746d16 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -78,6 +78,7 @@ export default {
'extendParams.reasoningEffort.title': 'Reasoning Intensity',
'extendParams.textVerbosity.title': 'Output Text Detail Level',
'extendParams.thinking.title': 'Deep Thinking Switch',
+ 'extendParams.thinkingBudget.title': 'Thinking Budget',
'extendParams.thinkingLevel.title': 'Level of Thinking',
'extendParams.title': 'Model Extension Features',
'extendParams.urlContext.desc':
diff --git a/src/locales/default/modelProvider.ts b/src/locales/default/modelProvider.ts
index fc2e1ae6972..97fd14f4802 100644
--- a/src/locales/default/modelProvider.ts
+++ b/src/locales/default/modelProvider.ts
@@ -220,6 +220,44 @@ export default {
'providerModels.item.modelConfig.displayName.placeholder':
'Please enter the display name of the model, e.g., ChatGPT, GPT-4, etc.',
'providerModels.item.modelConfig.displayName.title': 'Model Display Name',
+ 'providerModels.item.modelConfig.extendParams.extra':
+ 'Choose extended parameters supported by the model. Hover an option to preview controls. Incorrect configs may cause request failures.',
+ 'providerModels.item.modelConfig.extendParams.options.disableContextCaching.hint':
+ 'For Claude models; can lower cost and speed up responses.',
+ 'providerModels.item.modelConfig.extendParams.options.enableReasoning.hint':
+ 'For Claude, DeepSeek and other reasoning models; unlock deeper thinking.',
+ 'providerModels.item.modelConfig.extendParams.options.gpt5ReasoningEffort.hint':
+ 'For GPT-5 series; controls reasoning intensity.',
+ 'providerModels.item.modelConfig.extendParams.options.gpt5_1ReasoningEffort.hint':
+ 'For GPT-5.1 series; controls reasoning intensity.',
+ 'providerModels.item.modelConfig.extendParams.options.gpt5_2ProReasoningEffort.hint':
+ 'For GPT-5.2 Pro series; controls reasoning intensity.',
+ 'providerModels.item.modelConfig.extendParams.options.gpt5_2ReasoningEffort.hint':
+ 'For GPT-5.2 series; controls reasoning intensity.',
+ 'providerModels.item.modelConfig.extendParams.options.imageAspectRatio.hint':
+ 'For Gemini image generation models; controls aspect ratio of generated images.',
+ 'providerModels.item.modelConfig.extendParams.options.imageResolution.hint':
+ 'For Gemini 3 image generation models; controls resolution of generated images.',
+ 'providerModels.item.modelConfig.extendParams.options.reasoningBudgetToken.hint':
+ 'For Claude, Qwen3 and similar; controls token budget for reasoning.',
+ 'providerModels.item.modelConfig.extendParams.options.reasoningEffort.hint':
+ 'For OpenAI and other reasoning-capable models; controls reasoning effort.',
+ 'providerModels.item.modelConfig.extendParams.options.textVerbosity.hint':
+ 'For GPT-5+ series; controls output verbosity.',
+ 'providerModels.item.modelConfig.extendParams.options.thinking.hint':
+ 'For some Doubao models; allow model to decide whether to think deeply.',
+ 'providerModels.item.modelConfig.extendParams.options.thinkingBudget.hint':
+ 'For Gemini series; controls thinking budget.',
+ 'providerModels.item.modelConfig.extendParams.options.thinkingLevel.hint':
+ 'For Gemini 3 Flash Preview models; controls thinking depth.',
+ 'providerModels.item.modelConfig.extendParams.options.thinkingLevel2.hint':
+ 'For Gemini 3 Pro Preview models; controls thinking depth.',
+ 'providerModels.item.modelConfig.extendParams.options.urlContext.hint':
+ 'For Gemini series; supports providing URL context.',
+ 'providerModels.item.modelConfig.extendParams.placeholder':
+ 'Select extended parameters to enable',
+ 'providerModels.item.modelConfig.extendParams.previewFallback': 'Preview unavailable',
+ 'providerModels.item.modelConfig.extendParams.title': 'Extended Parameters',
'providerModels.item.modelConfig.files.extra':
'The current file upload implementation is just a hack solution, limited to self-experimentation. Please wait for complete file upload capabilities in future implementations.',
'providerModels.item.modelConfig.files.title': 'File Upload Support',