index.vue 17 KB

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