index.vue 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. <template>
  2. <el-container class="ai-layout">
  3. <!-- 左侧:会话列表 -->
  4. <Conversation :active-id="activeConversationId"
  5. ref="conversationRef"
  6. @onConversationClick="handleConversationClick"
  7. @onConversationClear="handlerConversationClear"
  8. @onConversationDelete="handlerConversationDelete"
  9. />
  10. <!-- 右侧:会话详情 -->
  11. <el-container class="detail-container">
  12. <!-- 右顶部 TODO 芋艿:右对齐 -->
  13. <el-header class="header">
  14. <div class="title">
  15. {{ activeConversation?.title ? activeConversation?.title : '对话' }}
  16. </div>
  17. <div class="btns" v-if="activeConversation">
  18. <!-- TODO @fan:样式改下;这里我已经改成点击后,弹出了 -->
  19. <el-button type="primary" bg text="plain" size="small" @click="openChatConversationUpdateForm">
  20. <span v-html="activeConversation?.modelName"></span>
  21. <Icon icon="ep:setting" style="margin-left: 10px"/>
  22. </el-button>
  23. <el-button size="small" class="btn" @click="handlerMessageClear">
  24. <img src="@/assets/ai/clear.svg" style="height: 14px;" />
  25. </el-button>
  26. <el-button size="small" :icon="Download" class="btn" />
  27. <el-button size="small" :icon="Top" class="btn" @click="handlerGoTop" />
  28. </div>
  29. </el-header>
  30. <!-- main -->
  31. <el-main class="main-container" >
  32. <div >
  33. <div class="message-container" >
  34. <MessageLoading v-if="listLoading" />
  35. <MessageNewChat v-if="!activeConversation" @on-new-chat="handlerNewChat" />
  36. <ChatEmpty v-if="!listLoading && list.length === 0 && activeConversation" @on-prompt="doSend"/>
  37. <Message v-if="!listLoading && list.length > 0"
  38. ref="messageRef"
  39. :list="list"
  40. @on-delete-success="handlerMessageDelete" />
  41. </div>
  42. </div>
  43. </el-main>
  44. <!-- 底部 -->
  45. <el-footer class="footer-container">
  46. <form class="prompt-from">
  47. <textarea
  48. class="prompt-input"
  49. v-model="prompt"
  50. @keydown="onSend"
  51. @input="onPromptInput"
  52. @compositionstart="onCompositionstart"
  53. @compositionend="onCompositionend"
  54. placeholder="问我任何问题...(Shift+Enter 换行,按下 Enter 发送)"
  55. ></textarea>
  56. <div class="prompt-btns">
  57. <div>
  58. <el-switch v-model="enableContext" /> <span style="font-size: 14px; color: #8f8f8f;">上下文</span>
  59. </div>
  60. <el-button
  61. type="primary"
  62. size="default"
  63. @click="onSendBtn"
  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 MessageNewChat from './MessageNewChat.vue'
  95. import {ChatMessageApi, ChatMessageVO} from '@/api/ai/chat/message'
  96. import {ChatConversationApi, ChatConversationVO} from '@/api/ai/chat/conversation'
  97. import { getUserProfile, ProfileVO } from '@/api/system/user/profile'
  98. import {useClipboard} from '@vueuse/core'
  99. import ChatConversationUpdateForm from "@/views/ai/chat/components/ChatConversationUpdateForm.vue";
  100. import {Download, Top} from "@element-plus/icons-vue";
  101. const route = useRoute() // 路由
  102. const message = useMessage() // 消息弹窗
  103. const {copy} = useClipboard() // 初始化 copy 到粘贴板
  104. // ref 属性定义
  105. const activeConversationId = ref<string | null>(null) // 选中的对话编号
  106. const activeConversation = ref<ChatConversationVO | null>(null) // 选中的 Conversation
  107. const conversationInProgress = ref(false) // 对话进行中
  108. const conversationInAbortController = ref<any>() // 对话进行中 abort 控制器(控制 stream 对话)
  109. const inputTimeout = ref<any>() // 处理输入中回车的定时器
  110. const prompt = ref<string>() // prompt
  111. const userInfo = ref<ProfileVO>() // 用户信息
  112. const enableContext = ref<boolean>(true) // 是否开启上下文
  113. const fullText = ref('');
  114. const displayedText = ref('');
  115. const textSpeed = ref<number>(50); // Typing speed in milliseconds
  116. const textRoleRunning = ref<boolean>(false); // Typing speed in milliseconds
  117. // chat message 列表
  118. const list = ref<ChatMessageVO[]>([]) // 列表的数据
  119. const listLoading = ref<boolean>(false) // 是否加载中
  120. const listLoadingTime = ref<any>() // time定时器,如果加载速度很快,就不进入加载中
  121. // 判断 消息列表 滚动的位置(用于判断是否需要滚动到消息最下方)
  122. const messageRef = ref()
  123. const conversationRef = ref()
  124. const isComposing = ref(false) // 判断用户是否在输入
  125. // 默认 role 头像
  126. const defaultRoleAvatar = 'http://test.yudao.iocoder.cn/eaef5f41acb911dd718429a0702dcc3c61160d16e57ba1d543132fab58934f9f.png'
  127. // =========== 自提滚动效果
  128. const textRoll = async () => {
  129. let index = 0;
  130. try {
  131. // 只能执行一次
  132. if (textRoleRunning.value) {
  133. return
  134. }
  135. // 设置状态
  136. textRoleRunning.value = true
  137. displayedText.value = ''
  138. const task = async () => {
  139. // 调整速度
  140. const diff = (fullText.value.length - displayedText.value.length) / 10
  141. if (diff > 5) {
  142. textSpeed.value = 10
  143. } else if (diff > 2) {
  144. textSpeed.value = 30
  145. } else if (diff > 1.5) {
  146. textSpeed.value = 50
  147. } else {
  148. textSpeed.value = 100
  149. }
  150. // 对话结束,就按30的速度
  151. if (!conversationInProgress.value) {
  152. textSpeed.value = 10
  153. }
  154. // console.log('index < fullText.value.length', index < fullText.value.length, conversationInProgress.value)
  155. if (index < fullText.value.length) {
  156. displayedText.value += fullText.value[index];
  157. index++;
  158. // 更新 message
  159. const lastMessage = list.value[list.value.length - 1]
  160. lastMessage.content = displayedText.value
  161. list.value[list.value - 1] = lastMessage
  162. // 滚动到住下面
  163. await scrollToBottom()
  164. // 重新设置任务
  165. timer = setTimeout(task, textSpeed.value);
  166. } else {
  167. // 不是对话中可以结束
  168. if (!conversationInProgress.value) {
  169. textRoleRunning.value = false
  170. clearTimeout(timer);
  171. console.log("字体滚动退出!")
  172. } else {
  173. // 重新设置任务
  174. timer = setTimeout(task, textSpeed.value);
  175. }
  176. }
  177. }
  178. let timer = setTimeout(task, textSpeed.value);
  179. } finally {
  180. }
  181. };
  182. // ============ 处理对话滚动 ==============
  183. function scrollToBottom(isIgnore?: boolean) {
  184. // isIgnore = isIgnore !== null ? isIgnore : false
  185. nextTick(() => {
  186. if (messageRef.value) {
  187. messageRef.value.scrollToBottom(isIgnore)
  188. }
  189. })
  190. }
  191. // ============= 处理聊天输入回车发送 =============
  192. const onCompositionstart = () => {
  193. isComposing.value = true
  194. }
  195. const onCompositionend = () => {
  196. // console.log('输入结束...')
  197. setTimeout(() => {
  198. isComposing.value = false
  199. }, 200)
  200. }
  201. const onPromptInput = (event) => {
  202. // 非输入法 输入设置为 true
  203. if (!isComposing.value) {
  204. // 回车 event data 是 null
  205. if (event.data == null) {
  206. return
  207. }
  208. isComposing.value = true
  209. }
  210. // 清理定时器
  211. if (inputTimeout.value) {
  212. clearTimeout(inputTimeout.value)
  213. }
  214. // 重置定时器
  215. inputTimeout.value = setTimeout(() => {
  216. isComposing.value = false
  217. }, 400)
  218. }
  219. // ============== 对话消息相关 =================
  220. /**
  221. * 发送消息
  222. */
  223. const onSend = async (event) => {
  224. // 判断用户是否在输入
  225. if (isComposing.value) {
  226. return
  227. }
  228. // 进行中不允许发送
  229. if (conversationInProgress.value) {
  230. return
  231. }
  232. const content = prompt.value?.trim() as string
  233. if (event.key === 'Enter') {
  234. if (event.shiftKey) {
  235. // 插入换行
  236. prompt.value += '\r\n';
  237. event.preventDefault(); // 防止默认的换行行为
  238. } else {
  239. // 发送消息
  240. await doSend(content)
  241. event.preventDefault(); // 防止默认的提交行为
  242. }
  243. }
  244. }
  245. const onSendBtn = async () => {
  246. await doSend(prompt.value?.trim() as string)
  247. }
  248. const doSend = async (content: string) => {
  249. if (content.length < 2) {
  250. ElMessage({
  251. message: '请输入内容!',
  252. type: 'error'
  253. })
  254. return
  255. }
  256. if (activeConversationId.value == null) {
  257. ElMessage({
  258. message: '还没创建对话,不能发送!',
  259. type: 'error'
  260. })
  261. return
  262. }
  263. // TODO 芋艿:这块交互要在优化;应该是先插入到 UI 界面,里面会有当前的消息,和正在思考中;之后发起请求;
  264. // 清空输入框
  265. prompt.value = ''
  266. const userMessage = {
  267. conversationId: activeConversationId.value,
  268. content: content
  269. } as ChatMessageVO
  270. // stream
  271. await doSendStream(userMessage)
  272. }
  273. const doSendStream = async (userMessage: ChatMessageVO) => {
  274. // 创建AbortController实例,以便中止请求
  275. conversationInAbortController.value = new AbortController()
  276. // 标记对话进行中
  277. conversationInProgress.value = true
  278. // 设置为空
  279. fullText.value = ''
  280. try {
  281. // 先添加两个假数据,等 stream 返回再替换
  282. list.value.push({
  283. id: -1,
  284. conversationId: activeConversationId.value,
  285. type: 'user',
  286. content: userMessage.content,
  287. userAvatar: userInfo.value?.avatar,
  288. createTime: new Date()
  289. } as ChatMessageVO)
  290. list.value.push({
  291. id: -2,
  292. conversationId: activeConversationId.value,
  293. type: 'system',
  294. content: '思考中...',
  295. roleAvatar: (activeConversation.value as ChatConversationVO).roleAvatar,
  296. createTime: new Date()
  297. } as ChatMessageVO)
  298. // 滚动到最下面
  299. nextTick(async () => {
  300. await scrollToBottom()
  301. })
  302. // 开始滚动
  303. textRoll()
  304. // 发送 event stream
  305. let isFirstMessage = true
  306. ChatMessageApi.sendStream(
  307. userMessage.conversationId, // TODO 芋艿:这里可能要在优化;
  308. userMessage.content,
  309. conversationInAbortController.value,
  310. enableContext.value,
  311. async (message) => {
  312. const data = JSON.parse(message.data) // TODO 芋艿:类型处理;
  313. // 如果内容为空,就不处理。
  314. if (data.receive.content === '') {
  315. return
  316. }
  317. // 首次返回需要添加一个 message 到页面,后面的都是更新
  318. if (isFirstMessage) {
  319. isFirstMessage = false
  320. // 弹出两个 假数据
  321. list.value.pop()
  322. list.value.pop()
  323. // 更新返回的数据
  324. list.value.push(data.send)
  325. list.value.push(data.receive)
  326. }
  327. // debugger
  328. fullText.value = fullText.value + data.receive.content
  329. // 滚动到最下面
  330. await scrollToBottom()
  331. },
  332. (error) => {
  333. console.log('onError')
  334. // 标记对话结束
  335. conversationInProgress.value = false
  336. // 结束 stream 对话
  337. conversationInAbortController.value.abort()
  338. },
  339. () => {
  340. console.log('onClose')
  341. // 标记对话结束
  342. conversationInProgress.value = false
  343. // 结束 stream 对话
  344. conversationInAbortController.value.abort()
  345. }
  346. )
  347. } finally {
  348. }
  349. }
  350. const stopStream = async () => {
  351. console.log('stopStream...')
  352. // tip:如果 stream 进行中的 message,就需要调用 controller 结束
  353. if (conversationInAbortController.value) {
  354. conversationInAbortController.value.abort()
  355. }
  356. // 设置为 false
  357. conversationInProgress.value = false
  358. }
  359. // ============== message 数据 =================
  360. /**
  361. * 获取 - message 列表
  362. */
  363. const getMessageList = async () => {
  364. try {
  365. // time 定时器,如果加载速度很快,就不进入加载中
  366. listLoadingTime.value = setTimeout(() => {
  367. listLoading.value = true
  368. }, 60)
  369. if (activeConversationId.value === null) {
  370. return
  371. }
  372. // 获取列表数据
  373. const messageListRes = await ChatMessageApi.messageList(activeConversationId.value)
  374. // 设置用户头像
  375. messageListRes.map(item => {
  376. // 设置 role 默认头像
  377. item.roleAvatar = item.roleAvatar ? item.roleAvatar : defaultRoleAvatar
  378. })
  379. list.value = messageListRes
  380. // 滚动到最下面
  381. await nextTick(() => {
  382. // 滚动到最后
  383. scrollToBottom()
  384. })
  385. } finally {
  386. // time 定时器,如果加载速度很快,就不进入加载中
  387. if (listLoadingTime.value) {
  388. clearTimeout(listLoadingTime.value)
  389. }
  390. // 加载结束
  391. listLoading.value = false
  392. }
  393. }
  394. /** 修改聊天会话 */
  395. const chatConversationUpdateFormRef = ref()
  396. const openChatConversationUpdateForm = async () => {
  397. chatConversationUpdateFormRef.value.open(activeConversationId.value)
  398. }
  399. /**
  400. * 对话 - 标题修改成功
  401. */
  402. const handlerTitleSuccess = async () => {
  403. // TODO 需要刷新 对话列表
  404. await getConversation(activeConversationId.value)
  405. }
  406. /**
  407. * 对话 - 点击
  408. */
  409. const handleConversationClick = async (conversation: ChatConversationVO) => {
  410. // 对话进行中,不允许切换
  411. if (conversationInProgress.value) {
  412. await message.alert("对话中,不允许切换!")
  413. return false
  414. }
  415. // 更新选中的对话 id
  416. activeConversationId.value = conversation.id
  417. activeConversation.value = conversation
  418. // 处理进行中的对话
  419. if (conversationInProgress.value) {
  420. await stopStream()
  421. }
  422. // 刷新 message 列表
  423. await getMessageList()
  424. // 滚动底部
  425. scrollToBottom(true)
  426. return true
  427. }
  428. /**
  429. * 对话 - 清理全部对话
  430. */
  431. const handlerConversationClear = async ()=> {
  432. activeConversationId.value = null
  433. activeConversation.value = null
  434. list.value = []
  435. }
  436. /**
  437. * 对话 - 删除
  438. */
  439. const handlerConversationDelete = async (delConversation: ChatConversationVO) => {
  440. // 删除的对话如果是当前选中的,那么久重置
  441. if (activeConversationId.value === delConversation.id) {
  442. await handlerConversationClear()
  443. }
  444. }
  445. /**
  446. * 对话 - 获取
  447. */
  448. const getConversation = async (id: string | null) => {
  449. if (!id) {
  450. return
  451. }
  452. const conversation: ChatConversationVO = await ChatConversationApi.getChatConversationMy(id)
  453. if (conversation) {
  454. activeConversation.value = conversation
  455. activeConversationId.value = conversation.id
  456. }
  457. }
  458. /**
  459. * 对话 - 新建
  460. */
  461. const handlerNewChat = async () => {
  462. // 创建对话
  463. await conversationRef.value.createConversation()
  464. }
  465. // ============ message ===========
  466. /**
  467. * 删除 message
  468. */
  469. const handlerMessageDelete = async () => {
  470. // 刷新 message
  471. await getMessageList()
  472. }
  473. /**
  474. * 回到顶部
  475. */
  476. const handlerGoTop = async () => {
  477. await messageRef.value.handlerGoTop()
  478. }
  479. /**
  480. * message 清除
  481. */
  482. const handlerMessageClear = async () => {
  483. if (!activeConversationId.value) {
  484. return
  485. }
  486. // 确认提示
  487. await message.delConfirm("确认清空对话消息?")
  488. // 清空对话
  489. await ChatMessageApi.deleteByConversationId(activeConversationId.value as string)
  490. // 刷新 message 列表
  491. await getMessageList()
  492. }
  493. /** 初始化 **/
  494. onMounted(async () => {
  495. // 设置当前对话 TODO 角色仓库过来的,自带 conversationId 需要选中
  496. if (route.query.conversationId) {
  497. const id = route.query.conversationId as string
  498. activeConversationId.value = id
  499. await getConversation(id)
  500. }
  501. // 获取列表数据
  502. listLoading.value = true
  503. await getMessageList()
  504. // 获取用户信息
  505. userInfo.value = await getUserProfile()
  506. })
  507. </script>
  508. <style lang="scss" scoped>
  509. .ai-layout {
  510. // TODO @范 这里height不能 100% 先这样临时处理
  511. position: absolute;
  512. flex: 1;
  513. top: 0;
  514. left: 0;
  515. height: 100%;
  516. width: 100%;
  517. }
  518. .conversation-container {
  519. position: relative;
  520. display: flex;
  521. flex-direction: column;
  522. justify-content: space-between;
  523. padding: 0 10px;
  524. padding-top: 10px;
  525. .btn-new-conversation {
  526. padding: 18px 0;
  527. }
  528. .search-input {
  529. margin-top: 20px;
  530. }
  531. .conversation-list {
  532. margin-top: 20px;
  533. .conversation {
  534. display: flex;
  535. flex-direction: row;
  536. justify-content: space-between;
  537. flex: 1;
  538. padding: 0 5px;
  539. margin-top: 10px;
  540. cursor: pointer;
  541. border-radius: 5px;
  542. align-items: center;
  543. line-height: 30px;
  544. &.active {
  545. background-color: #e6e6e6;
  546. .button {
  547. display: inline-block;
  548. }
  549. }
  550. .title-wrapper {
  551. display: flex;
  552. flex-direction: row;
  553. align-items: center;
  554. }
  555. .title {
  556. padding: 5px 10px;
  557. max-width: 220px;
  558. font-size: 14px;
  559. overflow: hidden;
  560. white-space: nowrap;
  561. text-overflow: ellipsis;
  562. }
  563. .avatar {
  564. width: 28px;
  565. height: 28px;
  566. display: flex;
  567. flex-direction: row;
  568. justify-items: center;
  569. }
  570. // 对话编辑、删除
  571. .button-wrapper {
  572. right: 2px;
  573. display: flex;
  574. flex-direction: row;
  575. justify-items: center;
  576. color: #606266;
  577. .el-icon {
  578. margin-right: 5px;
  579. }
  580. }
  581. }
  582. }
  583. // 角色仓库、清空未设置对话
  584. .tool-box {
  585. line-height: 35px;
  586. display: flex;
  587. justify-content: space-between;
  588. align-items: center;
  589. color: var(--el-text-color);
  590. > div {
  591. display: flex;
  592. align-items: center;
  593. color: #606266;
  594. padding: 0;
  595. margin: 0;
  596. cursor: pointer;
  597. > span {
  598. margin-left: 5px;
  599. }
  600. }
  601. }
  602. }
  603. // 头部
  604. .detail-container {
  605. background: #ffffff;
  606. .header {
  607. display: flex;
  608. flex-direction: row;
  609. align-items: center;
  610. justify-content: space-between;
  611. background: #fbfbfb;
  612. box-shadow: 0 0 0 0 #dcdfe6;
  613. .title {
  614. font-size: 18px;
  615. font-weight: bold;
  616. }
  617. .btns {
  618. display: flex;
  619. width: 300px;
  620. flex-direction: row;
  621. justify-content: flex-end;
  622. //justify-content: space-between;
  623. .btn {
  624. padding: 10px;
  625. }
  626. }
  627. }
  628. }
  629. // main 容器
  630. .main-container {
  631. margin: 0;
  632. padding: 0;
  633. position: relative;
  634. height: 100%;
  635. width: 100%;
  636. .message-container {
  637. position: absolute;
  638. top: 0;
  639. bottom: 0;
  640. left: 0;
  641. right: 0;
  642. //width: 100%;
  643. //height: 100%;
  644. overflow-y: hidden;
  645. padding: 0;
  646. margin: 0;
  647. }
  648. }
  649. // 底部
  650. .footer-container {
  651. display: flex;
  652. flex-direction: column;
  653. height: auto;
  654. margin: 0;
  655. padding: 0;
  656. .prompt-from {
  657. display: flex;
  658. flex-direction: column;
  659. height: auto;
  660. border: 1px solid #e3e3e3;
  661. border-radius: 10px;
  662. margin: 10px 20px 20px 20px;
  663. padding: 9px 10px;
  664. }
  665. .prompt-input {
  666. height: 80px;
  667. //box-shadow: none;
  668. border: none;
  669. box-sizing: border-box;
  670. resize: none;
  671. padding: 0px 2px;
  672. //padding: 5px 5px;
  673. overflow: auto;
  674. }
  675. .prompt-input:focus {
  676. outline: none;
  677. }
  678. .prompt-btns {
  679. display: flex;
  680. justify-content: space-between;
  681. padding-bottom: 0px;
  682. padding-top: 5px;
  683. }
  684. }
  685. </style>