St.button not working as intended

Hi all,
I am trying to implement streamlit st.button in order to clear chat history. but I realize that my chat history is getting cleared even before i click the button even though I have specified on_click. Below is my code.
import streamlit as st
import requests
import os
import json
from flask import Flask
import openai

class App():

def run(self):
    st.set_page_config(page_title="Cloud chatbot")
    with st.sidebar:
        openai_api_key = st.text_input("OpenAI API Key", key="chatbot_api_key", type="password")
        "[Get an OpenAI API key]("
        "[View the source code]("
        "[![Open in GitHub Codespaces](]("

    openai.api_key = openai_api_key
    if "messages" not in st.session_state:
        st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you?"}]
    for msg in st.session_state.messages:
    user_input = st.chat_input(
                        "ask a question", key="user_input")
    if 'chat_history' not in st.session_state:
        st.session_state["chat_history"] = []
    for user_msg in st.session_state.chat_history:
    if st.session_state.user_input:
        bot_reply = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=st.session_state.chat_history )
        msg = bot_reply.choices[0].message
    reset_butt = st.button('Clear',on_click=st.session_state.chat_history.clear())

Hi @Damian_Esene

It seems that youโ€™re assign a session state variable to the on_click parameter which may be the origin of the error.

It is advised to assign a custom function that contains the cleared session state variable to the on_click parameter:

def clear_chat_history():
    st.session_state.chat_history = []


Hope this helps!


Thank you. That solved my issue

1 Like

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