Capstone: Build and Run the Retrieval Baseline
Run a complete local implementation
Paste the entire script into the CodeWhet Python compiler. It uses only re, does not contact any service, and returns exact evidence rather than generating an answer. The audience parameter represents a trusted authenticated attribute; a production application must never let users grant themselves staff access.
import re
DOCUMENTS = [
{
"id": "refund-v2", "title": "Refund policy",
"audience": "public", "version": 2,
"text": ("Standard purchases qualify for refunds within 14 days. "
"Custom orders are excluded."),
},
{
"id": "account-v1", "title": "Account recovery",
"audience": "public", "version": 1,
"text": ("Use the password reset link to recover an account. "
"Support never asks for your password."),
},
{
"id": "export-v1", "title": "Data exports",
"audience": "public", "version": 1,
"text": "Workspace owners can download CSV exports from settings.",
},
{
"id": "staff-v1", "title": "Internal incident response",
"audience": "staff", "version": 1,
"text": "Internal incident response contact details are staff-only.",
},
]
STOP_WORDS = {"a", "an", "the", "is", "are", "i", "my", "can", "how",
"do", "to", "for", "of", "what", "please", "me", "and"}
def terms(text):
return set(re.findall(r"[a-z0-9]+", text.lower())) - STOP_WORDS
def retrieve(question, audience="public", top_k=2, documents=None):
if not isinstance(question, str) or not question.strip():
raise ValueError("Question must contain text")
if len(question) > 1000:
raise ValueError("Question exceeds this lab's 1000-character limit")
if audience not in {"public", "staff"}:
raise ValueError("Unknown audience")
if not isinstance(top_k, int) or top_k < 1 or top_k > 5:
raise ValueError("top_k must be between 1 and 5")
query = terms(question)
ranked = []
corpus = DOCUMENTS if documents is None else documents
for doc in corpus:
# Permission filtering happens BEFORE scoring and evidence assembly.
if doc["audience"] != "public" and audience != "staff":
continue
words = terms(doc["title"] + " " + doc["text"])
# Query coverage is an intentionally simple lexical score.
score = len(query & words) / len(query) if query else 0.0
if score > 0:
ranked.append((score, doc["id"], doc))
ranked.sort(key=lambda item: (-item[0], item[1]))
return [doc for _, _, doc in ranked[:top_k]]
def assistant(question, audience="public", documents=None):
evidence = retrieve(question, audience=audience, documents=documents)
if not evidence:
return {
"status": "abstain",
"message": "No matching authorized policy found.",
"evidence": [],
}
return {
"status": "evidence",
"message": "Relevant source excerpts; check that they answer your question.",
"evidence": [
{"id": d["id"], "title": d["title"],
"version": d["version"], "text": d["text"]}
for d in evidence
],
}
questions = ["refund policy", "reset password", "download CSV exports",
"internal incident response", "lunar weather"]
for question in questions:
result = assistant(question)
print(question, "=>", result["status"],
[item["id"] for item in result["evidence"]])Expected output
refund policy => evidence ['refund-v2']
reset password => evidence ['account-v1']
download CSV exports => evidence ['export-v1']
internal incident response => abstain []
lunar weather => abstain []Understand the tradeoffs
The query score measures term overlap, not meaning or answer support. It will miss “I want my money back” if those terms never occur in the documents. It can also retrieve a source when only a minor word overlaps. In a real retriever, introduce measured relevance thresholds, lexical normalization, hybrid search, or a reranker as appropriate.
The function receives the corpus explicitly for evaluation, preserves source IDs, and has deterministic tie-breaking. It avoids returning the entire inaccessible corpus to a model. Neither the public/staff string nor the in-memory collection is a complete production identity system.
Exercise with answer
Change the refund policy from 14 to 21 days and change its ID/version to v3/3. What should the next request return? Answer: the new authorized source text and version. No model retraining is needed for this retrieval baseline.
Try the question “refunds for custom orders.” Expected interpretation: the evidence contains the exclusion; a later generator must retain it. Merely returning the right document is not proof of a correct final answer.