Compare commits

..
Author SHA1 Message Date
mintlify[bot]andGitHub b52e915801 docs: expand short API reference descriptions for SEO 2026-06-26 10:33:14 +00:00
64 changed files with 853 additions and 686 deletions
+43 -130
View File
@@ -1,157 +1,72 @@
# Contributing to Mem0 # Contributing to mem0
First off, thank you for taking the time to contribute! 🎉 Mem0 is a Let us make contribution easy, collaborative and fun.
community-driven project and we welcome contributions of all kinds — bug fixes,
new features, documentation, examples, and integrations.
Mem0 is a polyglot monorepo, and this guide covers contributing to both the ## Submit your Contribution through PR
**Python SDK** and the **TypeScript SDK** (and the rest of the repository).
## Before You Start To make a contribution, follow these steps:
### 1. Open an Issue First 1. Fork and clone this repository
2. Do the changes on your fork with dedicated feature branch `feature/f1`
3. If you modified the code (new feature or bug-fix), please add tests for it
4. Include proper documentation / docstring and examples to run the feature
5. Ensure that all tests pass
6. Submit a pull request
**Always open an issue before opening a pull request.** This lets us discuss the For more details about pull requests, please read [GitHub's guides](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request).
change, avoid duplicate effort, and agree on the approach before you invest time
in code.
- Search [existing issues](https://github.com/mem0ai/mem0/issues) first to see if
your bug or idea already exists.
- If it doesn't, open a
[bug report](https://github.com/mem0ai/mem0/issues/new?template=bug_report.yml) or
[feature request](https://github.com/mem0ai/mem0/issues/new?template=feature_request.yml).
- For anything beyond a trivial fix, wait for a maintainer to confirm the approach
before starting significant work.
Every pull request must link to an issue using `Closes #<issue-number>`. ### 📦 Development Environment
### 2. Sign the Contributor License Agreement (CLA) We use `hatch` for managing development environments. To set up:
**We cannot accept or merge any pull request until you have signed our Contributor
License Agreement (CLA).**
When you open your first PR, the CLA bot will automatically comment with a link to
sign. Signing takes less than a minute and only needs to be done once. Pull
requests from contributors who have not signed the CLA will be blocked from
merging.
## Repository Layout
The two most common contribution targets are the SDKs:
| Package | Path | Language | Package manager |
| --------------------- | ---------- | ------------ | --------------- |
| Python SDK (`mem0ai`) | `mem0/` | Python 3.9+ | `hatch` |
| TypeScript SDK (`mem0ai`) | `mem0-ts/` | TypeScript | `pnpm` |
Other packages include the CLIs (`cli/python/`, `cli/node/`), integrations
(`integrations/`), the self-hosted `server/`, `openmemory/`, and the docs site
(`docs/`). See [AGENTS.md](./AGENTS.md) for a full map of the repository.
## Development Workflow
1. **Fork** the repository and **clone** your fork.
2. Create a **feature branch** from `main` (e.g. `feature/my-new-feature` or
`fix/issue-1234`).
3. Make your changes — add **tests**, **documentation**, and **examples** as
appropriate.
4. Run **linting and tests** for every package you touched (see below).
5. Commit using [Conventional Commits](https://www.conventionalcommits.org/)
(e.g. `feat:`, `fix:`, `docs:`, `refactor:`, `test:`).
6. Push and open a **pull request** against `main`, linking the issue with
`Closes #<number>` and filling out the
[PR template](./.github/PULL_REQUEST_TEMPLATE.md).
### Contributing to the Python SDK (`mem0/`)
We use [`hatch`](https://hatch.pypa.io/latest/install/) to manage environments.
**Do not use `pip` or `conda` for dependency management.**
```bash ```bash
# Activate a dev environment (3.9 / 3.10 / 3.11 / 3.12) # Activate environment for specific Python version:
hatch shell dev_py_3_11 hatch shell dev_py_3_9 # Python 3.9
hatch shell dev_py_3_10 # Python 3.10
hatch shell dev_py_3_11 # Python 3.11
hatch shell dev_py_3_12 # Python 3.12
# Install pre-commit hooks (runs ruff + isort on commit) # The environment will automatically install all dev dependencies
pre-commit install # Run tests within the activated shell:
# Lint, format, and sort imports
make lint
make format
make sort
# Run the test suite (run `make install_all` first if deps are missing)
make test make test
``` ```
- **Linter / formatter:** Ruff (line length **120**) ### 📌 Pre-commit
- **Import sorting:** isort (`profile = "black"`)
- **Tests:** pytest (in `tests/`)
See the full [Development guide](https://docs.mem0.ai/contributing/development) for To ensure our standards, make sure to install pre-commit before starting to contribute.
environment details.
### Contributing to the TypeScript SDK (`mem0-ts/`)
We use [`pnpm`](https://pnpm.io/) (v10+) for all TypeScript packages. **Do not use
`npm` or `yarn`.**
```bash ```bash
cd mem0-ts pre-commit install
pnpm install
pnpm run build # tsup (CJS + ESM)
pnpm run test # jest (all tests)
pnpm run test:unit # unit tests with coverage
``` ```
- **Build:** tsup ### 🧪 Testing
- **Formatter:** Prettier
- **Tests:** jest
- Always run type checking after changes: `pnpm run typecheck` (or `tsc --noEmit`).
- Use ES module `import` syntax — never `require()`.
## Good Contribution Practices We use `pytest` to test our code across multiple Python versions. You can run tests using:
- **Keep PRs small and focused.** One logical change per PR is easier to review and ```bash
merge. # Run tests with default Python version
- **Follow existing patterns.** Match the style, structure, and conventions of the make test
code around you. Don't introduce new frameworks or abstractions without
discussion.
- **Write tests** that would fail without your change — regression tests for bugs,
coverage for new features.
- **Update documentation** in `docs/` for any user-facing change. New `.mdx` pages
must be added to `docs/llms.txt` (run
`python scripts/check-llms-txt-coverage.py --write` to scaffold entries).
- **Add examples** when introducing new user-facing behavior.
- **Run linters and tests locally** before pushing — CI re-runs them on every PR
via the CI Gate.
- **Never commit secrets** — no `.env` files, API keys, or credentials.
- **Don't add core dependencies lightly.** New Python dependencies belong in an
optional group in `pyproject.toml`, not the core `dependencies` list.
- **Be responsive** to review feedback and keep your branch up to date with `main`.
## Pull Request Checklist # Test specific Python versions:
make test-py-3.9 # Python 3.9 environment
make test-py-3.10 # Python 3.10 environment
make test-py-3.11 # Python 3.11 environment
make test-py-3.12 # Python 3.12 environment
Before requesting review, make sure: # When using hatch shells, run tests with:
make test # After activating a shell with hatch shell test_XX
```
- [ ] An issue exists and is linked with `Closes #<number>` Make sure that all tests pass across all supported Python versions before submitting a pull request.
- [ ] You have signed the CLA
- [ ] Your code follows the project's style guidelines (lint passes)
- [ ] You performed a self-review of your changes
- [ ] Tests are added/updated and pass locally
- [ ] Documentation is updated if needed
## Reporting Security Issues We look forward to your pull requests and can't wait to see your contributions!
**Do not report security vulnerabilities through public issues or pull requests.** ### 🚀 Releasing
Please follow our [Security Policy](./SECURITY.md) to report them privately.
## Releasing All packages are published automatically via GitHub Actions when a GitHub Release is created with the correct tag prefix.
All packages are published automatically via GitHub Actions when a GitHub Release #### Tag Prefixes
is created with the correct tag prefix.
### Tag Prefixes
| Package | Registry | Tag Prefix | Example | | Package | Registry | Tag Prefix | Example |
|---------|----------|------------|---------| |---------|----------|------------|---------|
@@ -162,17 +77,15 @@ is created with the correct tag prefix.
| `@mem0/vercel-ai-provider` | npm | `vercel-ai-v*` | `vercel-ai-v2.0.6` | | `@mem0/vercel-ai-provider` | npm | `vercel-ai-v*` | `vercel-ai-v2.0.6` |
| `@mem0/openclaw-mem0` | npm | `openclaw-v*` | `openclaw-v1.0.1` | | `@mem0/openclaw-mem0` | npm | `openclaw-v*` | `openclaw-v1.0.1` |
### How to Release #### How to Release
1. Bump the version in `pyproject.toml` (Python) or `package.json` (Node) 1. Bump the version in `pyproject.toml` (Python) or `package.json` (Node)
2. Create a [GitHub Release](https://github.com/mem0ai/mem0/releases/new) with the matching tag prefix 2. Create a [GitHub Release](https://github.com/mem0ai/mem0/releases/new) with the matching tag prefix
3. The correct workflow will trigger automatically — verify in the [Actions tab](https://github.com/mem0ai/mem0/actions) 3. The correct workflow will trigger automatically — verify in the [Actions tab](https://github.com/mem0ai/mem0/actions)
### Publishing Details #### Publishing Details
- **PyPI packages** use OIDC trusted publishing via `pypa/gh-action-pypi-publish` - **PyPI packages** use OIDC trusted publishing via `pypa/gh-action-pypi-publish`
- **npm packages** use OIDC trusted publishing via npm CLI (>= 11.5.1) — no tokens or secrets required - **npm packages** use OIDC trusted publishing via npm CLI (>= 11.5.1) — no tokens or secrets required
- All workflows require `permissions: id-token: write` for OIDC authentication - All workflows require `permissions: id-token: write` for OIDC authentication
- First publish of a new npm package must be done manually; OIDC works for subsequent versions - First publish of a new npm package must be done manually; OIDC works for subsequent versions
We look forward to your pull requests and can't wait to see your contributions!
-48
View File
@@ -1,48 +0,0 @@
# Security Policy
We take the security of Mem0 and our community seriously. Thank you for helping
keep Mem0 and its users safe by disclosing vulnerabilities responsibly.
## Reporting a Vulnerability
Please **do not** report security vulnerabilities through public GitHub issues,
pull requests, or discussions.
If you believe you have found a security vulnerability in Mem0, please report it
privately through one of the following channels:
1. **GitHub Private Vulnerability Reporting** — open a
[private security advisory](https://github.com/mem0ai/mem0/security/advisories/new)
directly on this repository.
2. **Email** the maintainers at **support@mem0.ai** with the subject line:
`SECURITY: Mem0 vulnerability report`
To help us triage and resolve the issue quickly, please include as much of the
following as you can:
- Affected component or package (e.g. Python SDK, TypeScript SDK, server, OpenMemory)
- Affected version, tag, or commit
- Clear, step-by-step reproduction instructions
- The security impact and a proof of concept, if available
- Any suggested fix or mitigation
## Response Process
- We will acknowledge receipt of your report within **72 hours**.
- We will work with you privately to confirm the issue and assess its impact.
- Once a fix or mitigation is ready, we will coordinate a disclosure timeline
with you and credit you for the discovery, unless you prefer to remain anonymous.
## Public Disclosure
Please avoid sharing technical details of the vulnerability publicly until the
maintainers have reviewed the issue and a fix or mitigation has been released. We
are committed to resolving valid reports promptly and keeping you informed
throughout the process.
## Supported Versions
We release security fixes against the latest published version of each package.
Whenever possible, please reproduce the issue on the most recent release before
reporting.
@@ -4,4 +4,4 @@ description: "Submit an export job to create a structured memory export using a
openapi: post /v1/exports/ openapi: post /v1/exports/
--- ---
Submit a job to create a structured export of memories using a customizable Pydantic schema. This process may take some time to complete, especially if you're exporting a large number of memories. You can tailor the export by applying various filters (e.g., `user_id`, `agent_id`, `app_id`, or `run_id`) and by modifying the Pydantic schema to ensure the final data matches your exact needs. Submit a job to create a structured export of memories using a customizable Pydantic schema. This process may take some time to complete, especially if you're exporting a large number of memories. You can tailor the export by applying various filters (e.g., `user_id`, `agent_id`, `run_id`, or `session_id`) and by modifying the Pydantic schema to ensure the final data matches your exact needs.
@@ -4,4 +4,4 @@ description: "Retrieve the latest structured memory export after submitting an e
openapi: post /v1/exports/get openapi: post /v1/exports/get
--- ---
Retrieve the latest structured memory export after submitting an export job. You can filter the export by `user_id`, `agent_id`, `app_id`, `run_id`, `created_at`, or `updated_at` to get the most recent export matching your filters. Retrieve the latest structured memory export after submitting an export job. You can filter the export by `user_id`, `run_id`, `session_id`, or `app_id` to get the most recent export matching your filters.
@@ -24,11 +24,11 @@ The `filters` object supports complex logical operations (AND, OR, NOT) and comp
### Search parameter defaults ### Search parameter defaults
| Parameter | Default | | Parameter | V1/V2 | V3 |
| --- | --- | | --- | --- | --- |
| `top_k` | `10` (range 1–1000) | | `top_k` | Supported (default 10) | Supported (1-1000, default 10) |
| `threshold` | `0.1` (pass `0.0` to disable) | | `threshold` | No default | Default `0.1` (pass `0.0` to disable) |
| `rerank` | `false` (pass `true` to enable) | | `rerank` | Default `true` | Default `false` (pass `true` to enable) |
<CodeGroup> <CodeGroup>
```python Platform API Example ```python Platform API Example
@@ -1,5 +1,5 @@
--- ---
title: "Remove Organization Member" title: "Remove Organization Member"
description: "Remove a member from an organization to revoke their access to its projects and resources." description: "Remove a member from an organization by email, revoking their access to all projects within that organization."
openapi: "delete /api/v1/orgs/organizations/{org_id}/members/" openapi: "delete /api/v1/orgs/organizations/{org_id}/members/"
--- ---
@@ -1,5 +1,5 @@
--- ---
title: "Update Organization Member" title: "Update Organization Member"
description: "Update an existing member's role within an organization to change their permissions and access level." description: "Update an existing organization member's role to change their permissions and access level within the organization."
openapi: "put /api/v1/orgs/organizations/{org_id}/members/" openapi: "put /api/v1/orgs/organizations/{org_id}/members/"
--- ---
+2 -41
View File
@@ -14,7 +14,7 @@ Organizations and projects are **optional** features. You can use Mem0 without t
## Key Capabilities ## Key Capabilities
- **Multi-org/project Support**: Organization and project are resolved automatically from your API key via `/v1/ping/` — no org or project params are accepted by `MemoryClient.__init__`. Use a project-specific API key to target a particular project. - **Multi-org/project Support**: Specify organization and project when initializing the Mem0 client to attribute API usage appropriately
- **Member Management**: Control access to data through organization and project membership - **Member Management**: Control access to data through organization and project membership
- **Access Control**: Only members can access memories and data within their organization/project scope - **Access Control**: Only members can access memories and data within their organization/project scope
- **Team Isolation**: Maintain data separation between different teams and projects for secure collaboration - **Team Isolation**: Maintain data separation between different teams and projects for secure collaboration
@@ -79,7 +79,7 @@ new_project = client.project.create(
### Update Project Settings ### Update Project Settings
Modify project configuration including custom instructions, categories, language preferences, retrieval criteria, and memory decay: Modify project configuration including custom instructions, categories, and language preferences:
```python ```python
# Update project with custom categories # Update project with custom categories
@@ -98,17 +98,6 @@ client.project.update(
# Use the input language for memory storage and retrieval # Use the input language for memory storage and retrieval
client.project.update(multilingual=True) client.project.update(multilingual=True)
# Set retrieval criteria to control which memories are surfaced in search
client.project.update(
retrieval_criteria=[
{"name": "relevance", "description": "How directly relevant this memory is to the current topic or user query", "weight": 3},
{"name": "access_frequency", "description": "How often this memory has been accessed or surfaced recently", "weight": 1}
]
)
# Enable Memory Decay (boosts recently-accessed memories at search time)
client.project.update(decay=True)
# Update multiple settings at once # Update multiple settings at once
client.project.update( client.project.update(
custom_instructions="...", custom_instructions="...",
@@ -120,34 +109,6 @@ client.project.update(
) )
``` ```
#### Set Retrieval Criteria
`retrieval_criteria` is a per-project list of dictionaries (`List[Dict]`) that shapes how memories are ranked and filtered during search. Each dictionary has three fields: `name` (identifier), `description` (interpreted by the LLM to score each memory), and `weight` (relative influence on the final score). Use this to focus retrieval on intent-aligned or signal-specific memories:
```python
client.project.update(
retrieval_criteria=[
{
"name": "joy",
"description": "Measure the intensity of positive emotions such as happiness, excitement, or amusement expressed in the memory. A higher score reflects greater joy.",
"weight": 3
},
{
"name": "curiosity",
"description": "Assess the extent to which the memory reflects inquisitiveness or interest in exploring new information. A higher score reflects stronger curiosity.",
"weight": 2
},
{
"name": "access_frequency",
"description": "How often this memory has been accessed or surfaced recently.",
"weight": 1
}
]
)
```
Pass an empty list to clear all criteria and restore default retrieval behaviour.
#### Toggle Memory Decay #### Toggle Memory Decay
`decay` is a per-project boolean that turns on [Memory Decay](/platform/features/memory-decay) — a search-time ranking bias that reinforces recently-accessed memories and gently dampens stale ones. The flag is `false` by default; set it via the same project-update endpoint: `decay` is a per-project boolean that turns on [Memory Decay](/platform/features/memory-decay) — a search-time ranking bias that reinforces recently-accessed memories and gently dampens stale ones. The flag is `false` by default; set it via the same project-update endpoint:
@@ -1,5 +1,5 @@
--- ---
title: "Remove Project Member" title: "Remove Project Member"
description: "Remove a member from a project to revoke their access to its memories, configuration, and resources." description: "Remove a member from a project by email, revoking their access to that project's memories and settings."
openapi: "delete /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/" openapi: "delete /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/"
--- ---
@@ -1,5 +1,5 @@
--- ---
title: "Update Project Member" title: "Update Project Member"
description: "Update an existing member's role within a project to change their permissions and access level." description: "Update an existing project member's role to change their permissions and access level within the project."
openapi: "put /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/" openapi: "put /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/"
--- ---
@@ -1,5 +1,5 @@
--- ---
title: "Update Project" title: "Update Project"
description: "Update a project's settings, including name, custom instructions, and other configuration options." description: "Update a project's settings, including its name, custom instructions, and configuration options for memory behavior."
openapi: "patch /api/v1/orgs/organizations/{org_id}/projects/{project_id}/" openapi: "patch /api/v1/orgs/organizations/{org_id}/projects/{project_id}/"
--- ---
+1 -1
View File
@@ -113,7 +113,7 @@ Launched a unified Mem0 plugin across three major AI development environments
Major expansion of the provider ecosystem: Major expansion of the provider ecosystem:
- **Apache AGE** — New graph store support, bringing the total to 4 graph store backends (Neo4j, Memgraph, Kuzu, Apache AGE). **Note:** All external graph store backends (Neo4j, Memgraph, Kuzu, Apache AGE) were subsequently removed in v2.0.0 (2026-04-14). Graph memory is now built-in entity linking with no external graph store required; see the [v2.0.0 entry above](#mem0-sdk-v2-0-0-v3-0-0). - **Apache AGE** — New graph store support, bringing the total to 4 graph store backends (Neo4j, Memgraph, Kuzu, Apache AGE)
- **Turbopuffer** — New vector database provider for Python SDK - **Turbopuffer** — New vector database provider for Python SDK
- **MiniMax** — New LLM provider with dedicated AWS Bedrock support - **MiniMax** — New LLM provider with dedicated AWS Bedrock support
- **pgvector for Node.js** — PostgreSQL vector support added to the TypeScript OSS SDK - **pgvector for Node.js** — PostgreSQL vector support added to the TypeScript OSS SDK
+2 -34
View File
@@ -7,21 +7,6 @@ mode: "wide"
<Tabs> <Tabs>
<Tab title="Python"> <Tab title="Python">
<Update label="2026-06-27" description="v2.0.10">
**New Features:**
- **Client:** Expose `expiration_date` on `MemoryClient.update()` and `AsyncMemoryClient.update()` — callers can now set or clear a memory's expiration date; `None` is preserved and forwarded to the API ([#5874](https://github.com/mem0ai/mem0/pull/5874))
**Bug Fixes:**
- **Memory (OSS):** Apply `remove_code_blocks()` to the LangChain path in async `_create_procedural_memory` so code fences are stripped consistently ([#5711](https://github.com/mem0ai/mem0/pull/5711))
- **Rerankers:** Score HuggingFace cross-encoder results with per-document sigmoid instead of set-relative min-max, preventing a single low-score document from collapsing all relevance scores to zero ([#5715](https://github.com/mem0ai/mem0/pull/5715))
- **Core:** Validate and trim entity IDs (`user_id`, `agent_id`, `run_id`) in `delete_all()` for both sync and async `Memory` ([#5735](https://github.com/mem0ai/mem0/pull/5735))
- **Vector Stores:** Use `.get()` for `hash` and `created_at` in the Redis `insert()` and `update()` paths so entity payloads that omit those fields no longer raise `KeyError` ([#5709](https://github.com/mem0ai/mem0/pull/5709))
- **Memory:** Fix scale-threshold notices not firing for Redis and search-engine backends by resolving `col_info()` signature differences and adding `num_docs` to the count-extraction lookup ([#5687](https://github.com/mem0ai/mem0/pull/5687))
- **Vector Stores:** Escape special characters in Valkey FT.SEARCH tag filter values to prevent wildcard and operator injection through tenant-isolation filters ([#5750](https://github.com/mem0ai/mem0/pull/5750))
</Update>
<Update label="2026-06-24" description="v2.0.9"> <Update label="2026-06-24" description="v2.0.9">
**Bug Fixes:** **Bug Fixes:**
@@ -136,7 +121,7 @@ mode: "wide"
**New Features:** **New Features:**
- **Memory:** Warn at init time when hybrid/BM25 search silently degrades to semantic-only because the configured vector store does not implement `keyword_search`. Affected stores: Chroma, FAISS, Cassandra, LangChain, Neptune Analytics, S3 Vectors, Supabase, TurboPuffer, Valkey ([#5444](https://github.com/mem0ai/mem0/pull/5444)) - **Memory:** Warn at init time when hybrid/BM25 search silently degrades to semantic-only because the configured vector store does not implement `keyword_search`. Affected stores: Chroma, FAISS, Cassandra, LangChain, Neptune Analytics, S3 Vectors, Supabase, TurboPuffer, Valkey ([#5444](https://github.com/mem0ai/mem0/pull/5444))
- **Memory:** Add opt-in `explain=True` parameter to `Memory.search()` and `AsyncMemory.search()`. When enabled, each result includes a `score_details` dict with `semantic_score`, `bm25_score`, `entity_boost`, `raw_score`, `max_possible_score`, `final_score`, and `threshold` so callers can understand and tune retrieval ranking ([#5102](https://github.com/mem0ai/mem0/pull/5102)) - **Memory:** Add opt-in `explain=True` parameter to `Memory.search()` and `AsyncMemory.search()`. When enabled, each result includes a `score_breakdown` dict with `semantic`, `keyword` (normalized BM25), `entity_boost`, and `temporal_boost` signals so callers can understand and tune retrieval ranking ([#5102](https://github.com/mem0ai/mem0/pull/5102))
**Bug Fixes:** **Bug Fixes:**
- **Vector Stores:** Normalize similarity scores to `[0, 1]` (higher = better) consistently across all backends. 11 adapters previously returned raw distance metrics (lower = better) — FAISS, Chroma, Milvus, Redis, Cassandra, PGVector, S3 Vectors, Supabase, Valkey, Azure MySQL, and Vertex AI Vector Search — causing incorrect ranking in multi-store setups ([#5391](https://github.com/mem0ai/mem0/pull/5391)) - **Vector Stores:** Normalize similarity scores to `[0, 1]` (higher = better) consistently across all backends. 11 adapters previously returned raw distance metrics (lower = better) — FAISS, Chroma, Milvus, Redis, Cassandra, PGVector, S3 Vectors, Supabase, Valkey, Azure MySQL, and Vertex AI Vector Search — causing incorrect ranking in multi-store setups ([#5391](https://github.com/mem0ai/mem0/pull/5391))
@@ -244,7 +229,7 @@ mode: "wide"
**Improvements:** **Improvements:**
- **Telemetry:** Sample OSS hot-path events at 10% via PostHog `before_send` hook to reduce event volume ([#4771](https://github.com/mem0ai/mem0/pull/4771)) - **Telemetry:** Sample OSS hot-path events at 10% via PostHog `before_send` hook to reduce event volume ([#4771](https://github.com/mem0ai/mem0/pull/4771))
See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) and [Platform migration guide](https://docs.mem0.ai/migration/platform-v2-to-v3) for upgrade instructions. See the [OSS v1 to v2 migration guide](https://docs.mem0.ai/migration/oss-v1-to-v2) and [Platform migration guide](https://docs.mem0.ai/migration/platform-v2-to-v3) for upgrade instructions.
</Update> </Update>
@@ -1085,23 +1070,6 @@ See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-
<Tab title="TypeScript"> <Tab title="TypeScript">
<Update label="2026-06-27" description="v3.0.12">
**New Features:**
- **Client:** Add `expirationDate` to `AddMemoryOptions`, `update()`, and the `Memory` interface; add `showExpired` to `SearchMemoryOptions` and `GetAllMemoryOptions` ([#5874](https://github.com/mem0ai/mem0/pull/5874))
- **LLMs:** Add `MiniMaxLLM` provider backed by the OpenAI-compatible MiniMax API (`api.minimax.io/v1`, default model `MiniMax-M2.7`) ([#5858](https://github.com/mem0ai/mem0/pull/5858))
- **LLMs:** Add `LiteLLM` provider for routing requests through a local or hosted LiteLLM proxy ([#5830](https://github.com/mem0ai/mem0/pull/5830))
- **Vector Stores:** Add `connectionString` and `ssl` options to the PGVector config, allowing connection via URI instead of individual host/user/password/port fields ([#5789](https://github.com/mem0ai/mem0/pull/5789))
**Bug Fixes:**
- **Memory (OSS):** Validate and trim entity IDs (`userId`, `agentId`, `runId`) in `deleteAll()` via `validateAndTrimEntityId` ([#5735](https://github.com/mem0ai/mem0/pull/5735))
- **Vector Stores:** Use nullish coalescing for `hash` and timestamps in the Redis `insert()` and `update()` paths so entity payloads that omit those fields no longer crash ([#5860](https://github.com/mem0ai/mem0/pull/5860))
**Security:**
- **Dependencies:** Bump `undici` to `>=6.27.0` via pnpm override to remediate CVE-2026-12151 ([#5861](https://github.com/mem0ai/mem0/pull/5861))
</Update>
<Update label="2026-06-24" description="v3.0.11"> <Update label="2026-06-24" description="v3.0.11">
**Bug Fixes:** **Bug Fixes:**
@@ -59,9 +59,5 @@ Here are the parameters available for configuring AWS Bedrock embedder:
| Parameter | Description | Default Value | | Parameter | Description | Default Value |
| --- | --- | --- | | --- | --- | --- |
| `model` | The name of the embedding model to use | `amazon.titan-embed-text-v1` | | `model` | The name of the embedding model to use | `amazon.titan-embed-text-v1` |
| `aws_region` | AWS region for the Bedrock client | `us-west-2` |
| `aws_access_key_id` | AWS access key ID for authentication | `None` |
| `aws_secret_access_key` | AWS secret access key for authentication | `None` |
| `aws_session_token` | AWS session token for temporary credentials | `None` |
</Tab> </Tab>
</Tabs> </Tabs>
@@ -67,15 +67,14 @@ Here are the parameters available for configuring Gemini embedder:
| Parameter | Description | Default Value | | Parameter | Description | Default Value |
| ---------------- | ------------------------------------ | ----------------------- | | ---------------- | ------------------------------------ | ----------------------- |
| `model` | The name of the embedding model to use| `models/gemini-embedding-001` | | `model` | The name of the embedding model to use| `models/gemini-embedding-001` |
| `embedding_dims` | Dimensions of the embedding model | `768` | | `embedding_dims` | Dimensions of the embedding model | `1536` |
| `api_key` | The Google API key | `None` | | `api_key` | The Google API key | `None` |
| `output_dimensionality` | Output dimensionality for the embedding model (Gemini-specific; used when `embedding_dims` is not set) | `None` |
</Tab> </Tab>
<Tab title="TypeScript"> <Tab title="TypeScript">
| Parameter | Description | Default Value | | Parameter | Description | Default Value |
| ----------------- | --------------------------------------------- | -------------------------- | | ----------------- | --------------------------------------------- | -------------------------- |
| `model` | The name of the embedding model to use | `gemini-embedding-001` | | `model` | The name of the embedding model to use | `gemini-embedding-001` |
| `embeddingDims` | Dimensions of the embedding model. When not set, uses the model's native output dimensionality (3072 for `gemini-embedding-001`; MRL truncation to 768, 1536, or 3072 is supported) | `None` | | `embeddingDims` | Dimensions of the embedding model | `1536` |
| `apiKey` | Google API key | `None` | | `apiKey` | Google API key | `None` |
</Tab> </Tab>
</Tabs> </Tabs>
@@ -16,7 +16,7 @@ config = {
"embedder": { "embedder": {
"provider": "lmstudio", "provider": "lmstudio",
"config": { "config": {
"model": "nomic-ai/nomic-embed-text-v1.5-GGUF" "model": "nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.f16.gguf"
} }
} }
} }
@@ -37,6 +37,6 @@ Here are the parameters available for configuring LM Studio embedder:
| Parameter | Description | Default Value | | Parameter | Description | Default Value |
| --- | --- | --- | | --- | --- | --- |
| `model` | The name of the LM Studio model to use | `nomic-ai/nomic-embed-text-v1.5-GGUF` | | `model` | The name of the LM Studio model to use | `nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.f16.gguf` |
| `embedding_dims` | Dimensions of the embedding model | `1536` | | `embedding_dims` | Dimensions of the embedding model | `1536` |
| `lmstudio_base_url` | Base URL for LM Studio connection | `http://localhost:1234/v1` | | `lmstudio_base_url` | Base URL for LM Studio connection | `http://localhost:1234/v1` |
+1 -2
View File
@@ -10,7 +10,7 @@ Mem0 offers support for various embedding models, allowing users to choose the o
See the list of supported embedders below. See the list of supported embedders below.
<Note> <Note>
All embedders listed below are supported in the Python implementation. The TypeScript implementation supports: **OpenAI**, **Azure OpenAI**, **Google AI**, **Langchain**, **LM Studio**, and **Ollama**. The following embedders are supported in the Python implementation. The TypeScript implementation currently only supports OpenAI.
</Note> </Note>
<CardGroup cols={4}> <CardGroup cols={4}>
@@ -24,7 +24,6 @@ See the list of supported embedders below.
<Card title="LM Studio" href="/components/embedders/models/lmstudio"></Card> <Card title="LM Studio" href="/components/embedders/models/lmstudio"></Card>
<Card title="Langchain" href="/components/embedders/models/langchain"></Card> <Card title="Langchain" href="/components/embedders/models/langchain"></Card>
<Card title="AWS Bedrock" href="/components/embedders/models/aws_bedrock"></Card> <Card title="AWS Bedrock" href="/components/embedders/models/aws_bedrock"></Card>
<Card title="FastEmbed" href="/components/embedders/models/fastembed"></Card>
</CardGroup> </CardGroup>
## Usage ## Usage
+2 -2
View File
@@ -98,7 +98,7 @@ Here's a comprehensive list of all parameters that can be used across different
| `max_tokens` | Tokens to generate | All | | `max_tokens` | Tokens to generate | All |
| `top_p` | Probability threshold for nucleus sampling | All | | `top_p` | Probability threshold for nucleus sampling | All |
| `top_k` | Number of highest probability tokens to keep | All | | `top_k` | Number of highest probability tokens to keep | All |
| `http_client_proxies`| Allow proxy server settings | All | | `http_client_proxies`| Allow proxy server settings | AzureOpenAI |
| `models` | List of models | Openrouter | | `models` | List of models | Openrouter |
| `route` | Routing strategy | Openrouter | | `route` | Routing strategy | Openrouter |
| `openrouter_base_url`| Base URL for Openrouter API | Openrouter | | `openrouter_base_url`| Base URL for Openrouter API | Openrouter |
@@ -110,7 +110,7 @@ Here's a comprehensive list of all parameters that can be used across different
| `deepseek_base_url` | Base URL for DeepSeek API | DeepSeek | | `deepseek_base_url` | Base URL for DeepSeek API | DeepSeek |
| `xai_base_url` | Base URL for XAI API | XAI | | `xai_base_url` | Base URL for XAI API | XAI |
| `sarvam_base_url` | Base URL for Sarvam API | Sarvam | | `sarvam_base_url` | Base URL for Sarvam API | Sarvam |
| `reasoning_effort` | Reasoning level (low, medium, high) | All | | `reasoning_effort` | Reasoning level (low, medium, high) | Sarvam |
| `frequency_penalty` | Penalize frequent tokens (-2.0 to 2.0) | Sarvam | | `frequency_penalty` | Penalize frequent tokens (-2.0 to 2.0) | Sarvam |
| `presence_penalty` | Penalize existing tokens (-2.0 to 2.0) | Sarvam | | `presence_penalty` | Penalize existing tokens (-2.0 to 2.0) | Sarvam |
| `seed` | Seed for deterministic sampling | Sarvam | | `seed` | Seed for deterministic sampling | Sarvam |
+2 -2
View File
@@ -20,7 +20,7 @@ config = {
"llm": { "llm": {
"provider": "anthropic", "provider": "anthropic",
"config": { "config": {
"model": "claude-sonnet-4-6", "model": "claude-sonnet-4-20250514",
"temperature": 0.1, "temperature": 0.1,
"max_tokens": 2000, "max_tokens": 2000,
} }
@@ -45,7 +45,7 @@ const config = {
provider: 'anthropic', provider: 'anthropic',
config: { config: {
apiKey: process.env.ANTHROPIC_API_KEY || '', apiKey: process.env.ANTHROPIC_API_KEY || '',
model: 'claude-sonnet-4-6', model: 'claude-sonnet-4-20250514',
temperature: 0.1, temperature: 0.1,
maxTokens: 2000, maxTokens: 2000,
}, },
+1 -1
View File
@@ -6,7 +6,7 @@ description: "Configure AWS Bedrock as an LLM provider in Mem0 with IAM authenti
### Setup ### Setup
- Before using the AWS Bedrock LLM, make sure you have the appropriate model access from [Bedrock Console](https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess). - Before using the AWS Bedrock LLM, make sure you have the appropriate model access from [Bedrock Console](https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess).
- You will also need to authenticate the `boto3` client by using a method in the [AWS documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html#configuring-credentials) - You will also need to authenticate the `boto3` client by using a method in the [AWS documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html#configuring-credentials)
- You will have to export `AWS_REGION`, `AWS_ACCESS_KEY_ID`, and `AWS_SECRET_ACCESS_KEY` to set environment variables. - You will have to export `AWS_REGION`, `AWS_ACCESS_KEY`, and `AWS_SECRET_ACCESS_KEY` to set environment variables.
### Usage ### Usage
+2 -2
View File
@@ -21,7 +21,7 @@ config = {
"llm": { "llm": {
"provider": "groq", "provider": "groq",
"config": { "config": {
"model": "llama-3.3-70b-versatile", "model": "mixtral-8x7b-32768",
"temperature": 0.1, "temperature": 0.1,
"max_tokens": 2000, "max_tokens": 2000,
} }
@@ -46,7 +46,7 @@ const config = {
provider: 'groq', provider: 'groq',
config: { config: {
apiKey: process.env.GROQ_API_KEY || '', apiKey: process.env.GROQ_API_KEY || '',
model: 'llama3-70b-8192', model: 'mixtral-8x7b-32768',
temperature: 0.1, temperature: 0.1,
maxTokens: 1000, maxTokens: 1000,
}, },
+1 -1
View File
@@ -20,7 +20,7 @@ config = {
"llm": { "llm": {
"provider": "xai", "provider": "xai",
"config": { "config": {
"model": "grok-4.3", "model": "grok-3-beta",
"temperature": 0.1, "temperature": 0.1,
"max_tokens": 2000, "max_tokens": 2000,
} }
+1 -1
View File
@@ -16,7 +16,7 @@ For a comprehensive list of available parameters for llm configuration, please r
See the list of supported LLMs below. See the list of supported LLMs below.
<Note> <Note>
All LLMs are supported in Python. The following LLMs are also supported in TypeScript: **OpenAI**, **Anthropic**, **Groq**, **Azure OpenAI**, **DeepSeek**, **Google AI**, **Langchain**, **LM Studio**, **Mistral AI**, and **Ollama**. All LLMs are supported in Python. The following LLMs are also supported in TypeScript: **OpenAI**, **Anthropic**, and **Groq**.
</Note> </Note>
<CardGroup cols={4}> <CardGroup cols={4}>
+1 -1
View File
@@ -46,7 +46,7 @@ Here are the parameters available for configuring Baidu VectorDB:
| `account` | Baidu VectorDB account name | `root` | | `account` | Baidu VectorDB account name | `root` |
| `api_key` | API key for accessing Baidu VectorDB | Required | | `api_key` | API key for accessing Baidu VectorDB | Required |
| `database_name` | Name of the database | `mem0` | | `database_name` | Name of the database | `mem0` |
| `table_name` | Name of the table | `mem0` | | `table_name` | Name of the table | `mem0_table` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` | | `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `metric_type` | Distance metric for similarity search | `L2` | | `metric_type` | Distance metric for similarity search | `L2` |
@@ -56,8 +56,6 @@ Here are the parameters available for configuring Elasticsearch:
| `api_key` | API key for authentication | `None` | | `api_key` | API key for authentication | `None` |
| `user` | Username for basic authentication | `None` | | `user` | Username for basic authentication | `None` |
| `password` | Password for basic authentication | `None` | | `password` | Password for basic authentication | `None` |
| `use_ssl` | Whether to use SSL for the connection | `True` |
| `ca_certs` | Path to CA bundle for SSL certificate verification | `None` |
| `verify_certs` | Whether to verify SSL certificates | `True` | | `verify_certs` | Whether to verify SSL certificates | `True` |
| `auto_create_index` | Whether to automatically create the index | `True` | | `auto_create_index` | Whether to automatically create the index | `True` |
| `custom_search_query` | Function returning a custom search query | `None` | | `custom_search_query` | Function returning a custom search query | `None` |
-1
View File
@@ -55,7 +55,6 @@ Here are the parameters available for configuring FAISS:
| `path` | Path to store FAISS index and metadata | `/tmp/faiss/<collection_name>` | | `path` | Path to store FAISS index and metadata | `/tmp/faiss/<collection_name>` |
| `distance_strategy` | Distance metric strategy to use (options: 'euclidean', 'inner_product', 'cosine') | `euclidean` | | `distance_strategy` | Distance metric strategy to use (options: 'euclidean', 'inner_product', 'cosine') | `euclidean` |
| `normalize_L2` | Whether to normalize L2 vectors (only applicable for euclidean distance) | `False` | | `normalize_L2` | Whether to normalize L2 vectors (only applicable for euclidean distance) | `False` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
### Performance Considerations ### Performance Considerations
+3 -3
View File
@@ -47,12 +47,12 @@ m.add(messages, user_id="alice", metadata={"category": "movies"})
``` ```
```typescript TypeScript ```typescript TypeScript
import { Memory } from "mem0ai/oss"; import { Memory } from "mem0ai";
import { OpenAIEmbeddings } from "@langchain/openai"; import { OpenAIEmbeddings } from "@langchain/openai";
import { MemoryVectorStore } from "langchain/vectorstores/memory"; import { MemoryVectorStore as LangchainMemoryStore } from "langchain/vectorstores/memory";
const embeddings = new OpenAIEmbeddings(); const embeddings = new OpenAIEmbeddings();
const vectorStore = new MemoryVectorStore(embeddings); const vectorStore = new LangchainVectorStore(embeddings);
const config = { const config = {
"vector_store": { "vector_store": {
+3 -3
View File
@@ -42,8 +42,8 @@ Here are the parameters available for configuring MongoDB:
| Parameter | Description | Default Value | | Parameter | Description | Default Value |
| --- | --- | --- | | --- | --- | --- |
| db_name | Name of the MongoDB database | `"mem0_db"` | | db_name | Name of the MongoDB database | `"mem0_db"` |
| collection_name | Name of the MongoDB collection | `"mem0"` | | collection_name | Name of the MongoDB collection | `"mem0_collection"` |
| embedding_model_dims | Dimensions of the embedding vectors | `1536` | | embedding_model_dims | Dimensions of the embedding vectors | `1536` |
| mongo_uri | The MongoDB URI connection string | `mongodb://localhost:27017` | | mongo_uri | The MongoDB URI connection string | `mongodb://username:password@localhost:27017` |
> **Note**: If `mongo_uri` is not provided, it will default to `mongodb://localhost:27017`. > **Note**: If `mongo_uri` is not provided, it will default to `mongodb://username:password@localhost:27017`.
@@ -10,7 +10,7 @@ description: "Use AWS Neptune Analytics as a vector store in Mem0, combining gra
## Installation ## Installation
```bash ```bash
pip install mem0ai[vector-stores] pip install mem0ai[vector_stores]
``` ```
## Usage ## Usage
@@ -18,9 +18,7 @@ os.environ["UPSTASH_VECTOR_REST_TOKEN"] = "..."
config = { config = {
"vector_store": { "vector_store": {
"provider": "upstash_vector", "provider": "upstash_vector",
"config": { "enable_embeddings": True,
"enable_embeddings": True,
}
} }
} }
+2 -2
View File
@@ -9,7 +9,7 @@ description: "Use Valkey as an open-source vector store in Mem0 for high-perform
## Installation ## Installation
```bash ```bash
pip install mem0ai[vector-stores] pip install mem0ai[vector_stores]
``` ```
## Usage ## Usage
@@ -51,7 +51,7 @@ Here are the parameters available for configuring Valkey:
| `hnsw_ef_construction` | Size of dynamic candidate list for HNSW | `200` | | `hnsw_ef_construction` | Size of dynamic candidate list for HNSW | `200` |
| `hnsw_ef_runtime` | Size of dynamic candidate list for search | `10` | | `hnsw_ef_runtime` | Size of dynamic candidate list for search | `10` |
| `cluster_mode` | Enable cluster mode for Valkey cluster (CME) deployments | `false` | | `cluster_mode` | Enable cluster mode for Valkey cluster (CME) deployments | `false` |
| `timezone` | Timezone for timestamp handling | `UTC` | | `distance_metric` | Distance metric for vector similarity | `cosine` |
## Cluster Mode ## Cluster Mode
+2 -3
View File
@@ -24,7 +24,7 @@ config = {
"deployment_index_id": "YOUR_DEPLOYMENT_INDEX_ID", # Required: Deployment-specific ID "deployment_index_id": "YOUR_DEPLOYMENT_INDEX_ID", # Required: Deployment-specific ID
"project_id": "YOUR_PROJECT_ID", # Required: Google Cloud project ID "project_id": "YOUR_PROJECT_ID", # Required: Google Cloud project ID
"project_number": "YOUR_PROJECT_NUMBER", # Required: Google Cloud project number "project_number": "YOUR_PROJECT_NUMBER", # Required: Google Cloud project number
"region": "YOUR_REGION", # Required: Google Cloud region "region": "YOUR_REGION", # Optional: Defaults to GOOGLE_CLOUD_REGION
"credentials_path": "path/to/credentials.json", # Optional: Defaults to GOOGLE_APPLICATION_CREDENTIALS "credentials_path": "path/to/credentials.json", # Optional: Defaults to GOOGLE_APPLICATION_CREDENTIALS
"vector_search_api_endpoint": "YOUR_API_ENDPOINT" # Required for get operations "vector_search_api_endpoint": "YOUR_API_ENDPOINT" # Required for get operations
} }
@@ -45,6 +45,5 @@ m.add("Your text here", user_id="user", metadata={"category": "example"})
| `project_id` | Google Cloud project ID | Yes | | `project_id` | Google Cloud project ID | Yes |
| `project_number` | Google Cloud project number | Yes | | `project_number` | Google Cloud project number | Yes |
| `vector_search_api_endpoint` | Vector search API endpoint | Yes (for get operations) | | `vector_search_api_endpoint` | Vector search API endpoint | Yes (for get operations) |
| `region` | Google Cloud region | Yes | | `region` | Google Cloud region | No (defaults to GOOGLE_CLOUD_REGION) |
| `credentials_path` | Path to service account credentials | No (defaults to GOOGLE_APPLICATION_CREDENTIALS) | | `credentials_path` | Path to service account credentials | No (defaults to GOOGLE_APPLICATION_CREDENTIALS) |
| `service_account_json` | Service account credentials as a dictionary (alternative to `credentials_path`) | `None` |
+2 -3
View File
@@ -7,7 +7,7 @@ description: "Use Weaviate as an open-source vector search engine in Mem0 for st
### Installation ### Installation
```bash ```bash
pip install weaviate-client pip install weaviate weaviate-client
``` ```
### Usage ### Usage
@@ -48,5 +48,4 @@ Here are the parameters available for configuring Weaviate:
| `collection_name` | The name of the collection to store the vectors | `mem0` | | `collection_name` | The name of the collection to store the vectors | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` | | `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `cluster_url` | URL for the Weaviate server | `None` | | `cluster_url` | URL for the Weaviate server | `None` |
| `auth_client_secret` | API key for Weaviate authentication | `None` | | `auth_client_secret` | API key for Weaviate authentication | `None` |
| `additional_headers` | Additional headers to include in requests (`Dict[str, str]`) | `None` |
+1 -1
View File
@@ -10,7 +10,7 @@ Mem0 includes built-in support for various popular databases. Memory can utilize
See the list of supported vector databases below. See the list of supported vector databases below.
<Note> <Note>
The following vector databases are supported in the Python implementation. The TypeScript implementation currently supports Qdrant, Redis, PGVector, Supabase, LangChain, Azure AI Search, Vectorize, and an in-memory store. The following vector databases are supported in the Python implementation. The TypeScript implementation currently only supports Qdrant, Redis, Valkey, Vectorize and in-memory vector database.
</Note> </Note>
<CardGroup cols={3}> <CardGroup cols={3}>
+17 -83
View File
@@ -1,65 +1,32 @@
--- ---
title: Development title: Development
description: "Guide to contributing code to Mem0, covering the issue-first workflow, the CLA, environment setup for the Python and TypeScript SDKs, and code quality checks." description: "Guide to contributing code to Mem0, covering the fork and clone workflow, PR submission, and code quality checks."
icon: "code" icon: "code"
--- ---
# Development Contributions # Development Contributions
We strive to make contributions **easy, collaborative, and enjoyable**. Mem0 is a We strive to make contributions **easy, collaborative, and enjoyable**. Follow the steps below to ensure a smooth contribution process.
polyglot monorepo containing the **Python SDK** (`mem0/`), the **TypeScript SDK**
(`mem0-ts/`), CLIs, integrations, the self-hosted server, and the docs site.
Follow the steps below for a smooth contribution process.
<Note> ## Submitting Your Contribution through PR
For the complete contributor checklist, see
[CONTRIBUTING.md](https://github.com/mem0ai/mem0/blob/main/CONTRIBUTING.md) in
the repository root.
</Note>
## Before You Start To contribute, follow these steps:
### 1. Open an Issue First
**Always open an issue before opening a pull request.** This lets us discuss the
change, avoid duplicate work, and agree on the approach before you write code.
- Search [existing issues](https://github.com/mem0ai/mem0/issues) first.
- If none match, open a
[bug report](https://github.com/mem0ai/mem0/issues/new?template=bug_report.yml)
or [feature request](https://github.com/mem0ai/mem0/issues/new?template=feature_request.yml).
- For anything beyond a trivial fix, wait for a maintainer to confirm the approach.
Every pull request must link to an issue using `Closes #<issue-number>`.
### 2. Sign the Contributor License Agreement (CLA)
**We cannot merge any pull request until you have signed our Contributor License
Agreement (CLA).** When you open your first PR, the CLA bot will comment with a
link to sign — it takes less than a minute and only needs to be done once.
## Submitting Your Contribution through a PR
1. **Fork & Clone** the repository: [Mem0 on GitHub](https://github.com/mem0ai/mem0) 1. **Fork & Clone** the repository: [Mem0 on GitHub](https://github.com/mem0ai/mem0)
2. **Create a Feature Branch**: Use a dedicated branch, e.g., `feature/my-new-feature` 2. **Create a Feature Branch**: Use a dedicated branch for your changes, e.g., `feature/my-new-feature`
3. **Implement Changes**: If adding a feature or fixing a bug, be sure to: 3. **Implement Changes**: If adding a feature or fixing a bug, ensure to:
- Write necessary **tests** - Write necessary **tests**
- Add **documentation, docstrings, and runnable examples** - Add **documentation, docstrings, and runnable examples**
4. **Code Quality Checks**: 4. **Code Quality Checks**:
- Run **linting** to catch style issues - Run **linting** to catch style issues
- Ensure **all tests pass** - Ensure **all tests pass**
5. **Commit** using [Conventional Commits](https://www.conventionalcommits.org/) 5. **Submit a Pull Request**
(`feat:`, `fix:`, `docs:`, `refactor:`, `test:`)
6. **Submit a Pull Request** against `main`, linking the issue and filling out the
PR template.
For detailed guidance on pull requests, refer to [GitHub's documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request). For detailed guidance on pull requests, refer to [GitHub's documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request).
--- ---
## Python SDK (`mem0/`) ## Dependency Management
### Dependency Management
We use `hatch` as our package manager. Install it by following the [official instructions](https://hatch.pypa.io/latest/install/). We use `hatch` as our package manager. Install it by following the [official instructions](https://hatch.pypa.io/latest/install/).
@@ -77,9 +44,13 @@ hatch -e dev_py_3_11 shell # For dev_py_3_11 (differences are mentioned in pypr
make install_all make install_all
``` ```
---
## Development Standards
### Pre-commit Hooks ### Pre-commit Hooks
Ensure `pre-commit` is installed before contributing (hooks run ruff + isort): Ensure `pre-commit` is installed before contributing:
```bash ```bash
pre-commit install pre-commit install
@@ -87,7 +58,7 @@ pre-commit install
### Linting with `ruff` ### Linting with `ruff`
Run the linter and fix any reported issues before submitting your PR (line length **120**): Run the linter and fix any reported issues before submitting your PR:
```bash ```bash
make lint make lint
@@ -95,11 +66,10 @@ make lint
### Code Formatting ### Code Formatting
To maintain a consistent code style, format your code and sort imports (isort, `profile = "black"`): To maintain a consistent code style, format your code:
```bash ```bash
make format make format
make sort
``` ```
### Testing with `pytest` ### Testing with `pytest`
@@ -114,46 +84,10 @@ make test
--- ---
## TypeScript SDK (`mem0-ts/`)
We use [`pnpm`](https://pnpm.io/) (v10+) for all TypeScript packages. **Do NOT use
`npm` or `yarn`.**
```bash
cd mem0-ts
pnpm install
pnpm run build # tsup (CJS + ESM)
pnpm run test # jest (all tests)
pnpm run test:unit # unit tests with coverage
```
### Standards
- **Build:** tsup
- **Formatter:** Prettier
- **Tests:** jest
- Always run type checking after changes: `pnpm run typecheck` (or `tsc --noEmit`)
- Use ES module `import` syntax — never `require()`
---
## Reporting Security Issues
**Do not report security vulnerabilities through public issues or pull requests.**
Please follow our [Security Policy](https://github.com/mem0ai/mem0/blob/main/SECURITY.md)
to report them privately.
---
## Release Process ## Release Process
Packages are published automatically via GitHub Actions when a GitHub Release is Currently, releases are handled manually. We aim for frequent releases, typically when new features or bug fixes are introduced.
created with the correct tag prefix (e.g. `v*` for the Python SDK, `ts-v*` for the
TypeScript SDK). See
[CONTRIBUTING.md](https://github.com/mem0ai/mem0/blob/main/CONTRIBUTING.md#releasing)
for the full tag-prefix table and publishing details.
--- ---
Thank you for contributing to Mem0! Thank you for contributing to Mem0!
@@ -31,7 +31,7 @@ const openaiClient = new OpenAI();
const memory = new Memory(); const memory = new Memory();
async function chatWithMemories(message, userId = "default_user") { async function chatWithMemories(message, userId = "default_user") {
const relevantMemories = await memory.search(message, { filters: { user_id: userId } }); const relevantMemories = await memory.search(message, { userId: userId });
const memoriesStr = relevantMemories.results const memoriesStr = relevantMemories.results
.map(entry => `- ${entry.memory}`) .map(entry => `- ${entry.memory}`)
@@ -289,7 +289,8 @@ print([m["memory"] for m in constraints["results"]])
```python ```python
constraints = memory.search( constraints = memory.search(
query="injury concerns", query="injury concerns",
filters={"user_id": "max", "memory_bucket": {"in": ["constraints"]}}, user_id="max",
filters={"memory_bucket": {"in": ["constraints"]}},
threshold=0.0 # optional: widen recall for short phrases threshold=0.0 # optional: widen recall for short phrases
) )
print([m["memory"] for m in constraints["results"]]) print([m["memory"] for m in constraints["results"]])
@@ -735,7 +736,8 @@ mem0_client.add(messages, user_id="max", run_id="nyc-2025")
# Retrieve only Boston memories # Retrieve only Boston memories
boston_memories = mem0_client.search( boston_memories = mem0_client.search(
"training plan", "training plan",
filters={"user_id": "max", "run_id": "boston-2025"} user_id="max",
run_id="boston-2025"
) )
``` ```
</Tab> </Tab>
@@ -747,7 +749,8 @@ memory.add(messages, user_id="max", run_id="nyc-2025")
# Retrieve only Boston memories # Retrieve only Boston memories
boston_memories = memory.search( boston_memories = memory.search(
"training plan", "training plan",
filters={"user_id": "max", "run_id": "boston-2025"}, user_id="max",
run_id="boston-2025",
) )
``` ```
</Tab> </Tab>
@@ -843,7 +846,8 @@ Prioritize recent training over old data:
```python ```python
recent = mem0_client.search( recent = mem0_client.search(
"training progress", "training progress",
filters={"user_id": "max", "created_at": {"gte": "2025-10-01"}} user_id="max",
filters={"created_at": {"gte": "2025-10-01"}}
) )
``` ```
</Tab> </Tab>
@@ -862,7 +866,8 @@ memory.add(
cutoff = int(datetime(2025, 10, 1).timestamp()) cutoff = int(datetime(2025, 10, 1).timestamp())
recent = memory.search( recent = memory.search(
"training progress", "training progress",
filters={"user_id": "max", "logged_epoch": {"gte": cutoff}}, user_id="max",
filters={"logged_epoch": {"gte": cutoff}},
) )
``` ```
</Tab> </Tab>
@@ -884,7 +889,8 @@ mem0_client.add(
# Later, find all speed workouts # Later, find all speed workouts
speed_sessions = mem0_client.search( speed_sessions = mem0_client.search(
"speed work", "speed work",
filters={"user_id": "max", "metadata": {"workout_type": "speed"}} user_id="max",
filters={"metadata": {"workout_type": "speed"}}
) )
``` ```
</Tab> </Tab>
@@ -899,7 +905,8 @@ memory.add(
# Later, find all speed workouts # Later, find all speed workouts
speed_sessions = memory.search( speed_sessions = memory.search(
"speed work", "speed work",
filters={"user_id": "max", "workout_type": "speed"}, user_id="max",
filters={"workout_type": "speed"},
) )
``` ```
</Tab> </Tab>
@@ -58,7 +58,6 @@ Use `get_all()` with filters to retrieve everything for a specific user:
```python ```python
dev_memories = client.get_all( dev_memories = client.get_all(
filters={"user_id": "dev"}, filters={"user_id": "dev"},
page=1,
page_size=50 page_size=50
) )
@@ -211,8 +211,8 @@ class MultiAgentLearningSystem:
try: try:
# Search memory for learning patterns # Search memory for learning patterns
memories = self.memory.search( memories = self.memory.search(
query="learning machine learning", user_id=self.student_id,
filters={"user_id": self.student_id} query="learning machine learning"
) )
if memories and memories.get('results'): if memories and memories.get('results'):
@@ -50,7 +50,7 @@ load_dotenv()
USER_ID = "Alex" USER_ID = "Alex"
# Initialize Mem0 client # Initialize Mem0 client
mem0_client = MemoryClient() mem0 = MemoryClient()
``` ```
## Define Memory Tools ## Define Memory Tools
@@ -76,7 +76,7 @@ def retrieve_patient_info(query: str) -> dict:
# Search Mem0 # Search Mem0
results = mem0_client.search( results = mem0_client.search(
query, query,
filters={"user_id": USER_ID}, user_id=USER_ID,
top_k=5, top_k=5,
threshold=0.7 # Higher threshold for more relevant results threshold=0.7 # Higher threshold for more relevant results
) )
@@ -53,12 +53,34 @@ async function addUserPreferences() {
await addUserPreferences(); await addUserPreferences();
``` ```
```json Output ```json Output (Memories)
{ [
"message": "Memory processing has been queued for background execution", {
"status": "PENDING", "id": "ff9f3367-9e83-415d-b9c5-dc8befd9a4b4",
"event_id": "9f8c2b1a-4e7d-4c3a-9b21-1a2b3c4d5e6f" "data": { "memory": "Loves BMW, Audi, and Porsche" },
} "event": "ADD"
},
{
"id": "04172ce6-3d7b-45a3-b4a1-ee9798593cb4",
"data": { "memory": "Hates Mercedes" },
"event": "ADD"
},
{
"id": "db363a5d-d258-4953-9e4c-777c120de34d",
"data": { "memory": "Loves red cars and maroon cars" },
"event": "ADD"
},
{
"id": "5519aaad-a2ac-4c0d-81d7-0d55c6ecdba8",
"data": { "memory": "Has a budget of 120K to 150K USD" },
"event": "ADD"
},
{
"id": "523b7693-7344-4563-922f-5db08edc8634",
"data": { "memory": "Likes Audi the most" },
"event": "ADD"
}
]
``` ```
</CodeGroup> </CodeGroup>
## Retrieving Memories ## Retrieving Memories
@@ -66,7 +88,7 @@ await addUserPreferences();
Search for relevant memories based on the current user input: Search for relevant memories based on the current user input:
```javascript ```javascript
const relevantMemories = await mem0Client.search(userInput, { filters: { user_id: USER_ID } }); const relevantMemories = await mem0Client.search(userInput, { userId: USER_ID });
``` ```
## Structured Responses with Zod ## Structured Responses with Zod
@@ -172,7 +194,7 @@ async function main(memory = false) {
// Search for relevant memories // Search for relevant memories
let relevantMemories = [] let relevantMemories = []
if (memory) { if (memory) {
relevantMemories = await mem0Client.search(input, { filters: { user_id: USER_ID } }); relevantMemories = await mem0Client.search(input, { userId: USER_ID });
} }
const response = await openAIClient.responses.create({ const response = await openAIClient.responses.create({
@@ -4,6 +4,8 @@ description: "Blend Tavily's realtime results with personal context stored in Me
--- ---
<Snippet file="security-compliance.mdx" />
Imagine asking a search assistant for "coffee shops nearby" and instead of generic results, it shows remote-work-friendly cafes with great WiFi in your city because it remembers you mentioned working remotely before. Or when you search for "lunchbox ideas for kids" it knows you have a 7-year-old daughter and recommends peanut-free options that align with her allergy. Imagine asking a search assistant for "coffee shops nearby" and instead of generic results, it shows remote-work-friendly cafes with great WiFi in your city because it remembers you mentioned working remotely before. Or when you search for "lunchbox ideas for kids" it knows you have a 7-year-old daughter and recommends peanut-free options that align with her allergy.
That's what we are going to build today, a Personalized Search Assistant powered by Mem0 for memory and [Tavily](https://tavily.com) for real-time search. That's what we are going to build today, a Personalized Search Assistant powered by Mem0 for memory and [Tavily](https://tavily.com) for real-time search.
@@ -217,7 +217,8 @@ def apply_writing_style(original_content):
results = memory.search( results = memory.search(
query="What are my writing style preferences?", query="What are my writing style preferences?",
filters={"user_id": USER_ID, "run_id": RUN_ID}, user_id=USER_ID,
run_id=RUN_ID,
) )
if not results: if not results:
@@ -314,16 +314,18 @@ class EmailProcessor:
user_id (str): User identifier user_id (str): User identifier
sender (str, optional): Filter by sender email address sender (str, optional): Filter by sender email address
""" """
# In OSS, user_id is an explicit parameter (not inside filters)
if not sender: if not sender:
results = self.memory.search( results = self.memory.search(
query=query, query=query,
filters={"user_id": user_id, "memory_category": "email"}, user_id=user_id,
filters={"memory_category": "email"},
) )
else: else:
results = self.memory.search( results = self.memory.search(
query=query, query=query,
user_id=user_id,
filters={ filters={
"user_id": user_id,
"AND": [ "AND": [
{"memory_category": "email"}, {"memory_category": "email"},
{"sender": sender}, {"sender": sender},
@@ -341,9 +343,10 @@ class EmailProcessor:
subject (str): Email subject to match subject (str): Email subject to match
user_id (str): User identifier user_id (str): User identifier
""" """
# In OSS, user_id is an explicit parameter
thread = self.memory.get_all( thread = self.memory.get_all(
user_id=user_id,
filters={ filters={
"user_id": user_id,
"AND": [ "AND": [
{"memory_category": "email"}, {"memory_category": "email"},
{"subject": {"icontains": subject}}, {"subject": {"icontains": subject}},
+1 -1
View File
@@ -57,7 +57,7 @@ class CustomerSupportAIAgent:
""" """
# Start a streaming chat completion request to the AI # Start a streaming chat completion request to the AI
stream = self.client.chat.completions.create( stream = self.client.chat.completions.create(
model="gpt-5-mini", model="gpt-4",
stream=True, stream=True,
messages=[ messages=[
{"role": "system", "content": "You are a customer support AI agent."}, {"role": "system", "content": "You are a customer support AI agent."},
@@ -238,11 +238,11 @@ client.search("preferences", filters={
- **Use natural language**: Mem0 understands intent, so describe what you're looking for naturally - **Use natural language**: Mem0 understands intent, so describe what you're looking for naturally
- **Scope with user ID**: Always provide `user_id` to scope search to relevant memories - **Scope with user ID**: Always provide `user_id` to scope search to relevant memories
- **Platform API**: Use `filters={"user_id": "alice"}` - **Platform API**: Use `filters={"user_id": "alice"}`
- **OSS**: Use `filters={"user_id": "alice"}` (passing `user_id` as a top-level kwarg raises `ValueError` in v3) - **OSS**: Use `user_id="alice"` as parameter
- **Combine filters**: Use AND/OR logic to create precise queries (Platform) - **Combine filters**: Use AND/OR logic to create precise queries (Platform)
- **Consider wildcard filters**: Use wildcard filters (e.g., `run_id: "*"`) for broader matches - **Consider wildcard filters**: Use wildcard filters (e.g., `run_id: "*"`) for broader matches
- **Tune parameters**: Adjust `top_k` for result count, `threshold` for relevance cutoff - **Tune parameters**: Adjust `top_k` for result count, `threshold` for relevance cutoff
- **Enable reranking**: Use `rerank=True` (default is `False`) when you have a reranker configured - **Enable reranking**: Use `rerank=True` (default) when you have a reranker configured
<Callout type="tip" icon="plug"> <Callout type="tip" icon="plug">
**MCP Alternative**: With <Link href="/platform/mem0-mcp">Mem0 MCP</Link>, AI agents can search their own memories proactively when needed. **MCP Alternative**: With <Link href="/platform/mem0-mcp">Mem0 MCP</Link>, AI agents can search their own memories proactively when needed.
+3 -2
View File
@@ -60,7 +60,7 @@ import os
from mem0 import Memory from mem0 import Memory
memory = Memory() memory = Memory(api_key=os.environ["MEM0_API_KEY"])
# Sticky note: conversation memory # Sticky note: conversation memory
memory.add( memory.add(
@@ -72,7 +72,8 @@ memory.add(
# Later in the session, pull long-term + session context # Later in the session, pull long-term + session context
results = memory.search( results = memory.search(
"Any hotel preferences?", "Any hotel preferences?",
filters={"user_id": "alex", "run_id": "trip-planning-2025"}, user_id="alex",
run_id="trip-planning-2025",
) )
``` ```
+2 -5
View File
@@ -123,7 +123,8 @@
"icon": "arrow-right", "icon": "arrow-right",
"pages": [ "pages": [
"migration/platform-v2-to-v3", "migration/platform-v2-to-v3",
"migration/oss-to-platform" "migration/oss-to-platform",
"migration/api-changes"
] ]
}, },
{ {
@@ -641,10 +642,6 @@
"source": "/migration/v0-to-v1", "source": "/migration/v0-to-v1",
"destination": "/" "destination": "/"
}, },
{
"source": "/migration/api-changes",
"destination": "/migration/oss-v2-to-v3"
},
{ {
"source": "/platform/features/expiration-date", "source": "/platform/features/expiration-date",
"destination": "/" "destination": "/"
+1
View File
@@ -228,6 +228,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or Platform `output_f
- [OSS to Platform Migration](https://docs.mem0.ai/migration/oss-to-platform) [Both]: Use when moving from self-hosted to managed. - [OSS to Platform Migration](https://docs.mem0.ai/migration/oss-to-platform) [Both]: Use when moving from self-hosted to managed.
- [OSS v2 to v3 Migration](https://docs.mem0.ai/migration/oss-v2-to-v3) [OSS]: Use when upgrading a self-hosted deployment across major versions. - [OSS v2 to v3 Migration](https://docs.mem0.ai/migration/oss-v2-to-v3) [OSS]: Use when upgrading a self-hosted deployment across major versions.
- [Platform v2 to v3 Migration](https://docs.mem0.ai/migration/platform-v2-to-v3) [Platform]: Use when upgrading a Platform integration across major versions. - [Platform v2 to v3 Migration](https://docs.mem0.ai/migration/platform-v2-to-v3) [Platform]: Use when upgrading a Platform integration across major versions.
- [API Changes](https://docs.mem0.ai/migration/api-changes) [Both]: Use when the upgrade involves API surface changes.
- [Server pgvector Image Upgrade](https://docs.mem0.ai/migration/server-pgvector-upgrade) [OSS]: Use when upgrading the self-hosted server Docker image from ankane/pgvector to pgvector/pgvector. - [Server pgvector Image Upgrade](https://docs.mem0.ai/migration/server-pgvector-upgrade) [OSS]: Use when upgrading the self-hosted server Docker image from ankane/pgvector to pgvector/pgvector.
- [Changelog](https://docs.mem0.ai/changelog/highlights) [Both]: Use when the user asks what shipped recently. - [Changelog](https://docs.mem0.ai/changelog/highlights) [Both]: Use when the user asks what shipped recently.
+574
View File
@@ -0,0 +1,574 @@
---
title: API Reference Changes
description: "Comprehensive reference of all API changes between Mem0 v0.x and v1.0.0 Beta, organized by component and method."
icon: "code"
iconType: "solid"
---
## Overview
This page documents all API changes between Mem0 v0.x and v1.0.0 Beta, organized by component and method.
## Memory Class Changes
### Constructor
#### v0.x
```python
from mem0 import Memory
# Basic initialization
m = Memory()
# With configuration
config = {
"version": "v1.0", # Supported in v0.x
"vector_store": {...}
}
m = Memory.from_config(config)
```
#### v1.0.0
```python
from mem0 import Memory
# Basic initialization (same)
m = Memory()
# With configuration
config = {
"version": "v1.1", # v1.1+ only
"vector_store": {...},
# New optional features
"reranker": {
"provider": "cohere",
"config": {...}
}
}
m = Memory.from_config(config)
```
### add() Method
#### v0.x Signature
```python
def add(
self,
messages,
user_id: str = None,
agent_id: str = None,
run_id: str = None,
metadata: dict = None,
filters: dict = None,
output_format: str = None, # ❌ REMOVED
version: str = None # ❌ REMOVED
) -> Union[List[dict], dict]:
...
```
#### v1.0.0 Signature
```python
def add(
self,
messages,
user_id: str = None,
agent_id: str = None,
run_id: str = None,
metadata: dict = None,
filters: dict = None,
infer: bool = True # ✅ NEW: Control memory inference
) -> dict: # Always returns dict with "results" key
...
```
#### Changes Summary
| Parameter | v0.x | v1.0.0 | Change |
|-----------|------|-----------|---------|
| `messages` | ✅ | ✅ | Unchanged |
| `user_id` | ✅ | ✅ | Unchanged |
| `agent_id` | ✅ | ✅ | Unchanged |
| `run_id` | ✅ | ✅ | Unchanged |
| `metadata` | ✅ | ✅ | Unchanged |
| `filters` | ✅ | ✅ | Unchanged |
| `output_format` | ✅ | ❌ | **REMOVED** |
| `version` | ✅ | ❌ | **REMOVED** |
| `infer` | ❌ | ✅ | **NEW** |
#### Response Format Changes
**v0.x Response (variable format):**
```python
# With output_format="v1.0"
[
{
"id": "mem_123",
"memory": "User loves pizza",
"event": "ADD"
}
]
# With output_format="v1.1"
{
"results": [
{
"id": "mem_123",
"memory": "User loves pizza",
"event": "ADD"
}
]
}
```
**v1.0.0 Response (standardized):**
```python
# Always returns this format
{
"results": [
{
"id": "mem_123",
"memory": "User loves pizza",
"metadata": {...},
"event": "ADD"
}
]
}
```
### search() Method
#### v0.x Signature
```python
def search(
self,
query: str,
user_id: str = None,
agent_id: str = None,
run_id: str = None,
limit: int = 100,
filters: dict = None, # Basic key-value only
output_format: str = None, # ❌ REMOVED
version: str = None # ❌ REMOVED
) -> Union[List[dict], dict]:
...
```
#### v1.0.0 Signature
```python
def search(
self,
query: str,
user_id: str = None,
agent_id: str = None,
run_id: str = None,
limit: int = 100,
filters: dict = None, # ✅ ENHANCED: Advanced operators
rerank: bool = True # ✅ NEW: Reranking support
) -> dict: # Always returns dict with "results" key
...
```
#### Enhanced Filtering
**v0.x Filters (basic):**
```python
# Simple key-value filtering only
filters = {
"category": "food",
"user_id": "alice"
}
```
**v1.0.0 Filters (enhanced):**
```python
# Advanced filtering with operators
filters = {
"AND": [
{"category": "food"},
{"score": {"gte": 0.8}},
{
"OR": [
{"priority": "high"},
{"urgent": True}
]
}
]
}
# Comparison operators
filters = {
"score": {"gt": 0.5}, # Greater than
"priority": {"gte": 5}, # Greater than or equal
"rating": {"lt": 3}, # Less than
"confidence": {"lte": 0.9}, # Less than or equal
"status": {"eq": "active"}, # Equal
"archived": {"ne": True}, # Not equal
"tags": {"in": ["work", "personal"]}, # In list
"category": {"nin": ["spam", "deleted"]} # Not in list
}
```
### get_all() Method
#### v0.x Signature
```python
def get_all(
self,
user_id: str = None,
agent_id: str = None,
run_id: str = None,
filters: dict = None,
output_format: str = None, # ❌ REMOVED
version: str = None # ❌ REMOVED
) -> Union[List[dict], dict]:
...
```
#### v1.0.0 Signature
```python
def get_all(
self,
user_id: str = None,
agent_id: str = None,
run_id: str = None,
filters: dict = None # ✅ ENHANCED: Advanced operators
) -> dict: # Always returns dict with "results" key
...
```
### update() Method
#### No Breaking Changes
```python
# Same signature in both versions
def update(
self,
memory_id: str,
data: str
) -> dict:
...
```
### delete() Method
#### No Breaking Changes
```python
# Same signature in both versions
def delete(
self,
memory_id: str
) -> dict:
...
```
### delete_all() Method
#### Breaking Change — Empty filter no longer silently deletes everything
**Before:** calling `delete_all()` with no filters silently deleted **all memories in the project**.
**After:**
- No filters → raises a validation error (prevents accidental full-project wipe).
- Concrete ID (e.g. `user_id="alice"`) → deletes memories for that entity (unchanged).
- `"*"` for a filter → deletes all memories for that entity type across the project (new).
- All four filters set to `"*"` → explicit full project wipe (new, requires opt-in on every parameter).
This change replaces the silent full-project delete (triggered by an empty or missing filter) with a validation error, and introduces `"*"` wildcards as the intentional path for bulk deletion.
```python
# v0.x — no filter silently wiped all project memories
m.delete_all() # DANGER: deleted everything
m.delete_all(user_id="alice") # deleted alice's memories
# v1.x — no filter now raises an error; use "*" for intentional bulk deletes
m.delete_all() # ERROR: at least one filter required
m.delete_all(user_id="alice") # unchanged
m.delete_all(user_id="*") # NEW — delete all users' memories
m.delete_all(user_id="*", agent_id="*", app_id="*", run_id="*") # NEW — full project wipe
```
## Platform Client (MemoryClient) Changes
### async_mode Default Changed
#### v0.x
```python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-key")
# async_mode had to be explicitly set or had different default
result = client.add("content", user_id="alice", async_mode=True)
```
#### v1.0.0
```python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-key")
# async_mode defaults to True now (better performance)
result = client.add("content", user_id="alice") # Uses async_mode=True by default
# Can still override if needed
result = client.add("content", user_id="alice", async_mode=False)
```
## Configuration Changes
### Memory Configuration
#### v0.x Config Options
```python
config = {
"vector_store": {...},
"llm": {...},
"embedder": {...},
"graph_store": {...},
"version": "v1.0", # ❌ v1.0 no longer supported
"history_db_path": "...",
"custom_instructions": "..."
}
```
#### v1.0.0 Config Options
```python
config = {
"vector_store": {...},
"llm": {...},
"embedder": {...},
"graph_store": {...},
"reranker": { # ✅ NEW: Reranker support
"provider": "cohere",
"config": {...}
},
"version": "v1.1", # ✅ v1.1+ only
"history_db_path": "...",
"custom_instructions": "...",
"custom_update_memory_prompt": "..." # ✅ NEW: Custom update prompt
}
```
### New Configuration Options
#### Reranker Configuration
```text
# Cohere reranker
"reranker": {
"provider": "cohere",
"config": {
"model": "rerank-english-v3.0",
"api_key": "your-api-key",
"top_k": 10
}
}
# Sentence Transformer reranker
"reranker": {
"provider": "sentence_transformer",
"config": {
"model": "cross-encoder/ms-marco-MiniLM-L-6-v2",
"device": "cuda"
}
}
# Hugging Face reranker
"reranker": {
"provider": "huggingface",
"config": {
"model": "BAAI/bge-reranker-base",
"device": "cuda"
}
}
# LLM-based reranker
"reranker": {
"provider": "llm_reranker",
"config": {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4",
"api_key": "your-api-key"
}
}
}
}
```
## Error Handling Changes
### New Error Types
#### v0.x Errors
```python
# Generic exceptions
try:
result = m.add("content", user_id="alice", version="v1.0")
except Exception as e:
print(f"Error: {e}")
```
#### v1.0.0 Errors
```python
# More specific error handling
try:
result = m.add("content", user_id="alice")
except ValueError as e:
if "v1.0 API format is no longer supported" in str(e):
# Handle version compatibility error
pass
elif "Invalid filter operator" in str(e):
# Handle filter syntax error
pass
except TypeError as e:
# Handle parameter errors
pass
except Exception as e:
# Handle unexpected errors
pass
```
### Validation Changes
#### Stricter Parameter Validation
**v0.x (Lenient):**
```python
# Unknown parameters might be ignored
result = m.add("content", user_id="alice", unknown_param="value")
```
**v1.0.0 (Strict):**
```python
# Unknown parameters raise TypeError
try:
result = m.add("content", user_id="alice", unknown_param="value")
except TypeError as e:
print(f"Invalid parameter: {e}")
```
## Response Schema Changes
### Memory Object Schema
#### v0.x Schema
```python
{
"id": "mem_123",
"memory": "User loves pizza",
"user_id": "alice",
"metadata": {...},
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
"score": 0.95 # In search results
}
```
#### v1.0.0 Schema (Enhanced)
```python
{
"id": "mem_123",
"memory": "User loves pizza",
"user_id": "alice",
"agent_id": "assistant", # ✅ More context
"run_id": "session_001", # ✅ More context
"metadata": {...},
"categories": ["food"], # ✅ NEW: Auto-categorization
"immutable": false, # ✅ NEW: Immutability flag
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
"score": 0.95, # In search results
"rerank_score": 0.98 # ✅ NEW: If reranking used
}
```
## Migration Code Examples
### Simple Migration
#### Before (v0.x)
```python
from mem0 import Memory
m = Memory()
# Add with deprecated parameters
result = m.add(
"I love pizza",
user_id="alice",
output_format="v1.1",
version="v1.0"
)
# Handle variable response format
if isinstance(result, list):
memories = result
else:
memories = result.get("results", [])
for memory in memories:
print(memory["memory"])
```
#### After (v1.0.0 )
```python
from mem0 import Memory
m = Memory()
# Add without deprecated parameters
result = m.add(
"I love pizza",
user_id="alice"
)
# Always dict format with "results" key
for memory in result["results"]:
print(memory["memory"])
```
### Advanced Migration
#### Before (v0.x)
```python
# Basic filtering
results = m.search(
"food preferences",
user_id="alice",
filters={"category": "food"},
output_format="v1.1"
)
```
#### After (v1.0.0 )
```python
# Enhanced filtering with reranking
results = m.search(
"food preferences",
user_id="alice",
filters={
"AND": [
{"category": "food"},
{"score": {"gte": 0.8}}
]
},
rerank=True
)
```
## Summary
| Component | v0.x | v1.0.0 | Status |
|-----------|------|-----------|---------|
| `add()` method | Variable response | Standardized response | ⚠️ Breaking |
| `search()` method | Basic filtering | Enhanced filtering + reranking | ⚠️ Breaking |
| `get_all()` method | Variable response | Standardized response | ⚠️ Breaking |
| Response format | Variable | Always `{"results": [...]}` | ⚠️ Breaking |
| Reranking | ❌ Not available | ✅ Full support | ✅ New feature |
| Advanced filtering | ❌ Basic only | ✅ Full operators | ✅ Enhancement |
| Error handling | Generic | Specific error types | ✅ Improvement |
<Info>
Use this reference to systematically update your codebase. Test each change thoroughly before deploying to production.
</Info>
+7 -20
View File
@@ -4883,7 +4883,8 @@
"items": { "items": {
"type": "object", "type": "object",
"required": [ "required": [
"memory_id" "memory_id",
"text"
], ],
"properties": { "properties": {
"memory_id": { "memory_id": {
@@ -4894,11 +4895,6 @@
"text": { "text": {
"type": "string", "type": "string",
"description": "The new text content for the memory" "description": "The new text content for the memory"
},
"metadata": {
"type": "object",
"additionalProperties": true,
"description": "Updated metadata to associate with the memory."
} }
} }
}, },
@@ -4974,27 +4970,18 @@
"schema": { "schema": {
"type": "object", "type": "object",
"properties": { "properties": {
"memories": { "memory_ids": {
"type": "array", "type": "array",
"items": { "items": {
"type": "object", "type": "string",
"properties": { "format": "uuid"
"memory_id": {
"type": "string",
"format": "uuid",
"description": "The unique identifier of the memory to delete."
}
},
"required": [
"memory_id"
]
}, },
"maxItems": 1000, "maxItems": 1000,
"description": "Array of memory objects to delete." "description": "Array of memory IDs to delete."
} }
}, },
"required": [ "required": [
"memories" "memory_ids"
] ]
} }
} }
+13 -8
View File
@@ -9,6 +9,7 @@ description: "Run richer add/search/update/delete flows on the managed platform
**Prerequisites** **Prerequisites**
- Platform workspace with API key - Platform workspace with API key
- Python 3.10+ and Node.js 18+ - Python 3.10+ and Node.js 18+
- Async memories enabled in your dashboard (Settings → Memory Options)
</Info> </Info>
<Tip> <Tip>
@@ -20,9 +21,9 @@ description: "Run richer add/search/update/delete flows on the managed platform
<Tabs> <Tabs>
<Tab title="Python"> <Tab title="Python">
<Steps> <Steps>
<Step title="Install the SDK"> <Step title="Install the SDK with async extras">
```bash ```bash
pip install mem0ai pip install "mem0ai[async]"
``` ```
</Step> </Step>
<Step title="Export your API key"> <Step title="Export your API key">
@@ -54,9 +55,9 @@ export MEM0_API_KEY="sk-platform-..."
</Step> </Step>
<Step title="Instantiate the client"> <Step title="Instantiate the client">
```typescript ```typescript
import MemoryClient from 'mem0ai'; import { Memory } from "mem0ai";
const memory = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! }); const memory = new Memory({ apiKey: process.env.MEM0_API_KEY!, async: true });
``` ```
</Step> </Step>
</Steps> </Steps>
@@ -120,8 +121,10 @@ const result = await memory.add(conversation, {
```python ```python
matches = await memory.search( matches = await memory.search(
"Any food alerts?", "Any food alerts?",
filters={"user_id": "traveler-42", "metadata.trip": "japan-2025"}, user_id="traveler-42",
filters={"metadata.trip": "japan-2025"},
rerank=True, rerank=True,
include_vectors=False,
) )
``` ```
</Step> </Step>
@@ -129,7 +132,7 @@ matches = await memory.search(
```python ```python
await memory.update( await memory.update(
memory_id=matches["results"][0]["id"], memory_id=matches["results"][0]["id"],
data="Morgan avoids shellfish and prefers boutique hotels in central Tokyo.", content="Morgan avoids shellfish and prefers boutique hotels in central Tokyo.",
) )
``` ```
</Step> </Step>
@@ -140,15 +143,17 @@ await memory.update(
<Step title="Search with metadata filters"> <Step title="Search with metadata filters">
```typescript ```typescript
const matches = await memory.search("Any food alerts?", { const matches = await memory.search("Any food alerts?", {
filters: { user_id: "traveler-42", "metadata.trip": "japan-2025" }, userId: "traveler-42",
filters: { "metadata.trip": "japan-2025" },
rerank: true, rerank: true,
includeVectors: false,
}); });
``` ```
</Step> </Step>
<Step title="Apply an update"> <Step title="Apply an update">
```typescript ```typescript
await memory.update(matches.results[0].id, { await memory.update(matches.results[0].id, {
text: "Morgan avoids shellfish and prefers boutique hotels in central Tokyo.", content: "Morgan avoids shellfish and prefers boutique hotels in central Tokyo.",
}); });
``` ```
</Step> </Step>
+14 -14
View File
@@ -26,7 +26,7 @@ Reorders results using deep semantic understanding to put the most relevant memo
results = client.search( results = client.search(
query="What are my upcoming travel plans?", query="What are my upcoming travel plans?",
rerank=True, rerank=True,
filters={"user_id": "user123"}, user_id="user123"
) )
# Before reranking: After reranking: # Before reranking: After reranking:
@@ -52,7 +52,7 @@ results = client.search(
results = client.search( results = client.search(
query="How do I like my bedroom temperature?", query="How do I like my bedroom temperature?",
rerank=True, # Get most recent preferences first rerank=True, # Get most recent preferences first
filters={"user_id": "user123"}, user_id="user123"
) )
# Finds: "Keep bedroom at 68°F", "Too cold last night at 65°F", etc. # Finds: "Keep bedroom at 68°F", "Too cold last night at 65°F", etc.
@@ -63,7 +63,7 @@ results = client.search(
# Find specific product issues with high precision # Find specific product issues with high precision
results = client.search( results = client.search(
query="Problems with premium subscription billing", query="Problems with premium subscription billing",
filters={"user_id": "customer456"}, user_id="customer456"
) )
# Returns only relevant billing problems, not general questions # Returns only relevant billing problems, not general questions
@@ -75,7 +75,7 @@ results = client.search(
results = client.search( results = client.search(
query="Patient allergies and contraindications", query="Patient allergies and contraindications",
rerank=True, # Most important info first rerank=True, # Most important info first
filters={"user_id": "patient789"}, user_id="patient789"
) )
# Ensures critical allergy info appears first # Ensures critical allergy info appears first
@@ -87,7 +87,7 @@ results = client.search(
results = client.search( results = client.search(
query="Python programming progress and difficulties", query="Python programming progress and difficulties",
rerank=True, # Recent progress first rerank=True, # Recent progress first
filters={"user_id": "student123"}, user_id="student123"
) )
# Gets comprehensive view of Python learning journey # Gets comprehensive view of Python learning journey
@@ -105,7 +105,7 @@ results = client.search(
def quick_search(query, user_id): def quick_search(query, user_id):
return client.search( return client.search(
query=query, query=query,
filters={"user_id": user_id}, user_id=user_id
) )
# Reranked search - good for most applications # Reranked search - good for most applications
@@ -113,7 +113,7 @@ def standard_search(query, user_id):
return client.search( return client.search(
query=query, query=query,
rerank=True, rerank=True,
filters={"user_id": user_id}, user_id=user_id
) )
# Reranked search - good for critical applications # Reranked search - good for critical applications
@@ -121,7 +121,7 @@ def precise_search(query, user_id):
return client.search( return client.search(
query=query, query=query,
rerank=True, rerank=True,
filters={"user_id": user_id}, user_id=user_id
) )
``` ```
@@ -129,23 +129,23 @@ def precise_search(query, user_id):
// Basic search - good for exploration // Basic search - good for exploration
function quickSearch(query, userId) { function quickSearch(query, userId) {
return client.search(query, { return client.search(query, {
filters: { user_id: userId }, user_id: userId
}); });
} }
// Reranked search - good for most applications // Reranked search - good for most applications
function standardSearch(query, userId) { function standardSearch(query, userId) {
return client.search(query, { return client.search(query, {
filters: { user_id: userId }, user_id: userId,
rerank: true, rerank: true
}); });
} }
// Reranked search - good for critical applications // Reranked search - good for critical applications
function preciseSearch(query, userId) { function preciseSearch(query, userId) {
return client.search(query, { return client.search(query, {
filters: { user_id: userId }, user_id: userId,
rerank: true, rerank: true
}); });
} }
``` ```
@@ -178,7 +178,7 @@ start_time = time.time()
results = client.search( results = client.search(
query="user preferences", query="user preferences",
rerank=True, # +150ms rerank=True, # +150ms
filters={"user_id": "user123"}, user_id="user123"
) )
latency = time.time() - start_time latency = time.time() - start_time
print(f"Search completed in {latency:.2f}s") print(f"Search completed in {latency:.2f}s")
+7 -7
View File
@@ -25,7 +25,7 @@ const messages = [
{"role": "assistant", "content": "Great! I'll remember your preference for Italian cuisine."} {"role": "assistant", "content": "Great! I'll remember your preference for Italian cuisine."}
]; ];
await client.add(messages, { userId: "user123" }); await client.add(messages, { userId: "user123", version: "v2" });
``` ```
</CodeGroup> </CodeGroup>
@@ -65,14 +65,14 @@ const messages1 = [
{"role": "user", "content": "Hi, I'm Sarah from New York"}, {"role": "user", "content": "Hi, I'm Sarah from New York"},
{"role": "assistant", "content": "Hello Sarah! Nice to meet you."} {"role": "assistant", "content": "Hello Sarah! Nice to meet you."}
]; ];
await client.add(messages1, { userId: "sarah" }); await client.add(messages1, { userId: "sarah", version: "v2" });
// Later interaction - just send new messages // Later interaction - just send new messages
const messages2 = [ const messages2 = [
{"role": "user", "content": "I'm planning a trip to Italy next month"}, {"role": "user", "content": "I'm planning a trip to Italy next month"},
{"role": "assistant", "content": "How exciting! Italy is beautiful this time of year."} {"role": "assistant", "content": "How exciting! Italy is beautiful this time of year."}
]; ];
await client.add(messages2, { userId: "sarah" }); await client.add(messages2, { userId: "sarah", version: "v2" });
// Mem0 automatically knows Sarah is from New York and can use this context // Mem0 automatically knows Sarah is from New York and can use this context
``` ```
</CodeGroup> </CodeGroup>
@@ -104,7 +104,7 @@ const messages = [
{"role": "assistant", "content": "I've noted your allergies for future reference."} {"role": "assistant", "content": "I've noted your allergies for future reference."}
]; ];
await client.add(messages, { userId: "user123" }); await client.add(messages, { userId: "user123", version: "v2" });
// This allergy info will be available in ALL future interactions // This allergy info will be available in ALL future interactions
``` ```
</CodeGroup> </CodeGroup>
@@ -143,21 +143,21 @@ const messages1 = [
{"role": "user", "content": "I want to plan a 5-day trip to Tokyo"}, {"role": "user", "content": "I want to plan a 5-day trip to Tokyo"},
{"role": "assistant", "content": "Perfect! Let's plan your Tokyo adventure."} {"role": "assistant", "content": "Perfect! Let's plan your Tokyo adventure."}
]; ];
await client.add(messages1, { userId: "user123", runId: "tokyo-trip-2024" }); await client.add(messages1, { userId: "user123", runId: "tokyo-trip-2024", version: "v2" });
// Later in the same trip planning session // Later in the same trip planning session
const messages2 = [ const messages2 = [
{"role": "user", "content": "I prefer staying near Shibuya"}, {"role": "user", "content": "I prefer staying near Shibuya"},
{"role": "assistant", "content": "Great choice! Shibuya is very convenient."} {"role": "assistant", "content": "Great choice! Shibuya is very convenient."}
]; ];
await client.add(messages2, { userId: "user123", runId: "tokyo-trip-2024" }); await client.add(messages2, { userId: "user123", runId: "tokyo-trip-2024", version: "v2" });
// Different session for work project (separate context) // Different session for work project (separate context)
const workMessages = [ const workMessages = [
{"role": "user", "content": "Let's discuss the Q4 marketing strategy"}, {"role": "user", "content": "Let's discuss the Q4 marketing strategy"},
{"role": "assistant", "content": "Sure! What are your main goals for Q4?"} {"role": "assistant", "content": "Sure! What are your main goals for Q4?"}
]; ];
await client.add(workMessages, { userId: "user123", runId: "q4-marketing" }); await client.add(workMessages, { userId: "user123", runId: "q4-marketing", version: "v2" });
``` ```
</CodeGroup> </CodeGroup>
@@ -182,7 +182,7 @@ If no criteria are defined for a project, search behaves normally based on seman
This lets you prioritize memories that align with your agent's goals and not just those that look similar to the query. This lets you prioritize memories that align with your agent's goals and not just those that look similar to the query.
<Note> <Note>
Criteria retrieval is automatically enabled when criteria are defined in your project. Use `use_criteria=False` in search to temporarily disable it for a specific query. `use_criteria` is a server-side parameter passed through to the Platform API — it is not a typed option in the SDK's `SearchMemoryOptions` interface, but the server accepts and processes it when included in the request body. Criteria retrieval is automatically enabled when criteria are defined in your project. Use `use_criteria=False` in search to temporarily disable it for a specific query.
</Note> </Note>
@@ -150,7 +150,7 @@ Handle potential errors when submitting feedback:
```python Python ```python Python
from mem0 import MemoryClient from mem0 import MemoryClient
from mem0.exceptions import MemoryNotFoundError, NetworkError from mem0.exceptions import MemoryNotFoundError, APIError
client = MemoryClient(api_key="your_api_key") client = MemoryClient(api_key="your_api_key")
@@ -163,8 +163,8 @@ try:
print("Feedback submitted successfully") print("Feedback submitted successfully")
except MemoryNotFoundError: except MemoryNotFoundError:
print("Memory not found") print("Memory not found")
except NetworkError as e: except APIError as e:
print(f"Network error: {e}") print(f"API error: {e}")
except Exception as e: except Exception as e:
print(f"Unexpected error: {e}") print(f"Unexpected error: {e}")
``` ```
+47 -58
View File
@@ -111,37 +111,32 @@ print(all_memories)
``` ```
```json Output ```json Output
{ [
"count": 3, {
"next": null, "id": "147559a8-c5f7-44d0-9418-91f53f7a89a4",
"previous": null, "memory": "suggests considering Angular because it has great enterprise support",
"results": [ "user_id": "charlie",
{ "run_id": "group_chat_1",
"id": "147559a8-c5f7-44d0-9418-91f53f7a89a4", "created_at": "2025-06-21T05:51:11.007223-07:00",
"memory": "suggests considering Angular because it has great enterprise support", "updated_at": "2025-06-21T05:51:11.626562-07:00"
"user_id": "charlie", },
"run_id": "group_chat_1", {
"created_at": "2025-06-21T05:51:11.007223-07:00", "id": "1d8b8f39-7b17-4d18-8632-ab1c64fa35b9",
"updated_at": "2025-06-21T05:51:11.626562-07:00" "memory": "prefers Vue.js for our use case",
}, "user_id": "bob",
{ "run_id": "group_chat_1",
"id": "1d8b8f39-7b17-4d18-8632-ab1c64fa35b9", "created_at": "2025-06-21T05:51:08.675301-07:00",
"memory": "prefers Vue.js for our use case", "updated_at": "2025-06-21T05:51:09.319269-07:00",
"user_id": "bob", },
"run_id": "group_chat_1", {
"created_at": "2025-06-21T05:51:08.675301-07:00", "id": "4d82478a-8d50-47e6-9324-1f65efff5829",
"updated_at": "2025-06-21T05:51:09.319269-07:00" "memory": "prefers using React for the frontend",
}, "user_id": "alice",
{ "run_id": "group_chat_1",
"id": "4d82478a-8d50-47e6-9324-1f65efff5829", "created_at": "2025-06-21T05:51:05.943223-07:00",
"memory": "prefers using React for the frontend", "updated_at": "2025-06-21T05:51:06.982539-07:00",
"user_id": "alice", }
"run_id": "group_chat_1", ]
"created_at": "2025-06-21T05:51:05.943223-07:00",
"updated_at": "2025-06-21T05:51:06.982539-07:00"
}
]
}
``` ```
</CodeGroup> </CodeGroup>
@@ -166,21 +161,17 @@ print(charlie_memories)
``` ```
```json Output ```json Output
{ [
"count": 1, {
"next": null, "id": "147559a8-c5f7-44d0-9418-91f53f7a89a4",
"previous": null, "memory": "suggests considering Angular because it has great enterprise support",
"results": [ "user_id": "charlie",
{ "run_id": "group_chat_1",
"id": "147559a8-c5f7-44d0-9418-91f53f7a89a4", "created_at": "2025-06-21T05:51:11.007223-07:00",
"memory": "suggests considering Angular because it has great enterprise support", "updated_at": "2025-06-21T05:51:11.626562-07:00",
"user_id": "charlie",
"run_id": "group_chat_1", }
"created_at": "2025-06-21T05:51:11.007223-07:00", ]
"updated_at": "2025-06-21T05:51:11.626562-07:00"
}
]
}
``` ```
</CodeGroup> </CodeGroup>
@@ -208,18 +199,16 @@ print(search_response)
``` ```
```json Output ```json Output
{ [
"results": [ {
{ "id": "147559a8-c5f7-44d0-9418-91f53f7a89a4",
"id": "147559a8-c5f7-44d0-9418-91f53f7a89a4", "memory": "suggests considering Angular because it has great enterprise support",
"memory": "suggests considering Angular because it has great enterprise support", "user_id": "charlie",
"user_id": "charlie", "run_id": "group_chat_1",
"run_id": "group_chat_1", "created_at": "2025-06-21T05:51:11.007223-07:00",
"created_at": "2025-06-21T05:51:11.007223-07:00", "updated_at": "2025-06-21T05:51:11.626562-07:00",
"updated_at": "2025-06-21T05:51:11.626562-07:00" }
} ]
]
}
``` ```
</CodeGroup> </CodeGroup>
+1
View File
@@ -251,6 +251,7 @@ You can apply various filters to customize which memories are included in the ex
- `user_id`: Filter memories by specific user - `user_id`: Filter memories by specific user
- `agent_id`: Filter memories by specific agent - `agent_id`: Filter memories by specific agent
- `run_id`: Filter memories by specific run - `run_id`: Filter memories by specific run
- `session_id`: Filter memories by specific session
- `created_at`: Filter memories by date - `created_at`: Filter memories by date
<Note> <Note>
+1 -1
View File
@@ -9,7 +9,7 @@ estimatedTime: "~2 minutes"
**Prerequisites** **Prerequisites**
- Mem0 Platform account (<a href="https://app.mem0.ai?utm_source=oss&utm_medium=platform-mem0-mcp" rel="nofollow">Sign up here</a>) - Mem0 Platform account (<a href="https://app.mem0.ai?utm_source=oss&utm_medium=platform-mem0-mcp" rel="nofollow">Sign up here</a>)
- API key (<a href="https://app.mem0.ai/settings/api-keys?utm_source=oss&utm_medium=platform-mem0-mcp" rel="nofollow">Get one from dashboard</a>) - API key (<a href="https://app.mem0.ai/settings/api-keys?utm_source=oss&utm_medium=platform-mem0-mcp" rel="nofollow">Get one from dashboard</a>)
- Node.js 18+ (for npx) - Node.js 14+ (for npx)
- An MCP-compatible client (Claude, Claude Code, Codex, Cursor, Windsurf, VS Code, OpenCode) - An MCP-compatible client (Claude, Claude Code, Codex, Cursor, Windsurf, VS Code, OpenCode)
</Info> </Info>
+1 -1
View File
@@ -15,7 +15,7 @@ Get started with Mem0 Platform's hosted API in under 5 minutes. This guide shows
- Mem0 Platform account (<a href="https://app.mem0.ai?utm_source=oss&utm_medium=platform-quickstart" rel="nofollow">Sign up here</a>) - Mem0 Platform account (<a href="https://app.mem0.ai?utm_source=oss&utm_medium=platform-quickstart" rel="nofollow">Sign up here</a>)
- API key (<a href="https://app.mem0.ai/dashboard/settings?tab=api-keys&subtab=configuration" rel="nofollow">Get one from dashboard</a>) - API key (<a href="https://app.mem0.ai/dashboard/settings?tab=api-keys&subtab=configuration" rel="nofollow">Get one from dashboard</a>)
- Python 3.10+, Node.js 18+, or cURL - Python 3.10+, Node.js 14+, or cURL
## Installation ## Installation
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "mem0ai", "name": "mem0ai",
"version": "3.0.12", "version": "3.0.11",
"description": "The Memory Layer For Your AI Apps", "description": "The Memory Layer For Your AI Apps",
"main": "./dist/index.js", "main": "./dist/index.js",
"module": "./dist/index.mjs", "module": "./dist/index.mjs",
+7 -16
View File
@@ -337,14 +337,11 @@ export class RedisDB implements VectorStore {
const id = ids[idx]; const id = ids[idx];
// Create entry with required fields // Create entry with required fields
const createdAt = payload.created_at
? new Date(payload.created_at).getTime()
: 0;
const entry: Record<string, any> = { const entry: Record<string, any> = {
memory_id: id, memory_id: id,
hash: payload.hash ?? "", hash: payload.hash,
memory: payload.data ?? "", memory: payload.data,
created_at: createdAt, created_at: new Date(payload.created_at).getTime(),
embedding: new Float32Array(vector).buffer, embedding: new Float32Array(vector).buffer,
}; };
@@ -564,18 +561,12 @@ export class RedisDB implements VectorStore {
payload: Record<string, any>, payload: Record<string, any>,
): Promise<void> { ): Promise<void> {
const snakePayload = toSnakeCase(payload); const snakePayload = toSnakeCase(payload);
const createdAt = snakePayload.created_at
? new Date(snakePayload.created_at).getTime()
: 0;
const updatedAt = snakePayload.updated_at
? new Date(snakePayload.updated_at).getTime()
: 0;
const entry: Record<string, any> = { const entry: Record<string, any> = {
memory_id: vectorId, memory_id: vectorId,
hash: snakePayload.hash ?? "", hash: snakePayload.hash,
memory: snakePayload.data ?? "", memory: snakePayload.data,
created_at: createdAt, created_at: new Date(snakePayload.created_at).getTime(),
updated_at: updatedAt, updated_at: new Date(snakePayload.updated_at).getTime(),
embedding: Buffer.from(new Float32Array(vector).buffer), embedding: Buffer.from(new Float32Array(vector).buffer),
}; };
-128
View File
@@ -1,128 +0,0 @@
import { RedisDB } from "../src/vector_stores/redis";
jest.mock("redis", () => ({
createClient: jest.fn(() => ({
connect: jest.fn(),
on: jest.fn(),
moduleList: jest.fn().mockResolvedValue([{ name: "search", ver: 20800 }]),
ft: {
create: jest.fn(),
search: jest.fn(),
info: jest.fn().mockRejectedValue(new Error("Unknown index")),
_list: jest.fn().mockResolvedValue([]),
},
hSet: jest.fn(),
hGetAll: jest.fn(),
del: jest.fn(),
exists: jest.fn(),
quit: jest.fn(),
})),
}));
function createStore(): RedisDB {
return new RedisDB({
redisUrl: "redis://localhost:6379",
collectionName: "test",
embeddingModelDims: 4,
});
}
describe("RedisDB – entity payload handling", () => {
let store: RedisDB;
let mockClient: any;
beforeAll(async () => {
store = createStore();
await store.initialize();
mockClient = (store as any).client;
});
beforeEach(() => {
jest.clearAllMocks();
});
test("insert with entity payload (no hash/created_at) does not produce NaN", async () => {
const entityPayload = {
data: "OpenAI",
entityType: "organization",
linkedMemoryIds: ["mem-1"],
userId: "test_user",
};
await store.insert([[0.1, 0.2, 0.3, 0.4]], ["entity-1"], [entityPayload]);
expect(mockClient.hSet).toHaveBeenCalledTimes(1);
const call = mockClient.hSet.mock.calls[0];
const entry = call[1];
expect(entry.memory_id).toBe("entity-1");
expect(entry.memory).toBe("OpenAI");
expect(entry.hash).toBe("");
expect(entry.created_at).toBe(0);
expect(Number.isNaN(entry.created_at)).toBe(false);
});
test("update with entity payload (no hash/created_at/updated_at) does not produce NaN", async () => {
const entityPayload = {
data: "OpenAI",
entityType: "organization",
linkedMemoryIds: ["mem-1"],
userId: "test_user",
};
await store.update("entity-1", [0.1, 0.2, 0.3, 0.4], entityPayload);
expect(mockClient.hSet).toHaveBeenCalledTimes(1);
const call = mockClient.hSet.mock.calls[0];
const entry = call[1];
expect(entry.memory_id).toBe("entity-1");
expect(entry.memory).toBe("OpenAI");
expect(entry.hash).toBe("");
expect(entry.created_at).toBe(0);
expect(entry.updated_at).toBe(0);
expect(Number.isNaN(entry.created_at)).toBe(false);
expect(Number.isNaN(entry.updated_at)).toBe(false);
});
test("update with normal payload preserves timestamps", async () => {
const normalPayload = {
data: "likes coffee",
hash: "abc123",
createdAt: "2026-06-25T10:00:00.000Z",
updatedAt: "2026-06-25T12:00:00.000Z",
userId: "test_user",
};
await store.update("mem-1", [0.1, 0.2, 0.3, 0.4], normalPayload);
const call = mockClient.hSet.mock.calls[0];
const entry = call[1];
expect(entry.hash).toBe("abc123");
expect(entry.memory).toBe("likes coffee");
expect(entry.created_at).toBeGreaterThan(0);
expect(entry.updated_at).toBeGreaterThan(0);
expect(Number.isNaN(entry.created_at)).toBe(false);
expect(Number.isNaN(entry.updated_at)).toBe(false);
});
test("insert with normal payload preserves timestamp", async () => {
const normalPayload = {
data: "likes coffee",
hash: "abc123",
createdAt: "2026-06-25T10:00:00.000Z",
userId: "test_user",
};
await store.insert([[0.1, 0.2, 0.3, 0.4]], ["mem-1"], [normalPayload]);
const call = mockClient.hSet.mock.calls[0];
const entry = call[1];
expect(entry.hash).toBe("abc123");
expect(entry.memory).toBe("likes coffee");
expect(entry.created_at).toBeGreaterThan(0);
expect(Number.isNaN(entry.created_at)).toBe(false);
});
});
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project] [project]
name = "mem0ai" name = "mem0ai"
version = "2.0.10" version = "2.0.9"
description = "Long-term memory for AI Agents" description = "Long-term memory for AI Agents"
authors = [ authors = [
{ name = "Mem0", email = "support@mem0.ai" } { name = "Mem0", email = "support@mem0.ai" }