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星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2435573.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!