Spaces:
Runtime error
Runtime error
| # streamlit_chatbot.py | |
| # A minimal self-contained Streamlit chatbot example. | |
| # Run with: streamlit run streamlit_chatbot.py | |
| import random | |
| import streamlit as st | |
| # --- Configure the page --- | |
| st.set_page_config( | |
| page_title="Minimal Chatbot", | |
| page_icon="🤖", | |
| layout="centered", | |
| ) | |
| # --- Session-state helpers --- | |
| SESSION_KEY = "messages" | |
| def init_session(): | |
| """Initialize the chat history in session state.""" | |
| if SESSION_KEY not in st.session_state: | |
| st.session_state[SESSION_KEY] = [] | |
| def append_message(role: str, content: str): | |
| """Add a message to the session state.""" | |
| st.session_state[SESSION_KEY].append({"role": role, "content": content}) | |
| # --- Bot logic (stub) --- | |
| def bot_response(user_input: str) -> str: | |
| """Mock LLM: echo the user or give a canned answer.""" | |
| user_input = user_input.strip().lower() | |
| if not user_input: | |
| return "I didn't catch that. Please say something!" | |
| if "hello" in user_input or "hi" in user_input: | |
| return "Hello! How can I help you today?" | |
| if "bye" in user_input or "goodbye" in user_input: | |
| return "Goodbye! Have a great day." | |
| if "how are you" in user_input: | |
| return "I'm just code, but thanks for asking!" | |
| # Random fallback | |
| return random.choice( | |
| [ | |
| "Interesting point.", | |
| "Tell me more.", | |
| "Could you clarify that?", | |
| "I'm listening.", | |
| ] | |
| ) | |
| # --- Main app --- | |
| init_session() | |
| st.title("🤖 Minimal Chatbot") | |
| st.markdown("Ask me anything. Type `bye` to exit.") | |
| # Display chat history | |
| for msg in st.session_state[SESSION_KEY]: | |
| with st.chat_message(msg["role"]): | |
| st.write(msg["content"]) | |
| # Chat input | |
| if prompt := st.chat_input("Type your message..."): | |
| # Show user message | |
| with st.chat_message("user"): | |
| st.write(prompt) | |
| append_message("user", prompt) | |
| # Generate & show bot response | |
| response = bot_response(prompt) | |
| with st.chat_message("assistant"): | |
| st.write(response) | |
| append_message("assistant", response) |