最近ChatGPT很火,使用与InstructGPT相同的方法,使用来自人类反馈的强化学习 Reinforcement Learning from Human Feedback (RLHF) 来训练该模型,但数据收集设置略有不同。ChatGPT是在 GPT-3.5 系列中的一个模型进行微调的,该模型于 2022 年初完成训练。
现在因为官网 https://chat.openai.com/ 一直是满载状态,我决定使用GPT-3的公开API做一个基于python flask的网站。GPT-3的模型虽然比不上GPT-3.5的,但其功能仍然是十分强大。如果你有账号的话可以在https://platform.openai.com/playground运行GPT-3。
GPT-3 一共有4个模型,其中davinci是最有能力的模型,而ada是最快的模型。Davinci 最大请求量是4000个tokens,这其中包含了问题和回答。
这篇文章将教你如何把GPT-3的API用在自己的网站上,使用的是python flask框架。
第一步非常的复杂,需要先注册一个OpenAI的账号。这里不详细展开,可以tb或者查找其他教程(如sms虚拟电话)注册后获取API key,这里放一张图。
注意:添加一个key后需要在弹出的对话框内复制key的内容,关掉后将无法再查看,但是可以重新生成一个key。
其次,电脑要有python 3 的环境。这个也不展开。
最后需要确认用pip安装 openai 和 flask 两个库。
pip install openai
pip install flask
python 文件为 main.py。
在代码openai.api_key = 'your API'
的地方用自己的API key 进行替换。
from flask import Flask, request, render_template, redirect
import openaiopenai.api_key = 'your API' # 用自己的API key 进行替换server = Flask(__name__)def send_gpt(prompt,tem):try:response = openai.Completion.create(model='text-davinci-003',prompt=prompt,temperature=tem,max_tokens=3500, # prompt and answer together have 4096 tokenstop_p=1.0,frequency_penalty=0,presence_penalty=0)return response["choices"][0]["text"]except:mess = "Connection Error! Please try again."return mess@server.route('/', methods=['GET', 'POST'])
def get_request_json():if request.method == 'POST':if len(request.form['question']) < 1:return render_template('chat.html', question="NULL", res="Question can't be empty!")question = request.form['question']temperature = float(request.form['temperature'])print("======================================")print("Receive the question:", question)print("Receive the temperature:",temperature)res = send_gpt(question,temperature)print("Q:\n", question)print("A:\n", res)return render_template('chat.html', question=question, res=str(res), temperature=temperature)return render_template('chat.html', question=0)if __name__ == '__main__':server.run(debug=True, host='0.0.0.0', port=80)
html网页(chat.html)放在templates文件夹里,templates文件夹和python文件(main.py)放在同一目录下。
GPT 3
Davinci-003
Temperature Guide
Code Refactoring --- 0.2
Email Parser --- 0.3
Chat Bot --- 0.5
Summarise Text --- 0.5
Code Generation --- 0.8
Story Writing ---0.8
{% if message %} {{ message }} {% endif %}Waiting for the response...{% if question %}Legend:{{ question }}
Davinci-003-Tem{{ temperature }}:{{ res }}
{% endif %}
成功运行python代码将如下图显示,打开浏览器输入 127.0.0.1:80 或者 localhost 进行访问。
这个Flask网站可以自定义 Temperature 即GPT-3的回答随机度。网站上也给出了温度设置的建议,下面为效果图。
网站效果一般,主要是实现功能。如果还想加除Temperature之外的变量,可以照葫芦画瓢。
Github 链接:https://github.com/redemptionwxy/GPT3-API-Flask-Python_Chat_Website
上一篇:3.2 埃尔米特转置