【代码优化】AI:聊天对话 index.vue 代码梳理 20%

pull/473/MERGE
YunaiV 2024-07-07 20:30:44 +08:00
parent f3777f6334
commit 1064bbe570
6 changed files with 198 additions and 210 deletions

View File

@ -2,7 +2,7 @@ import request from '@/config/axios'
// AI 聊天对话 VO
export interface ChatConversationVO {
id: string // ID 编号
id: number // ID 编号
userId: number // 用户编号
title: string // 对话标题
pinned: boolean // 是否置顶
@ -23,7 +23,7 @@ export interface ChatConversationVO {
// AI 聊天对话 API
export const ChatConversationApi = {
// 获得【我的】聊天对话
getChatConversationMy: async (id: string) => {
getChatConversationMy: async (id: number) => {
return await request.get({ url: `/ai/chat/conversation/get-my?id=${id}` })
},

View File

@ -19,22 +19,17 @@ export interface ChatMessageVO {
userAvatar: string // 创建时间
}
export interface ChatMessageSendVO {
conversationId: string // 对话编号
content: number // 聊天内容
}
// AI chat 聊天
export const ChatMessageApi = {
// 消息列表
messageList: async (conversationId: string | null) => {
getChatMessageListByConversationId: async (conversationId: number | null) => {
return await request.get({
url: `/ai/chat/message/list-by-conversation-id?conversationId=${conversationId}`
})
},
// 发送 send stream 消息
// TODO axios 可以么? https://apifox.com/apiskills/how-to-create-axios-stream/
// 发送 Stream 消息
// 为什么不用 axios 呢?因为它不支持 SSE 调用
sendStream: async (
conversationId: number,
content: string,
@ -70,7 +65,7 @@ export const ChatMessageApi = {
},
// 删除消息 - 对话所有消息
deleteByConversationId: async (conversationId: string) => {
deleteByConversationId: async (conversationId: number) => {
return await request.delete({
url: `/ai/chat/message/delete-by-conversation-id?conversationId=${conversationId}`
})

View File

@ -1,15 +1,16 @@
<!-- message 新增对话 -->
<template>
<div class="new-chat" >
<div class="new-chat">
<div class="box-center">
<div class="tip">点击下方按钮开始你的对话吧</div>
<div class="btns"><el-button type="primary" round @click="handlerNewChat"></el-button></div>
<div class="btns">
<el-button type="primary" round @click="handlerNewChat"></el-button>
</div>
</div>
</div>
</template>
<script setup lang="ts">
//
const emits = defineEmits(['onNewChat'])
@ -19,7 +20,6 @@ const emits = defineEmits(['onNewChat'])
const handlerNewChat = async () => {
await emits('onNewChat')
}
</script>
<style scoped lang="scss">
.new-chat {

View File

@ -98,7 +98,7 @@
<script setup lang="ts">
import { ChatConversationApi, ChatConversationVO } from '@/api/ai/chat/conversation'
import { ref } from 'vue'
import Role from './role/index.vue'
import Role from '../../role/index.vue'
import { Bottom, Top } from '@element-plus/icons-vue'
import roleAvatarDefaultImg from '@/assets/ai/gpt.svg'
@ -398,8 +398,7 @@ onMounted(async () => {
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 0 10px;
padding-top: 10px;
padding: 10px 10px 0;
overflow: hidden;
.btn-new-conversation {

View File

@ -8,7 +8,12 @@
v-loading="formLoading"
>
<el-form-item label="角色设定" prop="systemMessage">
<el-input type="textarea" v-model="formData.systemMessage" rows="4" placeholder="请输入角色设定" />
<el-input
type="textarea"
v-model="formData.systemMessage"
rows="4"
placeholder="请输入角色设定"
/>
</el-form-item>
<el-form-item label="模型" prop="modelId">
<el-select v-model="formData.modelId" placeholder="请选择模型">
@ -57,10 +62,9 @@ import { CommonStatusEnum } from '@/utils/constants'
import { ChatModelApi, ChatModelVO } from '@/api/ai/model/chatModel'
import { ChatConversationApi, ChatConversationVO } from '@/api/ai/chat/conversation'
/** AI 聊天角色 表单 */
/** AI 聊天对话的更新表单 */
defineOptions({ name: 'ChatConversationUpdateForm' })
const { t } = useI18n() //
const message = useMessage() //
const dialogVisible = ref(false) //

View File

@ -1,12 +1,12 @@
<template>
<el-container class="ai-layout">
<!-- 左侧对话列表 -->
<Conversation
<ConversationList
:active-id="activeConversationId"
ref="conversationRef"
ref="conversationListRef"
@onConversationCreate="handleConversationCreate"
@onConversationClick="handleConversationClick"
@onConversationClear="handlerConversationClear"
@onConversationClear="handleConversationClear"
@onConversationDelete="handlerConversationDelete"
/>
<!-- 右侧对话详情 -->
@ -14,7 +14,7 @@
<el-header class="header">
<div class="title">
{{ activeConversation?.title ? activeConversation?.title : '对话' }}
<span v-if="list.length">({{ list.length }})</span>
<span v-if="activeMessageList.length">({{ activeMessageList.length }})</span>
</div>
<div class="btns" v-if="activeConversation">
<el-button type="primary" bg plain size="small" @click="openChatConversationUpdateForm">
@ -35,14 +35,18 @@
<el-main class="main-container">
<div>
<div class="message-container">
<MessageLoading v-if="listLoading" />
<!-- 情况一消息加载中 -->
<MessageLoading v-if="activeMessageListLoading" />
<!-- 情况二未选中对话 -->
<MessageNewChat v-if="!activeConversation" @on-new-chat="handlerNewChat" />
<!-- 情况三消息列表为空 -->
<ChatEmpty
v-if="!listLoading && messageList.length === 0 && activeConversation"
v-if="!activeMessageListLoading && messageList.length === 0 && activeConversation"
@on-prompt="doSend"
/>
<!-- 情况四消息列表不为空 -->
<Message
v-if="!listLoading && messageList.length > 0"
v-if="!activeMessageListLoading && messageList.length > 0"
ref="messageRef"
:conversation="activeConversation"
:list="messageList"
@ -93,59 +97,182 @@
</el-footer>
</el-container>
<!-- ========= 额外组件 ========== -->
<!-- 更新对话 Form -->
<ChatConversationUpdateForm
ref="chatConversationUpdateFormRef"
@success="handlerTitleSuccess"
<ConversationUpdateForm
ref="conversationUpdateFormRef"
@success="handleConversationUpdateSuccess"
/>
</el-container>
</template>
<script setup lang="ts">
// TODO @fan index.vue index /ai/chat /ai/chat/manager
import Conversation from './Conversation.vue'
import { ChatMessageApi, ChatMessageVO } from '@/api/ai/chat/message'
import { ChatConversationApi, ChatConversationVO } from '@/api/ai/chat/conversation'
import ConversationList from './components/conversation/ConversationList.vue'
import ConversationUpdateForm from './components/conversation/ConversationUpdateForm.vue'
import Message from './Message.vue'
import ChatEmpty from './ChatEmpty.vue'
import MessageLoading from './MessageLoading.vue'
import MessageNewChat from './MessageNewChat.vue'
import { ChatMessageApi, ChatMessageVO } from '@/api/ai/chat/message'
import { ChatConversationApi, ChatConversationVO } from '@/api/ai/chat/conversation'
import ChatConversationUpdateForm from './components/ChatConversationUpdateForm.vue'
import { Download, Top } from '@element-plus/icons-vue'
const route = useRoute() //
const message = useMessage() //
// ref
const activeConversationId = ref<string | null>(null) //
//
const conversationListRef = ref()
const activeConversationId = ref<number | null>(null) //
const activeConversation = ref<ChatConversationVO | null>(null) // Conversation
const conversationInProgress = ref(false) //
const conversationInProgress = ref(false) // true
//
const messageRef = ref()
const activeMessageList = ref<ChatMessageVO[]>([]) //
const activeMessageListLoading = ref<boolean>(false) // activeMessageList
const activeMessageListLoadingTimer = ref<any>() // activeMessageListLoading Timer
//
const textSpeed = ref<number>(50) // Typing speed in milliseconds
const textRoleRunning = ref<boolean>(false) // Typing speed in milliseconds
//
const isComposing = ref(false) //
const conversationInAbortController = ref<any>() // abort ( stream )
const inputTimeout = ref<any>() //
const prompt = ref<string>() // prompt
const enableContext = ref<boolean>(true) //
// TODO @fanfullText Text
// Stream
const fullText = ref('')
const displayedText = ref('')
const textSpeed = ref<number>(50) // Typing speed in milliseconds
const textRoleRunning = ref<boolean>(false) // Typing speed in milliseconds
// chat message
// TODO @fanlistlistLoadinglistLoadingTime
const list = ref<ChatMessageVO[]>([]) //
const listLoading = ref<boolean>(false) //
const listLoadingTime = ref<any>() // time
// =========== ===========
// ()
const messageRef = ref()
const conversationRef = ref()
const isComposing = ref(false) //
/** 获取对话信息 */
const getConversation = async (id: number | null) => {
if (!id) {
return
}
const conversation: ChatConversationVO = await ChatConversationApi.getChatConversationMy(id)
if (!conversation) {
return
}
activeConversation.value = conversation
activeConversationId.value = conversation.id
}
// role
const defaultRoleAvatar =
'http://test.yudao.iocoder.cn/eaef5f41acb911dd718429a0702dcc3c61160d16e57ba1d543132fab58934f9f.png'
/**
* 点击某个对话
*
* @param conversation 选中的对话
* @return 是否切换成功
*/
const handleConversationClick = async (conversation: ChatConversationVO) => {
//
if (conversationInProgress.value) {
message.alert('对话中,不允许切换!')
return false
}
// id
activeConversationId.value = conversation.id
activeConversation.value = conversation
//
// TODO @fan
if (conversationInProgress.value) {
await stopStream()
}
// message
await getMessageList()
//
scrollToBottom(true)
//
prompt.value = ''
return true
}
/** 删除某个对话*/
const handlerConversationDelete = async (delConversation: ChatConversationVO) => {
//
if (activeConversationId.value === delConversation.id) {
await handleConversationClear()
}
}
/** 清空选中的对话 */
const handleConversationClear = async () => {
// TODO @fan
activeConversationId.value = null
activeConversation.value = null
activeMessageList.value = []
}
/** 修改聊天对话 */
const conversationUpdateFormRef = ref()
const openChatConversationUpdateForm = async () => {
conversationUpdateFormRef.value.open(activeConversationId.value)
}
const handleConversationUpdateSuccess = async () => {
//
await getConversation(activeConversationId.value)
}
/** 处理聊天对话的创建成功 */
const handleConversationCreate = async () => {
//
prompt.value = ''
}
// =========== ===========
/** 获取消息 message 列表 */
const getMessageList = async () => {
try {
if (activeConversationId.value === null) {
return
}
// Timer
activeMessageListLoadingTimer.value = setTimeout(() => {
activeMessageListLoading.value = true
}, 60)
//
activeMessageList.value = await ChatMessageApi.getChatMessageListByConversationId(
activeConversationId.value
)
//
await nextTick()
scrollToBottom()
} finally {
// time
if (activeMessageListLoadingTimer.value) {
clearTimeout(activeMessageListLoadingTimer.value)
}
//
activeMessageListLoading.value = false
}
}
/**
* 消息列表
*
* {@link #getMessageList()} 的差异是 systemMessage 考虑进去
*/
const messageList = computed(() => {
if (activeMessageList.value.length > 0) {
return activeMessageList.value
}
// systemMessage
// TODO add by
if (activeConversation.value?.systemMessage) {
return [
{
id: 0,
type: 'system',
content: activeConversation.value.systemMessage
}
]
}
return []
})
// ===========
@ -184,10 +311,10 @@ const textRoll = async () => {
index++
// message
const lastMessage = list.value[list.value.length - 1]
const lastMessage = activeMessageList.value[activeMessageList.value.length - 1]
lastMessage.content = displayedText.value
// TODO @fanist.value ist.value.length
list.value[list.value - 1] = lastMessage
activeMessageList.value[activeMessageList.value - 1] = lastMessage
//
await scrollToBottom()
//
@ -314,7 +441,7 @@ const doSend = async (content: string) => {
}
const doSendStream = async (userMessage: ChatMessageVO) => {
// AbortController便
// AbortController 便
conversationInAbortController.value = new AbortController()
//
conversationInProgress.value = true
@ -322,14 +449,14 @@ const doSendStream = async (userMessage: ChatMessageVO) => {
fullText.value = ''
try {
// stream
list.value.push({
activeMessageList.value.push({
id: -1,
conversationId: activeConversationId.value,
type: 'user',
content: userMessage.content,
createTime: new Date()
} as ChatMessageVO)
list.value.push({
activeMessageList.value.push({
id: -2,
conversationId: activeConversationId.value,
type: 'system',
@ -366,11 +493,11 @@ const doSendStream = async (userMessage: ChatMessageVO) => {
if (isFirstMessage) {
isFirstMessage = false
//
list.value.pop()
list.value.pop()
activeMessageList.value.pop()
activeMessageList.value.pop()
//
list.value.push(data.send)
list.value.push(data.receive)
activeMessageList.value.push(data.send)
activeMessageList.value.push(data.receive)
}
// debugger
fullText.value = fullText.value + data.receive.content
@ -409,148 +536,15 @@ const stopStream = async () => {
// ============== message =================
/** 消息列表 */
const messageList = computed(() => {
if (list.value.length > 0) {
return list.value
}
// systemMessage
// TODO add by
if (activeConversation.value?.systemMessage) {
return [
{
id: 0,
type: 'system',
content: activeConversation.value.systemMessage
}
]
}
return []
})
// TODO @fan /** */= =
/**
* 获取 - message 列表
*/
const getMessageList = async () => {
try {
// time
listLoadingTime.value = setTimeout(() => {
listLoading.value = true
}, 60)
if (activeConversationId.value === null) {
return
}
//
list.value = await ChatMessageApi.messageList(activeConversationId.value)
//
await nextTick(() => {
//
scrollToBottom()
})
} finally {
// time
if (listLoadingTime.value) {
clearTimeout(listLoadingTime.value)
}
//
listLoading.value = false
}
}
/** 修改聊天对话 */
const chatConversationUpdateFormRef = ref()
const openChatConversationUpdateForm = async () => {
chatConversationUpdateFormRef.value.open(activeConversationId.value)
}
/**
* 对话 - 标题修改成功
*/
const handlerTitleSuccess = async () => {
// TODO
await getConversation(activeConversationId.value)
}
/**
* 对话 - 创建
*/
const handleConversationCreate = async () => {
//
prompt.value = ''
}
/**
* 对话 - 点击
*/
const handleConversationClick = async (conversation: ChatConversationVO) => {
//
if (conversationInProgress.value) {
await message.alert('对话中,不允许切换!')
return false
}
// id
activeConversationId.value = conversation.id
activeConversation.value = conversation
//
if (conversationInProgress.value) {
await stopStream()
}
// message
await getMessageList()
//
scrollToBottom(true)
//
prompt.value = ''
return true
}
/**
* 对话 - 清理全部对话
*/
const handlerConversationClear = async () => {
// TODO @fan
activeConversationId.value = null
activeConversation.value = null
list.value = []
}
/**
* 对话 - 删除
*/
const handlerConversationDelete = async (delConversation: ChatConversationVO) => {
//
if (activeConversationId.value === delConversation.id) {
await handlerConversationClear()
}
}
/**
* 对话 - 获取
*/
const getConversation = async (id: string | null) => {
if (!id) {
return
}
const conversation: ChatConversationVO = await ChatConversationApi.getChatConversationMy(id)
if (conversation) {
activeConversation.value = conversation
activeConversationId.value = conversation.id
}
}
/**
* 对话 - 新建
*/
// TODO @fan handleXXXhandler
const handlerNewChat = async () => {
//
await conversationRef.value.createConversation()
await conversationListRef.value.createConversation()
}
// ============ message ===========
/**
* 删除 message
*/
@ -595,7 +589,7 @@ const handlerMessageClear = async () => {
//
await message.delConfirm('确认清空对话消息?')
//
await ChatMessageApi.deleteByConversationId(activeConversationId.value as string)
await ChatMessageApi.deleteByConversationId(activeConversationId.value)
// TODO @fan
// message
await getMessageList()
@ -605,19 +599,19 @@ const handlerMessageClear = async () => {
onMounted(async () => {
// TODO conversationId
if (route.query.conversationId) {
const id = route.query.conversationId as string
const id = route.query.conversationId as unknown as number
activeConversationId.value = id
await getConversation(id)
}
//
listLoading.value = true
activeMessageListLoading.value = true
await getMessageList()
})
</script>
<style lang="scss" scoped>
.ai-layout {
// TODO @ height 100%
// TODO @ height 100% TODO @fan
position: absolute;
flex: 1;
top: 0;
@ -631,8 +625,7 @@ onMounted(async () => {
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 0 10px;
padding-top: 10px;
padding: 10px 10px 0;
.btn-new-conversation {
padding: 18px 0;
@ -771,8 +764,6 @@ onMounted(async () => {
bottom: 0;
left: 0;
right: 0;
//width: 100%;
//height: 100%;
overflow-y: hidden;
padding: 0;
margin: 0;
@ -803,8 +794,7 @@ onMounted(async () => {
border: none;
box-sizing: border-box;
resize: none;
padding: 0px 2px;
//padding: 5px 5px;
padding: 0 2px;
overflow: auto;
}
@ -815,7 +805,7 @@ onMounted(async () => {
.prompt-btns {
display: flex;
justify-content: space-between;
padding-bottom: 0px;
padding-bottom: 0;
padding-top: 5px;
}
}