Streamlit Button Behaviour on Click

Summary

Hi All
I have a button in my streamlit app that when clicked, calls the openai api to generate a response based on user inputs. My issue is that the response returned gets reset each time I try to change any of the user input fields (such as start date, end date).

Steps to reproduce

Code snippet:

if 'clicked' not in st.session_state:
    st.session_state.clicked = False

def click_button():
    st.session_state.clicked = True

st.button('Generate Response', on_click=click_button)
if st.session_state.clicked:
   st.write(openai)

If applicable, please provide the steps we should take to reproduce the error or specified behavior.

Expected behavior:

I expect that whenever I click the generate response button, only then the OpenAI function should be called.

Actual behavior:

The output from the previous call is cleared as soon as I change any of the user fields.

Debug info

  • Streamlit version: 1.26.0
  • Python version: 3.10.9
  • Conda
  • OS version: Windows 11
  • Browser version: Edge

hi @AMAN-9608 this is expected behavior of streamlit. If you want to persist the previous openai response, you may want to store it in the session state

2 Likes

Hi @AMAN-9608,

As @mliu had pointed out, you can store the generated response in the session state. Alternatively, you can embed the interaction widgets in an st.form (st.form - Streamlit Docs) and use this with st.form_submit_button which would not cause any app reruns upon adjusting the widgets.

1 Like

Hi @mliu mliu
Thanks for the response. Could you elaborate on how to store the response in st.session_state?
Should I store the response in a variable and then just say if ‘var’ not in session state?

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