ZdyRag.api.ts 2.4 KB
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import { useUserStore } from '@/store/modules/user';

const { createMessage } = useMessage();

enum Api {
  send = '/airag/zdyRag/send',
  buttonList = '/airagbutton/airagButton/buttonList',
}

/**
 * 发送消息(流式处理)
 * @param params
 */
export const sendMessage = async (params: { questionText: string; code: string; codeType: number }) => {
  try {
    const userStore = useUserStore();
    console.log("userStore",userStore.getUserInfo.username)
    const token = userStore.getToken;
    const username = userStore.getUserInfo.username
    // 拼接参数
    const query = new URLSearchParams({
      questionText: params.questionText,
      code: params.code,
      codeType: String(params.codeType),
      user: username == undefined  ? "public" : username
    }).toString();

    const response = await fetch(
      `/jeecgboot/airag/zdyRag/sendStream?${query}`,
      {
        method: 'GET',
        headers: {
          'x-access-token': token,
          'Accept': 'text/event-stream'
        },
        credentials: 'include',
      }
    );

    if (!response.ok || !response.body) {
      throw new Error(`请求失败: ${response.status} ${response.statusText}`);
    }

    return (async function* () {
      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8');
      let buffer = '';

      try {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          const chunk = decoder.decode(value, { stream: true });
          buffer += chunk;

          const lines = buffer.split('\n');
          buffer = lines.pop() || '';

          for (const line of lines) {
            if (line.startsWith('data:')) {
              try {
                const jsonStr = line.substring(5).trim();
                if (jsonStr) {
                  yield JSON.parse(jsonStr);
                }
              } catch (e) {
                console.error('JSON解析错误:', e);
              }
            }
          }
        }
      } finally {
        reader.releaseLock();
      }
    })();
  } catch (error) {
    console.error('Error sending message:', error);
    createMessage.error('发送消息失败');
    throw error;
  }
};

export const getButtonList = async () => {
  const res = await defHttp.get({
    url: Api.buttonList,
  });
  if (res) {
    return res;
  }
  return null;
}