运行中的网站例子:
用python flask 框架搭建的一个chatgpt服务例子:
from flask import Flask,request, abort
import os
import openai
from pygments import highlight
from pygments.lexers import guess_lexer
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from pygments.lexers import TextLexer
from pygments.lexers.html import HtmlLexer
from pygments.lexers.markup import XmlLexer
app = Flask(__name__)
@app.route('/chat', methods=['POST'])
def chat():
openai.api_key = "you api_key"
json_data = request.get_json()
conversation = [] # 创建空列表
conversation.append({"role": "system", "content": "You are a helpful assistant."})
questions = json_data['myArray'] #获取页面提交的问题,页面用js把对话中的问题组成json数组,python中以list获取
answers = json_data['assistant'] #组装gpt回复内容为list,也由js记录每次提交
temperatures = 0.7
if 'temperatures' in json_data:
if json_data['temperatures']=='适中':
temperatures = 0.7
if json_data['temperatures']=='更有创造力':
temperatures = 1.4
if json_data['temperatures']=='更精准':
temperatures = 0.2
tokens = 1000
if 'tokens' in json_data:
tokens = int(json_data['tokens'])
if tokens>4000:
tokens =4000
#会话深度控制为4次
if len(questions) > 4:
questions = questions[-4:]
answers = answers[-4:]
if len(questions):
# 遍历数组并添加到对话列表中
for i in range(len(questions)):
conversation.append({"role": "user", "content": questions[i]})
conversation.append({"role": "assistant", "content": answers[i]})
conversation.append({"role": "user", "content": json_data['text']})
else:
conversation.append({"role": "user", "content": json_data['text']})
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages = conversation,
temperature=temperatures,
max_tokens=tokens,
# frequency_penalty=0.5,
# presence_penalty=0.5,
# top_p=0.9
)
except Exception as e:
response = False
if 'a deactivated account' in str(e):
return {'error': '当前api key已经用完额度或者失效,可以通知管理员更新'}, 401
return {'error': '出错了稍后重试'}, 401
if response:
code = response['choices'][0]['message']['content']
assistant = code
# 对文本进行语法高亮处理
highlighted_code = ''
for line in code.split('\n'):
lexer = get_lexer_by_name('html', stripall=False)
highlighted_line = highlight(line, lexer, HtmlFormatter())
highlighted_code += highlighted_line
response['choices'][0]['text'] = highlighted_code
response['choices'][0]['assistant'] = assistant
return response
if __name__ == "__main__":
app.run(port=要使用的端口, host="服务器ip地址", debug=True)