首页 > 编程问答 >如何在streamlit python中流式传输由LLM生成的输出

如何在streamlit python中流式传输由LLM生成的输出

时间:2024-07-26 13:47:24浏览次数:9  
标签:python chatbot streamlit llama llama-cpp-python

代码:


from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain import PromptTemplate
from langchain_community.llms import LlamaCpp
from langchain.chains import RetrievalQA
import streamlit as st
from HtmlTemplates import bot_template , user_template , css
import torch

def set_prompt():
    custom_prompt_template = """[INST] <<SYS>>
    You are a trained to guide people about Indian Law. You will answer user's query with your knowledge and use context provided.
    Do not say thank you and tell you are an AI Assistant and be open about everything.
    Always complete the sentence you are generating
    <</SYS>>
    Use the following pieces of context to answer the users question.
    Context : {context}
    Question : {question}
    Answer : [/INST]
    """

    prompt = PromptTemplate(template=custom_prompt_template, input_variables=["context", "question"])
    return prompt


def retrieval_qa_chain(llm, prompt, db):
    qa_chain = RetrievalQA.from_chain_type(
        llm=llm,
        chain_type='stuff',
        retriever=db.as_retriever(search_kwargs={'k': 6}),
        chain_type_kwargs={'prompt': prompt}
    )

    return qa_chain

def qa_pipeline():
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    embeddings = HuggingFaceEmbeddings(model_name = 'multi-qa-mpnet-base-dot-v1' , model_kwargs = {'device': device})

    db = FAISS.load_local("vectorstore", embeddings , allow_dangerous_deserialization=True)

    llm = LlamaCpp(model_path = path,
                   temperature = temperature,
                   n_ctx = 2048,
                   n_batch = 128,
                   n_gpu_layers = -1,
                   max_tokens = max_tokens,
                   verbose = False )
    print(path)
    qa_prompt = set_prompt()

    chain = retrieval_qa_chain(llm, qa_prompt, db)
    return chain

def handle_user_input(user_question):
    with st.spinner("Generating response ..."):
            response = chain(user_question)
            response = response['result']
    st.write(bot_template.replace("{{MSG}}",response),unsafe_allow_html=True)
        

st.set_page_config(page_title = "Your personal Law ChatBot", page_icon = ":bot:")
st.write(css , unsafe_allow_html=True)

global chain, path, temperature, max_tokens

with st.sidebar:
    model = st.selectbox("Select Model :",("Llama2 7b (Faster)" , "Llama2 13b (Can answer complex queries)"))
    if model == 'Llama2 13b (Can answer complex queries)':
        path = "Models/llama-2-13b-chat.Q4_K_M.gguf"

    elif model == 'Llama2 7b (Faster)':
        path = "Models/llama-2-7b-chat.Q4_K_M.gguf"
    temperature = st.slider(label="Temperature",
              min_value=0.1,
              max_value=1.0,
              value=0.3,
              step=0.05
              )
    max_tokens = st.slider(label="Max Tokens",
              min_value=256,
              max_value=4096,
              value=1024,
              step=64
              )

if "chat_history" not in st.session_state:
  st.session_state.chat_history = []

st.header("Your personal Law ChatBot :books:")

user_question = st.chat_input("Ask a question :")
chain = qa_pipeline()

if user_question:
  st.write(user_template.replace("{{MSG}}",user_question),unsafe_allow_html=True)
  handle_user_input(user_question)

for chat in st.session_state.chat_history:
   st.write(user_template.replace("{{MSG}}",chat["User"]),unsafe_allow_html=True)
   st.write(bot_template.replace("{{MSG}}",chat["Bot"]),unsafe_allow_html=True)

当输出完全生成时才会显示。 有没有一种方法可以在生成它时在streamlit上进行流式传输??

我尝试了langchain中的StreamingStdCallbackHandler(),但它只在命令行中进行流式传输。 我想要得到类似ChatGPT的效果。 我希望它发生在流式网页中。


你可以使用 Streamlit 的 st.write 函数结合生成式回调来流式传输 LLM 的输出。

以下是如何修改代码以实现此目的的方法:

import streamlit as st
from HtmlTemplates import bot_template, user_template, css
import torch
from langchain.callbacks import StreamlitCallbackHandler

# ... 你现有的导入和函数 ...

