Sub topic 8
Where Memories Live: Key-Value, Document, and Vector Stores
This chapter assumes you know basic Python, have called a chat-style LLM API, and understand an agent as an LLM running in a loop with tools. It also assumes you know that a vector is a list of numbers and that similarity measures how close two vectors are.
By now you have seen that a model keeps no state between calls. Long-term memory is therefore data that your code saves somewhere and feeds back into the prompt. This chapter covers where that data can live. The choice of store decides what questions your agent can ask of its memory, how fast it gets answers, and how much work you do to keep the data tidy.
The question comes first
Pick a store by asking how the agent will look a memory up. There are three common lookup styles.
- By exact key. "What is the preferred language of user 42?" You know the name of the thing you want.
- By field or filter. "Show every note for user 42 tagged
billingfrom the last 30 days." You know the properties, not the exact key. - By meaning. "What did the user say that relates to travel plans?" You know the topic, but not the wording that was stored.
Each lookup style maps to a kind of store.
| Store type | Lookup style | Typical examples | Strength | Weakness |
|---|---|---|---|---|
| Key-value | Exact key | Python dict, Redis, DynamoDB | Fast, simple, predictable | You must know the key |
| Document | Fields and filters | JSON files, SQLite, MongoDB, PostgreSQL JSONB | Structured queries, flexible schema | Matches wording, not meaning |
| Vector | Similarity of embeddings | FAISS, pgvector, Chroma, Qdrant | Finds related text with different words | Approximate, needs an embedding model |
Key-value stores
A key-value store maps a string key to a value. It suits small, well-known facts where the agent always asks for the same slot, such as a user profile.
profiles = {}
def set_fact(user_id, field, value):
profiles.setdefault(user_id, {})[field] = value
def get_fact(user_id, field, default=None):
return profiles.get(user_id, {}).get(field, default)
set_fact("u42", "language", "Python")
set_fact("u42", "timezone", "Asia/Kolkata")
print(get_fact("u42", "language"))
print(get_fact("u42", "city", default="unknown"))Writing to the same key replaces the old value. That behavior is useful: when the user changes their timezone, the old one is gone and nothing contradicts it. The cost is that you must decide the keys in advance. A key-value store cannot answer "what do I know about this user's hobbies?" unless you already named a hobbies key.
Use this store for:
- Profile settings and preferences with fixed names.
- Counters, flags, and the latest state of a task.
- Session data that expires. Redis, for example, supports a time-to-live (TTL) on each key.
Document stores
A document store holds records as structured objects, usually JSON. Each record can carry its own fields, such as text, owner, type, tags, and timestamps. You query by those fields.
This is a good fit for agent memory because a memory is rarely just a string. You need to know who owns it, what kind it is, and when it was written. SQLite ships with Python and can store JSON text, so it works for a first version.
import json
import sqlite3
import time
db = sqlite3.connect(":memory:")
db.execute(
"CREATE TABLE memories ("
"id INTEGER PRIMARY KEY, user_id TEXT, kind TEXT, "
"created REAL, doc TEXT)"
)
def write(user_id, kind, doc):
db.execute(
"INSERT INTO memories (user_id, kind, created, doc) VALUES (?, ?, ?, ?)",
(user_id, kind, time.time(), json.dumps(doc)),
)
def recent(user_id, kind, limit=5):
rows = db.execute(
"SELECT doc FROM memories WHERE user_id = ? AND kind = ? "
"ORDER BY created DESC LIMIT ?",
(user_id, kind, limit),
).fetchall()
return [json.loads(r[0]) for r in rows]
write("u42", "episodic", {"text": "Debugged a failing deploy", "tags": ["devops"]})
write("u42", "semantic", {"text": "Prefers concise answers", "tags": ["style"]})
print(recent("u42", "semantic"))The queries use ? placeholders instead of string formatting. Memory text often comes from user input, and building SQL with string concatenation would let that text change the query.
A document store handles "the last five episodic memories for this user" well. It does not handle "memories related to deployment problems" unless the stored text contains the words you search for. A keyword search for deploy would miss "the release pipeline broke."
Vector stores
A vector store keeps an embedding next to each memory and answers queries by similarity. An embedding model turns text into a list of numbers so that texts with similar meaning land close together. The query is embedded with the same model, and the store returns the nearest vectors.
The MemoryStore class from earlier in this tutorial is a minimal vector store. It scans every item and computes cosine similarity. That is called brute-force search, and it is exact. It works well up to a few thousand memories.
Beyond that, scanning gets slow. Production vector stores use approximate nearest neighbor (ANN) indexes such as HNSW. These trade a small chance of missing the true best match for much faster search. Two consequences follow:
- Results are approximate, so a relevant memory can occasionally be missed.
- The index is tied to one embedding model. If you switch models, vectors from the old and new models are not comparable, and you must re-embed everything.
Vector stores are weak at exact facts. A query for "user's timezone" may return a memory about a trip to another country because the topics are close. Do not put facts you need exactly right behind similarity search alone.
Combining stores
Most real agents use more than one store, each for what it does well.
def recall(user_id, query, profiles, vector_store, k=3):
"""Exact profile fields plus the top-k similar memories."""
facts = profiles.get(user_id, {})
similar = vector_store.search(user_id, query, k=k)
return {"profile": facts, "related": [m["text"] for m in similar]}The profile comes from a key-value lookup and is always correct. The related memories come from similarity search and are best-effort. Keeping the two separate in the prompt also helps the model: it can treat the profile as settled and the related items as hints.
Many databases blend these roles. PostgreSQL with the pgvector extension stores JSON documents and vectors in the same row. Then one query can filter by user_id and kind and also rank by similarity. That removes the problem of keeping two systems in sync.
Common errors
- Using a vector store for everything. Similarity search is approximate. Keep exact settings in a key-value or document store.
- Storing only the text. Without
user_id,kind, and a timestamp, you cannot scope, expire, or deduplicate later. Store metadata from the first write. - Filtering after retrieval. If you fetch the top 3 matches across all users and then drop other users' items, you may be left with none. Filter by owner before ranking, as
MemoryStore.searchdoes. - Mixing embedding models. Vectors from different models cannot be compared. Record the model name with each vector.
- Keeping everything in process memory. A dict vanishes when the process exits. Persist anything that must survive a restart.
Exercise
An agent must remember (a) the user's preferred reply language, (b) a list of support tickets the user opened in the last month, and (c) a past conversation where the user described a flaky network problem, so it can be recalled when they later mention "connection drops." Which store type fits each, and why?
Show answer
(a) Key-value: it is a fixed, exact slot that is overwritten on change. (b) Document store: you filter by user, type, and date range, which needs structured fields. (c) Vector store: the later wording ("connection drops") differs from the stored wording ("flaky network"), so retrieval has to match by meaning.
Exercise
Your agent retrieves the top 3 memories across all users, then removes any that belong to other users. Users sometimes get zero memories back. What is wrong, and how do you fix it?
Show answer
The filter runs after ranking, so other users' memories can fill the top 3 and then get discarded. Apply the user_id filter before ranking, either by filtering the candidate list first or by passing a metadata filter to the vector store query.