Chapter 21 — Capstone Project: A Course Assistant You Can Trust
Overview¶
Students of this course would like an assistant that answers questions about it. A plain language model would answer fluently, sometimes wrongly, and without sources. Your assistant must be grounded (every answer comes from the course text and cites it), honest (it says “I don’t know” rather than guess) and evaluated (you measure how often it is right, wrong, or silent).
You will build it from parts you have met throughout the course: text processing and TF-IDF (Chapter 13), ranking metrics (Chapter 6), a decision threshold chosen on data (Chapter 11), and the agent loop with tools (this chapter). No API key is needed.
| Part | Task | Points |
|---|---|---|
| A | Build the knowledge base from the course chapters | 15 |
| B | Retrieval: TF-IDF against BM25 | 25 |
| C | Knowing when to say “I don’t know” | 20 |
| D | An agent that routes questions | 20 |
| E | System card | 20 |
import ast, json, math, operator, os, re, urllib.request
from collections import Counter
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer, ENGLISH_STOP_WORDS
def check(name, test):
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
BASE = 'https://chebil.github.io/AI-course-book/chapters/'
CHAPTERS = ['data', 'ch06_ml_intro', 'fit', 'evaluation', 'metrics', 'explainability', 'ch09_unsupervised', 'ch10_reinforcement',
'ch07_neural', 'training', 'convolution', 'ch08_domain_architectures', 'transfer', 'generative', 'ch11_pgm', 'ch12_knowledge_graphs']
def load_markdown(name):
if os.path.exists(f'{name}.ipynb'):
nb = json.load(open(f'{name}.ipynb', encoding='utf-8'))
else:
with urllib.request.urlopen(BASE + f'{name}.ipynb') as r:
nb = json.loads(r.read().decode('utf-8'))
return '\n'.join(''.join(c['source']) for c in nb['cells'] if c['cell_type'] == 'markdown')
TEXTS = {name: load_markdown(name) for name in CHAPTERS}
print({k: len(v.split()) for k, v in TEXTS.items()}, 'words')Part A — The Knowledge Base (15 points)¶
A1 (checked). Complete build_chunks(texts, max_words=250, overlap=50). For each chapter, split the text at lines starting with ## (one piece per section; drop anything before the first section, and drop the sections titled Exercises and Further Reading). A section longer than max_words words is cut into word windows of max_words with overlap (your Exercise 3 of the lab). Return a list of dicts with keys chapter, section (the title after ## ), part (0, 1, ... within the section) and text (the window’s words; the section title is not repeated in later windows).
def build_chunks(texts, max_words=250, overlap=50):
raise NotImplementedError # TODO_toy = {'t': 'intro text\n## 1 A\n' + ' '.join(f'a{i}' for i in range(10)) + '\n## Exercises\nx y\n## 2 B\nb1 b2'}
check('A1: sections, windows and dropped sections on a toy text', lambda: [(c['section'], c['part']) for c in build_chunks(_toy, max_words=6, overlap=2)] == [('1 A', 0), ('1 A', 1), ('1 A', 2), ('2 B', 0)])
CHUNKS = build_chunks(TEXTS)
print(len(CHUNKS), 'chunks;', Counter(c['chapter'] for c in CHUNKS))GOLD = [
('How does dropout reduce overfitting in a neural network?', '15.7 Regularisation: Generalising Better'),
('What is the formula for the output size of a convolution with padding and stride?', '18.3 Padding and Stride'),
('How do I choose the number of clusters with the silhouette?', '13.3 k-Means'),
('What is the difference between SARSA and Q-learning?', '14.7 Temporal-Difference Learning'),
('What does explaining away mean in a Bayesian network?', '22.3 Independence in a Network'),
('How does TransE represent a relation between entities?', '6.7 Reasoning and Completion'),
('Why do LSTM gates help remember information longer than a simple RNN?', '18.9 LSTM and GRU'),
('What is the Viterbi algorithm used for in a hidden Markov model?', '22.7 Hidden Markov Models'),
('How is precision different from recall?', '8.9 Evaluating Classifiers'),
('What does OPTIONAL do in a SPARQL query?', '6.4 Querying with SPARQL'),
('How do experience replay and a target network stabilise deep Q-learning?', '14.8 Deep Reinforcement Learning'),
('What does PCA keep when it reduces the number of dimensions?', '13.8 Principal Component Analysis'),
('What is the vanishing gradient problem, and why does ReLU help?', '15.3 Activation Functions'),
('How does backpropagation use the chain rule to compute gradients?', '15.5 Backpropagation'),
('What is information gain when building a decision tree?', '8.5 Decision Trees'),
('How does a random forest differ from a single decision tree?', '8.6 Ensembles: Many Models Are Better Than One'),
('How does transfer learning reuse a network pretrained on ImageNet?', '18.7 Transfer Learning'),
('What is the open-world assumption of knowledge graphs?', '6.3 Schemas and Inference'),
('How does DBSCAN find clusters of any shape and label noise?', '13.5 DBSCAN: Clusters of Any Shape'),
('What is the exploration and exploitation dilemma in a multi-armed bandit?', '14.5 Exploration and Exploitation'),
]
titles = {c['section'] for c in CHUNKS}
assert all(s in titles for _, s in GOLD), [s for _, s in GOLD if s not in titles]A retriever is a function retrieve(question, k) returning the indices of the k best chunks. We evaluate it by the rank of the first chunk from the right section, as Hits@1, Hits@3 and MRR (Chapter 6). The TF-IDF retriever is given.
tfidf = TfidfVectorizer(stop_words='english', sublinear_tf=True)
TFIDF_INDEX = tfidf.fit_transform([c['section'] + ' ' + c['text'] for c in CHUNKS])
def tfidf_scores(question):
return (TFIDF_INDEX @ tfidf.transform([question]).T).toarray().ravel()
def evaluate(score_fn, gold=GOLD):
ranks = []
for question, section in gold:
order = np.argsort(score_fn(question))[::-1]
ranks.append(1 + next(r for r, i in enumerate(order) if CHUNKS[i]['section'] == section))
ranks = np.array(ranks)
return {'Hits@1': np.mean(ranks == 1), 'Hits@3': np.mean(ranks <= 3), 'MRR': np.mean(1 / ranks)}, ranks
print('TF-IDF:', {k: round(v, 3) for k, v in evaluate(tfidf_scores)[0].items()})B1 (checked). Implement BM25, the classic search-engine ranking function. For a query and a chunk (as lists of tokens), with chunks, the number of chunks containing term , its count in , the length of and the average length:
with , . Each query term counts once; terms absent from every chunk contribute 0. Complete the class: __init__ receives the tokenised chunks; scores(query_tokens) returns one score per chunk.
def tokenize(text):
return [w for w in re.findall(r'[a-z0-9]+', text.lower()) if w not in ENGLISH_STOP_WORDS]
class BM25:
def __init__(self, docs, k1=1.5, b=0.75):
raise NotImplementedError # TODO
def scores(self, query_tokens):
raise NotImplementedError # TODOdef _bm25_ok():
docs = [['cat', 'sat'], ['cat', 'cat', 'dog'], ['bird']]
s = BM25(docs).scores(['cat', 'fish'])
idf = math.log((3 - 2 + 0.5) / (2 + 0.5) + 1); avg = 2.0
expected = [idf * 1 * 2.5 / (1 + 1.5 * (0.25 + 0.75 * 2 / avg)), idf * 2 * 2.5 / (2 + 1.5 * (0.25 + 0.75 * 3 / avg)), 0.0]
return np.allclose(s, expected)
check('B1: BM25 on a toy corpus', _bm25_ok)
bm25 = BM25([tokenize(c['section'] + ' ' + c['text']) for c in CHUNKS])
bm25_scores = lambda question: bm25.scores(tokenize(question))B2. Compare the two retrievers in a table, list the questions on which each fails (rank > 3), and explain one failure by looking at the chunks that beat the right one.
# TODOYour analysis:
Part C — Knowing When to Say “I Don’t Know” (20 points)¶
The assistant answers only when its best retrieval score is at least a threshold ; otherwise it abstains. We score its behaviour on the 20 course questions and on 8 questions it cannot answer from the course:
| answers from the right section | answers from a wrong section | abstains | |
|---|---|---|---|
| course question | +1 | −2 (a wrong answer misleads) | 0 |
| out-of-scope question | −2 | +1 |
OUT_OF_SCOPE = ['What is the capital of Mongolia?', 'Who won the football World Cup in 2022?', 'How do I bake bread at home?',
'What is the boiling point of water in Fahrenheit?', 'Translate good morning into Spanish.',
'What is the stock price of Apple today?', 'How tall is Mount Everest?', 'Who wrote the play Hamlet?']C1 (checked). Complete utility(score_fn, tau), returning the total score of the table above (use the top chunk of score_fn; its section is the answer).
def utility(score_fn, tau):
raise NotImplementedError # TODOcheck('C1: a threshold of 0 answers everything', lambda: utility(bm25_scores, 0.0) == sum(1 if CHUNKS[int(np.argmax(bm25_scores(q)))]['section'] == s else -2 for q, s in GOLD) - 2 * len(OUT_OF_SCOPE))
check('C1: an infinite threshold abstains on everything', lambda: utility(bm25_scores, np.inf) == len(OUT_OF_SCOPE))C2. For BM25, plot the utility against (try the distinct top scores of all 28 questions as candidate thresholds), choose the best , and report how many course questions are answered correctly, answered wrongly and abstained, and how many out-of-scope questions are correctly refused. Why is choosing on these same 28 questions optimistic, and what should be done instead?
# TODOYour answer:
Part D — An Agent That Routes Questions (20 points)¶
The assistant becomes an agent with three tools: calculator (safe arithmetic, from the lab), course_answer (retrieve with BM25; abstain below ; otherwise return the best section’s two most relevant sentences with a citation), and nothing else: anything else gets a polite refusal.
D1 (checked). Complete route(question), the decision function, returning 'calculator' when the question contains an arithmetic expression (digits and an operator such as + - * / ^), and 'course_answer' otherwise. Then complete assistant(question), which calls the chosen tool and returns its text.
OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Pow: operator.pow}
def calculator(expression):
def ev(n):
if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)): return n.value
if isinstance(n, ast.BinOp) and type(n.op) in OPS: return OPS[type(n.op)](ev(n.left), ev(n.right))
if isinstance(n, ast.UnaryOp) and isinstance(n.op, ast.USub): return -ev(n.operand)
raise ValueError('not allowed')
return ev(ast.parse(expression, mode='eval').body)
def course_answer(question, tau=None):
tau = TAU if tau is None else tau
s = bm25_scores(question); best = int(np.argmax(s))
if s[best] < tau:
return "I don't know: this does not seem to be covered in the course."
chunk = CHUNKS[best]
q = set(tokenize(question))
clean = re.sub(r'\s+', ' ', re.sub(r'[#*`|$]', ' ', chunk['text']))
sentences = [x.strip() for x in re.split(r'(?<=[.!?])\s+', clean) if len(x.split()) > 5]
top = sorted(sentences, key=lambda x: -len(q & set(tokenize(x))))[:2]
return ' '.join(top) + f' [source: {chunk["chapter"]}, section "{chunk["section"]}"]'
EXPRESSION = re.compile(r'[\d.]+(?:\s*(?:[-+*/^]|\*\*)\s*\(?\s*[\d.]+\)?)+')
def route(question):
raise NotImplementedError # TODO
def assistant(question):
raise NotImplementedError # TODOcheck('D1: routing', lambda: route('What is 3.5 * 4 + 2?') == 'calculator' and route('What is dropout?') == 'course_answer' and route('Explain chapter 7 of 2020') == 'course_answer')
check('D1: the calculator path', lambda: assistant('Compute 2^10 for me') == '2**10 = 1024')
check('D1: abstention on an unrelated question', lambda: assistant('Who wrote the play Hamlet?').startswith("I don't know"))D2. Run the assistant on the mixed questions below and judge each answer yourself (correct and supported / wrong / rightly refused / wrongly refused). Summarise in a table.
MIXED = ['What is the Viterbi algorithm used for in a hidden Markov model?', 'How much is 17 * 23?',
'What does the discount factor gamma do in reinforcement learning?', 'Who is the president of France?',
'How does a residual connection help train very deep networks?', 'What is 2 ** 0.5?',
'What does a knowledge graph embedding like TransE learn?', 'What is the best restaurant in Riyadh?']
# TODOYour judgement table:
Part E — System Card (20 points)¶
Write a one-page system card (300–400 words) for the assistant, for the course coordinator who would decide whether to offer it to students:
Purpose and users: what it answers, what it does not.
How it works: in plain words, the three parts (search, threshold, tools), and that it extracts sentences rather than generating new text.
Evaluation: your Part B and C numbers; what “right”, “wrong” and “abstained” mean.
Limits and risks: word-matching retrieval, near-miss questions, outdated or incomplete course text, over-reliance by students, privacy (questions may reveal what a student does not understand).
What would change with a language model: fluent answers and better matching, at the cost of possible hallucination; how grounding, citations and abstention would still be enforced.
Recommendation: offer it or not, and with what safeguards.
Your system card:
Grading Rubric¶
| Part | Full marks if… |
|---|---|
| A (15) | chunking correct (checked) |
| B (25) | BM25 correct (checked); a fair comparison; failures explained from the retrieved chunks |
| C (20) | utility correct (checked); threshold chosen and behaviour reported; the optimism of tuning on the test questions explained |
| D (20) | routing and assistant correct (checked); an honest judgement of every mixed answer |
| E (20) | all six sections, accurate numbers, honest limits, a clear recommendation |