添加聊天对话列表

This commit is contained in:
XIE7654
2025-07-18 11:34:20 +08:00
parent aef25112f6
commit c30db7d1ca
11 changed files with 470 additions and 4 deletions

View File

@@ -8,6 +8,8 @@ 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)
router.register(r'chat_conversation', views.ChatConversationViewSet)
urlpatterns = [
path('', include(router.urls)),

View File

@@ -3,9 +3,11 @@ __all__ = [
'AIModelViewSet',
'ToolViewSet',
'KnowledgeViewSet',
'ChatConversationViewSet',
]
from ai.views.ai_api_key import AIApiKeyViewSet
from ai.views.ai_model import AIModelViewSet
from ai.views.tool import ToolViewSet
from ai.views.knowledge import KnowledgeViewSet
from ai.views.chat_conversation import ChatConversationViewSet

View File

@@ -0,0 +1,39 @@
from rest_framework import serializers
from ai.models import ChatConversation
from utils.serializers import CustomModelSerializer
from utils.custom_model_viewSet import CustomModelViewSet
from django_filters import rest_framework as filters
class ChatConversationSerializer(CustomModelSerializer):
username = serializers.CharField(source='user.username', read_only=True)
"""
AI 聊天对话 序列化器
"""
class Meta:
model = ChatConversation
fields = '__all__'
read_only_fields = ['id', 'create_time', 'update_time']
class ChatConversationFilter(filters.FilterSet):
class Meta:
model = ChatConversation
fields = ['id', 'remark', 'creator', 'modifier', 'is_deleted', 'title', 'pinned', 'model',
'system_message', 'max_tokens', 'max_contexts']
class ChatConversationViewSet(CustomModelViewSet):
"""
AI 聊天对话 视图集
"""
queryset = ChatConversation.objects.filter(is_deleted=False).order_by('-id')
serializer_class = ChatConversationSerializer
filterset_class = ChatConversationFilter
search_fields = ['name'] # 根据实际字段调整
ordering_fields = ['create_time', 'id']
ordering = ['-create_time']
# 移入urls中

View File

@@ -14,7 +14,7 @@ class ${model_name}Serializer(CustomModelSerializer):
read_only_fields = ['id', 'create_time', 'update_time']
class $model_nameFilter(filters.FilterSet):
class ${model_name}Filter(filters.FilterSet):
class Meta:
model = $model_name
@@ -27,10 +27,12 @@ class ${model_name}ViewSet(CustomModelViewSet):
"""
queryset = $model_name.objects.filter(is_deleted=False).order_by('-id')
serializer_class = ${model_name}Serializer
filterset_class = [$filterset_fields]
filterset_class = ${model_name}Filter
search_fields = ['name'] # 根据实际字段调整
ordering_fields = ['create_time', 'id']
ordering = ['-create_time']
# 移入urls中
# router.register(r'${model_name_snake}', views.${model_name}ViewSet)
# 移入 __init__.py
# from ${app_name}.views.${model_name_snake} import ${model_name}ViewSet

View File

@@ -19,5 +19,9 @@
"chat": {
"title": "AI CHAT",
"name": "AI CHAT"
},
"chat_conversation": {
"title": "CHAT Management",
"name": "CHAT Management"
}
}

View File

@@ -19,5 +19,9 @@
"chat": {
"title": "AI对话",
"name": "AI对话"
},
"chat_conversation": {
"title": "对话列表",
"name": "对话列表"
}
}

View File

@@ -0,0 +1,30 @@
import { BaseModel } from '#/models/base';
export namespace AiChatConversationApi {
export interface AiChatConversation {
id: number;
remark: string;
creator: string;
modifier: string;
update_time: string;
create_time: string;
is_deleted: boolean;
title: string;
pinned: boolean;
pinned_time: string;
user: number;
role: number;
model_id: number;
model: string;
system_message: string;
temperature: any;
max_tokens: number;
max_contexts: number;
}
}
export class AiChatConversationModel extends BaseModel<AiChatConversationApi.AiChatConversation> {
constructor() {
super('/ai/chat_conversation/');
}
}

View File

@@ -151,7 +151,7 @@ export function useColumns(
cellRender: {
attrs: {
nameField: 'name',
nameTitle: $t('ai.ai_api_key.name'),
nameTitle: $t('ai.api_key.name'),
onClick: onActionClick,
},
name: 'CellOperation',

View File

@@ -0,0 +1,181 @@
import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';
import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn } from '#/adapter/vxe-table';
import type { AiChatConversationApi } from '#/models/ai/chat_conversation';
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: 'title',
label: '对话标题',
rules: z
.string()
.min(1, $t('ui.formRules.required', ['对话标题']))
.max(100, $t('ui.formRules.maxLength', ['对话标题', 100])),
},
{
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
options: [
{ label: '开启', value: 1 },
{ label: '关闭', value: 0 },
],
optionType: 'button',
},
defaultValue: 1,
fieldName: 'pinned',
label: '是否置顶',
},
{
component: 'Input',
fieldName: 'pinned_time',
label: '置顶时间',
},
{
component: 'Input',
fieldName: 'user',
label: '用户',
},
{
component: 'Input',
fieldName: 'role',
label: '聊天角色',
},
{
component: 'Input',
fieldName: 'model_id',
label: '向量模型编号',
},
{
component: 'Input',
fieldName: 'model',
label: '模型标识',
rules: z
.string()
.min(1, $t('ui.formRules.required', ['模型标识']))
.max(100, $t('ui.formRules.maxLength', ['模型标识', 100])),
},
{
component: 'Input',
fieldName: 'system_message',
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: '上下文的最大 Message 数量',
},
{
component: 'Input',
fieldName: 'remark',
label: '备注',
rules: z
.string()
.min(1, $t('ui.formRules.required', ['备注']))
.max(100, $t('ui.formRules.maxLength', ['备注', 100])),
},
];
}
/**
* 获取编辑表单的字段配置
*/
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
component: 'Input',
fieldName: 'title',
label: '对话标题',
},
{
component: 'Input',
fieldName: 'user',
label: '用户',
},
{
component: 'Input',
fieldName: 'model',
label: '模型标识',
},
];
}
/**
* 获取表格列配置
* @description 使用函数的形式返回列数据而不是直接export一个Array常量是为了响应语言切换时重新翻译表头
* @param onActionClick 表格操作按钮点击事件
*/
export function useColumns(
onActionClick?: OnActionClickFn<AiChatConversationApi.AiChatConversation>,
): VxeTableGridOptions<AiChatConversationApi.AiChatConversation>['columns'] {
return [
{
field: 'id',
title: 'ID',
},
{
field: 'username',
title: '用户',
},
{
field: 'role',
title: '聊天角色',
},
{
field: 'model_id',
title: '向量模型编号',
},
{
field: 'model',
title: '模型标识',
},
{
field: 'system_message',
title: '角色设定',
},
{
align: 'center',
cellRender: {
attrs: {
nameField: 'name',
nameTitle: $t('ai.chat_conversation.name'),
onClick: onActionClick,
},
name: 'CellOperation',
options: [
// op('ai:chat_conversation:edit', 'edit'),
// op('ai:chat_conversation:delete', 'delete'),
],
},
field: 'action',
fixed: 'right',
title: '操作',
width: 120,
},
];
}

View File

@@ -0,0 +1,123 @@
<script lang="ts" setup>
import type {
OnActionClickParams,
VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { AiChatConversationApi } from '#/models/ai/chat_conversation';
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 { AiChatConversationModel } from '#/models/ai/chat_conversation';
import { useColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
const formModel = new AiChatConversationModel();
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
/**
* 编辑AI 聊天对话
*/
function onEdit(row: AiChatConversationApi.AiChatConversation) {
formModalApi.setData(row).open();
}
/**
* 删除AI 聊天对话
*/
function onDelete(row: AiChatConversationApi.AiChatConversation) {
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<AiChatConversationApi.AiChatConversation>) {
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 聊天对话" />
</Page>
</template>

View File

@@ -0,0 +1,79 @@
<script lang="ts" setup>
import type { AiChatConversationApi } from '#/models/ai/chat_conversation';
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 { AiChatConversationModel } from '#/models/ai/chat_conversation';
import { useSchema } from '../data';
const emit = defineEmits(['success']);
const formModel = new AiChatConversationModel();
const formData = ref<AiChatConversationApi.AiChatConversation>();
const getTitle = computed(() => {
return formData.value?.id
? $t('ui.actionTitle.edit', [$t('ai.chat_conversation.name')])
: $t('ui.actionTitle.create', [$t('ai.chat_conversation.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<AiChatConversationApi.AiChatConversation>();
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>