index.vue 16 KB

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