首先,你需要在你的电脑上创建一个新的文件夹,我们可以将其命名为 "flask_bot"。然后在该文件夹下创建一个 Python 脚本文件 "app.py",用于编写我们的 Flask 应用。Python脚本程序如下:
from flask import Flask, render_template, request
import openai
openai.api_key = "sk-xxxxxxx" # 你的 OpenAI API Key
class Chat:
def __init__(self, conversation_list=None):
if conversation_list is None:
self.conversation_list = [{'role': 'system', 'content': '你是一个非常友善的助手'}]
else:
self.conversation_list = conversation_list
def show_conversation(self, msg_list):
conversation = []
for msg in msg_list:
if msg['role'] == 'user':
conversation.append({'role': 'user', 'content': f"\U0001f47b: {msg['content']}\n"})
else:
conversation.append({'role': 'assistant', 'content': f"\U0001f47D: {msg['content']}\n"})
return conversation
def ask(self, prompt):
if prompt == '清空':
self.conversation_list = [{'role': 'system', 'content': '已清空对话历史记录'}]
return self.show_conversation(self.conversation_list)
self.conversation_list.append({"role": "user", "content": prompt})
response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=self.conversation_list)
answer = response.choices[0].message['content']
self.conversation_list.append({"role": "assistant", "content": answer})
return self.show_conversation(self.conversation_list)
app = Flask(__name__)
chatbot = Chat()
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
prompt = request.form['message']
conversation = chatbot.ask(prompt)
return render_template('index.html', conversation=conversation)
else:
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
python程序同文件夹下创建一个名为 "templates" 的新文件夹,并在其中创建一个名为 "index.html" 的新文件。将以下 HTML 代码添加到该文件中:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chatbot</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css">
</head>
<body>
<div class="container py-5">
<h1 class="mb-5">Chatbot</h1>
<form method="POST" action="/" class="mb-3">
<div class="mb-3">
<label for="message" class="form-label">Your message:</label>
<input type="text" class="form-control" id="message" name="message">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% if conversation %}
<div class="mb-3">
<h2>Response:</h2>
{% for message in conversation %}
<p>{{ message['content'] }}</p>
{% endfor %}
</div>
{% endif %}
</div>
</body>
</html>