index.vue 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  1. <template>
  2. <el-container class="ai-layout">
  3. <!-- 左侧:会话列表 -->
  4. <Conversation :active-id="activeConversationId"
  5. ref="conversationRef"
  6. @onConversationClick="handleConversationClick"
  7. @onConversationClear="handlerConversationClear"
  8. @onConversationDelete="handlerConversationDelete"
  9. />
  10. <!-- 右侧:会话详情 -->
  11. <el-container class="detail-container">
  12. <!-- 右顶部 TODO 芋艿:右对齐 -->
  13. <el-header class="header">
  14. <div class="title">
  15. {{ activeConversation?.title ? activeConversation?.title : '对话' }}
  16. <span v-if="list.length">({{list.length}})</span>
  17. </div>
  18. <div class="btns" v-if="activeConversation">
  19. <!-- TODO @fan:样式改下;这里我已经改成点击后,弹出了 -->
  20. <el-button type="primary" bg text="plain" size="small" @click="openChatConversationUpdateForm">
  21. <span v-html="activeConversation?.modelName"></span>
  22. <Icon icon="ep:setting" style="margin-left: 10px"/>
  23. </el-button>
  24. <el-button size="small" class="btn" @click="handlerMessageClear">
  25. <img src="@/assets/ai/clear.svg" style="height: 14px;" />
  26. </el-button>
  27. <el-button size="small" :icon="Download" class="btn" />
  28. <el-button size="small" :icon="Top" class="btn" @click="handlerGoTop" />
  29. </div>
  30. </el-header>
  31. <!-- main -->
  32. <el-main class="main-container" >
  33. <div >
  34. <div class="message-container" >
  35. <MessageLoading v-if="listLoading" />
  36. <MessageNewChat v-if="!activeConversation" @on-new-chat="handlerNewChat" />
  37. <ChatEmpty v-if="!listLoading && list.length === 0 && activeConversation" @on-prompt="doSend"/>
  38. <Message v-if="!listLoading && list.length > 0"
  39. ref="messageRef"
  40. :list="list"
  41. @on-delete-success="handlerMessageDelete" />
  42. </div>
  43. </div>
  44. </el-main>
  45. <!-- 底部 -->
  46. <el-footer class="footer-container">
  47. <form class="prompt-from">
  48. <textarea
  49. class="prompt-input"
  50. v-model="prompt"
  51. @keydown="onSend"
  52. @input="onPromptInput"
  53. @compositionstart="onCompositionstart"
  54. @compositionend="onCompositionend"
  55. placeholder="问我任何问题...(Shift+Enter 换行,按下 Enter 发送)"
  56. ></textarea>
  57. <div class="prompt-btns">
  58. <div>
  59. <el-switch v-model="enableContext" /> <span style="font-size: 14px; color: #8f8f8f;">上下文</span>
  60. </div>
  61. <el-button
  62. type="primary"
  63. size="default"
  64. @click="onSendBtn"
  65. :loading="conversationInProgress"
  66. v-if="conversationInProgress == false"
  67. >
  68. {{ conversationInProgress ? '进行中' : '发送' }}
  69. </el-button>
  70. <el-button
  71. type="danger"
  72. size="default"
  73. @click="stopStream()"
  74. v-if="conversationInProgress == true"
  75. >
  76. 停止
  77. </el-button>
  78. </div>
  79. </form>
  80. </el-footer>
  81. </el-container>
  82. <!-- ========= 额外组件 ========== -->
  83. <!-- 更新对话 form -->
  84. <ChatConversationUpdateForm
  85. ref="chatConversationUpdateFormRef"
  86. @success="handlerTitleSuccess"
  87. />
  88. </el-container>
  89. </template>
  90. <script setup lang="ts">
  91. import Conversation from './Conversation.vue'
  92. import Message from './Message.vue'
  93. import ChatEmpty from './ChatEmpty.vue'
  94. import MessageLoading from './MessageLoading.vue'
  95. import MessageNewChat from './MessageNewChat.vue'
  96. import {ChatMessageApi, ChatMessageVO} from '@/api/ai/chat/message'
  97. import {ChatConversationApi, ChatConversationVO} from '@/api/ai/chat/conversation'
  98. import { getUserProfile, ProfileVO } from '@/api/system/user/profile'
  99. import {useClipboard} from '@vueuse/core'
  100. import ChatConversationUpdateForm from "@/views/ai/chat/components/ChatConversationUpdateForm.vue";
  101. import {Download, Top} from "@element-plus/icons-vue";
  102. const route = useRoute() // 路由
  103. const message = useMessage() // 消息弹窗
  104. const {copy} = useClipboard() // 初始化 copy 到粘贴板
  105. // ref 属性定义
  106. const activeConversationId = ref<string | null>(null) // 选中的对话编号
  107. const activeConversation = ref<ChatConversationVO | null>(null) // 选中的 Conversation
  108. const conversationInProgress = ref(false) // 对话进行中
  109. const conversationInAbortController = ref<any>() // 对话进行中 abort 控制器(控制 stream 对话)
  110. const inputTimeout = ref<any>() // 处理输入中回车的定时器
  111. const prompt = ref<string>() // prompt
  112. const userInfo = ref<ProfileVO>() // 用户信息
  113. const enableContext = ref<boolean>(true) // 是否开启上下文
  114. const fullText = ref('');
  115. const displayedText = ref('');
  116. const textSpeed = ref<number>(50); // Typing speed in milliseconds
  117. const textRoleRunning = ref<boolean>(false); // Typing speed in milliseconds
  118. // chat message 列表
  119. const list = ref<ChatMessageVO[]>([]) // 列表的数据
  120. const listLoading = ref<boolean>(false) // 是否加载中
  121. const listLoadingTime = ref<any>() // time定时器,如果加载速度很快,就不进入加载中
  122. // 判断 消息列表 滚动的位置(用于判断是否需要滚动到消息最下方)
  123. const messageRef = ref()
  124. const conversationRef = ref()
  125. const isComposing = ref(false) // 判断用户是否在输入
  126. // 默认 role 头像
  127. const defaultRoleAvatar = 'http://test.yudao.iocoder.cn/eaef5f41acb911dd718429a0702dcc3c61160d16e57ba1d543132fab58934f9f.png'
  128. // =========== 自提滚动效果
  129. const textRoll = async () => {
  130. let index = 0;
  131. try {
  132. // 只能执行一次
  133. if (textRoleRunning.value) {
  134. return
  135. }
  136. // 设置状态
  137. textRoleRunning.value = true
  138. displayedText.value = ''
  139. const task = async () => {
  140. // 调整速度
  141. const diff = (fullText.value.length - displayedText.value.length) / 10
  142. if (diff > 5) {
  143. textSpeed.value = 10
  144. } else if (diff > 2) {
  145. textSpeed.value = 30
  146. } else if (diff > 1.5) {
  147. textSpeed.value = 50
  148. } else {
  149. textSpeed.value = 100
  150. }
  151. // 对话结束,就按30的速度
  152. if (!conversationInProgress.value) {
  153. textSpeed.value = 10
  154. }
  155. // console.log('index < fullText.value.length', index < fullText.value.length, conversationInProgress.value)
  156. if (index < fullText.value.length) {
  157. displayedText.value += fullText.value[index];
  158. index++;
  159. // 更新 message
  160. const lastMessage = list.value[list.value.length - 1]
  161. lastMessage.content = displayedText.value
  162. list.value[list.value - 1] = lastMessage
  163. // 滚动到住下面
  164. await scrollToBottom()
  165. // 重新设置任务
  166. timer = setTimeout(task, textSpeed.value);
  167. } else {
  168. // 不是对话中可以结束
  169. if (!conversationInProgress.value) {
  170. textRoleRunning.value = false
  171. clearTimeout(timer);
  172. console.log("字体滚动退出!")
  173. } else {
  174. // 重新设置任务
  175. timer = setTimeout(task, textSpeed.value);
  176. }
  177. }
  178. }
  179. let timer = setTimeout(task, textSpeed.value);
  180. } finally {
  181. }
  182. };
  183. // ============ 处理对话滚动 ==============
  184. function scrollToBottom(isIgnore?: boolean) {
  185. // isIgnore = isIgnore !== null ? isIgnore : false
  186. nextTick(() => {
  187. if (messageRef.value) {
  188. messageRef.value.scrollToBottom(isIgnore)
  189. }
  190. })
  191. }
  192. // ============= 处理聊天输入回车发送 =============
  193. const onCompositionstart = () => {
  194. isComposing.value = true
  195. }
  196. const onCompositionend = () => {
  197. // console.log('输入结束...')
  198. setTimeout(() => {
  199. isComposing.value = false
  200. }, 200)
  201. }
  202. const onPromptInput = (event) => {
  203. // 非输入法 输入设置为 true
  204. if (!isComposing.value) {
  205. // 回车 event data 是 null
  206. if (event.data == null) {
  207. return
  208. }
  209. isComposing.value = true
  210. }
  211. // 清理定时器
  212. if (inputTimeout.value) {
  213. clearTimeout(inputTimeout.value)
  214. }
  215. // 重置定时器
  216. inputTimeout.value = setTimeout(() => {
  217. isComposing.value = false
  218. }, 400)
  219. }
  220. // ============== 对话消息相关 =================
  221. /**
  222. * 发送消息
  223. */
  224. const onSend = async (event) => {
  225. // 判断用户是否在输入
  226. if (isComposing.value) {
  227. return
  228. }
  229. // 进行中不允许发送
  230. if (conversationInProgress.value) {
  231. return
  232. }
  233. const content = prompt.value?.trim() as string
  234. if (event.key === 'Enter') {
  235. if (event.shiftKey) {
  236. // 插入换行
  237. prompt.value += '\r\n';
  238. event.preventDefault(); // 防止默认的换行行为
  239. } else {
  240. // 发送消息
  241. await doSend(content)
  242. event.preventDefault(); // 防止默认的提交行为
  243. }
  244. }
  245. }
  246. const onSendBtn = async () => {
  247. await doSend(prompt.value?.trim() as string)
  248. }
  249. const doSend = async (content: string) => {
  250. if (content.length < 2) {
  251. ElMessage({
  252. message: '请输入内容!',
  253. type: 'error'
  254. })
  255. return
  256. }
  257. if (activeConversationId.value == null) {
  258. ElMessage({
  259. message: '还没创建对话,不能发送!',
  260. type: 'error'
  261. })
  262. return
  263. }
  264. // TODO 芋艿:这块交互要在优化;应该是先插入到 UI 界面,里面会有当前的消息,和正在思考中;之后发起请求;
  265. // 清空输入框
  266. prompt.value = ''
  267. const userMessage = {
  268. conversationId: activeConversationId.value,
  269. content: content
  270. } as ChatMessageVO
  271. // stream
  272. await doSendStream(userMessage)
  273. }
  274. const doSendStream = async (userMessage: ChatMessageVO) => {
  275. // 创建AbortController实例,以便中止请求
  276. conversationInAbortController.value = new AbortController()
  277. // 标记对话进行中
  278. conversationInProgress.value = true
  279. // 设置为空
  280. fullText.value = ''
  281. try {
  282. // 先添加两个假数据,等 stream 返回再替换
  283. list.value.push({
  284. id: -1,
  285. conversationId: activeConversationId.value,
  286. type: 'user',
  287. content: userMessage.content,
  288. userAvatar: userInfo.value?.avatar,
  289. createTime: new Date()
  290. } as ChatMessageVO)
  291. list.value.push({
  292. id: -2,
  293. conversationId: activeConversationId.value,
  294. type: 'system',
  295. content: '思考中...',
  296. roleAvatar: (activeConversation.value as ChatConversationVO).roleAvatar,
  297. createTime: new Date()
  298. } as ChatMessageVO)
  299. // 滚动到最下面
  300. nextTick(async () => {
  301. await scrollToBottom()
  302. })
  303. // 开始滚动
  304. textRoll()
  305. // 发送 event stream
  306. let isFirstMessage = true
  307. ChatMessageApi.sendStream(
  308. userMessage.conversationId, // TODO 芋艿:这里可能要在优化;
  309. userMessage.content,
  310. conversationInAbortController.value,
  311. enableContext.value,
  312. async (message) => {
  313. const data = JSON.parse(message.data) // TODO 芋艿:类型处理;
  314. // 如果内容为空,就不处理。
  315. if (data.receive.content === '') {
  316. return
  317. }
  318. // 首次返回需要添加一个 message 到页面,后面的都是更新
  319. if (isFirstMessage) {
  320. isFirstMessage = false
  321. // 弹出两个 假数据
  322. list.value.pop()
  323. list.value.pop()
  324. // 更新返回的数据
  325. list.value.push(data.send)
  326. list.value.push(data.receive)
  327. }
  328. // debugger
  329. fullText.value = fullText.value + data.receive.content
  330. // 滚动到最下面
  331. await scrollToBottom()
  332. },
  333. (error) => {
  334. console.log('onError')
  335. // 标记对话结束
  336. conversationInProgress.value = false
  337. // 结束 stream 对话
  338. conversationInAbortController.value.abort()
  339. },
  340. () => {
  341. console.log('onClose')
  342. // 标记对话结束
  343. conversationInProgress.value = false
  344. // 结束 stream 对话
  345. conversationInAbortController.value.abort()
  346. }
  347. )
  348. } finally {
  349. }
  350. }
  351. const stopStream = async () => {
  352. console.log('stopStream...')
  353. // tip:如果 stream 进行中的 message,就需要调用 controller 结束
  354. if (conversationInAbortController.value) {
  355. conversationInAbortController.value.abort()
  356. }
  357. // 设置为 false
  358. conversationInProgress.value = false
  359. }
  360. // ============== message 数据 =================
  361. /**
  362. * 获取 - message 列表
  363. */
  364. const getMessageList = async () => {
  365. try {
  366. // time 定时器,如果加载速度很快,就不进入加载中
  367. listLoadingTime.value = setTimeout(() => {
  368. listLoading.value = true
  369. }, 60)
  370. if (activeConversationId.value === null) {
  371. return
  372. }
  373. // 获取列表数据
  374. const messageListRes = await ChatMessageApi.messageList(activeConversationId.value)
  375. // 设置用户头像
  376. messageListRes.map(item => {
  377. // 设置 role 默认头像
  378. item.roleAvatar = item.roleAvatar ? item.roleAvatar : defaultRoleAvatar
  379. })
  380. list.value = messageListRes
  381. // 滚动到最下面
  382. await nextTick(() => {
  383. // 滚动到最后
  384. scrollToBottom()
  385. })
  386. } finally {
  387. // time 定时器,如果加载速度很快,就不进入加载中
  388. if (listLoadingTime.value) {
  389. clearTimeout(listLoadingTime.value)
  390. }
  391. // 加载结束
  392. listLoading.value = false
  393. }
  394. }
  395. /** 修改聊天会话 */
  396. const chatConversationUpdateFormRef = ref()
  397. const openChatConversationUpdateForm = async () => {
  398. chatConversationUpdateFormRef.value.open(activeConversationId.value)
  399. }
  400. /**
  401. * 对话 - 标题修改成功
  402. */
  403. const handlerTitleSuccess = async () => {
  404. // TODO 需要刷新 对话列表
  405. await getConversation(activeConversationId.value)
  406. }
  407. /**
  408. * 对话 - 点击
  409. */
  410. const handleConversationClick = async (conversation: ChatConversationVO) => {
  411. // 对话进行中,不允许切换
  412. if (conversationInProgress.value) {
  413. await message.alert("对话中,不允许切换!")
  414. return false
  415. }
  416. // 更新选中的对话 id
  417. activeConversationId.value = conversation.id
  418. activeConversation.value = conversation
  419. // 处理进行中的对话
  420. if (conversationInProgress.value) {
  421. await stopStream()
  422. }
  423. // 刷新 message 列表
  424. await getMessageList()
  425. // 滚动底部
  426. scrollToBottom(true)
  427. return true
  428. }
  429. /**
  430. * 对话 - 清理全部对话
  431. */
  432. const handlerConversationClear = async ()=> {
  433. activeConversationId.value = null
  434. activeConversation.value = null
  435. list.value = []
  436. }
  437. /**
  438. * 对话 - 删除
  439. */
  440. const handlerConversationDelete = async (delConversation: ChatConversationVO) => {
  441. // 删除的对话如果是当前选中的,那么久重置
  442. if (activeConversationId.value === delConversation.id) {
  443. await handlerConversationClear()
  444. }
  445. }
  446. /**
  447. * 对话 - 获取
  448. */
  449. const getConversation = async (id: string | null) => {
  450. if (!id) {
  451. return
  452. }
  453. const conversation: ChatConversationVO = await ChatConversationApi.getChatConversationMy(id)
  454. if (conversation) {
  455. activeConversation.value = conversation
  456. activeConversationId.value = conversation.id
  457. }
  458. }
  459. /**
  460. * 对话 - 新建
  461. */
  462. const handlerNewChat = async () => {
  463. // 创建对话
  464. await conversationRef.value.createConversation()
  465. }
  466. // ============ message ===========
  467. /**
  468. * 删除 message
  469. */
  470. const handlerMessageDelete = async () => {
  471. // 刷新 message
  472. await getMessageList()
  473. }
  474. /**
  475. * 回到顶部
  476. */
  477. const handlerGoTop = async () => {
  478. await messageRef.value.handlerGoTop()
  479. }
  480. /**
  481. * message 清除
  482. */
  483. const handlerMessageClear = async () => {
  484. if (!activeConversationId.value) {
  485. return
  486. }
  487. // 确认提示
  488. await message.delConfirm("确认清空对话消息?")
  489. // 清空对话
  490. await ChatMessageApi.deleteByConversationId(activeConversationId.value as string)
  491. // 刷新 message 列表
  492. await getMessageList()
  493. }
  494. /** 初始化 **/
  495. onMounted(async () => {
  496. // 设置当前对话 TODO 角色仓库过来的,自带 conversationId 需要选中
  497. if (route.query.conversationId) {
  498. const id = route.query.conversationId as string
  499. activeConversationId.value = id
  500. await getConversation(id)
  501. }
  502. // 获取列表数据
  503. listLoading.value = true
  504. await getMessageList()
  505. // 获取用户信息
  506. userInfo.value = await getUserProfile()
  507. })
  508. </script>
  509. <style lang="scss" scoped>
  510. .ai-layout {
  511. // TODO @范 这里height不能 100% 先这样临时处理
  512. position: absolute;
  513. flex: 1;
  514. top: 0;
  515. left: 0;
  516. height: 100%;
  517. width: 100%;
  518. }
  519. .conversation-container {
  520. position: relative;
  521. display: flex;
  522. flex-direction: column;
  523. justify-content: space-between;
  524. padding: 0 10px;
  525. padding-top: 10px;
  526. .btn-new-conversation {
  527. padding: 18px 0;
  528. }
  529. .search-input {
  530. margin-top: 20px;
  531. }
  532. .conversation-list {
  533. margin-top: 20px;
  534. .conversation {
  535. display: flex;
  536. flex-direction: row;
  537. justify-content: space-between;
  538. flex: 1;
  539. padding: 0 5px;
  540. margin-top: 10px;
  541. cursor: pointer;
  542. border-radius: 5px;
  543. align-items: center;
  544. line-height: 30px;
  545. &.active {
  546. background-color: #e6e6e6;
  547. .button {
  548. display: inline-block;
  549. }
  550. }
  551. .title-wrapper {
  552. display: flex;
  553. flex-direction: row;
  554. align-items: center;
  555. }
  556. .title {
  557. padding: 5px 10px;
  558. max-width: 220px;
  559. font-size: 14px;
  560. overflow: hidden;
  561. white-space: nowrap;
  562. text-overflow: ellipsis;
  563. }
  564. .avatar {
  565. width: 28px;
  566. height: 28px;
  567. display: flex;
  568. flex-direction: row;
  569. justify-items: center;
  570. }
  571. // 对话编辑、删除
  572. .button-wrapper {
  573. right: 2px;
  574. display: flex;
  575. flex-direction: row;
  576. justify-items: center;
  577. color: #606266;
  578. .el-icon {
  579. margin-right: 5px;
  580. }
  581. }
  582. }
  583. }
  584. // 角色仓库、清空未设置对话
  585. .tool-box {
  586. line-height: 35px;
  587. display: flex;
  588. justify-content: space-between;
  589. align-items: center;
  590. color: var(--el-text-color);
  591. > div {
  592. display: flex;
  593. align-items: center;
  594. color: #606266;
  595. padding: 0;
  596. margin: 0;
  597. cursor: pointer;
  598. > span {
  599. margin-left: 5px;
  600. }
  601. }
  602. }
  603. }
  604. // 头部
  605. .detail-container {
  606. background: #ffffff;
  607. .header {
  608. display: flex;
  609. flex-direction: row;
  610. align-items: center;
  611. justify-content: space-between;
  612. background: #fbfbfb;
  613. box-shadow: 0 0 0 0 #dcdfe6;
  614. .title {
  615. font-size: 18px;
  616. font-weight: bold;
  617. }
  618. .btns {
  619. display: flex;
  620. width: 300px;
  621. flex-direction: row;
  622. justify-content: flex-end;
  623. //justify-content: space-between;
  624. .btn {
  625. padding: 10px;
  626. }
  627. }
  628. }
  629. }
  630. // main 容器
  631. .main-container {
  632. margin: 0;
  633. padding: 0;
  634. position: relative;
  635. height: 100%;
  636. width: 100%;
  637. .message-container {
  638. position: absolute;
  639. top: 0;
  640. bottom: 0;
  641. left: 0;
  642. right: 0;
  643. //width: 100%;
  644. //height: 100%;
  645. overflow-y: hidden;
  646. padding: 0;
  647. margin: 0;
  648. }
  649. }
  650. // 底部
  651. .footer-container {
  652. display: flex;
  653. flex-direction: column;
  654. height: auto;
  655. margin: 0;
  656. padding: 0;
  657. .prompt-from {
  658. display: flex;
  659. flex-direction: column;
  660. height: auto;
  661. border: 1px solid #e3e3e3;
  662. border-radius: 10px;
  663. margin: 10px 20px 20px 20px;
  664. padding: 9px 10px;
  665. }
  666. .prompt-input {
  667. height: 80px;
  668. //box-shadow: none;
  669. border: none;
  670. box-sizing: border-box;
  671. resize: none;
  672. padding: 0px 2px;
  673. //padding: 5px 5px;
  674. overflow: auto;
  675. }
  676. .prompt-input:focus {
  677. outline: none;
  678. }
  679. .prompt-btns {
  680. display: flex;
  681. justify-content: space-between;
  682. padding-bottom: 0px;
  683. padding-top: 5px;
  684. }
  685. }
  686. </style>