微信小程序AI流式输出

2025-03-18 10:51:43 阅读:2 编辑

js代码

const app = getApp();
Page({
  data: {
    info: {},
    question:"你是谁?",
    answer:"",
  },
  onPreviewTap: function (e) {
    let src = e.currentTarget.dataset.src;
    app.onPreviewTap(src);
  },
  bindinput(e){
    this.setData({
      question:e.detail.value
    });
  },
  onStart(){
    //let question = "你是谁?";
    let question = this.data.question;
    this.setData({
      answer:"",
    });
    this.toSendWithStream(question);
  },
  onLoad(options) {
//api请求(获取AI方案的配置)
let param = {
  };
  app.api.postWithPlugin('api_zhyai|getDefaultAiConfig','aiagent',param).then((res)=>{
          console.log(res);
          this.setData({info:res.data});
        }).catch((res)=>{
          app.tips(res);
        });
  },
  toSendWithStream(question) {

    let param = {
      question:question,
      response_mode: "streaming",
      is_web:0,
      flag:this.data.info.company_name,
    };
    let api_token =  this.data.info.token;
    let url = this.data.info.api_url;
    const requestTask = wx.request({
      url: url,
      timeout: 60000,
      responseType: 'arraybuffer',
      enableChunked: true,
      method: "POST",
      header: {
        'Authorization': `Bearer ` + api_token,
    },
      data: param,

      success: (res) => {

        console.log("success");
        console.log(res);
      }
    });

    requestTask.onChunkReceived((response) => {
      const arrayBuffer = response.data;
      const uint8Array = new Uint8Array(arrayBuffer);
      let json = String.fromCharCode.apply(null, uint8Array);
      console.log("json", json);
      let json_list = this.formatJson(json);
      console.log("json_list", json_list);
      for(var i =0; i < json_list.length;++i){
        let item = json_list[i];
        if(item.event == "message_end"){
this.toFinish(item);
        }else{
          this.toSetAnswer(item.answer);
        }

      }

      /*  let result = that.data.result + text;
       this.setData({
         result: result
       }); */
    });
  },
  toSetAnswer(text) {
    console.log("toSetAnswer",text);
    this.setData({
      answer:this.data.answer+text
    });
  },
  formatJson(str) {
    let arr = str.split("\t");
    //console.log(arr);
    let json_list = [];
    for (var i in arr) {
      let temp = arr[i].trim('"');
      if (temp != "") {
        json_list.push(JSON.parse(temp));
      }
    }
    return json_list;
  },
  toFinish(event){
    console.log("toFinish event",event);
    console.log("toFinish",this.data.answer);
  },
  checkPageLogin() {
    this.checkLogin(user => {
      this.setData({
        user
      });
    }, '/pages/test/mission/mission');
  },

});

wxml文件

<view class="mpage">
<input type="text" value="{{question}}" bindinput = "bindinput" />
<view>结果:</view>
<view>
{{answer}}
</view>
<button bindtap="onStart">发起</button>
</view>