您的位置:首页 >用Python和OpenAI打造交互式HTML聊天机器人
发布于2025-10-27 阅读(0)
扫一扫,手机访问

在开发Web应用程序时,常常需要将强大的后端逻辑(例如与OpenAI API交互)与用户友好的前端界面(HTML、CSS、JavaScript)结合起来。直接将Python脚本的输出展示在HTML页面上,并从HTML页面获取输入并回传给Python脚本,这在技术上是不可行的。浏览器执行的是HTML、CSS和JavaScript,而Python脚本运行在服务器端。为了实现两者之间的通信,我们需要引入一个中间层:Web服务器和API。
本教程将指导您如何使用Python的Flask Web框架创建一个简单的API,该API将作为前端HTML页面与OpenAI API之间的桥梁,实现实时的聊天交互。
要连接Python后端和HTML前端,关键在于理解Web API(应用程序编程接口)和HTTP通信。
我们将使用Flask来创建一个轻量级的Web服务器,它将暴露一个API端点供前端调用。
如果您尚未安装Flask,请通过pip安装:
pip install Flask openai python-dotenv
python-dotenv用于安全地管理API密钥。
将您的OpenAI API调用逻辑封装在一个Flask路由中。为了安全起见,OpenAI API密钥应从环境变量中加载,而不是硬编码在代码中。
app.py
import os
from flask import Flask, request, jsonify
from flask_cors import CORS # 用于处理跨域请求
import openai
from dotenv import load_dotenv
# 加载环境变量
load_dotenv()
app = Flask(__name__)
CORS(app) # 允许所有来源的跨域请求,生产环境中应限制特定来源
# 从环境变量中获取API密钥
openai.api_key = os.getenv("OPENAI_API_KEY")
def chat_with_gpt(prompt):
"""
调用OpenAI API获取ChatGPT响应。
"""
try:
response = openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content.strip()
except Exception as e:
print(f"Error calling OpenAI API: {e}")
return "抱歉,AI服务暂时不可用。"
@app.route('/chat', methods=['POST'])
def chat_endpoint():
"""
API端点,接收前端的用户消息,调用ChatGPT,并返回AI响应。
"""
data = request.get_json()
user_message = data.get('message')
if not user_message:
return jsonify({"error": "No message provided"}), 400
bot_response = chat_with_gpt(user_message)
return jsonify({"response": bot_response})
if __name__ == '__main__':
# 在开发模式下运行Flask应用
# host='0.0.0.0' 允许从外部IP访问
# port=5000 是默认端口
app.run(debug=True, host='0.0.0.0', port=5000).env文件 (与app.py同目录)
OPENAI_API_KEY="YOUR_OPENAI_API_KEY"
请将YOUR_OPENAI_API_KEY替换为您的实际OpenAI API密钥。
在终端中,导航到app.py所在的目录,然后运行:
python app.py
您会看到Flask服务器启动,通常在http://0.0.0.0:5000上监听请求。
现在,我们需要修改HTML文件中的JavaScript代码,使其不再使用硬编码的本地回复逻辑,而是通过HTTP请求与我们刚刚创建的Flask API进行通信。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chatbot</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f4f7f6; /* Set the background color */
}
#chatbot-content {
text-align: center;
width: 400px;
background-color: #ffffff;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
}
h1 {
color: #333;
margin-bottom: 20px;
}
#chat-area {
width: 100%;
height: 300px;
padding: 10px;
border: 1px solid #e0e0e0;
background-color: #f9f9f9;
margin-bottom: 15px;
overflow-y: auto; /* Changed to auto for better UX */
text-align: left;
border-radius: 5px;
}
.message {
margin-bottom: 8px;
padding: 5px 10px;
border-radius: 5px;
max-width: 80%;
}
.user-message {
background-color: #dcf8c6;
margin-left: auto;
text-align: right;
}
.bot-message {
background-color: #e8e8e8;
margin-right: auto;
text-align: left;
}
#user-input {
width: calc(100% - 70px); /* Adjust width for button */
padding: 12px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 5px;
margin-right: 10px;
vertical-align: middle;
}
#send-btn {
padding: 12px 20px;
background-color: #007bff; /* Bootstrap's Primary Color */
color: #fff;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s ease;
vertical-align: middle;
}
#send-btn:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div id="chatbot-content">
<h1>AI Chatbot</h1>
<!-- Chat Area -->
<div id="chat-area"></div>
<!-- Input and Button Container -->
<div>
<input type="text" id="user-input" placeholder="输入你的消息...">
<button id="send-btn">发送</button>
</div>
</div>
<script>
// Flask后端API的URL
const API_URL = 'http://localhost:5000/chat'; // 如果部署在VM上,请替换为VM的IP或域名
function displayMessage(message, sender) {
const chatArea = document.getElementById("chat-area");
const messageElement = document.createElement("div");
messageElement.classList.add("message");
messageElement.classList.add(sender === "You" ? "user-message" : "bot-message");
messageElement.textContent = `${sender}: ${message}`;
chatArea.appendChild(messageElement);
chatArea.scrollTop = chatArea.scrollHeight; // 滚动到底部
}
async function sendUserMessage() {
const userInputField = document.getElementById("user-input");
const userInput = userInputField.value.trim();
if (userInput === "") {
return; // 不发送空消息
}
displayMessage(userInput, "You");
userInputField.value = ""; // 清空输入框
// 禁用输入和发送按钮,等待AI回复
userInputField.disabled = true;
document.getElementById("send-btn").disabled = true;
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: userInput })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
displayMessage(data.response, "Bot");
} catch (error) {
console.error('Error:', error);
displayMessage("抱歉,无法连接到AI服务或发生错误。", "Bot");
} finally {
// 重新启用输入和发送按钮
userInputField.disabled = false;
document.getElementById("send-btn").disabled = false;
userInputField.focus(); // 聚焦输入框
}
}
document.getElementById("send-btn").addEventListener("click", sendUserMessage);
document.getElementById("user-input").addEventListener("keypress", function(event) {
if (event.key === "Enter") {
sendUserMessage();
}
});
</script>
</body>
</html>本地测试:
VM部署:
通过本教程,您已经成功地将一个独立的Python ChatGPT脚本改造为一个功能完善的Web API,并将其与HTML前端页面连接起来,实现了实时的、双向的聊天交互。这种前后端分离的架构是现代Web开发中的标准实践,它使得后端逻辑和前端界面可以独立开发和部署,极大地提高了开发效率和应用的可扩展性。掌握这种集成方式,将为您构建更复杂的Web应用打下坚实的基础。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9