index.vue 19 KB

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