huggingface部署本地大模型DeepSeek-R1-Distill-Llama-70B使用streamlit构建交互式 Web 应用

文章目录

一、Streamlit介绍

Streamlit 是一个开源的 Python 库,专门用于快速构建和部署交互式 Web 应用程序,尤其适合数据科学和机器学习领域。以下是关于 Streamlit 的详细介绍:

核心功能

快速开发

Streamlit 允许开发者通过简单的 Python 脚本创建交互式应用,无需编写复杂的前端代码。例如,可以轻松显示文本、数据表格、图表,并添加用户交互控件。

数据可视化

Streamlit 支持多种数据可视化方式,包括与 Pandas、Matplotlib、Plotly 等库集成,能够快速展示数据和图表。

用户交互

提供了丰富的控件(如滑块、下拉菜单、输入框等),用户可以通过这些控件与应用进行交互。

布局管理

支持分栏、选项卡等布局方式,方便组织页面内容。

文件上传与处理

用户可以上传文件(如 CSV 文件),Streamlit 可以读取并处理这些文件。

多页面应用

Streamlit 支持通过 st.navigation 和 st.Page 创建多页面应用。

二、模型下载

python 复制代码
#模型下载
from modelscope import snapshot_download
model_dir = snapshot_download('deepseek-ai/DeepSeek-R1-Distill-Llama-70B')

三 、模型部署

使用huggingface接口并使用llamaindex的rag功能,增加本地知识库。

document加载本地知识库,query_engine开启单轮对话引擎,chat_engine开启多轮对话引擎。

python 复制代码
import streamlit as st
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.huggingface import HuggingFaceLLM

st.set_page_config(page_title="AI小助手", page_icon="🦜🔗")
st.title("AI小助手")


# 初始化模型
@st.cache_resource
def init_models():
    embed_model = HuggingFaceEmbedding(
      model_name="/mnt/ollama/deepseek/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
    )
    Settings.embed_model = embed_model

    llm = HuggingFaceLLM(
        model_name="/mnt/ollama/deepseek/DeepSeek-R1-Distill-Llama-70B",
        tokenizer_name="/mnt/ollama/deepseek/DeepSeek-R1-Distill-Llama-70B",
        model_kwargs={"trust_remote_code": True},
        tokenizer_kwargs={"trust_remote_code": True}
    )
    Settings.llm = llm

    #documents = SimpleDirectoryReader(input_files=["/home/defaultuser/soft/README_zh-CN.md"]).load_data()
    documents = SimpleDirectoryReader(input_files=["/root/data/jianguang.txt"]).load_data()
    index = VectorStoreIndex.from_documents(documents)

    query_engine = index.as_query_engine()

    return query_engine


# 检查是否需要初始化模型
if 'query_engine' not in st.session_state:
    st.session_state['query_engine'] = init_models()


def greet2(question):
    response = st.session_state['query_engine'].query(question)
    return response


# Store LLM generated responses
if "messages" not in st.session_state.keys():
    st.session_state.messages = [{"role": "assistant", "content": "你好,我是AI助手,有什么我可以帮助你的吗?"}]

    # Display or clear chat messages
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.write(message["content"])


def clear_chat_history():
    st.session_state.messages = [{"role": "assistant", "content": "你好,我是AI小助手,有什么我可以帮助你的吗?"}]


st.sidebar.button('Clear Chat History', on_click=clear_chat_history)


# Function for generating LLaMA2 response
def generate_llama_index_response(prompt_input):
    return greet2(prompt_input)


# User-provided prompt
if prompt := st.chat_input():
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.write(prompt)

# Gegenerate_llama_index_response last message is not from assistant
if st.session_state.messages[-1]["role"] != "assistant":
    with st.chat_message("assistant"):
        with st.spinner("Thinking..."):
            response = generate_llama_index_response(prompt)
            placeholder = st.empty()
            placeholder.markdown(response)
    message = {"role": "assistant", "content": response}
    st.session_state.messages.append(message)

四、效果展示

安装streamlit库,run上面代码

启动了三个URL,可以根据自己情况访问。

!在这里插入图片描述(https://i-blog.csdnimg.cn/direct/069ca4a4ddde472b8739327f40332d6f.png![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/0a04ca53ef774c619e5fbcafdd6a928f.png)

默认的话,是localhost,直接点击右边。open in brower。

然后就可以开启对话模式。

相关推荐
东方芷兰4 分钟前
Agent 技术摘要 02 —— 区块链、比特币、挖矿、ETF、比特币疯涨事件、以太坊、以太币、显卡荒事件
人工智能·笔记·python
万物智能信息科技5 分钟前
GPIO控制状态灯—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
人工智能·华为·开源·harmonyos·鸿蒙
像豆芽一样优秀7 分钟前
用 Codex + 阿里云 DataWorks MCP 实现数仓自动化
大数据·人工智能
FII工业富联科技服务12 分钟前
从台积电微通道散热看 AI 热管理:热量究竟如何从芯片走向机房?
人工智能·ai
恋猫de小郭12 分钟前
Flutter GSoC 2026 提案进度解读,补上 DevTools、FFI 和原生平台的关键缺口
android·前端·flutter
AIGCmagic社区20 分钟前
Show-Harness拆读,语义动作单元让VLM直接控机械臂,零样本跨任务89%
人工智能·aigc·具身智能·ai多模态
ZYJCSZKJ20 分钟前
GEO 服务技术能力评估模型:交付体系、内容架构与持续运维的工程对比
人工智能
尘世中一位迷途小书童20 分钟前
我为什么在 Windows 上做了一个翻译软件:SnapLingo
前端·人工智能·机器学习
Java后端的Ai之路22 分钟前
大模型LLM评估完全指南
开发语言·人工智能·python·llm·评估
志尊宝25 分钟前
Vue3 零基础每日笔记(029):插槽 slot 三连——默认、具名、作用域一次讲透
前端·javascript·vue.js·vue·前端开发