Sub topic 13
Scoping Memory by User and Session
This chapter assumes you know basic Python, have called a chat-style LLM API, and understand an agent as an LLM in a loop. It also assumes you have seen the MemoryStore from the earlier chapters on long-term memory.
Why scope matters
A long-term store holds many memories. Without boundaries, a search for "what is my address?" can return another person's address. Scoping means attaching identifiers to each memory and filtering on them before ranking by similarity.
Two scopes cover most agents:
- User scope: facts that belong to one person and should follow them across conversations, such as a name or a preferred language.
- Session scope: facts that only matter in one conversation, such as the file being edited right now.
Choosing a scope
| Information | Scope | Reason |
|---|---|---|
| "I am vegetarian" | User | Useful in every future chat |
| "Use the second draft in this chat" | Session | Meaningless in a new chat |
| "Our refund policy is 30 days" | Shared (app-wide) | Same for everyone, and not personal |
Short-term memory is already session-scoped, because the buffer lives with one conversation. Scoping decisions mostly affect long-term memory.
Filtering before ranking
The MemoryStore.search method from the earlier chapter already filters by user_id. The version below adds an optional session_id. A memory with no session_id is user-wide. A memory with one is visible only inside that session.
import math
import time
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b) if norm_a and norm_b else 0.0
class ScopedMemoryStore:
def __init__(self, embed):
self.embed = embed
self.items = []
def write(self, user_id, text, session_id=None, kind="semantic"):
if not user_id:
raise ValueError("user_id is required")
self.items.append({
"user_id": user_id,
"session_id": session_id,
"text": text,
"kind": kind,
"vec": self.embed(text),
"created": time.time(),
})
def search(self, user_id, query, session_id=None, k=3):
if not user_id:
raise ValueError("user_id is required")
q = self.embed(query)
visible = [
m for m in self.items
if m["user_id"] == user_id
and m["session_id"] in (None, session_id)
]
visible.sort(key=lambda m: cosine(q, m["vec"]), reverse=True)
return visible[:k]
# Toy embedding: counts of a few keywords
def embed(text):
words = text.lower().split()
return [words.count(w) for w in ("vegetarian", "draft", "python")]
store = ScopedMemoryStore(embed)
store.write("priya", "Priya is vegetarian")
store.write("priya", "Use the second draft", session_id="s1")
store.write("sam", "Sam likes python")
for hit in store.search("priya", "draft vegetarian", session_id="s2", k=5):
print(hit["text"])Running it prints only "Priya is vegetarian". The session-s1 memory is hidden in session s2, and Sam's memory is hidden from Priya.
Common errors
- Filtering after ranking. If you take the top k from all users and then remove other users' items, you may return too few results. Worse, a bug in the second step leaks data. Filter first.
- Optional identifiers. A default of
user_id=Nonecan match every memory without an owner. Make the identifier required, as the code above does. - Trusting the model to supply the ID. The user ID must come from your authentication layer, not from text the model or the user wrote. Otherwise a message like "I am user sam" can cross the boundary.
- Session IDs that never change. If every chat reuses one session ID, session memories pile up and behave like user memories.
Where scoping fits in the loop
Scoping happens at the two points where memory crosses the store boundary. The agent writes with the current IDs, and it reads with the same IDs.
Exercise
A user says in a chat, "For this conversation, answer in French." Which scope should the memory have, and what happens if you store it as user-scoped?
Show answer
Session scope. If it is stored at user scope, every later conversation retrieves it and the agent keeps answering in French when the user no longer wants that.
Exercise
Why must the user_id filter run before the top-k cut instead of after it?
Show answer
Taking the top k first can fill the result list with other users' memories, so filtering afterward leaves too few results for the right user. It also keeps other users' data in the code path longer, which raises the chance of a leak.