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。

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

相关推荐
Dawson Zhu30 分钟前
【模型量化⑦】W4A8与GPTQ-Int4:极限压缩与MLC-LLM部署实战
人工智能·语言模型·架构·aigc·agi
zhanlang021743 分钟前
HTML 零基础入门到企业实战【第八章 8.5】画布 canvas、SVG 矢量图形基础入门
前端·html
千寻技术帮1 小时前
50055_基于AI的互帮互助小程序(源码+文档+数据库脚本+部署教程)
数据库·人工智能·小程序·毕业设计·springboot·课程设计
天树星智源1 小时前
KV 剪枝的同一个误差,模型确定时只改 1.4% 的 token,不确定时改 65%:接上不确定性,AIME25 端到端快 1.27 倍
人工智能·大模型
AI英德西牛仔1 小时前
PC 用户的效率革命:腾讯元宝导出 Word 指令与“AI 导出鸭”的底层逻辑
人工智能·word·excel·deepseek·ai导出鸭
星云_byto2 小时前
CSS面试题
前端·css
zhanlang02172 小时前
HTML 零基础入门到企业实战全套教程【连载 8.4】HTML5 新增表单属性与表单控件
前端·html·html5
Flynn Liang2 小时前
多智能体协同不再复杂:Redis Stream 消费者组、幂等与故障恢复
数据库·人工智能·redis·缓存·ai agent·智能体
科研邪修法10 小时前
PDF新增页面文字与文本批注怎么区分?以双版本培训讲义为例
前端·css·pdf
VIP_CQCRE10 小时前
GPT Image 2.6 商品图换背景后悬浮?接触阴影、透明区域与反射验收
图像处理·人工智能·ai·电商