Sub topic 9
Teaching Edge Cases and Out-of-Scope Inputs
This chapter assumes you can read short Python, know the system, user, and assistant roles in chat prompts, and have written a basic few-shot prompt with consistent input and output pairs. It also assumes you have seen how examples are chosen for coverage. Here the focus is the inputs that fall outside the easy middle of the task: ambiguous cases, malformed inputs, and requests the prompt should decline.
Why edge cases need their own examples
A few-shot prompt teaches by pattern. If every example is a clean, typical input with a confident label, the model learns that every input is clean, typical, and confidently labeled. Real traffic is different. Users send empty strings, text in another language, reviews that mix praise and complaint, and questions that have nothing to do with the task.
When the model meets an input unlike any example, it falls back on its general habits. For a classifier, that usually means forcing the input into the nearest label. A question about the weather gets labeled "neutral" because "neutral" is the closest thing to "no opinion." The output looks valid, so nobody notices the mistake.
Instructions alone often do not fix this. A line such as "If the input is not a review, say so" helps, but the model follows the demonstrated behavior more reliably than the described behavior. An example that shows the refusal makes the rule concrete.
Three kinds of hard input
It helps to separate the hard inputs by what the correct response should be.
| Kind | Example input | Correct response |
|---|---|---|
| Ambiguous but in scope | "The screen is bright but the speakers are weak." | A label from the allowed set, chosen by a stated rule |
| Malformed or empty | "" or "!!!!" | A fixed marker such as `invalid` |
| Out of scope | "What is the capital of France?" | A fixed marker such as `out_of_scope`, or a short refusal |
The first kind still has a right answer inside your label set. The second and third need an answer that is not in the original label set at all. That means the output vocabulary must be extended and the instruction must name the new labels.
Extending the label set
Suppose the sentiment classifier from earlier chapters now has to handle junk. Add two labels and say exactly when each applies.
Classify the sentiment of each product review as positive, negative, or neutral.
If the text is not a product review, answer out_of_scope.
If the text is empty or has no readable words, answer invalid.
Answer with one word.
Review: The battery lasts all day and charging is fast.
Sentiment: positive
Review: What is the capital of France?
Sentiment: out_of_scope
Review: It stopped working after a week.
Sentiment: negative
Review: !!!! ???
Sentiment: invalid
Review: The package arrived on Tuesday.
Sentiment: neutral
Review: The screen is bright but the speakers are weak.
Sentiment:Three details matter here.
- The instruction names every allowed output, including the special markers. The examples then confirm them.
- The special-case examples use exactly the same
Review:andSentiment:format as the normal ones. If the refusal were written as a sentence in a different shape, the model would treat it as a different task. - The special cases are mixed in among the normal examples, not grouped at the end. Placing both rare cases last would make the model more likely to emit one of them for the final query, because the most recent examples carry extra weight.
Ambiguous inputs: show the tie-break
Mixed reviews are the most common in-scope edge case. The final query in the prompt above ("bright but weak speakers") has no obviously correct label. If your team's rule is "mixed opinions with no clear lean count as neutral," then demonstrate that rule.
Review: Great camera, but the app crashes constantly.
Sentiment: neutralOne such example sets the convention. Without it, the model chooses by its own habit, and that choice can change between model versions or even between runs. A tie-break example is a way of writing down a decision that your labeling guidelines already contain.
Add a second example that leans one way, so the model learns that "mixed" does not mean "always neutral":
Review: Decent sound, but it broke twice and support never replied.
Sentiment: negativeTogether the two examples show where the line falls. Choose pairs that sit close to the boundary on either side.
Refusals and out-of-scope behavior
For an assistant that answers questions, the out-of-scope response is often a sentence, not a marker. The same rules apply: keep it short, keep it identical across examples, and say what the user can do instead.
When the output is consumed by code, prefer a fixed marker. A program can test for out_of_scope with an equality check. It cannot reliably test for a polite paraphrase. If a person also reads the output, you can map the marker to a message in your own code.
Two guidelines for refusal examples:
- Include only a few. One or two refusal examples are usually enough. If refusals make up half the examples, the model becomes over-cautious and starts refusing valid inputs.
- Make them near misses where you can. An input such as "Is this phone good for gaming?" is close to the task but is a question, not a review. It teaches the boundary better than an obviously unrelated question.
Building the prompt in chat format
In a chat-style API, each example is a user turn followed by an assistant turn, as in earlier chapters. Edge cases work the same way. The assistant turn simply contains the marker.
SYSTEM = (
"Classify the sentiment of each product review as positive, negative, or neutral. "
"If the text is not a product review, answer out_of_scope. "
"If the text is empty or has no readable words, answer invalid. "
"Answer with one word."
)
normal = [
("The battery lasts all day and charging is fast.", "positive"),
("It stopped working after a week.", "negative"),
("The package arrived on Tuesday.", "neutral"),
("Great camera, but the app crashes constantly.", "neutral"),
]
edge = [
("What is the capital of France?", "out_of_scope"),
("!!!! ???", "invalid"),
]
def build_messages(query):
# Interleave edge cases so they are not all at the end.
ordered = [normal[0], edge[0], normal[1], edge[1], normal[2], normal[3]]
messages = [{"role": "system", "content": SYSTEM}]
for text, label in ordered:
messages.append({"role": "user", "content": text})
messages.append({"role": "assistant", "content": label})
messages.append({"role": "user", "content": query})
return messages
if __name__ == "__main__":
for m in build_messages("Is this phone good for gaming?"):
print(m["role"], "->", m["content"])The empty string is a special case in code. Some APIs reject an empty user message. Handle it before the model call: if query.strip() is empty, return invalid directly without calling the model. Code is cheaper and more reliable than a model for checks that need no judgment.
A routing view
Treat the prompt as one stage in a pipeline. Cheap checks run first, the model handles judgment, and the output is validated afterwards.
The final check matters. Even with good examples, the model sometimes writes "Neutral." or "I think it is neutral." Normalize case and punctuation, then reject anything outside the allowed set instead of passing it downstream.
Testing edge cases
Edge-case examples need their own evaluation. Overall accuracy hides failures on rare inputs. If 3 percent of your test set is out of scope, a prompt that never refuses still scores 97 percent on that slice's share.
Build a held-out set with a labeled section for each kind of hard input, and report accuracy per section. Use inputs that are not copies of your in-prompt examples.
def accuracy_by_group(predict, labeled):
"""labeled is a list of (text, label, group) tuples."""
totals, hits = {}, {}
for text, label, group in labeled:
totals[group] = totals.get(group, 0) + 1
if predict(text).strip().lower() == label:
hits[group] = hits.get(group, 0) + 1
return {g: hits.get(g, 0) / n for g, n in totals.items()}
held_out = [
("Works fine, no complaints.", "positive", "normal"),
("Who won the match last night?", "out_of_scope", "out_of_scope"),
("Can I return this after 30 days?", "out_of_scope", "near_miss"),
("...", "invalid", "invalid"),
("Sturdy build, but the hinge squeaks.", "neutral", "mixed"),
]Read the result per group. A drop in normal after adding refusal examples signals over-refusal. A low score in near_miss means your boundary examples are too far from the boundary.
Common mistakes
- Edge cases in a different format. A refusal written as a paragraph, with the normal examples using one word, teaches two tasks.
- Markers that are not in the instruction. If
out_of_scopeappears only in examples, the model may still produce variants such asnot_applicable. - Too many rare cases. Examples teach frequency as well as content. If your real traffic is 2 percent junk, a prompt that is 40 percent junk shifts the model's prior.
- Testing only on the examples. The model can copy a demonstrated answer for a near-identical input without learning the rule.
Exercise
A few-shot sentiment prompt has six examples, all of them clean product reviews. In production, the model labels the question "Where can I buy this?" as neutral. Describe two changes to the prompt and one change to the evaluation that would address this.
Show answer
First, add an instruction that names a marker such as outofscope for text that is not a product review. Second, add one or two examples in the same Review/Sentiment format that show the marker, ideally including a near-miss question like "Where can I buy this?" and placed among the normal examples, not all at the end. For evaluation, add a held-out group of out-of-scope and near-miss inputs that are not copies of the in-prompt examples, and report accuracy per group, including a check that normal reviews are still classified correctly.
Exercise
Why is it better to return a fixed marker such as outofscope than a friendly refusal sentence when the output is parsed by code?
Show answer
Code can check a fixed marker with an equality test against the allowed label set. Free-form sentences vary in wording, so the check would fail or need fragile string matching. If a person needs to see a friendly message, map the marker to text in your own code.