微信小程序_调用openAi搭建虚拟伙伴聊天

news/2024/7/20 2:38:08 标签: 微信小程序, 小程序

小程序>微信小程序_调用openAi搭建虚拟伙伴聊天

  • 背景
  • 效果
    • 关于账号注册
    • 接口实现
      • 8行python搞定
    • 小程序实现
    • 页面结构
    • 数据逻辑
    • 结速

背景

从2022年的年底,网上都是chagpt的传说,个人理解这个chatgpt是模型优化训练,我们在用chatgpt的时候就在优化这个模型,这个是付费的,换言之,我们都是chagpt的韭菜,OpenAI 是一个研究组织,chagpt是他们的一个产品工具。
带着好奇心做了个小程序的聊天页面。

效果

像个机器人聊天
在这里插入图片描述

关于账号注册

由于国内电话不支持绑定openAi的邮箱,需要虚拟号码激活具体步骤网上都有教程

接口实现

8行python搞定

install openai,获取apiKey,调用即可向openai发送请求

def getOpenAiText(request):
    if request.method == 'GET':
        text = request.GET.get('text', default='')
        responseText = openai.Completion.create(
            model="text-davinci-003",
            prompt=text,
            max_tokens=100,
            temperature=0
        )
        return JsonResponse({"data": responseText, "code": 200,"msg":'success'})
    return JsonResponse({"data": {}, "code": 0,"msg":'not allowed'})

小程序实现

设计思路:灵感来源微信对话框模式一对一
只需要设计数据结构为
[{
question:‘’,
answer:‘’,
isEdit:false
}]
可以显示问答的状态
在添加一个currentIndex标识编辑的状态,遍历数字显示,加上时间绑定即可实现,
缓存采用storage。

页面结构

<view class="container-future">
  <view class="form-container-api">
    <view>
      <button style="width: 100%;" type="primary" formType="submit">openai调用</button>
    </view>
    <view class="chat-container">
      <view wx:for="{{ chatObjConfig.option }}" wx:for-index="index" wx:for-item="item" wx:key="index">
        <view class="form-request">
          <view wx:if="{{item.isEdit}}">问:$ <input bindinput="bindKeyInput" placeholder="输入关键词" data-column-index="{{index}}" disabled="{{isLoading}}" /></view> 
          <view wx:else class='questioned'>
          <view>
            问:$ {{item.question}}
          </view>
          </view>
        </view>
        <view class="form-response">
          
          <view class='questioned'>openai回答:$ {{item.answer}}</view>
        </view>
      </view>
    </view>
    <view class="form-submit">
      <button style="width: 100%;" type="primary" bindtap="search" loading="{{isLoading}}" disabled="{{isLoading}}">发送</button>
    </view>
  </view>
  <view class="loading" wx:if="{{isLoading}}">
    <view class="loader-child" />
    <view class="loader-child" />
    <view class="loader-child" />
  </view>
</view>

数据逻辑

// pages/future/future.js
const app = getApp();
const baseUrl = app.remoteConfig.baseUrl;
Component({

  /**
  * 继承父级样式
  */
  options: {
    addGlobalClass: true,
  },
  /**
   *组件的初始数据
   */
  data: {
    searchOpenAiText:'',
    responseText:'',
    // questions,answer,index
    chatObjConfig:{
      option:[{
        question:'',
        answer:'',
        isEdit:true
      }],
      currentIndex:0
    }
  },
  lifetimes: {
    // 生命周期函数,可以为函数,或一个在 methods 段中定义的方法名
    attached: function () {
      if(wx.getStorageSync('openAiOptions')){
        this.setData(
          {
            chatObjConfig:wx.getStorageSync('openAiOptions')
          }
        )
      }
    },
    moved: function () { },
    detached: function () {
      wx.setStorageSync('openAiOptions', this.data.chatObjConfig)
    },
  },

  methods: {
    bindKeyInput(e) {
      const {columnIndex}=e.currentTarget.dataset
      console.log('this.data.chatObjConfig',this.data.chatObjConfig)
      const option=this.data.chatObjConfig.option
      option.some((item,index)=>{
        if(columnIndex===index){
          item.question=e.detail.value
          item.isEdit=true
          return true
        }
        return false
      })
      this.setData({
        searchOpenAiText:e.detail.value,
        chatObjConfig:{
          option:option,
          currentIndex:columnIndex
        }
      })
    },
    search(e){
      console.log(this.data.searchOpenAiText)
      if(!this.data.searchOpenAiText){
        wx.showModal({
          cancelColor: 'cancelColor',
          title:'请输入!'
        })
      }
      wx.showLoading({
        title: '加载中',
      })
      this.setData({
        isLoading: true
      })
      console.log(e)
      const path = '/common-api/searchOpenAiText/'
      const headers = { 'Content-Type': 'application/json;charset=UTF-8' }
      const params={
        "text":this.data.searchOpenAiText
      }
      const thisBack=this
      return new Promise((resolve, reject) => {
        wx.request({
          url: baseUrl + path,
          headers: headers,
          data:params,
          method: 'GET',
          success: (res) => {
            console.log(res,'res')
            const data=res.data.data
            const option=thisBack.data.chatObjConfig.option
            const currentIndex=thisBack.data.chatObjConfig.currentIndex
            const choices=data.choices
            console.log('choices',choices)
            option.some((item,index)=>{
              if(currentIndex===index){
                item.answer=choices?choices.map(choicesItem=>{return choicesItem.text}).join('\n'):'。。。未知'
                item.isEdit=false
                return true
              }
              return false
            })
            const chatObjConfig={
              option:option,
              currentIndex:currentIndex+1
            }
            option.push({
              question:'',
              answer:'',
              isEdit:true
            })
            thisBack.setData(
              {
                isLoading: false,
                chatObjConfig:chatObjConfig
              }
            )
            setTimeout(function () {
              wx.hideLoading()
            }, 2000)
            resolve(res)
          },
          fail: error => {
            thisBack.setData({
              isLoading: false
            })
            setTimeout(function () {
              wx.hideLoading()
            }, 2000)
            reject(error)
          }
        });
      })
    }
  }
})

