Sub topic 10
Automating routing and duplicate detection
Prerequisites and scope
This chapter assumes you have read the chapters on question types and triage, and that you can read short Python functions. You do not need a machine learning background. Everything here uses plain rules and the Python standard library.
Automation in a course Q&A does two jobs. It routes each new question to the right queue, and it finds earlier questions that look the same so a moderator can link to an existing answer. In both jobs the software only suggests. A person confirms. That choice keeps mistakes cheap, and it is the main design rule of this chapter.
Why automate only these two things
Routing and duplicate detection are good first targets because they share three traits:
- The work is repetitive. Every new question needs a category and a duplicate check.
- A wrong result is easy to undo. A moderator moves the question or unlinks the suggestion.
- The result is easy to inspect. You can read the rule that fired and the earlier question that matched.
Automating the answers themselves is a different problem with different risks. The chapter on AI drafts covers it.
The routing pipeline
A new question passes through a few small steps. Each step can be tested alone.
Note that the duplicate suggestion does not remove the question from the queue. The moderator decides whether to link, merge, or answer it separately.
Rule-based routing
The simplest router is an ordered list of rules. Each rule has a category and a set of keywords. The first rule that matches wins, and a default category catches everything else.
RULES = [
("billing", ("refund", "invoice", "charge")),
("technical", ("error", "install", "traceback")),
("content", ("lecture", "quiz", "slide")),
]
def triage(text):
lowered = text.lower()
for category, keywords in RULES:
if any(word in lowered for word in keywords):
return category
return "general"
print(triage("I get an error when I install the course files")) # technicalThe function lowercases the text once, then checks each rule in order. any(...) stops at the first keyword that appears. The rule order is therefore a priority order. If a student writes "I was charged twice and now I see an error," the question goes to billing, because that rule comes first.
Common errors in keyword routing
Keyword rules fail in predictable ways. Know them before you ship the rules.
| Problem | Example | Effect | Mitigation |
|---|---|---|---|
| Substring matches | "charge" matches "in charge of the group project" | Content question lands in billing | Match whole words with a regular expression |
| Order sensitivity | Two categories match, the earlier one wins | Mixed questions go to the wrong queue | Put the costliest-to-miss category first, and log ties |
| Vocabulary drift | Students write "money back" instead of "refund" | Falls through to `general` | Review the `general` queue monthly and add keywords |
| Ambiguous words | "error" in a quiz question about error handling | Content question lands in technical | Require two signals, or lower the rule's priority |
| Non-English text | A question in another language | Always `general` | Add per-language keyword sets or route by language field |
A common fix for substring matches is whole-word matching:
import re
RULES = [
("billing", ("refund", "invoice", "charge", "charged")),
("technical", ("error", "install", "traceback")),
("content", ("lecture", "quiz", "slide")),
]
def triage_words(text):
words = set(re.findall(r"[a-z']+", text.lower()))
for category, keywords in RULES:
if words.intersection(keywords):
return category
return "general"
print(triage_words("Who is in charge of the group project?")) # general
print(triage_words("I was charged twice")) # billingWhole-word matching stops "in charge" from matching "charge" inside a longer word, but it also means you must list each word form yourself ("charge", "charged"). That is the trade-off: fewer false positives, more maintenance.
Keep the rules as data
Notice that RULES is a plain list, separate from the function. Moderators who do not write code can review and edit it if you store it in a configuration file. Keep a short comment or a note beside each rule saying why it exists. When a rule misroutes questions, you will want to know who added it and for what reason.
Adding urgency
Category and urgency are different things. A billing question about a duplicate charge may be more urgent than a general question, but a billing question about a receipt format may not be. Treat urgency as a second, separate check.
URGENT = ("locked out", "cannot access", "deadline today", "exam", "charged twice")
def is_urgent(text):
lowered = text.lower()
return any(phrase in lowered for phrase in URGENT)
def route(text):
return {
"category": triage(text),
"urgent": is_urgent(text),
}
print(route("I am locked out and the exam closes tonight"))The result is a dictionary rather than a single label, so downstream code can sort by urgency inside each category. Keep the urgent list short. A long list flags so many questions that the flag stops meaning anything. Questions that touch safety, privacy, or accusations of cheating should go straight to the escalation path rather than through ordinary routing.
Duplicate detection
Duplicates waste moderator time and split the discussion across several threads. Detecting them means scoring how alike two questions are. The standard library's difflib.SequenceMatcher gives a ratio from 0 (nothing in common) to 1 (identical text).
from difflib import SequenceMatcher
def similarity(a, b):
return SequenceMatcher(None, a.lower(), b.lower()).ratio()
def find_duplicates(new_question, existing, threshold=0.7):
scored = [(q, similarity(new_question, q)) for q in existing]
matches = [item for item in scored if item[1] >= threshold]
return sorted(matches, key=lambda item: item[1], reverse=True)
existing = ["How do I submit assignment 2?", "Where can I find the slides?"]
print(find_duplicates("How can I submit assignment 2?", existing))The function scores the new question against every existing one, keeps those at or above the threshold, and returns them best first. The first existing question scores high because only one word differs. The second scores low and is dropped.
Choosing a threshold
The threshold trades two kinds of error against each other.
- A low threshold shows many suggestions. Moderators see false matches and learn to ignore the list.
- A high threshold shows few suggestions. Real duplicates with different wording are missed.
Start around 0.7, then tune it on real data. Take 50 to 100 pairs of questions that moderators have already labeled as duplicate or not duplicate. Run the scorer on them and look at which labeled pairs fall on the wrong side of the line. Move the threshold until the errors are acceptable. For a moderator-facing suggestion, a few false matches are cheaper than missed ones, because a person reviews each suggestion anyway.
Limits of character-based similarity
SequenceMatcher compares characters, not meaning. This causes errors in both directions:
- False positives. "How do I submit assignment 2?" and "How do I submit assignment 3?" are almost identical text but have different answers. Numbers, module names, and version numbers carry the meaning.
- False negatives. "I can't turn in my homework" and "How do I submit assignment 2?" share few characters but ask the same thing.
- Slow on large forums. Comparing a new question with every existing one grows linearly with forum size, and each comparison is not free. Limit the search to the same category, or to questions from the last N months, before scoring.
A cheap improvement is to normalize before comparing. Lowercase the text, strip punctuation, and remove filler words. Another is to treat numbers specially: if both questions contain numbers and the sets differ, subtract from the score or skip the match.
import re
from difflib import SequenceMatcher
def numbers_in(text):
return set(re.findall(r"\d+", text))
def adjusted_similarity(a, b):
score = SequenceMatcher(None, a.lower(), b.lower()).ratio()
if numbers_in(a) != numbers_in(b):
score *= 0.5
return score
print(adjusted_similarity("How do I submit assignment 2?", "How do I submit assignment 3?"))This halves the score when the numbers differ, so the assignment 2 and assignment 3 questions no longer clear a 0.7 threshold. It is a blunt rule. It would also penalize a pair that differs only by a stray number. Test it against your labeled pairs before adopting it.
Putting a human in the loop
Both automations should end in a moderator action, not a silent change.
- Show the suggested category as a pre-filled field that a moderator can change in one click.
- Show duplicate suggestions with the earlier question, its score, and a link to its accepted answer.
- Record each override. When a moderator changes a category or rejects a suggestion, store the original text, what the tool said, and what the moderator chose.
- Review the overrides every month. They show you which rules to add, which to remove, and where the threshold sits wrong.
Never auto-close a question as a duplicate. A student whose question is closed without a human check may be told "already answered" when the earlier answer does not fit. That outcome damages trust in the whole Q&A.
Privacy and logging
Routing logs and override records contain student text. Store them with the same access limits as the Q&A itself. Do not copy question text into shared spreadsheets or external services without checking your platform's privacy rules. If a question contains grades, personal circumstances, or health details, the router should not pass it to any similarity index that other students can query.
Failure modes to watch
- Silent drift. Rules that were good in week 1 miss new vocabulary by week 8. Schedule a review.
- Overfitting to one cohort. Keywords tuned on one course run may not fit the next, if the content changed.
- Alert fatigue. Too many urgent flags or duplicate suggestions teach moderators to ignore both.
- Hidden queues. If the
generalcategory grows large, your rules are not covering real questions. Track its share of volume.
Exercises
Exercise
A router matches the keyword "charge" by substring. A student writes "Who is in charge of grading the group project?" Which queue does it reach, why is that a problem, and what change fixes it?
Show answer
It reaches the billing queue, because "charge" appears inside the text and the billing rule is checked first. A content or logistics question is then sent to the wrong team and waits longer. Matching whole words (for example by splitting the text into words with a regular expression and testing set membership) fixes it, at the cost of listing each word form such as "charged" yourself.
Exercise
Your duplicate detector at threshold 0.7 scores "How do I submit assignment 2?" against "How do I submit assignment 3?" at about 0.97. Moderators report many false suggestions of this kind. Name two changes and one risk of each.
Show answer
First, compare the numbers in each question and reduce the score when they differ. The risk is that a harmless extra number lowers the score of a true duplicate. Second, raise the threshold. The risk is that real duplicates worded differently are missed, and a threshold high enough to block this pair would block most others too. Test either change on labeled pairs before adopting it.
Exercise
Why should the system suggest duplicates to a moderator instead of closing them automatically?
Show answer
Character similarity does not measure meaning, so it makes both false positives and false negatives. An automatic close could tell a student their question was answered when the earlier answer does not fit. A moderator reviewing a suggestion catches those cases cheaply, and the recorded overrides give you data to improve the rules.