use-sse-chat.js 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import { ref } from 'vue';
  2. import fetchEventSource from '../../3rd-libs/microsoft-feat-event-source';
  3. import { kuky_Authorization } from '../../base/storage';
  4. import { getConfigField } from '../../config/index';
  5. /**
  6. * 区分智能体类型
  7. * 参数:mode
  8. * 1.聊天助手 [agent-dialog,advanced-chat]
  9. * 2.Agent [agent-chat]
  10. * 3.工作流 [workflow]
  11. * */
  12. /**
  13. * 获取sse连接的地址
  14. * @param {string} menu_id - 对话类型,可选值:1/2/3/4/5/6/7/8/9
  15. * @param {string} agent_id - 对话使用的agent ID
  16. * @param {string} chat_id - 对话记录的ID
  17. * @param {string} mode - 对话类型
  18. * [agent-dialog], ragflow 智能体
  19. * [agent-chat,chat,'advanced-chat'],dify智能体
  20. * [workflow] dify智能体
  21. * [agent-basic]
  22. * @returns
  23. */
  24. function getSseUrl(agent_id, mode) {
  25. const chat_id = agent_id;
  26. let base_url = '';
  27. // 获取环境配置并动态替换 URL
  28. if (import.meta.env.MODE === 'production') {
  29. base_url = getConfigField('API_BASE_URL');
  30. } else {
  31. base_url = '';
  32. }
  33. if (['agent-dialog'].includes(mode)) {
  34. return base_url + `/api/v1/chat/${chat_id}/completions`;
  35. }
  36. if (['advanced-chat', 'agent-chat', 'chat'].includes(mode)) {
  37. return base_url + `/api/v1/agent/${chat_id}/completions`;
  38. }
  39. if (['workflow'].includes(mode)) {
  40. return base_url + `/api/v1/workflow/${chat_id}/completions`;
  41. }
  42. if (['agent-basic'].includes(mode)) {
  43. return base_url + `/api/v1/complex/${chat_id}/completions`;
  44. }
  45. console.log(base_url);
  46. }
  47. /**
  48. *获取token
  49. */
  50. function getToken() {
  51. return kuky_Authorization.get();
  52. }
  53. export default function useFetchEventSource() {
  54. const messages_list = ref([]); // 存储接收到的消息
  55. const isLoading = ref(false); // 是否正在连接
  56. const error = ref(null); // 错误信息
  57. const isConnected = ref(false); // 是否已连接
  58. const abortController = new AbortController(); // 用于取消请求
  59. /**
  60. * queryParams: sse接口需要传递的参数
  61. * */
  62. const startStream = (queryParams, onMessage = defaultOnMessage) => {
  63. isLoading.value = true;
  64. isConnected.value = false;
  65. error.value = null;
  66. const { agent_id, session_id, mode, query, files, inputs } = queryParams;
  67. const sse_url = getSseUrl(agent_id, mode);
  68. if (!sse_url) {
  69. return;
  70. }
  71. fetchEventSource(sse_url, {
  72. method: 'POST',
  73. headers: {
  74. Authorization: `Bearer ${getToken()}`,
  75. 'Content-Type': 'application/json',
  76. Accept: 'text/event-stream'
  77. },
  78. body: JSON.stringify({ sessionId: session_id, query, files, inputs }),
  79. signal: abortController.signal, // 支持取消请求messages
  80. // openWhenHidden: true, //页面退至后台后保持连接
  81. onmessage(ev) {
  82. onMessage(ev);
  83. },
  84. onclose() {
  85. console.log('Connection closed by server');
  86. isConnected.value = false;
  87. isLoading.value = false;
  88. },
  89. onerror(err) {
  90. console.error('Error received:', err);
  91. error.value = err;
  92. isLoading.value = false;
  93. isConnected.value = false;
  94. }
  95. });
  96. };
  97. /**
  98. * 终止当前的流连接
  99. */
  100. const stopStream = () => {
  101. abortController.abort();
  102. isLoading.value = false;
  103. isConnected.value = false;
  104. console.log('Stream aborted');
  105. };
  106. /**
  107. * 默认的消息处理函数
  108. */
  109. const defaultOnMessage = (ev) => {
  110. try {
  111. const message = JSON.parse(ev.data); // 假设返回的是JSON数据
  112. console.log('Received message:', message);
  113. // messages_list.value.push(message); // 将消息存入 messages_list
  114. } catch (e) {
  115. console.error('Failed to parse message:', e);
  116. }
  117. };
  118. return {
  119. startStream,
  120. stopStream,
  121. messages_list,
  122. isLoading,
  123. error,
  124. isConnected
  125. };
  126. }