Phi-3-Mini-128K保姆级教学:Streamlit主题定制+响应式布局适配移动端

Phi-3-Mini-128K保姆级教学:Streamlit主题定制+响应式布局适配移动端 Phi-3-Mini-128K保姆级教学Streamlit主题定制响应式布局适配移动端1. 项目概述Phi-3-Mini-128K是基于微软Phi-3-mini-128k-instruct模型开发的轻量化对话工具专为本地部署和高效推理而设计。这个工具完美继承了原模型的128K超长上下文处理能力同时通过多项优化技术显著降低了显存占用使得在普通消费级GPU上也能流畅运行。1.1 核心优势显存优化采用bfloat16半精度加载显存占用仅7-8GB长文本处理原生支持128K上下文窗口多轮对话完整记忆历史对话上下文本地运行无需网络连接保护隐私安全易用界面仿ChatGPT风格的交互设计2. 环境准备与安装2.1 硬件要求建议配置GPUNVIDIA显卡显存≥8GB内存≥16GB存储≥10GB可用空间最低配置GPU支持CUDA的NVIDIA显卡显存≥6GB内存≥8GB2.2 软件依赖安装# 创建并激活虚拟环境 python -m venv phi3-env source phi3-env/bin/activate # Linux/macOS phi3-env\Scripts\activate # Windows # 安装核心依赖 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 pip install transformers streamlit3. 基础部署与启动3.1 快速启动脚本创建一个名为app.py的文件内容如下import streamlit as st from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline # 初始化Streamlit界面 st.title(Phi-3-Mini-128K Chat) # 加载模型 st.cache_resource def load_model(): model AutoModelForCausalLM.from_pretrained( microsoft/Phi-3-mini-128k-instruct, torch_dtypeauto, device_mapauto ) tokenizer AutoTokenizer.from_pretrained(microsoft/Phi-3-mini-128k-instruct) return pipeline(text-generation, modelmodel, tokenizertokenizer) pipe load_model() # 初始化对话历史 if messages not in st.session_state: st.session_state.messages [] # 显示历史消息 for message in st.session_state.messages: with st.chat_message(message[role]): st.markdown(message[content]) # 处理用户输入 if prompt : st.chat_input(请输入您的问题...): # 添加用户消息到历史 st.session_state.messages.append({role: user, content: prompt}) with st.chat_message(user): st.markdown(prompt) # 生成助手回复 with st.chat_message(assistant): message_placeholder st.empty() full_response for response in pipe(prompt, max_new_tokens512, do_sampleTrue): full_response response message_placeholder.markdown(full_response ▌) message_placeholder.markdown(full_response) # 添加助手回复到历史 st.session_state.messages.append({role: assistant, content: full_response})3.2 启动应用streamlit run app.py启动后控制台会显示访问地址通常是http://localhost:8501在浏览器中打开即可使用。4. Streamlit主题定制4.1 自定义主题配置在项目根目录创建.streamlit/config.toml文件[theme] primaryColor #4f8bf9 backgroundColor #ffffff secondaryBackgroundColor #f0f2f6 textColor #31333f font sans serif [server] headless true port 8501 enableCORS false enableXsrfProtection true4.2 暗黑模式支持修改app.py添加主题切换功能# 在文件开头添加 from streamlit_theme import st_theme # 在显示历史消息前添加 theme st_theme() if theme and theme.get(base) dark: st.markdown( style .stChatMessage { --primary-color: #4f8bf9; --background-color: #1e1e1e; --secondary-background-color: #2d2d2d; --text-color: #f0f0f0; } /style , unsafe_allow_htmlTrue)5. 响应式布局适配移动端5.1 基础响应式调整在.streamlit/config.toml中添加[client] showSidebarNavigation false5.2 移动端优化CSS在app.py中添加st.markdown( style media (max-width: 768px) { .stTextInputdivdivinput { font-size: 16px !important; } .stChatMessage { max-width: 80% !important; } .stButtonbutton { width: 100% !important; } } /style , unsafe_allow_htmlTrue)5.3 输入框优化修改聊天输入框部分# 替换原来的st.chat_input input_container st.container() with input_container: user_input st.text_area( 请输入您的问题..., keyinput, height100, max_chars2000, label_visibilitycollapsed ) if st.button(发送) or user_input: if user_input: # 添加用户消息到历史 st.session_state.messages.append({role: user, content: user_input}) with st.chat_message(user): st.markdown(user_input) # 生成助手回复 with st.chat_message(assistant): message_placeholder st.empty() full_response for response in pipe(user_input, max_new_tokens512, do_sampleTrue): full_response response message_placeholder.markdown(full_response ▌) message_placeholder.markdown(full_response) # 添加助手回复到历史 st.session_state.messages.append({role: assistant, content: full_response}) # 清空输入框 st.session_state.input 6. 高级功能扩展6.1 对话历史管理添加对话历史管理功能# 在文件开头添加 import json from datetime import datetime # 在界面中添加历史管理按钮 col1, col2 st.columns(2) with col1: if st.button(保存当前对话): timestamp datetime.now().strftime(%Y%m%d_%H%M%S) with open(fconversation_{timestamp}.json, w) as f: json.dump(st.session_state.messages, f) st.success(对话已保存) with col2: if st.button(清空对话历史): st.session_state.messages [] st.rerun()6.2 生成参数调整添加生成参数控制面板with st.sidebar: st.header(生成参数) max_tokens st.slider(最大生成长度, 128, 2048, 512) temperature st.slider(温度(创造性), 0.1, 1.0, 0.7) top_p st.slider(Top-p采样, 0.1, 1.0, 0.9) # 修改生成部分代码 # 替换原来的pipe调用 for response in pipe( user_input, max_new_tokensmax_tokens, temperaturetemperature, top_ptop_p, do_sampleTrue ): full_response response7. 总结通过本教程我们完成了Phi-3-Mini-128K对话工具的完整部署并实现了以下优化主题定制创建了美观的界面主题支持暗黑模式移动适配优化了移动端显示效果和操作体验功能扩展添加了对话历史管理和生成参数控制性能优化保持了低显存占用的同时提供流畅交互这套方案让Phi-3模型在普通硬件上也能提供接近ChatGPT的使用体验特别适合个人开发者和小型团队快速搭建本地AI助手。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。