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](https://platform.openai.com/account/api-keys)"
        "[View the source code](https://github.com/streamlit/llm-examples/blob/main/Chatbot.py)"
        "[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/streamlit/llm-examples?quickstart=1)"

    
    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:
        st.chat_message(msg["role"]).write(msg["content"])
    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:
        
        st.chat_message(user_msg["role"]).write(user_msg["content"])
       
       
   
    if st.session_state.user_input:
        
     
        st.session_state.chat_history.append({"role":"user","content":user_input})
        
        st.chat_message("user").write(user_input)
        
        
        bot_reply = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=st.session_state.chat_history )
        
        msg = bot_reply.choices[0].message
        )
        st.session_state.chat_history.append(msg)
        st.chat_message("assistant").write(msg.content)
    
    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 = []

st.button('Clear',on_click=clear_chat_history)

Hope this helps!

2 Likes

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.