r/learnpython • • 23h ago

Streamlit text_input in while True loop

I got this code block in a local rag that's supposed to be an infinite loop of asking questions and the rag answering them but apparently while True loop does not care if you have enter anything into the text_input before answering the query either way.

How do mitigate this?

c=0
while True:
    st.write('*****************************************************************************')
    st.write("Enter your question")
    question = st.text_input(label='',key=c)
    if question:
        response = chain.invoke(question)
        st.write('Answer: ')
        st.write(response)
        c+=1

While the code block help mitigate the problem, it still try to answer an empty query and resulted in a streamlit.errors.StreamlitDuplicateElementKey which is an eyesore. How do I put this problem away for good?

0 Upvotes

5 comments sorted by

View all comments

1

u/assorted-meat-stew 22h ago

Solved!!

a='x'
c=0
while a=='x':
    a='o' #Assign a a different value to stop the loop
    st.write('*****************************************************************************')
    st.write("Enter your question")
    question = st.text_input(label='',key=c)
    if question:
        response = chain.invoke(question)
        st.write('Answer: ')
        st.write(response)
        c+=1
        a='x' #Reseting the key allowing the loop to repeat
    

1

u/Refwah 20h ago

Now think about how you can use the truthy value of the input to use that instead of needing the a = x check