feat: Implement settings and configuration functionality

This commit introduces new features and modifies existing code to implement
functionality for the settings form. It includes adding new settings, modifying
existing settings, creating setting item groups, and updating files with new
functions, default settings, CSS overrides, and type declarations.

The changes aim to enhance the user experience by allowing users to customize
the application settings according to their preferences.
This commit is contained in:
canisminor1990
2023-07-18 22:13:26 +08:00
parent f9a814f5c5
commit 496c2d9a2d
13 changed files with 359 additions and 64 deletions

View File

@@ -20,60 +20,68 @@
"desc": "When the uncompressed chat history exceeds this value, it will be compressed",
"title": "Chat History Compression Threshold"
},
"enableCompressThreshold": {
"title": "Enable Chat History Compression Threshold"
},
"enableHistoryCount": {
"title": "Enable History Message Count Limit"
},
"historyCount": {
"desc": "Number of chat history messages carried in each request",
"desc": "Number of history messages to include in each request",
"title": "History Message Count"
},
"inputTemplate": {
"desc": "The latest user message will be filled into this template",
"title": "User Input Preprocessing"
},
"maxTokens": {
"desc": "Maximum number of tokens used for each interaction",
"title": "Reply Limit (max_tokens)"
},
"sendKey": {
"title": "Send Key"
},
"title": "Chat Settings"
},
"settingModel": {
"enableMaxTokens": {
"title": "Enable Single Reply Limit"
},
"frequencyPenalty": {
"desc": "The higher the value, the more likely it is to reduce repeated words",
"title": "Frequency Penalty (frequency_penalty)"
"title": "Frequency Penalty"
},
"maxTokens": {
"desc": "Maximum number of tokens used in a single interaction",
"title": "Single Reply Limit"
},
"model": {
"desc": "ChatGPT Model",
"title": "Model"
},
"presencePenalty": {
"desc": "The higher the value, the more likely it is to expand to new topics",
"title": "Topic Freshness (presence_penalty)"
"title": "Topic Freshness"
},
"temperature": {
"desc": "The higher the value, the more random the reply",
"title": "Randomness (temperature)"
"title": "Randomness"
},
"title": "Model Settings",
"topP": {
"desc": "Similar to randomness, but do not change together with randomness",
"title": "Nucleus Sampling (top_p)"
"title": "Top-p Sampling"
}
},
"settingOpenAI": {
"endpoint": {
"desc": "Must include http(s)://, in addition to the default address",
"title": "API Endpoint"
"placeholder": "https://api.openai.com/v1",
"title": "API Proxy Endpoint"
},
"title": "OpenAI Settings",
"token": {
"desc": "Use your own Key to bypass password access restrictions",
"desc": "Use your own OpenAI Key",
"placeholder": "OpenAI API Key",
"title": "API Key"
}
},
"settingSystem": {
"accessCode": {
"desc": "Encryption access has been enabled by the administrator",
"desc": "Encryption access is enabled by the administrator",
"placeholder": "Please enter the access password",
"title": "Access Password"
},
@@ -91,7 +99,7 @@
"title": "Language Settings"
},
"neutralColor": {
"desc": "Custom grayscale for different color tendencies",
"desc": "Custom grayscale for different color biases",
"title": "Neutral Color"
},
"primaryColor": {

View File

@@ -20,6 +20,12 @@
"desc": "当未压缩的历史消息超过该值时,将进行压缩",
"title": "历史消息长度压缩阈值"
},
"enableCompressThreshold": {
"title": "是否开启历史消息长度压缩阈值"
},
"enableHistoryCount": {
"title": "是否开启携带的历史消息数限制"
},
"historyCount": {
"desc": "每次请求携带的历史消息数",
"title": "附带历史消息数"
@@ -28,45 +34,47 @@
"desc": "用户最新的一条消息会填充到此模板",
"title": "用户输入预处理"
},
"maxTokens": {
"desc": "单次交互所用的最大 Token 数",
"title": "单次回复限制 (max_tokens)"
},
"sendKey": {
"title": "发送键"
},
"title": "聊天设置"
},
"settingModel": {
"enableMaxTokens": {
"title": "开启单次回复限制"
},
"frequencyPenalty": {
"desc": "值越大,越有可能降低重复字词",
"title": "频率惩罚度 (frequency_penalty)"
"title": "频率惩罚度"
},
"maxTokens": {
"desc": "单次交互所用的最大 Token 数",
"title": "单次回复限制"
},
"model": {
"desc": "ChatGPT 模型",
"title": "模型"
},
"presencePenalty": {
"desc": "值越大,越有可能扩展到新话题",
"title": "话题新鲜度 (presence_penalty)"
"title": "话题新鲜度"
},
"temperature": {
"desc": "值越大,回复越随机",
"title": "随机性 (temperature)"
"title": "随机性"
},
"title": "模型设置",
"topP": {
"desc": "与随机性类似,但不要和随机性一起更改",
"title": "核采样 (top_p)"
"title": "核采样"
}
},
"settingOpenAI": {
"endpoint": {
"desc": "除默认地址外,必须包含 http(s)://",
"title": "接口地址"
"placeholder": "https://api.openai.com/v1",
"title": "接口代理地址"
},
"title": "OpenAI 设置",
"token": {
"desc": "使用自己的 Key 可绕过密码访问限制",
"desc": "使用自己的 OpenAI Key",
"placeholder": "OpenAI API Key",
"title": "API Key"
}

View File

@@ -20,6 +20,12 @@ export default {
desc: '当未压缩的历史消息超过该值时,将进行压缩',
title: '历史消息长度压缩阈值',
},
enableCompressThreshold: {
title: '是否开启历史消息长度压缩阈值',
},
enableHistoryCount: {
title: '是否开启携带的历史消息数限制',
},
historyCount: {
desc: '每次请求携带的历史消息数',
title: '附带历史消息数',
@@ -28,45 +34,47 @@ export default {
desc: '用户最新的一条消息会填充到此模板',
title: '用户输入预处理',
},
maxTokens: {
desc: '单次交互所用的最大 Token 数',
title: '单次回复限制 (max_tokens)',
},
sendKey: {
title: '发送键',
},
title: '聊天设置',
},
settingModel: {
enableMaxTokens: {
title: '开启单次回复限制',
},
frequencyPenalty: {
desc: '值越大,越有可能降低重复字词',
title: '频率惩罚度 (frequency_penalty)',
title: '频率惩罚度',
},
maxTokens: {
desc: '单次交互所用的最大 Token 数',
title: '单次回复限制',
},
model: {
desc: 'ChatGPT 模型',
title: '模型',
},
presencePenalty: {
desc: '值越大,越有可能扩展到新话题',
title: '话题新鲜度 (presence_penalty)',
title: '话题新鲜度',
},
temperature: {
desc: '值越大,回复越随机',
title: '随机性 (temperature)',
title: '随机性',
},
title: '模型设置',
topP: {
desc: '与随机性类似,但不要和随机性一起更改',
title: '核采样 (top_p)',
title: '核采样',
},
},
settingOpenAI: {
endpoint: {
desc: '除默认地址外,必须包含 http(s)://',
title: '接口地址',
placeholder: 'https://api.openai.com/v1',
title: '接口代理地址',
},
title: 'OpenAI 设置',
token: {
desc: '使用自己的 Key 可绕过密码访问限制',
desc: '使用自己的 OpenAI Key',
placeholder: 'OpenAI API Key',
title: 'API Key',
},

View File

@@ -1,7 +1,9 @@
import common from '../../../locales/en_US/common.json';
import setting from '../../../locales/en_US/setting.json';
const resources = {
common,
setting,
} as const;
export default resources;

View File

@@ -1,16 +1,19 @@
import { Form, type ItemGroup, ThemeSwitch } from '@lobehub/ui';
import { Select, Slider } from 'antd';
import { Form as AntForm, Button, Input, Popconfirm, Select, Switch } from 'antd';
import isEqual from 'fast-deep-equal';
import { debounce } from 'lodash-es';
import { Palette } from 'lucide-react';
import { memo, useMemo } from 'react';
import { AppWindow, Bot, MessagesSquare, Palette, Webhook } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { shallow } from 'zustand/shallow';
import AvatarWithUpload from '@/features/AvatarWithUpload';
import { options } from '@/locales/options';
import SliderWithInput from '@/pages/setting/SliderWithInput';
import { settingsSelectors, useSettings } from '@/store/settings';
import { DEFAULT_SETTINGS } from '@/store/settings/initialState';
import { ConfigKeys } from '@/types/exportConfig';
import { LanguageModel } from '@/types/llm';
import { ThemeSwatchesNeutral, ThemeSwatchesPrimary } from './ThemeSwatches';
@@ -21,13 +24,27 @@ type SettingItemGroup = ItemGroup & {
};
const SettingForm = memo(() => {
const { t } = useTranslation('setting');
const [form] = AntForm.useForm();
const settings = useSettings(settingsSelectors.currentSettings, isEqual);
const { setThemeMode, setSettings } = useSettings(
(s) => ({ setSettings: s.setSettings, setThemeMode: s.setThemeMode }),
const { setThemeMode, setSettings, resetSettings } = useSettings(
(s) => ({
resetSettings: s.resetSettings,
setSettings: s.setSettings,
setThemeMode: s.setThemeMode,
}),
shallow,
);
const { t } = useTranslation('setting');
const handleReset = useCallback(() => {
resetSettings();
form.setFieldsValue(DEFAULT_SETTINGS);
}, []);
const handleClear = useCallback(() => {
handleReset();
// TODO: 删除聊天记录
}, []);
const theme: SettingItemGroup = useMemo(
() => ({
@@ -58,7 +75,7 @@ const SettingForm = memo(() => {
name: 'language',
},
{
children: <Slider max={18} min={12} />,
children: <SliderWithInput max={18} min={12} />,
desc: t('settingTheme.fontSize.desc'),
label: t('settingTheme.fontSize.title'),
name: 'fontSize',
@@ -82,11 +99,197 @@ const SettingForm = memo(() => {
[settings],
);
const OpenAI: SettingItemGroup = useMemo(
() => ({
children: [
{
children: <Input.Password placeholder={t('settingOpenAI.token.placeholder')} />,
desc: t('settingOpenAI.token.desc'),
label: t('settingOpenAI.token.title'),
name: 'token',
},
{
children: <Input placeholder={t('settingOpenAI.endpoint.placeholder')} />,
desc: t('settingOpenAI.endpoint.desc'),
label: t('settingOpenAI.endpoint.title'),
name: 'endpoint',
},
],
icon: Webhook,
title: t('settingOpenAI.title'),
}),
[settings],
);
const Chat: SettingItemGroup = useMemo(
() => ({
children: [
{
children: <Switch />,
label: t('settingChat.enableHistoryCount.title'),
minWidth: undefined,
name: 'enableHistoryCount',
valuePropName: 'checked',
},
{
children: <SliderWithInput max={32} min={0} />,
desc: t('settingChat.historyCount.desc'),
hidden: !settings.enableHistoryCount,
label: t('settingChat.historyCount.title'),
name: 'historyCount',
},
{
children: <Switch />,
label: t('settingChat.enableCompressThreshold.title'),
minWidth: undefined,
name: 'enableCompressThreshold',
valuePropName: 'checked',
},
{
children: <SliderWithInput max={32} min={0} />,
desc: t('settingChat.compressThreshold.desc'),
hidden: !settings.enableCompressThreshold,
label: t('settingChat.compressThreshold.title'),
name: 'compressThreshold',
},
],
icon: MessagesSquare,
title: t('settingChat.title'),
}),
[settings],
);
const Model: SettingItemGroup = useMemo(
() => ({
children: [
{
children: (
<Select
options={Object.values(LanguageModel).map((value) => ({
label: value,
value,
}))}
/>
),
desc: t('settingModel.model.desc'),
label: t('settingModel.model.title'),
name: 'model',
tag: 'model',
},
{
children: <SliderWithInput max={1} min={0} step={0.1} />,
desc: t('settingModel.temperature.desc'),
label: t('settingModel.temperature.title'),
name: 'temperature',
tag: 'temperature',
},
{
children: <SliderWithInput max={1} min={0} step={0.1} />,
desc: t('settingModel.topP.desc'),
label: t('settingModel.topP.title'),
name: 'topP',
tag: 'top_p',
},
{
children: <SliderWithInput max={2} min={-2} step={0.1} />,
desc: t('settingModel.presencePenalty.desc'),
label: t('settingModel.presencePenalty.title'),
name: 'presencePenalty',
tag: 'presence_penalty',
},
{
children: <SliderWithInput max={2} min={-2} step={0.1} />,
desc: t('settingModel.frequencyPenalty.desc'),
label: t('settingModel.frequencyPenalty.title'),
name: 'frequencyPenalty',
tag: 'frequency_penalty',
},
{
children: <Switch />,
label: t('settingModel.enableMaxTokens.title'),
minWidth: undefined,
name: 'enableMaxTokens',
valuePropName: 'checked',
},
{
children: <SliderWithInput max={32_000} min={0} step={100} />,
desc: t('settingModel.maxTokens.desc'),
hidden: !settings.enableMaxTokens,
label: t('settingModel.maxTokens.title'),
name: 'maxTokens',
tag: 'max_tokens',
},
],
icon: Bot,
title: t('settingModel.title'),
}),
[settings],
);
const System: SettingItemGroup = useMemo(
() => ({
children: [
{
children: <Input.Password placeholder={t('settingSystem.accessCode.placeholder')} />,
desc: t('settingSystem.accessCode.desc'),
label: t('settingSystem.accessCode.title'),
name: 'accessCode',
},
{
children: (
<Popconfirm
arrow={false}
cancelText={t('cancel', { ns: 'common' })}
okButtonProps={{ danger: true }}
okText={t('ok', { ns: 'common' })}
onConfirm={handleReset}
title={t('danger.reset.confirm')}
>
<Button danger type="primary">
{t('danger.reset.action')}
</Button>
</Popconfirm>
),
desc: t('danger.reset.title'),
label: t('danger.reset.desc'),
minWidth: undefined,
},
{
children: (
<Popconfirm
arrow={false}
cancelText={t('cancel', { ns: 'common' })}
okButtonProps={{ danger: true }}
okText={t('ok', { ns: 'common' })}
onConfirm={handleClear}
title={t('danger.clear.confirm')}
>
<Button danger type="primary">
{t('danger.clear.action')}
</Button>
</Popconfirm>
),
desc: t('danger.clear.title'),
label: t('danger.clear.desc'),
minWidth: undefined,
},
],
icon: AppWindow,
title: t('settingSystem.title'),
}),
[settings],
);
const items = useMemo(() => [theme, OpenAI, Chat, Model, System], [settings]);
return (
<Form
form={form}
initialValues={settings}
itemMinWidth="min(30%,200px)"
items={[theme]}
itemMinWidth="max(30%,240px)"
items={items}
onValuesChange={debounce(setSettings, 100)}
style={{ maxWidth: 1024, width: '100%' }}
/>

View File

@@ -0,0 +1,34 @@
import { InputNumber, Slider } from 'antd';
import { SliderSingleProps } from 'antd/es/slider';
import { memo } from 'react';
import { Flexbox } from 'react-layout-kit';
const SliderWithInput = memo<SliderSingleProps>(
({ step, value, onChange, max, min, defaultValue, ...props }) => {
return (
<Flexbox direction={'horizontal'} gap={8}>
<Slider
defaultValue={defaultValue}
max={max}
min={min}
onChange={onChange}
step={step}
style={{ flex: 1 }}
value={value}
{...props}
/>
<InputNumber
defaultValue={defaultValue}
max={max}
min={min}
onChange={onChange as any}
step={Number(step)}
style={{ flex: 1, maxWidth: 64 }}
value={value}
/>
</Flexbox>
);
},
);
export default SliderWithInput;

View File

@@ -24,12 +24,12 @@ const SettingLayout = memo(() => {
<Head>
<title>{pageTitle}</title>
</Head>
<Flexbox horizontal width={'100%'}>
<Flexbox height={'100vh'} horizontal width={'100%'}>
<SideBar />
<Sessions />
<Flexbox flex={1}>
<Header />
<Flexbox align={'center'} padding={24}>
<Flexbox align={'center'} flex={1} padding={24} style={{ overflow: 'auto' }}>
<SettingForm />
</Flexbox>
</Flexbox>

View File

@@ -1,16 +1,16 @@
import { ThemeMode } from 'antd-style';
import { merge } from 'lodash-es';
import type { StateCreator } from 'zustand/vanilla';
import type { ConfigSettings } from '@/types/exportConfig';
import type { SidebarTabKey } from './initialState';
import { GlobalSettingsState } from './initialState';
import { DEFAULT_SETTINGS, GlobalSettingsState } from './initialState';
import type { SettingsStore } from './store';
export interface SettingsAction {
resetSettings: () => void;
setGlobalSettings: (settings: GlobalSettingsState) => void;
setSettings: (settings: { [keys in keyof ConfigSettings]?: any }) => void;
setSettings: (settings: Partial<ConfigSettings>) => void;
setThemeMode: (themeMode: ThemeMode) => void;
switchSideBar: (key: SidebarTabKey) => void;
}
@@ -21,11 +21,15 @@ export const createSettings: StateCreator<
[],
SettingsAction
> = (set, get) => ({
resetSettings: () => {
set({ settings: DEFAULT_SETTINGS });
},
setGlobalSettings: (settings) => {
set({ ...settings });
},
setSettings: (settings) => {
set({ settings: merge(get().settings, settings) });
const oldSetting = get().settings;
set({ settings: { ...oldSetting, ...settings } });
},
setThemeMode: (themeMode) => {
get().setSettings({ themeMode });

View File

@@ -2,12 +2,26 @@ import type { ConfigSettings } from '@/types/exportConfig';
export type SidebarTabKey = 'chat' | 'market';
export const DEFAULT_SETTINGS: ConfigSettings = {
accessCode: '',
avatar: '',
compressThreshold: 24,
enableCompressThreshold: true,
enableHistoryCount: true,
enableMaxTokens: true,
endpoint: '',
fontSize: 14,
frequencyPenalty: 0,
historyCount: 24,
language: 'zh-CN',
maxTokens: 2000,
model: 'gpt-3.5-turbo',
neutralColor: '',
presencePenalty: 0,
primaryColor: '',
temperature: 0.5,
themeMode: 'auto',
token: '',
topP: 1,
};
export interface GlobalSettingsState {

View File

@@ -1,10 +1,10 @@
import { merge } from 'lodash-es';
import { defaults } from 'lodash-es';
import { DEFAULT_SETTINGS } from '@/store/settings/initialState';
import { SettingsStore } from './store';
const currentSettings = (s: SettingsStore) => merge(DEFAULT_SETTINGS, s.settings);
const currentSettings = (s: SettingsStore) => defaults(s.settings, DEFAULT_SETTINGS);
const selecThemeMode = (s: SettingsStore) => ({
setThemeMode: s.setThemeMode,

View File

@@ -16,7 +16,7 @@ export default (token: Theme) => css`
background: ${token.colorPrimary} !important;
}
.ant-btn-primary {
.ant-btn-primary:not(.ant-btn-dangerous) {
color: ${readableColor(token.colorPrimary)};
background: ${token.colorPrimary};

View File

@@ -7,12 +7,26 @@ import { Locales } from './locale';
* 配置设置
*/
export interface ConfigSettings {
avatar?: string;
accessCode: string;
avatar: string;
compressThreshold: number;
enableCompressThreshold: boolean;
enableHistoryCount: boolean;
enableMaxTokens: boolean;
endpoint: string;
fontSize: number;
frequencyPenalty: number;
historyCount: number;
language: Locales;
neutralColor?: NeutralColors | '';
primaryColor?: PrimaryColors | '';
maxTokens: number;
model: string;
neutralColor: NeutralColors | '';
presencePenalty: number;
primaryColor: PrimaryColors | '';
temperature: number;
themeMode: ThemeMode;
token: string;
topP: number;
}
export type ConfigKeys = keyof ConfigSettings;

View File

@@ -2,7 +2,7 @@ import { DefaultResources } from '@/types/locale';
declare module 'i18next' {
interface CustomTypeOptions {
defaultNS: 'common';
defaultNS: ['common', 'setting'];
resources: DefaultResources;
}
}