当前位置: 首页 > article >正文

Phi-3 Forest Laboratory 前端应用开发:Vue3集成AI对话组件实战

Phi-3 Forest Laboratory 前端应用开发Vue3集成AI对话组件实战最近在捣鼓一个内部知识库工具需要集成一个轻量级的AI对话能力。试了几个大模型要么部署起来太复杂要么对硬件要求太高。后来发现了Phi-3 Forest Laboratory这个模型在保持不错智能水平的同时对资源的需求相当友好特别适合集成到前端应用里。正好我们的前端技术栈是Vue3我就琢磨着怎么把Phi-3的对话能力无缝地嵌进去做一个类似ChatGPT那样的交互界面。整个过程下来发现其实没有想象中那么复杂核心就是处理好API调用、数据流和界面渲染这几块。今天我就把自己在Vue3项目里集成Phi-3对话组件的实战经验分享出来如果你也想在前端应用里加个AI助手这篇文章应该能帮你少走些弯路。1. 项目环境与准备工作在开始写代码之前我们需要先把基础环境搭好。这里假设你已经有一个运行起来的Phi-3 Forest Laboratory后端服务它提供了标准的对话API接口。1.1 创建Vue3项目如果你还没有Vue3项目可以用Vite快速创建一个。打开终端执行下面的命令npm create vuelatest phi3-chat-app创建过程中它会问你一些配置选项。对于这个项目我建议这样选TypeScript选是用TS能让代码更可靠JSX选否我们用模板语法就行Vue Router选否我们这个单页面应用暂时不需要路由Pinia选是状态管理后面会用到ESLint选是保持代码规范Prettier选是统一代码格式项目创建好后进入目录安装依赖cd phi3-chat-app npm install1.2 安装必要的依赖除了Vue3自带的我们还需要几个关键的包npm install axios marked highlight.jsaxios用来调用后端的API接口比原生的fetch用起来更方便marked把AI返回的Markdown格式文本转换成HTMLhighlight.js给代码块加上语法高亮让对话里的代码看起来更舒服如果你打算用Composition API的写法我推荐用这个可能还会用到vueuse/core里的一些工具函数不过不是必须的。1.3 配置API基础信息在项目根目录下创建一个.env.local文件用来存放环境变量VITE_API_BASE_URLhttp://localhost:8000 VITE_API_TIMEOUT30000这里VITE_API_BASE_URL是你的Phi-3后端服务地址VITE_API_TIMEOUT是请求超时时间设成30秒应该够用了。2. 构建API服务层有了基础环境我们先来封装调用Phi-3后端API的服务。把API相关的逻辑集中管理后面用起来会方便很多。2.1 创建Axios实例在src目录下新建一个services文件夹然后创建api.js文件import axios from axios; // 创建axios实例 const apiClient axios.create({ baseURL: import.meta.env.VITE_API_BASE_URL, timeout: parseInt(import.meta.env.VITE_API_TIMEOUT), headers: { Content-Type: application/json, }, }); // 请求拦截器 - 可以在这里加token之类的 apiClient.interceptors.request.use( (config) { // 如果需要认证可以在这里添加token // const token localStorage.getItem(token); // if (token) { // config.headers.Authorization Bearer ${token}; // } return config; }, (error) { return Promise.reject(error); } ); // 响应拦截器 - 统一处理错误 apiClient.interceptors.response.use( (response) { return response.data; }, (error) { console.error(API请求错误:, error); // 根据错误类型给出用户友好的提示 let message 请求失败请稍后重试; if (error.response) { switch (error.response.status) { case 401: message 认证失败请重新登录; break; case 404: message 请求的资源不存在; break; case 500: message 服务器内部错误; break; default: message 请求失败: ${error.response.status}; } } else if (error.request) { message 网络连接失败请检查网络设置; } return Promise.reject({ message, originalError: error }); } ); export default apiClient;2.2 封装对话API在services文件夹下再创建一个chatService.js专门处理对话相关的API调用import apiClient from ./api; class ChatService { /** * 发送消息给Phi-3模型 * param {string} message - 用户输入的消息 * param {Array} history - 对话历史 * param {Object} options - 其他参数 * returns {Promise} - 返回Promise */ async sendMessage(message, history [], options {}) { try { const response await apiClient.post(/chat/completions, { messages: [ ...history, { role: user, content: message } ], stream: false, // 非流式响应 ...options }); return response; } catch (error) { console.error(发送消息失败:, error); throw error; } } /** * 流式发送消息用于实时显示 * param {string} message - 用户输入的消息 * param {Array} history - 对话历史 * param {Function} onChunk - 收到数据块时的回调 * param {Function} onComplete - 完成时的回调 * param {Function} onError - 错误时的回调 * param {Object} options - 其他参数 */ async sendMessageStream(message, history [], { onChunk, onComplete, onError }, options {}) { try { const response await fetch(${import.meta.env.VITE_API_BASE_URL}/chat/completions, { method: POST, headers: { Content-Type: application/json, }, body: JSON.stringify({ messages: [ ...history, { role: user, content: message } ], stream: true, // 开启流式响应 ...options }), }); if (!response.ok) { throw new Error(HTTP error! status: ${response.status}); } const reader response.body.getReader(); const decoder new TextDecoder(); let buffer ; while (true) { const { done, value } await reader.read(); if (done) { if (onComplete) onComplete(); 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); if (data [DONE]) { if (onComplete) onComplete(); return; } try { const parsed JSON.parse(data); const content parsed.choices?.[0]?.delta?.content || ; if (content onChunk) { onChunk(content); } } catch (e) { console.warn(解析流数据失败:, e); } } } } } catch (error) { console.error(流式请求失败:, error); if (onError) onError(error); } } /** * 清除对话历史 * returns {Promise} - 返回Promise */ async clearHistory() { // 这里调用后端的清空历史接口如果后端没有这个接口前端自己处理也行 try { // 假设后端有清空历史的接口 // return await apiClient.post(/chat/clear); // 如果后端没有直接返回成功 return { success: true }; } catch (error) { console.error(清空历史失败:, error); throw error; } } } export default new ChatService();这个服务类提供了两种发送消息的方式普通方式和流式方式。流式方式能让用户看到AI一个字一个字打出来的效果体验更好。3. 实现对话状态管理接下来我们用Pinia来管理对话的状态。Pinia是Vue官方推荐的状态管理库用起来比Vuex简单不少。3.1 创建Chat Store在src/stores目录下创建chat.jsimport { defineStore } from pinia; import { ref, computed } from vue; import chatService from /services/chatService; export const useChatStore defineStore(chat, () { // 状态 const messages ref([]); const isLoading ref(false); const error ref(null); const currentStreamContent ref(); // 计算属性 const conversationHistory computed(() { return messages.value.map(msg ({ role: msg.role, content: msg.content })); }); // 添加消息 const addMessage (role, content) { messages.value.push({ id: Date.now() Math.random(), role, content, timestamp: new Date().toISOString() }); }; // 更新最后一条消息用于流式响应 const updateLastMessage (content) { if (messages.value.length 0) { const lastMessage messages.value[messages.value.length - 1]; if (lastMessage.role assistant) { lastMessage.content content; } } }; // 发送消息 const sendMessage async (content, options {}) { if (!content.trim()) return; isLoading.value true; error.value null; // 添加用户消息 addMessage(user, content); // 添加一个空的助手消息用于流式更新 addMessage(assistant, ); try { if (options.useStream) { // 流式响应 currentStreamContent.value ; await chatService.sendMessageStream( content, conversationHistory.value.slice(0, -2), // 排除刚添加的两条消息 { onChunk: (chunk) { currentStreamContent.value chunk; updateLastMessage(chunk); }, onComplete: () { currentStreamContent.value ; isLoading.value false; }, onError: (err) { error.value err.message; isLoading.value false; // 移除空的助手消息 messages.value.pop(); } }, options ); } else { // 普通响应 const response await chatService.sendMessage( content, conversationHistory.value.slice(0, -2), options ); // 更新最后一条消息 const lastMessage messages.value[messages.value.length - 1]; lastMessage.content response.choices[0].message.content; isLoading.value false; } } catch (err) { error.value err.message || 发送消息失败; isLoading.value false; // 移除空的助手消息 messages.value.pop(); } }; // 清空对话 const clearMessages async () { try { await chatService.clearHistory(); messages.value []; error.value null; currentStreamContent.value ; } catch (err) { error.value err.message || 清空对话失败; } }; return { // 状态 messages, isLoading, error, currentStreamContent, // 计算属性 conversationHistory, // 方法 addMessage, updateLastMessage, sendMessage, clearMessages }; });这个store管理了所有的对话状态包括消息列表、加载状态、错误信息等。它提供了发送消息和清空对话的方法并且支持流式响应。4. 构建对话界面组件状态管理搞定了现在我们来创建实际的Vue组件。我会把界面拆成几个小组件这样代码更清晰也更好维护。4.1 Markdown渲染组件先创建一个专门渲染Markdown的组件因为AI返回的内容通常是Markdown格式的。在src/components目录下创建MarkdownRenderer.vuetemplate div classmarkdown-content v-htmlrenderedContent/div /template script setup import { computed, onMounted, ref, watch } from vue; import { marked } from marked; import hljs from highlight.js; import highlight.js/styles/github-dark.css; const props defineProps({ content: { type: String, default: } }); // 配置marked marked.setOptions({ highlight: function(code, language) { if (language hljs.getLanguage(language)) { try { return hljs.highlight(code, { language }).value; } catch (err) { console.warn(代码高亮失败:, err); } } return hljs.highlightAuto(code).value; }, breaks: true, // 换行符转换为br gfm: true, // 使用GitHub风格的Markdown }); const renderedContent computed(() { if (!props.content) return ; return marked(props.content); }); // 处理链接点击在新窗口打开 const handleLinkClick (event) { if (event.target.tagName A) { event.preventDefault(); window.open(event.target.href, _blank); } }; // 高亮代码块 const highlightCodeBlocks () { nextTick(() { const container document.querySelector(.markdown-content); if (container) { container.querySelectorAll(pre code).forEach((block) { hljs.highlightElement(block); }); } }); }; // 监听内容变化 watch(() props.content, () { highlightCodeBlocks(); }); onMounted(() { highlightCodeBlocks(); }); /script style scoped .markdown-content { line-height: 1.6; } .markdown-content :deep(h1) { font-size: 1.8em; margin: 1em 0 0.5em; border-bottom: 2px solid #eaeaea; padding-bottom: 0.3em; } .markdown-content :deep(h2) { font-size: 1.5em; margin: 1.2em 0 0.5em; border-bottom: 1px solid #eaeaea; padding-bottom: 0.2em; } .markdown-content :deep(h3) { font-size: 1.3em; margin: 1em 0 0.5em; } .markdown-content :deep(p) { margin: 0.8em 0; } .markdown-content :deep(ul), .markdown-content :deep(ol) { margin: 0.8em 0; padding-left: 2em; } .markdown-content :deep(li) { margin: 0.4em 0; } .markdown-content :deep(blockquote) { border-left: 4px solid #ddd; margin: 1em 0; padding-left: 1em; color: #666; font-style: italic; } .markdown-content :deep(pre) { background: #1e1e1e; border-radius: 6px; padding: 1em; margin: 1em 0; overflow-x: auto; } .markdown-content :deep(code) { font-family: Courier New, Courier, monospace; padding: 0.2em 0.4em; border-radius: 3px; } .markdown-content :deep(pre code) { background: transparent; padding: 0; } .markdown-content :deep(a) { color: #0366d6; text-decoration: none; } .markdown-content :deep(a:hover) { text-decoration: underline; } .markdown-content :deep(table) { border-collapse: collapse; margin: 1em 0; width: 100%; } .markdown-content :deep(th), .markdown-content :deep(td) { border: 1px solid #ddd; padding: 0.5em; text-align: left; } .markdown-content :deep(th) { background-color: #f6f8fa; font-weight: 600; } /style这个组件负责把Markdown转换成漂亮的HTML并且给代码块加上语法高亮。4.2 消息气泡组件接下来创建消息气泡组件显示单条对话消息。创建MessageBubble.vuetemplate div :class[message, message.role, { streaming: isStreaming }] div classavatar div v-ifmessage.role user classuser-avatar svg width24 height24 viewBox0 0 24 24 fillnone circle cx12 cy8 r4 fill#4CAF50/ path dM12 14c-3.31 0-6 2.69-6 6v2h12v-2c0-3.31-2.69-6-6-6z fill#4CAF50/ /svg /div div v-else classai-avatar svg width24 height24 viewBox0 0 24 24 fillnone circle cx12 cy12 r10 fill#2196F3/ path dM8 10h8M8 14h6 strokewhite stroke-width2 stroke-linecapround/ /svg /div /div div classcontent div classheader span classrole{{ message.role user ? 你 : AI助手 }}/span span classtime{{ formattedTime }}/span /div div classmessage-body MarkdownRenderer v-ifmessage.role assistant :contentdisplayContent / div v-else classuser-text{{ message.content }}/div div v-ifisStreaming message.role assistant classstreaming-indicator div classtyping-dots span/span span/span span/span /div /div /div /div /div /template script setup import { computed } from vue; import MarkdownRenderer from ./MarkdownRenderer.vue; const props defineProps({ message: { type: Object, required: true }, isStreaming: { type: Boolean, default: false }, streamingContent: { type: String, default: } }); const formattedTime computed(() { if (!props.message.timestamp) return ; const date new Date(props.message.timestamp); return date.toLocaleTimeString([], { hour: 2-digit, minute: 2-digit }); }); const displayContent computed(() { if (props.isStreaming props.message.role assistant) { return props.message.content props.streamingContent; } return props.message.content; }); /script style scoped .message { display: flex; padding: 1rem; gap: 0.75rem; border-bottom: 1px solid #f0f0f0; } .message:last-child { border-bottom: none; } .message.user { background-color: #f9f9f9; } .message.assistant { background-color: white; } .message.streaming { background-color: #f8fbff; } .avatar { flex-shrink: 0; } .user-avatar, .ai-avatar { width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; } .user-avatar { background-color: #e8f5e9; } .ai-avatar { background-color: #e3f2fd; } .content { flex: 1; min-width: 0; } .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; } .role { font-weight: 600; font-size: 0.95rem; } .message.user .role { color: #2e7d32; } .message.assistant .role { color: #1565c0; } .time { font-size: 0.8rem; color: #888; } .message-body { line-height: 1.6; } .user-text { white-space: pre-wrap; word-break: break-word; } .streaming-indicator { margin-top: 0.5rem; } .typing-dots { display: flex; align-items: center; height: 20px; } .typing-dots span { width: 8px; height: 8px; margin: 0 2px; background-color: #999; border-radius: 50%; display: inline-block; animation: typing 1.4s infinite both; } .typing-dots span:nth-child(2) { animation-delay: 0.2s; } .typing-dots span:nth-child(3) { animation-delay: 0.4s; } keyframes typing { 0%, 60%, 100% { transform: translateY(0); opacity: 0.6; } 30% { transform: translateY(-5px); opacity: 1; } } /style这个组件根据消息的角色用户或AI显示不同的样式并且支持显示流式响应的打字效果。4.3 主对话组件最后创建主对话组件ChatInterface.vue把前面这些组件组合起来template div classchat-container div classchat-header h2Phi-3 AI助手/h2 div classheader-actions button clickclearChat classclear-btn :disabledstore.isLoading 清空对话 /button label classstream-toggle input typecheckbox v-modeluseStream :disabledstore.isLoading 流式响应 /label /div /div div classmessages-container refmessagesContainer div v-ifstore.messages.length 0 classempty-state div classempty-icon/div h3开始对话吧/h3 p输入你的问题Phi-3 AI助手会为你解答/p div classexample-prompts button v-forprompt in examplePrompts :keyprompt clickuseExamplePrompt(prompt) classexample-btn {{ prompt }} /button /div /div MessageBubble v-formessage in store.messages :keymessage.id :messagemessage :is-streamingstore.isLoading message.role assistant message.id lastMessageId :streaming-contentstore.currentStreamContent / div v-ifstore.isLoading store.messages.length 0 !store.currentStreamContent classloading 思考中... /div div v-ifstore.error classerror-message div classerror-icon⚠️/div div classerror-text{{ store.error }}/div button clickstore.error null classdismiss-btn×/button /div /div div classinput-container div classinput-wrapper textarea refinputRef v-modelinputText keydown.enter.exact.preventhandleSend keydown.enter.shift.exact.preventinputText \n placeholder输入你的消息... (Enter发送ShiftEnter换行) :disabledstore.isLoading rows3 classmessage-input /textarea div classinput-actions button clickhandleSend :disabled!canSend classsend-btn svg width20 height20 viewBox0 0 24 24 fillnone path dM2 21L23 12L2 3V10L17 12L2 14V21Z fillcurrentColor/ /svg /button /div /div div classinput-hint 提示Phi-3擅长代码解释、文本分析、逻辑推理等任务 /div /div /div /template script setup import { ref, computed, nextTick, onMounted, onUnmounted } from vue; import { useChatStore } from /stores/chat; import MessageBubble from ./MessageBubble.vue; const store useChatStore(); const inputText ref(); const useStream ref(true); const messagesContainer ref(null); const inputRef ref(null); const examplePrompts [ 用Vue3写一个计数器组件, 解释一下JavaScript中的闭包, 帮我写一个Python函数计算斐波那契数列, 什么是RESTful API ]; const canSend computed(() { return inputText.value.trim() ! !store.isLoading; }); const lastMessageId computed(() { if (store.messages.length 0) return null; return store.messages[store.messages.length - 1].id; }); // 滚动到底部 const scrollToBottom () { nextTick(() { if (messagesContainer.value) { messagesContainer.value.scrollTop messagesContainer.value.scrollHeight; } }); }; // 发送消息 const handleSend async () { if (!canSend.value) return; const text inputText.value.trim(); inputText.value ; await store.sendMessage(text, { useStream: useStream.value, temperature: 0.7, max_tokens: 1000 }); scrollToBottom(); focusInput(); }; // 使用示例提示 const useExamplePrompt (prompt) { inputText.value prompt; focusInput(); }; // 清空对话 const clearChat async () { if (confirm(确定要清空对话历史吗)) { await store.clearMessages(); } }; // 聚焦输入框 const focusInput () { nextTick(() { if (inputRef.value) { inputRef.value.focus(); } }); }; // 监听消息变化自动滚动 watch(() store.messages.length, scrollToBottom); watch(() store.currentStreamContent, scrollToBottom); // 键盘快捷键 const handleKeyDown (e) { if (e.ctrlKey e.key k) { e.preventDefault(); focusInput(); } if (e.key Escape inputRef.value document.activeElement) { inputRef.value.blur(); } }; onMounted(() { window.addEventListener(keydown, handleKeyDown); focusInput(); }); onUnmounted(() { window.removeEventListener(keydown, handleKeyDown); }); /script style scoped .chat-container { display: flex; flex-direction: column; height: 100vh; max-width: 900px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1); } .chat-header { padding: 1.25rem 1.5rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; display: flex; justify-content: space-between; align-items: center; } .chat-header h2 { margin: 0; font-size: 1.5rem; font-weight: 600; } .header-actions { display: flex; gap: 1rem; align-items: center; } .clear-btn { padding: 0.5rem 1rem; background: rgba(255, 255, 255, 0.2); border: 1px solid rgba(255, 255, 255, 0.3); color: white; border-radius: 6px; cursor: pointer; font-size: 0.9rem; transition: background 0.2s; } .clear-btn:hover:not(:disabled) { background: rgba(255, 255, 255, 0.3); } .clear-btn:disabled { opacity: 0.5; cursor: not-allowed; } .stream-toggle { display: flex; align-items: center; gap: 0.5rem; font-size: 0.9rem; cursor: pointer; } .stream-toggle input { cursor: pointer; } .messages-container { flex: 1; overflow-y: auto; padding: 1.5rem; background: #fafafa; } .empty-state { text-align: center; padding: 4rem 2rem; color: #666; } .empty-icon { font-size: 3rem; margin-bottom: 1rem; } .empty-state h3 { margin: 0 0 0.5rem; color: #333; } .empty-state p { margin: 0 0 2rem; color: #888; } .example-prompts { display: flex; flex-wrap: wrap; gap: 0.75rem; justify-content: center; max-width: 600px; margin: 0 auto; } .example-btn { padding: 0.75rem 1.25rem; background: white; border: 1px solid #e0e0e0; border-radius: 8px; color: #555; cursor: pointer; font-size: 0.9rem; transition: all 0.2s; } .example-btn:hover { background: #f5f5f5; border-color: #667eea; color: #667eea; transform: translateY(-1px); } .loading { text-align: center; padding: 1rem; color: #666; font-style: italic; } .error-message { display: flex; align-items: center; gap: 0.75rem; padding: 1rem; background: #ffebee; border-left: 4px solid #f44336; border-radius: 6px; margin-top: 1rem; } .error-icon { font-size: 1.25rem; } .error-text { flex: 1; color: #d32f2f; } .dismiss-btn { background: none; border: none; font-size: 1.5rem; color: #d32f2f; cursor: pointer; padding: 0 0.5rem; } .dismiss-btn:hover { color: #b71c1c; } .input-container { padding: 1.5rem; border-top: 1px solid #e0e0e0; background: white; } .input-wrapper { position: relative; margin-bottom: 0.75rem; } .message-input { width: 100%; padding: 1rem; padding-right: 3.5rem; border: 2px solid #e0e0e0; border-radius: 8px; font-size: 1rem; line-height: 1.5; resize: none; transition: border-color 0.2s; font-family: inherit; } .message-input:focus { outline: none; border-color: #667eea; } .message-input:disabled { background: #f5f5f5; cursor: not-allowed; } .input-actions { position: absolute; right: 0.75rem; bottom: 0.75rem; } .send-btn { width: 40px; height: 40px; background: #667eea; color: white; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: background 0.2s; } .send-btn:hover:not(:disabled) { background: #5a67d8; } .send-btn:disabled { background: #ccc; cursor: not-allowed; } .input-hint { font-size: 0.85rem; color: #888; text-align: center; } /* 滚动条样式 */ .messages-container::-webkit-scrollbar { width: 8px; } .messages-container::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 4px; } .messages-container::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 4px; } .messages-container::-webkit-scrollbar-thumb:hover { background: #a8a8a8; } /style这个主组件把所有的功能都整合在一起了显示对话历史、处理用户输入、控制流式响应、显示加载状态和错误信息。5. 集成与优化建议组件都写好了最后一步是把它们集成到应用里并且考虑一些优化点。5.1 在主应用中集成修改src/App.vue使用我们的对话组件template div idapp header classapp-header div classcontainer h1Phi-3 Forest Laboratory 对话演示/h1 p classsubtitle基于Vue3的AI对话界面集成/p /div /header main classapp-main div classcontainer ChatInterface / /div /main footer classapp-footer div classcontainer p使用Phi-3 Forest Laboratory构建 • 基于Vue3开发/p p classfooter-note 注意本演示需要连接可用的Phi-3后端服务请确保服务正常运行 /p /div /footer /div /template script setup import ChatInterface from ./components/ChatInterface.vue; /script style * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, sans-serif; line-height: 1.6; color: #333; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); min-height: 100vh; } #app { min-height: 100vh; display: flex; flex-direction: column; } .container { max-width: 1200px; margin: 0 auto; padding: 0 1rem; } .app-header { background: white; padding: 2rem 0; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); } .app-header h1 { font-size: 2rem; color: #333; margin-bottom: 0.5rem; } .subtitle { color: #666; font-size: 1.1rem; } .app-main { flex: 1; padding: 2rem 0; } .app-footer { background: #333; color: white; padding: 1.5rem 0; text-align: center; } .footer-note { margin-top: 0.5rem; font-size: 0.9rem; color: #aaa; } /style5.2 性能优化建议在实际使用中你可能还需要考虑下面这些优化点虚拟滚动如果对话历史很长可以考虑用虚拟滚动来提升性能。可以用vue-virtual-scroller这样的库。本地存储把对话历史存到localStorage里这样刷新页面也不会丢失// 在chat store里添加 const saveToLocalStorage () { localStorage.setItem(chat_messages, JSON.stringify(messages.value)); }; const loadFromLocalStorage () { const saved localStorage.getItem(chat_messages); if (saved) { messages.value JSON.parse(saved); } };请求取消如果用户快速发送多条消息可以取消之前的请求// 在chatService里 let abortController null; const sendMessageStream async (/* 参数 */) { // 取消之前的请求 if (abortController) { abortController.abort(); } abortController new AbortController(); try { const response await fetch(url, { // ... 其他配置 signal: abortController.signal }); // ... 处理响应 } catch (error) { if (error.name AbortError) { console.log(请求被取消); return; } throw error; } };错误重试网络不稳定时可以自动重试const retryRequest async (fn, maxRetries 3) { for (let i 0; i maxRetries; i) { try { return await fn(); } catch (error) { if (i maxRetries - 1) throw error; await new Promise(resolve setTimeout(resolve, 1000 * (i 1))); } } };打字机效果优化如果流式响应太快可以加个小的延迟让打字效果更自然// 在收到数据块时 const showTypingEffect async (chunk) { for (const char of chunk) { currentContent.value char; await new Promise(resolve setTimeout(resolve, 20)); // 20ms延迟 } };6. 实际使用感受把这个对话组件集成到项目里用了一段时间感觉整体效果还不错。Vue3的响应式系统用起来很顺手配合Pinia管理状态代码结构清晰维护起来也不费劲。流式响应的体验比一次性返回好很多用户能看到AI一个字一个字地思考和回答感觉更自然。Markdown渲染这块用highlight.js给代码加上高亮后技术对话的阅读体验提升很明显。不过在实际使用中也发现一些小问题。比如网络不太稳定的时候流式响应可能会中断这时候需要给用户明确的错误提示。还有对话历史太长的话滚动起来会有点卡后面可能得加上虚拟滚动。如果你要在生产环境用建议再加个消息持久化把对话历史存到本地或者后端数据库里。还可以考虑加个停止生成按钮让用户能随时中断AI的回复。总的来说用Vue3集成Phi-3的对话能力技术难度不算大但要做好用户体验还是有不少细节要考虑。上面的代码可以作为一个起点你可以根据自己的需求调整和扩展。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。

