Saqqa Academy

What are embeddings? Cosine similarity explained with a runnable example

Embeddings turn text into lists of numbers so a computer can compare meaning. Learn how they work, how cosine similarity scores them, and try it in JavaScript.

Saqqa Academy team

21-Nov-2026 · 5 min read

In this article

An embedding is a list of numbers that an AI model produces for a piece of text, so that texts with a similar meaning get similar lists. You compare two embeddings with cosine similarity, a score that is close to 1 when the two texts mean nearly the same thing and much lower when they are unrelated. That is how "Do you deliver on Sundays?" can find "Our delivery days are Monday to Saturday" even though the two sentences share almost no words. Embeddings power semantic search, the retrieval step in RAG, duplicate detection and grouping similar support questions.

This post explains the idea with a tiny example you can run in Node.js without an API key, then shows what a real embedding request looks like.

Why keyword search is not enough

Imagine a small shop's help page. A customer types "do you ship on weekends". The answer on the page says "delivery days are Monday to Saturday". A keyword search looks for the words ship and weekends, finds neither, and returns nothing.

An embedding model doesn't look at the words themselves. It has learned from huge amounts of text that ship and deliver are used in similar ways, and that weekend relates to Saturday and Sunday. So the vectors for the question and the answer end up pointing in nearly the same direction. Our post on what RAG is builds a tiny keyword version of this search; embeddings are the upgrade that makes it understand meaning.

How embeddings work, step by step

  1. Pick an embedding model. This is a different model from the chat model you talk to. OpenAI, Google, Voyage AI and several open-source projects offer them. Anthropic's embeddings guide (checked 21 November 2026) says Anthropic does not offer its own embedding model and points to Voyage AI as one option.
  2. Embed your documents once. Split your content into short chunks (a paragraph or an FAQ answer each), send each chunk to the model, and store the vector it returns next to the text.
  3. Embed the question. When a user asks something, send the question to the same model to get its vector.
  4. Compare. Score the question's vector against every stored vector with cosine similarity.
  5. Use the best matches. Show the top results as search results, or paste them into a prompt so a chat model can answer from them.
Embedding search flow: documents are embedded once and stored; the question is embedded with the same model; cosine similarity ranks stored vectors; the top matches go to search results or a chat prompt.
Embed documents once, embed each question, then rank by cosine similarity.

The one rule you must not break: use the same embedding model for documents and questions. Vectors from two different models live in different "spaces" and comparing them gives meaningless scores.

What cosine similarity measures

Think of each embedding as an arrow from the centre of a map. Cosine similarity ignores how long the arrows are and only asks: how close are their directions?

  • Arrows pointing the same way score close to 1.
  • Arrows at a right angle score 0.
  • Arrows pointing in opposite directions score -1.

In practice, text embeddings rarely go far below 0, and what counts as a "good" score depends on the model. Don't copy a threshold like 0.8 from someone else's project; test with your own data and see where relevant and irrelevant results fall.

Cosine similarity as the angle between arrows: the question and the delivery answer point almost the same way and score near 1; the weather sentence points elsewhere and scores low.
Cosine similarity compares direction, not length. Scores from the example in this post.

The formula is short: multiply the two lists number by number and add the results (the dot product), then divide by the length of each arrow.

Try it: cosine similarity in JavaScript

Real embeddings have hundreds or thousands of numbers. To keep the maths visible, this example uses made-up three-number vectors. Save it as cosine.mjs and run node cosine.mjs. We tested it with Node.js on 21 November 2026.

js
// Toy 3-number "embeddings" so you can see the maths.
// Real models return hundreds or thousands of numbers per text.
const vectors = {
  "Do you deliver on Sundays?":   [0.9, 0.1, 0.2],
  "Our delivery days are Mon-Sat": [0.8, 0.2, 0.1],
  "How much is the gift box?":     [0.1, 0.9, 0.3],
  "I love sunny weather":          [0.2, 0.1, 0.9],
};

