添加知识库管理

This commit is contained in:
XIE7654
2025-07-15 10:21:18 +08:00
parent badba2662f
commit b82b38940b
14 changed files with 474 additions and 66 deletions

View File

@@ -7,6 +7,7 @@ router = routers.DefaultRouter()
router.register(r'ai_api_key', views.AIApiKeyViewSet)
router.register(r'ai_model', views.AIModelViewSet)
router.register(r'tool', views.ToolViewSet)
router.register(r'knowledge', views.KnowledgeViewSet)
urlpatterns = [
path('', include(router.urls)),

View File

@@ -2,8 +2,10 @@ __all__ = [
'AIApiKeyViewSet',
'AIModelViewSet',
'ToolViewSet',
'KnowledgeViewSet',
]
from ai.views.ai_api_key import AIApiKeyViewSet
from ai.views.ai_model import AIModelViewSet
from ai.views.tool import ToolViewSet
from ai.views.tool import ToolViewSet
from ai.views.knowledge import KnowledgeViewSet

View File

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

View File

@@ -11,5 +11,9 @@
"tool": {
"title": "TOOL Management",
"name": "TOOL Management"
},
"knowledge": {
"title": "KNOWLEDGE Management",
"name": "KNOWLEDGE Management"
}
}

View File

@@ -11,5 +11,9 @@
"tool": {
"title": "工具管理",
"name": "工具管理"
},
"knowledge": {
"title": "知识库管理",
"name": "知识库管理"
}
}

View File

@@ -0,0 +1,26 @@
import { BaseModel } from '#/models/base';
export namespace AiKnowledgeApi {
export interface AiKnowledge {
id: number;
remark: string;
creator: string;
modifier: string;
update_time: string;
create_time: string;
is_deleted: boolean;
name: string;
description: string;
embedding_model_id: number;
embedding_model: string;
top_k: number;
similarity_threshold: any;
status: number;
}
}
export class AiKnowledgeModel extends BaseModel<AiKnowledgeApi.AiKnowledge> {
constructor() {
super('/ai/knowledge/');
}
}

View File

