Detailed content
📚 What is RAG
A language model only knows what it saw during training. It doesn’t know your product manual, your store’s exchange policy, or the contract signed yesterday. RAG (Retrieval-Augmented Generation, retrieval-augmented generation) solves this in two steps: first, a search system finds the passages in your documents that relate to the question; then the model receives those passages along with the question and answers based on them, citing the source.
The idea was formalized in a 2020 research paper and became the standard for “chatting with documents.” A knowledge base (knowledge base) is the set of documents prepared for this search. Even with models that accept huge context windows, RAG is still useful: it’s cheaper to send four passages than a thousand pages, updates are immediate (just reindex a file), and citations let you verify the answer.
What it is
RAG is an architectural pattern with two phases: indexing (breaking documents into passages, calculating embeddings, and storing them in an index) and querying (finding the most relevant passages for the question and asking the model to answer based only on them, with citations).
✓ RAG works well for
- ✓Questions about internal and private documents.
- ✓Content that changes (prices, policies, item inventory).
- ✓Answers that need to cite sources for auditing.
- ✓Access control: each user only searches what they’re allowed to see.
✗ RAG doesn’t solve
- ✗Teaching a fixed style or format (that’s a prompt or fine-tuning, module 2.4).
- ✗Questions that require reading everything ("how many contracts expire in March?") — that calls for querying structured data.
- ✗Poor documents: contradictory or outdated documents produce equally poor answers.
- ✗Completely eliminating hallucinations: RAG reduces them but doesn’t eliminate them.
Why learn
This is the most requested AI use case in companies: a support assistant that reads the knowledge base, searches internal policies, or answers questions about contracts. Understanding the two phases helps you diagnose the right problem when an answer fails — and most failures happen in search, not in the model.
Key concepts
🧬 Embeddings
A embedding is a list of numbers (a vector) that represents the meaning of a text. An embedding model, such as nomic-embed-text in Ollama, reads "how do I return a product?" and returns hundreds of numbers. The key is that texts with similar meanings get similar vectors — even without any words in common. "Return" and "exchange policy" end up close together; "Saturday hours" ends up far away.
To measure how "close" two vectors are, use cosine similarity: the angle between two vectors. It ranges from −1 to 1; the closer it is to 1, the more similar the meanings are. If you normalize the vectors (make them all length 1), the cosine becomes a simple dot product — a very fast calculation. Two things to keep in mind: use the same embedding model for documents and questions, and know that switching models requires recalculating the entire index.
What it is
An embedding represents text as a vector in a space where distance means difference in meaning. This lets you search "by meaning" instead of "by the exact word."
Try this: calculate embeddings and compare the meaning of three sentences.
# similarity.py
# 1) in the terminal, once:
# pip install openai numpy
# ollama pull nomic-embed-text
# 2) save this file and run: python3 similarity.py
import numpy as np
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
sentences = [
"How do I return a defective product?",
"Merchandise exchange and return policy",
"Store hours on Saturdays",
]
r = client.embeddings.create(model="nomic-embed-text", input=sentences)
v = np.array([d.embedding for d in r.data])
v = v / np.linalg.norm(v, axis=1, keepdims=True) # normalize: cosine = dot product
print("dimensions of each vector:", v.shape[1])
sim = v @ v.T
for i in range(len(sentences)):
for j in range(i + 1, len(sentences)):
print(f"{sim[i, j]:.3f} {sentences[i][:38]} x {sentences[j][:38]}")
How to check: the first line shows 768 dimensions (the size of the nomic-embed-text). Of the three comparisons, "return" and "exchange policy" should get the highest score; comparisons involving "hours" will be lower. Exact values vary from model to model — the order is what matters. A paid embeddings API works the same way if you replace base_url, api_key e model.
Why learn
Users never phrase a question with the same words used in the document. Embeddings connect “I was charged twice” to a paragraph about “duplicate billing.” Without understanding this link, it’s impossible to adjust the search when it gets things wrong.
Key concepts
✂️ Chunking
Chunking means splitting each document into chunks (chunks) before calculating the embeddings. Choosing the size is a balancing act: a chunk that’s too large mixes several topics, so the vector becomes an unfocused average; a chunk that’s too small loses context ("the period is 30 days" — the period for what?). There is no universal size: test with your real questions and measure the results (topic 7).
Three practices improve almost any chunking approach. Respect the structure: split at headings and paragraphs, not in the middle of a sentence. Overlap (overlap): repeat part of the previous chunk’s ending at the start of the next one, so you don’t split an idea in half. Metadatasave the file, section, date, and who can see each chunk—that’s what becomes the citation and access filter.
What it is
Chunking is the strategy for splitting documents into indexable chunks: the size, split point, overlap, and metadata for each chunk.
| Strategy | How it splits | Use when |
|---|---|---|
| Fixed size | Every N characters or tokens, with overlap. | Unstructured continuous text; a starting point. |
| By structure | Headings, sections, paragraphs, table rows. | Manuals, Markdown, documentation, contracts with clauses. |
| Recursive | Tries a section; if it’s too large, a paragraph; if that’s too large, a sentence. | Mixed documents; the default in several libraries. |
| Parent and child | Searches small chunks, then sends the larger chunk containing them to the model. | When search needs precision and the answer needs context. |
💡 Tip
Before changing the size, look at the chunks. Print ten of them and read them as if you were searching: does each one make sense on its own? A poorly converted PDF—repeated headers on every page, a table turned into number soup—hurts RAG more than any choice of chunk size.
Why learn
Search only finds what was split well. A chunk that mixes shipping and warranty won’t show up for either question; a rule split in half reaches the model only partially. Chunking is the cheapest step to adjust and the one that changes the result the most.
Key concepts
🔎 Vector search and vector databases
Vector search means calculating the question’s embedding and returning the top-k most similar chunks—the k nearest neighbors. With a few thousand chunks, comparing the question with all of them (exact search, or “brute force”) takes milliseconds in a NumPy array, which is what the RAG in Topic 6 does. With millions, you use approximate (ANN, approximate nearest neighbor), with indexes such as HNSW, which trade a little precision for much greater speed.
A vector database stores vectors, text, and metadata, creates these indexes, and lets you filter before searching (“only documents from the legal department,” “only current versions,” “only what this user can see”). Established options include Chroma (embedded, great for getting started), Qdrant (a dedicated, open server), pgvector (a Postgres extension—useful when you already use Postgres), and managed cloud services.
What it is
Vector search finds the k vectors closest to the question vector. A vector database is the system that stores vectors with metadata, indexes them for fast search, and applies filters.
| Option | Profile | Choose when |
|---|---|---|
| In-memory NumPy | Exact search, zero infrastructure. | Learning, prototypes, small datasets. |
| Chroma | Python library embedded in your app, saves to disk. | First real project, one server. |
| pgvector | Vectors inside Postgres, alongside your data. | You already use Postgres and want a single database. |
| Qdrant | Dedicated vector server, rich filters. | Large volume, hybrid search, multiple services. |
🧩 New terms
top-k: how many chunks the search returns; too few may leave out the answer, while too many fill the prompt with noise. HNSW: a graph-shaped index of “shortcuts” between neighboring vectors, used by several databases to search large collections quickly. Metadata filter: a condition applied along with the search, essential for access control.
✓ Best practices
- ✓Start with NumPy or Chroma; switch when you’ve measured the need.
- ✓Filter by permission during the search, not after the response.
- ✓Store the embedding model version alongside the index.
✗ Pitfalls
- ✗Setting up a vector cluster for five hundred documents.
- ✗Mixing vectors from two embedding models in the same index.
- ✗Indexing documents with personal data without a legal basis (LGPD).
Why learn
Choosing a search tool based on the actual size of the problem can save weeks of infrastructure work. And metadata filtering is what prevents an internal assistant from showing an executive team’s contract to someone who shouldn’t see it—a real risk in any corporate RAG system.
Key concepts
🎯 Hybrid search and reranking
Vector search understands meaning, but can stumble over exact terms: a product code (“XR-2049”), a clause number, or a rare proper name. Classic keyword search—the BM25algorithm used by search engines for decades—does the opposite: it finds the exact word and ignores synonyms. Hybrid search runs both and combines the lists.
The most common method for combining them is RRF (Reciprocal Rank Fusion): each chunk gets a score of 1/(60 + position) in each list, and the scores are added. Chunks that rank well in both lists move up. Next comes reranking: a specialized model (a cross-encoder, such as those in the bge-reranker family) reads the question and each candidate together, then reorders them more accurately. It’s slower, so it runs only on the top 20 or 30 from the fusion.
What it is
Hybrid search combines keyword search (BM25) and semantic search (vector search) into a single list, usually with RRF. Reranking is a second step that reorders the best candidates using a model that reads the question and passage together.
Step 1. Get vector search working on its own and measure it (topic 7).
Step 2. If questions with codes, acronyms, or names fail, add BM25 (the rank-bm25 library in Python, or the built-in feature in Qdrant or Postgres) and combine the results with RRF.
Step 3. If the right passage is among the top 20 but not the top 4, add a reranker for the top 20.
Step 4. Measure again. Keep each step only if it improves the score.
Why learn
Real-world knowledge bases are full of codes, acronyms, and names that semantic search misses. Hybrid search and reranking are the two search improvements with the best effort-to-results ratio after good chunking—and knowing the order to apply them helps you avoid complicating the system without a gain.
Key concepts
🧾 Minimal RAG with citations
Time to put everything together in a single script, without a framework: chunking split by paragraphs with overlap, embeddings with the nomic-embed-text, index saved in a JSON file, search exact cosine search with NumPy and answer from llama3.2 with citations in the format [file#passage]. It’s fewer than a hundred lines, and each function corresponds to a box in the diagram from topic 1.
Two details make a difference. The nomic-embed-text was trained with task prefixes— search_document: for passages and search_query: for the question—and works better with them. The answer prompt has three rules: use only the passages, cite the source after every claim, and say “I couldn’t find it” when the answer isn’t there. That last rule does the most to reduce fabrication.
What it is
An end-to-end RAG in Python: indexes a folder of files .md/.txt, searches for the four passages closest to the question, and generates an answer that cites each source, all locally and for free with Ollama.
Goal: a complete RAG—chunking, embeddings, search, and answers with citations.
# rag.py (pip install openai numpy · ollama pull nomic-embed-text · ollama pull llama3.2)
# Usage: python3 rag.py <folder-with-.md-or-.txt> "<your question>"
import json, sys
from pathlib import Path
import numpy as np
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
EMBED, CHAT = "nomic-embed-text", "llama3.2"
TAM, SOBRA, TOP_K = 800, 150, 4 # characters per chunk, overlap, chunks used
INDICE = Path("indice.json") # delete this file to reindex
def fatiar(texto, tam=TAM, sobra=SOBRA):
"""Combines paragraphs up to ~tam characters; each new chunk repeats the end of the previous one."""
paragrafos = [p.strip() for p in texto.split("\n\n") if p.strip()]
trechos, atual = [], ""
for p in paragrafos:
if atual and len(atual) + len(p) > tam:
trechos.append(atual)
atual = atual[-sobra:]
atual = (atual + "\n\n" + p).strip()
if atual:
trechos.append(atual)
return trechos
def embed(textos, prefixo):
r = client.embeddings.create(model=EMBED, input=[prefixo + t for t in textos])
v = np.array([d.embedding for d in r.data], dtype=np.float32)
return v / np.linalg.norm(v, axis=1, keepdims=True) # normalized: cosine = dot product
def indexar(pasta):
trechos, fontes = [], []
for arq in sorted(Path(pasta).rglob("*")):
if arq.suffix.lower() in (".md", ".txt"):
for i, t in enumerate(fatiar(arq.read_text(encoding="utf-8")), start=1):
trechos.append(t)
fontes.append(f"{arq.name}#{i}")
vetores = np.vstack([embed(trechos[i:i + 32], "search_document: ") for i in range(0, len(trechos), 32)])
INDICE.write_text(json.dumps({"modelo": EMBED, "fontes": fontes, "trechos": trechos,
"vetores": vetores.tolist()}, ensure_ascii=False))
print(f"indexed {len(trechos)} chunks from {len(set(f.split('#')[0] for f in fontes))} files")
def carregar():
dados = json.loads(INDICE.read_text())
dados["vetores"] = np.array(dados["vetores"], dtype=np.float32)
return dados
def buscar(pergunta, indice, k=TOP_K):
q = embed([pergunta], "search_query: ")[0]
notas = indice["vetores"] @ q
melhores = np.argsort(-notas)[:k]
return [(indice["fontes"][i], indice["trechos"][i], float(notas[i])) for i in melhores]
def responder(pergunta, achados):
contexto = "\n\n".join(f"[{fonte}]\n{texto}" for fonte, texto, _ in achados)
regras = ("Answer in English using ONLY the provided chunks. "
"End EVERY sentence with the source in brackets, exactly as it appears in the chunk, e.g.: [manual.md#2]. "
"If the answer is not in the chunks, say only: I couldn't find that in the documents.")
r = client.chat.completions.create(model=CHAT, temperature=0, messages=[
{"role": "system", "content": regras},
{"role": "user", "content": f"Chunks:\n{contexto}\n\nQuestion: {pergunta}"},
])
return r.choices[0].message.content
if __name__ == "__main__":
pasta, pergunta = sys.argv[1], sys.argv[2]
if not INDICE.exists():
indexar(pasta)
indice = carregar()
achados = buscar(pergunta, indice)
print("retrieved chunks:")
for fonte, _, nota in achados:
print(f" {nota:.3f} {fonte}")
print("\n" + responder(pergunta, achados))
How to check: create a folder docs/ with two or three files .md of your own (or the test ones in the block below) and run python3 rag.py docs "<a question whose answer is in one of them>". The first run prints "indexed N chunks" and creates indice.json. Then the four chunks appear with their scores (the correct one should be at the top), along with the answer and [file#n]. Ask something that isn't in the files: the answer should be "I couldn't find that in the documents." Small models like llama3.2 sometimes forget the citation or get synonyms wrong; with qwen2.5 (replace CHAT) compliance with the format tends to improve. Did the files change? Delete indice.json. To use paid APIs, replace base_url, api_key and the two model names.
Try this: test documents for RAG (paste into the terminal).
mkdir -p docs cat > docs/trocas.md <<'FIM' # Política de trocas O cliente pode trocar ou devolver um produto em até 30 dias corridos após o recebimento. O produto deve estar sem uso e na embalagem original. Produtos com defeito podem ser trocados mesmo usados. O reembolso é feito no mesmo meio de pagamento em até 10 dias úteis após recebermos o produto de volta. FIM cat > docs/entrega.md <<'FIM' # Entregas Entregamos de segunda a sábado. Pedidos feitos até 14h saem no mesmo dia útil. O frete é grátis para compras acima de R$ 200 nas capitais. Nas demais cidades, o valor aparece no carrinho. O código de rastreio é enviado por e-mail quando o pedido sai do depósito. FIM python3 rag.py docs "Comprei há três semanas e não gostei. Ainda posso devolver?" python3 rag.py docs "Vocês entregam no domingo?" python3 rag.py docs "Qual é o telefone do SAC?"
How to check: the first question should return trocas.md#… at the top and an answer about the 30 days, citing the source. The second should cite entrega.md (Monday through Saturday). The third isn't in the documents—if the model makes up a phone number, the "not found" rule failed, and that's what Topic 7 teaches you to measure. The values in the documents are fictional, just for testing.
Why learn
Frameworks like LlamaIndex and LangChain do all this in a few lines—and hide where the problem is when the answer comes out wrong. Building it by hand once makes it clear what each piece does; then you can use the framework knowing what to change, or discover that you don't need it.
Key concepts
🧪 RAG evaluation
"It seems better" isn't a measurement. Evaluating a RAG starts with a gold set (golden set): 20 to 50 real questions, each with the source that should be found and, if possible, the expected answer. With this, every change—chunk size, embedding model, hybrid search, reranker—becomes a number you can compare before and after.
Measure the two halves separately. For search: o hit@k (for how many questions the right source appeared among the k chunks) and MRR (the average of 1/the right source’s position: 1 if it came first, 0.5 if it came second…). For answer: faithfulness (is everything that was said supported by the chunks?) and relevance (did it answer the question?). Tools like RAGAS automate response metrics using a model as a judge—useful, as long as you manually check a sample.
What it is
Evaluating RAG means running a fixed set of questions and measuring separately whether the search found the right source (hit@k, MRR) and whether the answer was faithful to the sources and relevant to the question.
Try this: measure hit@k and MRR for your RAG search.
# evaluate.py (in the same folder as rag.py, after indexing)
from rag import TOP_K, buscar, carregar
# Gold set: (question, file that should appear). Use REAL user questions.
CASOS = [
("I bought it three weeks ago and didn’t like it. Can I still return it?", "trocas.md"),
("How long does the refund take to come through?", "trocas.md"),
("Can I exchange a broken product that has already been used?", "trocas.md"),
("Do you deliver on Sundays?", "entrega.md"),
("How much is shipping to Belo Horizonte?", "entrega.md"),
("How can I track my order?", "entrega.md"),
]
indice = carregar()
acertos, soma_rr = 0, 0.0
for pergunta, esperado in CASOS:
fontes = [fonte for fonte, _, _ in buscar(pergunta, indice)]
posicao = next((i for i, f in enumerate(fontes, start=1) if f.startswith(esperado + "#")), None)
if posicao:
acertos += 1
soma_rr += 1 / posicao
marca = f"position {posicao}" if posicao else "NOT FOUND"
print(f"{marca:12} {pergunta}")
print(f"\nhit@{TOP_K}: {acertos}/{len(CASOS)} MRR: {soma_rr / len(CASOS):.2f}")
How to check: with the test documents, run python3 avaliar.py: each line shows the position where the right source appeared, followed by hit@4 and MRR. With only two files, it’s easy to get everything right; the value comes from using your real knowledge base. Change TAM file in rag.py, delete indice.json, reindex, and compare the numbers—that’s how you evaluate a change.
✓ Effective evaluation
- ✓Questions drawn from real support tickets and conversations, with personal information removed.
- ✓Includes questions that the documents don’t answer.
- ✓Run it after every change, like an automated test.
- ✓Measures search and answers separately so you know what to change.
✗ Misleading evaluation
- ✗Questions written by copying phrases from the document.
- ✗Testing by looking at just three answers that “seemed good.”
- ✗Trusting the model judge 100% without checking a sample.
- ✗Changing three things at once and not knowing which one helped.
💡 Tip
Read the diagnosis in the right order: if hit@k is low, the problem is search or chunking—changing the response model won’t help. If hit@k is high but the answer is wrong or made up, the problem is in the prompt or generation model.
Why learn
Without evaluation, every RAG adjustment is a guess, and improvements on one question can hide regressions on others. With a gold set and two search metrics, you can use data to decide whether it’s worth changing the model or chunk size, or adding a reranker—and show the results to whoever pays the bill.
Key concepts
✅ Module summary
Next module:
2.4 — Fine-tuning and Customization 🎛️