Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 21: Language Models, RAG and Agents — Implementation

Open in Colab
  1. A complete RAG pipeline over this book: index, retrieve, answer with a citation, and refuse when nothing relevant is found

  2. 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.

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.

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']
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:

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.

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:

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.

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.

No ANTHROPIC_API_KEY set: the live model is skipped. The scripted agent above runs the same loop.

Summary

SectionResult
RAG pipelineTF-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 loopthe same loop runs with a scripted planner or a real LLM; tools are plain functions; errors become observations