最近用微信小程序做chatGpt的Ai对话,其中重要的一点就是流式响应,现在分享处理逻辑,先给演示图。
下面是关键代码实现逻辑
const that = this;const requestTask = wx.request({url: 'xxxxx',responseType: "arraybuffer",method: 'POST',enableChunked: true,header: {'content-type': 'application/json'},data: {'prompt': '青椒肉丝怎么做'},success: (res) => {console.log("request success", res);common_vendor.index.showToast({title: "请求成功",icon: "success",mask: true,duration});// this.res = "请求结果 : " + JSON.stringify(res);},fail: (err) => {console.log("request fail", err);common_vendor.index.showModal({content: err.errMsg,showCancel: false});},complete: () => {this.loading = false;}});requestTask.onHeadersReceived(function (r) {console.log(r);});requestTask.onChunkReceived(function (r) {// let decoder = new TextDecoder('utf-8');// let str = decoder.decode(new Uint8Array(r.data));// let en = String.fromCharCode.apply(null,new Uint8Array(r.data));// let de = decodeURIComponent(escape(en));// console.log("onChunkReceived", str);const data16 = that.buf2hex(r.data) // ArrayBuffer转16进制const requestData = that.hexToStr(data16) // 16进制转字符串console.log(requestData); that.res +=requestData;});
其中有两个关键点需要注意
1.enableChunked: true流式响应开关,会自动在header中加入transfer-encoding chunked
2.arraybuffer转字符串问题,有TextDecoder就很好处理,没有也可以参照我上面的示例。
最后提供免费源码下载地址和演示二维码,全量保真。
源码下载 ChatGpt插件,支持聊天,流式输出,UI漂亮,有小程序演示 - DCloud 插件市场