Streamlit turns a Python script into a web app, with no HTML or JavaScript: write st.button and a button appears, write st.chat_input and you have a chat box. It does it with one simple rule: whenever someone clicks, types or moves a slider, Streamlit runs your whole script again, from the first line to the last. That rule makes it quick to start, and it explains nearly every surprise that follows: counters stuck at one, chatbots that forget, apps that take seconds to respond to a click. Your script reruns on every interaction: keep what must survive in session state, and cache what’s slow.
A script that draws a page#
Save a script as app.py and run streamlit run app.py. Streamlit starts a small web server on your computer (at localhost:8501 by default) and opens it in your browser. Each st. call adds something to the page, in order: st.write some text, st.button a button, st.chat_message a speech bubble. Widgets also give you their value: st.button returns True or False, st.chat_input the message someone just sent, or None.
Then the rule. Streamlit’s documentation puts it plainly: when something on the screen must change, it reruns your entire Python script from top to bottom, whenever you change the code and whenever someone uses a widget. There’s no separate “handle the click” function. The click is just a value the script sees on the next run.
Every click runs everything#
Here’s the smallest app with a problem: a counter. It sets count to 0, adds one if the button was clicked, and shows the count.
Predict first
You open the counter app and click “Add one” three times. What does it show?
Every ordinary variable starts from scratch on every run. st.session_state doesn’t: it’s a dictionary that Streamlit keeps between runs, one for each browser tab, so the counter with session state counts properly and its chatbot remembers. Open it in a new tab and you start again with an empty one. The last app shows a subtler trap. st.button is True only on the run caused by its click, so when you click “Train model”, the script reruns, “Load data” is now False, and the block holding “Train model” never runs at all. Anything that has to outlast one run, like a conversation or a step someone finished, belongs in st.session_state.
Slow things: cache them#
If every interaction reruns everything, it reruns the slow parts too. We measured a real Streamlit app that does what many AI apps do: a help-centre chat that loads two models, an embedding model and a small chat model (SmolLM2-360M-Instruct), embeds 50 help articles, and answers questions from the closest ones. On a server CPU, loading the models took 0.5 s, embedding the articles 0.36 s, searching and answering 4.5 s, and the rest of the script 9 ms.
Predict first
The app has a slider for how many articles an answer uses. With plain functions, how long does the page take to respond when someone moves it?
Without the caches, every run loads the models and embeds the articles again, whatever caused it: a question, a slider, a new visitor. With them, that work happens once for the whole server. Streamlit has two caches, and the difference matters. st.cache_resource is for things like models and database connections: everyone shares the same object, without copies. st.cache_data is for results, such as a table you loaded or a long calculation: each call gets its own copy, so one visitor changing it can’t affect another. Both remember results by the function’s code and the values you pass in, so calling it with new values runs it again. Wrap model loading in @st.cache_resource and slow data work in @st.cache_data, or every click pays for it again.
A chat app in 25 lines#
Both lessons in one app: the model behind @st.cache_resource, the conversation in session state. Free and local (pip install streamlit transformers torch), run with streamlit run app.py. The second file uses Streamlit’s own tester to send two messages and print the conversation, which is how we checked it:
# app.py
import streamlit as st
from transformers import pipeline
st.title("Ask me anything")
@st.cache_resource # load once; every rerun and every visitor shares it
def load_model():
return pipeline("text-generation", model="HuggingFaceTB/SmolLM2-360M-Instruct")
chat = load_model()
if "messages" not in st.session_state: # survives reruns: one per browser tab
st.session_state.messages = []
for m in st.session_state.messages:
st.chat_message(m["role"]).write(m["content"])
if prompt := st.chat_input("Your question"):
st.session_state.messages.append({"role": "user", "content": prompt})
st.chat_message("user").write(prompt)
out = chat(st.session_state.messages, max_new_tokens=60, do_sample=False)
answer = out[0]["generated_text"][-1]["content"]
st.session_state.messages.append({"role": "assistant", "content": answer})
st.chat_message("assistant").write(answer)
# test_app.py: run with python test_app.py
from streamlit.testing.v1 import AppTest
at = AppTest.from_file("app.py", default_timeout=120).run()
for question in ["What is the capital of France?", "And what is the capital of Italy?"]:
at.chat_input[0].set_value(question).run()
for m in at.session_state.messages:
print(f"{m['role']:>9}: {m['content']}")
# user: What is the capital of France?
# assistant: The capital of France is Paris.
# user: And what is the capital of Italy?
# assistant: The capital of Italy is Rome.The second answer only works because the first exchange is still in st.session_state.messages and goes back to the model with the new question. To share the app, push it to GitHub and deploy it free on Streamlit Community Cloud, or create a Hugging Face Space and choose Streamlit as its SDK.
What to remember
- Streamlit reruns your whole script, top to bottom, every time someone uses a widget; ordinary variables start from scratch each time.
- Keep anything that must survive between runs, like a conversation, in st.session_state, one per browser tab.
- Wrap slow loading in @st.cache_resource (models, connections) and slow computations in @st.cache_data, or every click repeats them.