in streamlit how to create a chat window using st.chat_input and when user gives answer automatically goes to next step
Assistant
User
i have list of 3 questions , for each question print question first using st.chat_message and wait for user answer after all 3 questions got answers execute st.rerun()
Assistant
User
how to move “assistant” messages to left and "user" messages to right
Assistant
In Streamlit, you can create a chat-like interaction using st.chat_input, which takes user input and can trigger certain actions based on that input. Here's a step-by-step guide on how to create a simple chat window that automatically processes user input and goes to the next step.
Step 1: Setting Up Streamlit
Make sure you have Streamlit installed:
bash
pip install streamlit
Step 2: Create the Chat Window
You can use st.chat_input to allow users to send messages. Below is an example of a Streamlit application that responds to user input and moves to the next step of conversation or process automatically as the user sends a chat message.
Example Code
python
import streamlit as st
# Initialize session state for conversation history
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
# Function to process user input and generate a response
def process_input(user_input):
# Here, you can define how to respond to the user
# This is just a placeholder for demonstration.
return f"You said: {user_input}"
# Main app function
def main():
st.title("Chat Window Example")
# Display chat history
for message in st.session_state.chat_history:
st.chat_message(message['role'], message['content'])
# Get user input
user_input = st.chat_input("Type your message here...")
if user_input:
# Save user message to the chat history
st.session_state.chat_history.append({"role": "user", "content": user_input})
# Process the user input to generate a response
response = process_input(user_input)
# Save the assistant's response to the chat history
st.session_state.chat_history.append({"role": "assistant", "content": response})
# Optionally, provide user feedback
st.success("Message sent!")
if __name__ == "__main__":
main()
Step 3: Run the Streamlit App
Save the code in a file named chat_app.py, then run the following command in your terminal:
bash
streamlit run chat_app.py
How It Works
Session State: We use st.session_state to keep track of the messages exchanged in the chat. This allows the chat history to persist across user interactions.
Chat Input: The st.chat_input function creates a text input box where users can type their messages. When the user submits a message (presses Enter), it is added to the chat history, and a response is generated.
Processing Input: The process_input function can be customized to handle user input differently. In the example, it simply echoes back what the user said.
Chat Messages: st.chat_message is used to display messages in the chat, distinguishing between user and assistant messages.
This structure forms a basic chat interface that processes user input and automatically updates without requiring additional user interaction beyond sending the message. You can expand upon this code to include more complex logic for responding to the user's inputs.
To create a Streamlit app that presents three questions sequentially and waits for the user's responses before executing st.rerun(), you can store the questions and user responses in the session state. After all responses are received, you can rerun the app to process the answers. Here’s how you can implement this:
Example Code
python
import streamlit as st
# Define your questions
questions = [
"What is your name?",
"How old are you?",
"What is your favorite hobby?"
]
# Initialize session state to track question index and responses if not already initiated
if 'question_index' not in st.session_state:
st.session_state.question_index = 0 # Tracks the current question index
st.session_state.responses = [] # Stores user responses
# Function to ask the next question
def ask_question():
if st.session_state.question_index < len(questions):
question = questions[st.session_state.question_index]
st.chat_message("assistant", question) # Display the question
return True # Indicates that there is a question to ask
else:
return False # No more questions
# Main app function
def main():
# Check if we are at the end of the questions
if st.session_state.question_index >= len(questions):
st.success("All questions answered!")
st.write("Your responses:")
for i, response in enumerate(st.session_state.responses):
st.write(f"{questions[i]}: {response}")
st.rerun() # Rerun the app to reset for new input if needed
# Determine if we need to ask the next question
if ask_question():
user_input = st.chat_input("Your answer here...") # Input field for answers
if user_input:
# Save response
st.session_state.responses.append(user_input)
st.session_state.question_index += 1 # Move to the next question
# Automatically rerun to show the next question
st.experimental_rerun()
else:
# If there are no more questions and responses collected
st.success("Thank you for your answers!")
if __name__ == "__main__":
main()
How It Works:
Session State Initialization: The question_index is initialized to track which question is currently being asked, while responses is used to store the user responses.
Asking Questions: The ask_question() function checks if there are more questions to ask. If so, it displays the next question using st.chat_message.
User Input: The input field (st.chat_input) is displayed after each question, allowing the user to enter their answers.
Response Handling: When the user submits an answer, that response is saved to st.session_state.responses, the question index is incremented, and st.experimental_rerun() is called to refresh the page and show the next question.
Completion Handling: After all questions have been answered, the app displays the summary of responses, along with a success message. You can adjust this part of the code to handle the output differently or to perform further actions based on the responses.
Run the App
Save the provided code in a file named sequential_questions.py and then run it using:
bash
streamlit run sequential_questions.py
This will create a sequential question-answer flow in your Streamlit app, where the app responds to user input dynamically and updates accordingly.
In Streamlit, the messaging style for chat interfaces can be customized using st.chat_message. However, as of my last knowledge update, Streamlit does not provide direct options to change the alignment of the messages (e.g., left alignment for assistant messages and right alignment for user messages) out of the box.
Fortunately, you can achieve a chat-like interface with left and right alignment using some creative use of st.markdown and HTML/CSS styling. Here's how you can do that:
Example Code with Custom Alignment
Below is an adjusted version of the previous example that styles assistant messages to the left and user messages to the right:
python
import streamlit as st
# Define your questions
questions = [
"What is your name?",
"How old are you?",
"What is your favorite hobby?"
]
# Initialize session state to track question index and responses if not already initiated
if 'question_index' not in st.session_state:
st.session_state.question_index = 0 # Tracks the current question index
st.session_state.responses = [] # Stores user responses
# Function to ask the next question
def ask_question():
if st.session_state.question_index < len(questions):
question = questions[st.session_state.question_index]
st.markdown(f"<div style='text-align: left; color: blue;'>{question}</div>", unsafe_allow_html=True) # Display assistant's question
return True # Indicates that there is a question to ask
else:
return False # No more questions
# Main app function
def main():
# Check if we are at the end of the questions
if st.session_state.question_index >= len(questions):
st.success("All questions answered!")
st.write("Your responses:")
for i, response in enumerate(st.session_state.responses):
st.write(f"{questions[i]}: {response}")
st.stop() # Stop execution until user refreshes or restarts
# Determine if we need to ask the next question
if ask_question():
user_input = st.chat_input("Your answer here...") # Input field for answers
if user_input:
# Save response
st.session_state.responses.append(user_input)
st.session_state.question_index += 1 # Move to the next question
# Display the user's message on the right
st.markdown(f"<div style='text-align: right; color: green;'>{user_input}</div>", unsafe_allow_html=True)
# Automatically rerun to show the next question
st.experimental_rerun()
else:
# If there are no more questions and responses collected
st.success("Thank you for your answers!")
if __name__ == "__main__":
main()
Details of the Code
Markdown with HTML: The st.markdown function allows us to insert HTML code. By using CSS styles in the HTML string, we can control the alignment. To display assistant messages on the left, we set text-align: left;, and for user messages on the right, we set text-align: right;.
Message Styling: The colors for assistant and user messages are set to blue and green respectively, which you can change as per your preference. This styling helps to visually differentiate the two types of messages.
Prevent Stopping Execution: After collecting the responses, instead of using st.rerun(), I've used st.stop() to avoid rerunning immediately after the last question. The users would ideally refresh or restart after all questions to see their collected answers.
Run the App
Save the code into a file named aligned_chat.py and run it:
bash
streamlit run aligned_chat.py
Note
Security Concerns: When using unsafe_allow_html=True, ensure that the content being rendered does not allow injecting malicious HTML/JavaScript for security reasons. Always sanitize user inputs if they will be displayed as HTML.
This approach creates a visually appealing chat interface where assistant messages appear on the left and user messages on the right.