对chatGPT接口返回的数据进行流式获取

125 阅读1分钟
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" name="" id="" /> <button>提问</button>
    <h1></h1>
    <script>
      const h1 = document.querySelector("h1");
      const input = document.querySelector("input");
      const button = document.querySelector("button");
      async function getContent() {
        h1.innerHTML = "思考中";
        const data = {
          prompt: input.value,
          options: {
            parentMessageId: "chatcmpl-80nINVbjJRJzPRPxgk0buqJXf2Pxy",
          },
          temperature: 0.8,
          top_p: 1,
        };
        //具体网址不方便透露,需要可私信
        const res = await fetch("xxxxxx", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data),
        });
        // 定义读取器
        const reader = res.body.getReader();
        h1.innerHTML = "";
        while (1) {
          //  reader.read() 有多少读多少数据  done 是否已读完  value 读出的数据
          const { done, value } = await reader.read();
          if (done) {
            break;
          }
          // 将编码数据转为字符串
          const str = new TextDecoder().decode(value);
          // 对数据的2次处理
          const arr = str
            .trim()
            .split("\n")
            .map((str) => str.trim());
          arr.forEach((v, i) => {
            const obj = JSON.parse(v);
            h1.innerHTML += obj.delta ? obj.delta : "";
          });
        }
      }
      button.onclick = () => {
        getContent();
      };
    </script>
  </body>
</html>