前提:你应该要有一个能正常使用chatGPT的openAI账号;即你已经成功注册了chatGPT,并能正常使用。
文章目录
代码框架代码详解环境搭建过程代码框架
下面是一个使用Flask Web框架创建调用ChatGPT API的网页的示例代码和工程结构:
project/├── app.py├── templates/│ └── index.html└── static/└── style.css
具体的工程,你可以选择自己创建,也可以直接下载我创建好的工程,链接如下:
/download/AnChenliang_1002/87999631
代码详解
app.py
是Flask应用的入口文件,负责处理请求和返回响应。它的代码如下:
from flask import Flask, render_template, requestimport openaiapp = Flask(__name__)# 设置ChatGPT API的密钥openai.api_key = 'YOUR_API_KEY'# 定义根路由的处理函数@app.route('/', methods=['GET', 'POST'])def index():if request.method == 'POST':# 获取用户输入的消息message = request.form['message']# 调用ChatGPT API进行对话response = pletion.create(engine='davinci',prompt=message,max_tokens=50,temperature=0.7,n=1,stop=None,temperature=0.7)# 获取ChatGPT的回复reply = response.choices[0].text.strip()# 渲染模板并返回响应return render_template('index.html', message=message, reply=reply)# GET请求时,渲染空白的模板return render_template('index.html')if __name__ == '__main__':app.run()
templates/index.html
是网页的HTML模板文件,负责展示用户输入和ChatGPT的回复。它的代码如下:
<!DOCTYPE html><html><head><title>ChatGPT Demo</title><link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}"></head><body><h1>ChatGPT Demo</h1><form method="POST"><label for="message">Your Message:</label><br><input type="text" id="message" name="message" required><br><input type="submit" value="Send"></form>{% if message %}<div class="message"><p class="user">You: {{ message }}</p><p class="reply">ChatGPT: {{ reply }}</p></div>{% endif %}</body></html>
static/style.css
是网页的样式表文件,负责设置网页的样式。你可以根据需要自定义样式。
当使用Flask Web创建网页时,可以将CSS样式文件放置在static
文件夹中。下面是一个示例的style.css
文件的代码:
/* 设置整个页面的背景颜色和字体样式 */body {background-color: #f2f2f2;font-family: Arial, sans-serif;}/* 设置页面标题的样式 */h1 {color: #333;text-align: center;margin-top: 50px;}/* 设置聊天对话框的样式 */.chat-container {width: 500px;margin: 50px auto;background-color: #fff;border: 1px solid #ccc;border-radius: 5px;padding: 20px;}/* 设置用户输入框的样式 */.user-input {width: 100%;padding: 10px;border: 1px solid #ccc;border-radius: 3px;margin-bottom: 10px;}/* 设置助手回复的样式 */.bot-reply {background-color: #f2f2f2;padding: 10px;border-radius: 3px;margin-bottom: 10px;}/* 设置发送按钮的样式 */.send-button {background-color: #4CAF50;color: white;padding: 10px 20px;border: none;border-radius: 3px;cursor: pointer;}/* 鼠标悬停在发送按钮上时的样式 */.send-button:hover {background-color: #45a049;}
将上述代码保存为style.css
文件,并将其放置在static
文件夹中。然后在HTML模板中引入该样式文件,即可使用这些样式来美化网页的外观。
环境搭建过程
要运行这个工程,你需要在Linux系统上搭建Python环境。以下是一些基本的步骤:
安装Python:在终端中运行以下命令安装Python 3:
sudo apt updatesudo apt install python3
安装pip:在终端中运行以下命令安装pip:
sudo apt install python3-pip
安装虚拟环境(可选):为了隔离项目的依赖,你可以创建一个虚拟环境。在终端中运行以下命令安装虚拟环境:
sudo apt install python3-venv
创建虚拟环境(可选):在终端中进入项目目录,运行以下命令创建虚拟环境:
python3 -m venv venv
激活虚拟环境(可选):在终端中运行以下命令激活虚拟环境:
source venv/bin/activate
安装依赖:在终端中运行以下命令安装项目所需的依赖:
pip install flask openai
运行应用:在终端中运行以下命令启动应用:
python app.py
现在,你可以在浏览器中访问http://localhost:5000
来使用这个网页应用了。记得将YOUR_API_KEY
替换为你的ChatGPT API的密钥。