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

本文介绍了如何通过API获取GPT返回的流式数据,并将其格式化后在网页上实现类似打字机的效果,同时处理了流式数据中的特殊字符问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、实现效果图

二、读取数据

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

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;
      }
    }

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

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;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值