AIQuestions.vue 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. <template>
  2. <!-- 数字人智能问答 -->
  3. <div class="home-container">
  4. <!-- 展开收起侧边栏 -->
  5. <div
  6. class="icon-expand"
  7. :style="{
  8. backgroundColor: drawerVisible ? '#44449c' : '#7F70C840',
  9. left: drawerVisible ? '18%' : '0',
  10. }"
  11. @click="toggleDrawer"
  12. >
  13. <span
  14. class="vertical-lines"
  15. :style="{
  16. color: drawerVisible ? '#8a78d0' : 'white',
  17. }"
  18. >||</span
  19. >
  20. </div>
  21. <!-- 左侧折叠面板 -->
  22. <LeftPanel ref="leftPanelRef" v-if="drawerVisible" />
  23. <!-- 原左侧折叠面板和右侧AI问答 -->
  24. <div class="content-wrapper">
  25. <div class="left-group2">
  26. <div class="title-box">
  27. <div class="box-icon" @click="goBack">
  28. <el-icon class="left-icon"><ArrowLeftBold /></el-icon>
  29. {{ personName }}
  30. </div>
  31. </div>
  32. <div class="selected-image">
  33. <img :src="selectedImage" alt="" />
  34. </div>
  35. </div>
  36. <!-- 右侧AI问答 -->
  37. <div class="number-people">
  38. <div class="content-box">
  39. <!-- AI对话框 -->
  40. <div class="chat-dialog">
  41. <!-- 对话消息列表 -->
  42. <div class="message-list">
  43. <div v-for="(item, index) in messageList" :key="index">
  44. <!-- AI消息 -->
  45. <div class="ai-message" v-if="item.type !== 'user'">
  46. <MarkdownView class="left-text" :content="item.content" />
  47. <!-- {{item.content}} -->
  48. </div>
  49. <!-- 用户消息 -->
  50. <div class="user-message" v-if="item.type === 'user'">
  51. {{ item.content }}
  52. </div>
  53. </div>
  54. </div>
  55. <!-- 默认消息 -->
  56. <DefaultMessage
  57. v-if="showDefaultMessages"
  58. @select-message="handleDefaultMessageSelect"
  59. :category="route.query.category"
  60. :quest-tip="route.query.default"
  61. />
  62. <!-- 输入框和发送按钮 -->
  63. <div class="input-section">
  64. <input
  65. type="text"
  66. v-model="prompt"
  67. placeholder="问我任何问题..."
  68. @keyup.enter="handleSendByKeydown"
  69. />
  70. <button @click="handleSendByButton">发送</button>
  71. </div>
  72. </div>
  73. </div>
  74. </div>
  75. </div>
  76. </div>
  77. </template>
  78. <script setup>
  79. import { ref, onMounted, computed,watch } from "vue";
  80. import { CreateDialogue, sendChatMessageStream } from "@/api/questions.js";
  81. import { useRouter, useRoute } from "vue-router";
  82. import { saveRecord } from '@/api/personalized/index.js'
  83. // 导入全局状态
  84. import { globalState } from '@/utils/globalState.js'
  85. import MarkdownView from "@/components/MarkdownView/index.vue";
  86. import {
  87. Document,
  88. Menu as IconMenu,
  89. Location,
  90. Setting,
  91. ArrowLeftBold,
  92. MagicStick,
  93. ChatLineRound,
  94. Fold,
  95. Expand,
  96. Picture,
  97. Tickets,
  98. User,
  99. } from "@element-plus/icons-vue";
  100. import DefaultMessage from "@/components/DefaultMessage/index.vue";
  101. // 导入图片
  102. // import question from '@/assets/icon/question.png'
  103. // import painting from '@/assets/icon/painting.png'
  104. // import human from '@/assets/icon/human.png'
  105. import LeftPanel from "@/components/LeftPanel.vue";
  106. const leftPanelRef = ref(null);
  107. // 默认消息控制
  108. const showDefaultMessages = ref(true);
  109. const handleDefaultMessageSelect = (message) => {
  110. prompt.value = message;
  111. handleSendByButton();
  112. showDefaultMessages.value = false;
  113. };
  114. // 添加抽屉显示状态
  115. const drawerVisible = ref(true);
  116. // 添加切换抽屉显示状态的函数
  117. const toggleDrawer = () => {
  118. drawerVisible.value = !drawerVisible.value;
  119. };
  120. // 处理菜单展开和关闭
  121. const handleOpen = () => {};
  122. const handleClose = () => {};
  123. // 返回上一页
  124. const goBack = () => {
  125. router.push("/ai-laboratory");
  126. };
  127. const router = useRouter();
  128. const route = useRoute();
  129. const personId = ref(route.query.id);
  130. const personName = ref(route.query.name);
  131. const personIntroduce = ref(route.query.message);
  132. const personImage = ref(route.query.image);
  133. // 渲染实验室携带的人物形象图片
  134. const selectedImage = ref("");
  135. onMounted(() => {
  136. const image = route.query.image;
  137. if (image) {
  138. selectedImage.value = image;
  139. }
  140. });
  141. // 聊天对话
  142. const activeConversationModelPath = ref(null); // 选中的对话编号
  143. const activeConversationId = ref(null); // 选中的对话编号
  144. const activeConversation = ref(null); // 选中的 Conversation
  145. const conversationInProgress = ref(false); // 对话是否正在进行中。目前只有【发送】消息时,会更新为 true,避免切换对话、删除对话等操作,导致 stream 中断
  146. // 消息列表
  147. const messageRef = ref();
  148. const activeMessageList = ref([]); // 选中对话的消息列表
  149. const activeMessageListLoading = ref(false); // activeMessageList 是否正在加载中
  150. const activeMessageListLoadingTimer = ref(); // activeMessageListLoading Timer 定时器。如果加载速度很快,就不进入加载中
  151. // 消息滚动
  152. const textSpeed = ref(50); // Typing speed in milliseconds
  153. const textRoleRunning = ref(false); // Typing speed in milliseconds
  154. // 发送消息输入框
  155. const isComposing = ref(false); // 判断用户是否在输入
  156. const conversationInAbortController = ref(); // 对话进行中 abort 控制器(控制 stream 对话)
  157. const inputTimeout = ref(); // 处理输入中回车的定时器
  158. const prompt = ref(); // prompt
  159. const enableContext = ref(true); // 是否开启上下文
  160. // 接收 Stream 消息
  161. const receiveMessageFullText = ref("");
  162. const receiveMessageDisplayedText = ref("");
  163. // =========== 【聊天对话】相关 ===========
  164. /** 获取对话信息 */
  165. const getConversation = async (id) => {
  166. if (!id) {
  167. return;
  168. }
  169. const conversation = ref({});
  170. if (!conversation) {
  171. return;
  172. }
  173. conversation.systemMessage = personIntroduce.value;
  174. activeConversation.value = conversation;
  175. // activeConversationId.value = personId.value
  176. activeConversationModelPath.value = personImage.value;
  177. };
  178. // =========== 【发送消息】相关 ===========
  179. /** 处理来自 keydown 的发送消息 */
  180. const handleSendByKeydown = async (event) => {
  181. // 判断用户是否在输入
  182. if (isComposing.value) {
  183. return;
  184. }
  185. // 进行中不允许发送
  186. if (conversationInProgress.value) {
  187. return;
  188. }
  189. const content = prompt.value?.trim();
  190. if (event.key === "Enter") {
  191. if (event.shiftKey) {
  192. // 插入换行
  193. prompt.value += "\r\n";
  194. event.preventDefault(); // 防止默认的换行行为
  195. } else {
  196. // 发送消息
  197. await doSendMessage(content);
  198. event.preventDefault(); // 防止默认的提交行为
  199. }
  200. }
  201. };
  202. /** 处理来自【发送】按钮的发送消息 */
  203. const handleSendByButton = () => {
  204. doSendMessage(prompt.value?.trim());
  205. };
  206. /** 处理 prompt 输入变化 */
  207. const handlePromptInput = (event) => {
  208. // 非输入法 输入设置为 true
  209. if (!isComposing.value) {
  210. // 回车 event data 是 null
  211. if (event.data == null) {
  212. return;
  213. }
  214. isComposing.value = true;
  215. }
  216. // 清理定时器
  217. if (inputTimeout.value) {
  218. clearTimeout(inputTimeout.value);
  219. }
  220. // 重置定时器
  221. inputTimeout.value = setTimeout(() => {
  222. isComposing.value = false;
  223. }, 400);
  224. };
  225. // TODO注:是不是可以通过 @keydown.enter、@keydown.shift.enter 来实现,回车发送、shift+回车换行;主要看看,是不是可以简化 isComposing 相关的逻辑
  226. const onCompositionstart = () => {
  227. isComposing.value = true;
  228. };
  229. const onCompositionend = () => {
  230. setTimeout(() => {
  231. isComposing.value = false;
  232. }, 200);
  233. };
  234. // 保存记录
  235. // 年级ID相关
  236. const gradeId = ref('')
  237. onMounted(async () => {
  238. // 从全局状态初始化年级ID
  239. gradeId.value = globalState.initGradeId()
  240. console.log(gradeId.value);
  241. try{
  242. const res = await saveRecord({
  243. brpNjId: gradeId.value,
  244. brpType: "aiCount",
  245. brpProgress: 1
  246. });
  247. console.log(res);
  248. }catch(error){
  249. console.error('保存记录失败:', error);
  250. }
  251. });
  252. /** 真正执行【发送】消息操作 */
  253. const doSendMessage = async (content) => {
  254. // 校验
  255. if (content.length < 1) {
  256. console.error("发送失败,原因:内容为空!");
  257. return;
  258. }
  259. if (activeConversationId.value == null) {
  260. console.error("还没创建对话,不能发送!");
  261. return;
  262. }
  263. // 清空输入框
  264. prompt.value = "";
  265. // 执行发送
  266. await doSendMessageStream({
  267. conversationId: activeConversationId.value,
  268. content: content,
  269. });
  270. };
  271. /** 真正执行【发送】消息操作 */
  272. const doSendMessageStream = async (userMessage) => {
  273. // 创建 AbortController 实例,以便中止请求
  274. conversationInAbortController.value = new AbortController();
  275. // 标记对话进行中
  276. conversationInProgress.value = true;
  277. // 设置为空
  278. receiveMessageFullText.value = "";
  279. try {
  280. // 1.1 先添加两个假数据,等 stream 返回再替换
  281. activeMessageList.value.push({
  282. id: -1,
  283. conversationId: activeConversationId.value,
  284. type: "user",
  285. content: userMessage.content,
  286. createTime: new Date(),
  287. });
  288. activeMessageList.value.push({
  289. id: -2,
  290. conversationId: activeConversationId.value,
  291. type: "assistant",
  292. content: "思考中...",
  293. createTime: new Date(),
  294. });
  295. // 1.3 开始滚动
  296. textRoll();
  297. // 2. 发送 event stream
  298. let isFirstChunk = true; // 是否是第一个 chunk 消息段
  299. await sendChatMessageStream(
  300. userMessage.conversationId,
  301. userMessage.content,
  302. conversationInAbortController.value,
  303. enableContext.value,
  304. async (res) => {
  305. const { code, data, msg } = JSON.parse(res.data);
  306. if (code !== 0) {
  307. console.log(`对话异常! ${msg}`);
  308. return;
  309. }
  310. // 如果内容为空,就不处理。
  311. // if (data.receive.content === '') {
  312. // return
  313. // }
  314. receiveMessageFullText.value =
  315. receiveMessageFullText.value + data.receive.content;
  316. // 首次返回需要添加一个 message 到页面,后面的都是更新
  317. if (isFirstChunk) {
  318. isFirstChunk = false;
  319. // 弹出两个假数据
  320. activeMessageList.value.pop();
  321. activeMessageList.value.pop();
  322. // 更新返回的数据
  323. activeMessageList.value.push(data.send);
  324. activeMessageList.value.push(data.receive);
  325. }
  326. },
  327. (error) => {
  328. console.log(`对话异常! ${error}`);
  329. stopStream();
  330. // 需要抛出异常,禁止重试
  331. throw error;
  332. },
  333. () => {
  334. stopStream();
  335. }
  336. );
  337. } catch {}
  338. };
  339. /** 停止 stream 流式调用 */
  340. const stopStream = async () => {
  341. // tip:如果 stream 进行中的 message,就需要调用 controller 结束
  342. if (conversationInAbortController.value) {
  343. conversationInAbortController.value.abort();
  344. }
  345. // 设置为 false
  346. conversationInProgress.value = false;
  347. };
  348. /**
  349. * 消息列表
  350. *
  351. * 和 {@link #getMessageList()} 的差异是,把 systemMessage 考虑进去
  352. */
  353. const messageList = computed(() => {
  354. if (activeMessageList.value.length > 0) {
  355. return activeMessageList.value;
  356. }
  357. // 没有消息时,如果有 systemMessage 则展示它
  358. if (activeConversation.value?.systemMessage) {
  359. let systemMessage = {
  360. id: 0,
  361. type: "system",
  362. content: activeConversation.value.systemMessage,
  363. };
  364. activeMessageList.value.push(systemMessage);
  365. return [systemMessage];
  366. }
  367. return [];
  368. });
  369. // ============== 【消息滚动】相关 =============
  370. /** 滚动到 message 底部 */
  371. const scrollToBottom = async (isIgnore) => {
  372. // if (messageRef.value) {
  373. // messageRef.value.scrollToBottom(isIgnore)
  374. // }
  375. };
  376. /** 自提滚动效果 */
  377. const textRoll = async () => {
  378. let index = 0;
  379. try {
  380. // 只能执行一次
  381. if (textRoleRunning.value) {
  382. return;
  383. }
  384. // 设置状态
  385. textRoleRunning.value = true;
  386. receiveMessageDisplayedText.value = "";
  387. const task = async () => {
  388. // 调整速度
  389. const diff =
  390. (receiveMessageFullText.value.length -
  391. receiveMessageDisplayedText.value.length) /
  392. 10;
  393. if (diff > 5) {
  394. textSpeed.value = 10;
  395. } else if (diff > 2) {
  396. textSpeed.value = 30;
  397. } else if (diff > 1.5) {
  398. textSpeed.value = 50;
  399. } else {
  400. textSpeed.value = 100;
  401. }
  402. // 对话结束,就按 30 的速度
  403. if (!conversationInProgress.value) {
  404. textSpeed.value = 10;
  405. }
  406. if (index < receiveMessageFullText.value.length) {
  407. receiveMessageDisplayedText.value +=
  408. receiveMessageFullText.value[index];
  409. index++;
  410. // 更新 message
  411. const lastMessage =
  412. activeMessageList.value[activeMessageList.value.length - 1];
  413. lastMessage.content = receiveMessageDisplayedText.value;
  414. // 滚动到住下面
  415. await scrollToBottom();
  416. // 重新设置任务
  417. timer = setTimeout(task, textSpeed.value);
  418. } else {
  419. // 不是对话中可以结束
  420. if (!conversationInProgress.value) {
  421. textRoleRunning.value = false;
  422. clearTimeout(timer);
  423. } else {
  424. // 重新设置任务
  425. timer = setTimeout(task, textSpeed.value);
  426. }
  427. }
  428. };
  429. let timer = setTimeout(task, textSpeed.value);
  430. } catch {}
  431. };
  432. /** 初始化 **/
  433. onMounted(async () => {
  434. if (personId.value) {
  435. // 智能问答
  436. CreateDialogue({ roleId: personId.value })
  437. .then((res) => {
  438. console.log("创建会话:", res);
  439. activeConversationId.value = res.data;
  440. })
  441. .catch((error) => {
  442. console.error("请求出错:", error);
  443. });
  444. await getConversation(personId.value);
  445. }
  446. // 获取列表数据
  447. // activeMessageListLoading.value = true
  448. });
  449. </script>
  450. <style scoped lang="scss">
  451. @use "sass:math";
  452. // 定义rpx转换函数
  453. @function rpx($px) {
  454. @return math.div($px, 750) * 100vw;
  455. }
  456. /* 添加过渡样式 */
  457. .drawer-slide-enter-active,
  458. .drawer-slide-leave-active {
  459. transition: all 0.3s ease;
  460. }
  461. .drawer-slide-enter-from,
  462. .drawer-slide-leave-to {
  463. transform: translateX(-100%);
  464. opacity: 0;
  465. }
  466. .home-container {
  467. position: fixed;
  468. top: 0;
  469. left: 0;
  470. right: 0;
  471. bottom: 0;
  472. display: flex;
  473. flex-direction: row;
  474. gap: rpx(0);
  475. background: linear-gradient(to bottom, #e2ddfc, #f1effd);
  476. }
  477. .icon-expand {
  478. width: rpx(8);
  479. height: rpx(35);
  480. border-top-right-radius: rpx(5);
  481. border-bottom-right-radius: rpx(5);
  482. z-index: 9999;
  483. position: absolute;
  484. top: 50%;
  485. left: 18%;
  486. transform: translateY(-50%);
  487. background-color: #44449c;
  488. cursor: pointer; // 添加鼠标指针样式
  489. clip-path: polygon(0 0, 100% 15%, 100% 85%, 0 100%);
  490. display: flex;
  491. justify-content: center;
  492. align-items: center;
  493. transition: all 0.3s ease;
  494. }
  495. .icon-expand .vertical-lines {
  496. color: #8a78d0;
  497. font-size: rpx(10);
  498. }
  499. .menu-icon {
  500. width: rpx(11);
  501. height: rpx(11);
  502. margin-right: rpx(2);
  503. }
  504. .content-wrapper {
  505. display: flex;
  506. flex: 1;
  507. }
  508. .left-group {
  509. width: rpx(135);
  510. height: 100%;
  511. background: linear-gradient(to bottom, #001169, #8a78d0);
  512. }
  513. .mb-2 {
  514. color: black;
  515. margin-top: rpx(1);
  516. }
  517. .tac ::v-deep(.el-menu) {
  518. background-color: transparent;
  519. border: none;
  520. width: 100%;
  521. margin-top: rpx(55);
  522. margin-left: rpx(10);
  523. }
  524. .el-menu-item {
  525. width: rpx(115);
  526. height: rpx(25);
  527. margin-bottom: rpx(5);
  528. border-radius: rpx(6);
  529. color: white;
  530. font-size: rpx(8);
  531. }
  532. .el-menu-item .el-icon svg {
  533. font-size: rpx(15);
  534. color: white;
  535. }
  536. .el-menu ::v-deep(.el-menu-item:hover),
  537. .el-menu ::v-deep(.el-menu-item:focus),
  538. .el-menu ::v-deep(.el-menu-item:active) {
  539. background: linear-gradient(
  540. to bottom,
  541. #ffefb0,
  542. #ffcc00
  543. ); /* 设置悬停、聚焦、点击状态下的背景色 */
  544. box-shadow: 0 8px 8px rgb(0, 0, 0, 0.3);
  545. color: black;
  546. font-size: rpx(8);
  547. }
  548. .el-menu .el-menu-item.is-active {
  549. background: linear-gradient(to bottom, #fee78a, #ffce1b);
  550. color: black;
  551. font-size: rpx(8);
  552. box-shadow: 0 4px 8px rgba(3, 3, 3, 0.3);
  553. }
  554. // 侧边栏
  555. .left-group2 {
  556. width: rpx(150);
  557. height: 100%;
  558. display: flex;
  559. background-color: #ece9fd;
  560. }
  561. .left-group2 img {
  562. width: rpx(120);
  563. // height: auto;
  564. }
  565. .selected-image {
  566. flex: 1;
  567. margin: auto;
  568. margin-left: rpx(-60);
  569. }
  570. .title-box {
  571. height: rpx(50);
  572. }
  573. .box-icon {
  574. width: 100%;
  575. height: 100%;
  576. flex: 1;
  577. display: flex; // 添加 flex 布局
  578. align-items: center; // 垂直居中
  579. color: black; // 设置图标颜色为白色
  580. padding-left: rpx(15);
  581. font-size: rpx(10); // 设置图标大小,可按需调整
  582. cursor: pointer; // 添加鼠标指针样式
  583. }
  584. .box-icon .left-icon {
  585. margin-left: rpx(10);
  586. margin-right: rpx(5); // 设置图标和文字之间的间距 ;
  587. }
  588. .number-people {
  589. flex: 1;
  590. height: 100%;
  591. display: flex;
  592. background-color: #ece9fd;
  593. }
  594. .content-box {
  595. flex: 1;
  596. margin-top: rpx(10);
  597. margin-bottom: rpx(10);
  598. margin-right: rpx(10);
  599. border-radius: rpx(15);
  600. background: rgba($color: #ffffff, $alpha: 0.5);
  601. }
  602. // 对话框
  603. .chat-dialog {
  604. display: flex;
  605. flex-direction: column;
  606. height: 100%;
  607. }
  608. .message-list {
  609. flex: 1;
  610. overflow-y: auto;
  611. padding: rpx(15);
  612. }
  613. /* 自定义滚动条样式 */
  614. .message-list::-webkit-scrollbar {
  615. width: rpx(2); /* 滚动条宽度 */
  616. }
  617. .message-list::-webkit-scrollbar-track {
  618. background: #f1effd; /* 滚动条轨道背景色 */
  619. border-radius: rpx(4);
  620. }
  621. .message-list::-webkit-scrollbar-thumb {
  622. background: #e2ddfc; /* 滚动条滑块颜色 */
  623. border-radius: rpx(4);
  624. }
  625. .message-list::-webkit-scrollbar-thumb:hover {
  626. background: #e2ddfc; /* 滚动条滑块 hover 状态颜色 */
  627. }
  628. .message-list .user-message {
  629. background-color: #ffffff;
  630. margin-left: auto; // 消息靠右显示
  631. margin-right: 0; // 重置右边距
  632. margin-bottom: rpx(10);
  633. max-width: rpx(400);
  634. font-size: rpx(8);
  635. width: fit-content; // 宽度随文字内容变化
  636. border-radius: rpx(5);
  637. padding: rpx(5);
  638. text-align: left; // 文字左对齐
  639. }
  640. .message-list .ai-message {
  641. background-color: #ffdd55;
  642. margin-left: 0; // 消息靠左显示
  643. margin-right: auto; // 重置右边距
  644. margin-bottom: rpx(10);
  645. width: fit-content;
  646. max-width: rpx(400);
  647. padding: rpx(5);
  648. font-size: rpx(8);
  649. border-radius: rpx(5);
  650. text-align: left; // 文字左对齐
  651. }
  652. .input-section {
  653. display: flex;
  654. padding: rpx(10);
  655. gap: rpx(10);
  656. }
  657. .input-section input {
  658. flex: 1;
  659. padding: rpx(5);
  660. font-size: rpx(7);
  661. border: 1px solid #ccc;
  662. border-radius: rpx(5);
  663. }
  664. .input-section button {
  665. padding: rpx(5) rpx(15);
  666. background: linear-gradient(
  667. to bottom,
  668. #fee78a,
  669. #ffce1b
  670. ); /* 设置悬停、聚焦、点击状态下的背景色 */
  671. color: black;
  672. border: none;
  673. font-size: rpx(7);
  674. border-radius: rpx(5);
  675. cursor: pointer;
  676. box-shadow: 0 4px 8px rgba(202, 52, 52, 0.3);
  677. }
  678. </style>