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
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?",
]
return random.choice(responses)
st.set_page_config(page_title="Simple Chat Bot")
st.title("Simple Chat Bot")
# Initialize chat history and waiting state in session_state
if "messages" not in st.session_state:
st.session_state.messages = []
if "waiting_for_response" not in st.session_state:
st.session_state.waiting_for_response = 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 and control its disabled state based on waiting_for_response
if not st.session_state.waiting_for_response:
prompt = st.chat_input("What is up?", disabled=st.session_state.waiting_for_response)
if prompt:
# 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)
# Set state to wait for assistant response
st.session_state.waiting_for_response = True
st.rerun() # Re-render the page to disable the input
# If waiting for assistant response, generate and display it
if st.session_state.waiting_for_response:
with st.spinner("Assistant is typing..."):
# Simulate response time
time.sleep(1) # Adjust the sleep time as needed
response = response_generator()
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": response})
# Display assistant response in chat message container
with st.chat_message("assistant"):
st.markdown(response)
# Reset the waiting state to re-enable input
st.session_state.waiting_for_response = False
st.rerun() # Re-render the page to enable the input
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?