Recipe · recipe:add-memory-to-an-agent

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.

What you need

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

  1. 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.
  2. 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.
  3. Install the client in library mode: pip install mem0ai. For TypeScript, npm install mem0ai plus npm install pg, which the TS SDK loads only when the pgvector store is selected. Import from mem0ai/oss.
  4. Set MEM0_TELEMETRY=False in the environment before the process starts. This is opt out. It cannot be set after the client is constructed.
  5. Build the config explicitly and construct with Memory.from_config(config). Do not inherit defaults. Set vector_store.provider to pgvector with host, port, user, password and dbname. The Python config validator rejects the block unless both user and password, and both host and port, are present. dbname defaults to postgres and collection_name to mem0. Set both rather than discovering the defaults later.
  6. In the same config, set the llm provider and the embedder provider 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. Set embedding_model_dims to match the embedder's actual output dimensions. It defaults to 1536, and a mismatch produces wrong results rather than a clean error.
  7. Decide the namespaces before writing anything, and use them on both sides. Use user_id for the human, agent_id for the agent and run_id for the session. Put domain scope such as a tenant or project key in metadata.
  8. Write after a turn with m.add(messages, user_id=..., metadata={...}). add takes user_id, agent_id and run_id as keyword arguments, plus metadata, infer, memory_type, prompt, timestamp and expiration_date. Constrain eligibility: only user-confirmed or tool-verified claims. Store facts, not conversations. Keep infer=True so mem0 runs its extraction and update-on-contradiction path instead of storing raw text.
  9. Read before a turn with m.search(query, filters={"user_id": ...}, top_k=..., threshold=...). Note the required shape. search takes entity identifiers inside filters, not as top-level keyword arguments. filters must contain at least one of user_id, agent_id or run_id, or the call raises. top_k defaults to 20 and threshold to 0.1. Both are too loose for default use, so set them.
  10. 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.
  11. Build the lifecycle on day one. Use expiration_date on add for memory types that go stale. Use the history store to retain superseded values while exposing only the current one. Use m.delete(memory_id) for a single record and m.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.
  12. 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.
  13. 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

  1. Shipping an ephemeral store. The mistake is leaving the vector store on defaults. Why agents make it: mem0's own docs call path the local Qdrant location, so an agent reads /tmp/qdrant as a directory and assumes durability. It is not. on_disk defaults to False in QdrantConfig, which holds vectors in memory, and the path is under /tmp besides. 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.
  2. 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=False at step 4, because mem0 ships its own PostHog telemetry on by default. On the TS SDK, mem0.telemetryEnabled in the config is the documented equivalent.
  3. Calling search with a top-level user_id. The mistake is writing m.search(query, user_id="u1"). Why agents make it: add does take user_id as a keyword argument, so the symmetry looks safe, and older mem0 examples used it. In 2.2.1 search rejects top-level entity params and requires filters={"user_id": ...}. The fix is the filters form at step 9, and reading the signature rather than pattern-matching from add.
  4. 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.
  5. 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.
  6. 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.
  7. 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=True at 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.
  8. 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. search defaults to top_k=20 and threshold=0.1, which is permissive enough to make weak matches look like recall. The fix is a small top_k and a real threshold, with injecting nothing as documented, intended behaviour.
  9. 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.
  10. 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.
  11. 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:

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

pgvector

Issues cited above

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.