【代码评审】AI:review 聊天对话的实现

This commit is contained in:
YunaiV 2024-05-25 10:54:04 +08:00
parent 4c259cd60f
commit 46eb89695d
7 changed files with 105 additions and 91 deletions

View File

@ -1,4 +1,3 @@
<template>
<div class="chat-empty">
@ -15,7 +14,6 @@
</template>
<script setup lang="ts">
const router = useRouter()
const promptList = ref<any[]>() //
promptList.value = [
{
@ -31,9 +29,6 @@ const emits = defineEmits(['onPrompt'])
const handlerPromptClick = async ({ prompt }) => {
emits('onPrompt', prompt)
}
onMounted(async () => {
})
</script>
<style scoped lang="scss">
.chat-empty {

View File

@ -27,7 +27,6 @@
<el-empty v-if="loading" description="." :v-loading="loading" />
<!-- TODO done @fain置顶聊天记录一星期钱30天前前端对数据重新做一下分组或者后端接口改一下 -->
<div v-for="conversationKey in Object.keys(conversationMap)" :key="conversationKey">
<div class="conversation-item classify-title" v-if="conversationMap[conversationKey].length">
<el-text class="mx-1" size="small" tag="b">{{ conversationKey }}</el-text>
@ -47,7 +46,6 @@
<img class="avatar" :src="conversation.roleAvatar"/>
<span class="title">{{ conversation.title }}</span>
</div>
<!-- TODO done @fan缺一个置顶按钮效果改成 hover 上去展示 -->
<div class="button-wrapper" v-show="hoverConversationId === conversation.id">
<el-button class="btn" link @click.stop="handlerTop(conversation)" >
<el-icon title="置顶" v-if="!conversation.pinned"><Top /></el-icon>
@ -74,6 +72,7 @@
</div>
<!-- 左底部工具栏 -->
<!-- TODO @fan下面两个 icon可以使用类似 <Icon icon="ep:question-filled" /> 替代哈 -->
<div class="tool-box">
<div @click="handleRoleRepository">
<Icon icon="ep:user"/>
@ -109,7 +108,7 @@ const activeConversationId = ref<string | null>(null) // 选中的对话,默
const hoverConversationId = ref<string | null>(null) //
const conversationList = ref([] as ChatConversationVO[]) //
const conversationMap = ref<any>({}) // ()
const drawer = ref<boolean>(false) //
const drawer = ref<boolean>(false) // TODO @fanroleDrawer
const loading = ref<boolean>(false) //
const loadingTime = ref<any>() //
@ -154,6 +153,7 @@ const handleConversationClick = async (id: string) => {
return item.id === id
})
// onConversationClick
// TODO @fan: idea
const res = emits('onConversationClick', filterConversation[0])
//
if (res) {
@ -166,18 +166,18 @@ const handleConversationClick = async (id: string) => {
*/
const getChatConversationList = async () => {
try {
// 0
// 0.
loadingTime.value = setTimeout(() => {
loading.value = true
}, 50)
// 1
// 1.
const res = await ChatConversationApi.getChatConversationMyList()
// 2
// 2.
res.sort((a, b) => {
return b.createTime - a.createTime
})
conversationList.value = res
// 3
// 3.
if (!activeId?.value) {
// await handleConversationClick(res[0].id)
} else {
@ -189,13 +189,13 @@ const getChatConversationList = async () => {
// await handleConversationClick(res[0].id)
// }
}
// 4
// 4.
if (conversationList.value.length === 0) {
activeConversationId.value = null
conversationMap.value = {}
return
}
// 5(30)
// 5. (30)
conversationMap.value = await conversationTimeGroup(conversationList.value)
} finally {
//
@ -253,15 +253,15 @@ const conversationTimeGroup = async (list: ChatConversationVO[]) => {
* 对话 - 新建
*/
const createConversation = async () => {
// 1
// 1.
const conversationId = await ChatConversationApi.createChatConversationMy(
{} as unknown as ChatConversationVO
)
// 2
// 2.
await getChatConversationList()
// 3
// 3.
await handleConversationClick(conversationId)
// 4
// 4.
emits('onConversationCreate')
}
@ -269,21 +269,21 @@ const createConversation = async () => {
* 对话 - 更新标题
*/
const updateConversationTitle = async (conversation: ChatConversationVO) => {
// 1
// 1.
const {value} = await ElMessageBox.prompt('修改标题', {
inputPattern: /^[\s\S]*.*\S[\s\S]*$/, //
inputErrorMessage: '标题不能为空',
inputValue: conversation.title
})
// 2
// 2.
await ChatConversationApi.updateChatConversationMy({
id: conversation.id,
title: value
} as ChatConversationVO)
message.success('重命名成功')
//
// 3.
await getChatConversationList()
//
// 4.
const filterConversationList = conversationList.value.filter(item => {
return item.id === conversation.id
})
@ -316,6 +316,7 @@ const deleteChatConversation = async (conversation: ChatConversationVO) => {
/**
* 对话置顶
*/
// TODO @fan handleXXXhandler
const handlerTop = async (conversation: ChatConversationVO) => {
//
conversation.pinned = !conversation.pinned
@ -324,9 +325,9 @@ const handlerTop = async (conversation: ChatConversationVO) => {
await getChatConversationList()
}
// TODO @fan: ============ ============
// ============
/**
* 角色仓库抽屉
*/
@ -336,11 +337,11 @@ const handleRoleRepository = async () => {
// =============
/**
* 清空对话
*/
const handleClearConversation = async () => {
// TODO @fan使 await message.confirm( 使 await
ElMessageBox.confirm(
'确认后对话会全部清空,置顶的对话除外。',
'确认提示',

View File

@ -106,6 +106,7 @@ const messageList = computed(() => {
const scrollToBottom = async (isIgnore?: boolean) => {
await nextTick(() => {
// TODO @fannextick idea 绿线
//使nexttickdom
if (isIgnore || !isScrolling.value) {
messageContainer.value.scrollTop =
@ -184,6 +185,7 @@ const handlerGoTop = async () => {
}
// list
// TODO @fan
const { list, conversationId } = toRefs(props)
watch(list, async (newValue, oldValue) => {
console.log('watch list', list)

View File

@ -45,6 +45,4 @@ defineProps({
flex-direction: row;
}
}
</style>

View File

@ -10,27 +10,27 @@
/>
<!-- 右侧对话详情 -->
<el-container class="detail-container">
<!-- 右顶部 TODO 芋艿右对齐 -->
<el-header class="header">
<div class="title">
{{ activeConversation?.title ? activeConversation?.title : '对话' }}
<span v-if="list.length">({{list.length}})</span>
</div>
<div class="btns" v-if="activeConversation">
<!-- TODO @fan样式改下这里我已经改成点击后弹出了 -->
<el-button type="primary" bg text="plain" size="small" @click="openChatConversationUpdateForm">
<el-button type="primary" bg plain size="small" @click="openChatConversationUpdateForm">
<span v-html="activeConversation?.modelName"></span>
<Icon icon="ep:setting" style="margin-left: 10px"/>
</el-button>
<el-button size="small" class="btn" @click="handlerMessageClear">
<!-- TODO @fanstyle 部分可以考虑用 unocss 替代 -->
<img src="@/assets/ai/clear.svg" style="height: 14px;" />
</el-button>
<!-- TODO @fan下面两个 icon可以使用类似 <Icon icon="ep:question-filled" /> 替代哈 -->
<el-button size="small" :icon="Download" class="btn" />
<el-button size="small" :icon="Top" class="btn" @click="handlerGoTop" />
</div>
</el-header>
<!-- main -->
<!-- main消息列表 -->
<el-main class="main-container" >
<div >
<div class="message-container" >
@ -87,7 +87,7 @@
</el-container>
<!-- ========= 额外组件 ========== -->
<!-- 更新对话 form -->
<!-- 更新对话 Form -->
<ChatConversationUpdateForm
ref="chatConversationUpdateFormRef"
@success="handlerTitleSuccess"
@ -96,6 +96,7 @@
</template>
<script setup lang="ts">
// TODO @fan index.vue index /ai/chat /ai/chat/manager
import Conversation from './Conversation.vue'
import Message from './Message.vue'
import ChatEmpty from './ChatEmpty.vue'
@ -120,15 +121,17 @@ const prompt = ref<string>() // prompt
const userInfo = ref<ProfileVO>() //
const enableContext = ref<boolean>(true) //
// TODO @fanfullText Text
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 listLoadingTime = ref<any>() // time
// ()
const messageRef = ref()
@ -140,6 +143,7 @@ const defaultRoleAvatar = 'http://test.yudao.iocoder.cn/eaef5f41acb911dd718429a0
// ===========
// TODO @fan
const textRoll = async () => {
let index = 0;
try {
@ -162,7 +166,7 @@ const textRoll = async () => {
} else {
textSpeed.value = 100
}
// 30
// 30
if (!conversationInProgress.value) {
textSpeed.value = 10
}
@ -176,6 +180,7 @@ const textRoll = async () => {
// message
const lastMessage = list.value[list.value.length - 1]
lastMessage.content = displayedText.value
// TODO @fanist.value ist.value.length
list.value[list.value - 1] = lastMessage
//
await scrollToBottom()
@ -212,6 +217,7 @@ function scrollToBottom(isIgnore?: boolean) {
// ============= =============
// TODO @fan @keydown.enter@keydown.shift.enter shift+ isComposing
const onCompositionstart = () => {
isComposing.value = true
}
@ -276,12 +282,14 @@ const onSendBtn = async () => {
const doSend = async (content: string) => {
if (content.length < 2) {
// TODO @fan message.error(`${props.fileSize}MB!`)
ElMessage({
message: '请输入内容!',
type: 'error'
})
return
}
// TODO @fan message.error(`${props.fileSize}MB!`)
if (activeConversationId.value == null) {
ElMessage({
message: '还没创建对话,不能发送!',
@ -289,9 +297,9 @@ const doSend = async (content: string) => {
})
return
}
// TODO UI
//
prompt.value = ''
// TODO @fanidea
const userMessage = {
conversationId: activeConversationId.value,
content: content
@ -309,6 +317,7 @@ const doSendStream = async (userMessage: ChatMessageVO) => {
fullText.value = ''
try {
// stream
// TODO @fanidea
list.value.push({
id: -1,
conversationId: activeConversationId.value,
@ -326,13 +335,14 @@ const doSendStream = async (userMessage: ChatMessageVO) => {
createTime: new Date()
} as ChatMessageVO)
//
// TODO @fan await nextTick() scrollToBottom()
nextTick(async () => {
await scrollToBottom()
})
//
textRoll()
// event stream
let isFirstMessage = true
let isFirstMessage = true // TODO @fanisFirstChunk
ChatMessageApi.sendStream(
userMessage.conversationId, // TODO
userMessage.content,
@ -367,12 +377,14 @@ const doSendStream = async (userMessage: ChatMessageVO) => {
},
(error) => {
message.alert(`对话异常! ${error}`)
// TODO @fan stopStream
//
conversationInProgress.value = false
// stream
conversationInAbortController.value.abort()
},
() => {
// TODO @fan stopStream
//
conversationInProgress.value = false
// stream
@ -412,6 +424,7 @@ const messageList = computed(() => {
return []
})
// TODO @fan /** */= =
/**
* 获取 - message 列表
*/
@ -500,6 +513,7 @@ const handleConversationClick = async (conversation: ChatConversationVO) => {
* 对话 - 清理全部对话
*/
const handlerConversationClear = async ()=> {
// TODO @fan
activeConversationId.value = null
activeConversation.value = null
list.value = []
@ -509,7 +523,7 @@ const handlerConversationClear = async ()=> {
* 对话 - 删除
*/
const handlerConversationDelete = async (delConversation: ChatConversationVO) => {
//
//
if (activeConversationId.value === delConversation.id) {
await handlerConversationClear()
}
@ -532,6 +546,7 @@ const getConversation = async (id: string | null) => {
/**
* 对话 - 新建
*/
// TODO @fan handleXXXhandler
const handlerNewChat = async () => {
//
await conversationRef.value.createConversation()
@ -552,14 +567,14 @@ const handlerMessageDelete = async () => {
}
/**
* 编辑 message
* 编辑 message设置为 prompt可以再次编辑
*/
const handlerMessageEdit = async (message: ChatMessageVO) => {
prompt.value = message.content
}
/**
* 编辑 message
* 刷新 message基于指定消息再次发起对话
*/
const handlerMessageRefresh = async (message: ChatMessageVO) => {
await doSend(message.content)
@ -579,10 +594,12 @@ const handlerMessageClear = async () => {
if (!activeConversationId.value) {
return
}
// TODO @fan try catch
//
await message.delConfirm("确认清空对话消息?")
//
await ChatMessageApi.deleteByConversationId(activeConversationId.value as string)
// TODO @fan
// message
await getMessageList()
}

View File

@ -10,6 +10,7 @@
<el-icon><More /></el-icon>
</el-button>
</span>
<!-- TODO @fan下面两个 icon可以使用类似 <Icon icon="ep:question-filled" /> 替代哈 -->
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item :command="['edit', role]" >
@ -31,7 +32,6 @@
<div class="content-container">
<div class="title">{{ role.name }}</div>
<div class="description">{{ role.description }}</div>
</div>
<div class="btn-container">
<el-button type="primary" size="small" @click="handleUseClick(role)">使用</el-button>

View File

@ -1,9 +1,9 @@
<!-- chat 角色仓库 -->
<template>
<el-container class="role-container">
<ChatRoleForm ref="formRef" @success="handlerAddRoleSuccess"/>
<ChatRoleForm ref="formRef" @success="handlerAddRoleSuccess" />
<!-- header -->
<Header title="角色仓库" style="position: relative"/>
<Header title="角色仓库" style="position: relative" />
<!-- main -->
<el-main class="role-main">
<div class="search-container">
@ -17,9 +17,15 @@
:suffix-icon="Search"
@change="getActiveTabsRole"
/>
<el-button v-if="activeRole == 'my-role'" type="primary" @click="handlerAddRole" style="margin-left: 20px;">
<el-button
v-if="activeRole == 'my-role'"
type="primary"
@click="handlerAddRole"
style="margin-left: 20px"
>
<!-- TODO @fan下面两个 icon可以使用类似 <Icon icon="ep:question-filled" /> 替代哈 -->
<el-icon>
<User/>
<User />
</el-icon>
添加角色
</el-button>
@ -35,7 +41,8 @@
@on-edit="handlerCardEdit"
@on-use="handlerCardUse"
@on-page="handlerCardPage('my')"
style="margin-top: 20px;"/>
style="margin-top: 20px"
/>
</el-tab-pane>
<el-tab-pane label="公共角色" name="public-role">
<RoleCategoryList
@ -50,34 +57,33 @@
@on-edit="handlerCardEdit"
@on-use="handlerCardUse"
@on-page="handlerCardPage('public')"
style="margin-top: 20px;"
loading/>
style="margin-top: 20px"
loading
/>
</el-tab-pane>
</el-tabs>
</el-main>
</el-container>
</template>
<!-- setup -->
<script setup lang="ts">
import {ref} from "vue";
import { ref } from 'vue'
import Header from '@/views/ai/chat/components/Header.vue'
import RoleList from './RoleList.vue'
import ChatRoleForm from '@/views/ai/model/chatRole/ChatRoleForm.vue'
import RoleCategoryList from './RoleCategoryList.vue'
import {ChatRoleApi, ChatRolePageReqVO, ChatRoleVO} from '@/api/ai/model/chatRole'
import {ChatConversationApi, ChatConversationVO} from '@/api/ai/chat/conversation'
import {TabsPaneContext} from "element-plus";
import {Search, User} from "@element-plus/icons-vue";
import { ChatRoleApi, ChatRolePageReqVO, ChatRoleVO } from '@/api/ai/model/chatRole'
import { ChatConversationApi, ChatConversationVO } from '@/api/ai/chat/conversation'
import { TabsPaneContext } from 'element-plus'
import { Search, User } from '@element-plus/icons-vue'
//
const router = useRouter()
const router = useRouter() //
//
const loading = ref<boolean>(false) //
const activeRole = ref<string>('my-role') //
const activeRole = ref<string>('my-role') // TODO @fan activeTab
const search = ref<string>('') //
// TODO @fan myPagepubPage const queryParams = reactive({
const myPageNo = ref<number>(1) // my
const myPageSize = ref<number>(50) // my
const myRoleList = ref<ChatRoleVO[]>([]) // my
@ -86,18 +92,16 @@ const publicPageSize = ref<number>(50) // public 分页大小
const publicRoleList = ref<ChatRoleVO[]>([]) // public
const activeCategory = ref<string>('全部') //
const categoryList = ref<string[]>([]) //
/** 添加/修改操作 */
const formRef = ref()
// tabs
/** tabs 点击 */
const handleTabsClick = async (tab: TabsPaneContext) => {
//
const activeTabs = tab.paneName + ''
activeRole.value = activeTabs;
activeRole.value = tab.paneName + ''
//
await getActiveTabsRole()
}
// my role
/** 获取 my role 我的角色 */
const getMyRole = async (append?: boolean) => {
const params: ChatRolePageReqVO = {
pageNo: myPageNo.value,
@ -105,7 +109,7 @@ const getMyRole = async (append?: boolean) => {
name: search.value,
publicStatus: false
}
const {total, list} = await ChatRoleApi.getMyPage(params)
const { total, list } = await ChatRoleApi.getMyPage(params)
if (append) {
myRoleList.value.push.apply(myRoleList.value, list)
} else {
@ -113,7 +117,7 @@ const getMyRole = async (append?: boolean) => {
}
}
// public role
/** 获取 public role 公共角色 */
const getPublicRole = async (append?: boolean) => {
const params: ChatRolePageReqVO = {
pageNo: publicPageNo.value,
@ -122,7 +126,7 @@ const getPublicRole = async (append?: boolean) => {
name: search.value,
publicStatus: true
}
const {total, list} = await ChatRoleApi.getMyPage(params)
const { total, list } = await ChatRoleApi.getMyPage(params)
if (append) {
publicRoleList.value.push.apply(publicRoleList.value, list)
} else {
@ -130,7 +134,7 @@ const getPublicRole = async (append?: boolean) => {
}
}
// tabs
/** 获取选中的 tabs 角色 */
const getActiveTabsRole = async () => {
if (activeRole.value === 'my-role') {
myPageNo.value = 1
@ -141,14 +145,14 @@ const getActiveTabsRole = async () => {
}
}
//
/** 获取角色分类列表 */
const getRoleCategoryList = async () => {
const res = await ChatRoleApi.getCategoryList()
const defaultRole = ['全部']
categoryList.value = [...defaultRole, ...res]
}
//
/** 处理分类点击 */
const handlerCategoryClick = async (category: string) => {
//
activeCategory.value = category
@ -156,11 +160,18 @@ const handlerCategoryClick = async (category: string) => {
await getActiveTabsRole()
}
//
/** 添加/修改操作 */
const formRef = ref()
const handlerAddRole = async () => {
formRef.value.open('my-create', null, '添加角色')
}
/** 添加角色成功 */
const handlerAddRoleSuccess = async (e) => {
//
await getActiveTabsRole()
}
// card
const handlerCardDelete = async (role) => {
await ChatRoleApi.deleteMy(role.id)
@ -173,7 +184,7 @@ const handlerCardEdit = async (role) => {
formRef.value.open('my-update', role.id, '编辑角色')
}
// card
/** card 分页:获取下一页 */
const handlerCardPage = async (type) => {
console.log('handlerCardPage', type)
try {
@ -190,39 +201,33 @@ const handlerCardPage = async (type) => {
}
}
// card 使
/** 选择 card 角色:新建聊天对话 */
const handlerCardUse = async (role) => {
// 1.
const data: ChatConversationVO = {
roleId: role.id
} as unknown as ChatConversationVO
//
const conversation = await ChatConversationApi.createChatConversationMy(data)
//
router.push({
const conversationId = await ChatConversationApi.createChatConversationMy(data)
// 2.
// TODO @fan name~~~
await router.push({
path: `/ai/chat`,
query: {
conversationId: conversation,
conversationId: conversationId
}
})
}
//
const handlerAddRoleSuccess = async (e) => {
console.log(e)
//
await getActiveTabsRole()
}
//
/** 初始化 **/
onMounted(async () => {
//
await getRoleCategoryList()
// role
await getActiveTabsRole()
})
// TODO @fancss scss
</script>
<style lang="css">
.el-tabs__content {
position: relative;
height: 100%;
@ -232,11 +237,9 @@ onMounted(async () => {
.el-tabs__nav-scroll {
margin: 10px 20px;
}
</style>
<!-- 样式 -->
<style scoped lang="scss">
//
.role-container {
position: absolute;
@ -290,6 +293,4 @@ onMounted(async () => {
}
}
}
</style>