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 分钟前
Java基石--反射让你直捣黄龙
前端·spring boot·后端
静心问道20 分钟前
Idefics3:构建和更好地理解视觉-语言模型:洞察与未来方向
人工智能·多模态·ai技术应用
sheep888822 分钟前
AI与区块链Web3技术融合:重塑数字经济的未来格局
人工智能·区块链
奋进的孤狼29 分钟前
【Spring AI】阿里云DashScope灵积模型
人工智能·spring·阿里云·ai·云计算
AIGC_北苏34 分钟前
让UV管理一切!!!
linux·人工智能·uv
JosieBook2 小时前
【web应用】如何进行前后端调试Debug? + 前端JavaScript调试Debug?
前端·chrome·debug
LBJ辉2 小时前
2. Webpack 高级配置
前端·javascript·webpack
吕永强2 小时前
人工智能与环境:守护地球的智能防线
人工智能·科普
音元系统3 小时前
五度标调法调域统计分析工具
语言模型·自然语言处理·语音识别·输入法·语音分类
兮℡檬,3 小时前
房价预测|Pytorch
人工智能·pytorch·python