依赖于flask+openai 0.27.0模块
项目完整源码包含一个简单的前端页面:chatgpt-web-master.zip
如何使用参照源码和readme文件
主程序:
import os
import openai
from flask import Flask, request, render_template, redirect
server = Flask(__name__)
openai.api_key = os.environ.get('API_KEY')
model_engine = "gpt-3.5-turbo"
def get_completion(question):
try:
response = openai.ChatCompletion.create(
model=model_engine,
messages=[
{"role": "system", "content": "你是一个很有用的助手。"},
{"role": "user", "content": f"{question}\n"},
],
temperature=0.9,
max_tokens=2048,
top_p=1,
frequency_penalty=0,
presence_penalty=0.6,
stop=None
)
except Exception as error:
print(error)
return error
# 返回api传过来的文本
return response['choices'][0]['message']['content']
@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 = request.form['question']
# print("--------------------------")
# print("接到请求:", question)
res = get_completion(question)
# print("问题:\n", question)
# print("答案:\n", res)
return render_template('chat.html', question=question, res=str(res))
return render_template('chat.html', question=0)
if __name__ == '__main__':
server.run(debug=True, host='0.0.0.0', port=996)