Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
@@ -0,0 +1,277 @@
/*
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 React, { useState } from 'react';
import MissingModelsModal from './modals/MissingModelsModal';
import PrefillGroupManagement from './modals/PrefillGroupManagement';
import EditPrefillGroupModal from './modals/EditPrefillGroupModal';
import BatchCategoryModal from './modals/BatchCategoryModal';
import { Button, Modal, Popover } from '@douyinfe/semi-ui';
import { showSuccess, showError, copy, isRoot } from '../../../helpers';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
import SelectionNotification from './components/SelectionNotification';
import UpstreamConflictModal from './modals/UpstreamConflictModal';
import SyncWizardModal from './modals/SyncWizardModal';
const ModelsActions = ({
selectedKeys,
setSelectedKeys,
setEditingModel,
setShowEdit,
batchDeleteModels,
batchUpdateCategory,
syncing,
previewing,
syncUpstream,
previewUpstreamDiff,
applyUpstreamOverwrite,
compactMode,
setCompactMode,
t,
}) => {
// Modal states
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [showMissingModal, setShowMissingModal] = useState(false);
const [showGroupManagement, setShowGroupManagement] = useState(false);
const [showAddPrefill, setShowAddPrefill] = useState(false);
const [showCategoryModal, setShowCategoryModal] = useState(false);
const [prefillInit, setPrefillInit] = useState({ id: undefined });
const [showConflict, setShowConflict] = useState(false);
const [conflicts, setConflicts] = useState([]);
const [showSyncModal, setShowSyncModal] = useState(false);
const [syncLocale, setSyncLocale] = useState('zh');
const handleSyncUpstream = async (locale) => {
// 先预览
const data = await previewUpstreamDiff?.({ locale });
const conflictItems = data?.conflicts || [];
if (conflictItems.length > 0) {
setConflicts(conflictItems);
setShowConflict(true);
return;
}
// 无冲突,直接同步缺失
await syncUpstream?.({ locale });
};
// Handle delete selected models with confirmation
const handleDeleteSelectedModels = () => {
setShowDeleteModal(true);
};
// Handle delete confirmation
const handleConfirmDelete = () => {
batchDeleteModels();
setShowDeleteModal(false);
};
// Handle clear selection
const handleClearSelected = () => {
setSelectedKeys([]);
};
// Handle add selected models to prefill group
const handleCopyNames = async () => {
const text = selectedKeys.map((m) => m.model_name).join(',');
if (!text) return;
const ok = await copy(text);
if (ok) {
showSuccess(t('已复制模型名称'));
} else {
showError(t('复制失败'));
}
};
const handleAddToPrefill = () => {
// Prepare initial data
const items = selectedKeys.map((m) => m.model_name);
setPrefillInit({ id: undefined, type: 'model', items });
setShowAddPrefill(true);
};
return (
<>
<div className='flex flex-wrap gap-2 w-full md:w-auto order-2 md:order-1'>
{isRoot() && (
<Button
type='primary'
className='flex-1 md:flex-initial'
onClick={() => {
setEditingModel({
id: undefined,
});
setShowEdit(true);
}}
size='small'
>
{t('添加模型')}
</Button>
)}
<Button
type='secondary'
className='flex-1 md:flex-initial'
size='small'
onClick={() => setShowMissingModal(true)}
>
{t('未配置模型')}
</Button>
{isRoot() && (
<Popover
position='bottom'
trigger='hover'
content={
<div className='p-2 max-w-[360px]'>
<div className='text-[var(--semi-color-text-2)] text-sm'>
{t(
'模型社区需要大家的共同维护,如发现数据有误或想贡献新的模型数据,请访问:',
)}
</div>
<a
href='https://github.com/basellm/llm-metadata'
target='_blank'
rel='noreferrer'
className='text-blue-600 underline'
>
https://github.com/basellm/llm-metadata
</a>
</div>
}
>
<Button
type='secondary'
className='flex-1 md:flex-initial'
size='small'
loading={syncing || previewing}
onClick={() => {
setSyncLocale('zh');
setShowSyncModal(true);
}}
>
{t('同步')}
</Button>
</Popover>
)}
{isRoot() && (
<Button
type='secondary'
className='flex-1 md:flex-initial'
size='small'
onClick={() => setShowGroupManagement(true)}
>
{t('预填组管理')}
</Button>
)}
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
<SelectionNotification
selectedKeys={selectedKeys}
t={t}
onDelete={handleDeleteSelectedModels}
onAddPrefill={handleAddToPrefill}
onSetCategory={() => setShowCategoryModal(true)}
onClear={handleClearSelected}
onCopy={handleCopyNames}
/>
<Modal
title={t('批量删除模型')}
visible={showDeleteModal}
onCancel={() => setShowDeleteModal(false)}
onOk={handleConfirmDelete}
type='warning'
>
<div>
{t('确定要删除所选的 {{count}} 个模型吗?', {
count: selectedKeys.length,
})}
</div>
</Modal>
<SyncWizardModal
visible={showSyncModal}
onClose={() => setShowSyncModal(false)}
loading={syncing || previewing}
t={t}
onConfirm={async ({ option, locale }) => {
setSyncLocale(locale);
if (option === 'official') {
await handleSyncUpstream(locale);
}
setShowSyncModal(false);
}}
/>
<MissingModelsModal
visible={showMissingModal}
onClose={() => setShowMissingModal(false)}
onConfigureModel={(name) => {
setEditingModel({ id: undefined, model_name: name });
setShowEdit(true);
setShowMissingModal(false);
}}
t={t}
/>
<PrefillGroupManagement
visible={showGroupManagement}
onClose={() => setShowGroupManagement(false)}
/>
<EditPrefillGroupModal
visible={showAddPrefill}
onClose={() => setShowAddPrefill(false)}
editingGroup={prefillInit}
onSuccess={() => setShowAddPrefill(false)}
/>
<UpstreamConflictModal
visible={showConflict}
onClose={() => setShowConflict(false)}
conflicts={conflicts}
onSubmit={async (payload) => {
return await applyUpstreamOverwrite?.({
overwrite: payload,
locale: syncLocale,
});
}}
t={t}
loading={syncing}
/>
<BatchCategoryModal
visible={showCategoryModal}
onClose={() => setShowCategoryModal(false)}
selectedModels={selectedKeys}
onConfirm={batchUpdateCategory}
t={t}
/>
</>
);
};
export default ModelsActions;
@@ -0,0 +1,190 @@
/*
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 React, { useState, useEffect } from 'react';
import {
Card,
Row,
Col,
Typography,
Tag,
Spin,
Empty,
} from '@douyinfe/semi-ui';
import { API, showError } from '../../../helpers';
import { MODEL_CATEGORY_NAMES } from '../../../constants';
const { Title, Text } = Typography;
const ModelsCategoryStats = ({ t }) => {
const [stats, setStats] = useState({});
const [loading, setLoading] = useState(false);
const loadStats = async () => {
setLoading(true);
try {
const res = await API.get('/api/models/category-stats');
const { success, message, data } = res.data;
if (success) {
setStats(data || {});
} else {
showError(message || t('获取统计数据失败'));
}
} catch (error) {
console.error('Load category stats failed:', error);
showError(t('获取统计数据失败'));
}
setLoading(false);
};
useEffect(() => {
loadStats();
}, []);
const getCategoryColor = (category) => {
const colorMap = {
text_generation: 'blue',
image_generation: 'purple',
video_generation: 'pink',
audio_tts: 'cyan',
audio_stt: 'teal',
audio_generation: 'green',
embedding: 'violet',
multimodal: 'indigo',
rerank: 'orange',
other: 'grey',
};
return colorMap[category] || 'grey';
};
const totalModels = Object.values(stats).reduce(
(sum, count) => sum + count,
0,
);
if (loading) {
return (
<Card style={{ marginBottom: '16px' }}>
<div style={{ textAlign: 'center', padding: '20px' }}>
<Spin />
</div>
</Card>
);
}
if (totalModels === 0) {
return (
<Card style={{ marginBottom: '16px' }}>
<Empty description={t('暂无模型数据')} />
</Card>
);
}
return (
<Card
title={
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<Title heading={5} style={{ margin: 0 }}>
{t('模型分类统计')}
</Title>
<Tag color='blue' size='large'>
{t('总计')}: {totalModels}
</Tag>
</div>
}
style={{ marginBottom: '16px' }}
>
<Row gutter={[16, 16]}>
{Object.entries(MODEL_CATEGORY_NAMES).map(([category, name]) => {
const count = stats[category] || 0;
const percentage =
totalModels > 0 ? ((count / totalModels) * 100).toFixed(1) : 0;
return (
<Col key={category} xs={24} sm={12} md={8} lg={6} xl={4}>
<div
style={{
padding: '12px',
borderRadius: '8px',
background: 'var(--semi-color-fill-0)',
border: '1px solid var(--semi-color-border)',
transition: 'all 0.3s',
cursor: 'pointer',
}}
onMouseEnter={(e) => {
e.currentTarget.style.transform = 'translateY(-2px)';
e.currentTarget.style.boxShadow =
'0 4px 12px rgba(0,0,0,0.1)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.transform = 'translateY(0)';
e.currentTarget.style.boxShadow = 'none';
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '8px',
}}
>
<Tag
color={getCategoryColor(category)}
size='small'
style={{ marginRight: '8px' }}
>
{name}
</Tag>
</div>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'baseline',
}}
>
<Text
strong
style={{
fontSize: '24px',
color: 'var(--semi-color-text-0)',
}}
>
{count}
</Text>
<Text type='tertiary' size='small'>
{percentage}%
</Text>
</div>
</div>
</Col>
);
})}
</Row>
</Card>
);
};
export default ModelsCategoryStats;
@@ -0,0 +1,454 @@
/*
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 React from 'react';
import {
Button,
Space,
Tag,
Typography,
Modal,
Tooltip,
} from '@douyinfe/semi-ui';
import {
timestamp2string,
getLobeHubIcon,
stringToColor,
isRoot,
} from '../../../helpers';
import {
renderLimitedItems,
renderDescription,
} from '../../common/ui/RenderUtils';
const { Text } = Typography;
// Render timestamp
function renderTimestamp(timestamp) {
return <>{timestamp2string(timestamp)}</>;
}
// Render model icon column: prefer model.icon, then fallback to vendor icon
const renderModelIconCol = (record, vendorMap) => {
const iconKey = record?.icon || vendorMap[record?.vendor_id]?.icon;
if (!iconKey) return '-';
return (
<div className='flex items-center justify-center'>
{getLobeHubIcon(iconKey, 20)}
</div>
);
};
// Render vendor column with icon
const renderVendorTag = (vendorId, vendorMap, t) => {
if (!vendorId || !vendorMap[vendorId]) return '-';
const v = vendorMap[vendorId];
return (
<Tag
color='white'
shape='circle'
prefixIcon={getLobeHubIcon(v.icon || 'Layers', 14)}
>
{v.name}
</Tag>
);
};
// Render categories (multiple)
const renderCategories = (categories, t, categoryNames) => {
if (!categories || categories.length === 0) {
return (
<Tag color='grey' size='small' shape='circle'>
{t('未分类')}
</Tag>
);
}
const colorMap = {
text_generation: 'blue',
image_generation: 'purple',
t_g_i: 'purple',
i_g_i: 'violet',
video_generation: 'pink',
t_g_v: 'pink',
i_g_v: 'red',
audio_tts: 'cyan',
audio_stt: 'teal',
audio_generation: 'green',
embedding: 'violet',
multimodal: 'indigo',
rerank: 'orange',
other: 'grey',
};
// If categories is a single string (legacy), convert to array
const categoriesArray = Array.isArray(categories) ? categories : [categories];
return renderLimitedItems({
items: categoriesArray,
renderItem: (category, idx) => {
const categoryName = categoryNames[category] || category;
return (
<Tag
key={idx}
color={colorMap[category] || 'grey'}
size='small'
shape='circle'
>
{categoryName}
</Tag>
);
},
maxDisplay: 3,
});
};
// Render groups (enable_groups)
const renderGroups = (groups) => {
if (!groups || groups.length === 0) return '-';
return renderLimitedItems({
items: groups,
renderItem: (g, idx) => (
<Tag key={idx} size='small' shape='circle' color={stringToColor(g)}>
{g}
</Tag>
),
});
};
// Render tags
const renderTags = (text) => {
if (!text) return '-';
const tagsArr = text.split(',').filter(Boolean);
return renderLimitedItems({
items: tagsArr,
renderItem: (tag, idx) => (
<Tag key={idx} size='small' shape='circle' color={stringToColor(tag)}>
{tag}
</Tag>
),
});
};
// Render endpoints (supports object map or legacy array)
const renderEndpoints = (value) => {
try {
const parsed = typeof value === 'string' ? JSON.parse(value) : value;
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
const keys = Object.keys(parsed || {});
if (keys.length === 0) return '-';
return renderLimitedItems({
items: keys,
renderItem: (key, idx) => (
<Tag key={idx} size='small' shape='circle' color={stringToColor(key)}>
{key}
</Tag>
),
maxDisplay: 3,
});
}
if (Array.isArray(parsed)) {
if (parsed.length === 0) return '-';
return renderLimitedItems({
items: parsed,
renderItem: (ep, idx) => (
<Tag key={idx} color='white' size='small' shape='circle'>
{ep}
</Tag>
),
maxDisplay: 3,
});
}
return value || '-';
} catch (_) {
return value || '-';
}
};
// Render quota types (array) using common limited items renderer
const renderQuotaTypes = (arr, t) => {
if (!Array.isArray(arr) || arr.length === 0) return '-';
return renderLimitedItems({
items: arr,
renderItem: (qt, idx) => {
if (qt === 1) {
return (
<Tag key={`${qt}-${idx}`} color='teal' size='small' shape='circle'>
{t('按次计费')}
</Tag>
);
}
if (qt === 0) {
return (
<Tag key={`${qt}-${idx}`} color='violet' size='small' shape='circle'>
{t('按量计费')}
</Tag>
);
}
if (qt === 2) {
return (
<Tag key={`${qt}-${idx}`} color='green' size='small' shape='circle'>
{t('按秒计费')}
</Tag>
);
}
if (qt === 3) {
return (
<Tag key={`${qt}-${idx}`} color='blue' size='small' shape='circle'>
{t('按分辨率计费')}
</Tag>
);
}
return (
<Tag key={`${qt}-${idx}`} color='white' size='small' shape='circle'>
{qt}
</Tag>
);
},
maxDisplay: 3,
});
};
// Render bound channels
const renderBoundChannels = (channels) => {
if (!channels || channels.length === 0) return '-';
return renderLimitedItems({
items: channels,
renderItem: (c, idx) => (
<Tag key={idx} color='white' size='small' shape='circle'>
{c.name}({c.type})
</Tag>
),
});
};
// Render operations column
const renderOperations = (
text,
record,
setEditingModel,
setShowEdit,
manageModel,
refresh,
t,
) => {
return (
<Space wrap>
{isRoot() && (
<>
{record.status === 1 ? (
<Button
type='danger'
size='small'
onClick={() => manageModel(record.id, 'disable', record)}
>
{t('禁用')}
</Button>
) : (
<Button
size='small'
onClick={() => manageModel(record.id, 'enable', record)}
>
{t('启用')}
</Button>
)}
<Button
type='tertiary'
size='small'
onClick={() => {
setEditingModel(record);
setShowEdit(true);
}}
>
{t('编辑')}
</Button>
<Button
type='danger'
size='small'
onClick={() => {
Modal.confirm({
title: t('确定是否要删除此模型?'),
content: t('此修改将不可逆'),
onOk: () => {
(async () => {
await manageModel(record.id, 'delete', record);
await refresh();
})();
},
});
}}
>
{t('删除')}
</Button>
</>
)}
</Space>
);
};
// 名称匹配类型渲染(带匹配数量 Tooltip)
const renderNameRule = (rule, record, t) => {
const map = {
0: { color: 'green', label: t('精确') },
1: { color: 'blue', label: t('前缀') },
2: { color: 'orange', label: t('包含') },
3: { color: 'purple', label: t('后缀') },
};
const cfg = map[rule];
if (!cfg) return '-';
let label = cfg.label;
if (rule !== 0 && record.matched_count) {
label = `${cfg.label} ${record.matched_count}${t('个模型')}`;
}
const tagElement = (
<Tag color={cfg.color} size='small' shape='circle'>
{label}
</Tag>
);
if (
rule === 0 ||
!record.matched_models ||
record.matched_models.length === 0
) {
return tagElement;
}
return (
<Tooltip content={record.matched_models.join(', ')} showArrow>
{tagElement}
</Tooltip>
);
};
export const getModelsColumns = ({
t,
manageModel,
setEditingModel,
setShowEdit,
refresh,
vendorMap,
categoryNames = {},
}) => {
return [
{
title: t('图标'),
dataIndex: 'icon',
width: 70,
align: 'center',
render: (text, record) => renderModelIconCol(record, vendorMap),
},
{
title: t('模型名称'),
dataIndex: 'model_name',
render: (text) => (
<Text copyable onClick={(e) => e.stopPropagation()}>
{text}
</Text>
),
},
{
title: t('匹配类型'),
dataIndex: 'name_rule',
render: (val, record) => renderNameRule(val, record, t),
},
{
title: t('参与官方同步'),
dataIndex: 'sync_official',
render: (val) => (
<Tag size='small' shape='circle' color={val === 1 ? 'green' : 'orange'}>
{val === 1 ? t('是') : t('否')}
</Tag>
),
},
{
title: t('描述'),
dataIndex: 'description',
render: (text) => renderDescription(text, 200),
},
{
title: t('供应商'),
dataIndex: 'vendor_id',
render: (vendorId, record) => renderVendorTag(vendorId, vendorMap, t),
},
{
title: t('分类'),
dataIndex: 'categories',
render: (categories) => renderCategories(categories, t, categoryNames),
},
{
title: t('标签'),
dataIndex: 'tags',
render: renderTags,
},
{
title: t('端点'),
dataIndex: 'endpoints',
render: renderEndpoints,
},
{
title: t('已绑定渠道'),
dataIndex: 'bound_channels',
render: renderBoundChannels,
},
{
title: t('可用分组'),
dataIndex: 'enable_groups',
render: renderGroups,
},
{
title: t('计费类型'),
dataIndex: 'quota_types',
render: (qts) => renderQuotaTypes(qts, t),
},
{
title: t('创建时间'),
dataIndex: 'created_time',
render: (text, record, index) => {
return <div>{renderTimestamp(text)}</div>;
},
},
{
title: t('更新时间'),
dataIndex: 'updated_time',
render: (text, record, index) => {
return <div>{renderTimestamp(text)}</div>;
},
},
{
title: '',
dataIndex: 'operate',
fixed: 'right',
render: (text, record, index) =>
renderOperations(
text,
record,
setEditingModel,
setShowEdit,
manageModel,
refresh,
t,
),
},
];
};
@@ -0,0 +1,44 @@
/*
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 React from 'react';
import { Typography } from '@douyinfe/semi-ui';
import { Layers } from 'lucide-react';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
const { Text } = Typography;
const ModelsDescription = ({ compactMode, setCompactMode, t }) => {
return (
<div className='flex flex-col md:flex-row justify-between items-start md:items-center gap-2 w-full'>
<div className='flex items-center text-green-500'>
<Layers size={16} className='mr-2' />
<Text>{t('模型管理')}</Text>
</div>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
);
};
export default ModelsDescription;
@@ -0,0 +1,125 @@
/*
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 React, { useRef } from 'react';
import { Form, Button } from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
import { MODEL_CATEGORY_NAMES } from '../../../constants';
const ModelsFilters = ({
formInitValues,
setFormApi,
searchModels,
loading,
searching,
t,
}) => {
// Handle form reset and immediate search
const formApiRef = useRef(null);
const handleReset = () => {
if (!formApiRef.current) return;
formApiRef.current.reset();
setTimeout(() => {
searchModels();
}, 100);
};
return (
<Form
initValues={formInitValues}
getFormApi={(api) => {
setFormApi(api);
formApiRef.current = api;
}}
onSubmit={searchModels}
allowEmpty={true}
autoComplete='off'
layout='horizontal'
trigger='change'
stopValidateWithError={false}
className='w-full md:w-auto order-1 md:order-2'
>
<div className='flex flex-col md:flex-row items-center gap-2 w-full md:w-auto'>
<div className='relative w-full md:w-56'>
<Form.Input
field='searchKeyword'
prefix={<IconSearch />}
placeholder={t('搜索模型名称')}
showClear
pure
size='small'
/>
</div>
<div className='relative w-full md:w-56'>
<Form.Input
field='searchVendor'
prefix={<IconSearch />}
placeholder={t('搜索供应商')}
showClear
pure
size='small'
/>
</div>
<div className='relative w-full md:w-56'>
<Form.Select
field='searchCategory'
placeholder={t('选择分类')}
showClear
pure
size='small'
style={{ width: '100%' }}
>
<Form.Select.Option value=''>{t('全部分类')}</Form.Select.Option>
{Object.entries(MODEL_CATEGORY_NAMES).map(([key, name]) => (
<Form.Select.Option key={key} value={key}>
{name}
</Form.Select.Option>
))}
</Form.Select>
</div>
<div className='flex gap-2 w-full md:w-auto'>
<Button
type='tertiary'
htmlType='submit'
loading={loading || searching}
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('查询')}
</Button>
<Button
type='tertiary'
onClick={handleReset}
className='flex-1 md:flex-initial md:w-auto'
size='small'
>
{t('重置')}
</Button>
</div>
</div>
</Form>
);
};
export default ModelsFilters;
+121
View File
@@ -0,0 +1,121 @@
/*
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 React, { useMemo } from 'react';
import { Empty } from '@douyinfe/semi-ui';
import CardTable from '../../common/ui/CardTable';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../common/illustrations';
import { getModelsColumns } from './ModelsColumnDefs';
import { useModelCategories } from '../../../hooks/models/useModelCategories';
const ModelsTable = (modelsData) => {
const {
models,
loading,
activePage,
pageSize,
modelCount,
compactMode,
handlePageChange,
handlePageSizeChange,
rowSelection,
handleRow,
manageModel,
setEditingModel,
setShowEdit,
refresh,
vendorMap,
t,
} = modelsData;
// 加载分类名称映射
const { categoryNames } = useModelCategories();
// Get all columns
const columns = useMemo(() => {
return getModelsColumns({
t,
manageModel,
setEditingModel,
setShowEdit,
refresh,
vendorMap,
categoryNames,
});
}, [
t,
manageModel,
setEditingModel,
setShowEdit,
refresh,
vendorMap,
categoryNames,
]);
// Handle compact mode by removing fixed positioning
const tableColumns = useMemo(() => {
return compactMode
? columns.map((col) => {
if (col.dataIndex === 'operate') {
const { fixed, ...rest } = col;
return rest;
}
return col;
})
: columns;
}, [compactMode, columns]);
return (
<CardTable
columns={tableColumns}
dataSource={models}
scroll={compactMode ? undefined : { x: 'max-content' }}
pagination={{
currentPage: activePage,
pageSize: pageSize,
total: modelCount,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50, 100],
onPageSizeChange: handlePageSizeChange,
onPageChange: handlePageChange,
}}
hidePagination={true}
loading={loading}
rowSelection={rowSelection}
onRow={handleRow}
empty={
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('搜索无结果')}
style={{ padding: 30 }}
/>
}
className='rounded-xl overflow-hidden'
size='middle'
/>
);
};
export default ModelsTable;
+189
View File
@@ -0,0 +1,189 @@
/*
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 React from 'react';
import { Tabs, TabPane, Tag, Button, Dropdown, Modal } from '@douyinfe/semi-ui';
import { IconEdit, IconDelete } from '@douyinfe/semi-icons';
import {
getLobeHubIcon,
showError,
showSuccess,
isRoot,
} from '../../../helpers';
import { API } from '../../../helpers';
const ModelsTabs = ({
activeVendorKey,
setActiveVendorKey,
vendorCounts,
vendors,
loadModels,
activePage,
pageSize,
setActivePage,
setShowAddVendor,
setShowEditVendor,
setEditingVendor,
loadVendors,
t,
}) => {
const canManageVendors = isRoot();
const handleTabChange = (key) => {
setActiveVendorKey(key);
setActivePage(1);
loadModels(1, pageSize, key);
};
const handleEditVendor = (vendor, e) => {
e.stopPropagation(); // 阻止事件冒泡,避免触发tab切换
setEditingVendor(vendor);
setShowEditVendor(true);
};
const handleDeleteVendor = async (vendor, e) => {
e.stopPropagation(); // 阻止事件冒泡,避免触发tab切换
try {
const res = await API.delete(`/api/vendors/${vendor.id}`);
if (res.data.success) {
showSuccess(t('供应商删除成功'));
// 如果删除的是当前选中的供应商,切换到"全部"
if (activeVendorKey === String(vendor.id)) {
setActiveVendorKey('all');
loadModels(1, pageSize, 'all');
} else {
loadModels(activePage, pageSize, activeVendorKey);
}
loadVendors(); // 重新加载供应商列表
} else {
showError(res.data.message || t('删除失败'));
}
} catch (error) {
showError(error.response?.data?.message || t('删除失败'));
}
};
return (
<Tabs
activeKey={activeVendorKey}
type='card'
collapsible
onChange={handleTabChange}
className='mb-2'
tabBarExtraContent={
canManageVendors && (
<Button
type='primary'
size='small'
onClick={() => setShowAddVendor(true)}
>
{t('新增供应商')}
</Button>
)
}
>
<TabPane
itemKey='all'
tab={
<span className='flex items-center gap-2'>
{t('全部')}
<Tag
color={activeVendorKey === 'all' ? 'red' : 'grey'}
shape='circle'
>
{vendorCounts['all'] || 0}
</Tag>
</span>
}
/>
{vendors.map((vendor) => {
const key = String(vendor.id);
const count = vendorCounts[vendor.id] || 0;
return (
<TabPane
key={key}
itemKey={key}
tab={
<span className='flex items-center gap-2'>
{getLobeHubIcon(vendor.icon || 'Layers', 14)}
{vendor.name}
<Tag
color={activeVendorKey === key ? 'red' : 'grey'}
shape='circle'
>
{count}
</Tag>
{canManageVendors && (
<Dropdown
trigger='click'
position='bottomRight'
render={
<Dropdown.Menu>
<Dropdown.Item
icon={<IconEdit />}
onClick={(e) => handleEditVendor(vendor, e)}
>
{t('编辑')}
</Dropdown.Item>
<Dropdown.Item
type='danger'
icon={<IconDelete />}
onClick={(e) => {
e.stopPropagation();
Modal.confirm({
title: t('确认删除'),
content: t(
'确定要删除供应商 "{{name}}" 吗?此操作不可撤销。',
{ name: vendor.name },
),
onOk: () => handleDeleteVendor(vendor, e),
okText: t('删除'),
cancelText: t('取消'),
type: 'warning',
okType: 'danger',
});
}}
>
{t('删除')}
</Dropdown.Item>
</Dropdown.Menu>
}
onClickOutSide={(e) => e.stopPropagation()}
>
<Button
size='small'
type='tertiary'
theme='outline'
onClick={(e) => e.stopPropagation()}
>
{t('操作')}
</Button>
</Dropdown>
)}
</span>
}
/>
);
})}
</Tabs>
);
};
export default ModelsTabs;
@@ -0,0 +1,116 @@
/*
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 React, { useEffect } from 'react';
import { Notification, Button, Space, Typography } from '@douyinfe/semi-ui';
import { isRoot } from '../../../../helpers';
// 固定通知 ID,保持同一个实例即可避免闪烁
const NOTICE_ID = 'models-batch-actions';
/**
* SelectionNotification 选择通知组件
* 1. 当 selectedKeys.length > 0 时,使用固定 id 创建/更新通知
* 2. 当 selectedKeys 清空时关闭通知
*/
const SelectionNotification = ({
selectedKeys = [],
t,
onDelete,
onAddPrefill,
onSetCategory,
onClear,
onCopy,
}) => {
// 根据选中数量决定显示/隐藏或更新通知
useEffect(() => {
const selectedCount = selectedKeys.length;
if (selectedCount > 0) {
const titleNode = (
<Space wrap>
<span>{t('批量操作')}</span>
<Typography.Text type='tertiary' size='small'>
{t('已选择 {{count}} 个模型', { count: selectedCount })}
</Typography.Text>
</Space>
);
const content = (
<Space wrap>
<Button size='small' type='tertiary' theme='solid' onClick={onClear}>
{t('取消全选')}
</Button>
{isRoot() && (
<Button
size='small'
type='primary'
theme='solid'
onClick={onAddPrefill}
>
{t('加入预填组')}
</Button>
)}
{isRoot() && (
<Button
size='small'
type='warning'
theme='solid'
onClick={onSetCategory}
>
{t('设置分类')}
</Button>
)}
<Button size='small' type='secondary' theme='solid' onClick={onCopy}>
{t('复制名称')}
</Button>
{isRoot() && (
<Button size='small' type='danger' theme='solid' onClick={onDelete}>
{t('删除所选')}
</Button>
)}
</Space>
);
// 使用相同 id 更新通知(若已存在则就地更新,不存在则创建)
Notification.info({
id: NOTICE_ID,
title: titleNode,
content,
duration: 0, // 不自动关闭
position: 'bottom',
showClose: false,
});
} else {
// 取消全部勾选时关闭通知
Notification.close(NOTICE_ID);
}
}, [selectedKeys, t, onDelete, onAddPrefill, onSetCategory, onClear, onCopy]);
// 卸载时确保关闭通知
useEffect(() => {
return () => {
Notification.close(NOTICE_ID);
};
}, []);
return null; // 该组件不渲染可见内容
};
export default SelectionNotification;
+151
View File
@@ -0,0 +1,151 @@
/*
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 React from 'react';
import CardPro from '../../common/ui/CardPro';
import ModelsTable from './ModelsTable';
import ModelsActions from './ModelsActions';
import ModelsFilters from './ModelsFilters';
import ModelsTabs from './ModelsTabs';
import ModelsCategoryStats from './ModelsCategoryStats';
import EditModelModal from './modals/EditModelModal';
import EditVendorModal from './modals/EditVendorModal';
import { useModelsData } from '../../../hooks/models/useModelsData';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils';
const ModelsPage = () => {
const modelsData = useModelsData();
const isMobile = useIsMobile();
const {
// Edit state
showEdit,
editingModel,
closeEdit,
refresh,
// Actions state
selectedKeys,
setSelectedKeys,
setEditingModel,
setShowEdit,
batchDeleteModels,
// Filters state
formInitValues,
setFormApi,
searchModels,
loading,
searching,
// Description state
compactMode,
setCompactMode,
// Vendor state
showAddVendor,
setShowAddVendor,
showEditVendor,
setShowEditVendor,
editingVendor,
setEditingVendor,
loadVendors,
// Translation
t,
} = modelsData;
return (
<>
<EditModelModal
refresh={refresh}
editingModel={editingModel}
visiable={showEdit}
handleClose={closeEdit}
/>
<EditVendorModal
visible={showAddVendor || showEditVendor}
handleClose={() => {
setShowAddVendor(false);
setShowEditVendor(false);
setEditingVendor({ id: undefined });
}}
editingVendor={showEditVendor ? editingVendor : { id: undefined }}
refresh={() => {
loadVendors();
refresh();
}}
/>
<ModelsCategoryStats t={t} />
<CardPro
type='type3'
tabsArea={<ModelsTabs {...modelsData} />}
actionsArea={
<div className='flex flex-col md:flex-row justify-between items-center gap-2 w-full'>
<ModelsActions
selectedKeys={selectedKeys}
setSelectedKeys={setSelectedKeys}
setEditingModel={setEditingModel}
setShowEdit={setShowEdit}
batchDeleteModels={batchDeleteModels}
batchUpdateCategory={modelsData.batchUpdateCategory}
syncing={modelsData.syncing}
syncUpstream={modelsData.syncUpstream}
previewing={modelsData.previewing}
previewUpstreamDiff={modelsData.previewUpstreamDiff}
applyUpstreamOverwrite={modelsData.applyUpstreamOverwrite}
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
<div className='w-full md:w-full lg:w-auto order-1 md:order-2'>
<ModelsFilters
formInitValues={formInitValues}
setFormApi={setFormApi}
searchModels={searchModels}
loading={loading}
searching={searching}
t={t}
/>
</div>
</div>
}
paginationArea={createCardProPagination({
currentPage: modelsData.activePage,
pageSize: modelsData.pageSize,
total: modelsData.modelCount,
onPageChange: modelsData.handlePageChange,
onPageSizeChange: modelsData.handlePageSizeChange,
isMobile: isMobile,
t: modelsData.t,
})}
t={modelsData.t}
>
<ModelsTable {...modelsData} />
</CardPro>
</>
);
};
export default ModelsPage;
@@ -0,0 +1,191 @@
/*
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 React, { useState, useEffect } from 'react';
import { Modal, Select, Typography, Spin } from '@douyinfe/semi-ui';
import { API, showError } from '../../../../helpers';
const { Text } = Typography;
const BatchCategoryModal = ({
visible,
onClose,
selectedModels,
onConfirm,
t,
}) => {
const [selectedCategories, setSelectedCategories] = useState([]);
const [loading, setLoading] = useState(false);
const [categoriesLoading, setCategoriesLoading] = useState(false);
const [level1Categories, setLevel1Categories] = useState([]);
const [level2Categories, setLevel2Categories] = useState([]);
// 加载分类数据
const loadCategories = async () => {
setCategoriesLoading(true);
try {
const res = await API.get('/api/model_categories/flat');
const { success, data, message } = res.data;
if (success) {
const categoriesData = data || [];
// 分离一级和二级分类,只保留启用的分类
const level1 = categoriesData.filter(
(cat) => cat.parent_id === 0 && cat.status === 1,
);
const level2 = categoriesData.filter(
(cat) => cat.parent_id !== 0 && cat.status === 1,
);
setLevel1Categories(level1);
setLevel2Categories(level2);
} else {
showError(message || t('加载分类失败'));
}
} catch (error) {
showError(t('加载分类失败: ') + error.message);
} finally {
setCategoriesLoading(false);
}
};
// 当弹窗打开时加载分类
useEffect(() => {
if (visible) {
loadCategories();
}
}, [visible]);
const handleConfirm = async () => {
if (selectedCategories.length === 0) return;
setLoading(true);
try {
await onConfirm(selectedCategories);
setSelectedCategories([]);
onClose();
} finally {
setLoading(false);
}
};
const handleClose = () => {
setSelectedCategories([]);
onClose();
};
// 按一级分类分组二级分类
const groupedCategories = level1Categories
.map((level1) => {
const children = level2Categories.filter(
(level2) => level2.parent_id === level1.id,
);
return {
label: level1.category_name,
children: children.map((cat) => ({
label: cat.category_name,
value: cat.category_key,
})),
};
})
.filter((group) => group.children.length > 0); // 只显示有子分类的一级分类
return (
<Modal
title={t('批量设置模型分类')}
visible={visible}
onCancel={handleClose}
onOk={handleConfirm}
okText={t('确定')}
cancelText={t('取消')}
confirmLoading={loading}
okButtonProps={{ disabled: selectedCategories.length === 0 }}
>
<Spin spinning={categoriesLoading}>
<div className='space-y-4'>
<Text>
{t('已选择 {{count}} 个模型', { count: selectedModels.length })}
</Text>
<div className='mt-4'>
<Text strong style={{ display: 'block', marginBottom: '8px' }}>
{t('选择分类(可多选)')}:
</Text>
<Select
value={selectedCategories}
onChange={setSelectedCategories}
placeholder={
categoriesLoading
? t('加载中...')
: t('请选择一个或多个模型分类')
}
style={{ width: '100%' }}
multiple
maxTagCount={3}
showClear
disabled={categoriesLoading}
filter
>
{groupedCategories.map((group) => (
<Select.OptGroup key={group.label} label={group.label}>
{group.children.map((option) => (
<Select.Option key={option.value} value={option.value}>
{option.label}
</Select.Option>
))}
</Select.OptGroup>
))}
</Select>
<Text
type='tertiary'
size='small'
style={{ display: 'block', marginTop: '8px' }}
>
{t('提示:只显示二级分类,按一级分类分组')}
</Text>
</div>
{selectedModels.length > 0 && (
<div className='mt-4 p-3 bg-gray-50 dark:bg-gray-800 rounded'>
<Text type='secondary' size='small'>
{t('将为以下模型设置分类')}:
</Text>
<div className='mt-2 max-h-40 overflow-y-auto'>
{selectedModels.slice(0, 10).map((model, index) => (
<div key={model.id} className='text-sm py-1'>
• {model.model_name}
</div>
))}
{selectedModels.length > 10 && (
<Text type='tertiary' size='small'>
{t('...还有 {{count}} 个', {
count: selectedModels.length - 10,
})}
</Text>
)}
</div>
</div>
)}
</div>
</Spin>
</Modal>
);
};
export default BatchCategoryModal;
@@ -0,0 +1,696 @@
/*
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 React, { useState, useEffect, useRef, useMemo } from 'react';
import JSONEditor from '../../../common/ui/JSONEditor';
import {
SideSheet,
Form,
Button,
Space,
Spin,
Typography,
Card,
Tag,
Avatar,
Col,
Row,
} from '@douyinfe/semi-ui';
import { Save, X, FileText } from 'lucide-react';
import { IconLink } from '@douyinfe/semi-icons';
import { API, showError, showSuccess } from '../../../../helpers';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const { Text, Title } = 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 placement = useMemo(() => (isEdit ? 'right' : 'left'), [isEdit]);
// 供应商列表
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
placement={placement}
title={
<Space>
{isEdit ? (
<Tag color='blue' shape='circle'>
{t('更新')}
</Tag>
) : (
<Tag color='green' shape='circle'>
{t('新建')}
</Tag>
)}
<Title heading={4} className='m-0'>
{isEdit ? t('更新模型信息') : t('创建新的模型')}
</Title>
</Space>
}
bodyStyle={{ padding: '0' }}
visible={props.visiable}
width={isMobile ? '100%' : 600}
footer={
<div className='flex justify-end'>
<Space>
<Button
theme='solid'
className='!rounded-lg'
onClick={() => formApiRef.current?.submitForm()}
icon={<Save size={16} />}
loading={loading}
>
{t('提交')}
</Button>
<Button
theme='light'
className='!rounded-lg'
type='primary'
onClick={handleCancel}
icon={<X size={16} />}
>
{t('取消')}
</Button>
</Space>
</div>
}
closeIcon={null}
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='flex items-center mb-2'>
<Avatar size='small' color='green' className='mr-2 shadow-md'>
<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>
{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}>
<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'
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;
@@ -0,0 +1,274 @@
/*
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 React, { useState, useRef, useEffect } from 'react';
import JSONEditor from '../../../common/ui/JSONEditor';
import {
SideSheet,
Button,
Form,
Typography,
Space,
Tag,
Row,
Col,
Card,
Avatar,
Spin,
} from '@douyinfe/semi-ui';
import { IconLayers, IconSave, IconClose } from '@douyinfe/semi-icons';
import { API, showError, showSuccess } from '../../../../helpers';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const { Text, Title } = 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 EditPrefillGroupModal = ({
visible,
onClose,
editingGroup,
onSuccess,
}) => {
const { t } = useTranslation();
const isMobile = useIsMobile();
const [loading, setLoading] = useState(false);
const formRef = useRef(null);
const isEdit = editingGroup && editingGroup.id !== undefined;
const [selectedType, setSelectedType] = useState(editingGroup?.type || 'tag');
// 当外部传入的编辑组类型变化时同步 selectedType
useEffect(() => {
setSelectedType(editingGroup?.type || 'tag');
}, [editingGroup?.type]);
const typeOptions = [
{ label: t('模型组'), value: 'model' },
{ label: t('标签组'), value: 'tag' },
{ label: t('端点组'), value: 'endpoint' },
];
// 提交表单
const handleSubmit = async (values) => {
setLoading(true);
try {
const submitData = {
...values,
};
if (values.type === 'endpoint') {
submitData.items = values.items || '';
} else {
submitData.items = Array.isArray(values.items) ? values.items : [];
}
if (editingGroup.id) {
submitData.id = editingGroup.id;
const res = await API.put('/api/prefill_group', submitData);
if (res.data.success) {
showSuccess(t('更新成功'));
onSuccess();
} else {
showError(res.data.message || t('更新失败'));
}
} else {
const res = await API.post('/api/prefill_group', submitData);
if (res.data.success) {
showSuccess(t('创建成功'));
onSuccess();
} else {
showError(res.data.message || t('创建失败'));
}
}
} catch (error) {
showError(t('操作失败'));
}
setLoading(false);
};
return (
<SideSheet
placement='left'
title={
<Space>
{isEdit ? (
<Tag color='blue' shape='circle'>
{t('更新')}
</Tag>
) : (
<Tag color='green' shape='circle'>
{t('新建')}
</Tag>
)}
<Title heading={4} className='m-0'>
{isEdit ? t('更新预填组') : t('创建新的预填组')}
</Title>
</Space>
}
visible={visible}
onCancel={onClose}
width={isMobile ? '100%' : 600}
bodyStyle={{ padding: '0' }}
footer={
<div className='flex justify-end'>
<Space>
<Button
theme='solid'
className='!rounded-lg'
onClick={() => formRef.current?.submitForm()}
icon={<IconSave />}
loading={loading}
>
{t('提交')}
</Button>
<Button
theme='light'
className='!rounded-lg'
type='primary'
onClick={onClose}
icon={<IconClose />}
>
{t('取消')}
</Button>
</Space>
</div>
}
closeIcon={null}
>
<Spin spinning={loading}>
<Form
getFormApi={(api) => (formRef.current = api)}
initValues={{
name: editingGroup?.name || '',
type: editingGroup?.type || 'tag',
description: editingGroup?.description || '',
items: (() => {
try {
if (editingGroup?.type === 'endpoint') {
// 保持原始字符串
return typeof editingGroup?.items === 'string'
? editingGroup.items
: JSON.stringify(editingGroup.items || {}, null, 2);
}
return Array.isArray(editingGroup?.items)
? editingGroup.items
: [];
} catch {
return editingGroup?.type === 'endpoint' ? '' : [];
}
})(),
}}
onSubmit={handleSubmit}
>
<div className='p-2'>
{/* 基本信息 */}
<Card className='!rounded-2xl shadow-sm border-0'>
<div className='flex items-center mb-2'>
<Avatar size='small' color='green' className='mr-2 shadow-md'>
<IconLayers 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='name'
label={t('组名')}
placeholder={t('请输入组名')}
rules={[{ required: true, message: t('请输入组名') }]}
showClear
/>
</Col>
<Col span={24}>
<Form.Select
field='type'
label={t('类型')}
placeholder={t('选择组类型')}
optionList={typeOptions}
rules={[{ required: true, message: t('请选择组类型') }]}
style={{ width: '100%' }}
onChange={(val) => setSelectedType(val)}
/>
</Col>
<Col span={24}>
<Form.TextArea
field='description'
label={t('描述')}
placeholder={t('请输入组描述')}
rows={3}
showClear
/>
</Col>
<Col span={24}>
{selectedType === 'endpoint' ? (
<JSONEditor
field='items'
label={t('端点映射')}
value={
formRef.current?.getValue('items') ??
(typeof editingGroup?.items === 'string'
? editingGroup.items
: JSON.stringify(editingGroup.items || {}, null, 2))
}
onChange={(val) =>
formRef.current?.setValue('items', val)
}
editorType='object'
placeholder={
'{\n "openai": {"path": "/v1/chat/completions", "method": "POST"}\n}'
}
template={ENDPOINT_TEMPLATE}
templateLabel={t('填入模板')}
extraText={t('键为端点类型,值为路径和方法对象')}
/>
) : (
<Form.TagInput
field='items'
label={t('项目')}
placeholder={t('输入项目名称,按回车添加')}
addOnBlur
showClear
style={{ width: '100%' }}
/>
)}
</Col>
</Row>
</Card>
</div>
</Form>
</Spin>
</SideSheet>
);
};
export default EditPrefillGroupModal;
@@ -0,0 +1,186 @@
/*
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 React, { useState, useRef, useEffect } from 'react';
import { Modal, Form, Col, Row } from '@douyinfe/semi-ui';
import { API, showError, showSuccess } from '../../../../helpers';
import { Typography } from '@douyinfe/semi-ui';
import { IconLink } from '@douyinfe/semi-icons';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const EditVendorModal = ({ visible, handleClose, refresh, editingVendor }) => {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const formApiRef = useRef(null);
const isMobile = useIsMobile();
const isEdit = editingVendor && editingVendor.id !== undefined;
const getInitValues = () => ({
name: '',
description: '',
icon: '',
status: true,
});
const handleCancel = () => {
handleClose();
formApiRef.current?.reset();
};
const loadVendor = async () => {
if (!isEdit || !editingVendor.id) return;
setLoading(true);
try {
const res = await API.get(`/api/vendors/${editingVendor.id}`);
const { success, message, data } = res.data;
if (success) {
// 将数字状态转为布尔值
data.status = data.status === 1;
if (formApiRef.current) {
formApiRef.current.setValues({ ...getInitValues(), ...data });
}
} else {
showError(message);
}
} catch (error) {
showError(t('加载供应商信息失败'));
}
setLoading(false);
};
useEffect(() => {
if (visible) {
if (isEdit) {
loadVendor();
} else {
formApiRef.current?.setValues(getInitValues());
}
} else {
formApiRef.current?.reset();
}
}, [visible, editingVendor?.id]);
const submit = async (values) => {
setLoading(true);
try {
// 转换 status 为数字
const submitData = {
...values,
status: values.status ? 1 : 0,
};
if (isEdit) {
submitData.id = editingVendor.id;
const res = await API.put('/api/vendors/', submitData);
const { success, message } = res.data;
if (success) {
showSuccess(t('供应商更新成功!'));
refresh();
handleClose();
} else {
showError(t(message));
}
} else {
const res = await API.post('/api/vendors/', submitData);
const { success, message } = res.data;
if (success) {
showSuccess(t('供应商创建成功!'));
refresh();
handleClose();
} else {
showError(t(message));
}
}
} catch (error) {
showError(error.response?.data?.message || t('操作失败'));
}
setLoading(false);
};
return (
<Modal
title={isEdit ? t('编辑供应商') : t('新增供应商')}
visible={visible}
onOk={() => formApiRef.current?.submitForm()}
onCancel={handleCancel}
confirmLoading={loading}
size={isMobile ? 'full-width' : 'small'}
>
<Form
initValues={getInitValues()}
getFormApi={(api) => (formApiRef.current = api)}
onSubmit={submit}
>
<Row gutter={12}>
<Col span={24}>
<Form.Input
field='name'
label={t('供应商名称')}
placeholder={t('请输入供应商名称,如:OpenAI')}
rules={[{ required: true, message: t('请输入供应商名称') }]}
showClear
/>
</Col>
<Col span={24}>
<Form.TextArea
field='description'
label={t('描述')}
placeholder={t('请输入供应商描述')}
rows={3}
showClear
/>
</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.Switch field='status' label={t('状态')} initValue={true} />
</Col>
</Row>
</Form>
</Modal>
);
};
export default EditVendorModal;
@@ -0,0 +1,201 @@
/*
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 React, { useEffect, useState } from 'react';
import {
Modal,
Table,
Spin,
Button,
Typography,
Empty,
Input,
} from '@douyinfe/semi-ui';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../common/illustrations';
import { IconSearch } from '@douyinfe/semi-icons';
import { API, showError } from '../../../../helpers';
import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const MissingModelsModal = ({ visible, onClose, onConfigureModel, t }) => {
const [loading, setLoading] = useState(false);
const [missingModels, setMissingModels] = useState([]);
const [searchKeyword, setSearchKeyword] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const isMobile = useIsMobile();
const fetchMissing = async () => {
setLoading(true);
try {
const res = await API.get('/api/models/missing');
if (res.data.success) {
setMissingModels(res.data.data || []);
} else {
showError(res.data.message);
}
} catch (_) {
showError(t('获取未配置模型失败'));
}
setLoading(false);
};
useEffect(() => {
if (visible) {
fetchMissing();
setSearchKeyword('');
setCurrentPage(1);
} else {
setMissingModels([]);
}
}, [visible]);
// 过滤和分页逻辑
const filteredModels = missingModels.filter((model) =>
model.toLowerCase().includes(searchKeyword.toLowerCase()),
);
const dataSource = (() => {
const start = (currentPage - 1) * MODEL_TABLE_PAGE_SIZE;
const end = start + MODEL_TABLE_PAGE_SIZE;
return filteredModels.slice(start, end).map((model) => ({
model,
key: model,
}));
})();
const columns = [
{
title: t('模型名称'),
dataIndex: 'model',
render: (text) => (
<div className='flex items-center'>
<Typography.Text strong>{text}</Typography.Text>
</div>
),
},
{
title: '',
dataIndex: 'operate',
fixed: 'right',
width: 120,
render: (text, record) => (
<Button
type='primary'
size='small'
onClick={() => onConfigureModel(record.model)}
>
{t('配置')}
</Button>
),
},
];
return (
<Modal
title={
<div className='flex flex-col gap-2 w-full'>
<div className='flex items-center gap-2'>
<Typography.Text
strong
className='!text-[var(--semi-color-text-0)] !text-base'
>
{t('未配置的模型列表')}
</Typography.Text>
<Typography.Text type='tertiary' size='small'>
{t('共')} {missingModels.length} {t('个未配置模型')}
</Typography.Text>
</div>
</div>
}
visible={visible}
onCancel={onClose}
footer={null}
size={isMobile ? 'full-width' : 'medium'}
className='!rounded-lg'
>
<Spin spinning={loading}>
{missingModels.length === 0 && !loading ? (
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={
<IllustrationNoResultDark style={{ width: 150, height: 150 }} />
}
description={t('暂无缺失模型')}
style={{ padding: 30 }}
/>
) : (
<div className='missing-models-content'>
{/* 搜索框 */}
<div className='flex items-center justify-end gap-2 w-full mb-4'>
<Input
placeholder={t('搜索模型...')}
value={searchKeyword}
onChange={(v) => {
setSearchKeyword(v);
setCurrentPage(1);
}}
className='!w-full'
prefix={<IconSearch />}
showClear
/>
</div>
{/* 表格 */}
{filteredModels.length > 0 ? (
<Table
// 列宽合计远超窄屏视口;没有 scroll 时表格会压缩到 min-content 硬塞进去,
// 末尾的操作列落在视口外,且 iOS 上滚动条不可见、毫无可拖动提示
scroll={{ x: 'max-content' }}
columns={columns}
dataSource={dataSource}
pagination={{
currentPage: currentPage,
pageSize: MODEL_TABLE_PAGE_SIZE,
total: filteredModels.length,
showSizeChanger: false,
onPageChange: (page) => setCurrentPage(page),
}}
/>
) : (
<Empty
image={
<IllustrationNoResult style={{ width: 100, height: 100 }} />
}
darkModeImage={
<IllustrationNoResultDark
style={{ width: 100, height: 100 }}
/>
}
description={
searchKeyword ? t('未找到匹配的模型') : t('暂无缺失模型')
}
style={{ padding: 20 }}
/>
)}
</div>
)}
</Spin>
</Modal>
);
};
export default MissingModelsModal;
@@ -0,0 +1,308 @@
/*
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 React, { useState, useEffect } from 'react';
import {
SideSheet,
Button,
Typography,
Space,
Tag,
Popconfirm,
Card,
Avatar,
Spin,
Empty,
} from '@douyinfe/semi-ui';
import { IconPlus, IconLayers } from '@douyinfe/semi-icons';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../../common/illustrations';
import {
API,
showError,
showSuccess,
stringToColor,
} from '../../../../helpers';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import CardTable from '../../../common/ui/CardTable';
import EditPrefillGroupModal from './EditPrefillGroupModal';
import {
renderLimitedItems,
renderDescription,
} from '../../../common/ui/RenderUtils';
const { Text, Title } = Typography;
const PrefillGroupManagement = ({ visible, onClose }) => {
const { t } = useTranslation();
const isMobile = useIsMobile();
const [loading, setLoading] = useState(false);
const [groups, setGroups] = useState([]);
const [showEdit, setShowEdit] = useState(false);
const [editingGroup, setEditingGroup] = useState({ id: undefined });
const typeOptions = [
{ label: t('模型组'), value: 'model' },
{ label: t('标签组'), value: 'tag' },
{ label: t('端点组'), value: 'endpoint' },
];
// 加载组列表
const loadGroups = async () => {
setLoading(true);
try {
const res = await API.get('/api/prefill_group');
if (res.data.success) {
setGroups(res.data.data || []);
} else {
showError(res.data.message || t('获取组列表失败'));
}
} catch (error) {
showError(t('获取组列表失败'));
}
setLoading(false);
};
// 删除组
const deleteGroup = async (id) => {
try {
const res = await API.delete(`/api/prefill_group/${id}`);
if (res.data.success) {
showSuccess(t('删除成功'));
loadGroups();
} else {
showError(res.data.message || t('删除失败'));
}
} catch (error) {
showError(t('删除失败'));
}
};
// 编辑组
const handleEdit = (group = {}) => {
setEditingGroup(group);
setShowEdit(true);
};
// 关闭编辑
const closeEdit = () => {
setShowEdit(false);
setTimeout(() => {
setEditingGroup({ id: undefined });
}, 300);
};
// 编辑成功回调
const handleEditSuccess = () => {
closeEdit();
loadGroups();
};
// 表格列定义
const columns = [
{
title: t('组名'),
dataIndex: 'name',
key: 'name',
render: (text, record) => (
<Space>
<Text strong>{text}</Text>
<Tag color='white' shape='circle' size='small'>
{typeOptions.find((opt) => opt.value === record.type)?.label ||
record.type}
</Tag>
</Space>
),
},
{
title: t('描述'),
dataIndex: 'description',
key: 'description',
render: (text) => renderDescription(text, 150),
},
{
title: t('项目内容'),
dataIndex: 'items',
key: 'items',
render: (items, record) => {
try {
if (record.type === 'endpoint') {
const obj =
typeof items === 'string'
? JSON.parse(items || '{}')
: items || {};
const keys = Object.keys(obj);
if (keys.length === 0)
return <Text type='tertiary'>{t('暂无项目')}</Text>;
return renderLimitedItems({
items: keys,
renderItem: (key, idx) => (
<Tag
key={idx}
size='small'
shape='circle'
color={stringToColor(key)}
>
{key}
</Tag>
),
maxDisplay: 3,
});
}
const itemsArray =
typeof items === 'string' ? JSON.parse(items) : items;
if (!Array.isArray(itemsArray) || itemsArray.length === 0) {
return <Text type='tertiary'>{t('暂无项目')}</Text>;
}
return renderLimitedItems({
items: itemsArray,
renderItem: (item, idx) => (
<Tag
key={idx}
size='small'
shape='circle'
color={stringToColor(item)}
>
{item}
</Tag>
),
maxDisplay: 3,
});
} catch {
return <Text type='tertiary'>{t('数据格式错误')}</Text>;
}
},
},
{
title: '',
key: 'action',
fixed: 'right',
width: 140,
render: (_, record) => (
<Space>
<Button size='small' onClick={() => handleEdit(record)}>
{t('编辑')}
</Button>
<Popconfirm
title={t('确定删除此组?')}
onConfirm={() => deleteGroup(record.id)}
>
<Button size='small' type='danger'>
{t('删除')}
</Button>
</Popconfirm>
</Space>
),
},
];
useEffect(() => {
if (visible) {
loadGroups();
}
}, [visible]);
return (
<>
<SideSheet
placement='left'
title={
<Space>
<Tag color='blue' shape='circle'>
{t('管理')}
</Tag>
<Title heading={4} className='m-0'>
{t('预填组管理')}
</Title>
</Space>
}
visible={visible}
onCancel={onClose}
width={isMobile ? '100%' : 800}
bodyStyle={{ padding: '0' }}
closeIcon={null}
>
<Spin spinning={loading}>
<div className='p-2'>
<Card className='!rounded-2xl shadow-sm border-0'>
<div className='flex items-center mb-2'>
<Avatar size='small' color='blue' className='mr-2 shadow-md'>
<IconLayers size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('组列表')}</Text>
<div className='text-xs text-gray-600'>
{t('管理模型、标签、端点等预填组')}
</div>
</div>
</div>
<div className='flex justify-end mb-4'>
<Button
type='primary'
theme='solid'
size='small'
icon={<IconPlus />}
onClick={() => handleEdit()}
>
{t('新建组')}
</Button>
</div>
{groups.length > 0 ? (
<CardTable
columns={columns}
dataSource={groups}
rowKey='id'
hidePagination={true}
size='small'
scroll={{ x: 'max-content' }}
/>
) : (
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark
style={{ width: 150, height: 150 }}
/>
}
description={t('暂无预填组')}
style={{ padding: 30 }}
/>
)}
</Card>
</div>
</Spin>
</SideSheet>
{/* 编辑组件 */}
<EditPrefillGroupModal
visible={showEdit}
onClose={closeEdit}
editingGroup={editingGroup}
onSuccess={handleEditSuccess}
/>
</>
);
};
export default PrefillGroupManagement;
@@ -0,0 +1,132 @@
/*
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 React, { useEffect, useState } from 'react';
import { Modal, RadioGroup, Radio, Steps, Button } from '@douyinfe/semi-ui';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const SyncWizardModal = ({ visible, onClose, onConfirm, loading, t }) => {
const [step, setStep] = useState(0);
const [option, setOption] = useState('official');
const [locale, setLocale] = useState('zh');
const isMobile = useIsMobile();
useEffect(() => {
if (visible) {
setStep(0);
setOption('official');
setLocale('zh');
}
}, [visible]);
return (
<Modal
title={t('同步向导')}
visible={visible}
onCancel={onClose}
footer={
<div className='flex justify-end'>
{step === 1 && (
<Button onClick={() => setStep(0)}>{t('上一步')}</Button>
)}
<Button onClick={onClose}>{t('取消')}</Button>
{step === 0 && (
<Button
type='primary'
onClick={() => setStep(1)}
disabled={option !== 'official'}
>
{t('下一步')}
</Button>
)}
{step === 1 && (
<Button
type='primary'
theme='solid'
loading={loading}
onClick={async () => {
await onConfirm?.({ option, locale });
}}
>
{t('开始同步')}
</Button>
)}
</div>
}
width={isMobile ? '100%' : 'small'}
>
<div className='mb-3'>
<Steps type='basic' current={step} size='small'>
<Steps.Step title={t('选择方式')} description={t('选择同步来源')} />
<Steps.Step title={t('选择语言')} description={t('选择同步语言')} />
</Steps>
</div>
{step === 0 && (
<div className='mt-2 flex justify-center'>
<RadioGroup
value={option}
onChange={(e) => setOption(e?.target?.value ?? e)}
type='card'
direction='horizontal'
aria-label={t('同步方式选择')}
name='sync-mode-selection'
>
<Radio value='official' extra={t('从官方模型库同步')}>
{t('官方模型同步')}
</Radio>
<Radio value='config' extra={t('从配置文件同步')} disabled>
{t('配置文件同步')}
</Radio>
</RadioGroup>
</div>
)}
{step === 1 && (
<div className='mt-2'>
<div className='mb-2 text-[var(--semi-color-text-2)]'>
{t('请选择同步语言')}
</div>
<div className='flex justify-center'>
<RadioGroup
value={locale}
onChange={(e) => setLocale(e?.target?.value ?? e)}
type='card'
direction='horizontal'
aria-label={t('语言选择')}
name='sync-locale-selection'
>
<Radio value='en' extra='English'>
EN
</Radio>
<Radio value='zh' extra='中文'>
ZH
</Radio>
<Radio value='ja' extra='日本語'>
JA
</Radio>
</RadioGroup>
</div>
</div>
)}
</Modal>
);
};
export default SyncWizardModal;
@@ -0,0 +1,326 @@
/*
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 React, { useEffect, useMemo, useState, useCallback } from 'react';
import {
Modal,
Table,
Checkbox,
Typography,
Empty,
Tag,
Popover,
Input,
} from '@douyinfe/semi-ui';
import { MousePointerClick } from 'lucide-react';
import { hoverOrClickTrigger } from '../../../../helpers';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants';
import { IconSearch } from '@douyinfe/semi-icons';
const { Text } = Typography;
const FIELD_LABELS = {
description: '描述',
icon: '图标',
tags: '标签',
vendor: '供应商',
name_rule: '命名规则',
status: '状态',
};
const FIELD_KEYS = Object.keys(FIELD_LABELS);
const UpstreamConflictModal = ({
visible,
onClose,
conflicts = [],
onSubmit,
t,
loading = false,
}) => {
const [selections, setSelections] = useState({});
const isMobile = useIsMobile();
const [currentPage, setCurrentPage] = useState(1);
const [searchKeyword, setSearchKeyword] = useState('');
const formatValue = (v) => {
if (v === null || v === undefined) return '-';
if (typeof v === 'string') return v || '-';
try {
return JSON.stringify(v, null, 2);
} catch (_) {
return String(v);
}
};
useEffect(() => {
if (visible) {
const init = {};
conflicts.forEach((item) => {
init[item.model_name] = new Set();
});
setSelections(init);
setCurrentPage(1);
setSearchKeyword('');
} else {
setSelections({});
}
}, [visible, conflicts]);
const toggleField = useCallback((modelName, field, checked) => {
setSelections((prev) => {
const next = { ...prev };
const set = new Set(next[modelName] || []);
if (checked) set.add(field);
else set.delete(field);
next[modelName] = set;
return next;
});
}, []);
// 构造数据源与过滤后的数据源
const dataSource = useMemo(
() =>
(conflicts || []).map((c) => ({
key: c.model_name,
model_name: c.model_name,
fields: c.fields || [],
})),
[conflicts],
);
const filteredDataSource = useMemo(() => {
const kw = (searchKeyword || '').toLowerCase();
if (!kw) return dataSource;
return dataSource.filter((item) =>
(item.model_name || '').toLowerCase().includes(kw),
);
}, [dataSource, searchKeyword]);
// 列头工具:当前过滤范围内可操作的行集合/勾选状态/批量设置
const getPresentRowsForField = useCallback(
(fieldKey) =>
(filteredDataSource || []).filter((row) =>
(row.fields || []).some((f) => f.field === fieldKey),
),
[filteredDataSource],
);
const getHeaderState = useCallback(
(fieldKey) => {
const presentRows = getPresentRowsForField(fieldKey);
const selectedCount = presentRows.filter((row) =>
selections[row.model_name]?.has(fieldKey),
).length;
const allCount = presentRows.length;
return {
headerChecked: allCount > 0 && selectedCount === allCount,
headerIndeterminate: selectedCount > 0 && selectedCount < allCount,
hasAny: allCount > 0,
};
},
[getPresentRowsForField, selections],
);
const applyHeaderChange = useCallback(
(fieldKey, checked) => {
setSelections((prev) => {
const next = { ...prev };
getPresentRowsForField(fieldKey).forEach((row) => {
const set = new Set(next[row.model_name] || []);
if (checked) set.add(fieldKey);
else set.delete(fieldKey);
next[row.model_name] = set;
});
return next;
});
},
[getPresentRowsForField],
);
const columns = useMemo(() => {
const base = [
{
title: t('模型'),
dataIndex: 'model_name',
fixed: 'left',
render: (text) => <Text strong>{text}</Text>,
},
];
const cols = FIELD_KEYS.map((fieldKey) => {
const rawLabel = FIELD_LABELS[fieldKey] || fieldKey;
const label = t(rawLabel);
const { headerChecked, headerIndeterminate, hasAny } =
getHeaderState(fieldKey);
if (!hasAny) return null;
const onHeaderChange = (e) =>
applyHeaderChange(fieldKey, e?.target?.checked);
return {
title: (
<div className='flex items-center gap-2'>
<Checkbox
checked={headerChecked}
indeterminate={headerIndeterminate}
onChange={onHeaderChange}
/>
<Text>{label}</Text>
</div>
),
dataIndex: fieldKey,
render: (_, record) => {
const f = (record.fields || []).find((x) => x.field === fieldKey);
if (!f) return <Text type='tertiary'>-</Text>;
const checked = selections[record.model_name]?.has(fieldKey) || false;
return (
<Checkbox
checked={checked}
onChange={(e) =>
toggleField(record.model_name, fieldKey, e?.target?.checked)
}
>
<Popover
// 触屏没有 hover:不改的话用户只能盲勾「覆盖」而看不到差异
trigger={hoverOrClickTrigger()}
position='top'
content={
<div className='p-2 max-w-[520px]'>
<div className='mb-2'>
<Text type='tertiary' size='small'>
{t('本地')}
</Text>
<pre className='whitespace-pre-wrap m-0'>
{formatValue(f.local)}
</pre>
</div>
<div>
<Text type='tertiary' size='small'>
{t('官方')}
</Text>
<pre className='whitespace-pre-wrap m-0'>
{formatValue(f.upstream)}
</pre>
</div>
</div>
}
>
<Tag
color='white'
size='small'
prefixIcon={<MousePointerClick size={14} />}
>
{t('点击查看差异')}
</Tag>
</Popover>
</Checkbox>
);
},
};
});
return [...base, ...cols.filter(Boolean)];
}, [
t,
selections,
filteredDataSource,
getHeaderState,
applyHeaderChange,
toggleField,
]);
const pagedDataSource = useMemo(() => {
const start = (currentPage - 1) * MODEL_TABLE_PAGE_SIZE;
const end = start + MODEL_TABLE_PAGE_SIZE;
return filteredDataSource.slice(start, end);
}, [filteredDataSource, currentPage]);
const handleOk = async () => {
const payload = Object.entries(selections)
.map(([modelName, set]) => ({
model_name: modelName,
fields: Array.from(set || []),
}))
.filter((x) => x.fields.length > 0);
const ok = await onSubmit?.(payload);
if (ok) onClose?.();
};
return (
<Modal
title={t('选择要覆盖的冲突项')}
visible={visible}
onCancel={onClose}
onOk={handleOk}
confirmLoading={loading}
okText={t('应用覆盖')}
cancelText={t('取消')}
width={isMobile ? '100%' : 1000}
>
{dataSource.length === 0 ? (
<Empty description={t('无冲突项')} className='p-6' />
) : (
<>
<div className='mb-3 text-[var(--semi-color-text-2)]'>
{t('仅会覆盖你勾选的字段,未勾选的字段保持本地不变。')}
</div>
{/* 搜索框 */}
<div className='flex items-center justify-end gap-2 w-full mb-4'>
<Input
placeholder={t('搜索模型...')}
value={searchKeyword}
onChange={(v) => {
setSearchKeyword(v);
setCurrentPage(1);
}}
className='!w-full'
prefix={<IconSearch />}
showClear
/>
</div>
{filteredDataSource.length > 0 ? (
<Table
columns={columns}
dataSource={pagedDataSource}
pagination={{
currentPage: currentPage,
pageSize: MODEL_TABLE_PAGE_SIZE,
total: filteredDataSource.length,
showSizeChanger: false,
onPageChange: (page) => setCurrentPage(page),
}}
scroll={{ x: 'max-content' }}
/>
) : (
<Empty
description={
searchKeyword ? t('未找到匹配的模型') : t('无冲突项')
}
className='p-6'
/>
)}
</>
)}
</Modal>
);
};
export default UpstreamConflictModal;