import streamlit as st import random import time # --- CONFIGURATION --- st.set_page_config( page_title="Simple Streamlit Chatbot", page_icon="🤖", layout="centered" ) # --- INITIAL STATE --- if "messages" not in st.session_state: st.session_state.messages = [] if "bot_index" not in st.session_state: st.session_state.bot_index = 0 # --- HELPER FUNCTIONS --- def simple_bot_response(user_text: str) -> str: """A very naive rule-based responder.""" user_text = user_text.lower().strip() if any(k in user_text for k in ("hello", "hi", "hey")): return "Hello! How can I help you today?" elif "bye" in user_text: return "Goodbye! Have a great day." elif "name" in user_text: return "I'm a Streamlit bot, here to chat." elif "age" in user_text: return "I was born when you clicked 'Run'." else: replies = [ "Interesting... tell me more.", "I see.", "Could you elaborate on that?", "Thanks for sharing!", "I'm not sure I follow." ] # Cycle through replies deterministically reply = replies[st.session_state.bot_index % len(replies)] st.session_state.bot_index += 1 return reply # --- UI --- st.title("🤖 Simple Chatbot") st.caption("Powered by Streamlit and a few if-statements.") # --- CHAT HISTORY --- for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # --- CHAT INPUT --- if prompt := st.chat_input("Type your message here..."): # Display user message with st.chat_message("user"): st.markdown(prompt) st.session_state.messages.append({"role": "user", "content": prompt}) # Simulate bot typing with st.chat_message("assistant"): message_placeholder = st.empty() full_response = "" # Get bot response bot_reply = simple_bot_response(prompt) # Fake typing animation for chunk in bot_reply.split(): full_response += chunk + " " time.sleep(0.05) message_placeholder.markdown(full_response + "▌") message_placeholder.markdown(full_response) # Append bot message to history st.session_state.messages.append({"role": "assistant", "content": full_response})