import { modelsExpandKeysAtom } from '@/atoms/models'; import AutoTooltip from '@/components/auto-tooltip'; import DeleteModal from '@/components/delete-modal'; import DropdownButtons from '@/components/drop-down-buttons'; import IconFont from '@/components/icon-font'; import { PageSize } from '@/components/logs-viewer/config'; import PageTools from '@/components/page-tools'; import SealTable from '@/components/seal-table'; import SealColumn from '@/components/seal-table/components/seal-column'; import { PageAction } from '@/config'; import HotKeys from '@/config/hotkeys'; import useExpandedRowKeys from '@/hooks/use-expanded-row-keys'; import useTableRowSelection from '@/hooks/use-table-row-selection'; import useTableSort from '@/hooks/use-table-sort'; import { GPUDeviceItem, ListItem as WorkerListItem } from '@/pages/resources/config/types'; import { handleBatchRequest } from '@/utils'; import { AudioOutlined, DeleteOutlined, DownOutlined, EditOutlined, ExperimentOutlined, PictureOutlined, SyncOutlined, WechatWorkOutlined } from '@ant-design/icons'; import { PageContainer } from '@ant-design/pro-components'; import { Access, useAccess, useIntl, useNavigate } from '@umijs/max'; import { Button, Dropdown, Input, Select, Space, Tag, message } from 'antd'; import dayjs from 'dayjs'; import { useAtom } from 'jotai'; import _ from 'lodash'; import { memo, useCallback, useEffect, useRef, useState } from 'react'; import { useHotkeys } from 'react-hotkeys-hook'; import { MODELS_API, MODEL_INSTANCE_API, createModel, deleteModel, deleteModelInstance, queryModelInstancesList, updateModel } from '../apis'; import { InstanceRealLogStatus, getSourceRepoConfigValue, modelCategories, modelCategoriesMap, modelSourceMap } from '../config'; import { FormData, ListItem, ModelInstanceListItem } from '../config/types'; import DeployModal from './deploy-modal'; import InstanceItem from './instance-item'; import UpdateModel from './update-modal'; import ViewLogsModal from './view-logs-modal'; interface ModelsProps { handleSearch: () => void; handleNameChange: (e: any) => void; handleShowSizeChange?: (page: number, size: number) => void; handlePageChange: (page: number, pageSize: number | undefined) => void; handleDeleteSuccess: () => void; handleCategoryChange: (val: any) => void; onViewLogs: () => void; onCancelViewLogs: () => void; allInstances: ModelInstanceListItem[]; queryParams: { page: number; perPage: number; query?: string; categories?: string[]; }; deleteIds?: number[]; gpuDeviceList: GPUDeviceItem[]; workerList: WorkerListItem[]; dataSource: ListItem[]; loading: boolean; total: number; } const ActionList = [ { label: 'common.button.edit', key: 'edit', icon: }, { label: 'models.openinplayground', key: 'chat', icon: }, { label: 'common.button.stop', key: 'stop', icon: }, { label: 'common.button.start', key: 'start', icon: }, { label: 'common.button.delete', key: 'delete', props: { danger: true }, icon: } ]; const Models: React.FC = ({ handleNameChange, handleSearch, handlePageChange, handleDeleteSuccess, onViewLogs, onCancelViewLogs, handleCategoryChange, allInstances, deleteIds, dataSource, gpuDeviceList, workerList, queryParams, loading, total }) => { const [expandAtom, setExpandAtom] = useAtom(modelsExpandKeysAtom); const access = useAccess(); const intl = useIntl(); const navigate = useNavigate(); const rowSelection = useTableRowSelection(); const { handleExpandChange, updateExpandedRowKeys, removeExpandedRowKey, expandedRowKeys } = useExpandedRowKeys(expandAtom); const { sortOrder, setSortOrder } = useTableSort({ defaultSortOrder: 'descend' }); const [openLogModal, setOpenLogModal] = useState(false); const [openAddModal, setOpenAddModal] = useState(false); const [openDeployModal, setOpenDeployModal] = useState({ show: false, width: 600, source: modelSourceMap.huggingface_value }); const [currentData, setCurrentData] = useState({} as ListItem); const [currentInstance, setCurrentInstance] = useState<{ url: string; status: string; id?: number | string; modelId?: number | string; tail?: number; }>({ url: '', status: '' }); const modalRef = useRef(null); useHotkeys( HotKeys.NEW1.join(','), () => { setOpenDeployModal({ show: true, width: 'calc(100vw - 220px)', source: modelSourceMap.huggingface_value }); }, { preventDefault: true, enabled: !openAddModal && !openDeployModal.show && !openLogModal } ); useHotkeys( HotKeys.NEW3.join(','), () => { setOpenDeployModal({ show: true, width: 'calc(100vw - 220px)', source: modelSourceMap.modelscope_value }); }, { preventDefault: true, enabled: !openAddModal && !openDeployModal.show && !openLogModal } ); useHotkeys( HotKeys.NEW2.join(','), () => { setOpenDeployModal({ show: true, width: 600, source: modelSourceMap.ollama_library_value }); }, { preventDefault: true, enabled: !openAddModal && !openDeployModal.show && !openLogModal } ); useHotkeys( HotKeys.NEW4.join(','), () => { setOpenDeployModal({ show: true, width: 600, source: modelSourceMap.local_path_value }); }, { preventDefault: true, enabled: !openAddModal && !openDeployModal.show && !openLogModal } ); useEffect(() => { if (deleteIds?.length) { rowSelection.removeSelectedKey(deleteIds); } }, [deleteIds]); useEffect(() => { return () => { setExpandAtom([]); }; }, []); const sourceOptions = [ { label: intl.formatMessage({ id: 'menu.models.modelCatalog' }), value: 'catalog', key: 'catalog', icon: }, { label: 'Hugging Face', value: modelSourceMap.huggingface_value, key: 'huggingface', icon: }, { label: 'Ollama Library', value: modelSourceMap.ollama_library_value, key: 'ollama_library', icon: }, { label: 'ModelScope', value: modelSourceMap.modelscope_value, key: 'modelscope', icon: }, { label: intl.formatMessage({ id: 'models.form.localPath' }), value: modelSourceMap.local_path_value, key: 'local_path', icon: } ]; const setActionList = useCallback((record: ListItem) => { return _.filter(ActionList, (action: any) => { if (action.key === 'chat') { return record.ready_replicas > 0; } if (action.key === 'start') { return record.replicas === 0; } if (action.key === 'stop') { return record.replicas > 0; } return true; }); }, []); const handleOnSort = (dataIndex: string, order: any) => { setSortOrder(order); }; const handleOnCell = async (record: any, dataIndex: string) => { const params = { id: record.id, data: _.omit(record, [ 'id', 'ready_replicas', 'created_at', 'updated_at', 'rowIndex' ]) }; await updateModel(params); message.success(intl.formatMessage({ id: 'common.message.success' })); }; const handleStartModel = async (row: ListItem) => { try { await updateModel({ id: row.id, data: { ..._.omit(row, [ 'id', 'ready_replicas', 'created_at', 'updated_at', 'rowIndex' ]), replicas: 1 } }); message.success(intl.formatMessage({ id: 'common.message.success' })); updateExpandedRowKeys([row.id, ...expandedRowKeys]); } catch (error) { // ingore } }; const handleStopModel = async (row: ListItem) => { try { await updateModel({ id: row.id, data: { ..._.omit(row, [ 'id', 'ready_replicas', 'created_at', 'updated_at', 'rowIndex' ]), replicas: 0 } }); removeExpandedRowKey([row.id]); } catch (error) { // ingore } }; const handleModalOk = useCallback( async (data: FormData) => { try { const result = getSourceRepoConfigValue(currentData?.source, data); await updateModel({ data: { ...result.values, ..._.omit(data, result.omits) }, id: currentData?.id as number }); setOpenAddModal(false); message.success(intl.formatMessage({ id: 'common.message.success' })); handleSearch(); } catch (error) {} }, [currentData] ); const handleModalCancel = useCallback(() => { setOpenAddModal(false); }, []); const handleDeployModalCancel = () => { setOpenDeployModal({ ...openDeployModal, show: false }); }; const handleCreateModel = useCallback( async (data: FormData) => { try { console.log('data:', data, openDeployModal); const result = getSourceRepoConfigValue(openDeployModal.source, data); const modelData = await createModel({ data: { ...result.values, ..._.omit(data, result.omits) } }); setOpenDeployModal({ ...openDeployModal, show: false }); setTimeout(() => { updateExpandedRowKeys([modelData.id, ...expandedRowKeys]); }, 300); message.success(intl.formatMessage({ id: 'common.message.success' })); handleSearch?.(); } catch (error) {} }, [openDeployModal] ); const handleLogModalCancel = useCallback(() => { setOpenLogModal(false); onCancelViewLogs(); }, [onCancelViewLogs]); const handleDelete = async (row: any) => { modalRef.current.show({ content: 'models.table.models', operation: 'common.delete.single.confirm', name: row.name, async onOk() { await deleteModel(row.id); removeExpandedRowKey([row.id]); rowSelection.removeSelectedKey(row.id); handleDeleteSuccess(); handleSearch(); } }); }; const handleDeleteBatch = () => { modalRef.current.show({ content: 'models.table.models', operation: 'common.delete.confirm', selection: true, async onOk() { await handleBatchRequest(rowSelection.selectedRowKeys, deleteModel); rowSelection.clearSelections(); removeExpandedRowKey(rowSelection.selectedRowKeys); handleDeleteSuccess(); handleSearch(); } }); }; const handleOpenPlayGround = (row: any) => { if (row.categories?.includes(modelCategoriesMap.image)) { navigate(`/playground/text-to-image?model=${row.name}`); return; } if (row.categories?.includes(modelCategoriesMap.text_to_speech)) { navigate(`/playground/speech?model=${row.name}&type=tts`); return; } if (row.categories?.includes(modelCategoriesMap.speech_to_text)) { navigate(`/playground/speech?model=${row.name}&type=stt`); return; } if (row.categories?.includes(modelCategoriesMap.reranker)) { navigate(`/playground/rerank?model=${row.name}`); return; } if (row.categories?.includes(modelCategoriesMap.embedding)) { navigate(`/playground/embedding?model=${row.name}`); return; } navigate(`/playground/chat?model=${row.name}`); }; const handleViewLogs = useCallback( async (row: any) => { try { setCurrentInstance({ url: `${MODEL_INSTANCE_API}/${row.id}/logs`, status: row.state, id: row.id, modelId: row.model_id, tail: InstanceRealLogStatus.includes(row.state) ? undefined : PageSize }); setOpenLogModal(true); onViewLogs(); } catch (error) { console.log('error:', error); } }, [onViewLogs] ); const handleDeleteInstace = useCallback( (row: any, list: ModelInstanceListItem[]) => { modalRef.current.show({ content: 'models.instances', okText: 'common.button.delrecreate', operation: 'common.delete.single.confirm', name: row.name, async onOk() { await deleteModelInstance(row.id); } }); }, [deleteModelInstance] ); const getModelInstances = async (row: any, options?: any) => { const params = { id: row.id, page: 1, perPage: 100 }; const data = await queryModelInstancesList(params, { token: options?.token }); return data.items || []; }; const generateChildrenRequestAPI = (params: any) => { return `${MODELS_API}/${params.id}/instances`; }; const handleEdit = (row: ListItem) => { setCurrentData(row); setOpenAddModal(true); }; const handleSelect = useCallback( (val: any, row: ListItem) => { if (val === 'edit') { handleEdit(row); } if (val === 'chat') { handleOpenPlayGround(row); } if (val === 'delete') { handleDelete(row); } if (val === 'start') { handleStartModel(row); } if (val === 'stop') { modalRef.current.show({ content: 'models.instances', title: 'common.title.stop.confirm', okText: 'common.button.stop', operation: 'common.stop.single.confirm', name: row.name, async onOk() { await handleStopModel(row); } }); } }, [handleEdit, handleOpenPlayGround, handleDelete] ); const handleChildSelect = useCallback( (val: any, row: ModelInstanceListItem, list: ModelInstanceListItem[]) => { if (val === 'delete') { handleDeleteInstace(row, list); } if (val === 'viewlog') { handleViewLogs(row); } }, [handleViewLogs, handleDeleteInstace] ); const renderModelTags = useCallback( (record: ListItem) => { if (record.categories?.includes(modelCategoriesMap.reranker)) { return ( } style={{ margin: 0, opacity: 1, paddingInline: 8, borderRadius: 12, transform: 'scale(0.9)' }} color="cyan" > Reranker ); } if (record.categories?.includes(modelCategoriesMap.embedding)) { return ( } style={{ margin: 0, opacity: 1, paddingInline: 8, borderRadius: 12, transform: 'scale(0.9)' }} color="purple" > Embedding ); } if (record.categories?.includes(modelCategoriesMap.text_to_speech)) { return ( } style={{ margin: 0, opacity: 1, paddingInline: 8, borderRadius: 12, transform: 'scale(0.9)' }} color="geekblue" > Text-To-Speech ); } if (record.categories?.includes(modelCategoriesMap.speech_to_text)) { return ( } style={{ margin: 0, opacity: 1, paddingInline: 8, borderRadius: 12, transform: 'scale(0.9)' }} color="processing" > Speech-To-Text ); } if (record.categories?.includes(modelCategoriesMap.image)) { return ( } style={{ margin: 0, opacity: 1, paddingInline: 8, borderRadius: 12, transform: 'scale(0.9)' }} color="orange" > Image ); } if (record.categories?.includes(modelCategoriesMap.llm)) { return ( } style={{ margin: 0, opacity: 1, paddingInline: 8, borderRadius: 12, transform: 'scale(0.9)' }} color="green" > LLM ); } return null; }, [intl] ); const renderChildren = useCallback( (list: any, parent?: any) => { let childList = list; if (allInstances.length) { childList = list.filter((item: any) => { return allInstances.some((instance) => instance.id === item.id); }); } return ( ); }, [workerList, allInstances] ); const generateSource = useCallback((record: ListItem) => { if (record.source === modelSourceMap.modelscope_value) { return `${modelSourceMap.modelScope}/${record.model_scope_model_id}`; } if (record.source === modelSourceMap.huggingface_value) { return `${modelSourceMap.huggingface}/${record.huggingface_repo_id}`; } if (record.source === modelSourceMap.local_path_value) { return `${record.local_path}`; } if (record.source === modelSourceMap.ollama_library_value) { return `${modelSourceMap.ollama_library}/${record.ollama_library_model_name}`; } return ''; }, []); const handleClickDropdown = (item: any) => { if (item.key === 'huggingface') { setOpenDeployModal({ show: true, width: 'calc(100vw - 220px)', source: modelSourceMap.huggingface_value }); } if (item.key === 'ollama_library') { setOpenDeployModal({ show: true, width: 600, source: modelSourceMap.ollama_library_value }); } if (item.key === 'modelscope') { setOpenDeployModal({ show: true, width: 'calc(100vw - 220px)', source: modelSourceMap.modelscope_value }); } if (item.key === 'local_path') { setOpenDeployModal({ show: true, width: 600, source: modelSourceMap.local_path_value }); } if (item.key === 'catalog') { navigate('/models/catalog'); } }; return ( <> } right={ } > { return ( {text} {renderModelTags(record)} ); }} /> { return ( {generateSource(record)} ); }} /> { return ( {record.ready_replicas} / {record.replicas} ); }} /> { return ( {dayjs(text).format('YYYY-MM-DD HH:mm:ss')} ); }} /> { return ( handleSelect(val, record)} > ); }} /> ); }; export default memo(Models);