Issue with defining session_state keys

Hi,

I am working on LLM web app where LLM api key and user file_upload does not retain values in the widgets. For more context see the video below:

Code:

if "api_key" not in st.session_state:
    st.session_state.api_key = ""

if 'user_db' not in st.session_state:
    st.session_state.user_db = None

app_configs, playground_tab = st.tabs(["Apps Configurations", "Query Data Playground"])

with app_configs:
    st.session_state.api_key = st.text_input(label=":key: Enter Gemini API Key :", type='password',
                                             key=st.session_state['api_key'])

    if st.session_state.api_key != '':
        try:
            is_valid = check_api_key(st.session_state.api_key)
            if is_valid:
                st.success("Gemini API Key is valid...!")
                genai.configure(api_key=st.session_state.api_key)
                # st.write('<h4 style="color: #fff;">:computer: Upload your database file',
                #          unsafe_allow_html=True)
                st.session_state.user_db = st.file_uploader(":open_file_folder: Upload your database file",
                                                            type=[".sqlite", '.db', '.sql'],
                                                            key=st.session_state['user_db'])
        except:
            st.error("Please pass a valid API key.")

Can anyone suggest what thing I am doing wrong here?
Fast responses are appreciated

Hi @Irfan,

It looks like you’re using a pattern like this:

if "foo" not in st.session_state:
    st.session_state.foo = ""

st.session_state.foo = st.text_input(..., key=st.session_state.foo)

What you want to do instead is simply this:

st.text_input(..., key="foo")

This will automatically create st.session_state.foo, and give it the current value of the widget. There is no need to pre-create the entry, or say key=st.session_state.something, just key="some string" is what you want.

You can read more about it here Widget behavior - Streamlit Docs

1 Like

I’ve been using Streamlit for about 16 months now and have made lots of apps, including some very complex things, and it only just now “clicked” with your comment that the “key” of the input widget directly corresponds to a value on the session_state object that I could utilize. Awesome!

1 Like

@blackary you mean to say I need to define key at widget level like this:

api_key = st.text_input(label=":key: Enter Gemini API Key :", type='password',
                                             key='api_key')
user_db = st.file_uploader(":open_file_folder: Upload your database file",
                                                            type=[".sqlite", '.db', '.sql'],
                                                            key='user_db')

Is this below code required to store variables in session_state ?

if "api_key" not in st.session_state:
    st.session_state.api_key = ""

if 'user_db' not in st.session_state:
    st.session_state.user_db = None

Hi @Irfan, it’s not necessary to do the “if foo not in session state” code if you’re using the key on a widget.

If you have a session state entry that you are making directly, not using a widget, and you want it to have a certain starting value when the app is first loaded, THEN you want to use that “if not in session state” code.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.