# file: chatbot_rulebased.py import re import random RESPONSES = { "greeting": ["Hey!", "Hi there!", "Hello! How can I help?"], "bye": ["Goodbye!", "See ya!", "Take care!"], "thanks": ["You’re welcome!", "No problem!", "Anytime!"], "default": [ "Sorry — I don't understand. Can you say that differently?", "Hmm, tell me more.", ], } KEYWORDS = { "greeting": ["hello", "hi", "hey", "yo"], "bye": ["bye", "goodbye", "see you", "later"], "thanks": ["thanks", "thank you", "thx"], } def classify(message: str): m = message.lower() for intent, keys in KEYWORDS.items(): for k in keys: if re.search(r"\b" + re.escape(k) + r"\b", m): return intent return "default" def respond(message: str, user_state: dict): intent = classify(message) if intent == "greeting": return random.choice(RESPONSES["greeting"]) if intent == "bye": return random.choice(RESPONSES["bye"]) if intent == "thanks": return random.choice(RESPONSES["thanks"]) # simple small-talk memory example: if "name is" in message.lower(): name = message.split("name is")[-1].strip().split()[0].capitalize() user_state["name"] = name return f"Nice to meet you, {name}!" if "what is my name" in message.lower() or "do you remember my name" in message.lower(): return f"I think your name is {user_state.get('name', 'not set yet — tell me!')}" return random.choice(RESPONSES["default"]) def main(): print("Chatbot (type 'quit' to exit)\n") state = {} while True: user = input("You: ").strip() if not user: continue if user.lower() in ("quit", "exit"): print("Bot:", random.choice(RESPONSES["bye"])) break print("Bot:", respond(user, state)) if __name__ == "__main__": main()