2026/4/18 12:18:20
网站建设
项目流程
如何查看网站空间大小,项目建设管理 公司 网站,网站开发工具安卓版,如何创建二级域名Day 93#xff1a;【99天精通Python】终极项目 - AI 聊天机器人 (下) - 前端界面与部署
前言
欢迎来到第93天#xff01;
在过去的两个章节中#xff0c;我们已经搭建了一个功能强大的后端#xff1a;
支持流式对话和多轮记忆。支持上传 PDF 作为知识库进行 RAG 问答。…Day 93【99天精通Python】终极项目 - AI 聊天机器人 (下) - 前端界面与部署前言欢迎来到第93天在过去的两个章节中我们已经搭建了一个功能强大的后端支持流式对话和多轮记忆。支持上传 PDF 作为知识库进行 RAG 问答。今天我们要为这个强大的大脑配上一副漂亮的面孔。我们将使用原生HTML, CSS, JavaScript编写一个聊天界面并学习如何将整个项目部署上线。本节内容聊天界面 HTML 结构CSS 美化JavaScript 核心逻辑 (EventSource)文件上传交互项目最终部署一、HTML 骨架 (templates/chat.html)我们需要一个聊天记录框、一个输入框、一个发送按钮和一个文件上传按钮。!DOCTYPEhtmlhtmllangzh-CNheadmetacharsetUTF-8titleAI 聊天机器人/titlelinkrelstylesheethref{{ url_for(static, filenamestyle.css) }}/headbodydivclasschat-containerdivclasschat-headerh2Python AI Bot/h2/divdivclasschat-messagesidchat-messages!-- 聊天记录放这里 --/divdivclasschat-input-forminputtypefileidfile-inputstyledisplay:none;buttonidupload-btn/buttoninputtypetextiduser-inputplaceholder输入消息...buttonidsend-btn发送/button/div/divscriptsrc{{ url_for(static, filenameapp.js) }}/script/body/html二、CSS 美化 (static/style.css)让界面看起来像一个真正的聊天软件。/* 省略基础样式 */.chat-container{display:flex;flex-direction:column;height:90vh;max-width:800px;...}.chat-messages{flex-grow:1;overflow-y:auto;padding:20px;border-bottom:1px solid #ddd;}.message{margin-bottom:15px;display:flex;flex-direction:column;}.message.user{align-items:flex-end;}.message.bot{align-items:flex-start;}.message .bubble{max-width:70%;padding:10px 15px;border-radius:18px;}.message.user .bubble{background-color:#007bff;color:white;}.message.bot .bubble{background-color:#f1f0f0;}/* ... 更多样式 */三、JS 核心逻辑 (static/app.js)这是前端的灵魂负责与后端 API 交互。3.1 监听事件constchatMessagesdocument.getElementById(chat-messages);constuserInputdocument.getElementById(user-input);constsendBtndocument.getElementById(send-btn);constuploadBtndocument.getElementById(upload-btn);constfileInputdocument.getElementById(file-input);// 随机生成一个 Session ID或者从 localStorage 读取letsessionIdlocalStorage.getItem(sessionId)||session_Date.now();localStorage.setItem(sessionId,sessionId);sendBtn.addEventListener(click,sendMessage);userInput.addEventListener(keydown,(e){if(e.keyEnter)sendMessage();});uploadBtn.addEventListener(click,()fileInput.click());fileInput.addEventListener(change,uploadFile);3.2 发送消息与接收流式响应 (SSE)我们使用EventSource来接收后端的流式数据。functionsendMessage(){constmessageuserInput.value.trim();if(!message)return;appendMessage(user,message);userInput.value;// 创建 AI 的消息容器准备接收流式数据constbotMessageContainerappendMessage(bot,);constbubblebotMessageContainer.querySelector(.bubble);// 使用 EventSource 连接流式 APIconsteventSourcenewEventSource(/api/chat?session_id${sessionId}input${encodeURIComponent(message)});// 注意GET 请求示例POST 更佳eventSource.onmessagefunction(event){constdataJSON.parse(event.data);// 逐字追加到 bubble 中bubble.textContentdata.token;chatMessages.scrollTopchatMessages.scrollHeight;// 自动滚动};eventSource.onerrorfunction(){eventSource.close();};}(注为简化演示这里将 POST 改为 GET 传参生产环境中应保持 POST)3.3 文件上传functionuploadFile(){constfilefileInput.files[0];if(!file)return;constformDatanewFormData();formData.append(file,file);formData.append(session_id,sessionId);appendMessage(system,正在上传并学习文件:${file.name}...);fetch(/api/upload,{method:POST,body:formData}).then(responseresponse.json()).then(data{appendMessage(system,data.message||处理完成);}).catch(error{appendMessage(system,上传失败: error);});}四、部署到生产环境我们使用Gunicorn Nginx的经典组合。4.1 Gunicorn 启动gunicorn -w4-k gevent -b127.0.0.1:5001app:app-k gevent: 使用gevent作为 worker 类型非常适合流式 IO 场景。(需pip install gevent)4.2 Nginx 配置流式响应对 Nginx 配置有特殊要求需要禁用代理缓冲。server { # ... location /api/chat { proxy_pass http://127.0.0.1:5001; proxy_buffering off; # 关闭缓冲 proxy_cache off; proxy_set_header Connection ; proxy_http_version 1.1; chunked_transfer_encoding off; } location / { proxy_pass http://127.0.0.1:5001; # ... } }五、项目总结与展望至此我们的全栈 AI 聊天机器人就完成了我们实现了一个能理解上下文的 AI 大脑 (LangChain Memory)。一个能读取外部知识的 RAG 系统 (VectorDB)。一个支持流式打字效果的 Web 界面 (Flask SSE JS EventSource)。一套可部署到生产环境的架构。未来可扩展的方向用户系统集成 Day 61 的用户认证实现多用户隔离。工具调用 (Agent)让 AI 能调用外部 API如查询天气、计算器。模型切换增加一个下拉框允许用户在 GPT-4, 文心一言, 通义千问之间切换。六、小结这个项目是对我们过去 92 天学习成果的一次大阅兵。它不仅是一个酷炫的玩具更是一个可以不断迭代、具备商业潜力的产品原型。希望通过这个项目你不仅学会了如何用 Python更学会了如何组合运用各种技术去创造一个完整的产品。下节预告Day 94Python 开发最佳实践- 项目做完了但代码写得好不好是另一回事。明天我们总结一些 Python 开发中的最佳实践如代码风格 (PEP8)、文档编写、版本控制 (Git) 等。系列导航上一篇Day 92 - AI聊天机器人(中)下一篇Day 94 - Python开发最佳实践待更新