ChatBox.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. import LoginModal from "@/components/LoginModal";
  2. import MarkdownIt from "markdown-it";
  3. import { pcInnerAi,getMinioURl } from "@/api/api";
  4. import {modelList,listBuckets,selectTypeList,getBucketContents,configSave,configList,configDelete} from "@/api/knowledge"
  5. import axios from 'axios';
  6. const md = new MarkdownIt();
  7. export default {
  8. components: {
  9. LoginModal,
  10. },
  11. data() {
  12. return {
  13. isThinking: false,
  14. thinkingDots: '',
  15. messages: [
  16. {
  17. user: "bot",
  18. messageType: "TEXT",
  19. message: "欢迎使用轻良智能AI助理",
  20. html: "",
  21. time: "",
  22. done: true,
  23. },
  24. ],
  25. generating: false,
  26. userInput: "",
  27. websocket: null,
  28. wsUrl:'http://58.246.234.210:7860/api/v1/run/3ef7369e-b617-40d2-9e2e-54f3ee76ed2e?stream=false',
  29. tweaks:{},
  30. showLoginModal: false,
  31. isLoggedIn: false, // 添加登录状态标志
  32. idArray: [],
  33. minioUrls: [], // 新增:用于存储 Minio URL
  34. AImodel:'1',//模型
  35. AIknowledgeBase:"1",//知识库
  36. AIFile:'1',//文件
  37. AIform:{
  38. chat_name:'',
  39. modelLibrary: 'ollama',
  40. model_type: 'chat',
  41. model_name: '',
  42. knowledge_base_names: [],
  43. document_directories: [],
  44. documents: [],
  45. temperature: 0.7,
  46. max_tokens: 150,
  47. top_p: 1.0,
  48. frequency_penalty: 0.0,
  49. presence_penalty: 0.0,
  50. response_format: "text",
  51. context_window: 2048,
  52. user_id: "user123",
  53. session_id: "session456",
  54. language: "en",
  55. timeout: 30,
  56. role_name: "Admin",
  57. role_description: "",
  58. role_permissions: ["read", "write", "delete"]
  59. },
  60. /* 模型库 */
  61. modelList:[],
  62. /* 模型类型 */
  63. modelTypeList:[],
  64. /* 模型名称 */
  65. modelNameList:[],
  66. /* 知识库 */
  67. kneList:[],
  68. /* 文档目录 */
  69. directoryList: [],
  70. /* 文档 */
  71. documentList: [],
  72. bucket_id:'',
  73. rules: {
  74. chat_name: [
  75. { required: true, message: '请填写应名称', trigger: 'blur' }
  76. ],
  77. model_name: [
  78. { required: true, message: '请选择模型名称', trigger: 'change' }
  79. ],
  80. knowledge_base_names: [
  81. { required: true, message: '请选择至少一个知识库', trigger: 'change' }
  82. ],
  83. /* document_directories: [
  84. { required: true, message: '请选择文档目录', trigger: 'change' }
  85. ], */
  86. documents: [
  87. { required: true, message: '请选择至少一个文档', trigger: 'change' }
  88. ]
  89. },
  90. chatDialogVisible: false,
  91. /* 应用列表 */
  92. knowledgeBases: [],
  93. currentChat: {},
  94. /* 修改弹窗 */
  95. editDialogVisible: false,
  96. editForm: {
  97. // 复制 AIform 的结构,但初始值为空
  98. chat_name: '',
  99. modelLibrary: 'ollama',
  100. model_type: 'chat',
  101. model_name: '',
  102. knowledge_base_names: [],
  103. document_directories: [],
  104. documents: [],
  105. temperature: 0.7,
  106. max_tokens: 150,
  107. top_p: 1.0,
  108. frequency_penalty: 0.0,
  109. presence_penalty: 0.0,
  110. response_format: "text",
  111. context_window: 2048,
  112. user_id: "user123",
  113. session_id: "session456",
  114. language: "en",
  115. timeout: 30,
  116. role_name: "Admin",
  117. role_description: "",
  118. role_permissions: ["read", "write", "delete"]
  119. },
  120. editDirectoryList: [],
  121. editDocumentList: [],
  122. };
  123. },
  124. created() {
  125. // this.connectWebSocket();
  126. },
  127. mounted() {
  128. /* */
  129. if(this.$route.name=='ai'){
  130. /* 外部知识库 */
  131. const AIData=JSON.parse(sessionStorage.getItem("AIData"))
  132. this.wsUrl=AIData.data.url
  133. this.tweaks=AIData.data.tweaks
  134. }else{
  135. /* 内部知识库 */
  136. pcInnerAi().then(res=>{
  137. if(res.status!==200) return
  138. this.wsUrl=res.data.url
  139. this.tweaks=res.data.tweaks
  140. })
  141. }
  142. /* 获取模型列表 */
  143. this.init()
  144. },
  145. computed: {
  146. getKnowledgeBaseNames() {
  147. const names = this.AIform.knowledge_base_names.map(id =>
  148. this.kneList.find(item => item.id === id)?.name || id
  149. );
  150. if (names.length <= 2) {
  151. return names.join(', ');
  152. } else {
  153. return `${names[0]}, ${names[1]} 等${names.length}个`;
  154. }
  155. },
  156. getDocumentNames() {
  157. const names = this.AIform.documents.map(id =>
  158. this.documentList.find(item => item.id === id)?.name || id
  159. );
  160. if (names.length <= 2) {
  161. return names.join(', ');
  162. } else {
  163. return `${names[0]}, ${names[1]} 等${names.length}个`;
  164. }
  165. }
  166. },
  167. methods: {
  168. /* 删除 */
  169. deleteApplication(card) {
  170. this.$confirm('确定要删除这个应用吗?', '提示', {
  171. confirmButtonText: '确定',
  172. cancelButtonText: '取消',
  173. type: 'warning'
  174. }).then(() => {
  175. // 调用删除 API
  176. configDelete({id:card.id}).then(response => {
  177. if (response.status==200) {
  178. this.$message({
  179. type: 'success',
  180. message: '删除成功!'
  181. });
  182. // 从列表中移除已删除的应用
  183. /* const index = this.knowledgeBases.findIndex(kb => kb.id === card.id);
  184. if (index > -1) {
  185. this.knowledgeBases.splice(index, 1);
  186. } */
  187. this.fetchApplicationList();
  188. } else {
  189. this.$message.error('删除失败: ' + response.message);
  190. }
  191. }).catch(error => {
  192. console.error('删除应用时出错:', error);
  193. this.$message.error('删除失败,请稍后重试');
  194. });
  195. }).catch(() => {
  196. this.$message({
  197. type: 'info',
  198. message: '已取消删除'
  199. });
  200. });
  201. },
  202. handleEditKnowledgeBaseChange(val) {
  203. // 重置目录和文档选择
  204. this.editForm.document_directories = [];
  205. this.editForm.documents = [];
  206. this.editDocumentList = [];
  207. // 加载新选择的知识库对应的目录列表
  208. this.loadEditDirectoryList(val);
  209. },
  210. handleEditDirectoryChange(val) {
  211. // 重置文档选择
  212. this.editForm.documents = [];
  213. // 加载选中目录对应的文档列表
  214. this.loadEditDocumentList(val);
  215. },
  216. /* 编辑 */
  217. editApplication(card) {
  218. // 根据 card 的数据填充 editForm
  219. this.editForm = JSON.parse(JSON.stringify(card)); // 深拷贝以避免直接修改原对象
  220. this.editForm.knowledge_base_names = this.editForm.knowledge_base_names.map(name => {
  221. const kb = this.kneList.find(kb => kb.name === name);
  222. return kb ? kb.id : name; // 如果找不到对应的知识库,保留原名称
  223. });
  224. this.editDialogVisible = true;
  225. console.log(this.editForm);
  226. // 加载知识库对应的目录列表
  227. this.loadEditDirectoryList(this.editForm.knowledge_base_names);
  228. },
  229. handleEditDialogClose() {
  230. this.$refs.editFormRef.resetFields();
  231. this.editDirectoryList = [];
  232. this.editDocumentList = [];
  233. },
  234. async loadEditDirectoryList(val) {
  235. this.editDirectoryList = []; // 清空现有目录列表
  236. let totalDocuments = 0;
  237. let otherFolderCount = 0;
  238. for (const kbName of val) {
  239. // 根据知识库名称找到对应的 ID
  240. const kbId = this.kneList.find(kb => kb.name === kbName)?.id;
  241. /* if (!kbId) {
  242. console.error(`No matching knowledge base found for name: ${kbName}`);
  243. continue;
  244. } */
  245. const typeForm = {
  246. page: 1,
  247. pageSize: 9999,
  248. kb_id: kbName,
  249. };
  250. try {
  251. const res = await selectTypeList(typeForm);
  252. if (res.data) {
  253. this.editDirectoryList = [...new Set([...this.editDirectoryList, ...res.data.dataList])];
  254. res.data.dataList.forEach(folder => {
  255. if (folder.id === "other") {
  256. otherFolderCount += folder.document_count || 0;
  257. } else {
  258. totalDocuments += folder.document_count || 0;
  259. }
  260. });
  261. }
  262. } catch (error) {
  263. console.error(`Error loading directory list for kb_id ${kbId}:`, error);
  264. }
  265. }
  266. this.editDirectoryList.unshift({
  267. id: "001",
  268. name: "全部",
  269. document_count: totalDocuments + otherFolderCount,
  270. });
  271. },
  272. loadEditDocumentList(val) {
  273. // 找到选中目录的名称
  274. const selectedDirectoryName = val[0];
  275. // 从 kneList 中找到对应的知识库
  276. const selectedKnowledgeBase = this.kneList.find(kb =>
  277. kb.name === this.editForm.knowledge_base_names[0]
  278. );
  279. /* if (!selectedKnowledgeBase) {
  280. console.error('No matching knowledge base found');
  281. return;
  282. } */
  283. let queryForm = {
  284. page: 1,
  285. pageSize: 9999,
  286. bucket_id: this.editForm.knowledge_base_names[0],
  287. doc_type_id: selectedDirectoryName === '全部' ? 0 : this.getDirectoryIdByName(selectedDirectoryName),
  288. };
  289. getBucketContents(queryForm).then(res => {
  290. console.log(res);
  291. this.editDocumentList = res.data.documents;
  292. });
  293. },
  294. // 添加一个辅助方法来根据目录名称获取目录ID
  295. getDirectoryIdByName(directoryName) {
  296. const directory = this.editDirectoryList.find(dir => dir.name === directoryName);
  297. return directory ? directory.id : null;
  298. },
  299. submitEdit() {
  300. this.$refs.editFormRef.validate(async (valid) => {
  301. if (valid) {
  302. try {
  303. const convertedForm = { ...this.editForm };
  304. console.log(this.editForm.documents);
  305. // 转换知识库、文档目录和文档的ID为名称
  306. convertedForm.knowledge_base_names = this.safeGetNamesByIds(this.editForm.knowledge_base_names, this.kneList);
  307. /* convertedForm.documents = this.safeGetNamesByIds(this.editForm.documents, this.editDocumentList); */
  308. convertedForm.document_directories = this.safeGetNamesByIds(this.editForm.document_directories, this.editDirectoryList);
  309. if (convertedForm.document_directories.length === 0) {
  310. convertedForm.document_directories = ['全部'];
  311. }
  312. console.log('Converted form for edit:', convertedForm);
  313. const response = await axios.post(`${process.env.VUE_APP_BASE_API}/chatbot/configuration/update/`, convertedForm, {
  314. headers: {
  315. 'Content-Type': 'application/json'
  316. }
  317. });
  318. if (response.status === 200) {
  319. this.$message.success('应用更新成功');
  320. this.editDialogVisible = false;
  321. this.fetchApplicationList();
  322. } else {
  323. this.$message.error(response.data.message || '应用更新失败');
  324. }
  325. } catch (error) {
  326. console.error('Error updating application:', error);
  327. this.$message.error('应用更新失败,请稍后重试');
  328. }
  329. } else {
  330. this.$message.error('请填写所有必填字段');
  331. return false;
  332. }
  333. });
  334. },
  335. // 添加一个方法来获取完整的应用配置
  336. async fetchFullApplicationConfig(appId) {
  337. try {
  338. const response = await axios.get(`${process.env.VUE_APP_BASE_API}/chatbot/configDetail/${appId}`);
  339. if (response.status === 200 && response.data.code === 200) {
  340. return response.data.data;
  341. } else {
  342. throw new Error(response.data.message || '获取应用配置失败');
  343. }
  344. } catch (error) {
  345. console.error('Error fetching application config:', error);
  346. this.$message.error('获取应用配置失败,请稍后重试');
  347. return null;
  348. }
  349. },
  350. // 实现获取应用列表的方法
  351. async fetchApplicationList() {
  352. try {
  353. const response = await configList();
  354. if (response.status === 200) {
  355. this.knowledgeBases = response.data; // 假设返回的数据结构符合要求
  356. } else {
  357. throw new Error(response.data.message || '获取应用列表失败');
  358. }
  359. } catch (error) {
  360. console.error('Error fetching application list:', error);
  361. this.$message.error('获取应用列表失败,请稍后重试');
  362. }
  363. },
  364. /* */
  365. openChatDialog(card) {
  366. console.log(card);
  367. this.currentChat = card;
  368. this.chatDialogVisible = true;
  369. // 可能需要在这里初始化聊天记录或执行其他操作
  370. this.messages = []; // 清空之前的聊天记录
  371. // 可以添加一个欢迎消息
  372. this.messages.push({
  373. user: "bot",
  374. messageType: "TEXT",
  375. message: `欢迎使用 ${card.name} 聊天应用`,
  376. html: "",
  377. time: "",
  378. done: true,
  379. });
  380. },
  381. /* 关闭 */
  382. handleCloseDialog(done) {
  383. // 在这里可以添加关闭前的确认逻辑
  384. this.$confirm('确认关闭?')
  385. .then(_ => {
  386. done();
  387. })
  388. .catch(_ => {});
  389. },
  390. /* 点击应用 */
  391. getFileTypeIcon(type) {
  392. const iconMap = {
  393. word: 'el-icon-document',
  394. excel: 'el-icon-tickets',
  395. pdf: 'el-icon-document-copy'
  396. };
  397. return iconMap[type] || 'el-icon-document';
  398. },
  399. /* 生成引用 */
  400. generateApplication() {
  401. this.$refs.AIformRef.validate(async (valid) => {
  402. if (valid) {
  403. try {
  404. // 创建一个新对象来存储转换后的数据
  405. const convertedForm = { ...this.AIform };
  406. // 将知识库 ID 转换为名称
  407. convertedForm.knowledge_base_names = this.safeGetNamesByIds(this.AIform.knowledge_base_names, this.kneList);
  408. // 将文档 ID 转换为名称
  409. convertedForm.documents = this.safeGetNamesByIds(this.AIform.documents, this.documentList);
  410. // 将文档目录 ID 转换为名称,如果为空则传递 '全部'
  411. convertedForm.document_directories = this.safeGetNamesByIds(this.AIform.document_directories, this.directoryList);
  412. if (convertedForm.document_directories.length === 0) {
  413. convertedForm.document_directories = ['全部'];
  414. }
  415. console.log('Converted form:', convertedForm);
  416. // 使用 axios 发送 POST 请求
  417. const response = await axios.post(`${process.env.VUE_APP_BASE_API}/chatbot/configSave/`, convertedForm, {
  418. headers: {
  419. 'Content-Type': 'application/json'
  420. }
  421. });
  422. if (response.status === 200) {
  423. this.$message.success('应用生成成功');
  424. this.AIform={}
  425. this.fetchApplicationList();
  426. // 可选:重定向到新应用或更新 UI
  427. } else {
  428. this.$message.error(response.data.message || '应用生成失败');
  429. }
  430. } catch (error) {
  431. console.error('Error generating application:', error);
  432. this.$message.error('应用生成失败,请稍后重试');
  433. }
  434. } else {
  435. this.$message.error('请填写所有必填字段');
  436. return false;
  437. }
  438. });
  439. },
  440. // 安全的辅助方法:通过 ID 数组获取名称数组
  441. safeGetNamesByIds(ids, list) {
  442. if (!Array.isArray(ids)) {
  443. console.warn('Expected an array of ids, but received:', ids);
  444. return [];
  445. }
  446. return ids.map(id => {
  447. if (id === '001') {
  448. return '全部';
  449. }
  450. const item = list.find(item => item.id === id);
  451. return item ? item.name : '';
  452. }).filter(name => name !== '');
  453. },
  454. /* 监听联动 */
  455. handleKnowledgeBaseChange(val) {
  456. // 重置目录和文档选择
  457. this.AIform.document_directories = [];
  458. this.AIform.documents = [];
  459. this.documentList = [];
  460. this.bucket_id=val[0]
  461. // 根据选中的知识库加载目录列表
  462. // 这里需要调用后端 API 来获取目录列表
  463. this.loadDirectoryList(val);
  464. },
  465. handleDirectoryChange(val) {
  466. // 重置文档选择
  467. this.AIform.documents = [];
  468. // 根据选中的目录加载文档列表
  469. // 这里需要调用后端 API 来获取文档列表
  470. this.loadDocumentList(val);
  471. },
  472. async loadDirectoryList(val) {
  473. this.directoryList = []; // 清空现有目录列表
  474. let totalDocuments = 0;
  475. let otherFolderCount = 0;
  476. for (const kbId of val) {
  477. const typeForm = {
  478. page: 1,
  479. pageSize: 9999,
  480. kb_id: kbId,
  481. };
  482. try {
  483. const res = await selectTypeList(typeForm);
  484. // 假设 res.data 包含目录列表
  485. if (res.data) {
  486. // 将新的目录添加到列表中,避免重复
  487. this.directoryList = [...new Set([...this.directoryList, ...res.data.dataList])];
  488. console.log(res.data.dataList);
  489. // 计算总文档数和其他文件夹数量
  490. res.data.dataList.forEach(folder => {
  491. if (folder.id === "other") {
  492. otherFolderCount += folder.document_count || 0;
  493. } else {
  494. totalDocuments += folder.document_count || 0;
  495. }
  496. });
  497. }
  498. } catch (error) {
  499. console.error(`Error loading directory list for kb_id ${kbId}:`, error);
  500. // 可以在这里添加错误处理,比如显示一个错误提示
  501. }
  502. }
  503. // 在列表开头插入"全部"选项
  504. this.directoryList.unshift({
  505. id: "001",
  506. name: "全部",
  507. /* document_count: totalDocuments + otherFolderCount, */
  508. });
  509. },
  510. loadDocumentList(val) {
  511. console.log(val);
  512. let queryForm={
  513. page: 1,
  514. pageSize: 9999,
  515. bucket_id: this.bucket_id,
  516. doc_type_id: val=='001'?0 :val,
  517. }
  518. getBucketContents(queryForm).then(res=>{
  519. this.documentList=res.data.documents
  520. })
  521. },
  522. /* 聊天记录 */
  523. selectChat(index) {
  524. this.currentChatIndex = index;
  525. // Load the selected chat messages
  526. // This is where you would typically load the messages for the selected chat
  527. },
  528. newChat() {
  529. this.chatHistory.push({ title: `聊天 ${this.chatHistory.length + 1}`, preview: "新的聊天..." });
  530. this.currentChatIndex = this.chatHistory.length - 1;
  531. // Clear the current messages and start a new chat
  532. this.messages = [];
  533. },
  534. handleLinkClick(event) {
  535. if (event.target.tagName === 'A') {
  536. event.preventDefault(); // 阻止默认行为
  537. const href = event.target.href;
  538. localStorage.setItem('href', href);
  539. // 使用 window.open 打开新标签页
  540. window.open('#/preview', '_blank');
  541. }
  542. },
  543. handleLoginSuccess() {
  544. this.showLoginModal = false;
  545. this.isLoggedIn = true;
  546. // 登录成功后,可以继续发送消息
  547. this.sendMessage();
  548. },
  549. getUuid() {
  550. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
  551. /[xy]/g,
  552. function (c) {
  553. var r = (Math.random() * 16) | 0,
  554. v = c == "x" ? r : (r & 0x3) | 0x8;
  555. return v.toString(16);
  556. }
  557. );
  558. },
  559. connectWebSocket() {
  560. const wsUrl = 'http://58.246.234.210:7860/api/v1/run/2f1faff2-99df-4821-87d6-43d693084c4b?stream=false'
  561. // 这里做一个简单的鉴权,只有符合条件的鉴权才能握手成功
  562. // 移除这里的fetch调用,改用WebSocket
  563. this.websocket = new WebSocket(wsUrl);
  564. /* this.websocket.onerror = (event) => {
  565. console.error("WebSocket 连接错误:", event);
  566. };
  567. */
  568. this.websocket.onclose = (event) => {
  569. console.log("WebSocket 连接关闭:", event);
  570. };
  571. this.websocket.onopen = (event) => {
  572. console.log("WebSocket 连接已建立:", event);
  573. };
  574. this.websocket.onmessage = (event) => {
  575. // 解析收到的消息
  576. const result = JSON.parse(event.data);
  577. // 检查消息是否完结
  578. if (result.done) {
  579. this.messages[this.messages.length - 1].done = true;
  580. return;
  581. }
  582. if (this.messages[this.messages.length - 1].done) {
  583. // 添加新的消息
  584. this.messages.push({
  585. time: Date.now(),
  586. message: result.content,
  587. messageType: "TEXT",
  588. user: "bot",
  589. done: false,
  590. });
  591. } else {
  592. // 更新最后一条消息
  593. let lastMessage = this.messages[this.messages.length - 1];
  594. lastMessage.message += result.content;
  595. this.messages[this.messages.length - 1] = lastMessage;
  596. }
  597. };
  598. },
  599. async sendMessage() {
  600. if(this.$route.name=='ai'){
  601. if(!sessionStorage.getItem('AIData')){
  602. this.showLoginModal=true
  603. return
  604. }
  605. }
  606. const chatId = this.getUuid();
  607. const wsUrl =this.wsUrl//'http://58.246.234.210:7860/api/v1/run/3ef7369e-b617-40d2-9e2e-54f3ee76ed2e?stream=false'
  608. let message = this.userInput.trim();
  609. if (message) {
  610. // Markdown换行:在每个换行符之前添加两个空格
  611. message = message.replace(/(\r\n|\r|\n)/g, " \n");
  612. this.messages.push({
  613. time: Date.now(),
  614. message: message,
  615. messageType: "TEXT",
  616. user: "user",
  617. done: true,
  618. });
  619. this.userInput = "";
  620. // 添加机器人的响应消息(初始为空)
  621. const botMessage = {
  622. user: "bot",
  623. messageType: "TEXT",
  624. message: "",
  625. html: "",
  626. time: Date.now(),
  627. done: false,
  628. };
  629. this.messages.push(botMessage);
  630. // 开始模拟思考
  631. const thinkingPromise = this.simulateThinking(botMessage);
  632. // 通过 HTTP 发送消息
  633. try {
  634. ///send-message
  635. const response = await fetch(`${wsUrl}`, {
  636. method: "POST",
  637. headers: {
  638. "Content-Type": "application/json",
  639. },
  640. body: JSON.stringify({
  641. chatId: chatId,
  642. input_value: message,
  643. output_type: "chat",
  644. input_type: "chat",
  645. tweaks:this.tweaks /* {
  646. "ChatInput-U82Vu": {},
  647. "Prompt-b8Z1E": {},
  648. "OllamaModel-z9SVx": {},
  649. "Milvus-l0vvr": {},
  650. "OllamaEmbeddings-4Ml5q": {},
  651. "ParseData-LM8yW": {},
  652. "ParseData-jVoZg": {},
  653. "APIRequest-OnZHl": {},
  654. "ParseData-fH1vY": {},
  655. "ChatOutput-ybzb9": {}
  656. } */,
  657. }),
  658. });
  659. if (!response.ok) {
  660. const errorText = await response.text(); // 获取错误文本
  661. throw new Error(
  662. `HTTP error! status: ${response.status}, message: ${errorText}`
  663. );
  664. }
  665. const result = await response.json();
  666. // 等待思考动画完成
  667. await thinkingPromise;
  668. if(this.$route.name !== 'ai'){
  669. // 提取 additional_input 数据
  670. const additionalInput = result.outputs?.[0]?.outputs?.[0]?.results?.message?.data?.additional_input;
  671. // 处理字符串,提取 ID 值
  672. this.idArray = additionalInput.split('\n') // 按换行符分割
  673. .map(line => line.trim()) // 去除每行首尾空白
  674. .filter(line => line.startsWith('ID:')) // 只保留以 'ID:' 开头的行
  675. .map(line => line.substring(3).trim()); // 提取 'ID:' 后面的内容并去除空白
  676. // 创建符合要求格式的对象
  677. const idObject = { ids: this.idArray };
  678. console.log("ID Object:", idObject);
  679. // 调用方法来获取 Minio URL,传递新的 idObject
  680. await this.getMinioUrls(idObject);
  681. }
  682. this.handleResponse(result, botMessage);
  683. } catch (error) {
  684. console.error("Error sending message:", error);
  685. // 如果发生错误,停止思考动画
  686. botMessage.done = true;
  687. botMessage.message = "抱歉,发生了错误,请稍后再试。";
  688. }
  689. }
  690. },
  691. async getMinioUrls(idObject) {
  692. this.minioUrls = []; // 清空之前的 URL
  693. try {
  694. console.log("Sending to backend:", JSON.stringify(idObject));
  695. const response = await axios.post('http://58.246.234.210:8084/milvus/getMinioURl', idObject, {
  696. headers: {
  697. 'Content-Type': 'application/json'
  698. }
  699. });
  700. if (response.status === 200 && response.data) {
  701. this.minioUrls = response.data.data; // 假设返回的是 URL 数组
  702. console.log("Received Minio URLs:", this.minioUrls);
  703. } else {
  704. console.error('Failed to get Minio URLs');
  705. }
  706. } catch (error) {
  707. console.error('Error fetching Minio URLs:', error);
  708. if (error.response) {
  709. console.error('Response data:', error.response.data);
  710. console.error('Response status:', error.response.status);
  711. console.error('Response headers:', error.response.headers);
  712. } else if (error.request) {
  713. console.error('No response received:', error.request);
  714. } else {
  715. console.error('Error message:', error.message);
  716. }
  717. }
  718. },
  719. async simulateThinking(message) {
  720. this.isThinking = true;
  721. const thinkingTime = Math.random() * 1000 + 500; // 思考时间为 0.5-1.5 秒
  722. const dotInterval = 200; // 每 200ms 更新一次点
  723. const updateDots = () => {
  724. this.thinkingDots += '.';
  725. if (this.thinkingDots.length > 3) {
  726. this.thinkingDots = '';
  727. }
  728. message.message = this.thinkingDots;
  729. };
  730. const intervalId = setInterval(updateDots, dotInterval);
  731. await new Promise(resolve => setTimeout(resolve, thinkingTime));
  732. clearInterval(intervalId);
  733. this.isThinking = false;
  734. this.thinkingDots = '';
  735. message.message = '';
  736. },
  737. async handleResponse(value, existingMessage) {
  738. const data = value.outputs[0].outputs[0].results.message;
  739. existingMessage.messageType = data.text_key;
  740. existingMessage.time = data.timestamp;
  741. existingMessage.message = '';
  742. let mainText = data.text;
  743. let sourceText = '';
  744. if (this.$route.name !== 'ai' && this.minioUrls && this.minioUrls.length > 0) {
  745. sourceText = "\n\n<div class='source-section'><h3>相关资料来源:</h3><ol>";
  746. this.minioUrls.forEach((url, index) => {
  747. sourceText += `<li><a href="${url.url}" target="_blank" class="source-link">${url.object_name}</a></li>`;
  748. });
  749. sourceText += "</ol></div>";
  750. }
  751. // 先进行主要内容的打字效果
  752. await this.typeMessage(existingMessage, mainText);
  753. // 直接添加资料来源部分
  754. if (sourceText) {
  755. existingMessage.message += sourceText;
  756. existingMessage.html = this.renderMarkdown(existingMessage.message);
  757. }
  758. },
  759. typeMessage(message, fullText) {
  760. return new Promise(resolve => {
  761. const delay = 30;
  762. let i = 0;
  763. const typeChar = () => {
  764. if (i < fullText.length) {
  765. message.message += fullText[i];
  766. i++;
  767. setTimeout(typeChar, delay);
  768. } else {
  769. message.done = true;
  770. message.html = this.renderMarkdown(message.message);
  771. resolve();
  772. }
  773. };
  774. typeChar();
  775. });
  776. },
  777. renderMarkdown(rawMarkdown) {
  778. const md = new MarkdownIt({
  779. html: true,
  780. breaks: true,
  781. linkify: true
  782. });
  783. // 自定义链接渲染规则
  784. md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
  785. const token = tokens[idx];
  786. const hrefIndex = token.attrIndex('href');
  787. const href = token.attrs[hrefIndex][1];
  788. return `<span class="custom-link" data-href="${href}">`;
  789. };
  790. md.renderer.rules.link_close = () => '</span>';
  791. const renderedHtml = md.render(rawMarkdown);
  792. // 使用 setTimeout 来确保 DOM 更新后再添加事件监听器
  793. setTimeout(() => {
  794. const links = document.querySelectorAll('.custom-link');
  795. links.forEach(link => {
  796. link.addEventListener('click', (e) => {
  797. e.preventDefault();
  798. const href = link.getAttribute('data-href');
  799. window.open(href, '_blank');
  800. });
  801. });
  802. }, 0);
  803. return renderedHtml;
  804. },
  805. handleKeydown(event) {
  806. // Check if 'Enter' is pressed without the 'Alt' key
  807. if (event.key === "Enter" && !(event.shiftKey || event.altKey)) {
  808. event.preventDefault(); // Prevent the default action to avoid line break in textarea
  809. this.sendMessage();
  810. } else if (event.key === "Enter" && event.altKey) {
  811. // Allow 'Alt + Enter' to insert a newline
  812. const cursorPosition = event.target.selectionStart;
  813. const textBeforeCursor = this.userInput.slice(0, cursorPosition);
  814. const textAfterCursor = this.userInput.slice(cursorPosition);
  815. // Insert the newline character at the cursor position
  816. this.userInput = textBeforeCursor + "\n" + textAfterCursor;
  817. // Move the cursor to the right after the inserted newline
  818. this.$nextTick(() => {
  819. event.target.selectionStart = cursorPosition + 1;
  820. event.target.selectionEnd = cursorPosition + 1;
  821. });
  822. }
  823. },
  824. beforeDestroy() {
  825. if (this.websocket) {
  826. this.websocket.close();
  827. }
  828. },
  829. /* 获取列表 */
  830. init(){
  831. /* 模型库 */
  832. modelList({model_type:'model'}).then(res=>{
  833. this.modelNameList=res.data
  834. })
  835. /* 知识库 */
  836. listBuckets({ user_id: this.$store.state.user.id }).then(res=>{
  837. this.kneList=res.data
  838. })
  839. /* 应用列表 */
  840. configList().then(res=>{
  841. this.knowledgeBases=res.data
  842. console.log(res);
  843. })
  844. }
  845. },
  846. updated() {
  847. const messagesContainer = this.$el.querySelector(".messages");
  848. if(messagesContainer){
  849. messagesContainer.scrollTop = messagesContainer.scrollHeight;
  850. }
  851. },
  852. };