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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,12 +1,12 @@
<template> <template>
<el-container class="ai-layout"> <el-container class="ai-layout">
<!-- 左侧对话列表 --> <!-- 左侧对话列表 -->
<Conversation <ConversationList
:active-id="activeConversationId" :active-id="activeConversationId"
ref="conversationRef" ref="conversationListRef"
@onConversationCreate="handleConversationCreate" @onConversationCreate="handleConversationCreate"
@onConversationClick="handleConversationClick" @onConversationClick="handleConversationClick"
@onConversationClear="handlerConversationClear" @onConversationClear="handleConversationClear"
@onConversationDelete="handlerConversationDelete" @onConversationDelete="handlerConversationDelete"
/> />
<!-- 右侧对话详情 --> <!-- 右侧对话详情 -->
@ -14,7 +14,7 @@
<el-header class="header"> <el-header class="header">
<div class="title"> <div class="title">
{{ activeConversation?.title ? activeConversation?.title : '对话' }} {{ activeConversation?.title ? activeConversation?.title : '对话' }}
<span v-if="list.length">({{ list.length }})</span> <span v-if="activeMessageList.length">({{ activeMessageList.length }})</span>
</div> </div>
<div class="btns" v-if="activeConversation"> <div class="btns" v-if="activeConversation">
<el-button type="primary" bg plain size="small" @click="openChatConversationUpdateForm"> <el-button type="primary" bg plain size="small" @click="openChatConversationUpdateForm">
@ -35,14 +35,18 @@
<el-main class="main-container"> <el-main class="main-container">
<div> <div>
<div class="message-container"> <div class="message-container">
<MessageLoading v-if="listLoading" /> <!-- 情况一消息加载中 -->
<MessageLoading v-if="activeMessageListLoading" />
<!-- 情况二未选中对话 -->
<MessageNewChat v-if="!activeConversation" @on-new-chat="handlerNewChat" /> <MessageNewChat v-if="!activeConversation" @on-new-chat="handlerNewChat" />
<!-- 情况三消息列表为空 -->
<ChatEmpty <ChatEmpty
v-if="!listLoading && messageList.length === 0 && activeConversation" v-if="!activeMessageListLoading && messageList.length === 0 && activeConversation"
@on-prompt="doSend" @on-prompt="doSend"
/> />
<!-- 情况四消息列表不为空 -->
<Message <Message
v-if="!listLoading && messageList.length > 0" v-if="!activeMessageListLoading && messageList.length > 0"
ref="messageRef" ref="messageRef"
:conversation="activeConversation" :conversation="activeConversation"
:list="messageList" :list="messageList"
@ -93,59 +97,182 @@
</el-footer> </el-footer>
</el-container> </el-container>
<!-- ========= 额外组件 ========== -->
<!-- 更新对话 Form --> <!-- 更新对话 Form -->
<ChatConversationUpdateForm <ConversationUpdateForm
ref="chatConversationUpdateFormRef" ref="conversationUpdateFormRef"
@success="handlerTitleSuccess" @success="handleConversationUpdateSuccess"
/> />
</el-container> </el-container>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
// TODO @fan index.vue index /ai/chat /ai/chat/manager import { ChatMessageApi, ChatMessageVO } from '@/api/ai/chat/message'
import Conversation from './Conversation.vue' 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 Message from './Message.vue'
import ChatEmpty from './ChatEmpty.vue' import ChatEmpty from './ChatEmpty.vue'
import MessageLoading from './MessageLoading.vue' import MessageLoading from './MessageLoading.vue'
import MessageNewChat from './MessageNewChat.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' import { Download, Top } from '@element-plus/icons-vue'
const route = useRoute() // const route = useRoute() //
const message = useMessage() // 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 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 conversationInAbortController = ref<any>() // abort ( stream )
const inputTimeout = ref<any>() // const inputTimeout = ref<any>() //
const prompt = ref<string>() // prompt const prompt = ref<string>() // prompt
const enableContext = ref<boolean>(true) // const enableContext = ref<boolean>(true) //
// Stream
// TODO @fanfullText Text
const fullText = ref('') const fullText = ref('')
const displayedText = 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 getConversation = async (id: number | null) => {
const conversationRef = ref() if (!id) {
const isComposing = ref(false) // 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++ index++
// message // message
const lastMessage = list.value[list.value.length - 1] const lastMessage = activeMessageList.value[activeMessageList.value.length - 1]
lastMessage.content = displayedText.value lastMessage.content = displayedText.value
// TODO @fanist.value ist.value.length // TODO @fanist.value ist.value.length
list.value[list.value - 1] = lastMessage activeMessageList.value[activeMessageList.value - 1] = lastMessage
// //
await scrollToBottom() await scrollToBottom()
// //
@ -314,7 +441,7 @@ const doSend = async (content: string) => {
} }
const doSendStream = async (userMessage: ChatMessageVO) => { const doSendStream = async (userMessage: ChatMessageVO) => {
// AbortController便 // AbortController 便
conversationInAbortController.value = new AbortController() conversationInAbortController.value = new AbortController()
// //
conversationInProgress.value = true conversationInProgress.value = true
@ -322,14 +449,14 @@ const doSendStream = async (userMessage: ChatMessageVO) => {
fullText.value = '' fullText.value = ''
try { try {
// stream // stream
list.value.push({ activeMessageList.value.push({
id: -1, id: -1,
conversationId: activeConversationId.value, conversationId: activeConversationId.value,
type: 'user', type: 'user',
content: userMessage.content, content: userMessage.content,
createTime: new Date() createTime: new Date()
} as ChatMessageVO) } as ChatMessageVO)
list.value.push({ activeMessageList.value.push({
id: -2, id: -2,
conversationId: activeConversationId.value, conversationId: activeConversationId.value,
type: 'system', type: 'system',
@ -366,11 +493,11 @@ const doSendStream = async (userMessage: ChatMessageVO) => {
if (isFirstMessage) { if (isFirstMessage) {
isFirstMessage = false isFirstMessage = false
// //
list.value.pop() activeMessageList.value.pop()
list.value.pop() activeMessageList.value.pop()
// //
list.value.push(data.send) activeMessageList.value.push(data.send)
list.value.push(data.receive) activeMessageList.value.push(data.receive)
} }
// debugger // debugger
fullText.value = fullText.value + data.receive.content fullText.value = fullText.value + data.receive.content
@ -409,148 +536,15 @@ const stopStream = async () => {
// ============== message ================= // ============== 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 // TODO @fan handleXXXhandler
const handlerNewChat = async () => { const handlerNewChat = async () => {
// //
await conversationRef.value.createConversation() await conversationListRef.value.createConversation()
} }
// ============ message ===========
/** /**
* 删除 message * 删除 message
*/ */
@ -595,7 +589,7 @@ const handlerMessageClear = async () => {
// //
await message.delConfirm('确认清空对话消息?') await message.delConfirm('确认清空对话消息?')
// //
await ChatMessageApi.deleteByConversationId(activeConversationId.value as string) await ChatMessageApi.deleteByConversationId(activeConversationId.value)
// TODO @fan // TODO @fan
// message // message
await getMessageList() await getMessageList()
@ -605,19 +599,19 @@ const handlerMessageClear = async () => {
onMounted(async () => { onMounted(async () => {
// TODO conversationId // TODO conversationId
if (route.query.conversationId) { if (route.query.conversationId) {
const id = route.query.conversationId as string const id = route.query.conversationId as unknown as number
activeConversationId.value = id activeConversationId.value = id
await getConversation(id) await getConversation(id)
} }
// //
listLoading.value = true activeMessageListLoading.value = true
await getMessageList() await getMessageList()
}) })
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.ai-layout { .ai-layout {
// TODO @ height 100% // TODO @ height 100% TODO @fan
position: absolute; position: absolute;
flex: 1; flex: 1;
top: 0; top: 0;
@ -631,8 +625,7 @@ onMounted(async () => {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
justify-content: space-between; justify-content: space-between;
padding: 0 10px; padding: 10px 10px 0;
padding-top: 10px;
.btn-new-conversation { .btn-new-conversation {
padding: 18px 0; padding: 18px 0;
@ -771,8 +764,6 @@ onMounted(async () => {
bottom: 0; bottom: 0;
left: 0; left: 0;
right: 0; right: 0;
//width: 100%;
//height: 100%;
overflow-y: hidden; overflow-y: hidden;
padding: 0; padding: 0;
margin: 0; margin: 0;
@ -803,8 +794,7 @@ onMounted(async () => {
border: none; border: none;
box-sizing: border-box; box-sizing: border-box;
resize: none; resize: none;
padding: 0px 2px; padding: 0 2px;
//padding: 5px 5px;
overflow: auto; overflow: auto;
} }
@ -815,7 +805,7 @@ onMounted(async () => {
.prompt-btns { .prompt-btns {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
padding-bottom: 0px; padding-bottom: 0;
padding-top: 5px; padding-top: 5px;
} }
} }