← Back to docs

Introduction to rules.py — when and why to use it

Power user

Introduction to rules.py

Every bot has a rules.py file that runs before the LLM. It is plain Python with one function — respond(message, context) — that returns either a hand-written reply or None to fall through to the AI.

When should you use rules?

Use rules.py when you want deterministic, predictable, free answers — no LLM call, no tokens used, no monthly message counted.

Good fits:

  • Frequent questions with one correct answer (opening hours, refund policy, address)
  • Hard guardrails (block off-topic, profanity, competitor mentions)
  • Lead capture (detect "how much", "pricing", "demo" → ask for email)
  • Multi-step flows (booking, returns, ticket creation)
  • Routing (forward urgent messages to a human)

Don't use rules for:

  • Anything that needs to read the customer's actual content (let the LLM handle it)
  • Long lists of variations — use the LLM, that's what it's good at

The basic shape

def respond(message, context):
    msg = message.lower().strip()

    if "hours" in msg or "open" in msg:
        return "We are open Mon-Fri 9am-6pm UK time, closed weekends."

    if "refund" in msg:
        return "Refunds are processed within 5 working days. See our returns policy at /returns."

    return None  # let the AI handle it

Returning None means "I don't know — pass to the LLM". Returning a string means "use this exact reply, don't call the LLM at all".

What's in context?

The context dict gives you:

  • context["history"] — list of previous messages in this session
  • context["session_id"] — unique conversation ID
  • context["visitor"] — geo info if available (country, city)
  • context["page_url"] — what page the visitor is on (if widget passes it)

How rules save you money

Every LLM call counts towards your monthly message limit. A rule that catches "what are your hours" returns instantly, costs nothing, and doesn't count against your quota. On a busy bot, well-written rules can absorb 30-50% of total traffic.

Where to edit

Dashboard → Rules. The editor has syntax highlighting and a Save button. Changes take effect within a few seconds.

Testing

After saving, use Dashboard → Test bots to fire test messages and see whether your rule fires or falls through to the AI.

See also: Rules cheat-sheet, Recipe: FAQ shortcuts, Debugging your rules.