Vue3——如何读取chatgpt的流式数据

一、实现效果图

二、读取数据

下图是gpt返回的流式数据的数据形式,那么我们怎么把这个数据放到页面中,以实现gpt的打字机效果呢?

javascript 复制代码
const response = await fetch(baseURLs + "/api/ut/plan/smartWriteStream", {
      method: "POST",
      body: JSON.stringify(par),
      headers: {
        "Content-Type": "application/json",
        Accept: "text/event-stream",
        tk: localStorage.getItem("token"),
      },
    });
    searchCon.value = "";
    const encode = new TextDecoder("utf-8");
    const reader = response.body.getReader();
    while (true) {
      const { done, value } = await reader.read();
      const decodeText = encode.decode(value);
      // console.log(decodeText, "流式数据");

      // 读取结束
      if (done) {
        isShowstopBtn.value = false;
        isShowconfirmBtn.value = true;
        break;
      }


      if (isAddText.value) {
        longText.value += getReaderText(decodeText);
        setTimeout(() => {
          if (scrollbarRef.value) {
            let ele = document.getElementById("innerRef");
            const max = ele.clientHeight;
            scrollbarRef.value[0].setScrollTop(max * 1 + 1000000);
          }
        }, 300);
      } else {
        break;
      }
    }

三、处理流式数据中的特殊字符

javascript 复制代码
const getReaderText = (str) => {
  let matchStr = "";
  try {
    let resultList = str.trim().split("\n");
    resultList.forEach((item) => {
      const firstQuoteIndex = item.indexOf('"');
      const lastQuoteIndex = item.lastIndexOf('"');
      matchStr += item
        .substring(firstQuoteIndex + 1, lastQuoteIndex)
        .replace("\\n\\n", "")
        .replace("\n\n", "")
        .replace("\\n", "")
        .replace("\n", "")
        .replace("\\\\", "")
        .replace("\\", "");
    });
    // console.log(resultList, "4444");
  } catch (e) {
    // console.log(e);
  }
  // console.log(matchStr);
  return matchStr;
};
相关推荐
KaMeidebaby3 小时前
卡梅德生物技术快报|PD1 单克隆抗体定制配套 N 糖全谱质控开发
前端·人工智能·算法·数据挖掘·数据分析
nuIl4 小时前
实现一个 Coding Agent(3):工具调用
前端·agent·cursor
nuIl4 小时前
实现一个 Coding Agent(4):ReAct 循环
前端·agent·cursor
nuIl4 小时前
实现一个 Coding Agent(1):一次 LLM 调用
前端·agent·cursor
nuIl4 小时前
实现一个 Coding Agent(2):让 LLM 流式响应
前端·agent·cursor
copyer_xyf4 小时前
Python 异常处理
前端·后端·python
sugar__salt4 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
独特的螺狮粉5 小时前
篮球集训班器具管理系统 - 鸿蒙PC Electron框架完整技术实现指南
前端·javascript·华为·electron·前端框架·开源·鸿蒙
pusheng20255 小时前
IFSJ全英文专访:中国创新力量重塑先进气体感知技术,赋能全球关键基础设施安全
前端·网络·人工智能·物联网·安全
AI_零食5 小时前
番茄钟鸿蒙PC Electron框架完成:状态机、定时器管理与专注力工具设计
前端·javascript·华为·electron·开源·鸿蒙·鸿蒙系统