Session state and button in streamlit

Summary

I want to display the chat summary when the end chat and summarize button is clicked. Iโ€™m not getting any output on clicking the button.

Steps to reproduce

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

        #@st.cache_data(show_spinner=False)
        def onClickFunction():
            st.session_state.click = True
            st.session_state.out = chat_summary(agree_sumary=agree_sumary, chat_files=chat_files, messages = messages)

        runButton = st.button("End chat and summarize", on_click=onClickFunction)

        if st.session_state.click:
            st.write("out", st.session_state.out)

Expected behavior:

The chat summary should be output on clicking the button.

Hey @stuser,

Thanks for sharing this question. Can you edit your post to include a runnable code snippet? Itโ€™s hard to say exactly whatโ€™s going wrong without seeing what chat_summary() is doing.

A simpler way to create a chat history and display it when someone clicks a button would be the following:

  1. At the beginning of your script, initialize the chat history:
if "messages" not in st.session_state:
    st.session_state.messages = []
  1. After the user enters a message, append that message to the message history:
    st.session_state.messages.append({"role": "user", "content": prompt})
  1. In your on_click function, iterate through the message history and display each message:
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

You might also find our tutorial on building conversational apps helpful.