Chapter 21: Language Models, RAG and Agents — Implementation
A complete RAG pipeline over this book: index, retrieve, answer with a citation, and refuse when nothing relevant is found
An agent loop with tools, and how a real language model plugs into it
Everything runs offline. Only the optional cell of Section 2 calls a real language model, if you have an API key.
import ast, json, math, operator, os, re, urllib.request
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
np.set_printoptions(precision=3, suppress=True)
1. A Complete RAG Pipeline¶
The theory chapter compared retrievers; here we assemble the whole query pipeline around one of them. The documents are the theory chapters of Parts II and III of this book, one chunk per section (summaries left out); the vectors are TF-IDF; the similarity is the cosine.
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']
def load_notebook(name):
if os.path.exists(f'{name}.ipynb'): # in the book's folder
return json.load(open(f'{name}.ipynb', encoding='utf-8'))
with urllib.request.urlopen(BASE + f'{name}.ipynb') as r: # e.g. in Colab
return json.loads(r.read().decode('utf-8'))
def section_chunks(name):
text = '\n'.join(''.join(c['source']) for c in load_notebook(name)['cells'] if c['cell_type'] == 'markdown')
chunks = []
for part in re.split(r'\n(?=## )', text):
title = part.split('\n', 1)[0].lstrip('# ').strip()
if part.startswith('## ') and title[:1].isdigit() and not title.split(' ', 1)[1].startswith('Summary'):
chunks.append({'source': name, 'title': title, 'text': part})
return chunks
chunks = [c for name in CHAPTERS for c in section_chunks(name)]
print(len(chunks), 'chunks; for example:', [c['title'] for c in chunks[:4]])127 chunks; for example: ['7.1 Look Before You Learn', '7.2 Examples, Features and a Target', '7.3 A First Look', '7.4 Distributions and Outliers']
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(stop_words='english', sublinear_tf=True, ngram_range=(1, 2), min_df=1)
index = vectorizer.fit_transform([c['title'] + ' ' + c['text'] for c in chunks]) # rows have length 1
def retrieve(question, k=3):
scores = (index @ vectorizer.transform([question]).T).toarray().ravel() # cosine similarity
best = np.argsort(scores)[::-1][:k]
return [(chunks[i], scores[i]) for i in best]
for chunk, score in retrieve('How does LoRA reduce the number of trainable parameters?'):
print(f'{score:.3f} {chunk["source"]}: {chunk["title"]}')0.105 transfer: 19.8 Parameter-Efficient Fine-Tuning: LoRA
0.069 transfer: 19.9 Vision Transformers
0.045 ch06_ml_intro: 8.7 k-Nearest Neighbours
Evaluating the retriever. Twelve questions with the section that answers them:
TEST = [
('What is data leakage and how does a pipeline prevent it?', '7.9 Data Leakage'),
('Why use nested cross-validation to report a tuned model?', '10.5 Nested Cross-Validation'),
('When is accuracy misleading with imbalanced classes?', '11.5 Imbalanced Classes'),
('What does a Shapley value measure for one prediction?', '12.5 Explaining One Prediction: Shapley Values'),
('How does DBSCAN find clusters of any shape?', '13.5 DBSCAN: Clusters of Any Shape'),
('What is the difference between SARSA and Q-learning?', '14.7 Temporal-Difference Learning'),
('How does Adam adapt the step size of each weight?', '16.3 Optimisers: Momentum, RMSProp and Adam'),
('What does batch normalisation do in evaluation mode?', '16.6 Batch Normalisation'),
('How does LoRA reduce the number of trainable parameters?', '19.8 Parameter-Efficient Fine-Tuning: LoRA'),
('What is mode collapse when training a GAN?', '20.4 Training GANs'),
('Why do LSTM gates help remember information longer?', '18.9 LSTM and GRU'),
('How do experience replay and a target network stabilise deep Q-learning?', '14.8 Deep Reinforcement Learning'),
]
ranks = []
for question, answer in TEST:
titles = [c['title'] for c, _ in retrieve(question, k=len(chunks))]
ranks.append(titles.index(answer) + 1)
print(f'rank {ranks[-1]:2d} {question}')
ranks = np.array(ranks)
print(f'\nHits@1 {np.mean(ranks == 1):.2f} Hits@3 {np.mean(ranks <= 3):.2f} MRR {np.mean(1 / ranks):.2f}')
rank 1 What is data leakage and how does a pipeline prevent it?
rank 1 Why use nested cross-validation to report a tuned model?
rank 1 When is accuracy misleading with imbalanced classes?
rank 1 What does a Shapley value measure for one prediction?
rank 1 How does DBSCAN find clusters of any shape?
rank 1 What is the difference between SARSA and Q-learning?
rank 2 How does Adam adapt the step size of each weight?
rank 1 What does batch normalisation do in evaluation mode?
rank 1 How does LoRA reduce the number of trainable parameters?
rank 2 What is mode collapse when training a GAN?
rank 1 Why do LSTM gates help remember information longer?
rank 1 How do experience replay and a target network stabilise deep Q-learning?
Hits@1 0.83 Hits@3 1.00 MRR 0.92
Ten of the twelve questions find their section first, and all twelve are in the top 3 (Hits@1 0.83, MRR 0.92). The two misses (the Adam and the GAN questions) rank second, behind another section on the same topic. Near-duplicate sections are a real difficulty for RAG over any book or knowledge base.
Answering, with a citation, or refusing. Without a language model we can still give a grounded extractive answer: the sentences of the best chunk that share the most words with the question, with a citation. A language model would instead read the top chunks and write the answer, instructed to cite them. In both cases the system should refuse when the best chunk is not similar enough. The threshold is set from the test questions above: just below the lowest similarity at which a right section was found first.
THRESHOLD = 0.9 * min(retrieve(q, k=1)[0][1] for q, a in TEST if retrieve(q, k=1)[0][0]['title'] == a)
print(f'refusal threshold: similarity {THRESHOLD:.3f}')
def extractive_answer(question, n_sentences=2):
chunk, score = retrieve(question, k=1)[0]
if score < THRESHOLD:
return f"I don't know: the book has nothing close enough (best similarity {score:.2f})."
q_words = set(re.findall(r'[a-z]+', question.lower())) - set(vectorizer.get_stop_words())
clean = re.sub(r'\s+', ' ', re.sub(r'[#*`|]|^- ', ' ', chunk['text'], flags=re.M))
sentences = [s.strip() for s in re.split(r'(?<=[.!?])\s+', clean) if len(s.split()) > 5]
best = sorted(sentences, key=lambda s: -len(q_words & set(re.findall(r'[a-z]+', s.lower()))))[:n_sentences]
return ' '.join(best) + f'\n [source: {chunk["source"]}, "{chunk["title"]}", similarity {score:.2f}]'
for q in ['What does batch normalisation do in evaluation mode?', 'Who won the 2018 football World Cup?']:
print(q); print(' ', extractive_answer(q)); print()refusal threshold: similarity 0.095
What does batch normalisation do in evaluation mode?
For sequences and Transformers, layer normalisation normalises over the units of one example instead of over the batch, so it works the same in training and evaluation and for any batch size. 16.6 Batch Normalisation Even with a good initialisation, the distribution of each layer's inputs changes as the layers before it learn, and a deep network is sensitive to it.
[source: training, "16.6 Batch Normalisation", similarity 0.15]
Who won the 2018 football World Cup?
I don't know: the book has nothing close enough (best similarity 0.04).
2. An Agent Loop with Tools¶
Three tools, each a plain Python function with a description, as an LLM would see them:
SAFE_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv,
ast.Pow: operator.pow, ast.USub: operator.neg}
def calculator(expression: str) -> str:
"""Evaluate an arithmetic expression with + - * / ** and parentheses."""
def ev(node):
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in SAFE_OPS:
return SAFE_OPS[type(node.op)](ev(node.left), ev(node.right))
if isinstance(node, ast.UnaryOp) and type(node.op) in SAFE_OPS:
return SAFE_OPS[type(node.op)](ev(node.operand))
raise ValueError('only numbers and + - * / ** are allowed')
return str(ev(ast.parse(expression, mode='eval').body)) # never eval() untrusted text
CAPITALS = {'Saudi Arabia': 'Riyadh', 'Egypt': 'Cairo', 'Tunisia': 'Tunis', 'Morocco': 'Rabat', 'Jordan': 'Amman',
'France': 'Paris', 'Germany': 'Berlin', 'Japan': 'Tokyo', 'Brazil': 'Brasilia', 'Kenya': 'Nairobi'}
def capital_of(country: str) -> str:
"""Return the capital city of a country, from a small knowledge base."""
return CAPITALS.get(country, f'unknown country: {country}')
def course_search(query: str) -> str:
"""Search the course chapters and return the best-matching section."""
chunk, score = retrieve(query, k=1)[0]
return f'{chunk["source"]} / {chunk["title"]} (similarity {score:.2f}): {chunk["text"][:300]}...'
TOOLS = {'calculator': calculator, 'capital_of': capital_of, 'course_search': course_search}The loop is the same whatever chooses the actions: ask the decision-maker for the next step; if it is a tool call, run it (catching errors) and record the observation; stop at a final answer or after a maximum number of steps.
To run offline, the decision-maker below is a small scripted planner standing in for the language model: it follows hand-written rules. A real LLM replaces only this function.
def scripted_model(question, history):
"""Stand-in for an LLM: returns {'tool': name, 'input': {...}} or {'answer': text}."""
q = question.lower()
done = [step['tool'] for step in history]
if 'capital' in q and 'capital_of' not in done:
country = next(c for c in CAPITALS if c.lower() in q)
return {'thought': f'I need the capital of {country}.', 'tool': 'capital_of', 'input': {'country': country}}
if 'letters' in q and 'calculator' not in done:
city = history[-1]['observation']
return {'thought': f'Count the letters of {city}, then square the count.', 'tool': 'calculator', 'input': {'expression': f'{len(city)} ** 2'}}
if q.startswith('explain') and 'course_search' not in done:
return {'thought': 'This is about the course: search it.', 'tool': 'course_search', 'input': {'query': question}}
if done == ['capital_of', 'calculator']:
city = history[0]['observation']
return {'answer': f'The capital is {city}; it has {len(city)} letters, and {len(city)} squared is {history[1]["observation"]}.'}
if done == ['course_search']:
return {'answer': extractive_answer(question)}
if history:
return {'answer': history[-1]['observation']}
return {'answer': "I don't know how to answer that with my tools."}
def run_agent(question, model=scripted_model, max_steps=5):
history = []
print(f'QUESTION: {question}')
for step in range(max_steps):
decision = model(question, history)
if 'answer' in decision:
print(f' ANSWER: {decision["answer"][:400]}')
return decision['answer']
print(f' THOUGHT: {decision["thought"]}')
try:
observation = TOOLS[decision['tool']](**decision['input'])
except Exception as e: # errors are observations too
observation = f'error: {e}'
print(f' ACT: {decision["tool"]}({decision["input"]}) -> {observation[:90]}')
history.append({'tool': decision['tool'], 'input': decision['input'], 'observation': observation})
print(' STOPPED: step limit reached')
run_agent('What is the capital of Morocco? Square its number of letters.')
print()
run_agent('Explain what experience replay does in deep Q-learning')
print()
run_agent('What is the weather tomorrow?')QUESTION: What is the capital of Morocco? Square its number of letters.
THOUGHT: I need the capital of Morocco.
ACT: capital_of({'country': 'Morocco'}) -> Rabat
THOUGHT: Count the letters of Rabat, then square the count.
ACT: calculator({'expression': '5 ** 2'}) -> 25
ANSWER: The capital is Rabat; it has 5 letters, and 5 squared is 25.
QUESTION: Explain what experience replay does in deep Q-learning
THOUGHT: This is about the course: search it.
ACT: course_search({'query': 'Explain what experience replay does in deep Q-learning'}) -> ch10_reinforcement / 14.8 Deep Reinforcement Learning (similarity 0.15): ## 14.8 Deep Rein
ANSWER: 14.8 Deep Reinforcement Learning Tables of $Q(s, a)$ cannot cover large or continuous state spaces: an Atari screen has more possible states than atoms in the universe. Naively plugging a network into Q-learning is unstable: consecutive experiences are strongly correlated, and the target moves every time the weights change.
[source: ch10_reinforcement, "14.8 Deep Reinforcement Learning", simila
QUESTION: What is the weather tomorrow?
ANSWER: I don't know how to answer that with my tools.
"I don't know how to answer that with my tools."With a real language model (optional)¶
The cell below connects the same tools to Claude through the Anthropic Python SDK. It runs only if ANTHROPIC_API_KEY is set (in Colab: add it as a secret, then !pip install anthropic); otherwise it prints a message. The loop has the same shape as run_agent: call the model; while it asks for tools, run them and send back the results. It also asks the API to retry on a fallback model if a request is declined (fallbacks="default"), and stops cleanly if the final answer is still a refusal.
TOOL_SPECS = [
{'name': 'calculator', 'description': 'Evaluate an arithmetic expression with + - * / ** and parentheses.',
'input_schema': {'type': 'object', 'properties': {'expression': {'type': 'string'}}, 'required': ['expression']}},
{'name': 'capital_of', 'description': 'Return the capital city of a country, from a small knowledge base.',
'input_schema': {'type': 'object', 'properties': {'country': {'type': 'string'}}, 'required': ['country']}},
{'name': 'course_search', 'description': 'Search the chapters of this AI course and return the best-matching section.',
'input_schema': {'type': 'object', 'properties': {'query': {'type': 'string'}}, 'required': ['query']}},
]
def run_claude_agent(question, max_steps=8):
import anthropic
client = anthropic.Anthropic()
messages = [{'role': 'user', 'content': question}]
for _ in range(max_steps):
response = client.beta.messages.create(
model='claude-opus-5-5', max_tokens=16000, tools=TOOL_SPECS, messages=messages,
betas=['server-side-fallback-2026-07-01'], fallbacks='default')
if response.stop_reason == 'refusal':
return 'The model declined this request.'
if response.stop_reason != 'tool_use':
return ''.join(b.text for b in response.content if b.type == 'text')
messages.append({'role': 'assistant', 'content': response.content})
results = []
for block in response.content:
if block.type == 'tool_use':
try:
results.append({'type': 'tool_result', 'tool_use_id': block.id, 'content': TOOLS[block.name](**block.input)})
except Exception as e:
results.append({'type': 'tool_result', 'tool_use_id': block.id, 'content': f'error: {e}', 'is_error': True})
messages.append({'role': 'user', 'content': results}) # all results in one message
return 'Stopped: step limit reached.'
if os.environ.get('ANTHROPIC_API_KEY'):
print(run_claude_agent('What is the capital of Morocco? Square its number of letters, and explain briefly what experience replay is in this course.'))
else:
print('No ANTHROPIC_API_KEY set: the live model is skipped. The scripted agent above runs the same loop.')No ANTHROPIC_API_KEY set: the live model is skipped. The scripted agent above runs the same loop.
Summary¶
| Section | Result |
|---|---|
| RAG pipeline | TF-IDF over 127 sections finds 10 of 12 sections first and all in the top 3; an extractive answer cites its section, and a similarity threshold refuses off-topic questions |
| Agent loop | the same loop runs with a scripted planner or a real LLM; tools are plain functions; errors become observations |