微信小程序通过Laf云平台接入ChatGPT实现聊天,回答方式采用流式回答。
以下是图片展示其页面
回答次数通过卡密兑换
以下是对话页面的代码
<!--pages/content/content.wxml--><view class="container"><view class="div" hidden="{{AnswerList.length>0}}"><view><image src="../../images/editor.png" mode=""/><text class="one-text">AI创作</text></view><view><image src="../../images/tip.png" mode=""/><text class="one-text">有趣的提问</text></view><view><image src="../../images/book.png" mode=""/><text class="one-text">AI百科</text></view></view><view class="div-two" hidden="{{AnswerList.length>0}}"><view class="div-two-one"><text bindtap="handleTextClick" data-message="写一首赞美祖国的诗">写一首赞美祖国的诗→</text><text bindtap="handleTextClick" data-message="写一篇科幻小说" >写一篇科幻小说→</text><text bindtap="handleTextClick" data-message="安排一场发布会流程" >安排一场发布会流程→</text></view><view class="div-two-one"><view class="div-two-one"><text bindtap="handleTextClick" data-message="有哪些有趣的科学实验" >有哪些有趣的科学实验→</text><text bindtap="handleTextClick" data-message="一个AI也回答不出来的问题" >问一个AI也回答不出来的问题→</text><text bindtap="handleTextClick" data-message="AI会替代人类工作吗?" >AI会替代人类工作吗?→</text></view></view><view class="div-two-one"><text bindtap="handleTextClick" data-message="用简单的术语来解释人工智能" >用简单的术语来解释人工智能→</text><text bindtap="handleTextClick" data-message="红烧牛肉的做法" >红烧牛肉的做法→</text><text bindtap="handleTextClick" data-message="请介绍一下你自己" >请介绍一下你自己→</text></view></view><scroll-view scroll-y="true" hidden="{{AnswerList.length==0}}"><view class="div-answer" wx:for="{{AnswerList}}" wx:key="index"><view class="answer"><image src="../../images/49.webp"></image><rich-text>{{item.message}}</rich-text></view><view class="answer answer-one"><image src="../../images/chatgpt.jpeg"></image><rich-text>{{item.answer || '...'}}</rich-text></view></view></scroll-view><view class="question"><view class="question-one"><textarea disabled="{{isDisable}}" class="texta" value="{{question}}" placeholder="请输入内容" style="width: 80%;" bindinput="inputChange" ></textarea><image src="../../images/send.png" bind:tap="submitQuestion"></image></view></view></view>
//流式响应格式
const requestTask=wx.request({url: ,method:'POST',data:{message:this.data.AnswerList[this.data.AnswerList.length-1].message,parentMessageId:this.data.conversationId},enableChunked:true,success:(res)=>{//流式输出完成后,修改并保存balancewx.request({url: ,method:'POST',data:{balance:this.data.balance,_id:this.data._id},success:(res)=>{wx.setStorageSync('user', res.data)console.log(res.data);}})}})//通过流式输出响应到页面上,并保存对话idrequestTask.onChunkReceived((response)=>{const arrayBuffer = response.data;const uint8Array = new Uint8Array(arrayBuffer);let text = wx.arrayBufferToBase64(uint8Array);text = Base64.decode(text);const t1=text.split("--!")if (t1.length>1) {this.setData({parentMessageId:t1[1]})}const len=this.data.AnswerList.lengththis.data.AnswerList[len-1]={message:this.data.AnswerList[len-1].message,answer:this.data.AnswerList[len-1].answer+t1[0]}this.setData({AnswerList:this.data.AnswerList,isDisable:false})console.log(t1);})
详细代码通过加企鹅获取
493305086