小程序流式模式AI

2024-08-08 14:22:40 阅读:1 编辑
// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    id: "",
    //question: "福建厦门的土特产有哪些?,列出3个,字数不超过30个字",
    question: "推荐3个福建厦门的景点,字数不超过150个字",
    answer: "",
  },
  onLoad(o) {
    if (o.id) {
      this.setData({
        id: o.id,
      });
    }
    this.checkLogin(user => {
      this.setData({
        user
      });
      this.getData();
    }, "/meta/ai/agent/agent", true);
  },
  toSend() {
    this.toSendWithStream();
  },
  toSendWithStream() {

    let question = this.data.question;
    if (question == "") {
      app.alert('请输入问题');
      return;
    }

    let data = {
      query: question,
      is_web: 0,
    };
   // this.addQuestion(data);
  //  this.initAnswer(uuid);
    let url = app.siteInfo.siteroot + '?i=' + app.siteInfo.uniacid + '&t=0&v=1.0&from=wxapp&c=entry&a=wxapp&do=Api_zhyai|query_stream&m=zhyshop_sun';
      const requestTask = wx.request({
        url: url,
        timeout: 60000,
        responseType: 'arraybuffer',
        enableChunked: true,
        method: "POST",
        data: data,

        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 text = this.formatText(json);
       if(text !== false){
        this.toSetAnswer(text);
       }

    });
  },
  toSetAnswer(text){
      this.setData({
        answer:this.data.answer + text
      });
  },
  formatText(str) {
    let arr = str.split("\t");
    console.log(arr);
     let text = "";
    for (var i in arr) {
      let temp = arr[i].trim('"');
      if (temp != "") {
        let json =JSON.parse(temp);
        if(json){
          if(json.event == "message"){
            text += json.answer;
          }else if(json.event == "error"){
              return false;
          }else if(json.event == "message_end"){
            return false;
        }
        }
      }
    } 
    return text;
  },
  getData() {

  }
})