def handle_user_input(user_question):
    st.write(user_template.replace("{{MSG}}", user_question), unsafe_allow_html=True)

    # 创建一个占位符,用于显示响应
    response_placeholder = st.empty()

    # 创建 StreamlitCallbackHandler 实例
    stream_handler = StreamlitCallbackHandler(response_placeholder)

    # 调用 LLM 时传递 stream_handler
    response = chain(user_question, callbacks=[stream_handler])

    # 获取完整响应(如果需要)
    full_response = response['result']

    # 可选:在流式传输完成后更新占位符
    response_placeholder.write(bot_template.replace("{{MSG}}", full_response), unsafe_allow_html=True)

# ... 你现有的 Streamlit 代码 ...

说明:

  1. 导入 StreamlitCallbackHandler: python from langchain.callbacks import StreamlitCallbackHandler

  2. 创建 StreamlitCallbackHandler: handle_user_input 函数中,创建一个 StreamlitCallbackHandler 实例,并传入 st.empty() 创建的占位符。 python stream_handler = StreamlitCallbackHandler(response_placeholder)

  3. 传递回调: 调用 chain 时,将 stream_handler 作为 callbacks 参数传递。 python response = chain(user_question, callbacks=[stream_handler])

现在,当 LLM 生成其响应时,它将通过 StreamlitCallbackHandler 流式传输到 Streamlit 应用程序,从而创建类似 ChatGPT 的体验。

标签:python,chatbot,streamlit,llama,llama-cpp-python
From: 78796331

相关文章

  • python mysql操作
    pipinstallmysql-connector-pythonimportmysql.connector#配置数据库连接参数config={'user':'your_username','password':'your_password','host':'your_host','database'......
  • Python 中的面向对象编程
    一.介绍在本文中,我们将使用Python中的类和对象来探索基本的OOP概念。面向对象编程(OOP)是一种强大的方法,可帮助开发人员组织代码,使其易于理解、重用和维护。Python是一种灵活的语言,可以很好地支持OOP概念。1.类和对象类是创建对象的蓝图。它定义了该类的对象将......
  • 学习资源系列之《Python深度学习基于PyTorch》
     前言近期应部分读者朋友的强烈邀请,希望推荐一本python深度学习实操的书籍。呐,今天为大家推荐小编偶然发现的这一本珍藏好书:《Python深度学习基于PyTorch》,文末附电子版获取方式《Python深度学习基于PyTorch》BriefIntroduction前言面对众多的深......
  • 如何使用Python实现语音转文字/字幕
    文章目录......
  • Python 教程(三):字符串特性大全
    目录专栏列表前言1.字符串基础2.字符串方法字符串查询字符串修改字符串切片3.字符串格式化旧式格式化(`%`操作符)`str.format()`方法f-string(Python3.6+)4.字符串编码5.Unicode和ASCII6.正则表达式7.字符串比较8.字符串连接9.字符串不可变性10.字符串的内......
  • python+flask计算机毕业设计新冠肺炎疫情人员统计及打卡系统(程序+开题+论文)
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景自新冠肺炎疫情爆发以来,全球公共卫生体系面临前所未有的挑战。疫情防控工作的高效开展,依赖于对人员流动、健康状况及疫情数据的精准掌握与......
  • python+flask计算机毕业设计基于智能匹配的体育场馆预约系统App(程序+开题+论文)
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景随着全民健身意识的日益增强,体育场馆作为民众参与体育活动的重要场所,其利用率与便捷性成为了社会关注的焦点。然而,传统的体育场馆预约方式......
  • Vonage 语音 API - 使用 python 出现错误
    我正在尝试使用vonage语音api模拟语音通话。我正在尝试使用python来做到这一点。我创建了一个.env文件并更新了应用程序id和私钥值的值,而不是路径(不确定从哪里获取它)。这是下面编写的代码:#!/usr/bin/envpython3importosfromos.pathimportjoin,dirname......
  • 数据清洗与预处理:使用 Python Pandas 库
    数据清洗与预处理:使用PythonPandas库1.简介数据清洗与预处理是数据科学和机器学习中必不可少的步骤。它涉及识别和处理原始数据中的错误、不一致和缺失值,以确保数据的质量和可靠性。Python的Pandas库提供了强大的工具,简化了数据清洗和预处理的过程。2.数据加载与探索......
  • 【Python】成功解决:`FileExistsError: [Errno 17] File exists: ‘xxx’`
    【Python】成功解决:FileExistsError:[Errno17]Fileexists:‘xxx’在Python编程中,处理文件和目录是常见的任务之一。然而,当我们尝试执行某些文件操作,如创建新文件或目录时,如果目标文件或目录已经存在,就可能会遇到FileExistsError异常。这个错误通常伴随着消息[Errno1......