search(): filters, not user_id
Storing is half of it. search is the half that makes a memory useful, and its signature contains the single most common mistake in Mem0 code written before 2.0.
from pretend_mem0 import memory
shop = memory()
shop.add("I prefer email updates, not SMS. Deliver to my office.", user_id="ravi")
for hit in shop.search("email updates", filters={"user_id": "ravi"})["results"]:
print(round(hit["score"], 2), "|", hit["memory"])One question, one answer, and a score saying how close the match was. The other memory scored below the cut and is not shown.
The argument that changed
Every tutorial written for Mem0 1.x passes the user id directly. In 2.0 that raises.
from pretend_mem0 import memory
shop = memory()
shop.add("I prefer email updates, not SMS. Deliver to my office.", user_id="ravi")
try:
shop.search("email updates", user_id="ravi")
except ValueError as wrong:
print(wrong)The error says exactly what to do, which is kinder than most. The trap is that add still takes user_id directly, so the two calls that look like a pair now disagree, and code that has worked for a year fails on one line of it.
add(..., user_id="ravi") but search(..., filters={"user_id": "ravi"}). That asymmetry is worth writing on a sticky note. It exists because search filters can match on far more than an identifier, which lesson 13 uses.The score and the cut
Results come back ranked, highest first, and Mem0 drops anything below a threshold that defaults to 0.1. Raise it when searches return loosely related things and lower it when you know a memory exists but nothing comes back.
from pretend_mem0 import memory
shop = memory()
shop.add("I prefer email updates, not SMS. Deliver to my office.", user_id="ravi")
loose = shop.search("office", filters={"user_id": "ravi"}, threshold=0.0)
print(len(loose["results"]), "results with no cut")
tight = shop.search("office", filters={"user_id": "ravi"}, threshold=0.9)
print(len(tight["results"]), "results with a high cut")top_k caps how many come back and defaults to 20. On a store with a thousand memories per user, both numbers matter.
- Search with a word that appears in neither memory and see what you get.
- Raise the threshold until the correct answer disappears, and note the number.
- Search with
top_k=1and check you get the higher scoring memory.
This is what real progress feels like.