相关文章:

Phi-3 Forest Laboratory 前端应用开发:Vue3集成AI对话组件实战

Phi-3 Forest Laboratory 前端应用开发:Vue3集成AI对话组件实战 最近在捣鼓一个内部知识库工具,需要集成一个轻量级的AI对话能力。试了几个大模型,要么部署起来太复杂,要么对硬件要求太高。后来发现了Phi-3 Forest Laboratory&am…...

I²C总线原理与硬件协议深度解析

1. IC总线原理深度解析:从硬件电气特性到软件协议实现IC(Inter-Integrated Circuit)总线自1982年由Philips(现NXP)提出以来,已成为嵌入式系统中连接微控制器与外围器件最广泛采用的串行通信标准之一。其核心…...

实战复盘:我们公司从EDR升级到XDR的完整踩坑与避坑指南

实战复盘:我们公司从EDR升级到XDR的完整踩坑与避坑指南 去年夏天的一次安全事件彻底改变了我们对端点防护的认知。某个周五下午,安全团队突然收到大量异常登录告警——攻击者利用一个未打补丁的第三方应用漏洞,在内部网络中横向移动了近3小时…...

PT6312 VFD驱动库深度解析:8位MCU三线制段码显示方案

1. PT6312库深度技术解析:面向嵌入式工程师的VFD控制器驱动开发指南真空荧光显示器(Vacuum Fluorescent Display, VFD)因其高亮度、宽视角、宽温工作范围及独特的蓝绿色冷光特性,在工业控制面板、高端音响设备、老式DVD播放器及复…...

