BUILD · 5 MIN READ

Add a dedicated memory layer with Mem0

Store selected information and retrieve it for a particular user.

Download example files Code + setup + checks in a ZIP
Jump to a section 9 sections

EXAMPLE USE CASE

Recall a user’s answer-format preference in a later conversation

A returning user should not have to repeat that they prefer concise technical explanations.

Input
A preference message associated with authenticated demo-user, followed by a separate recall query.
Expected output
A scoped memory record relevant to formatting the next answer.
  • Success check: After extraction finishes, the intended user’s preference is recalled; a different user query cannot retrieve it.
  • Try a failure: An immediate empty search may mean extraction is pending. Distinguish pending processing from an authorization or recall failure.

Example scope: The hosted Mem0 client, not self-hosted storage. The example adds and searches a synthetic preference; it does not implement the full deletion lifecycle.

Mem0 examplePostgreSQL example
SEE HOW THE SYSTEM FITS TOGETHERSELECT A COMPONENT
candidateapprovedretrieverecallcontextmaintainConversationAuthenticated subjectMemory policyExtract and validateMem0Scoped durable recordsRelevant queryScope before rankingSelected contextSmall evidence setCorrection + expiryPropagate changes
  1. Resolve tenant, user, and thread from the application session.

  2. Decide which supported facts or preferences can be retained.

  3. Store content with provenance, subject, timestamps, and a lifecycle policy.

  4. Retrieve only data the authenticated subject is permitted to access.

  5. Rank useful memories within a context budget; do not include every past conversation.

  6. Correct conflicting facts and remove expired or deleted records from derived stores.

Mem0

Store content with provenance, subject, timestamps, and a lifecycle policy.

Follow the arrows, then select a component to inspect its responsibility. On mobile, downward arrows connect the next step; bent arrows identify branches and return paths. Select a destination to jump to that component.

What the layer does

  • A memory layer sits between interactions and storage.
  • It can identify information to retain and make relevant memories available to later turns.
  • Define the user or tenant scope in application code before writing or searching.

Prepare the example

  • This example uses Mem0’s hosted platform client.
  • Install mem0ai and set MEM0_API_KEY.
  • The sample user identifier is a local demonstration value; resolve the real user from your authenticated session.
Shell · install in a virtual environment
pip install mem0ai
Python · memory.py
import os
from mem0 import MemoryClient

client = MemoryClient(api_key=os.environ["MEM0_API_KEY"])
user_id = "demo-user"  # Resolve from auth in a real app.

client.add(
    [{"role": "user", "content": "I prefer concise technical answers."}],
    user_id=user_id,
)

# Memory extraction may be asynchronous; search after it completes.
memories = client.search(
    "How should I format an explanation?",
    filters={"user_id": user_id},
)
print(memories)

Educational example. Uses your configured environment and credentials; no paid model call is made by this website.

Design the lifecycle

  • Choose what can be remembered, how a user can correct it, and when it expires.
  • A search can return an older fact, so retain provenance and update time.
  • Deletion must cover derived stores and caches as well as the visible conversation.

Set up the lab

  • This walkthrough uses the hosted MemoryClient, not an automatically configured self-hosted Memory instance.
  • Save the existing Python example as memory.py and use a dedicated test user.
Shell
python3 -m venv .venv
source .venv/bin/activate
python -m pip install mem0ai
export MEM0_API_KEY="your-platform-api-key"

Run and verify

Shell
python memory.py
  • The add request is accepted for demo-user. Wait for extraction to finish before expecting a search match.
  • Search with another user identifier: no demo-user memory should be returned.

Troubleshooting and failure tests

  • An empty immediate search may mean extraction is still running; inspect the returned operation status.
  • A platform key and an OpenAI key configure different services. Do not substitute one for the other.

Before production

  • Define permitted memory types, source evidence, expiry, correction, and deletion before enabling automatic writes.
  • Store the authenticated identity outside model control; propagate deletion to derived indexes and caches.

Keep exploring

A layered architecture for agent memoryUse PostgreSQL and pgvector for agent memory