feat(skills): introduce Mem0 skill graph with dedicated CLI and Vercel AI SDK skills (#4725)

This commit is contained in:
Saket Aryan
2026-04-06 20:41:29 +05:30
committed by GitHub
parent 07f0d4f1e0
commit 4c2db3e68b
19 changed files with 4316 additions and 72 deletions
@@ -0,0 +1,690 @@
# Mem0 CLI Command Reference
Complete reference for every command, argument, flag, and output mode in the mem0 CLI. Both the Node.js (`@mem0/cli`) and Python (`mem0-cli`) implementations are identical in behavior.
---
## Global Options
These options are available on every command:
| Flag | Type | Description |
|------|------|-------------|
| `--json` / `--agent` | boolean | Agent mode: wrap all output in a structured JSON envelope on stdout. Spinners and progress go to stderr. |
| `-o, --output <format>` | string | Output format. Supported values vary per command (see matrix below). |
| `--api-key <key>` | string | Override the API key for this invocation. Takes precedence over env var and config file. |
| `--base-url <url>` | string | Override the API base URL (default: `https://api.mem0.ai`). |
| `--version` | boolean | Print version and exit. |
---
## Commands
### `mem0 init`
Interactive setup wizard. Configures API key and default user ID.
**Usage:** `mem0 init [OPTIONS]`
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `--api-key <key>` | string | - | API key (skip interactive prompt). |
| `-u, --user-id <id>` | string | - | Default user ID (skip interactive prompt). |
| `--email <addr>` | string | - | Login via email verification code instead of API key. |
| `--code <code>` | string | - | Verification code (use with `--email` for fully non-interactive login). |
| `--force` | boolean | false | Overwrite existing config without confirmation. |
**Behavior:**
- If `~/.mem0/config.json` already exists with an API key, warns and asks for confirmation (or errors in non-TTY unless `--force` is set).
- **Email login flow** (`--email`): sends a 6-digit code to the email via `POST /api/v1/auth/email_code/`. If `--code` is also given, verifies immediately. On success, saves API key, org_id, and project_id. Cannot be combined with `--api-key`.
- **API key flow**: if both `--api-key` and `--user-id` are given, runs fully non-interactively. Otherwise prompts for missing values.
- In non-TTY without sufficient flags, prints a usage hint and exits with error.
**Examples:**
```bash
mem0 init
mem0 init --api-key m0-xxx --user-id alice
mem0 init --api-key m0-xxx --user-id alice --force
mem0 init --email alice@company.com
mem0 init --email alice@company.com --code 482901
```
---
### `mem0 add`
Add a memory from text, messages, file, or stdin.
**Usage:** `mem0 add [text] [OPTIONS]`
**Arguments:**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `text` | string | No | Text content to add as a memory. |
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-u, --user-id <id>` | string | - | Scope to user. |
| `--agent-id <id>` | string | - | Scope to agent. |
| `--app-id <id>` | string | - | Scope to app. |
| `--run-id <id>` | string | - | Scope to run. |
| `--messages <json>` | string | - | Conversation messages as JSON array (e.g. `'[{"role":"user","content":"..."}]'`). |
| `-f, --file <path>` | path | - | Read messages from a JSON file. |
| `-m, --metadata <json>` | string | - | Custom metadata as JSON object (e.g. `'{"source":"cli"}'`). |
| `--immutable` | boolean | false | Prevent future updates to this memory. |
| `--no-infer` | boolean | false | Skip inference; store the text verbatim. |
| `--expires <date>` | string | - | Expiration date in `YYYY-MM-DD` format. |
| `--categories <cats>` | string | - | Categories as JSON array or comma-separated string. |
| `--graph` | boolean | false | Enable graph memory extraction for this call. |
| `--no-graph` | boolean | false | Disable graph memory extraction for this call. |
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`, `quiet`. |
**Input priority:** `--file` > `--messages` > text argument > stdin (if piped and no text).
Text content is wrapped as `[{"role": "user", "content": "<text>"}]` before sending to the API. Messages from `--messages` or `--file` are sent as-is.
**Output events:** The API returns results with an `event` field per memory:
| Event | Meaning |
|-------|---------|
| `ADD` | New memory created |
| `UPDATE` | Existing memory updated (deduplication) |
| `DELETE` | Existing memory removed (contradiction) |
| `NOOP` | No change needed |
| `PENDING` | Processing asynchronously in background |
**Examples:**
```bash
mem0 add "I prefer dark mode" --user-id alice
mem0 add "allergic to nuts" -u alice -m '{"source":"onboarding"}'
mem0 add --messages '[{"role":"user","content":"I like Python"}]' -u alice
mem0 add --file conversation.json -u alice -o json
echo "I prefer dark mode" | mem0 add -u alice
mem0 add "temporary note" -u alice --expires 2025-12-31
mem0 add "important fact" -u alice --immutable
mem0 add "uses vim" -u alice --categories "tools,preferences"
```
---
### `mem0 search`
Search memories by semantic query.
**Usage:** `mem0 search <query> [OPTIONS]`
**Arguments:**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `query` | string | Yes | The search query. Falls back to stdin if piped. |
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-u, --user-id <id>` | string | - | Filter by user. |
| `--agent-id <id>` | string | - | Filter by agent. |
| `--app-id <id>` | string | - | Filter by app. |
| `--run-id <id>` | string | - | Filter by run. |
| `-k, --top-k, --limit <n>` | integer | 10 | Maximum number of results to return. |
| `--threshold <score>` | float | 0.3 | Minimum similarity score (0.0 to 1.0). |
| `--rerank` | boolean | false | Enable reranking for improved relevance (Platform only). |
| `--keyword` | boolean | false | Use keyword search instead of semantic. |
| `--filter <json>` | string | - | Advanced filter expression as JSON (AND/OR operators). |
| `--fields <list>` | string | - | Comma-separated list of fields to return. |
| `--graph` | boolean | false | Enable graph in search. |
| `--no-graph` | boolean | false | Disable graph in search. |
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`, `table`. |
**Examples:**
```bash
mem0 search "preferences" --user-id alice
mem0 search "tools" -u alice -o json -k 5
mem0 search "dietary restrictions" -u alice --threshold 0.5
mem0 search "project setup" -u alice --rerank
mem0 search "preferences" -u alice --filter '{"categories":{"contains":"food"}}'
echo "preferences" | mem0 search -u alice
```
---
### `mem0 get`
Get a specific memory by ID.
**Usage:** `mem0 get <memory_id> [OPTIONS]`
**Arguments:**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `memory_id` | string | Yes | The UUID of the memory to retrieve. |
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`. |
**Examples:**
```bash
mem0 get abc-123-def-456
mem0 get abc-123-def-456 -o json
```
---
### `mem0 list`
List memories with optional filters and pagination.
**Usage:** `mem0 list [OPTIONS]`
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-u, --user-id <id>` | string | - | Filter by user. |
| `--agent-id <id>` | string | - | Filter by agent. |
| `--app-id <id>` | string | - | Filter by app. |
| `--run-id <id>` | string | - | Filter by run. |
| `--page <n>` | integer | 1 | Page number. |
| `--page-size <n>` | integer | 100 | Results per page. |
| `--category <name>` | string | - | Filter by category. |
| `--after <date>` | string | - | Created after (YYYY-MM-DD). |
| `--before <date>` | string | - | Created before (YYYY-MM-DD). |
| `--graph` | boolean | false | Enable graph in listing. |
| `--no-graph` | boolean | false | Disable graph in listing. |
| `-o, --output <fmt>` | string | `table` | Output format: `text`, `json`, `table`. |
**Examples:**
```bash
mem0 list -u alice
mem0 list --category prefs --after 2024-01-01 -o json
mem0 list -u alice --page 2 --page-size 50
mem0 list --before 2024-06-01 -o table
```
---
### `mem0 update`
Update a memory's text or metadata.
**Usage:** `mem0 update <memory_id> [text] [OPTIONS]`
**Arguments:**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `memory_id` | string | Yes | The UUID of the memory to update. |
| `text` | string | No | New memory text. Falls back to stdin if piped and no `--metadata`. |
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-m, --metadata <json>` | string | - | Update metadata as JSON object. |
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`, `quiet`. |
**Examples:**
```bash
mem0 update abc-123 "new text"
mem0 update abc-123 --metadata '{"priority":"high"}'
mem0 update abc-123 "new text" -m '{"priority":"high"}'
echo "new text" | mem0 update abc-123
```
---
### `mem0 delete`
Delete a memory, all memories matching a scope, or an entity. This command has three mutually exclusive modes.
**Usage:** `mem0 delete [memory_id] [OPTIONS]`
**Arguments:**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `memory_id` | string | No | Memory ID to delete (omit when using `--all` or `--entity`). |
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `--all` | boolean | false | Delete all memories matching scope filters. |
| `--entity` | boolean | false | Delete the entity itself and all its memories (cascade). |
| `--project` | boolean | false | With `--all`: delete ALL memories project-wide (sends wildcard IDs). |
| `--dry-run` | boolean | false | Show what would be deleted without actually deleting. |
| `--force` | boolean | false | Skip confirmation prompt. |
| `-u, --user-id <id>` | string | - | Scope to user. |
| `--agent-id <id>` | string | - | Scope to agent. |
| `--app-id <id>` | string | - | Scope to app. |
| `--run-id <id>` | string | - | Scope to run. |
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`, `quiet`. |
**Three modes (mutually exclusive):**
1. **Single memory:** `mem0 delete <memory_id>` -- deletes one memory by its UUID.
2. **Bulk delete:** `mem0 delete --all [scope flags]` -- deletes all memories matching the scope. Add `--project` to wipe all memories project-wide (sends wildcard `*` entity IDs).
3. **Entity cascade:** `mem0 delete --entity [scope flags]` -- deletes the entity itself AND all its memories.
You cannot combine `<memory_id>` with `--all` or `--entity`, and you cannot combine `--all` with `--entity`. If none of these are provided, the command prints a usage hint and exits with an error.
**Dry-run behavior:**
- Single: fetches the memory, displays it, prints "No changes made."
- `--all`: lists matching memories with count, prints "No changes made."
- `--entity`: shows the affected scope without deleting.
**Confirmation:** Without `--force`, all destructive modes prompt `[y/N]`. With `--all --project`, the prompt explicitly warns about project-wide deletion.
**`--all --project` behavior:** Sends `DELETE /v1/memories/` with `user_id=*&agent_id=*&app_id=*&run_id=*`. The API returns an async response. The CLI prints "Deletion started. Memories will be removed in the background."
**Examples:**
```bash
mem0 delete abc-123-def-456
mem0 delete --all -u alice --force
mem0 delete --all --project --force
mem0 delete --entity -u alice --force
mem0 delete abc-123 --dry-run
mem0 delete --all -u alice --dry-run
```
---
### `mem0 import`
Import memories from a JSON file.
**Usage:** `mem0 import <file_path> [OPTIONS]`
**Arguments:**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `file_path` | string | Yes | Path to a JSON file containing memories. |
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-u, --user-id <id>` | string | - | Override user ID for all imported items. |
| `--agent-id <id>` | string | - | Override agent ID for all imported items. |
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`. |
**File format:** A JSON array (or single object) where each item has a `memory`, `text`, or `content` field for the text, plus optional `user_id`, `agent_id`, and `metadata` fields. CLI-provided `--user-id` and `--agent-id` override per-item values.
**Import format example:**
```json
[
{ "memory": "Prefers dark mode", "user_id": "alice" },
{ "text": "Allergic to nuts", "metadata": { "source": "intake" } },
{ "content": "Uses VS Code" }
]
```
**Behavior:** Iterates through items, calling the add API for each. Displays progress and reports `added` and `failed` counts on completion.
**Examples:**
```bash
mem0 import memories.json --user-id alice
mem0 import data.json -u alice -o json
```
---
### `mem0 config show`
Display current configuration with secrets redacted.
**Usage:** `mem0 config show [OPTIONS]`
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`. |
**Examples:**
```bash
mem0 config show
mem0 config show -o json
```
---
### `mem0 config get`
Get a single configuration value.
**Usage:** `mem0 config get <key>`
**Arguments:**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `key` | string | Yes | Dotted config key (e.g. `platform.api_key`, `defaults.user_id`). |
**Valid keys:** `platform.api_key`, `platform.base_url`, `defaults.user_id`, `defaults.agent_id`, `defaults.app_id`, `defaults.run_id`, `defaults.enable_graph`.
API key values are always redacted in output.
**Examples:**
```bash
mem0 config get platform.api_key
mem0 config get defaults.user_id
```
---
### `mem0 config set`
Set a configuration value.
**Usage:** `mem0 config set <key> <value>`
**Arguments:**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `key` | string | Yes | Dotted config key (e.g. `defaults.user_id`). |
| `value` | string | Yes | Value to set. |
**Type coercion:** Boolean fields accept `true`/`1`/`yes` (case-insensitive) as true, anything else as false.
**Examples:**
```bash
mem0 config set defaults.user_id alice
mem0 config set platform.base_url https://api.mem0.ai
mem0 config set defaults.enable_graph true
```
---
### `mem0 config clear`
Clear the configuration file. Removes `~/.mem0/config.json`.
**Usage:** `mem0 config clear`
**Examples:**
```bash
mem0 config clear
```
---
### `mem0 entity list`
List all entities of a given type.
**Usage:** `mem0 entity list <entity_type> [OPTIONS]`
**Arguments:**
| Name | Type | Required | Choices | Description |
|------|------|----------|---------|-------------|
| `entity_type` | string | Yes | `users`, `agents`, `apps`, `runs` | Entity type to list. |
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-o, --output <fmt>` | string | `table` | Output format: `table`, `json`. |
**Behavior:** Calls `GET /v1/entities/` (returns all types), then filters client-side using the type map (`users` -> `user`, `agents` -> `agent`, etc.). Displays a table with "Name / ID" and "Created" columns.
**Examples:**
```bash
mem0 entity list users
mem0 entity list agents -o json
```
---
### `mem0 entity delete`
Delete an entity and ALL its memories (cascade).
**Usage:** `mem0 entity delete [OPTIONS]`
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-u, --user-id <id>` | string | - | User ID of the entity to delete. |
| `--agent-id <id>` | string | - | Agent ID of the entity to delete. |
| `--app-id <id>` | string | - | App ID of the entity to delete. |
| `--run-id <id>` | string | - | Run ID of the entity to delete. |
| `--dry-run` | boolean | false | Show what would be deleted without deleting. |
| `--force` | boolean | false | Skip confirmation prompt. |
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`, `quiet`. |
At least one entity ID is required. Errors if none provided.
**Examples:**
```bash
mem0 entity delete --user-id alice --force
mem0 entity delete --user-id alice --dry-run
mem0 entity delete --agent-id bot1 --force
```
---
### `mem0 event list`
List recent background processing events.
**Usage:** `mem0 event list [OPTIONS]`
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-o, --output <fmt>` | string | `table` | Output format: `text` (table), `json`. |
**Behavior:** Fetches all events for the project. Displays a table with columns: Event ID (first 8 chars), Type, Status (color-coded), Latency, Created. Status values: `PENDING`, `SUCCEEDED`, `FAILED`, `PROCESSING`.
**Examples:**
```bash
mem0 event list
mem0 event list --output json
```
---
### `mem0 event status`
Get the status and results of a specific background event.
**Usage:** `mem0 event status <event_id> [OPTIONS]`
**Arguments:**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `event_id` | string | Yes | Event ID to inspect. |
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`. |
**Behavior:** Fetches the event by ID. Displays: Event ID, Type, Status, Latency, Created, Updated, and a list of result memories.
**Examples:**
```bash
mem0 event status evt-abc-123
mem0 event status evt-abc-123 --output json
```
---
### `mem0 status`
Check connectivity and authentication.
**Usage:** `mem0 status [OPTIONS]`
**Options:**
| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`. |
**Behavior:** Calls `GET /v1/ping/` to validate connectivity and authentication. Displays connection status, backend type, and base URL.
**JSON output:**
```json
{
"status": "success",
"command": "status",
"duration_ms": 112,
"data": {
"connected": true,
"backend": "platform",
"base_url": "https://api.mem0.ai"
}
}
```
**Examples:**
```bash
mem0 status
mem0 status -o json
```
---
## Agent Mode Envelope Format
When `--json` or `--agent` is passed, every command wraps its output in a consistent JSON envelope on stdout:
```json
{
"status": "success",
"command": "<command_name>",
"duration_ms": 245,
"scope": { "user_id": "alice", "agent_id": null },
"count": 10,
"error": null,
"data": { ... }
}
```
**Fields:**
- `status`: `"success"` or `"error"`.
- `command`: The command name (e.g. `"search"`, `"add"`, `"list"`).
- `duration_ms`: Elapsed time in milliseconds (optional).
- `scope`: Active entity scope, omitted if empty (optional).
- `count`: Number of results, where applicable (optional).
- `error`: Error message string, or `null` on success.
- `data`: Command-specific response data, or `null` on error.
**Sanitized data fields per command in agent mode:**
| Command | `data` shape |
|---------|-------------|
| `add` | `[{id, memory, event}]` or `[{status, event_id}]` for PENDING |
| `search` | `[{id, memory, score, created_at, categories}]` |
| `list` | `[{id, memory, created_at, categories}]` |
| `get` | `{id, memory, created_at, updated_at, categories, metadata}` |
| `update` | `{id, memory}` |
| `delete` | Raw API response |
| `entity list` | `[{name, type, count}]` |
| `event list` | `[{id, event_type, status, latency, created_at}]` |
| `event status` | `{id, event_type, status, latency, created_at, updated_at, results}` |
| `status` | `{connected, backend, base_url}` |
| `config show` | Config object (keys redacted) |
| `import` | `{added, failed, duration_s}` |
**Error envelope:**
```json
{
"status": "error",
"command": "search",
"error": "Authentication failed. Your API key may be invalid or expired.",
"data": null
}
```
---
## Entity ID Resolution
**Rule:** If **any** explicit entity ID is provided via CLI flags (`--user-id`, `--agent-id`, `--app-id`, `--run-id`), the CLI uses only the explicitly provided IDs. It does NOT mix in defaults from config for the other entity types.
If **no** explicit IDs are given, all configured defaults from config file and env vars apply.
**Rationale:** If a user passes `--user-id alice` and the config also has `agent_id=bot1`, they want only Alice's memories -- not the intersection of Alice AND bot1.
```
if any(user_id, agent_id, app_id, run_id) were passed as flags:
use only the explicitly provided IDs (others = null)
else:
use all configured defaults
```
This applies to commands with `resolveIds: true`: `add`, `search`, `list`, `delete`, `import`.
---
## Graph Tri-State
The `enable_graph` parameter follows a three-level precedence:
```
--no-graph (explicit disable) > --graph (explicit enable) > config default
```
If `--no-graph` is passed, graph is disabled regardless of other settings. If `--graph` is passed (without `--no-graph`), graph is enabled. If neither is passed, the config value `defaults.enable_graph` is used.
This applies to commands with `resolveGraph: true`: `add`, `search`, `list`.
---
## Filter Building
For `search` and `list`, entity IDs and additional filters are composed into the API filter structure:
1. If the user provides a pre-built filter via `--filter` containing `AND` or `OR` keys, it is passed through to the API as-is.
2. Otherwise, the CLI builds an array of AND conditions:
- Each entity ID becomes a condition: `{"user_id": "alice"}`, etc.
- Category filters: `{"categories": {"contains": "<category>"}}`.
- Date filters: `{"created_at": {"gte": "YYYY-MM-DD"}}` and/or `{"created_at": {"lte": "YYYY-MM-DD"}}`.
3. If exactly 1 condition: sent as a single object (no wrapping).
4. If 2+ conditions: wrapped as `{"AND": [condition1, condition2, ...]}`.
5. If 0 conditions: no filter sent.
---
## Output Mode Support Matrix
| Command | `text` | `json` | `table` | `quiet` | Default |
|---------|--------|--------|---------|---------|---------|
| `add` | Y | Y | - | Y | `text` |
| `search` | Y | Y | Y | - | `text` |
| `get` | Y | Y | - | - | `text` |
| `list` | Y | Y | Y | - | `table` |
| `update` | Y | Y | - | Y | `text` |
| `delete` | Y | Y | - | Y | `text` |
| `import` | Y | Y | - | - | `text` |
| `config show` | Y | Y | - | - | `text` |
| `config get` | raw | - | - | - | raw |
| `config set` | msg | - | - | - | msg |
| `entity list` | - | Y | Y | - | `table` |
| `entity delete` | Y | Y | - | Y | `text` |
| `event list` | Y (table) | Y | - | - | `table` |
| `event status` | Y | Y | - | - | `text` |
| `status` | Y | Y | - | - | `text` |
All commands additionally support agent mode (`--json`/`--agent`) which overrides the output format with the JSON envelope.
+244
View File
@@ -0,0 +1,244 @@
# Mem0 CLI Configuration
Everything about configuring the mem0 CLI: config file format, environment variables, the init wizard, and precedence rules.
---
## Config File Location
| Path | Permissions | Description |
|------|-------------|-------------|
| `~/.mem0/` | `0700` (owner rwx) | Config directory. Created automatically by `mem0 init`. |
| `~/.mem0/config.json` | `0600` (owner rw) | Config file. Contains API key, defaults, and platform settings. |
The restricted permissions ensure API keys are not world-readable.
---
## Config File Schema
```json
{
"version": 1,
"defaults": {
"user_id": "",
"agent_id": "",
"app_id": "",
"run_id": "",
"enable_graph": false
},
"platform": {
"api_key": "",
"base_url": "https://api.mem0.ai"
}
}
```
### Field Reference
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `version` | integer | `1` | Config schema version. |
| `defaults.user_id` | string | `""` | Default user ID for scoping commands. |
| `defaults.agent_id` | string | `""` | Default agent ID for scoping commands. |
| `defaults.app_id` | string | `""` | Default app ID for scoping commands. |
| `defaults.run_id` | string | `""` | Default run ID for scoping commands. |
| `defaults.enable_graph` | boolean | `false` | Default graph memory extraction toggle. |
| `platform.api_key` | string | `""` | API key for the Mem0 Platform. |
| `platform.base_url` | string | `"https://api.mem0.ai"` | Base URL for API requests. |
---
## `mem0 init` Wizard
The `init` command provides two authentication flows:
### API Key Flow (default)
```bash
# Fully interactive:
mem0 init
# Fully non-interactive:
mem0 init --api-key m0-xxx --user-id alice
```
**Interactive mode steps:**
1. Displays the mem0 banner.
2. Checks for existing config. If found with an API key, asks for confirmation to overwrite.
3. Prompts for API key (input masked with `*` characters; supports backspace and Ctrl+U to clear).
4. Prompts for default user ID (default value: `mem0-cli`).
5. Validates the connection by calling the status endpoint.
6. Saves config to `~/.mem0/config.json` with `0600` permissions.
7. Prints success message.
**Non-interactive mode:** When both `--api-key` and `--user-id` are provided, skips all prompts and saves directly. When running in a non-TTY without both flags, prints an error:
```
Non-interactive terminal detected and missing required flags.
Usage: mem0 init --api-key <key> --user-id <id>
```
### Email Login Flow
```bash
# Interactive (prompts for code):
mem0 init --email alice@company.com
# Fully non-interactive:
mem0 init --email alice@company.com --code 482901
```
**Steps:**
1. Sends a 6-digit verification code to the email via `POST /api/v1/auth/email_code/`.
2. If `--code` is provided, verifies immediately. Otherwise prompts for the code.
3. On success: receives API key, org_id, and project_id from the server.
4. Saves to config. Creates a new account if the email is not registered.
Cannot be combined with `--api-key`.
### Force Overwrite
If `~/.mem0/config.json` already exists with an API key, `mem0 init` warns and asks for confirmation. Use `--force` to skip:
```bash
mem0 init --api-key m0-new-key --user-id alice --force
```
---
## `mem0 config` Subcommands
### `mem0 config show`
Displays the current configuration as a formatted table (text mode) or JSON envelope (json mode). API keys are always redacted.
```bash
mem0 config show
mem0 config show -o json
```
### `mem0 config get <key>`
Reads a single configuration value. The key uses dotted notation.
```bash
mem0 config get platform.api_key # prints: m0-x...xxxx (redacted)
mem0 config get defaults.user_id # prints: alice
mem0 config get defaults.enable_graph # prints: false
```
**Valid keys:**
- `platform.api_key`
- `platform.base_url`
- `defaults.user_id`
- `defaults.agent_id`
- `defaults.app_id`
- `defaults.run_id`
- `defaults.enable_graph`
Unknown keys print an error message.
### `mem0 config set <key> <value>`
Sets a configuration value and saves the config file.
```bash
mem0 config set defaults.user_id alice
mem0 config set platform.base_url https://api.mem0.ai
mem0 config set defaults.enable_graph true
```
**Type coercion:**
- Boolean fields accept `true`, `1`, `yes` (case-insensitive) as true. Anything else is false.
- Integer fields are parsed with `parseInt`.
- String fields are stored as-is.
### `mem0 config clear`
Removes the config file (`~/.mem0/config.json`).
```bash
mem0 config clear
```
---
## Environment Variables
Environment variables override config file values but are overridden by CLI flags.
| Variable | Config Path | Type | Default |
|----------|-------------|------|---------|
| `MEM0_API_KEY` | `platform.api_key` | string | `""` |
| `MEM0_BASE_URL` | `platform.base_url` | string | `"https://api.mem0.ai"` |
| `MEM0_USER_ID` | `defaults.user_id` | string | `""` |
| `MEM0_AGENT_ID` | `defaults.agent_id` | string | `""` |
| `MEM0_APP_ID` | `defaults.app_id` | string | `""` |
| `MEM0_RUN_ID` | `defaults.run_id` | string | `""` |
| `MEM0_ENABLE_GRAPH` | `defaults.enable_graph` | boolean | `false` |
### Boolean Parsing for `MEM0_ENABLE_GRAPH`
Accepted truthy values (case-insensitive): `"true"`, `"1"`, `"yes"`. Everything else is treated as `false`.
```bash
export MEM0_ENABLE_GRAPH=true # enabled
export MEM0_ENABLE_GRAPH=1 # enabled
export MEM0_ENABLE_GRAPH=yes # enabled
export MEM0_ENABLE_GRAPH=false # disabled
export MEM0_ENABLE_GRAPH=0 # disabled
export MEM0_ENABLE_GRAPH="" # disabled
```
---
## Precedence
Configuration values are resolved in this order (highest priority first):
```
1. CLI flags --api-key, --user-id, --base-url, --graph, --no-graph, etc.
2. Environment vars MEM0_API_KEY, MEM0_USER_ID, MEM0_ENABLE_GRAPH, etc.
3. Config file ~/.mem0/config.json
4. Defaults Hardcoded defaults (empty strings, false, https://api.mem0.ai)
```
**Example:** If your config file has `user_id: "bob"`, the env var `MEM0_USER_ID=charlie` is set, and you pass `--user-id alice` on the command line, the effective user_id is `alice`.
---
## API Key Redaction Rules
Whenever an API key is displayed (in `config show`, `config get`, status output, etc.), it is redacted:
| Condition | Output |
|-----------|--------|
| Empty string | `(not set)` |
| Length <= 8 | First 2 characters + `***` |
| Length > 8 | First 4 characters + `...` + last 4 characters |
**Examples:**
- `""` -> `(not set)`
- `"m0-abc"` -> `m0***`
- `"m0-abcdefghijklmnop"` -> `m0-a...mnop`
The redaction function is named `redact_key` (Python) / `redactKey` (Node).
---
## Dotted Key Map
The `config get` and `config set` commands use dotted key paths. Here is the full mapping:
| Dotted Key | Section | Field |
|------------|---------|-------|
| `platform.api_key` | platform | api_key |
| `platform.base_url` | platform | base_url |
| `defaults.user_id` | defaults | user_id |
| `defaults.agent_id` | defaults | agent_id |
| `defaults.app_id` | defaults | app_id |
| `defaults.run_id` | defaults | run_id |
| `defaults.enable_graph` | defaults | enable_graph |
+439
View File
@@ -0,0 +1,439 @@
# Mem0 CLI Workflows
Practical recipes for using the mem0 CLI in scripts, pipelines, and agent loops.
---
## Piping Content via Stdin
The CLI reads from stdin when no text argument is provided and input is piped (not a TTY). This works with `add`, `search`, and `update`.
**Stdin detection method:**
- Python: `not sys.stdin.isatty()`
- Node: `!process.stdin.isTTY`
### Add from pipe
```bash
echo "I prefer dark mode" | mem0 add --user-id alice
```
### Pipe multi-line content
```bash
cat <<EOF | mem0 add --user-id alice
The user prefers dark mode in all applications.
They also like monospace fonts for code editing.
EOF
```
### Pipe from another command
```bash
git log --oneline -5 | mem0 add --user-id ci-bot --metadata '{"source":"git"}'
```
### Search from pipe
```bash
echo "preferences" | mem0 search --user-id alice
```
### Update from pipe
```bash
echo "Updated: prefers dark mode AND high contrast" | mem0 update abc-123-def-456
```
---
## File Import
Use `mem0 import` to bulk-load memories from a JSON file.
### Basic import
```bash
mem0 import memories.json --user-id alice
```
### File format
The file should be a JSON array where each item has a `memory`, `text`, or `content` field:
```json
[
{ "memory": "Prefers dark mode" },
{ "text": "Allergic to nuts", "metadata": { "source": "intake-form" } },
{ "content": "Uses VS Code", "user_id": "bob" }
]
```
CLI-provided `--user-id` overrides per-item `user_id` values.
### Import with JSON output
```bash
mem0 import data.json --user-id alice -o json
```
Output:
```json
{
"status": "success",
"command": "import",
"data": { "added": 42, "failed": 0, "duration_s": 3.14 },
"duration_ms": 3140
}
```
---
## Agent Mode for LLM Consumption
Use `--json` or `--agent` to get structured JSON output suitable for LLM tool calling or agent frameworks. Spinners and progress always go to stderr, keeping stdout clean.
### Search with agent mode
```bash
mem0 search "preferences" --user-id alice --agent
```
Output (stdout):
```json
{
"status": "success",
"command": "search",
"duration_ms": 187,
"scope": { "user_id": "alice" },
"count": 2,
"error": null,
"data": [
{ "id": "mem-abc", "memory": "User prefers dark mode", "score": 0.95, "created_at": "2025-01-15T10:00:00Z", "categories": ["preferences"] },
{ "id": "mem-def", "memory": "User likes monospace fonts", "score": 0.82, "created_at": "2025-01-15T10:01:00Z", "categories": ["preferences"] }
]
}
```
### Add with agent mode
```bash
mem0 add "Uses Python 3.12" --user-id alice --json
```
### Error handling in agent mode
Errors also return valid JSON with `"status": "error"`:
```bash
mem0 search "test" --user-id alice --api-key invalid --agent
```
Output:
```json
{
"status": "error",
"command": "search",
"error": "Authentication failed. Your API key may be invalid or expired.",
"data": null
}
```
---
## JSON Output + jq
Use `--output json` (or `-o json`) for raw JSON output, then pipe to `jq` for processing.
### Extract just memory text
```bash
mem0 list --user-id alice --output json | jq '.[] | .memory'
```
### Get memory IDs
```bash
mem0 list --user-id alice -o json | jq '.[].id'
```
### Count memories
```bash
mem0 list --user-id alice -o json | jq 'length'
```
### Filter by category in jq
```bash
mem0 list --user-id alice -o json | jq '[.[] | select(.categories[]? == "preferences")]'
```
### Extract search scores
```bash
mem0 search "tools" --user-id alice -o json | jq '.[] | {memory, score}'
```
---
## Bulk Operations
### Delete multiple memories by ID
```bash
# Get IDs, then delete each one
mem0 list --user-id alice -o json | jq -r '.[].id' | while read id; do
mem0 delete "$id" --force
done
```
### Bulk add from a text file (one memory per line)
```bash
while IFS= read -r line; do
mem0 add "$line" --user-id alice
done < memories.txt
```
### Copy memories between users
```bash
mem0 list --user-id alice -o json | jq -r '.[].memory' | while IFS= read -r mem; do
mem0 add "$mem" --user-id bob
done
```
### Export all memories to a file
```bash
mem0 list --user-id alice -o json > alice_memories.json
```
### Paginate through all results
```bash
page=1
while true; do
result=$(mem0 list --user-id alice -o json --page "$page" --page-size 100)
count=$(echo "$result" | jq 'length')
if [ "$count" -eq 0 ]; then
break
fi
echo "$result"
page=$((page + 1))
done
```
---
## CI/CD Patterns
### Store build context as a memory
```bash
mem0 add "Build #${BUILD_NUMBER} deployed ${APP_VERSION} to ${ENVIRONMENT} at $(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--agent-id "ci-bot" \
--metadata "{\"build_number\":\"${BUILD_NUMBER}\",\"version\":\"${APP_VERSION}\",\"env\":\"${ENVIRONMENT}\"}"
```
### Retrieve deployment history
```bash
mem0 search "deployment to production" --agent-id ci-bot -o json -k 10
```
### Check CLI connectivity in CI
```bash
if mem0 status -o json | jq -e '.data.connected' > /dev/null 2>&1; then
echo "mem0 is connected"
else
echo "mem0 connection failed" >&2
exit 1
fi
```
### Non-interactive init in CI
```bash
mem0 init --api-key "$MEM0_API_KEY" --user-id ci-bot --force
```
Or simply use the environment variable (no init needed):
```bash
export MEM0_API_KEY="$MEM0_API_KEY"
mem0 add "CI run started" --user-id ci-bot
```
### Store test results
```bash
test_summary=$(cat test-results.txt | head -20)
mem0 add "$test_summary" --agent-id ci-bot --metadata '{"type":"test-results"}' --categories "ci,testing"
```
---
## Stdin Detection Details
The CLI reads from stdin only when ALL of these conditions are met:
1. No text argument was provided on the command line.
2. For `add`: no `--messages` and no `--file` flag.
3. For `update`: no `--metadata` flag.
4. stdin is piped (not a TTY).
**This means:**
- `mem0 add --user-id alice` in an interactive terminal will NOT hang waiting for input. It will print a usage error.
- `echo "text" | mem0 add --user-id alice` will read "text" from stdin.
- `mem0 add "explicit text" --user-id alice` will use the explicit text, even if stdin is piped.
**Reading method:**
- Python: `sys.stdin.read().strip()`
- Node: `fs.readFileSync(0, "utf-8").trim()`
---
## Common Shell Patterns
### Error handling with exit codes
```bash
set -e # Exit on error
# This will exit the script if the API key is invalid
mem0 status > /dev/null 2>&1
# Add with error check
if mem0 add "test memory" --user-id alice 2>/dev/null; then
echo "Memory added successfully"
else
echo "Failed to add memory" >&2
exit 1
fi
```
### Capture memory ID from add
```bash
# Use agent mode to get structured output
result=$(mem0 add "new fact" --user-id alice --agent 2>/dev/null)
memory_id=$(echo "$result" | jq -r '.data[0].id // empty')
if [ -n "$memory_id" ]; then
echo "Created memory: $memory_id"
fi
```
### Conditional memory addition
```bash
# Only add if search returns no results
count=$(mem0 search "dark mode" --user-id alice --agent 2>/dev/null | jq '.count // 0')
if [ "$count" -eq 0 ]; then
mem0 add "User prefers dark mode" --user-id alice
fi
```
### Quiet mode for scripts
```bash
# Suppress all output except errors
mem0 add "background note" --user-id alice --output quiet 2>/dev/null
mem0 delete --all --user-id temp-user --force --output quiet 2>/dev/null
```
### Using environment variables for scope
```bash
export MEM0_USER_ID="alice"
export MEM0_API_KEY="m0-xxx"
# All commands now default to user alice, no --user-id needed
mem0 add "prefers dark mode"
mem0 search "preferences"
mem0 list
```
### Timeout handling
The CLI uses a 30-second timeout for all API requests. For long-running scripts, handle timeouts:
```bash
if ! mem0 search "query" --user-id alice -o json 2>/dev/null; then
echo "Request failed or timed out" >&2
fi
```
---
## Processing Delay Workaround
Memories are processed asynchronously after `mem0 add`. If you need to search for a newly added memory immediately, add a short delay:
```bash
mem0 add "new preference" --user-id alice
sleep 3
mem0 search "new preference" --user-id alice
```
Or use the event system to poll for completion:
```bash
# Add and capture event ID from agent output
result=$(mem0 add "new preference" --user-id alice --agent 2>/dev/null)
event_id=$(echo "$result" | jq -r '.data[0].event_id // empty')
if [ -n "$event_id" ]; then
# Poll until processing completes
while true; do
status=$(mem0 event status "$event_id" --agent 2>/dev/null | jq -r '.data.status')
if [ "$status" = "SUCCEEDED" ] || [ "$status" = "FAILED" ]; then
break
fi
sleep 1
done
fi
```
---
## Multi-User Agent Pattern
For AI agents managing memories across multiple users:
```bash
#!/bin/bash
# agent_memory.sh -- manage memories for the current conversation
USER_ID="$1"
ACTION="$2"
shift 2
case "$ACTION" in
recall)
mem0 search "$*" --user-id "$USER_ID" --agent 2>/dev/null
;;
remember)
mem0 add "$*" --user-id "$USER_ID" --agent 2>/dev/null
;;
forget)
mem0 delete --all --user-id "$USER_ID" --force --agent 2>/dev/null
;;
history)
mem0 list --user-id "$USER_ID" --agent 2>/dev/null
;;
*)
echo '{"status":"error","error":"Unknown action: '"$ACTION"'"}' >&2
exit 1
;;
esac
```
Usage:
```bash
./agent_memory.sh alice recall "dietary preferences"
./agent_memory.sh alice remember "allergic to shellfish"
./agent_memory.sh alice history
```