一、环境准备
1 安装python
2 安装vscode
3 安装相关python库
pip install flask flask_cors openai4.在vscode里安装TONGYI Lingma(AI编程助手)
二、后端搭建
创建一个后端文件夹chatbot,再新建一个app.py的python文件
from flask import Flask, request, jsonify
from flask_cors import CORS
from openai import OpenAI
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
client = OpenAI()
app = Flask(__name__)
CORS(app, resources={r"/*":{"origins": "*"}}) # 这会为所有端点添加跨源头部分
@app.route('/ask', methods=['POST'])
def ask():
user_question = request.json['message']
answer = get_answer_from_model(user_question)
return jsonify({'answer': answer})
def get_answer_from_model(message):
response = client.completions.create(
model="gpt-3.5-turbo-instruct",
prompt=message,
max_tokens=512,
# stream=False
stream=True
)
print('response:',response)
# answer = response.choices[0].text.strip()
answer = ""
for chunk in response:
answer += chunk.choices[0].text
return answer
if __name__ == '__main__':
app.run(debug=True, port=5000)
三、前端搭建
1 创建前端文件夹chatbot-interface
2 创建三个前端的文件index.html styles.css srcript.js
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AI Chatbot</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="chat-container">
<div class="chat-header">
<h3>AI Chatbot</h3>
</div>
<div class="chat-box" id="chat-box">
<!-- 聊天消息将在这里显示 -->
</div>
<div class="chat-input">
<input type="text" id="user-input" placeholder="Type your message...">
<button id="send-button" onclick="sendMessage()">Send</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
styles.css
body, html {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
.chat-container {
max-width: 1080px;
margin: 30px auto;
border: 1px solid #ccc;
border-radius: 5px;
}
.chat-header {
background-color: #f4f4f4;
padding: 10px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.chat-box {
height: 720px;
overflow-y: scroll;
padding: 15px;
background-color: #fff;
}
.chat-input {
padding: 10px;
display: flex;
justify-content: space-between;
}
.chat-input input {
flex-grow: 1;
padding: 5px;
border: 1px solid #ccc;
border-radius: 5px;
}
.chat-input button {
padding: 5px 15px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
/* 简单的动画效果 */
.chat-box::-webkit-scrollbar {
width: 6px;
}
.chat-box::-webkit-scrollbar-thumb {
background-color: #ccc;
}
script.js
var inputBox = document.getElementById('user-input');
var sendButton = document.getElementById('send-button');
inputBox.addEventListener('keydown', function(event) {
if (event.keyCode === 13 || event.key === 'Enter') {
event.preventDefault();
sendMessage();
}
});
function sendMessage() {
//var userInput = document.getElementById('user-input').value;
var userInput = inputBox.value;
if (userInput.trim() === '') return;
// 将用户输入添加到聊天框
addToChatBox('baiyang', userInput);
// 清空输入框
document.getElementById('user-input').value = '';
// 假设这里发送请求到服务器,并获取AI的回复
fetch('http://127.0.0.1:5000/ask', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: userInput })
})
.then(response => {
if (!response.ok){
throw new Error('Network response was not ok');
}
return response.json()})
.then(data => {
// 将AI的回复添加到聊天框
if (data && data.answer){
console.log(data.answer);
addToChatBox("douwan", data.answer);
}
else{
console.error('Invalid response data:', data);
}
// addToChatBox('AI', data.reply);
})
.catch((error) => {
console.error('Error:', error);
});
}
function addToChatBox(sender, message) {
var chatBox = document.getElementById('chat-box');
var div = document.createElement('div');
div.innerHTML = `<strong>${sender}:</strong> ${message}`;
chatBox.appendChild(div);
chatBox.scrollTop = chatBox.scrollHeight; // 自动滚动到底部
}
四、效果展示
1 首先运行app.py文件,在vscode中运行,如
2 浏览器打开index文件,在输入框中输入相关文件,发送可返回信息。