大家好,我正在尝试使用一个 python 脚本来调用 openai api 来从 chatgpt 获取响应,因为目前 python 脚本可以工作并在终端中显示对话,但作业要求它显示在我的 html 网页上。有没有办法将python脚本的输出发送到html页面,同时将html页面的输入发送回python脚本,然后调用api?这就是我到目前为止所得到的。
Python
import openai
openai.api_key = "apikey"
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()
if __name__ == "__main__":
while True:
user_input = input("You: ")
if user_input.lower() in ["quit", "exit", "bye"]:
break
response = chat_with_gpt(user_input)
print("Chatbot: ", response)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text 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: #fff; /* Set the background color */
}
#chatbot-content {
text-align: center;
width: 300px;
}
#chat-area {
width: 100%;
height: 200px;
padding: 10px;
border: 1px solid #333;
background-color: #f0f0f0;
margin-bottom: 10px;
overflow-y: scroll;
}
#user-input {
width: 100%;
padding: 10px;
font-size: 16px;
margin-bottom: 10px;
}
#send-btn {
padding: 10px 20px;
background-color: #007bff; /* Bootstrap's Primary Color */
color: #fff;
text-decoration: none;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="chatbot-content">
<h1>Text Chatbot</h1>
<!-- Chat Area -->
<div id="chat-area"></div>
<!-- User Input -->
<input type="text" id="user-input" placeholder="Type your message here">
<!-- Send Button -->
<button id="send-btn">Send</button>
</div>
<script>
function displayMessage(message) {
// Get the chat area
const chatArea = document.getElementById("chat-area");
// Create a new message element
const messageElement = document.createElement("div");
messageElement.textContent = message;
// Append the message element to the chat area
chatArea.appendChild(messageElement);
// Scroll to the bottom of the chat area to show the latest message
chatArea.scrollTop = chatArea.scrollHeight;
}
function getBotReply(userInput) {
// Convert user input to lowercase for case-insensitive matching
const lowerCaseInput = userInput.toLowerCase();
// Define responses based on keywords
if (lowerCaseInput.includes("hi") || lowerCaseInput.includes("hello")) {
return "Hello!";
} else if (lowerCaseInput.includes("how are you")) {
return "I'm doing well, thank you!";
} else {
return "I'm here to chat! Ask me anything.";
}
}
document.getElementById("send-btn").addEventListener("click", function () {
// Get the user's input
const userInput = document.getElementById("user-input").value;
// Display the user's message in the chat area
displayMessage("You: " + userInput);
// Get the bot's reply based on user input
const botReply = getBotReply(userInput);
displayMessage("Bot: " + botReply);
// Clear the user input
document.getElementById("user-input").value = "";
});
</script>
</body>
</html>
我目前已经在 Google 云虚拟机上启动并运行了该网站,但在显示 html 代码之外,它似乎没有对 python 脚本执行任何操作。
要将 Python 脚本与 HTML 页面集成,您可以使用名为 Flask 的 Web 框架。 Flask 允许您用 Python 创建一个 Web 服务器,可以处理来自 HTML 页面的请求。
@app.route('/chat', methods=['POST'])
def chat():
user_input = request.json['message']
response = chat_with_gpt(user_input)
return jsonify({"reply": response})
在 HTML 文件的标签中进行这些更改:
异步函数 getBotReply(userInput) { const 响应 = 等待 fetch('/chat', { 方法:'POST', 标题:{ '内容类型':'应用程序/json' }, body: JSON.stringify({ 消息: userInput }) }); const data =等待response.json(); 返回数据.reply; } document.getElementById("send-btn").addEventListener("click", async function () { // 获取用户的输入 const userInput = document.getElementById("用户输入").value; // 在聊天区显示用户的消息 displayMessage("您:" + userInput); // 使用 Flask 服务器获取机器人的回复 const botReply = 等待 getBotReply(userInput); displayMessage("机器人:" + botReply); // 清空用户输入框 document.getElementById("用户输入").value = ""; }); 函数显示消息(消息){ // 现有的显示消息的函数 ... }
运行您的 Flask 应用程序:它将启动本地 Web 服务器。然后,您可以在浏览器中打开 HTML 文件,它应该能够与您的 Python 后端进行通信。