Mem0mem0ai 2.0.20 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
24 small wins to finish your pathNext lesson

Writing the stand-in embedder

The model decides what to keep. The embedder is what makes it findable, and it is the piece that makes search feel like magic when it works.

An embedder turns text into a list of numbers. The only rule that matters is that texts meaning similar things should produce similar lists, because search works by measuring how close two lists are.

python
class PretendEmbedder(Embeddings):
    """One vector per text, built from its words. Same words, same vector."""

    def embed_query(self, text):
        vector = [0.0] * 64
        for word in WORD.findall((text or "").lower()):
            vector[sum(ord(c) for c in word) % 64] += 1.0
        size = sum(v * v for v in vector) ** 0.5 or 1.0
        return [v / size for v in vector]

    def embed_documents(self, texts):
        return [self.embed_query(t) for t in texts]

Sixty-four numbers, one slot per bucket. Every word in the text adds one to the slot its letters add up to, and the whole list is then scaled to length one so that a long memory does not beat a short one just for being long.

Two texts sharing words land in the same slots, so they end up close. Two texts sharing meaning but not words do not, which is exactly the limitation to keep in mind.

Watching it work

Example
from pretend_mem0 import PretendEmbedder

embed = PretendEmbedder()
a = embed.embed_query("I prefer email updates")
b = embed.embed_query("email updates please")
c = embed.embed_query("deliver to the office")

near = lambda x, y: round(sum(i * j for i, j in zip(x, y)), 2)
print("shared words ", near(a, b))
print("no overlap   ", near(a, c))

Nearly one for the pair that shares words and nothing for the pair that does not. That single number is what ranks every search result in this course.

The stand-in matches words. A real embedder matches meaning. Search for how should we contact him here and you get nothing, because no word overlaps, while a real embedder would find the email memory immediately. So in this course, search with words you expect to see. That limitation is not a bug in the code, it is the entire difference between a word index and an embedding, and it is worth feeling once.

Sixty-four, and why the number matters

The store has to be told the same length. Say 64 here and 1536 in the store configuration and Mem0 will fail on the first insert, complaining about dimensions. It is the most common setup error when swapping an embedder, including the swap to a real one in lesson 19.

Try it yourself
  • Compare SMS with I prefer email updates, not SMS and explain the score.
  • Change the vector length to 8 and see two unrelated sentences start colliding.
  • Try near on two sentences that mean the same thing with no shared words.

Little by little, you're building something great.