Duplicate keys error and I don't know why

Can someone help me understand why this simple conversational interface won’t work?

import streamlit as st


# Main Streamlit app code
def main():
    # Set page title and heading
    st.title("Conversational Interface")
    st.header("Chat with the Chatbot")

    # Initialize variables
    user_input = ""
    chat_history = []
    counter = 1

    while user_input.lower() != "bye":
        # User input section
        user_input = st.text_input(f"User Input {counter}", key=f'{counter}')

        if st.button("Submit", key=counter) or st.session_state.get('enter_pressed'):
            if user_input:
                # Store user input in chat history
                chat_history.append(user_input)

                # Display chat history
                st.subheader("Chat History")
                for i, chat in enumerate(chat_history):
                    st.text(f"Chat {i + 1}: {chat}")

                # Clear user input
                user_input = ""
                counter += 1
                st.session_state['enter_pressed'] = False

        # Capture the Enter key press
        if user_input:
            st.session_state['enter_pressed'] = st.session_state.get('enter_pressed', False) or st.session_state.get(
                'last_input') != user_input
            st.session_state['last_input'] = user_input


# Run the app
if __name__ =

= ‘main’:
main()

Hi @amir650,

Thanks for posting!

From a quick glance, this is the first point of failure in the code:

if __name__ == "main":
    main()

add the following in the if statement at the end:

if __name__ == "__main__":
    main()

Since you’re building conversational bots, I recommend you look into our recent release → Build conversational apps - Streamlit Docs

Example code here for reference to achieve similar output as the one you have:

import streamlit as st

st.title("Echo Bot")

# Initialize chat history
if "messages" not in st.session_state:
    st.session_state.messages = []

# Display chat messages from history on app rerun
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

# React to user input
if prompt := st.chat_input("What is up?"):
    # Display user message in chat message container
    st.chat_message("user").markdown(prompt)
    # Add user message to chat history
    st.session_state.messages.append({"role": "user", "content": prompt})

    response = f"Echo: {prompt}"
    # Display assistant response in chat message container
    with st.chat_message("assistant"):
        st.markdown(response)
    # Add assistant response to chat history
    st.session_state.messages.append({"role": "assistant", "content": response})