Claude only knows what’s in its training data, plus whatever’s in the current conversation. RAG closes that gap: before answering, the agent searches a knowledge base for relevant content and grounds its answer in it — citing which document the answer came from, rather than guessing.
This module deliberately uses a simple word-overlap similarity score instead of a real embeddings API or vector database, to stay dependency-free:
def cosine_similarity(vec_a: Counter, vec_b: Counter) -> float:
shared = set(vec_a) & set(vec_b)
dot = sum(vec_a[w] * vec_b[w] for w in shared)
magnitude_a = math.sqrt(sum(v * v for v in vec_a.values()))
magnitude_b = math.sqrt(sum(v * v for v in vec_b.values()))
return dot / (magnitude_a * magnitude_b) if magnitude_a and magnitude_b else 0.0
search_knowledge_base scores every document against the query this way and returns the top matches. The search algorithm here is a teaching stand-in — swap it for a real embeddings model and vector index and every other part of this module (the tool definition, the system prompt insisting retrieval happens before answering, the citation requirement) stays exactly the same. That’s the actual lesson: RAG is a structure, not a specific search technology.
The knowledge base (knowledge_base/*.txt) is fictional documentation for a fake product, “Aperture Dashboard,” covering onboarding, billing, security, and API limits — enough variety to see retrieval pick the right document for different questions.
exercise.py — fill in tokenize, cosine_similarity, and search_knowledge_base.solution.py — the completed reference implementation.knowledge_base/ — the documents being searched.pip install -r requirements.txt
export ANTHROPIC_API_KEY=your_key_here
python exercise.py # after filling in the TODOs
python solution.py # to compare against a working version
Try asking about billing, security, and rate limits — each should cite a different document.
Module 9 — Evaluation & Testing Agents — how do you know any of this actually works, beyond trying it by hand?