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 response text
def get_response():
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.title("Simple Chat Bot")
# Initialize chat history and control flags 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
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 response generation is complete
if st.session_state.response_complete and (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
with st.chat_message("user"):
st.markdown(prompt)
# Initialize response generation process
st.session_state.input_disabled = True
st.session_state.response_complete = False
st.session_state.response_text = ""
st.session_state.full_response = get_response() # Generate the full response
st.rerun() # Rerun to start incremental response display
# Display the response incrementally if response generation is in progress
if not st.session_state.response_complete:
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 typing delay
st.rerun() # Rerun to display the next word
else:
# Complete the response, add it to message history
st.session_state.messages.append({"role": "assistant", "content": st.session_state.response_text})
st.session_state.input_disabled = False
st.session_state.response_complete = True
st.rerun() # Rerun to re-enable the input
# Display the assistant's response incrementally
if st.session_state.response_text:
with st.chat_message("assistant"):
st.markdown(st.session_state.response_text)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?