Spaces:
No application file
No application file
| # streamlit_chatbot.py | |
| import streamlit as st | |
| import random | |
| import time | |
| st.set_page_config(page_title="Simple Chatbot", page_icon="🤖") | |
| # --- Session State Init --- | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [] | |
| # --- Helper Functions --- | |
| def simple_bot_response(user_input: str) -> str: | |
| """Very basic rule-based reply.""" | |
| user_input = user_input.lower() | |
| if "hello" in user_input or "hi" in user_input: | |
| return "Hi there! 👋 How can I help you?" | |
| elif "bye" in user_input or "goodbye" in user_input: | |
| return "Goodbye! Thanks for chatting." | |
| elif "name" in user_input: | |
| return "I'm a simple Streamlit bot—no name yet!" | |
| elif "time" in user_input: | |
| return f"The current time is {time.strftime('%H:%M:%S')}." | |
| else: | |
| replies = [ | |
| "Interesting... tell me more.", | |
| "I see. Could you elaborate?", | |
| "Thanks for sharing!", | |
| "That's cool!", | |
| "Hmm, I'm not sure how to respond to that.", | |
| ] | |
| return random.choice(replies) | |
| # --- UI --- | |
| st.title("Simple Streamlit Chatbot 🤖") | |
| st.caption("A tiny rule-based bot made with Streamlit") | |
| # --- Display Chat History --- | |
| for message in st.session_state.messages: | |
| with st.chat_message(message["role"]): | |
| st.markdown(message["content"]) | |
| # --- User Input --- | |
| if prompt := st.chat_input("Type your message..."): | |
| # 1. Save user message | |
| st.session_state.messages.append({"role": "user", "content": prompt}) | |
| with st.chat_message("user"): | |
| st.markdown(prompt) | |
| # 2. Generate & save bot response | |
| response = simple_bot_response(prompt) | |
| # Optional: mimic streaming effect | |
| with st.chat_message("assistant"): | |
| message_placeholder = st.empty() | |
| full_response = "" | |
| for chunk in response.split(): | |
| full_response += chunk + " " | |
| time.sleep(0.05) | |
| message_placeholder.markdown(full_response + "▌") | |
| message_placeholder.markdown(response) | |
| st.session_state.messages.append({"role": "assistant", "content": response}) |