NSudo权限管理工具终极指南:Windows系统权限突破完全教程

NSudo权限管理工具终极指南:Windows系统权限突破完全教程 【免费下载链接】NSudo [Deprecated, work in progress alternative: https://github.com/M2Team/NanaRun] Series of System Administration Tools 项目地址: https://gitcode.com/gh_mirrors/nsu/NSudo …...

单片机ADC数据滤波十大实用算法详解

1. 单片机ADC数据滤波:十大实用算法原理与工程实现在嵌入式系统开发中,模数转换器(ADC)采集的原始数据往往受到电源噪声、PCB布线耦合、传感器自身特性及环境电磁干扰等多重因素影响。即使采用高精度基准源与合理布局,…...

嵌入式INI配置管理器:零堆内存、回调驱动的轻量解析方案

1. IniManager:嵌入式系统轻量级配置管理器深度解析IniManager 是一个专为资源受限嵌入式环境设计的纯 C 语言.ini文件解析与管理库。它不依赖标准 C 库的stdio.h(如fopen/fread),不使用动态内存分配(malloc/free&…...

YOLO12模型在C++环境下的高效调用与优化

YOLO12模型在C环境下的高效调用与优化 1. 引言 目标检测是计算机视觉领域的核心任务之一,而YOLO系列模型一直是这个领域的佼佼者。最新发布的YOLO12引入了以注意力为中心的架构,在保持实时推理速度的同时显著提升了检测精度。对于需要在C环境中部署高性…...

EcomGPT电商智能助手保姆级教程:电商培训讲师如何用AI生成课程案例题库

EcomGPT电商智能助手保姆级教程:电商培训讲师如何用AI生成课程案例题库 1. 引言:电商讲师的痛点与AI解决方案 作为电商培训讲师,你是否经常为这些事头疼?每天要准备大量教学案例,手动编写商品描述、设计分类题目、制…...

告别物理翻车!深度调参指南:UE5 ChaosVehicles载具运动与手感优化全解析

告别物理翻车!深度调参指南:UE5 ChaosVehicles载具运动与手感优化全解析 当你驾驶着自己精心设计的UE5载具在赛道上飞驰,却发现转向迟钝得像在开卡车,或是轻轻一碰障碍物就表演360度空中转体——这种"物理翻车"的挫败感…...

Linux内核链表遍历:list_for_each_entry_safe宏的5个实战技巧

Linux内核链表遍历:list_for_each_entry_safe宏的5个实战技巧 在Linux内核开发中,链表是最基础也是最常用的数据结构之一。不同于用户空间的链表实现,内核链表采用了一种独特的侵入式设计,通过struct list_head将链表节点嵌入到业…...

EmbeddingGemma-300m部署教程:从零开始搭建本地AI服务

EmbeddingGemma-300m部署教程:从零开始搭建本地AI服务 1. 准备工作与环境搭建 1.1 了解EmbeddingGemma-300m EmbeddingGemma-300m是谷歌推出的轻量级文本嵌入模型,具有以下特点: 参数量3.08亿,专为设备端优化支持100多种语言的…...

5大核心优势,立即掌握专业级3D点云标注工具labelCloud

5大核心优势,立即掌握专业级3D点云标注工具labelCloud 【免费下载链接】labelCloud 项目地址: https://gitcode.com/gh_mirrors/la/labelCloud labelCloud是一款专为计算机视觉工程师和研究人员设计的轻量级3D点云标注工具,能够高效生成用于3D目…...

零基础玩转TranslateGemma:浏览器端翻译组件实战教程

零基础玩转TranslateGemma:浏览器端翻译组件实战教程 1. 为什么选择浏览器端翻译 想象一下这样的场景:你在浏览一个外语技术文档时,遇到一段关键的API说明,但语言障碍让你无法理解。传统做法是复制文本、打开翻译网站、粘贴、等…...

Lingbot-Depth-Pretrain-ViTL-14 3D视觉实战:SolidWorks模型深度图生成教程

Lingbot-Depth-Pretrain-ViTL-14 3D视觉实战:SolidWorks模型深度图生成教程 如果你是一位工业设计师或机械工程师,每天都要和SolidWorks里那些复杂的3D模型打交道,那你肯定遇到过这样的烦恼:想快速给模型做个可视化分析&#xff…...

VCNL4200传感器驱动开发:I²C寄存器控制与中断实战

1. VCNL4200传感器驱动库技术解析与工程实践VCNL4200是Vishay公司推出的集成式环境光(ALS)与近距(Proximity)二合一传感器,采用8引脚QFN封装,内置红外LED发射器、光电二极管接收器、16位ADC、IC接口及可编程…...

TensorFlow-v2.9镜像性能优化:SSH远程操作卡顿解决方案

TensorFlow-v2.9镜像性能优化:SSH远程操作卡顿解决方案 1. 问题现象与初步分析 当你通过SSH连接到TensorFlow-v2.9镜像进行深度学习训练时,是否遇到过以下情况: 命令行响应延迟明显,按键后需要等待才能看到回显训练过程中系统整…...

ClickHouse写入性能翻倍?试试RowBinary格式与异步插入的黄金组合

ClickHouse写入性能翻倍:RowBinary格式与异步插入的黄金组合实战 当你的物联网传感器每分钟产生百万级数据点,或是实时日志分析系统需要处理每秒GB级的文本流时,ClickHouse的写入性能直接决定了业务能否跑赢时间。本文将揭示一个被许多团队忽…...

【安卓逆向】APK反编译与回编译实战:从工具使用到代码修改

1. 安卓逆向入门:为什么需要APK反编译? 刚接触安卓逆向时,很多人会疑惑:为什么放着现成的APK不用,非要大费周章反编译?我刚开始做安卓开发时也这么想,直到有次线上版本出现紧急Bug,但…...

MATLAB画图时坐标光标显示不准?一招教你自定义数据提示框的显示精度(附代码)

MATLAB数据可视化进阶:精准控制坐标光标显示精度的完整方案 在科研数据分析和工程可视化领域,MATLAB的图形界面(Figure)是我们最常打交道的"老伙伴"。但当你处理海量数据时,是否遇到过这样的困扰:明明是两个不同的数据点…...

leboncoin:微调如何击败RAG

在leboncoin——法国最大的分类广告平台,我们每天帮助数百万用户出售他们的物品。广告发布是我们市场的核心,这是供应进入平台的关键时刻。当有人列出一部iPhone出售时,我们会要求他们填写属性:品牌、型号、存储和颜色。这些属性驱…...

SpringCloud实战:Resilience4j断路器与舱壁隔离的深度解析

1. Resilience4j断路器实战指南 第一次接触Resilience4j断路器是在去年双十一大促期间,当时我们的订单服务突然出现大面积超时,导致整个电商系统几乎瘫痪。后来分析发现是支付服务响应缓慢,但订单服务仍然持续调用支付接口,最终拖…...

Pixel Dimension Fissioner生产环境实践:日均万次调用下的稳定性与GPU优化策略

Pixel Dimension Fissioner生产环境实践:日均万次调用下的稳定性与GPU优化策略 1. 项目背景与挑战 Pixel Dimension Fissioner是一款基于MT5-Zero-Shot-Augment核心引擎构建的高端文本改写工具,其独特的16-bit像素冒险工坊设计风格为用户提供了全新的交…...

OFA图像英文描述模型在微信小程序开发中的应用:智能图片标注实战

OFA图像英文描述模型在微信小程序开发中的应用:智能图片标注实战 为微信小程序添加智能图片理解能力,让用户上传的每张图片都能自动生成准确的英文描述 1. 项目背景与需求场景 在跨境电商和旅游导览这类小程序里,用户经常需要上传商品图片或…...

Golang实战速成:从零构建高并发微服务

1. 为什么选择Golang构建高并发微服务 第一次接触Golang是在2014年,当时团队需要重构一个日活百万的推送系统。用Java写的旧系统在高并发场景下频繁GC卡顿,而改用Go后,不仅吞吐量提升了3倍,内存占用还降低了60%。这段经历让我深刻…...

Pixel Dimension Fissioner可部署方案:私有化部署保障企业文案数据安全

Pixel Dimension Fissioner可部署方案:私有化部署保障企业文案数据安全 1. 企业数据安全新选择 在数字化内容创作时代,企业文案数据安全已成为不可忽视的核心需求。Pixel Dimension Fissioner(像素语言维度裂变器)作为基于MT5-Z…...

Cosmos-Reason1-7B处理长文本技术详解:上下文窗口管理与关键信息提取

Cosmos-Reason1-7B处理长文本技术详解:上下文窗口管理与关键信息提取 你是不是也遇到过这样的烦恼?面对一份几十页的技术报告或者一份复杂的法律合同,想要快速找到某个关键条款或者理解其中的核心结论,却不得不花上大半天时间从头…...

Win7虚拟机下UltraISO找不到虚拟光驱?3步搞定镜像加载问题

Win7虚拟机下UltraISO虚拟光驱识别难题的深度解决方案 在虚拟化技术广泛应用的今天,许多开发者依然需要在Windows 7虚拟机环境中处理ISO镜像文件。UltraISO作为老牌光盘映像工具,其虚拟光驱功能在物理机上表现稳定,但在VMware虚拟机环境中却常…...

Arduino嵌入式日志框架:零堆分配与编译期裁剪设计

1. 项目概述ArduinoLog 是一款专为 Arduino 及兼容嵌入式平台设计的轻量级 C 日志框架,其核心目标是在资源受限的微控制器环境中提供高可控性、零动态内存分配、低运行时开销的日志能力。它并非简单封装Serial.print()的工具,而是借鉴 log4j、log4cpp 等…...

TGX嵌入式图形库:轻量级2D/3D帧缓冲渲染引擎

1. TGX图形库概述 TGX(Tiny Graphics eXtended)是一个专为资源受限嵌入式平台设计的轻量级C图形库,其核心目标是在32位微控制器上实现高性能2D/3D图形渲染,同时保持极低的内存占用与确定性执行时间。与传统GUI框架不同&#xff0…...