【小笔记】streamlit使用笔记

1.streamlit是什么,为什么要用它?
一句话,这个东西是一个python的可视化库,当你想要给你的程序添加个web界面,而又不会或不想用前端技术时,你就可以考虑用它。
 类似的可视化库还有下面这几个,对比如下:
 
 参考:
 Python 可视化 web 神器:streamlit、Gradio、dash、nicegui;低代码 Python Web 框架:PyWebIO
2.安装及版本要求:
安装:
 pip install streamlit
以下辅助库也可以安装:
 pip install pyecharts
 pip install streamlit_echarts
特别注意:streamlit最新版要求python >= 3.8
3.一个问答demo
教程参考:小白也能轻松搞定:用几行代码实现强大的问答机器人!
创建:
 demo.py
import streamlit as st
def display_existing_messages():
    if "messages" not in st.session_state:
        st.session_state["messages"] = []
    for message in st.session_state["messages"]:
        with st.chat_message(message["role"]):
            st.markdown(message["content"])
def add_user_message_to_session(prompt):
    if prompt:
        st.session_state["messages"].append({"role": "user", "content": prompt})
        with st.chat_message("user"):
            st.markdown(prompt)
#
def generate_assistant_response(query):
    # add_user_message_to_session 显示消息的时候做了处理,所以这里不需要再次添加最新提问
    print('history-->')
    history = st.session_state["messages"]
    print(history)
    with st.chat_message("assistant"):
        message_placeholder = st.empty()
        full_response = ""
        for response in client.chat.completions.create(
                model=model,
                temperature=0,
                messages=history,
                stream=True,
        ):
            try:
                full_response += response.choices[0].delta.content
            except Exception as e:
                print("")
            message_placeholder.markdown(full_response + "▌")
        message_placeholder.markdown(full_response)
        st.session_state["messages"].append(
            {"role": "assistant", "content": full_response}
        )
    return full_response
def hide_streamlit_header_footer():
    hide_st_style = """
            <style>
            #MainMenu {visibility: hidden;}
            footer {visibility: hidden;}
            header {visibility: hidden;}
            #root > div:nth-child(1) > div > div > div > div > section > div {padding-top: 0rem;}
            </style>
            """
    st.markdown(hide_st_style, unsafe_allow_html=True)
def main():
    st.title("问答机器人")
    st.write(
        "我的第一个专属机器人,它可以回答你的问题,也可以和你聊天。"
    )
    hide_streamlit_header_footer()
    display_existing_messages()
    query = st.chat_input("你可以问我任何你想问的问题")
    if query:
        print(query)
        add_user_message_to_session(query)
        # response = generate_assistant_response(query)
        # print(response)
if __name__ == "__main__":
    main()
 
启动:
 streamlit run demo.py

其它问答系统界面参考示例:
 1.【Langchain+Streamlit】打造一个旅游问答AI
 
2.当科技遇上神奇:用Streamlit打造定制AI问答界面
 
4.stream包含些什么组件?
推荐:
 1.实用篇 | 一文快速构建人工智能前端展示streamlit应用
 2.python库streamlit学习笔记
暂时就先记录这些,后面使用深入后再更新…(2024.5.10)













![Python 机器学习 基础 之 监督学习 [朴素贝叶斯分类器] / [决策树] 算法 的简单说明 / [graphviz] 绘制决策树](https://img-blog.csdnimg.cn/direct/c9d55ea9fb5c46469b4b4263eedf383f.png)





