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;
};
相关推荐
问心无愧05134 分钟前
ctf show web入门27
前端
小村儿18 分钟前
给 AI Agent 装上"长期记忆":Karpathy 的 LLM Wiki 思想,我做成了工具
前端·后端·ai编程
竹林81823 分钟前
用ethers.js连接MetaMask实现Web3钱包登录:从踩坑到稳定运行的完整记录
前端·javascript
heyCHEEMS26 分钟前
如何用 Recast 实现静态配置文件源码级读写
前端·node.js
心连欣27 分钟前
从零开始,学习所有指令!
前端·javascript·vue.js
review4454330 分钟前
大模型和function calling分别是如何工作的
前端
东东同学31 分钟前
耗时一个月,我把 Nuxt 首屏性能排障经验做成了一个 AI Skill
前端·agent
冴羽2 小时前
超越 Vibe Coding —— AI 辅助编程指南
前端·ai编程·vibecoding
梦想的颜色2 小时前
一天一个SKILL——前端最佳自动化测试 webapp-testing
前端·web app
SoaringHeart2 小时前
Flutter进阶:放弃 MediaQuery.of(context) 使用 NScreenManager
前端·flutter