{
  "id": "recipe:add-memory-to-an-agent",
  "kind": "recipe",
  "title": "Add memory to an agent",
  "job": "An agent that forgets everything when the session ends costs you twice. It re-learns the same things,\nand you keep a growing summary in the prompt until the summary crowds out the work.\n\nThe job is to give one agent, or a small set of agents, durable memory of facts across sessions,\nstored in a database you own and operate. The agent stops re-learning. The prompt stops carrying\nstale summaries.",
  "approach": "We run mem0 OSS as a library inside the agent, pointed at a Postgres database with the pgvector\nextension that you operate. mem0 does the two hard parts, and you own the rows.\n\nmem0 decides what is worth keeping. That means extraction, deduplication, and updating a fact when a\nnewer one contradicts an older one. mem0 also gets the right facts back. That means semantic search\nwith metadata filters, plus an optional reranker. Because you own the rows, scoping, deletion and\naudit are yours to define.\n\nThe integration is short. Build a `Memory` object once with `Memory.from_config(...)`, call `add`\nafter a turn, and call `search` before one.\n\nTwo mem0 defaults are wrong for production. We override both.\n\n**The default store is ephemeral.** The library default provider is `qdrant` with `path` at\n`/tmp/qdrant` and `on_disk` at `False`. `on_disk` at `False` means the vectors are held in memory,\nso they are not written to that path at all. Do not try to make the embedded Qdrant durable. Use\nPostgres plus pgvector instead. That is mem0's own documented default for its server deployment, and\nit gives you backup, restore and independent deletion.\n\n**Every write can leave your infrastructure.** The default LLM is OpenAI `gpt-5-mini` and the default\nembedder is OpenAI `text-embedding-3-small`, so user content leaves on every write. Set both\nproviders explicitly. mem0 also ships PostHog telemetry on by default, so set `MEM0_TELEMETRY=False`\nbefore the process starts.\n\nWe considered three alternatives and did not make them the default.\n\n- A temporal knowledge graph, such as Graphiti or hosted Zep, is the better model when relationships\n  between facts matter and facts have validity windows. It costs a graph database alongside the\n  vector database, LLM-driven entity extraction on every write, and ontology modelling. That is heavy\n  machinery for remembering that a user prefers short answers.\n- A framework-native answer, such as LangGraph checkpointers and stores, LangMem or Letta, describes\n  the memory in that framework's own abstractions. The public demand evidence is full of builders\n  changing exactly that framework. LangMem compounds this by being roughly a year stale on PyPI at\n  0.0.30.\n- Rolling your own vector store plus a rolling summary reproduces every trap below by construction:\n  unbounded context growth, drift, no deduplication, no decay and no attribution.",
  "components": [
    {
      "name": "mem0 OSS, Python package `mem0ai`",
      "version": "2.2.1, released 2026-09-25 (PyPI and the GitHub release `v2.2.1` agree)",
      "license": "Apache-2.0 (GitHub API `license.spdx_id`; PyPI exposes it as `license_expression`, the legacy `license` field is null)",
      "url": "https://github.com/mem0ai/mem0"
    },
    {
      "name": "mem0 OSS, npm package `mem0ai`",
      "version": "3.3.1 (npm `dist-tags.latest`; GitHub release tag is `ts-v3.3.1`)",
      "license": "Apache-2.0",
      "url": "https://www.npmjs.com/package/mem0ai"
    },
    {
      "name": "pgvector, Postgres extension",
      "version": "v0.8.7, tag commit 2026-10-01 (`Version bump to 0.8.7`)",
      "license": "PostgreSQL License. The GitHub API reports `NOASSERTION` because it does not recognise the file; the file text is the PostgreSQL licence",
      "url": "https://github.com/pgvector/pgvector"
    },
    {
      "name": "pgvector is built against nlohmann/json",
      "version": "v3.12.0, released 2025-04-11 (bundled dependency, do not pin it yourself)",
      "license": "MIT",
      "url": "https://github.com/nlohmann/json"
    },
    {
      "name": "mem0 pgvector configuration reference",
      "version": "n/a (docs)",
      "license": "n/a",
      "url": "https://docs.mem0.ai/components/vectordbs/dbs/pgvector"
    },
    {
      "name": "mem0 OSS overview and defaults",
      "version": "n/a (docs)",
      "license": "n/a",
      "url": "https://docs.mem0.ai/open-source/quickstart"
    },
    {
      "name": "mem0 reranker hub",
      "version": "n/a (docs)",
      "license": "n/a",
      "url": "https://docs.mem0.ai/components/rerankers/overview"
    },
    {
      "name": "Default extraction LLM, OpenAI `gpt-5-mini`",
      "version": "not pinned by the docs; it is a default, not a version",
      "license": "proprietary, per OpenAI terms",
      "url": "https://platform.openai.com/docs/models"
    },
    {
      "name": "Default embedding model, OpenAI `text-embedding-3-small`",
      "version": "not pinned",
      "license": "proprietary, per OpenAI terms",
      "url": "https://platform.openai.com/docs/models"
    },
    {
      "name": "Default history store, SQLite at `~/.mem0/history.db`, overridable with `MEM0_DIR`",
      "version": "n/a",
      "license": "n/a",
      "url": "https://docs.mem0.ai/open-source/quickstart"
    },
    {
      "name": "Reranker slot",
      "version": "no default provider is shipped enabled; disabled by default (`RerankerConfig` defaults to `None`)",
      "license": "n/a. Supported providers are Cohere, Sentence Transformers, Hugging Face, LLM Reranker and Zero Entropy; their individual versions are unconfirmed",
      "url": "https://docs.mem0.ai/components/rerankers/overview"
    }
  ],
  "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 mem0ai` plus `npm install pg`, which the TS SDK loads only when the pgvector store is selected. Import from `mem0ai/oss`.",
    "Set `MEM0_TELEMETRY=False` in 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. 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.",
    "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.",
    "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`.",
    "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.",
    "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.",
    "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_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.",
    "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 `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.",
    "**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.",
    "**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`.",
    "**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=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.",
    "**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.",
    "**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\nmem0 OSS as a library over a Postgres plus pgvector store that the builder operates. It covers\nnamespace scoping for users, agents, sessions and tenants. It covers the write path, the read path,\nthe injection format, the lifecycle (dedup, supersede, expiry, delete), the portability of the store,\nand how to verify the result.\n\nIt does not cover, and each of these is a different recipe:\n\n- Temporal knowledge graphs and as-of reasoning. That is the Graphiti and Zep route, described here\n  only as an alternative.\n- Replacing the agent runtime with one that owns memory. That is Letta's job.\n- Short-term within-run state, checkpointing and resume after failure. That is a different problem\n  from remembering across sessions.\n- Retrieval over a fixed document corpus. That is RAG. It has no write path, no dedup and no\n  lifecycle.\n- Fine tuning or weight editing as a substitute for memory.\n- Managed or hosted memory services and their commercial terms, data residency and SLAs.\n- Multi-tenant enterprise governance, certifications and audit regimes beyond the namespace and\n  delete requirements above.\n- Benchmark leaderboards and accuracy comparisons between memory engines.\n- The scale at which a vector index stops being enough and graph traversal is required.\n- The mem0 self-hosted server deployment, its dashboard, per-user API keys and its request audit log.\n\n**This recipe is curated.** Nothing in it has been run end to end in our harness, so we make no claim\nthat it works. The two claims most likely to break on first contact with a real environment are the\npgvector configuration block, because the validator rejects partial connection parameters, and the\n`on_disk` finding, because it is the difference between a recipe that works and one that appears to\nwork. Both are cheap to settle with one run record.",
  "use_case": "add-memory-to-an-agent",
  "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.py` for the `path` and `on_disk` defaults, and `mem0/memory/telemetry.py` for the `MEM0_TELEMETRY` default.",
    "**pgvector**",
    "https://github.com/pgvector/pgvector",
    "https://github.com/nlohmann/json",
    "**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**",
    "https://arxiv.org/abs/2604.16548",
    "https://arxiv.org/abs/2603.11768",
    "**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."
  ],
  "status": "curated",
  "superseded_by": null,
  "citation": "Add memory to an agent. Recipe by alexndr.ai. https://alexndr.ai/recipes/add-memory-to-an-agent",
  "human_page": "https://alexndr.ai/recipes/add-memory-to-an-agent"
}