uniapp 微信小程序,最简单的流式输出:Transfer-Encoding: chunked

在GPT项目中,流式输出是实现流畅对话体验的关键技术之一。今天,我们将探讨如何在uniapp开发的微信小程序中优雅地实现这一功能。虽然WebSocket是一种常见的解决方案,但在某些场景下,我们可能寻求更轻量级且易于集成的替代方案。本文将介绍一种基于Transfer-Encoding: chunked的HTTP请求方式,它不仅避免了WebSocket的复杂性,同时也绕过了微信小程序对XHR和EventSource的限制。

在微信小程序环境下,由于平台限制,XHR和EventSource并不总是可用,而WebSocket的部署和维护成本相对较高。因此,我们探索了一种更为直接的方法------利用HTTP协议中的Transfer-Encoding: chunked特性。

实现细节:Transfer-Encoding: chunked
Transfer-Encoding: chunked允许服务器以分块的方式发送数据,而无需事先知道整个响应的大小。这种方式特别适合于流式输出场景,因为它可以实时地将数据推送给客户端,而无需等待整个响应构建完成。对于uniapp小程序而言,这意味着可以即时更新UI,提供更流畅的用户体验。

后台不需要改动,继续采用流式输出的形式即可,以通义千问的demo为例,代码如下

复制代码
@RequestMapping(value = "/completions", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Result<CompletionsOutMsg>> completions(@RequestBody CompletionsInMsg inMsg) {
    ....
}

客户端处理:uniapp小程序

在uniapp小程序端,需要监听网络请求的onProgressUpdate事件或使用onChunkReceived回调来处理分块数据。下面是一个处理分块数据的示例代码:

复制代码
<template>
  <view class="page">
    <view class="box">
      <textarea class="uni-textarea" v-model="inputValue" placeholder="请输入内容"/>
    </view>
    <button class="mini-btn btn" type="primary" size="mini" @click="commit">提交</button>
    <view>
      {{ resultText }}
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      inputValue: '',
      resultText: '',
    };
  },
  methods: {
    commit() {
      var that = this;
      const requestTask = uni.request({
        url: 'YOUR_API_URL',
        method: 'POST',
        responseType: 'text',
        enableChunked: true,  //流式输出需要设置enableChunked为true
        data: {
          prompt: this.inputValue,
        },
        success: function (res) {
          console.log(JSON.stringify(res))
        },
        fail: function (err) {
        }
      });

      // 监听流式输出
      requestTask.onChunkReceived(function(res) {
        const uint8Array = new Uint8Array(res.data);
        let text = String.fromCharCode.apply(null, uint8Array);
        text = decodeURIComponent(escape(text));
        console.log(text);
        if (text) {
          let cleanedContent = text.replaceAll("data:", ',');
          let splitContent = "[" + cleanedContent.replace(/^,/, '') + "]";
          const dataArray = JSON.parse(splitContent);
          for (let i = 0; i < dataArray.length; i++) {
            that.resultText += dataArray[i].data.text;
          }
        }

      })


    },

  },


}
</script>

<style lang="scss">
.page {
  display: flex;
  justify-content: center;
  align-content: center;
  flex-direction: column;
}

.box {
  padding: 20rpx;
}

.btn {
  text-align: center;
  margin-top: 20rpx;
}

.uni-textarea {
  border: solid 1px #a59d9d;
  padding: 20rpx;
  width: 100%;
}

</style>
相关推荐
2501_9159184115 分钟前
掌握 iOS 26 App 运行状况,多工具协作下的监控策略
android·ios·小程序·https·uni-app·iphone·webview
知识分享小能手40 分钟前
uni-app 入门学习教程,从入门到精通,uni-app基础扩展 —— 详细知识点与案例(3)
vue.js·学习·ui·微信小程序·小程序·uni-app·编程
2501_915909063 小时前
iOS 混淆实战,多工具组合完成 IPA 混淆与加固(源码 + 成品 + 运维一体化方案)
android·运维·ios·小程序·uni-app·iphone·webview
狂团商城小师妹3 小时前
智尚房产中介小程序
微信小程序·小程序
赵庆明老师4 小时前
Uniapp微信小程序开发:EF Core 中级联删除
uni-app
Javashop_jjj5 小时前
三勾软件| 用SpringBoot+Element-UI+UniApp+Redis+MySQL打造的点餐连锁系统
spring boot·ui·uni-app
狂团商城小师妹7 小时前
预约洗车小程序
微信小程序·小程序
future_studio7 小时前
聊聊 Unity(小白专享、C# 小程序 之 图片播放器)
unity·小程序·c#
Q_Q51100828512 小时前
python+uniapp基于微信小程序的心理咨询信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
HuYi_code13 小时前
WeChat 小程序下载文件实现
微信小程序·uni-app