Compare commits
43 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 32b74e18b7 | |||
| daa4495583 | |||
| cfb5f1776e | |||
| 573e5212a4 | |||
| 8ba225cec8 | |||
| 4b09943092 | |||
| 4e611e8dba | |||
| 5520226b5b | |||
| 00695e3113 | |||
| 7b6790bafb | |||
| 93da5ef8f7 | |||
| c1c5bd62f6 | |||
| 2ec3c4ab20 | |||
| 3fbc1c9aef | |||
| 0b14f75c05 | |||
| fb224083e4 | |||
| 30469aec17 | |||
| 50db9e428d | |||
| fb87349664 | |||
| 8827553576 | |||
| c8e20a9bb5 | |||
| 93a51f4763 | |||
| 86fe275f53 | |||
| e6d6276bb9 | |||
| 9692726db4 | |||
| d8d776636f | |||
| a5a688295e | |||
| 5d40592e42 | |||
| a488e19044 | |||
| 57f944e18a | |||
| fe3f7ae618 | |||
| 4a7e166f9a | |||
| 85768e78e7 | |||
| 7b395f3bf7 | |||
| 4180409b09 | |||
| 649e719ce6 | |||
| 1a53852d93 | |||
| ac9cdd4840 | |||
| cf530c4bec | |||
| 92b958c1cc | |||
| c239d8a483 | |||
| 9d6b79a14e | |||
| e44b46ef2e |
@@ -14,8 +14,48 @@ on:
|
||||
- 'mem0/**'
|
||||
- 'tests/**'
|
||||
- 'embedchain/**'
|
||||
- 'pyproject.toml'
|
||||
|
||||
jobs:
|
||||
changelog_check:
|
||||
if: github.event_name == 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Require CHANGELOG entry when Python SDK version changes
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
extract_version() {
|
||||
python3 -c "import sys, re; m = re.search(r'^\s*version\s*=\s*\"([^\"]+)\"', sys.stdin.read(), re.M); print(m.group(1) if m else '')"
|
||||
}
|
||||
|
||||
base_version=$(git show "$BASE_SHA:pyproject.toml" 2>/dev/null | extract_version || echo "")
|
||||
head_version=$(extract_version < pyproject.toml)
|
||||
|
||||
echo "Base version: ${base_version:-<unknown>}"
|
||||
echo "Head version: $head_version"
|
||||
|
||||
if [ -z "$base_version" ] || [ "$base_version" = "$head_version" ]; then
|
||||
echo "pyproject.toml version unchanged — no CHANGELOG entry required."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Detected version bump ${base_version} -> ${head_version}. Checking docs/changelog/sdk.mdx…"
|
||||
|
||||
if git diff --name-only "$BASE_SHA" "$HEAD_SHA" -- docs/changelog/sdk.mdx | grep -q .; then
|
||||
echo "Changelog update present in docs/changelog/sdk.mdx ✅"
|
||||
else
|
||||
echo "::error file=pyproject.toml::pyproject.toml version changed from ${base_version} to ${head_version} but docs/changelog/sdk.mdx was not updated in this PR. Add a new <Update> entry under the Python tab for v${head_version}."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
check_changes:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
name: docs - llms.txt check
|
||||
|
||||
# Blocks PRs that introduce new .mdx pages without a matching entry in
|
||||
# docs/llms.txt, or that link to pages that no longer exist. Contributors
|
||||
# must update docs/llms.txt in the same PR. Run locally with:
|
||||
# python scripts/check-llms-txt-coverage.py # read-only
|
||||
# python scripts/check-llms-txt-coverage.py --write # scaffold placeholders
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'docs/**/*.mdx'
|
||||
- 'docs/llms.txt'
|
||||
- 'scripts/check-llms-txt-coverage.py'
|
||||
- 'scripts/llms-txt-ignore.txt'
|
||||
workflow_dispatch: {}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check-llms-txt:
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 2
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Verify docs/llms.txt coverage
|
||||
run: |
|
||||
if ! python3 scripts/check-llms-txt-coverage.py; then
|
||||
echo ""
|
||||
echo "::error title=llms.txt out of sync::docs/llms.txt does not match docs/**/*.mdx."
|
||||
echo ""
|
||||
echo "To fix:"
|
||||
echo " 1. Run locally: python scripts/check-llms-txt-coverage.py --write"
|
||||
echo " This appends placeholder entries under '## Unclassified - needs triage'."
|
||||
echo " 2. For each placeholder:"
|
||||
echo " - replace [TODO: Platform|OSS|Both] with the correct scope tag"
|
||||
echo " - rewrite the description as 'Use when ...'"
|
||||
echo " - move the entry into the appropriate section"
|
||||
echo " - delete the '## Unclassified - needs triage' heading once empty"
|
||||
echo " 3. Resolve any stale URLs listed above by updating or removing the link."
|
||||
echo " 4. Commit the updated docs/llms.txt to this PR."
|
||||
exit 1
|
||||
fi
|
||||
@@ -24,6 +24,42 @@ jobs:
|
||||
ts_sdk:
|
||||
- 'mem0-ts/**'
|
||||
|
||||
changelog_check:
|
||||
needs: check_changes
|
||||
if: github.event_name == 'pull_request' && needs.check_changes.outputs.ts_sdk_changed == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Require CHANGELOG entry when SDK version changes
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
base_version=$(git show "$BASE_SHA:mem0-ts/package.json" 2>/dev/null | jq -r .version || echo "")
|
||||
head_version=$(jq -r .version mem0-ts/package.json)
|
||||
|
||||
echo "Base version: ${base_version:-<unknown>}"
|
||||
echo "Head version: $head_version"
|
||||
|
||||
if [ -z "$base_version" ] || [ "$base_version" = "$head_version" ]; then
|
||||
echo "mem0-ts/package.json version unchanged — no CHANGELOG entry required."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Detected version bump ${base_version} -> ${head_version}. Checking docs/changelog/sdk.mdx…"
|
||||
|
||||
if git diff --name-only "$BASE_SHA" "$HEAD_SHA" -- docs/changelog/sdk.mdx | grep -q .; then
|
||||
echo "Changelog update present in docs/changelog/sdk.mdx ✅"
|
||||
else
|
||||
echo "::error file=mem0-ts/package.json::mem0-ts/package.json version changed from ${base_version} to ${head_version} but docs/changelog/sdk.mdx was not updated in this PR. Add a new <Update> entry under the TypeScript tab for v${head_version}."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
build_ts_sdk:
|
||||
needs: check_changes
|
||||
if: needs.check_changes.outputs.ts_sdk_changed == 'true'
|
||||
|
||||
@@ -35,6 +35,7 @@ This is a **polyglot monorepo** containing Python and TypeScript packages, CLIs,
|
||||
| `cookbooks/` | Jupyter notebooks — customer support chatbot, AutoGen integration |
|
||||
| `embedchain/` | Legacy Embedchain RAG framework (maintained separately, Poetry-based) |
|
||||
| `pr-reviews/` | Pull request review materials |
|
||||
| `scripts/` | Repo-wide utility scripts (e.g., `check-llms-txt-coverage.py` for docs/llms.txt sync) |
|
||||
|
||||
### Core Package Dependencies
|
||||
|
||||
@@ -433,6 +434,7 @@ To add a new LLM, embedding, vector store, or reranker provider:
|
||||
|----------|------|---------|
|
||||
| Issue Labeler | `issue-labeler.yml` | Automatic issue labeling |
|
||||
| Stale Bot | `stale.yml` | Marks stale issues and PRs |
|
||||
| llms.txt Check | `docs-llms-txt-check.yml` | Blocks PRs touching `docs/**/*.mdx` when `docs/llms.txt` is out of sync. Fix locally with `python scripts/check-llms-txt-coverage.py --write`. |
|
||||
|
||||
## Task Completion Guidelines
|
||||
|
||||
@@ -451,6 +453,7 @@ These guidelines outline typical artifacts for different task types. Use judgmen
|
||||
2. **Unit tests**: Comprehensive test coverage for new functionality
|
||||
3. **Documentation**: Update relevant docs in `docs/` for public APIs
|
||||
4. **Examples**: Add usage examples if the feature introduces new user-facing behavior
|
||||
5. **llms.txt**: Any new `.mdx` page under `docs/` must be linked in `docs/llms.txt` with a scope tag (`[Platform]` / `[OSS]` / `[Both]`) and a `Use when ...` description. The `docs-llms-txt-check.yml` workflow runs on every PR that touches docs and **fails the check** if the index is out of sync. To fix: run `python scripts/check-llms-txt-coverage.py --write` locally to scaffold placeholders under `## Unclassified - needs triage`, then replace the `[TODO: ...]` tags, rewrite descriptions as `Use when ...`, move entries into the right section, and delete the triage heading when empty.
|
||||
|
||||
### New Provider (LLM / Embedding / Vector Store / Reranker)
|
||||
|
||||
|
||||
@@ -266,7 +266,7 @@ config = MemoryConfig(
|
||||
graph_store=GraphStoreConfig(provider="neo4j", config={...}), # optional
|
||||
history_db_path="~/.mem0/history.db",
|
||||
version="v1.1",
|
||||
custom_fact_extraction_prompt="Custom prompt...",
|
||||
custom_instructions="Custom prompt...",
|
||||
custom_update_memory_prompt="Custom prompt..."
|
||||
)
|
||||
```
|
||||
@@ -684,7 +684,7 @@ Conversation: {messages}
|
||||
"""
|
||||
|
||||
config = MemoryConfig(
|
||||
custom_fact_extraction_prompt=custom_extraction_prompt
|
||||
custom_instructions=custom_extraction_prompt
|
||||
)
|
||||
memory = Memory(config)
|
||||
```
|
||||
|
||||
@@ -42,9 +42,6 @@ clean:
|
||||
test:
|
||||
hatch run test
|
||||
|
||||
test-py-3.9:
|
||||
hatch run dev_py_3_9:test
|
||||
|
||||
test-py-3.10:
|
||||
hatch run dev_py_3_10:test
|
||||
|
||||
|
||||
@@ -41,16 +41,30 @@
|
||||
<p align="center">
|
||||
<a href="https://mem0.ai/research"><strong>📄 Building Production-Ready AI Agents with Scalable Long-Term Memory →</strong></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<strong>⚡ +26% Accuracy vs. OpenAI Memory • 🚀 91% Faster • 💰 90% Fewer Tokens</strong>
|
||||
</p>
|
||||
|
||||
> **🎉 mem0ai v1.0.0 is now available!** This major release includes API modernization, improved vector store support, and enhanced GCP integration. [See migration guide →](MIGRATION_GUIDE_v1.0.md)
|
||||
## New Memory Algorithm (April 2026)
|
||||
|
||||
## 🔥 Research Highlights
|
||||
- **+26% Accuracy** over OpenAI Memory on the LOCOMO benchmark
|
||||
- **91% Faster Responses** than full-context, ensuring low-latency at scale
|
||||
- **90% Lower Token Usage** than full-context, cutting costs without compromise
|
||||
| Benchmark | Old | New | Tokens | Latency p50 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| **LoCoMo** | 71.4 | **91.6** | 7.0K | 0.88s |
|
||||
| **LongMemEval** | 67.8 | **93.4** | 6.8K | 1.09s |
|
||||
| **BEAM (1M)** | — | **64.1** | 6.7K | 1.00s |
|
||||
| **BEAM (10M)** | — | **48.6** | 6.9K | 1.05s |
|
||||
|
||||
All benchmarks run on the same production-representative model stack. Single-pass retrieval (one call, no agentic loops).
|
||||
|
||||
**What changed:**
|
||||
- **Single-pass ADD-only extraction** -- one LLM call, no UPDATE/DELETE. Memories accumulate; nothing is overwritten.
|
||||
- **Agent-generated facts are first-class** -- when an agent confirms an action, that information is now stored with equal weight.
|
||||
- **Entity linking** -- entities are extracted, embedded, and linked across memories for retrieval boosting.
|
||||
- **Multi-signal retrieval** -- semantic, BM25 keyword, and entity matching scored in parallel and fused.
|
||||
|
||||
See the [migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for upgrade instructions. The [evaluation framework](https://github.com/mem0ai/memory-benchmarks) is open-sourced so anyone can reproduce the numbers.
|
||||
|
||||
## Research Highlights
|
||||
- **91.6 on LoCoMo** -- +20 points over the previous algorithm
|
||||
- **93.4 on LongMemEval** -- +26 points, with +53.6 on assistant memory recall
|
||||
- **64.1 on BEAM (1M)** -- production-scale memory evaluation at 1M tokens
|
||||
- [Read the full paper](https://mem0.ai/research)
|
||||
|
||||
# Introduction
|
||||
@@ -88,6 +102,13 @@ Install the sdk via pip:
|
||||
pip install mem0ai
|
||||
```
|
||||
|
||||
For enhanced hybrid search with BM25 keyword matching and entity extraction, install with NLP support:
|
||||
|
||||
```bash
|
||||
pip install mem0ai[nlp]
|
||||
python -m spacy download en_core_web_sm
|
||||
```
|
||||
|
||||
Install sdk via npm:
|
||||
```bash
|
||||
npm install mem0ai
|
||||
@@ -109,7 +130,9 @@ See the [CLI documentation](https://docs.mem0.ai/platform/cli) for the full comm
|
||||
|
||||
### Basic Usage
|
||||
|
||||
Mem0 requires an LLM to function, with `gpt-4.1-nano-2025-04-14 from OpenAI as the default. However, it supports a variety of LLMs; for details, refer to our [Supported LLMs documentation](https://docs.mem0.ai/components/llms/overview).
|
||||
Mem0 requires an LLM to function, with `gpt-5-mini` from OpenAI as the default. However, it supports a variety of LLMs; for details, refer to our [Supported LLMs documentation](https://docs.mem0.ai/components/llms/overview).
|
||||
|
||||
Mem0 uses `text-embedding-3-small` from OpenAI as the default embedding model. For best results with hybrid search (semantic + keyword + entity boosting), we recommend using at least [Qwen 600M](https://huggingface.co/Alibaba-NLP/gte-Qwen2-1.5B-instruct) or a comparable embedding model. See [Supported Embeddings](https://docs.mem0.ai/components/embedders/overview) for configuration details.
|
||||
|
||||
First step is to instantiate the memory:
|
||||
|
||||
@@ -122,13 +145,13 @@ memory = Memory()
|
||||
|
||||
def chat_with_memories(message: str, user_id: str = "default_user") -> str:
|
||||
# Retrieve relevant memories
|
||||
relevant_memories = memory.search(query=message, user_id=user_id, limit=3)
|
||||
relevant_memories = memory.search(query=message, filters={"user_id": user_id}, top_k=3)
|
||||
memories_str = "\n".join(f"- {entry['memory']}" for entry in relevant_memories["results"])
|
||||
|
||||
# Generate Assistant response
|
||||
system_prompt = f"You are a helpful AI. Answer the question based on query and memories.\nUser Memories:\n{memories_str}"
|
||||
messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": message}]
|
||||
response = openai_client.chat.completions.create(model="gpt-4.1-nano-2025-04-14", messages=messages)
|
||||
response = openai_client.chat.completions.create(model="gpt-5-mini", messages=messages)
|
||||
assistant_response = response.choices[0].message.content
|
||||
|
||||
# Create new memories from the conversation
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@mem0/cli",
|
||||
"version": "0.2.3",
|
||||
"version": "0.2.4",
|
||||
"description": "The official CLI for mem0 — the memory layer for AI agents",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -15,7 +15,6 @@ export interface AddOptions {
|
||||
infer?: boolean;
|
||||
expires?: string;
|
||||
categories?: string[];
|
||||
enableGraph?: boolean;
|
||||
}
|
||||
|
||||
export interface SearchOptions {
|
||||
@@ -29,7 +28,6 @@ export interface SearchOptions {
|
||||
keyword?: boolean;
|
||||
filters?: Record<string, unknown>;
|
||||
fields?: string[];
|
||||
enableGraph?: boolean;
|
||||
}
|
||||
|
||||
export interface ListOptions {
|
||||
@@ -42,7 +40,6 @@ export interface ListOptions {
|
||||
category?: string;
|
||||
after?: string;
|
||||
before?: string;
|
||||
enableGraph?: boolean;
|
||||
}
|
||||
|
||||
export interface DeleteOptions {
|
||||
|
||||
@@ -115,10 +115,9 @@ export class PlatformBackend implements Backend {
|
||||
if (opts.infer === false) payload.infer = false;
|
||||
if (opts.expires) payload.expiration_date = opts.expires;
|
||||
if (opts.categories) payload.categories = opts.categories;
|
||||
if (opts.enableGraph) payload.enable_graph = true;
|
||||
payload.source = "CLI";
|
||||
|
||||
return (await this._request("POST", "/v1/memories/", {
|
||||
return (await this._request("POST", "/v3/memories/add/", {
|
||||
json: payload,
|
||||
})) as Record<string, unknown>;
|
||||
}
|
||||
@@ -176,10 +175,9 @@ export class PlatformBackend implements Backend {
|
||||
if (opts.rerank) payload.rerank = true;
|
||||
if (opts.keyword) payload.keyword_search = true;
|
||||
if (opts.fields) payload.fields = opts.fields;
|
||||
if (opts.enableGraph) payload.enable_graph = true;
|
||||
payload.source = "CLI";
|
||||
|
||||
const result = (await this._request("POST", "/v2/memories/search/", {
|
||||
const result = (await this._request("POST", "/v3/memories/search/", {
|
||||
json: payload,
|
||||
})) as unknown;
|
||||
if (Array.isArray(result)) return result;
|
||||
@@ -227,10 +225,9 @@ export class PlatformBackend implements Backend {
|
||||
extraFilters: Object.keys(extra).length > 0 ? extra : undefined,
|
||||
});
|
||||
if (apiFilters) payload.filters = apiFilters;
|
||||
if (opts.enableGraph) payload.enable_graph = true;
|
||||
payload.source = "CLI";
|
||||
|
||||
const result = (await this._request("POST", "/v2/memories/", {
|
||||
const result = (await this._request("POST", "/v3/memories/", {
|
||||
json: payload,
|
||||
params,
|
||||
})) as unknown;
|
||||
|
||||
@@ -29,7 +29,6 @@ export function cmdConfigShow(opts: { output?: string } = {}): void {
|
||||
agent_id: config.defaults.agentId || null,
|
||||
app_id: config.defaults.appId || null,
|
||||
run_id: config.defaults.runId || null,
|
||||
enable_graph: config.defaults.enableGraph,
|
||||
},
|
||||
platform: {
|
||||
api_key: redactKey(config.platform.apiKey),
|
||||
@@ -56,7 +55,6 @@ export function cmdConfigShow(opts: { output?: string } = {}): void {
|
||||
]);
|
||||
table.push(["defaults.app_id", config.defaults.appId || dim("(not set)")]);
|
||||
table.push(["defaults.run_id", config.defaults.runId || dim("(not set)")]);
|
||||
table.push(["defaults.enable_graph", String(config.defaults.enableGraph)]);
|
||||
table.push(["", ""]);
|
||||
|
||||
// Platform
|
||||
|
||||
@@ -49,7 +49,6 @@ export async function cmdAdd(
|
||||
noInfer: boolean;
|
||||
expires?: string;
|
||||
categories?: string;
|
||||
enableGraph: boolean;
|
||||
output: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
@@ -140,7 +139,6 @@ export async function cmdAdd(
|
||||
infer: !opts.noInfer,
|
||||
expires: opts.expires,
|
||||
categories: cats,
|
||||
enableGraph: opts.enableGraph,
|
||||
});
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -225,7 +223,6 @@ export async function cmdSearch(
|
||||
keyword: boolean;
|
||||
filterJson?: string;
|
||||
fields?: string;
|
||||
enableGraph: boolean;
|
||||
output: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
@@ -274,7 +271,6 @@ export async function cmdSearch(
|
||||
keyword: opts.keyword,
|
||||
filters,
|
||||
fields: fieldList,
|
||||
enableGraph: opts.enableGraph,
|
||||
});
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -368,7 +364,6 @@ export async function cmdList(
|
||||
category?: string;
|
||||
after?: string;
|
||||
before?: string;
|
||||
enableGraph: boolean;
|
||||
output: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
@@ -396,7 +391,6 @@ export async function cmdList(
|
||||
category: opts.category,
|
||||
after: opts.after,
|
||||
before: opts.before,
|
||||
enableGraph: opts.enableGraph,
|
||||
});
|
||||
});
|
||||
} catch (e) {
|
||||
|
||||
@@ -28,7 +28,6 @@ export interface DefaultsConfig {
|
||||
agentId: string;
|
||||
appId: string;
|
||||
runId: string;
|
||||
enableGraph: boolean;
|
||||
}
|
||||
|
||||
export interface TelemetryConfig {
|
||||
@@ -50,7 +49,6 @@ export function createDefaultConfig(): Mem0Config {
|
||||
agentId: "",
|
||||
appId: "",
|
||||
runId: "",
|
||||
enableGraph: false,
|
||||
},
|
||||
platform: {
|
||||
apiKey: "",
|
||||
@@ -87,8 +85,6 @@ export function loadConfig(): Mem0Config {
|
||||
config.defaults.agentId = defaults.agent_id ?? "";
|
||||
config.defaults.appId = defaults.app_id ?? "";
|
||||
config.defaults.runId = defaults.run_id ?? "";
|
||||
config.defaults.enableGraph = defaults.enable_graph ?? false;
|
||||
|
||||
const telemetry = data.telemetry ?? {};
|
||||
config.telemetry.anonymousId = telemetry.anonymous_id ?? "";
|
||||
}
|
||||
@@ -104,12 +100,6 @@ export function loadConfig(): Mem0Config {
|
||||
config.defaults.agentId = process.env.MEM0_AGENT_ID;
|
||||
if (process.env.MEM0_APP_ID) config.defaults.appId = process.env.MEM0_APP_ID;
|
||||
if (process.env.MEM0_RUN_ID) config.defaults.runId = process.env.MEM0_RUN_ID;
|
||||
if (process.env.MEM0_ENABLE_GRAPH) {
|
||||
config.defaults.enableGraph = ["true", "1", "yes"].includes(
|
||||
process.env.MEM0_ENABLE_GRAPH.toLowerCase(),
|
||||
);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
@@ -123,7 +113,6 @@ export function saveConfig(config: Mem0Config): void {
|
||||
agent_id: config.defaults.agentId,
|
||||
app_id: config.defaults.appId,
|
||||
run_id: config.defaults.runId,
|
||||
enable_graph: config.defaults.enableGraph,
|
||||
},
|
||||
platform: {
|
||||
api_key: config.platform.apiKey,
|
||||
@@ -154,7 +143,6 @@ const KEY_MAP: Record<string, [keyof Mem0Config, string]> = {
|
||||
"defaults.agent_id": ["defaults", "agentId"],
|
||||
"defaults.app_id": ["defaults", "appId"],
|
||||
"defaults.run_id": ["defaults", "runId"],
|
||||
"defaults.enable_graph": ["defaults", "enableGraph"],
|
||||
// Short-form aliases
|
||||
api_key: ["platform", "apiKey"],
|
||||
base_url: ["platform", "baseUrl"],
|
||||
@@ -163,7 +151,6 @@ const KEY_MAP: Record<string, [keyof Mem0Config, string]> = {
|
||||
agent_id: ["defaults", "agentId"],
|
||||
app_id: ["defaults", "appId"],
|
||||
run_id: ["defaults", "runId"],
|
||||
enable_graph: ["defaults", "enableGraph"],
|
||||
};
|
||||
|
||||
export function getNestedValue(config: Mem0Config, dottedKey: string): unknown {
|
||||
|
||||
@@ -134,18 +134,6 @@ function resolveIds(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve graph tri-state: --no-graph > --graph > config default.
|
||||
*/
|
||||
function resolveGraph(
|
||||
config: Mem0Config,
|
||||
opts: { graph?: boolean; noGraph?: boolean },
|
||||
): boolean {
|
||||
if (opts.noGraph) return false;
|
||||
if (opts.graph) return true;
|
||||
return config.defaults.enableGraph;
|
||||
}
|
||||
|
||||
// ── Main program ──────────────────────────────────────────────────────────
|
||||
|
||||
program
|
||||
@@ -236,8 +224,6 @@ program
|
||||
.option("--no-infer", "Skip inference, store raw.")
|
||||
.option("--expires <date>", "Expiration date (YYYY-MM-DD).")
|
||||
.option("--categories <value>", "Categories (JSON array or comma-separated).")
|
||||
.option("--graph", "Enable graph memory extraction.", false)
|
||||
.option("--no-graph", "Disable graph memory extraction.")
|
||||
.option("-o, --output <format>", "Output format: text, json, quiet.", "text")
|
||||
.option("--api-key <key>", "Override API key.")
|
||||
.option("--base-url <url>", "Override API base URL.")
|
||||
@@ -253,9 +239,8 @@ program
|
||||
opts.baseUrl,
|
||||
);
|
||||
const ids = resolveIds(config, opts);
|
||||
const enableGraph = resolveGraph(config, opts);
|
||||
const output = isAgent ? "agent" : opts.output;
|
||||
await cmdAdd(backend, text, { ...ids, ...opts, enableGraph, output });
|
||||
await cmdAdd(backend, text, { ...ids, ...opts, output });
|
||||
});
|
||||
|
||||
// ── Memory: search ────────────────────────────────────────────────────────
|
||||
@@ -285,8 +270,6 @@ program
|
||||
.option("--keyword", "Use keyword search.", false)
|
||||
.option("--filter <json>", "Advanced filter expression (JSON).")
|
||||
.option("--fields <list>", "Specific fields to return (comma-separated).")
|
||||
.option("--graph", "Enable graph in search.", false)
|
||||
.option("--no-graph", "Disable graph in search.")
|
||||
.option("-o, --output <format>", "Output: text, json, table.", "text")
|
||||
.option("--api-key <key>", "Override API key.")
|
||||
.option("--base-url <url>", "Override API base URL.")
|
||||
@@ -310,7 +293,6 @@ program
|
||||
opts.baseUrl,
|
||||
);
|
||||
const ids = resolveIds(config, opts);
|
||||
const enableGraph = resolveGraph(config, opts);
|
||||
const output = isAgent ? "agent" : opts.output;
|
||||
await cmdSearch(backend, resolvedQuery, {
|
||||
...ids,
|
||||
@@ -320,7 +302,6 @@ program
|
||||
keyword: opts.keyword,
|
||||
filterJson: opts.filter,
|
||||
fields: opts.fields,
|
||||
enableGraph,
|
||||
output,
|
||||
});
|
||||
});
|
||||
@@ -364,8 +345,6 @@ program
|
||||
.option("--category <name>", "Filter by category.")
|
||||
.option("--after <date>", "Created after (YYYY-MM-DD).")
|
||||
.option("--before <date>", "Created before (YYYY-MM-DD).")
|
||||
.option("--graph", "Enable graph in listing.", false)
|
||||
.option("--no-graph", "Disable graph in listing.")
|
||||
.option("-o, --output <format>", "Output: text, json, table.", "table")
|
||||
.option("--api-key <key>", "Override API key.")
|
||||
.option("--base-url <url>", "Override API base URL.")
|
||||
@@ -381,7 +360,6 @@ program
|
||||
opts.baseUrl,
|
||||
);
|
||||
const ids = resolveIds(config, opts);
|
||||
const enableGraph = resolveGraph(config, opts);
|
||||
const output = isAgent ? "agent" : opts.output;
|
||||
await cmdList(backend, {
|
||||
...ids,
|
||||
@@ -390,7 +368,6 @@ program
|
||||
category: opts.category,
|
||||
after: opts.after,
|
||||
before: opts.before,
|
||||
enableGraph,
|
||||
output,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -107,22 +107,22 @@ describe("CLI Integration — help and version", () => {
|
||||
expect(result.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
it("add help has --graph flag", () => {
|
||||
it("add help has --output flag", () => {
|
||||
const result = run(["add", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("--graph");
|
||||
expect(result.stdout).toContain("--output");
|
||||
});
|
||||
|
||||
it("search help has --graph flag", () => {
|
||||
it("search help has --rerank flag", () => {
|
||||
const result = run(["search", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("--graph");
|
||||
expect(result.stdout).toContain("--rerank");
|
||||
});
|
||||
|
||||
it("list help has --graph flag", () => {
|
||||
it("list help has --category flag", () => {
|
||||
const result = run(["list", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("--graph");
|
||||
expect(result.stdout).toContain("--category");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ describe("cmdAdd", () => {
|
||||
userId: "alice",
|
||||
immutable: false,
|
||||
noInfer: false,
|
||||
enableGraph: false,
|
||||
|
||||
output: "text",
|
||||
});
|
||||
expect(mockBackend.add).toHaveBeenCalledOnce();
|
||||
@@ -55,7 +55,7 @@ describe("cmdAdd", () => {
|
||||
messages: JSON.stringify([{ role: "user", content: "I love Python" }]),
|
||||
immutable: false,
|
||||
noInfer: false,
|
||||
enableGraph: false,
|
||||
|
||||
output: "text",
|
||||
});
|
||||
expect(mockBackend.add).toHaveBeenCalledOnce();
|
||||
@@ -67,7 +67,7 @@ describe("cmdAdd", () => {
|
||||
userId: "alice",
|
||||
immutable: false,
|
||||
noInfer: false,
|
||||
enableGraph: false,
|
||||
|
||||
output: "json",
|
||||
});
|
||||
expect(output).toContain("results");
|
||||
@@ -79,7 +79,7 @@ describe("cmdAdd", () => {
|
||||
userId: "alice",
|
||||
immutable: false,
|
||||
noInfer: false,
|
||||
enableGraph: false,
|
||||
|
||||
output: "quiet",
|
||||
});
|
||||
expect(output).not.toContain("dark mode");
|
||||
@@ -101,7 +101,7 @@ describe("cmdAdd deduplicates PENDING", () => {
|
||||
userId: "alice",
|
||||
immutable: false,
|
||||
noInfer: false,
|
||||
enableGraph: false,
|
||||
|
||||
output: "text",
|
||||
});
|
||||
expect(output.match(/Queued/g)?.length).toBe(1);
|
||||
@@ -114,7 +114,7 @@ describe("cmdAdd deduplicates PENDING", () => {
|
||||
userId: "alice",
|
||||
immutable: false,
|
||||
noInfer: false,
|
||||
enableGraph: false,
|
||||
|
||||
output: "json",
|
||||
});
|
||||
const data = JSON.parse(output);
|
||||
@@ -130,7 +130,7 @@ describe("cmdAdd deduplicates PENDING", () => {
|
||||
userId: "alice",
|
||||
immutable: false,
|
||||
noInfer: false,
|
||||
enableGraph: false,
|
||||
|
||||
output: "agent",
|
||||
});
|
||||
const data = JSON.parse(output);
|
||||
@@ -148,7 +148,7 @@ describe("cmdSearch", () => {
|
||||
threshold: 0.3,
|
||||
rerank: false,
|
||||
keyword: false,
|
||||
enableGraph: false,
|
||||
|
||||
output: "text",
|
||||
});
|
||||
expect(output).toContain("Found 2");
|
||||
@@ -162,7 +162,7 @@ describe("cmdSearch", () => {
|
||||
threshold: 0.3,
|
||||
rerank: false,
|
||||
keyword: false,
|
||||
enableGraph: false,
|
||||
|
||||
output: "json",
|
||||
});
|
||||
expect(output).toContain("memory");
|
||||
@@ -177,7 +177,7 @@ describe("cmdSearch", () => {
|
||||
threshold: 0.3,
|
||||
rerank: false,
|
||||
keyword: false,
|
||||
enableGraph: false,
|
||||
|
||||
output: "text",
|
||||
});
|
||||
expect(errOutput).toContain("No memories found");
|
||||
@@ -205,7 +205,7 @@ describe("cmdList", () => {
|
||||
userId: "alice",
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
enableGraph: false,
|
||||
|
||||
output: "table",
|
||||
});
|
||||
expect(output).toContain("dark mode");
|
||||
@@ -218,7 +218,7 @@ describe("cmdList", () => {
|
||||
userId: "alice",
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
enableGraph: false,
|
||||
|
||||
output: "text",
|
||||
});
|
||||
expect(errOutput).toContain("No memories found");
|
||||
@@ -316,7 +316,7 @@ describe("agent mode", () => {
|
||||
userId: "alice",
|
||||
immutable: false,
|
||||
noInfer: false,
|
||||
enableGraph: false,
|
||||
|
||||
output: "agent",
|
||||
});
|
||||
const parsed = JSON.parse(output.trim());
|
||||
@@ -336,7 +336,7 @@ describe("agent mode", () => {
|
||||
threshold: 0.3,
|
||||
rerank: false,
|
||||
keyword: false,
|
||||
enableGraph: false,
|
||||
|
||||
output: "agent",
|
||||
});
|
||||
const parsed = JSON.parse(output.trim());
|
||||
@@ -361,7 +361,7 @@ describe("agent mode", () => {
|
||||
userId: "alice",
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
enableGraph: false,
|
||||
|
||||
output: "agent",
|
||||
});
|
||||
const parsed = JSON.parse(output.trim());
|
||||
|
||||
@@ -64,7 +64,6 @@ describe("createDefaultConfig", () => {
|
||||
expect(config.platform.baseUrl).toBe("https://api.mem0.ai");
|
||||
expect(config.platform.apiKey).toBe("");
|
||||
expect(config.defaults.userId).toBe("");
|
||||
expect(config.defaults.enableGraph).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -105,9 +104,4 @@ describe("setNestedValue", () => {
|
||||
expect(config.defaults.userId).toBe("bob");
|
||||
});
|
||||
|
||||
it("coerces boolean for enable_graph", () => {
|
||||
const config = createDefaultConfig();
|
||||
expect(setNestedValue(config, "defaults.enable_graph", "true")).toBe(true);
|
||||
expect(config.defaults.enableGraph).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "mem0-cli"
|
||||
version = "0.2.3"
|
||||
version = "0.2.4"
|
||||
description = "The official CLI for mem0 — the memory layer for AI agents"
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
"""mem0 CLI — the command-line interface for the mem0 memory layer."""
|
||||
|
||||
__version__ = "0.2.3"
|
||||
__version__ = "0.2.4"
|
||||
|
||||
@@ -267,8 +267,6 @@ def add(
|
||||
categories: str | None = typer.Option(
|
||||
None, "--categories", help="Categories (JSON array or comma-separated)."
|
||||
),
|
||||
graph: bool = typer.Option(False, "--graph", help="Enable graph memory extraction."),
|
||||
no_graph: bool = typer.Option(False, "--no-graph", help="Disable graph memory extraction."),
|
||||
output: str = typer.Option(
|
||||
"text", "--output", "-o", help="Output format: text, json, quiet.", rich_help_panel="Output"
|
||||
),
|
||||
@@ -295,13 +293,6 @@ def add(
|
||||
backend, config = _get_backend_and_config(api_key, base_url)
|
||||
ids = _resolve_ids(config, user_id=user_id, agent_id=agent_id, app_id=app_id, run_id=run_id)
|
||||
|
||||
if no_graph:
|
||||
graph_enabled = False
|
||||
elif graph:
|
||||
graph_enabled = True
|
||||
else:
|
||||
graph_enabled = config.defaults.enable_graph
|
||||
|
||||
cmd_add(
|
||||
backend,
|
||||
text,
|
||||
@@ -313,7 +304,6 @@ def add(
|
||||
no_infer=no_infer,
|
||||
expires=expires,
|
||||
categories=categories,
|
||||
enable_graph=graph_enabled,
|
||||
output=output,
|
||||
)
|
||||
|
||||
@@ -357,12 +347,6 @@ def search(
|
||||
help="Specific fields to return (comma-separated).",
|
||||
rich_help_panel="Search",
|
||||
),
|
||||
graph: bool = typer.Option(
|
||||
False, "--graph", help="Enable graph in search.", rich_help_panel="Search"
|
||||
),
|
||||
no_graph: bool = typer.Option(
|
||||
False, "--no-graph", help="Disable graph in search.", rich_help_panel="Search"
|
||||
),
|
||||
output: str = typer.Option(
|
||||
"text", "--output", "-o", help="Output: text, json, table.", rich_help_panel="Output"
|
||||
),
|
||||
@@ -396,13 +380,6 @@ def search(
|
||||
backend, config = _get_backend_and_config(api_key, base_url)
|
||||
ids = _resolve_ids(config, user_id=user_id, agent_id=agent_id, app_id=app_id, run_id=run_id)
|
||||
|
||||
if no_graph:
|
||||
graph_enabled = False
|
||||
elif graph:
|
||||
graph_enabled = True
|
||||
else:
|
||||
graph_enabled = config.defaults.enable_graph
|
||||
|
||||
cmd_search(
|
||||
backend,
|
||||
query,
|
||||
@@ -413,7 +390,6 @@ def search(
|
||||
keyword=keyword,
|
||||
filter_json=filter_json,
|
||||
fields=fields,
|
||||
enable_graph=graph_enabled,
|
||||
output=output,
|
||||
)
|
||||
|
||||
@@ -480,12 +456,6 @@ def list_cmd(
|
||||
before: str | None = typer.Option(
|
||||
None, "--before", help="Created before (YYYY-MM-DD).", rich_help_panel="Filters"
|
||||
),
|
||||
graph: bool = typer.Option(
|
||||
False, "--graph", help="Enable graph in listing.", rich_help_panel="Filters"
|
||||
),
|
||||
no_graph: bool = typer.Option(
|
||||
False, "--no-graph", help="Disable graph in listing.", rich_help_panel="Filters"
|
||||
),
|
||||
output: str = typer.Option(
|
||||
"table", "--output", "-o", help="Output: text, json, table.", rich_help_panel="Output"
|
||||
),
|
||||
@@ -511,13 +481,6 @@ def list_cmd(
|
||||
backend, config = _get_backend_and_config(api_key, base_url)
|
||||
ids = _resolve_ids(config, user_id=user_id, agent_id=agent_id, app_id=app_id, run_id=run_id)
|
||||
|
||||
if no_graph:
|
||||
graph_enabled = False
|
||||
elif graph:
|
||||
graph_enabled = True
|
||||
else:
|
||||
graph_enabled = config.defaults.enable_graph
|
||||
|
||||
cmd_list(
|
||||
backend,
|
||||
**ids,
|
||||
@@ -526,7 +489,6 @@ def list_cmd(
|
||||
category=category,
|
||||
after=after,
|
||||
before=before,
|
||||
enable_graph=graph_enabled,
|
||||
output=output,
|
||||
)
|
||||
|
||||
|
||||
@@ -26,7 +26,6 @@ class Backend(ABC):
|
||||
infer: bool = True,
|
||||
expires: str | None = None,
|
||||
categories: list[str] | None = None,
|
||||
enable_graph: bool = False,
|
||||
) -> dict: ...
|
||||
|
||||
@abstractmethod
|
||||
@@ -44,7 +43,6 @@ class Backend(ABC):
|
||||
keyword: bool = False,
|
||||
filters: dict | None = None,
|
||||
fields: list[str] | None = None,
|
||||
enable_graph: bool = False,
|
||||
) -> list[dict]: ...
|
||||
|
||||
@abstractmethod
|
||||
@@ -63,7 +61,6 @@ class Backend(ABC):
|
||||
category: str | None = None,
|
||||
after: str | None = None,
|
||||
before: str | None = None,
|
||||
enable_graph: bool = False,
|
||||
) -> list[dict]: ...
|
||||
|
||||
@abstractmethod
|
||||
|
||||
@@ -64,7 +64,6 @@ class PlatformBackend(Backend):
|
||||
infer: bool = True,
|
||||
expires: str | None = None,
|
||||
categories: list[str] | None = None,
|
||||
enable_graph: bool = False,
|
||||
) -> dict:
|
||||
payload: dict[str, Any] = {}
|
||||
|
||||
@@ -91,11 +90,9 @@ class PlatformBackend(Backend):
|
||||
payload["expiration_date"] = expires
|
||||
if categories:
|
||||
payload["categories"] = categories
|
||||
if enable_graph:
|
||||
payload["enable_graph"] = True
|
||||
payload["source"] = "CLI"
|
||||
|
||||
return self._request("POST", "/v1/memories/", json=payload)
|
||||
return self._request("POST", "/v3/memories/add/", json=payload)
|
||||
|
||||
def _build_filters(
|
||||
self,
|
||||
@@ -106,7 +103,7 @@ class PlatformBackend(Backend):
|
||||
run_id: str | None = None,
|
||||
extra_filters: dict | None = None,
|
||||
) -> dict | None:
|
||||
"""Build a filters dict for v2 API endpoints.
|
||||
"""Build a filters dict for v3 API endpoints.
|
||||
|
||||
Entity IDs are ANDed (all provided IDs must match).
|
||||
Extra filters (date ranges, categories) are also ANDed.
|
||||
@@ -152,7 +149,6 @@ class PlatformBackend(Backend):
|
||||
keyword: bool = False,
|
||||
filters: dict | None = None,
|
||||
fields: list[str] | None = None,
|
||||
enable_graph: bool = False,
|
||||
) -> list[dict]:
|
||||
payload: dict[str, Any] = {"query": query, "top_k": top_k, "threshold": threshold}
|
||||
|
||||
@@ -171,11 +167,9 @@ class PlatformBackend(Backend):
|
||||
payload["keyword_search"] = True
|
||||
if fields:
|
||||
payload["fields"] = fields
|
||||
if enable_graph:
|
||||
payload["enable_graph"] = True
|
||||
payload["source"] = "CLI"
|
||||
|
||||
result = self._request("POST", "/v2/memories/search/", json=payload)
|
||||
result = self._request("POST", "/v3/memories/search/", json=payload)
|
||||
return (
|
||||
result
|
||||
if isinstance(result, list)
|
||||
@@ -197,12 +191,11 @@ class PlatformBackend(Backend):
|
||||
category: str | None = None,
|
||||
after: str | None = None,
|
||||
before: str | None = None,
|
||||
enable_graph: bool = False,
|
||||
) -> list[dict]:
|
||||
payload: dict[str, Any] = {}
|
||||
params = {"page": str(page), "page_size": str(page_size)}
|
||||
|
||||
# Build filters for v2 API — entity IDs and date filters go inside "filters"
|
||||
# Build filters — entity IDs and date filters go inside "filters"
|
||||
extra: dict[str, Any] = {}
|
||||
if category:
|
||||
extra["categories"] = {"contains": category}
|
||||
@@ -220,11 +213,9 @@ class PlatformBackend(Backend):
|
||||
)
|
||||
if api_filters:
|
||||
payload["filters"] = api_filters
|
||||
if enable_graph:
|
||||
payload["enable_graph"] = True
|
||||
payload["source"] = "CLI"
|
||||
|
||||
result = self._request("POST", "/v2/memories/", json=payload, params=params)
|
||||
result = self._request("POST", "/v3/memories/", json=payload, params=params)
|
||||
return (
|
||||
result
|
||||
if isinstance(result, list)
|
||||
|
||||
@@ -39,7 +39,6 @@ def cmd_config_show(*, output: str = "text") -> None:
|
||||
"agent_id": config.defaults.agent_id or None,
|
||||
"app_id": config.defaults.app_id or None,
|
||||
"run_id": config.defaults.run_id or None,
|
||||
"enable_graph": config.defaults.enable_graph,
|
||||
},
|
||||
"platform": {
|
||||
"api_key": redact_key(config.platform.api_key),
|
||||
@@ -73,10 +72,6 @@ def cmd_config_show(*, output: str = "text") -> None:
|
||||
"defaults.run_id",
|
||||
config.defaults.run_id or f"[{DIM_COLOR}](not set)[/]",
|
||||
)
|
||||
table.add_row(
|
||||
"defaults.enable_graph",
|
||||
str(config.defaults.enable_graph).lower(),
|
||||
)
|
||||
table.add_row("", "")
|
||||
|
||||
# Platform
|
||||
|
||||
@@ -62,7 +62,6 @@ def cmd_add(
|
||||
no_infer: bool,
|
||||
expires: str | None,
|
||||
categories: str | None,
|
||||
enable_graph: bool = False,
|
||||
output: str = "text",
|
||||
) -> None:
|
||||
"""Add a memory."""
|
||||
@@ -145,7 +144,6 @@ def cmd_add(
|
||||
infer=not no_infer,
|
||||
expires=expires,
|
||||
categories=cats,
|
||||
enable_graph=enable_graph,
|
||||
)
|
||||
except Exception as e:
|
||||
ts.error_msg = str(e)
|
||||
@@ -226,7 +224,6 @@ def cmd_search(
|
||||
keyword: bool,
|
||||
filter_json: str | None,
|
||||
fields: str | None,
|
||||
enable_graph: bool = False,
|
||||
output: str = "text",
|
||||
) -> None:
|
||||
"""Search memories."""
|
||||
@@ -269,7 +266,6 @@ def cmd_search(
|
||||
keyword=keyword,
|
||||
filters=filters,
|
||||
fields=field_list,
|
||||
enable_graph=enable_graph,
|
||||
)
|
||||
except Exception as e:
|
||||
print_error(err_console, str(e))
|
||||
@@ -356,7 +352,6 @@ def cmd_list(
|
||||
category: str | None,
|
||||
after: str | None,
|
||||
before: str | None,
|
||||
enable_graph: bool = False,
|
||||
output: str = "table",
|
||||
) -> None:
|
||||
"""List memories."""
|
||||
@@ -385,7 +380,6 @@ def cmd_list(
|
||||
category=category,
|
||||
after=after,
|
||||
before=before,
|
||||
enable_graph=enable_graph,
|
||||
)
|
||||
except Exception as e:
|
||||
print_error(err_console, str(e))
|
||||
|
||||
@@ -36,7 +36,6 @@ class DefaultsConfig:
|
||||
agent_id: str = ""
|
||||
app_id: str = ""
|
||||
run_id: str = ""
|
||||
enable_graph: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -60,7 +59,6 @@ SHORT_KEY_ALIASES: dict[str, str] = {
|
||||
"agent_id": "defaults.agent_id",
|
||||
"app_id": "defaults.app_id",
|
||||
"run_id": "defaults.run_id",
|
||||
"enable_graph": "defaults.enable_graph",
|
||||
}
|
||||
|
||||
|
||||
@@ -91,8 +89,6 @@ def load_config() -> Mem0Config:
|
||||
config.defaults.agent_id = defaults.get("agent_id", "")
|
||||
config.defaults.app_id = defaults.get("app_id", "")
|
||||
config.defaults.run_id = defaults.get("run_id", "")
|
||||
config.defaults.enable_graph = defaults.get("enable_graph", False)
|
||||
|
||||
telemetry = data.get("telemetry", {})
|
||||
config.telemetry.anonymous_id = telemetry.get("anonymous_id", "")
|
||||
|
||||
@@ -121,10 +117,6 @@ def load_config() -> Mem0Config:
|
||||
if env_run_id:
|
||||
config.defaults.run_id = env_run_id
|
||||
|
||||
env_graph = os.environ.get("MEM0_ENABLE_GRAPH")
|
||||
if env_graph:
|
||||
config.defaults.enable_graph = env_graph.lower() in ("true", "1", "yes")
|
||||
|
||||
return config
|
||||
|
||||
|
||||
@@ -139,7 +131,6 @@ def save_config(config: Mem0Config) -> None:
|
||||
"agent_id": config.defaults.agent_id,
|
||||
"app_id": config.defaults.app_id,
|
||||
"run_id": config.defaults.run_id,
|
||||
"enable_graph": config.defaults.enable_graph,
|
||||
},
|
||||
"platform": {
|
||||
"api_key": config.platform.api_key,
|
||||
|
||||
@@ -224,24 +224,13 @@ class TestCLIIsolated:
|
||||
|
||||
|
||||
class TestCLINewFeatures:
|
||||
"""Tests for MCP parity features: --graph, --limit, entities delete."""
|
||||
"""Tests for MCP parity features: --limit, entities delete."""
|
||||
|
||||
def test_add_help_has_graph(self):
|
||||
result = _run(["add", "--help"])
|
||||
assert result.returncode == 0
|
||||
assert "--graph" in result.stdout
|
||||
|
||||
def test_search_help_has_graph_and_limit(self):
|
||||
def test_search_help_has_limit(self):
|
||||
result = _run(["search", "--help"])
|
||||
assert result.returncode == 0
|
||||
assert "--graph" in result.stdout
|
||||
assert "--limit" in result.stdout
|
||||
|
||||
def test_list_help_has_graph(self):
|
||||
result = _run(["list", "--help"])
|
||||
assert result.returncode == 0
|
||||
assert "--graph" in result.stdout
|
||||
|
||||
def test_delete_entity_via_delete_flag(self):
|
||||
"""delete --entity should appear in help output."""
|
||||
result = _run(["delete", "--help"])
|
||||
|
||||
@@ -997,85 +997,6 @@ class TestEntitiesDeleteCommand:
|
||||
mock_backend.delete_entities.assert_not_called()
|
||||
|
||||
|
||||
class TestEnableGraph:
|
||||
def test_add_with_graph(self, mock_backend):
|
||||
console, _buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
):
|
||||
cmd_add(
|
||||
mock_backend,
|
||||
"test",
|
||||
user_id="alice",
|
||||
agent_id=None,
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
messages=None,
|
||||
file=None,
|
||||
metadata=None,
|
||||
immutable=False,
|
||||
no_infer=False,
|
||||
expires=None,
|
||||
categories=None,
|
||||
enable_graph=True,
|
||||
output="text",
|
||||
)
|
||||
call_kwargs = mock_backend.add.call_args
|
||||
assert call_kwargs.kwargs.get("enable_graph") is True
|
||||
|
||||
def test_search_with_graph(self, mock_backend):
|
||||
console, _buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
):
|
||||
cmd_search(
|
||||
mock_backend,
|
||||
"test",
|
||||
user_id="alice",
|
||||
agent_id=None,
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
top_k=10,
|
||||
threshold=0.3,
|
||||
rerank=False,
|
||||
keyword=False,
|
||||
filter_json=None,
|
||||
fields=None,
|
||||
enable_graph=True,
|
||||
output="text",
|
||||
)
|
||||
call_kwargs = mock_backend.search.call_args
|
||||
assert call_kwargs.kwargs.get("enable_graph") is True
|
||||
|
||||
def test_list_with_graph(self, mock_backend):
|
||||
console, _buf = _make_console()
|
||||
err_console, _err_buf = _make_err_console()
|
||||
with (
|
||||
patch("mem0_cli.commands.memory.console", console),
|
||||
patch("mem0_cli.commands.memory.err_console", err_console),
|
||||
):
|
||||
cmd_list(
|
||||
mock_backend,
|
||||
user_id="alice",
|
||||
agent_id=None,
|
||||
app_id=None,
|
||||
run_id=None,
|
||||
page=1,
|
||||
page_size=100,
|
||||
category=None,
|
||||
after=None,
|
||||
before=None,
|
||||
enable_graph=True,
|
||||
output="table",
|
||||
)
|
||||
call_kwargs = mock_backend.list_memories.call_args
|
||||
assert call_kwargs.kwargs.get("enable_graph") is True
|
||||
|
||||
|
||||
class TestEventCommands:
|
||||
def test_event_list_table(self, mock_backend):
|
||||
console, buf = _make_console()
|
||||
|
||||
@@ -121,46 +121,6 @@ class TestConfig:
|
||||
assert config.defaults.agent_id == ""
|
||||
assert config.defaults.app_id == ""
|
||||
assert config.defaults.run_id == ""
|
||||
assert config.defaults.enable_graph is False
|
||||
|
||||
def test_enable_graph_save_and_load(self, isolate_config):
|
||||
config = Mem0Config()
|
||||
config.defaults.enable_graph = True
|
||||
save_config(config)
|
||||
loaded = load_config()
|
||||
assert loaded.defaults.enable_graph is True
|
||||
|
||||
def test_enable_graph_env_var_true(self, isolate_config, monkeypatch):
|
||||
monkeypatch.setenv("MEM0_ENABLE_GRAPH", "true")
|
||||
loaded = load_config()
|
||||
assert loaded.defaults.enable_graph is True
|
||||
|
||||
def test_enable_graph_env_var_false(self, isolate_config, monkeypatch):
|
||||
config = Mem0Config()
|
||||
config.defaults.enable_graph = True
|
||||
save_config(config)
|
||||
monkeypatch.setenv("MEM0_ENABLE_GRAPH", "false")
|
||||
loaded = load_config()
|
||||
assert loaded.defaults.enable_graph is False
|
||||
|
||||
def test_backward_compat_no_enable_graph_key(self, isolate_config):
|
||||
"""Old config files without 'enable_graph' key should default to False."""
|
||||
import json
|
||||
|
||||
from mem0_cli.config import CONFIG_FILE, ensure_config_dir
|
||||
|
||||
ensure_config_dir()
|
||||
data = {
|
||||
"version": 1,
|
||||
"defaults": {"user_id": "alice"},
|
||||
"platform": {"api_key": "m0-test", "base_url": "https://api.mem0.ai"},
|
||||
}
|
||||
with open(CONFIG_FILE, "w") as f:
|
||||
json.dump(data, f)
|
||||
|
||||
loaded = load_config()
|
||||
assert loaded.defaults.enable_graph is False
|
||||
assert loaded.defaults.user_id == "alice"
|
||||
|
||||
|
||||
class TestNestedAccess:
|
||||
@@ -192,11 +152,6 @@ class TestNestedAccess:
|
||||
assert set_nested_value(config, "defaults.user_id", "bob")
|
||||
assert config.defaults.user_id == "bob"
|
||||
|
||||
def test_set_defaults_enable_graph(self):
|
||||
config = Mem0Config()
|
||||
assert set_nested_value(config, "defaults.enable_graph", "true")
|
||||
assert config.defaults.enable_graph is True
|
||||
|
||||
|
||||
class TestResolveIds:
|
||||
def test_cli_flag_overrides_default(self):
|
||||
|
||||
@@ -56,7 +56,7 @@ class Mem0Teachability(AgentCapability):
|
||||
|
||||
def process_last_received_message(self, text: Union[Dict, str]):
|
||||
expanded_text = text
|
||||
if self.memory.get_all(agent_id=self.agent_id):
|
||||
if self.memory.get_all(filters={"agent_id": self.agent_id}):
|
||||
expanded_text = self._consider_memo_retrieval(text)
|
||||
self._consider_memo_storage(text)
|
||||
return expanded_text
|
||||
@@ -139,7 +139,7 @@ class Mem0Teachability(AgentCapability):
|
||||
return comment + self._concatenate_memo_texts(memo_list)
|
||||
|
||||
def _retrieve_relevant_memos(self, input_text: str) -> list:
|
||||
search_results = self.memory.search(input_text, agent_id=self.agent_id, limit=self.max_num_retrievals)
|
||||
search_results = self.memory.search(input_text, filters={"agent_id": self.agent_id}, top_k=self.max_num_retrievals)
|
||||
memo_list = [result["memory"] for result in search_results if result["score"] <= self.recall_threshold]
|
||||
|
||||
if self.verbosity >= 1 and not memo_list:
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
<Note type="info">
|
||||
<strong>🎉 Mem0 1.0.0 is here!</strong> Enhanced filtering, reranking, and smarter memory management.
|
||||
</Note>
|
||||
@@ -47,8 +47,6 @@ Provide at least one message or direct memory string. Most callers supply `messa
|
||||
| `messages` | array | No* | Conversation turns for Mem0 to infer memories from. Each object should include `role` and `content`. |
|
||||
| `metadata` | object | Optional | Custom key/value metadata (e.g., `{"topic": "preferences"}`). |
|
||||
| `infer` | boolean (default `true`) | Optional | Set to `false` to skip inference and store the provided text as-is. |
|
||||
| `async_mode` | boolean (default `true`) | Optional | Controls asynchronous processing. Most clients leave this enabled. |
|
||||
| `output_format` | string (default `v1.1`) | Optional | Response format. `v1.1` wraps results in a `results` array. |
|
||||
|
||||
> \* Provide at least one `messages` entry to describe what you are storing. For scoped memories, include `user_id`. You can also attach `agent_id`, `app_id`, `run_id`, `project_id`, or `org_id` to refine ownership.
|
||||
|
||||
@@ -83,20 +81,3 @@ Successful requests return an array of events queued for processing. Each event
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Graph relationships
|
||||
|
||||
Add Memories can enrich the knowledge graph on write. Set `enable_graph: true` to create entity nodes and relationships for the stored memory. Use this when you want downstream `get_all` or search calls to traverse connected entities.
|
||||
|
||||
<CodeGroup>
|
||||
```json Graph-aware request
|
||||
{
|
||||
"user_id": "alice",
|
||||
"messages": [
|
||||
{ "role": "user", "content": "I met with Dr. Lee at General Hospital." }
|
||||
],
|
||||
"enable_graph": true
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
The response follows the same format, and related entities become available in [Graph Memory](/platform/features/graph-memory) queries.
|
||||
|
||||
@@ -53,48 +53,3 @@ memories = client.get_all(
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
## Graph Memory
|
||||
|
||||
To retrieve graph memory relationships between entities, pass `output_format="v1.1"` in your request. This will return memories with entity and relationship information from the knowledge graph.
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
memories = client.get_all(
|
||||
filters={
|
||||
"user_id": "alex"
|
||||
},
|
||||
output_format="v1.1"
|
||||
)
|
||||
```
|
||||
|
||||
```python Output
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"id": "f4cbdb08-7062-4f3e-8eb2-9f5c80dfe64c",
|
||||
"memory": "Alex is planning a trip to San Francisco",
|
||||
"entities": [
|
||||
{
|
||||
"id": "entity-1",
|
||||
"name": "Alex",
|
||||
"type": "person"
|
||||
},
|
||||
{
|
||||
"id": "entity-2",
|
||||
"name": "San Francisco",
|
||||
"type": "location"
|
||||
}
|
||||
],
|
||||
"relations": [
|
||||
{
|
||||
"source": "entity-1",
|
||||
"target": "entity-2",
|
||||
"relationship": "traveling_to"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
@@ -32,7 +32,7 @@ Example with the mem0 Python package:
|
||||
|
||||
```python
|
||||
from mem0 import MemoryClient
|
||||
client = MemoryClient(org_id='YOUR_ORG_ID', project_id='YOUR_PROJECT_ID')
|
||||
client = MemoryClient(api_key="your-api-key")
|
||||
```
|
||||
|
||||
</Tab>
|
||||
@@ -41,10 +41,7 @@ client = MemoryClient(org_id='YOUR_ORG_ID', project_id='YOUR_PROJECT_ID')
|
||||
|
||||
```javascript
|
||||
import { MemoryClient } from "mem0ai";
|
||||
const client = new MemoryClient({
|
||||
organizationId: "YOUR_ORG_ID",
|
||||
projectId: "YOUR_PROJECT_ID"
|
||||
});
|
||||
const client = new MemoryClient({ apiKey: "your-api-key" });
|
||||
```
|
||||
|
||||
</Tab>
|
||||
@@ -98,9 +95,6 @@ client.project.update(
|
||||
custom_instructions="..."
|
||||
)
|
||||
|
||||
# Enable graph memory for the project
|
||||
client.project.update(enable_graph=True)
|
||||
|
||||
# Use the input language for memory storage and retrieval
|
||||
client.project.update(multilingual=True)
|
||||
|
||||
@@ -111,7 +105,6 @@ client.project.update(
|
||||
{"personal_info": "User personal information and preferences"},
|
||||
{"work_context": "Professional context and work-related information"}
|
||||
],
|
||||
enable_graph=True,
|
||||
multilingual=True
|
||||
)
|
||||
```
|
||||
@@ -172,11 +165,11 @@ All project methods are available in async mode:
|
||||
from mem0 import AsyncMemoryClient
|
||||
|
||||
async def manage_project():
|
||||
client = AsyncMemoryClient(org_id='YOUR_ORG_ID', project_id='YOUR_PROJECT_ID')
|
||||
client = AsyncMemoryClient(api_key="your-api-key")
|
||||
|
||||
# All methods support async/await
|
||||
project_info = await client.project.get()
|
||||
await client.project.update(enable_graph=True)
|
||||
await client.project.update(multilingual=True)
|
||||
members = await client.project.get_members()
|
||||
|
||||
# To call the async function properly
|
||||
|
||||
@@ -4,6 +4,26 @@ description: "Major product launches, headline features, and milestones for Mem0
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
<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**
|
||||
|
||||
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
|
||||
- **Entity linking** — Entities extracted, embedded, and linked across memories
|
||||
|
||||
Breaking changes: Graph memory removed from OSS, `search()` defaults changed, deprecated params removed. See [migration guide](/migration/oss-v2-to-v3).
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-04-06" description="Mem0 Skill Graph">
|
||||
|
||||
**Mem0 Skill Graph — In-Context Documentation for AI Agents**
|
||||
@@ -31,7 +51,7 @@ A full-featured command-line interface for Mem0, available in both Python and No
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-04-04" description="OpenClaw v1.0.4">
|
||||
<Update label="2026-04-06" description="OpenClaw v1.0.4">
|
||||
|
||||
**OpenClaw Plugin — Production-Ready**
|
||||
|
||||
|
||||
@@ -4,6 +4,19 @@ description: "Release notes for the OpenClaw plugin and agent harness."
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
<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:**
|
||||
|
||||
@@ -4,6 +4,13 @@ description: "Release notes for the Mem0 hosted platform — backend, dashboard,
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
<Update label="2026-04-16" description="">
|
||||
|
||||
**Improvements:**
|
||||
- **UI:** Removed Graph Memory tab, page, and all references from dashboard, sidebar, project settings, playground, and billing
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2025-07-23" description="">
|
||||
|
||||
**Bug Fixes:**
|
||||
|
||||
@@ -7,7 +7,57 @@ mode: "wide"
|
||||
<Tabs>
|
||||
<Tab title="Python">
|
||||
|
||||
<Update label="2026-04-04" description="v1.0.11">
|
||||
<Update label="2026-04-14" description="v2.0.0">
|
||||
|
||||
**Major Release** — Python SDK with V3 memory pipeline, ADD-only extraction, and cleaned-up API surface.
|
||||
|
||||
**New Features:**
|
||||
- **Single-Pass Extraction:** Replaced 2-LLM-call pipeline with additive extraction using `ADDITIVE_EXTRACTION_PROMPT`. Memories accumulate via `linked_memory_ids` — no more UPDATE/DELETE events ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **Hybrid Search:** Combined semantic + BM25 keyword matching + entity boost with additive scoring. Native `keyword_search()` added to 15 vector store adapters (Qdrant, Elasticsearch, OpenSearch, Azure AI Search, Weaviate, Redis, PGVector, Pinecone, Databricks, MongoDB, Milvus, Baidu, Upstash, Azure MySQL, Vertex AI) ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **Entity Extraction & Linking:** spaCy-based entity extraction with second vector collection (`{collection}_entities`) for cross-memory relationship retrieval. Optional dependency: `pip install mem0ai[nlp]` ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **Batch Operations:** Batch embedding, batch persist, and batch entity linking (8-phase pipeline) for both sync `Memory` and async `AsyncMemory` at full parity ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **Message Persistence:** SQLite-based rolling window (10 messages per session scope) for LLM context ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **Valkey Cluster Mode:** Added `cluster_mode` parameter for Valkey Cluster Mode Enabled (CME) deployments ([#4759](https://github.com/mem0ai/mem0/pull/4759))
|
||||
- **V3 API Endpoints:** `MemoryClient.add()` now posts to `/v3/memories/add/`; `MemoryClient.get_all()` posts to `/v3/memories/` and returns a paginated envelope `{"count": int, "next": str | None, "previous": str | None, "results": [...]}` ([#4856](https://github.com/mem0ai/mem0/pull/4856))
|
||||
- **Default model:** `gpt-5-mini` is now the default across `OpenAILLM`, `OpenAIStructuredLLM`, `AzureOpenAILLM`, `AzureOpenAIStructuredLLM`, and `LiteLLM` fallback ([#4829](https://github.com/mem0ai/mem0/pull/4829))
|
||||
|
||||
**Breaking Changes:**
|
||||
- **`add()` returns ADD-only events** — No more `"UPDATE"` or `"DELETE"` events. Memories accumulate; nothing is overwritten ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **`search()` default `threshold` is now `0.1`** — Pass `threshold=0.0` for previous behavior ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **`search()` `score` is now a combined multi-signal score** — The top-level `score` fuses semantic similarity, BM25 keyword match, and entity boost into one value. Absolute numbers shift versus the old raw cosine score; retune any hard thresholds against representative queries. Per-signal scores are not exposed on the response ([#4805](https://github.com/mem0ai/mem0/pull/4805), [#4836](https://github.com/mem0ai/mem0/pull/4836))
|
||||
- **`search()` default `rerank` is now `False`** — Pass `rerank=True` for previous behavior ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **`top_k` default changed 100 → 20** in `Memory.get_all()` and `Memory.search()` (sync + async). Pass `top_k=100` explicitly to restore the old behavior ([#4843](https://github.com/mem0ai/mem0/pull/4843))
|
||||
- **Entity ID validation:** `user_id` / `agent_id` / `run_id` are trimmed; empty-string and whitespace-only values now raise `ValueError` ([#4843](https://github.com/mem0ai/mem0/pull/4843))
|
||||
- **Search params validation:** `threshold` must be a number in `[0, 1]`; `top_k` must be a non-negative integer — invalid inputs raise `ValueError` ([#4843](https://github.com/mem0ai/mem0/pull/4843))
|
||||
- **`messages` in `Memory.add()` rejects invalid types:** Passing `None` or non-`(str | dict | list)` values raises `Mem0ValidationError` (`error_code="VALIDATION_003"`) ([#4843](https://github.com/mem0ai/mem0/pull/4843))
|
||||
- **`qdrant-client>=1.12.0` required** — Upgrade from `>=1.9.1` ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **`org_id` and `project_id` removed** — Removed from `MemoryClient` constructor and all method signatures ([#4740](https://github.com/mem0ai/mem0/pull/4740))
|
||||
- **Graph Memory Removed (OSS):** `mem0/memory/graph_memory.py`, `memgraph_memory.py`, `kuzu_memory.py`, `apache_age_memory.py`, and `mem0/graphs/` (Neo4j / Memgraph / Kuzu / Apache AGE / Neptune drivers) deleted — ~4,000 lines. Graph memory is no longer supported in the OSS SDK; graph drivers (neo4j, memgraph, kuzu, etc.) can be uninstalled. Use the Platform API for graph features. Remove `enable_graph` and `graph_store` from your config ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **`enable_graph` removed from Client SDK** — Graph memory is now a project-level setting on the Platform. Remove `enable_graph` from `MemoryClient.add()` / `search()` / `get_all()` / `update_project()` calls ([#4776](https://github.com/mem0ai/mem0/pull/4776))
|
||||
- **`custom_fact_extraction_prompt` renamed to `custom_instructions`** — Update config and memory module references ([#4740](https://github.com/mem0ai/mem0/pull/4740))
|
||||
- **Typed option classes** — Added Pydantic v2 typed classes: `AddMemoryOptions`, `SearchMemoryOptions`, `GetAllMemoryOptions`, `DeleteAllMemoryOptions`, `UpdateMemoryOptions`, `ProjectUpdateOptions` ([#4740](https://github.com/mem0ai/mem0/pull/4740))
|
||||
|
||||
**Security:**
|
||||
- **FAISS:** Prevent arbitrary code execution via pickle deserialization in `FAISS` vector store ([#4833](https://github.com/mem0ai/mem0/pull/4833))
|
||||
|
||||
**Bug Fixes:**
|
||||
- **V3 migration crashes:** Fixed crashes in the v3 migration path; entity linking on OSS is now functional across Qdrant and Milvus backends ([#4836](https://github.com/mem0ai/mem0/pull/4836))
|
||||
- **Qdrant entity store:** Entity store now shares the existing Qdrant client when using embedded mode (`path=...`), eliminating RocksDB lock contention between the main and entity collections ([#4836](https://github.com/mem0ai/mem0/pull/4836))
|
||||
- **Reranker:** Fixed incorrect use of SentenceTransformer for cross-encoder reranker models — switched to CrossEncoder API for proper scoring ([#4806](https://github.com/mem0ai/mem0/pull/4806))
|
||||
- **S3 Vectors:** Handle `vector=None` in `update()` to prevent boto3 validation error when `event=NONE` ([#4594](https://github.com/mem0ai/mem0/pull/4594))
|
||||
- **LLMs:** Made OpenAI `store` parameter opt-in to prevent leaking to non-OpenAI backends like Google Gemini ([#4757](https://github.com/mem0ai/mem0/pull/4757))
|
||||
- **LLMs:** Forward `response_format` to Azure OpenAI API to prevent JSON parsing failures ([#4689](https://github.com/mem0ai/mem0/pull/4689))
|
||||
- **Core:** Guard `temp_uuid_mapping` lookups against LLM-hallucinated IDs with safe `.get()` and warnings ([#4674](https://github.com/mem0ai/mem0/pull/4674))
|
||||
- **Client:** Prevent `MemoryClient.feedback()` telemetry TypeError by merging feedback data into single payload ([#4795](https://github.com/mem0ai/mem0/pull/4795))
|
||||
|
||||
**Improvements:**
|
||||
- **Telemetry:** Sample OSS hot-path events at 10% via PostHog `before_send` hook to reduce event volume ([#4771](https://github.com/mem0ai/mem0/pull/4771))
|
||||
|
||||
See the [OSS v1 to v2 migration guide](https://docs.mem0.ai/migration/oss-v1-to-v2) and [Platform migration guide](https://docs.mem0.ai/migration/platform-v2-to-v3) for upgrade instructions.
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-04-06" description="v1.0.11">
|
||||
|
||||
**New Features & Updates:**
|
||||
- **SDK:** Added `multilingual` parameter to project update ([#4314](https://github.com/mem0ai/mem0/pull/4314))
|
||||
@@ -843,7 +893,66 @@ mode: "wide"
|
||||
</Tab>
|
||||
|
||||
<Tab title="TypeScript">
|
||||
<Update label="2026-04-04" description="v2.4.6">
|
||||
<Update label="2026-04-20" description="v3.0.1">
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Telemetry:** SDK version is now injected into telemetry at build time via esbuild's `define`, replacing the two hardcoded version strings in `src/client/telemetry.ts` and `src/oss/src/utils/telemetry.ts`. Previously these were stuck at `2.1.36` and `2.1.34` while the published package was on `3.x`, so every telemetry event was reporting the wrong `client_version`. The placeholder is substituted with a string literal at bundle time — no runtime `require("./package.json")` in the shipped bundle ([#4897](https://github.com/mem0ai/mem0/pull/4897)).
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-04-14" description="v3.0.0">
|
||||
|
||||
**Major Release** — TypeScript SDK with V3 memory pipeline, camelCase parameters, and cleaned-up API surface.
|
||||
|
||||
**V3 Memory Pipeline (OSS):**
|
||||
- **Single-Pass Extraction:** Additive extraction pipeline aligned with Python SDK — memories accumulate, no UPDATE/DELETE events ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **Entity Extraction & Linking:** New `entity_extraction.ts` module (720+ lines) with cross-memory relationship retrieval ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **Message Persistence:** SQLite-based message history via new `SQLiteManager.ts` with rolling window for LLM context ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **Batch Embeddings:** `embedBatch()` support in OpenAI and Azure embedding providers ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **Scoring & Lemmatization:** New `scoring.ts` and `lemmatization.ts` utilities for hybrid search ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **New Prompts:** `prompts/index.ts` (592+ lines) with additive extraction prompt aligned with Python SDK ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **V3 API Endpoints:** `MemoryClient.add()` now posts to `/v3/memories/add/`; `MemoryClient.getAll()` posts to `/v3/memories/` with paginated envelope `{ count, next, previous, results }` ([#4856](https://github.com/mem0ai/mem0/pull/4856))
|
||||
- **Default model:** `gpt-5-mini` is now the default in `OpenAI`, `OpenAIStructured`, and `Azure` LLM providers ([#4829](https://github.com/mem0ai/mem0/pull/4829))
|
||||
|
||||
**Breaking Changes:**
|
||||
- **Graph Memory Removed (OSS):** `graph_memory.ts` (675 lines), `graphs/tools.ts` (267 lines), `graphs/utils.ts` (116 lines), `graphs/configs.ts` (30 lines) deleted. Graph memory is no longer supported in the OSS SDK — use Platform API for graph features ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **camelCase Parameters (Client SDK):** All user-facing parameters converted from snake_case to camelCase. Mapping is transparent at API boundary via `camelToSnakeKeys()` / `snakeToCamelKeys()` ([#4776](https://github.com/mem0ai/mem0/pull/4776))
|
||||
```typescript
|
||||
// Before
|
||||
client.add(messages, { user_id: "alice", top_k: 5 });
|
||||
// After
|
||||
client.add(messages, { userId: "alice", topK: 5 });
|
||||
```
|
||||
- **Per-Method Option Types:** Replaced monolithic `MemoryOptions` with typed interfaces: `AddMemoryOptions`, `SearchMemoryOptions`, `GetAllMemoryOptions`, `DeleteAllMemoryOptions` ([#4740](https://github.com/mem0ai/mem0/pull/4740))
|
||||
- **Removed Deprecated Parameters:** `org_id`, `project_id`, `api_version`, `output_format`, `async_mode`, `enable_graph`, `limit` removed from client method signatures. `ClientOptions` reduced to `{ apiKey, host }` only ([#4740](https://github.com/mem0ai/mem0/pull/4740))
|
||||
- **`limit` renamed to `topK` (OSS):** Update all search calls ([#4740](https://github.com/mem0ai/mem0/pull/4740))
|
||||
- **`topK` default changed 100 → 20** in `Memory.getAll()` and `Memory.search()`. Pass `topK: 100` explicitly to restore the old behavior ([#4843](https://github.com/mem0ai/mem0/pull/4843))
|
||||
- **Entity ID validation:** `userId` / `agentId` / `runId` are trimmed; empty-string and whitespace-only values now throw ([#4843](https://github.com/mem0ai/mem0/pull/4843))
|
||||
- **Search params validation:** `threshold` must be in `[0, 1]`; `topK` must be a non-negative integer — invalid inputs throw ([#4843](https://github.com/mem0ai/mem0/pull/4843))
|
||||
- **`messages` in `Memory.add()` is required:** Passing `undefined` or `null` now throws ([#4843](https://github.com/mem0ai/mem0/pull/4843))
|
||||
- **`customPrompt` renamed to `customInstructions` (OSS):** Update memory and vector store configurations ([#4740](https://github.com/mem0ai/mem0/pull/4740))
|
||||
- **`enableGraph` removed (OSS):** Config option removed — graph memory no longer available in OSS ([#4776](https://github.com/mem0ai/mem0/pull/4776))
|
||||
|
||||
**New Features:**
|
||||
- **LLMs:** Added DeepSeek LLM provider with OpenAI-compatible integration using custom baseURL to `api.deepseek.com` ([#4613](https://github.com/mem0ai/mem0/pull/4613))
|
||||
- **Entity store isolation:** `MemoryVectorStore` now uses a dedicated `_entities.db` file, preventing entity/memory store collisions ([#4829](https://github.com/mem0ai/mem0/pull/4829), [#4841](https://github.com/mem0ai/mem0/pull/4841))
|
||||
- **Payload backward compatibility:** Legacy camelCase payload keys normalized to snake_case on read ([#4841](https://github.com/mem0ai/mem0/pull/4841))
|
||||
|
||||
**Bug Fixes:**
|
||||
- **V3 migration:** Fixed crashes in the OSS migration path; entity linking works end-to-end ([#4836](https://github.com/mem0ai/mem0/pull/4836))
|
||||
- **PGVector init race:** `PGVector.initialize()` now memoises the in-flight init promise ([#4841](https://github.com/mem0ai/mem0/pull/4841))
|
||||
- **Redis module detection:** Handles both node-redis v4+ and legacy `moduleList` response shapes ([#4841](https://github.com/mem0ai/mem0/pull/4841))
|
||||
- **Config:** Fixed `ConfigManager.mergeConfig()` to only include `graphStore` when explicitly provided by user, preventing default Neo4j connection attempts ([#4776](https://github.com/mem0ai/mem0/pull/4776))
|
||||
- **LLMs:** Config manager now falls back to `userConf.url` for `baseURL` — prevents custom LLM providers (Ollama, LMStudio) from silently connecting to OpenAI ([#4761](https://github.com/mem0ai/mem0/pull/4761))
|
||||
|
||||
**Improvements:**
|
||||
- **Telemetry:** Sample OSS hot-path events at 10% to reduce PostHog event volume ([#4771](https://github.com/mem0ai/mem0/pull/4771))
|
||||
|
||||
See the [TypeScript SDK migration guide](https://docs.mem0.ai/migration/ts-v2-to-v3) for upgrade instructions.
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-04-06" description="v2.4.6">
|
||||
|
||||
**New Features & Updates:**
|
||||
- **Client:** Added `multilingual` parameter to project update types ([#4314](https://github.com/mem0ai/mem0/pull/4314))
|
||||
@@ -1160,6 +1269,16 @@ mode: "wide"
|
||||
|
||||
<Tab title="CLI">
|
||||
|
||||
<Update label="2026-04-22" description="Python v0.2.4 / Node v0.2.4">
|
||||
|
||||
**New Features:**
|
||||
- **V3 API Routes:** Migrated `add`, `search`, and `list` commands from v1/v2 to v3 API endpoints — `POST /v3/memories/add/`, `POST /v3/memories/search/`, `POST /v3/memories/`. Aligns both CLIs with the Python and TypeScript SDKs which already use v3 ([#4916](https://github.com/mem0ai/mem0/pull/4916))
|
||||
|
||||
**Breaking Changes:**
|
||||
- **`--graph` / `--no-graph` removed:** The `enable_graph` config option, `--graph` and `--no-graph` CLI flags, and `MEM0_ENABLE_GRAPH` environment variable have been removed from both CLIs. Graph memory is now a project-level setting on the Platform ([#4916](https://github.com/mem0ai/mem0/pull/4916))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-04-11" description="Python v0.2.3 / Node v0.2.3">
|
||||
|
||||
**Bug Fixes:**
|
||||
|
||||
@@ -21,7 +21,7 @@ os.environ["OPENAI_API_KEY"] = "your-api-key"
|
||||
|
||||
# Initialize a LangChain model directly
|
||||
openai_model = ChatOpenAI(
|
||||
model="gpt-4.1-nano-2025-04-14",
|
||||
model="gpt-5-mini",
|
||||
temperature=0.2,
|
||||
max_tokens=2000
|
||||
)
|
||||
|
||||
@@ -16,7 +16,7 @@ config = {
|
||||
"llm": {
|
||||
"provider": "litellm",
|
||||
"config": {
|
||||
"model": "gpt-4.1-nano-2025-04-14",
|
||||
"model": "gpt-5-mini",
|
||||
"temperature": 0.2,
|
||||
"max_tokens": 2000,
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ config = {
|
||||
"llm": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "gpt-4.1-nano-2025-04-14",
|
||||
"model": "gpt-5-mini",
|
||||
"temperature": 0.2,
|
||||
"max_tokens": 2000,
|
||||
}
|
||||
@@ -86,7 +86,7 @@ config = {
|
||||
"llm": {
|
||||
"provider": "openai_structured",
|
||||
"config": {
|
||||
"model": "gpt-4.1-nano-2025-04-14",
|
||||
"model": "gpt-5-mini",
|
||||
"temperature": 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ config = {
|
||||
"llm": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "gpt-4.1-nano-2025-04-14"
|
||||
"model": "gpt-5-mini"
|
||||
}
|
||||
},
|
||||
"reranker": {
|
||||
|
||||
@@ -189,7 +189,7 @@ for i, prompt in enumerate(prompts):
|
||||
config["reranker"]["config"]["scoring_prompt"] = prompt
|
||||
memory = Memory.from_config(config)
|
||||
|
||||
results = memory.search("test query", user_id="test_user")
|
||||
results = memory.search("test query", filters={"user_id": "test_user"})
|
||||
print(f"Prompt {i+1} results: {results}")
|
||||
```
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ config = {
|
||||
"llm": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "gpt-4.1-nano-2025-04-14"
|
||||
"model": "gpt-5-mini"
|
||||
}
|
||||
},
|
||||
"reranker": {
|
||||
@@ -95,7 +95,7 @@ messages = [
|
||||
memory.add(messages, user_id="bob")
|
||||
|
||||
# Search with reranking
|
||||
results = memory.search("What is the user's profession?", user_id="bob")
|
||||
results = memory.search("What is the user's profession?", filters={"user_id": "bob"})
|
||||
|
||||
for result in results['results']:
|
||||
print(f"Memory: {result['memory']}")
|
||||
|
||||
@@ -175,7 +175,7 @@ queries = [
|
||||
|
||||
results = []
|
||||
for query in queries:
|
||||
result = m.search(query, user_id="alice", rerank=True)
|
||||
result = m.search(query, filters={"user_id": "alice"}, rerank=True)
|
||||
results.append(result)
|
||||
```
|
||||
|
||||
|
||||
@@ -111,7 +111,7 @@ messages = [
|
||||
memory.add(messages, user_id="david")
|
||||
|
||||
# Search with LLM reranking
|
||||
results = memory.search("What programming topics is the user studying?", user_id="david")
|
||||
results = memory.search("What programming topics is the user studying?", filters={"user_id": "david"})
|
||||
|
||||
for result in results['results']:
|
||||
print(f"Memory: {result['memory']}")
|
||||
|
||||
@@ -283,12 +283,12 @@ for result in results["results"]:
|
||||
def safe_llm_rerank_search(query, user_id, max_retries=3):
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
return m.search(query, user_id=user_id, rerank=True)
|
||||
return m.search(query, filters={"user_id": user_id}, rerank=True)
|
||||
except Exception as e:
|
||||
print(f"Attempt {attempt + 1} failed: {e}")
|
||||
if attempt == max_retries - 1:
|
||||
# Fall back to vector search
|
||||
return m.search(query, user_id=user_id, rerank=False)
|
||||
return m.search(query, filters={"user_id": user_id}, rerank=False)
|
||||
|
||||
# Use the safe function
|
||||
results = safe_llm_rerank_search("What are my preferences?", "alice")
|
||||
@@ -376,19 +376,19 @@ class RobustLLMReranker:
|
||||
# Try primary LLM reranker
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
return self.primary.search(query, user_id=user_id, rerank=True)
|
||||
return self.primary.search(query, filters={"user_id": user_id}, rerank=True)
|
||||
except Exception as e:
|
||||
print(f"Primary reranker attempt {attempt + 1} failed: {e}")
|
||||
|
||||
# Try fallback reranker
|
||||
if self.fallback:
|
||||
try:
|
||||
return self.fallback.search(query, user_id=user_id, rerank=True)
|
||||
return self.fallback.search(query, filters={"user_id": user_id}, rerank=True)
|
||||
except Exception as e:
|
||||
print(f"Fallback reranker failed: {e}")
|
||||
|
||||
# Final fallback: vector search only
|
||||
return self.primary.search(query, user_id=user_id, rerank=False)
|
||||
return self.primary.search(query, filters={"user_id": user_id}, rerank=False)
|
||||
|
||||
# Usage
|
||||
primary_config = {
|
||||
|
||||
@@ -101,7 +101,7 @@ messages = [
|
||||
memory.add(messages, user_id="charlie")
|
||||
|
||||
# Search with local reranking
|
||||
results = memory.search("What books does the user like?", user_id="charlie")
|
||||
results = memory.search("What books does the user like?", filters={"user_id": "charlie"})
|
||||
|
||||
for result in results['results']:
|
||||
print(f"Memory: {result['memory']}")
|
||||
|
||||
@@ -86,7 +86,7 @@ messages = [
|
||||
memory.add(messages, user_id="alice")
|
||||
|
||||
# Search with reranking
|
||||
results = memory.search("What Italian food does the user like?", user_id="alice")
|
||||
results = memory.search("What Italian food does the user like?", filters={"user_id": "alice"})
|
||||
|
||||
for result in results['results']:
|
||||
print(f"Memory: {result['memory']}")
|
||||
|
||||
@@ -153,7 +153,7 @@ def measure_reranker_performance(config, queries, user_id):
|
||||
latencies = []
|
||||
for query in queries:
|
||||
start_time = time.time()
|
||||
results = memory.search(query, user_id=user_id)
|
||||
results = memory.search(query, filters={"user_id": user_id})
|
||||
latency = time.time() - start_time
|
||||
latencies.append(latency)
|
||||
|
||||
@@ -191,7 +191,7 @@ class CachedReranker:
|
||||
|
||||
@lru_cache(maxsize=1000)
|
||||
def search_cached(self, query_hash, user_id):
|
||||
return self.memory.search(query, user_id=user_id)
|
||||
return self.memory.search(query, filters={"user_id": user_id})
|
||||
|
||||
def search(self, query, user_id):
|
||||
query_hash = hashlib.md5(f"{query}_{user_id}".encode()).hexdigest()
|
||||
|
||||
@@ -15,7 +15,7 @@ Mem0 supports LangChain as a provider for vector store integration. LangChain pr
|
||||
```python Python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
from langchain_community.vectorstores import Chroma
|
||||
from langchain_chroma import Chroma
|
||||
from langchain_openai import OpenAIEmbeddings
|
||||
|
||||
# Initialize a LangChain vector store
|
||||
|
||||
@@ -72,7 +72,7 @@ m.add(messages, user_id="alice", metadata={"category": "movies"})
|
||||
### Search Memories
|
||||
|
||||
```python
|
||||
results = m.search("What kind of movies does Alice like?", user_id="alice")
|
||||
results = m.search("What kind of movies does Alice like?", filters={"user_id": "alice"})
|
||||
```
|
||||
|
||||
### Features
|
||||
|
||||
@@ -36,7 +36,7 @@ messages = [
|
||||
m.add(messages, user_id="alice", metadata={"category": "movies"})
|
||||
|
||||
# Search memories
|
||||
results = m.search(query="sci-fi recommendations", user_id="alice")
|
||||
results = m.search(query="sci-fi recommendations", filters={"user_id": "alice"})
|
||||
```
|
||||
|
||||
### Config
|
||||
|
||||
@@ -50,4 +50,25 @@ Here are the parameters available for configuring Valkey:
|
||||
| `hnsw_m` | Number of bi-directional links for HNSW | `16` |
|
||||
| `hnsw_ef_construction` | Size of dynamic candidate list for HNSW | `200` |
|
||||
| `hnsw_ef_runtime` | Size of dynamic candidate list for search | `10` |
|
||||
| `cluster_mode` | Enable cluster mode for Valkey cluster (CME) deployments | `false` |
|
||||
| `distance_metric` | Distance metric for vector similarity | `cosine` |
|
||||
|
||||
## Cluster Mode
|
||||
|
||||
To use Valkey with cluster mode enabled (CME), set `cluster_mode` to `true`:
|
||||
|
||||
```python
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "valkey",
|
||||
"config": {
|
||||
"collection_name": "memories",
|
||||
"valkey_url": "valkey://cluster-endpoint:6379",
|
||||
"embedding_model_dims": 1536,
|
||||
"cluster_mode": True
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When cluster mode is enabled, the connector uses `ValkeyCluster` instead of the standalone client, which handles `MOVED`/`ASK` redirections automatically. Search queries are coordinated across all shards by the valkey-search module's built-in coordinator. See the [valkey-search documentation](https://github.com/valkey-io/valkey-search) for details on cluster mode behavior.
|
||||
|
||||
@@ -60,7 +60,7 @@ class PersonalAITutor:
|
||||
"""
|
||||
# Start a streaming response request to the AI
|
||||
response = self.client.responses.create(
|
||||
model="gpt-4.1-nano-2025-04-14",
|
||||
model="gpt-5-mini",
|
||||
instructions="You are a personal AI Tutor.",
|
||||
input=question,
|
||||
stream=True
|
||||
@@ -81,7 +81,7 @@ class PersonalAITutor:
|
||||
:param user_id: Optional user ID to filter memories.
|
||||
:return: List of memories.
|
||||
"""
|
||||
return self.memory.get_all(user_id=user_id)
|
||||
return self.memory.get_all(filters={"user_id": user_id})
|
||||
|
||||
# Instantiate the PersonalAITutor
|
||||
ai_tutor = PersonalAITutor()
|
||||
|
||||
@@ -57,7 +57,7 @@ m = Memory.from_config(config)
|
||||
m.add("I'm visiting Paris", user_id="john")
|
||||
|
||||
# Retrieve memories
|
||||
memories = m.get_all(user_id="john")
|
||||
memories = m.get_all(filters={"user_id": "john"})
|
||||
```
|
||||
|
||||
## Key Points
|
||||
|
||||
@@ -47,7 +47,7 @@ ${memoriesStr}`;
|
||||
];
|
||||
|
||||
const response = await openaiClient.chat.completions.create({
|
||||
model: "gpt-4.1-nano-2025-04-14",
|
||||
model: "gpt-5-mini",
|
||||
messages: messages
|
||||
});
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ config = {
|
||||
"llm": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "gpt-4.1-nano-2025-04-14",
|
||||
"model": "gpt-5-mini",
|
||||
"temperature": 0.1,
|
||||
"max_tokens": 2000,
|
||||
}
|
||||
@@ -54,7 +54,6 @@ config = {
|
||||
"embedding_model_dims": 3072,
|
||||
}
|
||||
},
|
||||
"version": "v1.1",
|
||||
}
|
||||
|
||||
class PersonalTravelAssistant:
|
||||
@@ -77,7 +76,7 @@ class PersonalTravelAssistant:
|
||||
|
||||
# Generate response using Responses API
|
||||
response = self.client.responses.create(
|
||||
model="gpt-4.1-nano-2025-04-14",
|
||||
model="gpt-5-mini",
|
||||
input=prompt
|
||||
)
|
||||
|
||||
@@ -89,11 +88,11 @@ class PersonalTravelAssistant:
|
||||
return answer
|
||||
|
||||
def get_memories(self, user_id):
|
||||
memories = self.memory.get_all(user_id=user_id)
|
||||
memories = self.memory.get_all(filters={"user_id": user_id})
|
||||
return [m['memory'] for m in memories['results']]
|
||||
|
||||
def search_memories(self, query, user_id):
|
||||
memories = self.memory.search(query, user_id=user_id)
|
||||
memories = self.memory.search(query, filters={"user_id": user_id})
|
||||
return [m['memory'] for m in memories['results']]
|
||||
|
||||
# Usage example
|
||||
@@ -143,7 +142,7 @@ class PersonalTravelAssistant:
|
||||
|
||||
# Generate response using gpt-4.1-nano
|
||||
response = self.client.chat.completions.create(
|
||||
model="gpt-4.1-nano-2025-04-14"2025-04-14",
|
||||
model="gpt-5-mini",
|
||||
messages=self.messages
|
||||
)
|
||||
answer = response.choices[0].message.content
|
||||
@@ -154,11 +153,11 @@ class PersonalTravelAssistant:
|
||||
return answer
|
||||
|
||||
def get_memories(self, user_id):
|
||||
memories = self.memory.get_all(user_id=user_id)
|
||||
memories = self.memory.get_all(filters={"user_id": user_id})
|
||||
return [m['memory'] for m in memories.get('results', [])]
|
||||
|
||||
def search_memories(self, query, user_id):
|
||||
memories = self.memory.search(query, user_id=user_id)
|
||||
memories = self.memory.search(query, filters={"user_id": user_id})
|
||||
return [m['memory'] for m in memories.get('results', [])]
|
||||
|
||||
# Usage example
|
||||
|
||||
@@ -126,16 +126,15 @@ async def search_memories(
|
||||
print(f"Finding memories related to: {query}")
|
||||
results = await mem0_client.search(
|
||||
query,
|
||||
user_id=USER_ID,
|
||||
limit=5,
|
||||
filters={"user_id": USER_ID},
|
||||
top_k=5,
|
||||
threshold=0.7, # Higher threshold for more relevant results
|
||||
|
||||
)
|
||||
|
||||
|
||||
# Format and return the results
|
||||
if not results.get('results', []):
|
||||
return "I don't have any relevant memories about this topic."
|
||||
|
||||
|
||||
memories = [f"• {result['memory']}" for result in results.get('results', [])]
|
||||
return "Here's what I remember that might be relevant:\n" + "\n".join(memories)
|
||||
```
|
||||
@@ -161,7 +160,7 @@ def create_memory_voice_agent():
|
||||
Use the search_memories tool when you need context from past conversations or user asks you to recall something.
|
||||
""",
|
||||
),
|
||||
model="gpt-4.1-nano-2025-04-14",
|
||||
model="gpt-5-mini",
|
||||
tools=[save_memories, search_memories],
|
||||
)
|
||||
|
||||
@@ -342,16 +341,15 @@ async def search_memories(
|
||||
print(f"Finding memories related to: {query}")
|
||||
results = await mem0_client.search(
|
||||
query,
|
||||
user_id=USER_ID,
|
||||
limit=5,
|
||||
filters={"user_id": USER_ID},
|
||||
top_k=5,
|
||||
threshold=0.7, # Higher threshold for more relevant results
|
||||
|
||||
)
|
||||
|
||||
|
||||
# Format and return the results
|
||||
if not results.get('results', []):
|
||||
return "I don't have any relevant memories about this topic."
|
||||
|
||||
|
||||
memories = [f"• {result['memory']}" for result in results.get('results', [])]
|
||||
return "Here's what I remember that might be relevant:\n" + "\n".join(memories)
|
||||
|
||||
@@ -368,7 +366,7 @@ def create_memory_voice_agent():
|
||||
Use the search_memories tool when you need context from past conversations or user asks you to recall something.
|
||||
""",
|
||||
),
|
||||
model="gpt-4.1-nano-2025-04-14",
|
||||
model="gpt-5-mini",
|
||||
tools=[save_memories, search_memories],
|
||||
)
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ mem0_client = MemoryClient(api_key="your-mem0-key")
|
||||
|
||||
def chat(user_input, user_id):
|
||||
# Retrieve relevant memories
|
||||
memories = mem0_client.search(user_input, user_id=user_id, limit=5)
|
||||
memories = mem0_client.search(user_input, filters={"user_id": user_id}, top_k=5)
|
||||
context = "\\n".join(m["memory"] for m in memories["results"])
|
||||
|
||||
# Call LLM with memory context
|
||||
@@ -123,7 +123,7 @@ ollama_chat = OpenAI(base_url=f"{OLLAMA_URL}/v1", api_key="ollama")
|
||||
|
||||
def chat(user_input, user_id):
|
||||
# Retrieve relevant memories
|
||||
memories = memory.search(user_input, user_id=user_id, limit=5)
|
||||
memories = memory.search(user_input, filters={"user_id": user_id}, top_k=5)
|
||||
context = "\n".join(m["memory"] for m in memories["results"])
|
||||
|
||||
# Call LLM with memory context (Ollama via OpenAI-compatible API)
|
||||
@@ -319,7 +319,7 @@ print([m["memory"] for m in memories["results"]])
|
||||
</Tab>
|
||||
<Tab title="Open Source">
|
||||
```python
|
||||
memories = memory.get_all(user_id="max")
|
||||
memories = memory.get_all(filters={"user_id": "max"})
|
||||
print([m["memory"] for m in memories["results"]])
|
||||
# Output: ["Max wants to run marathon under 4 hours", "hey", "lol ok", "cool thanks", "gtg bye"]
|
||||
```
|
||||
@@ -354,10 +354,10 @@ Exclude:
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Open Source">
|
||||
Tell Mem0 what matters by including `custom_fact_extraction_prompt` in the config dict:
|
||||
Tell Mem0 what matters by including `custom_instructions` in the config dict:
|
||||
|
||||
```python
|
||||
MEMORY_CONFIG["custom_fact_extraction_prompt"] = """
|
||||
MEMORY_CONFIG["custom_instructions"] = """
|
||||
Extract from running coach conversations:
|
||||
- Training goals and race targets
|
||||
- Physical constraints or injuries
|
||||
@@ -375,7 +375,7 @@ Return JSON with key "facts" as a list of strings (use [] if nothing to store).
|
||||
memory = Memory.from_config(MEMORY_CONFIG)
|
||||
```
|
||||
|
||||
<Note>`custom_fact_extraction_prompt` 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()`. Make sure it's set before creating the Memory instance — not after.</Note>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
@@ -397,7 +397,7 @@ print([m["memory"] for m in memories["results"]])
|
||||
chat("hey how's it going", user_id="max")
|
||||
chat("I prefer trail running over roads", user_id="max")
|
||||
|
||||
memories = memory.get_all(user_id="max")
|
||||
memories = memory.get_all(filters={"user_id": "max"})
|
||||
print([m["memory"] for m in memories["results"]])
|
||||
# Output: ["Max wants to run marathon under 4 hours", "Max prefers trail running over roads"]
|
||||
```
|
||||
@@ -446,7 +446,7 @@ Retrieve agent style alongside user memories:
|
||||
<Tab title="Platform">
|
||||
```python
|
||||
# Get coach personality
|
||||
agent_memories = mem0_client.search("coaching style", agent_id="ray_coach")
|
||||
agent_memories = mem0_client.search("coaching style", filters={"agent_id": "ray_coach"})
|
||||
# Output: ["Max wants direct, data-driven feedback. Skip motivational language."]
|
||||
|
||||
# Store conversations with agent_id
|
||||
@@ -459,7 +459,7 @@ mem0_client.add([
|
||||
<Tab title="Open Source">
|
||||
```python
|
||||
# Get coach personality
|
||||
agent_memories = memory.search("coaching style", agent_id="ray_coach")
|
||||
agent_memories = memory.search("coaching style", filters={"agent_id": "ray_coach"})
|
||||
# Output: ["Max wants direct, data-driven feedback. Skip motivational language."]
|
||||
|
||||
# Store conversations with agent_id
|
||||
@@ -520,7 +520,7 @@ memory.add(
|
||||
# "hey" → don't store
|
||||
# "cool thanks" → don't store
|
||||
|
||||
# Or rely on custom_fact_extraction_prompt to filter automatically
|
||||
# Or rely on custom_instructions to filter automatically
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
@@ -545,11 +545,11 @@ expiration = (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d")
|
||||
mem0_client.add(
|
||||
[{"role": "user", "content": "Rolled my left ankle, needs rest"}],
|
||||
user_id="max",
|
||||
expiration_date=expiration
|
||||
metadata={"memory_bucket": "constraints", "expires_on": expiration}
|
||||
)
|
||||
```
|
||||
|
||||
In 14 days, this memory disappears automatically. Ray stops asking about the ankle.
|
||||
Store `expires_on` in metadata and periodically clean up expired memories. Ray stops asking about the ankle once it's removed.
|
||||
</Tab>
|
||||
<Tab title="Open Source">
|
||||
```python
|
||||
@@ -627,7 +627,7 @@ MEMORY_CONFIG = {
|
||||
"ollama_base_url": "http://localhost:11434",
|
||||
},
|
||||
},
|
||||
"custom_fact_extraction_prompt": """
|
||||
"custom_instructions": """
|
||||
Extract: goals, constraints, preferences, progress
|
||||
Exclude: greetings, filler, casual chat
|
||||
Return JSON with key "facts" as a list of strings.
|
||||
@@ -684,8 +684,7 @@ expiration = (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d")
|
||||
mem0_client.add(
|
||||
[{"role": "user", "content": "Rolled ankle, need light workouts"}],
|
||||
user_id="max",
|
||||
categories=["constraints"],
|
||||
expiration_date=expiration
|
||||
metadata={"memory_bucket": "constraints", "expires_on": expiration}
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
@@ -706,13 +705,13 @@ memory.add(
|
||||
<Tabs>
|
||||
<Tab title="Platform">
|
||||
```python
|
||||
memories = mem0_client.search("training plan", user_id="max", limit=5)
|
||||
memories = mem0_client.search("training plan", filters={"user_id": "max"}, top_k=5)
|
||||
# Gets: marathon goal, trail preference, ankle injury (if still valid)
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Open Source">
|
||||
```python
|
||||
memories = memory.search("training plan", user_id="max", limit=5)
|
||||
memories = memory.search("training plan", filters={"user_id": "max"}, top_k=5)
|
||||
# Gets: marathon goal, trail preference, ankle injury (if still valid / not pruned)
|
||||
```
|
||||
</Tab>
|
||||
@@ -806,7 +805,7 @@ mem0_client.update(goal_memory["id"], "Max wants to run sub-3:45 marathon")
|
||||
<Tab title="Open Source">
|
||||
```python
|
||||
# Find the old memory
|
||||
memories = memory.get_all(user_id="max")
|
||||
memories = memory.get_all(filters={"user_id": "max"})
|
||||
goal_memory = [m for m in memories["results"] if "sub-4" in m["memory"]][0]
|
||||
|
||||
# Update it
|
||||
|
||||
@@ -1,361 +0,0 @@
|
||||
---
|
||||
title: Choose Vector vs Graph Memory
|
||||
description: "Blend vector search with graph relationships to answer multi-hop questions."
|
||||
---
|
||||
|
||||
|
||||
Most AI agents use vector stores for RAG operations - they work great for semantic search and retrieving relevant context. But there's a gap when queries require understanding connections between entities.
|
||||
|
||||
Mem0 brings graph memory into the picture to fill this gap. In this cookbook, we'll create a company knowledge base with Mem0, using both vector and graph stores. You'll learn when each one helps along the way.
|
||||
|
||||
---
|
||||
|
||||
## Vector and Graph Stores
|
||||
|
||||
When you add a memory to Mem0, it goes into a **vector store** by default. Vector stores are excellent at semantic search - finding memories that match the meaning of your query.
|
||||
|
||||
**Graph stores** work differently. They extract **entities** (people, projects, teams) and **relationships between them** (works_with, reports_to, member_of). This lets you answer questions that need connecting information across multiple memories.
|
||||
|
||||
We will go through examples in this cookbook while building a company's knowledge base along the way.
|
||||
|
||||
---
|
||||
|
||||
## Starting Simple
|
||||
|
||||
Since we're building a company knowledge base, let's add some employee information:
|
||||
|
||||
```python
|
||||
from mem0 import MemoryClient
|
||||
|
||||
client = MemoryClient(api_key="your-api-key")
|
||||
# Add employee info
|
||||
client.add("Emma is a software engineer in Seattle", user_id="company_kb")
|
||||
client.add("David is a product manager in Austin", user_id="company_kb")
|
||||
|
||||
```
|
||||
|
||||
Now let's search for Emma's role:
|
||||
|
||||
```python
|
||||
results = client.search("What does Emma do?", filters={"user_id": "company_kb"})
|
||||
print(results['results'][0]['memory'])
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Emma is a software engineer in Seattle
|
||||
|
||||
```
|
||||
|
||||
<Info>
|
||||
**Expected output:** Vector search returned Emma's role instantly. When queries ask for facts directly stored in one memory, vector semantic search is perfect—fast and accurate.
|
||||
</Info>
|
||||
|
||||
This works perfectly. Vector search found the memory that semantically matches "What does Emma do?" and returned Emma's role.
|
||||
|
||||
---
|
||||
|
||||
## Adding Team Structure
|
||||
|
||||
Let's add some information about how the team works together:
|
||||
|
||||
```python
|
||||
client.add("Emma works with David on the mobile app redesign", user_id="company_kb")
|
||||
client.add("David reports to Rachel, who manages the design team", user_id="company_kb")
|
||||
|
||||
```
|
||||
|
||||
Now we have two pieces of information stored:
|
||||
|
||||
1. Emma works with David
|
||||
2. David reports to Rachel
|
||||
|
||||
Let's try asking something that needs both pieces:
|
||||
|
||||
```python
|
||||
results = client.search(
|
||||
"Who is Emma's teammate's manager?",
|
||||
filters={"user_id": "company_kb"}
|
||||
)
|
||||
|
||||
for r in results['results']:
|
||||
print(r['memory'])
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Emma works with David on the mobile app redesign
|
||||
David reports to Rachel, who manages the design team
|
||||
|
||||
```
|
||||
|
||||
Vector search returned both memories, but it didn't connect them. You'd need to manually figure out:
|
||||
|
||||
- Emma's teammate is David (from memory 1)
|
||||
- David's manager is Rachel (from memory 2)
|
||||
- So the answer is Rachel
|
||||
|
||||
<Warning>
|
||||
Vector search can't traverse relationships. It returns relevant memories, but you must connect the dots manually. For "Who is Emma's teammate's manager?", vector search gives you the pieces—not the answer. This breaks down as queries get more complex (3+ hops).
|
||||
</Warning>
|
||||
|
||||
---
|
||||
|
||||
## Enter Graph Memory
|
||||
|
||||
Let's add the same information with graph memory enabled:
|
||||
|
||||
```python
|
||||
client.add(
|
||||
"Emma works with David on the mobile app redesign",
|
||||
user_id="company_kb",
|
||||
enable_graph=True
|
||||
)
|
||||
|
||||
client.add(
|
||||
"David reports to Rachel, who manages the design team",
|
||||
user_id="company_kb",
|
||||
enable_graph=True
|
||||
)
|
||||
|
||||
```
|
||||
|
||||
When you set `enable_graph=True`, Mem0 extracts entities and relationships:
|
||||
|
||||
- `emma --[works_with]--> david`
|
||||
- `david --[reports_to]--> rachel`
|
||||
- `rachel --[manages]--> design_team`
|
||||
|
||||
Now the same query works differently:
|
||||
|
||||
```python
|
||||
results = client.search(
|
||||
"Who is Emma's teammate's manager?",
|
||||
filters={"user_id": "company_kb"},
|
||||
enable_graph=True
|
||||
)
|
||||
|
||||
print(results['results'][0]['memory'])
|
||||
print("\\nRelationships found:")
|
||||
for rel in results.get('relations', []):
|
||||
print(f" {rel['source']}, {rel['target']} ({rel['relationship']})")
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
David reports to Rachel, who manages the design team
|
||||
|
||||
Relationships found:
|
||||
emma, david (works_with)
|
||||
david, rachel (reports_to)
|
||||
|
||||
```
|
||||
|
||||
<Info>
|
||||
**Expected behavior:** Graph memory returns the direct answer—"David reports to Rachel"—plus the relationship chain that got there. No manual connecting needed. The graph traversed: Emma → works_with → David → reports_to → Rachel.
|
||||
</Info>
|
||||
|
||||
Graph memory traversed the relationships automatically: Emma works with David, David reports to Rachel, so Rachel is the answer.
|
||||
|
||||
---
|
||||
|
||||
## How It Connects
|
||||
|
||||
Here's what the graph looks like behind the scenes:
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
Emma[Emma] -->|works_with| David[David]
|
||||
David -->|reports_to| Rachel[Rachel]
|
||||
Rachel -->|manages| DesignTeam[Design Team]
|
||||
David -->|works_on| MobileApp[Mobile App]
|
||||
Emma -->|works_on| MobileApp
|
||||
|
||||
```
|
||||
|
||||
Graph memory lets you discover relations and memories which are tricky to do with direct vector stores.
|
||||
|
||||
Vector search would need the exact words in your query to match. Graph memory follows the connections.
|
||||
|
||||
---
|
||||
|
||||
## When to Use Each
|
||||
|
||||
Use **vector store** (default) when:
|
||||
|
||||
- Searching documents by semantic similarity
|
||||
- Looking up facts that don't need relationships
|
||||
- Building FAQs or knowledge bases where each item stands alone
|
||||
|
||||
Use **graph memory** when:
|
||||
|
||||
- Tracking organizational hierarchies (who reports to whom)
|
||||
- Understanding project teams (who collaborates with whom)
|
||||
- Building CRMs (which contacts connect to which companies)
|
||||
- Product recommendations (what items are bought together)
|
||||
|
||||
For our company knowledge base, we'll use both:
|
||||
|
||||
- Vector for individual facts: "Emma specializes in React"
|
||||
- Graph for relationships: "Emma works with David"
|
||||
|
||||
---
|
||||
|
||||
## Putting It Together
|
||||
|
||||
Let's build a small company knowledge base with both approaches:
|
||||
|
||||
```python
|
||||
# Facts about individuals - vector store is fine
|
||||
client.add("Emma specializes in React and TypeScript", user_id="company_kb")
|
||||
client.add("David has 5 years of product management experience", user_id="company_kb")
|
||||
|
||||
# Relationships - use graph memory
|
||||
client.add(
|
||||
"Emma and David work together on the mobile app",
|
||||
user_id="company_kb",
|
||||
enable_graph=True
|
||||
)
|
||||
|
||||
client.add(
|
||||
"David reports to Rachel",
|
||||
user_id="company_kb",
|
||||
enable_graph=True
|
||||
)
|
||||
|
||||
client.add(
|
||||
"Rachel runs weekly team syncs every Tuesday",
|
||||
user_id="company_kb",
|
||||
enable_graph=True
|
||||
)
|
||||
|
||||
```
|
||||
|
||||
Now we can ask different types of questions:
|
||||
|
||||
```python
|
||||
# Direct fact - vector search
|
||||
results = client.search("What are Emma's skills?", filters={"user_id": "company_kb"})
|
||||
print(results['results'][0]['memory'])
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Emma specializes in React and TypeScript
|
||||
|
||||
```
|
||||
|
||||
```python
|
||||
# Multi-hop relationship - graph search
|
||||
results = client.search(
|
||||
"What meetings does Emma's project manager's boss run?",
|
||||
filters={"user_id": "company_kb"},
|
||||
enable_graph=True
|
||||
)
|
||||
print(results['results'][0]['memory'])
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Rachel runs weekly team syncs every Tuesday
|
||||
|
||||
```
|
||||
|
||||
Graph memory connected: Emma works with David, David reports to Rachel, Rachel runs team syncs.
|
||||
|
||||
<Tip>
|
||||
Enable graph memory when your queries need multi-hop traversal: org charts (who reports to whom), project teams (who collaborates), CRMs (which contacts connect to companies). For single-fact lookups, stick with vector search—it's faster and cheaper.
|
||||
</Tip>
|
||||
|
||||
---
|
||||
|
||||
## The Tradeoff
|
||||
|
||||
Graph memory adds processing time and cost. When you call `client.add()` with `enable_graph=True`, Mem0 makes extra LLM calls to extract entities and relationships.
|
||||
|
||||
<Note>
|
||||
**Cost consideration:** Graph memory extraction adds ~2-3 extra LLM calls per `add()` operation to identify entities and relationships. Use it selectively—enable graph for organizational structure and long-term relationships, skip it for temporary notes and simple facts.
|
||||
</Note>
|
||||
|
||||
Use graph memory when the relationship traversal adds real value. For most use cases, vector search is sufficient and faster.
|
||||
|
||||
```python
|
||||
# Long-term organizational structure - worth using graph
|
||||
client.add(
|
||||
"Emma mentors two junior engineers on the frontend team",
|
||||
user_id="company_kb",
|
||||
enable_graph=True
|
||||
)
|
||||
|
||||
# Temporary notes - skip graph, not worth the cost
|
||||
client.add(
|
||||
"Emma is out sick today",
|
||||
user_id="company_kb",
|
||||
run_id="daily_notes"
|
||||
)
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Enabling Graph Memory
|
||||
|
||||
You can enable graph memory in two ways:
|
||||
|
||||
**Per-call** (recommended to start):
|
||||
|
||||
```python
|
||||
client.add("Emma works with David", user_id="company_kb", enable_graph=True)
|
||||
client.search("team structure", filters={"user_id": "company_kb"}, enable_graph=True)
|
||||
|
||||
```
|
||||
|
||||
**Project-wide** (if most of your data has relationships):
|
||||
|
||||
```python
|
||||
client.project.update(enable_graph=True)
|
||||
|
||||
# Now every add uses graph automatically
|
||||
client.add("Emma mentors Jordan", user_id="company_kb")
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## What You Built
|
||||
|
||||
A hybrid company knowledge base that combines both architectures:
|
||||
|
||||
- **Vector search** - Fast semantic lookups for individual facts (Emma's skills, David's experience)
|
||||
- **Graph memory** - Multi-hop relationship traversal (Emma's teammate's manager, project hierarchies)
|
||||
- **Selective enablement** - Graph only for long-term organizational structure, vector for everything else
|
||||
- **Cost optimization** - Skip graph extraction for temporary notes and simple facts
|
||||
|
||||
This pattern scales from 10-person startups to enterprise org charts with thousands of employees.
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
Vector stores handle most memory operations efficiently—semantic search works great for finding relevant information. Add graph memory when your queries need to understand how entities connect across multiple hops.
|
||||
|
||||
The key is knowing which tool fits your query pattern: direct questions work with vectors, multi-hop relationship queries need graphs.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Partition Memories by Entity" icon="layers" href="/cookbooks/essentials/entity-partitioning-playbook">
|
||||
Scope memories across users, agents, apps, and sessions to balance personalization and reuse.
|
||||
</Card>
|
||||
<Card title="Export Everything Safely" icon="download" href="/cookbooks/essentials/exporting-memories">
|
||||
Learn how to migrate or audit stored memories with structured exports.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -513,11 +513,6 @@ These controls prevent retrieval failures and ensure your AI assistant works wit
|
||||
|
||||
Start with conservative filters (only store confirmed facts) and iterate based on your application's needs. Combine custom instructions with confidence thresholds for the most reliable memory ingestion pipeline.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Expire Short-Term Data" icon="timer" href="/cookbooks/essentials/memory-expiration-short-and-long-term">
|
||||
Automatically clean up session context before it clutters retrieval.
|
||||
</Card>
|
||||
<Card title="Choose Your Memory Architecture" icon="sitemap" href="/cookbooks/essentials/choosing-memory-architecture-vector-vs-graph">
|
||||
Learn when to layer graph memory alongside vectors for multi-hop queries.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
<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>
|
||||
|
||||
@@ -280,8 +280,8 @@ This covers data portability, GDPR compliance, system migrations, and manual rev
|
||||
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="Expire Short-Term Data" icon="timer" href="/cookbooks/essentials/memory-expiration-short-and-long-term">
|
||||
Keep exports lean by clearing session context before you archive it.
|
||||
<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>
|
||||
<Card title="Control Memory Ingestion" icon="filter" href="/cookbooks/essentials/controlling-memory-ingestion">
|
||||
Ensure only verified insights make it into your export pipeline.
|
||||
|
||||
@@ -1,277 +0,0 @@
|
||||
---
|
||||
title: Set Memory Expiration
|
||||
description: "Define short-term versus long-term retention so the store stays fresh."
|
||||
---
|
||||
|
||||
|
||||
While building memory systems, we realized their size grows fast. Session notes, temporary context, chat history - everything starts accumulating and bogging down the system. This pollutes search results and increase storage costs. Not every memory needs to persist forever.
|
||||
|
||||
In this cookbook, we'll go through how to use short-term vs long-term memories and see where it's best to use them.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
By default, Mem0 memories persist forever. This works for user preferences and core facts, but temporary data should expire automatically.
|
||||
|
||||
In this tutorial, we will:
|
||||
|
||||
- Understand default (permanent) memory behavior
|
||||
- Add expiration dates for temporary memories
|
||||
- Decide what should be temporary vs permanent
|
||||
|
||||
---
|
||||
|
||||
## Setup
|
||||
|
||||
```python
|
||||
from mem0 import MemoryClient
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
client = MemoryClient(api_key="your-api-key")
|
||||
```
|
||||
|
||||
<Note>
|
||||
Import `datetime` and `timedelta` to calculate expiration dates. Without these imports, you'll need to manually format ISO timestamps—error-prone and harder to read.
|
||||
</Note>
|
||||
|
||||
---
|
||||
|
||||
## Default Behavior: Everything Persists
|
||||
|
||||
By default, all memories persist forever:
|
||||
|
||||
```python
|
||||
# Store user preference
|
||||
client.add("User prefers dark mode", user_id="sarah")
|
||||
|
||||
# Store session context
|
||||
client.add("Currently browsing electronics category", user_id="sarah")
|
||||
|
||||
# 6 months later - both still exist
|
||||
results = client.get_all(filters={"user_id": "sarah"})
|
||||
print(f"Total memories: {len(results['results'])}")
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Total memories: 2
|
||||
|
||||
```
|
||||
|
||||
Both the preference and session context persist. The preference is useful, but the 6-month-old session context is not.
|
||||
|
||||
---
|
||||
|
||||
## The Problem: Memory Bloat
|
||||
|
||||
Without expiration, memories accumulate forever. Session notes from weeks ago mix with current preferences. Storage grows, search results get polluted with irrelevant old context, and retrieval quality degrades.
|
||||
|
||||
<Warning>
|
||||
Memory bloat degrades search quality. When "User prefers dark mode" competes with "Currently browsing electronics" from 6 months ago, semantic search returns stale session data instead of actual preferences. Old memories pollute retrieval.
|
||||
</Warning>
|
||||
|
||||
---
|
||||
|
||||
## Short-Term Memories: Adding Expiration
|
||||
|
||||
Set `expiration_date` to make memories temporary:
|
||||
|
||||
```python
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# Session context - expires in 7 days
|
||||
expires_at = (datetime.now() + timedelta(days=7)).isoformat()
|
||||
|
||||
client.add(
|
||||
"Currently browsing electronics category",
|
||||
user_id="sarah",
|
||||
expiration_date=expires_at
|
||||
)
|
||||
|
||||
# User preference - no expiration, persists forever
|
||||
client.add(
|
||||
"User prefers dark mode",
|
||||
user_id="sarah"
|
||||
)
|
||||
|
||||
```
|
||||
|
||||
<Info icon="check">
|
||||
**Expected behavior:** After 7 days, the session context automatically disappears—no cron jobs, no manual cleanup. The preference persists forever. Mem0 handles expiration transparently.
|
||||
</Info>
|
||||
|
||||
Memories with `expiration_date` are automatically removed after expiring. No cleanup job needed - Mem0 handles it.
|
||||
|
||||
<Tip>
|
||||
Start conservative with short expiration windows (7 days), then extend them based on usage patterns. It's easier to increase retention than to clean up over-retained stale data. Monitor search quality to find the right balance.
|
||||
</Tip>
|
||||
|
||||
---
|
||||
|
||||
## When to Use Each
|
||||
|
||||
### Permanent Memories (no expiration_date):
|
||||
|
||||
**Use for:**
|
||||
|
||||
- User preferences and settings
|
||||
- Account information
|
||||
- Important facts and milestones
|
||||
- Historical data that matters long-term
|
||||
|
||||
```python
|
||||
client.add("User prefers email notifications", user_id="sarah")
|
||||
client.add("User's birthday is March 15th", user_id="sarah")
|
||||
client.add("User completed onboarding on Jan 5th", user_id="sarah")
|
||||
|
||||
```
|
||||
|
||||
### Temporary Memories (with expiration_date):
|
||||
|
||||
**Use for:**
|
||||
|
||||
- Session context (current page, browsing history)
|
||||
- Temporary reminders
|
||||
- Recent chat history
|
||||
- Cached data
|
||||
|
||||
```python
|
||||
expires_7d = (datetime.now() + timedelta(days=7)).isoformat()
|
||||
|
||||
client.add(
|
||||
"Currently viewing product ABC123",
|
||||
user_id="sarah",
|
||||
expiration_date=expires_7d
|
||||
)
|
||||
|
||||
client.add(
|
||||
"Asked about return policy",
|
||||
user_id="sarah",
|
||||
expiration_date=expires_7d
|
||||
)
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Setting Different Expiration Periods
|
||||
|
||||
Different data needs different lifetimes:
|
||||
|
||||
```python
|
||||
# Session context - 7 days
|
||||
expires_7d = (datetime.now() + timedelta(days=7)).isoformat()
|
||||
client.add("Browsing electronics", user_id="sarah", expiration_date=expires_7d)
|
||||
|
||||
# Recent chat - 30 days
|
||||
expires_30d = (datetime.now() + timedelta(days=30)).isoformat()
|
||||
client.add("User asked about warranty", user_id="sarah", expiration_date=expires_30d)
|
||||
|
||||
# Important preference - no expiration
|
||||
client.add("User prefers dark mode", user_id="sarah")
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Using Metadata to Track Memory Types
|
||||
|
||||
Tag memories to make filtering easier:
|
||||
|
||||
```python
|
||||
expires_7d = (datetime.now() + timedelta(days=7)).isoformat()
|
||||
|
||||
# Tag session context
|
||||
client.add(
|
||||
"Browsing electronics",
|
||||
user_id="sarah",
|
||||
expiration_date=expires_7d,
|
||||
metadata={"type": "session"}
|
||||
)
|
||||
|
||||
# Tag preference
|
||||
client.add(
|
||||
"User prefers dark mode",
|
||||
user_id="sarah",
|
||||
metadata={"type": "preference"}
|
||||
)
|
||||
|
||||
# Query only preferences
|
||||
preferences = client.get_all(
|
||||
filters={
|
||||
"AND": [
|
||||
{"user_id": "sarah"},
|
||||
{"metadata": {"type": "preference"}}
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Checking Expiration Status
|
||||
|
||||
See which memories will expire and when:
|
||||
|
||||
```python
|
||||
results = client.get_all(filters={"user_id": "sarah"})
|
||||
|
||||
for memory in results['results']:
|
||||
exp_date = memory.get('expiration_date')
|
||||
|
||||
if exp_date:
|
||||
print(f"Temporary: {memory['memory']}")
|
||||
print(f" Expires: {exp_date}\\n")
|
||||
else:
|
||||
print(f"Permanent: {memory['memory']}\\n")
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Temporary: Browsing electronics
|
||||
Expires: 2025-11-01T10:30:00Z
|
||||
|
||||
Temporary: Viewed MacBook Pro and Dell XPS
|
||||
Expires: 2025-11-01T10:30:00Z
|
||||
|
||||
Permanent: User prefers dark mode
|
||||
|
||||
Permanent: User prefers email notifications
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## What You Built
|
||||
|
||||
A self-cleaning memory system with automatic retention policies:
|
||||
|
||||
- **Automatic expiration** - Memories self-destruct after defined periods, no cron jobs needed
|
||||
- **Tiered retention** - 7-day session context, 30-day chat history, permanent preferences
|
||||
- **Metadata tagging** - Classify memories by type (session, preference, chat) for filtered retrieval
|
||||
- **Expiration tracking** - Check which memories will expire and when using `get_all()`
|
||||
|
||||
This pattern keeps storage costs low and search quality high as your memory store scales.
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
Memory expiration keeps storage clean and search results relevant. Use **`expiration_date`** for temporary data (session context, recent chats), skip it for permanent facts (preferences, account info). Mem0 handles cleanup automatically—no background jobs required.
|
||||
|
||||
Start by identifying what's temporary versus permanent, then set conservative expiration windows and adjust based on retrieval quality.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Control Memory Ingestion" icon="filter" href="/cookbooks/essentials/controlling-memory-ingestion">
|
||||
Pair expirations with ingestion rules so only trusted context persists.
|
||||
</Card>
|
||||
<Card title="Export Memories Safely" icon="download" href="/cookbooks/essentials/exporting-memories">
|
||||
Build compliant archives once your retention windows are dialed in.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -1,70 +0,0 @@
|
||||
---
|
||||
title: Browser Extension Memory
|
||||
description: "Add Mem0's universal memory layer to Chrome chat surfaces."
|
||||
---
|
||||
|
||||
|
||||
Enhance your AI interactions with Mem0, a Chrome extension that introduces a universal memory layer across platforms like ChatGPT, Claude, and Perplexity. Mem0 ensures seamless context sharing, making your AI experiences more personalized and efficient.
|
||||
|
||||
<Note>
|
||||
We now support Grok! The Mem0 Chrome Extension has been updated to work with Grok, bringing the same powerful memory capabilities to your Grok conversations.
|
||||
</Note>
|
||||
|
||||
|
||||
## Features
|
||||
|
||||
- **Universal Memory Layer**: Share context seamlessly across ChatGPT, Claude, Perplexity, and Grok.
|
||||
- **Smart Context Detection**: Automatically captures relevant information from your conversations.
|
||||
- **Intelligent Memory Retrieval**: Surfaces pertinent memories at the right time.
|
||||
- **One-Click Sync**: Easily synchronize with existing ChatGPT memories.
|
||||
- **Memory Dashboard**: Manage all your memories in one centralized location.
|
||||
|
||||
## Installation
|
||||
|
||||
You can install the Mem0 Chrome Extension using one of the following methods:
|
||||
|
||||
### Method 1: Chrome Web Store Installation
|
||||
|
||||
1. **Download the Extension**: Open Google Chrome and navigate to the [Mem0 Chrome Extension page](https://chromewebstore.google.com/detail/mem0/onihkkbipkfeijkadecaafbgagkhglop?hl=en).
|
||||
2. **Add to Chrome**: Click on the "Add to Chrome" button.
|
||||
3. **Confirm Installation**: In the pop-up dialog, click "Add extension" to confirm. The Mem0 icon should now appear in your Chrome toolbar.
|
||||
|
||||
### Method 2: Manual Installation
|
||||
|
||||
1. **Download the Extension**: Clone or download the extension files from the [Mem0 Chrome Extension GitHub repository](https://github.com/mem0ai/mem0-chrome-extension).
|
||||
2. **Access Chrome Extensions**: Open Google Chrome and navigate to `chrome://extensions`.
|
||||
3. **Enable Developer Mode**: Toggle the "Developer mode" switch in the top right corner.
|
||||
4. **Load Unpacked Extension**: Click "Load unpacked" and select the directory containing the extension files.
|
||||
5. **Confirm Installation**: The Mem0 Chrome Extension should now appear in your Chrome toolbar.
|
||||
|
||||
## Usage
|
||||
|
||||
1. **Locate the Mem0 Icon**: After installation, find the Mem0 icon in your Chrome toolbar.
|
||||
2. **Sign In**: Click the icon and sign in with your Google account.
|
||||
3. **Interact with AI Assistants**:
|
||||
- **ChatGPT and Perplexity**: Continue your conversations as usual; Mem0 operates seamlessly in the background.
|
||||
- **Claude**: Click the Mem0 button or use the shortcut `Ctrl + M` to activate memory functions.
|
||||
|
||||
## Configuration
|
||||
|
||||
- **API Key**: Obtain your API key from the Mem0 Dashboard to connect the extension to the Mem0 API.
|
||||
- **User ID**: This is your unique identifier in the Mem0 system. If not provided, it defaults to `chrome-extension-user`.
|
||||
|
||||
## Demo Video
|
||||
|
||||
<iframe width="700" height="400" src="https://www.youtube.com/embed/dqenCMMlfwQ?si=zhGVrkq6IS_0Jwyj" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
|
||||
|
||||
## Privacy and Data Security
|
||||
|
||||
Your messages are sent to the Mem0 API for extracting and retrieving memories. Mem0 is committed to ensuring your data's privacy and security.
|
||||
|
||||
---
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
|
||||
Learn the foundations of memory-powered assistants that work across platforms.
|
||||
</Card>
|
||||
<Card title="Multimodal Support" icon="image" href="/platform/features/multimodal-support">
|
||||
Extend your browser interactions with vision and audio memory.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -83,7 +83,7 @@ class MultiAgentLearningSystem:
|
||||
|
||||
def __init__(self, student_id: str):
|
||||
self.student_id = student_id
|
||||
self.llm = OpenAI(model="gpt-4.1-nano-2025-04-14", temperature=0.2)
|
||||
self.llm = OpenAI(model="gpt-5-mini", temperature=0.2)
|
||||
|
||||
# Memory context for this student
|
||||
self.memory_context = {"user_id": student_id, "app": "learning_assistant"}
|
||||
|
||||
@@ -22,7 +22,7 @@ import os
|
||||
from llama_index.llms.openai import OpenAI
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
|
||||
llm = OpenAI(model="gpt-4.1-nano-2025-04-14")
|
||||
llm = OpenAI(model="gpt-5-mini")
|
||||
```
|
||||
|
||||
Initialize the Mem0 client. You can find your API key <a href="https://app.mem0.ai/dashboard/api-keys" rel="nofollow">here</a>. Read about Mem0 [Open Source](https://docs.mem0.ai/open-source/overview).
|
||||
|
||||
@@ -1,766 +0,0 @@
|
||||
---
|
||||
title: MiroFish Swarm Memory
|
||||
description: "Build a multi-agent swarm simulation with graph-powered memory using Mem0 and MiroFish patterns."
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Build a multi-agent swarm simulation with graph-powered memory using Mem0 OSS and [MiroFish](https://github.com/666ghj/MiroFish) patterns. MiroFish is a graph-centric system — it extracts entities and relationships from documents, builds a knowledge graph, and queries it throughout its pipeline. Mem0's Graph Memory is a natural replacement for its Zep Cloud integration.
|
||||
|
||||
<Note>
|
||||
This cookbook demonstrates the **core memory patterns** using a simplified simulation. MiroFish's actual architecture uses a factory pattern (`memory_factory.py`) with abstract providers, batch buffering with retries in `ZepGraphMemoryUpdater`, and IPC-based agent interviews. This cookbook focuses on the Mem0 API integration points — wrap these calls in your own retry/batch logic for production use.
|
||||
</Note>
|
||||
|
||||
## Overview
|
||||
|
||||
This cookbook implements a **Housing Policy Prediction Simulation** following MiroFish's five-stage workflow:
|
||||
|
||||
1. **Graph Building** — Ingest seed documents, extract entities and relationships
|
||||
2. **Environment Setup** — Query the knowledge graph to enrich agent profiles
|
||||
3. **Simulation** — Track agent interactions with per-agent memory isolation
|
||||
4. **Report Generation** — Semantic search + graph traversal for analysis
|
||||
5. **Deep Interaction** — Query post-simulation memory and relationships (MiroFish also supports live agent interviews via IPC — not covered here)
|
||||
|
||||
Three agents debate a housing policy reform:
|
||||
- **Mayor Chen** — Policy advocate pushing for zoning reform
|
||||
- **Wang (Homeowner)** — Opposition leader organizing resistance
|
||||
- **Professor Li** — Academic providing data-driven analysis
|
||||
|
||||
## Prerequisites
|
||||
|
||||
```bash
|
||||
pip install "mem0ai[graph]"
|
||||
```
|
||||
|
||||
You need a graph backend. Choose one:
|
||||
|
||||
| Backend | Setup | Best for |
|
||||
|---|---|---|
|
||||
| **Neo4j Aura** (free tier) | [Sign up](https://neo4j.com/product/auradb/), get Bolt URI | Production, closest to Zep |
|
||||
| **Neo4j Docker** | `docker run -p 7687:7687 -e NEO4J_AUTH=neo4j/password neo4j:5` | Local development |
|
||||
| **Kuzu** (embedded) | No setup needed — runs in-process | Quick testing, zero dependencies |
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="sk-..."
|
||||
|
||||
# Option A: Neo4j Docker (local development)
|
||||
docker run -p 7687:7687 -e NEO4J_AUTH=neo4j/password neo4j:5
|
||||
export NEO4J_URL="neo4j://localhost:7687"
|
||||
export NEO4J_USERNAME="neo4j"
|
||||
export NEO4J_PASSWORD="password"
|
||||
|
||||
# Option B: Neo4j Aura (production — free tier available)
|
||||
export NEO4J_URL="neo4j+s://<your-instance>.databases.neo4j.io"
|
||||
export NEO4J_USERNAME="neo4j"
|
||||
export NEO4J_PASSWORD="your-aura-password"
|
||||
|
||||
# Option C: Kuzu (zero setup — auto-detected when NEO4J_URL is not set)
|
||||
# No exports needed
|
||||
```
|
||||
|
||||
## Complete Implementation
|
||||
|
||||
```python
|
||||
"""
|
||||
MiroFish Swarm Prediction Simulation with Mem0 Graph Memory
|
||||
|
||||
MiroFish uses Zep Cloud as its knowledge graph backend. This implementation
|
||||
replaces Zep with Mem0 OSS Graph Memory, which provides:
|
||||
- Automatic entity extraction from text
|
||||
- Relationship mining (source → relationship → destination triples)
|
||||
- Combined vector + graph search returning memories AND relations
|
||||
- Per-agent isolation via run_id
|
||||
- Self-hosted with no node caps
|
||||
|
||||
Follows MiroFish's 5-stage pipeline:
|
||||
1. Graph Building - Ingest seed documents, extract entities
|
||||
2. Environment Setup - Query graph to enrich agent profiles
|
||||
3. Simulation - Track agent actions with per-agent isolation
|
||||
4. Report Generation - Semantic + graph search for analysis
|
||||
5. Deep Interaction - Query post-simulation knowledge graph
|
||||
|
||||
Run:
|
||||
export OPENAI_API_KEY="sk-..."
|
||||
export NEO4J_URL="neo4j://localhost:7687"
|
||||
export NEO4J_USERNAME="neo4j"
|
||||
export NEO4J_PASSWORD="password"
|
||||
python mirofish_swarm_memory.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from mem0 import Memory
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# MiroFish Agent Action Types (matches OASIS simulation output)
|
||||
# ======================================================================
|
||||
|
||||
# Twitter actions
|
||||
TWITTER_ACTIONS = [
|
||||
"CREATE_POST", "LIKE_POST", "REPOST", "FOLLOW",
|
||||
"DO_NOTHING", "QUOTE_POST",
|
||||
]
|
||||
|
||||
# Reddit actions (superset — includes moderation + discovery)
|
||||
REDDIT_ACTIONS = [
|
||||
"LIKE_POST", "DISLIKE_POST", "CREATE_POST", "CREATE_COMMENT",
|
||||
"LIKE_COMMENT", "DISLIKE_COMMENT", "SEARCH_POSTS", "SEARCH_USER",
|
||||
"TREND", "REFRESH", "DO_NOTHING", "FOLLOW", "MUTE",
|
||||
]
|
||||
|
||||
# Combined (DO_NOTHING is skipped during memory storage)
|
||||
MIROFISH_ACTIONS = list(set(TWITTER_ACTIONS + REDDIT_ACTIONS) - {"DO_NOTHING"})
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# Graph Memory Configuration
|
||||
# ======================================================================
|
||||
|
||||
def build_config():
|
||||
"""Build Mem0 config with Graph Memory.
|
||||
|
||||
Uses Neo4j if credentials are set, otherwise falls back to Kuzu (embedded).
|
||||
"""
|
||||
neo4j_url = os.environ.get("NEO4J_URL")
|
||||
|
||||
# Shared config for LLM, embedder, and vector store
|
||||
base = {
|
||||
"llm": {
|
||||
"provider": "openai",
|
||||
"config": {"model": "gpt-4o-mini", "temperature": 0.1}
|
||||
},
|
||||
"embedder": {
|
||||
"provider": "openai",
|
||||
"config": {"model": "text-embedding-3-small", "embedding_dims": 1536}
|
||||
},
|
||||
"vector_store": {
|
||||
"provider": "qdrant",
|
||||
"config": {
|
||||
"collection_name": "mirofish",
|
||||
"embedding_model_dims": 1536,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
custom_prompt = (
|
||||
"Extract all people, organizations, policies, locations, "
|
||||
"and their relationships. Capture support/opposition stances, "
|
||||
"affiliations, and quantitative claims."
|
||||
)
|
||||
|
||||
if neo4j_url:
|
||||
base["graph_store"] = {
|
||||
"provider": "neo4j",
|
||||
"config": {
|
||||
"url": neo4j_url,
|
||||
"username": os.environ.get("NEO4J_USERNAME", "neo4j"),
|
||||
"password": os.environ.get("NEO4J_PASSWORD", "password"),
|
||||
},
|
||||
"custom_prompt": custom_prompt,
|
||||
}
|
||||
else:
|
||||
# Fallback: Kuzu embedded (no external services needed)
|
||||
print(" NEO4J_URL not set — using Kuzu (embedded) graph store")
|
||||
base["graph_store"] = {
|
||||
"provider": "kuzu",
|
||||
"config": {"db": "/tmp/mirofish_graph.kuzu"},
|
||||
"custom_prompt": custom_prompt,
|
||||
}
|
||||
|
||||
return base
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# Simulation Engine
|
||||
# ======================================================================
|
||||
|
||||
class MiroFishSimulation:
|
||||
"""
|
||||
Multi-agent simulation with graph-powered memory.
|
||||
|
||||
Uses Mem0 Graph Memory to replace MiroFish's Zep Cloud integration:
|
||||
- Entities and relationships are extracted automatically from text
|
||||
- search() returns both semantic memories AND graph relations
|
||||
- Per-agent isolation via run_id
|
||||
- Project isolation via user_id
|
||||
"""
|
||||
|
||||
def __init__(self, project_id: str, config: dict):
|
||||
self.project_id = project_id
|
||||
self.memory = Memory.from_config(config)
|
||||
self.stats = {
|
||||
"documents_ingested": 0,
|
||||
"activities_recorded": 0,
|
||||
"rounds_completed": 0,
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Stage 1: Graph Building — Seed Document Ingestion
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def ingest_documents(self, documents: list[str]):
|
||||
"""Ingest seed documents and extract entities + relationships.
|
||||
|
||||
MiroFish equivalent: GraphBuilderService.build_graph()
|
||||
Zep equivalent: graph.add_batch() with episode polling
|
||||
|
||||
With Mem0 Graph Memory, each document is processed by the LLM
|
||||
to extract entities (people, orgs, policies) and relationships
|
||||
(supports, opposes, filed). These become nodes and edges in the
|
||||
graph store, alongside vector embeddings for semantic search.
|
||||
"""
|
||||
print(" Ingesting documents and building knowledge graph...")
|
||||
for i, doc in enumerate(documents):
|
||||
result = self.memory.add(
|
||||
[{"role": "user", "content": doc}],
|
||||
user_id=self.project_id,
|
||||
metadata={"stage": "graph_building", "source": "seed_document", "chunk_index": i}
|
||||
)
|
||||
# Graph Memory returns extracted relations
|
||||
relations = result.get("relations", {})
|
||||
added = relations.get("added_entities", [])
|
||||
if added:
|
||||
print(f" Doc {i}: extracted {len(added)} entities/relations")
|
||||
|
||||
self.stats["documents_ingested"] = len(documents)
|
||||
print(f" Ingested {len(documents)} documents")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Stage 2: Environment Setup — Agent Profile Enrichment
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def enrich_agent_profile(self, agent_name: str, persona_query: str) -> dict:
|
||||
"""Search memory + graph for context relevant to an agent's persona.
|
||||
|
||||
MiroFish equivalent: OasisProfileGenerator using graph.search()
|
||||
|
||||
Returns both semantic memories and graph relations that can be
|
||||
injected into the agent's system prompt.
|
||||
"""
|
||||
results = self.memory.search(
|
||||
persona_query,
|
||||
user_id=self.project_id,
|
||||
limit=10
|
||||
)
|
||||
facts = [r["memory"] for r in results.get("results", [])]
|
||||
relations = results.get("relations", [])
|
||||
|
||||
print(f" {agent_name}: {len(facts)} facts, {len(relations)} relations")
|
||||
return {"facts": facts, "relations": relations}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Stage 3: Simulation — Agent Activity Tracking
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def record_action(self, agent_id: str, agent_name: str,
|
||||
action_type: str, content: str,
|
||||
platform: str, round_num: int):
|
||||
"""Record a single agent action as a memory with graph extraction.
|
||||
|
||||
MiroFish equivalent: ZepGraphMemoryUpdater.add_activity()
|
||||
Zep equivalent: graph.add(type="text", data=episode_text)
|
||||
|
||||
Agent memories use run_id to group by agent (no assistant
|
||||
memories involved). Graph Memory extracts entities/relationships
|
||||
from the action content automatically.
|
||||
"""
|
||||
formatted = f"{agent_name} [{action_type}]: {content}"
|
||||
|
||||
self.memory.add(
|
||||
[{"role": "user", "content": formatted}],
|
||||
run_id=agent_id,
|
||||
metadata={
|
||||
"action_type": action_type,
|
||||
"platform": platform,
|
||||
"round": round_num,
|
||||
"agent_name": agent_name,
|
||||
}
|
||||
)
|
||||
self.stats["activities_recorded"] += 1
|
||||
|
||||
def run_round(self, round_num: int, activities: list[tuple]):
|
||||
"""Execute one simulation round."""
|
||||
print(f" Round {round_num}: {len(activities)} actions")
|
||||
for agent_id, agent_name, action_type, content, platform in activities:
|
||||
self.record_action(agent_id, agent_name, action_type, content, platform, round_num)
|
||||
self.stats["rounds_completed"] = max(self.stats["rounds_completed"], round_num)
|
||||
|
||||
def recall_agent_memory(self, agent_id: str, query: str) -> dict:
|
||||
"""Agent recalls its own memories mid-simulation.
|
||||
|
||||
Searches by run_id to match the scope used during add().
|
||||
"""
|
||||
results = self.memory.search(
|
||||
query,
|
||||
run_id=agent_id,
|
||||
limit=5
|
||||
)
|
||||
return {
|
||||
"memories": [r["memory"] for r in results.get("results", [])],
|
||||
"relations": results.get("relations", []),
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Stage 4: Report Generation — Semantic + Graph Retrieval
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def quick_search(self, query: str, limit: int = 10) -> dict:
|
||||
"""Semantic search + graph relations across all agents.
|
||||
|
||||
MiroFish equivalent: ZepToolsService.quick_search()
|
||||
Returns both vector-matched memories and related graph triples.
|
||||
"""
|
||||
results = self.memory.search(
|
||||
query,
|
||||
user_id=self.project_id,
|
||||
limit=limit
|
||||
)
|
||||
return {
|
||||
"memories": [r["memory"] for r in results.get("results", [])],
|
||||
"relations": results.get("relations", []),
|
||||
}
|
||||
|
||||
def panorama_search(self) -> dict:
|
||||
"""Retrieve all memories + all graph relations.
|
||||
|
||||
MiroFish equivalent: ZepToolsService.panorama_search()
|
||||
Returns the complete knowledge state for report generation.
|
||||
"""
|
||||
results = self.memory.get_all(user_id=self.project_id)
|
||||
return {
|
||||
"memories": [r["memory"] for r in results.get("results", [])],
|
||||
"relations": results.get("relations", []),
|
||||
}
|
||||
|
||||
def agent_search(self, agent_id: str, query: str, limit: int = 10) -> dict:
|
||||
"""Search within a single agent's memory space."""
|
||||
results = self.memory.search(
|
||||
query,
|
||||
run_id=agent_id,
|
||||
limit=limit
|
||||
)
|
||||
return {
|
||||
"memories": [r["memory"] for r in results.get("results", [])],
|
||||
"relations": results.get("relations", []),
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Cleanup
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def cleanup(self):
|
||||
"""Delete all memories and graph data for this simulation."""
|
||||
self.memory.delete_all(user_id=self.project_id)
|
||||
print(f" Cleaned up all memories for {self.project_id}")
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# Run the full 5-stage pipeline
|
||||
# ======================================================================
|
||||
|
||||
def main():
|
||||
project_id = f"mirofish_housing_{int(time.time())}"
|
||||
config = build_config()
|
||||
sim = MiroFishSimulation(project_id=project_id, config=config)
|
||||
|
||||
# ==================================================================
|
||||
# STAGE 1: Graph Building — Ingest seed documents
|
||||
# ==================================================================
|
||||
print("=" * 60)
|
||||
print("STAGE 1: Graph Building")
|
||||
print("=" * 60)
|
||||
|
||||
sim.ingest_documents([
|
||||
"The city council proposed a new zoning reform allowing higher "
|
||||
"density housing in suburban areas. Mayor Chen expressed strong "
|
||||
"support, citing a 40% housing shortage affecting young professionals. "
|
||||
"The reform would allow buildings up to 8 stories in previously "
|
||||
"restricted 3-story zones.",
|
||||
|
||||
"Local homeowners association president Wang opposes the reform, "
|
||||
"arguing it will decrease property values by 15-20%. The association "
|
||||
"represents 5,000 homeowners in the affected districts. Wang has "
|
||||
"organized three community meetings and collected 2,000 signatures.",
|
||||
|
||||
"Professor Li from Beijing University published research showing "
|
||||
"similar reforms in Shenzhen led to 15% price drops in existing "
|
||||
"homes but created 30% more affordable housing units within 3 years. "
|
||||
"The study covered 12 districts and 50,000 housing units.",
|
||||
])
|
||||
|
||||
# ==================================================================
|
||||
# STAGE 2: Environment Setup — Enrich agent profiles
|
||||
# ==================================================================
|
||||
print("\n" + "=" * 60)
|
||||
print("STAGE 2: Environment Setup")
|
||||
print("=" * 60)
|
||||
|
||||
mayor_context = sim.enrich_agent_profile(
|
||||
"Mayor Chen",
|
||||
"Mayor Chen housing reform zoning policy"
|
||||
)
|
||||
wang_context = sim.enrich_agent_profile(
|
||||
"Wang",
|
||||
"Wang homeowner opposition property values petition"
|
||||
)
|
||||
li_context = sim.enrich_agent_profile(
|
||||
"Professor Li",
|
||||
"Professor Li research housing data Shenzhen"
|
||||
)
|
||||
|
||||
print("\n Example profile context for Mayor Chen:")
|
||||
for fact in mayor_context["facts"][:3]:
|
||||
print(f" Fact: {fact}")
|
||||
for rel in mayor_context["relations"][:3]:
|
||||
src = rel.get("source", "?")
|
||||
edge = rel.get("relationship", "?")
|
||||
dst = rel.get("destination", rel.get("target", "?"))
|
||||
print(f" Relation: {src} --[{edge}]--> {dst}")
|
||||
|
||||
# ==================================================================
|
||||
# STAGE 3: Simulation — Run agent interactions
|
||||
# ==================================================================
|
||||
print("\n" + "=" * 60)
|
||||
print("STAGE 3: Simulation")
|
||||
print("=" * 60)
|
||||
|
||||
# Round 1: Opening statements
|
||||
sim.run_round(1, [
|
||||
("mayor_chen", "Mayor Chen", "CREATE_POST",
|
||||
"This reform will create 10,000 new housing units by 2028. "
|
||||
"Young families deserve affordable homes. #HousingForAll",
|
||||
"twitter"),
|
||||
|
||||
("wang_homeowner", "Wang", "CREATE_POST",
|
||||
"Our property values will plummet! The council ignores the "
|
||||
"voices of 5,000 homeowners. #StopTheReform",
|
||||
"twitter"),
|
||||
|
||||
("prof_li", "Professor Li", "CREATE_POST",
|
||||
"New analysis: Shenzhen zoning data shows net positive outcomes "
|
||||
"after 3 years. Short-term pain, long-term gain for housing equity.",
|
||||
"twitter"),
|
||||
])
|
||||
|
||||
# Round 2: Debate and interaction
|
||||
sim.run_round(2, [
|
||||
("wang_homeowner", "Wang", "CREATE_COMMENT",
|
||||
"Replied to Professor Li: 'Shenzhen is a tier-1 city with "
|
||||
"completely different dynamics. Your comparison is misleading.'",
|
||||
"twitter"),
|
||||
|
||||
("mayor_chen", "Mayor Chen", "LIKE_POST",
|
||||
"Liked Professor Li's post about Shenzhen housing data.",
|
||||
"twitter"),
|
||||
|
||||
("prof_li", "Professor Li", "CREATE_COMMENT",
|
||||
"Replied to Wang: 'The methodology controls for city tier "
|
||||
"and population density. I invite you to review the full dataset.'",
|
||||
"twitter"),
|
||||
|
||||
("mayor_chen", "Mayor Chen", "CREATE_POST",
|
||||
"Data from @ProfLi confirms what we've been saying: zoning "
|
||||
"reform works. Let's move forward with evidence, not fear.",
|
||||
"twitter"),
|
||||
])
|
||||
|
||||
# Round 3: Escalation and platform expansion
|
||||
sim.run_round(3, [
|
||||
("wang_homeowner", "Wang", "CREATE_POST",
|
||||
"Filing formal petition with 3,000 signatures against the "
|
||||
"zoning reform. Council meeting next Tuesday. All homeowners "
|
||||
"must attend!",
|
||||
"reddit"),
|
||||
|
||||
("mayor_chen", "Mayor Chen", "CREATE_POST",
|
||||
"Announcing public town hall on zoning reform this Saturday. "
|
||||
"All voices welcome. Data-driven decisions benefit everyone.",
|
||||
"twitter"),
|
||||
|
||||
("prof_li", "Professor Li", "CREATE_POST",
|
||||
"Published full dataset and methodology on my university page. "
|
||||
"Transparency is essential for informed public debate.",
|
||||
"twitter"),
|
||||
|
||||
("wang_homeowner", "Wang", "FOLLOW",
|
||||
"Followed @MayorChen to monitor policy updates.",
|
||||
"twitter"),
|
||||
])
|
||||
|
||||
# Mid-simulation: agent recalls own memory + graph
|
||||
print("\n Mid-simulation recall for Mayor Chen:")
|
||||
mayor_recall = sim.recall_agent_memory(
|
||||
"mayor_chen",
|
||||
"What positions have I taken on housing reform?"
|
||||
)
|
||||
for mem in mayor_recall["memories"]:
|
||||
print(f" Memory: {mem}")
|
||||
for rel in mayor_recall["relations"][:3]:
|
||||
src = rel.get("source", "?")
|
||||
edge = rel.get("relationship", "?")
|
||||
dst = rel.get("destination", rel.get("target", "?"))
|
||||
print(f" Relation: {src} --[{edge}]--> {dst}")
|
||||
|
||||
# ==================================================================
|
||||
# STAGE 4: Report Generation — Retrieve memories + graph for analysis
|
||||
# ==================================================================
|
||||
print("\n" + "=" * 60)
|
||||
print("STAGE 4: Report Generation")
|
||||
print("=" * 60)
|
||||
|
||||
# Quick search: targeted query
|
||||
print("\n Quick Search: 'opposition to housing reform'")
|
||||
opposition = sim.quick_search("opposition to housing reform", limit=5)
|
||||
for mem in opposition["memories"]:
|
||||
print(f" Memory: {mem}")
|
||||
for rel in opposition["relations"][:3]:
|
||||
src = rel.get("source", "?")
|
||||
edge = rel.get("relationship", "?")
|
||||
dst = rel.get("destination", rel.get("target", "?"))
|
||||
print(f" Relation: {src} --[{edge}]--> {dst}")
|
||||
|
||||
# Agent-specific search
|
||||
print("\n Agent Search: Wang's activities")
|
||||
wang_activities = sim.agent_search("wang_homeowner", "all actions and statements")
|
||||
for mem in wang_activities["memories"]:
|
||||
print(f" Memory: {mem}")
|
||||
|
||||
# Panorama: full overview
|
||||
print("\n Panorama Search: all memories + relations")
|
||||
panorama = sim.panorama_search()
|
||||
print(f" Total memories: {len(panorama['memories'])}")
|
||||
print(f" Total relations: {len(panorama['relations'])}")
|
||||
for mem in panorama["memories"][:5]:
|
||||
print(f" Memory: {mem}")
|
||||
if len(panorama["memories"]) > 5:
|
||||
print(f" ... and {len(panorama['memories']) - 5} more")
|
||||
for rel in panorama["relations"][:5]:
|
||||
src = rel.get("source", "?")
|
||||
edge = rel.get("relationship", "?")
|
||||
dst = rel.get("destination", rel.get("target", "?"))
|
||||
print(f" Relation: {src} --[{edge}]--> {dst}")
|
||||
|
||||
# ==================================================================
|
||||
# STAGE 5: Deep Interaction — Post-simulation queries
|
||||
# ==================================================================
|
||||
print("\n" + "=" * 60)
|
||||
print("STAGE 5: Deep Interaction")
|
||||
print("=" * 60)
|
||||
|
||||
queries = [
|
||||
"How did the debate evolve across the three rounds?",
|
||||
"What evidence was cited by each side?",
|
||||
"Who supports and who opposes the reform?",
|
||||
]
|
||||
|
||||
for query in queries:
|
||||
print(f"\n Query: '{query}'")
|
||||
results = sim.quick_search(query, limit=3)
|
||||
for mem in results["memories"][:2]:
|
||||
print(f" Memory: {mem}")
|
||||
for rel in results["relations"][:2]:
|
||||
src = rel.get("source", rel.get("source_node", "?"))
|
||||
edge = rel.get("relationship", rel.get("relation", "?"))
|
||||
dst = rel.get("destination", rel.get("destination_node", "?"))
|
||||
print(f" Relation: {src} --[{edge}]--> {dst}")
|
||||
|
||||
# ==================================================================
|
||||
# Summary
|
||||
# ==================================================================
|
||||
print("\n" + "=" * 60)
|
||||
print("SIMULATION COMPLETE")
|
||||
print("=" * 60)
|
||||
print(f" Project ID: {project_id}")
|
||||
print(f" Documents ingested: {sim.stats['documents_ingested']}")
|
||||
print(f" Activities tracked: {sim.stats['activities_recorded']}")
|
||||
print(f" Rounds completed: {sim.stats['rounds_completed']}")
|
||||
print(f" Total memories: {len(panorama['memories'])}")
|
||||
print(f" Total relations: {len(panorama['relations'])}")
|
||||
|
||||
# Cleanup (uncomment to delete all memories + graph data)
|
||||
# sim.cleanup()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("MiroFish Swarm Prediction Simulation powered by Mem0 Graph Memory\n")
|
||||
main()
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
### Graph Memory: The Right Fit for MiroFish
|
||||
|
||||
MiroFish's entire pipeline revolves around a **knowledge graph** — it extracts entities from documents, builds relationships, and queries the graph throughout simulation and reporting. Mem0's Graph Memory provides the same capabilities:
|
||||
|
||||
| MiroFish needs | Zep Cloud | Mem0 Graph Memory |
|
||||
|---|---|---|
|
||||
| **Entity extraction** | Built-in via Zep API | Automatic via LLM extraction |
|
||||
| **Relationship mining** | Graph edges | `(source) --[relationship]--> (destination)` triples |
|
||||
| **Semantic + keyword search** | Semantic + BM25 | Vector similarity + graph relation retrieval |
|
||||
| **Graph traversal** | Node/edge queries | `relations` array in search results |
|
||||
| **Per-agent isolation** | Single shared graph in MiroFish | Native `run_id` scoping |
|
||||
| **Self-hosting** | No (cloud only) | Yes — Neo4j, Memgraph, Kuzu, Neptune |
|
||||
| **Node/memory limits** | Capped on free tier | Unlimited (self-hosted) |
|
||||
|
||||
### How search() Returns Both Memories and Relations
|
||||
|
||||
When Graph Memory is enabled, every `search()` call returns two arrays:
|
||||
|
||||
```python
|
||||
results = memory.search("housing reform", user_id="my_sim")
|
||||
|
||||
# Vector-matched memories (ordered by similarity)
|
||||
results["results"] # [{"memory": "...", "score": 0.85, ...}, ...]
|
||||
|
||||
# Graph relations connected to query entities
|
||||
results["relations"] # [{"source": "mayor_chen", "relationship": "supports", "destination": "zoning_reform"}, ...]
|
||||
```
|
||||
|
||||
This is what makes Mem0 Graph Memory a natural replacement for Zep — you get semantic search AND structured graph data in a single call.
|
||||
|
||||
### Per-Agent Memory Isolation
|
||||
|
||||
`user_id` scopes the simulation project. `run_id` tags individual agent actions at storage time (we use `run_id` instead of `agent_id` since no assistant memories are involved). Searches use `user_id` for project-wide retrieval:
|
||||
|
||||
```python
|
||||
# Store project-level memories (seed documents)
|
||||
memory.add(
|
||||
[{"role": "user", "content": "Mayor Chen supports the zoning reform."}],
|
||||
user_id="my_sim"
|
||||
)
|
||||
|
||||
# Store agent-specific memories (simulation actions)
|
||||
memory.add(
|
||||
[{"role": "user", "content": "Mayor Chen [CREATE_POST]: Reform works!"}],
|
||||
run_id="mayor_chen"
|
||||
)
|
||||
|
||||
# Search project-level memories (seed docs)
|
||||
memory.search("housing reform", user_id="my_sim")
|
||||
|
||||
# Search agent-specific memories (actions stored with run_id)
|
||||
memory.search("housing reform", run_id="mayor_chen")
|
||||
|
||||
# Get all project-level memories + graph relations
|
||||
memory.get_all(user_id="my_sim")
|
||||
```
|
||||
|
||||
<Note>
|
||||
Use `user_id` for project-level data (seed documents) and `run_id` for agent actions — both for `add()` and `search()`. Always match the scope: if you `add()` with `run_id`, `search()` with `run_id`. Use the message list format `[{"role": "user", "content": "..."}]` for all `add()` calls — it works on both OSS and Cloud.
|
||||
</Note>
|
||||
|
||||
### Stage Mapping
|
||||
|
||||
| MiroFish Stage | What Happens | Mem0 Graph Memory Call |
|
||||
|---|---|---|
|
||||
| **1. Graph Building** | Ingest docs, extract entities | `memory.add(doc, user_id=project)` — entities/relations extracted automatically |
|
||||
| **2. Environment Setup** | Enrich agent personas from graph | `memory.search(query, user_id=project)` — returns facts + relations |
|
||||
| **3. Simulation** | Track per-agent actions | `memory.add(messages, run_id=agent)` |
|
||||
| **3. Simulation** | Mid-round recall | `memory.search(query, run_id=agent)` |
|
||||
| **4. Report Generation** | Targeted analysis | `memory.search(query, user_id=project)` — memories + graph |
|
||||
| **4. Report Generation** | Full overview | `memory.get_all(user_id=project)` — all memories + all relations |
|
||||
| **5. Deep Interaction** | Follow-up queries | `memory.search(query, user_id=project)` |
|
||||
|
||||
### Zep-to-Mem0 Migration Reference
|
||||
|
||||
For developers replacing MiroFish's Zep integration. Note that Mem0 Graph Memory covers the core graph operations but some Zep features have no direct equivalent — see caveats below.
|
||||
|
||||
| MiroFish Service | Zep Call | Mem0 Graph Memory Equivalent | Caveat |
|
||||
|---|---|---|---|
|
||||
| GraphBuilderService | `client.graph.create()` | Implicit on first `memory.add()` | |
|
||||
| GraphBuilderService | `client.graph.set_ontology()` | `custom_prompt` in graph_store config | Freeform text, not a typed schema like Zep's `EntityModel`/`EdgeModel` |
|
||||
| GraphBuilderService | `client.graph.add_batch(episodes)` | `memory.add()` per chunk | No batch API — call per chunk |
|
||||
| GraphBuilderService | `client.graph.episode.get(uuid)` | Not needed (add is synchronous in OSS) | |
|
||||
| GraphBuilderService | `client.graph.delete(id)` | `memory.delete_all(user_id=...)` | |
|
||||
| ZepEntityReader | `client.graph.node.get_by_graph_id()` | `memory.get_all(user_id=...)` → `relations` | |
|
||||
| ZepEntityReader | `client.graph.node.get(uuid)` | `memory.search(entity_name, user_id=...)` | Semantic search, not exact ID lookup |
|
||||
| ZepEntityReader | `client.graph.node.get_entity_edges()` | `memory.search(entity_name, user_id=...)` → `relations` | Returns all matching relations, not edges for a specific node |
|
||||
| ZepGraphMemoryUpdater | `client.graph.add(type="text")` | `memory.add(messages, run_id=...)` | No batch buffering or retry — implement in your wrapper |
|
||||
| ZepToolsService | `search_graph(query, scope)` | `memory.search(query, user_id=...)` → memories + relations | |
|
||||
| ZepToolsService | `get_entities()` | `memory.get_all(user_id=...)` → `relations` | |
|
||||
| ZepToolsService | Panorama (all nodes + edges) | `memory.get_all(user_id=...)` | No temporal fact separation (active vs historical) |
|
||||
| ZepToolsService | InsightForge (multi-query decomposition) | Not available | Implement LLM-driven sub-query decomposition in your own ReportAgent |
|
||||
| OasisProfileGenerator | `client.graph.search()` | `memory.search(query, user_id=...)` | |
|
||||
|
||||
<Note>
|
||||
**What Mem0 Graph Memory does not cover**: Zep's typed ontology schemas (`EntityModel`, `EdgeModel`), temporal fact lifecycle (`valid_at`/`invalid_at`/`expired_at`), single-node-by-ID lookup, and InsightForge's multi-query decomposition. For InsightForge-like functionality, implement sub-query logic in your own ReportAgent using `memory.search()` as the retrieval primitive.
|
||||
</Note>
|
||||
|
||||
### Custom Extraction Prompts
|
||||
|
||||
Guide what entities and relationships Mem0 extracts — analogous to (but less structured than) Zep's `set_ontology()`:
|
||||
|
||||
```python
|
||||
config = {
|
||||
"graph_store": {
|
||||
"provider": "neo4j",
|
||||
"config": {"url": "...", "username": "...", "password": "..."},
|
||||
"custom_prompt": (
|
||||
"Extract all people, organizations, policies, locations, "
|
||||
"and their relationships. Capture support/opposition stances, "
|
||||
"affiliations, and quantitative claims."
|
||||
),
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Action Types
|
||||
|
||||
MiroFish's OASIS engine produces these agent action types. Format them as natural language when storing. Skip `DO_NOTHING` actions (no memory value). `TREND` and `REFRESH` are Reddit-only discovery actions — store if you want to track browsing behavior.
|
||||
|
||||
| Action Type | Platform | Example Memory Content |
|
||||
|---|---|---|
|
||||
| `CREATE_POST` | Both | `"Mayor Chen [CREATE_POST]: This reform will create 10,000 units"` |
|
||||
| `CREATE_COMMENT` | Reddit | `"Wang [CREATE_COMMENT]: Replied to Prof Li: 'Your data is misleading'"` |
|
||||
| `LIKE_POST` | Both | `"Mayor Chen [LIKE_POST]: Liked Prof Li's post about Shenzhen data"` |
|
||||
| `REPOST` | Twitter | `"Prof Li [REPOST]: Reposted Mayor Chen's town hall announcement"` |
|
||||
| `FOLLOW` | Both | `"Wang [FOLLOW]: Followed @MayorChen"` |
|
||||
| `QUOTE_POST` | Twitter | `"Mayor Chen [QUOTE_POST]: 'Data confirms reform works' quoting Prof Li"` |
|
||||
| `DISLIKE_POST` | Reddit | `"Wang [DISLIKE_POST]: Downvoted Mayor Chen's reform post"` |
|
||||
| `TREND` | Reddit | `"Prof Li [TREND]: Browsed trending topics"` |
|
||||
| `DO_NOTHING` | Both | Skip — no memory value |
|
||||
|
||||
## Running the Example
|
||||
|
||||
```bash
|
||||
# Option A: Neo4j (production)
|
||||
export OPENAI_API_KEY="sk-..."
|
||||
export NEO4J_URL="neo4j://localhost:7687"
|
||||
export NEO4J_USERNAME="neo4j"
|
||||
export NEO4J_PASSWORD="password"
|
||||
python mirofish_swarm_memory.py
|
||||
|
||||
# Option B: Kuzu (zero dependencies, just need OpenAI key)
|
||||
export OPENAI_API_KEY="sk-..."
|
||||
python mirofish_swarm_memory.py # auto-detects missing NEO4J_URL, uses Kuzu
|
||||
```
|
||||
|
||||
<Note>
|
||||
Exact output varies as Mem0 automatically extracts and deduplicates entities. The specific relations and memory counts depend on LLM extraction quality.
|
||||
</Note>
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Unique `user_id` per simulation** — Use timestamps or UUIDs (e.g., `mirofish_housing_1742198400`) to prevent memory collisions between runs
|
||||
2. **Always set `run_id` for agent actions** — Per-agent isolation prevents memory cross-contamination between agents
|
||||
3. **Use `custom_prompt`** — Guide entity extraction to capture domain-specific relationships (people, policies, stances)
|
||||
4. **Format actions as natural language** — `"Mayor Chen [CREATE_POST]: content"` extracts better entities than raw JSON
|
||||
5. **Query relations for reports** — The `relations` array in search results gives structured `(source, relationship, destination)` triples for building analytical reports
|
||||
6. **Cleanup old simulations** — Call `delete_all(user_id=...)` when a simulation run is no longer needed
|
||||
|
||||
## Resources
|
||||
|
||||
- [MiroFish GitHub](https://github.com/666ghj/MiroFish) — Source code and setup guide
|
||||
- [MiroFish Documentation](https://deepwiki.com/666ghj/MiroFish) — Full framework docs
|
||||
- [Mem0 Graph Memory](/open-source/features/graph-memory) — Graph Memory documentation
|
||||
- [Mem0 Documentation](https://docs.mem0.ai/introduction) — Full API reference
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Graph Memory" icon="network-wired" href="/open-source/features/graph-memory">
|
||||
Full Graph Memory documentation with provider setup.
|
||||
</Card>
|
||||
<Card title="MiroFish GitHub" icon="fish" href="https://github.com/666ghj/MiroFish">
|
||||
MiroFish source code and setup guide.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -112,7 +112,7 @@ async def search_memory(
|
||||
query: The search query.
|
||||
"""
|
||||
user_id = context.context.user_id or "default_user"
|
||||
memories = await client.search(query, user_id=user_id)
|
||||
memories = await client.search(query, filters={"user_id": user_id})
|
||||
results = '\n'.join([result["memory"] for result in memories["results"]])
|
||||
return str(results)
|
||||
```
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
---
|
||||
title: Bedrock with Persistent Memory
|
||||
description: "Pair Mem0 with AWS Bedrock, OpenSearch, and Neptune for a managed stack."
|
||||
description: "Pair Mem0 with AWS Bedrock and OpenSearch for a managed stack."
|
||||
---
|
||||
|
||||
|
||||
This example demonstrates how to configure and use the `mem0ai` SDK with **AWS Bedrock**, **OpenSearch Service (AOSS)**, and **AWS Neptune Analytics** for persistent memory capabilities in Python.
|
||||
This example demonstrates how to configure and use the `mem0ai` SDK with **AWS Bedrock** and **OpenSearch Service (AOSS)** for persistent memory capabilities in Python.
|
||||
|
||||
## Installation
|
||||
|
||||
Install the required dependencies to include the Amazon data stack, including **boto3**, **opensearch-py**, and **langchain-aws**:
|
||||
|
||||
```bash
|
||||
pip install "mem0ai[graph,extras]"
|
||||
pip install "mem0ai[extras]"
|
||||
```
|
||||
|
||||
## Environment Setup
|
||||
@@ -38,12 +38,11 @@ This sets up Mem0 with:
|
||||
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
|
||||
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
|
||||
- [OpenSearch as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/opensearch)
|
||||
- [Graph Memory guide](https://docs.mem0.ai/open-source/features/graph-memory)
|
||||
|
||||
```python
|
||||
import boto3
|
||||
from opensearchpy import RequestsHttpConnection, AWSV4SignerAuth
|
||||
from mem0.memory.main import Memory
|
||||
from mem0 import Memory
|
||||
|
||||
region = 'us-west-2'
|
||||
service = 'aoss'
|
||||
@@ -79,12 +78,6 @@ config = {
|
||||
"embedding_model_dims": 1024,
|
||||
}
|
||||
},
|
||||
"graph_store": {
|
||||
"provider": "neptune",
|
||||
"config": {
|
||||
"endpoint": f"neptune-graph://my-graph-identifier",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
# Initialize the memory system
|
||||
@@ -93,8 +86,6 @@ m = Memory.from_config(config)
|
||||
|
||||
## Usage
|
||||
|
||||
Reference [Notebook example](https://github.com/mem0ai/mem0/blob/main/examples/graph-db-demo/neptune-example.ipynb)
|
||||
|
||||
### Add a memory
|
||||
|
||||
```python
|
||||
@@ -112,13 +103,13 @@ result = m.add(messages, user_id="alice", metadata={"category": "movie_recommend
|
||||
### Search a memory
|
||||
|
||||
```python
|
||||
relevant_memories = m.search(query, user_id="alice")
|
||||
relevant_memories = m.search(query, filters={"user_id": "alice"})
|
||||
```
|
||||
|
||||
### Get all memories
|
||||
|
||||
```python
|
||||
all_memories = m.get_all(user_id="alice")
|
||||
all_memories = m.get_all(filters={"user_id": "alice"})
|
||||
```
|
||||
|
||||
### Get a specific memory
|
||||
@@ -129,15 +120,12 @@ memory = m.get(memory_id)
|
||||
|
||||
## Conclusion
|
||||
|
||||
With Mem0 and AWS services like Bedrock, OpenSearch, and Neptune Analytics, you can build intelligent AI companions that remember, adapt, and personalize their responses over time. This makes them ideal for long-term assistants, tutors, or support bots with persistent memory and natural conversation abilities.
|
||||
With Mem0 and AWS services like Bedrock and OpenSearch, you can build intelligent AI companions that remember, adapt, and personalize their responses over time. This makes them ideal for long-term assistants, tutors, or support bots with persistent memory and natural conversation abilities.
|
||||
|
||||
---
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Neptune Analytics with Mem0" icon="database" href="/cookbooks/integrations/neptune-analytics">
|
||||
Explore graph-based memory storage with AWS Neptune Analytics.
|
||||
</Card>
|
||||
<Card title="Graph Memory Features" icon="sitemap" href="/platform/features/graph-memory">
|
||||
Learn how to leverage knowledge graphs for entity relationships.
|
||||
<Card title="Memory Evaluation" icon="chart-line" href="/core-concepts/memory-evaluation">
|
||||
Understand how Mem0's memory system is benchmarked and evaluated.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -77,7 +77,7 @@ def retrieve_patient_info(query: str) -> dict:
|
||||
results = mem0_client.search(
|
||||
query,
|
||||
user_id=USER_ID,
|
||||
limit=5,
|
||||
top_k=5,
|
||||
threshold=0.7 # Higher threshold for more relevant results
|
||||
)
|
||||
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
---
|
||||
title: Graph Memory on Neptune
|
||||
description: "Combine Mem0 graph memory with AWS Neptune Analytics and Bedrock."
|
||||
---
|
||||
|
||||
|
||||
This example demonstrates how to configure and use the `mem0ai` SDK with **AWS Bedrock** and **AWS Neptune Analytics** for persistent memory capabilities in Python.
|
||||
|
||||
## Installation
|
||||
|
||||
Install the required dependencies to include the Amazon data stack, including **boto3** and **langchain-aws**:
|
||||
|
||||
```bash
|
||||
pip install "mem0ai[graph,extras]"
|
||||
```
|
||||
|
||||
## Environment Setup
|
||||
|
||||
Set your AWS environment variables:
|
||||
|
||||
```python
|
||||
import os
|
||||
|
||||
# Set these in your environment or notebook
|
||||
os.environ['AWS_REGION'] = 'us-west-2'
|
||||
os.environ['AWS_ACCESS_KEY_ID'] = 'AK00000000000000000'
|
||||
os.environ['AWS_SECRET_ACCESS_KEY'] = 'AS00000000000000000'
|
||||
|
||||
# Confirm they are set
|
||||
print(os.environ['AWS_REGION'])
|
||||
print(os.environ['AWS_ACCESS_KEY_ID'])
|
||||
print(os.environ['AWS_SECRET_ACCESS_KEY'])
|
||||
```
|
||||
|
||||
## Configuration and Usage
|
||||
|
||||
This sets up Mem0 with:
|
||||
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
|
||||
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
|
||||
- [Neptune Analytics as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/neptune_analytics)
|
||||
- [Graph Memory guide](https://docs.mem0.ai/open-source/features/graph-memory).
|
||||
|
||||
```python
|
||||
import boto3
|
||||
from mem0.memory.main import Memory
|
||||
|
||||
region = 'us-west-2'
|
||||
neptune_analytics_endpoint = 'neptune-graph://my-graph-identifier'
|
||||
|
||||
config = {
|
||||
"embedder": {
|
||||
"provider": "aws_bedrock",
|
||||
"config": {
|
||||
"model": "amazon.titan-embed-text-v2:0"
|
||||
}
|
||||
},
|
||||
"llm": {
|
||||
"provider": "aws_bedrock",
|
||||
"config": {
|
||||
"model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
|
||||
"temperature": 0.1,
|
||||
"max_tokens": 2000
|
||||
}
|
||||
},
|
||||
"vector_store": {
|
||||
"provider": "neptune",
|
||||
"config": {
|
||||
"collection_name": "mem0",
|
||||
"endpoint": neptune_analytics_endpoint,
|
||||
},
|
||||
},
|
||||
"graph_store": {
|
||||
"provider": "neptune",
|
||||
"config": {
|
||||
"endpoint": neptune_analytics_endpoint,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
# Initialize the memory system
|
||||
m = Memory.from_config(config)
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Reference [Notebook example](https://github.com/mem0ai/mem0/blob/main/examples/graph-db-demo/neptune-example.ipynb)
|
||||
|
||||
#### Add a memory:
|
||||
|
||||
```python
|
||||
messages = [
|
||||
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
|
||||
{"role": "assistant", "content": "How about a 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."}
|
||||
]
|
||||
|
||||
# Store inferred memories (default behavior)
|
||||
result = m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"})
|
||||
```
|
||||
|
||||
#### Search a memory:
|
||||
```python
|
||||
relevant_memories = m.search(query, user_id="alice")
|
||||
```
|
||||
|
||||
#### Get all memories:
|
||||
```python
|
||||
all_memories = m.get_all(user_id="alice")
|
||||
```
|
||||
|
||||
#### Get a specific memory:
|
||||
```python
|
||||
memory = m.get(memory_id)
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Conclusion
|
||||
|
||||
With Mem0 and AWS services like Bedrock and Neptune Analytics, you can build intelligent AI companions that remember, adapt, and personalize their responses over time. This makes them ideal for long-term assistants, tutors, or support bots with persistent memory and natural conversation abilities.
|
||||
|
||||
---
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="AWS Bedrock with Mem0" icon="aws" href="/cookbooks/integrations/aws-bedrock">
|
||||
Combine Neptune Analytics with AWS Bedrock for complete AWS stack.
|
||||
</Card>
|
||||
<Card title="Graph Memory Architecture" icon="sitemap" href="/cookbooks/essentials/choosing-memory-architecture-vector-vs-graph">
|
||||
Understand when to use graph vs vector memory for your use case.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -28,13 +28,10 @@ Get your Mem0 API key from the <a href="https://app.mem0.ai/dashboard/api-keys"
|
||||
### Configuration
|
||||
|
||||
```javascript
|
||||
const mem0Config = {
|
||||
apiKey: process.env.MEM0_API_KEY,
|
||||
user_id: "sample-user",
|
||||
};
|
||||
const USER_ID = "sample-user";
|
||||
|
||||
const openAIClient = new OpenAI();
|
||||
const mem0Client = new MemoryClient(mem0Config);
|
||||
const mem0Client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY });
|
||||
```
|
||||
|
||||
## Adding Memories
|
||||
@@ -43,14 +40,14 @@ Store user preferences, past interactions, or any relevant information:
|
||||
<CodeGroup>
|
||||
```javascript JavaScript
|
||||
async function addUserPreferences() {
|
||||
const mem0Client = new MemoryClient(mem0Config);
|
||||
const mem0Client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY });
|
||||
|
||||
const userPreferences = "I Love BMW, Audi and Porsche. I Hate Mercedes. I love Red cars and Maroon cars. I have a budget of 120K to 150K USD. I like Audi the most.";
|
||||
|
||||
await mem0Client.add([{
|
||||
role: "user",
|
||||
content: userPreferences,
|
||||
}], mem0Config);
|
||||
}], { userId: "sample-user" });
|
||||
}
|
||||
|
||||
await addUserPreferences();
|
||||
@@ -91,7 +88,7 @@ await addUserPreferences();
|
||||
Search for relevant memories based on the current user input:
|
||||
|
||||
```javascript
|
||||
const relevantMemories = await mem0Client.search(userInput, mem0Config);
|
||||
const relevantMemories = await mem0Client.search(userInput, { userId: USER_ID });
|
||||
```
|
||||
|
||||
## Structured Responses with Zod
|
||||
@@ -121,7 +118,7 @@ const carRecommendationTool = zodResponsesFunction({
|
||||
|
||||
// Use the tool in your OpenAI request
|
||||
const response = await openAIClient.responses.create({
|
||||
model: "gpt-4.1-nano-2025-04-14",
|
||||
model: "gpt-5-mini",
|
||||
tools: [{ type: "web_search_preview" }, carRecommendationTool],
|
||||
input: `${getMemoryString(relevantMemories)}\n${userInput}`,
|
||||
});
|
||||
@@ -133,7 +130,7 @@ Combine memory with web search for up-to-date recommendations:
|
||||
|
||||
```javascript
|
||||
const response = await openAIClient.responses.create({
|
||||
model: "gpt-4.1-nano-2025-04-14",
|
||||
model: "gpt-5-mini",
|
||||
tools: [{ type: "web_search_preview" }, carRecommendationTool],
|
||||
input: `${getMemoryString(relevantMemories)}\n${userInput}`,
|
||||
});
|
||||
@@ -152,10 +149,7 @@ import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const mem0Config = {
|
||||
apiKey: process.env.MEM0_API_KEY,
|
||||
user_id: "sample-user",
|
||||
};
|
||||
const USER_ID = "sample-user";
|
||||
|
||||
async function run() {
|
||||
// Responses without memories
|
||||
@@ -185,7 +179,7 @@ const Cars = z.object({
|
||||
|
||||
async function main(memory = false) {
|
||||
const openAIClient = new OpenAI();
|
||||
const mem0Client = new MemoryClient(mem0Config);
|
||||
const mem0Client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY });
|
||||
|
||||
const input = "Suggest me some cars that I can buy today.";
|
||||
|
||||
@@ -195,16 +189,16 @@ async function main(memory = false) {
|
||||
await mem0Client.add([{
|
||||
role: "user",
|
||||
content: input,
|
||||
}], mem0Config);
|
||||
}], { userId: USER_ID });
|
||||
|
||||
// Search for relevant memories
|
||||
let relevantMemories = []
|
||||
if (memory) {
|
||||
relevantMemories = await mem0Client.search(input, mem0Config);
|
||||
relevantMemories = await mem0Client.search(input, { userId: USER_ID });
|
||||
}
|
||||
|
||||
const response = await openAIClient.responses.create({
|
||||
model: "gpt-4.1-nano-2025-04-14",
|
||||
model: "gpt-5-mini",
|
||||
tools: [{ type: "web_search_preview" }, tool],
|
||||
input: `${getMemoryString(relevantMemories)}\n${input}`,
|
||||
});
|
||||
@@ -213,14 +207,14 @@ async function main(memory = false) {
|
||||
}
|
||||
|
||||
async function addSampleMemories() {
|
||||
const mem0Client = new MemoryClient(mem0Config);
|
||||
const mem0Client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY });
|
||||
|
||||
const myInterests = "I Love BMW, Audi and Porsche. I Hate Mercedes. I love Red cars and Maroon cars. I have a budget of 120K to 150K USD. I like Audi the most.";
|
||||
|
||||
await mem0Client.add([{
|
||||
role: "user",
|
||||
content: myInterests,
|
||||
}], mem0Config);
|
||||
}], { userId: USER_ID });
|
||||
}
|
||||
|
||||
const getMemoryString = (memories) => {
|
||||
|
||||
@@ -202,7 +202,7 @@ Preferences:
|
||||
]
|
||||
|
||||
response = openai.chat.completions.create(
|
||||
model="gpt-4.1-nano-2025-04-14",
|
||||
model="gpt-5-mini",
|
||||
messages=messages
|
||||
)
|
||||
clean_response = response.choices[0].message.content.strip()
|
||||
|
||||
@@ -79,7 +79,7 @@ class CustomerSupportAIAgent:
|
||||
:param user_id: Optional user ID to filter memories.
|
||||
:return: List of memories.
|
||||
"""
|
||||
return self.memory.get_all(user_id=user_id)
|
||||
return self.memory.get_all(filters={"user_id": user_id})
|
||||
|
||||
# Instantiate the CustomerSupportAIAgent
|
||||
support_agent = CustomerSupportAIAgent()
|
||||
|
||||
@@ -45,7 +45,7 @@ class CollaborativeAgent:
|
||||
|
||||
def brainstorm(self, prompt):
|
||||
# Get recent messages for context
|
||||
memories = self.mem.search(prompt, run_id=self.run_id, limit=5)["results"]
|
||||
memories = self.mem.search(prompt, filters={"run_id": self.run_id}, top_k=5)["results"]
|
||||
context = "\n".join(f"- {m['memory']} (by {m.get('actor_id', 'Unknown')})" for m in memories)
|
||||
client = OpenAI()
|
||||
messages = [
|
||||
@@ -53,14 +53,14 @@ class CollaborativeAgent:
|
||||
{"role": "user", "content": f"Prompt: {prompt}\nContext:\n{context}"}
|
||||
]
|
||||
reply = client.chat.completions.create(
|
||||
model="gpt-4.1-nano-2025-04-14",
|
||||
model="gpt-5-mini",
|
||||
messages=messages
|
||||
).choices[0].message.content.strip()
|
||||
self.add_message("assistant", "assistant", reply)
|
||||
return reply
|
||||
|
||||
def get_all_messages(self):
|
||||
return self.mem.get_all(run_id=self.run_id)["results"]
|
||||
return self.mem.get_all(filters={"run_id": self.run_id})["results"]
|
||||
|
||||
def print_sorted_by_time(self):
|
||||
messages = self.get_all_messages()
|
||||
|
||||
@@ -37,13 +37,6 @@ Here are some examples of how Mem0 can be integrated into various applications:
|
||||
>
|
||||
Filter speculation and low-confidence data.
|
||||
</Card>
|
||||
<Card
|
||||
title="Set Memory Expiration"
|
||||
icon="timer"
|
||||
href="/cookbooks/essentials/memory-expiration-short-and-long-term"
|
||||
>
|
||||
Short-term vs long-term retention strategies.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Companion Playbooks
|
||||
@@ -201,10 +194,7 @@ Here are some examples of how Mem0 can be integrated into various applications:
|
||||
>
|
||||
Persistent personality for Eliza agents.
|
||||
</Card>
|
||||
<Card title="Browser Extension Memory" icon="globe" href="/cookbooks/frameworks/chrome-extension">
|
||||
Universal memory layer for Chrome.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
</CardGroup>
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
---
|
||||
title: "Memory Evaluation"
|
||||
description: "Understand how Mem0's memory system is evaluated, benchmark results, and how to run evaluations on your own data."
|
||||
icon: "chart-bar"
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
Mem0's memory system operates across two phases — **extraction** (writing) and **retrieval** (reading) — with an entity linking layer connecting them.
|
||||
|
||||
### Memory Extraction (Distillation)
|
||||
|
||||
When new conversations arrive, the extraction pipeline processes them through five 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
|
||||
5. **Entity Linking** — Identify entities (proper nouns, quoted text, compound noun phrases) and link them across memories
|
||||
|
||||
Memories are distributed across three storage layers, each tuned for a specific retrieval pattern:
|
||||
|
||||
| Store | Contents | Purpose |
|
||||
|---|---|---|
|
||||
| **Vector Database** | Memory text, embeddings, metadata (timestamps, hash, categories, attributed_to) | Primary fact storage + semantic retrieval |
|
||||
| **Entity Store** | Entities + embeddings + linked memory IDs | Entity-based retrieval boost |
|
||||
| **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.
|
||||
</Info>
|
||||
|
||||
### Multi-Signal Retrieval
|
||||
|
||||
When a query arrives, the retrieval pipeline scores candidates across three 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 graph matching boosts memories linked to query entities
|
||||
|
||||
Results are fused via rank scoring into a final top-K set. 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?" |
|
||||
|
||||
The combined score outperformed every individual signal across every category tested.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
### LoCoMo
|
||||
|
||||
[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 |
|
||||
|
||||
*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 entity linking (connecting facts across memories).
|
||||
|
||||
### 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 |
|
||||
|
||||
*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.
|
||||
|
||||
### BEAM
|
||||
|
||||
[BEAM](https://github.com/mem0ai/memory-benchmarks) evaluates memory systems at 1M and 10M token scales across ten task categories. It is the only public benchmark that operates at context volumes production AI agents actually encounter.
|
||||
|
||||
| Category | 1M | 10M |
|
||||
|---|---|---|
|
||||
| **Overall** | **64.1** | **48.6** |
|
||||
| preference_following | 88.3 | 90.4 |
|
||||
| instruction_following | 85.2 | 82.5 |
|
||||
| information_extraction | 70.0 | 56.3 |
|
||||
| knowledge_update | 65.0 | 75.0 |
|
||||
| multi_session_reasoning | 65.2 | 26.1 |
|
||||
| summarization | 63.5 | 46.9 |
|
||||
| temporal_reasoning | 61.8 | 16.3 |
|
||||
| event_ordering | 53.6 | 20.2 |
|
||||
| abstention | 52.5 | 40.0 |
|
||||
| contradiction_resolution | 35.7 | 32.5 |
|
||||
|
||||
*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.
|
||||
</Info>
|
||||
|
||||
### Performance Summary
|
||||
|
||||
All results use a single-pass retrieval setup: one retrieval call, one answer, no agentic loops.
|
||||
|
||||
| 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 |
|
||||
|
||||
<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.
|
||||
</Info>
|
||||
|
||||
All benchmarks run on the same production-representative model stack. Scores carry a ±1 point confidence interval due to judge inconsistency.
|
||||
|
||||
## Running Evaluations
|
||||
|
||||
The full evaluation framework is [open-sourced](https://github.com/mem0ai/memory-benchmarks) so anyone can reproduce the numbers independently. It supports both Mem0 Cloud and self-hosted OSS backends.
|
||||
|
||||
### Setup
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Mem0 Cloud">
|
||||
```bash
|
||||
git clone https://github.com/mem0ai/memory-benchmarks.git
|
||||
cd memory-benchmarks
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Set your API keys
|
||||
export MEM0_API_KEY=m0-your-key
|
||||
export OPENAI_API_KEY=sk-your-key
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Mem0 OSS (Docker)">
|
||||
```bash
|
||||
git clone https://github.com/mem0ai/memory-benchmarks.git
|
||||
cd memory-benchmarks
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Copy and configure environment
|
||||
cp .env.example .env
|
||||
# Edit .env to add OPENAI_API_KEY
|
||||
|
||||
# Start local Mem0 server + Qdrant
|
||||
docker compose up -d
|
||||
# Mem0 server: http://localhost:8888
|
||||
# Qdrant: http://localhost:6333
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Running a Benchmark
|
||||
|
||||
Each benchmark is a Python module with its own runner ([source code](https://github.com/mem0ai/memory-benchmarks/tree/main/benchmarks)). All share common CLI options:
|
||||
|
||||
| Option | Default | Description |
|
||||
|---|---|---|
|
||||
| `--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-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`) |
|
||||
| `--answerer-model` | *(varies)* | LLM for generating answers from retrieved memories |
|
||||
| `--judge-model` | *(varies)* | LLM for judging answer correctness |
|
||||
| `--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) |
|
||||
|
||||
<CodeGroup>
|
||||
```bash LoCoMo
|
||||
# ~300 questions across 10 conversations (fastest benchmark)
|
||||
python -m benchmarks.locomo.run \
|
||||
--project-name my-eval \
|
||||
--backend cloud \
|
||||
--mem0-api-key $MEM0_API_KEY \
|
||||
--top-k 200
|
||||
|
||||
# Self-hosted
|
||||
python -m benchmarks.locomo.run \
|
||||
--project-name my-eval \
|
||||
--top-k 200
|
||||
```
|
||||
|
||||
```bash LongMemEval
|
||||
# 500 questions across 6 categories
|
||||
python -m benchmarks.longmemeval.run \
|
||||
--project-name my-eval \
|
||||
--backend cloud \
|
||||
--mem0-api-key $MEM0_API_KEY \
|
||||
--all-questions \
|
||||
--top-k 200
|
||||
|
||||
# Self-hosted
|
||||
python -m benchmarks.longmemeval.run \
|
||||
--project-name my-eval \
|
||||
--all-questions \
|
||||
--top-k 200
|
||||
```
|
||||
|
||||
```bash BEAM
|
||||
# 1M token scale (100 conversations)
|
||||
python -m benchmarks.beam.run \
|
||||
--project-name my-eval \
|
||||
--backend cloud \
|
||||
--mem0-api-key $MEM0_API_KEY \
|
||||
--chat-sizes 1M \
|
||||
--conversations 0-99 \
|
||||
--top-k 200
|
||||
|
||||
# 10M token scale
|
||||
python -m benchmarks.beam.run \
|
||||
--project-name my-eval \
|
||||
--backend cloud \
|
||||
--mem0-api-key $MEM0_API_KEY \
|
||||
--chat-sizes 10M \
|
||||
--conversations 0-99 \
|
||||
--top-k 200
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### Custom Model Configuration
|
||||
|
||||
To run evaluations with custom models (Azure OpenAI, Ollama, etc.), copy one of the provided configs:
|
||||
|
||||
```bash
|
||||
# Available configs: openai.yaml, azure-openai.yaml, ollama.yaml
|
||||
cp configs/azure-openai.yaml mem0-config.yaml
|
||||
# Edit mem0-config.yaml with your model details
|
||||
|
||||
# Uncomment the volume mount in docker-compose.yml, then restart:
|
||||
docker compose down && docker compose up -d
|
||||
```
|
||||
|
||||
### Viewing Results
|
||||
|
||||
Results are saved to `results/[benchmark]/` and can be explored through the built-in web UI:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev -- -p 3001
|
||||
# Open http://localhost:3001
|
||||
```
|
||||
|
||||
The UI lets you browse per-question results, inspect retrieval details, and compare multiple runs.
|
||||
|
||||
### Result Format
|
||||
|
||||
Each evaluated question produces a structured result:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "locomo_q_001",
|
||||
"group": "temporal",
|
||||
"question": "When did the user first mention moving?",
|
||||
"ground_truth": "During the March 3rd conversation",
|
||||
"retrieval": {
|
||||
"search_query": "when did user mention moving",
|
||||
"search_results": ["..."],
|
||||
"search_latency_ms": 123.4,
|
||||
"total_results": 42
|
||||
},
|
||||
"generation": {
|
||||
"generated_answer": "The user first mentioned moving on March 3rd",
|
||||
"model": "<answerer-model>",
|
||||
"prompt_tokens": 500,
|
||||
"completion_tokens": 100
|
||||
},
|
||||
"judgment": {
|
||||
"judgment": "CORRECT",
|
||||
"score": 0.85,
|
||||
"reason": "Answer correctly identifies the date",
|
||||
"model": "<judge-model>"
|
||||
},
|
||||
"cutoff_results": {
|
||||
"top_10": { "score": 0.75, "judgment": "CORRECT" },
|
||||
"top_50": { "score": 0.85, "judgment": "CORRECT" },
|
||||
"top_200": { "score": 0.90, "judgment": "CORRECT" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Interpreting Results
|
||||
|
||||
When evaluating memory systems, keep these considerations in mind:
|
||||
|
||||
- **Saturating a small benchmark is not the same as building a memory system that works at scale.** Small benchmarks can be brute-forced with aggressive retrieval and frontier models.
|
||||
- **Token efficiency matters as much as accuracy.** A system that scores 95% using 25K tokens per query isn't comparable to one scoring 90% using 7K tokens. Report mean tokens per query alongside scores.
|
||||
- **Compare at equal constraints.** Always compare systems using the same retrieval budget, the same model, and the same latency budget. A frontier model at maximum recall is not comparable to a smaller production-grade model at production-realistic retrieval depth.
|
||||
- **Watch for score ceiling effects.** Categories like "single-session user" are already near-saturated (97%+). Improvements in these categories are less meaningful than gains in harder categories like temporal reasoning or multi-session.
|
||||
- **BEAM at 10M is the real test.** Any system can look good at small scale. The 10M-token BEAM benchmark reveals whether the retrieval system actually scales.
|
||||
|
||||
## FAQ
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="What judge model is used for evaluation?">
|
||||
The judge model is configurable via `--judge-model` and `--judge-provider` flags. See the [evaluation repository](https://github.com/mem0ai/memory-benchmarks) for the current defaults. Scores carry a ±1 point confidence interval due to judge inconsistency.
|
||||
</Accordion>
|
||||
<Accordion title="Can I evaluate with a different extraction model?">
|
||||
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.
|
||||
</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.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Resources
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Evaluation Repository" icon="github" href="https://github.com/mem0ai/memory-benchmarks">
|
||||
Open-source evaluation framework for reproducing all benchmark results
|
||||
</Card>
|
||||
<Card title="Research" icon="flask" href="https://mem0.ai/research">
|
||||
Published research papers and technical reports
|
||||
</Card>
|
||||
<Card title="Blog Post" icon="newspaper" href="https://mem0.ai/blog/new-algorithm">
|
||||
Detailed writeup of the new algorithm design and results
|
||||
</Card>
|
||||
<Card title="Platform Migration" icon="arrow-right" href="/migration/platform-v2-to-v3">
|
||||
Guide for migrating your Platform integration
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -85,7 +85,6 @@ const messages = [
|
||||
|
||||
await client.add(messages, {
|
||||
user_id: "alice",
|
||||
version: "v2",
|
||||
});
|
||||
```
|
||||
</CodeGroup>
|
||||
@@ -173,7 +172,6 @@ For full list of supported fields, required formats, and advanced options, see t
|
||||
| Capability | Mem0 Platform | Mem0 OSS |
|
||||
| --- | --- | --- |
|
||||
| Conflict resolution | Automatic with dashboard visibility | SDK handles merges locally; you control storage |
|
||||
| Graph writes | Toggle per request (`enable_graph=True`) | Requires configuring a graph provider |
|
||||
| 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 |
|
||||
|
||||
|
||||
@@ -120,7 +120,7 @@ import MemoryClient from 'mem0ai';
|
||||
|
||||
const client = new MemoryClient({ apiKey: "your-api-key" });
|
||||
|
||||
client.deleteAll({ user_id: "alice" })
|
||||
client.deleteAll({ userId: "alice" })
|
||||
.then(result => console.log(result))
|
||||
.catch(error => console.error(error));
|
||||
```
|
||||
@@ -162,12 +162,12 @@ import MemoryClient from 'mem0ai';
|
||||
const client = new MemoryClient({ apiKey: "your-api-key" });
|
||||
|
||||
// Delete all memories across every user in the project
|
||||
client.deleteAll({ user_id: "*" })
|
||||
client.deleteAll({ userId: "*" })
|
||||
.then(result => console.log(result))
|
||||
.catch(error => console.error(error));
|
||||
|
||||
// Full project wipe — all four filters must be explicitly set to "*"
|
||||
client.deleteAll({ user_id: "*", agent_id: "*", app_id: "*", run_id: "*" })
|
||||
client.deleteAll({ userId: "*", agentId: "*", appId: "*", runId: "*" })
|
||||
.then(result => console.log(result))
|
||||
.catch(error => console.error(error));
|
||||
```
|
||||
@@ -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/expiration-date">Expiration Policies</Link> to automate retention.
|
||||
- Pair deletes with <Link href="/platform/features/platform-overview">Expiration Policies</Link> to automate retention.
|
||||
|
||||
## See it live
|
||||
|
||||
@@ -236,6 +236,6 @@ memory.delete_all(user_id="alice")
|
||||
title="Enable Expiration Policies"
|
||||
description="Automate retention with the platform’s expiration feature."
|
||||
icon="clock"
|
||||
href="/platform/features/expiration-date"
|
||||
href="/platform/features/platform-overview"
|
||||
/>
|
||||
</CardGroup>
|
||||
|
||||
@@ -56,7 +56,7 @@ Search converts your natural language question into a vector embedding, then fin
|
||||
client.search("What are Alice's hobbies?", filters={"user_id": "alice"})
|
||||
|
||||
# OSS
|
||||
m.search("What are Alice's hobbies?", user_id="alice")
|
||||
m.search("What are Alice's hobbies?", filters={"user_id": "alice"})
|
||||
```
|
||||
|
||||
<Tip>
|
||||
@@ -74,7 +74,7 @@ m.search("What are Alice's hobbies?", user_id="alice")
|
||||
|
||||
| Capability | Mem0 Platform | Mem0 OSS |
|
||||
| --- | --- | --- |
|
||||
| **user_id usage** | In `filters={"user_id": "alice"}` for search/get_all | As parameter `user_id="alice"` for all operations |
|
||||
| **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 |
|
||||
@@ -125,14 +125,13 @@ from mem0 import Memory
|
||||
|
||||
m = Memory()
|
||||
|
||||
# Simple search
|
||||
related_memories = m.search("Should I drink coffee or tea?", user_id="alice")
|
||||
# Simple search — entity IDs go in `filters`
|
||||
related_memories = m.search("Should I drink coffee or tea?", filters={"user_id": "alice"})
|
||||
|
||||
# Search with filters
|
||||
# Search with additional metadata filters (combine entity + metadata in the same dict)
|
||||
memories = m.search(
|
||||
"food preferences",
|
||||
user_id="alice",
|
||||
filters={"categories": {"contains": "diet"}}
|
||||
filters={"user_id": "alice", "categories": {"contains": "diet"}},
|
||||
)
|
||||
```
|
||||
|
||||
@@ -141,13 +140,14 @@ import { Memory } from 'mem0ai/oss';
|
||||
|
||||
const memory = new Memory();
|
||||
|
||||
// Simple search
|
||||
const relatedMemories = memory.search("Should I drink coffee or tea?", { userId: "alice" });
|
||||
// Simple search — entity IDs go inside `filters`
|
||||
const relatedMemories = memory.search("Should I drink coffee or tea?", {
|
||||
filters: { userId: "alice" },
|
||||
});
|
||||
|
||||
// Search with filters (if supported)
|
||||
// Combine entity + metadata filters in the same filters object
|
||||
const memories = memory.search("food preferences", {
|
||||
userId: "alice",
|
||||
filters: { categories: { contains: "diet" } }
|
||||
filters: { userId: "alice", categories: { contains: "diet" } },
|
||||
});
|
||||
```
|
||||
</CodeGroup>
|
||||
@@ -176,8 +176,12 @@ client.search("query", filters={
|
||||
|
||||
*OSS:*
|
||||
```python
|
||||
# Get memories from a specific agent session
|
||||
m.search("query", user_id="alice", agent_id="chatbot", run_id="session-123")
|
||||
# Get memories from a specific agent session — entity IDs combined in filters
|
||||
m.search("query", filters={
|
||||
"user_id": "alice",
|
||||
"agent_id": "chatbot",
|
||||
"run_id": "session-123",
|
||||
})
|
||||
```
|
||||
|
||||
**Filter by Date Range:**
|
||||
|
||||
@@ -55,7 +55,8 @@
|
||||
"core-concepts/memory-operations/add",
|
||||
"core-concepts/memory-operations/search",
|
||||
"core-concepts/memory-operations/update",
|
||||
"core-concepts/memory-operations/delete"
|
||||
"core-concepts/memory-operations/delete",
|
||||
"core-concepts/memory-evaluation"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -70,7 +71,6 @@
|
||||
"platform/features/v2-memory-filters",
|
||||
"platform/features/entity-scoped-memory",
|
||||
"platform/features/async-client",
|
||||
"platform/features/async-mode-default-change",
|
||||
"platform/features/multimodal-support",
|
||||
"platform/features/custom-categories"
|
||||
]
|
||||
@@ -79,8 +79,6 @@
|
||||
"group": "Advanced Features",
|
||||
"icon": "bolt",
|
||||
"pages": [
|
||||
"platform/features/graph-memory",
|
||||
"platform/features/graph-threshold",
|
||||
"platform/features/advanced-retrieval",
|
||||
"platform/advanced-memory-operations",
|
||||
"platform/features/criteria-retrieval",
|
||||
@@ -94,8 +92,7 @@
|
||||
"pages": [
|
||||
"platform/features/direct-import",
|
||||
"platform/features/memory-export",
|
||||
"platform/features/timestamp",
|
||||
"platform/features/expiration-date"
|
||||
"platform/features/timestamp"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -121,9 +118,8 @@
|
||||
"group": "Migration Guide",
|
||||
"icon": "arrow-right",
|
||||
"pages": [
|
||||
"migration/platform-v2-to-v3",
|
||||
"migration/oss-to-platform",
|
||||
"migration/v0-to-v1",
|
||||
"migration/breaking-changes",
|
||||
"migration/api-changes"
|
||||
]
|
||||
},
|
||||
@@ -133,16 +129,6 @@
|
||||
"pages": [
|
||||
"platform/contribute"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Release Notes",
|
||||
"icon": "rocket",
|
||||
"pages": [
|
||||
"changelog/highlights",
|
||||
"changelog/sdk",
|
||||
"changelog/platform",
|
||||
"changelog/openclaw"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -177,13 +163,11 @@
|
||||
"icon": "server",
|
||||
"pages": [
|
||||
"open-source/features/overview",
|
||||
"open-source/features/graph-memory",
|
||||
"open-source/features/metadata-filtering",
|
||||
"open-source/features/reranker-search",
|
||||
"open-source/features/async-memory",
|
||||
"open-source/features/multimodal-support",
|
||||
"open-source/features/custom-fact-extraction-prompt",
|
||||
"open-source/features/custom-update-memory-prompt",
|
||||
"open-source/features/custom-instructions",
|
||||
"open-source/features/rest-api",
|
||||
"open-source/features/openai_compatibility"
|
||||
]
|
||||
@@ -310,6 +294,13 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Migration",
|
||||
"icon": "arrow-right",
|
||||
"pages": [
|
||||
"migration/oss-v2-to-v3"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Community & Support",
|
||||
"icon": "users",
|
||||
@@ -337,10 +328,8 @@
|
||||
"cookbooks/essentials/building-ai-companion",
|
||||
"cookbooks/essentials/entity-partitioning-playbook",
|
||||
"cookbooks/essentials/controlling-memory-ingestion",
|
||||
"cookbooks/essentials/memory-expiration-short-and-long-term",
|
||||
"cookbooks/essentials/tagging-and-organizing-memories",
|
||||
"cookbooks/essentials/exporting-memories",
|
||||
"cookbooks/essentials/choosing-memory-architecture-vector-vs-graph"
|
||||
"cookbooks/essentials/exporting-memories"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -376,7 +365,6 @@
|
||||
"cookbooks/integrations/mastra-agent",
|
||||
"cookbooks/integrations/healthcare-google-adk",
|
||||
"cookbooks/integrations/aws-bedrock",
|
||||
"cookbooks/integrations/neptune-analytics",
|
||||
"cookbooks/integrations/tavily-search"
|
||||
]
|
||||
},
|
||||
@@ -388,9 +376,7 @@
|
||||
"cookbooks/frameworks/llamaindex-multiagent",
|
||||
"cookbooks/frameworks/multimodal-retrieval",
|
||||
"cookbooks/frameworks/eliza-os-character",
|
||||
"cookbooks/frameworks/chrome-extension",
|
||||
"cookbooks/frameworks/gemini-3-with-mem0-mcp",
|
||||
"cookbooks/frameworks/mirofish-swarm-memory"
|
||||
"cookbooks/frameworks/gemini-3-with-mem0-mcp"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -562,6 +548,21 @@
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tab": "Release Notes",
|
||||
"groups": [
|
||||
{
|
||||
"group": "Release Notes",
|
||||
"icon": "rocket",
|
||||
"pages": [
|
||||
"changelog/highlights",
|
||||
"changelog/sdk",
|
||||
"changelog/platform",
|
||||
"changelog/openclaw"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -612,6 +613,38 @@
|
||||
]
|
||||
},
|
||||
"redirects": [
|
||||
{
|
||||
"source": "/migration/breaking-changes",
|
||||
"destination": "/"
|
||||
},
|
||||
{
|
||||
"source": "/migration/v0-to-v1",
|
||||
"destination": "/"
|
||||
},
|
||||
{
|
||||
"source": "/platform/features/expiration-date",
|
||||
"destination": "/"
|
||||
},
|
||||
{
|
||||
"source": "/cookbooks/essentials/memory-expiration-short-and-long-term",
|
||||
"destination": "/cookbooks/essentials/building-ai-companion"
|
||||
},
|
||||
{
|
||||
"source": "/platform/features/async-mode-default-change",
|
||||
"destination": "/"
|
||||
},
|
||||
{
|
||||
"source": "/open-source/features/custom-fact-extraction-prompt",
|
||||
"destination": "/open-source/features/custom-instructions"
|
||||
},
|
||||
{
|
||||
"source": "/platform/features/graph-memory",
|
||||
"destination": "/migration/oss-v2-to-v3"
|
||||
},
|
||||
{
|
||||
"source": "/cookbooks/essentials/choosing-memory-architecture-vector-vs-graph",
|
||||
"destination": "/migration/oss-v2-to-v3"
|
||||
},
|
||||
{
|
||||
"source": "/changelog",
|
||||
"destination": "/changelog/highlights"
|
||||
@@ -710,11 +743,23 @@
|
||||
},
|
||||
{
|
||||
"source": "/examples/aws_neptune_analytics_hybrid_store",
|
||||
"destination": "/cookbooks/integrations/neptune-analytics"
|
||||
"destination": "/migration/oss-v2-to-v3"
|
||||
},
|
||||
{
|
||||
"source": "/examples/aws_neptune_analytics_hybrid_st",
|
||||
"destination": "/cookbooks/integrations/neptune-analytics"
|
||||
"destination": "/migration/oss-v2-to-v3"
|
||||
},
|
||||
{
|
||||
"source": "/cookbooks/integrations/neptune-analytics",
|
||||
"destination": "/migration/oss-v2-to-v3"
|
||||
},
|
||||
{
|
||||
"source": "/platform/features/graph-threshold",
|
||||
"destination": "/migration/platform-v2-to-v3"
|
||||
},
|
||||
{
|
||||
"source": "/open-source/features/custom-update-memory-prompt",
|
||||
"destination": "/open-source/features/custom-instructions"
|
||||
},
|
||||
{
|
||||
"source": "/examples/personalized-search-tavily-mem0",
|
||||
@@ -774,7 +819,11 @@
|
||||
},
|
||||
{
|
||||
"source": "/examples/chrome-extension",
|
||||
"destination": "/cookbooks/frameworks/chrome-extension"
|
||||
"destination": "/cookbooks/overview"
|
||||
},
|
||||
{
|
||||
"source": "/cookbooks/frameworks/chrome-extension",
|
||||
"destination": "/cookbooks/overview"
|
||||
},
|
||||
{
|
||||
"source": "/examples",
|
||||
@@ -782,11 +831,11 @@
|
||||
},
|
||||
{
|
||||
"source": "/open-source/graph_memory/overview",
|
||||
"destination": "/open-source/features/graph-memory"
|
||||
"destination": "/migration/oss-v2-to-v3"
|
||||
},
|
||||
{
|
||||
"source": "/open-source/graph_memory/features",
|
||||
"destination": "/open-source/features/graph-memory"
|
||||
"destination": "/migration/oss-v2-to-v3"
|
||||
},
|
||||
{
|
||||
"source": "/v0x/examples/ai_companion_js",
|
||||
@@ -814,7 +863,7 @@
|
||||
},
|
||||
{
|
||||
"source": "/v0x/examples/chrome-extension",
|
||||
"destination": "/cookbooks/frameworks/chrome-extension"
|
||||
"destination": "/cookbooks/overview"
|
||||
},
|
||||
{
|
||||
"source": "/v0x/examples/youtube-assistant",
|
||||
@@ -882,7 +931,7 @@
|
||||
},
|
||||
{
|
||||
"source": "/v0x/examples/aws_neptune_analytics_hybrid_store",
|
||||
"destination": "/cookbooks/integrations/neptune-analytics"
|
||||
"destination": "/migration/oss-v2-to-v3"
|
||||
},
|
||||
{
|
||||
"source": "/features/memory-export",
|
||||
@@ -966,7 +1015,7 @@
|
||||
},
|
||||
{
|
||||
"source": "/features/graph-memory",
|
||||
"destination": "/platform/features/graph-memory"
|
||||
"destination": "/migration/oss-v2-to-v3"
|
||||
},
|
||||
{
|
||||
"source": "/features/:slug",
|
||||
@@ -1074,7 +1123,7 @@
|
||||
},
|
||||
{
|
||||
"source": "/open-source/graph-memory",
|
||||
"destination": "/open-source/features/graph-memory"
|
||||
"destination": "/migration/oss-v2-to-v3"
|
||||
},
|
||||
{
|
||||
"source": "/cookbooks/customer-support-agent",
|
||||
|
||||
|
Before Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 58 KiB |
|
Before Width: | Height: | Size: 59 KiB |
|
Before Width: | Height: | Size: 71 KiB |
|
Before Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 88 KiB |
|
Before Width: | Height: | Size: 114 KiB |
|
Before Width: | Height: | Size: 94 KiB |
@@ -50,7 +50,7 @@ local_config = {
|
||||
"llm": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "gpt-4.1-nano-2025-04-14",
|
||||
"model": "gpt-5-mini",
|
||||
"temperature": 0.1,
|
||||
"max_tokens": 2000,
|
||||
},
|
||||
@@ -103,7 +103,7 @@ def demonstrate_sync_memory(local_config, sample_messages, sample_preferences, u
|
||||
]
|
||||
|
||||
for query in search_queries:
|
||||
results = memory.search(query, user_id=user_id)
|
||||
results = memory.search(query, filters={"user_id": user_id})
|
||||
|
||||
if results and "results" in results:
|
||||
for j, result in enumerate(results['results']):
|
||||
@@ -111,7 +111,7 @@ def demonstrate_sync_memory(local_config, sample_messages, sample_preferences, u
|
||||
else:
|
||||
print("No results found")
|
||||
|
||||
all_memories = memory.get_all(user_id=user_id)
|
||||
all_memories = memory.get_all(filters={"user_id": user_id})
|
||||
if all_memories and "results" in all_memories:
|
||||
print(f"Total memories: {len(all_memories['results'])}")
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ from agno.tools.mem0 import Mem0Tools
|
||||
|
||||
agent = Agent(
|
||||
name="Memory Agent",
|
||||
model=OpenAIChat(id="gpt-4.1-nano-2025-04-14"),
|
||||
model=OpenAIChat(id="gpt-5-mini"),
|
||||
tools=[Mem0Tools()],
|
||||
description="An assistant that remembers and personalizes using Mem0 memory."
|
||||
)
|
||||
@@ -126,7 +126,7 @@ def chat_user(
|
||||
|
||||
if user_input:
|
||||
# Search for relevant memories
|
||||
memories = client.search(user_input, user_id=user_id)
|
||||
memories = client.search(user_input, filters={"user_id": user_id})
|
||||
memory_context = "\n".join(f"- {m['memory']}" for m in memories['results'])
|
||||
|
||||
# Construct the prompt
|
||||
|
||||
@@ -72,7 +72,7 @@ Create a function to get context-aware responses based on user's question and pr
|
||||
|
||||
```python
|
||||
def get_context_aware_response(question):
|
||||
relevant_memories = memory_client.search(question, user_id=USER_ID)
|
||||
relevant_memories = memory_client.search(question, filters={"user_id": USER_ID})
|
||||
context = "\n".join([m["memory"] for m in relevant_memories.get('results', [])])
|
||||
|
||||
prompt = f"""Answer the user question considering the previous interactions:
|
||||
@@ -104,7 +104,7 @@ manager = ConversableAgent(
|
||||
)
|
||||
|
||||
def escalate_to_manager(question):
|
||||
relevant_memories = memory_client.search(question, user_id=USER_ID)
|
||||
relevant_memories = memory_client.search(question, filters={"user_id": USER_ID})
|
||||
context = "\n".join([m["memory"] for m in relevant_memories.get('results', [])])
|
||||
|
||||
prompt = f"""
|
||||
|
||||
@@ -49,7 +49,7 @@ Import necessary modules and configure Mem0:
|
||||
```python
|
||||
import boto3
|
||||
from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth
|
||||
from mem0.memory.main import Memory
|
||||
from mem0 import Memory
|
||||
|
||||
region = 'us-west-2'
|
||||
service = 'aoss'
|
||||
@@ -107,10 +107,10 @@ messages = [
|
||||
m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"})
|
||||
|
||||
# Search for memory
|
||||
relevant = m.search("What kind of movies does Alice like?", user_id="alice")
|
||||
relevant = m.search("What kind of movies does Alice like?", filters={"user_id": "alice"})
|
||||
|
||||
# Retrieve all user memories
|
||||
all_memories = m.get_all(user_id="alice")
|
||||
all_memories = m.get_all(filters={"user_id": "alice"})
|
||||
```
|
||||
|
||||
## Key Features
|
||||
@@ -125,8 +125,5 @@ all_memories = m.get_all(user_id="alice")
|
||||
<Card title="AWS Bedrock Cookbook" icon="aws" href="/cookbooks/integrations/aws-bedrock">
|
||||
Complete guide to using Bedrock with Mem0
|
||||
</Card>
|
||||
<Card title="Neptune Analytics Cookbook" icon="database" href="/cookbooks/integrations/neptune-analytics">
|
||||
Build graph memory with AWS Neptune
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
@@ -32,12 +32,19 @@ export MEM0_API_KEY="m0-your-api-key"
|
||||
|
||||
### Option A — Plugin Marketplace (Recommended)
|
||||
|
||||
Install the full plugin including MCP server, lifecycle hooks, and SDK skill:
|
||||
Install the full plugin including MCP server, lifecycle hooks, and SDK skill.
|
||||
|
||||
```
|
||||
/plugin marketplace add mem0ai/mem0
|
||||
/plugin install mem0@mem0-plugins
|
||||
```
|
||||
1. Add the Mem0 marketplace:
|
||||
|
||||
```
|
||||
/plugin marketplace add mem0ai/mem0
|
||||
```
|
||||
|
||||
2. Install the plugin:
|
||||
|
||||
```
|
||||
/plugin install mem0@mem0-plugins
|
||||
```
|
||||
|
||||
**Claude Cowork desktop app:** Open the Cowork tab, click **Customize** in the sidebar, click **Browse plugins**, and install Mem0.
|
||||
|
||||
|
||||
@@ -268,7 +268,7 @@ memories = mem0.search(
|
||||
{"categories": {"contains": "travel"}}
|
||||
]
|
||||
},
|
||||
limit=5
|
||||
top_k=5
|
||||
)
|
||||
|
||||
# Configure agent with custom model settings
|
||||
|
||||
@@ -16,7 +16,7 @@ Combining Mem0 with Keywords AI allows you to:
|
||||
4. Optimize token usage and reduce costs
|
||||
|
||||
<Note>
|
||||
You can get your Mem0 API key, user_id, and org_id from the <a href="https://app.mem0.ai/" rel="nofollow">Mem0 dashboard</a>. These are required for proper integration.
|
||||
You can get your Mem0 API key from the <a href="https://app.mem0.ai/" rel="nofollow">Mem0 dashboard</a>.
|
||||
</Note>
|
||||
|
||||
## Setup and Configuration
|
||||
@@ -24,7 +24,7 @@ You can get your Mem0 API key, user_id, and org_id from the <a href="https://app
|
||||
Install the necessary libraries:
|
||||
|
||||
```bash
|
||||
pip install mem0 keywordsai-sdk
|
||||
pip install mem0ai keywordsai-sdk
|
||||
```
|
||||
|
||||
Set up your environment variables:
|
||||
@@ -56,7 +56,7 @@ config = {
|
||||
"llm": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "gpt-4.1-nano-2025-04-14",
|
||||
"model": "gpt-5-mini",
|
||||
"temperature": 0.0,
|
||||
"api_key": keywordsai_api_key,
|
||||
"openai_base_url": base_url,
|
||||
@@ -65,7 +65,7 @@ config = {
|
||||
}
|
||||
|
||||
# Initialize Memory
|
||||
memory = Memory.from_config(config_dict=config)
|
||||
memory = Memory.from_config(config)
|
||||
|
||||
# Add a memory
|
||||
result = memory.add(
|
||||
@@ -107,7 +107,6 @@ response = client.chat.completions.create(
|
||||
extra_body={
|
||||
"mem0_params": {
|
||||
"user_id": "test_user",
|
||||
"org_id": "org_1",
|
||||
"api_key": os.environ.get("MEM0_API_KEY"),
|
||||
"add_memories": {
|
||||
"messages": messages,
|
||||
|
||||
@@ -29,10 +29,7 @@ import os
|
||||
|
||||
os.environ["MEM0_API_KEY"] = "your-api-key"
|
||||
|
||||
client = MemoryClient(
|
||||
org_id=your_org_id,
|
||||
project_id=your_project_id
|
||||
)
|
||||
client = MemoryClient()
|
||||
```
|
||||
|
||||
## Available Tools
|
||||
|
||||
@@ -40,7 +40,7 @@ load_dotenv()
|
||||
# os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
|
||||
|
||||
# Initialize LangChain and Mem0
|
||||
llm = ChatOpenAI(model="gpt-4.1-nano-2025-04-14")
|
||||
llm = ChatOpenAI(model="gpt-5-mini")
|
||||
mem0 = MemoryClient()
|
||||
```
|
||||
|
||||
@@ -66,7 +66,7 @@ Create functions to handle context retrieval, response generation, and addition
|
||||
def retrieve_context(query: str, user_id: str) -> List[Dict]:
|
||||
"""Retrieve relevant context from Mem0"""
|
||||
try:
|
||||
memories = mem0.search(query, user_id=user_id)
|
||||
memories = mem0.search(query, filters={"user_id": user_id})
|
||||
memory_list = memories['results']
|
||||
|
||||
serialized_memories = ' '.join([mem["memory"] for mem in memory_list])
|
||||
|
||||
@@ -68,7 +68,7 @@ def chatbot(state: State):
|
||||
|
||||
try:
|
||||
# Retrieve relevant memories
|
||||
memories = mem0.search(messages[-1].content, user_id=user_id)
|
||||
memories = mem0.search(messages[-1].content, filters={"user_id": user_id})
|
||||
|
||||
# Handle dict response format
|
||||
memory_list = memories['results']
|
||||
|
||||