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
# Function to generate a random response
def get_response():
responses = [
"Hello there! How can I assist you today?",
"I'm here to help. What can I do for you?",
"Do you need assistance with something?",
"Hi! How can I make your day easier?",
]
return random.choice(responses)
st.title("Simple Chat Bot")
# Initialize session state variables
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
if "response_text" not in st.session_state:
st.session_state.response_text = ""
if "full_response" not in st.session_state:
st.session_state.full_response = ""
if "response_complete" not in st.session_state:
st.session_state.response_complete = True
# Display chat messages from history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Check for user input only if no response is being generated
if st.session_state.response_complete and (user_input := st.chat_input("Type your message here...", disabled=st.session_state.input_disabled)):
# Add the user's message to chat history
st.session_state.messages.append({"role": "user", "content": user_input})
# Display user's message in the chat
with st.chat_message("user"):
st.markdown(user_input)
# Prepare to generate the response
st.session_state.input_disabled = True # Disable the input
st.session_state.response_complete = False
st.session_state.response_text = ""
st.session_state.full_response = get_response() # Generate the bot's full response
st.rerun() # Rerun to start displaying the response incrementally
# Display the response incrementally if a response is being generated
if not st.session_state.response_complete:
# Split the response into words for incremental display
words = st.session_state.full_response.split()
next_word_index = len(st.session_state.response_text.split())
# Add the next word to the response text if there are remaining words
if next_word_index < len(words):
st.session_state.response_text += words[next_word_index] + " "
time.sleep(0.1) # Simulate a typing delay
st.rerun() # Rerun to display the next word
else:
# Once the response is complete, add it to the chat history
st.session_state.messages.append({"role": "assistant", "content": st.session_state.response_text})
st.session_state.input_disabled = False # Re-enable the input field
st.session_state.response_complete = True
st.rerun() # Rerun to refresh the chat input
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?