介绍
Get started with Streamlit - Streamlit Docs
Streamlit apps 是经典的 CS 架构。 APP 的 server 是使用 python 实现的后端,APP 的 client 是通过浏览器访问的前端页面。当在本地部署时,server 与 client 都运行在本地电脑上。如果需要提供线上服务,server 与 client 则运行在不同的机器上
开发
命令行运行
使用 streamlit run
Once you've created your script, say your_script.py, the easiest way to run it is with streamlit run:
streamlit run your_script.py
As soon as you run the script as shown above, a local Streamlit server will spin up and your app will open in a new tab in your default web browser.
Pass arguments to your script
When passing your script some custom arguments, they must be passed after two dashes. Otherwise the arguments get interpreted as arguments to Streamlit itself:
streamlit run your_script.py [-- script args]
Streamlit 作为 Python module 运行
Another way of running Streamlit is to run it as a Python module. This is useful when configuring an IDE like PyCharm to work with Streamlit:
# Running python -m streamlit run your_script.py
# is equivalent to: streamlit run your_script.py
VS Code 调试
在 .vscode 目录下创建一个名为 launch.json 的文件,其中包含启动配置。该文件将如下所示
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Streamlit",
"type": "debugpy",
"request": "launch",
"module": "streamlit",
"args": [
"run",
"${file}"
]
}
]
}
在 VS code debug 中,执行对应的 "Python: Streamlit" 配置,则进入调试运行。
基本范式
单页面
Create an app - Streamlit Docs Streamlit is more than just a way to make data apps, it’s also a community of creators that share their apps and ideas and help each other make their work better. Please come join us on the community forum. We love to hear your questions, ideas, and help you work through your bugs — stop by today!
-
The first step is to create a new Python script. Let's call it
uber_pickups.py. -
Open
uber_pickups.pyin your favorite IDE or text editor, then add these lines:import streamlit as st import pandas as pd import numpy as np -
Every good app has a title, so let's add one:
st.title('Uber pickups in NYC') -
Now it's time to run Streamlit from the command line:
streamlit run uber_pickups.pyRunning a Streamlit app is no different than any other Python script. Whenever you need to view the app, you can use this command.
多页面
Overview of multipage apps - Streamlit Docs
Streamlit provides two built-in mechanisms for creating multipage apps. The simplest method is to use a pages/ directory. However, the preferred and more customizable method is to use st.navigation.
st.Page and st.navigation
If you want maximum flexibility in defining your multipage app, we recommend using st.Page and st.navigation. With st.Page you can declare any Python file or Callable as a page in your app. Furthermore, you can define common elements for your pages in your entrypoint file (the file you pass to streamlit run). With these methods, your entrypoint file becomes like a picture frame shared by all your pages.
You must include st.navigation in your entrypoint file to configure your app's navigation menu. This is also how your entrypoint file serves as the router between your pages.
pages/ directory
If you're looking for a quick and simple solution, just place a pages/ directory next to your entrypoint file. For every Python file in your pages/ directory, Streamlit will create an additional page for your app. Streamlit determines the page labels and URLs from the file name and automatically populates a navigation menu at the top of your app's sidebar.
Streamlit determines the page order in navigation from the filenames. You can use numerical prefixes in the filenames to adjust page order. For more information, see How pages are sorted in the sidebar. If you want to customize your navigation menu with this option, you can deactivate the default navigation through configuration (client.showSidebarNavigation = false). Then, you can use st.page_link to manually contruct a custom navigation menu. With st.page_link, you can change the page label and icon in your navigation menu, but you can't change the URLs of your pages.
聊天页面
Build a basic LLM chat app - Streamlit Docs
The advent of large language models like GPT has revolutionized the ease of developing chat-based applications. Streamlit offers several Chat elements, enabling you to build Graphical User Interfaces (GUIs) for conversational agents or chatbots. Leveraging session state along with these elements allows you to construct anything from a basic chatbot to a more advanced, ChatGPT-like experience using purely Python code.
In this tutorial, we'll start by walking through Streamlit's chat elements, st.chat_message and st.chat_input. Then we'll proceed to construct three distinct applications, each showcasing an increasing level of complexity and functionality:
-
First, we'll Build a bot that mirrors your input to get a feel for the chat elements and how they work. We'll also introduce session state and how it can be used to store the chat history. This section will serve as a foundation for the rest of the tutorial.
-
Next, you'll learn how to Build a simple chatbot GUI with streaming.
-
Finally, we'll Build a ChatGPT-like app that leverages session state to remember conversational context, all within less than 50 lines of code.
The Full Code
import streamlit as st
import random
import time
# Streamed response emulator
def response_generator():
response = random.choice(
[
"Hello there! How can I assist you today?",
"Hi, human! Is there anything I can help you with?",
"Do you need help?",
]
)
for word in response.split():
yield word + " "
time.sleep(0.05)
st.title("Simple chat")
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
# Display chat messages from history on app rerun
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Accept user input
if prompt := st.chat_input("What is up?"):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message in chat message container
with st.chat_message("user"):
st.markdown(prompt)
# Display assistant response in chat message container
with st.chat_message("assistant"):
response = st.write_stream(response_generator())
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": response})