The text input box does not clear automatically with each enter

# Initialize session state
if "user_input" not in st.session_state:
    st.session_state.user_input = ""
if "chat_history" not in st.session_state:
    st.session_state.chat_history = []

def clear_input():
    st.session_state.user_input = ""

# Main app
def app():
    user_input = st.text_input("", 
                            value=st.session_state.user_input, 
                            placeholder="Your AI assistant here! Please feel free to say something ...",
                            on_change=clear_input)
    if user_input:  # If there is user input (enter was pressed)
        if "context" not in st.session_state:
            st.session_state.context = get_initial_context()
            st.session_state.context.append({'role': 'user', 'content': user_input})
        else:
            st.session_state.context.append({'role': 'user', 'content': user_input})
        completion = get_completion_from_messages(st.session_state.context)
        st.session_state.context.append({'role': 'assistant', 'content': completion})
        st.session_state.chat_history.insert(0, ('assistant', completion))  # Insert at the beginning
        st.session_state.chat_history.insert(0, ('user', user_input))  # Insert at the beginning
        st.session_state.user_input = ""  # Clear the user input

I want the chatbot to automatically empty the input box after each input again and not interfere with the normal functionality. But it didn’t work and I still need to empty it manually. Hope someone knows, thanks

Hey @123_Gao,

Thanks for sharing your question! Please update your code snippet so that it’s runnable as-is (get_initial_context() isn’t defined).

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