
Nanbeige 4.1-3B代码实例实现对话历史本地存储像素风时间轴回溯1. 项目概述Nanbeige 4.1-3B像素冒险聊天终端是一款融合复古游戏美学与AI对话技术的创新界面。不同于传统聊天界面它采用JRPG风格设计将AI对话转化为一场视觉化的冒险体验。核心功能亮点像素游戏风UI4px像素边框、高饱和度配色、角色化对话框对话历史管理自动保存完整对话记录到本地时间轴回溯可视化浏览历史对话像游戏存档系统思考过程可视化通过think标签展示模型推理逻辑2. 环境准备与快速部署2.1 基础环境要求Python 3.8Streamlit 1.25Transformers 4.30至少16GB内存运行3B模型2.2 一键安装命令pip install streamlit transformers torch2.3 快速启动应用创建pixel_chat.py文件复制以下启动代码import streamlit as st from transformers import AutoModelForCausalLM, AutoTokenizer st.cache_resource def load_model(): model AutoModelForCausalLM.from_pretrained(nanbeige/nanbeige-4.1-3B) tokenizer AutoTokenizer.from_pretrained(nanbeige/nanbeige-4.1-3B) return model, tokenizer model, tokenizer load_model()3. 对话历史本地存储实现3.1 数据结构设计使用JSON格式存储对话记录每条记录包含{ timestamp: 2024-03-15 14:30:22, role: player|bot, content: 用户输入或AI回复, think_log: 模型思考过程(可选) }3.2 本地存储核心代码import json from datetime import datetime def save_conversation(role, content, think_logNone): record { timestamp: datetime.now().strftime(%Y-%m-%d %H:%M:%S), role: role, content: content, think_log: think_log } # 读取已有记录 try: with open(conversation_history.json, r) as f: history json.load(f) except: history [] # 添加新记录 history.append(record) # 保存更新 with open(conversation_history.json, w) as f: json.dump(history, f, indent2)3.3 对话记录加载def load_conversation(): try: with open(conversation_history.json, r) as f: return json.load(f) except: return []4. 像素风时间轴实现4.1 时间轴UI设计采用游戏存档界面风格关键CSS样式.pixel-timeline { border: 4px solid #2C2C2C; background-color: #FDF6E3; padding: 12px; margin: 8px 0; position: relative; } .timeline-entry { border-left: 4px solid #4D96FF; padding: 8px 12px; margin: 8px 0; background-color: rgba(255, 255, 255, 0.7); } .bot-entry { border-left-color: #6BCB77; } .timeline-date { color: #FFD700; font-weight: bold; margin-bottom: 4px; }4.2 Streamlit时间轴组件def show_timeline(): history load_conversation() st.markdown( style .pixel-timeline { border: 4px solid #2C2C2C; background-color: #FDF6E3; padding: 12px; margin: 8px 0; } /style , unsafe_allow_htmlTrue) with st.container(): st.markdown(div classpixel-timeline, unsafe_allow_htmlTrue) st.subheader(️ 冒险日志时间轴) for entry in history[-10:]: # 显示最近10条 entry_class timeline-entry bot-entry if entry[role] bot else timeline-entry st.markdown(f div class{entry_class} div classtimeline-date{entry[timestamp]}/div strong{大贤者 if entry[role] bot else 勇者}:/strong {entry[content]} /div , unsafe_allow_htmlTrue) st.markdown(/div, unsafe_allow_htmlTrue)5. 完整对话流程集成5.1 主界面代码def main(): # 像素风格CSS注入 with open(pixel_style.css) as f: st.markdown(fstyle{f.read()}/style, unsafe_allow_htmlTrue) # 标题和状态栏 st.title( 南北阁大冒险) st.markdown(---) # 显示时间轴 show_timeline() # 用户输入区域 user_input st.text_input(️ 勇者请输入你的指令:, keyinput) if user_input: # 保存玩家输入 save_conversation(player, user_input) # 生成AI回复 inputs tokenizer(user_input, return_tensorspt) outputs model.generate(**inputs, max_new_tokens2048) bot_response tokenizer.decode(outputs[0], skip_special_tokensTrue) # 提取思考日志如果有 think_log None if think in bot_response: think_log bot_response.split(think)[1].split(/think)[0] bot_response bot_response.replace(fthink{think_log}/think, ) # 保存AI回复 save_conversation(bot, bot_response, think_log) # 显示最新对话 st.experimental_rerun() if __name__ __main__: main()5.2 思考过程可视化def show_think_log(): history load_conversation() last_entry history[-1] if history else None if last_entry and last_entry[think_log]: st.markdown( div classpixel-timeline stylebackground-color:#2C2C2C; color:#FFF; h3 系统思考日志/h3 pre stylecolor:#FFD700;{}/pre /div .format(last_entry[think_log]), unsafe_allow_htmlTrue)6. 功能扩展与优化建议6.1 对话存档管理def save_snapshot(): history load_conversation() timestamp datetime.now().strftime(%Y%m%d_%H%M%S) with open(fconversation_snapshot_{timestamp}.json, w) as f: json.dump(history, f) st.success(f️ 冒险日志已存档为: conversation_snapshot_{timestamp}.json)6.2 性能优化技巧对话记录分块加载def load_conversation_chunk(start_idx, chunk_size10): history load_conversation() return history[start_idx:start_idxchunk_size]使用SQLite替代JSONimport sqlite3 def init_db(): conn sqlite3.connect(conversation.db) c conn.cursor() c.execute(CREATE TABLE IF NOT EXISTS history (timestamp TEXT, role TEXT, content TEXT, think_log TEXT)) conn.commit() conn.close()7. 项目总结通过本教程我们实现了一个完整的像素风格AI对话界面具有以下特点独特的视觉体验JRPG风格界面让AI对话变得生动有趣完整的历史记录所有对话自动保存到本地JSON文件直观的时间轴像游戏存档系统一样浏览历史对话思考过程可视化通过think标签展示模型推理逻辑下一步改进方向添加对话导出为Markdown功能实现多存档槽位管理增加像素风动画效果支持对话记录搜索过滤获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。