话不多说,请先看效果:
演示地址:点击查看
需求分析:
后端部分需要使用Python框架处理HTTP请求和流式响应。Flask是一个轻量级的选择,适合快速搭建API。需要设置一个路由,比如'/stream_chat',接受POST请求,获取用户的问题和API密钥,然后调用DeepSeek的流式接口,并将每个块实时发送回前端。前端部分需要用jQuery监听输入事件,比如用户按下回车,然后通过AJAX发送请求到后端。由于是流式处理,可能需要使用EventSource或者fetch API来读取流式响应。不过,考虑到跨域问题,需要确保后端支持CORS,或者在Flask中设置CORS头。
前端界面需要显示对话历史,用户输入在下方,类似于聊天应用。CSS需要美化界面,设置滚动条,使消息自动滚动到底部。当接收到流式数据时,需要逐步更新最后一条消息的内容,而不是等待整个响应完成。
需要处理流式数据的接收,比如通过fetch API的response.body.getReader()来读取流,然后逐步解码和处理每个块。每个块可能是部分数据,需要拼接,直到遇到换行符或特定分隔符,然后解析JSON。但需要确认DeepSeek的流式响应格式,例如是否是每个块为一个完整的JSON对象,还是需要拼接多个块。
此外,错误处理也很重要。如果API调用失败,或者网络出现问题,前端需要显示错误信息。后端也需要捕获异常,并返回适当的HTTP状态码。
最后,需要编写完整的代码,包括前端的HTML、CSS、JavaScript,以及后端的Python代码。确保代码结构清晰,注释明确,用户能够直接运行,并替换API密钥进行测试。
可能遇到的问题:跨域请求,需要在Flask中配置CORS;流式数据的正确处理和解析;前端实时更新的实现;API密钥的安全处理等。需要逐一解决这些问题,并在代码中体现。
以下是一个完整的前后端分离实现方案,使用Python Flask作为后端,HTML+jQuery+CSS作为前端,支持DeepSeek的流式输出:
文件结构
chatbot/
├── backend/
│ ├── app.py
│ └── requirements.txt
└── frontend/
├── index.html
├── styles.css
└── script.js
后端实现(Python Flask)
文件:backend/app.py
from flask import Flask, request, Response, jsonify
from flask_cors import CORS
import requests
app = Flask(__name__)
CORS(app) # 允许跨域请求
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"
def generate_stream(prompt, api_key):
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
data = {
"model": "deepseek-r1",
"messages": [{"role": "user", "content": prompt}],
"stream": True # 启用流式输出
}
response = requests.post(
DEEPSEEK_API_URL,
headers=headers,
json=data,
stream=True
)
for chunk in response.iter_lines():
if chunk:
decoded_chunk = chunk.decode('utf-8')
if decoded_chunk.startswith("data: "):
yield decoded_chunk[6:] + "\n\n"
@app.route('/stream_chat', methods=['POST'])
def stream_chat():
try:
data = request.get_json()
api_key = data.get('api_key')
prompt = data.get('prompt')
return Response(
generate_stream(prompt, api_key),
mimetype='text/event-stream',
headers={'Cache-Control': 'no-cache'}
)
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(port=5000, debug=True)
文件:backend/requirements.txt
flask>=2.0.0
requests>=2.20.0
flask-cors>=3.0.0
前端实现
文件:frontend/index.html
<!DOCTYPE html>
<html>
<head>
<title>DeepSeek Chat</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>DeepSeek Chatbot</h1>
<div class="chat-box" id="chatBox"></div>
<div class="input-area">
<input type="text" id="apiKey" placeholder="输入API密钥">
<div class="message-input">
<input type="text" id="messageInput" placeholder="输入消息...">
<button onclick="sendMessage()">发送</button>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
文件:frontend/styles.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f0f2f5;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
border-radius: 10px;
padding: 20px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.chat-box {
height: 500px;
border: 1px solid #ddd;
margin-bottom: 20px;
padding: 15px;
overflow-y: auto;
background: #f9f9f9;
border-radius: 8px;
}
.message {
margin: 10px 0;
padding: 10px;
border-radius: 5px;
max-width: 70%;
}
.user-message {
background: #e3f2fd;
margin-left: auto;
}
.bot-message {
background: #fff;
border: 1px solid #ddd;
}
.input-area {
display: flex;
flex-direction: column;
gap: 10px;
}
.message-input {
display: flex;
gap: 10px;
}
input[type="text"] {
flex: 1;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
button {
padding: 10px 20px;
background: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background: #0056b3;
}
#apiKey {
width: 100%;
margin-bottom: 10px;
}
文件:frontend/script.js
let isStreaming = false;
function appendMessage(content, isUser = false) {
const chatBox = $('#chatBox');
const messageClass = isUser ? 'user-message' : 'bot-message';
if (!isUser) {
chatBox.append(`
<div class="message ${messageClass}">
<div class="message-content">${content}</div>
</div>
`);
} else {
chatBox.append(`
<div class="message ${messageClass}">
<div class="message-content">${content}</div>
</div>
`);
}
chatBox.scrollTop(chatBox.scrollHeight);
}
function handleStream(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
function read() {
reader.read().then(({ done, value }) => {
if (done) {
isStreaming = false;
return;
}
buffer += decoder.decode(value, { stream: true });
// 处理完整的事件
while (buffer.indexOf('\n\n') >= 0) {
const eventEnd = buffer.indexOf('\n\n');
const eventData = buffer.slice(0, eventEnd);
buffer = buffer.slice(eventEnd + 2);
try {
const jsonData = JSON.parse(eventData);
const content = jsonData.choices.delta.content || '';
const lastMessage = $('.bot-message').last();
if (lastMessage.length > 0) {
lastMessage.find('.message-content').append(content);
} else {
appendMessage(content);
}
} catch (e) {
console.error('解析错误:', e);
}
}
read();
});
}
read();
}
function sendMessage() {
if (isStreaming) return;
const apiKey = $('#apiKey').val();
const input = $('#messageInput');
const message = input.val().trim();
if (!apiKey || !message) return;
isStreaming = true;
input.val('');
appendMessage(message, true);
fetch('http://localhost:5000/stream_chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
api_key: apiKey,
prompt: message
})
})
.then(response => {
if (!response.ok) throw new Error('请求失败');
return response;
})
.then(handleStream)
.catch(error => {
console.error('错误:', error);
appendMessage(`错误: ${error.message}`);
isStreaming = false;
});
}
// 回车键发送
$('#messageInput').keypress(function(e) {
if (e.which === 13 && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
使用说明
安装依赖
cd backend pip install -r requirements.txt
启动后端
python app.py
打开前端
直接用浏览器打开
frontend/index.html
输入信息
在API Key输入框填入你的DeepSeek API密钥 在消息输入框输入问题后按回车或点击发送
功能特点
流式输出:实时显示生成过程中的文字
对话历史:保留完整的聊天记录
自动滚动:新消息自动滚动到可视区域
错误处理:网络错误和API异常均有提示
响应式布局:适配不同屏幕尺寸
注意事项
确保DeepSeek API支持流式输出(检查API文档)
部署生产环境时需要: 添加HTTPS支持
实现API密钥的安全存储 添加速率限制
如果遇到CORS问题,可以安装Chrome插件临时解决开发环境跨域问题
部分效果图:
移动端截图:
暗黑主题截图:
示例演示:
演示地址:点击查看
源码下载:
下载地址:点击下载
参考文献:
1、基于Uni-app前端框架的SUMER UI3.0组件库
2、uniapp精仿支付宝UI界面源码下载,基于SumerUI一款仿支付宝APP
3、uniapp精仿微信源码,基于SumerUI一款仿微信APP应用
SUMER UI
【用于开发APP
、小程序
、H5网站
、毕业设计
…】
评论