创建一个支持多个AI模型的在线聊天网站可以分为几个主要步骤。以下是一个简要的框架,帮助你构建这个网站。你可以根据需求进行调整。
1. 网站基本结构
你需要前端(用户界面)和后端(AI模型处理)两部分,前端展示聊天界面,后端处理AI的请求。
前端(HTML, CSS, JavaScript)
- HTML: 用于构建网页结构。
- CSS: 用于网页样式。
- JavaScript: 用于处理与后端的交互。
<!DOCTYPE html>
<html lang="zh">
<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 id="chat-box" class="chat-box">
<!-- Chat history will appear here -->
</div>
<input id="user-input" type="text" placeholder="请输入消息" />
<button onclick="sendMessage()">发送</button>
</div>
<script src="scripts.js"></script>
</body>
</html>
CSS (styles.css):
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f4f4f4;
}
.chat-container {
width: 400px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
padding: 20px;
display: flex;
flex-direction: column;
gap: 10px;
}
.chat-box {
height: 300px;
overflow-y: scroll;
border: 1px solid #ccc;
padding: 10px;
border-radius: 4px;
background-color: #f9f9f9;
}
input {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
width: 100%;
}
button {
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
}
JavaScript (scripts.js):
function sendMessage() {
const userInput = document.getElementById("user-input").value;
if (userInput.trim() === "") return;
appendMessage("用户", userInput);
fetch("/chat", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ message: userInput })
})
.then(response => response.json())
.then(data => {
appendMessage("AI", data.reply);
});
document.getElementById("user-input").value = "";
}
function appendMessage(sender, message) {
const chatBox = document.getElementById("chat-box");
const messageDiv = document.createElement("div");
messageDiv.textContent = `${sender}: ${message}`;
chatBox.appendChild(messageDiv);
chatBox.scrollTop = chatBox.scrollHeight;
}
2. 后端(Python + Flask)
后端负责处理前端发来的聊天请求,并与不同的AI模型进行交互。这里我们以Flask为例,并接入一个简单的AI接口。
安装依赖:
pip install flask openai
Flask应用代码(app.py):
from flask import Flask, request, jsonify
import openai
app = Flask(__name__)
# 设置你的OpenAI API密钥
openai.api_key = 'your-openai-api-key'
@app.route('/')
def home():
return "聊天机器人服务正常运行"
@app.route('/chat', methods=['POST'])
def chat():
user_message = request.json.get('message')
if not user_message:
return jsonify({'error': 'No message provided'}), 400
# 接入不同的AI模型,你可以选择不同的API或者本地模型
response = get_ai_response(user_message)
return jsonify({'reply': response})
def get_ai_response(user_message):
# 调用OpenAI GPT模型,替换为其他模型时修改这里
try:
response = openai.Completion.create(
engine="text-davinci-003", # 选择你想要的模型
prompt=user_message,
max_tokens=150
)
return response.choices[0].text.strip()
except Exception as e:
return f"发生错误: {str(e)}"
if __name__ == '__main__':
app.run(debug=True)
3. 运行和测试
- 启动Flask服务器:
python app.py
- 打开浏览器访问
http://localhost:5000
,你应该能看到聊天界面。 - 在文本框中输入消息,点击“发送”,系统会将消息发送到后端,然后后端会返回AI模型的回复。
4. 接入更多AI模型
如果你希望接入多个AI模型,可以在后端逻辑中增加模型选择的功能。例如,你可以通过请求中的参数选择不同的AI模型,如model="openai"
或 model="other_model"
,然后根据选择的模型调用不同的API。
def get_ai_response(user_message, model="openai"):
if model == "openai":
return openai_response(user_message)
elif model == "other_model":
return other_model_response(user_message)
else:
return "不支持的模型"
def openai_response(user_message):
response = openai.Completion.create(
engine="text-davinci-003",
prompt=user_message,
max_tokens=150
)
return response.choices[0].text.strip()
你可以根据实际需求替换other_model_response
部分,接入其他模型的API或服务。
总结
这是一个简单的在线聊天网站示例,使用Flask作为后端,支持多个AI模型的接入。你可以根据需要修改模型接口,并通过前端和后端的交互实现聊天功能。
没有评论内容