Session state and conversation memory
Real apps need memory that survives reloads, multiple users, and budget caps. Streamlit gives you the first tools to learn this properly.
A diary on your nightstand vs a journal app that syncs. Both are memory. One is fragile, one is durable.
st.session_state lives in memory per browser tab. Refresh = gone. For real persistence:
- Save chat history to a file (
json) keyed by user. - Save to a database (Supabase, SQLite, Firebase).
- Use Streamlit's
st.experimental_userfor SSO-style auth.
Memory strategies from Module 3.4 (full, window, summary, retrieval) all apply here.
Add a 10-message rolling window:
MAX_HISTORY = 20 # 10 user + 10 assistant
if len(st.session_state.messages) > MAX_HISTORY + 1: # +1 for system
st.session_state.messages = (
[st.session_state.messages[0]] # keep system
+ st.session_state.messages[-MAX_HISTORY:]
)
Add reset and export:
col1, col2 = st.sidebar.columns(2)
if col1.button("Clear"):
st.session_state.messages = []
st.rerun()
if col2.download_button("Export", data=str(st.session_state.messages), file_name="chat.json"):
pass
Quick recall
3 prompts · think before you flip
Prompt 1 of 3
What is the scope of `st.session_state`?
Quiz time
1 question · tap an answer to check it
1. To persist chat across refreshes you need
Finished lesson 6.4?
Mark complete to update your module progress and unlock the streak.
Loading