index.vue 17 KB

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