I want to create a simple streamlit app that offers a chat bot. When I input to the chat bot, while the chat bot is thinking for a response, disable the input field. Once a response if displayed, allow for user input again.
Drop files here
or click to upload
import streamlit as st
import random
import time
# Streamed response emulator
def response_generator():
responses = [
"Hello there! How can I assist you today?",
"Hi, human! Is there anything I can help you with?",
"Do you need help?",
]
response = random.choice(responses)
for word in response.split():
yield word + " "
time.sleep(0.1)
st.title("Simple Chat Bot")
# Initialize chat history and input disabled status in session state
if "messages" not in st.session_state:
st.session_state.messages = []
if "input_disabled" not in st.session_state:
st.session_state.input_disabled = False
# 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"])
# Accept user input if input is not disabled
if prompt := st.chat_input("What is up?", disabled=st.session_state.input_disabled):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message in chat message container
with st.chat_message("user"):
st.markdown(prompt)
# Disable chat input during response generation and rerun to apply changes
st.session_state.input_disabled = True
st.rerun()
# Generate response if input is disabled
if st.session_state.input_disabled:
with st.chat_message("assistant"):
response_text = ""
for chunk in response_generator():
response_text += chunk
st.markdown(response_text) # Display response incrementally
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": response_text})
# Re-enable input after response generation and rerun to refresh input state
st.session_state.input_disabled = False
st.rerun()
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?