chartGPT流式返回前端处理

const { data } = await checkCensor({ msg: `${this.content}用中文回答` });
      if (data.data) {
        const object = {
          content: "您的问题不在我的能力范围之内。",
          role: "assistant",
        };
        this.chatList.push(object);
        $(".ai-content .content").animate({ scrollTop: 900000 }, 400);
        this.loading = false;
        this.content = "";
        return;
      }
      $(".ai-content .content").animate({ scrollTop: 900000 }, 400);
      this.content = "";
      try {
        const response = await fetch("https://www.chatbase.co/api/v1/chat", {
          method: "POST",
          headers: {
            Authorization: this.botInfo.authorization,
          },
          body: JSON.stringify({
            messages: [...this.chatList].slice(-5),
            chatId: this.botInfo.chatId,
            stream: this.botInfo.stream,
            model: this.botInfo.model,
          }),
        });

        const data = response.body;
        if (!data) {
          // error happened
        }
        const reader = data.getReader();
        const decoder = new TextDecoder();
        let done = false;
        const object2 = {
          content: "",
          role: "assistant",
        };
        this.chatList.push(object2);
        $(".ai-content .content").animate({ scrollTop: 900000 }, 400);

        while (!done) {
          const { value, done: doneReading } = await reader.read();
          done = doneReading;
          const chunkValue = decoder.decode(value);
          this.resMessage += chunkValue;
          this.chatList[this.chatList.length - 1].content += chunkValue;
          $(".ai-content .content").animate({ scrollTop: 900000 }, 0);
          //      console.log(this.resMessage); // This will log chunks of the chatbot reply until the reply is finished.
        }
        if (done) {
          // clearTimeout(this.timer)
          // $(".ai-content .content").animate({ scrollTop: 0 }, 400);
          this.toSaveChatMsg();
        }
      } catch (e) {
        this.loading = false;
      }
posted @ 2023-05-10 14:06  敲敲碰碰  阅读(468)  评论(0)    收藏  举报