You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将调用OpenAI API的Python脚本与HTML网页对接实现ChatGPT交互

实现静态HTML与GPT-3.5 Python脚本的交互

问题背景

现有一个可在终端运行的Python脚本,调用OpenAI的gpt-3.5-turbo模型获取响应;同时有一个部署在Google Cloud VM上的静态HTML聊天页面,当前仅能展示静态内容,无法与Python脚本交互。需要实现:HTML页面的用户输入传递给Python脚本,脚本调用API后将GPT响应返回至HTML页面展示。

解决方案步骤

1. 将Python脚本改造为Web API服务

使用Flask框架将原有的GPT调用逻辑封装成HTTP接口,支持接收前端的POST请求并返回响应。

步骤1.1 安装依赖

在VM终端执行以下命令安装所需库:

pip install flask flask-cors openai

步骤1.2 修改Python代码

替换原Python脚本为以下内容:

from flask import Flask, request, jsonify
from flask_cors import CORS
import openai

app = Flask(__name__)
CORS(app)  # 允许跨域请求,解决前端与后端不同源的问题

openai.api_key = "你的OpenAI API密钥"  # 替换为你的实际API密钥

def chat_with_gpt(prompt):
    response = openai.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message.content.strip()

@app.route('/api/chat', methods=['POST'])
def chat_api():
    data = request.get_json()
    user_input = data.get('prompt')
    if not user_input:
        return jsonify({'error': '缺少用户输入'}), 400
    
    try:
        reply = chat_with_gpt(user_input)
        return jsonify({'reply': reply})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)  # 绑定VM的所有IP地址,监听5000端口

2. 修改HTML页面的JavaScript逻辑

替换原HTML中的<script>部分,实现通过fetch调用后端API:

<script>
    function displayMessage(message) {
        // 获取聊天区域元素
        const chatArea = document.getElementById("chat-area");
        // 创建新的消息元素
        const messageElement = document.createElement("div");
        messageElement.textContent = message;
        // 将消息添加到聊天区域
        chatArea.appendChild(messageElement);
        // 滚动到聊天区域底部,显示最新消息
        chatArea.scrollTop = chatArea.scrollHeight;
    }

    async function getBotReply(userInput) {
        try {
            // 调用后端API,替换为你的VM公网IP
            const response = await fetch('http://你的VM公网IP:5000/api/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({prompt: userInput})
            });

            if (!response.ok) {
                throw new Error('请求失败,请检查后端服务是否正常');
            }

            const data = await response.json();
            return data.reply;
        } catch (error) {
            return `错误:${error.message}`;
        }
    }

    document.getElementById("send-btn").addEventListener("click", async function () {
        const userInput = document.getElementById("user-input").value.trim();
        if (!userInput) return; // 空输入不处理

        // 显示用户消息
        displayMessage("你: " + userInput);
        // 清空输入框
        document.getElementById("user-input").value = "";

        // 显示加载状态
        displayMessage("Bot: 正在思考...");
        // 获取AI回复
        const botReply = await getBotReply(userInput);
        
        // 移除加载状态消息,替换为实际回复
        const chatArea = document.getElementById("chat-area");
        chatArea.removeChild(chatArea.lastChild);
        displayMessage("Bot: " + botReply);
    });

    // 添加回车键发送功能
    document.getElementById("user-input").addEventListener("keypress", function(e) {
        if (e.key === 'Enter') {
            document.getElementById("send-btn").click();
        }
    });
</script>

3. 在Google Cloud VM上部署配置

  • 开放端口:在GCP控制台的VM实例防火墙规则中,添加允许外部访问5000端口的规则(协议TCP)。
  • 启动后端服务:在VM终端执行命令启动服务,使用nohup让服务在后台运行:
    nohup python3 your_script_name.py &
    
    或使用更稳定的gunicorn部署:
    pip install gunicorn
    nohup gunicorn -w 4 -b 0.0.0.0:5000 your_script_name:app &
    
  • 验证服务:用POST工具(如curl)访问http://你的VM公网IP:5000/api/chat,确认服务正常响应。

内容的提问来源于stack exchange,提问作者Mike4082

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:34:56