index.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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. // debugger
  287. // 如果没有内容结束链接
  288. if (data.receive.content === '') {
  289. // 标记对话结束
  290. conversationInProgress.value = false
  291. // 结束 stream 对话
  292. conversationInAbortController.value.abort()
  293. return
  294. }
  295. // 首次返回需要添加一个 message 到页面,后面的都是更新
  296. if (isFirstMessage) {
  297. isFirstMessage = false
  298. // 弹出两个 假数据
  299. list.value.pop()
  300. list.value.pop()
  301. // 更新返回的数据
  302. list.value.push(data.send)
  303. list.value.push(data.receive)
  304. }
  305. // debugger
  306. fullText.value = fullText.value + data.receive.content
  307. // 滚动到最下面
  308. await scrollToBottom()
  309. },
  310. (error) => {
  311. // 标记对话结束
  312. conversationInProgress.value = false
  313. // 结束 stream 对话
  314. conversationInAbortController.value.abort()
  315. },
  316. () => {
  317. // 标记对话结束
  318. conversationInProgress.value = false
  319. // 结束 stream 对话
  320. conversationInAbortController.value.abort()
  321. }
  322. )
  323. } finally {
  324. }
  325. }
  326. const stopStream = async () => {
  327. // tip:如果 stream 进行中的 message,就需要调用 controller 结束
  328. if (conversationInAbortController.value) {
  329. conversationInAbortController.value.abort()
  330. }
  331. // 设置为 false
  332. conversationInProgress.value = false
  333. }
  334. // ============== message 数据 =================
  335. /**
  336. * 获取 - message 列表
  337. */
  338. const getMessageList = async () => {
  339. try {
  340. // time 定时器,如果加载速度很快,就不进入加载中
  341. listLoadingTime.value = setTimeout(() => {
  342. listLoading.value = true
  343. }, 60)
  344. if (activeConversationId.value === null) {
  345. return
  346. }
  347. // 获取列表数据
  348. list.value = await ChatMessageApi.messageList(activeConversationId.value)
  349. // 滚动到最下面
  350. await nextTick(() => {
  351. // 滚动到最后
  352. scrollToBottom()
  353. })
  354. } finally {
  355. // time 定时器,如果加载速度很快,就不进入加载中
  356. if (listLoadingTime.value) {
  357. clearTimeout(listLoadingTime.value)
  358. }
  359. // 加载结束
  360. listLoading.value = false
  361. }
  362. }
  363. /** 修改聊天会话 */
  364. const chatConversationUpdateFormRef = ref()
  365. const openChatConversationUpdateForm = async () => {
  366. chatConversationUpdateFormRef.value.open(activeConversationId.value)
  367. }
  368. /**
  369. * 对话 - 标题修改成功
  370. */
  371. const handlerTitleSuccess = async () => {
  372. // TODO 需要刷新 对话列表
  373. await getConversation(activeConversationId.value)
  374. }
  375. /**
  376. * 对话 - 点击
  377. */
  378. const handleConversationClick = async (conversation: ChatConversationVO) => {
  379. // 更新选中的对话 id
  380. activeConversationId.value = conversation.id
  381. activeConversation.value = conversation
  382. // 刷新 message 列表
  383. await getMessageList()
  384. // 滚动底部
  385. scrollToBottom(true)
  386. }
  387. /**
  388. * 对话 - 清理全部对话
  389. */
  390. const handlerConversationClear = async ()=> {
  391. activeConversationId.value = null
  392. activeConversation.value = null
  393. list.value = []
  394. }
  395. /**
  396. * 对话 - 删除
  397. */
  398. const handlerConversationDelete = async (delConversation: ChatConversationVO) => {
  399. // 删除的对话如果是当前选中的,那么久重置
  400. if (activeConversationId.value === delConversation.id) {
  401. await handlerConversationClear()
  402. }
  403. }
  404. /**
  405. * 对话 - 获取
  406. */
  407. const getConversation = async (id: string | null) => {
  408. if (!id) {
  409. return
  410. }
  411. const conversation: ChatConversationVO = await ChatConversationApi.getChatConversationMy(id)
  412. if (conversation) {
  413. activeConversation.value = conversation
  414. activeConversationId.value = conversation.id
  415. }
  416. }
  417. // ============ message ===========
  418. /**
  419. * 删除 message
  420. */
  421. const handlerMessageDelete = async () => {
  422. // 刷新 message
  423. await getMessageList()
  424. }
  425. /**
  426. * 回到顶部
  427. */
  428. const handlerGoTop = async () => {
  429. await messageRef.value.handlerGoTop()
  430. }
  431. /** 初始化 **/
  432. onMounted(async () => {
  433. // 设置当前对话 TODO 角色仓库过来的,自带 conversationId 需要选中
  434. if (route.query.conversationId) {
  435. const id = route.query.conversationId as string
  436. await getConversation(id)
  437. }
  438. // 获取列表数据
  439. await getMessageList()
  440. })
  441. </script>
  442. <style lang="scss" scoped>
  443. .ai-layout {
  444. // TODO @范 这里height不能 100% 先这样临时处理
  445. position: absolute;
  446. flex: 1;
  447. top: 0;
  448. left: 0;
  449. height: 100%;
  450. width: 100%;
  451. }
  452. .conversation-container {
  453. position: relative;
  454. display: flex;
  455. flex-direction: column;
  456. justify-content: space-between;
  457. padding: 0 10px;
  458. padding-top: 10px;
  459. .btn-new-conversation {
  460. padding: 18px 0;
  461. }
  462. .search-input {
  463. margin-top: 20px;
  464. }
  465. .conversation-list {
  466. margin-top: 20px;
  467. .conversation {
  468. display: flex;
  469. flex-direction: row;
  470. justify-content: space-between;
  471. flex: 1;
  472. padding: 0 5px;
  473. margin-top: 10px;
  474. cursor: pointer;
  475. border-radius: 5px;
  476. align-items: center;
  477. line-height: 30px;
  478. &.active {
  479. background-color: #e6e6e6;
  480. .button {
  481. display: inline-block;
  482. }
  483. }
  484. .title-wrapper {
  485. display: flex;
  486. flex-direction: row;
  487. align-items: center;
  488. }
  489. .title {
  490. padding: 5px 10px;
  491. max-width: 220px;
  492. font-size: 14px;
  493. overflow: hidden;
  494. white-space: nowrap;
  495. text-overflow: ellipsis;
  496. }
  497. .avatar {
  498. width: 28px;
  499. height: 28px;
  500. display: flex;
  501. flex-direction: row;
  502. justify-items: center;
  503. }
  504. // 对话编辑、删除
  505. .button-wrapper {
  506. right: 2px;
  507. display: flex;
  508. flex-direction: row;
  509. justify-items: center;
  510. color: #606266;
  511. .el-icon {
  512. margin-right: 5px;
  513. }
  514. }
  515. }
  516. }
  517. // 角色仓库、清空未设置对话
  518. .tool-box {
  519. line-height: 35px;
  520. display: flex;
  521. justify-content: space-between;
  522. align-items: center;
  523. color: var(--el-text-color);
  524. > div {
  525. display: flex;
  526. align-items: center;
  527. color: #606266;
  528. padding: 0;
  529. margin: 0;
  530. cursor: pointer;
  531. > span {
  532. margin-left: 5px;
  533. }
  534. }
  535. }
  536. }
  537. // 头部
  538. .detail-container {
  539. background: #ffffff;
  540. .header {
  541. display: flex;
  542. flex-direction: row;
  543. align-items: center;
  544. justify-content: space-between;
  545. background: #fbfbfb;
  546. box-shadow: 0 0 0 0 #dcdfe6;
  547. .title {
  548. font-size: 18px;
  549. font-weight: bold;
  550. }
  551. .btns {
  552. display: flex;
  553. width: 300px;
  554. justify-content: space-between;
  555. }
  556. }
  557. }
  558. // main 容器
  559. .main-container {
  560. margin: 0;
  561. padding: 0;
  562. position: relative;
  563. height: 100%;
  564. width: 100%;
  565. .message-container {
  566. position: absolute;
  567. top: 0;
  568. bottom: 0;
  569. left: 0;
  570. right: 0;
  571. //width: 100%;
  572. //height: 100%;
  573. overflow-y: hidden;
  574. padding: 0;
  575. margin: 0;
  576. }
  577. }
  578. // 底部
  579. .footer-container {
  580. display: flex;
  581. flex-direction: column;
  582. height: auto;
  583. margin: 0;
  584. padding: 0;
  585. .prompt-from {
  586. display: flex;
  587. flex-direction: column;
  588. height: auto;
  589. border: 1px solid #e3e3e3;
  590. border-radius: 10px;
  591. margin: 20px 20px;
  592. padding: 9px 10px;
  593. }
  594. .prompt-input {
  595. height: 80px;
  596. //box-shadow: none;
  597. border: none;
  598. box-sizing: border-box;
  599. resize: none;
  600. padding: 0px 2px;
  601. //padding: 5px 5px;
  602. overflow: auto;
  603. }
  604. .prompt-input:focus {
  605. outline: none;
  606. }
  607. .prompt-btns {
  608. display: flex;
  609. justify-content: space-between;
  610. padding-bottom: 0px;
  611. padding-top: 5px;
  612. }
  613. }
  614. </style>