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。

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

相关推荐
vx_biyesheji00011 分钟前
豆瓣电影推荐系统 | Python Django 协同过滤 Echarts可视化 深度学习 大数据 毕业设计源码
大数据·爬虫·python·深度学习·django·毕业设计·echarts
禁默3 分钟前
基于CANN的ops-cv仓库-多模态场景理解与实践
人工智能·cann
禁默11 分钟前
【硬核入门】无需板卡也能造 AI 算子?深度玩转 CANN ops-math 通用数学库
人工智能·aigc·cann
敏叔V58717 分钟前
AI智能体的工具学习进阶:零样本API理解与调用
人工智能·学习
徐小夕@趣谈前端25 分钟前
拒绝重复造轮子?我们偏偏花365天,用Vue3写了款AI协同的Word编辑器
人工智能·编辑器·word
阿里云大数据AI技术26 分钟前
全模态、多引擎、一体化,阿里云DLF3.0构建Data+AI驱动的智能湖仓平台
人工智能·阿里云·云计算
陈天伟教授26 分钟前
人工智能应用- 语言理解:05.大语言模型
人工智能·语言模型·自然语言处理
池央28 分钟前
CANN GE 深度解析:图编译器的核心优化策略、执行流调度与模型下沉技术原理
人工智能·ci/cd·自动化
七月稻草人31 分钟前
CANN ops-nn:AIGC底层神经网络算力的核心优化引擎
人工智能·神经网络·aigc·cann
种时光的人31 分钟前
CANN仓库核心解读:ops-nn打造AIGC模型的神经网络算子核心支撑
人工智能·神经网络·aigc