@@ -16,6 +16,27 @@ const AiKeyModel = new AiAIApiKeyModel();
*/
export function useSchema(): VbenFormSchema[] {
return [
{
component: 'ApiSelect',
componentProps: {
api: () => AiKeyModel.list(),
class: 'w-full',
resultField: 'items',
labelField: 'name',
valueField: 'id',
},
fieldName: 'key',
label: 'API 秘钥',
},
{
component: 'Input',
fieldName: 'platform',
label: '模型平台',
rules: z
.string()
.min(1, $t('ui.formRules.required', ['模型平台']))
.max(100, $t('ui.formRules.maxLength', ['模型平台', 100])),
},
{
component: 'Input',
fieldName: 'name',
@@ -25,6 +46,20 @@ export function useSchema(): VbenFormSchema[] {
.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: 'InputNumber',
fieldName: 'sort',
label: '排序',
},
{
component: 'RadioGroup',
componentProps: {
@@ -39,41 +74,6 @@ export function useSchema(): VbenFormSchema[] {
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',

View File

@@ -0,0 +1,149 @@
import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';
import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn } from '#/adapter/vxe-table';
import type { AiKnowledgeApi } from '#/models/ai/knowledge';
import { z } from '#/adapter/form';
import { $t } from '#/locales';
import { format_datetime } from '#/utils/date';
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',
componentProps: { rows: 3, showCount: true },
fieldName: 'description',
label: '知识库描述',
rules: z
.string()
.max(500, $t('ui.formRules.maxLength', ['知识库描述', 500]))
.optional(),
},
{
component: 'Input',
fieldName: 'embedding_model_id',
label: '向量模型编号',
},
{
component: 'Input',
fieldName: 'embedding_model',
label: '向量模型标识',
rules: z
.string()
.min(1, $t('ui.formRules.required', ['向量模型标识']))
.max(100, $t('ui.formRules.maxLength', ['向量模型标识', 100])),
},
{ component: 'InputNumber', fieldName: 'top_k', label: 'topK' },
{
component: 'Input',
fieldName: 'similarity_threshold',
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: 'Select',
fieldName: 'status',
label: '状态',
componentProps: {
allowClear: true,
options: [
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
],
},
},
];
}
/**
* 获取表格列配置
* @description 使用函数的形式返回列数据而不是直接export一个Array常量是为了响应语言切换时重新翻译表头
* @param onActionClick 表格操作按钮点击事件
*/
export function useColumns(
onActionClick?: OnActionClickFn<AiKnowledgeApi.AiKnowledge>,
): VxeTableGridOptions<AiKnowledgeApi.AiKnowledge>['columns'] {
return [
{ field: 'id', title: 'ID' },
{ field: 'name', title: '知识库名称' },
{ field: 'description', title: '知识库描述' },
{ field: 'embedding_model_id', title: '向量模型编号' },
{ field: 'embedding_model', title: '向量模型标识' },
{ field: 'top_k', title: 'topK' },
{ field: 'similarity_threshold', title: '相似度阈值' },
{ field: 'status', title: '状态', cellRender: { name: 'CellTag' } },
{ field: 'remark', title: '备注' },
{
field: 'update_time',
title: '修改时间',
width: 150,
formatter: ({ cellValue }) => format_datetime(cellValue),
},
{
field: 'create_time',
title: '创建时间',
width: 150,
formatter: ({ cellValue }) => format_datetime(cellValue),
},
{
align: 'center',
cellRender: {
attrs: {
nameField: 'name',
nameTitle: $t('ai.knowledge.name'),
onClick: onActionClick,
},
name: 'CellOperation',
options: [
op('ai:knowledge:edit', 'edit'),
op('ai:knowledge: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 { AiKnowledgeApi } from '#/models/ai/knowledge';
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 { AiKnowledgeModel } from '#/models/ai/knowledge';
import { useColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const formModel = new AiKnowledgeModel();
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/**
* 编辑AI 知识库
*/
function onEdit(row: AiKnowledgeApi.AiKnowledge) {
formModalApi.setData(row).open();
}
/**
* 创建新AI 知识库
*/
function onCreate() {
formModalApi.setData(null).open();
}
/**
* 删除AI 知识库
*/
function onDelete(row: AiKnowledgeApi.AiKnowledge) {
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<AiKnowledgeApi.AiKnowledge>) {
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:knowledge: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 { AiKnowledgeApi } from '#/models/ai/knowledge';
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 { AiKnowledgeModel } from '#/models/ai/knowledge';
import { useSchema } from '../data';
const emit = defineEmits(['success']);
const formModel = new AiKnowledgeModel();
const formData = ref<AiKnowledgeApi.AiKnowledge>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', [$t('ai.knowledge.name')])
: $t('ui.actionTitle.create', [$t('ai.knowledge.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<AiKnowledgeApi.AiKnowledge>();
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>

View File

@@ -27,35 +27,25 @@ export function useSchema(): VbenFormSchema[] {
},
fieldName: 'dict_type',
label: '字典类型',
rules: z.any(),
},
{
component: 'Input',
fieldName: 'label',
label: '字典标签',
rules: z
.string()
.min(2, $t('ui.formRules.minLength', [$t('system.dict_data.type'), 2]))
.max(
20,
$t('ui.formRules.maxLength', [$t('system.dict_data.type'), 20]),
),
rules: z.string(),
},
{
component: 'Input',
fieldName: 'value',
label: '字典键值',
rules: z
.string()
.min(2, $t('ui.formRules.minLength', [$t('system.dict_data.type'), 2]))
.max(
50,
$t('ui.formRules.maxLength', [$t('system.dict_data.type'), 50]),
),
rules: z.string(),
},
{
component: 'InputNumber',
fieldName: 'sort',
label: '字典排序',
rules: z.number(),
},
{
component: 'ApiSelect',
@@ -119,10 +109,6 @@ export function useSchema(): VbenFormSchema[] {
},
fieldName: 'remark',
label: '备注',
rules: z
.string()
.max(50, $t('ui.formRules.maxLength', [$t('system.remark'), 50]))
.optional(),
},
];
}
@@ -140,7 +126,7 @@ export function useColumns(
align: 'left',
field: 'id',
fixed: 'left',
title: '字典编码',
title: 'id',
treeNode: true,
width: 150,
},

View File

@@ -23,7 +23,7 @@ const getTitle = computed(() => {
});
const route = useRoute();
const [Form, formApi] = useVbenForm({
layout: 'vertical',
layout: 'horizontal',
schema: useSchema(),
showDefaultActions: false,
});

View File

@@ -7,7 +7,7 @@ import type { SystemDictTypeApi } from '#/api/system/dict_type';
import { z } from '#/adapter/form';
import { $t } from '#/locales';
import { format_datetime } from '#/utils/date';
import {op} from "#/utils/permission";
import { op } from "#/utils/permission";
/**
* 获取编辑表单的字段配置。如果没有使用多语言可以直接export一个数组常量
@@ -30,13 +30,6 @@ export function useSchema(): VbenFormSchema[] {
component: 'Input',
fieldName: 'value',
label: '字典类型',
rules: z
.string()
.min(2, $t('ui.formRules.minLength', [$t('system.dict_type.value'), 2]))
.max(
20,
$t('ui.formRules.maxLength', [$t('system.dict_type.value'), 20]),
),
},
{
component: 'RadioGroup',
@@ -98,7 +91,6 @@ export function useColumns(
{
cellRender: {
name: 'CellTag',
},
field: 'status',
title: '状态',

View File

@@ -22,7 +22,7 @@ const getTitle = computed(() => {
});
const [Form, formApi] = useVbenForm({
layout: 'vertical',
layout: 'horizontal',
schema: useSchema(),
showDefaultActions: false,
});