一、实现效果图
二、读取数据
下图是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;
};