672 lines
25 KiB
React
672 lines
25 KiB
React
/*
|
|
Copyright (C) 2025 QuantumNous
|
|
|
|
This program is free software: you can redistribute it and/or modify
|
|
it under the terms of the GNU Affero General Public License as
|
|
published by the Free Software Foundation, either version 3 of the
|
|
License, or (at your option) any later version.
|
|
|
|
This program is distributed in the hope that it will be useful,
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
GNU Affero General Public License for more details.
|
|
|
|
You should have received a copy of the GNU Affero General Public License
|
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
For commercial licensing, please contact support@quantumnous.com
|
|
*/
|
|
|
|
import '../../../console/module-alignment.css';
|
|
import React, { useState, useEffect, useRef } from 'react';
|
|
import JSONEditor from '../../../common/ui/JSONEditor';
|
|
import {
|
|
SideSheet,
|
|
Form,
|
|
Button,
|
|
Space,
|
|
Spin,
|
|
Typography,
|
|
Card,
|
|
Avatar,
|
|
Col,
|
|
Row,
|
|
} from '@/components/ui';
|
|
import { FileText } from 'lucide-react';
|
|
import { IconLink } from '@/components/ui/icons';
|
|
import { API, showError, showSuccess } from '../../../../helpers';
|
|
import { useTranslation } from 'react-i18next';
|
|
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
|
|
|
|
const { Text } = Typography;
|
|
|
|
// Example endpoint template for quick fill
|
|
const ENDPOINT_TEMPLATE = {
|
|
openai: { path: '/v1/chat/completions', method: 'POST' },
|
|
'openai-response': { path: '/v1/responses', method: 'POST' },
|
|
anthropic: { path: '/v1/messages', method: 'POST' },
|
|
gemini: { path: '/v1beta/models/{model}:generateContent', method: 'POST' },
|
|
'jina-rerank': { path: '/rerank', method: 'POST' },
|
|
'image-generation': { path: '/v1/images/generations', method: 'POST' },
|
|
};
|
|
|
|
const nameRuleOptions = [
|
|
{ label: '精确名称匹配', value: 0 },
|
|
{ label: '前缀名称匹配', value: 1 },
|
|
{ label: '包含名称匹配', value: 2 },
|
|
{ label: '后缀名称匹配', value: 3 },
|
|
];
|
|
|
|
const EditModelModal = (props) => {
|
|
const { t } = useTranslation();
|
|
const [loading, setLoading] = useState(false);
|
|
const isMobile = useIsMobile();
|
|
const formApiRef = useRef(null);
|
|
const isEdit = props.editingModel && props.editingModel.id !== undefined;
|
|
|
|
// 供应商列表
|
|
const [vendors, setVendors] = useState([]);
|
|
|
|
// 预填组(标签、端点)
|
|
const [tagGroups, setTagGroups] = useState([]);
|
|
const [endpointGroups, setEndpointGroups] = useState([]);
|
|
|
|
// 分类数据
|
|
const [level1Categories, setLevel1Categories] = useState([]);
|
|
const [level2Categories, setLevel2Categories] = useState([]);
|
|
const [allLevel2Categories, setAllLevel2Categories] = useState([]);
|
|
const [selectedLevel1Keys, setSelectedLevel1Keys] = useState([]);
|
|
|
|
// 获取供应商列表
|
|
const fetchVendors = async () => {
|
|
try {
|
|
const res = await API.get('/api/vendors/?page_size=1000'); // 获取全部供应商
|
|
if (res.data.success) {
|
|
const items = res.data.data.items || res.data.data || [];
|
|
setVendors(Array.isArray(items) ? items : []);
|
|
}
|
|
} catch (error) {
|
|
// ignore
|
|
}
|
|
};
|
|
|
|
// 获取分类数据
|
|
const fetchCategories = async () => {
|
|
try {
|
|
const res = await API.get('/api/model_categories/flat');
|
|
if (res.data.success) {
|
|
const categoriesData = res.data.data || [];
|
|
const level1 = categoriesData.filter((cat) => cat.parent_id === 0);
|
|
const level2 = categoriesData.filter((cat) => cat.parent_id !== 0);
|
|
setLevel1Categories(level1);
|
|
setAllLevel2Categories(level2);
|
|
}
|
|
} catch (error) {
|
|
// ignore
|
|
}
|
|
};
|
|
|
|
// 获取预填组(标签、端点)
|
|
const fetchPrefillGroups = async () => {
|
|
try {
|
|
const [tagRes, endpointRes] = await Promise.all([
|
|
API.get('/api/prefill_group?type=tag'),
|
|
API.get('/api/prefill_group?type=endpoint'),
|
|
]);
|
|
if (tagRes?.data?.success) {
|
|
setTagGroups(tagRes.data.data || []);
|
|
}
|
|
if (endpointRes?.data?.success) {
|
|
setEndpointGroups(endpointRes.data.data || []);
|
|
}
|
|
} catch (error) {
|
|
// ignore
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (props.visiable) {
|
|
fetchVendors();
|
|
fetchPrefillGroups();
|
|
fetchCategories();
|
|
}
|
|
}, [props.visiable]);
|
|
|
|
const getInitValues = () => ({
|
|
model_name: props.editingModel?.model_name || '',
|
|
description: '',
|
|
icon: '',
|
|
tags: [],
|
|
vendor_id: undefined,
|
|
vendor: '',
|
|
vendor_icon: '',
|
|
categories: [],
|
|
level1_categories: [],
|
|
level2_categories: [],
|
|
endpoints: '',
|
|
name_rule: props.editingModel?.model_name ? 0 : undefined, // 通过未配置模型过来的固定为精确匹配
|
|
status: true,
|
|
sync_official: true,
|
|
});
|
|
|
|
const handleCancel = () => {
|
|
props.handleClose();
|
|
};
|
|
|
|
const loadModel = async () => {
|
|
if (!isEdit || !props.editingModel.id) return;
|
|
|
|
setLoading(true);
|
|
try {
|
|
const res = await API.get(`/api/models/${props.editingModel.id}`);
|
|
const { success, message, data } = res.data;
|
|
if (success) {
|
|
// 处理tags
|
|
if (data.tags) {
|
|
data.tags = data.tags.split(',').filter(Boolean);
|
|
} else {
|
|
data.tags = [];
|
|
}
|
|
// endpoints 保持原始 JSON 字符串,若为空设为空串
|
|
if (!data.endpoints) {
|
|
data.endpoints = '';
|
|
}
|
|
// 处理status/sync_official,将数字转为布尔值
|
|
data.status = data.status === 1;
|
|
data.sync_official = (data.sync_official ?? 1) === 1;
|
|
|
|
// 处理分类:从 categories 数组中分离出一级分类和二级分类
|
|
if (data.categories && Array.isArray(data.categories)) {
|
|
const level1Keys = [];
|
|
const level2Keys = [];
|
|
|
|
data.categories.forEach((categoryKey) => {
|
|
// 查找是一级还是二级分类
|
|
const isLevel1 = level1Categories.some(
|
|
(cat) => cat.category_key === categoryKey,
|
|
);
|
|
const isLevel2 = allLevel2Categories.some(
|
|
(cat) => cat.category_key === categoryKey,
|
|
);
|
|
|
|
if (isLevel1) {
|
|
level1Keys.push(categoryKey);
|
|
} else if (isLevel2) {
|
|
level2Keys.push(categoryKey);
|
|
}
|
|
});
|
|
|
|
data.level1_categories = level1Keys;
|
|
data.level2_categories = level2Keys;
|
|
|
|
// 设置选中的一级分类,用于过滤二级分类
|
|
setSelectedLevel1Keys(level1Keys);
|
|
|
|
// 更新可见的二级分类
|
|
if (level1Keys.length > 0) {
|
|
const level1Ids = level1Categories
|
|
.filter((cat) => level1Keys.includes(cat.category_key))
|
|
.map((cat) => cat.id);
|
|
const filtered = allLevel2Categories.filter((cat) =>
|
|
level1Ids.includes(cat.parent_id),
|
|
);
|
|
setLevel2Categories(filtered);
|
|
} else {
|
|
setLevel2Categories([]);
|
|
}
|
|
}
|
|
|
|
if (formApiRef.current) {
|
|
formApiRef.current.setValues({ ...getInitValues(), ...data });
|
|
}
|
|
} else {
|
|
showError(message);
|
|
}
|
|
} catch (error) {
|
|
showError(t('加载模型信息失败'));
|
|
}
|
|
setLoading(false);
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (formApiRef.current) {
|
|
if (!isEdit) {
|
|
formApiRef.current.setValues({
|
|
...getInitValues(),
|
|
model_name: props.editingModel?.model_name || '',
|
|
});
|
|
}
|
|
}
|
|
}, [props.editingModel?.id, props.editingModel?.model_name]);
|
|
|
|
useEffect(() => {
|
|
if (props.visiable) {
|
|
if (isEdit) {
|
|
loadModel();
|
|
} else {
|
|
formApiRef.current?.setValues({
|
|
...getInitValues(),
|
|
model_name: props.editingModel?.model_name || '',
|
|
});
|
|
}
|
|
} else {
|
|
formApiRef.current?.reset();
|
|
}
|
|
}, [props.visiable, props.editingModel?.id, props.editingModel?.model_name]);
|
|
|
|
const submit = async (values) => {
|
|
setLoading(true);
|
|
try {
|
|
// 合并一级分类和二级分类到 categories 数组
|
|
const categories = [
|
|
...(values.level1_categories || []),
|
|
...(values.level2_categories || []),
|
|
];
|
|
|
|
const submitData = {
|
|
...values,
|
|
tags: Array.isArray(values.tags) ? values.tags.join(',') : values.tags,
|
|
endpoints: values.endpoints || '',
|
|
status: values.status ? 1 : 0,
|
|
sync_official: values.sync_official ? 1 : 0,
|
|
categories: categories, // 提交合并后的分类
|
|
};
|
|
|
|
// 删除临时字段
|
|
delete submitData.level1_categories;
|
|
delete submitData.level2_categories;
|
|
|
|
if (isEdit) {
|
|
submitData.id = props.editingModel.id;
|
|
const res = await API.put('/api/models/', submitData);
|
|
const { success, message } = res.data;
|
|
if (success) {
|
|
showSuccess(t('模型更新成功!'));
|
|
props.refresh();
|
|
props.handleClose();
|
|
} else {
|
|
showError(t(message));
|
|
}
|
|
} else {
|
|
const res = await API.post('/api/models/', submitData);
|
|
const { success, message } = res.data;
|
|
if (success) {
|
|
showSuccess(t('模型创建成功!'));
|
|
props.refresh();
|
|
props.handleClose();
|
|
} else {
|
|
showError(t(message));
|
|
}
|
|
}
|
|
} catch (error) {
|
|
showError(error.response?.data?.message || t('操作失败'));
|
|
}
|
|
setLoading(false);
|
|
formApiRef.current?.setValues(getInitValues());
|
|
};
|
|
|
|
return (
|
|
<SideSheet
|
|
rootClassName='console-model-drawer'
|
|
classNames={{ header: 'console-model-editor-header' }}
|
|
placement='right'
|
|
title={isEdit ? t('更新模型信息') : t('创建新的模型')}
|
|
bodyStyle={{ padding: '0' }}
|
|
visible={props.visiable}
|
|
width={isMobile ? '100%' : 600}
|
|
footer={
|
|
<div className='console-model-footer'>
|
|
<Button onClick={handleCancel}>{t('取消')}</Button>
|
|
<Button
|
|
theme='solid'
|
|
type='primary'
|
|
onClick={() => formApiRef.current?.submitForm()}
|
|
loading={loading}
|
|
>
|
|
{t('确定')}
|
|
</Button>
|
|
</div>
|
|
}
|
|
onCancel={() => handleCancel()}
|
|
>
|
|
<Spin spinning={loading}>
|
|
<Form
|
|
key={isEdit ? 'edit' : 'new'}
|
|
initValues={getInitValues()}
|
|
getFormApi={(api) => (formApiRef.current = api)}
|
|
onSubmit={submit}
|
|
>
|
|
{({ values }) => (
|
|
<div className='p-2'>
|
|
{/* 基本信息 */}
|
|
<Card className='!rounded-2xl shadow-sm border-0'>
|
|
<div className='console-model-section'>
|
|
<Avatar size='small' color='green'>
|
|
<FileText size={16} />
|
|
</Avatar>
|
|
<div>
|
|
<Text className='text-lg font-medium'>{t('基本信息')}</Text>
|
|
<div className='text-xs text-gray-600'>
|
|
{t('设置模型的基本信息')}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<Row gutter={12}>
|
|
<Col span={24}>
|
|
<Form.Input
|
|
field='model_name'
|
|
label={t('模型名称')}
|
|
placeholder={t('请输入模型名称,如:gpt-4')}
|
|
rules={[{ required: true, message: t('请输入模型名称') }]}
|
|
showClear
|
|
/>
|
|
</Col>
|
|
|
|
<Col span={24}>
|
|
<Form.Select
|
|
field='name_rule'
|
|
label={t('名称匹配类型')}
|
|
placeholder={t('请选择名称匹配类型')}
|
|
optionList={nameRuleOptions.map((o) => ({
|
|
label: t(o.label),
|
|
value: o.value,
|
|
}))}
|
|
rules={[
|
|
{ required: true, message: t('请选择名称匹配类型') },
|
|
]}
|
|
extraText={t(
|
|
'根据模型名称和匹配规则查找模型元数据,优先级:精确 > 前缀 > 后缀 > 包含',
|
|
)}
|
|
style={{ width: '100%' }}
|
|
/>
|
|
</Col>
|
|
|
|
<Col span={24}>
|
|
<Form.Input
|
|
field='icon'
|
|
label={t('模型图标')}
|
|
placeholder={t('请输入图标名称')}
|
|
extraText={
|
|
<span>
|
|
{t(
|
|
"图标使用@lobehub/icons库,如:OpenAI、Claude.Color,支持链式参数:OpenAI.Avatar.type={'platform'}、OpenRouter.Avatar.shape={'square'},查询所有可用图标请 ",
|
|
)}
|
|
<Typography.Text
|
|
link={{
|
|
href: 'https://icons.lobehub.com/components/lobe-hub',
|
|
target: '_blank',
|
|
}}
|
|
icon={<IconLink />}
|
|
underline
|
|
>
|
|
{t('请点击我')}
|
|
</Typography.Text>
|
|
</span>
|
|
}
|
|
showClear
|
|
/>
|
|
</Col>
|
|
|
|
<Col span={24}>
|
|
<Form.TextArea
|
|
field='description'
|
|
label={t('描述')}
|
|
placeholder={t('请输入模型描述')}
|
|
rows={3}
|
|
showClear
|
|
/>
|
|
</Col>
|
|
<Col span={24}>
|
|
<Form.TagInput
|
|
field='tags'
|
|
label={t('标签')}
|
|
placeholder={t('输入标签或使用","分隔多个标签')}
|
|
addOnBlur
|
|
showClear
|
|
onChange={(newTags) => {
|
|
if (!formApiRef.current) return;
|
|
const normalize = (tags) => {
|
|
if (!Array.isArray(tags)) return [];
|
|
return [
|
|
...new Set(
|
|
tags.flatMap((tag) =>
|
|
tag
|
|
.split(',')
|
|
.map((t) => t.trim())
|
|
.filter(Boolean),
|
|
),
|
|
),
|
|
];
|
|
};
|
|
const normalized = normalize(newTags);
|
|
formApiRef.current.setValue('tags', normalized);
|
|
}}
|
|
style={{ width: '100%' }}
|
|
{...(tagGroups.length > 0 && {
|
|
extraText: (
|
|
<Space wrap className='console-model-tag-presets'>
|
|
{tagGroups.map((group) => (
|
|
<Button
|
|
key={group.id}
|
|
size='small'
|
|
type='primary'
|
|
onClick={() => {
|
|
if (formApiRef.current) {
|
|
const currentTags =
|
|
formApiRef.current.getValue('tags') || [];
|
|
const newTags = [
|
|
...currentTags,
|
|
...(group.items || []),
|
|
];
|
|
const uniqueTags = [...new Set(newTags)];
|
|
formApiRef.current.setValue(
|
|
'tags',
|
|
uniqueTags,
|
|
);
|
|
}
|
|
}}
|
|
>
|
|
{group.name}
|
|
</Button>
|
|
))}
|
|
</Space>
|
|
),
|
|
})}
|
|
/>
|
|
</Col>
|
|
<Col span={24}>
|
|
<Form.Select
|
|
field='vendor_id'
|
|
label={t('供应商')}
|
|
placeholder={t('选择模型供应商')}
|
|
optionList={vendors.map((v) => ({
|
|
label: v.name,
|
|
value: v.id,
|
|
}))}
|
|
filter
|
|
showClear
|
|
onChange={(value) => {
|
|
const vendorInfo = vendors.find((v) => v.id === value);
|
|
if (vendorInfo && formApiRef.current) {
|
|
formApiRef.current.setValue(
|
|
'vendor',
|
|
vendorInfo.name,
|
|
);
|
|
}
|
|
}}
|
|
style={{ width: '100%' }}
|
|
/>
|
|
</Col>
|
|
<Col span={24}>
|
|
<Form.Select
|
|
field='level1_categories'
|
|
label={t('一级分类(可多选)')}
|
|
placeholder={t('选择一级分类')}
|
|
optionList={level1Categories.map((cat) => ({
|
|
label: cat.category_name,
|
|
value: cat.category_key,
|
|
}))}
|
|
multiple
|
|
maxTagCount={3}
|
|
showClear
|
|
style={{ width: '100%' }}
|
|
onChange={(values) => {
|
|
// 更新选中的一级分类keys
|
|
setSelectedLevel1Keys(values || []);
|
|
|
|
// 根据选中的一级分类过滤二级分类
|
|
if (values && values.length > 0) {
|
|
const level1Ids = level1Categories
|
|
.filter((cat) => values.includes(cat.category_key))
|
|
.map((cat) => cat.id);
|
|
const filtered = allLevel2Categories.filter((cat) =>
|
|
level1Ids.includes(cat.parent_id),
|
|
);
|
|
setLevel2Categories(filtered);
|
|
|
|
// 清除不在范围内的二级分类选择
|
|
if (formApiRef.current) {
|
|
const currentLevel2 =
|
|
formApiRef.current.getValue(
|
|
'level2_categories',
|
|
) || [];
|
|
const validLevel2 = currentLevel2.filter((key) =>
|
|
filtered.some((cat) => cat.category_key === key),
|
|
);
|
|
if (validLevel2.length !== currentLevel2.length) {
|
|
formApiRef.current.setValue(
|
|
'level2_categories',
|
|
validLevel2,
|
|
);
|
|
}
|
|
}
|
|
} else {
|
|
setLevel2Categories([]);
|
|
if (formApiRef.current) {
|
|
formApiRef.current.setValue(
|
|
'level2_categories',
|
|
[],
|
|
);
|
|
}
|
|
}
|
|
}}
|
|
extraText={t('选择模型的一级分类,可多选')}
|
|
/>
|
|
</Col>
|
|
<Col span={24}>
|
|
<Form.Select
|
|
field='level2_categories'
|
|
label={t('二级分类(可多选)')}
|
|
placeholder={
|
|
selectedLevel1Keys.length > 0
|
|
? t('选择二级分类')
|
|
: t('请先选择一级分类')
|
|
}
|
|
optionList={level2Categories.map((cat) => ({
|
|
label: `${cat.parent_category_name} - ${cat.category_name}`,
|
|
value: cat.category_key,
|
|
}))}
|
|
multiple
|
|
maxTagCount={3}
|
|
showClear
|
|
disabled={selectedLevel1Keys.length === 0}
|
|
style={{ width: '100%' }}
|
|
extraText={t(
|
|
'根据选择的一级分类自动过滤二级分类,可多选',
|
|
)}
|
|
/>
|
|
</Col>
|
|
<Col span={24} className='console-model-endpoints'>
|
|
<JSONEditor
|
|
field='endpoints'
|
|
label={t('端点映射')}
|
|
placeholder={
|
|
'{\n "openai": {"path": "/v1/chat/completions", "method": "POST"}\n}'
|
|
}
|
|
value={values.endpoints}
|
|
onChange={(val) =>
|
|
formApiRef.current?.setValue('endpoints', val)
|
|
}
|
|
formApi={formApiRef.current}
|
|
editorType='object'
|
|
objectValueAutoSize={{ minRows: 3, maxRows: 8 }}
|
|
template={ENDPOINT_TEMPLATE}
|
|
templateLabel={t('填入模板')}
|
|
extraText={t('留空则使用默认端点;支持 {path, method}')}
|
|
extraFooter={
|
|
endpointGroups.length > 0 && (
|
|
<Space wrap>
|
|
{endpointGroups.map((group) => (
|
|
<Button
|
|
key={group.id}
|
|
size='small'
|
|
type='primary'
|
|
onClick={() => {
|
|
try {
|
|
const current =
|
|
formApiRef.current?.getValue(
|
|
'endpoints',
|
|
) || '';
|
|
let base = {};
|
|
if (current && current.trim())
|
|
base = JSON.parse(current);
|
|
const groupObj =
|
|
typeof group.items === 'string'
|
|
? JSON.parse(group.items || '{}')
|
|
: group.items || {};
|
|
const merged = { ...base, ...groupObj };
|
|
formApiRef.current?.setValue(
|
|
'endpoints',
|
|
JSON.stringify(merged, null, 2),
|
|
);
|
|
} catch (e) {
|
|
try {
|
|
const groupObj =
|
|
typeof group.items === 'string'
|
|
? JSON.parse(group.items || '{}')
|
|
: group.items || {};
|
|
formApiRef.current?.setValue(
|
|
'endpoints',
|
|
JSON.stringify(groupObj, null, 2),
|
|
);
|
|
} catch {}
|
|
}
|
|
}}
|
|
>
|
|
{group.name}
|
|
</Button>
|
|
))}
|
|
</Space>
|
|
)
|
|
}
|
|
/>
|
|
</Col>
|
|
<Col span={24}>
|
|
<Form.Switch
|
|
field='sync_official'
|
|
label={t('参与官方同步')}
|
|
extraText={t(
|
|
'关闭后,此模型将不会被“同步官方”自动覆盖或创建',
|
|
)}
|
|
size='large'
|
|
/>
|
|
</Col>
|
|
<Col span={24}>
|
|
<Form.Switch
|
|
field='status'
|
|
label={t('状态')}
|
|
size='large'
|
|
/>
|
|
</Col>
|
|
</Row>
|
|
</Card>
|
|
</div>
|
|
)}
|
|
</Form>
|
|
</Spin>
|
|
</SideSheet>
|
|
);
|
|
};
|
|
|
|
export default EditModelModal;
|