DuplicateWidgetID when used in a Recursive call/loop etc


I want to create a chatbot similar from the structure like the original chat gpt.

Steps to reproduce

Code snippet:

I added here the code to of the file where I have streamline structuring


If applicable, please provide the steps we should take to reproduce the error or specified behavior.

Expected behavior:

I want to create a chatbot similar from the structure like the original chat gpt. I want first to be the title than the chat history and an input field for the user input.

Actual behavior:

I know that I have to add new keys to the widgets but I call the function recursively whenever I click on submit. So I can do different key but than it generates a whole new field.

Additional information

Help is kindly appreciated :slight_smile:

The fundamental structure of Streamlit is that the whole page is going to reload with every interaction from the user. In your case, if someone clicks submit, you will render the two input widgets on screen then the recursion is going to try and render those same two widgets again and you will get the duplicate widget id error.

In cases where you actually intend to create new widgets with each loop, you would need to use unique keys for the widgets in each loop. However, in this case that doesn’t actually appear to be what you intend so you need to change your workflow.

  1. You will need to save your chat history into an object in session state to prevent it from re-initializing with every interaction.
  2. You don’t want recurse your main logic like that. The “reload with every interaction” structure of Streamlit is going to be your means of iterating, not recursion.

Here is a simplified example to illustrate the logic of Streamlit:

import streamlit as st

if 'chat' not in st.session_state:
    st.session_state.chat = [('A','Hello.')]

def submit():
    st.session_state.chat.append(('A','Some response.'))
    # Clear the text input widget for convenience
    st.session_state.B = ''

for entry in st.session_state.chat:
    st.write(f'{entry[0]}: {entry[1]}')

st.text_input('B\'s Response', key='B', on_change=submit)

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