国内十大网站建设品牌网站建设制作首页流程
国内十大网站建设品牌,网站建设制作首页流程,桂林两江四湖景区导游词,室内设计软件下载为InternLM2-Chat-1.8B制作前端界面#xff1a;简单聊天机器人Demo
你是不是已经成功部署了InternLM2-Chat-1.8B模型#xff0c;看着命令行里一行行的日志#xff0c;却不知道怎么把它变成一个普通人也能用的聊天工具#xff1f;或者#xff0c;你是个前端开发者#xf…为InternLM2-Chat-1.8B制作前端界面简单聊天机器人Demo你是不是已经成功部署了InternLM2-Chat-1.8B模型看着命令行里一行行的日志却不知道怎么把它变成一个普通人也能用的聊天工具或者你是个前端开发者想找个有趣的项目练手把AI能力包装成一个看得见、摸得着的应用今天我们就来解决这个问题。我将带你一步步用最基础的HTML、CSS和JavaScript为你的大模型服务搭建一个简洁、美观的Web聊天界面。这个界面不仅能发送消息、接收回复还能实现流式显示效果让对话体验更流畅自然。整个过程不需要复杂的框架如果你会写一点前端代码跟着做就能完成。1. 项目目标与准备工作在开始写代码之前我们先明确一下我们要做一个什么样的东西以及需要准备些什么。1.1 我们要实现什么想象一下一个最简单的聊天窗口就像你手机上的短信应用。我们的目标就是做出这样一个界面但它连接的不是你的朋友而是你部署好的InternLM2-Chat-1.8B模型。具体来说这个Demo需要实现几个核心功能消息发送在输入框里打字点击按钮或按回车把问题发给后端的模型。消息接收与显示把模型“思考”后生成的回答显示在聊天窗口里。流式响应这是提升体验的关键。我们不希望等模型全部生成完再一次性显示大段文字而希望像真人打字一样一个字一个字地“流”出来。对话历史能清晰地看到你和模型一来一回的对话记录用户消息和AI回复用不同的样式区分开。基本交互比如清空对话、在模型“思考”时显示加载状态防止用户重复发送。1.2 你需要准备什么一个正在运行的InternLM2模型服务这是前提。你的模型服务应该已经通过类似OpenAI格式的API例如使用openai库或vLLM等工具部署在某个端口比如8000上跑起来了并且有一个可用的/v1/chat/completions这样的聊天接口。我们前端的工作就是去调用这个接口。基础的Web开发知识了解HTML结构、CSS样式和JavaScript特别是fetchAPI的基本用法就足够了。一个代码编辑器比如VSCode、Sublime Text甚至记事本都可以。一个现代浏览器Chrome、Edge或Firefox用于测试。好了概念清楚了工具也齐了我们这就开始动手。2. 搭建聊天界面的骨架HTML CSS我们先从静态页面开始把聊天窗口的样子画出来。创建一个名为index.html的文件然后把下面的代码放进去。代码里我写了详细的注释帮你理解每一部分是干什么的。!DOCTYPE html html langzh-CN head meta charsetUTF-8 meta nameviewport contentwidthdevice-width, initial-scale1.0 titleInternLM2 聊天机器人 Demo/title link relstylesheet hrefstyle.css link relstylesheet hrefhttps://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css /head body div classchat-container !-- 聊天区域头部 -- header classchat-header h1i classfas fa-robot/i InternLM2-Chat-1.8B 助手/h1 p classsubtitle一个轻量级大语言模型对话演示/p button idclearBtn classbtn-clear title清空对话历史 i classfas fa-trash-alt/i 清空对话 /button /header !-- 核心消息显示区域 -- main classchat-messages idmessageContainer !-- 初始欢迎消息 -- div classmessage ai-message div classavatari classfas fa-robot/i/div div classbubble div classsenderAI助手/div div classtext你好我是基于InternLM2-Chat-1.8B模型的AI助手。有什么可以帮你的吗/div /div /div !-- 新的消息会通过JavaScript动态添加到这里 -- /main !-- 底部输入区域和状态栏 -- footer classchat-footer !-- 状态提示 -- div classstatus-bar idstatusBar span idstatusText准备就绪/span div classtyping-indicator idtypingIndicator styledisplay: none; span/spanspan/spanspan/span AI正在思考... /div /div !-- 输入框和发送按钮 -- div classinput-area textarea iduserInput placeholder输入你的问题按Enter发送ShiftEnter换行... rows2 /textarea button idsendBtn classbtn-send title发送消息 i classfas fa-paper-plane/i 发送 /button /div div classhint smalli classfas fa-info-circle/i 提示模型为1.8B参数版本适合处理一般性问答和对话。/small /div /footer /div script srcscript.js/script /body /html现在页面只有结构还很丑。我们来加点样式让它变得好看点。创建一个style.css文件。/* 基础重置和全局样式 */ * { margin: 0; padding: 0; box-sizing: border-box; font-family: Segoe UI, Microsoft YaHei, sans-serif; } body { background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); min-height: 100vh; display: flex; justify-content: center; align-items: center; padding: 20px; } /* 主聊天容器 */ .chat-container { width: 100%; max-width: 800px; height: 85vh; background-color: white; border-radius: 20px; box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1); display: flex; flex-direction: column; overflow: hidden; } /* 头部样式 */ .chat-header { background: linear-gradient(to right, #4a6fa5, #6d9dc5); color: white; padding: 20px 25px; text-align: center; position: relative; } .chat-header h1 { font-size: 1.8rem; margin-bottom: 5px; } .chat-header .subtitle { font-size: 0.9rem; opacity: 0.9; } .btn-clear { position: absolute; right: 20px; top: 50%; transform: translateY(-50%); background: rgba(255, 255, 255, 0.2); border: none; color: white; padding: 8px 15px; border-radius: 50px; cursor: pointer; font-size: 0.85rem; transition: background 0.3s; } .btn-clear:hover { background: rgba(255, 255, 255, 0.3); } /* 消息显示区域 */ .chat-messages { flex: 1; padding: 25px; overflow-y: auto; display: flex; flex-direction: column; gap: 20px; background-color: #f8f9fa; } /* 单条消息通用样式 */ .message { display: flex; max-width: 85%; animation: fadeIn 0.3s ease-out; } keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } /* 用户消息靠右 */ .user-message { align-self: flex-end; flex-direction: row-reverse; } .user-message .avatar { background-color: #6d9dc5; } .user-message .bubble { background-color: #e3f2fd; border-top-right-radius: 5px; } .user-message .sender { text-align: right; color: #4a6fa5; } /* AI消息靠左 */ .ai-message { align-self: flex-start; } .ai-message .avatar { background-color: #ff7e5f; } .ai-message .bubble { background-color: #fff; border: 1px solid #eee; border-top-left-radius: 5px; } .ai-message .sender { color: #ff7e5f; } /* 消息内部组件 */ .avatar { width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-size: 1.2rem; flex-shrink: 0; margin: 0 12px; } .bubble { padding: 15px; border-radius: 18px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); line-height: 1.5; } .sender { font-weight: bold; font-size: 0.85rem; margin-bottom: 5px; } .text { word-wrap: break-word; white-space: pre-wrap; /* 保留空格和换行 */ } /* 底部区域 */ .chat-footer { border-top: 1px solid #eee; padding: 20px 25px; background-color: white; } /* 状态栏 */ .status-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; font-size: 0.9rem; color: #666; min-height: 24px; } .typing-indicator { display: flex; align-items: center; color: #ff7e5f; font-weight: 500; } .typing-indicator span { height: 8px; width: 8px; background-color: #ff7e5f; border-radius: 50%; display: inline-block; margin-right: 4px; animation: bounce 1.4s infinite ease-in-out both; } .typing-indicator span:nth-child(1) { animation-delay: -0.32s; } .typing-indicator span:nth-child(2) { animation-delay: -0.16s; } keyframes bounce { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1.0); } } /* 输入区域 */ .input-area { display: flex; gap: 15px; align-items: flex-end; } textarea#userInput { flex: 1; border: 2px solid #e1e5eb; border-radius: 12px; padding: 15px; font-size: 1rem; resize: none; outline: none; transition: border 0.3s; min-height: 60px; max-height: 150px; } textarea#userInput:focus { border-color: #6d9dc5; } .btn-send { background: linear-gradient(to right, #4a6fa5, #6d9dc5); color: white; border: none; border-radius: 12px; padding: 0 30px; height: 60px; font-size: 1rem; font-weight: bold; cursor: pointer; transition: all 0.3s; display: flex; align-items: center; justify-content: center; gap: 8px; } .btn-send:hover:not(:disabled) { background: linear-gradient(to right, #3a5f95, #5d8db5); transform: translateY(-2px); box-shadow: 0 5px 15px rgba(109, 157, 197, 0.4); } .btn-send:disabled { background: #cccccc; cursor: not-allowed; transform: none; box-shadow: none; } .hint { margin-top: 12px; color: #888; font-size: 0.85rem; text-align: center; }现在用浏览器打开index.html你应该能看到一个像模像样的聊天窗口了有欢迎语有输入框还有清空按钮。不过它还不会动。接下来我们就要用JavaScript给它注入灵魂。3. 让聊天机器人动起来JavaScript这是最核心的部分。我们将创建script.js文件实现与后端模型API的通信和所有交互逻辑。3.1 连接后端与发送消息首先我们需要知道你的模型服务地址。假设你的服务跑在http://localhost:8000并且提供了兼容OpenAI的聊天接口。// script.js // 配置你的模型服务地址 const API_BASE_URL http://localhost:8000; // 请根据你的实际服务地址修改 const API_CHAT_ENDPOINT ${API_BASE_URL}/v1/chat/completions; // 获取DOM元素 const messageContainer document.getElementById(messageContainer); const userInput document.getElementById(userInput); const sendBtn document.getElementById(sendBtn); const clearBtn document.getElementById(clearBtn); const statusText document.getElementById(statusText); const typingIndicator document.getElementById(typingIndicator); // 存储对话历史用于上下文这里先简单存储 let conversationHistory [ { role: system, content: 你是一个乐于助人的AI助手。 } ]; // 添加一条消息到聊天窗口 function appendMessage(sender, text, isAI false) { const messageDiv document.createElement(div); messageDiv.className message ${isAI ? ai-message : user-message}; const avatarIcon isAI ? fa-robot : fa-user; const senderName isAI ? AI助手 : 你; messageDiv.innerHTML div classavatari classfas ${avatarIcon}/i/div div classbubble div classsender${senderName}/div div classtext${text}/div /div ; messageContainer.appendChild(messageDiv); // 滚动到底部确保看到最新消息 messageContainer.scrollTop messageContainer.scrollHeight; } // 更新状态栏 function updateStatus(message, isThinking false) { statusText.textContent message; typingIndicator.style.display isThinking ? flex : none; } // 发送消息到AI模型 async function sendMessageToAI(userMessage) { // 1. 将用户消息添加到历史并显示 conversationHistory.push({ role: user, content: userMessage }); appendMessage(user, userMessage, false); // 2. 清空输入框并禁用发送按钮 userInput.value ; sendBtn.disabled true; updateStatus(AI正在思考..., true); // 3. 准备请求体 const requestBody { model: internlm2-chat-1.8b, // 模型名称需与后端匹配 messages: conversationHistory, stream: true, // 关键启用流式响应 max_tokens: 512, temperature: 0.7, }; try { const response await fetch(API_CHAT_ENDPOINT, { method: POST, headers: { Content-Type: application/json, // 如果需要API密钥在这里添加 // Authorization: Bearer YOUR_API_KEY }, body: JSON.stringify(requestBody) }); if (!response.ok) { throw new Error(网络请求失败: ${response.status}); } // 4. 处理流式响应 const reader response.body.getReader(); const decoder new TextDecoder(utf-8); let aiResponseText ; let buffer ; // 在界面上先创建一个空的AI消息气泡 const messageDiv document.createElement(div); messageDiv.className message ai-message; messageDiv.innerHTML div classavatari classfas fa-robot/i/div div classbubble div classsenderAI助手/div div classtext idstreamingText/div /div ; messageContainer.appendChild(messageDiv); const streamingTextEl messageDiv.querySelector(.text); // 读取数据流 while (true) { const { done, value } await reader.read(); if (done) break; buffer decoder.decode(value, { stream: true }); const lines buffer.split(\n); buffer lines.pop(); // 最后一行可能不完整放回缓冲区 for (const line of lines) { if (line.startsWith(data: )) { const data line.slice(6); // 去掉 data: 前缀 if (data [DONE]) { // 流结束 continue; } try { const parsed JSON.parse(data); const chunk parsed.choices[0]?.delta?.content || ; if (chunk) { aiResponseText chunk; // 逐字显示模拟打字效果 streamingTextEl.textContent aiResponseText; messageContainer.scrollTop messageContainer.scrollHeight; } } catch (e) { console.warn(解析流数据出错:, e, 原始数据:, data); } } } } // 5. 流读取完毕更新状态和历史 updateStatus(准备就绪, false); conversationHistory.push({ role: assistant, content: aiResponseText }); } catch (error) { console.error(请求出错:, error); appendMessage(AI助手, 抱歉出错了: ${error.message}, true); updateStatus(请求出错请检查网络或服务, false); } finally { // 无论成功失败都重新启用发送按钮 sendBtn.disabled false; userInput.focus(); } }3.2 绑定事件与交互逻辑有了核心的通信函数我们还需要把按钮、输入框和这些函数连接起来。// 继续在 script.js 中添加 // 发送按钮点击事件 sendBtn.addEventListener(click, handleSendMessage); // 输入框回车键事件 userInput.addEventListener(keydown, (e) { if (e.key Enter !e.shiftKey) { e.preventDefault(); // 防止输入框换行 handleSendMessage(); } }); // 处理发送消息的通用函数 function handleSendMessage() { const text userInput.value.trim(); if (!text) { alert(请输入消息内容); userInput.focus(); return; } if (sendBtn.disabled) { return; // 防止重复发送 } sendMessageToAI(text); } // 清空对话历史 clearBtn.addEventListener(click, () { if (confirm(确定要清空所有对话记录吗)) { // 清空界面显示 const messagesToKeep messageContainer.querySelectorAll(.message)[0]; // 保留第一条欢迎消息 messageContainer.innerHTML ; if (messagesToKeep) { messageContainer.appendChild(messagesToKeep); } // 重置对话历史保留系统提示 conversationHistory [ { role: system, content: 你是一个乐于助人的AI助手。 } ]; updateStatus(对话已清空, false); userInput.focus(); } }); // 输入框自动调整高度 userInput.addEventListener(input, function () { this.style.height auto; this.style.height (this.scrollHeight) px; }); // 页面加载完成后让输入框自动获得焦点 window.onload function() { userInput.focus(); updateStatus(已连接到模型服务可以开始聊天了。, false); };4. 实际运行与效果体验代码都写好了现在让我们来运行它看看效果如何。确保后端服务运行首先确认你的InternLM2-Chat-1.8B模型服务已经在http://localhost:8000或你修改的地址正常运行。启动前端因为我们的前端使用了fetchAPI直接通过浏览器打开本地HTML文件file://协议访问不同端口的后端服务可能会遇到跨域问题CORS。最简单的解决方法是使用一个轻量级的本地HTTP服务器。如果你有Python可以在index.html所在目录打开终端运行python -m http.server 8080如果你有Node.js和npm可以安装http-servernpm install -g http-server然后运行http-server -p 8080或者使用VSCode的Live Server插件。访问页面打开浏览器访问http://localhost:8080或你设置的端口。开始聊天在输入框里问点问题吧比如“介绍一下你自己”或者“用JavaScript写一个Hello World程序”。你应该能看到你的消息出现在右侧。状态栏显示“AI正在思考...”并有打字动画。AI的回答会从左边的气泡中一个字一个字地流式显示出来。对话历史会累积可以用“清空对话”按钮重置。5. 总结与后续优化思路好了一个功能完整的InternLM2-Chat-1.8B前端聊天Demo就完成了。我们从头到尾搭建了一个具有现代感的Web界面并实现了与后端模型服务的流式交互。整个过程没有依赖任何复杂的前端框架核心就是HTML、CSS和原生JavaScript这让它非常轻量易于理解和修改。实际用下来这个Demo已经具备了聊天机器人的基本形态流式响应的体验也比一次性等待要舒服得多。当然这只是一个起点。如果你有兴趣可以基于这个基础进行很多有趣的扩展美化与交互可以加入消息发送的动画、消息的复制按钮、对AI回答的点赞/点踩反馈。上下文管理现在的conversationHistory会一直增长对于长对话可能会超出模型的上下文长度。你可以实现一个“滑动窗口”机制只保留最近N轮对话。参数调节在界面上增加滑动条或输入框让用户能实时调整temperature创造性、max_tokens生成长度等参数。多轮对话与工具调用如果模型支持Function Calling或工具调用可以在界面上设计更复杂的交互比如让用户选择“联网搜索”或“画图”。错误处理与重试增强网络错误、服务超时等情况下的用户提示和自动重试机制。部署上线将前端静态文件HTML, CSS, JS和后端模型服务一起通过Nginx等Web服务器部署到云服务器让更多人能访问。这个项目很好地展示了如何将强大的AI模型能力通过一个简单的Web界面释放出来。希望它能成为你探索AI应用开发的一个有趣起点。动手试试加入你自己的创意让它变得更强大吧。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。