Hey everyone! I could be missing something simple but I am following the documentation on how to create a chat bot but everytime I try to initialize chat history I get this error:
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
If applicable, please provide the steps we should take to reproduce the error or specified behavior.
Expected behavior:
web pg app to load
Actual behavior:
receiving error: AttributeError: st.session_state has no attribute āmessagesā. Did you forget to initialize it? More info: Add statefulness to apps - Streamlit Docs
Debug info
Streamlit version: (1.27.2)
Python version: (3.10.1)
VS code
OS version: Sonoma Ver 14
Browser version:
Requirements file
only streamlit is required, using nothing else atm
Not sure what a requirements file is? Check out this doc and add a requirements file to your app.
Links
no repo yet, just playing around.
Additional information
If needed, add any other context about the problem here.
import streamlit as st
st.title("Echo Bot")
# 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"])
# React to user input
if prompt := st.chat_input("What is up?"):
# Display user message in chat message container
st.chat_message("user").markdown(prompt)
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
response = f"Echo: {prompt}"
# Display assistant response in chat message container
with st.chat_message("assistant"):
st.markdown(response)
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": response})
That is so bizarre. Does it happen if you switch to a different Streamlit version too? Iām wondering if I can reproduce if I update my computer to Sonoma
Did you forget to read the full error message, maybe? In my case, I accidentally tried to run the streamline app with python app.py, but you need to use streamline run app.py.
You should be promoted about this, if you accidentally did the same. In my case it said:
2023-10-24 09:00:23.842 Session state does not function when running a script without `streamlit run`
(...)
AttributeError: st.session_state has no attribute "messages". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization
The confusion was that the streamlin run āwarningā came at the very top of the log, whereas the final error came much later, making a bit challenging to debug.
@dilln - Could you please try run with streamlit cli. For example - **streamlit run main.py**. I got the same error while I was trying to run app with python main.py command.