add api tool

This commit is contained in:
xie7654
2025-07-11 11:00:37 +08:00
parent bd9f9c39e3
commit ec30340b43
12 changed files with 534 additions and 7 deletions

View File

@@ -0,0 +1,105 @@
# Generated by Django 5.2.1 on 2025-07-11 02:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("ai", "0002_alter_aiapikey_api_key_alter_aiapikey_create_time_and_more"),
]
operations = [
migrations.CreateModel(
name="Tool",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"remark",
models.CharField(
blank=True,
db_comment="备注",
help_text="备注",
max_length=256,
null=True,
verbose_name="备注",
),
),
(
"creator",
models.CharField(
blank=True,
db_comment="创建人",
help_text="创建人",
max_length=64,
null=True,
verbose_name="创建人",
),
),
(
"modifier",
models.CharField(
blank=True,
db_comment="修改人",
help_text="修改人",
max_length=64,
null=True,
verbose_name="修改人",
),
),
(
"update_time",
models.DateTimeField(
auto_now=True,
db_comment="修改时间",
help_text="修改时间",
null=True,
verbose_name="修改时间",
),
),
(
"create_time",
models.DateTimeField(
auto_now_add=True,
db_comment="创建时间",
help_text="创建时间",
null=True,
verbose_name="创建时间",
),
),
(
"is_deleted",
models.BooleanField(
db_comment="是否软删除",
default=False,
verbose_name="是否软删除",
),
),
("name", models.CharField(max_length=128, verbose_name="工具名称")),
(
"description",
models.CharField(
blank=True, max_length=256, null=True, verbose_name="工具描述"
),
),
("status", models.SmallIntegerField(verbose_name="状态")),
],
options={
"verbose_name": "AI 工具",
"verbose_name_plural": "AI 工具",
"db_table": "ai_tool",
},
),
migrations.AlterModelOptions(
name="aimodel",
options={"verbose_name": "模型配置", "verbose_name_plural": "模型配置"},
),
]

View File

@@ -59,3 +59,18 @@ class AIModel(CoreModel):
def __str__(self):
return self.name
class Tool(CoreModel):
""" AI 工具表 """
name = models.CharField(max_length=128, verbose_name="工具名称")
description = models.CharField(max_length=256, null=True, blank=True, verbose_name="工具描述")
status = models.SmallIntegerField(verbose_name="状态")
class Meta:
db_table = "ai_tool"
verbose_name = "AI 工具"
verbose_name_plural = verbose_name
def __str__(self):
return self.name

View File

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

View File

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

24
backend/ai/views/tool.py Normal file
View File

@@ -0,0 +1,24 @@
from ai.models import Tool
from utils.serializers import CustomModelSerializer
from utils.custom_model_viewSet import CustomModelViewSet
class ToolSerializer(CustomModelSerializer):
"""
AI 工具 序列化器
"""
class Meta:
model = Tool
fields = '__all__'
read_only_fields = ['id', 'create_time', 'update_time']
class ToolViewSet(CustomModelViewSet):
"""
AI 工具 视图集
"""
queryset = Tool.objects.filter(is_deleted=False).order_by('-id')
serializer_class = ToolSerializer
filterset_fields = ['id', 'remark', 'creator', 'modifier', 'is_deleted', 'name', 'description', 'status']
search_fields = ['name'] # 根据实际字段调整
ordering_fields = ['create_time', 'id']
ordering = ['-create_time']

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('ui.actionTitle.create') }}
</Button>
</template>
</Grid>

View File

@@ -1,11 +1,15 @@
{
"title": "AI Management",
"ai_api_key": {
"title": "API KEY",
"name": "API KEY"
"title": "KEY Management",
"name": "KEY Management"
},
"ai_model": {
"title": "MODEL CONFIG",
"name": "MODEL CONFIG"
"title": "MODEL Management",
"name": "MODEL Management"
},
"tool": {
"title": "TOOL Management",
"name": "TOOL Management"
}
}

View File

@@ -7,5 +7,9 @@
"ai_model": {
"title": "模型配置",
"name": "模型配置"
},
"tool": {
"title": "工具管理",
"name": "工具管理"
}
}

View File

@@ -0,0 +1,22 @@
import { BaseModel } from '#/models/base';
export namespace AiToolApi {
export interface AiTool {
id: number;
remark: string;
creator: string;
modifier: string;
update_time: string;
create_time: string;
is_deleted: boolean;
name: string;
description: string;
status: number;
}
}
export class AiToolModel extends BaseModel<AiToolApi.AiTool> {
constructor() {
super('/ai/tool/');
}
}

View File

@@ -0,0 +1,131 @@
import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';
import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn } from '#/adapter/vxe-table';
import type { AiToolApi } from '#/models/ai/tool';
import { z } from '#/adapter/form';
import { $t } from '#/locales';
import { op } from '#/utils/permission';
/**
* 获取编辑表单的字段配置
*/
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: 'Input',
fieldName: 'description',
label: '工具描述',
},
{
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: 'Input',
fieldName: 'remark',
label: '备注',
},
];
}
/**
* 获取编辑表单的字段配置
*/
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'name',
label: '工具名称',
},
{
component: 'Input',
fieldName: 'description',
label: '工具描述',
},
{
component: 'Select',
fieldName: 'status',
label: '状态',
componentProps: {
allowClear: true,
options: [
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
],
},
},
];
}
/**
* 获取表格列配置
* @description 使用函数的形式返回列数据而不是直接export一个Array常量是为了响应语言切换时重新翻译表头
* @param onActionClick 表格操作按钮点击事件
*/
export function useColumns(
onActionClick?: OnActionClickFn<AiToolApi.AiTool>,
): VxeTableGridOptions<AiToolApi.AiTool>['columns'] {
return [
{
field: 'id',
title: 'ID',
},
{
field: 'name',
title: '工具名称',
},
{
field: 'description',
title: '工具描述',
},
{
cellRender: {
name: 'CellTag',
},
field: 'status',
title: '状态',
},
{
field: 'remark',
title: '备注',
},
{
align: 'center',
cellRender: {
attrs: {
nameField: 'name',
nameTitle: $t('ai.tool.name'),
onClick: onActionClick,
},
name: 'CellOperation',
options: [op('ai:tool:edit', 'edit'), op('ai:tool: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 { AiToolApi } from '#/models/ai/tool';
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 { AiToolModel } from '#/models/ai/tool';
import { useColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const formModel = new AiToolModel();
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/**
* 编辑AI 工具
*/
function onEdit(row: AiToolApi.AiTool) {
formModalApi.setData(row).open();
}
/**
* 创建新AI 工具
*/
function onCreate() {
formModalApi.setData(null).open();
}
/**
* 删除AI 工具
*/
function onDelete(row: AiToolApi.AiTool) {
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<AiToolApi.AiTool>) {
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:tool: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 { AiToolApi } from '#/models/ai/tool';
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 { AiToolModel } from '#/models/ai/tool';
import { useSchema } from '../data';
const emit = defineEmits(['success']);
const formModel = new AiToolModel();
const formData = ref<AiToolApi.AiTool>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', [$t('ai.tool.name')])
: $t('ui.actionTitle.create', [$t('ai.tool.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<AiToolApi.AiTool>();
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>