A Streamlit app reruns its Python script from top to bottom whenever a user interacts with it. Ordinary variables are reset, but `st.session_state` keeps values across reruns. That lets a chat app retain its messages when someone sends a new one. section 11.2.1
Initialize a value only if its key is missing. For a chatbot, `if "messages" not in st.session_state: st.session_state.messages = []` creates the history once; later reruns reuse it. Store other values there when they need to survive an interaction. section 11.2.2 section 11.2.3
import streamlit as st
st.title("Session State Explorer")
# Initialize a counter
if "counter" not in st.session_state: #1
st.session_state.counter = 0
# Display the counter
st.write(f"Counter value: {st.session_state.counter}")
# Buttons to modify the counter
col1, col2, col3 = st.columns(3)
with col1:
if st.button("Increment"): #2
st.session_state.counter += 1
st.rerun()
with col2:
if st.button("Decrement"):
st.session_state.counter -= 1
st.rerun()
with col3:
if st.button("Reset"):
st.session_state.counter = 0
st.rerun()
# Show all session state contents
st.divider()
st.subheader("Current Session State:")
st.write(dict(st.session_state))
Try the counter: each button changes a value in session state, then reruns the app. The displayed value persists even though the script runs again. section 11.2.2
Session context is not permanent storage. It resets when the browser tab closes, the page refreshes, or the Streamlit server restarts. Each user has an independent session state. section 11.2.4
In a chatbot, stored messages supply the conversation history displayed on each rerun. The language model does not remember earlier exchanges on its own: the app sends it messages from that history. It can send a trimmed history to stay within the model’s context window while continuing to display the full history to the user. section 11.9 section 11.7
