Lesson 64.9 · 9 of 11 · 6 min read · Reviewed 24 Nov 2026
Topical and off-rail classifiers
By the end, you can
- Build a topical classifier that keeps an assistant on its job.
- Decide what to do with off-topic and borderline requests.
An assistant built to answer questions about a bank account will be asked to write poems, debug code, give medical advice and comment on politics. None of those may be harmful, but none is its job. A topical classifier (also called an off-rail or scope classifier) keeps it on its rails.
Why not just say so in the system prompt?
You should say so in the prompt. But a prompt is a preference (64.4): a persistent user, a long conversation or a role-play setup can drift the model off topic. A separate check, run on every turn, is predictable, can be logged and can be tested on its own.
Topical checks also save cost. Off-topic chat on a free assistant can become a large share of traffic.
How it works
A small, fast model reads the latest message (and a little context) and returns a label in a fixed schema:
{"scope": "in_scope" | "out_of_scope" | "unsure",
"topic": "cards" | "payments" | "account" | "other",
"reason": "one sentence"}
The prompt defines scope positively: the tasks the product does, each with one or two example questions, plus examples near the edge and how to label them. A list of banned words works badly: “travel”, “medical” or “Python” appear in perfectly good questions.
Some teams use embeddingsEmbedding: A list of numbers (a vector) that represents the meaning of a piece of text, so similar meanings land close together. instead: compare the request with example in-scope questions and call it out of scope below a similarity threshold. It is cheaper but cruder; a model label with a reason is easier to debug. Frameworks such as NeMo GuardrailsGuardrail: A control that keeps an AI system within safe and allowed behaviour, such as input checks, tool limits or output filters. let you declare topical rails like this in configuration.
A worked example
Scope: cards, payments, account settings, fees, fraud reports.
| Message | Label | Action |
|---|---|---|
| “Why was I charged a foreign transaction fee?” | in_scope (fees) | Answer |
| “Can I use my card in Japan?” | in_scope (cards) | Answer |
| “Which shares should I buy this year?” | out_of_scope | Redirect: “I can’t give investment advice. I can help with your account and cards.” |
| “My partner opened a card in my name without asking” | unsure | Careful path: answer what it can and offer a person |
| “Write a poem about volcanoes” | out_of_scope | Polite redirect |
Three points from the table:
- Out of scope is not abuse. Reply kindly and say what the assistant can do. Do not lecture.
- Unsure gets a careful path, not a block: a stricter prompt, a clarifying question, or a hand-off (45.3).
- Topics drift within a conversation. Classify each turn, not only the first.
Measuring it
Build a labelled set from real traffic: clear in-scope, clear out-of-scope and edge cases (64.7). Track two numbers:
- False blocks: good questions refused. These hurt users quietly, because they rarely complain; they leave.
- Off-rail passes: out-of-scope requests answered.
Review a sample of blocked messages every week. Most fixes are better edge examples in the scope definition, not a stronger model.
Common mistakes
- Blocking by keyword instead of by task.
- Treating every off-topic message as an attack and logging it as a security event.
- One label for safety and scope. Keep them separate: “off topic” and “harmful” need different responses and different owners.
Key points
- A topical classifier labels each request as in scope, out of scope or unsure, before the main model answers.
- Define scope with a written list of allowed topics plus examples near the edge, not with a list of banned words.
- Off-rail does not mean harmful: answer with a polite redirect, and send unsure cases down a careful path.
- Measure it on real traffic: blocking good questions is a failure too.
Build and test a topical classifier
Label messages as in scope, out of scope or unsure by comparing them with in-scope examples, and measure the errors.
You will have: A score() and classify() pair with two thresholds, and a report of false blocks and off-rail passes on seven labelled messages.
Steps
- Run the starter: everything is labelled in scope.
- Write score() to find the in-scope example that shares the most words with the message.
- Use two thresholds so middling scores become 'unsure' instead of a hard block.
- Count false blocks and off-rail passes; try changing the thresholds and watch the trade-off.
Done when
- The Japan travel question is in scope even though it mentions travel.
- The output shows 'false blocks: 0' and 'off-rail passes: 0'.
- At least 6 of 7 messages get the expected label.
Open in the Playground No API key needed.
Starter code (Python)
import re
# A topical classifier: compare a message with in-scope examples. Stands in for a small model or embeddings.
IN_SCOPE = {
"cards": ["lost my card", "use my card abroad", "card declined", "card blocked"],
"fees": ["foreign transaction fee", "monthly account fee", "why was i charged"],
"account": ["change my phone number", "update my address", "close my account"],
"fraud": ["someone used my card", "a payment i do not recognise"],
}
TESTS = [ # (message, expected: in_scope / out_of_scope / unsure)
("Can I use my card when travelling to Japan?", "in_scope"),
("Why was I charged a foreign transaction fee?", "in_scope"),
("How do I change my phone number on the app?", "in_scope"),
("Which shares should I buy this year?", "out_of_scope"),
("Write a poem about volcanoes", "out_of_scope"),
("My card was declined in a shop", "in_scope"),
("Can you recommend a good travel insurance policy?", "unsure"),
]
words = lambda s: set(re.findall(r"[a-z]+", s.lower())) - {"a", "i", "my", "the", "can", "in", "do", "on", "was", "you", "how", "why"}
def score(msg):
# TODO: return the best (topic, overlap) where overlap = shared words / words in the example
return "other", 0.0
def classify(msg, hi=0.6, lo=0.25):
# TODO: in_scope at or above hi, unsure between lo and hi, out_of_scope below lo
return "in_scope"
for m, want in TESTS:
print(f"{classify(m):12} (want {want:12}) {m}")
Show a solution
import re
IN_SCOPE = {
"cards": ["lost my card", "use my card abroad", "card declined", "card blocked"],
"fees": ["foreign transaction fee", "monthly account fee", "why was i charged"],
"account": ["change my phone number", "update my address", "close my account"],
"fraud": ["someone used my card", "a payment i do not recognise"],
}
TESTS = [
("Can I use my card when travelling to Japan?", "in_scope"),
("Why was I charged a foreign transaction fee?", "in_scope"),
("How do I change my phone number on the app?", "in_scope"),
("Which shares should I buy this year?", "out_of_scope"),
("Write a poem about volcanoes", "out_of_scope"),
("My card was declined in a shop", "in_scope"),
("Can you recommend a good travel insurance policy?", "unsure"),
]
words = lambda s: set(re.findall(r"[a-z]+", s.lower())) - {"a", "i", "my", "the", "can", "in", "do", "on", "was", "you", "how", "why"}
def score(msg):
m = words(msg)
best = ("other", 0.0)
for topic, examples in IN_SCOPE.items():
for ex in examples:
e = words(ex)
overlap = len(m & e) / len(e) if e else 0
if overlap > best[1]:
best = (topic, overlap)
return best
def classify(msg, hi=0.6, lo=0.25):
topic, s = score(msg)
if s >= hi: return "in_scope"
if s >= lo: return "unsure"
return "out_of_scope"
false_blocks = off_rail = right = 0
for m, want in TESTS:
got = classify(m)
right += got == want
false_blocks += want == "in_scope" and got == "out_of_scope"
off_rail += want == "out_of_scope" and got == "in_scope"
print(f"{got:12} (want {want:12}) {m}")
print(f"correct: {right}/{len(TESTS)} | false blocks: {false_blocks} | off-rail passes: {off_rail}")