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.
To upload files, please first save the app
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
if "messages" not in st.session_state:
st.session_state.messages = []
# Disable input during response generation
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 prompt := st.chat_input("What is up?", disabled=input_disabled) or input_disabled:
# Add user message to chat history
if not input_disabled:
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
input_disabled = True
# Display assistant response in chat message container
with st.chat_message("assistant"):
st.write_stream(response_generator())
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": prompt})
# Re-enable input after the response is generated
st.rerun()
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?