Search code examples
pythonstreamlit

Streamlit session variable does not persist on chat


I am trying to implement a chat with Streamlit, where I need to keep a counter of words being exchanged, essentially starting from this.

So I initialize a session variable at the beginning of the main() function as follows:

st.session_state['words'] = 0

After the question has been asked and response has been provided, i.e. at the end of the st.chat_input block, after the spinner block, I calculate the count of words in the question and response (wd_cnt). I increment the count and write it:

st.session_state.words += wd_cnt
st.write(st.session_state.words)

The problem is: the counter is not incremented. The write statement above always outputs the value of wd_cnt, as if st.session_state.words was reset every time.

What am I missing?


Solution

  • Just to clarify; you do remember to have the initialisation inside a if statement so that it only runs on initialization? Streamlit re-runs your mainfile each time a change happens, and thus you would set word to zero if it is not inside an if statement.

    Typical implementation is:

    if "words" not in st.session_state.keys():
        st.session_state["words"] = 0
    

    Here is a simple example of how a general counter looks.

    import streamlit as st
    
    if "words" not in st.session_state.keys():
        st.session_state["words"] = 0
    
    def increase_count():
        st.session_state["words"] += 1
    
    st.button("Increase count", on_click=increase_count)
    
    
    st.write(st.session_state["words"])