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。

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

相关推荐
Allen Bright3 分钟前
【CSS-5】掌握CSS文本样式:从基础到高级技巧
前端·css
亚马逊云开发者10 分钟前
准确率从 19% 提升至 95%!文本审核模型优化的三个阶段实践(下)
人工智能
盛寒11 分钟前
词法分析和词性标注 自然语言处理
人工智能·自然语言处理
贩卖纯净水.11 分钟前
Webpack常见的插件和模式
前端·webpack·node.js
计算机集成_11 分钟前
具身智能之人形机器人核心零部件介绍
人工智能·经验分享·机器人
寻丶幽风16 分钟前
论文阅读笔记——Muffin: Testing Deep Learning Libraries via Neural Architecture Fuzzing
论文阅读·笔记·深度学习·网络安全·差分测试
brzhang19 分钟前
Flutter 调用原生代码,看这篇就够了:从零教你搭起通信的桥
前端·后端·架构
袁煦丞20 分钟前
知识管理的六边形战士Trilium Notes:cpolar内网穿透实验室第520个成功挑战
前端·程序员·远程工作
新智元23 分钟前
苹果 OS 全家桶 12 年最狠升级!AI 入侵一切,唯独 Siri 没更
人工智能·openai
我是初九23 分钟前
【李沐-动手学深度学习v2】1.Colab学习环境配置
人工智能·python·学习·colab