Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| from datetime import datetime | |
| import random | |
| # --- CONFIGURATION --- | |
| APP_TITLE = "π€ Streamlit Chatbot" | |
| AVATAR_BOT = "π€" | |
| AVATAR_USER = "π§βπ»" | |
| # --- SESSION STATE INITIALIZATION --- | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [] # list of dicts: {"role": "user"|"assistant", "content": str} | |
| # --- HELPER FUNCTIONS --- | |
| def fake_llm_response(user_input: str) -> str: | |
| """ | |
| A very small, fake language model. | |
| Replace this function with a real LLM call (OpenAI, Anthropic, local model, etc.). | |
| """ | |
| responses = [ | |
| "Interesting point! Tell me more.", | |
| "I see what you mean. Could you elaborate?", | |
| "That's a great question. I'm still learning, but here's what I think...", | |
| "Hmm, I hadn't considered that angle.", | |
| "Thanks for sharing that with me!", | |
| ] | |
| return random.choice(responses) + f"\n\n*(You said: {user_input})*" | |
| # --- STREAMLIT UI --- | |
| st.set_page_config(page_title=APP_TITLE, page_icon=AVATAR_BOT) | |
| st.title(APP_TITLE) | |
| # --- CHAT HISTORY --- | |
| for message in st.session_state.messages: | |
| avatar = AVATAR_USER if message["role"] == "user" else AVATAR_BOT | |
| with st.chat_message(message["role"], avatar=avatar): | |
| st.markdown(message["content"]) | |
| # --- USER INPUT --- | |
| if prompt := st.chat_input("Type your message here..."): | |
| # 1. Append user message to session state | |
| st.session_state.messages.append({"role": "user", "content": prompt}) | |
| # 2. Display user message immediately | |
| with st.chat_message("user", avatar=AVATAR_USER): | |
| st.markdown(prompt) | |
| # 3. Generate assistant response | |
| response = fake_llm_response(prompt) | |
| # 4. Append assistant response to session state | |
| st.session_state.messages.append({"role": "assistant", "content": response}) | |
| # 5. Display assistant response | |
| with st.chat_message("assistant", avatar=AVATAR_BOT): | |
| st.markdown(response) | |
| # --- SIDEBAR OPTIONS --- | |
| with st.sidebar: | |
| st.header("Options") | |
| if st.button("Clear Chat"): | |
| st.session_state.messages = [] | |
| st.rerun() | |
| st.caption(f"Chat started at {datetime.now():%Y-%m-%d %H:%M:%S}") |