Embeddings and cosine similarity
Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.
What you will be able to do
#- Compute cosine similarity between small vectors by hand and in code, with deterministic rounding.
- Rank documents against a query vector and predict the exact ranking order.
- State what a high similarity score does and does not imply about truth or correctness.
Overview
#What an embedding is
An embedding model maps text to a vector of numbers such that texts with similar meaning land near each other. "Near" is measured with a similarity metric, and the workhorse is cosine similarity: the cosine of the angle between two vectors, independent of their lengths.
Real embedding models output hundreds to thousands of dimensions learned from data. To make the geometry fully traceable, this course uses tiny hand-designed 3-dimensional mock vectors where each dimension stands for a topic. The math is identical to the real thing; only the dimensionality and the provenance of the vectors differ.
Cosine similarity, computed by hand
function dot(a, b) {
let sum = 0;
for (let i = 0; i < a.length; i++) sum += a[i] * b[i];
return sum;
}
function norm(a) {
return Math.sqrt(dot(a, a));
}
function cosineSimilarity(a, b) {
const raw = dot(a, b) / (norm(a) * norm(b));
return Math.round(raw * 1000) / 1000;
}
Worked values for a query vector [2, 1, 0] about password resets:
| Vector | Meaning in the mock | Cosine to query |
|---|---|---|
[2, 1, 0] | identical topic mix | 1 |
[1, 2, 0] | related, more account weight | 0.8 |
[0, 1, 1] | unrelated office topic | 0.316 |
Check the middle row by hand: dot product 2*1 + 1*2 + 0*0 = 4, norms sqrt(5) and sqrt(5), so 4 / 5 = 0.8. The rounding to three decimals keeps floating-point noise out of comparisons; the unrounded value is 0.7999999999999998, a good reminder that similarity scores are for ranking, not for promises.
Three anchor values are worth memorizing: identical directions give 1, orthogonal topics give 0, and opposite directions give -1.
From similarity to search
Semantic search over documents is a loop you can write in an afternoon:
- Embed every document chunk once, store the vectors.
- Embed the query.
- Score every chunk against the query with cosine similarity.
- Return the top
kby score.
function rankBySimilarity(queryVec, chunks) {
return chunks
.map((c) => ({ id: c.id, score: cosineSimilarity(queryVec, c.vec) }))
.sort((a, b) => b.score - a.score);
}
With a handful of chunks, brute force is fine. Production corpora use approximate nearest-neighbor indexes that trade a little recall for a lot of speed; the scoring math you wrote above is exactly what those indexes approximate.
What a high score does not mean
Cosine similarity measures statistical closeness of text representations. It does not measure truth, freshness, or authority. A plausible-sounding but wrong document can sit near your query; an authoritative document phrased differently can sit far away. Two consequences matter for everything that follows:
- Retrieval quality is a measurable, tunable pipeline stage, not a binary "has embeddings" checkbox. Lesson 9 builds the pipeline; lesson 13 measures it.
- A similarity score is evidence for ranking candidates, never proof that an answer is correct. Grounding answers in retrieved text, and abstaining when retrieval comes up empty, is how a RAG system earns trust.
Also note what embeddings encode: associations present in their training data. That includes stereotypes and stale facts. Treat retrieved chunks as untrusted data (lesson 12) even when your own pipeline produced them.
Continue with ai-engineering-rag-foundations to turn ranking into a grounded answer pipeline.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Implement dot(a, b), norm(a) and cosineSimilarity(a, b) for equal-length numeric vectors. Round the similarity to three decimals with Math.round(raw * 1000) / 1000.
starter.javascriptfunction dot(a, b) { // Sum of elementwise products. } function norm(a) { // Square root of the dot product of a with itself. } function cosineSimilarity(a, b) { // dot(a, b) divided by norm(a) * norm(b), rounded to 3 decimals: // Math.round(raw * 1000) / 1000. }Reveal the reference answer
reference.javascriptfunction dot(a, b) { let sum = 0; for (let i = 0; i < a.length; i++) sum += a[i] * b[i]; return sum; } function norm(a) { return Math.sqrt(dot(a, a)); } function cosineSimilarity(a, b) { const raw = dot(a, b) / (norm(a) * norm(b)); return Math.round(raw * 1000) / 1000; } console.log(String(cosineSimilarity([2, 1, 0], [1, 2, 0])));Authored expected output: 0.8
cosineSimilarity([2, 1, 0], [1, 2, 0]): dot is 4, both norms are sqrt(5), so the raw value is 4/5 = 0.7999999999999998 in floating point; rounding to three decimals yields 0.8. Rounding makes scores comparable across calls.
Exercise 2Predict
Given the query vector [2, 1, 0] and documents docA [2, 1, 0], docB [0, 1, 1], docC [1, 2, 0], predict the logged ranking order and scores produced by rankBySimilarity.
starter.javascriptfunction rankBySimilarity(queryVec, chunks) { // Map each chunk to { id, score } using cosineSimilarity(queryVec, c.vec), // then sort by score descending. } const query = [2, 1, 0]; const chunks = [ { id: "docA", vec: [2, 1, 0] }, { id: "docB", vec: [0, 1, 1] }, { id: "docC", vec: [1, 2, 0] } ]; for (const r of rankBySimilarity(query, chunks)) { console.log(r.id + " " + r.score); }Reveal the reference answer
reference.javascriptfunction dot(a, b) { let sum = 0; for (let i = 0; i < a.length; i++) sum += a[i] * b[i]; return sum; } function norm(a) { return Math.sqrt(dot(a, a)); } function cosineSimilarity(a, b) { const raw = dot(a, b) / (norm(a) * norm(b)); return Math.round(raw * 1000) / 1000; } function rankBySimilarity(queryVec, chunks) { return chunks .map((c) => ({ id: c.id, score: cosineSimilarity(queryVec, c.vec) })) .sort((a, b) => b.score - a.score); } const query = [2, 1, 0]; const chunks = [ { id: "docA", vec: [2, 1, 0] }, { id: "docB", vec: [0, 1, 1] }, { id: "docC", vec: [1, 2, 0] } ]; for (const r of rankBySimilarity(query, chunks)) { console.log(r.id + " " + r.score); }Authored expected output: docA 1 docC 0.8 docB 0.316
docA is identical to the query (1), docC shares the password dimension with extra account weight (0.8), and docB is nearly orthogonal (0.316). Sorting by score descending gives the order docA, docC, docB.
Exercise 3Test
Write assertions for cosineSimilarity covering the three anchors: identical vectors give 1, orthogonal vectors give 0, opposite vectors give -1.
starter.javascriptfunction check(label, condition) { console.log(condition ? "PASS" : "FAIL"); } // Write three assertions for cosineSimilarity: // 1. cosineSimilarity([1, 0, 0], [1, 0, 0]) === 1 // 2. cosineSimilarity([1, 0, 0], [0, 1, 0]) === 0 // 3. cosineSimilarity([1, 0], [-1, 0]) === -1Reveal the reference answer
reference.javascriptfunction dot(a, b) { let sum = 0; for (let i = 0; i < a.length; i++) sum += a[i] * b[i]; return sum; } function norm(a) { return Math.sqrt(dot(a, a)); } function cosineSimilarity(a, b) { const raw = dot(a, b) / (norm(a) * norm(b)); return Math.round(raw * 1000) / 1000; } function check(label, condition) { console.log(condition ? "PASS" : "FAIL"); } check("identical vectors give 1", cosineSimilarity([1, 0, 0], [1, 0, 0]) === 1); check("orthogonal vectors give 0", cosineSimilarity([1, 0, 0], [0, 1, 0]) === 0); check("opposite vectors give -1", cosineSimilarity([1, 0], [-1, 0]) === -1);Authored expected output: PASS PASS PASS
The anchors pin the metric's boundaries. They are the cheapest possible regression test for a similarity function and take seconds to run in any environment.
Exercise 4Explain
Knowledge check: a support document scores 0.9 cosine similarity against a user's question. What does that number establish?
starter.text// Choose the correct option.Reveal the reference answer
reference.textOnly that the document's text is statistically close to the question in the embedding space, making it a good ranking candidate. It does not establish that the document is true, current or sufficient; grounding and evaluation establish usefulness.Authored expected output: Statistical closeness only, useful for ranking
Similarity ranks candidates; it never certifies answers. That distinction drives the grounding rules of lesson 9.
Common misconceptions
#- Myth: a similarity score of 0.8 means the document is correct. Fact: cosine similarity measures statistical closeness of text representations, not truth, freshness or authority.
- Myth: embeddings understand facts. Fact: they encode learned associations, which include stale facts and biases from training data.
- Myth: you need a paid embedding API to learn retrieval. Fact: the geometry is fully learnable with small hand-designed vectors, which is how this course keeps every number checkable.
Follow-up practice
#- ai-engineering-rag-foundations
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.