结速

最后我的小程序:yma16
欢迎大家访问!
在这里插入图片描述


http://www.niftyadmin.cn/n/58289.html

相关文章

Vue驼峰与短横线分割命名中有哪些坑

目录 0.前言 驼峰和短横线分割命名注意事项 组件注册命名 父子组件数据传递时命名 父子组件函数传递 0.前言 Vue驼峰命名法指的是将变量以驼峰形式命名&#xff0c;例如 userName、userId 等&#xff0c;而短横线分隔符法则指的是用短横线分隔变量名&#xff0c;例如 user…

Elasticsearch的读写搜索过程

问题 Elasticsearch在读写数据的过程是什么样的?你该如何理解这个问题&#xff01; Elasticsearch的写数据过程 客户端选择一个节点发送请求&#xff0c;这个时候我们所说的这个节点就是协调节点&#xff08;coordinating node&#xff09;协调节点对document进行了路由&am…

大数据之Hadoop

文章目录一、大数据概论1、大数据概念2、大数据的特点3、大数据应用场景4、大数据部门的业务流程分析5、大数据部门组织结构&#xff08;重点&#xff09;二、从Hadoop框架讨论大数据生态1、什么是Hadoop2、Hadoop发展历史3、Hadoop三大发行版本1.Apache Hadoop2.Cloudera Hado…

Python-项目实战--贪吃蛇小游戏(1)

1.贪吃蛇游戏规则贪吃蛇游戏规则如下:1.1开始和结束贪吃蛇初始出现在游戏窗口的左上角位置,体长共有3节游戏过程中&#xff0c;一旦蛇头撞到了窗口的边缘或者身体的其他部位,游戏结束游戏过程中&#xff0c;点击游戏窗口的关闭按钮&#xff0c;或者按下ESC键可以直接退出游戏一…

如何使用代码注释:关于JavaScript与TypeScript 注释和文档的自动生成

如何使用代码注释&#xff1a;关于JavaScript与TypeScript 注释和文档的自动生成jcLee95&#xff1a;https://blog.csdn.net/qq_28550263?spm1001.2101.3001.5343 邮箱 &#xff1a;291148484163.com 本文地址&#xff1a;https://blog.csdn.net/qq_28550263/article/detail…

2023关键词:挑战

未失踪人口回归… 好久不见&#xff0c;不经意间拖更2个多月。今天周末&#xff0c;外面淅淅沥沥下着小雨&#xff0c;这种窝在床上的时刻最适合写点东西了。 但是建议大家在办公或者写博客的时候尽量还是端正坐姿&#xff0c;我就是因为喜欢这样靠在床背上&#xff0c;长时间…

UVa 10603 Fill 倒水问题 单元最短路 Dijkstra

题目链接&#xff1a;Fill 题目描述&#xff1a; 给定容积为a,b,ca, b, ca,b,c的三个杯子&#xff0c;初始只有第三个杯子有ccc单位的水&#xff0c;每次可以将一个杯子的水倒入到另一个没有满的杯子中&#xff0c;倒水过程中除非出现一个杯子为空或出现一个杯子为满&#xff0…

《Keras深度学习:入门、实战与进阶》CIFAR-10图像识别

本文摘自《Keras深度学习&#xff1a;入门、实战与进阶》。 https://item.jd.com/10038325202263.html 这个数据集由Alex Krizhevsky、Vinod Nair和Geoffrey Hinton收集整理&#xff0c;共包含了60000张3232的彩色图像&#xff0c;50000张用于训练模型、10000张用于评估模型。…