Lesson 276 of 296
Embeddings and RAG (retrieval-augmented generation)
What you will learn
- The problem RAG solves
- Embeddings and vectors
- Cosine similarity
- Chunking documents
- Vector search and pgvector
- The full RAG pipeline
On this page
The problem
A model does not know your company's documents, your product prices or today's data. You cannot paste every document into every request: it is too big for the context window and too expensive.
RAG (retrieval-augmented generation) solves this: for each question, find the few most relevant pieces of your documents, and send only those to the model with the question. The model then answers from real data, which also reduces hallucination.
Embeddings
An embedding is a list of numbers (a vector) that represents the meaning of a piece of text. An embedding model turns text into this vector, often with hundreds or thousands of numbers.
The key idea: texts with similar meaning get similar vectors, even if they use different words. "How do I reset my password?" and "I forgot my login details" end up close together.
Cosine similarity
To compare two vectors we usually use cosine similarity: a number from -1 to 1. Closer to 1 means more similar in meaning.
function cosineSimilarity(a: number[], b: number[]): number {
if (a.length !== b.length) throw new Error("Vectors must be the same length");
let dot = 0;
let normA = 0;
let normB = 0;
for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i];
normA += a[i] * a[i];
normB += b[i] * b[i];
}
if (normA === 0 || normB === 0) return 0;
return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}
console.log(cosineSimilarity([1, 0], [1, 0]).toFixed(2)); // 1.00 (same direction)
console.log(cosineSimilarity([1, 0], [0, 1]).toFixed(2)); // 0.00 (unrelated)
console.log(cosineSimilarity([1, 2], [2, 4]).toFixed(2)); // 1.00 (same direction, different length)Chunking
Documents are split into chunks before embedding, because:
- A whole document has too many topics for one vector.
- You only want to send the relevant part to the model.
Common choices: chunks of a few hundred tokens, split on headings or paragraphs where possible, with a small overlap so a sentence cut at the edge is not lost. Keep metadata with each chunk: document title, URL, section and date. You need it for citations and filtering.
function chunkWords(text: string, size: number, overlap: number): string[] {
if (overlap >= size) throw new Error("overlap must be smaller than size");
const words = text.split(/\s+/).filter(Boolean);
const chunks: string[] = [];
for (let start = 0; start < words.length; start += size - overlap) {
chunks.push(words.slice(start, start + size).join(" "));
if (start + size >= words.length) break;
}
return chunks;
}
console.log(chunkWords("a b c d e f g h", 4, 1));
// [ 'a b c d', 'd e f g', 'g h' ]Vector search
Comparing the question with every chunk is fine for a few thousand chunks. For millions, databases use approximate nearest neighbour (ANN) indexes such as HNSW, which find very close matches much faster without checking every row.
You do not always need a special vector database. pgvector is a PostgreSQL extension that adds a vector column type and similarity search, so the vectors live next to your normal data (Part 17):
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE doc_chunks (
id bigserial PRIMARY KEY,
doc_title text NOT NULL,
content text NOT NULL,
embedding vector(3) NOT NULL -- real embeddings have hundreds or thousands of numbers
);
-- The 5 chunks closest in meaning to the question's embedding.
-- <=> is pgvector's cosine distance operator (smaller = more similar).
SELECT doc_title, content
FROM doc_chunks
ORDER BY embedding <=> '[0.1, 0.9, 0.2]'
LIMIT 5;The full RAG pipeline
Indexing (done ahead of time, and again when documents change):
- Load documents.
- Split into chunks with metadata.
- Create an embedding for each chunk.
- Store chunks and vectors.
Answering (for each question):
- Create an embedding for the question.
- Find the top matching chunks (for example the top 5).
- Build a prompt: instructions + the chunks, each marked with its source + the question.
- Tell the model to answer only from the given chunks, to cite sources, and to say "I don't know" when the answer is not there.
- Return the answer with links to the sources.
type Chunk = { id: string; text: string; vector: number[] };
function cosine(a: number[], b: number[]): number {
let dot = 0, na = 0, nb = 0;
for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; na += a[i] ** 2; nb += b[i] ** 2; }
return na && nb ? dot / Math.sqrt(na * nb) : 0;
}
function topK(question: number[], chunks: Chunk[], k: number): Chunk[] {
return chunks
.map((c) => ({ c, score: cosine(question, c.vector) }))
.sort((x, y) => y.score - x.score)
.slice(0, k)
.map((x) => x.c);
}
function buildPrompt(question: string, found: Chunk[]): string {
const sources = found.map((c) => `<source id="${c.id}">${c.text}</source>`).join("\n");
return `Answer only from the sources. Cite the source id. If the answer is not in them, say "I don't know".\n${sources}\nQuestion: ${question}`;
}
const chunks: Chunk[] = [
{ id: "returns", text: "You can return items within 30 days.", vector: [0.9, 0.1, 0] },
{ id: "delivery", text: "UK delivery takes 2 to 4 working days.", vector: [0.1, 0.9, 0.1] },
{ id: "jobs", text: "We are hiring developers.", vector: [0, 0.1, 0.9] },
];
const found = topK([0.2, 0.95, 0.1], chunks, 1);
console.log(found[0].id); // delivery
console.log(buildPrompt("How long is delivery?", found).includes('<source id="delivery">')); // trueWhen RAG is the right tool
| Need | Better choice |
|---|---|
| Answer from your own, changing documents | RAG |
| Change the model's style or format permanently | Prompting first; fine-tuning only if prompting fails |
| Exact numbers from your database | A tool call or a SQL query, not vector search |
| A small fixed set of facts | Put them in the system message |
How to say it in an interview
"RAG lets a model answer from our own data. Offline, I split documents into chunks with metadata and small overlaps, embed each chunk and store the vectors, for example in PostgreSQL with pgvector and an HNSW index. For each question I embed it, retrieve the top chunks by cosine similarity, and send them with the question, telling the model to answer only from those sources, cite them, and say when it does not know. For exact figures I use a tool or SQL instead of vector search."
Key words
| Word | Meaning |
|---|---|
| RAG | Retrieve relevant chunks, then send them with the question |
| Embedding | A vector of numbers representing meaning |
| Cosine similarity | A score of how similar two vectors are in direction |
| Chunk | A small part of a document that is embedded and retrieved |
| ANN / HNSW | Fast approximate search for the nearest vectors |
| pgvector | A PostgreSQL extension for storing and searching vectors |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.