aiIndex.vue 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. <template>
  2. <div class="chat-container">
  3. <div class="content">
  4. <div class="messages">
  5. <ul>
  6. <li
  7. v-for="message in messages"
  8. :key="message.id"
  9. :class="[
  10. message.user,
  11. message.user === 'user' ? 'user-message' : '',
  12. ]"
  13. >
  14. <!-- 添加判断,如果是机器人的消息也显示头像 -->
  15. <div class="message_name">
  16. <div
  17. class="avatar"
  18. :class="{
  19. 'user-avatar': message.user === 'user',
  20. 'bot-avatar': message.user === 'bot',
  21. }"
  22. ></div>
  23. <div class="name">
  24. <span
  25. class="sender-name"
  26. style="color: #666666"
  27. v-if="message.user === 'user'"
  28. >你</span
  29. >
  30. <span class="sender-name" v-if="message.user === 'bot'"
  31. >AI助理</span
  32. >
  33. </div>
  34. </div>
  35. <!-- 使用 v-html 来渲染 Markdown 文本 -->
  36. <div class="message-content">
  37. <div class="message-text">
  38. <!-- 如果有图片,先显示图片 -->
  39. <div v-if="message.imageUrls && message.imageUrls.length" class="message-images">
  40. <img
  41. v-for="(url, index) in message.imageUrls"
  42. :key="index"
  43. :src="url"
  44. class="uploaded-image"
  45. alt="Uploaded content"
  46. />
  47. </div>
  48. <!-- 如果有文档,显示文档预览 -->
  49. <div v-if="message.documentUrls && message.documentUrls.length" class="message-documents">
  50. <div
  51. v-for="(doc, index) in message.documentUrls"
  52. :key="index"
  53. class="document-preview-item"
  54. >
  55. <i class="el-icon-document"></i>
  56. <span class="document-name">{{ getDocumentName(doc) }}</span>
  57. <a :href="doc" target="_blank" class="document-link">查看文档</a>
  58. </div>
  59. </div>
  60. <!-- 显示文本内容 -->
  61. <div v-html="renderMarkdown(message.message)" @click="handleLinkClick"></div>
  62. </div>
  63. </div>
  64. </li>
  65. </ul>
  66. </div>
  67. <!-- <div class="input-container">
  68. <textarea
  69. v-model="userInput"
  70. rows="4"
  71. @keydown="handleKeydown"
  72. placeholder="发送消息..."
  73. ></textarea>
  74. <button @click="sendMessage" class="btn">发送</button>
  75. </div> -->
  76. <div class="input-container">
  77. <!-- 文件上传预览区 -->
  78. <div
  79. class="upload-preview"
  80. v-if="uploadFiles.length > 0 || documents.length > 0"
  81. >
  82. <div
  83. v-for="(file, index) in uploadFiles"
  84. :key="'img-' + index"
  85. class="preview-item image-preview"
  86. >
  87. <div class="preview-content">
  88. <img
  89. v-if="file.type.startsWith('image/')"
  90. :src="file.preview"
  91. class="preview-image"
  92. alt="preview"
  93. />
  94. </div>
  95. <i class="el-icon-close remove-file" @click="removeFile(index)"></i>
  96. </div>
  97. <div
  98. v-for="(doc, index) in documents"
  99. :key="'doc-' + index"
  100. class="preview-item document-preview"
  101. >
  102. <div class="preview-content">
  103. <i class="el-icon-document"></i>
  104. <span class="doc-name">{{ doc.name }}</span>
  105. </div>
  106. <i
  107. class="el-icon-close remove-file"
  108. @click="removeDocument(index)"
  109. ></i>
  110. </div>
  111. </div>
  112. <!-- 输入区域 -->
  113. <div class="input-area">
  114. <textarea
  115. v-model="userInput"
  116. rows="4"
  117. @keydown="handleKeydown"
  118. placeholder="发送消息..."
  119. ></textarea>
  120. <!-- 工具栏 -->
  121. <div class="toolbar">
  122. <div class="left-tools">
  123. <input
  124. type="file"
  125. ref="fileInput"
  126. multiple
  127. @change="handleFileUpload"
  128. accept="image/*,.pdf,.doc,.docx,.txt"
  129. style="display: none"
  130. />
  131. <button class="tool-btn" @click="$refs.fileInput.click()">
  132. <i class="el-icon-upload2"></i>
  133. </button>
  134. </div>
  135. <!-- <button @click="playAudio" class="btn">播放音频</button> -->
  136. <button @click="sendMessage" class="btn">发送</button>
  137. </div>
  138. </div>
  139. </div>
  140. <!-- </div> -->
  141. </div>
  142. <LoginModal
  143. :visible.sync="showLoginModal"
  144. @close="showLoginModal = false"
  145. @login-success="handleLoginSuccess"
  146. />
  147. </div>
  148. </template>
  149. <script>
  150. import ChatBox from "@/components/webAi/index.vue";
  151. import LoginModal from "@/components/LoginModal";
  152. import MarkdownIt from "markdown-it";
  153. import { pcInnerAi, getMinioURl } from "@/api/api";
  154. import { modelList, get_default } from "@/api/knowledge";
  155. import axios from "axios";
  156. const md = new MarkdownIt();
  157. export default {
  158. components: {
  159. ChatBox,
  160. LoginModal,
  161. },
  162. data() {
  163. return {
  164. showLoginModal: false,
  165. isThinking: false,
  166. thinkingDots: "",
  167. messages: [
  168. {
  169. user: "bot",
  170. messageType: "TEXT",
  171. message: "欢迎使用智能AI助理",
  172. html: "",
  173. time: "",
  174. done: true,
  175. },
  176. ],
  177. generating: false,
  178. userInput: "",
  179. websocket: null,
  180. wsUrl:
  181. "http://58.246.234.210:7860/api/v1/run/3ef7369e-b617-40d2-9e2e-54f3ee76ed2e?stream=false",
  182. tweaks: {},
  183. isLoggedIn: false, // 添加登录状态标志
  184. idArray: [],
  185. minioUrls: [], // 新增:用于存储 Minio URL
  186. AImodel: "1", //模型
  187. AIknowledgeBase: "1", //知识库
  188. AIFile: "1", //文件
  189. AIform: {
  190. modelLibrary: "ollama",
  191. modelType: "",
  192. modelName: "",
  193. knowledgeBase: "",
  194. documentDirectory: "",
  195. document: "",
  196. },
  197. currentChat_id: "",
  198. phone: "",
  199. uploadFiles: [], // 存储上传的文件
  200. documents: [], // 新增:专门存储文档类型文件的数组
  201. currentAudio: null, // 添加当前播放的音频实例
  202. };
  203. },
  204. mounted() {
  205. this.checkAIData();
  206. if (this.$route.name == "ai") {
  207. /* 外部知识库 */
  208. /* 外部知识库 */
  209. const AIDataString = localStorage.getItem("AIData");
  210. if (!AIDataString) {
  211. this.showLoginModal = true;
  212. return;
  213. }
  214. try {
  215. const AIData = JSON.parse(AIDataString);
  216. if (AIData && AIData.data) {
  217. console.log(AIData);
  218. this.wsUrl = AIData.data.url || "";
  219. this.phone = AIData.data.phone || "";
  220. this.tweaks = AIData.data.tweaks || {};
  221. } else {
  222. console.error("Invalid AIData structure");
  223. this.showLoginModal = true;
  224. }
  225. } catch (error) {
  226. console.error("Error parsing AIData:", error);
  227. this.showLoginModal = true;
  228. }
  229. } else {
  230. /* 内部知识库 */
  231. pcInnerAi().then((res) => {
  232. if (res.status !== 200) return;
  233. this.wsUrl = res.data.url;
  234. this.tweaks = res.data.tweaks;
  235. });
  236. }
  237. this.init();
  238. },
  239. methods: {
  240. /* 播放音频 */
  241. playAudio(audioBase64) {
  242. // 如果有正在播放的音频,先停止它
  243. if (this.currentAudio) {
  244. this.currentAudio.pause();
  245. this.currentAudio = null;
  246. }
  247. // 创建新的音频实例并播放
  248. const audio = new Audio(audioBase64);
  249. this.currentAudio = audio;
  250. audio.play().catch((error) => {
  251. console.error("Error playing audio:", error);
  252. this.currentAudio = null;
  253. });
  254. },
  255. async handleFileUpload(event) {
  256. const files = Array.from(event.target.files);
  257. for (const file of files) {
  258. try {
  259. const formData = new FormData();
  260. formData.append("file", file);
  261. const response = await axios.post(
  262. `${process.env.VUE_APP_BASE_AI_API}/upload/file`, //process.env.VUE_APP_BASE_API
  263. formData,
  264. {
  265. headers: {
  266. "Content-Type": "multipart/form-data",
  267. },
  268. }
  269. );
  270. const fileUrl = response.data.data.fileUrl;
  271. const fileInfo = {
  272. name: file.name,
  273. type: file.type,
  274. preview: fileUrl,
  275. url: fileUrl,
  276. };
  277. // 根据文件类型分别存储
  278. if (file.type.startsWith("image/")) {
  279. this.uploadFiles.push(fileInfo);
  280. } else {
  281. // 文档类型:pdf, doc, docx, txt 等
  282. this.documents.push(fileInfo);
  283. }
  284. } catch (error) {
  285. console.error("文件上传失败:", error);
  286. this.$message.error(`文件 ${file.name} 上传失败`);
  287. }
  288. }
  289. event.target.value = "";
  290. },
  291. removeFile(index) {
  292. this.uploadFiles.splice(index, 1);
  293. },
  294. removeDocument(index) {
  295. this.documents.splice(index, 1);
  296. },
  297. /* */
  298. checkAIData() {
  299. const aiData = localStorage.getItem("AIData");
  300. this.showLoginModal = !aiData;
  301. },
  302. handleLoginSuccess() {
  303. this.showLoginModal = false;
  304. // 处理登录成功后的逻辑,例如刷新数据或更新状态
  305. },
  306. /* 聊天记录 */
  307. selectChat(index) {
  308. this.currentChatIndex = index;
  309. // Load the selected chat messages
  310. // This is where you would typically load the messages for the selected chat
  311. },
  312. newChat() {
  313. this.chatHistory.push({
  314. title: `聊天 ${this.chatHistory.length + 1}`,
  315. preview: "新的聊天...",
  316. });
  317. this.currentChatIndex = this.chatHistory.length - 1;
  318. // Clear the current messages and start a new chat
  319. this.messages = [];
  320. },
  321. handleLinkClick(event) {
  322. if (event.target.tagName.toLowerCase() === "a") {
  323. event.preventDefault();
  324. // 获取文件名
  325. const fullFileName = event.target.textContent.trim();
  326. // 分离文件名和后缀
  327. const lastDotIndex = fullFileName.lastIndexOf(".");
  328. const fileName =
  329. lastDotIndex > -1
  330. ? fullFileName.slice(0, lastDotIndex)
  331. : fullFileName;
  332. const fileExtension =
  333. lastDotIndex > -1 ? fullFileName.slice(lastDotIndex + 1) : "";
  334. // 编码文件名和后缀以便于URL传参
  335. const encodedFileName = encodeURIComponent(fileName);
  336. const encodedFileExtension = encodeURIComponent(fileExtension);
  337. // 构建新的URL,包含文件名和后缀作为查询参数
  338. const newUrl = `#/preview?fileName=${encodedFileName}&fileExtension=${encodedFileExtension}`;
  339. try {
  340. localStorage.setItem("href", event.target.href);
  341. } catch (e) {
  342. console.warn("无法存储 URL 到 localStorage:", e);
  343. }
  344. // 使用新的URL打开窗口
  345. const newWindow = window.open(newUrl, "_blank");
  346. if (newWindow) {
  347. newWindow.focus();
  348. } else {
  349. alert("弹出窗口被阻止,请允许此网站的弹出窗口。");
  350. }
  351. }
  352. },
  353. handleLoginSuccess() {
  354. this.showLoginModal = false;
  355. this.isLoggedIn = true;
  356. // 登录成功后,可以继续发送消息
  357. this.sendMessage();
  358. },
  359. getUuid() {
  360. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
  361. /[xy]/g,
  362. function (c) {
  363. var r = (Math.random() * 16) | 0,
  364. v = c == "x" ? r : (r & 0x3) | 0x8;
  365. return v.toString(16);
  366. }
  367. );
  368. },
  369. connectWebSocket() {
  370. const wsUrl =
  371. "http://58.246.234.210:7860/api/v1/run/2f1faff2-99df-4821-87d6-43d693084c4b?stream=false";
  372. // 这里做一个简单的鉴权,只有符合条件的鉴权才能握手成功
  373. // 移除这里的fetch调用,改用WebSocket
  374. this.websocket = new WebSocket(wsUrl);
  375. /* this.websocket.onerror = (event) => {
  376. console.error("WebSocket 连接错误:", event);
  377. };
  378. */
  379. this.websocket.onclose = (event) => {
  380. console.log("WebSocket 连接关闭:", event);
  381. };
  382. this.websocket.onopen = (event) => {
  383. console.log("WebSocket 连接已建立:", event);
  384. };
  385. this.websocket.onmessage = (event) => {
  386. // 解收到的消息
  387. const result = JSON.parse(event.data);
  388. // 检查消息是否完结
  389. if (result.done) {
  390. this.messages[this.messages.length - 1].done = true;
  391. return;
  392. }
  393. if (this.messages[this.messages.length - 1].done) {
  394. // 添加的消息
  395. this.messages.push({
  396. time: Date.now(),
  397. message: result.content,
  398. messageType: "TEXT",
  399. user: "bot",
  400. done: false,
  401. });
  402. } else {
  403. // 更新最后一条消息
  404. let lastMessage = this.messages[this.messages.length - 1];
  405. lastMessage.message += result.content;
  406. this.messages[this.messages.length - 1] = lastMessage;
  407. }
  408. };
  409. },
  410. async sendMessage() {
  411. if (this.$route.name == "ai") {
  412. if (!localStorage.getItem("AIData")) {
  413. this.showLoginModal = true;
  414. return;
  415. }
  416. }
  417. const chatId = this.getUuid();
  418. const wsUrl = `${process.env.VUE_APP_BASE_AI_API}/chatbot/multimodal`; //process.env.VUE_APP_BASE_AI_API /chatbot/multimodal /api/chat/chatgpt
  419. let message = this.userInput.trim();
  420. const imageUrls = this.uploadFiles
  421. .filter((file) => file.type.startsWith("image/"))
  422. .map((file) => file.url);
  423. // 获取文档 URL
  424. const documentUrls = this.documents.map((doc) => doc.url);
  425. if (message || imageUrls.length > 0 || documentUrls.length > 0) {
  426. message = message.replace(/(\r\n|\r|\n)/g, " \n");
  427. this.messages.push({
  428. time: Date.now(),
  429. message: message,
  430. messageType: "TEXT",
  431. user: "user",
  432. imageUrls: imageUrls, // 添加图片URLs
  433. documentUrls: documentUrls, // 添加文档URLs
  434. done: true,
  435. });
  436. this.userInput = "";
  437. this.uploadFiles = [];
  438. this.documents = [];
  439. const botMessage = {
  440. user: "bot",
  441. messageType: "TEXT",
  442. message: "",
  443. html: "",
  444. time: Date.now(),
  445. done: false,
  446. };
  447. this.messages.push(botMessage);
  448. const thinkingController = new AbortController();
  449. const thinkingPromise = this.simulateThinking(
  450. botMessage,
  451. thinkingController.signal
  452. );
  453. try {
  454. const response = await axios({
  455. method: "post",
  456. url: wsUrl,
  457. data: {
  458. message: message,
  459. chat_config_id: "2",
  460. user_id: this.phone,
  461. session_id: this.session_id || "",
  462. source: "pc",
  463. image_urls: imageUrls,
  464. documents: documentUrls, // 添加文档 URLs
  465. //history_limit: 10
  466. },
  467. });
  468. this.session_id = response.data.data.session_id;
  469. if (response.data.code !== 200) {
  470. throw new Error(
  471. `HTTP error! status: ${response.status}, message: ${response.data.message}`
  472. );
  473. }
  474. thinkingController.abort();
  475. await thinkingPromise;
  476. const additionalInput = response.data.data.document_ids;
  477. this.idArray = additionalInput;
  478. const idObject = { document_ids: this.idArray };
  479. console.log("ID Object:", idObject);
  480. await this.getMinioUrls(idObject);
  481. /* if (this.$route.name !== "ai") {} */
  482. // 如果有音频,播放音频
  483. if (
  484. response.data.data.audio_info &&
  485. response.data.data.audio_info.audio
  486. ) {
  487. this.playAudio(response.data.data.audio_info.audio);
  488. }
  489. this.handleResponse(response.data, botMessage);
  490. } catch (error) {
  491. console.error("Error sending message:", error);
  492. thinkingController.abort();
  493. await thinkingPromise;
  494. botMessage.done = true;
  495. botMessage.message = "抱歉,发生了错误,请稍后再试。";
  496. if (error.response) {
  497. console.error("Response data:", error.response.data);
  498. console.error("Response status:", error.response.status);
  499. } else if (error.request) {
  500. console.error("No response received:", error.request);
  501. } else {
  502. console.error("Error message:", error.message);
  503. }
  504. }
  505. }
  506. },
  507. async getMinioUrls(idObject) {
  508. this.minioUrls = []; // 清空之前的 URL
  509. try {
  510. console.log("Sending to backend:", JSON.stringify(idObject));
  511. const response = await axios.post(
  512. `${process.env.VUE_APP_BASE_AI_API}/milvus/getMinioURlbyDocid`,
  513. idObject,
  514. {
  515. headers: {
  516. "Content-Type": "application/json",
  517. },
  518. }
  519. );
  520. if (response.status === 200 && response.data) {
  521. this.minioUrls = response.data.data; // 假设返回的是 URL 数组
  522. console.log("Received Minio URLs:", this.minioUrls);
  523. } else {
  524. console.error("Failed to get Minio URLs");
  525. }
  526. } catch (error) {
  527. console.error("Error fetching Minio URLs:", error);
  528. if (error.response) {
  529. console.error("Response data:", error.response.data);
  530. console.error("Response status:", error.response.status);
  531. console.error("Response headers:", error.response.headers);
  532. } else if (error.request) {
  533. console.error("No response received:", error.request);
  534. } else {
  535. console.error("Error message:", error.message);
  536. }
  537. }
  538. },
  539. async simulateThinking(message, signal) {
  540. this.isThinking = true;
  541. const dotInterval = 200; // 每 200ms 更新次点
  542. return new Promise((resolve) => {
  543. const updateDots = () => {
  544. if (signal.aborted) {
  545. clearInterval(intervalId);
  546. this.isThinking = false;
  547. this.thinkingDots = "";
  548. message.message = "";
  549. resolve();
  550. return;
  551. }
  552. this.thinkingDots += ".";
  553. if (this.thinkingDots.length > 3) {
  554. this.thinkingDots = "";
  555. }
  556. message.message = "思考中" + this.thinkingDots;
  557. };
  558. const intervalId = setInterval(updateDots, dotInterval);
  559. signal.addEventListener("abort", () => {
  560. clearInterval(intervalId);
  561. this.isThinking = false;
  562. this.thinkingDots = "";
  563. message.message = "";
  564. resolve();
  565. });
  566. });
  567. },
  568. async handleResponse(value, existingMessage) {
  569. const data = value.data.answer;
  570. existingMessage.messageType = data;
  571. /* existingMessage.time = data.timestamp; this.$route.name !== "ai" &&*/
  572. existingMessage.message = "";
  573. let mainText = data;
  574. let sourceText = "";
  575. if (this.minioUrls && this.minioUrls.length > 0) {
  576. sourceText =
  577. "\n\n<div class='source-section'><h3>相关资料来源:</h3><ol>";
  578. this.minioUrls.forEach((url, index) => {
  579. sourceText += `<li><a href="${url.url}" target="_blank" class="source-link">${url.object_name}</a></li>`;
  580. });
  581. sourceText += "</ol></div>";
  582. }
  583. console.log(mainText);
  584. // 先进行主要内容的打字效果
  585. await this.typeMessage(existingMessage, mainText);
  586. // 直接添加资料来源部分
  587. if (sourceText) {
  588. existingMessage.message += sourceText;
  589. existingMessage.html = this.renderMarkdown(existingMessage.message);
  590. }
  591. },
  592. typeMessage(message, fullText) {
  593. return new Promise((resolve) => {
  594. const delay = 30;
  595. let i = 0;
  596. const typeChar = () => {
  597. if (i < fullText.length) {
  598. message.message += fullText[i];
  599. i++;
  600. setTimeout(typeChar, delay);
  601. } else {
  602. message.done = true;
  603. message.html = this.renderMarkdown(message.message);
  604. resolve();
  605. }
  606. };
  607. typeChar();
  608. });
  609. },
  610. renderMarkdown(rawMarkdown) {
  611. const md = new MarkdownIt({
  612. html: true,
  613. breaks: true,
  614. linkify: true,
  615. });
  616. // 自定义链接渲染规则
  617. md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
  618. const token = tokens[idx];
  619. const hrefIndex = token.attrIndex("href");
  620. const href = token.attrs[hrefIndex][1];
  621. return `<span class="custom-link" data-href="${href}">`;
  622. };
  623. md.renderer.rules.link_close = () => "</span>";
  624. const renderedHtml = md.render(rawMarkdown);
  625. // 使用 setTimeout 来确保 DOM 更新后再添加事件监听器
  626. setTimeout(() => {
  627. const links = document.querySelectorAll(".custom-link");
  628. links.forEach((link) => {
  629. link.addEventListener("click", (e) => {
  630. e.preventDefault();
  631. const href = link.getAttribute("data-href");
  632. window.open(href, "_blank");
  633. });
  634. });
  635. }, 0);
  636. return renderedHtml;
  637. },
  638. handleKeydown(event) {
  639. // Check if 'Enter' is pressed without the 'Alt' key
  640. if (event.key === "Enter" && !(event.shiftKey || event.altKey)) {
  641. event.preventDefault(); // Prevent the default action to avoid line break in textarea
  642. this.sendMessage();
  643. } else if (event.key === "Enter" && event.altKey) {
  644. // Allow 'Alt + Enter' to insert a newline
  645. const cursorPosition = event.target.selectionStart;
  646. const textBeforeCursor = this.userInput.slice(0, cursorPosition);
  647. const textAfterCursor = this.userInput.slice(cursorPosition);
  648. // Insert the newline character at the cursor position
  649. this.userInput = textBeforeCursor + "\n" + textAfterCursor;
  650. // Move the cursor to the right after the inserted newline
  651. this.$nextTick(() => {
  652. event.target.selectionStart = cursorPosition + 1;
  653. event.target.selectionEnd = cursorPosition + 1;
  654. });
  655. }
  656. },
  657. beforeDestroy() {
  658. if (this.websocket) {
  659. this.websocket.close();
  660. }
  661. },
  662. /* 获取列表 */
  663. init() {
  664. /* modelList().then((res) => {
  665. console.log(res);
  666. }); */
  667. get_default().then((res) => {
  668. if (res.status !== 200) return;
  669. this.currentChat_id = res.data.id;
  670. });
  671. },
  672. getDocumentName(url) {
  673. // 从URL中提取文件名
  674. const parts = url.split('/');
  675. const fileName = parts[parts.length - 1];
  676. // 解码URL编码的文件名
  677. return decodeURIComponent(fileName);
  678. }
  679. },
  680. updated() {
  681. const messagesContainer = this.$el.querySelector(".messages");
  682. messagesContainer.scrollTop = messagesContainer.scrollHeight;
  683. },
  684. };
  685. </script>
  686. <style scoped>
  687. .chat-container {
  688. position: relative;
  689. display: flex;
  690. flex-direction: column;
  691. margin-bottom: 150px;
  692. /* 或者按照实际需要调整高度 */
  693. }
  694. .chat-container .header {
  695. width: 1200px;
  696. margin: 10px auto 0;
  697. border: 1px solid #d7d7d7;
  698. border-radius: 10px;
  699. }
  700. .form-container {
  701. max-width: 1200px; /* 或者其他适合你布局的宽度 */
  702. margin: 0 auto; /* 这会使容器水平居中 */
  703. padding: 0 15px; /* 添加一些左右内边距 */
  704. }
  705. .el-form-item {
  706. margin-bottom: 15px;
  707. }
  708. .el-select {
  709. width: 100%;
  710. }
  711. .generate-button {
  712. margin-top: 10px; /* 在小屏幕上给按钮一些上边距 */
  713. margin-right: 25px;
  714. }
  715. @media (max-width: 768px) {
  716. .selection-summary {
  717. flex-direction: column;
  718. }
  719. .generate-button {
  720. margin-left: 0;
  721. margin-top: 15px;
  722. align-self: flex-end; /* 在小屏幕上将按钮右对齐 */
  723. }
  724. }
  725. .selection-summary {
  726. background-color: #f2f2f2;
  727. border-radius: 4px;
  728. padding: 15px;
  729. margin: 15px;
  730. display: flex;
  731. justify-content: space-between;
  732. align-items: center;
  733. margin-right: 85px;
  734. border-radius: 10px;
  735. }
  736. .summary-content {
  737. flex-grow: 1;
  738. }
  739. .summary-label {
  740. font-weight: bold;
  741. color: #7f7f7f;
  742. margin-right: 10px;
  743. }
  744. .summary-text {
  745. color: #606266;
  746. margin: 0;
  747. margin-top: 3px;
  748. font-size: 14px;
  749. }
  750. .title {
  751. width: 1200px;
  752. margin: 0 auto 15px;
  753. display: flex;
  754. align-items: center;
  755. }
  756. .title_info {
  757. cursor: pointer;
  758. color: #1296db;
  759. font-size: 14px;
  760. margin-left: 10px;
  761. }
  762. /* .chat-container .header ::v-deep .el-select .el-input--medium .el-input__inner{
  763. border: none;
  764. }
  765. .chat-container .header ::v-deep .el-select .el-input--medium .el-input__suffix .el-input__suffix-inner{
  766. display: none;
  767. } */
  768. .chat-container .content {
  769. display: flex;
  770. justify-content: flex-start;
  771. }
  772. .chat-container .content .left {
  773. margin-left: 10px;
  774. width: 330px;
  775. height: 87vh;
  776. }
  777. .chat-item {
  778. border-radius: 10px;
  779. padding: 10px;
  780. border-bottom: 1px solid #e8edf2;
  781. background-color: #f5f5fa;
  782. margin-bottom: 10px;
  783. }
  784. .chat-header {
  785. display: flex;
  786. align-items: center;
  787. margin-bottom: 5px;
  788. }
  789. .avatar {
  790. width: 40px;
  791. height: 40px;
  792. border-radius: 50%;
  793. margin-right: 10px;
  794. }
  795. .user-info {
  796. flex-grow: 1;
  797. }
  798. .user-info .info_header {
  799. display: flex;
  800. align-items: flex-end;
  801. }
  802. .username {
  803. font-weight: bold;
  804. }
  805. .timestamp {
  806. margin-left: 13px;
  807. font-size: 0.8em;
  808. color: #888;
  809. }
  810. .more-options {
  811. cursor: pointer;
  812. }
  813. .chat-message {
  814. font-weight: bold;
  815. margin-top: 8px;
  816. margin-bottom: 10px;
  817. }
  818. .chat-preview {
  819. font-size: 0.9em;
  820. color: #666;
  821. }
  822. /* Adjust existing styles */
  823. .left {
  824. width: 300px; /* Increased width to accommodate the new layout */
  825. }
  826. .chat-history {
  827. width: 330px;
  828. height: 100%;
  829. overflow-y: auto;
  830. }
  831. .messages {
  832. width: 1180px; /* 设置消息列表宽度为屏幕宽度的 80% */
  833. max-width: 90%; /* 限制最大宽度,避免超出视口 */
  834. margin: 0 auto; /* 上下保持原有的 margin,左右自动调整以居中 */
  835. overflow-y: auto; /* 如果消息太多允许滚动 */
  836. height: calc(100vh - 230px); /* 高度需要根据输入框和其他元素的高度调整 */
  837. padding: 10px; /* 或你希望的内边距大小 */
  838. margin-bottom: 110px;
  839. }
  840. /* 针对手机端的媒体查询 */
  841. @media screen and (max-width: 768px) {
  842. .messages {
  843. width: 100%;
  844. max-width: 100%;
  845. margin: 0;
  846. margin-bottom: 120px;
  847. }
  848. }
  849. .user-message {
  850. display: flex;
  851. flex-direction: column !important;
  852. align-items: flex-end !important;
  853. }
  854. .user-message .message-content {
  855. order: 1;
  856. text-align: right;
  857. }
  858. .user-message .avatar {
  859. order: 2;
  860. margin-left: 10px;
  861. margin-right: 0;
  862. }
  863. .message-text {
  864. margin-top: 5px;
  865. }
  866. .messages li {
  867. display: flex;
  868. flex-direction: column;
  869. align-items: flex-start; /* 这将确保所有子元素对齐到容器的顶部 */
  870. /* margin-bottom: 10px; */
  871. }
  872. .avatar {
  873. width: 40px; /* 头像的尺寸 */
  874. height: 40px;
  875. border-radius: 50%; /* 圆形头像 */
  876. /*background-color: #e9e0e0; 暂时用灰色代替,你可以用图片替换 */
  877. align-self: start; /* 这将覆盖 flex 容器的 align-items 并将头像对齐到顶部 */
  878. margin-right: 10px; /* 按需调整以在头像和消息之间提供空间 */
  879. }
  880. .user-avatar {
  881. background-image: url("../../components/webAi/assets/用户.png");
  882. background-position: center;
  883. background-repeat: no-repeat;
  884. background-size: cover;
  885. /* background-color: #93939d; */ /* 用户头像颜色 */
  886. }
  887. .bot-avatar {
  888. background-image: url("../../components/webAi/assets/机器人.png");
  889. background-position: center;
  890. background-repeat: no-repeat;
  891. background-size: cover;
  892. /* background-color: green; */ /* AI头像颜色 */
  893. }
  894. /* 针对手机端的媒体查询 */
  895. @media screen and (max-width: 768px) {
  896. .user-avatar,
  897. .bot-avatar {
  898. width: 30px; /* 或其他更小的尺寸 */
  899. height: 30px;
  900. }
  901. }
  902. .message_name {
  903. display: flex;
  904. align-items: center;
  905. padding-top: 5px;
  906. padding-bottom: 5px;
  907. }
  908. .name {
  909. margin-left: 8px;
  910. /* margin-bottom: 5px; */
  911. }
  912. .message-content {
  913. background-color: #f0f0f0; /* 消息背景 */
  914. padding-left: 20px; /* 上下左右的内边距 */
  915. padding-right: 20px; /* 上下左右的内边距 */
  916. padding-top: 10px; /* 上下左右的内边距 */
  917. padding-bottom: 0px; /* 上下左的内边距 */
  918. max-width: calc(90% - 10px); /* 计算头像和间距 */
  919. border-radius: 7px; /* 边框圆角 */
  920. /* margin-bottom: 10px; 和下一条消息之间的间距 */
  921. /* 消息内容样式 */
  922. display: flex;
  923. flex-direction: column; /* 排列文本 */
  924. margin-top: 0;
  925. }
  926. .message-text {
  927. margin: 0;
  928. white-space: normal; /* 确保文本会换行 */
  929. word-wrap: break-word; /* 长单词或 URL 会被断开适应容器宽度 */
  930. overflow: auto;
  931. font-size: 14px;
  932. }
  933. .message-text ::v-deep p {
  934. font-size: 14px !important;
  935. margin: 5px 0 10px;
  936. padding: 0;
  937. font-size: inherit;
  938. line-height: 22px;
  939. font-weight: inherit;
  940. }
  941. .message-text ::v-deep ol {
  942. padding-bottom: 10px;
  943. }
  944. .message-text ::v-deep .source-section h3 {
  945. margin: 20px 0 3px;
  946. color: #333;
  947. font-size: 16px;
  948. }
  949. .message-text ::v-deep ol li {
  950. padding-top: 3px;
  951. }
  952. .message-text ::v-deep ol li a {
  953. font-size: 14px;
  954. color: #1296db;
  955. }
  956. .input-container {
  957. position: absolute; /* 改为绝对定位 */
  958. bottom: -115px; /* 距离底部的距离 */
  959. left: 50%;
  960. transform: translateX(-50%);
  961. width: 90%; /* 设置宽度为弹窗宽度的90% */
  962. max-width: 1170px; /* 设置最大宽度 */
  963. display: flex;
  964. justify-content: space-between;
  965. align-items: flex-start;
  966. flex-direction: column;
  967. padding: 15px;
  968. background: white;
  969. border-radius: 10px;
  970. box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
  971. }
  972. textarea {
  973. font-size: 16px;
  974. width: 100%; /* 可以根据需要调整 */
  975. padding: 10px;
  976. border: 1px solid #ccc;
  977. border-radius: 4px;
  978. border: none;
  979. outline: none;
  980. resize: none;
  981. }
  982. .input-container textarea {
  983. width: 100%; /* 输入框占据所有可用空间 */
  984. padding: 10px;
  985. margin-right: 10px; /* 与按钮的间距 */
  986. box-sizing: border-box;
  987. }
  988. .input-container button {
  989. min-width: 80px; /* 例如,按钮的最小宽度为 100px */
  990. white-space: nowrap; /* 防止文字折行 */
  991. padding: 10px 20px;
  992. cursor: pointer;
  993. }
  994. .sender-name {
  995. font-weight: bold;
  996. color: #333;
  997. margin-left: -5px;
  998. }
  999. .btn {
  1000. font-size: 16px;
  1001. color: #ffffff;
  1002. border-radius: 5px;
  1003. border: none;
  1004. background-color: #3cbade;
  1005. padding: 10px 20px; /* 添加内边距 */
  1006. width: auto; /* 让宽度自适应内容 */
  1007. }
  1008. /* 针对手机端的媒体查询 */
  1009. @media screen and (max-width: 768px) {
  1010. .btn {
  1011. font-size: 14px; /* 稍微减小字体大小 */
  1012. padding: 8px 16px; /* 减小内边距 */
  1013. max-width: 80px; /* 限制最大宽度 */
  1014. margin: 0 auto; /* 居中显示 */
  1015. }
  1016. }
  1017. /* 新输入框 */
  1018. .upload-preview {
  1019. display: flex;
  1020. flex-wrap: wrap;
  1021. gap: 8px;
  1022. padding: 10px 0;
  1023. max-height: 120px;
  1024. overflow-y: auto;
  1025. }
  1026. .preview-item {
  1027. position: relative;
  1028. border-radius: 4px;
  1029. overflow: hidden;
  1030. }
  1031. .image-preview {
  1032. width: 80px;
  1033. height: 40px;
  1034. }
  1035. .image-preview img{
  1036. width: 100%;
  1037. }
  1038. .document-preview {
  1039. width: 120px;
  1040. height: 40px;
  1041. background: #f5f5f5;
  1042. display: flex;
  1043. align-items: center;
  1044. padding: 0 10px;
  1045. }
  1046. .doc-name {
  1047. font-size: 12px;
  1048. overflow: hidden;
  1049. text-overflow: ellipsis;
  1050. white-space: nowrap;
  1051. max-width: 90px;
  1052. }
  1053. .remove-file {
  1054. position: absolute;
  1055. top: 4px;
  1056. right: 4px;
  1057. background: rgba(0, 0, 0, 0.5);
  1058. color: white;
  1059. border-radius: 50%;
  1060. padding: 4px;
  1061. cursor: pointer;
  1062. font-size: 12px;
  1063. z-index: 1;
  1064. }
  1065. .input-area {
  1066. width: 100%;
  1067. }
  1068. .toolbar {
  1069. display: flex;
  1070. justify-content: space-between;
  1071. align-items: center;
  1072. margin-top: 10px;
  1073. }
  1074. .left-tools {
  1075. display: flex;
  1076. gap: 10px;
  1077. }
  1078. .tool-btn {
  1079. background: none;
  1080. border: none;
  1081. cursor: pointer;
  1082. padding: 5px;
  1083. color: #666;
  1084. font-size: 20px;
  1085. }
  1086. .tool-btn:hover {
  1087. color: #3cbade;
  1088. }
  1089. .document-item {
  1090. width: 120px; /* 文档预览项可以设置得更宽一些 */
  1091. height: 60px;
  1092. background-color: #f5f5f5;
  1093. }
  1094. .document-item .file-info {
  1095. display: flex;
  1096. align-items: center;
  1097. gap: 5px;
  1098. }
  1099. .document-item .file-info i {
  1100. font-size: 20px;
  1101. color: #666;
  1102. }
  1103. .document-item .file-info span {
  1104. font-size: 12px;
  1105. overflow: hidden;
  1106. text-overflow: ellipsis;
  1107. white-space: nowrap;
  1108. }
  1109. .message-images {
  1110. display: flex;
  1111. flex-wrap: wrap;
  1112. gap: 8px;
  1113. margin-bottom: 10px;
  1114. }
  1115. .uploaded-image {
  1116. max-width: 200px;
  1117. max-height: 200px;
  1118. border-radius: 4px;
  1119. object-fit: contain;
  1120. }
  1121. .message-documents {
  1122. display: flex;
  1123. flex-direction: column;
  1124. gap: 8px;
  1125. margin-bottom: 10px;
  1126. }
  1127. .document-preview-item {
  1128. display: flex;
  1129. align-items: center;
  1130. background: #f5f5f5;
  1131. padding: 10px;
  1132. border-radius: 4px;
  1133. gap: 8px;
  1134. }
  1135. .document-preview-item i {
  1136. font-size: 20px;
  1137. color: #666;
  1138. }
  1139. .document-name {
  1140. flex: 1;
  1141. font-size: 14px;
  1142. color: #333;
  1143. overflow: hidden;
  1144. text-overflow: ellipsis;
  1145. white-space: nowrap;
  1146. }
  1147. .document-link {
  1148. color: #3cbade;
  1149. text-decoration: none;
  1150. font-size: 14px;
  1151. padding: 4px 8px;
  1152. border-radius: 4px;
  1153. }
  1154. .document-link:hover {
  1155. background: rgba(60, 186, 222, 0.1);
  1156. }
  1157. </style>