下面是一个简单的示例,展示如何使用 Python Flask 框架创建一个调用 ChatGPT AI 的网站。

from flask import Flask, render_template, request
import openai

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

app = Flask(__name__)

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

@app.route('/chat', methods=['POST'])
def chat():
    # 获取用户输入的消息
    message = request.form['message']

    # 调用 ChatGPT AI 进行对话
    response = openai.Completion.create(
        engine='text-davinci-003',
        prompt=message,
        max_tokens=50,
        temperature=0.7,
        n=1,
        stop=None,
        timeout=10
    )

    # 获取 AI 的回复
    reply = response.choices[0].text.strip()

    # 渲染回复到网页
    return render_template('index.html', reply=reply)

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

上述代码假设你已经安装了 Flask 和 OpenAI Python 库,并且已经获取了自己的 OpenAI API 密钥。你需要在代码中将 YOUR_API_KEY 替换为你的实际 API 密钥。

接下来,你需要在项目文件夹中创建一个名为 templates 的文件夹,并在其中创建一个名为 index.html 的 HTML 模板文件。这个文件将用于渲染网页内容。

index.html 模板文件的示例内容如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>ChatGPT AI</title>
</head>
<body>
    <h1>ChatGPT AI</h1>

    <form action='/chat' method='POST'>
        <input type='text' name='message' placeholder='输入你的消息' required>
        <input type='submit' value='发送'>
    </form>

    {% if reply %}
        <h3>AI 回复:</h3>
        <p>{{ reply }}</p>
    {% endif %}
</body>
</html>

这个模板文件包括一个表单,用户可以在其中输入消息,并将其提交给服务器进行处理。如果在服务器端生成了 AI 的回复,它将会显示在页面上。

将这两个文件保存在同一个文件夹中,并运行 Python 脚本。然后,访问 http://localhost:5000 即可在浏览器中打开网站。你可以在输入框中输入消息,并点击发送按钮与 ChatGPT AI 进行对话。

用 Python Flask 构建 ChatGPT AI 网站源码

原文地址: https://www.cveoy.top/t/topic/qqAv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录