::: title

LM02 RAG (aka Retrieval-Augmented Generation)

LLM external memory ::: César Freire

::: image
ai-future.jpeg
:::


What is RAG?


RAG vs. Traditional LLM

Plain LLMRAG system
Knowledge sourceModel weights, frozen at trainingExternal corpus, updated any time
HallucinationsHigh on niche / factual questionsLower — the answer must come from evidence
FreshnessMonths to years oldAs fresh as the last ingest
LatencyOne forward pass+ retrieval, + larger prompt

Cache-Augmented Generation (CAG)

RAGCAG
Knowledge loadedAt query time, on demandOffline, preloaded (context + KV cache)
LatencyVariable; retrieval on every callNo retrieval overhead; TTFT drops sharply
CostPrompt recomputed per queryPreprocessing paid once, amortized over all queries
KB sizeLarge and elasticBounded by the context window / cache budget
FreshnessUpdate one doc, re-embed that docRecompute and reload the whole cache

Python RAG Sample

# Sample knowledge base (documents)
KNOWLEDGE_BASE = [
    "Python is a high-level programming ...",
    "Python supports multiple programming ...",
    "Pandas is a fast, powerful, flexible ...",
    "NumPy is a Python library used for ...",
    "Machine learning is a subset of artificial..."
]
 
class SimpleRAG:
    def __init__(self, knowledge_base: List[str]):
        self.knowledge_base = knowledge_base
    
    # (...)
 

The Role of Vector Stores

EngineTypeBest when
FAISSin-process libraryprototyping, local, single node
Chromaembeddednotebooks and demos
pgvectorPostgres extensionalready on Postgres — SQL, ACID, one backup plan
Qdrantself-hosted serverperformance + rich payload filtering
Weaviateself-hosted serverhybrid search and modules out of the box

The Different Types of RAG

TypeRetrievalWhat it addsUse when
Naïveone vector search, top-knothingprototype, small FAQ
Advancedhybrid, query rewrite, rerank, compressionprecisionmost production systems
Graph (GraphRAG)entities, relations, community summariesmulti-hop and “global” questionscross-document reasoning, e.g. regulations
Agenticthe LLM plans the loop, rewrites, self-reflectsautonomyopen-ended, multi-step queries