使用Python Flask搭建Chat-GPT

在本文中,我们将介绍如何使用Python Flask框架搭建一个简单的Chat-GPT应用。Chat-GPT是由OpenAI开发的自然语言处理模型,能够进行对话和回答问题。

准备工作

首先,确保你已经安装了Python和Flask。如果没有安装,你可以通过以下命令安装:

pip install flask

接下来,你需要注册并获取OpenAI的API密钥。你可以在OpenAI的官方网站上申请访问API。

**

创建Flask应用

**
创建一个新的文件,比如app.py,然后输入以下代码:

from flask import Flask, render_template, request
import openai

app = Flask(__name__)

# 设置你的OpenAI API密钥
openai.api_key = 'YOUR_OPENAI_API_KEY'

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/ask', methods=['POST'])
def ask():
    user_input = request.form['user_input']

    # 调用Chat-GPT进行对话
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=user_input,
        max_tokens=150
    )

    answer = response['choices'][0]['text'].strip()
    return render_template('index.html', user_input=user_input, answer=answer)

if __name__ == '__main__':
    app.run(debug=True)

在上面的代码中,我们使用了Flask来创建一个简单的Web应用。用户可以在浏览器中输入问题,然后应用将该问题传递给Chat-GPT,并将响应显示在页面上。

**

创建HTML模板

**
在项目目录中创建一个templates文件夹,并在其中创建一个名为index.html的文件,用于显示用户界面。输入以下代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat-GPT Demo</title>
</head>
<body>
    <h1>Chat-GPT Demo</h1>
    <form action="/ask" method="post">
        <label for="user_input">Ask a question:</label>
        <input type="text" id="user_input" name="user_input" required>
        <button type="submit">Submit</button>
    </form>

    {% if user_input %}
        <p><strong>You:</strong> {
   
   { user_input }}</p>
        <p><strong>Chat-GPT:</strong> {
   
   { answer }}</p>
    {% endif %}
</body>
</html>

这个HTML模板包含一个表单,用户可以在其中输入问题。一旦用户提交问题,应用将向Chat-GPT发送请求,并显示用户输入和Chat-GPT的回答。

运行应用

在命令行中运行以下命令启动应用:

python app.py

访问http://localhost:5000,你将看到Chat-GPT的简单界面。输入问题,点击提交,即可看到Chat-GPT的回答。

猜你喜欢

转载自blog.csdn.net/we2006mo/article/details/134436261