File size: 2,356 Bytes
59afc8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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})