Build a Rule-Based Chatbot

Build a simple chatbot with rule logic in this Applied AI engineering tutorial. Step-by-step, hands-on, with troubleshooting and next steps.

Focus: build a simple chatbot with rule logic

Sponsored

Ever found yourself answering the same repetitive questions over and over — "How do I reset my password?", "What are your hours?", "Where is the nearest store?" — and wished a script could handle it for you? That's exactly the pain a simple chatbot with rule logic solves: it lets you automate predictable conversations without expensive machine learning models or API calls. This lesson walks you through building a dead-simple, rule-based chatbot in Python that you can extend into a real support assistant, a FAQ bot, or a guided questionnaire. You'll learn the core patterns, write runnable code, and know exactly when rule logic beats (and loses to) smarter AI approaches.

The problem this lesson solves

Building a full conversational AI with natural language processing (NLP) or large language models (LLMs) is overkill for many tasks. If your interactions are predictable — customers asking about shipping, users requesting help with a command, students practicing language drills — a complex model is slow, costly, and hard to debug. You need a lightweight, deterministic solution that:

  • Runs instantly with zero internet dependency.
  • Gives consistent, predictable answers every time.
  • Is easy to test, modify, and audit.

Rule-based chatbots solve exactly that. They're the first step in the Applied AI engineering path because they teach you the fundamentals of intent detection, response generation, and state management — patterns you'll reuse when you switch to ML-powered bots.

Core concept / mental model

Think of a rule-based chatbot as a decision tree and a lookup table combined. The user's input goes through a series of checks (rules) to determine the intent (what they want), and then the bot picks a pre-written response.

A simple mental model: your bot is a switchboard operator. The user says something, you listen for keywords (e.g., "order", "refund", "hello"), you route the call to the right department (a set of responses), and you transfer back with the answer.

In code, you'll typically define:

  • Rules: a list of patterns (keyword lists or regex) that match user input.
  • Responses: a dictionary or function that returns the right answer for each rule.
  • A loop: to keep the conversation going until the user says goodbye.

This pattern is called pattern matching, and it's the foundation of more advanced NLP techniques like intent classification.

How it works step by step

Let's break down building a simple rule-based chatbot into logical steps.

  1. Define the conversation domain. What should your bot handle? Start with a narrow set of intents: greeting, asking for help, asking about hours, saying goodbye.
  2. Create rule patterns. For each intent, define trigger words or phrases. Use if statements or a dictionary mapping patterns to responses.
  3. Write the response logic. For each rule, define a response. Make it varied if you want (pick randomly from a list) — but the core idea is deterministic mapping.
  4. Implement the main loop. Read user input, run rules in priority order, respond, and repeat until a stop condition (e.g., "bye" or "exit").
  5. Handle edge cases. What if the user says something not covered? Fallback to a default "I don't understand" message, and maybe offer suggestions.
  6. Test and iterate. Add more rules as you notice new patterns.

Hands-on walkthrough

Now let's write a rule-based chatbot in Python. We'll start with a minimal version, then evolve it.

Baseline rule bot

# rule_bot.py
import re

def respond(user_input):
    user_input = user_input.lower()

    if re.search(r'\b(hi|hello|hey)\b', user_input):
        return "Hello! How can I help you today?"
    elif re.search(r'\b(hours|open|close)\b', user_input):
        return "We're open Monday to Friday, 9am to 5pm."
    elif re.search(r'\b(shipping|delivery)\b', user_input):
        return "Standard shipping takes 3-5 business days."
    elif re.search(r'\b(bye|goodbye)\b', user_input):
        return "Goodbye! Have a great day."
    else:
        return "Sorry, I don't understand. Try asking about hours, shipping, or say hello."

def main():
    print("RuleBot: Hello! Type 'bye' to exit.")
    while True:
        user_input = input("You: ")
        if re.search(r'\b(bye|exit)\b', user_input.lower()):
            print("RuleBot: Goodbye!")
            break
        print(f"RuleBot: {respond(user_input)}")

if __name__ == "__main__":
    main()

Run it:

python rule_bot.py

Try: hello"Hello! How can I help you today?"; What are your hours?"We're open..."; when will my order arrive?"Standard shipping...". Type bye to exit.

Adding state with a simple dictionary

Real bots often track context, like whether the user already said hello. Let's add a simple state variable.

# stateful_rule_bot.py
import re

class RuleBot:
    def __init__(self):
        self.state = {"greeted": False}
        self.rules = [
            (r'\b(hi|hello|hey)\b', self.greet),
            (r'\b(hours|open|close)\b', self.hours),
            (r'\b(shipping|delivery)\b', self.shipping),
            (r'\b(bye|goodbye)\b', self.bye),
        ]

    def greet(self, _):
        self.state["greeted"] = True
        return "Hello! How can I help?"
    def hours(self, _):
        if not self.state["greeted"]:
            return "First, say hello! Then I can help."
        return "We're open 9-5, Monday-Friday."
    def shipping(self, _):
        return "Shipping takes 3-5 business days."
    def bye(self, _):
        return "Goodbye!"

    def respond(self, user_input):
        for pattern, func in self.rules:
            if re.search(pattern, user_input):
                return func(user_input)
        return "I didn't get that. Try hello, hours, shipping, or bye."

