Skip to content
ml-recall

Topic notes

RAG & Agents

Giving an LLM outside knowledge and the ability to act — retrieval-augmented generation, tool calling, the agent loop, MCP hosts, clients and servers, and how agents are observed and evaluated.

4-min read AI-checked

Practise 47 questions Take a test

Key ideas

Formulas

Worked example

In code

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer

chunks = ["Refunds are possible within 30 days of purchase.",
          "Shipping to Taiwan takes 5 to 7 business days.",
          "Gift cards cannot be refunded or exchanged."]
query = "Are refunds possible after 40 days?"
vec = TfidfVectorizer(stop_words="english").fit(chunks)    # index the knowledge base
C, q = vec.transform(chunks).toarray(), vec.transform([query]).toarray()[0]
scores = C @ q                                             # rows are L2-normalized: cosine
top = np.argsort(-scores)[:2]                              # retrieve the top-k = 2 chunks
prompt = "Answer from the context only.\n" + "\n".join(chunks[i] for i in top) + "\nQ: " + query
print(scores.round(2), top)                                # [0.75 0.17 0.  ] [0 1]

The prompt now starts with the refund rule; the LLM answers from it. Exact keyword matching is brittle: for "Can I get a refund after 40 days?" only "days" matches ("refund" ≠ "refunds"), so the refund and shipping chunks tie at 0.355. Dense embeddings or stemming close this gap.

Common pitfalls

References

  1. Hugging Face AI Agents Course — Unit 2.1, Building Agentic RAG Systems (introduction, Enhanced Retrieval Capabilities)
  2. Hugging Face AI Agents Course — Unit 1, What are Tools? (How do tools work?, How do we give tools to an LLM?)
  3. Hugging Face AI Agents Course — Unit 1, Actions (Types of Agent Actions, The Stop and Parse Approach, Code Agents)
  4. Model Context Protocol Specification (2025-06-18): Architecture — Core Components (Host, Clients, Servers)
  5. Model Context Protocol Specification (2025-06-18): Server Features Overview — Overview (control hierarchy of Prompts, Resources, Tools)
  6. Hugging Face AI Agents Course — Bonus Unit 2, AI Agent Observability and Evaluation (Traces and Spans, Key Metrics, Offline and Online Evaluation)
  7. Yao et al. (2022), ReAct: Synergizing Reasoning and Acting in Language Models — Sec. 2 ReAct: Synergizing Reasoning + Acting (Figure 1: Thought, Act, Obs trajectories)
  8. Wikipedia: Evaluation measures (information retrieval) — Offline metrics (Precision, Recall, Precision at k, Average precision, Mean average precision)