I1 · Python Programming for AI

Project: A Rule-Based Chatbot

A rule-based chatbot replies to messages by matching them against rules written by people, usually keywords linked to responses, inside a loop that keeps the conversation going until the user leaves. It uses no machine learning, so it is predictable but only handles what its rules cover.

20 min Intermediate · Sublevel Beginner Jump to the activity

What you need: The earlier topics of this module.

Definition

Can you build a help-desk bot with only what you've learned so far?

A rule-based chatbot replies to messages by matching them against rules written by people, usually keywords linked to responses, inside a loop that keeps the conversation going until the user leaves. It uses no machine learning, so it is predictable but only handles what its rules cover.

In simple words

The bot cleans each message (lowercase, no extra spaces), looks for keywords such as 'fees' or 'timing', and replies with the matching answer. If nothing matches, it says sorry and suggests what it can help with. Typing 'bye' ends the chat. This is how the first chatbot, ELIZA, worked in 1966.

Overview

  • A rule-based chatbot replies by matching the user's message against hand-written rules, with no machine learning.
  • The project uses strings, conditionals, loops, dictionaries and functions together.
  • Cleaning input (lower-casing, removing punctuation) makes rules match more often.
  • A dictionary from keywords to replies keeps the rules easy to add and change.
  • A fallback reply handles messages that match no rule.
  • ELIZA (1966) was a famous rule-based chatbot; today's assistants combine rules with machine learning and LLMs.

Why it matters

This project uses everything in the module: strings, dictionaries, loops, conditions and functions. It also shows clearly why modern AI chatbots learn from data: rules break as soon as people word things differently.

Key terms

Chatbot
A program that holds a conversation in text or speech.
Rule-based system
A system whose behaviour is fixed by rules written by people.
Intent
What the user wants, such as asking for timings or saying goodbye.
Keyword matching
Choosing a reply by checking whether certain words appear in the message.
Fallback response
The reply used when no rule matches.
Main loop
The loop that keeps reading messages and replying until the user quits.

Types

Chatbots range from simple rule-followers to large language models. Knowing the types shows where your project fits and how it could grow.

1. Keyword (rule-based) chatbot

A bot that looks for keywords or patterns in a message and returns a fixed reply.

  • How it works: Clean the message, check each rule in order (if "fee" in text) and send the reply of the first rule that matches.
  • Example: A school bot that answers "timing", "fees" and "holiday" questions.
  • When to use it: Use it for small, predictable sets of questions where full control over replies matters.

2. Menu (button-based) chatbot

A bot that offers numbered options or buttons instead of reading free text.

  • How it works: Each choice leads to a reply or a sub-menu, like a decision tree; the user never types a sentence.
  • Example: "Press 1 for balance, 2 for recent transactions" on a bank's WhatsApp service.
  • When to use it: Use it when tasks are well defined and errors must be avoided, such as bookings and payments.

3. Retrieval (FAQ-matching) chatbot

A bot that finds the stored question most similar to the user's message and returns its answer.

  • How it works: Questions and messages are turned into vectors (for example TF-IDF or embeddings), and cosine similarity picks the closest one.
  • Example: A college helpdesk bot with 200 stored questions about admissions.
  • When to use it: Use it when you have a good FAQ and want to handle many ways of asking the same thing.

4. Intent-based (machine-learning) chatbot

A bot that uses a trained classifier to recognise the user's intent and extract details.

  • How it works: Training examples teach the model intents such as book_ticket; entity extraction finds details like the date and city.
  • Example: "Book a train to Jaipur tomorrow" is classified as book_ticket with city = Jaipur and date = tomorrow.
  • When to use it: Use it for services with many intents and varied phrasing; module I8 builds one.

5. Generative (LLM) chatbot

A bot that writes new replies with a large language model.

  • How it works: The message, a system prompt and often retrieved documents are sent to an LLM, which generates the answer word by word.
  • Example: ChatGPT, Gemini and customer-support assistants built on them.
  • When to use it: Use it for open-ended conversation, with grounding and safety checks because it can make things up; module I9 covers it.

Explained in detail

A short history of rule-based chatbots

The first famous chatbot, ELIZA, was written by Joseph Weizenbaum at MIT between 1964 and 1966. Its best-known script imitated a therapist by matching keywords and turning the user's sentences into questions: "I am sad" became "Why do you say you are sad?" Weizenbaum was startled that some people treated it as if it understood them, though it had no understanding at all. For decades afterwards, most customer-service bots were rule-based in the same way. Your project rebuilds this idea with the Python you have learned.

