Code Lab / Challenge 8

Semantic Search + RAG Pipeline

MediumEmbed, index, cosine retrieval, context assembly (mini-RAG)

The problem, as an interviewer would set it

Build the retrieval core of a RAG system, end to end, with no external
services. Implement:

1. HashedNGramEmbedder - a deterministic mock embedder. Extract character
   n-grams (default n=3) from normalized text, hash each into one of `dim`
   buckets with a sign (the "hashing trick"), and L2-normalize the result.
   Same text must always produce the same unit vector.

       embed(text: str) -> np.ndarray            # shape (dim,), ||v|| == 1
       embed_batch(texts: list[str]) -> np.ndarray  # shape (len(texts), dim)

2. VectorIndex - cosine top-k retrieval over an in-memory corpus.

       add(docs: list[str]) -> None
       search(query: str, k: int = 3) -> list[tuple[int, float]]
           # [(doc_id, score), ...] sorted by score descending

3. build_prompt(query, docs) - assemble a grounded prompt with numbered
   citations [1], [2], ... so the model can cite sources.

4. recall_at_k(retrieved, relevant, k) - retrieval eval against a golden set:
   mean over queries of |top-k ∩ relevant| / |relevant|.
What interviewers look for

Vector normalization, top-k retrieval correctness, token-budgeted context packing

A strong solution demonstrates:
- Knowing that cosine similarity over L2-normalized vectors is just a dot
  product, so search is a single matrix-vector multiply.
- Determinism awareness: Python's built-in hash() is salted per process
  (PYTHONHASHSEED), so a stable hash (crc32/md5) is required.
- top-k via argpartition (O(n)) before sorting only the k winners, rather
  than a full O(n log n) argsort. Brute force is fine to ~1M vectors; past
  that, say you'd move to an ANN index (HNSW, IVF-PQ) and measure the recall
  you trade for latency.
- Clean separation of embed / index / prompt / eval, which mirrors how real
  RAG stacks are tested (retrieval metrics independent of generation).
Common mistakes: normalizing after batching but not in embed(), recall@k
computed per-doc instead of per-query, prompts that dump documents with no
citation anchors, and dividing by zero when a query has no relevant docs.
Follow-ups: add MMR re-ranking for diversity; swap recall@k for MRR/nDCG;
add a keyword (BM25-ish) scorer and reciprocal-rank-fusion hybrid search;
rerank the top 50 with a cross-encoder; filter by metadata (tenant, ACL,
date) before or during the vector search, not after.

Write your own version first. The reference solution and its tests are one click away when you are ready.

Next challenge