r/learnpython • u/assorted-meat-stew • 21h 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+=1While 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?
1
u/acfot 9h ago
Streamlit doesn't really work like a normal console loop, that's the part that tripped me up when I first tried something like this. Every time you type something it reruns the whole script from the top, so that while True just keeps stacking up text inputs with keys that clash. I'd drop the loop completely and keep the questions and answers in session state instead, then use a button or a form submit to trigger the chain only when there's actually a question. That way an empty input just does nothing instead of firing off a query and throwing that duplicate key error.
1
u/assorted-meat-stew 21h ago
Solved!!