Compare commits

...

48 Commits

Author SHA1 Message Date
Younes Slaoui 047fc1254f chore(cli): remove agent-rush command and de-brand whoami
The AGENTRUSH game has ended. Remove the agent-rush add/search
subcommands from both CLIs, change the whoami output to
'Your user_id:  <default_user_id>', drop the agent_rush config
key handling, and update the CLI docs page accordingly.

Bumps mem0-cli to 0.2.10 and @mem0/cli to 0.2.11.
2026-07-07 19:51:16 -07:00
张思孝 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
355 changed files with 16653 additions and 4144 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.11"
"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.11"
"version": "0.2.12"
}
]
}
-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.11",
"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>;
}
}
-147
View File
@@ -1,147 +0,0 @@
/**
* `mem0 agent-rush <add|search> "..."` — wraps the AGENTRUSH platform endpoints.
* Project routing is implicit (server-side); zero flags needed.
*/
import readline from "node:readline";
import { colors, printError, printSuccess } from "../branding.js";
import { loadConfig, saveConfig } from "../config.js";
import { CLI_VERSION } from "../version.js";
const PII_WARNING = [
"",
"⚠️ AGENTRUSH memories are PUBLIC — visible to any other player.",
" Do not include real names, emails, secrets, work content, or PII.",
"",
].join("\n");
const ERROR_HINTS: Record<string, string> = {
agentrush_search_first:
"Run 3 'mem0 agent-rush search' commands before adding.",
agentrush_search_quota: "You've used your 3 lifetime searches.",
agentrush_add_quota: "You've used your 3 lifetime adds.",
agentrush_not_agent_mode:
"Re-run 'mem0 init --agent' to bootstrap an agent-mode key.",
agentrush_length: "Memory text must be 50-1000 characters.",
agentrush_no_urls: "URLs are not allowed.",
agentrush_blocklist: "Content contains a blocked term.",
agentrush_global_quota: "Event-wide cap reached. Try again later.",
agentrush_not_provisioned:
"AGENTRUSH is not provisioned in this environment.",
};
async function callEndpoint(
path: string,
body: Record<string, unknown>,
): Promise<unknown> {
const config = loadConfig();
const baseUrl = (config.platform?.baseUrl ?? "https://api.mem0.ai").replace(
/\/+$/,
"",
);
if (!config.platform?.apiKey) {
printError("Not initialized. Run `mem0 init --agent` first.");
process.exit(1);
}
const resp = await fetch(`${baseUrl}${path}`, {
method: "POST",
headers: {
Authorization: `Token ${config.platform.apiKey}`,
"Content-Type": "application/json",
"X-Mem0-Source": "cli",
"X-Mem0-Client-Language": "node",
"X-Mem0-Client-Version": CLI_VERSION,
"X-Mem0-Mode": "agent-rush",
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(30_000),
});
const json = await resp.json().catch(() => ({}));
if (!resp.ok) {
const code =
(json as { error?: { code?: string } }).error?.code ?? "unknown";
printError(`AGENTRUSH error: ${code}`);
if (ERROR_HINTS[code]) {
console.log(` ${colors.dim(ERROR_HINTS[code])}`);
}
process.exit(1);
}
return json;
}
function promptLine(question: string): Promise<string> {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(question, (answer) => {
rl.close();
resolve(answer.trim());
});
});
}
/**
* Ensure the human has acknowledged that AGENTRUSH memories are PUBLIC.
*
* Interactive (TTY): show the prompt; on "y" persist `agentRush.acknowledgedAt`
* so we never ask the same machine twice. On anything else, abort.
*
* Non-interactive (agent invocation, no TTY): print the warning to stderr
* for the human reading the agent's transcript and proceed — agents can't
* answer y/N prompts.
*/
async function ensureWarningAcknowledged(): Promise<void> {
const config = loadConfig();
if (config.agentRush?.acknowledgedAt) return;
if (!process.stdin.isTTY || !process.stdout.isTTY) {
// Agent context: surface the warning to stderr, don't block.
console.error(PII_WARNING);
return;
}
console.log(PII_WARNING);
const answer = (await promptLine(" Continue? [y/N]: ")).toLowerCase();
if (answer !== "y" && answer !== "yes") {
printError("Aborted.");
process.exit(1);
}
config.agentRush.acknowledgedAt = new Date().toISOString();
saveConfig(config);
}
export async function cmdAgentRushAdd(content: string): Promise<void> {
await ensureWarningAcknowledged();
const result = await callEndpoint("/v1/agent-rush/memories/", { content });
printSuccess(
`Memory submitted (event_id: ${(result as { event_id?: string }).event_id ?? "?"})`,
);
}
export async function cmdAgentRushSearch(query: string): Promise<void> {
const result = (await callEndpoint("/v1/agent-rush/memories/search/", {
query,
})) as {
results?: Array<{ memory?: string }>;
memories?: Array<{ memory?: string }>;
};
const memories = result.results ?? result.memories ?? [];
if (memories.length === 0) {
console.log(colors.dim("(no results)"));
return;
}
memories.slice(0, 5).forEach((m, i) => {
console.log(` ${i + 1}. ${m.memory ?? JSON.stringify(m)}`);
});
}
+3 -4
View File
@@ -1,9 +1,9 @@
/**
* `mem0 whoami` — print the active agent's default_user_id (AGENTRUSH identifier).
* `mem0 whoami` — print the active agent's default_user_id.
* Reads from local config; no network call.
*/
import { colors, printError, printInfo } from "../branding.js";
import { colors, printError } from "../branding.js";
import { loadConfig } from "../config.js";
export async function cmdWhoami(): Promise<void> {
@@ -13,6 +13,5 @@ export async function cmdWhoami(): Promise<void> {
printError("No default_user_id found. Run `mem0 init --agent` first.");
process.exit(1);
}
console.log(`Your AGENTRUSH identifier: ${colors.brand(sessionId)}`);
printInfo("Find your row at https://mem0.ai/agentrush");
console.log(`Your user_id: ${colors.brand(sessionId)}`);
}
-15
View File
@@ -40,18 +40,11 @@ export interface TelemetryConfig {
anonymousId: string;
}
export interface AgentRushConfig {
// ISO timestamp the human acknowledged the "memories are public" warning.
// Empty until first interactive `mem0 agent-rush add`.
acknowledgedAt: string;
}
export interface Mem0Config {
version: number;
defaults: DefaultsConfig;
platform: PlatformConfig;
telemetry: TelemetryConfig;
agentRush: AgentRushConfig;
}
export function createDefaultConfig(): Mem0Config {
@@ -76,9 +69,6 @@ export function createDefaultConfig(): Mem0Config {
telemetry: {
anonymousId: "",
},
agentRush: {
acknowledgedAt: "",
},
};
}
@@ -113,8 +103,6 @@ export function loadConfig(): Mem0Config {
config.defaults.runId = defaults.run_id ?? "";
const telemetry = data.telemetry ?? {};
config.telemetry.anonymousId = telemetry.anonymous_id ?? "";
const agentRush = data.agent_rush ?? {};
config.agentRush.acknowledgedAt = agentRush.acknowledged_at ?? "";
}
// Environment variable overrides
@@ -155,9 +143,6 @@ export function saveConfig(config: Mem0Config): void {
telemetry: {
anonymous_id: config.telemetry.anonymousId,
},
agent_rush: {
acknowledged_at: config.agentRush.acknowledgedAt,
},
};
fs.writeFileSync(CONFIG_FILE, JSON.stringify(data, null, 2));
+1 -33
View File
@@ -266,44 +266,12 @@ program
program
.command("whoami")
.description("Print the active agent's AGENTRUSH identifier.")
.description("Print your user_id (default_user_id).")
.action(async () => {
const { cmdWhoami } = await import("./commands/whoami.js");
await cmdWhoami();
});
// ── AGENTRUSH subcommand group ────────────────────────────────────────────
const agentRush = program
.command("agent-rush")
.description("AGENTRUSH game commands.")
.addHelpCommand(false)
.configureHelp({ formatHelp: richFormatHelp });
agentRush
.command("add <content...>")
.description("Submit a memory to AGENTRUSH.")
.addHelpText(
"after",
'\nExamples:\n $ mem0 agent-rush add "I used mem0 to build a coding agent"\n $ mem0 agent-rush add "Agents that remember are better agents"',
)
.action(async (parts: string[]) => {
const { cmdAgentRushAdd } = await import("./commands/agent-rush.js");
await cmdAgentRushAdd(parts.join(" "));
});
agentRush
.command("search <query...>")
.description("Search AGENTRUSH memories.")
.addHelpText(
"after",
'\nExamples:\n $ mem0 agent-rush search "agents and memory and tools"\n $ mem0 agent-rush search "coding assistant"',
)
.action(async (parts: string[]) => {
const { cmdAgentRushSearch } = await import("./commands/agent-rush.js");
await cmdAgentRushSearch(parts.join(" "));
});
// ── Memory: add ───────────────────────────────────────────────────────────
program
+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.10"
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.10"
+1 -48
View File
@@ -916,7 +916,7 @@ def identify(
@app.command(name="whoami", rich_help_panel="Setup")
def whoami_cmd() -> None:
"""Print your AGENTRUSH identifier (default_user_id).
"""Print your user_id (default_user_id).
Example:
mem0 whoami
@@ -926,53 +926,6 @@ def whoami_cmd() -> None:
run_whoami()
# ── AGENTRUSH sub-app ─────────────────────────────────────────────────────
agent_rush_app = typer.Typer(
name="agent-rush",
help="AGENTRUSH game commands",
no_args_is_help=True,
rich_markup_mode="rich",
)
@agent_rush_app.callback(invoke_without_command=True)
def _agent_rush_callback(ctx: typer.Context) -> None:
if ctx.invoked_subcommand:
_fire_telemetry(f"agent-rush.{ctx.invoked_subcommand}")
@agent_rush_app.command(name="add")
def agent_rush_add(
content: str = typer.Argument(..., help="Memory content (50-1000 characters, no URLs)."),
) -> None:
"""Submit a memory to AGENTRUSH.
Example:
mem0 agent-rush add "I enjoy solving constraint-satisfaction problems."
"""
from mem0_cli.commands.agent_rush_cmd import run_agent_rush_add
run_agent_rush_add(content)
@agent_rush_app.command(name="search")
def agent_rush_search(
query: str = typer.Argument(..., help="Search query."),
) -> None:
"""Search AGENTRUSH memories.
Example:
mem0 agent-rush search "constraint satisfaction"
"""
from mem0_cli.commands.agent_rush_cmd import run_agent_rush_search
run_agent_rush_search(query)
app.add_typer(agent_rush_app, name="agent-rush", rich_help_panel="Setup")
# (entity_app registered at module level, below sub-group definitions)
+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):
@@ -1,132 +0,0 @@
"""mem0 agent-rush — AGENTRUSH game commands.
Wraps the platform's /v1/agent-rush/{memories/, memories/search/} endpoints.
Hardcoded routing; no flags needed.
"""
from __future__ import annotations
import sys
from datetime import datetime, timezone
import httpx
import typer
from rich.console import Console
from mem0_cli.branding import print_error, print_success
from mem0_cli.config import load_config, save_config
console = Console()
err_console = Console(stderr=True)
_PII_WARNING_LINES = (
"",
"[yellow]⚠️ AGENTRUSH memories are PUBLIC — visible to any other player.[/yellow]",
"[yellow] Do not include real names, emails, secrets, work content, or PII.[/yellow]",
"",
)
_SOURCE_HEADERS = {
"X-Mem0-Source": "cli",
"X-Mem0-Client-Language": "python",
"X-Mem0-Mode": "agent-rush",
}
_ERROR_HINTS = {
"agentrush_search_first": "Run 3 'mem0 agent-rush search' commands before adding.",
"agentrush_search_quota": "You've used your 3 lifetime searches.",
"agentrush_add_quota": "You've used your 3 lifetime adds.",
"agentrush_not_agent_mode": "Re-run 'mem0 init --agent' to bootstrap an agent-mode key.",
"agentrush_length": "Memory text must be 50-1000 characters.",
"agentrush_no_urls": "URLs are not allowed.",
"agentrush_blocklist": "Content contains a blocked term.",
"agentrush_global_quota": "Event-wide cap reached. Try again later.",
"agentrush_not_provisioned": "AGENTRUSH is not provisioned in this environment.",
}
def _call(path: str, body: dict) -> dict:
config = load_config()
if not config.platform.api_key:
print_error(err_console, "Not initialized. Run `mem0 init --agent` first.")
raise typer.Exit(1)
base_url = (config.platform.base_url or "https://api.mem0.ai").rstrip("/")
try:
with httpx.Client(timeout=30.0) as client:
resp = client.post(
f"{base_url}{path}",
headers={
**_SOURCE_HEADERS,
"Authorization": f"Token {config.platform.api_key}",
"Content-Type": "application/json",
},
json=body,
)
except httpx.HTTPError as exc:
print_error(err_console, f"Network error: {exc}")
raise typer.Exit(1) from exc
try:
data = resp.json()
except Exception:
data = {}
if resp.status_code >= 400:
code = (
(data.get("error") or {}).get("code", "unknown")
if isinstance(data, dict)
else "unknown"
)
print_error(err_console, f"AGENTRUSH error: {code}")
hint = _ERROR_HINTS.get(code)
if hint:
console.print(f" [dim]{hint}[/dim]")
raise typer.Exit(1)
return data
def _ensure_warning_acknowledged() -> None:
"""Block the first interactive add on the PII warning; pass-through for agents.
Interactive (TTY): show prompt, require explicit 'y', persist
`agent_rush.acknowledged_at` so we never ask the same machine twice.
Non-interactive (no TTY — typical when an agent runs the CLI): surface
the warning to stderr for the human reading the agent transcript and
proceed without prompting (agents can't answer y/N).
"""
config = load_config()
if config.agent_rush.acknowledged_at:
return
is_tty = sys.stdin.isatty() and sys.stdout.isatty()
if not is_tty:
for line in _PII_WARNING_LINES:
err_console.print(line)
return
for line in _PII_WARNING_LINES:
console.print(line)
answer = typer.prompt(" Continue? [y/N]", default="N", show_default=False).strip().lower()
if answer not in ("y", "yes"):
print_error(err_console, "Aborted.")
raise typer.Exit(1)
config.agent_rush.acknowledged_at = datetime.now(timezone.utc).isoformat()
save_config(config)
def run_agent_rush_add(content: str) -> None:
_ensure_warning_acknowledged()
result = _call("/v1/agent-rush/memories/", {"content": content})
event_id = result.get("event_id", "?")
print_success(console, f"Memory submitted (event_id: {event_id})")
def run_agent_rush_search(query: str) -> None:
result = _call("/v1/agent-rush/memories/search/", {"query": query})
memories = result.get("results") or result.get("memories") or []
if not memories:
console.print("[dim](no results)[/dim]")
return
for i, m in enumerate(memories[:5], start=1):
text = m.get("memory") if isinstance(m, dict) else str(m)
console.print(f" {i}. {text}")
@@ -1,11 +1,11 @@
"""mem0 whoami — print the active agent's default_user_id (AGENTRUSH identifier)."""
"""mem0 whoami — print the active agent's default_user_id."""
from __future__ import annotations
import typer
from rich.console import Console
from mem0_cli.branding import BRAND_COLOR, print_error, print_info
from mem0_cli.branding import BRAND_COLOR, print_error
from mem0_cli.config import load_config
console = Console()
@@ -21,5 +21,4 @@ def run_whoami() -> None:
"No default_user_id found. Run `mem0 init --agent` first.",
)
raise typer.Exit(1)
console.print(f"Your AGENTRUSH identifier: [{BRAND_COLOR}]{session_id}[/{BRAND_COLOR}]")
print_info(console, "Find your row at https://mem0.ai/agentrush")
console.print(f"Your user_id: [{BRAND_COLOR}]{session_id}[/{BRAND_COLOR}]")
+4 -15
View File
@@ -51,20 +51,12 @@ class TelemetryConfig:
anonymous_id: str = ""
@dataclass
class AgentRushConfig:
# ISO timestamp the human acknowledged the "memories are public" warning.
# Empty until first interactive `mem0 agent-rush add`.
acknowledged_at: str = ""
@dataclass
class Mem0Config:
version: int = CONFIG_VERSION
defaults: DefaultsConfig = field(default_factory=DefaultsConfig)
platform: PlatformConfig = field(default_factory=PlatformConfig)
telemetry: TelemetryConfig = field(default_factory=TelemetryConfig)
agent_rush: AgentRushConfig = field(default_factory=AgentRushConfig)
SHORT_KEY_ALIASES: dict[str, str] = {
@@ -113,9 +105,6 @@ def load_config() -> Mem0Config:
telemetry = data.get("telemetry", {})
config.telemetry.anonymous_id = telemetry.get("anonymous_id", "")
agent_rush = data.get("agent_rush", {})
config.agent_rush.acknowledged_at = agent_rush.get("acknowledged_at", "")
# Environment variable overrides
env_key = os.environ.get("MEM0_API_KEY")
if env_key:
@@ -169,9 +158,6 @@ def save_config(config: Mem0Config) -> None:
"telemetry": {
"anonymous_id": config.telemetry.anonymous_id,
},
"agent_rush": {
"acknowledged_at": config.agent_rush.acknowledged_at,
},
}
with open(CONFIG_FILE, "w") as f:
@@ -235,7 +221,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>
+1 -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
+1 -1
View File
@@ -4,7 +4,7 @@ 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.
@@ -4,9 +4,9 @@ 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.
@@ -14,7 +14,7 @@ Organizations and projects are **optional** features. You can use Mem0 without t
## Key Capabilities
- **Multi-org/project Support**: Organization and project are resolved automatically from your API key via `/v1/ping/` — no org or project params are accepted by `MemoryClient.__init__`. Use a project-specific API key to target a particular project.
- **Multi-org/project Support**: 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
@@ -150,7 +150,7 @@ 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/ \
+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). **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
- **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"
---
+798 -71
View File
File diff suppressed because it is too large Load Diff
@@ -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
+63 -2
View File
@@ -7,10 +7,18 @@ You can use FastEmbed to run embedding models locally in Mem0. FastEmbed is an O
### Installation
```bash
FastEmbed is an optional dependency, so install it alongside Mem0.
<CodeGroup>
```bash Python
pip install fastembed
```
```bash TypeScript
npm install fastembed
```
</CodeGroup>
### Usage
<CodeGroup>
@@ -38,13 +46,66 @@ messages = [
]
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 FastEmbed embedder:
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>
+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 -12
View File
@@ -10,21 +10,21 @@ Mem0 offers support for various embedding models, allowing users to choose the o
See the list of supported embedders below.
<Note>
All embedders listed below are supported in the Python implementation. The TypeScript implementation supports: **OpenAI**, **Azure OpenAI**, **Google AI**, **Langchain**, **LM Studio**, and **Ollama**.
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="FastEmbed" href="/components/embedders/models/fastembed"></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
+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.
+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 |
+28 -2
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
@@ -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).
+17 -17
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).
@@ -20,22 +20,22 @@ See the list of supported LLMs below.
</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
+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.
+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>
@@ -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:
@@ -74,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__
+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"` |
| embedding_model_dims | Dimensions of the embedding vectors | `1536` |
| mongo_uri | The MongoDB URI connection string | `mongodb://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://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.
+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
+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
@@ -34,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
@@ -58,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:
@@ -74,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>
+46 -1
View File
@@ -14,7 +14,8 @@ 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 |
@@ -52,6 +81,22 @@ Here are the parameters available for configuring Valkey:
| `hnsw_ef_runtime` | Size of dynamic candidate list for search | `10` |
| `cluster_mode` | Enable cluster mode for Valkey cluster (CME) deployments | `false` |
| `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
+49 -3
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,7 +20,7 @@ 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
@@ -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 |
@@ -48,3 +79,18 @@ m.add("Your text here", user_id="user", metadata={"category": "example"})
| `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>
+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 supports Qdrant, Redis, PGVector, Supabase, LangChain, Azure AI Search, Vectorize, and an in-memory store.
The following vector databases are supported in the Python implementation. The TypeScript implementation currently supports Qdrant, Redis, PGVector, Supabase, LangChain, Azure AI Search, Vectorize, Amazon S3 Vectors, 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
+2 -2
View File
@@ -36,7 +36,7 @@ Every pull request must link to an issue using `Closes #<issue-number>`.
**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.
link to sign: it takes less than a minute and only needs to be done once.
## Submitting Your Contribution through a PR
@@ -134,7 +134,7 @@ pnpm run test:unit # unit tests with coverage
- **Formatter:** Prettier
- **Tests:** jest
- Always run type checking after changes: `pnpm run typecheck` (or `tsc --noEmit`)
- Use ES module `import` syntax — never `require()`
- Use ES module `import` syntax: never `require()`
---
+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" />
@@ -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
@@ -326,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.
@@ -374,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>
@@ -404,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.
@@ -849,7 +849,7 @@ recent = mem0_client.search(
</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())
@@ -973,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" />
@@ -76,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:
@@ -128,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.
---
@@ -278,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">
@@ -288,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" />
@@ -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" />
@@ -41,3 +41,5 @@ Visit [multimodal-demo.mem0.ai](https://multimodal-demo.mem0.ai) to experience M
Build voice-first companions that remember conversations.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -236,3 +236,5 @@ context = Mem0Context(user_id="user123")
Learn the core patterns for memory-powered agents with any SDK.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -129,3 +129,5 @@ With Mem0 and AWS services like Bedrock and OpenSearch, you can build intelligen
Understand how Mem0's memory system is benchmarked and evaluated.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -299,3 +299,5 @@ By storing and retrieving patient information intelligently, the assistant provi
Apply similar memory patterns to customer support workflows.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -136,3 +136,5 @@ In the example above:
Explore tool-calling patterns with the OpenAI Agents SDK.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -295,3 +295,5 @@ run().catch(console.error);
Fine-tune what memories get stored during tool calls.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -39,7 +39,7 @@ Let’s break down the main components.
### 1: Initialize Mem0 with Custom Instructions
We configure Mem0 with custom instructions that guide it to infer user memories tailored specifically for our usecase.
We configure Mem0 with custom instructions that guide it to infer user memories tailored specifically for our use case.
```python
from mem0 import MemoryClient
@@ -202,3 +202,5 @@ Full Code: [Personalized Search GitHub](https://github.com/mem0ai/mem0/blob/main
Categorize search results and user preferences for better personalization.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -364,3 +364,5 @@ Mem0 enables a seamless, intelligent content-writing workflow, perfect for conte
Automate email drafting with memory-powered context and tone matching.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -77,3 +77,5 @@ Watch Deep Research in action:
Build a video research assistant that remembers insights from content.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -432,3 +432,5 @@ By combining Mem0's memory capabilities with email processing, you can create in
Build customer support agents that remember context across tickets.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -121,3 +121,5 @@ As the conversation progresses, Mem0's memory automatically updates based on the
Extend support capabilities with intelligent email processing and routing.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
@@ -134,3 +134,5 @@ Mem0 enables fast, transparent collaboration for teams and agents, with full att
Apply collaborative memory patterns to customer support scenarios.
</Card>
</CardGroup>
<Snippet file="star-on-github.mdx" />
+17 -1
View File
@@ -9,10 +9,26 @@ With Mem0, you can create stateful LLM-based applications such as chatbots, virt
- More reliable
- Cost-effective by reducing the number of LLM interactions
- More engaging
- Enables long-term memory
- Enriched by long-term memory
Here are some examples of how Mem0 can be integrated into various applications:
## Start here
The most popular cookbooks to get going fast:
<CardGroup cols={3}>
<Card title="Build an AI companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
The core memory lifecycle, end to end.
</Card>
<Card title="Self-host with Ollama" icon="server" href="/cookbooks/companions/local-companion-ollama">
Run Mem0 fully local with Ollama.
</Card>
<Card title="Partition memory by entity" icon="layer-group" href="/cookbooks/essentials/entity-partitioning-playbook">
Scope memories per user, agent, and app.
</Card>
</CardGroup>
## Essentials
<CardGroup cols={2}>
+101
View File
@@ -0,0 +1,101 @@
---
title: "How Mem0 Works"
description: "What happens when you add, store, and search memories with Mem0."
icon: "diagram-project"
---
Mem0 sits between your application and your model. You send conversation turns to `add`, then call `search` before the next model request to fetch relevant context. Your app decides which returned memories to include in the prompt.
Use Mem0 when you want agents to remember useful facts across turns, sessions, or users without replaying the full transcript every time.
<Frame caption="Memory extraction: Mem0 turns messages into stored facts with metadata, embeddings, and optional entity relationships.">
<img src="/images/memory-extraction.png" alt="Mem0 memory extraction pipeline: store new memories after the response, context lookup to find related memories, extract memories (ADD only) from input and context, deduplicate and embed, entity linking, written to a SQL database (facts and metadata), vector database (embeddings and similarity), and entity store (entities and relationships)." />
</Frame>
## The mental model
| Without a memory layer | With Mem0 |
|---|---|
| Keep appending chat history to the prompt | Store facts once, then retrieve them by query |
| Make the model re-read old turns | Give the model only the relevant memories |
| Lose context when a session ends | Scope memory by `user_id`, `agent_id`, `run_id`, and metadata |
## Messages vs memories
You send Mem0 messages. By default, Mem0 stores extracted memories, not a verbatim transcript.
| Input | Stored memory |
|---|---|
| `"I prefer aisle seats"` | `User prefers aisle seats` |
| `"Let's use Postgres for this project"` | `Project decision: use Postgres` |
| Message metadata | Filterable fields such as category, app, user, or run |
Use `infer=False` when you need to store raw content exactly as provided. Otherwise, keep inference enabled so retrieval works on clean, deduplicated facts.
## Two phases: extraction and retrieval
Most applications use Mem0 in two places:
1. **After a useful interaction**, call `add` to store what should be remembered.
2. **Before a model call**, call `search` and pass the best results into your prompt.
### 1. Extraction (writing memory)
When new messages arrive, Mem0 extracts durable facts and stores them with the identifiers and metadata you provide.
1. **Context lookup.** Mem0 checks related existing memories so it can avoid storing the same fact again.
2. **Fact extraction.** An LLM extracts preferences, decisions, plans, and other details your agent can reuse.
3. **Deduplication and embedding.** Redundant facts are removed, then each memory is embedded for semantic search.
4. **Entity linking.** When configured, Mem0 links people, places, organizations, and concepts across memories.
The automatic extraction path is additive. If a user says, "I moved from Austin to Seattle," Mem0 can store the new fact without silently rewriting the old one. Use explicit `update` or `delete` operations when your application needs to correct or remove a memory.
### 2. Retrieval (reading memory)
When you call `search`, Mem0 ranks stored memories against your query and filters.
| Signal | What it does | Best for |
|---|---|---|
| **Semantic** | Vector similarity over embeddings | Conceptual questions |
| **Keyword** | Term matching for exact words and phrases | Names, IDs, and factual lookups |
| **Entity** | Boosts memories linked to entities in the query | Questions about a person, project, or account |
| **Temporal** | Scores candidates on time metadata extracted at write time against the query's temporal intent | Temporal questions ("when did...", current state, recency) |
Platform retrieval fuses these signals in the managed service. OSS retrieval depends on your configured vector store, optional reranker, and graph store.
<Note>
Always scope searches with filters such as `user_id`, `agent_id`, or `run_id`. This keeps memories from different users, agents, or sessions from mixing.
</Note>
## Where memories live
Mem0 stores different parts of a memory in stores built for different lookup patterns:
| Store | Holds | Purpose |
|---|---|---|
| **SQL database** | Facts and metadata | The source of truth for each memory |
| **Vector database** | Embeddings | Semantic similarity search |
| **Entity or graph store** | Entities and relationships | Relationship-aware retrieval when graph memory is enabled |
On Mem0 Platform, these stores are managed for you. In OSS, you choose and operate the backing stores through your configuration.
## Build against this flow
- Call `add` only for information worth reusing later: preferences, decisions, account facts, goals, and durable feedback.
- Call `search` before the model response, then include only the returned memories that help answer the current request.
- Use metadata for filters your product already cares about, such as workspace, feature area, tenant, or data source.
- Avoid storing secrets, raw credentials, or unredacted sensitive data. Mem0 is designed to retrieve stored context.
## Next steps
<CardGroup cols={3}>
<Card title="Memory types" icon="brain" href="/core-concepts/memory-types">
Choose the right scope for user, agent, run, and session memory.
</Card>
<Card title="Memory operations" icon="database" href="/core-concepts/memory-operations/add">
Add, search, update, and delete memories from your app.
</Card>
<Card title="See the benchmarks" icon="chart-line" href="/core-concepts/memory-evaluation">
Review the evaluation setup and benchmark results.
</Card>
</CardGroup>
+51 -51
View File
@@ -7,27 +7,28 @@ iconType: "solid"
## Why Memory Evaluation Matters
Most AI agent memory systems retrieve information by maximizing context window size. That works on benchmarks but not in production, where every token adds cost. **Token efficiency** — achieving high accuracy with less context per query — is what separates benchmark performance from production viability.
Most AI agent memory systems retrieve information by maximizing context window size. That works on benchmarks but not in production, where every token adds cost. **Token efficiency** means achieving high accuracy with less context per query. It is what separates benchmark performance from production viability.
The new Mem0 algorithm achieves competitive accuracy on LoCoMo, LongMemEval, and BEAM while averaging **under 7,000 tokens per retrieval call**. Full-context approaches on the same benchmarks routinely consume 25,000+ tokens per query.
Mem0's algorithm achieves competitive accuracy on LoCoMo, LongMemEval, and BEAM while averaging **under 7,000 tokens per retrieval call**. Full-context approaches on the same benchmarks routinely consume 25,000+ tokens per query. Unless noted otherwise, scores are reported at a **top_200 retrieval budget** (the 200 highest-ranked memories per query).
Evaluating a memory system at scale comes down to three parameters: **accuracy** (what the benchmarks measure), **cost** (context tokens per query), and **performance** (latency). Optimizing one is easy. Balancing all three at scale is the actual problem.
Some benchmarks today — particularly smaller ones like LoCoMo and LongMemEval — can be materially improved by aggressive retrieval strategies, larger context windows, or frontier models. That does not necessarily mean the underlying memory system has gotten better. We evaluate under constraints that reflect how memory systems actually run in production: limited context windows and practical token budgets.
Some benchmarks today, particularly smaller ones like LoCoMo and LongMemEval, can be materially improved by aggressive retrieval strategies, larger context windows, or frontier models. That does not necessarily mean the underlying memory system has gotten better. We evaluate under constraints that reflect how memory systems actually run in production: limited context windows and practical token budgets.
## Architecture Overview
Mem0's memory system operates across two phases, **extraction** (writing) and **retrieval** (reading), with a graph memory layer (entity linking) connecting them.
Mem0's memory system operates across two phases, **extraction** (writing) and **retrieval** (reading), connected by a graph memory layer (entity linking) and a temporal reasoning layer (time metadata written during extraction and scored during retrieval).
### Memory Extraction (Distillation)
When new conversations arrive, the extraction pipeline processes them through five stages:
When new conversations arrive, the extraction pipeline processes them through six stages:
1. **Store New Memories** — Conversation enters the pipeline asynchronously (after the agent responds)
2. **Context Lookup** — Find related existing memories to avoid duplicates
3. **Distill Memories** — Single-pass LLM extraction produces ADD-only facts from input + context
4. **Deduplicate + Embed** — Hash-based deduplication, then vectorize new memories
1. **Store New Memories**: Conversation enters the pipeline asynchronously (after the agent responds)
2. **Context Lookup**: Find related existing memories to avoid duplicates
3. **Distill Memories**: Single-pass LLM extraction produces ADD-only facts from input + context
4. **Deduplicate + Embed**: Hash-based deduplication, then vectorize new memories
5. **Graph Memory (Entity Linking)**: Identify entities (proper nouns, quoted text, compound noun phrases) and link them across memories into a graph
6. **Temporal Reasoning**: A separate temporal reasoning pass reads each new memory alongside the source conversation and its date, extracting temporal metadata: when the event occurred, whether it is ongoing or completed, how precise the timing is, and the memory type (event, state, plan, preference, relationship, absence). It is independent of extraction and can run asynchronously so writes stay fast; this metadata is stored with the memory and used later at retrieval.
Memories are distributed across three storage layers, each tuned for a specific retrieval pattern:
@@ -38,25 +39,26 @@ Memories are distributed across three storage layers, each tuned for a specific
| **SQL Database** | History log (ADD events) + rolling message window | Audit trail + extraction dedup context |
<Info>
The key architectural decision is **ADD-only extraction**. New facts are stored alongside old ones — nothing is overwritten or deleted. When information changes, both the old and new facts survive. This preserves temporal context and eliminates information loss from premature consolidation.
The key architectural decision is **ADD-only extraction**. New facts are stored alongside old ones. Nothing is overwritten or deleted. When information changes, both the old and new facts survive. This preserves temporal context and eliminates information loss from premature consolidation.
</Info>
### Multi-Signal Retrieval
When a query arrives, the retrieval pipeline scores candidates across three signals in parallel:
When a query arrives, the retrieval pipeline scores candidates across multiple signals in parallel:
1. **Semantic Search** — Vector similarity scoring against memory embeddings
2. **Keyword Search** — Normalized term matching via BM25 with verb-form lemmatization
3. **Entity Search** — Entity matching boosts memories linked to query entities
1. **Semantic Search**: Vector similarity scoring against memory embeddings
2. **Keyword Search**: Normalized term matching via BM25 with verb-form lemmatization
3. **Entity Search**: Entity matching boosts memories linked to query entities
4. **Temporal Reasoning**: The query's temporal intent is classified (with no extra LLM call), then each candidate is scored by how well the temporal metadata extracted at write time matches that intent.
Results are fused via rank scoring into a final top-K set. Different query types lean on different signals:
These signals are fused via rank scoring into the final top-K set. The temporal score is additive and semantic relevance always dominates; it nudges ranking toward the correct dated instance without filtering candidates out or overriding a strong semantic match, so relevant memories are never dropped. Different query types lean on different signals:
| Query Type | Primary Signal | Example |
|---|---|---|
| Conceptual | Semantic | "What does the user think about remote work?" |
| Factual/exact | BM25 keyword | "What meetings did I attend last week?" |
| Entity-centric | Entity matching | "What do we know about Alice?" |
| Temporal | Semantic + keyword | "When did the user first mention the project?" |
| Temporal | Temporal reasoning | "When did the user first mention the project?" |
The combined score outperformed every individual signal across every category tested.
@@ -66,37 +68,35 @@ The combined score outperformed every individual signal across every category te
[LoCoMo](https://github.com/snap-stanford/locomo) tests single-hop, multi-hop, open-domain, and temporal memory recall across conversational sessions.
| Category | Old Algorithm | New Algorithm | Delta |
|---|---|---|---|
| **Overall** | **71.4** | **91.6** | **+20.2** |
| Single-hop | 76.6 | 92.3 | +15.7 |
| Multi-hop | 70.2 | 93.3 | +23.1 |
| Open-domain | 57.3 | 76.0 | +18.7 |
| Temporal | 63.2 | 92.8 | +29.6 |
| Category | Score |
|---|---|
| **Overall** | **92.5** |
| Single-hop | 91.2 |
| Multi-hop | 91.3 |
| Open-domain | 72.7 |
| Temporal | 92.0 |
*Mean tokens: 6,956*
*Mean tokens: 6,956.*
The two largest gains are **temporal queries (+29.6)** and **multi-hop reasoning (+23.1)**. Both categories directly test the ADD-only architecture (preserving temporal context) and graph memory / entity linking (connecting facts across memories).
Temporal reasoning is on by default and helps most on temporal (92.0) and multi-hop (91.3) questions, where the system has to identify which dated instance applies, while open-domain (72.7) does not benefit and is actively being tuned.
### LongMemEval
[LongMemEval](https://github.com/xiaowu0162/LongMemEval) evaluates memory across single-session and multi-session contexts, including knowledge updates and temporal reasoning.
| Category | Old Algorithm | New Algorithm | Delta |
|---|---|---|---|
| **Overall** | **67.8** | **93.4** | **+25.6** |
| Single-session (user) | 94.3 | 97.1 | +2.8 |
| Single-session (assistant) | 46.4 | 100.0 | +53.6 |
| Single-session (preference) | 76.7 | 96.7 | +20.0 |
| Knowledge update | 79.5 | 96.2 | +16.7 |
| Temporal reasoning | 51.1 | 93.2 | +42.1 |
| Multi-session | 70.7 | 86.5 | +15.8 |
| Category | Score |
|---|---|
| **Overall** | **94.4** |
| Single-session (user) | 98.6 |
| Single-session (assistant) | 98.2 |
| Single-session (preference) | 96.7 |
| Knowledge update | 93.6 |
| Temporal reasoning | 97.0 |
| Multi-session | 88.0 |
*Mean tokens: 6,787*
*Mean tokens: 6,787.*
The biggest gain is **single-session assistant (+53.6)** — the previous algorithm had a blind spot for agent-generated facts. The new algorithm treats them as first-class memories.
The **+42.1 on temporal reasoning** reflects the ADD-only architecture preserving chronological context that the previous UPDATE/DELETE model would destroy.
Temporal reasoning is the standout at a top_200 budget, reaching **97.0** on the temporal-reasoning category, with single-session user and assistant both near-saturated (98.6 and 98.2). Knowledge update (93.6) remains the hardest category for an additive, ADD-only architecture: older facts are preserved rather than overwritten, so semantically similar prior facts can still surface alongside newer ones.
### BEAM
@@ -119,19 +119,19 @@ The **+42.1 on temporal reasoning** reflects the ADD-only architecture preservin
*Mean tokens (1M): 6,719. Mean tokens (10M): 6,914.*
<Info>
**BEAM is the most relevant benchmark here.** It operates at 1M and 10M token scales and cannot be solved by simply expanding the context window. The results at 10M reflect where memory systems actually stand at production context volumes. The system holds up well on preference following, instruction following, and knowledge updates at both scales. Weaker categories at 10M (temporal reasoning, event ordering, multi-session reasoning) are open problems across the field — they require higher-order representations of how events relate to each other across time, which is a primary focus of our ongoing research.
**BEAM is the most relevant benchmark here.** It operates at 1M and 10M token scales and cannot be solved by simply expanding the context window. The results at 10M reflect where memory systems actually stand at production context volumes. The system holds up well on preference following, instruction following, and knowledge updates at both scales. Weaker categories at 10M (temporal reasoning, event ordering, multi-session reasoning) are open problems across the field. They require higher-order representations of how events relate to each other across time, which is a primary focus of our ongoing research.
</Info>
### Performance Summary
All results use a single-pass retrieval setup: one retrieval call, one answer, no agentic loops.
All results use a single-pass retrieval setup (one retrieval call, one answer, no agentic loops) at a top_200 retrieval budget.
| Benchmark | Old Algorithm | New Algorithm | Average tokens / query |
|---|---|---|---|
| **LoCoMo** | 71.4 | **91.6** | 6,956 |
| **LongMemEval** | 67.8 | **93.4** | 6,787 |
| **BEAM (1M)** | — | **64.1** | 6,719 |
| **BEAM (10M)** | — | **48.6** | 6,914 |
| Benchmark | Score | Average tokens / query |
|---|---|---|
| **LoCoMo** | **92.5** | 6,956 |
| **LongMemEval** | **94.4** | 6,787 |
| **BEAM (1M)** | **64.1** | 6,719 |
| **BEAM (10M)** | **48.6** | 6,914 |
<Info>
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.
@@ -183,7 +183,7 @@ Each benchmark is a Python module with its own runner ([source code](https://git
|---|---|---|
| `--project-name` | (required) | Run identifier for tracking results |
| `--backend` | `oss` | `oss` (self-hosted) or `cloud` (Mem0 Platform) |
| `--mem0-api-key` | — | Mem0 API key (required for `cloud` backend) |
| `--mem0-api-key` | N/A | Mem0 API key (required for `cloud` backend) |
| `--mem0-host` | `http://localhost:8888` | Mem0 server URL (for `oss` backend) |
| `--top-k` | `200` | Number of memories to retrieve per query |
| `--top-k-cutoffs` | `10,20,50,200` | Evaluate accuracy at multiple retrieval depths (BEAM default: `100`) |
@@ -192,9 +192,9 @@ Each benchmark is a Python module with its own runner ([source code](https://git
| `--provider` | `openai` | LLM provider: `openai`, `anthropic`, `azure` |
| `--judge-provider` | (same as `--provider`) | Override provider for the judge model |
| `--max-workers` | `10` | Parallel workers for evaluation |
| `--predict-only` | — | Stop after search, skip answer + judge phases |
| `--evaluate-only` | — | Skip ingest + search, evaluate existing results |
| `--resume` | — | Resume from checkpoint (BEAM and LongMemEval; on by default for LongMemEval) |
| `--predict-only` | N/A | Stop after search, skip answer + judge phases |
| `--evaluate-only` | N/A | Skip ingest + search, evaluate existing results |
| `--resume` | N/A | Resume from checkpoint (BEAM and LongMemEval; on by default for LongMemEval) |
<CodeGroup>
```bash LoCoMo
@@ -329,7 +329,7 @@ When evaluating memory systems, keep these considerations in mind:
Yes. For self-hosted, configure the extraction model in your `mem0-config.yaml` (see the `configs/` directory of the evaluation repo for provider-specific examples). For Mem0 Cloud, extraction uses the platform's default. Using a frontier model will likely produce higher scores but at higher cost and latency.
</Accordion>
<Accordion title="Why are BEAM scores lower than LoCoMo/LongMemEval?">
BEAM operates at 1M and 10M token scales — orders of magnitude larger than LoCoMo or LongMemEval. At these scales, similar content appears multiple times across the window, and the memory system must surface the exact correct memory over many close matches. The scores reflect the genuine difficulty of the task, not a regression in the algorithm.
BEAM operates at 1M and 10M token scales, orders of magnitude larger than LoCoMo or LongMemEval. At these scales, similar content appears multiple times across the window, and the memory system must surface the exact correct memory over many close matches. The scores reflect the genuine difficulty of the task, not a regression in the algorithm.
</Accordion>
<Accordion title="How do I contribute a new benchmark?">
Open a pull request to the [memory-benchmarks repository](https://github.com/mem0ai/memory-benchmarks) with your benchmark implementation. See the repository README for the expected interface and format.
+8 -16
View File
@@ -9,26 +9,19 @@ iconType: "solid"
Adding memory is how Mem0 captures useful details from a conversation so your agents can reuse them later. Think of it as saving the important sentences from a chat transcript into a structured notebook your agent can search.
<Info>
**Why it matters**
- Preserves user preferences, goals, and feedback across sessions.
- Powers personalization and decision-making in downstream conversations.
- Keeps context consistent between managed Platform and OSS deployments.
</Info>
## Key terms
- **Messages** – The ordered list of user/assistant turns you send to `add`.
- **Infer** – Controls whether Mem0 extracts structured memories (`infer=True`, default) or stores raw messages.
- **Metadata** – Optional filters (e.g., `{"category": "movie_recommendations"}`) that improve retrieval later.
- **User / Session identifiers** – `user_id`, `agent_id`, `app_id`, or `run_id` that scope the memory for future searches.
- **Messages**: The ordered list of user/assistant turns you send to `add`.
- **Infer**: Controls whether Mem0 extracts structured memories (`infer=True`, default) or stores raw messages.
- **Metadata**: Optional filters (e.g., `{"category": "movie_recommendations"}`) that improve retrieval later.
- **User / Session identifiers**: `user_id`, `agent_id`, `app_id`, or `run_id` that scope the memory for future searches.
## How does it work?
Mem0 offers two flows:
- **Mem0 Platform** – Fully managed API with dashboard and scaling.
- **Mem0 Open Source** – Local SDK that you run in your own environment.
- **Mem0 Platform**: Fully managed API with dashboard and scaling.
- **Mem0 Open Source**: Local SDK that you run in your own environment.
Both flows take the same payload and add memories through an additive pipeline.
@@ -48,7 +41,7 @@ Future searches rank the most relevant memories for the query.
When you switch to `infer=False`, Mem0 stores your payload exactly as provided, so duplicates can land. Mixing both modes for the same fact can save it twice.
</Warning>
You trigger this pipeline with a single `add` call—no manual orchestration needed.
You trigger this pipeline with a single `add` call: no manual orchestration needed.
## Add with Mem0 Platform
@@ -157,7 +150,6 @@ Add memory whenever your agent learns something useful:
Storing this context allows the agent to reason better in future interactions.
### More Details
For full list of supported fields, required formats, and advanced options, see the
@@ -169,7 +161,7 @@ For full list of supported fields, required formats, and advanced options, see t
| --- | --- | --- |
| Add behavior | ADD-only; memories accumulate | ADD-only; you control storage |
| Rate limits | Managed quotas per workspace | Limited by your hardware and provider APIs |
| Dashboard visibility | Yes — inspect memories visually | Inspect via CLI, logs, or custom UI |
| Dashboard visibility | Yes: inspect memories visually | Inspect via CLI, logs, or custom UI |
## Put it into practice
+11 -11
View File
@@ -18,10 +18,10 @@ Deleting memories is how you honor compliance requests, undo bad data, or clean
## Key terms
- **memory_id** – Unique ID returned by `add`/`search` identifying the record to delete.
- **batch_delete** – API call that removes up to 1000 memories in one request.
- **delete_all** – Filter-based deletion by user, agent, run, or metadata.
- **immutable** – Flagged memories that cannot be updated; delete + re-add instead.
- **memory_id**: Unique ID returned by `add`/`search` identifying the record to delete.
- **batch_delete**: API call that removes up to 1000 memories in one request.
- **delete_all**: Filter-based deletion by user, agent, run, or metadata.
- **immutable**: Flagged memories that cannot be updated; delete + re-add instead.
## How the delete flow works
@@ -152,7 +152,7 @@ client.delete_all(user_id="*")
# Delete all memories across every agent in the project
client.delete_all(agent_id="*")
# Full project wipe — all four filters must be explicitly set to "*"
# Full project wipe: all four filters must be explicitly set to "*"
client.delete_all(user_id="*", agent_id="*", app_id="*", run_id="*")
```
@@ -166,7 +166,7 @@ client.deleteAll({ userId: "*" })
.then(result => console.log(result))
.catch(error => console.error(error));
// Full project wipe — all four filters must be explicitly set to "*"
// Full project wipe: all four filters must be explicitly set to "*"
client.deleteAll({ userId: "*", agentId: "*", appId: "*", runId: "*" })
.then(result => console.log(result))
.catch(error => console.error(error));
@@ -191,7 +191,7 @@ memory.delete_all(user_id="alice")
</CodeGroup>
<Note>
The OSS JavaScript SDK does not yet expose deletion helpers—use the REST API or Python SDK when self-hosting.
The OSS JavaScript SDK does not yet expose deletion helpers: use the REST API or Python SDK when self-hosting.
</Note>
## Use cases recap
@@ -216,7 +216,7 @@ memory.delete_all(user_id="alice")
## Put it into practice
- Review the <Link href="/api-reference/memory/delete-memory">Delete Memory API reference</Link>, plus <Link href="/api-reference/memory/batch-delete">Batch Delete</Link> and <Link href="/api-reference/memory/delete-memories">Filtered Delete</Link>.
- Pair deletes with <Link href="/platform/features/platform-overview">Expiration Policies</Link> to automate retention.
- Pair deletes with the <Link href="/api-reference/memory/update-memory">expiration date field</Link> to automate retention.
## See it live
@@ -233,9 +233,9 @@ memory.delete_all(user_id="alice")
href="/core-concepts/memory-operations/add"
/>
<Card
title="Enable Expiration Policies"
description="Automate retention with the platform’s expiration feature."
title="Set an Expiration Date"
description="Automate retention with the expiration date field on update."
icon="clock"
href="/platform/features/platform-overview"
href="/api-reference/memory/update-memory"
/>
</CardGroup>
@@ -9,19 +9,12 @@ iconType: "solid"
Mem0's search operation lets agents ask natural-language questions and get back the memories that matter most. Like a smart librarian, it finds exactly what you need from everything you've stored.
<Info>
**Why it matters**
- Retrieves the right facts without rebuilding prompts from scratch.
- Supports both managed Platform and OSS so you can test locally and deploy at scale.
- Keeps results relevant with filters, rerankers, and thresholds.
</Info>
## Key terms
- **Query** – Natural-language question or statement you pass to `search`.
- **Filters** – JSON logic (AND/OR, comparison operators) that narrows results by user, categories, dates, etc.
- **top_k / threshold** – Controls how many memories return and the minimum similarity score.
- **Rerank** – Optional second pass that boosts precision when a reranker is configured.
- **Query**: Natural-language question or statement you pass to `search`.
- **Filters**: JSON logic (AND/OR, comparison operators) that narrows results by user, categories, dates, etc.
- **top_k / threshold**: Controls how many memories return and the minimum similarity score.
- **Rerank**: Optional second pass that boosts precision when a reranker is configured.
## Architecture
@@ -70,7 +63,7 @@ m.search("What are Alice's hobbies?", filters={"user_id": "alice"})
| Capability | Mem0 Platform | Mem0 OSS |
| --- | --- | --- |
| **Entity IDs on search / get_all** | Inside `filters={"user_id": "alice"}` | Inside `filters={"user_id": "alice"}` (aligned with Platform in v3 — top-level kwargs raise `ValueError`) |
| **Entity IDs on search / get_all** | Inside `filters={"user_id": "alice"}` | Inside `filters={"user_id": "alice"}` (aligned with Platform in v3: top-level kwargs raise `ValueError`) |
| **Filter syntax** | Logical operators (`AND`, `OR`, comparisons) with field-level access | Basic field filters, extend via Python hooks |
| **Reranking** | Toggle `rerank=True` with managed reranker catalog | Requires configuring local or third-party rerankers |
| **Thresholds** | Request-level configuration (`threshold`, `top_k`) | Controlled via SDK parameters |
@@ -121,7 +114,7 @@ from mem0 import Memory
m = Memory()
# Simple search — entity IDs go in `filters`
# Simple search: entity IDs go in `filters`
related_memories = m.search("Should I drink coffee or tea?", filters={"user_id": "alice"})
# Search with additional metadata filters (combine entity + metadata in the same dict)
@@ -136,7 +129,7 @@ import { Memory } from 'mem0ai/oss';
const memory = new Memory();
// Simple search — entity IDs go inside `filters`
// Simple search: entity IDs go inside `filters`
const relatedMemories = memory.search("Should I drink coffee or tea?", {
filters: { userId: "alice" },
});
@@ -203,7 +196,7 @@ client.search("query", filters={
*OSS:*
```python
# Get memories from a specific agent session — entity IDs combined in filters
# Get memories from a specific agent session: entity IDs combined in filters
m.search("query", filters={
"user_id": "alice",
"agent_id": "chatbot",
@@ -9,21 +9,14 @@ iconType: "solid"
Mem0’s update operation lets you fix or enrich an existing memory without deleting it. When a user changes their preference or clarifies a fact, use update to keep the knowledge base fresh.
<Info>
**Why it matters**
- Corrects outdated or incorrect memories immediately.
- Adds new metadata so filters and rerankers stay sharp.
- Works for both one-off edits and large batches (up to 1000 memories).
</Info>
## Key terms
- **memory_id** – Unique identifier returned by `add` or `search` results.
- **text** / **data** – New content that replaces the stored memory value.
- **metadata** – Optional key-value pairs you update alongside the text.
- **timestamp** – Unix epoch (int/float) or ISO 8601 string to override the memory's timestamp.
- **batch_update** – Platform API that edits multiple memories in a single request.
- **immutable** – Flagged memories that must be deleted and re-added instead of updated.
- **memory_id**: Unique identifier returned by `add` or `search` results.
- **text** / **data**: New content that replaces the stored memory value.
- **metadata**: Optional key-value pairs you update alongside the text.
- **timestamp**: Unix epoch (int/float) or ISO 8601 string to override the memory's timestamp.
- **batch_update**: Platform API that edits multiple memories in a single request.
- **immutable**: Flagged memories that must be deleted and re-added instead of updated.
## How the update flow works
@@ -127,7 +120,7 @@ memory.update(
</CodeGroup>
<Note>
OSS JavaScript SDK does not expose `update` yet—use the REST API or Python SDK when self-hosting.
OSS JavaScript SDK does not expose `update` yet: use the REST API or Python SDK when self-hosting.
</Note>
## Tips
@@ -148,7 +141,7 @@ memory.update(
| Update call | `client.update(memory_id, {...})` | `memory.update(memory_id, data=...)` |
| Batch updates | `client.batch_update` (up to 1000 memories) | Script your own loop or bulk job |
| Dashboard visibility | Inspect updates in the UI | Inspect via logs or custom tooling |
| Immutable handling | Returns descriptive error | Raises exception—delete and re-add |
| Immutable handling | Returns descriptive error | Raises exception: delete and re-add |
## Put it into practice
+18 -25
View File
@@ -9,19 +9,12 @@ iconType: "solid"
Mem0 separates memory into layers so agents remember the right detail at the right time. Think of it like a notebook: a sticky note for the current task, a daily journal for the session, and an archive for everything a user has shared.
<Info>
**Why it matters**
- Keeps conversations coherent without repeating instructions.
- Lets agents personalize responses based on long-term preferences.
- Avoids over-fetching data by scoping memory to the correct layer.
</Info>
## Key terms
- **Conversation memory** – In-flight messages inside a single turn (what was just said).
- **Session memory** – Short-lived facts that apply for the current task or channel.
- **User memory** – Long-lived knowledge tied to a person, account, or workspace.
- **Organizational memory** – Shared context available to multiple agents or teams.
- **Conversation memory**: In-flight messages inside a single turn (what was just said).
- **Session memory**: Short-lived facts that apply for the current task or channel.
- **User memory**: Long-lived knowledge tied to a person, account, or workspace.
- **Organizational memory**: Shared context available to multiple agents or teams.
```mermaid
graph LR
@@ -35,15 +28,15 @@ graph LR
Short-term memory keeps the current conversation coherent. It includes:
- **Conversation history** – recent turns in order so the agent remembers what was just said.
- **Working memory** – temporary state such as tool outputs or intermediate calculations.
- **Attention context** – the immediate focus of the assistant, similar to what a person holds in mind mid-sentence.
- **Conversation history**: recent turns in order so the agent remembers what was just said.
- **Working memory**: temporary state such as tool outputs or intermediate calculations.
- **Attention context**: the immediate focus of the assistant, similar to what a person holds in mind mid-sentence.
Long-term memory preserves knowledge across sessions. It captures:
- **Factual memory** – user preferences, account details, and domain facts.
- **Episodic memory** – summaries of past interactions or completed tasks.
- **Semantic memory** – relationships between concepts so agents can reason about them later.
- **Factual memory**: user preferences, account details, and domain facts.
- **Episodic memory**: summaries of past interactions or completed tasks.
- **Semantic memory**: relationships between concepts so agents can reason about them later.
Mem0 maps these classic categories onto its layered storage so you can decide what should fade quickly versus what should last for months.
@@ -51,9 +44,9 @@ Mem0 maps these classic categories onto its layered storage so you can decide wh
Mem0 stores each layer separately and merges them when you query:
1. **Capture** – Messages enter the conversation layer while the turn is active.
2. **Promote** – Relevant details persist to session or user memory based on your `user_id`, `run_id`, and metadata.
3. **Retrieve** – The search pipeline pulls from all layers, ranking user memories first, then session notes, then raw history.
1. **Capture**: Messages enter the conversation layer while the turn is active.
2. **Promote**: Relevant details persist to session or user memory based on your `user_id`, `run_id`, and metadata.
3. **Retrieve**: The search pipeline pulls from all layers, ranking user memories first, then session notes, then raw history.
```python
import os
@@ -82,10 +75,10 @@ results = memory.search(
## When should you use each layer?
- **Conversation memory** – Tool calls or chain-of-thought that only matter within the current turn.
- **Session memory** – Multi-step tasks (onboarding flows, debugging sessions) that should reset once complete.
- **User memory** – Personal preferences, account state, or compliance details that must persist across interactions.
- **Organizational memory** – Shared FAQs, product catalogs, or policies that every agent should recall.
- **Conversation memory**: Tool calls or chain-of-thought that only matter within the current turn.
- **Session memory**: Multi-step tasks (onboarding flows, debugging sessions) that should reset once complete.
- **User memory**: Personal preferences, account state, or compliance details that must persist across interactions.
- **Organizational memory**: Shared FAQs, product catalogs, or policies that every agent should recall.
## How it compares
@@ -97,7 +90,7 @@ results = memory.search(
| Org | Configured globally | Long-term | Shared knowledge | Needs owner to keep current |
<Warning>
Avoid storing secrets or unredacted PII in user or org memories—Mem0 is retrievable by design. Encrypt or hash sensitive values first.
Avoid storing secrets or unredacted PII in user or org memories: Mem0 is retrievable by design. Encrypt or hash sensitive values first.
</Warning>
## Put it into practice
+190 -124
View File
@@ -8,7 +8,7 @@
"light": "#8F74E0",
"dark": "#8F74E0"
},
"favicon": "/logo/favicon.png",
"favicon": "/logo/favicon.svg",
"logo": {
"light": "/logo/light.svg",
"dark": "/logo/dark.svg",
@@ -21,7 +21,7 @@
"icon": "book-open",
"tabs": [
{
"tab": "Welcome",
"tab": "Get Started",
"groups": [
{
"group": "Start Here",
@@ -39,19 +39,20 @@
"group": "Getting Started",
"icon": "rocket",
"pages": [
"platform/quickstart",
"platform/overview",
"platform/agent-signup",
"vibecoding",
"platform/mem0-mcp",
"platform/cli",
"platform/platform-vs-oss",
"platform/quickstart"
"platform/mem0-mcp",
"platform/platform-vs-oss"
]
},
{
"group": "Core Concepts",
"icon": "brain",
"pages": [
"core-concepts/how-it-works",
"core-concepts/memory-types",
"core-concepts/memory-operations/add",
"core-concepts/memory-operations/search",
@@ -61,12 +62,11 @@
]
},
{
"group": "Platform Features",
"group": "Features",
"icon": "star",
"pages": [
"platform/features/platform-overview",
{
"group": "Essential Features",
"group": "Essentials",
"icon": "circle-check",
"pages": [
"platform/features/v2-memory-filters",
@@ -79,7 +79,7 @@
]
},
{
"group": "Advanced Features",
"group": "Advanced",
"icon": "bolt",
"pages": [
"platform/features/advanced-retrieval",
@@ -100,52 +100,30 @@
]
},
{
"group": "Integration Features",
"group": "Integrations",
"icon": "plug",
"pages": [
"platform/features/webhooks",
"platform/features/feedback-mechanism",
"platform/features/group-chat",
"platform/features/mcp-integration"
"platform/features/group-chat"
]
}
]
},
{
"group": "Support & Troubleshooting",
"group": "Support",
"icon": "life-buoy",
"pages": [
"platform/faqs"
]
},
{
"group": "Migration Guide",
"group": "Migration",
"icon": "arrow-right",
"pages": [
"migration/platform-v2-to-v3",
"migration/oss-to-platform"
]
},
{
"group": "Contribute",
"icon": "clipboard-list",
"pages": [
"platform/contribute"
]
}
]
},
{
"tab": "OpenClaw",
"groups": [
{
"group": "Agent Harness",
"icon": "robot",
"pages": [
"integrations/openclaw",
"integrations/hermes",
"integrations/pi-agent"
]
}
]
},
@@ -157,14 +135,14 @@
"icon": "rocket",
"pages": [
"open-source/overview",
"open-source/setup",
"vibecoding",
"open-source/python-quickstart",
"open-source/node-quickstart"
"open-source/node-quickstart",
"open-source/setup",
"vibecoding"
]
},
{
"group": "Self-Hosting Features",
"group": "Features",
"icon": "server",
"pages": [
"open-source/features/overview",
@@ -314,77 +292,8 @@
"icon": "users",
"pages": [
"contributing/development",
"contributing/documentation"
]
}
]
},
{
"tab": "Cookbooks",
"groups": [
{
"group": "Getting Started",
"icon": "lightbulb",
"pages": [
"cookbooks/overview"
]
},
{
"group": "Essentials",
"icon": "flag",
"pages": [
"cookbooks/essentials/building-ai-companion",
"cookbooks/essentials/entity-partitioning-playbook",
"cookbooks/essentials/controlling-memory-ingestion",
"cookbooks/essentials/tagging-and-organizing-memories",
"cookbooks/essentials/exporting-memories"
]
},
{
"group": "Companion Playbooks",
"icon": "users",
"pages": [
"cookbooks/companions/quickstart-demo",
"cookbooks/companions/nodejs-companion",
"cookbooks/companions/ai-tutor",
"cookbooks/companions/travel-assistant",
"cookbooks/companions/youtube-research",
"cookbooks/companions/voice-companion-openai",
"cookbooks/companions/local-companion-ollama"
]
},
{
"group": "Ops & Automations",
"icon": "briefcase",
"pages": [
"cookbooks/operations/support-inbox",
"cookbooks/operations/email-automation",
"cookbooks/operations/content-writing",
"cookbooks/operations/deep-research",
"cookbooks/operations/team-task-agent"
]
},
{
"group": "Integrations & Platforms",
"icon": "plug",
"pages": [
"cookbooks/integrations/agents-sdk-tool",
"cookbooks/integrations/openai-tool-calls",
"cookbooks/integrations/mastra-agent",
"cookbooks/integrations/healthcare-google-adk",
"cookbooks/integrations/aws-bedrock",
"cookbooks/integrations/tavily-search"
]
},
{
"group": "Frameworks & Multimodal",
"icon": "layers",
"pages": [
"cookbooks/frameworks/llamaindex-react",
"cookbooks/frameworks/llamaindex-multiagent",
"cookbooks/frameworks/multimodal-retrieval",
"cookbooks/frameworks/eliza-os-character",
"cookbooks/frameworks/gemini-3-with-mem0-mcp"
"contributing/documentation",
"platform/contribute"
]
}
]
@@ -472,6 +381,76 @@
}
]
},
{
"tab": "Cookbooks",
"groups": [
{
"group": "Getting Started",
"icon": "lightbulb",
"pages": [
"cookbooks/overview"
]
},
{
"group": "Essentials",
"icon": "flag",
"pages": [
"cookbooks/essentials/building-ai-companion",
"cookbooks/essentials/entity-partitioning-playbook",
"cookbooks/essentials/controlling-memory-ingestion",
"cookbooks/essentials/tagging-and-organizing-memories",
"cookbooks/essentials/exporting-memories"
]
},
{
"group": "Companion Playbooks",
"icon": "users",
"pages": [
"cookbooks/companions/quickstart-demo",
"cookbooks/companions/nodejs-companion",
"cookbooks/companions/ai-tutor",
"cookbooks/companions/travel-assistant",
"cookbooks/companions/youtube-research",
"cookbooks/companions/voice-companion-openai",
"cookbooks/companions/local-companion-ollama"
]
},
{
"group": "Ops & Automations",
"icon": "briefcase",
"pages": [
"cookbooks/operations/support-inbox",
"cookbooks/operations/email-automation",
"cookbooks/operations/content-writing",
"cookbooks/operations/deep-research",
"cookbooks/operations/team-task-agent"
]
},
{
"group": "Integrations & Platforms",
"icon": "plug",
"pages": [
"cookbooks/integrations/agents-sdk-tool",
"cookbooks/integrations/openai-tool-calls",
"cookbooks/integrations/mastra-agent",
"cookbooks/integrations/healthcare-google-adk",
"cookbooks/integrations/aws-bedrock",
"cookbooks/integrations/tavily-search"
]
},
{
"group": "Frameworks & Multimodal",
"icon": "layers",
"pages": [
"cookbooks/frameworks/llamaindex-react",
"cookbooks/frameworks/llamaindex-multiagent",
"cookbooks/frameworks/multimodal-retrieval",
"cookbooks/frameworks/eliza-os-character",
"cookbooks/frameworks/gemini-3-with-mem0-mcp"
]
}
]
},
{
"tab": "API Reference",
"groups": [
@@ -495,7 +474,7 @@
]
},
{
"group": "Memory APIs",
"group": "Memory Management",
"icon": "sparkles",
"pages": [
"api-reference/memory/create-memory-export",
@@ -509,7 +488,7 @@
]
},
{
"group": "Events APIs",
"group": "Events",
"icon": "clock",
"pages": [
"api-reference/events/get-events",
@@ -517,7 +496,7 @@
]
},
{
"group": "Entities APIs",
"group": "Entities",
"icon": "users",
"pages": [
"api-reference/entities/get-users",
@@ -525,7 +504,7 @@
]
},
{
"group": "Organizations APIs",
"group": "Organizations",
"icon": "building",
"pages": [
"api-reference/organization/create-org",
@@ -539,7 +518,7 @@
]
},
{
"group": "Project APIs",
"group": "Projects",
"icon": "folder",
"pages": [
"api-reference/project/create-project",
@@ -554,7 +533,7 @@
]
},
{
"group": "Webhook APIs",
"group": "Webhooks",
"icon": "webhook",
"pages": [
"api-reference/webhook/create-webhook",
@@ -574,8 +553,7 @@
"pages": [
"changelog/highlights",
"changelog/sdk",
"changelog/platform",
"changelog/openclaw"
"changelog/platform"
]
}
]
@@ -629,6 +607,10 @@
]
},
"redirects": [
{
"source": "/changelog/openclaw",
"destination": "/changelog/sdk"
},
{
"source": "/components/rerankers/models/llm",
"destination": "/components/rerankers/models/llm_reranker"
@@ -981,17 +963,25 @@
"source": "/v0x/introduction",
"destination": "/introduction"
},
{
"source": "/platform/features/mcp-integration",
"destination": "/platform/mem0-mcp"
},
{
"source": "/platform/features/platform-overview",
"destination": "/platform/features/v2-memory-filters"
},
{
"source": "/features/async-client",
"destination": "/platform/features/async-client"
},
{
"source": "/features/custom-prompts",
"destination": "/platform/features/platform-overview"
"destination": "/platform/features/custom-instructions"
},
{
"source": "/features/selective-memory",
"destination": "/platform/features/platform-overview"
"destination": "/platform/features/custom-instructions"
},
{
"source": "/features/custom-categories",
@@ -1023,7 +1013,7 @@
},
{
"source": "/features/online-memory",
"destination": "/platform/features/platform-overview"
"destination": "/platform/features/async-client"
},
{
"source": "/features/multimodal",
@@ -1031,7 +1021,7 @@
},
{
"source": "/features/inferences",
"destination": "/platform/features/platform-overview"
"destination": "/core-concepts/how-it-works"
},
{
"source": "/features/graph-memory",
@@ -1043,7 +1033,7 @@
},
{
"source": "/platform/features/online-memory",
"destination": "/platform/features/platform-overview"
"destination": "/platform/features/async-client"
},
{
"source": "/platform/features/multimodal",
@@ -1051,7 +1041,7 @@
},
{
"source": "/platform/features/inferences",
"destination": "/platform/features/platform-overview"
"destination": "/core-concepts/how-it-works"
},
{
"source": "/platform/features/custom-prompts",
@@ -1160,6 +1150,82 @@
{
"source": "/openmemory/integrations",
"destination": "/introduction"
},
{
"source": "/self-hosting",
"destination": "/open-source/overview"
},
{
"source": "/self-hosting/:slug",
"destination": "/open-source/overview"
},
{
"source": "/self-hosted",
"destination": "/open-source/overview"
},
{
"source": "/self-hosted/:slug",
"destination": "/open-source/overview"
},
{
"source": "/getting-started",
"destination": "/platform/quickstart"
},
{
"source": "/getting-started/:slug",
"destination": "/platform/quickstart"
},
{
"source": "/deployment",
"destination": "/open-source/setup"
},
{
"source": "/deployment/:slug",
"destination": "/open-source/setup"
},
{
"source": "/configuration",
"destination": "/open-source/configuration"
},
{
"source": "/oss",
"destination": "/open-source/overview"
},
{
"source": "/oss/:slug",
"destination": "/open-source/overview"
},
{
"source": "/concepts/:slug",
"destination": "/core-concepts/:slug"
},
{
"source": "/pricing",
"destination": "/platform/overview"
},
{
"source": "/get-started/installation",
"destination": "/platform/quickstart"
},
{
"source": "/api-reference/add-memory",
"destination": "/api-reference/memory/add-memories"
},
{
"source": "/components/graph_memory/overview",
"destination": "/migration/oss-v2-to-v3"
},
{
"source": "/platform/features/mcp-quickstart",
"destination": "/platform/mem0-mcp"
},
{
"source": "/open-source/features/supported-vector-dbs",
"destination": "/components/vectordbs/overview"
},
{
"source": "/open-source/multimodal-support",
"destination": "/open-source/features/multimodal-support"
}
]
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 383 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 222 KiB

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