AI Hints
Home›LangGraph Tutorial›Memory in Graphs
LangGraph · Lesson 78 of 120

Searching Memories

By meaning.

⏱ 2 min read▶ Video at 1:23:47🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

As memories grow, you can't put them all in every prompt. Better to find the few that matter for this question. Give the store an embedding model, and search becomes search by meaning.

Searching Memories
From the video: Searching Memories
  • Too many memories
  • Find the relevant few
  • Search by meaning

Semantic search in the store

The index setting gives the store an embedding model, and the vector size. Every item we put is embedded. Search with a query returns the closest memories, with a score. Run it. Asked what Sam likes to read, the store returns the reading memories, and leaves out the one about nuts.

memory_search.pypython
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from langgraph.store.memory import InMemoryStore

embeddings = GoogleGenerativeAIEmbeddings(model="gemini-embedding-001")
store = InMemoryStore(index={"embed": embeddings, "dims": 3072})

ns = ("memories", "sam")
store.put(ns, "1", {"text": "Loves space opera and epic sci-fi"})
store.put(ns, "2", {"text": "Allergic to nuts, avoid cafe snacks"})
store.put(ns, "3", {"text": "Prefers paperbacks over hardbacks"})

for item in store.search(ns, query="what kind of books does he like?", limit=2):
    print(f"{item.score:.3f}  {item.value['text']}")
Output
0.744  Loves space opera and epic sci-fi
0.736  Prefers paperbacks over hardbacks

Semantic memory tips

Search by meaning works even when the words differ. Limit the results to a few, to keep prompts short. And just like RAG, check the scores, because the top result isn't always relevant.

keyvalue
indexembed + dims
querysearch by meaning
limita few results
Scorescheck relevance

Summary

A store with an embedding index searches memories by meaning, so prompts include only relevant ones. Next, a new section on reliability, starting with retries.

Key takeaways
  • index={'embed', 'dims'}
  • search(ns, query=...)
  • Only relevant memories
Next up: Retry Policies — trying again