Compare commits

...

88 Commits

Author SHA1 Message Date
kartik-mem0 9897951783 docs: update README benchmarks to current temporal-reasoning results
Refresh the README benchmark table and Research Highlights to match the
current numbers on the Memory Evaluation page (docs/core-concepts/
memory-evaluation.mdx), updated in #6056.

- LoCoMo: 91.6 -> 92.5
- LongMemEval: 94.8 -> 94.4 (94.8 was not sourced by any docs page)
- Assistant memory recall highlight: +53.6 delta -> 98.2 absolute
- State the top_200 retrieval budget and the managed-platform caveat

BEAM (1M / 10M), token counts, and latency are unchanged.
2026-07-09 15:50:16 +05:30
Rod Boev b26469e006 feat(vector-stores): add Weaviate adapter to TypeScript OSS SDK (#5800)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-08 21:12:01 +05:30
Bartok e72ae96ad4 feat(ts-sdk): add Milvus vector store provider (closes #5774) (#5889)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-08 20:25:06 +05:30
Bartok fbdbab805d feat(ts-sdk): add HuggingFace embedding provider (#6027)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-08 19:43:53 +05:30
sahithreddy05 22f70d50e1 feat(ts-sdk): add Chroma vector store provider (#6145)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-08 19:14:05 +05:30
Saumya Kathuria f89edb45dc feat(ts-sdk): add Sarvam LLM provider to OSS SDK (#6130)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-08 19:03:38 +05:30
Harsh Vardhan Gupta 846f25bd39 fix(mem0-ts): patch fast-xml-parser and tar transitive CVEs (#6160) 2026-07-08 18:25:59 +05:30
张思孝 9b04509433 feat(ts-sdk): add Together LLM provider (#6049)
Co-authored-by: zhangsixiao <zhangsixiao@bytedance.com>
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-07 21:08:26 +05:30
Diveyam Mishra 803ff13bb8 feat(mem0-ts): add MongoDB vector store provider to OSS TypeScript SDK (#5793)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-07 17:13:51 +05:30
404 Ameyy 94e46526bc feat(ts-sdk): add Elasticsearch vector store provider (#5866)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-07 17:10:25 +05:30
Parteeksachdeva d122479687 security: fix SQL and Cypher injection vulnerabilities in PGVector, Azure MySQL, and Neptune (#4878)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-07 16:16:36 +05:30
VectorPeak cc52f0e367 fix: encode dynamic URL path segments (#5963)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-07 16:11:54 +05:30
AxelRay 87276ef968 feat(ts-sdk): add OpenSearch vector store (#5810)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-07 15:40:20 +05:30
Kartik 002fe46ab3 feat(ts-sdk): add xAI (Grok) LLM provider to OSS SDK (#6115) 2026-07-07 11:29:56 +05:30
AxelRay 9d36b2c94d feat(ts-sdk): add Upstash Vector vector store (#5811)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-06 23:41:05 +05:30
Rod Boev c944bed460 feat(ts-sdk): add Azure MySQL vector store (#5827)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-06 23:17:43 +05:30
Rod Boev 2cc060fd76 feat(vector-stores): add Turbopuffer provider to TypeScript OSS SDK (#5801)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-06 22:57:00 +05:30
Div 2bc2f763d9 feat: add Google Vertex AI Vector Search support to vector store factory (#5791)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
Co-authored-by: divyansh-1009 <divyansh-1009@users.noreply.github.com>
2026-07-06 22:54:24 +05:30
Rod Boev 7fb3feb5cd feat(vector-stores): add Cassandra provider to TypeScript OSS SDK (#5823)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-06 21:57:32 +05:30
Rod Boev fec7cdf118 feat(ts-sdk): add FastEmbed embedding provider (#5862)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-06 21:56:11 +05:30
Rod Boev 03b41ab00f feat(vector-stores): add Pinecone provider to TypeScript SDK (#5802)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-06 21:39:10 +05:30
Jaco-Ren 4c974c8fa8 Add Together embedder to TS SDK (#5989)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-06 20:24:14 +05:30
Barry b0bee551cb feat(ts-sdk): add vLLM provider (#5805)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-06 20:23:43 +05:30
Kartik b8141aaea8 docs: remove duplicate multimodal page and normalize em/en-dashes (#6112) 2026-07-06 20:22:20 +05:30
Yash a7ecf781cd Feat/valkey vector store (#5826)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-06 20:20:59 +05:30
Rod Boev 6dc4606dcf feat(vector-stores): add S3 Vectors provider to TypeScript OSS SDK (#5822)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-07-06 20:08:13 +05:30
Harsh Vardhan Gupta 580d390e4d fix(transformers): upgrade to >=5.3.0 (GHSA-29pf-2h5f-8g72 / CVE-2026-4372) (#6110) 2026-07-06 17:56:39 +05:30
Kartik 2bd3ff1eff fix(vector-stores): prevent unhandled promise rejection in Supabase & Redis constructors (#6111) 2026-07-06 14:57:30 +05:30
Agam Pandey cd79fa8914 docs: show current benchmark numbers on memory evaluation page (#6056)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 22:38:33 +05:30
Hrushikesh Yadav 59484f066f fix(elasticsearch): validate filter keys and values to prevent term injection (#5980)
Signed-off-by: Hrushikesh Yadav <yadavhrushikesh65@gmail.com>
2026-07-02 18:35:02 +05:30
Kushagra Gupta 8a5c0729e5 fix(server): do not forward empty-string entity ids as filters (#5992)
Co-authored-by: Kartik <kartik.labhshetwar@mem0.ai>
2026-07-02 18:33:16 +05:30
Trupti Agrawal 3b9aed866a docs: fix typos and grammar errors across docs (#6033) 2026-07-01 23:25:12 +05:30
Kartik fb2593e10d docs: add subtle GitHub star nudges at OSS win-moments (#5928) 2026-07-01 23:13:51 +05:30
Kartik 207f65deda docs: navigation (#5900) 2026-07-01 22:48:23 +05:30
Kartik f2532f072f chore: update changelog, bump SDK versions to Python 2.0.11 and TypeScript 3.0.13 (#6031) 2026-07-01 22:17:41 +05:30
Kartik 41c8f00851 chore(integrations): plugin updates, pi-agent auto-recall, and version bumps (#6011) 2026-07-01 20:57:32 +05:30
Hrushikesh Yadav a36a392cd3 fix(opensearch): validate filter values to prevent term query injection (#5986) 2026-07-01 20:47:45 +05:30
Bartok 152d1e66f7 fix(embeddings): guard embed_batch count mismatch in OpenAI and Azure OpenAI (#5966) 2026-07-01 18:53:28 +05:30
Hrushikesh Yadav bc05fd9623 fix(neptune): escape filter values in openCypher queries to prevent injection (#5982)
Signed-off-by: Hrushikesh Yadav <yadavhrushikesh65@gmail.com>
2026-07-01 18:48:04 +05:30
Bartok ad7e09851c fix(memory): re-raise LLM extraction failures instead of returning [] (salvage of #5178) (#5878) 2026-07-01 18:36:19 +05:30
Kartik c325bd3b8e docs(changelog): consolidate per-package changelogs into the SDK changelog page (#6007) 2026-06-30 14:09:41 +05:30
rudrajmehta-mem0 2add7fd57d docs(graph-memory): gate Graph view visualization to Pro/Enterprise (#6000)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 18:12:50 -07:00
Kartik b2ff3aeda5 Clean up release highlights copy and removing emdash from the docs (#5984) 2026-06-29 21:27:53 +05:30
Kartik 754034abbc Revert "fix(memory): accept llm kwarg in sync Memory.add()/_create_procedural_memory (#5911)" (#5990) 2026-06-29 21:27:16 +05:30
ly-wang19 bedf862d64 fix(memory): accept llm kwarg in sync Memory.add()/_create_procedural_memory (#5911) (#5953)
Co-authored-by: ly-wang19 <ly-wang19@users.noreply.github.com>
2026-06-29 20:43:35 +05:30
Terrasse cc59d122db docs: remove instructions for unavailable Cursor marketplace plugin (#5971) 2026-06-29 20:35:07 +05:30
Hrushikesh Yadav 3619fd77ae fix(azure-ai-search): validate filter value types and escape quotes in OData (#5983) 2026-06-29 20:31:26 +05:30
Hrushikesh Yadav 2dcb3542f8 fix(databricks): validate catalog/schema/table identifiers to prevent SQL injection (#5988) 2026-06-29 20:30:27 +05:30
Abhay Singh 31cec11a79 fix(cli-node): keep every result in entity delete, not just the last (#5970) 2026-06-29 15:26:57 +05:30
冯基魁 4c0ea22d31 fix(ts): handle empty Google chat candidates (#5817) 2026-06-29 15:08:44 +05:30
Muhammad Furqan f59320df65 fix(faiss): normalize vectors for cosine distance strategy (#5960) 2026-06-29 15:03:55 +05:30
Abhay Singh ad57cbb8d6 fix(cli): keep every result in entity delete, not just the last (#5936) 2026-06-29 14:58:16 +05:30
Barry ee0c38e081 fix(cli): handle null memory fields in output formatters (#5957) 2026-06-29 14:53:22 +05:30
Barry d5b64ccec9 fix(cli): reject invalid int config values without traceback (#5956) 2026-06-29 14:47:32 +05:30
Kartik 8d6b7c1d67 chore: update changelog, bump SDK versions to Python 2.0.10 and TypeScript 3.0.12 (#5927) 2026-06-27 22:33:14 +05:30
Kartik b44ce4dcc3 docs(cookbooks): fix v3 filters, response shapes & dead snippet in cookbooks (#5841) 2026-06-27 18:55:08 +05:30
Kartik e9c930c430 docs(components): fix LLM & embedder model IDs and TS support lists (#5838) 2026-06-27 18:42:02 +05:30
Kartik 4b39d01ccb docs(platform): align Platform docs with v3 SDK behavior (#5849) 2026-06-27 18:41:47 +05:30
Kartik 49061718bd docs(cookbooks): fix v3 filters & update() in companions/essentials (#5844) 2026-06-27 18:41:35 +05:30
Kartik 7e7682a06d docs(vectordbs): correct vector store config defaults & imports (#5843) 2026-06-27 12:40:16 +05:30
Kartik f38608fb50 docs(api-reference): align API docs & openapi.json with v3 spec (#5848) 2026-06-26 22:07:53 +05:30
Kartik fb11cdffbb docs(changelog): fix score_details fields, graph-store note & dead link (#5845) 2026-06-26 22:05:14 +05:30
Kartik ee600705c2 docs: remove inaccurate api-changes migration page (#5857) 2026-06-26 22:03:53 +05:30
Hrushikesh Yadav f4ccef5157 fix(ts/redis): use nullish coalescing for hash/timestamps in insert/update (#5860)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-06-26 19:01:58 +05:30
mintlify[bot] 08da741a31 SEO & metadata audit: expand short API reference descriptions (#5897)
Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com>
2026-06-26 16:34:52 +05:30
Kartik e4efdd2e29 docs: add SECURITY.md and improve contribution guidelines (#5855) 2026-06-26 16:02:53 +05:30
Kartik a87c9ce367 docs: fix mangled Python formatting in pgvector & Neon vector store guides (#5853) 2026-06-26 16:00:58 +05:30
Kartik d258b638ef docs: document FastEmbed embedder + missing org/project API endpoints (#5852) 2026-06-26 16:00:12 +05:30
Harsh Vardhan Gupta bbbfcfea07 fix(deps): bump undici to >=6.27.0 (CVE-2026-12151) (#5861) 2026-06-26 15:32:09 +05:30
Kartik fbef369b91 docs(open-source): fix OSS feature docs for v3 SDK (#5847) 2026-06-26 14:14:33 +05:30
Kartik a7ed68e697 docs(integrations): fix retired model IDs, v3 response shapes & vercel deps (#5842) 2026-06-26 13:59:33 +05:30
Kartik 8a92cf0306 docs(integrations): sync agent-plugin hook tables with actual hooks.json (#5839) 2026-06-26 13:58:28 +05:30
soumil-rathi 0fbbb2f525 feat(memory): expose expiration controls in client docs (#5874)
Co-authored-by: Soumil Rathi <soumilrathi@gmail.com>
2026-06-25 17:14:33 -07:00
Barry Collins 818c2981b7 feat(ts-sdk): add MiniMax LLM provider (#5858)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-06-25 17:01:50 +05:30
Rod Boev 1f66aadfa3 fix(openclaw): normalize Windows skill-loader URLs before fileURLToPath (#5679) 2026-06-25 16:36:11 +05:30
Hrushikesh Yadav b91c745fbc fix: apply remove_code_blocks() to LangChain path in async _create_procedural_memory (#5711) 2026-06-25 16:34:28 +05:30
Muhammad Furqan af70668308 fix(reranker): score HuggingFace reranker with sigmoid, not min-max (#5715) 2026-06-25 16:18:02 +05:30
rafid001 890473f891 fix(core): validate and trim entity IDs in delete_all() (#5735)
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Kartik <kartik.labhshetwar@mem0.ai>
2026-06-25 16:14:30 +05:30
Hrushikesh Yadav d2ff83cf72 fix(redis): use .get() for hash/created_at in insert() to handle entity payloads (#5709) 2026-06-25 16:13:44 +05:30
Rod Boev 0e02effaf7 fix(notices): derive scale counts for Redis and search backends (#5687) 2026-06-25 16:04:44 +05:30
Rod Boev 9269a0ad6e feat(ts-sdk): add LiteLLM as LLM provider (#5830)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
2026-06-25 15:52:46 +05:30
Hrushikesh Yadav 3d06006f36 fix(valkey): escape special chars in FT.SEARCH tag filter values (#5750) 2026-06-25 15:20:13 +05:30
Rod Boev 6bb1d328ad fix(mem0-ts): support pgvector connection strings and ssl (#5789) 2026-06-25 11:57:37 +05:30
Taranjeet Singh ac296f7534 docs: make example code fences copy-safe (#5833) 2026-06-24 22:19:40 -07:00
Kartik ac8f862ff7 fix(mem0-plugin): store files_touched as a list to stop double JSON-encoding (#5806) 2026-06-25 09:06:11 +05:30
soumil-rathi b33fa5427c fix(memory): align entity extraction precision (#5829)
Making the entity extraction function cleaner


Co-authored-by: Soumil Rathi <soumilrathi@gmail.com>
2026-06-24 15:48:37 -07:00
Ashutosh Kasudhan 5d573dd2ae docs: added typescript support to deepseek provider (#5723) 2026-06-24 20:55:14 +05:30
Kartik 98dbf90864 chore: update changelog, bump SDK versions to Python 2.0.8 and TypeScript 3.0.10 (#5825) 2026-06-24 20:21:06 +05:30
435 changed files with 24225 additions and 5477 deletions
+1 -1
View File
@@ -12,7 +12,7 @@
"name": "mem0",
"source": "./integrations/mem0-plugin",
"description": "Mem0 memory layer for AI applications. Add persistent memory, personalization, and semantic search to Claude workflows.",
"version": "0.2.10"
"version": "0.2.12"
}
]
}
+1 -1
View File
@@ -12,7 +12,7 @@
"name": "mem0",
"source": "./integrations/mem0-plugin",
"description": "Mem0 memory layer for AI applications. Add persistent memory, personalization, and semantic search.",
"version": "0.2.10"
"version": "0.2.12"
}
]
}
+134 -47
View File
@@ -1,72 +1,157 @@
# Contributing to mem0
# Contributing to Mem0
Let us make contribution easy, collaborative and fun.
First off, thank you for taking the time to contribute! 🎉 Mem0 is a
community-driven project and we welcome contributions of all kinds — bug fixes,
new features, documentation, examples, and integrations.
## Submit your Contribution through PR
Mem0 is a polyglot monorepo, and this guide covers contributing to both the
**Python SDK** and the **TypeScript SDK** (and the rest of the repository).
To make a contribution, follow these steps:
## Before You Start
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
### 1. Open an Issue First
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).
**Always open an issue before opening a pull request.** This lets us discuss the
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.
### 📦 Development Environment
Every pull request must link to an issue using `Closes #<issue-number>`.
We use `hatch` for managing development environments. To set up:
### 2. Sign the Contributor License Agreement (CLA)
**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
# Activate environment for specific Python version:
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
# Activate a dev environment (3.9 / 3.10 / 3.11 / 3.12)
hatch shell dev_py_3_11
# The environment will automatically install all dev dependencies
# Run tests within the activated shell:
make test
```
### 📌 Pre-commit
To ensure our standards, make sure to install pre-commit before starting to contribute.
```bash
# Install pre-commit hooks (runs ruff + isort on commit)
pre-commit install
# 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
```
### 🧪 Testing
- **Linter / formatter:** Ruff (line length **120**)
- **Import sorting:** isort (`profile = "black"`)
- **Tests:** pytest (in `tests/`)
We use `pytest` to test our code across multiple Python versions. You can run tests using:
See the full [Development guide](https://docs.mem0.ai/contributing/development) for
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
# Run tests with default Python version
make test
cd mem0-ts
pnpm install
# 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
# When using hatch shells, run tests with:
make test # After activating a shell with hatch shell test_XX
pnpm run build # tsup (CJS + ESM)
pnpm run test # jest (all tests)
pnpm run test:unit # unit tests with coverage
```
Make sure that all tests pass across all supported Python versions before submitting a pull request.
- **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()`.
We look forward to your pull requests and can't wait to see your contributions!
## Good Contribution Practices
### 🚀 Releasing
- **Keep PRs small and focused.** One logical change per PR is easier to review and
merge.
- **Follow existing patterns.** Match the style, structure, and conventions of the
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`.
All packages are published automatically via GitHub Actions when a GitHub Release is created with the correct tag prefix.
## Pull Request Checklist
#### Tag Prefixes
Before requesting review, make sure:
- [ ] An issue exists and is linked with `Closes #<number>`
- [ ] 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
**Do not report security vulnerabilities through public issues or pull requests.**
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.
### Tag Prefixes
| Package | Registry | Tag Prefix | Example |
|---------|----------|------------|---------|
@@ -77,15 +162,17 @@ All packages are published automatically via GitHub Actions when a GitHub Releas
| `@mem0/vercel-ai-provider` | npm | `vercel-ai-v*` | `vercel-ai-v2.0.6` |
| `@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)
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)
#### Publishing Details
### Publishing Details
- **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
- 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
We look forward to your pull requests and can't wait to see your contributions!
+5 -5
View File
@@ -46,12 +46,12 @@
| Benchmark | Old | New | Tokens | Latency p50 |
| --- | --- | --- | --- | --- |
| **LoCoMo** | 71.4 | **91.6** | 7.0K | 0.88s |
| **LongMemEval** | 67.8 | **94.8** | 6.8K | 1.09s |
| **LoCoMo** | 71.4 | **92.5** | 7.0K | 0.88s |
| **LongMemEval** | 67.8 | **94.4** | 6.8K | 1.09s |
| **BEAM (1M)** | — | **64.1** | 6.7K | 1.00s |
| **BEAM (10M)** | — | **48.6** | 6.9K | 1.05s |
All benchmarks run on the same production-representative model stack. Single-pass retrieval (one call, no agentic loops).
All benchmarks run on the same production-representative model stack. Single-pass retrieval (one call, no agentic loops) at a top_200 retrieval budget. Scores reflect Mem0's managed platform, which includes proprietary optimizations not available in the open-source SDK; open-source users should expect directionally similar gains but not identical numbers.
**What changed:**
- **Single-pass ADD-only extraction** -- one LLM call, no UPDATE/DELETE. Memories accumulate; nothing is overwritten.
@@ -63,8 +63,8 @@ All benchmarks run on the same production-representative model stack. Single-pas
See the [migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for upgrade instructions. The [evaluation framework](https://github.com/mem0ai/memory-benchmarks) is open-sourced so anyone can reproduce the numbers.
## Research Highlights
- **91.6 on LoCoMo** -- +20 points over the previous algorithm
- **94.8 on LongMemEval** -- +27 points, with +53.6 on assistant memory recall
- **92.5 on LoCoMo** -- +21 points over the previous algorithm
- **94.4 on LongMemEval** -- +27 points, with 98.2 on assistant memory recall
- **64.1 on BEAM (1M)** -- production-scale memory evaluation at 1M tokens
- [Read the full paper](https://mem0.ai/research)
+48
View File
@@ -0,0 +1,48 @@
# 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.
-60
View File
@@ -1,60 +0,0 @@
# Changelog
All notable changes to `@mem0/cli` are documented here.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.2.9] — 2026-06-19
### Security
- Telemetry no longer passes the Mem0 API key to its child process via
command-line arguments. The context is now sent over stdin, so the key is no
longer visible in the process list (`ps`, `/proc/<pid>/cmdline`, Activity
Monitor). Fixes #4862.
## [0.2.8] — 2026-06-01
### Security
- Pinned transitive dependencies via pnpm overrides to remediate high-severity CVEs:
- `jws` → 4.0.1 (CVE-2025-65945)
- `langsmith` → ^0.6.0 (CVE-2026-45134)
- `tar-fs` → ^2.1.4 (CVE-2025-48387, CVE-2025-59343)
- `picomatch` → ^2.3.2 (CVE-2026-33671)
- `minimatch` → ^3.1.3 / ^5.1.8 / ^9.0.7 (CVE-2026-27903, CVE-2026-27904, CVE-2026-26996)
- `path-to-regexp` → ^8.4.0 (CVE-2026-4926)
- `rollup` → ^4.59.0 (CVE-2026-27606)
- `glob` → ^10.5.0 (CVE-2025-64756)
- `@modelcontextprotocol/sdk` → ^1.25.4 (CVE-2025-66414, CVE-2026-0621)
## [0.2.7] — 2026-05-20
### Added
- `mem0 whoami` — print the active agent's `default_user_id` (the AGENTRUSH
leaderboard identifier). Reads from local config, no network call.
- `mem0 agent-rush <add | search>` — subcommand group that wraps the new
`/v1/agent-rush/` platform endpoints for the 7-day AGENTRUSH game. Project
routing is implicit (resolved server-side); no flags exposed. Pretty-prints
platform error codes into actionable hints (e.g. `agentrush_search_first`
→ "Run 3 'mem0 agent-rush search' commands before adding.").
- PII safety prompt on first `mem0 agent-rush add`. Interactive runs require
explicit `y` to acknowledge that AGENTRUSH memories are public; the
acknowledgement is persisted in `~/.mem0/config.json` under
`agent_rush.acknowledged_at` so the prompt only appears once per machine.
Non-interactive (agent) invocations surface the warning to stderr without
blocking.
- New config schema field: `agent_rush.acknowledged_at` (ISO timestamp,
empty until first interactive acknowledgement).
### Changed
- HTTP requests from the new agent-rush commands send `X-Mem0-Mode: agent-rush`
in addition to the existing source headers, so platform telemetry can split
game traffic from regular CLI usage.
## [0.2.6] and earlier
Unlogged historical releases. See git history under `cli/node/`.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@mem0/cli",
"version": "0.2.9",
"version": "0.2.10",
"description": "The official CLI for mem0 — the memory layer for AI agents",
"type": "module",
"bin": {
+36 -18
View File
@@ -17,6 +17,10 @@ import {
type SearchOptions,
} from "./base.js";
function encodePathSegment(value: unknown): string {
return encodeURIComponent(String(value));
}
export class PlatformBackend implements Backend {
private baseUrl: string;
private headers: Record<string, string>;
@@ -218,9 +222,13 @@ export class PlatformBackend implements Backend {
}
async get(memoryId: string): Promise<Record<string, unknown>> {
return (await this._request("GET", `/v1/memories/${memoryId}/`, {
params: { source: "CLI" },
})) as Record<string, unknown>;
return (await this._request(
"GET",
`/v1/memories/${encodePathSegment(memoryId)}/`,
{
params: { source: "CLI" },
},
)) as Record<string, unknown>;
}
async listMemories(
@@ -277,9 +285,13 @@ export class PlatformBackend implements Backend {
if (content) payload.text = content;
if (metadata) payload.metadata = metadata;
payload.source = "CLI";
return (await this._request("PUT", `/v1/memories/${memoryId}/`, {
json: payload,
})) as Record<string, unknown>;
return (await this._request(
"PUT",
`/v1/memories/${encodePathSegment(memoryId)}/`,
{
json: payload,
},
)) as Record<string, unknown>;
}
async delete(
@@ -297,9 +309,13 @@ export class PlatformBackend implements Backend {
})) as Record<string, unknown>;
}
if (memoryId) {
return (await this._request("DELETE", `/v1/memories/${memoryId}/`, {
params: { source: "CLI" },
})) as Record<string, unknown>;
return (await this._request(
"DELETE",
`/v1/memories/${encodePathSegment(memoryId)}/`,
{
params: { source: "CLI" },
},
)) as Record<string, unknown>;
}
throw new Error("Either memoryId or --all is required");
}
@@ -316,16 +332,18 @@ export class PlatformBackend implements Backend {
if (entities.length === 0) {
throw new Error("At least one entity ID is required for deleteEntities.");
}
// Delete each provided entity via the v2 path-based endpoint
let result: Record<string, unknown> = {};
// Delete each provided entity via the v2 path-based endpoint. Key each
// response by entity type so a multi-entity delete (e.g. --user-id and
// --agent-id together) doesn't discard everything but the last result.
const results: Record<string, unknown> = {};
for (const [entityType, entityId] of entities) {
result = (await this._request(
results[entityType] = (await this._request(
"DELETE",
`/v2/entities/${entityType}/${entityId}/`,
`/v2/entities/${encodePathSegment(entityType)}/${encodePathSegment(entityId)}/`,
{ params: { source: "CLI" } },
)) as Record<string, unknown>;
}
return result;
return results;
}
async ping(): Promise<Record<string, unknown>> {
@@ -384,9 +402,9 @@ export class PlatformBackend implements Backend {
}
async getEvent(eventId: string): Promise<Record<string, unknown>> {
return (await this._request("GET", `/v1/event/${eventId}/`)) as Record<
string,
unknown
>;
return (await this._request(
"GET",
`/v1/event/${encodePathSegment(eventId)}/`,
)) as Record<string, unknown>;
}
}
+100
View File
@@ -0,0 +1,100 @@
/**
* Tests for the Platform backend (mem0 Platform API client).
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import { PlatformBackend } from "../src/backend/platform.js";
import { createDefaultConfig } from "../src/config.js";
function makeBackend(): PlatformBackend {
// apiKey/baseUrl only build request headers; every test spies on _request,
// so no real network calls are made.
return new PlatformBackend(createDefaultConfig().platform);
}
function mockFetch() {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
status: 200,
headers: { get: vi.fn().mockReturnValue(null) },
json: vi.fn().mockResolvedValue({ message: "ok" }),
});
vi.stubGlobal("fetch", fetchMock);
return fetchMock;
}
beforeEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
describe("deleteEntities", () => {
it("returns all results keyed by entity type for a multi-entity delete", async () => {
const backend = makeBackend();
const responses: Record<string, unknown> = {
"/v2/entities/user/alice/": { message: "user deleted" },
"/v2/entities/agent/bob/": { message: "agent deleted" },
};
const spy = vi
// biome-ignore lint/suspicious/noExplicitAny: spying on a private method
.spyOn(backend as any, "_request")
.mockImplementation(async (_method: string, path: string) => responses[path]);
const result = await backend.deleteEntities({ userId: "alice", agentId: "bob" });
// Regression: previously only the last entity's response survived.
expect(result).toEqual({
user: { message: "user deleted" },
agent: { message: "agent deleted" },
});
expect(spy).toHaveBeenCalledTimes(2);
});
it("keys a single-entity delete by its type", async () => {
const backend = makeBackend();
// biome-ignore lint/suspicious/noExplicitAny: spying on a private method
vi.spyOn(backend as any, "_request").mockResolvedValue({ message: "user deleted" });
const result = await backend.deleteEntities({ userId: "alice" });
expect(result).toEqual({ user: { message: "user deleted" } });
});
it("throws when no entity id is provided", async () => {
const backend = makeBackend();
await expect(backend.deleteEntities({})).rejects.toThrow(
"At least one entity ID is required",
);
});
});
describe("PlatformBackend path encoding", () => {
it("encodes memory IDs before interpolating them into paths", async () => {
const fetchMock = mockFetch();
const backend = makeBackend();
await backend.get("mem/a?b#c");
await backend.update("mem/a?b#c", "updated");
await backend.delete("mem/a?b#c");
const urls = fetchMock.mock.calls.map((call) => call[0]);
expect(urls).toEqual([
"https://api.mem0.ai/v1/memories/mem%2Fa%3Fb%23c/?source=CLI",
"https://api.mem0.ai/v1/memories/mem%2Fa%3Fb%23c/",
"https://api.mem0.ai/v1/memories/mem%2Fa%3Fb%23c/?source=CLI",
]);
});
it("encodes entity and event IDs before interpolating them into paths", async () => {
const fetchMock = mockFetch();
const backend = makeBackend();
await backend.deleteEntities({ userId: "org/team?active#frag" });
await backend.getEvent("evt/a?b#c");
const urls = fetchMock.mock.calls.map((call) => call[0]);
expect(urls).toEqual([
"https://api.mem0.ai/v2/entities/user/org%2Fteam%3Factive%23frag/?source=CLI",
"https://api.mem0.ai/v1/event/evt%2Fa%3Fb%23c/",
]);
});
});
-49
View File
@@ -1,49 +0,0 @@
# Changelog
All notable changes to `mem0-cli` (Python) are documented here.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.2.8] — 2026-06-19
### Security
- Telemetry no longer passes the Mem0 API key to its child process via
command-line arguments. The context is now sent over stdin, so the key is no
longer visible in the process list (`ps`, `/proc/<pid>/cmdline`, Activity
Monitor). Fixes #4862.
### Fixed
- `__version__` now matches the packaged version (was stale at 0.2.4).
## [0.2.7] — 2026-05-20
### Added
- `mem0 whoami` — print the active agent's `default_user_id` (the AGENTRUSH
leaderboard identifier). Reads from local config, no network call.
- `mem0 agent-rush <add | search>` — subcommand group that wraps the new
`/v1/agent-rush/` platform endpoints for the 7-day AGENTRUSH game. Project
routing is implicit (resolved server-side); no flags exposed. Pretty-prints
platform error codes into actionable hints (e.g. `agentrush_search_first`
→ "Run 3 'mem0 agent-rush search' commands before adding.").
- PII safety prompt on first `mem0 agent-rush add`. Interactive runs require
explicit `y` to acknowledge that AGENTRUSH memories are public; the
acknowledgement is persisted in `~/.mem0/config.json` under
`agent_rush.acknowledged_at` so the prompt only appears once per machine.
Non-interactive (agent) invocations surface the warning to stderr without
blocking.
- New config schema field: `agent_rush.acknowledged_at` (ISO timestamp,
empty until first interactive acknowledgement).
### Changed
- HTTP requests from the new agent-rush commands send `X-Mem0-Mode: agent-rush`
in addition to the existing source headers, so platform telemetry can split
game traffic from regular CLI usage.
## [0.2.6] and earlier
Unlogged historical releases. See git history under `cli/python/`.
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "mem0-cli"
version = "0.2.8"
version = "0.2.9"
description = "The official CLI for mem0 — the memory layer for AI agents"
readme = "README.md"
license = "Apache-2.0"
+1 -1
View File
@@ -1,3 +1,3 @@
"""mem0 CLI — the command-line interface for the mem0 memory layer."""
__version__ = "0.2.8"
__version__ = "0.2.9"
+30 -9
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
from typing import Any
from urllib.parse import quote
import httpx
@@ -11,6 +12,10 @@ from mem0_cli.backend.base import Backend
from mem0_cli.config import PlatformConfig
def _encode_path_segment(value: Any) -> str:
return quote(str(value), safe="")
class PlatformBackend(Backend):
"""Backend that talks to the mem0 Platform API."""
@@ -196,7 +201,11 @@ class PlatformBackend(Backend):
)
def get(self, memory_id: str) -> dict:
return self._request("GET", f"/v1/memories/{memory_id}/", params={"source": "CLI"})
return self._request(
"GET",
f"/v1/memories/{_encode_path_segment(memory_id)}/",
params={"source": "CLI"},
)
def list_memories(
self,
@@ -250,7 +259,11 @@ class PlatformBackend(Backend):
if metadata:
payload["metadata"] = metadata
payload["source"] = "CLI"
return self._request("PUT", f"/v1/memories/{memory_id}/", json=payload)
return self._request(
"PUT",
f"/v1/memories/{_encode_path_segment(memory_id)}/",
json=payload,
)
def delete(
self,
@@ -274,7 +287,11 @@ class PlatformBackend(Backend):
params["run_id"] = run_id
return self._request("DELETE", "/v1/memories/", params=params)
elif memory_id:
return self._request("DELETE", f"/v1/memories/{memory_id}/", params={"source": "CLI"})
return self._request(
"DELETE",
f"/v1/memories/{_encode_path_segment(memory_id)}/",
params={"source": "CLI"},
)
else:
raise ValueError("Either memory_id or --all is required")
@@ -296,13 +313,17 @@ class PlatformBackend(Backend):
entities = {t: v for t, v in type_map.items() if v}
if not entities:
raise ValueError("At least one entity ID is required for delete_entities.")
# Delete each provided entity via the v2 path-based endpoint
result: dict = {}
# Delete each provided entity via the v2 path-based endpoint. Key each
# response by entity type so a multi-entity delete (e.g. --user-id and
# --agent-id together) doesn't discard everything but the last result.
results: dict = {}
for entity_type, entity_id in entities.items():
result = self._request(
"DELETE", f"/v2/entities/{entity_type}/{entity_id}/", params={"source": "CLI"}
results[entity_type] = self._request(
"DELETE",
f"/v2/entities/{_encode_path_segment(entity_type)}/{_encode_path_segment(entity_id)}/",
params={"source": "CLI"},
)
return result
return results
def ping(self, timeout: float | None = None) -> dict:
"""Call the ping endpoint and return the raw response.
@@ -346,7 +367,7 @@ class PlatformBackend(Backend):
return result if isinstance(result, list) else result.get("results", [])
def get_event(self, event_id: str) -> dict:
return self._request("GET", f"/v1/event/{event_id}/")
return self._request("GET", f"/v1/event/{_encode_path_segment(event_id)}/")
class AuthError(Exception):
+4 -1
View File
@@ -235,7 +235,10 @@ def set_nested_value(config: Mem0Config, dotted_key: str, value: str) -> bool:
if isinstance(current, bool):
value = value.lower() in ("true", "1", "yes") # type: ignore[assignment]
elif isinstance(current, int):
value = int(value) # type: ignore[assignment]
try:
value = int(value) # type: ignore[assignment]
except ValueError:
return False
setattr(obj, final_key, value)
return True
+6 -6
View File
@@ -20,8 +20,8 @@ def format_memories_text(console: Console, memories: list[dict], title: str = "m
console.print(f"\n[{BRAND_COLOR}]Found {count} {title}:[/]\n")
for i, mem in enumerate(memories, 1):
memory_text = mem.get("memory", mem.get("text", ""))
mem_id = mem.get("id", "")[:8]
memory_text = mem.get("memory") or mem.get("text") or ""
mem_id = (mem.get("id") or "")[:8]
score = mem.get("score")
created = _format_date(mem.get("created_at"))
category = mem.get("categories", [None])
@@ -67,8 +67,8 @@ def format_memories_table(
table.add_column("Created", max_width=12)
for mem in memories:
mem_id = mem.get("id", "")
memory_text = mem.get("memory", mem.get("text", ""))
mem_id = mem.get("id") or ""
memory_text = mem.get("memory") or mem.get("text") or ""
if len(memory_text) > 60:
memory_text = memory_text[:57] + "..."
categories = mem.get("categories", [])
@@ -104,8 +104,8 @@ def format_single_memory(console: Console, mem: dict, output: str = "text") -> N
format_json(console, mem)
return
memory_text = mem.get("memory", mem.get("text", ""))
mem_id = mem.get("id", "")
memory_text = mem.get("memory") or mem.get("text") or ""
mem_id = mem.get("id") or ""
lines = []
lines.append(f" [white bold]{memory_text}[/]")
+5
View File
@@ -139,6 +139,11 @@ class TestNestedAccess:
assert set_nested_value(config, "platform.api_key", "new-key")
assert config.platform.api_key == "new-key"
def test_set_int_value_rejects_invalid_input(self):
config = Mem0Config()
assert set_nested_value(config, "version", "abc") is False
assert config.version == 1
def test_set_nonexistent_key(self):
config = Mem0Config()
assert set_nested_value(config, "nonexistent.key", "val") is False
+23
View File
@@ -54,6 +54,11 @@ class TestTextFormat:
output = buf.getvalue()
assert "Found 0" in output
def test_format_memories_text_handles_null_fields(self):
console, buf = _make_console()
format_memories_text(console, [{"id": None, "memory": None, "created_at": None}])
assert "Found 1 memories" in buf.getvalue()
class TestTableFormat:
def test_format_memories_table(self):
@@ -70,6 +75,13 @@ class TestTableFormat:
# Should still render (empty table)
assert "ID" in output
def test_format_memories_table_handles_null_fields(self):
console, buf = _make_console()
format_memories_table(console, [{"id": None, "memory": None, "created_at": None}])
output = buf.getvalue()
assert "ID" in output
assert "Memory" in output
class TestSingleMemory:
def test_format_single_memory_text(self):
@@ -87,6 +99,17 @@ class TestSingleMemory:
output = buf.getvalue()
assert '"memory"' in output
def test_format_single_memory_handles_null_fields(self):
console, buf = _make_console()
format_single_memory(
console,
{"id": None, "memory": None, "text": "Fallback memory", "created_at": None},
"text",
)
output = buf.getvalue()
assert "Fallback memory" in output
assert "ID:" not in output
class TestAddResult:
def test_format_add_result_text(self):
+46
View File
@@ -0,0 +1,46 @@
"""Tests for the Platform backend (mem0 Platform API client)."""
from __future__ import annotations
from unittest.mock import patch
from mem0_cli.backend.platform import PlatformBackend
from mem0_cli.config import PlatformConfig
def _make_backend() -> PlatformBackend:
# api_key/base_url are only used to build the httpx client; every test here
# patches _request, so no real network calls are made.
return PlatformBackend(PlatformConfig(api_key="test-key", base_url="https://api.mem0.ai"))
class TestDeleteEntities:
def test_multiple_entities_returns_all_results(self):
backend = _make_backend()
responses = {
"/v2/entities/user/alice/": {"message": "user deleted"},
"/v2/entities/agent/bob/": {"message": "agent deleted"},
}
with patch.object(backend, "_request") as mock_request:
mock_request.side_effect = lambda method, path, **kw: responses[path]
result = backend.delete_entities(user_id="alice", agent_id="bob")
# Regression: previously only the last entity's response survived.
assert result == {
"user": {"message": "user deleted"},
"agent": {"message": "agent deleted"},
}
assert mock_request.call_count == 2
def test_single_entity_keyed_by_type(self):
backend = _make_backend()
with patch.object(backend, "_request", return_value={"message": "user deleted"}):
result = backend.delete_entities(user_id="alice")
assert result == {"user": {"message": "user deleted"}}
def test_no_entities_raises(self):
backend = _make_backend()
import pytest
with pytest.raises(ValueError):
backend.delete_entities()
@@ -0,0 +1,43 @@
from unittest.mock import MagicMock
from mem0_cli.backend.platform import PlatformBackend
def _backend(sample_config):
backend = PlatformBackend(sample_config.platform)
backend._client = MagicMock()
backend._client.request.return_value = MagicMock(
status_code=200,
json=lambda: {"message": "ok"},
headers={},
raise_for_status=lambda: None,
)
return backend
def test_memory_id_path_segments_are_encoded(sample_config):
backend = _backend(sample_config)
backend.get("mem/a?b#c")
backend.update("mem/a?b#c", content="updated")
backend.delete("mem/a?b#c")
paths = [call.args[1] for call in backend._client.request.call_args_list]
assert paths == [
"/v1/memories/mem%2Fa%3Fb%23c/",
"/v1/memories/mem%2Fa%3Fb%23c/",
"/v1/memories/mem%2Fa%3Fb%23c/",
]
def test_entity_and_event_path_segments_are_encoded(sample_config):
backend = _backend(sample_config)
backend.delete_entities(user_id="org/team?active#frag")
backend.get_event("evt/a?b#c")
paths = [call.args[1] for call in backend._client.request.call_args_list]
assert paths == [
"/v2/entities/user/org%2Fteam%3Factive%23frag/",
"/v1/event/evt%2Fa%3Fb%23c/",
]
+1 -1
View File
@@ -24,7 +24,7 @@ mintlify dev
### Publishing Changes
Install our Github App to auto propagate changes from your repo to your deployment. Changes will be deployed to production automatically after pushing to the default branch. Find the link to install on your dashboard.
Install our GitHub App to auto-propagate changes from your repo to your deployment. Changes will be deployed to production automatically after pushing to the default branch. Find the link to install on your dashboard.
#### Troubleshooting
+5
View File
@@ -0,0 +1,5 @@
{/* Subtle, value-anchored nudge to star the repo. Drop in at peak-end "win" moments in the OSS docs (after a successful add/search, a server bootstrap, etc.). Keep it off the Platform/API pages. */}
{/* Clicks are tracked via PostHog autocapture: the data-ph-capture-attribute-cta below tags each click with cta="star-on-github" so it's filterable as an event property. Metric = count of $autocapture where cta = star-on-github; break down by Current URL to see which win-moment converts. */}
<Callout icon="star" iconType="solid" color="#FACC15">
**Using Mem0?** <a href="https://github.com/mem0ai/mem0" data-ph-capture-attribute-cta="star-on-github">Star us on GitHub</a> to help more developers discover memory for AI apps.
</Callout>
+5 -1
View File
@@ -97,7 +97,7 @@ Get your API key from the <a href="https://app.mem0.ai/dashboard/api-keys?utm_so
## Next Steps
<CardGroup cols={2}>
<CardGroup cols={3}>
<Card title="Add Your First Memory" icon="rocket" href="/api-reference/memory/add-memories">
Start storing memories via the REST API
</Card>
@@ -105,4 +105,8 @@ Get your API key from the <a href="https://app.mem0.ai/dashboard/api-keys?utm_so
<Card title="Search with Filters" icon="filter" href="/api-reference/memory/search-memories">
Learn advanced search and filtering techniques
</Card>
<Card title="Build with cookbooks" icon="book-open" href="/cookbooks/overview">
See the API used end to end in real projects.
</Card>
</CardGroup>
+10 -1
View File
@@ -4,7 +4,7 @@ description: "Add facts, messages, or metadata to a user memory store with async
openapi: post /v3/memories/add/
---
Extract and store memories from a conversation using the V3 additive pipeline. The endpoint uses single-pass ADD-only extraction — one LLM call, no UPDATE/DELETE. Memories accumulate over time; nothing is overwritten.
Extract and store memories from a conversation using the V3 additive pipeline. The endpoint uses single-pass ADD-only extraction: one LLM call, no UPDATE/DELETE. Memories accumulate over time; nothing is overwritten.
## Endpoint
@@ -50,6 +50,7 @@ Provide conversation messages for Mem0 to extract memories from. At least one en
| `app_id` | string | No* | Associates the memory with an app. |
| `metadata` | object | Optional | Custom key/value metadata (e.g., `{"topic": "preferences"}`). |
| `infer` | boolean (default `true`) | Optional | Set to `false` to skip inference and store the provided text as-is. |
| `expiration_date` | string | Optional | Date in `YYYY-MM-DD` format. The memory is visible through this date and hidden by default after it passes. |
> \* At least one entity ID (`user_id`, `agent_id`, `app_id`, or `run_id`) is required.
@@ -83,3 +84,11 @@ The request is queued for background processing. The response contains an `event
<Info>
Poll the event status via `GET /v1/event/{event_id}/`. Status will be `SUCCEEDED` or `FAILED` once processing completes.
</Info>
<Info>
Memories with `expiration_date` remain stored after they expire. Search and get-all hide them by default; pass `show_expired: true` to include them.
</Info>
<Info>
Python uses `expiration_date`; TypeScript uses `expirationDate`.
</Info>
@@ -4,4 +4,4 @@ description: "Submit an export job to create a structured memory export using a
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`, `run_id`, or `session_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`, `app_id`, or `run_id`) and by modifying the Pydantic schema to ensure the final data matches your exact needs.
+8 -1
View File
@@ -4,7 +4,11 @@ description: "Retrieve memories with paginated results and advanced filtering us
openapi: post /v3/memories/
---
List memories scoped by filters with paginated results. Entity IDs (`user_id`, `agent_id`, `app_id`, `run_id`) **must** be passed inside the `filters` object — top-level entity IDs are rejected with 400.
List memories scoped by filters with paginated results. Entity IDs (`user_id`, `agent_id`, `app_id`, `run_id`) **must** be passed inside the `filters` object: top-level entity IDs are rejected with 400.
Expired memories are hidden by default. Pass `show_expired: true` to include memories whose `expiration_date` has passed.
Python uses `show_expired`; TypeScript uses `showExpired`.
The `filters` object supports complex logical operations (AND, OR, NOT) and comparison operators:
@@ -32,6 +36,7 @@ memories = client.get_all(
}
]
},
show_expired=False,
page=1,
page_size=50
)
@@ -46,12 +51,14 @@ memories = client.get_all(
{
"id": "f4cbdb08-7062-4f3e-8eb2-9f5c80dfe64c",
"memory": "Alex is planning a trip to San Francisco from July 1st to July 10th",
"expiration_date": null,
"created_at": "2024-07-01T12:00:00Z",
"updated_at": "2024-07-01T12:00:00Z"
},
{
"id": "a2b8c3d4-5e6f-7g8h-9i0j-1k2l3m4n5o6p",
"memory": "Alex prefers vegetarian restaurants",
"expiration_date": null,
"created_at": "2024-07-05T15:30:00Z",
"updated_at": "2024-07-05T15:30:00Z"
}
@@ -4,4 +4,4 @@ description: "Retrieve the latest structured memory export after submitting an e
openapi: post /v1/exports/get
---
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.
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.
+13 -7
View File
@@ -4,9 +4,13 @@ description: "Search memories with hybrid retrieval (semantic + BM25 + entity ma
openapi: post /v3/memories/search/
---
Relevance-ranked hybrid search across stored memories. V3 uses multi-signal retrieval — semantic, BM25 keyword, and entity matching scored in parallel and fused. The returned `score` is a combined `[0, 1]` value.
Relevance-ranked hybrid search across stored memories. V3 uses multi-signal retrieval: semantic, BM25 keyword, and entity matching scored in parallel and fused. The returned `score` is a combined `[0, 1]` value.
Entity IDs (`user_id`, `agent_id`, `app_id`, `run_id`) **must** be passed inside the `filters` object — top-level entity IDs are rejected with 400. At least one entity ID is required.
Entity IDs (`user_id`, `agent_id`, `app_id`, `run_id`) **must** be passed inside the `filters` object: top-level entity IDs are rejected with 400. At least one entity ID is required.
Expired memories are hidden by default. Pass `show_expired: true` to include memories whose `expiration_date` has passed.
Python uses `show_expired`; TypeScript uses `showExpired`.
The `filters` object supports complex logical operations (AND, OR, NOT) and comparison operators:
- `in`: Matches any of the values specified
@@ -20,16 +24,17 @@ The `filters` object supports complex logical operations (AND, OR, NOT) and comp
### Search parameter defaults
| Parameter | V1/V2 | V3 |
| --- | --- | --- |
| `top_k` | Supported (default 10) | Supported (1-1000, default 10) |
| `threshold` | No default | Default `0.1` (pass `0.0` to disable) |
| `rerank` | Default `true` | Default `false` (pass `true` to enable) |
| Parameter | Default |
| --- | --- |
| `top_k` | `10` (range 1–1000) |
| `threshold` | `0.1` (pass `0.0` to disable) |
| `rerank` | `false` (pass `true` to enable) |
<CodeGroup>
```python Platform API Example
related_memories = client.search(
query="What are Alice's hobbies?",
show_expired=False,
filters={
"OR": [
{
@@ -54,6 +59,7 @@ related_memories = client.search(
"category": "hobbies"
},
"score": 0.82,
"expiration_date": null,
"created_at": "2024-07-26T10:29:36.630547-07:00",
"updated_at": null,
"categories": ["hobbies"]
+11 -2
View File
@@ -1,5 +1,14 @@
---
title: 'Update Memory'
description: "Update the content or metadata of a single memory by its unique ID using the PUT endpoint."
description: "Update the content, metadata, timestamp, or expiration date of a single memory by its unique ID using the PUT endpoint."
openapi: put /v1/memories/{memory_id}/
---
---
Use this endpoint to update mutable memory fields. To make a memory expire, set `expiration_date` to a `YYYY-MM-DD` date. To make it permanent again, send `expiration_date: null`.
```python
client.update("mem_123", expiration_date="2030-01-31")
client.update("mem_123", expiration_date=None)
```
TypeScript uses `expirationDate`.
@@ -0,0 +1,5 @@
---
title: "Remove Organization Member"
description: "Remove a member from an organization to revoke their access to its projects and resources."
openapi: "delete /api/v1/orgs/organizations/{org_id}/members/"
---
@@ -0,0 +1,5 @@
---
title: "Update Organization Member"
description: "Update an existing member's role within an organization to change their permissions and access level."
openapi: "put /api/v1/orgs/organizations/{org_id}/members/"
---
+42 -3
View File
@@ -14,7 +14,7 @@ Organizations and projects are **optional** features. You can use Mem0 without t
## Key Capabilities
- **Multi-org/project Support**: Specify organization and project when initializing the Mem0 client to attribute API usage appropriately
- **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.
- **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
- **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
Modify project configuration including custom instructions, categories, and language preferences:
Modify project configuration including custom instructions, categories, language preferences, retrieval criteria, and memory decay:
```python
# Update project with custom categories
@@ -98,6 +98,17 @@ client.project.update(
# Use the input language for memory storage and retrieval
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
client.project.update(
custom_instructions="...",
@@ -109,9 +120,37 @@ 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
`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:
```bash cURL
curl -X PATCH https://api.mem0.ai/api/v1/orgs/organizations/$ORG_ID/projects/$PROJECT_ID/ \
@@ -0,0 +1,5 @@
---
title: "Remove Project Member"
description: "Remove a member from a project to revoke their access to its memories, configuration, and resources."
openapi: "delete /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/"
---
@@ -0,0 +1,5 @@
---
title: "Update Project Member"
description: "Update an existing member's role within a project to change their permissions and access level."
openapi: "put /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/"
---
@@ -0,0 +1,5 @@
---
title: "Update Project"
description: "Update a project's settings, including name, custom instructions, and other configuration options."
openapi: "patch /api/v1/orgs/organizations/{org_id}/projects/{project_id}/"
---
+138 -61
View File
@@ -4,16 +4,121 @@ description: "Major product launches, headline features, and milestones for Mem0
mode: "wide"
---
<Update label="2026-06-27" description="SDK memory expiration">
**SDK Memory Expiration: Expiring Memories Across Python and TypeScript**
The latest SDK releases add first-class expiration controls to memory writes, updates, and reads, plus new TypeScript provider coverage for production deployments.
- **Python client updates:** `MemoryClient.update()` and `AsyncMemoryClient.update()` now accept `expiration_date`, including `None` to clear an existing expiration.
- **TypeScript client updates:** `AddMemoryOptions`, `update()`, and `Memory` now support `expirationDate`; `search()` and `getAll()` can include expired memories with `showExpired`.
- **New TypeScript LLM providers:** `MiniMaxLLM` and `LiteLLM` are now available for OpenAI-compatible MiniMax and LiteLLM proxy deployments.
- **PGVector deployment flexibility:** TypeScript PGVector config now supports `connectionString` and `ssl`, so apps can use a managed Postgres URI instead of separate connection fields.
See [SDK & Tools](/changelog/sdk) for version details and PR links.
</Update>
<Update label="2026-06-25" description="Mem0 Plugin v0.2.11">
**Mem0 Plugin: Shared Memory for Claude Code, Cursor, Codex, and Antigravity**
The shared Mem0 editor plugin is current through v0.2.11:
- **Automatic context injection:** File reads, bash errors, session resume prompts, and startup timelines can retrieve relevant memories automatically.
- **Project and global scopes:** Project-scoped memories remain the default, while `global_search` supports team-wide recall across users and app scopes.
- **Coding categories:** A 17-category coding taxonomy installs in the background and is cached per Mem0 account.
- **Reliable capture:** Auto-capture, compaction summaries, session summaries, and metadata defaults keep memories scoped and readable.
- **Editor correctness:** Telemetry now reports Claude Code, Cursor, Codex, and Antigravity separately with each editor's real plugin version.
</Update>
<Update label="2026-06-25" description="Antigravity Plugin v0.1.3">
**Antigravity Plugin: Mem0 for Google Antigravity**
Antigravity support in the shared Mem0 editor plugin family is current through v0.1.3:
- **Self-contained plugin:** Includes its own plugin manifest, MCP config, hooks, shared scripts, and skills.
- **AGENTS.md convention:** Uses Antigravity's `contextFileName: "AGENTS.md"` convention.
- **Lifecycle hooks:** Wires session start, prompt recall, file-read context, memory-tool metadata enforcement, bash-error lookup, post-tool tracking, and stop summaries.
- **Shared memory layer:** Reuses the Mem0 Platform MCP tools and the shared 16-skill command bundle.
- **Better automatic recall:** v0.1.3 adds reranked injected context and clean `files_touched` metadata in session summaries.
- **Telemetry correctness:** v0.1.2 reports Antigravity as `antigravity` with the plugin's own version.
</Update>
<Update label="2026-06-22" description="OpenCode Plugin v0.2.0">
**OpenCode Plugin: Native SDK Memory Tools for OpenCode**
`@mem0/opencode-plugin` adds memory to OpenCode and is current through v0.2.0:
- **Native SDK tools:** Memory tools register through `@opencode-ai/plugin` and call the `mem0ai` SDK directly, so the plugin no longer depends on `mcp.mem0.ai`.
- **Memory scopes:** Operations support `project`, `session`, and `global` scope, with `/mem0-scope` to change the default.
- **Automatic context:** File-context injection, structured compaction summaries, and a recent-activity timeline surface relevant memories without manual recall.
- **Auto-dream consolidation:** Gated consolidation merges duplicates, drops stale or sensitive entries, and rewrites vague memories.
- **Skills load in place:** The `config` hook adds bundled skills to `skills.paths` instead of copying them into user config directories.
- **Safety controls:** Blocks `MEMORY.md` writes and redacts secrets before storing memories.
</Update>
<Update label="2026-06-12" description="Pi Agent Plugin v0.1.2">
**Pi Agent Plugin: Persistent Memory for Pi Agent**
`@mem0/pi-agent-plugin` adds semantic memory to Pi Agent and has been updated through v0.1.2:
- **Agent memory tool:** Registers `mem0_memory` for scoped search, add, get, delete, and delete-all operations.
- **Slash commands:** Adds `/mem0-remember`, `/mem0-search`, `/mem0-forget`, `/mem0-tour`, `/mem0-dream`, `/mem0-pin`, `/mem0-scope`, and `/mem0-status`.
- **Auto-capture:** Stores user and assistant memories after agent turns.
- **Dream consolidation:** Merges duplicates, resolves contradictions, and prunes stale memories behind session, time, and memory-count gates.
- **Project scoping:** Uses git-root detection for stable `app_id` values across monorepos.
- **Relevant command results:** v0.1.2 adds visible command feedback and thresholded, reranked search for search, forget, and pin commands.
</Update>
<Update label="2026-06-12" description="OpenClaw v1.0.13">
**OpenClaw Plugin: Current Memory Backend for OpenClaw**
`@mem0/openclaw-mem0` is current through v1.0.13, with the original production-ready memory backend plus newer setup, security, and runtime work:
- **Skills-based memory architecture:** Triage, recall, and dream skills handle extraction, recall, consolidation, and tool guidance.
- **Chat and CLI setup:** Supports chat-based platform setup, `openclaw mem0 init`, direct API keys, email OTP, autonomous agent setup, and OSS onboarding.
- **Platform and OSS modes:** Works with Mem0 Platform or self-hosted OSS providers including OpenAI, Anthropic, Ollama, Qdrant, and PGVector.
- **Agent-friendly CLI:** All 16 CLI commands support `--json` for machine-driven setup and diagnostics.
- **Runtime integration:** Exposes OpenClaw memory capability APIs for search manager and backend config status.
- **Security and compliance:** Added path containment checks, sensitive config metadata, dependency overrides, telemetry hashing, and metadata-only registration safety.
</Update>
<Update label="2026-06-10" description="Vercel AI SDK Provider v3.0.0">
**Vercel AI SDK Provider: Memory-Augmented Generation for AI SDK v6**
The Vercel AI SDK provider moved to the v6 provider contract and Mem0 v3 APIs:
- **AI SDK v6 support:** Migrated to `LanguageModelV3` / `ProviderV3`, including v3 stream lifecycle events and content arrays.
- **Mem0 v3 API support:** Memory writes and searches now use `/v3/memories/add/` and `/v3/memories/search/`.
- **Mem0 sources in responses:** `generateText` and `streamText` responses include memories as sources with `providerMetadata.mem0.memories`.
- **Safer prompt handling:** Prompts are cloned before memory injection, avoiding caller-side mutation.
- **Async storage fix:** `addMemories` is awaited so generated memories are not silently dropped.
- **Raw memory utilities:** Exports `searchMemories`, `retrieveMemories`, `getMemories`, and `addMemories` for apps that need direct memory control.
- **Deployment controls:** Per-request `mem0ApiKey` and `host` support Mem0 Platform, custom API keys, and self-hosted API endpoints.
</Update>
<Update label="2026-05-13" description="Temporal Reasoning for Mem0 Platform v3">
**Temporal Reasoning — Time-Aware Retrieval for Platform v3**
**Temporal Reasoning: Time-Aware Retrieval for Platform v3**
Mem0 Platform v3 can now interpret time-aware memories and queries so assistants retrieve the right information for questions about the past, upcoming plans, and current state.
- **Time-aware search intent** — Queries like `last week`, `upcoming`, `right now`, and `as of March 2025` return contextually appropriate results automatically
- **Enabled by default** — No per-request toggle required for v3 writes or searches
- **Anchored relative queries** — `reference_date` anchors relative search phrases for tests, backfills, and reproducible demos
- **Normal response shape** — Temporal reasoning affects ranking while preserving existing client response patterns
- **Search intent parsing:** Queries like `last week`, `upcoming`, `right now`, and `as of March 2025` now resolve against memory timestamps automatically.
- **Default v3 behavior:** No per-request toggle is needed for v3 writes or searches.
- **Deterministic testing:** Pass `reference_date` to anchor relative phrases in tests, backfills, and demos.
- **Stable API shape:** Temporal reasoning changes ranking, not the client response contract.
See [Temporal Reasoning](/platform/features/temporal-reasoning) for usage details.
@@ -21,11 +126,11 @@ See [Temporal Reasoning](/platform/features/temporal-reasoning) for usage detail
<Update label="2026-05-08" description="Memory Decay">
**Memory Decay — Recently-Used Memories Surface Higher, Automatically**
**Memory Decay: Recently-Used Memories Surface Higher**
Per-project search-time ranking bias that boosts recently-touched memories and gently dampens stale ones. Off by default; opt in per project via the `decay` field on the project endpoint, or via `client.project.update(decay=True)` in the SDKs (Python `v2.0.2` / TypeScript `v3.0.3`).
- **Soft bias, never a filter.** The scaling factor stays in `0.3×–1.5×`. Decay can reorder candidates but never zeros them out — anything that surfaced before decay can still surface after.
- **Soft bias, never a filter.** The scaling factor stays in `0.3×–1.5×`. Decay can reorder candidates but never removes them; anything that surfaced before decay can still surface after.
- **Reinforcement loop.** Every memory returned in a search has its access history updated, so frequently-used facts naturally float to the top over time.
- **Public score still clamped to `[0, 1]`.** Existing API contract preserved; no client-side changes needed.
- **v3 search only**, fully reversible. See [Memory Decay docs](/platform/features/memory-decay).
@@ -34,18 +139,18 @@ Per-project search-time ranking bias that boosts recently-touched memories and g
<Update label="2026-04-14" description="Mem0 SDK v2.0.0 / v3.0.0">
**New Memory Algorithm — State-of-the-Art Accuracy at ~3-4x Lower Cost**
**New Memory Algorithm: State-of-the-Art Accuracy at ~3-4x Lower Cost**
Ground-up rewrite of the memory pipeline with 20+ point benchmark improvements:
- **LoCoMo:** 71.4 → **91.6** (+20) — multi-turn conversation recall
- **LongMemEval:** 67.8 → **93.4** (+26) — long-term memory across sessions
- **BEAM (1M tokens):** **64.1** — production-scale memory evaluation
- **Agent memories are first-class** — Previous algorithm: 46% on assistant recall. New: **100%**
- **Temporal reasoning works** — "Where did I live before SF?" Previous: 51%. New: **93%**
- **~3-4x fewer tokens** — Under 7K tokens per retrieval vs 25K+ for full-context approaches
- **ADD-only extraction** — Memories accumulate; nothing is overwritten or deleted
- **Hybrid retrieval** — Semantic + BM25 keyword + entity boost, scored in parallel
- **LoCoMo:** 71.4 → **91.6** (+20) for multi-turn conversation recall.
- **LongMemEval:** 67.8 → **93.4** (+26) for long-term memory across sessions.
- **BEAM (1M tokens):** **64.1** on production-scale memory evaluation.
- **Agent memories:** Assistant recall moves from 46% to **100%**.
- **Temporal reasoning:** "Where did I live before SF?" improves from 51% to **93%**.
- **Lower token use:** Retrieval stays under 7K tokens versus 25K+ for full-context approaches.
- **ADD-only extraction:** Memories accumulate; nothing is overwritten or deleted.
- **Hybrid retrieval:** Semantic search, BM25 keyword search, and entity boost are scored in parallel.
- **Graph memory (built-in)**: entities extracted, embedded, and linked across memories, with no external graph store required
Breaking changes: external graph stores removed from OSS (replaced by built-in graph memory), `search()` defaults changed, deprecated params removed. See [migration guide](/migration/oss-v2-to-v3).
@@ -54,56 +159,28 @@ Breaking changes: external graph stores removed from OSS (replaced by built-in g
<Update label="2026-04-06" description="Mem0 Skill Graph">
**Mem0 Skill Graph — In-Context Documentation for AI Agents**
**Mem0 Skill Graph: In-Context Documentation for AI Agents**
AI coding agents in Claude Code, Cursor, and Codex can now access Mem0 knowledge directly in their workflow — no doc searching required. Three interconnected skills launched:
AI coding agents in Claude Code, Cursor, and Codex can now access Mem0 knowledge directly in their workflow without leaving the editor. Three interconnected skills launched:
- **mem0 Core Skill** — Complete Python and TypeScript SDK reference, REST API patterns, and integration guides for LangChain, CrewAI, Autogen, and more
- **mem0-cli Skill** — Terminal command reference, configuration walkthroughs, and CI/CD recipes
- **mem0-vercel-ai-sdk Skill** — Vercel AI SDK provider API, memory-augmented generation patterns, and multi-provider setup
- **mem0 Core Skill:** Python and TypeScript SDK reference, REST API patterns, and integration guides for LangChain, CrewAI, Autogen, and more.
- **mem0-cli Skill:** Terminal command reference, configuration walkthroughs, and CI/CD recipes.
- **mem0-vercel-ai-sdk Skill:** Vercel AI SDK provider API, memory-augmented generation patterns, and multi-provider setup.
</Update>
<Update label="2026-04-06" description="Mem0 CLI v0.2.2">
**Official Mem0 CLI — Now on PyPI and npm**
**Official Mem0 CLI: Now on PyPI and npm**
A full-featured command-line interface for Mem0, available in both Python and Node.js:
- **Install:** `pip install mem0-cli` or `npm install -g @mem0/cli`
- **Full command suite** — `add`, `search`, `list`, `get`, `update`, `delete`, `import`, `config`, `init`, `status`, `entity`, `event`
- **Interactive setup** — `mem0 init` with email verification or direct API key entry
- **Works everywhere** — Platform (Mem0 Cloud) and self-hosted OSS modes
- **Scriptable** — `--json` flag for CI/CD pipelines and automation
- **Dual SDK** — Same commands, same experience across Python and Node.js
</Update>
<Update label="2026-04-06" description="OpenClaw v1.0.4">
**OpenClaw Plugin — Production-Ready**
The OpenClaw Mem0 plugin went from initial release to production-ready in one week (v1.0.0 → v1.0.4):
- **Skills-based memory architecture** — New extraction pipeline with skill-loader, batched extraction, and domain-aware memory triage
- **Dream gate** — Automatic memory consolidation during idle periods for higher-quality long-term recall
- **Interactive CLI** — `openclaw mem0 init`, `status`, `config`, `import`, and `event` commands
- **Unified tool naming** — `memory_add` and `memory_delete` replace 4 legacy tools, matching the platform API
- **Security hardened** — Path traversal protection, pinned dependencies, 329 tests across 10 files
</Update>
<Update label="2026-04-02" description="Mem0 Plugin for AI Editors">
**Mem0 Plugin for Claude Code, Cursor, and Codex**
Launched a unified Mem0 plugin across three major AI development environments — Claude Code and Cursor first (March 25), then Codex (April 2):
- **9 MCP memory tools** — add, search, get, update, delete, bulk delete, entity management via `mcp.mem0.ai`
- **Lifecycle hooks** — Automatic memory capture at session start, context compaction, task completion, and session end
- **Cloud MCP server** — Managed endpoint replaces local MCP and Smithery setup
- **Streamable HTTP transport** — New MCP transport protocol for real-time streaming
- **Codex-specific skill** — Dedicated skill in `mem0-plugin/skills/mem0-codex` for Codex workflows
- **Full command suite:** `add`, `search`, `list`, `get`, `update`, `delete`, `import`, `config`, `init`, `status`, `entity`, `event`.
- **Interactive setup:** `mem0 init` supports email verification and direct API key entry.
- **Runtime coverage:** Works with Mem0 Platform and self-hosted OSS modes.
- **Automation support:** Use `--json` for CI/CD pipelines and agent workflows.
- **Dual implementation:** Same commands and behavior across Python and Node.js.
</Update>
@@ -113,11 +190,11 @@ Launched a unified Mem0 plugin across three major AI development environments
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)
- **Turbopuffer** — New vector database provider for Python SDK
- **MiniMax** — New LLM provider with dedicated AWS Bedrock support
- **pgvector for Node.js** — PostgreSQL vector support added to the TypeScript OSS SDK
- **Reasoning models** — `reasoning_effort` parameter for OpenAI o1/o3-style models
- **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).
- **Turbopuffer:** New vector database provider for Python SDK.
- **MiniMax:** New LLM provider with dedicated AWS Bedrock support.
- **pgvector for Node.js:** PostgreSQL vector support added to the TypeScript OSS SDK.
- **Reasoning models:** `reasoning_effort` parameter for OpenAI o1/o3-style models.
</Update>
@@ -125,6 +202,6 @@ Major expansion of the provider ecosystem:
**Mem0 Platform Skill on skills.sh**
First skill launch — a dedicated Mem0 skill providing platform API reference, quickstart patterns, and integration examples directly inside agent sessions. Available on [skills.sh](https://skills.sh) for any compatible AI coding agent.
First skill launch: a dedicated Mem0 skill providing platform API reference, quickstart patterns, and integration examples directly inside agent sessions. Available on [skills.sh](https://skills.sh) for any compatible AI coding agent.
</Update>
-336
View File
@@ -1,336 +0,0 @@
---
title: "OpenClaw"
description: "Release notes for the OpenClaw plugin and agent harness."
mode: "wide"
---
<Update label="2026-06-12" description="v1.0.13">
**Fixes:**
- **Custom categories payload:** `customCategories` (a `Record<string, string>` map) is now converted via the new `customCategoryMapToList()` helper into the `Array<Record<string, string>>` shape the Mem0 SDK expects on `add` calls — previously the raw object was passed as `custom_categories` and silently ignored ([#5345](https://github.com/mem0ai/mem0/pull/5345))
- **Skip runtime setup during metadata registration:** `register()` now detects `registrationMode === "cli-metadata"`, registers only the CLI commands, and returns early — avoiding backend initialization, service/tool registration, and hook installation during OpenClaw's metadata-only registration pass ([#5383](https://github.com/mem0ai/mem0/pull/5383))
**Security:**
- Bumped `mem0ai` from `3.0.3` to `3.0.7` (latest Node SDK) — includes the transitive axios CVE remediation shipped in `3.0.6` ([#5460](https://github.com/mem0ai/mem0/pull/5460))
- Added pnpm override `uuid@<11.1.1` → `>=11.1.1` to resolve an open MEDIUM Dependabot alert ([#5489](https://github.com/mem0ai/mem0/pull/5489))
**Improvements:**
- **Repo consolidation:** Plugin moved from repo-root `openclaw/` to `integrations/openclaw/`; `package.json` `repository.directory` updated to match so npm provenance links to the correct subdirectory ([#5491](https://github.com/mem0ai/mem0/pull/5491))
**Tests:**
- Added `customCategoryMapToList` unit tests and a `PlatformProvider` test asserting `custom_categories` is passed to the Mem0 SDK as a list ([#5345](https://github.com/mem0ai/mem0/pull/5345))
- Added a regression test asserting `cli-metadata` registration registers only CLI commands and triggers no runtime side effects ([#5383](https://github.com/mem0ai/mem0/pull/5383))
</Update>
<Update label="2026-06-02" description="v1.0.12">
**Docs:**
- **Agent Mode onboarding:** README now documents an autonomous setup path for AI agents — `mem0 init --agent --json` mints an evaluation Mem0 API key with no email, OTP, or browser and exports it as `MEM0_API_KEY` for `openclaw mem0 init`; a human owner can later run `mem0 init --email <email>` to claim ownership without disrupting the agent ([#5123](https://github.com/mem0ai/mem0/pull/5123))
**Security:**
- Added pnpm overrides to remediate advisories in transitive dependencies: `langsmith@<0.6.0` → `^0.6.0`, `picomatch@<2.3.2` → `^2.3.2`, `vite` → `^8.0.5`, and `@qdrant/js-client-rest` → `^1.18.0` ([#5294](https://github.com/mem0ai/mem0/pull/5294))
**Dependencies:**
- Bumped `mem0ai` from `3.0.2` to `3.0.3` ([#5212](https://github.com/mem0ai/mem0/pull/5212))
- Bumped dev dependencies `@vitest/coverage-v8` and `vitest` from `^4.0.18` to `^4.1.7`; added `vite@^8.0.5` and `@qdrant/js-client-rest@^1.18.0` ([#5294](https://github.com/mem0ai/mem0/pull/5294))
</Update>
<Update label="2026-04-29" description="v1.0.11">
**New Features:**
- **Skills-mode auto-setup:** `enableSkillsConfig()` now runs automatically after onboarding — enables triage, recall (with reranking + keyword search), and dream consolidation with `tools.profile = "full"` and disables the built-in session-memory hook to avoid conflicts
- **Memory runtime capability:** Plugin now exposes `runtime.getMemorySearchManager()` and `resolveMemoryBackendConfig()` on the registered memory capability, enabling OpenClaw gateway to query memory status and backend config directly
- **Dimension-aware collections:** OSS wizard detects embedder dimension changes and creates a new collection (`mem0_<dims>d`) automatically, with a warning about old memories being inaccessible under the new embedder
- **Tool documentation in skills:** Both `memory-triage` and `memory-dream` SKILL.md files now include full tool reference sections listing all available tools with parameters
**Improvements:**
- **Auto-capture and auto-recall default to enabled:** `autoCapture` and `autoRecall` now default to `true` (was `false`). Manifest descriptions updated accordingly. Ignored in skills mode
- **`memory_update` over delete+add:** Skills now prefer `memory_update` for in-place edits — atomic and preserves edit history. Consolidation pattern updated: update best memory, delete redundant ones
- **Search threshold lowered:** Default `searchThreshold` reduced from `0.5` to `0.1` for broader recall. Removed hardcoded `0.6` recall-specific override — all searches now use the configured threshold
- **Embedder dimension propagation:** Vector store config auto-resolves dimensions from embedder config when not explicitly set. Syncs `dimension` and `embeddingModelDims` fields for Qdrant/PGVector compatibility
- **Config file write safety:** `writeFullConfig()` now re-reads and deep-merges the `plugins` section before writing, preserving `installs` and `slots` written by the OpenClaw gateway
- **Additional embedder models:** Added `mxbai-embed-large` (1024), `all-minilm` (384), and `snowflake-arctic-embed` (1024) to known embedder dimensions
**Security:**
- Bumped `protobufjs` to `>=7.5.5` via pnpm overrides (GHSA-xq3m-2v4x-88gg) ([#5012](https://github.com/mem0ai/mem0/pull/5012))
**Fixes:**
- Moved `bootstrapTelemetryFlag()` and removed `ensureInstallRecord()` from module-level side effects — both now run inside `register()` to avoid crashes when loaded outside OpenClaw gateway
- Fixed OSS history DB path resolution: absolute paths no longer passed through `resolvePath()`, preventing double-prefix bugs
- Manifest `providerAuthEnvVars` replaced with spec-compliant `setup.providers` format using `id` + `envVars`
**Dependencies:**
- Bumped `mem0ai` from `3.0.1` to `3.0.2`
- Bumped `pluginApi` and `minGatewayVersion` compat to `>=2026.4.24`
</Update>
<Update label="2026-04-23" description="v1.0.10">
**Security:**
- Telemetry `distinct_id` now uses SHA-256 instead of MD5 — prevents rainbow-table reversal of API key hashes
- User email is now SHA-256 hashed before sending as `distinct_id` — no PII in telemetry payloads
- Declared PostHog telemetry endpoint (`us.i.posthog.com`) in `providerEndpoints`
**Fixes:**
- Fixed version-pinned install records preventing plugin updates. `ensureInstallRecord()` now detects semver-pinned specs (e.g. `@mem0/openclaw-mem0@1.0.7`) and rewrites them to `@latest` or `clawhub:` prefix so `openclaw plugins update` resolves to the newest release
- Fixed `searchThreshold` default inconsistency: standardized to `0.3` across docs, README, and manifest
- `PLUGIN_VERSION` now injected at build time via tsup `define` from `package.json` — no more hardcoded version strings
**Manifest Compliance:**
- Removed non-spec fields: `requiredEnvVars`, `dataLocations`, `privacy`, `setup` (with `externalEndpoints`, `providers`, `requiresRuntime`, `postInstallHint`)
- Replaced `setup.externalEndpoints` with spec-compliant `providerEndpoints` using `endpointClass` + `hosts` format
- Env var declarations now rely solely on `providerAuthEnvVars` (already spec-compliant)
**Docs:**
- Fixed `openclaw plugins update` command: uses plugin ID (`openclaw-mem0`), not npm package name (`@mem0/openclaw-mem0`)
- Added update section to README
- Removed redundant "Key Features" and "Conclusion" sections from integration docs
</Update>
<Update label="2026-04-22" description="v1.0.9">
**Security & Compliance:**
- Added top-level `requiredEnvVars` to plugin manifest, declaring env vars per mode (platform, OSS OpenAI, OSS Anthropic, OSS Ollama). Fixes ClaHub scanner "required env vars: none" mismatch
- Added `sensitive: true` and descriptions to `apiKey` and `userEmail` in `configSchema` — previously only declared in `uiHints`
- Added `default: false` with descriptions to `autoCapture` and `autoRecall` in `configSchema` so scanner can confirm opt-in defaults
- Added `dataLocations` field to manifest declaring all persistence paths (config, vectorStore, historyDb, dreamState)
- Added `privacy` field to manifest documenting data flow for platform vs open-source mode and credential storage guidance
- Added `externalEndpoints` to `setup` section declaring api.mem0.ai and app.mem0.ai with purpose and requirement context
**Tests:**
- Replaced direct `process.env` access in `tests/cli-commands.test.ts` and `tests/fs-safe.test.ts` with `vi.stubEnv`/`vi.unstubAllEnvs`. Fixes ClaHub static analysis flag for "environment variable access combined with network send"
- 421 tests across 15 test files
</Update>
<Update label="2026-04-21" description="v1.0.8">
**New Features:**
- **OSS Onboarding Wizard:** New guided 4-step interactive setup for open-source mode — walks through LLM provider, embedding provider, vector store, and user ID selection with prefilled defaults
- **Agent-Friendly CLI:** Added `--json` flag to all 16 CLI commands for machine-readable output. Agents can call `openclaw mem0 help --json` to discover every command and flag
- **Non-Interactive OSS Setup:** Added `--mode open-source` with `--oss-llm`, `--oss-embedder`, `--oss-vector` flags for fully automated OSS configuration without prompts
- **JSON Helpers Module:** New `cli/json-helpers.ts` with `jsonOut`, `jsonErr`, and `redactSecrets` utilities for consistent structured output
**Improvements:**
- **Init Flow Redesigned:** Replaced 3-option flat menu with 2-level structure: Platform (email login or API key) and Open Source (guided wizard)
- **Provider Selection:** LLM providers: OpenAI, Ollama, Anthropic. Embedding providers: OpenAI, Ollama. Vector stores: Qdrant, PGVector
- **Input Prefill:** All prompts with defaults (base URL, user ID) now prefill the input field instead of showing defaults in brackets
- **Smart Reuse:** When LLM and embedder use the same provider, API key and base URL are automatically reused from the LLM step
- **Default Model:** Updated default LLM model to `gpt-5-mini`
- **Manifest Compliance:** Removed undocumented fields, aligned env var declarations between SKILL.md and manifest, fixed `configSchema.required` for clean installs
**Tests:**
- 404 tests across 15 test files (+3 new: `json-helpers.test.ts`, `oss-wizard.test.ts`, `cli-commands.test.ts`)
</Update>
<Update label="2026-04-20" description="v1.0.7">
**New Features:**
- **Chat-Based Setup:** Added chat-based Platform setup flow — users can now configure the plugin conversationally instead of editing config files manually
- **Installation Docs Rewrite:** Rewrote README and integration docs with chat-first setup, numbered manual steps.
**Improvements:**
- **SDK Upgrade:** Bumped `mem0ai` dependency to 3.0.1 for V3 API compatibility
- **Config Cleanup:** Dropped deprecated `orgId`, `projectId`, `enableGraph` config options; updated CLI prompts ([#4734](https://github.com/mem0ai/mem0/pull/4734), [#4764](https://github.com/mem0ai/mem0/pull/4764))
- **Noise Filtering:** Expanded noise patterns in memory add tool; handle leading text in JSON extraction
</Update>
<Update label="2026-04-11" description="v1.0.6">
**Bug Fixes:**
- **Telemetry:** Replaced shared `"anonymous-openclaw"` fallback with a persistent per-machine random hash (`openclaw-anon-<uuid>`), so anonymous plugin users are counted individually in PostHog ([#4790](https://github.com/mem0ai/mem0/pull/4790))
- **Telemetry:** Added PostHog `$identify` event on first authenticated run to stitch anonymous history onto the authenticated profile ([#4790](https://github.com/mem0ai/mem0/pull/4790))
- **Telemetry:** Fixed event loss on short-lived CLI invocations — added `beforeExit` handler to flush queued events before the process exits ([#4790](https://github.com/mem0ai/mem0/pull/4790))
- **Telemetry:** Added lazy `/v1/ping/` email resolution so users who configure API key outside `mem0 init` show as their email in PostHog, not an md5 hash ([#4790](https://github.com/mem0ai/mem0/pull/4790))
- **Telemetry:** Unified CLI event prefix from `openclaw.<cmd>` to `openclaw.cli.<cmd>` on the needsSetup branch to match the authenticated branch ([#4790](https://github.com/mem0ai/mem0/pull/4790))
**Improvements:**
- **API:** Added `source: "OPENCLAW"` to all provider calls (`add`, `search`, `getAll`) across tools, CLI commands, recall, and the OSS backend adapter ([#4790](https://github.com/mem0ai/mem0/pull/4790))
</Update>
<Update label="2026-04-07" description="v1.0.5">
**Bug Fixes:**
- **Init interactive choice bug**: Fixed number selection in `openclaw mem0 init` — entering 1/2/3 now correctly selects the corresponding option (was broken by readline prefill concatenating with user input)
- **OSS pgvector crash** ([#4727](https://github.com/mem0ai/mem0/issues/4727)): Fixed "Client has already been connected" cascade when using pgvector in OSS mode. The warmup call swallowed errors leaving a half-initialized pg client; concurrent recall/capture then all hit `client.connect()` on the same client. Fix: let warmup errors propagate (so `initPromise` resets and retries with a fresh Memory + fresh pg client) and build fresh config objects per attempt instead of mutating shared state.
**Removed:**
- **`orgId` / `projectId` config parameters**: Removed from config schema, CLI (`config show/get/set`), init display, and providers. The API key is project-scoped, so separate org/project IDs are unnecessary and could cause access errors if mismatched.
- **`enableGraph` config parameter**: Removed from all config surfaces, providers, backend, and tools. Graph memory is being deprecated — removing the flag avoids unnecessary exposure.
</Update>
<Update label="2026-04-04" description="v1.0.4">
**New Features:**
- **Interactive init flow**: `openclaw mem0 init` with interactive menu (email verification or direct API key). Non-interactive modes: `--api-key`, `--email`, `--email --code`
- **`memory_add` tool**: Replaces `memory_store` — name now matches `mem0` CLI and platform API
- **`memory_delete` tool**: Unified delete — single ID, search-then-delete, bulk, entity cascade. Replaces `memory_forget` and `memory_delete_all`
- **CLI subcommands**: `openclaw mem0 init`, `openclaw mem0 status`, `openclaw mem0 config show`, `openclaw mem0 config set`
- **`import` CLI command**: Bulk-import memories from a JSON file with `--user-id` and `--agent-id` overrides
- **`event list` / `event status` CLI commands**: Monitor background processing events
- **`fs-safe.ts` module**: Isolated filesystem wrappers in a separate entry point
- **`backend/` module**: `PlatformBackend` with direct HTTP API access for CLI commands
- **Plugin manifest**: Added `contracts.tools`, `configSchema`, and `uiHints` to `openclaw.plugin.json`
- **Test suite**: 329 tests across 10 test files
**Changes:**
- **Modular architecture**: Extracted tools into `tools/` directory (6 files) and CLI into `cli/commands.ts`
- **Code splitting**: tsup builds with `splitting: true` and two entry points
- **Skills updated**: All SKILL.md files reference new tool names (`memory_add`, `memory_delete`)
- **Auto-recall timeout**: Recall wrapped in 8-second `Promise.race`
- **Auto-capture fire-and-forget**: `provider.add()` runs in background via `.then()/.catch()`
- **Auto-capture minimum content gate**: Skips extraction when total user content is fewer than 50 chars
**Removed:**
- `memory_store` tool — replaced by `memory_add`
- `memory_forget` tool — replaced by `memory_delete`
- `memory_delete_all` tool — merged into `memory_delete`
- `memory_history` tool and `history` CLI command — deprecated
</Update>
<Update label="2026-04-03" description="v1.0.3">
**Bug Fixes:**
- **Security**: Added `safePath()` containment helper to `readSkillFile` and `readDomainOverlay` in `skill-loader.ts` — prevents directory traversal
- **Noise filter**: Reverted incorrect `After-Compaction` regex rename back to `Post-Compaction`
**Changes:**
- **Supply-chain hardening**: Pinned `mem0ai` dependency to exact `2.3.0` (was `^2.3.0`)
**Tests:**
- 12 new tests covering `safePath`, `readSkillFile`, `readDomainOverlay`, and `loadSkill` with traversal inputs
</Update>
<Update label="2026-04-02" description="v1.0.2">
**Bug Fixes:**
- **Security**: Removed `resolveEnvVars()` and `resolveEnvVarsDeep()` from `config.ts` — plugin-side env resolution was redundant and triggered static analysis warnings ([#4676](https://github.com/mem0ai/mem0/pull/4676))
</Update>
<Update label="2026-04-02" description="v1.0.1">
**New Features:**
- **CD workflow**: Added continuous deployment workflow with OIDC trusted publishing ([#4672](https://github.com/mem0ai/mem0/pull/4672))
- **Plugin configuration manifest**: Added `compat` and `build` metadata to `package.json` ([#4667](https://github.com/mem0ai/mem0/pull/4667))
- **LICENSE**: Added Apache-2.0 license file ([#4667](https://github.com/mem0ai/mem0/pull/4667))
**Bug Fixes:**
- **Dream gate**: Fixed cheap-first ordering, session isolation, and verified completion ([#4666](https://github.com/mem0ai/mem0/pull/4666))
- **Graceful startup**: Plugin now starts gracefully when no API key is configured ([#4669](https://github.com/mem0ai/mem0/pull/4669))
</Update>
<Update label="2026-04-01" description="v1.0.0">
**New Features:**
- **Skills-based memory architecture**: New skill-loader and skill-based extraction pipeline with batched extraction ([#4624](https://github.com/mem0ai/mem0/pull/4624))
- **Dream gate**: Memory consolidation and dream-cycle processing during idle periods
- **Enhanced recall**: New `recall.ts` module with improved recall logic and skill-aware retrieval
- **Memory triage skill**: Domain-aware memory triage with companion domain support and recall protocol
- **Memory dream skill**: Skill for memory consolidation during idle periods
- **Plugin configuration**: Added `openclaw.plugin.json` manifest and `scripts/configure.py` setup helper
**Changes:**
- Extraction pipeline refactored to use skills-based architecture for more contextual and higher quality memory capture
</Update>
<Update label="2026-03-26" description="v0.4.1">
**New Features:**
- **Improved extraction quality**: Enhanced noise filtering, deduplication, and better extraction instructions
**Bug Fixes:**
- **Credential detection**: Improved detection of credentials, API keys, and secrets in extraction instructions (#4552)
- **Standalone timestamps**: Prevented extraction of standalone timestamps as memories (#4550)
</Update>
<Update label="2026-03-16" description="v0.4.0">
**New Features:**
- **Non-interactive trigger filtering**: Skips recall and capture for `cron`, `heartbeat`, `automation`, and `schedule` triggers
- **Subagent hallucination prevention**: Detects ephemeral subagent sessions and routes recall to parent namespace
- **Dynamic recall thresholding**: Memories scoring less than 50% of top result are dropped
- **SQLite resilience**: Init error recovery with automatic retry for OSS mode
- **`disableHistory` config option**: New `oss.disableHistory` flag
- 78 unit tests covering filtering, isolation, trigger filtering, subagent detection, and SQLite resilience
**Changes:**
- Auto-recall threshold raised from 0.5 to 0.6 for stricter precision
- Recall candidate pool increased to `topK * 2` for better filtering headroom
- Relaxed extraction instructions: related facts kept together to preserve context
**Bug Fixes:**
- **Concurrent session race condition**: Lifecycle hooks now use `ctx.sessionKey` directly instead of a shared mutable variable
</Update>
<Update label="2026-03-12" description="v0.3.1">
**New Features:**
- **Message filtering pipeline**: Multi-stage noise removal before extraction
- **Broad recall for new sessions**: Short or new-session prompts trigger secondary broad search
- **Client-side threshold filtering**: Safety net that drops low-relevance results
- **Temporal anchoring**: Extraction instructions now include current date
- 55 unit tests covering filtering and isolation helpers
**Changes:**
- Extraction window expanded from last 10 to last 20 messages
- Rewritten custom extraction instructions for conciseness and deduplication
- Refactored monolithic `index.ts` (1772 lines) into 6 focused modules
</Update>
<Update label="2026-03-10" description="v0.3.0">
**Bug Fixes:**
- Updated `mem0ai` dependency with sqlite3 to better-sqlite3 migration (#4270)
</Update>
<Update label="2026-03-09" description="v0.2.0">
**New Features:**
- Per-agent memory isolation for multi-agent setups via `agentId`
- "Understanding userId" section in docs
**Changes:**
- Updated config examples to use concrete `userId` values instead of placeholders
**Bug Fixes:**
- Migrated platform search to Mem0 v2 API
</Update>
<Update label="2026-02-19" description="v0.1.2">
**New Features:**
- Source field for openclaw memory entries
**Bug Fixes:**
- Auto-recall injection and auto-capture message drop
</Update>
<Update label="2026-02-02" description="v0.1.0">
**New Features:**
- Initial release of the OpenClaw Mem0 plugin
- Platform mode (Mem0 Cloud) and open-source mode support
- Auto-recall: inject relevant memories before each turn
- Auto-capture: store facts after each turn
- Configurable `topK`, `threshold`, and `apiVersion` options
</Update>
+1 -1
View File
@@ -1,6 +1,6 @@
---
title: "Platform"
description: "Release notes for the Mem0 hosted platform — backend, dashboard, billing, and infrastructure changes."
description: "Release notes for the Mem0 hosted platform: backend, dashboard, billing, and infrastructure changes."
mode: "wide"
---
+905 -71
View File
File diff suppressed because it is too large Load Diff
@@ -59,5 +59,9 @@ Here are the parameters available for configuring AWS Bedrock embedder:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `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>
</Tabs>
@@ -3,7 +3,7 @@ title: Azure OpenAI
description: "Configure Azure OpenAI as an embedding provider in Mem0 with API key, deployment, and endpoint settings."
---
To use Azure OpenAI embedding models, set the `EMBEDDING_AZURE_OPENAI_API_KEY`, `EMBEDDING_AZURE_DEPLOYMENT`, `EMBEDDING_AZURE_ENDPOINT` and `EMBEDDING_AZURE_API_VERSION` environment variables. You can obtain the Azure OpenAI API key from the Azure.
To use Azure OpenAI embedding models, set the `EMBEDDING_AZURE_OPENAI_API_KEY`, `EMBEDDING_AZURE_DEPLOYMENT`, `EMBEDDING_AZURE_ENDPOINT` and `EMBEDDING_AZURE_API_VERSION` environment variables. You can obtain the Azure OpenAI API key from the Azure Portal.
### Usage
@@ -0,0 +1,111 @@
---
title: "FastEmbed"
description: "Configure FastEmbed as an embedding provider in Mem0 to generate embeddings locally using ONNX-based models without a GPU."
---
You can use FastEmbed to run embedding models locally in Mem0. FastEmbed is an ONNX-based embedding library that runs efficiently on CPU without requiring a GPU or an external API key.
### Installation
FastEmbed is an optional dependency, so install it alongside Mem0.
<CodeGroup>
```bash Python
pip install fastembed
```
```bash TypeScript
npm install fastembed
```
</CodeGroup>
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
config = {
"embedder": {
"provider": "fastembed",
"config": {
"model": "thenlper/gte-large"
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="john")
```
```typescript TypeScript
import { Memory } from "mem0ai/oss";
// FastEmbed needs no API key. Leave the embedder config empty to use the
// default model (fast-bge-small-en-v1.5), or set `model` to one of the
// supported models listed below.
const memory = new Memory({
embedder: {
provider: "fastembed",
config: {
model: "fast-bge-small-en-v1.5",
},
},
llm: {
provider: "openai",
config: { apiKey: process.env.OPENAI_API_KEY }, // For fact extraction
},
});
const messages = [
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
{ role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." },
{ role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." },
];
await memory.add(messages, { userId: "john" });
```
</CodeGroup>
<Note>
**The Python and TypeScript SDKs default to different models.** Python defaults to `thenlper/gte-large` (1024 dimensions), while TypeScript defaults to `fast-bge-small-en-v1.5` (384 dimensions). The TypeScript package (`fastembed` on npm) ships a fixed set of ONNX models and does not include `thenlper/gte-large`. Because the two defaults produce vectors of different dimensions, do not point both SDKs at the same vector store collection unless you configure them to use the same model.
</Note>
The TypeScript SDK supports these FastEmbed models. Pass the exact string as `model`:
- `fast-bge-small-en-v1.5` (default)
- `fast-bge-small-en`
- `fast-bge-base-en`
- `fast-bge-base-en-v1.5`
- `fast-bge-small-zh-v1.5`
- `fast-all-MiniLM-L6-v2`
- `fast-multilingual-e5-large`
### Config
Here are the parameters available for configuring the FastEmbed embedder:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the FastEmbed model to use | `thenlper/gte-large` |
| `embedding_dims` | Dimensions of the embedding model (auto-derived from the model if not set) | `None` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The FastEmbed model to use (see the supported list above) | `fast-bge-small-en-v1.5` |
The embedding dimension is detected automatically at startup, so you do not need to set it manually.
</Tab>
</Tabs>
@@ -67,14 +67,15 @@ Here are the parameters available for configuring Gemini embedder:
| Parameter | Description | Default Value |
| ---------------- | ------------------------------------ | ----------------------- |
| `model` | The name of the embedding model to use| `models/gemini-embedding-001` |
| `embedding_dims` | Dimensions of the embedding model | `1536` |
| `embedding_dims` | Dimensions of the embedding model | `768` |
| `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 title="TypeScript">
| Parameter | Description | Default Value |
| ----------------- | --------------------------------------------- | -------------------------- |
| `model` | The name of the embedding model to use | `gemini-embedding-001` |
| `embeddingDims` | Dimensions of the embedding model | `1536` |
| `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` |
| `apiKey` | Google API key | `None` |
</Tab>
</Tabs>
@@ -5,6 +5,10 @@ description: "Configure Hugging Face as an embedding provider in Mem0 for local
You can use embedding models from Huggingface to run Mem0 locally.
<Note>
The TypeScript SDK supports Hugging Face only through a hosted [Text Embeddings Inference (TEI)](#using-text-embeddings-inference-tei) endpoint, or any OpenAI-compatible Hugging Face endpoint. The local `sentence-transformers` mode shown first is Python-only.
</Note>
### Usage
```python
@@ -34,9 +38,10 @@ m.add(messages, user_id="john")
### Using Text Embeddings Inference (TEI)
You can also use Hugging Face's Text Embeddings Inference service for faster and more efficient embeddings:
You can also use Hugging Face's Text Embeddings Inference service for faster and more efficient embeddings. This is the mode the TypeScript SDK uses.
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -56,6 +61,24 @@ m = Memory.from_config(config)
m.add("This text will be embedded using the TEI service.", user_id="john")
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
// Point at a running TEI server, or any OpenAI-compatible HF endpoint
const config = {
embedder: {
provider: 'huggingface',
config: {
huggingfaceBaseUrl: 'http://localhost:3000/v1',
},
},
};
const memory = new Memory(config);
await memory.add("This text will be embedded using the TEI service.", { userId: "john" });
```
</CodeGroup>
To run the TEI service, you can use Docker:
```bash
@@ -66,11 +89,22 @@ docker run -d -p 3000:80 -v huggingfacetei:/data --platform linux/amd64 \
### Config
Here are the parameters available for configuring Huggingface embedder:
Here are the parameters available for configuring the Hugging Face embedder:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the model to use | `multi-qa-MiniLM-L6-cos-v1` |
| `embedding_dims` | Dimensions of the embedding model | `selected_model_dimensions` |
| `model_kwargs` | Additional arguments for the model | `None` |
| `huggingface_base_url` | URL to connect to Text Embeddings Inference (TEI) API | `None` |
| `huggingface_base_url` | URL to connect to Text Embeddings Inference (TEI) API | `None` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `huggingfaceBaseUrl` | TEI or OpenAI-compatible endpoint URL. Required; falls back to `baseURL`, `url`, then the `HUGGINGFACE_BASE_URL` env var | `None` |
| `model` | Model name sent to the endpoint (TEI ignores it) | `tei` |
| `apiKey` | API key for the endpoint; falls back to the `HUGGINGFACE_API_KEY` env var | `"hf"` |
</Tab>
</Tabs>
@@ -16,7 +16,7 @@ config = {
"embedder": {
"provider": "lmstudio",
"config": {
"model": "nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.f16.gguf"
"model": "nomic-ai/nomic-embed-text-v1.5-GGUF"
}
}
}
@@ -37,6 +37,6 @@ Here are the parameters available for configuring LM Studio embedder:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the LM Studio model to use | `nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.f16.gguf` |
| `model` | The name of the LM Studio model to use | `nomic-ai/nomic-embed-text-v1.5-GGUF` |
| `embedding_dims` | Dimensions of the embedding model | `1536` |
| `lmstudio_base_url` | Base URL for LM Studio connection | `http://localhost:1234/v1` |
+45 -8
View File
@@ -1,15 +1,20 @@
---
title: Together
description: "Configure Together AI as an embedding provider in Mem0 with support for 768-dimensional embedding models."
description: "Configure Together AI as an embedding provider in Mem0 with support for 1024-dimensional embedding models."
---
To use Together embedding models, set the `TOGETHER_API_KEY` environment variable. You can obtain the Together API key from the [Together Platform](https://api.together.xyz/settings/api-keys).
To use Together embedding models, set the `TOGETHER_API_KEY` environment variable. You can obtain the Together API key from the [Together Platform](https://api.together.ai/settings/projects/~current/api-keys).
### Usage
<Note> The `embedding_model_dims` parameter for `vector_store` should be set to `768` for Together embedder. </Note>
<Note> The `embedding_model_dims` parameter for `vector_store` should be set to `1024` for Together embedder. </Note>
```python
<Warning>
**Breaking default change.** The default Together embedding model is now `intfloat/multilingual-e5-large-instruct` (**1024-dim**), replacing the previous default `togethercomputer/m2-bert-80M-8k-retrieval` (**768-dim**). If you created a self-hosted vector store with the old default, its collection is 768-dim and will reject the new 1024-dim vectors **recreate/reindex the collection at 1024 dimensions** after upgrading. To defer the change, pin the previous values explicitly (`model="togethercomputer/m2-bert-80M-8k-retrieval"`, `embedding_dims=768`) note Together no longer lists this model among its recommended embeddings, so reindexing at 1024 is the durable path.
</Warning>
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -20,7 +25,7 @@ config = {
"embedder": {
"provider": "together",
"config": {
"model": "togethercomputer/m2-bert-80M-8k-retrieval"
"model": "intfloat/multilingual-e5-large-instruct"
}
}
}
@@ -29,18 +34,50 @@ m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="john")
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
embedder: {
provider: 'together',
config: {
apiKey: process.env.TOGETHER_API_KEY || '',
model: 'intfloat/multilingual-e5-large-instruct',
embeddingDims: 1024,
},
},
};
const memory = new Memory(config);
await memory.add("I'm visiting Paris", { userId: "john" });
```
</CodeGroup>
### Config
Here are the parameters available for configuring Together embedder:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the embedding model to use | `togethercomputer/m2-bert-80M-8k-retrieval` |
| `embedding_dims` | Dimensions of the embedding model | `768` |
| `model` | The name of the embedding model to use | `intfloat/multilingual-e5-large-instruct` |
| `embedding_dims` | Dimensions of the embedding model | `1024` |
| `api_key` | The Together API key | `None` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the embedding model to use | `intfloat/multilingual-e5-large-instruct` |
| `embeddingDims` | Dimensions of the embedding model for vector store configuration | `1024` |
| `apiKey` | The Together API key | `TOGETHER_API_KEY` |
| `baseURL` | Base URL for an OpenAI-compatible Together endpoint | `https://api.together.ai/v1` |
</Tab>
</Tabs>
+12 -11
View File
@@ -10,20 +10,21 @@ Mem0 offers support for various embedding models, allowing users to choose the o
See the list of supported embedders below.
<Note>
The following embedders are supported in the Python implementation. The TypeScript implementation currently only supports OpenAI.
All embedders listed below are supported in the Python implementation. The TypeScript implementation supports: **OpenAI**, **Azure OpenAI**, **FastEmbed**, **Google AI**, **Langchain**, **LM Studio**, **Ollama**, and **Together**.
</Note>
<CardGroup cols={4}>
<Card title="OpenAI" href="/components/embedders/models/openai"></Card>
<Card title="Azure OpenAI" href="/components/embedders/models/azure_openai"></Card>
<Card title="Ollama" href="/components/embedders/models/ollama"></Card>
<Card title="Hugging Face" href="/components/embedders/models/huggingface"></Card>
<Card title="Google AI" href="/components/embedders/models/google_AI"></Card>
<Card title="Vertex AI" href="/components/embedders/models/vertexai"></Card>
<Card title="Together" href="/components/embedders/models/together"></Card>
<Card title="LM Studio" href="/components/embedders/models/lmstudio"></Card>
<Card title="Langchain" href="/components/embedders/models/langchain"></Card>
<Card title="AWS Bedrock" href="/components/embedders/models/aws_bedrock"></Card>
<Card title="OpenAI" icon="/images/provider-icons/openai.svg" href="/components/embedders/models/openai"></Card>
<Card title="Azure OpenAI" icon="/images/provider-icons/azure-color.svg" href="/components/embedders/models/azure_openai"></Card>
<Card title="Ollama" icon="/images/provider-icons/ollama.svg" href="/components/embedders/models/ollama"></Card>
<Card title="Hugging Face" icon="/images/provider-icons/huggingface.svg" href="/components/embedders/models/huggingface"></Card>
<Card title="Google AI" icon="/images/provider-icons/google-color.svg" href="/components/embedders/models/google_AI"></Card>
<Card title="Vertex AI" icon="/images/provider-icons/vertexai.svg" href="/components/embedders/models/vertexai"></Card>
<Card title="Together" icon="/images/provider-icons/together-color.svg" href="/components/embedders/models/together"></Card>
<Card title="LM Studio" icon="/images/provider-icons/lmstudio.svg" href="/components/embedders/models/lmstudio"></Card>
<Card title="Langchain" icon="/images/provider-icons/langchain-color.svg" href="/components/embedders/models/langchain"></Card>
<Card title="AWS Bedrock" icon="/images/provider-icons/bedrock-color.svg" href="/components/embedders/models/aws_bedrock"></Card>
<Card title="FastEmbed" icon="/images/provider-icons/qdrant.svg" href="/components/embedders/models/fastembed"></Card>
</CardGroup>
## 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 |
| `top_p` | Probability threshold for nucleus sampling | All |
| `top_k` | Number of highest probability tokens to keep | All |
| `http_client_proxies`| Allow proxy server settings | AzureOpenAI |
| `http_client_proxies`| Allow proxy server settings | All |
| `models` | List of models | Openrouter |
| `route` | Routing strategy | 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 |
| `xai_base_url` | Base URL for XAI API | XAI |
| `sarvam_base_url` | Base URL for Sarvam API | Sarvam |
| `reasoning_effort` | Reasoning level (low, medium, high) | Sarvam |
| `reasoning_effort` | Reasoning level (low, medium, high) | All |
| `frequency_penalty` | Penalize frequent tokens (-2.0 to 2.0) | Sarvam |
| `presence_penalty` | Penalize existing tokens (-2.0 to 2.0) | Sarvam |
| `seed` | Seed for deterministic sampling | Sarvam |
+2 -2
View File
@@ -20,7 +20,7 @@ config = {
"llm": {
"provider": "anthropic",
"config": {
"model": "claude-sonnet-4-20250514",
"model": "claude-sonnet-4-6",
"temperature": 0.1,
"max_tokens": 2000,
}
@@ -45,7 +45,7 @@ const config = {
provider: 'anthropic',
config: {
apiKey: process.env.ANTHROPIC_API_KEY || '',
model: 'claude-sonnet-4-20250514',
model: 'claude-sonnet-4-6',
temperature: 0.1,
maxTokens: 2000,
},
+1 -1
View File
@@ -6,7 +6,7 @@ description: "Configure AWS Bedrock as an LLM provider in Mem0 with IAM authenti
### 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).
- 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`, and `AWS_SECRET_ACCESS_KEY` to set environment variables.
- You will have to export `AWS_REGION`, `AWS_ACCESS_KEY_ID`, and `AWS_SECRET_ACCESS_KEY` to set environment variables.
### Usage
+1 -1
View File
@@ -5,7 +5,7 @@ description: "Configure Azure OpenAI as an LLM provider in Mem0 with Azure Ident
<Note> Mem0 Now Supports Azure OpenAI Models in TypeScript SDK </Note>
To use Azure OpenAI models, you have to set the `LLM_AZURE_OPENAI_API_KEY`, `LLM_AZURE_ENDPOINT`, `LLM_AZURE_DEPLOYMENT` and `LLM_AZURE_API_VERSION` environment variables. You can obtain the Azure API key from the [Azure](https://azure.microsoft.com/).
To use Azure OpenAI models, you have to set the `LLM_AZURE_OPENAI_API_KEY`, `LLM_AZURE_ENDPOINT`, `LLM_AZURE_DEPLOYMENT` and `LLM_AZURE_API_VERSION` environment variables. You can obtain the Azure API key from the [Azure Portal](https://azure.microsoft.com/).
Optionally, you can use Azure Identity to authenticate with Azure OpenAI, which allows you to use managed identities or service principals for production and Azure CLI login for development instead of an API key. If an Azure Identity is to be used, ***do not*** set the `LLM_AZURE_OPENAI_API_KEY` environment variable or the api_key in the config dictionary.
+28 -1
View File
@@ -7,7 +7,8 @@ To use DeepSeek LLM models, you have to set the `DEEPSEEK_API_KEY` environment v
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -36,6 +37,32 @@ messages = [
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'deepseek',
config: {
apiKey: process.env.DEEPSEEK_API_KEY || '',
model: 'deepseek-chat',
temperature: 0.2,
maxTokens: 2000,
top_p: 1.0,
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
];
await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } });
```
</CodeGroup>
You can also configure the API base URL in the config:
```python
+2 -2
View File
@@ -21,7 +21,7 @@ config = {
"llm": {
"provider": "groq",
"config": {
"model": "mixtral-8x7b-32768",
"model": "llama-3.3-70b-versatile",
"temperature": 0.1,
"max_tokens": 2000,
}
@@ -46,7 +46,7 @@ const config = {
provider: 'groq',
config: {
apiKey: process.env.GROQ_API_KEY || '',
model: 'mixtral-8x7b-32768',
model: 'llama3-70b-8192',
temperature: 0.1,
maxTokens: 1000,
},
+31 -1
View File
@@ -4,9 +4,12 @@ description: "Use LiteLLM as an LLM provider in Mem0 to access over 100 language
---
[Litellm](https://litellm.vercel.app/docs/) is compatible with over 100 large language models (LLMs), all using a standardized input/output format. You can explore the [available models](https://litellm.vercel.app/docs/providers) to use with Litellm. Ensure you set the `API_KEY` for the model you choose to use.
In the TypeScript SDK, run LiteLLM as a [proxy server](https://docs.litellm.ai/docs/simple_proxy) (an OpenAI-compatible endpoint) and point Mem0 at it via `LITELLM_API_BASE` (defaults to `http://localhost:4000`).
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -33,6 +36,33 @@ messages = [
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
// Point Mem0 at your LiteLLM proxy. apiKey defaults to "sk-anything"
// (the proxy handles real auth); baseURL defaults to http://localhost:4000.
const config = {
llm: {
provider: 'litellm',
config: {
apiKey: process.env.LITELLM_API_KEY || 'sk-anything',
baseURL: process.env.LITELLM_API_BASE || 'http://localhost:4000',
model: 'gpt-5-mini',
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
];
await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } });
```
</CodeGroup>
## Config
All available parameters for the `litellm` config are present in [Master List of All Params in Config](../config).
+45 -2
View File
@@ -7,7 +7,8 @@ To use MiniMax LLM models, you have to set the `MINIMAX_API_KEY` environment var
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -36,9 +37,37 @@ messages = [
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'minimax',
config: {
apiKey: process.env.MINIMAX_API_KEY || '',
model: 'MiniMax-M2.7',
temperature: 0.2,
maxTokens: 2000,
topP: 1.0,
},
},
};
const memory = new Memory(config);
const messages = [
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
{ role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." },
{ role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." },
];
await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } });
```
</CodeGroup>
You can also configure the API base URL in the config:
```python
<CodeGroup>
```python Python
config = {
"llm": {
"provider": "minimax",
@@ -51,6 +80,20 @@ config = {
}
```
```typescript TypeScript
const config = {
llm: {
provider: 'minimax',
config: {
model: 'MiniMax-M2.7',
baseURL: 'https://your-custom-endpoint.com',
apiKey: 'your-api-key', // alternatively to using the environment variable
},
},
};
```
</CodeGroup>
## Config
All available parameters for the `minimax` config are present in [Master List of All Params in Config](../config).
+29 -1
View File
@@ -9,7 +9,8 @@ To use Sarvam AI's models, please set the `SARVAM_API_KEY` which you can get fro
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -34,8 +35,35 @@ messages = [
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alex")
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'sarvam',
config: {
apiKey: process.env.SARVAM_API_KEY || '',
model: 'sarvam-m',
temperature: 0.7,
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
];
await memory.add(messages, { userId: 'alex' });
```
</CodeGroup>
## Advanced Usage with Sarvam-Specific Features
```python
+64 -6
View File
@@ -1,13 +1,15 @@
---
title: Together
description: "Configure Together AI as an LLM provider in Mem0 with API key setup and Mixtral model configuration."
description: "Configure Together AI as an LLM provider in Mem0 with API key setup and optional custom endpoint configuration."
---
To use Together LLM models, you have to set the `TOGETHER_API_KEY` environment variable. You can obtain the Together API key from their [Account settings page](https://api.together.xyz/settings/api-keys).
To use Together LLM models, you have to set the `TOGETHER_API_KEY` environment variable. You can obtain the Together API key from their [Account settings page](https://api.together.ai/settings/projects/~current/api-keys).
In the TypeScript SDK, you can optionally set `TOGETHER_API_BASE` or pass `baseURL` in the config (defaults to `https://api.together.ai/v1`).
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -18,7 +20,7 @@ config = {
"llm": {
"provider": "together",
"config": {
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
"model": "MiniMaxAI/MiniMax-M3",
"temperature": 0.2,
"max_tokens": 2000,
}
@@ -29,12 +31,68 @@ m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'together',
config: {
apiKey: process.env.TOGETHER_API_KEY || '',
model: 'MiniMaxAI/MiniMax-M3',
temperature: 0.2,
maxTokens: 2000,
},
},
};
const memory = new Memory(config);
const messages = [
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
{ role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." },
{ role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." },
];
await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } });
```
</CodeGroup>
You can also configure the API base URL in the config:
<CodeGroup>
```python Python
config = {
"llm": {
"provider": "together",
"config": {
"model": "MiniMaxAI/MiniMax-M3",
"api_key": "your-api-key"
}
}
}
```
```typescript TypeScript
const config = {
llm: {
provider: "together",
config: {
model: "MiniMaxAI/MiniMax-M3",
baseURL: "https://api.together.ai/v1",
apiKey: "your-api-key",
},
},
};
```
</CodeGroup>
## Config
All available parameters for the `together` config are present in [Master List of All Params in Config](../config).
All available parameters for the `together` config are present in [Master List of All Params in Config](../config).
+42 -1
View File
@@ -25,7 +25,8 @@ description: "Configure vLLM as an LLM provider in Mem0 for high-performance loc
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -53,6 +54,46 @@ messages = [
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from "mem0ai/oss";
const config = {
llm: {
provider: "vllm",
config: {
model: "Qwen/Qwen2.5-32B-Instruct",
baseURL: "http://localhost:8000/v1",
apiKey: process.env.VLLM_API_KEY || "vllm-api-key",
temperature: 0.1,
maxTokens: 2000,
},
},
};
const memory = new Memory(config);
const messages = [
{
role: "user",
content: "I'm planning to watch a movie tonight. Any recommendations?",
},
{
role: "assistant",
content: "How about thriller movies? They can be quite engaging.",
},
{
role: "user",
content: "I'm not a big fan of thrillers, but I love sci-fi movies.",
},
{
role: "assistant",
content: "Got it! I'll avoid thrillers and suggest sci-fi movies instead.",
},
];
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
## Configuration Parameters
| Parameter | Description | Default | Environment Variable |
+29 -3
View File
@@ -5,11 +5,12 @@ description: "Configure xAI Grok models as an LLM provider in Mem0 with API key
[xAI](https://x.ai/) is a new AI company founded by Elon Musk that develops large language models, including Grok. Grok is trained on real-time data from X (formerly Twitter) and aims to provide accurate, up-to-date responses with a touch of wit and humor.
In order to use LLMs from xAI, go to their [platform](https://console.x.ai) and get the API key. Set the API key as `XAI_API_KEY` environment variable to use the model as given below in the example.
In order to use LLMs from xAI, go to their [platform](https://console.x.ai) and get the API key. Set the API key as `XAI_API_KEY` environment variable to use the model as given below in the example. You can also optionally set `XAI_API_BASE` to use a different API endpoint (defaults to `https://api.x.ai/v1`).
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -20,7 +21,7 @@ config = {
"llm": {
"provider": "xai",
"config": {
"model": "grok-3-beta",
"model": "grok-4.3",
"temperature": 0.1,
"max_tokens": 2000,
}
@@ -37,6 +38,31 @@ messages = [
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'xai',
config: {
apiKey: process.env.XAI_API_KEY || '',
model: 'grok-4.3',
temperature: 0.1,
maxTokens: 2000,
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
];
await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } });
```
</CodeGroup>
## Config
All available parameters for the `xai` config are present in [Master List of All Params in Config](../config).
+18 -18
View File
@@ -7,7 +7,7 @@ Mem0 includes built-in support for various popular large language models. Memory
## Usage
To use a llm, you must provide a configuration to customize its usage. If no configuration is supplied, a default configuration will be applied, and `OpenAI` will be used as the llm.
To use an LLM, you must provide a configuration to customize its usage. If no configuration is supplied, a default configuration will be applied, and `OpenAI` will be used as the LLM.
For a comprehensive list of available parameters for llm configuration, please refer to [Config](./config).
@@ -16,26 +16,26 @@ For a comprehensive list of available parameters for llm configuration, please r
See the list of supported LLMs below.
<Note>
All LLMs are supported in Python. The following LLMs are also supported in TypeScript: **OpenAI**, **Anthropic**, and **Groq**.
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**.
</Note>
<CardGroup cols={4}>
<Card title="OpenAI" href="/components/llms/models/openai" />
<Card title="Ollama" href="/components/llms/models/ollama" />
<Card title="Azure OpenAI" href="/components/llms/models/azure_openai" />
<Card title="Anthropic" href="/components/llms/models/anthropic" />
<Card title="Together" href="/components/llms/models/together" />
<Card title="Groq" href="/components/llms/models/groq" />
<Card title="Litellm" href="/components/llms/models/litellm" />
<Card title="Mistral AI" href="/components/llms/models/mistral_AI" />
<Card title="Google AI" href="/components/llms/models/google_AI" />
<Card title="AWS bedrock" href="/components/llms/models/aws_bedrock" />
<Card title="DeepSeek" href="/components/llms/models/deepseek" />
<Card title="MiniMax" href="/components/llms/models/minimax" />
<Card title="xAI" href="/components/llms/models/xAI" />
<Card title="Sarvam AI" href="/components/llms/models/sarvam" />
<Card title="LM Studio" href="/components/llms/models/lmstudio" />
<Card title="Langchain" href="/components/llms/models/langchain" />
<Card title="OpenAI" icon="/images/provider-icons/openai.svg" href="/components/llms/models/openai" />
<Card title="Ollama" icon="/images/provider-icons/ollama.svg" href="/components/llms/models/ollama" />
<Card title="Azure OpenAI" icon="/images/provider-icons/azure-color.svg" href="/components/llms/models/azure_openai" />
<Card title="Anthropic" icon="/images/provider-icons/anthropic.svg" href="/components/llms/models/anthropic" />
<Card title="Together" icon="/images/provider-icons/together-color.svg" href="/components/llms/models/together" />
<Card title="Groq" icon="/images/provider-icons/groq.svg" href="/components/llms/models/groq" />
<Card title="Litellm" icon="shuffle" href="/components/llms/models/litellm" />
<Card title="Mistral AI" icon="/images/provider-icons/mistral-color.svg" href="/components/llms/models/mistral_AI" />
<Card title="Google AI" icon="/images/provider-icons/google-color.svg" href="/components/llms/models/google_AI" />
<Card title="AWS bedrock" icon="/images/provider-icons/bedrock-color.svg" href="/components/llms/models/aws_bedrock" />
<Card title="DeepSeek" icon="/images/provider-icons/deepseek-color.svg" href="/components/llms/models/deepseek" />
<Card title="MiniMax" icon="/images/provider-icons/minimax-color.svg" href="/components/llms/models/minimax" />
<Card title="xAI" icon="/images/provider-icons/xai.svg" href="/components/llms/models/xAI" />
<Card title="Sarvam AI" icon="/images/provider-icons/sarvam.svg" href="/components/llms/models/sarvam" />
<Card title="LM Studio" icon="/images/provider-icons/lmstudio.svg" href="/components/llms/models/lmstudio" />
<Card title="Langchain" icon="/images/provider-icons/langchain-color.svg" href="/components/llms/models/langchain" />
</CardGroup>
## Structured vs Unstructured Outputs
+1 -1
View File
@@ -198,4 +198,4 @@ for i, prompt in enumerate(prompts):
- **Too Long**: Keep prompts under token limits for your chosen LLM
- **Too Vague**: Be specific about scoring criteria
- **Wrong Scale**: Use 0.0-1.0 scale to match the default score extractor
- **Extra Output**: Ask for only the numeric score — extra text can confuse score extraction
- **Extra Output**: Ask for only the numeric score: extra text can confuse score extraction
-226
View File
@@ -1,226 +0,0 @@
---
title: LLM as Reranker
description: "Use any LLM as a flexible reranker in Mem0 with custom prompts and domain-specific scoring logic."
---
<Warning>
**This page has been superseded.** Please see [LLM Reranker](/components/rerankers/models/llm_reranker) for the complete and up-to-date documentation on using LLMs for reranking.
</Warning>
LLM-based reranker provides maximum flexibility by using any Large Language Model to score document relevance. This approach allows for custom prompts and domain-specific scoring logic.
## Supported LLM Providers
Any LLM provider supported by Mem0 can be used for reranking:
- **OpenAI**: GPT-4, GPT-3.5-turbo, etc.
- **Anthropic**: Claude models
- **Together**: Open-source models
- **Groq**: Fast inference
- **Ollama**: Local models
- And more...
## Configuration
```python Python
from mem0 import Memory
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "my_memories",
"path": "./chroma_db"
}
},
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini"
}
},
"reranker": {
"provider": "llm",
"config": {
"model": "gpt-4o-mini",
"provider": "openai",
"api_key": "your-openai-api-key", # or set OPENAI_API_KEY
"top_k": 5,
"temperature": 0.0
}
}
}
memory = Memory.from_config(config)
```
## Custom Scoring Prompt
You can provide a custom prompt for relevance scoring:
```python Python
custom_prompt = """You are a relevance scoring assistant. Rate how well this document answers the query.
Query: "{query}"
Document: "{document}"
Score from 0.0 to 1.0 where:
- 1.0: Perfect match, directly answers the query
- 0.8-0.9: Highly relevant, good match
- 0.6-0.7: Moderately relevant, partial match
- 0.4-0.5: Slightly relevant, limited useful information
- 0.0-0.3: Not relevant or no useful information
Provide only a single numerical score between 0.0 and 1.0."""
config["reranker"]["config"]["scoring_prompt"] = custom_prompt
```
## Usage Example
```python Python
import os
from mem0 import Memory
# Set API key
os.environ["OPENAI_API_KEY"] = "your-api-key"
# Initialize memory with LLM reranker
config = {
"vector_store": {"provider": "chroma"},
"llm": {"provider": "openai", "config": {"model": "gpt-4o-mini"}},
"reranker": {
"provider": "llm",
"config": {
"model": "gpt-4o-mini",
"provider": "openai",
"temperature": 0.0
}
}
}
memory = Memory.from_config(config)
# Add memories
messages = [
{"role": "user", "content": "I'm learning Python programming"},
{"role": "user", "content": "I find object-oriented programming challenging"},
{"role": "user", "content": "I love hiking in national parks"}
]
memory.add(messages, user_id="david")
# Search with LLM reranking
results = memory.search("What programming topics is the user studying?", filters={"user_id": "david"})
for result in results['results']:
print(f"Memory: {result['memory']}")
print(f"Vector Score: {result['score']:.3f}")
print(f"Rerank Score: {result['rerank_score']:.3f}")
print()
```
```text Output
Memory: I'm learning Python programming
Vector Score: 0.856
Rerank Score: 0.920
Memory: I find object-oriented programming challenging
Vector Score: 0.782
Rerank Score: 0.850
```
## Domain-Specific Scoring
Create specialized scoring for your domain:
```python Python
medical_prompt = """You are a medical relevance expert. Score how relevant this medical record is to the clinical query.
Clinical Query: "{query}"
Medical Record: "{document}"
Consider:
- Clinical relevance and accuracy
- Patient safety implications
- Diagnostic value
- Treatment relevance
Score from 0.0 to 1.0. Provide only the numerical score."""
config = {
"reranker": {
"provider": "llm",
"config": {
"model": "gpt-4o-mini",
"provider": "openai",
"scoring_prompt": medical_prompt,
"temperature": 0.0
}
}
}
```
## Multiple LLM Providers
Use different LLM providers for reranking:
```python Python
# Using Anthropic Claude
anthropic_config = {
"reranker": {
"provider": "llm",
"config": {
"model": "claude-3-haiku-20240307",
"provider": "anthropic",
"temperature": 0.0
}
}
}
# Using local Ollama model
ollama_config = {
"reranker": {
"provider": "llm",
"config": {
"model": "llama2:7b",
"provider": "ollama",
"temperature": 0.0
}
}
}
```
## Configuration Parameters
| Parameter | Description | Type | Default |
|-----------|-------------|------|---------|
| `model` | LLM model to use for scoring | `str` | `"gpt-4o-mini"` |
| `provider` | LLM provider name | `str` | `"openai"` |
| `api_key` | API key for the LLM provider | `str` | `None` |
| `top_k` | Maximum documents to return | `int` | `None` |
| `temperature` | Temperature for LLM generation | `float` | `0.0` |
| `max_tokens` | Maximum tokens for LLM response | `int` | `100` |
| `scoring_prompt` | Custom prompt template | `str` | Default prompt |
## Advantages
- **Maximum Flexibility**: Custom prompts for any use case
- **Domain Expertise**: Leverage LLM knowledge for specialized domains
- **Interpretability**: Understand scoring through prompt engineering
- **Multi-criteria**: Score based on multiple relevance factors
## Considerations
- **Latency**: Higher latency than specialized rerankers
- **Cost**: LLM API costs per reranking operation
- **Consistency**: May have slight variations in scoring
- **Prompt Engineering**: Requires careful prompt design
## Best Practices
1. **Temperature**: Use 0.0 for consistent scoring
2. **Prompt Design**: Be specific about scoring criteria
3. **Token Efficiency**: Keep prompts concise to reduce costs
4. **Caching**: Cache results for repeated queries when possible
5. **Fallback**: Handle API errors gracefully
+16 -4
View File
@@ -9,6 +9,18 @@ Mem0 rerankers rescore vector search hits so your agents surface the most releva
Reranking trades extra latency for better precision. Start once you have baseline search working and measure before/after relevance.
</Info>
## Supported Rerankers
<CardGroup cols={3}>
<Card title="Cohere" icon="/images/provider-icons/cohere.svg" href="/components/rerankers/models/cohere" />
<Card title="Sentence Transformers" icon="vector-square" href="/components/rerankers/models/sentence_transformer" />
<Card title="Hugging Face" icon="/images/provider-icons/huggingface.svg" href="/components/rerankers/models/huggingface" />
<Card title="LLM Reranker" icon="wand-magic-sparkles" href="/components/rerankers/models/llm_reranker" />
<Card title="Zero Entropy" icon="/images/provider-icons/zeroentropy.svg" href="/components/rerankers/models/zero_entropy" />
</CardGroup>
## Reranking Workflow
<CardGroup cols={3}>
<Card
title="Understand Reranking"
@@ -19,13 +31,13 @@ Reranking trades extra latency for better precision. Start once you have baselin
<Card
title="Configure Providers"
description="Add reranker blocks to your memory configuration."
icon="settings"
icon="gear"
href="/components/rerankers/config"
/>
<Card
title="Optimize Performance"
description="Balance relevance, latency, and cost with tuning tactics."
icon="speedometer"
icon="gauge"
href="/components/rerankers/optimization"
/>
<Card
@@ -43,7 +55,7 @@ Reranking trades extra latency for better precision. Start once you have baselin
<Card
title="Sentence Transformers"
description="Keep reranking on-device with cross-encoder models."
icon="cpu"
icon="microchip"
href="/components/rerankers/models/sentence_transformer"
/>
</CardGroup>
@@ -66,7 +78,7 @@ Reranking trades extra latency for better precision. Start once you have baselin
<Card
title="Set Up Reranking"
description="Walk through the configuration fields and defaults."
icon="settings"
icon="gear"
href="/components/rerankers/config"
/>
<Card
+4 -4
View File
@@ -81,13 +81,13 @@ Azure client ID, secret, tenant ID, or certificate in environment variables for
Utilizes Azure Workload Identity (relevant for Kubernetes and Azure workloads).
3. **Managed Identity Credential:**
Authenticates as a Managed Identity (for apps/services hosted in Azure with Managed Identity enabled), this is the most secure production credential.
Authenticates as a Managed Identity (for apps/services hosted in Azure with Managed Identity enabled); this is the most secure production credential.
4. **Shared Token Cache Credential / Visual Studio Credential (Windows only):**
Uses cached credentials from Visual Studio sign-ins (and sometimes VS Code if SSO is enabled).
5. **Azure CLI Credential:**
Uses the currently logged-in user from the Azure CLI (`az login`), this is the most common development credential.
Uses the currently logged-in user from the Azure CLI (`az login`); this is the most common development credential.
6. **Azure PowerShell Credential:**
Uses the identity from Azure PowerShell (`Connect-AzAccount`).
@@ -100,7 +100,7 @@ To enable Role-Based Access Control (RBAC) for Azure AI Search, follow these ste
1. In the Azure Portal, navigate to your **Azure AI Search** service.
2. In the left menu, select **Settings** > **Keys**.
3. Change the authentication setting to **Role-based access control**, or **Both** if you need API key compatibility. The default is “Key-based authentication”—you must switch it to use Azure roles.
3. Change the authentication setting to **Role-based access control**, or **Both** if you need API key compatibility. The default is “Key-based authentication”: you must switch it to use Azure roles.
4. **Go to Access Control (IAM):**
- In the Azure Portal, select your Search service.
- Click **Access Control (IAM)** on the left.
@@ -135,7 +135,7 @@ config = {
```
### Environment Variables to Use Azure Identity Credential
* For an Environment Credential, you will need to setup a Service Principal and set the following environment variables:
* For an Environment Credential, you will need to set up a Service Principal and set the following environment variables:
- `AZURE_TENANT_ID`: Your Azure Active Directory tenant ID.
- `AZURE_CLIENT_ID`: The client ID of your service principal or managed identity.
- `AZURE_CLIENT_SECRET`: The client secret of your service principal.
+1 -1
View File
@@ -46,7 +46,7 @@ Here are the parameters available for configuring Baidu VectorDB:
| `account` | Baidu VectorDB account name | `root` |
| `api_key` | API key for accessing Baidu VectorDB | Required |
| `database_name` | Name of the database | `mem0` |
| `table_name` | Name of the table | `mem0_table` |
| `table_name` | Name of the table | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `metric_type` | Distance metric for similarity search | `L2` |
+89 -7
View File
@@ -7,7 +7,8 @@ description: "Use Apache Cassandra as a distributed vector store in Mem0 with se
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -37,11 +38,43 @@ messages = [
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
// Set OPENAI_API_KEY in your environment for the default embedder
const config = {
vectorStore: {
provider: 'cassandra',
config: {
contactPoints: ['127.0.0.1'],
localDataCenter: 'datacenter1', // required with contactPoints; "datacenter1" is the default for a single-node cluster
port: 9042,
username: 'cassandra',
password: 'cassandra',
keyspace: 'mem0',
collectionName: 'memories',
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
#### Using DataStax Astra DB
For managed Cassandra with DataStax Astra DB:
```python
<CodeGroup>
```python Python
config = {
"vector_store": {
"provider": "cassandra",
@@ -57,8 +90,24 @@ config = {
}
```
```typescript TypeScript
const config = {
vectorStore: {
provider: 'cassandra',
config: {
username: 'token',
password: 'AstraCS:...', // Your Astra DB application token
keyspace: 'mem0',
collectionName: 'memories',
secureConnectBundle: '/path/to/secure-connect-bundle.zip',
},
},
};
```
</CodeGroup>
<Note>
When using DataStax Astra DB, provide the secure connect bundle path. The contact_points parameter is ignored when a secure connect bundle is provided.
When using DataStax Astra DB, provide the secure connect bundle path. Contact points and `localDataCenter` are not needed when a secure connect bundle is provided.
</Note>
### Config
@@ -78,6 +127,10 @@ Here are the parameters available for configuring Apache Cassandra:
| `protocol_version` | CQL protocol version | `4` |
| `load_balancing_policy` | Custom load balancing policy | `None` |
<Note>
The TypeScript SDK uses camelCase keys: `contactPoints`, `collectionName`, `embeddingModelDims`, `secureConnectBundle`, `protocolVersion`, and `loadBalancingPolicy`. It also requires `localDataCenter` (for example, `datacenter1`) when you connect with `contactPoints` instead of a secure connect bundle. The Node.js driver needs this to route queries; it has no default.
</Note>
### Setup
#### Option 1: Local Cassandra Setup using Docker:
@@ -139,14 +192,20 @@ brew services start cassandra
cqlsh
```
### Python Client Installation
### Client Installation
Install the required Python package:
Install the driver for your SDK:
```bash
<CodeGroup>
```bash Python
pip install cassandra-driver
```
```bash TypeScript
npm install cassandra-driver
```
</CodeGroup>
### Performance Considerations
- **Replication Factor**: For production, use replication factor of at least 3
@@ -156,7 +215,8 @@ pip install cassandra-driver
### Advanced Configuration
```python
<CodeGroup>
```python Python
from cassandra.policies import DCAwareRoundRobinPolicy
config = {
@@ -176,6 +236,28 @@ config = {
}
```
```typescript TypeScript
// The Node.js driver routes to localDataCenter by default, so set it to your
// primary DC for datacenter-aware routing. Pass loadBalancingPolicy only when
// you need a custom policy from the cassandra-driver package.
const config = {
vectorStore: {
provider: 'cassandra',
config: {
contactPoints: ['node1.example.com', 'node2.example.com', 'node3.example.com'],
localDataCenter: 'DC1',
port: 9042,
username: 'mem0_user',
password: 'secure_password',
keyspace: 'mem0_prod',
collectionName: 'memories',
protocolVersion: 4,
},
},
};
```
</CodeGroup>
<Warning>
For production use, configure appropriate replication strategies and consistency levels based on your availability and consistency requirements.
</Warning>
+54 -4
View File
@@ -6,9 +6,8 @@ description: "Use Chroma as a vector database in Mem0 for local or cloud-hosted
### Usage
#### Local Installation
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -37,10 +36,46 @@ messages = [
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
// The Node.js client connects to a running Chroma server.
// Start one locally with: chroma run --host localhost --port 8000
const config = {
vectorStore: {
provider: 'chroma',
config: {
collectionName: 'memories',
host: 'localhost',
port: 8000,
// Optional: ChromaDB Cloud configuration
// apiKey: 'your-chroma-cloud-api-key',
// tenant: 'your-chroma-cloud-tenant-id',
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
<Note>
The Node.js SDK uses the `chromadb` v3 client, which talks to a Chroma server over HTTP (local server or ChromaDB Cloud). Install it with `npm install chromadb`. Mem0 supplies the embeddings, so the collection is created without an embedding function.
</Note>
### Config
Here are the parameters available for configuring Chroma:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection | `mem0` |
@@ -49,4 +84,19 @@ Here are the parameters available for configuring Chroma:
| `host` | The host where the Chroma server is running | `None` |
| `port` | The port where the Chroma server is running | `None` |
| `api_key` | ChromaDB Cloud API key (for cloud usage) | `None` |
| `tenant` | ChromaDB Cloud tenant ID (for cloud usage) | `None` |
| `tenant` | ChromaDB Cloud tenant ID (for cloud usage) | `None` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collectionName` | The name of the collection | `mem0` |
| `client` | Pre-configured `ChromaClient` or `CloudClient` instance | `None` |
| `host` | The host where the Chroma server is running | `None` |
| `port` | The port where the Chroma server is running | `None` |
| `ssl` | Whether to use SSL when connecting to the Chroma server | `false` |
| `path` | Full URL of a Chroma server, e.g. `http://localhost:8000` (alternative to `host` and `port`) | `None` |
| `apiKey` | ChromaDB Cloud API key (for cloud usage) | `None` |
| `tenant` | ChromaDB Cloud tenant ID (for cloud usage) | `None` |
| `database` | ChromaDB Cloud database name (for cloud usage) | `mem0` |
</Tab>
</Tabs>
@@ -6,15 +6,22 @@ description: "Use Elasticsearch as a vector database in Mem0 for distributed vec
### Installation
Elasticsearch support requires additional dependencies. Install them with:
Elasticsearch support requires the Elasticsearch client as an extra dependency.
```bash
<CodeGroup>
```bash Python
pip install elasticsearch>=8.0.0
```
```bash TypeScript
npm install mem0ai @elastic/elasticsearch
```
</CodeGroup>
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -36,12 +43,52 @@ m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from "mem0ai/oss";
// Set OPENAI_API_KEY in your environment.
const config = {
embedder: {
provider: "openai",
config: {
apiKey: process.env.OPENAI_API_KEY,
model: "text-embedding-3-small",
},
},
vectorStore: {
provider: "elasticsearch",
config: {
collectionName: "mem0",
embeddingModelDims: 1536,
host: "localhost",
port: 9200,
// For Elastic Cloud, pass cloudId and apiKey instead of host/port.
// For basic auth, pass username and password.
},
},
};
const memory = new Memory(config);
const messages = [
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
{ role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." },
{ role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." },
];
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
<Note>
The TypeScript SDK uses camelCase config keys: `collectionName`, `embeddingModelDims`, `cloudId`, `apiKey`, `useSsl`, `verifyCerts`, `caCerts`, `autoCreateIndex`, and `username` (in place of the Python `user`). `collectionName` and `embeddingModelDims` are required. Because the vector store embeds text with your configured embedder before writing, set an `embedder` in the config as shown above.
</Note>
### Config
Here are the parameters available for configuring Elasticsearch:
@@ -56,6 +103,8 @@ Here are the parameters available for configuring Elasticsearch:
| `api_key` | API key for authentication | `None` |
| `user` | Username 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` |
| `auto_create_index` | Whether to automatically create the index | `True` |
| `custom_search_query` | Function returning a custom search query | `None` |
@@ -72,6 +121,10 @@ Here are the parameters available for configuring Elasticsearch:
### Custom Search Query
<Note>
`custom_search_query` is available in the Python SDK only. The TypeScript SDK runs a fixed k-NN query with optional metadata filters.
</Note>
The `custom_search_query` parameter allows you to customize the search query when `Memory.search` is called.
__Example__
+1
View File
@@ -55,6 +55,7 @@ Here are the parameters available for configuring FAISS:
| `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` |
| `normalize_L2` | Whether to normalize L2 vectors (only applicable for euclidean distance) | `False` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
### Performance Considerations
+3 -3
View File
@@ -47,12 +47,12 @@ m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from "mem0ai";
import { Memory } from "mem0ai/oss";
import { OpenAIEmbeddings } from "@langchain/openai";
import { MemoryVectorStore as LangchainMemoryStore } from "langchain/vectorstores/memory";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
const embeddings = new OpenAIEmbeddings();
const vectorStore = new LangchainVectorStore(embeddings);
const vectorStore = new MemoryVectorStore(embeddings);
const config = {
"vector_store": {
+49 -1
View File
@@ -6,7 +6,14 @@ description: "Use Milvus as an open-source vector database in Mem0, scalable fro
### Usage
```python
The TypeScript SDK loads the Milvus client lazily. Install it alongside `mem0ai` when you use this provider:
```bash
npm install @zilliz/milvus2-sdk-node
```
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -33,10 +40,39 @@ messages = [
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
vectorStore: {
provider: 'milvus',
config: {
collectionName: 'test',
embeddingModelDims: 1536,
url: 'http://localhost:19530',
token: '8e4b8ca8cf2c67',
dbName: 'my_database',
},
},
};
const memory = new Memory(config);
const messages = [
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
{ role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." },
{ role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." },
];
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
### Config
Here are the parameters available for configuring Milvus:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `url` | Full URL/Uri for Milvus/Zilliz server | `http://localhost:19530` |
@@ -45,3 +81,15 @@ Here are the parameters available for configuring Milvus:
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `metric_type` | Metric type for similarity search | `L2` |
| `db_name` | Name of the database | `""` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `url` | Full URL/Uri for Milvus/Zilliz server | `http://localhost:19530` |
| `token` | Token for Zilliz Cloud (optional for a local setup) | `undefined` |
| `collectionName` | The name of the collection | `mem0` |
| `embeddingModelDims` | Dimensions of the embedding model | `1536` |
| `metricType` | Metric type for similarity search (`L2`, `IP`, `COSINE`, `HAMMING`, `JACCARD`) | `L2` |
| `dbName` | Name of the database | `undefined` |
</Tab>
</Tabs>
+75 -13
View File
@@ -2,13 +2,15 @@
title: "MongoDB"
description: "Use MongoDB as a vector database in Mem0 with built-in vector search for high-dimensional similarity queries."
---
# MongoDB
[MongoDB](https://www.mongodb.com/) is a versatile document database that supports vector search capabilities, allowing for efficient high-dimensional similarity searches over large datasets with robust scalability and performance.
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -20,30 +22,90 @@ config = {
"config": {
"db_name": "mem0-db",
"collection_name": "mem0-collection",
"mongo_uri":"mongodb://username:password@localhost:27017"
"mongo_uri": "mongodb://username:password@localhost:27017"
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
{
"role": "user",
"content": "I'm planning to watch a movie tonight. Any recommendations?",
},
{
"role": "assistant",
"content": "How about thriller movies? They can be quite engaging.",
},
{
"role": "user",
"content": "I’m not a big fan of thriller movies but I love sci-fi movies.",
},
{
"role": "assistant",
"content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future.",
},
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from "mem0ai/oss";
const config = {
vectorStore: {
provider: "mongodb",
config: {
dbName: "mem0-db",
collectionName: "mem0-collection",
url: "mongodb://username:password@localhost:27017",
},
},
};
const memory = new Memory(config);
const messages = [
{
role: "user",
content: "I'm planning to watch a movie tonight. Any recommendations?",
},
{
role: "assistant",
content: "How about thriller movies? They can be quite engaging.",
},
{
role: "user",
content: "I’m not a big fan of thriller movies but I love sci-fi movies.",
},
{
role: "assistant",
content:
"Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future.",
},
];
await memory.add(messages, {
userId: "alice",
metadata: {
category: "movies",
},
});
```
</CodeGroup>
## Config
Here are the parameters available for configuring MongoDB:
| Parameter | Description | Default Value |
| --- | --- | --- |
| db_name | Name of the MongoDB database | `"mem0_db"` |
| collection_name | Name of the MongoDB collection | `"mem0_collection"` |
| embedding_model_dims | Dimensions of the embedding vectors | `1536` |
| mongo_uri | The MongoDB URI connection string | `mongodb://username:password@localhost:27017` |
| Python | TypeScript | Description | Default Value |
| --- | --- | --- | --- |
| db_name | dbName | Name of the MongoDB database | "mem0_db" |
| collection_name | collectionName | Name of the MongoDB collection | "mem0" |
| embedding_model_dims | embeddingModelDims | Dimensions of the embedding vectors | 1536 |
| mongo_uri | url | The MongoDB URI connection string | mongodb://localhost:27017 |
> **Note**: If `mongo_uri` is not provided, it will default to `mongodb://username:password@localhost:27017`.
> **Note**: If `mongo_uri` (Python) or `url` (TypeScript) is not provided, it defaults to `mongodb://localhost:27017`. A local instance must be running MongoDB v8.2+ for vector search to work.
> **Note**: The vector search index builds asynchronously after the first write. A search issued right after the first `add()` may return no results (and log an "index not initialized" message) until the index finishes building. This takes a few seconds on a local deployment and up to about a minute on Atlas. This is expected; the search returns results once the index is ready.
+17 -20
View File
@@ -53,17 +53,14 @@ print(results)
import "dotenv/config";
import { Memory } from "mem0ai/oss";
const databaseUrl = new URL(process.env.DATABASE_URL!);
const m = new Memory({
vectorStore: {
provider: "pgvector",
config: {
user: decodeURIComponent(databaseUrl.username),
password: decodeURIComponent(databaseUrl.password),
host: databaseUrl.hostname,
port: Number(databaseUrl.port || 5432),
dbname: databaseUrl.pathname.slice(1) || "neondb",
connectionString: process.env.DATABASE_URL!,
ssl: {
rejectUnauthorized: false,
},
collectionName: "memories",
dimension: 1536,
embeddingModelDims: 1536,
@@ -90,6 +87,7 @@ const results = await m.search("What movies should I recommend?", {
console.log(results);
```
</CodeGroup>
## SQL Migration
@@ -116,20 +114,19 @@ DATABASE_URL=postgresql://user:password@ep-example.us-east-2.aws.neon.tech/neond
| `sslmode` | PostgreSQL SSL mode. Use `require` for Neon. | Driver default |
</Tab>
<Tab title="TypeScript">
The current Mem0 TypeScript `pgvector` adapter takes individual Postgres fields,
so parse `DATABASE_URL` before creating `Memory`.
Use the Neon `DATABASE_URL` directly with `connectionString`. Set `ssl` if your runtime needs an explicit TLS config object.
| Parameter | Description | Default |
| -------------------- | ---------------------------------------------- | -------------- |
| `connectionString` | Neon Postgres connection string. | Required |
| `ssl` | Optional TLS settings passed directly to `pg`. | Driver default |
| `collectionName` | Name for the vector collection. | `memories` |
| `dimension` | Vector dimension for Mem0 config. | Auto-detected |
| `embeddingModelDims` | Embedding model dimensions for table creation. | Required |
| `hnsw` | Enables HNSW indexing. | `false` |
**TLS note:** `ssl: true` is sufficient for most Neon connections since Neon uses valid certificates. Use `ssl: { rejectUnauthorized: false }` only when connecting through Neon's connection pooler on certain edge runtimes (e.g. Cloudflare Workers) that require it, or when your environment does not trust the Neon CA chain.
| Parameter | Description | Default |
| --- | --- | --- |
| `user` | Database user. | Required |
| `password` | Database password. | Required |
| `host` | Database host. | Required |
| `port` | Database port. | `5432` |
| `dbname` | Database name. | `vector_store` |
| `collectionName` | Name for the vector collection. | `memories` |
| `dimension` | Vector dimension for Mem0 config. | Auto-detected |
| `embeddingModelDims` | Embedding model dimensions for table creation. | Required |
| `hnsw` | Enables HNSW indexing. | `false` |
</Tab>
</Tabs>
@@ -10,7 +10,7 @@ description: "Use AWS Neptune Analytics as a vector store in Mem0, combining gra
## Installation
```bash
pip install mem0ai[vector_stores]
pip install mem0ai[vector-stores]
```
## Usage
+62 -3
View File
@@ -6,12 +6,18 @@ description: "Use OpenSearch as a vector database in Mem0 with k-NN search suppo
### Installation
OpenSearch support requires additional dependencies. Install them with:
OpenSearch support requires an additional client library. Install the one for your SDK:
```bash
<CodeGroup>
```bash Python
pip install opensearch-py
```
```bash TypeScript
npm install @opensearch-project/opensearch
```
</CodeGroup>
### Prerequisites
Before using OpenSearch with Mem0, you need to set up a collection in AWS OpenSearch Service.
@@ -26,7 +32,8 @@ You can create a collection through the AWS Console:
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
import boto3
@@ -56,8 +63,43 @@ config = {
}
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
// Basic self-hosted OpenSearch. For AWS OpenSearch Serverless, build an
// @opensearch-project/opensearch Client with AwsSigv4Signer and pass it as
// `client` instead of host/port/user/password.
const config = {
vectorStore: {
provider: 'opensearch',
config: {
collectionName: 'mem0',
embeddingModelDims: 1024,
host: 'localhost',
port: 9200,
user: 'admin',
password: 'admin',
useSSL: false,
verifyCerts: false,
},
},
};
const memory = new Memory(config);
const messages = [
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
{ role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." },
{ role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." },
];
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
### Configuration Options
<Tabs>
<Tab title="Python">
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `collection_name` | string | required | Name of the OpenSearch index |
@@ -68,6 +110,23 @@ config = {
| `use_ssl` | bool | False | Enable SSL/TLS connection |
| `verify_certs` | bool | False | Verify SSL certificates |
| `auto_refresh` | bool | False | Automatically refresh index after insert. OpenSearch refreshes every ~1 second by default, so this is rarely needed. |
</Tab>
<Tab title="TypeScript">
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `collectionName` | string | required | Name of the OpenSearch index |
| `embeddingModelDims` | number | 1536 | Dimension of embedding vectors |
| `host` | string | `localhost` | OpenSearch endpoint host |
| `port` | number | 9200 | Port number |
| `httpAuth` | object | None | Authentication credentials, an object or `[user, password]` tuple |
| `user` | string | None | Username for basic auth (used together with `password`) |
| `password` | string | None | Password for basic auth (used together with `user`) |
| `useSSL` | boolean | false | Enable SSL/TLS connection |
| `verifyCerts` | boolean | false | Verify SSL certificates |
| `autoRefresh` | boolean | false | Refresh the index after each write so new memories are searchable immediately. Not supported on AWS Serverless. |
| `client` | object | None | Preconfigured OpenSearch client, e.g. one built with AwsSigv4Signer for AWS auth |
</Tab>
</Tabs>
<Note>
The defaults above match a local OpenSearch instance. The AWS OpenSearch Serverless
+37 -32
View File
@@ -2,6 +2,7 @@
title: "pgvector"
description: "Use pgvector as a vector store in Mem0 for PostgreSQL-based vector similarity search with open-source simplicity."
---
[pgvector](https://github.com/pgvector/pgvector) is an open-source vector similarity search extension for Postgres. After connecting to Postgres, run `CREATE EXTENSION IF NOT EXISTS vector;` to create the vector extension.
### Usage
@@ -21,7 +22,7 @@ config = {
"password": "123",
"host": "127.0.0.1",
"port": "5432",
}
},
}
}
@@ -30,25 +31,22 @@ messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."},
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
import { Memory } from "mem0ai/oss";
const config = {
vectorStore: {
provider: 'pgvector',
provider: "pgvector",
config: {
collectionName: 'memories',
collectionName: "memories",
embeddingModelDims: 1536,
user: 'test',
password: '123',
host: '127.0.0.1',
port: 5432,
dbname: 'vector_store', // Optional; TypeScript OSS defaults to `vector_store` when omitted
connectionString: "postgresql://test:123@localhost:5432/vector_store",
diskann: false, // Optional, requires pgvectorscale extension
hnsw: false, // Optional, for HNSW indexing
},
@@ -57,37 +55,44 @@ const config = {
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
{ role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." },
{ role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." },
];
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
### Config
Here are the parameters available for configuring pgvector:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `dbname` | The name of the database | `postgres` |
| `collection_name` | The name of the collection | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `user` | User name to connect to the database | `None` |
| `password` | Password to connect to the database | `None` |
| `host` | The host where the Postgres server is running | `None` |
| `port` | The port where the Postgres server is running | `None` |
| `diskann` | Whether to use diskann for vector similarity search (requires pgvectorscale) | `True` |
| `hnsw` | Whether to use hnsw for vector similarity search | `False` |
| `sslmode` | SSL mode for PostgreSQL connection (e.g., 'require', 'prefer', 'disable') | `None` |
| `connection_string` | PostgreSQL connection string (overrides individual connection parameters) | `None` |
| `connection_pool` | psycopg2 connection pool object (overrides connection string and individual parameters) | `None` |
| Parameter | SDK | Description | Default Value |
| -------------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |
| `connectionString` | TypeScript OSS | PostgreSQL connection string for direct connections. When set, Mem0 connects to the target database directly and skips the bootstrap `postgres` database flow. | `None` |
| `ssl` | TypeScript OSS | SSL option passed directly to `pg`, either `true` or an SSL config object, for both `connectionString` and split-field connections. | `None` |
| `dbname` | TypeScript OSS | Split-field database name. This is only used when `connectionString` is absent. | `vector_store` |
| `collectionName` | TypeScript OSS | Collection name. | `memories` |
| `embeddingModelDims` | TypeScript OSS | Dimensions of the embedding model. | Required |
| `user` | TypeScript OSS + Python | Database user for split-field connections. | `None` |
| `password` | TypeScript OSS + Python | Database password for split-field connections. | `None` |
| `host` | TypeScript OSS + Python | Database host for split-field connections. | `None` |
| `port` | TypeScript OSS + Python | Database port for split-field connections. | `None` |
| `diskann` | TypeScript OSS + Python | Whether to use DiskANN for vector similarity search, requires pgvectorscale. | `False` |
| `hnsw` | TypeScript OSS + Python | Whether to use HNSW for vector similarity search. | TypeScript OSS: `False`, Python: `True` |
| `connection_string` | Python only | PostgreSQL connection string, overrides individual connection parameters. | `None` |
| `sslmode` | Python only | SSL mode for PostgreSQL connections, such as `require`, `prefer`, or `disable`. | `None` |
| `connection_pool` | Python only | psycopg connection pool object, overrides connection string and individual connection parameters. | `None` |
**Note (TypeScript OSS):** If you omit `dbname`, the TypeScript client uses the database name `vector_store`. Python defaults to `postgres` for `dbname`, as in the table above.
**TypeScript OSS:** Use `connectionString` plus optional `ssl` for managed Postgres setups. If you omit `connectionString`, Mem0 falls back to split fields and uses `dbname`, `user`, `password`, `host`, `port`, and optional `ssl`.
**Python:** The Python SDK uses snake_case keys such as `connection_string`, `sslmode`, `collection_name`, and `embedding_model_dims`.
**Python connection priority**:
**Note**: The connection parameters have the following priority:
1. `connection_pool` (highest priority)
2. `connection_string`
3. Individual connection parameters (`user`, `password`, `host`, `port`, `sslmode`)
3. Individual connection parameters (`user`, `password`, `host`, `port`, `sslmode`)
+93 -4
View File
@@ -10,7 +10,8 @@ description: "Use Pinecone as a fully managed vector database in Mem0 with serve
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -44,10 +45,43 @@ messages = [
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
// Set OPENAI_API_KEY and PINECONE_API_KEY in your environment
const config = {
vectorStore: {
provider: 'pinecone',
config: {
collectionName: 'testing',
embeddingModelDims: 1536, // Matches OpenAI's text-embedding-3-small
namespace: 'my-namespace', // Optional: specify a namespace for multi-tenancy
serverlessConfig: {
cloud: 'aws', // 'aws' | 'gcp' | 'azure'
region: 'us-east-1',
},
metric: 'cosine',
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
### Config
Here are the parameters available for configuring Pinecone:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | Name of the index/collection | Required |
@@ -61,11 +95,28 @@ Here are the parameters available for configuring Pinecone:
| `metric` | Distance metric for vector similarity | `"cosine"` |
| `batch_size` | Batch size for operations | `100` |
| `namespace` | Namespace for the collection, useful for multi-tenancy. | `None` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collectionName` | Name of the index/collection | Required |
| `embeddingModelDims` | Dimensions of the embedding model (must match your chosen embedding model) | `1536` |
| `client` | Existing Pinecone client instance | `undefined` |
| `apiKey` | API key for Pinecone | Environment variable: `PINECONE_API_KEY` |
| `serverlessConfig` | Configuration for serverless deployment (`cloud`, `region`) | `undefined` |
| `podConfig` | Configuration for pod-based deployment (`environment`, `podType`, `pods`, `replicas`, `shards`) | `undefined` |
| `metric` | Distance metric for vector similarity (`cosine`, `dotproduct`, `euclidean`) | `"cosine"` |
| `batchSize` | Batch size for insert operations | `100` |
| `namespace` | Namespace for the collection, useful for multi-tenancy. | `undefined` |
| `extraParams` | Extra parameters spread into the Pinecone `createIndex` call | `{}` |
</Tab>
</Tabs>
> **Important**: You must choose either `serverless_config` or `pod_config` for your deployment, but not both.
#### Serverless Config Example
```python
<CodeGroup>
```python Python
config = {
"vector_store": {
"provider": "pinecone",
@@ -82,8 +133,27 @@ config = {
}
```
```typescript TypeScript
const config = {
vectorStore: {
provider: 'pinecone',
config: {
collectionName: 'memory_index',
embeddingModelDims: 1536, // For OpenAI's text-embedding-3-small
namespace: 'my-namespace', // Optional: custom namespace
serverlessConfig: {
cloud: 'aws', // 'gcp' | 'azure'
region: 'us-east-1', // Choose appropriate region
},
},
},
};
```
</CodeGroup>
#### Pod Config Example
```python
<CodeGroup>
```python Python
config = {
"vector_store": {
"provider": "pinecone",
@@ -99,4 +169,23 @@ config = {
}
}
}
```
```
```typescript TypeScript
const config = {
vectorStore: {
provider: 'pinecone',
config: {
collectionName: 'memory_index',
embeddingModelDims: 1536, // For OpenAI's text-embedding-ada-002
namespace: 'my-namespace', // Optional: custom namespace
podConfig: {
environment: 'gcp-starter',
replicas: 1,
podType: 'starter',
},
},
},
};
```
</CodeGroup>
+39 -2
View File
@@ -9,15 +9,22 @@ description: "Use Amazon S3 Vectors as a cost-optimized vector storage service i
S3 Vectors support requires additional dependencies. Install them with:
```bash
<CodeGroup>
```bash Python
pip install boto3
```
```bash TypeScript
npm install @aws-sdk/client-s3vectors
```
</CodeGroup>
### Usage
To use Amazon S3 Vectors with Mem0, you need to have an AWS account and the necessary IAM permissions (`s3vectors:*`). Ensure your environment is configured with AWS credentials (e.g., via `~/.aws/credentials` or environment variables).
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -47,6 +54,36 @@ messages = [
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
// Ensure your AWS credentials are configured in your environment
// e.g., by setting AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_DEFAULT_REGION
const config = {
vectorStore: {
provider: 's3_vectors',
config: {
vectorBucketName: 'my-mem0-vector-bucket',
collectionName: 'my-memories-index',
embeddingModelDims: 1536,
distanceMetric: 'cosine',
region: 'us-east-1',
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movie? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
### Config
Here are the parameters available for configuring Amazon S3 Vectors:
+54 -2
View File
@@ -6,7 +6,8 @@ description: "Use Turbopuffer as a serverless vector database in Mem0 for low-la
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -39,6 +40,36 @@ m.add(messages, user_id="alice", metadata={"category": "movies"})
results = m.search(query="sci-fi recommendations", filters={"user_id": "alice"})
```
```typescript TypeScript
import { Memory } from "mem0ai/oss";
// Set TURBOPUFFER_API_KEY in your environment, or pass it as config.apiKey below.
const config = {
vectorStore: {
provider: "turbopuffer",
config: {
collectionName: "movie_preferences",
region: "gcp-us-central1",
},
},
};
const memory = new Memory(config);
const messages = [
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
{ role: "user", content: "I'm not a big fan of thrillers but I love sci-fi." },
{ role: "assistant", content: "Got it! I'll suggest sci-fi movies instead." },
];
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
// Search memories
const results = await memory.search("sci-fi recommendations", { userId: "alice" });
```
</CodeGroup>
### Config
Here are the parameters available for configuring Turbopuffer:
@@ -53,6 +84,10 @@ Here are the parameters available for configuring Turbopuffer:
| `batch_size` | Batch size for bulk operations | `100` |
| `extra_params` | Additional parameters for the Turbopuffer client | `None` |
<Note>
**TypeScript (Node.js) config keys** are camelCase: `collectionName`, `apiKey`, `region`, `distanceMetric`, and `batchSize`. The TypeScript SDK infers the vector dimension from your embedder, so `embeddingModelDims` is not required.
</Note>
### Regions
| Region | Location |
@@ -62,7 +97,8 @@ Here are the parameters available for configuring Turbopuffer:
### Config Example
```python
<CodeGroup>
```python Python
config = {
"vector_store": {
"provider": "turbopuffer",
@@ -77,3 +113,19 @@ config = {
}
}
```
```typescript TypeScript
const config = {
vectorStore: {
provider: "turbopuffer",
config: {
collectionName: "my_memories",
apiKey: "tpuf_xxxxxxxxxxxx",
region: "aws-us-west-2",
distanceMetric: "cosine_distance",
batchSize: 200,
},
},
};
```
</CodeGroup>
@@ -8,6 +8,10 @@ description: "Use Upstash Vector as a serverless vector database in Mem0 with op
You can enable the built-in embedding models by setting `enable_embeddings` to `True`. This allows you to use Upstash's embedding models for vectorization.
<Note>
Server-side Upstash embeddings (`enable_embeddings`) are available in the Python SDK only. The TypeScript SDK always embeds text with your configured embedder before writing to Upstash, so use the external embedding provider setup below.
</Note>
```python
import os
from mem0 import Memory
@@ -18,7 +22,9 @@ os.environ["UPSTASH_VECTOR_REST_TOKEN"] = "..."
config = {
"vector_store": {
"provider": "upstash_vector",
"enable_embeddings": True,
"config": {
"enable_embeddings": True,
}
}
}
@@ -32,7 +38,8 @@ m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category"
### Usage with external embedding providers
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -56,6 +63,36 @@ m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
```
```typescript TypeScript
import { Memory } from "mem0ai/oss";
// Set OPENAI_API_KEY, UPSTASH_VECTOR_REST_URL, and UPSTASH_VECTOR_REST_TOKEN in your environment.
const config = {
embedder: {
provider: "openai",
config: {
apiKey: process.env.OPENAI_API_KEY,
model: "text-embedding-3-large",
},
},
vectorStore: {
provider: "upstash_vector",
config: {
collectionName: "memories",
url: process.env.UPSTASH_VECTOR_REST_URL,
token: process.env.UPSTASH_VECTOR_REST_TOKEN,
},
},
};
const memory = new Memory(config);
await memory.add("Likes to play cricket on weekends", {
userId: "alice",
metadata: { category: "hobbies" },
});
```
</CodeGroup>
### Config
Here are the parameters available for configuring Upstash Vector:
@@ -72,3 +109,7 @@ Here are the parameters available for configuring Upstash Vector:
When `url` and `token` are not provided, the `UPSTASH_VECTOR_REST_URL` and
`UPSTASH_VECTOR_REST_TOKEN` environment variables are used.
</Note>
<Note>
The TypeScript SDK uses camelCase config keys (`collectionName`, `url`, `token`), where `collectionName` is required. Pass `url` and `token` (or a preconfigured `client`) explicitly, since the TypeScript SDK does not read them from environment variables. `enable_embeddings` is not supported in TypeScript.
</Note>
+48 -3
View File
@@ -9,12 +9,13 @@ description: "Use Valkey as an open-source vector store in Mem0 for high-perform
## Installation
```bash
pip install mem0ai[vector_stores]
pip install mem0ai[vector-stores]
```
## Usage
```python
<CodeGroup>
```python Python
config = {
"vector_store": {
"provider": "valkey",
@@ -37,8 +38,36 @@ messages = [
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
vectorStore: {
provider: 'valkey',
config: {
collectionName: 'test',
valkeyUrl: 'valkey://localhost:6379',
embeddingModelDims: 1536,
indexType: 'flat',
},
},
};
const memory = new Memory(config);
const messages = [
{ role: 'user', content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: 'assistant', content: 'How about thriller movies? They can be quite engaging.' },
{ role: 'user', content: "I'm not a big fan of thriller movies but I love sci-fi movies." },
{ role: 'assistant', content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." },
];
await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } });
```
</CodeGroup>
## Parameters
<Tabs>
<Tab title="Python">
Here are the parameters available for configuring Valkey:
| Parameter | Description | Default Value |
@@ -51,7 +80,23 @@ Here are the parameters available for configuring Valkey:
| `hnsw_ef_construction` | Size of dynamic candidate list for HNSW | `200` |
| `hnsw_ef_runtime` | Size of dynamic candidate list for search | `10` |
| `cluster_mode` | Enable cluster mode for Valkey cluster (CME) deployments | `false` |
| `distance_metric` | Distance metric for vector similarity | `cosine` |
| `timezone` | Timezone for timestamp handling | `UTC` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collectionName` | The name of the collection to store the vectors | `mem0` |
| `valkeyUrl` | Connection URL for the Valkey server | `valkey://localhost:6379` |
| `embeddingModelDims` | Dimensions of the embedding model | `1536` |
| `indexType` | Vector index algorithm (`hnsw` or `flat`) | `hnsw` |
| `hnswM` | Number of bi-directional links for HNSW | `16` |
| `hnswEfConstruction` | Size of dynamic candidate list for HNSW | `200` |
| `hnswEfRuntime` | Size of dynamic candidate list for search | `10` |
| `clusterMode` | Enable cluster mode for Valkey cluster (CME) deployments | `false` |
| `timezone` | Timezone for timestamp handling | `UTC` |
</Tab>
</Tabs>
## Cluster Mode
+52 -5
View File
@@ -8,8 +8,8 @@ description: "Use Google Cloud Vertex AI Vector Search as a managed vector store
To use Google Cloud Vertex AI Vector Search with `mem0`, you need to configure the `vector_store` in your `mem0` config:
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -20,11 +20,11 @@ config = {
"provider": "vertex_ai_vector_search",
"config": {
"endpoint_id": "YOUR_ENDPOINT_ID", # Required: Vector Search endpoint ID
"index_id": "YOUR_INDEX_ID", # Required: Vector Search index ID
"index_id": "YOUR_INDEX_ID", # Required: Vector Search index ID
"deployment_index_id": "YOUR_DEPLOYMENT_INDEX_ID", # Required: Deployment-specific ID
"project_id": "YOUR_PROJECT_ID", # Required: Google Cloud project ID
"project_number": "YOUR_PROJECT_NUMBER", # Required: Google Cloud project number
"region": "YOUR_REGION", # Optional: Defaults to GOOGLE_CLOUD_REGION
"region": "YOUR_REGION", # Required: Google Cloud region
"credentials_path": "path/to/credentials.json", # Optional: Defaults to GOOGLE_APPLICATION_CREDENTIALS
"vector_search_api_endpoint": "YOUR_API_ENDPOINT" # Required for get operations
}
@@ -34,9 +34,40 @@ m = Memory.from_config(config)
m.add("Your text here", user_id="user", metadata={"category": "example"})
```
```typescript TypeScript
import { Memory } from "mem0ai/oss";
// Authenticate with GOOGLE_APPLICATION_CREDENTIALS in your environment,
// or pass credentialsPath / serviceAccountJson in the config below.
const config = {
vectorStore: {
provider: "vertex_ai_vector_search",
config: {
endpointId: "YOUR_ENDPOINT_ID", // Required: Vector Search endpoint ID
indexId: "YOUR_INDEX_ID", // Required: Vector Search index ID
deploymentIndexId: "YOUR_DEPLOYMENT_INDEX_ID", // Required: Deployment-specific ID
projectId: "YOUR_PROJECT_ID", // Required: Google Cloud project ID
projectNumber: "YOUR_PROJECT_NUMBER", // Required: Google Cloud project number
region: "YOUR_REGION", // Required: Google Cloud region
credentialsPath: "path/to/credentials.json", // Optional: defaults to GOOGLE_APPLICATION_CREDENTIALS
vectorSearchApiEndpoint: "YOUR_API_ENDPOINT", // Required for search/get operations
},
},
};
const memory = new Memory(config);
await memory.add("Your text here", {
userId: "user",
metadata: { category: "example" },
});
```
</CodeGroup>
### Required Parameters
<Tabs>
<Tab title="Python">
| Parameter | Description | Required |
|-----------|-------------|----------|
| `endpoint_id` | Vector Search endpoint ID | Yes |
@@ -45,5 +76,21 @@ m.add("Your text here", user_id="user", metadata={"category": "example"})
| `project_id` | Google Cloud project ID | Yes |
| `project_number` | Google Cloud project number | Yes |
| `vector_search_api_endpoint` | Vector search API endpoint | Yes (for get operations) |
| `region` | Google Cloud region | No (defaults to GOOGLE_CLOUD_REGION) |
| `region` | Google Cloud region | Yes |
| `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` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Required |
|-----------|-------------|----------|
| `endpointId` | Vector Search endpoint ID | Yes |
| `indexId` | Vector Search index ID | Yes |
| `deploymentIndexId` | Deployment-specific index ID | Yes |
| `projectId` | Google Cloud project ID | Yes |
| `projectNumber` | Google Cloud project number | Yes |
| `vectorSearchApiEndpoint` | Vector search API endpoint | Yes (for get operations) |
| `region` | Google Cloud region | Yes |
| `credentialsPath` | Path to service account credentials | No (defaults to GOOGLE_APPLICATION_CREDENTIALS) |
| `serviceAccountJson` | Service account credentials as an object (alternative to `credentialsPath`) | No |
</Tab>
</Tabs>
+71 -10
View File
@@ -4,14 +4,21 @@ description: "Use Weaviate as an open-source vector search engine in Mem0 for st
---
[Weaviate](https://weaviate.io/) is an open-source vector search engine. It allows efficient storage and retrieval of high-dimensional vector embeddings, enabling powerful search and retrieval capabilities.
### Installation
```bash
pip install weaviate weaviate-client
<CodeGroup>
```bash Python
pip install weaviate-client
```
```bash TypeScript
npm install weaviate-client
```
</CodeGroup>
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -33,19 +40,73 @@ m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movie? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from "mem0ai/oss";
const config = {
vectorStore: {
provider: "weaviate",
config: {
collectionName: "test",
embeddingModelDims: 1536,
clusterUrl: "http://localhost:8080",
},
},
};
const memory = new Memory(config);
const messages = [
{
role: "user",
content: "I'm planning to watch a movie tonight. Any recommendations?",
},
{
role: "assistant",
content: "How about a thriller movie? They can be quite engaging.",
},
{
role: "user",
content: "I'm not a big fan of thriller movies but I love sci-fi movies.",
},
{
role: "assistant",
content:
"Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future.",
},
];
await memory.add(messages, {
userId: "alice",
metadata: {
category: "movies",
},
});
```
</CodeGroup>
The TypeScript SDK picks the connection mode from the config you pass:
- `clusterUrl` pointing at `localhost` connects to a local instance.
- `clusterUrl` plus `apiKey` connects to a Weaviate Cloud cluster (for example `https://my-cluster.weaviate.cloud`).
- Any other `clusterUrl` without an `apiKey` connects to a custom deployment, using the host and port from the URL.
You can also pass a pre-configured `client` (a `WeaviateClient` instance) to reuse an existing connection.
### Config
Here are the parameters available for configuring Weaviate:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection to store the vectors | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `cluster_url` | URL for the Weaviate server | `None` |
| `auth_client_secret` | API key for Weaviate authentication | `None` |
| Python | TypeScript | Description | Default Value |
| --- | --- | --- | --- |
| `collection_name` | `collectionName` | The name of the collection to store the vectors | `mem0` |
| `embedding_model_dims` | `embeddingModelDims` | Dimensions of the embedding model | `1536` |
| `cluster_url` | `clusterUrl` | URL for the Weaviate server | `None` |
| `auth_client_secret` | `apiKey` | API key for Weaviate authentication | `None` |
| `additional_headers` | `additionalHeaders` | Additional headers to include in requests | `None` |
+21 -21
View File
@@ -10,30 +10,30 @@ Mem0 includes built-in support for various popular databases. Memory can utilize
See the list of supported vector databases below.
<Note>
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.
The following vector databases are supported in the Python implementation. The TypeScript implementation currently supports Qdrant, Redis, PGVector, Supabase, LangChain, Azure AI Search, Vectorize, Amazon S3 Vectors, Milvus, and an in-memory store.
</Note>
<CardGroup cols={3}>
<Card title="Qdrant" href="/components/vectordbs/dbs/qdrant"></Card>
<Card title="Chroma" href="/components/vectordbs/dbs/chroma"></Card>
<Card title="PGVector" href="/components/vectordbs/dbs/pgvector"></Card>
<Card title="Upstash Vector" href="/components/vectordbs/dbs/upstash-vector"></Card>
<Card title="Milvus" href="/components/vectordbs/dbs/milvus"></Card>
<Card title="Pinecone" href="/components/vectordbs/dbs/pinecone"></Card>
<Card title="MongoDB" href="/components/vectordbs/dbs/mongodb"></Card>
<Card title="Azure" href="/components/vectordbs/dbs/azure"></Card>
<Card title="Redis" href="/components/vectordbs/dbs/redis"></Card>
<Card title="Valkey" href="/components/vectordbs/dbs/valkey"></Card>
<Card title="Elasticsearch" href="/components/vectordbs/dbs/elasticsearch"></Card>
<Card title="OpenSearch" href="/components/vectordbs/dbs/opensearch"></Card>
<Card title="Supabase" href="/components/vectordbs/dbs/supabase"></Card>
<Card title="Vertex AI" href="/components/vectordbs/dbs/vertex_ai"></Card>
<Card title="Weaviate" href="/components/vectordbs/dbs/weaviate"></Card>
<Card title="FAISS" href="/components/vectordbs/dbs/faiss"></Card>
<Card title="LangChain" href="/components/vectordbs/dbs/langchain"></Card>
<Card title="Amazon S3 Vectors" href="/components/vectordbs/dbs/s3_vectors"></Card>
<Card title="Databricks" href="/components/vectordbs/dbs/databricks"></Card>
<Card title="Turbopuffer" href="/components/vectordbs/dbs/turbopuffer"></Card>
<Card title="Qdrant" icon="/images/provider-icons/qdrant.svg" href="/components/vectordbs/dbs/qdrant"></Card>
<Card title="Chroma" icon="/images/provider-icons/chroma.svg" href="/components/vectordbs/dbs/chroma"></Card>
<Card title="PGVector" icon="/images/provider-icons/postgresql.svg" href="/components/vectordbs/dbs/pgvector"></Card>
<Card title="Upstash Vector" icon="/images/provider-icons/upstash.svg" href="/components/vectordbs/dbs/upstash-vector"></Card>
<Card title="Milvus" icon="/images/provider-icons/milvus.svg" href="/components/vectordbs/dbs/milvus"></Card>
<Card title="Pinecone" icon="/images/provider-icons/pinecone.svg" href="/components/vectordbs/dbs/pinecone"></Card>
<Card title="MongoDB" icon="/images/provider-icons/mongodb.svg" href="/components/vectordbs/dbs/mongodb"></Card>
<Card title="Azure" icon="/images/provider-icons/azure-color.svg" href="/components/vectordbs/dbs/azure"></Card>
<Card title="Redis" icon="/images/provider-icons/redis.svg" href="/components/vectordbs/dbs/redis"></Card>
<Card title="Valkey" icon="/images/provider-icons/valkey.svg" href="/components/vectordbs/dbs/valkey"></Card>
<Card title="Elasticsearch" icon="/images/provider-icons/elasticsearch.svg" href="/components/vectordbs/dbs/elasticsearch"></Card>
<Card title="OpenSearch" icon="/images/provider-icons/opensearch.svg" href="/components/vectordbs/dbs/opensearch"></Card>
<Card title="Supabase" icon="/images/provider-icons/supabase.svg" href="/components/vectordbs/dbs/supabase"></Card>
<Card title="Vertex AI" icon="/images/provider-icons/vertexai.svg" href="/components/vectordbs/dbs/vertex_ai"></Card>
<Card title="Weaviate" icon="circle-nodes" href="/components/vectordbs/dbs/weaviate"></Card>
<Card title="FAISS" icon="layer-group" href="/components/vectordbs/dbs/faiss"></Card>
<Card title="LangChain" icon="/images/provider-icons/langchain-color.svg" href="/components/vectordbs/dbs/langchain"></Card>
<Card title="Amazon S3 Vectors" icon="/images/provider-icons/aws-color.svg" href="/components/vectordbs/dbs/s3_vectors"></Card>
<Card title="Databricks" icon="/images/provider-icons/databricks.svg" href="/components/vectordbs/dbs/databricks"></Card>
<Card title="Turbopuffer" icon="/images/provider-icons/turbopuffer.svg" href="/components/vectordbs/dbs/turbopuffer"></Card>
</CardGroup>
## Usage
+84 -18
View File
@@ -1,32 +1,65 @@
---
title: Development
description: "Guide to contributing code to Mem0, covering the fork and clone workflow, PR submission, and code quality checks."
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."
icon: "code"
---
# Development Contributions
We strive to make contributions **easy, collaborative, and enjoyable**. Follow the steps below to ensure a smooth contribution process.
We strive to make contributions **easy, collaborative, and enjoyable**. Mem0 is a
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.
## Submitting Your Contribution through PR
<Note>
For the complete contributor checklist, see
[CONTRIBUTING.md](https://github.com/mem0ai/mem0/blob/main/CONTRIBUTING.md) in
the repository root.
</Note>
To contribute, follow these steps:
## Before You Start
### 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)
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, ensure to:
2. **Create a Feature Branch**: Use a dedicated branch, e.g., `feature/my-new-feature`
3. **Implement Changes**: If adding a feature or fixing a bug, be sure to:
- Write necessary **tests**
- Add **documentation, docstrings, and runnable examples**
4. **Code Quality Checks**:
- Run **linting** to catch style issues
- Ensure **all tests pass**
5. **Submit a Pull Request**
5. **Commit** using [Conventional Commits](https://www.conventionalcommits.org/)
(`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).
---
## Dependency Management
## Python SDK (`mem0/`)
### Dependency Management
We use `hatch` as our package manager. Install it by following the [official instructions](https://hatch.pypa.io/latest/install/).
@@ -44,13 +77,9 @@ hatch -e dev_py_3_11 shell # For dev_py_3_11 (differences are mentioned in pypr
make install_all
```
---
## Development Standards
### Pre-commit Hooks
Ensure `pre-commit` is installed before contributing:
Ensure `pre-commit` is installed before contributing (hooks run ruff + isort):
```bash
pre-commit install
@@ -58,7 +87,7 @@ pre-commit install
### Linting with `ruff`
Run the linter and fix any reported issues before submitting your PR:
Run the linter and fix any reported issues before submitting your PR (line length **120**):
```bash
make lint
@@ -66,10 +95,11 @@ make lint
### Code Formatting
To maintain a consistent code style, format your code:
To maintain a consistent code style, format your code and sort imports (isort, `profile = "black"`):
```bash
make format
make sort
```
### Testing with `pytest`
@@ -84,10 +114,46 @@ make test
---
## Release Process
## TypeScript SDK (`mem0-ts/`)
Currently, releases are handled manually. We aim for frequent releases, typically when new features or bug fixes are introduced.
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()`
---
Thank you for contributing to Mem0!
## 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
Packages are published automatically via GitHub Actions when a GitHub Release is
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!
+2
View File
@@ -123,3 +123,5 @@ As the conversation progresses, Mem0's memory automatically updates based on the
Build a travel companion that remembers preferences and past conversations.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -81,3 +81,5 @@ This local setup of Mem0 using Ollama provides a fully self-contained solution f
Learn core companion patterns that work with any LLM provider.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -31,7 +31,7 @@ const openaiClient = new OpenAI();
const memory = new Memory();
async function chatWithMemories(message, userId = "default_user") {
const relevantMemories = await memory.search(message, { userId: userId });
const relevantMemories = await memory.search(message, { filters: { user_id: userId } });
const memoriesStr = relevantMemories.results
.map(entry => `- ${entry.memory}`)
@@ -137,3 +137,5 @@ As users interact with the system, Mem0's memory system continuously learns and
Run the full showcase app to see memory-powered companions in action.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -78,3 +78,5 @@ This setup demonstrates how to build an AI Companion that maintains memory acros
Implement a command-line companion using the Node.js SDK.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -211,3 +211,5 @@ This Personalized AI Travel Assistant leverages Mem0's memory capabilities to pr
Build an educational companion that remembers learning progress and preferences.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -156,7 +156,7 @@ def create_memory_voice_agent():
"""You're speaking to a human, so be polite and concise.
Always respond in clear, natural English.
You have the ability to remember information about the user.
Use the save_memories tool when the user shares an important information worth remembering.
Use the save_memories tool when the user shares important information worth remembering.
Use the search_memories tool when you need context from past conversations or user asks you to recall something.
""",
),
@@ -362,7 +362,7 @@ def create_memory_voice_agent():
"""You're speaking to a human, so be polite and concise.
Always respond in clear, natural English.
You have the ability to remember information about the user.
Use the save_memories tool when the user shares an important information worth remembering.
Use the save_memories tool when the user shares important information worth remembering.
Use the search_memories tool when you need context from past conversations or user asks you to recall something.
""",
),
@@ -544,3 +544,5 @@ async def save_memories(
Master the core patterns for building memory-powered companions.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -66,3 +66,5 @@ Your API keys are stored locally in your browser. Your messages are sent to the
Combine memory with search tools to conduct comprehensive research projects.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -231,7 +231,7 @@ mem0_client.add(
<Tab title="Open Source">
**Categories via Metadata:**
In open source, model categories with a stable field in `metadata`—here we use `memory_bucket`:
In open source, model categories with a stable field in `metadata`. This example uses `memory_bucket`:
```python
# Add goal
@@ -289,8 +289,7 @@ print([m["memory"] for m in constraints["results"]])
```python
constraints = memory.search(
query="injury concerns",
user_id="max",
filters={"memory_bucket": {"in": ["constraints"]}},
filters={"user_id": "max", "memory_bucket": {"in": ["constraints"]}},
threshold=0.0 # optional: widen recall for short phrases
)
print([m["memory"] for m in constraints["results"]])
@@ -327,7 +326,7 @@ print([m["memory"] for m in memories["results"]])
</Tabs>
<Warning>
Without filters, Mem0 stores everything—greetings, filler, and casual chat. This pollutes retrieval: instead of pulling "marathon goal," you get "lol ok." Set custom instructions to keep memory clean.
Without filters, Mem0 stores everything: greetings, filler, and casual chat. This pollutes retrieval: instead of pulling "marathon goal," you get "lol ok." Set custom instructions to keep memory clean.
</Warning>
Noise. Greetings and filler clutter the memory.
@@ -375,7 +374,7 @@ Return JSON with key "facts" as a list of strings (use [] if nothing to store).
memory = Memory.from_config(MEMORY_CONFIG)
```
<Note>`custom_instructions` is a top-level key in the config dictionary passed to `Memory.from_config()`. Make sure it's set before creating the Memory instance — not after.</Note>
<Note>`custom_instructions` is a top-level key in the config dictionary passed to `Memory.from_config()`. Set it before creating the Memory instance, not after.</Note>
</Tab>
</Tabs>
@@ -405,7 +404,7 @@ print([m["memory"] for m in memories["results"]])
</Tabs>
<Info>
**Expected output:** Only 2 memories stored—the marathon goal and trail preference. The greeting "hey how's it going" was filtered out automatically. Custom instructions are working.
**Expected output:** Only 2 memories stored: the marathon goal and trail preference. The greeting "hey how's it going" was filtered out automatically. Custom instructions are working.
</Info>
Only meaningful facts. Filler gets dropped automatically.
@@ -736,8 +735,7 @@ mem0_client.add(messages, user_id="max", run_id="nyc-2025")
# Retrieve only Boston memories
boston_memories = mem0_client.search(
"training plan",
user_id="max",
run_id="boston-2025"
filters={"user_id": "max", "run_id": "boston-2025"}
)
```
</Tab>
@@ -749,8 +747,7 @@ memory.add(messages, user_id="max", run_id="nyc-2025")
# Retrieve only Boston memories
boston_memories = memory.search(
"training plan",
user_id="max",
run_id="boston-2025",
filters={"user_id": "max", "run_id": "boston-2025"},
)
```
</Tab>
@@ -846,14 +843,13 @@ Prioritize recent training over old data:
```python
recent = mem0_client.search(
"training progress",
user_id="max",
filters={"created_at": {"gte": "2025-10-01"}}
filters={"user_id": "max", "created_at": {"gte": "2025-10-01"}}
)
```
</Tab>
<Tab title="Open Source">
```python
# Qdrant range filters require numbers — store an epoch timestamp in metadata
# Qdrant range filters require numbers: store an epoch timestamp in metadata
from datetime import datetime
epoch = int(datetime(2025, 10, 15).timestamp())
@@ -866,8 +862,7 @@ memory.add(
cutoff = int(datetime(2025, 10, 1).timestamp())
recent = memory.search(
"training progress",
user_id="max",
filters={"logged_epoch": {"gte": cutoff}},
filters={"user_id": "max", "logged_epoch": {"gte": cutoff}},
)
```
</Tab>
@@ -889,8 +884,7 @@ mem0_client.add(
# Later, find all speed workouts
speed_sessions = mem0_client.search(
"speed work",
user_id="max",
filters={"metadata": {"workout_type": "speed"}}
filters={"user_id": "max", "metadata": {"workout_type": "speed"}}
)
```
</Tab>
@@ -905,8 +899,7 @@ memory.add(
# Later, find all speed workouts
speed_sessions = memory.search(
"speed work",
user_id="max",
filters={"workout_type": "speed"},
filters={"user_id": "max", "workout_type": "speed"},
)
```
</Tab>
@@ -980,3 +973,5 @@ Before launching:
Organize customer context to keep assistants responsive at scale.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -65,7 +65,7 @@ Patient is allergic to penicillin
```
<Warning>
Without custom instructions, AI assistants treat speculation as confirmed facts. "I think I might be allergic" becomes "Patient is allergic"—a dangerous transformation in sensitive domains like healthcare, legal, or financial services.
Without custom instructions, AI assistants treat speculation as confirmed facts. "I think I might be allergic" becomes "Patient is allergic": a dangerous transformation in sensitive domains like healthcare, legal, or financial services.
</Warning>
The speculation became a confirmed fact. Let's add controls.
@@ -328,7 +328,7 @@ That “no duplicates” promise comes from the inference pipeline. Keep `infer=
| Mode | What it does | Best for | Watch out for |
| --- | --- | --- | --- |
| `infer=True` *(default)* | Runs the LLM pipeline so Mem0 extracts structured facts and resolves conflicts automatically. | Daily conversations, preference tracking, anything you want deduped. | Slightly slower because inference runs on every write. |
| `infer=False` | Stores your payload exactly as-is—no inference, no dedupe. | Bulk imports, compliance snapshots, curated facts you already trust. | Later `infer=True` calls for the same fact will create duplicates you must clean manually. |
| `infer=False` | Stores your payload exactly as-is: no inference, no dedupe. | Bulk imports, compliance snapshots, curated facts you already trust. | Later `infer=True` calls for the same fact will create duplicates you must clean manually. |
<Tip>
Stay consistent per data source. If you need both behaviors, keep them in separate scopes (e.g., different `app_id` or `run_id`) so you always know which memories are inferred vs direct imports.
@@ -512,3 +512,5 @@ Start with conservative filters (only store confirmed facts) and iterate based o
<Card title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
Learn core memory patterns including temporary vs permanent data handling.
</Card>
<Snippet file="star-on-github.mdx" />
@@ -70,7 +70,7 @@ print(agent_memories)
```
<Tip icon="compass">
Memories can be written with several identifiers, but each search resolves one entity boundary at a time. Run separate queries for user and agent scopes—just like above—rather than combining both in a single filter.
Memories can be written with several identifiers, but each search resolves one entity boundary at a time. Run separate queries for user and agent scopes, as shown above, rather than combining both in a single filter.
</Tip>
## When Memories Leak
@@ -334,3 +334,5 @@ You learned how to:
href="/cookbooks/essentials/controlling-memory-ingestion"
/>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -58,6 +58,7 @@ Use `get_all()` with filters to retrieve everything for a specific user:
```python
dev_memories = client.get_all(
filters={"user_id": "dev"},
page=1,
page_size=50
)
@@ -75,7 +76,7 @@ First memory: Dev works at TechCorp as a senior engineer
```
<Info>
**Expected output:** `get_all()` retrieved Dev's complete memory record. This method returns everything matching your filters—no semantic search, no ranking, just raw retrieval. Perfect for exports and audits.
**Expected output:** `get_all()` retrieved Dev's complete memory record. This method returns everything matching your filters: no semantic search, no ranking, just raw retrieval. Perfect for exports and audits.
</Info>
You can filter by metadata to get specific types:
@@ -127,7 +128,7 @@ Dev works at TechCorp as a senior engineer (score: 0.89)
```
Search works across all memory fields and ranks by relevance. Use it when you have a specific question, use `get_all()` when you need everything.
Search works across all memory fields and ranks by relevance. Use it when you have a specific question; use `get_all()` when you need everything.
---
@@ -277,7 +278,7 @@ This covers data portability, GDPR compliance, system migrations, and manual rev
## Summary
Use **`get_all()`** for bulk retrieval, **`search()`** for specific questions, and **`create_memory_export()`** for structured data exports with custom schemas. Remember exports expire after 7 days—download them locally for long-term archives.
Use **`get_all()`** for bulk retrieval, **`search()`** for specific questions, and **`create_memory_export()`** for structured data exports with custom schemas. Remember exports expire after 7 days: download them locally for long-term archives.
<CardGroup cols={2}>
<Card title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
@@ -287,3 +288,5 @@ Use **`get_all()`** for bulk retrieval, **`search()`** for specific questions, a
Ensure only verified insights make it into your export pipeline.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -19,7 +19,7 @@ client = MemoryClient(api_key="your-api-key")
```
<Note>
Define custom categories at the **project level** with `client.project.update()` before adding memories. Categories apply to all future memories—Mem0 auto-assigns them based on content semantics.
Define custom categories at the **project level** with `client.project.update()` before adding memories. Categories apply to all future memories: Mem0 auto-assigns them based on content semantics.
</Note>
---
@@ -67,7 +67,7 @@ Total memories: 3
```
<Warning>
Without categories, agents waste time reading through everything. For a customer with 100 memories, finding one billing issue means scanning all 100. Categories let you filter to exactly what you need—billing issues only, no password resets or feedback mixed in.
Without categories, agents waste time reading through everything. For a customer with 100 memories, finding one billing issue means scanning all 100. Categories let you filter to exactly what you need: billing issues only, no password resets or feedback mixed in.
</Warning>
Everything is mixed together. Support agents have to read through all memories to find what they need.
@@ -91,7 +91,7 @@ client.project.update(custom_categories=custom_categories)
```
<Tip>
Start with 3-5 clear categories that match how your team thinks. Too many categories dilute auto-tagging accuracy. Add more later if needed—it's easier to expand than to fix over-complicated classification.
Start with 3-5 clear categories that match how your team thinks. Too many categories dilute auto-tagging accuracy. Add more later if needed: it's easier to expand than to fix over-complicated classification.
</Tip>
These categories are now available project-wide. Every memory can be tagged with one or more categories.
@@ -160,7 +160,7 @@ Billing issues:
```
<Info icon="check">
**Expected output:** Only the billing issue returned—no password reset, no upgrade request. Category filtering worked. Joseph can audit billing without reading through unrelated support tickets.
**Expected output:** Only the billing issue returned: no password reset, no upgrade request. Category filtering worked. Joseph can audit billing without reading through unrelated support tickets.
</Info>
Only billing-related memories are returned. No need to filter through account updates or feedback.
@@ -239,7 +239,7 @@ This pattern scales from 10 customers to 10,000 without degrading retrieval spee
Categories make retrieval faster and compliance easier. Define 3-5 clear categories with `client.project.update()`, let Mem0 auto-assign them based on content, then filter with `categories: {in: [...]}` to pull exactly what you need.
Instead of searching through everything, agents jump directly to the information type they need—billing issues, account details, or support tickets.
Instead of searching through everything, agents jump directly to the information type they need: billing issues, account details, or support tickets.
<CardGroup cols={2}>
<Card title="Control Memory Ingestion" icon="filter" href="/cookbooks/essentials/controlling-memory-ingestion">
@@ -249,3 +249,5 @@ Instead of searching through everything, agents jump directly to the information
Use categories to drive audits, migrations, and compliance reports.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -83,3 +83,5 @@ This is a simple example of how to use Mem0 to create a personalized AI agent. Y
Build another type of personalized companion with memory capabilities.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -238,17 +238,13 @@ You've successfully built a Gemini 3 agent with persistent memory using Mem0's M
## Next Steps
<CardGroup cols={2}>
<Card
title="MCP Integration Feature"
description="Learn about MCP configuration options and deployment methods"
icon="plug"
href="/platform/features/mcp-integration"
/>
<CardGroup cols={1}>
<Card
title="MCP Quickstart"
description="Get started with MCP for any AI client in minutes"
icon="rocket"
href="/platform/mem0-mcp"
/>
</CardGroup>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -211,8 +211,8 @@ class MultiAgentLearningSystem:
try:
# Search memory for learning patterns
memories = self.memory.search(
user_id=self.student_id,
query="learning machine learning"
query="learning machine learning",
filters={"user_id": self.student_id}
)
if memories and memories.get('results'):
@@ -369,3 +369,5 @@ Based on our previous session, I remember we covered Vision Language Models and
Learn how to scope memories across multiple agents, users, and sessions.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -197,3 +197,5 @@ I've ordered a pizza for you, and the bill has been sent to your email. Enjoy yo
Master the core patterns for memory-powered agents across frameworks.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />

Some files were not shown because too many files have changed in this diff Show More