add api model

This commit is contained in:
xie7654
2025-07-11 10:24:38 +08:00
parent c6e41c92ee
commit bd9f9c39e3
12 changed files with 498 additions and 5 deletions

View File

@@ -54,7 +54,7 @@ class AIModel(CoreModel):
class Meta:
db_table = "ai_model"
verbose_name = "AI 模型"
verbose_name = "模型配置"
verbose_name_plural = verbose_name
def __str__(self):

View File

@@ -5,6 +5,8 @@ from . import views
router = routers.DefaultRouter()
router.register(r'ai_api_key', views.AIApiKeyViewSet)
router.register(r'ai_model', views.AIModelViewSet)
urlpatterns = [
path('', include(router.urls)),

View File

@@ -1,5 +1,7 @@
__all__ = [
'AIApiKeyViewSet'
'AIApiKeyViewSet',
'AIModelViewSet',
]
from ai.views.ai_api_key import AIApiKeyViewSet
from ai.views.ai_api_key import AIApiKeyViewSet
from ai.views.ai_model import AIModelViewSet

View File

@@ -0,0 +1,28 @@
from rest_framework import serializers
from ai.models import AIModel
from utils.serializers import CustomModelSerializer
from utils.custom_model_viewSet import CustomModelViewSet
class AIModelSerializer(CustomModelSerializer):
api_key_name = serializers.CharField(source='key.name', read_only=True)
"""
AI 模型 序列化器
"""
class Meta:
model = AIModel
fields = '__all__'
read_only_fields = ['id', 'create_time', 'update_time']
class AIModelViewSet(CustomModelViewSet):
"""
AI 模型 视图集
"""
queryset = AIModel.objects.filter(is_deleted=False).select_related('key').order_by('-id')
serializer_class = AIModelSerializer
filterset_fields = ['id', 'remark', 'creator', 'modifier', 'is_deleted', 'name', 'sort', 'status', 'platform',
'model', 'max_tokens', 'max_contexts']
search_fields = ['name'] # 根据实际字段调整
ordering_fields = ['create_time', 'id']
ordering = ['-create_time']

View File

@@ -27,7 +27,6 @@ ${grid_form_fields}
];
}
/**
* 获取表格列配置
* @description 使用函数的形式返回列数据而不是直接export一个Array常量是为了响应语言切换时重新翻译表头

View File

@@ -133,7 +133,7 @@ function refreshGrid() {
v-permission="'${app_name}:${model_name_snake}:create'"
>
<Plus class="size-5" />
{{ $$t('ui.actionTitle.create', [$$t('${app_name}.${model_name_snake}.name')]) }}
{{ $t('ui.actionTitle.create') }}
</Button>
</template>
</Grid>

View File

@@ -3,5 +3,9 @@
"ai_api_key": {
"title": "API KEY",
"name": "API KEY"
},
"ai_model": {
"title": "MODEL CONFIG",
"name": "MODEL CONFIG"
}
}

View File

@@ -3,5 +3,9 @@
"ai_api_key": {
"title": "API 密钥",
"name": "API 密钥"
},
"ai_model": {
"title": "模型配置",
"name": "模型配置"
}
}

View File

@@ -0,0 +1,28 @@
import { BaseModel } from '#/models/base';
export namespace AiAIModelApi {
export interface AiAIModel {
id: number;
remark: string;
creator: string;
modifier: string;
update_time: string;
create_time: string;
is_deleted: boolean;
name: string;
sort: number;
status: number;
key: number;
platform: string;
model: string;
temperature: any;
max_tokens: number;
max_contexts: number;
}
}
export class AiAIModelModel extends BaseModel<AiAIModelApi.AiAIModel> {
constructor() {
super('/ai/ai_model/');
}
}

View File

@@ -0,0 +1,206 @@
import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';
import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn } from '#/adapter/vxe-table';
import type { AiAIModelApi } from '#/models/ai/ai_model';
import { z } from '#/adapter/form';
import { $t } from '#/locales';
import { AiAIApiKeyModel } from '#/models/ai/ai_api_key';
import { op } from '#/utils/permission';
const AiKeyModel = new AiAIApiKeyModel();
/**
* 获取编辑表单的字段配置
*/
export function useSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'name',
label: '模型名字',
rules: z
.string()
.min(1, $t('ui.formRules.required', ['模型名字']))
.max(100, $t('ui.formRules.maxLength', ['模型名字', 100])),
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: [
{ label: $t('common.enabled'), value: 1 },
{ label: $t('common.disabled'), value: 0 },
],
optionType: 'button',
},
defaultValue: 1,
fieldName: 'status',
label: $t('system.status'),
},
{
component: 'ApiSelect',
componentProps: {
api: () => AiKeyModel.list(),
class: 'w-full',
resultField: 'items',
labelField: 'name',
valueField: 'id',
},
fieldName: 'key',
label: 'API 秘钥',
},
{
component: 'InputNumber',
fieldName: 'sort',
label: '排序',
},
{
component: 'Input',
fieldName: 'platform',
label: '模型平台',
rules: z
.string()
.min(1, $t('ui.formRules.required', ['模型平台']))
.max(100, $t('ui.formRules.maxLength', ['模型平台', 100])),
},
{
component: 'Input',
fieldName: 'model',
label: '模型标识',
rules: z
.string()
.min(1, $t('ui.formRules.required', ['模型标识']))
.max(100, $t('ui.formRules.maxLength', ['模型标识', 100])),
},
{
component: 'Input',
fieldName: 'temperature',
label: '温度参数',
},
{
component: 'InputNumber',
fieldName: 'max_tokens',
label: '回复数 Token 数',
},
{
component: 'InputNumber',
fieldName: 'max_contexts',
label: '上下文数量',
},
{
component: 'Input',
fieldName: 'remark',
label: '备注',
},
];
}
/**
* 获取编辑表单的字段配置
*/
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'name',
label: '模型名字',
},
{
component: 'Select',
fieldName: 'status',
label: '状态',
componentProps: {
allowClear: true,
options: [
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
],
},
},
{
component: 'Input',
fieldName: 'platform',
label: '模型平台',
},
];
}
/**
* 获取表格列配置
* @description 使用函数的形式返回列数据而不是直接export一个Array常量是为了响应语言切换时重新翻译表头
* @param onActionClick 表格操作按钮点击事件
*/
export function useColumns(
onActionClick?: OnActionClickFn<AiAIModelApi.AiAIModel>,
): VxeTableGridOptions<AiAIModelApi.AiAIModel>['columns'] {
return [
{
field: 'id',
title: 'ID',
},
{
field: 'name',
title: '模型名字',
},
{
field: 'sort',
title: '排序',
},
{
cellRender: {
name: 'CellTag',
},
field: 'status',
title: '状态',
},
{
field: 'api_key_name',
title: 'API 秘钥',
},
{
field: 'platform',
title: '模型平台',
},
{
field: 'model',
title: '模型标识',
},
{
field: 'temperature',
title: '温度参数',
},
{
field: 'max_tokens',
title: 'Token 数量',
},
{
field: 'max_contexts',
title: 'Message 数量',
},
{
field: 'remark',
title: '备注',
},
{
align: 'center',
cellRender: {
attrs: {
nameField: 'name',
nameTitle: $t('ai.ai_model.name'),
onClick: onActionClick,
},
name: 'CellOperation',
options: [
op('ai:ai_model:edit', 'edit'),
op('ai:ai_model:delete', 'delete'),
],
},
field: 'action',
fixed: 'right',
title: '操作',
width: 120,
},
];
}

