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>
相关推荐
m0_462803886 小时前
“趣味运动会记分”功能教学指南
小程序
网络安全学习库10 小时前
很喜欢Vue,但还是选择了React: AI时代的新考量
vue.js·人工智能·react.js·小程序·aigc·产品经理·ai编程
叱咤少帅(少帅)11 小时前
Uniapp开发pc端,小程序和APK
小程序·uni-app
2501_915918411 天前
iOS性能测试工具 Instruments、Keymob的使用方法 不局限 FPS
android·ios·小程序·https·uni-app·iphone·webview
Chengbei111 天前
利用 LibreNMS snmpget 配置篡改实现 RCE 的完整攻击链
人工智能·web安全·网络安全·小程序·系统安全
苏灵凯1 天前
智能环境监测终端全栈设计:从单片机到微信小程序,手把手搞定!
单片机·嵌入式硬件·mcu·物联网·微信小程序·小程序·蓝牙模块
nhc0881 天前
贵阳纳海川科技有限公司・货运物流行业解决方案
科技·微信小程序·小程序·软件开发·小程序开发
admin and root1 天前
AWS S3 对象存储攻防&云安全之OSS存储桶漏洞
微信小程序·小程序·渗透测试·云计算·aws·src·攻防演练
取码网1 天前
新版点微同城主题源码34.7+全套插件+小程序前后端 源文件
小程序
2501_915918411 天前
iOS 混淆流程 提升 IPA 分析难度 实现 IPA 深度加固
android·ios·小程序·https·uni-app·iphone·webview