0. 背景和环境介绍
服务器:阿里云轻量应用服务器(一年期)
系统:Ubuntu20.02
背景:某日,观旧有阿里云之机与界域之名,骤生一念:欲借以托置一网,仿某人工智慧之对话良制。私定志于后,以供北科之校园风云,望其效若问讯之台。欲望使然,费尽心机,终得此对话之机制。已试之,果然如意。遭逢之难,皆记于此,以资后日之修护。
1. 网站托管
1.1网页前端代码
html代码:
简单的对话框和发送按钮
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>北科万事通</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="chat-container">
<div class="chat-history" id="chatHistory"></div>
<div class="chat-input">
<textarea id="userInput" placeholder="Type your message..."></textarea>
<button id="sendButton">Send</button>
</div>
</div>
<script src="scripts.js"></script>
</body>
</html>"
js代码:
只负责向后端发送请求和向页面增加对话
fetch中的连接不能是localhost:8080 必须把域名写出来
document.getElementById("sendButton").addEventListener("click", function() {
const userInput = document.getElementById("userInput").value;
const chatHistory = document.getElementById("chatHistory").textContent; // 获取已有的聊天历史
// Send user input to the server
fetch("http://morphotherain.cn:8080/api/chat", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
message: userInput,
history: chatHistory
})
})
.then(response => response.json())
.then(data => {
console.log(JSON.stringify(data, null, 2));
const chatHistoryElem = document.getElementById("chatHistory");
// Display user message
chatHistoryElem.innerHTML += `<div>User: ${userInput}</div>`;
// Display ChatGPT's response
chatHistoryElem.innerHTML += `<div>ChatGPT: ${data.reply}</div>`;
// Clear the input
document.getElementById("userInput").value = '';
})
.catch(error => {
console.error("Error:", error);}
);
});
1.2网页后端代码
使用flask框架构建,将openai请求转发到代理服务器,并处理对话内容,进行脱敏和迭代处理等操作。
1.安装必要的库
pip install Flask
2.上线服务
转到项目目录并运行
python app.py
运行之后,它将监听localhost
的8080端口。当前端发送请求到/api/chat
时,服务器会响应该请求,并返回从代理服务器返回的请求。
3.使用flask的cors扩展解决跨域资源共享问题
当前端和后端分别运行在不同的域或端口时,可能会遇到CORS错误。这是一个安全特性,但有时它可能阻止前后端之间的通信。
解决方式:
安装Flask的CORS扩展
pip install Flask-CORS
并添加代码
from flask_cors import CORS
# ...
CORS(app)
4.设置端口
app.run(host='0.0.0.0', port=8080)
完整代码
from flask import Flask, request, jsonify, session
import openai
import requests
from flask_cors import CORS
# ...
app = Flask(__name__)
CORS(app)
OPENAI_API_URL = "https://91c5-240e-33d-8b72-ab00-f4f5-7eda-8735-9313.ngrok-free.app/openai-proxy"
HEADERS = {
"Authorization": "Bearer #OPENAIapi密钥#",
"Content-Type": "application/json",
}
@app.route('/api/chat', methods=['POST'])
def chat():
data = request.json
user_message = data.get("message")
conversation_history = data.get("history", "") # 获取之前的对话记录
full_prompt = conversation_history + "\n" + user_message + "\n"
try:
# 通过HTTP请求调用OpenAI API
response = requests.post(
OPENAI_API_URL,
headers=HEADERS,
json={
"model": "gpt-3.5-turbo",
"messages": [{"role": "system", "content": conversation_history},{"role": "user", "content": user_message}],
}
)
response_data = response.json()
with open("/var/www/html/server_log.txt", "a") as log_file:
log_file.write(str(response_data) + "\n")
chatgpt_reply = response_data['choices'][0]['message']['content'].strip()
with open("/var/www/html/server_log.txt", "a") as log_file:
log_file.write(str(response_data) + "\n")
# 更新对话记录
updated_history = full_prompt + "ChatGPT: " + chatgpt_reply + "\n"
except Exception as e:
with open("/var/www/html/server_log.txt", "a") as log_file:
log_file.write(type(e).__name__ + str(e) + "\n")
return jsonify({"reply": str(e), "history": conversation_history})
return jsonify({"reply": chatgpt_reply, "history": updated_history})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
2. 代理服务器
同样使用flask框架运行服务
将网站服务器的请求转发到openai
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
HEADERS = {
"Authorization": "Bearer OpenAI API密钥",
"Content-Type": "application/json",
}
@app.route('/openai-proxy', methods=['POST'])
def openai_proxy():
# 获取请求数据
data = request.json
# 将请求转发到OpenAI API
response = requests.post(
'https://api.openai.com/v1/chat/completions',
headers=HEADERS,
json=data
)
return jsonify(response.json())
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)