bot = RuleBot()
print(bot.respond("hi"))          # Hello! How can I help?
print(bot.respond("hours"))       # First, say hello! Then I can help.
print(bot.respond("hello"))       # Hello! How can I help? (state now True)
print(bot.respond("hours"))       # We're open 9-5...

Handling multiple responses and priorities

Sometimes two rules could match. Order them by priority — the first match wins.

# priority_bot.py
rules = [
    (r'\b(help|support)\b', "I can help with hours, shipping, or returns."),
    (r'\b(hi|hello)\b', "Hello!"),
]
# "help" matches both? No — only the first rule matches, so it wins.
print(rules[0][1])  # "I can help with hours, shipping, or returns."

Compare options / when to choose what

Rule logic is not the only way to build a chatbot. Here's a comparison:

Approach Pros Cons Best for
Rule-based Fast, predictable, easy to debug, zero pre-training Brittle; fails on unexpected phrasing FAQs, forms, command bots
ML classification Handles varied phrasing, robust to typos Needs training data, more complex, slower to iterate Intent detection at scale
LLM-based Uses natural language context, handles open-ended Costly, black-box, needs careful prompting & guardrails Open-ended assistants

When to choose rule logic: - Fixed domain: if the conversation space is limited (e.g., a coffee shop menu bot). - High reliability: you need exact answers (e.g., legal disclaimers). - Tight budget: no API costs, no training infrastructure.

When not to: - If users type free-form with many variations, rule bots will frustrate. In that case, consider ML or LLMs.

Troubleshooting & edge cases

  • Case sensitivity: Always lower() user input before matching, or the word "Hello" won't match hello.
  • Regex pitfalls: Use \b word boundaries so "hi" doesn't match "this". Test with re.search(r'\bhi\b', 'this') → returns None.
  • Priority conflicts: If multiple rules match, the first one in your list wins. Order them from most specific to generic.
  • Fallback loop: If the bot can't understand, don't repeat the same generic message forever — after a few failures, offer help or escalation.
  • Empty input: If the user presses Enter, your regex might match nothing, so add an if not user_input: check.
  • State handling: If you use state, reset it when the conversation ends — test with new sessions.

What you learned & what's next

You've built a simple chatbot with rule logic from scratch — you now know how to:

  • Recognize when rule-based chatbots are the right tool.
  • Structure a chatbot as a set of (pattern, response) pairs.
  • Add basic state to track conversation context.
  • Prioritize rules and handle unmatched input gracefully.
  • Extend the bot with new rules easily.

Congrats! You've completed lesson 93 in the Applied AI engineering path. Next, you'll dive into intent classification with machine learning — teaching a model to recognize user intent beyond hard-coded patterns. That builds on the exact same idea (matching user input to an action) but with the flexibility of learned patterns. Stay curious!

Practice recap

Extend your rule bot to handle a new intent — for example, answers about product returns. Add at least two new rules, test with a few variations (e.g., 'how do I return?' vs 'return policy'), and make sure priority is correct. Then refactor your bot to load rules from a JSON file — this sets you up for the more dynamic, data-driven patterns coming next.

Common mistakes

  • Not normalizing case before matching: 'Hello' won't match 'hello' unless you call .lower() first.
  • Using regex without word boundaries: r'hi' matches 'this', causing false positives.
  • Overlapping rules with wrong priority: putting generic rules before specific ones leads to wrong responses (e.g., 'I need help with shipping' matching 'help' instead of 'shipping').
  • Forgetting a fallback for unmatched input: users get stuck when the bot rolls off the edge of its rules.
  • Not handling empty or whitespace-only input: pressing Enter breaks the loop or triggers a confusing fallback.

Variations

  1. Use if/elif chains instead of a list of (pattern, function) pairs — simpler but harder to maintain as rules grow.
  2. Load rules from a JSON file so you can update the bot without changing Python code.
  3. Add randomness: choose from multiple response templates using random.choice() for a less robotic feel — still deterministic in intent, varied in expression.

Real-world use cases

  • Customer support FAQ bot that answers 'hours,' 'shipping,' and 'return' queries consistently on a checkout page.
  • Internal IT helpdesk bot that routes password reset and software installation requests using keyword triggers.
  • Hotel concierge bot that guides guests through amenities ('pool hours,' 'breakfast time') with high reliability and zero latency.

Key takeaways

  • Rule-based chatbots are deterministic, predictable, and perfect for narrow, well-defined conversation domains.
  • Model your bot as a decision tree of (pattern, response) pairs, ordered by priority.
  • Start with a small intent set and add rules iteratively as you see real user queries.
  • Handle edge cases: case sensitivity, empty input, overlapping rules, and a graceful fallback message.
  • Compare rule logic vs. ML vs. LLM to choose the simplest tool that meets your requirements.
  • Mastering rule logic builds the foundation for intent classification in later lessons.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.