AI Hints
Home›LangChain Tutorial›Similarity and Vector Stores
LangChain · Lesson 64 of 120

Similarity

Close in meaning.

⏱ 2 min read▶ Video at 1:12:17🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

How do we measure whether two embeddings are close? The usual measure is cosine similarity. It compares the direction of two vectors. The closer to one, the more similar the meanings.

Similarity
From the video: Similarity
  • Are two vectors close?
  • Cosine similarity
  • Closer to 1 = more similar

Comparing meanings

We embed a customer question, and three sentences from the shop. Then we compute the cosine similarity between the question and each sentence. Run it. The delivery sentence scores highest, even though it shares hardly any words with the question. The unrelated sentences score lower.

cosine.pypython
import math
from langchain_google_genai import GoogleGenerativeAIEmbeddings

def cosine(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))

emb = GoogleGenerativeAIEmbeddings(model="gemini-embedding-001")
question = emb.embed_query("When will my parcel arrive?")
texts = ["Standard delivery takes 3 to 5 working days.",
         "Gift cards never expire.",
         "Story time is every Saturday at 10am."]
for text, vec in zip(texts, emb.embed_documents(texts)):
    print(f"{cosine(question, vec):.3f}  {text}")
Output
0.731  Standard delivery takes 3 to 5 working days.
0.580  Gift cards never expire.
0.563  Story time is every Saturday at 10am.

Reading the scores

The exact numbers depend on the embedding model, so don't treat any value as a magic threshold. What matters is the ranking. The best match comes first. In practice, you never compute this by hand. A vector store does it for you, across thousands of chunks.

keyvalue
Cosinecompares direction
Highermore similar
Rankingwhat matters
In practicethe vector store does it

Summary

Cosine similarity compares embeddings, and the highest scores mean the closest meanings. Next, the vector store that searches all your chunks this way.

Key takeaways
  • Embed both
  • Compare with cosine
  • Rank the results
Next up: Vector Stores — search by meaning