function cosineSimilarity(a, b) {
  let dot = 0, lenA = 0, lenB = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    lenA += a[i] * a[i];
    lenB += b[i] * b[i];
  }
  return dot / (Math.sqrt(lenA) * Math.sqrt(lenB));
}

const question = "Do you deliver on Sundays?";
const q = vectors[question];
const ranked = Object.entries(vectors)
  .filter(([text]) => text !== question)
  .map(([text, v]) => ({ text, score: cosineSimilarity(q, v) }))
  .sort((x, y) => y.score - x.score);

for (const { text, score } of ranked) {
  console.log(score.toFixed(3), text);
}

Output:

0.987 Our delivery days are Mon-Sat
0.430 I love sunny weather
0.271 How much is the gift box?

The delivery answer wins by a wide margin. The other two are both unrelated, and their low scores say so; the small difference between them means nothing. That is normal: only the top of the list matters.

What a real embedding request looks like

With a real model you replace the made-up vectors with API calls. Here is the shape of a request to OpenAI's embeddings endpoint, based on the official embeddings guide and API reference (both checked 21 November 2026). We did not run this one, because it needs a paid API key; the cosineSimilarity function above works with its output unchanged.

js
// Needs Node.js 18+ and an OPENAI_API_KEY environment variable.
async function embed(texts) {
  const res = await fetch("https://api.openai.com/v1/embeddings", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
    },
    body: JSON.stringify({ model: "text-embedding-3-small", input: texts }),
  });
  if (!res.ok) throw new Error(`Embedding request failed: ${res.status}`);
  const json = await res.json();
  return json.data.map((item) => item.embedding); // one vector per text
}

A few practical points from the same guide:

  • You pay per input token, so embedding a whole website costs money once, and each question costs a little more. Our guide to counting tokens before an API call helps you estimate it.
  • text-embedding-3-small returns 1,536 numbers by default, and a dimensions setting lets you ask for fewer to save storage.
  • Each input has a token limit, which is another reason to split long documents into chunks.

Where to store the vectors

For a few hundred chunks, a JSON file and a loop like the one above is honestly enough. For thousands or millions, use a vector database or a database extension that can search vectors quickly, such as pgvector for PostgreSQL. They do the same comparison, just with indexes that avoid checking every row.

Common mistakes

  • Mixing models. Re-embed everything if you switch embedding models.
  • Chunks that are too big. One vector for a 20-page PDF blurs every topic together. Paragraph-sized chunks usually retrieve better.
  • Trusting the top result blindly. Show the top three to five, or let a chat model read them and say when none of them answers the question. Our post on what a context window is explains why you shouldn't paste everything in instead.

Frequently asked questions

Are embeddings the same as tokens?

No. Tokens are the small pieces a model splits text into before reading it. An embedding is the output: one list of numbers that represents the meaning of a whole chunk of text.

Can I use Claude to create embeddings?

Not directly. Anthropic's documentation says it does not offer an embedding model and suggests using a provider such as Voyage AI. You can still use Claude as the chat model that answers from the results.

What is a good cosine similarity score?

It depends on the model and your data. Run a few questions where you know the right answer, look at the scores for good and bad matches, and pick a cut-off between them.

Do I need a vector database?

Not for small projects. A file of stored vectors and a simple loop work fine for a few hundred chunks. Move to a vector database when search gets slow or your data grows large.

  • #embeddings
  • #cosine similarity
  • #semantic search
  • #rag
  • #javascript

Share this guide

Want a full course on this?

Build Apps with AI

Use AI coding assistants to build, fix and ship real websites and apps.

Join the free waitlist

Want to learn AI video properly?

The AI Content Creator Program takes you from your first prompt to a portfolio you can show: 27 short, focused lessons in easy Urdu, with a weekly live session and tasks our team reviews.

Enroll now

Keep learning