index.vue 15 KB

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