View File

@@ -0,0 +1,141 @@
<script lang="ts" setup>
import type {
OnActionClickParams,
VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { AiAIModelApi } from '#/models/ai/ai_model';
import { Page, useVbenModal } from '@vben/common-ui';
import { Plus } from '@vben/icons';
import { Button, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { $t } from '#/locales';
import { AiAIModelModel } from '#/models/ai/ai_model';
import { useColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const formModel = new AiAIModelModel();
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/**
* 编辑AI 模型
*/
function onEdit(row: AiAIModelApi.AiAIModel) {
formModalApi.setData(row).open();
}
/**
* 创建新AI 模型
*/
function onCreate() {
formModalApi.setData(null).open();
}
/**
* 删除AI 模型
*/
function onDelete(row: AiAIModelApi.AiAIModel) {
const hideLoading = message.loading({
content: '删除AI 模型',
duration: 0,
key: 'action_process_msg',
});
formModel
.delete(row.id)
.then(() => {
message.success({
content: '删除成功',
key: 'action_process_msg',
});
refreshGrid();
})
.catch(() => {
hideLoading();
});
}
/**
* 表格操作按钮的回调函数
*/
function onActionClick({
code,
row,
}: OnActionClickParams<AiAIModelApi.AiAIModel>) {
switch (code) {
case 'delete': {
onDelete(row);
break;
}
case 'edit': {
onEdit(row);
break;
}
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
submitOnChange: true,
},
gridEvents: {},
gridOptions: {
columns: useColumns(onActionClick),
height: 'auto',
keepSource: true,
pagerConfig: {
enabled: true,
},
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await formModel.list({
page: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
toolbarConfig: {
custom: true,
export: false,
refresh: { code: 'query' },
zoom: true,
search: true,
},
} as VxeTableGridOptions,
});
/**
* 刷新表格
*/
function refreshGrid() {
gridApi.query();
}
</script>
<template>
<Page auto-content-height>
<FormModal @success="refreshGrid" />
<Grid table-title="AI 模型">
<template #toolbar-tools>
<Button
type="primary"
@click="onCreate"
v-permission="'ai:ai_model:create'"
>
<Plus class="size-5" />
{{ $t('ui.actionTitle.create') }}
</Button>
</template>
</Grid>
</Page>
</template>

View File

@@ -0,0 +1,79 @@
<script lang="ts" setup>
import type { AiAIModelApi } from '#/models/ai/ai_model';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Button } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { $t } from '#/locales';
import { AiAIModelModel } from '#/models/ai/ai_model';
import { useSchema } from '../data';
const emit = defineEmits(['success']);
const formModel = new AiAIModelModel();
const formData = ref<AiAIModelApi.AiAIModel>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', [$t('ai.ai_model.name')])
: $t('ui.actionTitle.create', [$t('ai.ai_model.name')]);
});
const [Form, formApi] = useVbenForm({
layout: 'horizontal',
schema: useSchema(),
showDefaultActions: false,
});
function resetForm() {
formApi.resetForm();
formApi.setValues(formData.value || {});
}
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (valid) {
modalApi.lock();
const data = await formApi.getValues();
try {
await (formData.value?.id
? formModel.update(formData.value.id, data)
: formModel.create(data));
await modalApi.close();
emit('success');
} finally {
modalApi.lock(false);
}
}
},
onOpenChange(isOpen) {
if (isOpen) {
const data = modalApi.getData<AiAIModelApi.AiAIModel>();
if (data) {
formData.value = data;
formApi.setValues(formData.value);
}
}
},
});
</script>
<template>
<Modal :title="getTitle">
<Form />
<template #prepend-footer>
<div class="flex-auto">
<Button type="primary" danger @click="resetForm">
{{ $t('common.reset') }}
</Button>
</div>
</template>
</Modal>
</template>
<style lang="css" scoped></style>