Design before you build

  1. Choose a narrow purpose, such as answering questions about a school library: timings, borrowing rules, fines, how to find a book.
  2. List the intents users will have, with sample messages for each.
  3. For each intent, choose keywords and write one or more replies.
  4. Decide the fallback reply and the words that end the conversation.
  5. Write test conversations, including messages that should not match anything.

How the Python fits together

Concept from this moduleRole in the chatbot
DictionaryMaps each intent to its keywords and replies
String methodslower() and strip() normalise the message; split() breaks it into words
SetsIntersect message words with keywords for fast matching
while loop and breakKeeps the conversation going until "bye"
Functionsfind_intent(message) and reply(intent) keep the logic testable
random.choiceVaries replies so the bot sounds less robotic

Limits you will discover

Testing will quickly reveal the weaknesses of keyword rules. "Is the library not open on Sunday?" contains "open" and "Sunday" but the word "not" changes its meaning. A spelling mistake, "tmings", matches nothing. Two intents can share a keyword. Every new question needs a new rule, and rules start to conflict as they multiply. These problems are exactly why chatbots moved first to machine-learning intent classifiers, which you will build in the NLP module, and then to large language models, which you will use in the Generative AI module. A rule-based bot remains useful where predictability matters, such as a bank bot that must never invent policy.

How it works

  1. Write a dictionary of intents: each has keywords and a reply.
  2. Write clean(message): lowercase it and strip spaces and punctuation.
  3. Write reply(message): return the reply of the first intent whose keyword appears.
  4. Add a fallback reply for messages that match nothing.
  5. Run a loop until the user says bye.

In code

A keyword chatbot with a fallback and a conversation loop.

help_desk_bot.py
INTENTS = {
    "greeting": (["hello", "hi", "namaste"], "Hello! Ask me about fees, timings or the library."),
    "fees": (["fee", "fees", "cost", "price"], "The course is free for all learners."),
    "timing": (["time", "timing", "open", "hours"], "We're open 9 am to 6 pm, Monday to Saturday."),
    "library": (["library", "book", "books"], "The library is on the first floor."),
}
FALLBACK = "Sorry, I didn't get that. Try asking about fees, timings or the library."

def clean(message):
    return "".join(ch for ch in message.lower() if ch.isalnum() or ch == " ").split()

def reply(message):
    words = clean(message)
    for keywords, answer in INTENTS.values():
        if any(word in keywords for word in words):
            return answer
    return FALLBACK

conversation = ["Hi!", "What are the FEES?", "when do you open", "Can I park here?", "bye"]
for message in conversation:
    print("You:", message)
    if "bye" in clean(message):
        print("Bot: Goodbye, and happy learning!")
        break
    print("Bot:", reply(message))

Output

You: Hi!
Bot: Hello! Ask me about fees, timings or the library.
You: What are the FEES?
Bot: The course is free for all learners.
You: when do you open
Bot: We're open 9 am to 6 pm, Monday to Saturday.
You: Can I park here?
Bot: Sorry, I didn't get that. Try asking about fees, timings or the library.
You: bye
Bot: Goodbye, and happy learning!

Try it yourself

Which intent should match?

For each message, which reply would the bot give?

  • "Is there a canteen?"

  • "What hours are you open?"

  • "How much does it cost?"

  • "Where can I find books?"

  • "Is it expensive?"

Extend your bot

Try these changes in the runner above.

  1. Add a new intent, such as 'exam', with three keywords and a reply.
  2. Add 'expensive' to the fees keywords and test it.
  3. Write three messages that should match but don't. What would a learning chatbot do better?

Common mistakes

  • Forgetting to lowercase messages, so 'FEES' doesn't match 'fees'.
  • Matching parts of words: 'hi' inside 'this'. Split into words first.
  • No fallback, so the bot says nothing to unexpected messages.

Check yourself

Question 1

1. Why clean messages before matching?

Question 2

2. What is the biggest weakness of a rule-based bot?

Question 3

3. Which Python structure holds the intents?

Summary

  • A rule-based bot matches keywords to replies inside a loop.
  • Cleaning text, a fallback and an exit word make it usable.
  • Its limits show why modern chatbots learn from data.

Finished reading?

Sources: Python tutorial, decisions and iteration