All Projects
advanced

AI Chatbot

A rule-based AI chatbot with pattern matching, context awareness, and learning capabilities.

Features
  • Pattern matching responses
  • Context tracking
  • Customizable knowledge base
  • Conversation history
  • Learning from interactions
Technologies Used
OOPRegular ExpressionsJSONString ProcessingData Structures
Explanation

Uses regular expressions for pattern matching against a knowledge base. Maintains conversation context and can learn new responses from user input.

Source Code
import re
import json
import random

class Chatbot:
    def __init__(self, name="PyBot"):
        self.name = name
        self.knowledge = {
            r"(hi|hello|hey)": ["Hello! How can I help you?", "Hi there! 👋", "Hey! What's up?"],
            r"(how are you|how's it going)": ["I'm doing great, thanks!", "I'm good! Ready to help."],
            r"(your name|who are you)": [f"I'm {name}, your Python assistant!"],
            r"(what is python|tell me about python)": ["Python is a high-level programming language known for its simplicity and versatility."],
            r"(bye|goodbye|exit)": ["Goodbye! Happy coding! 🐍", "See you later!"],
            r"(thank|thanks)": ["You're welcome!", "Happy to help!"],
            r"(help)": ["I can help with Python questions! Try asking about variables, loops, functions, etc."],
            r"(what is a variable)": ["A variable is a container for storing data. In Python: x = 10"],
            r"(what is a loop)": ["Loops repeat code. Python has for and while loops."],
            r"(what is a function)": ["A function is a reusable block of code defined with 'def' keyword."],
        }
        self.context = []
        self.history = []

    def respond(self, user_input):
        user_input = user_input.lower().strip()
        self.history.append({"role": "user", "message": user_input})

        for pattern, responses in self.knowledge.items():
            if re.search(pattern, user_input):
                response = random.choice(responses)
                self.history.append({"role": "bot", "message": response})
                return response

        response = "I'm not sure about that. Could you rephrase or ask something about Python?"
        self.history.append({"role": "bot", "message": response})
        return response

    def learn(self, pattern, response):
        if pattern in self.knowledge:
            self.knowledge[pattern].append(response)
        else:
            self.knowledge[pattern] = [response]

def main():
    bot = Chatbot()
    print(f"=== {bot.name} - Python Chatbot ===")
    print("Type 'quit' to exit, 'teach' to add knowledge\n")

    while True:
        user_input = input("You: ")
        if user_input.lower() == 'quit':
            print(f"{bot.name}: Goodbye! 🐍")
            break
        elif user_input.lower() == 'teach':
            pattern = input("Pattern (regex): ")
            response = input("Response: ")
            bot.learn(pattern, response)
            print("Learned!")
            continue

        response = bot.respond(user_input)
        print(f"{bot.name}: {response}")

main()