3小时开发chatgpt微信小程序
chatGPT是一款由OpenAI开发的聊天机器人模型,是一种高效语言模型,它能够模拟人类的语言行为,与用户进行自然的交互。它的名称来源于它所使用的技术——GPT-3架构,即生成式语言模型的第3代。
准备工作
去微信中搜索 "chatGPT"相关的小程序,看下还有哪些名字可以注册
选好名字,去申请微信小程序,记录准备logo,需要满足144px*144px
提交审核之后,就可以同时准备进行小程序开发
openai 账号申请
由于openai https://openai.com/ 不在中国区域开展业务,国内不能正常的体验到openai提供的服务;
我们可以通过曲线救国的方式来实现账号的申请和注册,具体教程可以自行搜索;
申请到账号之后,为了在代码中实现对openai 提供的 api
,我们还需要申请一个apiKey;这是通过代码访问chatGPT的关键所在。
账号申请成功后,访问 https://beta.openai.com/account/api-keys
页面生成apiKey,后面会用到;尤其注意保存好这个key,后面需要用到,且不能再次查看,如果丢失,只能重新生成。
开发环境
根据自己的实际情况,下载对应版本的微信开发者工具
https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html
新建小程序,导入小程序源码 https://github.com/smallnew666/ChatGPT-wxapp
服务器接口
编写服务器接口,推荐使用阿里云函数计算搭建flask,写入index.py文件
from flask import Flask,request
import requests
import json
import random
app = Flask(__name__)
@app.route('/')
def hello_world(): # put application's code here
return '在此输入apikey 样式:sk-s5S5BoV...'
@app.route('/message',methods = ['POST'])
def mess():
sk = request.json.get('openaikey')
msg = request.json.get('msg')
maxtoken = request.json.get('maxtoken')
print(sk,msg)
req = requests.post('https://api.openai.com/v1/completions',
json={"prompt": msg, "max_tokens": maxtoken, "model": "text-davinci-003","temperature": 0}, headers={
'content-type': 'application/json', 'Authorization': 'Bearer ' + sk})
print(req.status_code)
if req.status_code == 200:
reqdic = json.loads(req.text)
print(reqdic)
# aa = reqdic['choices'][0]['text']
res = {
"resmsg":reqdic,
"code":200
}
return res
else:
reqdic = json.loads(req.text)
err = reqdic['error']['message']
res = {
"resmsg":err,
"code":412
}
return res
if __name__ == '__main__':
app.run(threaded = False,processes=5)
在小程序的index.js文件中填入接口调用地址
至此,小程序搭建完成