index.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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="onSend"
  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(`diff ${diff} 速度 ${textSpeed.value} `)
  142. // console.log('index < fullText.value.length', index < fullText.value.length, conversationInProgress.value)
  143. if (index < fullText.value.length) {
  144. displayedText.value += fullText.value[index];
  145. index++;
  146. // 更新 message
  147. const lastMessage = list.value[list.value.length - 1]
  148. lastMessage.content = displayedText.value
  149. list.value[list.value - 1] = lastMessage
  150. // 滚动到住下面
  151. await scrollToBottom()
  152. // 重新设置任务
  153. timer = setTimeout(task, textSpeed.value);
  154. } else {
  155. // 不是对话中可以结束
  156. if (!conversationInProgress.value) {
  157. textRoleRunning.value = false
  158. clearTimeout(timer);
  159. console.log("字体滚动退出!")
  160. } else {
  161. // 重新设置任务
  162. timer = setTimeout(task, textSpeed.value);
  163. }
  164. }
  165. }
  166. let timer = setTimeout(task, textSpeed.value);
  167. } finally {
  168. }
  169. };
  170. // ============ 处理对话滚动 ==============
  171. function scrollToBottom(isIgnore?: boolean) {
  172. // isIgnore = isIgnore !== null ? isIgnore : false
  173. nextTick(() => {
  174. if (messageRef.value) {
  175. messageRef.value.scrollToBottom(isIgnore)
  176. }
  177. })
  178. }
  179. // ============= 处理聊天输入回车发送 =============
  180. const onCompositionstart = () => {
  181. isComposing.value = true
  182. }
  183. const onCompositionend = () => {
  184. // console.log('输入结束...')
  185. setTimeout(() => {
  186. isComposing.value = false
  187. }, 200)
  188. }
  189. const onPromptInput = (event) => {
  190. // 非输入法 输入设置为 true
  191. if (!isComposing.value) {
  192. // 回车 event data 是 null
  193. if (event.data == null) {
  194. return
  195. }
  196. isComposing.value = true
  197. }
  198. // 清理定时器
  199. if (inputTimeout.value) {
  200. clearTimeout(inputTimeout.value)
  201. }
  202. // 重置定时器
  203. inputTimeout.value = setTimeout(() => {
  204. isComposing.value = false
  205. }, 400)
  206. }
  207. // ============== 对话消息相关 =================
  208. /**
  209. * 发送消息
  210. */
  211. const onSend = async (event) => {
  212. // 判断用户是否在输入
  213. if (isComposing.value) {
  214. return
  215. }
  216. // 进行中不允许发送
  217. if (conversationInProgress.value) {
  218. return
  219. }
  220. const content = prompt.value?.trim() as string
  221. if (event.key === 'Enter') {
  222. if (event.shiftKey) {
  223. // 插入换行
  224. prompt.value += '\r\n';
  225. event.preventDefault(); // 防止默认的换行行为
  226. } else {
  227. // 发送消息
  228. await doSend(content)
  229. event.preventDefault(); // 防止默认的提交行为
  230. }
  231. }
  232. }
  233. const doSend = async (content: string) => {
  234. if (content.length < 2) {
  235. ElMessage({
  236. message: '请输入内容!',
  237. type: 'error'
  238. })
  239. return
  240. }
  241. if (activeConversationId.value == null) {
  242. ElMessage({
  243. message: '还没创建对话,不能发送!',
  244. type: 'error'
  245. })
  246. return
  247. }
  248. // TODO 芋艿:这块交互要在优化;应该是先插入到 UI 界面,里面会有当前的消息,和正在思考中;之后发起请求;
  249. // 清空输入框
  250. prompt.value = ''
  251. const userMessage = {
  252. conversationId: activeConversationId.value,
  253. content: content
  254. } as ChatMessageVO
  255. // stream
  256. await doSendStream(userMessage)
  257. }
  258. const doSendStream = async (userMessage: ChatMessageVO) => {
  259. // 创建AbortController实例,以便中止请求
  260. conversationInAbortController.value = new AbortController()
  261. // 标记对话进行中
  262. conversationInProgress.value = true
  263. // 设置为空
  264. fullText.value = ''
  265. try {
  266. // 先添加两个假数据,等 stream 返回再替换
  267. list.value.push({
  268. id: -1,
  269. conversationId: activeConversationId.value,
  270. type: 'user',
  271. content: userMessage.content,
  272. createTime: new Date()
  273. } as ChatMessageVO)
  274. list.value.push({
  275. id: -2,
  276. conversationId: activeConversationId.value,
  277. type: 'system',
  278. content: '思考中...',
  279. createTime: new Date()
  280. } as ChatMessageVO)
  281. // 开始滚动
  282. textRoll()
  283. // 发送 event stream
  284. let isFirstMessage = true
  285. ChatMessageApi.sendStream(
  286. userMessage.conversationId, // TODO 芋艿:这里可能要在优化;
  287. userMessage.content,
  288. conversationInAbortController.value,
  289. async (message) => {
  290. const data = JSON.parse(message.data) // TODO 芋艿:类型处理;
  291. // 如果内容为空,就不处理。
  292. if (data.receive.content === '') {
  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. flex-direction: row;
  555. justify-content: flex-end;
  556. //justify-content: space-between;
  557. .btn {
  558. padding: 10px;
  559. }
  560. }
  561. }
  562. }
  563. // main 容器
  564. .main-container {
  565. margin: 0;
  566. padding: 0;
  567. position: relative;
  568. height: 100%;
  569. width: 100%;
  570. .message-container {
  571. position: absolute;
  572. top: 0;
  573. bottom: 0;
  574. left: 0;
  575. right: 0;
  576. //width: 100%;
  577. //height: 100%;
  578. overflow-y: hidden;
  579. padding: 0;
  580. margin: 0;
  581. }
  582. }
  583. // 底部
  584. .footer-container {
  585. display: flex;
  586. flex-direction: column;
  587. height: auto;
  588. margin: 0;
  589. padding: 0;
  590. .prompt-from {
  591. display: flex;
  592. flex-direction: column;
  593. height: auto;
  594. border: 1px solid #e3e3e3;
  595. border-radius: 10px;
  596. margin: 10px 20px 20px 20px;
  597. padding: 9px 10px;
  598. }
  599. .prompt-input {
  600. height: 80px;
  601. //box-shadow: none;
  602. border: none;
  603. box-sizing: border-box;
  604. resize: none;
  605. padding: 0px 2px;
  606. //padding: 5px 5px;
  607. overflow: auto;
  608. }
  609. .prompt-input:focus {
  610. outline: none;
  611. }
  612. .prompt-btns {
  613. display: flex;
  614. justify-content: space-between;
  615. padding-bottom: 0px;
  616. padding-top: 5px;
  617. }
  618. }
  619. </style>