Lab: Abstain When Evidence Is Missing
Calibrate a retrieval-score threshold on questions with and without answers, add a reply schema that reports full, partial or no support and conflicting sources, and turn each case into an honest response: an answer, a qualified answer, both sides of a conflict, or a not-found message with next steps.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: A corpus with dates and a stand-in retriever
- Step 2: Calibrate the threshold on labelled questions
- Step 3: A reply that reports its own coverage
- Step 4: Turn each case into a response
- Step 5: Swap in a real model
- Troubleshooting
- Check your understanding
- Apply it: stretch task
- Review prompt
Lessons of Grounding & Citations
- Grounded Versus Fluent: Kinds of Unsupported Claims Concept · 15 min
- Asking for Citations and Validating Them Worked example · 20 min
- Lab: Abstain When Evidence Is Missing Lab · 25 min
- Scoring Groundedness on a Sample Worked example · 20 min
- Check: Judge Five Answers for Support Knowledge check · 6 questions
What you will learn
- Implement abstention or qualified answers when retrieved evidence is missing, weak or contradictory.
Prerequisites: RAG Foundations
01. Goal and setup
An assistant that always answers will answer questions its documents cannot. In this lab you give the Lumen help-centre assistant two gates and four kinds of response:
- Gate 1, in code: if the best retrieval score is below a threshold you calibrated, skip the model and say the help centre does not cover the question.
- Gate 2, in the reply: a
statusfield says whether the passages answer all of the question, part of it or none of it, and aconflictsfield lists passages that disagree. - Your code writes the response: an answer with sources, a qualified answer that names what is missing, both sides of a conflict with a stated preference, or a not-found message with next steps.
The corpus has ten passages, the retriever is a word-count stand-in for vector search and the model is a FAKE with scripted replies, so steps 1 to 4 run offline and give exactly the outputs shown. Step 5 swaps in a real model. You need Python 3.12 or later; the lab was tested with Pydantic 2.14 and the anthropic package 2.9, which only step 5 uses.
abstain-lab/
corpus.py ten help-centre passages with IDs, kinds and dates
retrieve.py stand-in retriever: cosine similarity of word counts
calibrate.py sweeps the score threshold over labelled questions
reply.py reply schema: status, claims, gaps and conflicts
try_replies.py checks the schema rules on five sample replies
fake_model.py FAKE model with one scripted reply per question
policy.py the two gates, the conflict rule and the wording
run_policy.py runs five questions through the policy
claude_reply.py gate 2 with a real model (needs an API key)mkdir abstain-lab && cd abstain-lab
python3 -m venv .venv
source .venv/bin/activate # Windows (PowerShell): .venv\Scripts\Activate.ps1
python -m pip install "pydantic>=2.7,<3" "anthropic>=2.9,<3"
python -c "import pydantic, sys; print(sys.version.split()[0], pydantic.VERSION)"3.12.13 2.14.302. Step 1: A corpus with dates and a stand-in retriever
Each passage carries what the conflict rule in step 4 needs: a kind (an official help-centre article or a community forum answer) and the date of its last edit. Two passages disagree on purpose, about upload limits.
"""A small Lumen help-centre corpus: one passage per chunk, each with a stable ID."""
from dataclasses import dataclass
@dataclass(frozen=True)
class Passage:
id: str
title: str
kind: str # "article" (official help centre) or "forum" (community answer)
updated: str # date of the last edit, YYYY-MM-DD
text: str
CORPUS = [
Passage(
"billing-refunds#1", "Refund eligibility", "article", "2026-04-02",
"Monthly plans can be refunded within 14 days of a charge. Annual plans can"
" be refunded within 30 days of purchase; after that you can turn off"
" renewal, but the current term is not refunded.",
),
Passage(
"billing-refunds#2", "Requesting a refund", "article", "2026-04-02",
"To request a refund, open Settings > Billing > Invoices, choose the invoice"
" and select Request refund. Refunds reach the original payment method"
" within 10 business days.",
),
Passage(
"files-limits#1", "File upload limits", "article", "2026-05-12",
"A single file upload can be up to 250 MB on the Business plan and up to"
" 100 MB on the Pro plan.",
),
Passage(
"forum-4821#1", "Forum: what is the max attachment size?", "forum",
"2024-02-03",
"Uploads are capped at 100 MB per file, whatever plan you are on.",
),
Passage(
"guests#1", "Inviting guests", "article", "2026-01-20",
"Guests can view and comment on the projects they are invited to, but"
" they cannot create projects. A workspace can invite up to 50 guests.",
),
Passage(
"export#1", "Exporting workspace data", "article", "2025-11-08",
"Workspace admins can export all projects as CSV or JSON from Settings >"
" Data > Export. Exports larger than 5 GB are emailed as a download link"
" within 24 hours.",
),
Passage(
"sso#1", "Single sign-on", "article", "2026-03-15",
"SAML single sign-on is available on the Business plan. Supported identity"
" providers are Okta, Microsoft Entra ID and Google Workspace.",
),
Passage(
"2fa#1", "Lost two-factor device", "article", "2025-09-30",
"If you lose your authenticator app, sign in with one of your ten backup"
" codes. Without backup codes, a workspace admin can reset two-factor"
" authentication for you.",
),
Passage(
"integrations#1", "Integrations", "article", "2026-02-11",
"Lumen integrates with Slack, GitHub and Google Drive. Workspace admins"
" connect integrations from Settings > Integrations.",
),
Passage(
"api-limits#1", "API rate limits", "article", "2026-06-01",
"The REST API allows 600 requests per minute per workspace. Requests over"
" the limit get status 429 with a Retry-After header.",
),
]
BY_ID = {p.id: p for p in CORPUS}The retriever scores every passage by the cosine similarity of word counts. It is crude, deterministic and fast, which is all the lab needs. In your project, call your vector search and keep the same output: a list of (passage, score) pairs, best first.
"""Stand-in for vector search: cosine similarity of word counts, deterministic.
Swap in the vector search from your RAG tool; keep the (passage, score) output.
"""
import math
import re
from collections import Counter
from corpus import CORPUS, Passage
STOP = set(
"a an and are as at be by can do does for from how i if in is it my of on or"
" the to what when where which who with you your".split()
)
def words(text: str) -> Counter[str]:
tokens = re.findall(r"[a-z0-9]+", text.lower())
# crude stemming: "refunds" and "refund" count as the same word
return Counter(t.removesuffix("s") for t in tokens if t not in STOP)
def cosine(a: Counter[str], b: Counter[str]) -> float:
dot = sum(a[w] * b[w] for w in a)
norm = math.sqrt(sum(v * v for v in a.values()) * sum(v * v for v in b.values()))
return dot / norm if norm else 0.0
VECTORS = {p.id: words(f"{p.title} {p.text}") for p in CORPUS}
def search(question: str, k: int = 3) -> list[tuple[Passage, float]]:
query = words(question)
scored = [(p, round(cosine(query, VECTORS[p.id]), 3)) for p in CORPUS]
scored.sort(key=lambda hit: (-hit[1], hit[0].id))
return scored[:k]
if __name__ == "__main__":
for question in [
"How do I request a refund for an annual plan?",
"Who founded Lumen?",
]:
print(question)
for passage, score in search(question):
print(f" {score:.3f} {passage.id}")python retrieve.pyHow do I request a refund for an annual plan?
0.487 billing-refunds#2
0.324 billing-refunds#1
0.196 files-limits#1
Who founded Lumen?
0.162 integrations#1
0.000 2fa#1
0.000 api-limits#1Nothing in the corpus mentions a founder, yet the second search still returns three passages, because nearest-neighbour search always returns k results. The only hint that they are irrelevant is the score.
03. Step 2: Calibrate the threshold on labelled questions
A threshold only means something on the scale of one retriever. Word-count cosine, one embedding model and another all produce scores in different ranges, so you calibrate on questions you have labelled answerable or not, and sweep. The list mixes 10 questions the corpus answers with 6 it does not.
"""Sweep a threshold on the best retrieval score over labelled questions."""
from retrieve import search
# (question, answerable): True if a passage in the corpus answers it
LABELLED = [
("How do I request a refund for an annual plan?", True),
("How long does a refund take to arrive?", True),
("What is the biggest file I can upload on the Pro plan?", True),
("How many guests can a workspace invite?", True),
("Can guests create projects?", True),
("How do I export all my projects?", True),
("Which identity providers work with single sign-on?", True),
("I lost my phone with the authenticator app. How do I sign in?", True),
("Does Lumen integrate with Slack?", True),
("What happens if I go over the API rate limit?", True),
("Who founded Lumen?", False),
("Can I pay my invoice with PayPal?", False),
("Does Lumen integrate with Jira?", False),
("Is there a mobile app for Android?", False),
("What is the price of the Business plan?", False),
("Can I change the colour theme of the dashboard?", False),
]
best = [(search(q)[0][1], answerable) for q, answerable in LABELLED]
n_in = sum(answerable for _, answerable in best)
n_out = len(best) - n_in
print("threshold answerable passed unanswerable passed")
for threshold in (0.15, 0.20, 0.25, 0.30, 0.35, 0.40):
passed_in = sum(s >= threshold for s, answerable in best if answerable)
passed_out = sum(s >= threshold for s, answerable in best if not answerable)
print(f" {threshold:.2f}{passed_in:>10}/{n_in}{passed_out:>15}/{n_out}")
print(f"lowest answerable score: {min(s for s, a in best if a):.3f}")
print(f"highest unanswerable score: {max(s for s, a in best if not a):.3f}")python calibrate.pythreshold answerable passed unanswerable passed
0.15 10/10 4/6
0.20 10/10 2/6
0.25 10/10 2/6
0.30 10/10 1/6
0.35 8/10 0/6
0.40 7/10 0/6
lowest answerable score: 0.324
highest unanswerable score: 0.340Read the table as a trade-off. Every answerable question passes at 0.30 and below, but one unanswerable question gets through: "What is the price of the Business plan?" scores 0.340, because it shares words with the upload-limits article. At 0.35 every unanswerable question is stopped, at the cost of two answerable ones. No threshold separates the groups, because the lowest answerable score (0.324) is below the highest unanswerable one (0.340). That overlap is normal.
This lab chooses 0.30. Wrongly refusing a question the help centre covers costs the user, and gate 2 exists to catch the question that leaks through. A product where any wrong answer is expensive might choose 0.35 and accept more refusals. Whichever you choose:
- calibrate on far more than 16 questions in a real project, ideally taken from logs, and keep some aside to check the chosen value;
- recalibrate whenever the embedding model, the chunking or the corpus changes;
- log the best score of every request, so that you can see drift.
04. Step 3: A reply that reports its own coverage
Gate 2 needs the model to say how well the passages cover the question, in a form your code can check. The schema extends the cited answer from the previous lesson with a status, the parts that are not covered and any conflicts.
"""What the model returns: claims, plus how well the passages cover the question."""
from typing import Literal, Self
from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, model_validator
class Claim(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(min_length=1)
sources: list[str] = Field(min_length=1, description="Passage IDs, e.g. P1")
class Conflict(BaseModel):
model_config = ConfigDict(extra="forbid")
topic: str = Field(description="What the passages disagree about")
sources: list[str] = Field(min_length=2, description="The disagreeing passages")
class Reply(BaseModel):
model_config = ConfigDict(extra="forbid")
status: Literal["answered", "partial", "not_found"]
claims: list[Claim]
not_covered: list[str] = Field(
description="Parts of the question that no passage answers"
)
conflicts: list[Conflict]
@model_validator(mode="after")
def consistent(self, info: ValidationInfo) -> Self:
retrieved = (info.context or {}).get("retrieved", set())
cited = {s for item in [*self.claims, *self.conflicts] for s in item.sources}
if cited - retrieved:
raise ValueError(f"cites {sorted(cited - retrieved)}, not retrieved")
if self.status == "not_found" and self.claims:
raise ValueError("not_found must not make claims")
if self.status != "not_found" and not self.claims:
raise ValueError(f"{self.status} needs at least one claim")
if self.status == "partial" and not self.not_covered:
raise ValueError("partial must say what is not covered")
return selfThe validator checks consistency, not truth: a not_found reply must make no claims, an answered or partial reply must make at least one, a partial reply must name what is missing, a conflict needs at least two sources, and every ID must have been retrieved. Test the rules with five replies:
import json
from pydantic import ValidationError
from reply import Reply
claim = {"text": "Guests cannot create projects.", "sources": ["P1"]}
replies = [
{"status": "answered", "claims": [claim], "not_covered": [], "conflicts": []},
{"status": "not_found", "claims": [claim], "not_covered": [], "conflicts": []},
{"status": "partial", "claims": [claim], "not_covered": [], "conflicts": []},
{"status": "answered", "claims": [claim], "not_covered": [],
"conflicts": [{"topic": "guest limits", "sources": ["P1"]}]},
{"status": "answered", "claims": [{**claim, "sources": ["P9"]}],
"not_covered": [], "conflicts": []},
]
for number, reply in enumerate(replies, start=1):
try:
Reply.model_validate_json(json.dumps(reply), context={"retrieved": {"P1"}})
print(number, "valid")
except ValidationError as err:
first = err.errors()[0]
where = ".".join(map(str, first["loc"])) or "reply"
print(number, "->", f"{where}: {first['msg']}")python try_replies.py1 valid
2 -> reply: Value error, not_found must not make claims
3 -> reply: Value error, partial must say what is not covered
4 -> conflicts.0.sources: List should have at least 2 items after validation, not 1
5 -> reply: Value error, cites ['P9'], not retrieved05. Step 4: Turn each case into a response
Now the policy. The FAKE model has one scripted reply for each question that passes gate 1.
"""FAKE model for offline practice: one scripted JSON reply per question."""
import json
SCRIPT = {
"How do I request a refund for an annual plan?": {
"status": "answered",
"claims": [
{"text": "Annual plans can be refunded within 30 days of purchase.",
"sources": ["P2"]},
{"text": "Open Settings > Billing > Invoices, choose the invoice and"
" select Request refund.", "sources": ["P1"]},
],
"not_covered": [], "conflicts": [],
},
"What is the upload limit on the Pro plan, and can guests upload files?": {
"status": "partial",
"claims": [
{"text": "On the Pro plan a single file can be up to 100 MB.",
"sources": ["P1", "P2"]},
],
"not_covered": ["whether guests can upload files"], "conflicts": [],
},
"What is the maximum upload size on the Business plan?": {
"status": "answered",
"claims": [
{"text": "On the Business plan a single file can be up to 250 MB.",
"sources": ["P1"]},
{"text": "A forum answer says files are capped at 100 MB on every plan.",
"sources": ["P2"]},
],
"not_covered": [],
"conflicts": [{"topic": "the Business plan upload limit",
"sources": ["P1", "P2"]}],
},
"What is the price of the Business plan?": {
"status": "not_found", "claims": [],
"not_covered": ["the price of the Business plan"], "conflicts": [],
},
}
def fake_chat(system: str, messages: list[dict[str, str]]) -> str:
question = messages[0]["content"].rsplit("Question: ", 1)[1]
return json.dumps(SCRIPT[question])respond() applies gate 1, labels the passages, asks the model and validates the reply. The passages go to the model with their updated dates, so it can tell when two of them disagree.
"""Gate 1 skips weak retrieval; gate 2 lets the model report what is covered."""
import json
from collections.abc import Callable
from datetime import date
from pydantic import ValidationError
from corpus import Passage
from fake_model import fake_chat
from reply import Conflict, Reply
from retrieve import search
THRESHOLD = 0.30 # from calibrate.py; recalibrate whenever retrieval changes
NEXT_STEPS = "Try other words, browse the help centre, or contact Lumen support."
RANK = {"article": 0, "forum": 1} # lower outranks higher
SYSTEM = (
"You answer questions about Lumen using only the passages in <doc> tags.\n"
"- Make claims, one fact each, citing passage IDs such as P1.\n"
"- status is answered if the passages answer every part of the question,"
" partial if they answer some parts (list the rest in not_covered), and"
" not_found if they answer none of it (then make no claims).\n"
"- If passages disagree, make a claim for each side and add a conflict.\n"
"Reply with only a JSON object that matches this JSON Schema:\n"
+ json.dumps(Reply.model_json_schema())
)
Chat = Callable[[str, list[dict[str, str]]], str]
def respond(question: str, chat: Chat = fake_chat) -> str:
hits = search(question)
if hits[0][1] < THRESHOLD: # gate 1: no model call at all
return f"[gate 1, best score {hits[0][1]:.3f}] {not_found()}"
labelled = {f"P{n}": passage for n, (passage, _) in enumerate(hits, start=1)}
context = "".join(
f'<doc id="{pid}" title="{p.title}" updated="{p.updated}">\n{p.text}\n</doc>\n'
for pid, p in labelled.items()
)
messages = [{"role": "user", "content": f"{context}\nQuestion: {question}"}]
try:
reply = Reply.model_validate_json(
chat(SYSTEM, messages), context={"retrieved": set(labelled)}
)
except ValidationError: # add the retry from the previous lesson here
titles = ", ".join(p.title for p in labelled.values())
return f"I could not build a sourced answer. Related articles: {titles}."
return render(reply, labelled)The second part writes the response. The model never writes the not-found or partial wording: fixed text always offers next steps, and the conflict explanation applies a rule you can read and test. preference() ranks official articles above forum answers, then newer edits above older ones. When a newer source loses to an older but more authoritative one, the response says so and suggests confirming with support.
def not_found() -> str:
return f"I could not find this in the Lumen help centre. {NEXT_STEPS}"
def render(reply: Reply, labelled: dict[str, Passage]) -> str:
if reply.status == "not_found": # gate 2
return f"[gate 2, model found no answer] {not_found()}"
lines = [
f"{c.text} [{', '.join(labelled[s].id for s in c.sources)}]"
for c in reply.claims
]
lines += [explain(conflict, labelled) for conflict in reply.conflicts]
if reply.status == "partial":
missing = "; ".join(reply.not_covered)
lines.append(f"The help centre does not cover {missing}. {NEXT_STEPS}")
return "\n".join(lines)
def preference(p: Passage) -> tuple[int, int]:
"""Official articles before forum answers, then newer before older."""
return RANK[p.kind], -date.fromisoformat(p.updated).toordinal()
def explain(conflict: Conflict, labelled: dict[str, Passage]) -> str:
preferred, *others = sorted((labelled[s] for s in conflict.sources), key=preference)
rest = ", ".join(f"{p.id} ({p.kind}, {p.updated})" for p in others)
text = (
f"Sources disagree on {conflict.topic}. Going by {preferred.id}"
f" ({preferred.kind}, {preferred.updated}) over {rest}: official"
" articles outrank forum answers, and newer edits outrank older ones."
)
if any(p.updated > preferred.updated for p in others):
text += " A newer source disagrees, so please confirm with support."
return textimport textwrap
from policy import respond
QUESTIONS = [
"How do I request a refund for an annual plan?",
"What is the upload limit on the Pro plan, and can guests upload files?",
"What is the maximum upload size on the Business plan?",
"What is the price of the Business plan?",
"Who founded Lumen?",
]
def show(question: str, **options) -> None:
print(question)
for line in respond(question, **options).splitlines():
print(textwrap.fill(line, 78, initial_indent=" ", subsequent_indent=" "))
if __name__ == "__main__":
for question in QUESTIONS:
show(question)python run_policy.pyHow do I request a refund for an annual plan?
Annual plans can be refunded within 30 days of purchase. [billing-refunds#1]
Open Settings > Billing > Invoices, choose the invoice and select Request
refund. [billing-refunds#2]
What is the upload limit on the Pro plan, and can guests upload files?
On the Pro plan a single file can be up to 100 MB. [files-limits#1,
forum-4821#1]
The help centre does not cover whether guests can upload files. Try other
words, browse the help centre, or contact Lumen support.
What is the maximum upload size on the Business plan?
On the Business plan a single file can be up to 250 MB. [files-limits#1]
A forum answer says files are capped at 100 MB on every plan. [forum-4821#1]
Sources disagree on the Business plan upload limit. Going by files-limits#1
(article, 2026-05-12) over forum-4821#1 (forum, 2024-02-03): official
articles outrank forum answers, and newer edits outrank older ones.
What is the price of the Business plan?
[gate 2, model found no answer] I could not find this in the Lumen help
centre. Try other words, browse the help centre, or contact Lumen support.
Who founded Lumen?
[gate 1, best score 0.162] I could not find this in the Lumen help centre.
Try other words, browse the help centre, or contact Lumen support.Five questions, five behaviours:
- A full answer, every claim cited.
- A qualified answer: the upload limit is answered, and the guest question is named as not covered instead of guessed. The guests article says what guests can do, and silence about uploads is not evidence either way.
- A conflict, shown with both sides and the reason for the preference, instead of quietly picking one.
- A question that passed gate 1 on shared words, which the model then reported as not found.
- A question stopped at gate 1 without a model call, which also saves tokens on obviously out-of-scope traffic.
The last two show why you need both gates: the threshold is cheap but blunt, and the model catches what the threshold lets through. A reply that fails validation ends in a short note with related articles; the one-retry loop from the previous lesson fits at the comment in respond().
06. Step 5: Swap in a real model
To run gate 2 with Claude, pass an adapter that turns on structured outputs. As in the previous lesson, the provider enforces the shape and your validator still checks the IDs and the status rules. transform_schema() also moves constraints the API cannot enforce, such as a conflict's minimum of two sources, into the field description, so only Pydantic checks them.
"""Gate 2 with a real model. Needs ANTHROPIC_API_KEY and ANTHROPIC_MODEL."""
import os
import anthropic
from reply import Reply
from run_policy import show
client = anthropic.Anthropic()
FORMAT = {"type": "json_schema", "schema": anthropic.transform_schema(Reply)}
def claude_chat(system: str, messages: list[dict[str, str]]) -> str:
response = client.messages.create(
model=os.environ["ANTHROPIC_MODEL"], # for example claude-sonnet-5-5
max_tokens=16000,
system=system,
messages=messages,
output_config={"format": FORMAT},
)
# A refusal or a cut-off reply fails validation, so respond() falls back.
return "".join(block.text for block in response.content if block.type == "text")
if __name__ == "__main__":
for question in ["Can guests upload files?", "Does Lumen integrate with Jira?"]:
show(question, chat=claude_chat)ANTHROPIC_MODEL=claude-sonnet-5-5 python claude_reply.pyCan guests upload files?
Guests can view and comment on the projects they are invited to. [guests#1]
The help centre does not cover whether guests can upload files. Try other
words, browse the help centre, or contact Lumen support.
Does Lumen integrate with Jira?
[gate 1, best score 0.265] I could not find this in the Lumen help centre.
Try other words, browse the help centre, or contact Lumen support.A real model will sometimes answer partly where you expected not found, or the reverse; that is why the status rules are validated and the wording stays in code. Whenever the model answers an out-of-scope question anyway, add the question to your calibration set and to the sample you will score in the next lesson.
07. Troubleshooting
08. Check your understanding
09. Apply it: stretch task
Finish the practice project for this skill:
- Add both gates to your RAG tool, with a threshold calibrated on your own labelled questions (at least 30, with a held-out part to check the value).
- Keep the claim-level citations and validation from the previous lesson.
- Run your 10 in-scope and 5 out-of-scope questions with a real model. For each, record the best retrieval score, the gate result, the status, the cited chunk IDs and any rejected citations.
- Count how many out-of-scope questions were stopped at gate 1, how many at gate 2, and how many were answered anyway, and how many in-scope questions were wrongly refused.
Stretch: add a newer forum answer that contradicts an older official article and check that the response flags the disagreement and suggests confirming with support. Then decide, in writing, whether your product should ever prefer a newer forum answer over an older article.
10. Review prompt
Without looking back:
- Why must a retrieval-score threshold be calibrated for each retriever, and what do you trade when you raise it?
- What do the two gates each catch, and why is one of them not enough?
- Write the four kinds of response, with one example question for each.
- Which rule did the lab use to prefer one of two conflicting sources, and what does the response say when the rule picks the older one?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.