index.vue 18 KB

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