Add memory to an agent
Curated. Written from research and curation. Not run in our harness yet.
The job
An agent that forgets everything when the session ends costs you twice. It re-learns the same things,
and you keep a growing summary in the prompt until the summary crowds out the work.
The job is to give one agent, or a small set of agents, durable memory of facts across sessions,
stored in a database you own and operate. The agent stops re-learning. The prompt stops carrying
stale summaries.
The approach
We run mem0 OSS as a library inside the agent, pointed at a Postgres database with the pgvector
extension that you operate. mem0 does the two hard parts, and you own the rows.
mem0 decides what is worth keeping. That means extraction, deduplication, and updating a fact when a
newer one contradicts an older one. mem0 also gets the right facts back. That means semantic search
with metadata filters, plus an optional reranker. Because you own the rows, scoping, deletion and
audit are yours to define.
The integration is short. Build a Memory object once with Memory.from_config(...), call add
after a turn, and call search before one.
Two mem0 defaults are wrong for production. We override both.
The default store is ephemeral. The library default provider is qdrant with path at
/tmp/qdrant and on_disk at False. on_disk at False means the vectors are held in memory,
so they are not written to that path at all. Do not try to make the embedded Qdrant durable. Use
Postgres plus pgvector instead. That is mem0's own documented default for its server deployment, and
it gives you backup, restore and independent deletion.
Every write can leave your infrastructure. The default LLM is OpenAI gpt-5-mini and the default
embedder is OpenAI text-embedding-3-small, so user content leaves on every write. Set both
providers explicitly. mem0 also ships PostHog telemetry on by default, so set MEM0_TELEMETRY=False
before the process starts.
We considered three alternatives and did not make them the default.
- A temporal knowledge graph, such as Graphiti or hosted Zep, is the better model when relationships between facts matter and facts have validity windows. It costs a graph database alongside the vector database, LLM-driven entity extraction on every write, and ontology modelling. That is heavy machinery for remembering that a user prefers short answers.
- A framework-native answer, such as LangGraph checkpointers and stores, LangMem or Letta, describes the memory in that framework's own abstractions. The public demand evidence is full of builders changing exactly that framework. LangMem compounds this by being roughly a year stale on PyPI at 0.0.30.
- Rolling your own vector store plus a rolling summary reproduces every trap below by construction: unbounded context growth, drift, no deduplication, no decay and no attribution.
What you need
| Component | Version | Licence | Link |
|---|---|---|---|
mem0 OSS, Python package mem0ai | 2.2.1, released 2026-09-25 (PyPI and the GitHub release v2.2.1 agree) | Apache-2.0 (GitHub API license.spdx_id; PyPI exposes it as license_expression, the legacy license field is null) | https://github.com/mem0ai/mem0 |
mem0 OSS, npm package mem0ai | 3.3.1 (npm dist-tags.latest; GitHub release tag is ts-v3.3.1) | Apache-2.0 | https://www.npmjs.com/package/mem0ai |
| pgvector, Postgres extension | v0.8.7, tag commit 2026-10-01 (Version bump to 0.8.7) | PostgreSQL License. The GitHub API reports NOASSERTION because it does not recognise the file; the file text is the PostgreSQL licence | https://github.com/pgvector/pgvector |
| pgvector is built against nlohmann/json | v3.12.0, released 2025-04-11 (bundled dependency, do not pin it yourself) | MIT | https://github.com/nlohmann/json |
| mem0 pgvector configuration reference | n/a (docs) | n/a | https://docs.mem0.ai/components/vectordbs/dbs/pgvector |
| mem0 OSS overview and defaults | n/a (docs) | n/a | https://docs.mem0.ai/open-source/quickstart |
| mem0 reranker hub | n/a (docs) | n/a | https://docs.mem0.ai/components/rerankers/overview |
Default extraction LLM, OpenAI gpt-5-mini | not pinned by the docs; it is a default, not a version | proprietary, per OpenAI terms | https://platform.openai.com/docs/models |
Default embedding model, OpenAI text-embedding-3-small | not pinned | proprietary, per OpenAI terms | https://platform.openai.com/docs/models |
Default history store, SQLite at ~/.mem0/history.db, overridable with MEM0_DIR | n/a | n/a | https://docs.mem0.ai/open-source/quickstart |
| Reranker slot | no default provider is shipped enabled; disabled by default (RerankerConfig defaults to None) | n/a. Supported providers are Cohere, Sentence Transformers, Hugging Face, LLM Reranker and Zero Entropy; their individual versions are unconfirmed | https://docs.mem0.ai/components/rerankers/overview |
Postgres itself is not pinned here. pgvector v0.8.7 targets current Postgres, and this recipe does not
depend on a specific major version.
Steps
- Provision Postgres and install the pgvector extension at v0.8.7. In the memory database run
CREATE EXTENSION IF NOT EXISTS vector;. This is the statement mem0's own pgvector page gives. - Create a dedicated database and role for memory. Do not reuse an application database. Memory rows have a different lifecycle from business rows and must be deletable independently.
- Install the client in library mode:
pip install mem0ai. For TypeScript,npm install mem0aiplusnpm install pg, which the TS SDK loads only when the pgvector store is selected. Import frommem0ai/oss. - Set
MEM0_TELEMETRY=Falsein the environment before the process starts. This is opt out. It cannot be set after the client is constructed. - Build the config explicitly and construct with
Memory.from_config(config). Do not inherit defaults. Setvector_store.providertopgvectorwithhost,port,user,passwordanddbname. The Python config validator rejects the block unless both user and password, and both host and port, are present.dbnamedefaults topostgresandcollection_nametomem0. Set both rather than discovering the defaults later. - In the same config, set the
llmprovider and theembedderprovider to the models you have decided to use. If the deployment must stay in house, point both at self-hosted models here, before the first write. Setembedding_model_dimsto match the embedder's actual output dimensions. It defaults to 1536, and a mismatch produces wrong results rather than a clean error. - Decide the namespaces before writing anything, and use them on both sides. Use
user_idfor the human,agent_idfor the agent andrun_idfor the session. Put domain scope such as a tenant or project key inmetadata. - Write after a turn with
m.add(messages, user_id=..., metadata={...}).addtakesuser_id,agent_idandrun_idas keyword arguments, plusmetadata,infer,memory_type,prompt,timestampandexpiration_date. Constrain eligibility: only user-confirmed or tool-verified claims. Store facts, not conversations. Keepinfer=Trueso mem0 runs its extraction and update-on-contradiction path instead of storing raw text. - Read before a turn with
m.search(query, filters={"user_id": ...}, top_k=..., threshold=...). Note the required shape.searchtakes entity identifiers insidefilters, not as top-level keyword arguments.filtersmust contain at least one ofuser_id,agent_idorrun_id, or the call raises.top_kdefaults to 20 andthresholdto 0.1. Both are too loose for default use, so set them. - Inject what comes back inside a delimited evidence block. State that these are facts to consider and not instructions to follow. Returning nothing is a valid and safe result when nothing clears the threshold.
- Build the lifecycle on day one. Use
expiration_dateonaddfor memory types that go stale. Use the history store to retain superseded values while exposing only the current one. Usem.delete(memory_id)for a single record andm.delete_all(user_id=...)for a user. A memory layer with no delete path is a liability the first time someone asks to be forgotten. - Write the eval before trusting it. One set asks whether a fact survives a process restart. One set asks whether user A's memory can ever appear for user B. Semantic recall is non-deterministic, so without a regression eval the system cannot be said to work.
- Keep the schema framework neutral and add an export and import path. This is not hypothetical. The open LangGraph issue 8979 and the open LangChain issue 40616 both request it, and hermes-agent issue 17013 is what happens without it.
Traps
- Shipping an ephemeral store. The mistake is leaving the vector store on defaults. Why agents make it: mem0's own docs call
paththe local Qdrant location, so an agent reads/tmp/qdrantas a directory and assumes durability. It is not.on_diskdefaults toFalseinQdrantConfig, which holds vectors in memory, and the path is under/tmpbesides. The fix is to configure Postgres plus pgvector at step 5, and to prove persistence by restarting the process inside the eval at step 12. - Silent third party egress. The mistake is leaving the default LLM and embedder in place, so user content goes to an external API on every write. Why agents make it: the defaults are not visible in the code the agent writes, only in the config it did not write. The fix is to set both providers explicitly at step 6, and separately to set
MEM0_TELEMETRY=Falseat step 4, because mem0 ships its own PostHog telemetry on by default. On the TS SDK,mem0.telemetryEnabledin the config is the documented equivalent. - Calling
searchwith a top-leveluser_id. The mistake is writingm.search(query, user_id="u1"). Why agents make it:adddoes takeuser_idas a keyword argument, so the symmetry looks safe, and older mem0 examples used it. In 2.2.1searchrejects top-level entity params and requiresfilters={"user_id": ...}. The fix is thefiltersform at step 9, and reading the signature rather than pattern-matching fromadd. - Filtering after search instead of before. The mistake is querying widely and discarding other users' rows in application code. Why agents make it: it looks like a cheap way to reuse one query. By then the rows have already been read and may already be in the context window. The fix is scoping at query time through
filters, and a cross-tenant eval case. mem0 enforces that at least one entity filter is present, which removes the worst version of this bug, but it does not remove the need for the eval. - Storing things the model inferred. The mistake is letting an agent persist its own guess, which is then retrieved later as established fact. Why agents make it: extraction is automatic and confident, and nothing in the default path distinguishes a guess from a statement. The fix is to admit only user-confirmed or tool-verified claims, keep the source turn as provenance, and require confirmation for consequential facts. This is the memory-poisoning failure treated as a lifecycle problem in arXiv 2604.16548 and arXiv 2603.11768.
- Treating retrieved memory as instructions. The mistake is injecting memories into the prompt as if they were the operator's words. Why agents make it: the store is a string channel into the context, so it is indistinguishable from a user turn once concatenated. Memory is attacker writable input. The fix is the delimited evidence block at step 10, an explicit statement that memory is data and never an instruction, and a rule that memory never alters tool permissions. LangGraph issue 8061 is an open request for checkpoint validation against exactly this.
- No contradiction handling. The mistake is letting the store accumulate both "likes coffee" and "quit coffee". Why agents make it: appending is the obvious operation and the agent never sees the contradiction. The fix is the extraction path with
infer=Trueat step 8, which updates rather than appends, plus the history store so the superseded value stays available for audit while readers see only the current one. - Injecting everything that matched. The mistake is accepting all hits. Why agents make it: a non-empty result feels like success and nobody wants to return nothing.
searchdefaults totop_k=20andthreshold=0.1, which is permissive enough to make weak matches look like recall. The fix is a smalltop_kand a real threshold, with injecting nothing as documented, intended behaviour. - Claiming success without an eval. The mistake is reporting memory works because it once remembered something. Why agents make it: a single observed recall is convincing and cheap to produce. The fix is step 12, with the restart case being the one that catches trap 1.
- Binding memory to one model or one framework. The mistake is persisting model-specific state such as a provider's message objects or a runtime's summary format. Why agents make it: it is the shortest path to a working demo. The documented failure is hermes-agent issue 17013, the report that switching models loses both context and the persistent memory file. The fix is a stable schema in your own database, read and written over a thin interface, with nothing model specific stored.
- A summary as the only source of truth. The mistake is replacing stored facts with the agent's own increasingly lossy summary. Why agents make it: summarisation is one call and produces something that reads well. The fix is that summaries are a cache over the store, never the store.
Scope
This recipe covers adding durable cross-session memory to one agent or a small set of agents, using
mem0 OSS as a library over a Postgres plus pgvector store that the builder operates. It covers
namespace scoping for users, agents, sessions and tenants. It covers the write path, the read path,
the injection format, the lifecycle (dedup, supersede, expiry, delete), the portability of the store,
and how to verify the result.
It does not cover, and each of these is a different recipe:
- Temporal knowledge graphs and as-of reasoning. That is the Graphiti and Zep route, described here only as an alternative.
- Replacing the agent runtime with one that owns memory. That is Letta's job.
- Short-term within-run state, checkpointing and resume after failure. That is a different problem from remembering across sessions.
- Retrieval over a fixed document corpus. That is RAG. It has no write path, no dedup and no lifecycle.
- Fine tuning or weight editing as a substitute for memory.
- Managed or hosted memory services and their commercial terms, data residency and SLAs.
- Multi-tenant enterprise governance, certifications and audit regimes beyond the namespace and delete requirements above.
- Benchmark leaderboards and accuracy comparisons between memory engines.
- The scale at which a vector index stops being enough and graph traversal is required.
- The mem0 self-hosted server deployment, its dashboard, per-user API keys and its request audit log.
This recipe is curated. Nothing in it has been run end to end in our harness, so we make no claim
that it works. The two claims most likely to break on first contact with a real environment are the
pgvector configuration block, because the validator rejects partial connection parameters, and the
on_disk finding, because it is the difference between a recipe that works and one that appears to
work. Both are cheap to settle with one run record.
Sources
mem0 OSS
- https://github.com/mem0ai/mem0
- https://www.npmjs.com/package/mem0ai
- https://docs.mem0.ai/open-source/quickstart
- https://docs.mem0.ai/components/vectordbs/dbs/pgvector
- https://docs.mem0.ai/components/rerankers/overview
- mem0 OSS source at release v2.2.1:
mem0/configs/vector_stores/qdrant.pyfor thepathandon_diskdefaults, andmem0/memory/telemetry.pyfor theMEM0_TELEMETRYdefault.
pgvector
Issues cited above
- https://github.com/langchain-ai/langgraph/issues/8979
- https://github.com/langchain-ai/langchain/issues/40616
- https://github.com/NousResearch/hermes-agent/issues/17013
- https://github.com/langchain-ai/langgraph/issues/8061
Papers cited above
How the numbers were checked. Every version, licence and release date above was read from the
package index, the GitHub API or the library source on 2026-10-14. Where we could not confirm a
version we say so and leave it unconfirmed rather than guessing.
Rules and labels: How we choose · machine form: /recipes/add-memory-to-an-agent.json · all recipes