用Python搭建一個ChatGPT聊天頁面
搭建一個基于Python的ChatGPT聊天頁面通常涉及以下幾個步驟:
- 創(chuàng)建Web應(yīng)用框架
- 創(chuàng)建HTML聊天界面
- 實現(xiàn)后端邏輯
- 完善前端JavaScript
創(chuàng)建Web應(yīng)用框架: 使用Python的Web開發(fā)框架,如Flask或Django,來構(gòu)建基礎(chǔ)的Web應(yīng)用程序。這里以Flask為例,首先安裝Flask:
pip install Flask
創(chuàng)建一個名為app.py的文件,初始化Flask應(yīng)用:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def chat_page():
return render_template('chat.html')
if __name__ == '__main__':
app.run(debug=True)
上述代碼定義了一個簡單的路由/,當(dāng)訪問根URL時,會渲染并返回chat.html模板。
創(chuàng)建HTML聊天界面: 在項目目錄下創(chuàng)建一個名為templates的文件夾(Flask默認(rèn)查找此路徑下的模板文件),并在其中創(chuàng)建chat.html文件,編寫HTML、CSS和JavaScript代碼,構(gòu)建聊天界面。以下是一個簡化的示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat with ChatGPT</title>
<style>
/* Add your CSS styles for the chat page here */
</style>
</head>
<body>
<div id="chat-container">
<!-- Render chat history here -->
</div>
<form id="message-form">
<input type="text" id="user-input" placeholder="Type your message...">
<button type="submit">Send</button>
</form>
<script>
// Add your JavaScript code for handling user input and sending requests to the server here
</script>
</body>
</html>
這里創(chuàng)建了聊天區(qū)域(#chat-container)和用戶輸入表單(#message-form)。你需要添加CSS樣式以美化界面,并編寫JavaScript代碼來處理用戶輸入、發(fā)送請求到服務(wù)器以及在頁面上動態(tài)顯示聊天記錄。
實現(xiàn)后端邏輯:修改app.py,添加一個新的路由,用于處理來自前端的聊天請求。在這個路由中,調(diào)用ChatGPT API獲取回復(fù),然后返回給前端。同時,確保已經(jīng)按照上一節(jié)的步驟設(shè)置了OpenAI API密鑰。
from flask import jsonify
import openai
openai.api_key = 'your-api-key-here'
@app.route('/chat', methods=['POST'])
def chat_with_chatgpt():
user_message = request.form.get('user_message')
prompt = f"User: {user_message}\nExpert: "
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an expert in early childhood education."},
{"role": "user", "content": prompt}
]
)
chatbot_reply = response['choices'][0]['message']['content']
return jsonify({'chatbot_reply': chatbot_reply})
這個路由接收POST請求,從請求數(shù)據(jù)中提取用戶輸入的消息,構(gòu)造ChatGPT的提示,并調(diào)用ChatGPT API獲取回復(fù)。最后,將ChatGPT的回復(fù)以JSON格式返回給前端。
完善前端JavaScript: 在chat.html中的
document.addEventListener('DOMContentLoaded', function () {
const messageForm = document.getElementById('message-form');
const userInput = document.getElementById('user-input');
const chatContainer = document.getElementById('chat-container');
messageForm.addEventListener('submit', async (event) => {
event.preventDefault();
const userMessage = userInput.value.trim();
if (userMessage) {
// Send AJAX POST request to /chat endpoint
const response = await fetch('/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `user_message=${encodeURIComponent(userMessage)}`
});
const data = await response.json();
const chatbotReply = data.chatbot_reply;
// Append user and chatbot messages to the chat container
chatContainer.innerHTML += `
User: ${userMessage}`;
chatContainer.innerHTML += `
ChatGPT: ${chatbotReply}`;
userInput.value = '';
chatContainer.scrollTop = chatContainer.scrollHeight;
}
});
});
這段代碼首先監(jiān)聽表單提交事件,阻止默認(rèn)提交行為。然后,提取用戶輸入,發(fā)送POST請求到/chat,接收并解析返回的JSON數(shù)據(jù),將用戶消息和ChatGPT回復(fù)添加到聊天記錄中,并滾動到聊天記錄底部。
完成以上步驟后,運行app.py啟動Web應(yīng)用。訪問http://localhost:5000/(默認(rèn)端口為5000),您應(yīng)該能看到一個與ChatGPT進(jìn)行交互的聊天頁面。用戶在頁面上輸入消息后,前端會發(fā)送請求到后端,后端調(diào)用ChatGPT API獲取回復(fù),并返回給前端,前端再將回復(fù)顯示在聊天界面上。
請注意,這只是一個基礎(chǔ)示例,實際應(yīng)用中可能需要考慮更多細(xì)節(jié),如錯誤處理、用戶體驗優(yōu)化、API調(diào)用頻率限制、安全性等。同時,確保遵循OpenAI的服務(wù)條款和使用指南。