Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7b6790bafb | |||
| 93da5ef8f7 | |||
| c1c5bd62f6 | |||
| 2ec3c4ab20 | |||
| 3fbc1c9aef | |||
| 0b14f75c05 |
@@ -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
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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>
|
||||
@@ -53,47 +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"
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
```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>
|
||||
|
||||
@@ -6,7 +6,7 @@ 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 90% Lower Cost**
|
||||
**New Memory Algorithm — State-of-the-Art Accuracy at ~3-4x Lower Cost**
|
||||
|
||||
Ground-up rewrite of the memory pipeline with 20+ point benchmark improvements:
|
||||
|
||||
@@ -15,7 +15,7 @@ Ground-up rewrite of the memory pipeline with 20+ point benchmark improvements:
|
||||
- **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%**
|
||||
- **90% fewer tokens** — Under 7K tokens per retrieval vs 25K+ for full-context approaches
|
||||
- **~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
|
||||
|
||||
@@ -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:**
|
||||
|
||||
@@ -158,7 +158,7 @@ class PersonalTravelAssistant:
|
||||
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
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
@@ -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
|
||||
)
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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,12 +189,12 @@ 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({
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -328,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"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -627,6 +625,10 @@
|
||||
"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": "/"
|
||||
@@ -639,6 +641,10 @@
|
||||
"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"
|
||||
|
||||
|
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 |
@@ -1,304 +1,474 @@
|
||||
# Mem0
|
||||
|
||||
> Mem0 is a self-improving memory layer for LLM applications, enabling personalized AI experiences that retain context across sessions, adapt over time, and reduce costs by intelligently storing and retrieving relevant information.
|
||||
> Mem0 is a memory layer for LLM agents - persistent, self-improving context that survives across sessions. Two products share one mental model: Mem0 Platform (managed) and Mem0 Open Source (self-hosted). Every link below is tagged `[Platform]`, `[OSS]`, or `[Both]` so you can load only what the current user needs.
|
||||
|
||||
Mem0 provides both a managed platform and open-source solutions for adding persistent memory to AI agents and applications. Unlike traditional RAG systems that are stateless, Mem0 creates stateful agents that remember user preferences, learn from interactions, and evolve behavior over time.
|
||||
## For agents reading this file
|
||||
|
||||
Key differentiators:
|
||||
- **Stateful vs Stateless**: Retains context across sessions rather than forgetting after each interaction
|
||||
- **Intelligent Memory Management**: Uses LLMs to extract, filter, and organize relevant information
|
||||
- **Dual Storage Architecture**: Combines vector embeddings with graph databases for comprehensive memory
|
||||
- **Sub-50ms Retrieval**: Lightning-fast memory lookups for real-time applications
|
||||
- **Multimodal Support**: Handles text, images, and documents seamlessly
|
||||
- Use `MemoryClient` (Python) / `mem0ai` (npm) when the user has a Mem0 Platform API key. Docs under `/platform/` and `/api-reference/` apply; the managed product handles providers server-side, so you can ignore `## Optional` below.
|
||||
- Use `Memory` (Python) / `mem0ai/oss` (npm) when the user self-hosts. Docs under `/open-source/` and `/components/` apply; Platform-only features (entity filters v2, custom categories, webhooks, advanced retrieval) may not be available.
|
||||
- Scope tag reference: `[Platform]` = managed only, `[OSS]` = self-hosted only, `[Both]` = same API surface on both.
|
||||
- OpenAPI spec: https://docs.mem0.ai/openapi.json
|
||||
- Live MCP server: https://mcp.mem0.ai (see `platform/mem0-mcp`).
|
||||
- Source repo: https://github.com/mem0ai/mem0
|
||||
|
||||
## Install
|
||||
|
||||
- Python SDK: `pip install mem0ai`
|
||||
- Node SDK: `npm install mem0ai`
|
||||
- Python CLI: `pip install mem0-cli`
|
||||
- Node CLI: `npm install -g @mem0/cli`
|
||||
|
||||
## Identify the User's Setup
|
||||
|
||||
Look at the user's imports first - they determine which product (Platform vs OSS) and which language you should quote docs from. **Mem0 Platform (managed) is the recommended path** - 4-line integration, sub-50ms retrieval, no infra. Route to OSS only when the user has an explicit self-hosting requirement.
|
||||
|
||||
### Platform - Python [Platform]
|
||||
|
||||
Import signature: `from mem0 import MemoryClient`
|
||||
|
||||
```python
|
||||
from mem0 import MemoryClient
|
||||
|
||||
client = MemoryClient(api_key="your-api-key")
|
||||
|
||||
# Create
|
||||
client.add(
|
||||
[{"role": "user", "content": "I love hiking on weekends"}],
|
||||
user_id="alice",
|
||||
)
|
||||
|
||||
# Read
|
||||
client.search("What does Alice like to do?", user_id="alice")
|
||||
client.get_all(user_id="alice")
|
||||
client.get(memory_id="<id>")
|
||||
|
||||
# Update
|
||||
client.update(memory_id="<id>", data="Alice loves mountain hiking")
|
||||
|
||||
# Delete
|
||||
client.delete(memory_id="<id>")
|
||||
client.delete_all(user_id="alice")
|
||||
```
|
||||
|
||||
Relevant docs: `platform/quickstart`, `platform/features/*`, `api-reference/*`.
|
||||
|
||||
### Platform - TypeScript / JavaScript [Platform]
|
||||
|
||||
Import signature: `import MemoryClient from "mem0ai"`
|
||||
|
||||
```ts
|
||||
import MemoryClient from "mem0ai";
|
||||
|
||||
const client = new MemoryClient({ apiKey: "your-api-key" });
|
||||
|
||||
// Create
|
||||
await client.add(
|
||||
[{ role: "user", content: "I love hiking on weekends" }],
|
||||
{ user_id: "alice" },
|
||||
);
|
||||
|
||||
// Read
|
||||
await client.search("What does Alice like to do?", { user_id: "alice" });
|
||||
await client.getAll({ user_id: "alice" });
|
||||
await client.get("<memory_id>");
|
||||
|
||||
// Update
|
||||
await client.update("<memory_id>", { text: "Alice loves mountain hiking" });
|
||||
|
||||
// Delete
|
||||
await client.delete("<memory_id>");
|
||||
await client.deleteAll({ user_id: "alice" });
|
||||
```
|
||||
|
||||
Relevant docs: same as Platform Python.
|
||||
|
||||
### OSS - Python [OSS]
|
||||
|
||||
Import signature: `from mem0 import Memory`
|
||||
|
||||
```python
|
||||
from mem0 import Memory
|
||||
|
||||
m = Memory() # needs OPENAI_API_KEY; see components/ for custom providers
|
||||
|
||||
# Create
|
||||
m.add("I love hiking on weekends", user_id="alice")
|
||||
|
||||
# Read
|
||||
m.search("What does Alice like to do?", user_id="alice")
|
||||
m.get_all(user_id="alice")
|
||||
m.get(memory_id="<id>")
|
||||
|
||||
# Update
|
||||
m.update(memory_id="<id>", data="Alice loves mountain hiking")
|
||||
|
||||
# Delete
|
||||
m.delete(memory_id="<id>")
|
||||
m.delete_all(user_id="alice")
|
||||
```
|
||||
|
||||
Relevant docs: `open-source/*` plus provider pages under `## Optional`.
|
||||
|
||||
### OSS - Node [OSS]
|
||||
|
||||
Import signature: `import { Memory } from "mem0ai/oss"`
|
||||
|
||||
```ts
|
||||
import { Memory } from "mem0ai/oss";
|
||||
|
||||
const memory = new Memory();
|
||||
|
||||
// Create
|
||||
await memory.add("I love hiking on weekends", { userId: "alice" });
|
||||
|
||||
// Read
|
||||
await memory.search("What does Alice like to do?", { userId: "alice" });
|
||||
await memory.getAll({ userId: "alice" });
|
||||
await memory.get("<memory_id>");
|
||||
|
||||
// Update
|
||||
await memory.update("<memory_id>", "Alice loves mountain hiking");
|
||||
|
||||
// Delete
|
||||
await memory.delete("<memory_id>");
|
||||
await memory.deleteAll({ userId: "alice" });
|
||||
```
|
||||
|
||||
Relevant docs: same as OSS Python.
|
||||
|
||||
### Version Probes
|
||||
|
||||
Once you know which product, check the installed version - v2 vs v3 APIs differ in both OSS and Platform. Current published versions: Python `mem0ai` 2.x, TypeScript `mem0ai` 3.x, Node CLI `@mem0/cli` 0.2.x.
|
||||
|
||||
```bash
|
||||
pip show mem0ai | grep -i ^version
|
||||
npm list mem0ai --depth 0 2>/dev/null | grep mem0ai
|
||||
mem0 --version # Python or Node CLI, whichever is on PATH
|
||||
```
|
||||
|
||||
If the user is on a pre-current major (Python < 2, TS < 3, or Platform `output_format: "v1.1"`), route them through the matching migration guide in the Platform section before quoting current docs. If no Mem0 package is installed, recommend `pip install mem0ai` or `npm install mem0ai` and the corresponding quickstart above.
|
||||
|
||||
## Getting Started
|
||||
|
||||
- [Introduction](https://docs.mem0.ai/introduction): Overview of Mem0's memory layer for AI agents, including stateless vs stateful agents and how memory fits in the agent stack
|
||||
- [Platform Overview](https://docs.mem0.ai/platform/overview): Managed solution with 4-line integration, sub-50ms latency, and intuitive dashboard
|
||||
- [Vibe Code with Mem0](https://docs.mem0.ai/vibecoding): Single entry point for developers using AI coding tools (Claude Code, Cursor, Windsurf) with Mem0
|
||||
- [Mem0 MCP Server](https://docs.mem0.ai/platform/mem0-mcp): Model Context Protocol server for integrating Mem0 with AI coding assistants
|
||||
- [Platform vs Open Source](https://docs.mem0.ai/platform/platform-vs-oss): Compare managed platform vs self-hosted options
|
||||
- [Platform Quickstart](https://docs.mem0.ai/platform/quickstart): Get started with Mem0 Platform (managed) in minutes
|
||||
- [Open Source Overview](https://docs.mem0.ai/open-source/overview): Self-hosted solution with full infrastructure control and customization
|
||||
- [Open Source Python Quickstart](https://docs.mem0.ai/open-source/python-quickstart): Get started with Mem0 Open Source using Python
|
||||
- [Open Source Node.js Quickstart](https://docs.mem0.ai/open-source/node-quickstart): Get started with Mem0 Open Source using Node.js
|
||||
- [Introduction](https://docs.mem0.ai/introduction) [Both]: Use when the user wants a one-page overview of how memory fits between the LLM and the app.
|
||||
- [Vibe Code with Mem0](https://docs.mem0.ai/vibecoding) [Both]: Use when the user is in Claude Code, Cursor, or Windsurf and wants memory wired into their editor.
|
||||
- [Platform Overview](https://docs.mem0.ai/platform/overview) [Platform]: Use when the user picks the managed product - 4-line integration, sub-50ms retrieval, dashboard.
|
||||
- [Platform vs Open Source](https://docs.mem0.ai/platform/platform-vs-oss) [Both]: Use when the user is deciding between managed and self-hosted.
|
||||
- [Platform Quickstart](https://docs.mem0.ai/platform/quickstart) [Platform]: Use for the first Platform integration - API key plus `MemoryClient.add/search`.
|
||||
- [Platform CLI](https://docs.mem0.ai/platform/cli) [Platform]: Use when the user wants to manage Platform memories from the terminal.
|
||||
- [Mem0 MCP Server](https://docs.mem0.ai/platform/mem0-mcp) [Platform]: Use when connecting memory to AI coding tools over MCP.
|
||||
- [Open Source Overview](https://docs.mem0.ai/open-source/overview) [OSS]: Use when the user needs full infra control and custom provider wiring.
|
||||
- [Open Source Configuration](https://docs.mem0.ai/open-source/configuration) [OSS]: Use when configuring `Memory` - LLM, embedder, vector store, graph store.
|
||||
- [Open Source Python Quickstart](https://docs.mem0.ai/open-source/python-quickstart) [OSS]: Use for the first self-hosted Python integration.
|
||||
- [Open Source Node.js Quickstart](https://docs.mem0.ai/open-source/node-quickstart) [OSS]: Use for the first self-hosted Node integration.
|
||||
|
||||
## Core Concepts
|
||||
|
||||
- [Memory Types](https://docs.mem0.ai/core-concepts/memory-types): Working memory (short-term session awareness), factual memory (structured knowledge), episodic memory (past conversations), and semantic memory (general knowledge)
|
||||
- [Memory Operations - Add](https://docs.mem0.ai/core-concepts/memory-operations/add): How Mem0 processes conversations through information extraction, conflict resolution, and dual storage
|
||||
- [Memory Operations - Search](https://docs.mem0.ai/core-concepts/memory-operations/search): Retrieval of relevant memories using semantic search with query processing and result ranking
|
||||
- [Memory Operations - Update](https://docs.mem0.ai/core-concepts/memory-operations/update): Modifying existing memories when new information conflicts or supplements stored data
|
||||
- [Memory Operations - Delete](https://docs.mem0.ai/core-concepts/memory-operations/delete): Removing outdated or irrelevant memories to maintain memory quality
|
||||
- [Memory Types](https://docs.mem0.ai/core-concepts/memory-types) [Both]: Use when explaining working, factual, episodic, and semantic memory distinctions.
|
||||
- [Memory Operations - Add](https://docs.mem0.ai/core-concepts/memory-operations/add) [Both]: Use when explaining how `add()` extracts facts, resolves conflicts, and writes to both stores.
|
||||
- [Memory Operations - Search](https://docs.mem0.ai/core-concepts/memory-operations/search) [Both]: Use when explaining how queries are processed and ranked.
|
||||
- [Memory Operations - Update](https://docs.mem0.ai/core-concepts/memory-operations/update) [Both]: Use when memories need to be edited in place or reconciled against new info.
|
||||
- [Memory Operations - Delete](https://docs.mem0.ai/core-concepts/memory-operations/delete) [Both]: Use when outdated memories must be removed.
|
||||
- [Memory Evaluation](https://docs.mem0.ai/core-concepts/memory-evaluation) [Both]: Use when benchmarking memory quality or comparing against baselines.
|
||||
|
||||
## Platform Features
|
||||
## Platform
|
||||
|
||||
- [Platform Features Overview](https://docs.mem0.ai/platform/features/platform-overview): High-level overview of all Mem0 Platform capabilities
|
||||
- [Advanced Memory Operations](https://docs.mem0.ai/platform/advanced-memory-operations): Sophisticated memory management techniques for complex applications
|
||||
### Features - Essential
|
||||
- [Platform Features Overview](https://docs.mem0.ai/platform/features/platform-overview) [Platform]: Use when surveying what managed offers beyond CRUD.
|
||||
- [V2 Memory Filters](https://docs.mem0.ai/platform/features/v2-memory-filters) [Platform]: Use when compound filters (AND/OR on metadata, entity, time) are needed at search.
|
||||
- [Entity-Scoped Memory](https://docs.mem0.ai/platform/features/entity-scoped-memory) [Platform]: Use when partitioning memories by user, agent, app, or run.
|
||||
- [Async Client](https://docs.mem0.ai/platform/features/async-client) [Platform]: Use when the app issues many concurrent Mem0 calls and needs non-blocking I/O.
|
||||
- [Multimodal Support](https://docs.mem0.ai/platform/features/multimodal-support) [Platform]: Use when storing images or PDFs as memory input.
|
||||
- [Custom Categories](https://docs.mem0.ai/platform/features/custom-categories) [Platform]: Use when the default categories do not match the domain.
|
||||
|
||||
### Essential Features
|
||||
- [V2 Memory Filters](https://docs.mem0.ai/platform/features/v2-memory-filters): Advanced filtering and querying capabilities for memories
|
||||
- [Entity-Scoped Memory](https://docs.mem0.ai/platform/features/entity-scoped-memory): Organize memories by user, agent, app, and session identifiers
|
||||
- [Async Client](https://docs.mem0.ai/platform/features/async-client): Non-blocking operations for high-concurrency applications
|
||||
- [Async Mode Default Changes](https://docs.mem0.ai/platform/features/async-mode-default-change): Understanding new async behavior defaults
|
||||
- [Multimodal Support](https://docs.mem0.ai/platform/features/multimodal-support): Integration of images and documents (JPG, PNG, MDX, TXT, PDF) via URLs or Base64
|
||||
- [Custom Categories](https://docs.mem0.ai/platform/features/custom-categories): Define domain-specific categories to improve memory organization
|
||||
### Features - Advanced Retrieval
|
||||
- [Advanced Retrieval](https://docs.mem0.ai/platform/features/advanced-retrieval) [Platform]: Use when the user needs keyword search, reranking, or hybrid retrieval.
|
||||
- [Criteria-Based Retrieval](https://docs.mem0.ai/platform/features/criteria-retrieval) [Platform]: Use when targeting memories by custom criteria, not just semantic similarity.
|
||||
- [Contextual Add](https://docs.mem0.ai/platform/features/contextual-add) [Platform]: Use when `add()` should consider the surrounding conversation, not just the latest turn.
|
||||
- [Custom Instructions](https://docs.mem0.ai/platform/features/custom-instructions) [Platform]: Use when tailoring what Mem0 extracts and stores on Platform.
|
||||
- [Advanced Memory Operations](https://docs.mem0.ai/platform/advanced-memory-operations) [Platform]: Use when basic CRUD is not enough - batch ops, complex filters, workflows.
|
||||
|
||||
### Advanced Features
|
||||
- [Graph Threshold](https://docs.mem0.ai/platform/features/graph-threshold): Configure graph relationship sensitivity and strength
|
||||
- [Advanced Retrieval](https://docs.mem0.ai/platform/features/advanced-retrieval): Enhanced search with keyword search, reranking, and filtering capabilities
|
||||
- [Criteria-Based Retrieval](https://docs.mem0.ai/platform/features/criteria-retrieval): Targeted memory retrieval using custom criteria
|
||||
- [Contextual Add](https://docs.mem0.ai/platform/features/contextual-add): Add memories with enhanced context awareness
|
||||
- [Custom Instructions](https://docs.mem0.ai/platform/features/custom-instructions): Customize how Mem0 processes and stores information
|
||||
### Features - Data Management
|
||||
- [Direct Import](https://docs.mem0.ai/platform/features/direct-import) [Platform]: Use when seeding a Mem0 project from existing data.
|
||||
- [Memory Export](https://docs.mem0.ai/platform/features/memory-export) [Platform]: Use when exporting memories via a Pydantic schema.
|
||||
- [Timestamp Support](https://docs.mem0.ai/platform/features/timestamp) [Platform]: Use when temporal queries or time-based filtering matter.
|
||||
|
||||
### Data Management
|
||||
- [Direct Import](https://docs.mem0.ai/platform/features/direct-import): Bulk import existing data into Mem0 memory
|
||||
- [Memory Export](https://docs.mem0.ai/platform/features/memory-export): Export memories in structured formats using customizable Pydantic schemas
|
||||
- [Timestamp Support](https://docs.mem0.ai/platform/features/timestamp): Temporal memory management with time-based queries
|
||||
- [Expiration Dates](https://docs.mem0.ai/platform/features/expiration-date): Automatic memory cleanup with configurable expiration
|
||||
|
||||
### Integration Features
|
||||
- [Webhooks](https://docs.mem0.ai/platform/features/webhooks): Real-time notifications for memory events
|
||||
- [Feedback Mechanism](https://docs.mem0.ai/platform/features/feedback-mechanism): Improve memory quality through user feedback
|
||||
- [Group Chat Support](https://docs.mem0.ai/platform/features/group-chat): Multi-conversation memory management
|
||||
- [MCP Integration](https://docs.mem0.ai/platform/features/mcp-integration): Model Context Protocol integration for AI coding tools
|
||||
### Features - Integration & Ops
|
||||
- [Webhooks](https://docs.mem0.ai/platform/features/webhooks) [Platform]: Use when another system needs to react to memory changes in real time.
|
||||
- [Feedback Mechanism](https://docs.mem0.ai/platform/features/feedback-mechanism) [Platform]: Use when capturing user feedback to improve memory quality.
|
||||
- [Group Chat Support](https://docs.mem0.ai/platform/features/group-chat) [Platform]: Use when the conversation has multiple participants.
|
||||
- [MCP Integration](https://docs.mem0.ai/platform/features/mcp-integration) [Platform]: Use when wiring Mem0 into Claude/Cursor/other MCP clients.
|
||||
|
||||
### Support & Migration
|
||||
- [FAQs](https://docs.mem0.ai/platform/faqs): Frequently asked questions about Mem0 Platform
|
||||
- [Contribute Guide](https://docs.mem0.ai/platform/contribute): Contributing to Mem0 Platform development
|
||||
- [OSS to Platform Migration](https://docs.mem0.ai/migration/oss-to-platform): Guide for migrating from open-source to managed platform
|
||||
- [V0 to V1 Migration](https://docs.mem0.ai/migration/v0-to-v1): Upgrading from Mem0 v0 to v1
|
||||
- [Breaking Changes](https://docs.mem0.ai/migration/breaking-changes): List of breaking changes across versions
|
||||
- [API Changes](https://docs.mem0.ai/migration/api-changes): Detailed API changes and migration paths
|
||||
- [FAQs](https://docs.mem0.ai/platform/faqs) [Platform]: Use when answering common Platform questions.
|
||||
- [Contribute to Platform](https://docs.mem0.ai/platform/contribute) [Platform]: Use when a user wants to contribute to Platform docs or code.
|
||||
- [OSS to Platform Migration](https://docs.mem0.ai/migration/oss-to-platform) [Both]: Use when moving from self-hosted to managed.
|
||||
- [OSS v2 to v3 Migration](https://docs.mem0.ai/migration/oss-v2-to-v3) [OSS]: Use when upgrading a self-hosted deployment across major versions.
|
||||
- [Platform v2 to v3 Migration](https://docs.mem0.ai/migration/platform-v2-to-v3) [Platform]: Use when upgrading a Platform integration across major versions.
|
||||
- [API Changes](https://docs.mem0.ai/migration/api-changes) [Both]: Use when the upgrade involves API surface changes.
|
||||
- [Changelog](https://docs.mem0.ai/changelog/highlights) [Both]: Use when the user asks what shipped recently.
|
||||
|
||||
## Open Source
|
||||
|
||||
### Getting Started
|
||||
- [Python Quickstart](https://docs.mem0.ai/open-source/python-quickstart): Installation, configuration, and usage examples for Python SDK
|
||||
- [Node.js Quickstart](https://docs.mem0.ai/open-source/node-quickstart): Installation, configuration, and usage examples for Node.js SDK
|
||||
- [Configuration Guide](https://docs.mem0.ai/open-source/configuration): Complete configuration options for self-hosted deployment
|
||||
|
||||
### Open Source Features
|
||||
- [Features Overview](https://docs.mem0.ai/open-source/features/overview): Overview of all open-source features
|
||||
- [Metadata Filtering](https://docs.mem0.ai/open-source/features/metadata-filtering): Advanced filtering using custom metadata fields
|
||||
- [Reranker Search](https://docs.mem0.ai/open-source/features/reranker-search): Enhanced search results with reranking models
|
||||
- [Async Memory](https://docs.mem0.ai/open-source/features/async-memory): Asynchronous memory operations for better performance
|
||||
- [Multimodal Support](https://docs.mem0.ai/open-source/features/multimodal-support): Handle text, images, and documents in self-hosted setup
|
||||
- [Custom Instructions](https://docs.mem0.ai/open-source/features/custom-instructions): Tailor information extraction for specific use cases
|
||||
- [Custom Memory Update Prompt](https://docs.mem0.ai/open-source/features/custom-update-memory-prompt): Customize how memories are updated and merged
|
||||
- [REST API Server](https://docs.mem0.ai/open-source/features/rest-api): FastAPI-based server with core operations and OpenAPI documentation
|
||||
- [OpenAI Compatibility](https://docs.mem0.ai/open-source/features/openai_compatibility): Seamless integration with OpenAI-compatible APIs
|
||||
|
||||
## Components
|
||||
|
||||
### LLMs
|
||||
- [LLM Overview](https://docs.mem0.ai/components/llms/overview): Comprehensive guide to Large Language Model integration and configuration options
|
||||
- [LLM Configuration](https://docs.mem0.ai/components/llms/config): Configuration reference for LLM providers
|
||||
- [OpenAI](https://docs.mem0.ai/components/llms/models/openai): Integration with OpenAI models including GPT-4
|
||||
- [Anthropic](https://docs.mem0.ai/components/llms/models/anthropic): Claude model integration with advanced reasoning capabilities
|
||||
- [Azure OpenAI](https://docs.mem0.ai/components/llms/models/azure_openai): Microsoft Azure hosted OpenAI models for enterprise environments
|
||||
- [Ollama](https://docs.mem0.ai/components/llms/models/ollama): Local model deployment for privacy-focused applications
|
||||
- [Together](https://docs.mem0.ai/components/llms/models/together): Open-source model inference platform
|
||||
- [Groq](https://docs.mem0.ai/components/llms/models/groq): High-performance LPU optimized models for fast inference
|
||||
- [LiteLLM](https://docs.mem0.ai/components/llms/models/litellm): Unified LLM interface and proxy
|
||||
- [Mistral AI](https://docs.mem0.ai/components/llms/models/mistral_AI): Mistral model integration
|
||||
- [Google AI](https://docs.mem0.ai/components/llms/models/google_AI): Gemini model integration for multimodal applications
|
||||
- [AWS Bedrock](https://docs.mem0.ai/components/llms/models/aws_bedrock): Enterprise-grade AWS managed model integration
|
||||
- [DeepSeek](https://docs.mem0.ai/components/llms/models/deepseek): Advanced reasoning models
|
||||
- [MiniMax](https://docs.mem0.ai/components/llms/models/minimax): MiniMax model integration
|
||||
- [xAI](https://docs.mem0.ai/components/llms/models/xAI): xAI Grok models integration
|
||||
- [Sarvam](https://docs.mem0.ai/components/llms/models/sarvam): Indian language models
|
||||
- [LM Studio](https://docs.mem0.ai/components/llms/models/lmstudio): Local model management and deployment
|
||||
- [LangChain LLM](https://docs.mem0.ai/components/llms/models/langchain): LangChain LLM integration
|
||||
- [vLLM](https://docs.mem0.ai/components/llms/models/vllm): High-performance inference framework
|
||||
|
||||
### Vector Databases
|
||||
- [Vector Database Overview](https://docs.mem0.ai/components/vectordbs/overview): Guide to supported vector databases for semantic memory storage
|
||||
- [Vector Database Configuration](https://docs.mem0.ai/components/vectordbs/config): Configuration reference for vector database providers
|
||||
- [Qdrant](https://docs.mem0.ai/components/vectordbs/dbs/qdrant): High-performance vector similarity search engine
|
||||
- [Chroma](https://docs.mem0.ai/components/vectordbs/dbs/chroma): AI-native open-source vector database optimized for speed
|
||||
- [PGVector](https://docs.mem0.ai/components/vectordbs/dbs/pgvector): PostgreSQL extension for vector similarity search
|
||||
- [Milvus](https://docs.mem0.ai/components/vectordbs/dbs/milvus): Open-source vector database for AI applications at scale
|
||||
- [Pinecone](https://docs.mem0.ai/components/vectordbs/dbs/pinecone): Managed vector database with serverless and pod deployment options
|
||||
- [MongoDB](https://docs.mem0.ai/components/vectordbs/dbs/mongodb): Document database with vector search capabilities
|
||||
- [Azure AI Search](https://docs.mem0.ai/components/vectordbs/dbs/azure): Microsoft's enterprise search service
|
||||
- [Azure MySQL](https://docs.mem0.ai/components/vectordbs/dbs/azure_mysql): Azure Database for MySQL with vector search
|
||||
- [Redis](https://docs.mem0.ai/components/vectordbs/dbs/redis): Real-time vector storage and search with Redis Stack
|
||||
- [Valkey](https://docs.mem0.ai/components/vectordbs/dbs/valkey): Open-source Redis alternative with vector search
|
||||
- [Elasticsearch](https://docs.mem0.ai/components/vectordbs/dbs/elasticsearch): Distributed search and analytics engine
|
||||
- [OpenSearch](https://docs.mem0.ai/components/vectordbs/dbs/opensearch): Open-source search and analytics platform
|
||||
- [Supabase](https://docs.mem0.ai/components/vectordbs/dbs/supabase): Open-source Firebase alternative with vector support
|
||||
- [Upstash Vector](https://docs.mem0.ai/components/vectordbs/dbs/upstash-vector): Serverless vector database
|
||||
- [Vectorize](https://docs.mem0.ai/components/vectordbs/dbs/vectorize): Vectorize vector database integration
|
||||
- [Vertex AI Vector Search](https://docs.mem0.ai/components/vectordbs/dbs/vertex_ai): Google Cloud's vector search service
|
||||
- [Weaviate](https://docs.mem0.ai/components/vectordbs/dbs/weaviate): Open-source vector search engine with built-in ML capabilities
|
||||
- [FAISS](https://docs.mem0.ai/components/vectordbs/dbs/faiss): Facebook AI Similarity Search library
|
||||
- [LangChain Vector Store](https://docs.mem0.ai/components/vectordbs/dbs/langchain): LangChain vector store integration
|
||||
- [Baidu](https://docs.mem0.ai/components/vectordbs/dbs/baidu): Baidu vector database integration
|
||||
- [Cassandra](https://docs.mem0.ai/components/vectordbs/dbs/cassandra): Apache Cassandra with vector search capabilities
|
||||
- [S3 Vectors](https://docs.mem0.ai/components/vectordbs/dbs/s3_vectors): Amazon S3 Vectors integration
|
||||
- [Databricks](https://docs.mem0.ai/components/vectordbs/dbs/databricks): Delta Lake integration for vector search
|
||||
- [Neptune Analytics](https://docs.mem0.ai/components/vectordbs/dbs/neptune_analytics): AWS Neptune Analytics for graph and vector search
|
||||
- [Turbopuffer](https://docs.mem0.ai/components/vectordbs/dbs/turbopuffer): High-performance serverless vector database
|
||||
|
||||
### Embedding Models
|
||||
- [Embeddings Overview](https://docs.mem0.ai/components/embedders/overview): Embedding model configuration for semantic understanding
|
||||
- [Embeddings Configuration](https://docs.mem0.ai/components/embedders/config): Configuration reference for embedding providers
|
||||
- [OpenAI Embeddings](https://docs.mem0.ai/components/embedders/models/openai): High-quality text embeddings with customizable dimensions
|
||||
- [Azure OpenAI Embeddings](https://docs.mem0.ai/components/embedders/models/azure_openai): Enterprise Azure-hosted embedding models
|
||||
- [Ollama Embeddings](https://docs.mem0.ai/components/embedders/models/ollama): Local embedding models for privacy-focused applications
|
||||
- [Hugging Face Embeddings](https://docs.mem0.ai/components/embedders/models/huggingface): Open-source embedding models for local deployment
|
||||
- [Vertex AI Embeddings](https://docs.mem0.ai/components/embedders/models/vertexai): Google Cloud's enterprise embedding models
|
||||
- [Google AI Embeddings](https://docs.mem0.ai/components/embedders/models/google_AI): Gemini embedding models
|
||||
- [LM Studio Embeddings](https://docs.mem0.ai/components/embedders/models/lmstudio): Local model embeddings
|
||||
- [Together Embeddings](https://docs.mem0.ai/components/embedders/models/together): Open-source model embeddings
|
||||
- [LangChain Embeddings](https://docs.mem0.ai/components/embedders/models/langchain): LangChain embedder integration
|
||||
- [AWS Bedrock Embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock): Amazon embedding models through Bedrock
|
||||
|
||||
### Rerankers
|
||||
- [Reranker Overview](https://docs.mem0.ai/components/rerankers/overview): Guide to reranking models for improving search result quality
|
||||
- [Reranker Configuration](https://docs.mem0.ai/components/rerankers/config): Configuration reference for reranker providers
|
||||
- [Reranker Optimization](https://docs.mem0.ai/components/rerankers/optimization): Performance tuning and optimization strategies for rerankers
|
||||
- [Custom Reranker Prompts](https://docs.mem0.ai/components/rerankers/custom-prompts): Customize reranker behavior with custom prompts
|
||||
- [Cohere Reranker](https://docs.mem0.ai/components/rerankers/models/cohere): Cohere reranking model integration
|
||||
- [Sentence Transformer Reranker](https://docs.mem0.ai/components/rerankers/models/sentence_transformer): Cross-encoder reranking with sentence transformers
|
||||
- [Hugging Face Reranker](https://docs.mem0.ai/components/rerankers/models/huggingface): Hugging Face reranking models
|
||||
- [LLM Reranker](https://docs.mem0.ai/components/rerankers/models/llm_reranker): Use LLMs as rerankers for flexible relevance scoring
|
||||
- [Zero Entropy Reranker](https://docs.mem0.ai/components/rerankers/models/zero_entropy): Zero Entropy reranking model
|
||||
- [Open Source Features Overview](https://docs.mem0.ai/open-source/features/overview) [OSS]: Use when surveying OSS-only capabilities.
|
||||
- [Metadata Filtering](https://docs.mem0.ai/open-source/features/metadata-filtering) [OSS]: Use when filtering by custom metadata fields in self-hosted.
|
||||
- [Reranker Search](https://docs.mem0.ai/open-source/features/reranker-search) [OSS]: Use when improving OSS search quality with a reranker.
|
||||
- [Reranking](https://docs.mem0.ai/open-source/features/reranking) [OSS]: Use when configuring reranking end-to-end in OSS.
|
||||
- [Async Memory](https://docs.mem0.ai/open-source/features/async-memory) [OSS]: Use when the self-hosted app needs `AsyncMemory`.
|
||||
- [OSS Multimodal Support (features)](https://docs.mem0.ai/open-source/features/multimodal-support) [OSS]: Use when handling images and PDFs self-hosted (feature guide).
|
||||
- [OSS Multimodal Support](https://docs.mem0.ai/open-source/multimodal-support) [OSS]: Use when handling images and PDFs self-hosted (concept overview).
|
||||
- [Custom Instructions (OSS)](https://docs.mem0.ai/open-source/features/custom-instructions) [OSS]: Use when tailoring extraction prompts in OSS.
|
||||
- [REST API Server](https://docs.mem0.ai/open-source/features/rest-api) [OSS]: Use when exposing a self-hosted Mem0 as a FastAPI service.
|
||||
- [OpenAI Compatibility](https://docs.mem0.ai/open-source/features/openai_compatibility) [OSS]: Use when hitting an OpenAI-compatible endpoint with self-hosted.
|
||||
|
||||
## Integrations
|
||||
|
||||
- [Integrations Overview](https://docs.mem0.ai/integrations): Overview of all available Mem0 integrations
|
||||
- [Integrations Overview](https://docs.mem0.ai/integrations) [Both]: Use when surveying every available integration.
|
||||
|
||||
### Agent Frameworks
|
||||
- [LangChain](https://docs.mem0.ai/integrations/langchain): Seamless integration with LangChain framework for enhanced agent capabilities
|
||||
- [LangGraph](https://docs.mem0.ai/integrations/langgraph): Build stateful, multi-actor applications with persistent memory
|
||||
- [LlamaIndex](https://docs.mem0.ai/integrations/llama-index): Enhanced RAG applications with intelligent memory layer
|
||||
- [CrewAI](https://docs.mem0.ai/integrations/crewai): Multi-agent systems with shared and individual memory capabilities
|
||||
- [AutoGen](https://docs.mem0.ai/integrations/autogen): Microsoft's multi-agent conversation framework with memory
|
||||
- [Agno](https://docs.mem0.ai/integrations/agno): Agno framework integration with persistent memory
|
||||
- [Camel AI](https://docs.mem0.ai/integrations/camel-ai): Camel AI multi-agent framework with memory support
|
||||
- [OpenClaw](https://docs.mem0.ai/integrations/openclaw): OpenClaw framework integration
|
||||
- [OpenAI Agents SDK](https://docs.mem0.ai/integrations/openai-agents-sdk): OpenAI's agent framework with Mem0 memory
|
||||
- [Google AI ADK](https://docs.mem0.ai/integrations/google-ai-adk): Google AI Agent Development Kit with persistent memory
|
||||
- [Mastra](https://docs.mem0.ai/integrations/mastra): Mastra TypeScript agent framework integration
|
||||
- [Vercel AI SDK](https://docs.mem0.ai/integrations/vercel-ai-sdk): Build AI-powered web applications with persistent memory
|
||||
- [LangChain](https://docs.mem0.ai/integrations/langchain) [Both]: Use when the user is on LangChain.
|
||||
- [LangGraph](https://docs.mem0.ai/integrations/langgraph) [Both]: Use when building stateful multi-actor LangGraph apps.
|
||||
- [LangChain Tools](https://docs.mem0.ai/integrations/langchain-tools) [Both]: Use when Mem0 should be exposed as a LangChain tool.
|
||||
- [LlamaIndex](https://docs.mem0.ai/integrations/llama-index) [Both]: Use when layering memory on a LlamaIndex RAG app.
|
||||
- [CrewAI](https://docs.mem0.ai/integrations/crewai) [Both]: Use when building CrewAI multi-agent systems.
|
||||
- [AutoGen](https://docs.mem0.ai/integrations/autogen) [Both]: Use when the user is on Microsoft AutoGen.
|
||||
- [Agno](https://docs.mem0.ai/integrations/agno) [Both]: Use when the user is on Agno.
|
||||
- [Camel AI](https://docs.mem0.ai/integrations/camel-ai) [Both]: Use when the user is on Camel AI.
|
||||
- [ChatDev](https://docs.mem0.ai/integrations/chatdev) [Both]: Use when the user is on ChatDev.
|
||||
- [Hermes](https://docs.mem0.ai/integrations/hermes) [Both]: Use when the user is on Hermes.
|
||||
- [OpenAI Agents SDK](https://docs.mem0.ai/integrations/openai-agents-sdk) [Both]: Use when the user is on the OpenAI Agents SDK.
|
||||
- [Google AI ADK](https://docs.mem0.ai/integrations/google-ai-adk) [Both]: Use when the user is on Google's Agent Development Kit.
|
||||
- [Mastra](https://docs.mem0.ai/integrations/mastra) [Both]: Use when the user is on Mastra (TypeScript).
|
||||
- [OpenClaw](https://docs.mem0.ai/integrations/openclaw) [Both]: Use when wiring Mem0 into Claude Code or editors via OpenClaw.
|
||||
- [Vercel AI SDK](https://docs.mem0.ai/integrations/vercel-ai-sdk) [Both]: Use when the user is on the Vercel AI SDK.
|
||||
|
||||
### AI Coding Tools
|
||||
- [Claude Code](https://docs.mem0.ai/integrations/claude-code) [Both]: Use when wiring memory into Claude Code.
|
||||
- [Cursor](https://docs.mem0.ai/integrations/cursor) [Both]: Use when wiring memory into Cursor.
|
||||
- [Codex](https://docs.mem0.ai/integrations/codex) [Both]: Use when wiring memory into Codex / other editor assistants.
|
||||
|
||||
### Voice & Real-time
|
||||
- [LiveKit](https://docs.mem0.ai/integrations/livekit): Real-time voice and video AI with persistent memory
|
||||
- [Pipecat](https://docs.mem0.ai/integrations/pipecat): Voice AI pipeline framework with memory capabilities
|
||||
- [ElevenLabs](https://docs.mem0.ai/integrations/elevenlabs): Voice synthesis integration with conversational memory
|
||||
- [LiveKit](https://docs.mem0.ai/integrations/livekit) [Both]: Use when building real-time voice/video with memory.
|
||||
- [Pipecat](https://docs.mem0.ai/integrations/pipecat) [Both]: Use when the voice pipeline is Pipecat.
|
||||
- [ElevenLabs](https://docs.mem0.ai/integrations/elevenlabs) [Both]: Use when voice synthesis uses ElevenLabs.
|
||||
|
||||
### Cloud & Infrastructure
|
||||
- [AWS Bedrock](https://docs.mem0.ai/integrations/aws-bedrock): Enterprise AWS integration for managed AI services
|
||||
- [AWS Bedrock](https://docs.mem0.ai/integrations/aws-bedrock) [Both]: Use when the user is on AWS Bedrock managed AI services.
|
||||
|
||||
### Developer Tools
|
||||
- [Dify](https://docs.mem0.ai/integrations/dify): LLMOps platform integration for production AI applications
|
||||
- [Flowise](https://docs.mem0.ai/integrations/flowise): No-code LLM workflow builder with memory capabilities
|
||||
- [LangChain Tools](https://docs.mem0.ai/integrations/langchain-tools): Use Mem0 as a LangChain tool for agents
|
||||
- [AgentOps](https://docs.mem0.ai/integrations/agentops): Agent observability and monitoring with memory tracking
|
||||
- [Keywords AI](https://docs.mem0.ai/integrations/keywords): Keywords AI integration for LLM monitoring
|
||||
- [Raycast](https://docs.mem0.ai/integrations/raycast): Raycast extension for quick memory access
|
||||
- [Dify](https://docs.mem0.ai/integrations/dify) [Both]: Use when the user is on Dify LLMOps.
|
||||
- [Flowise](https://docs.mem0.ai/integrations/flowise) [Both]: Use when the user is on Flowise no-code.
|
||||
- [AgentOps](https://docs.mem0.ai/integrations/agentops) [Both]: Use when tracking agent observability with memory metadata.
|
||||
- [Keywords AI](https://docs.mem0.ai/integrations/keywords) [Both]: Use when monitoring with Keywords AI.
|
||||
- [Raycast](https://docs.mem0.ai/integrations/raycast) [Both]: Use when the user wants quick memory access via Raycast.
|
||||
|
||||
## Cookbooks and Examples
|
||||
## Cookbooks
|
||||
|
||||
- [Cookbooks Overview](https://docs.mem0.ai/cookbooks/overview): Complete guide to Mem0 examples and implementation patterns
|
||||
- [Cookbooks Overview](https://docs.mem0.ai/cookbooks/overview) [Both]: Use when surveying all reference examples.
|
||||
|
||||
### Essential Guides
|
||||
- [Building AI Companion](https://docs.mem0.ai/cookbooks/essentials/building-ai-companion): Core patterns for building AI agents with memory
|
||||
- [Partition Memories by Entity](https://docs.mem0.ai/cookbooks/essentials/entity-partitioning-playbook): Keep multi-tenant assistants isolated by tagging user, agent, app, and session identifiers
|
||||
- [Controlling Memory Ingestion](https://docs.mem0.ai/cookbooks/essentials/controlling-memory-ingestion): Fine-tune what gets stored in memory and when
|
||||
- [Memory Expiration](https://docs.mem0.ai/cookbooks/essentials/memory-expiration-short-and-long-term): Implement short-term and long-term memory strategies
|
||||
- [Tagging and Organizing Memories](https://docs.mem0.ai/cookbooks/essentials/tagging-and-organizing-memories): Advanced memory organization and categorization
|
||||
- [Exporting Memories](https://docs.mem0.ai/cookbooks/essentials/exporting-memories): Backup and transfer memory data between systems
|
||||
- [Choosing Memory Architecture](https://docs.mem0.ai/cookbooks/essentials/choosing-memory-architecture-vector-vs-graph): Vector vs Graph memory architectures comparison
|
||||
### Essentials
|
||||
- [Building an AI Companion](https://docs.mem0.ai/cookbooks/essentials/building-ai-companion) [Both]: Use when starting a companion app from scratch.
|
||||
- [Partition Memories by Entity](https://docs.mem0.ai/cookbooks/essentials/entity-partitioning-playbook) [Both]: Use when isolating multi-tenant memories.
|
||||
- [Controlling Memory Ingestion](https://docs.mem0.ai/cookbooks/essentials/controlling-memory-ingestion) [Both]: Use when deciding what to store and what to skip.
|
||||
- [Tagging and Organizing Memories](https://docs.mem0.ai/cookbooks/essentials/tagging-and-organizing-memories) [Both]: Use when memory taxonomy matters.
|
||||
- [Exporting Memories](https://docs.mem0.ai/cookbooks/essentials/exporting-memories) [Both]: Use when backing up or migrating memory data.
|
||||
|
||||
### AI Companion Examples
|
||||
- [Quickstart Demo](https://docs.mem0.ai/cookbooks/companions/quickstart-demo): Quick demo of building an AI companion with memory
|
||||
- [Node.js Companion](https://docs.mem0.ai/cookbooks/companions/nodejs-companion): JavaScript-based AI companion applications
|
||||
- [AI Tutor](https://docs.mem0.ai/cookbooks/companions/ai-tutor): Educational AI that adapts to learning progress
|
||||
- [Travel Assistant](https://docs.mem0.ai/cookbooks/companions/travel-assistant): Travel planning agent that learns preferences
|
||||
- [YouTube Research Assistant](https://docs.mem0.ai/cookbooks/companions/youtube-research): AI that researches and learns from video content
|
||||
- [Voice Companion](https://docs.mem0.ai/cookbooks/companions/voice-companion-openai): Voice-enabled AI with conversational memory
|
||||
- [Local Companion](https://docs.mem0.ai/cookbooks/companions/local-companion-ollama): Privacy-focused companion using local models
|
||||
### AI Companions
|
||||
- [Quickstart Demo](https://docs.mem0.ai/cookbooks/companions/quickstart-demo) [Both]: Use when showing the smallest end-to-end companion.
|
||||
- [Node.js Companion](https://docs.mem0.ai/cookbooks/companions/nodejs-companion) [Both]: Use when the companion is in JavaScript/TypeScript.
|
||||
- [AI Tutor](https://docs.mem0.ai/cookbooks/companions/ai-tutor) [Both]: Use when the agent adapts to a learner over time.
|
||||
- [Travel Assistant](https://docs.mem0.ai/cookbooks/companions/travel-assistant) [Both]: Use when the agent learns travel preferences.
|
||||
- [YouTube Research Assistant](https://docs.mem0.ai/cookbooks/companions/youtube-research) [Both]: Use when building an agent that ingests video content over sessions.
|
||||
- [Voice Companion (OpenAI)](https://docs.mem0.ai/cookbooks/companions/voice-companion-openai) [Both]: Use when the companion is voice-first with OpenAI Realtime.
|
||||
- [Local Companion (Ollama)](https://docs.mem0.ai/cookbooks/companions/local-companion-ollama) [OSS]: Use when the companion must run entirely on local models.
|
||||
|
||||
### Operations & Automation
|
||||
- [Support Inbox](https://docs.mem0.ai/cookbooks/operations/support-inbox): Customer service agents with conversation history
|
||||
- [Email Automation](https://docs.mem0.ai/cookbooks/operations/email-automation): Smart email processing with contextual memory
|
||||
- [Content Writing](https://docs.mem0.ai/cookbooks/operations/content-writing): AI writers that maintain brand voice and style
|
||||
- [Deep Research](https://docs.mem0.ai/cookbooks/operations/deep-research): Research assistants that build on previous findings
|
||||
- [Team Task Agent](https://docs.mem0.ai/cookbooks/operations/team-task-agent): Collaborative AI agents with shared project memory
|
||||
- [Support Inbox](https://docs.mem0.ai/cookbooks/operations/support-inbox) [Both]: Use when a support agent needs conversation history across tickets.
|
||||
- [Email Automation](https://docs.mem0.ai/cookbooks/operations/email-automation) [Both]: Use when processing email with contextual memory.
|
||||
- [Content Writing](https://docs.mem0.ai/cookbooks/operations/content-writing) [Both]: Use when an AI writer must maintain brand voice across sessions.
|
||||
- [Deep Research](https://docs.mem0.ai/cookbooks/operations/deep-research) [Both]: Use when research agents build on previous findings.
|
||||
- [Team Task Agent](https://docs.mem0.ai/cookbooks/operations/team-task-agent) [Both]: Use when collaborative agents share project memory.
|
||||
|
||||
### Integration Examples
|
||||
- [Agents SDK Tool](https://docs.mem0.ai/cookbooks/integrations/agents-sdk-tool): Using Mem0 as a tool with OpenAI Agents SDK
|
||||
- [OpenAI Tool Calls](https://docs.mem0.ai/cookbooks/integrations/openai-tool-calls): Mem0 integrated with OpenAI function calling
|
||||
- [Mastra Agent](https://docs.mem0.ai/cookbooks/integrations/mastra-agent): Mastra framework integration with memory
|
||||
- [Healthcare Google ADK](https://docs.mem0.ai/cookbooks/integrations/healthcare-google-adk): Medical AI applications with memory
|
||||
- [AWS Bedrock](https://docs.mem0.ai/cookbooks/integrations/aws-bedrock): Enterprise memory with AWS managed services
|
||||
- [Neptune Analytics](https://docs.mem0.ai/cookbooks/integrations/neptune-analytics): Graph and vector search with AWS Neptune
|
||||
- [Tavily Search](https://docs.mem0.ai/cookbooks/integrations/tavily-search): Web search with persistent memory of results
|
||||
- [Agents SDK Tool](https://docs.mem0.ai/cookbooks/integrations/agents-sdk-tool) [Platform]: Use when exposing Mem0 as a tool in OpenAI Agents SDK.
|
||||
- [OpenAI Tool Calls](https://docs.mem0.ai/cookbooks/integrations/openai-tool-calls) [Platform]: Use when hooking Mem0 into OpenAI function calling.
|
||||
- [Mastra Agent](https://docs.mem0.ai/cookbooks/integrations/mastra-agent) [Both]: Use when the agent is built in Mastra.
|
||||
- [Healthcare Google ADK](https://docs.mem0.ai/cookbooks/integrations/healthcare-google-adk) [Both]: Use when the domain is medical and the framework is Google ADK.
|
||||
- [AWS Bedrock](https://docs.mem0.ai/cookbooks/integrations/aws-bedrock) [Both]: Use when deploying with AWS managed model services.
|
||||
- [Tavily Search](https://docs.mem0.ai/cookbooks/integrations/tavily-search) [Both]: Use when the agent layers web search on memory.
|
||||
|
||||
### Framework Examples
|
||||
- [LlamaIndex React](https://docs.mem0.ai/cookbooks/frameworks/llamaindex-react): React applications with LlamaIndex and memory
|
||||
- [LlamaIndex Multiagent](https://docs.mem0.ai/cookbooks/frameworks/llamaindex-multiagent): Multi-agent systems with shared memory
|
||||
- [Multimodal Retrieval](https://docs.mem0.ai/cookbooks/frameworks/multimodal-retrieval): Memory systems handling text, images, and documents
|
||||
- [Eliza OS Character](https://docs.mem0.ai/cookbooks/frameworks/eliza-os-character): Character-based AI with persistent personality
|
||||
- [Gemini with Mem0 MCP](https://docs.mem0.ai/cookbooks/frameworks/gemini-3-with-mem0-mcp): Google Gemini integration using MCP server
|
||||
- [LlamaIndex React](https://docs.mem0.ai/cookbooks/frameworks/llamaindex-react) [Both]: Use when building a React UI with LlamaIndex and memory.
|
||||
- [LlamaIndex Multiagent](https://docs.mem0.ai/cookbooks/frameworks/llamaindex-multiagent) [Both]: Use when running LlamaIndex multi-agent systems with shared memory.
|
||||
- [Multimodal Retrieval](https://docs.mem0.ai/cookbooks/frameworks/multimodal-retrieval) [Both]: Use when memory must handle text, images, and docs together.
|
||||
- [Eliza OS Character](https://docs.mem0.ai/cookbooks/frameworks/eliza-os-character) [Both]: Use when building a character-based agent with persistent personality.
|
||||
- [Gemini with Mem0 MCP](https://docs.mem0.ai/cookbooks/frameworks/gemini-3-with-mem0-mcp) [Platform]: Use when Gemini connects to Mem0 over MCP.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [API Reference Overview](https://docs.mem0.ai/api-reference): REST API overview with authentication and quick start guide
|
||||
- [Organizations & Projects](https://docs.mem0.ai/api-reference/organizations-projects): Managing organizations and projects for multi-tenant setups
|
||||
All API Reference docs describe Mem0 Platform REST endpoints (requires API key).
|
||||
|
||||
### Core Memory APIs
|
||||
- [Add Memories](https://docs.mem0.ai/api-reference/memory/add-memories): REST API for storing new memories with detailed request/response formats
|
||||
- [Get All Memories](https://docs.mem0.ai/api-reference/memory/get-memories): Retrieve all memories with pagination and filtering options
|
||||
- [Search Memories](https://docs.mem0.ai/api-reference/memory/search-memories): Advanced search API with filtering and ranking capabilities
|
||||
- [Update Memory](https://docs.mem0.ai/api-reference/memory/update-memory): Modify existing memories with conflict resolution
|
||||
- [Delete Memory](https://docs.mem0.ai/api-reference/memory/delete-memory): Remove a specific memory by ID
|
||||
- [API Reference Overview](https://docs.mem0.ai/api-reference) [Platform]: Use when explaining authentication and the general request/response shape.
|
||||
- [Organizations & Projects](https://docs.mem0.ai/api-reference/organizations-projects) [Platform]: Use when the user needs multi-tenant isolation.
|
||||
|
||||
### Additional Memory APIs
|
||||
- [Create Memory Export](https://docs.mem0.ai/api-reference/memory/create-memory-export): Export memories in bulk
|
||||
- [Feedback](https://docs.mem0.ai/api-reference/memory/feedback): Submit feedback on memory quality
|
||||
- [Get Memory](https://docs.mem0.ai/api-reference/memory/get-memory): Retrieve a single memory by ID
|
||||
- [Memory History](https://docs.mem0.ai/api-reference/memory/history-memory): View the history of changes to a memory
|
||||
- [Get Memory Export](https://docs.mem0.ai/api-reference/memory/get-memory-export): Retrieve a previously created memory export
|
||||
- [Batch Update](https://docs.mem0.ai/api-reference/memory/batch-update): Update multiple memories in a single request
|
||||
- [Batch Delete](https://docs.mem0.ai/api-reference/memory/batch-delete): Delete multiple memories in a single request
|
||||
- [Delete All Memories](https://docs.mem0.ai/api-reference/memory/delete-memories): Remove all memories matching criteria
|
||||
### Core Memory
|
||||
- [Add Memories](https://docs.mem0.ai/api-reference/memory/add-memories) [Platform]: Use when writing one or more memories.
|
||||
- [Get All Memories](https://docs.mem0.ai/api-reference/memory/get-memories) [Platform]: Use when paginating memories for a user/agent.
|
||||
- [Get Memory](https://docs.mem0.ai/api-reference/memory/get-memory) [Platform]: Use when fetching one memory by ID.
|
||||
- [Search Memories](https://docs.mem0.ai/api-reference/memory/search-memories) [Platform]: Use when running a semantic query with filters.
|
||||
- [Update Memory](https://docs.mem0.ai/api-reference/memory/update-memory) [Platform]: Use when editing a memory in place.
|
||||
- [Delete Memory](https://docs.mem0.ai/api-reference/memory/delete-memory) [Platform]: Use when removing one memory.
|
||||
- [Delete All Memories](https://docs.mem0.ai/api-reference/memory/delete-memories) [Platform]: Use when purging memories matching a scope.
|
||||
- [Batch Update](https://docs.mem0.ai/api-reference/memory/batch-update) [Platform]: Use when updating many memories in one call.
|
||||
- [Batch Delete](https://docs.mem0.ai/api-reference/memory/batch-delete) [Platform]: Use when deleting many memories in one call.
|
||||
- [Memory History](https://docs.mem0.ai/api-reference/memory/history-memory) [Platform]: Use when the user needs the change log for a memory.
|
||||
- [Feedback](https://docs.mem0.ai/api-reference/memory/feedback) [Platform]: Use when capturing user signals on memory quality.
|
||||
- [Create Memory Export](https://docs.mem0.ai/api-reference/memory/create-memory-export) [Platform]: Use when kicking off an async export job.
|
||||
- [Get Memory Export](https://docs.mem0.ai/api-reference/memory/get-memory-export) [Platform]: Use when fetching the result of an export job.
|
||||
|
||||
### Events APIs
|
||||
- [Get Events](https://docs.mem0.ai/api-reference/events/get-events): List asynchronous memory operation events
|
||||
- [Get Event](https://docs.mem0.ai/api-reference/events/get-event): Retrieve details of a specific event
|
||||
### Events
|
||||
- [Get Events](https://docs.mem0.ai/api-reference/events/get-events) [Platform]: Use when listing async memory operation events.
|
||||
- [Get Event](https://docs.mem0.ai/api-reference/events/get-event) [Platform]: Use when fetching one event by ID.
|
||||
|
||||
### Entities APIs
|
||||
- [Get Users](https://docs.mem0.ai/api-reference/entities/get-users): List all entities (users, agents, apps)
|
||||
- [Delete User](https://docs.mem0.ai/api-reference/entities/delete-user): Remove an entity and all associated memories
|
||||
### Entities
|
||||
- [Get Users](https://docs.mem0.ai/api-reference/entities/get-users) [Platform]: Use when listing users, agents, or apps known to a project.
|
||||
- [Delete User](https://docs.mem0.ai/api-reference/entities/delete-user) [Platform]: Use when removing an entity and all its memories.
|
||||
|
||||
### Organizations APIs
|
||||
- [Create Organization](https://docs.mem0.ai/api-reference/organization/create-org): Create a new organization
|
||||
- [Get Organizations](https://docs.mem0.ai/api-reference/organization/get-orgs): List all organizations
|
||||
- [Get Organization](https://docs.mem0.ai/api-reference/organization/get-org): Retrieve organization details
|
||||
- [Get Organization Members](https://docs.mem0.ai/api-reference/organization/get-org-members): List organization members
|
||||
- [Add Organization Member](https://docs.mem0.ai/api-reference/organization/add-org-member): Add a member to an organization
|
||||
- [Delete Organization](https://docs.mem0.ai/api-reference/organization/delete-org): Remove an organization
|
||||
### Organizations
|
||||
- [Create Organization](https://docs.mem0.ai/api-reference/organization/create-org) [Platform]: Use when setting up a new org.
|
||||
- [Get Organizations](https://docs.mem0.ai/api-reference/organization/get-orgs) [Platform]: Use when listing orgs.
|
||||
- [Get Organization](https://docs.mem0.ai/api-reference/organization/get-org) [Platform]: Use when fetching one org.
|
||||
- [Get Organization Members](https://docs.mem0.ai/api-reference/organization/get-org-members) [Platform]: Use when listing org members.
|
||||
- [Add Organization Member](https://docs.mem0.ai/api-reference/organization/add-org-member) [Platform]: Use when inviting a member to an org.
|
||||
- [Delete Organization](https://docs.mem0.ai/api-reference/organization/delete-org) [Platform]: Use when removing an org.
|
||||
|
||||
### Project APIs
|
||||
- [Create Project](https://docs.mem0.ai/api-reference/project/create-project): Create a new project within an organization
|
||||
- [Get Projects](https://docs.mem0.ai/api-reference/project/get-projects): List all projects
|
||||
- [Get Project](https://docs.mem0.ai/api-reference/project/get-project): Retrieve project details
|
||||
- [Get Project Members](https://docs.mem0.ai/api-reference/project/get-project-members): List project members
|
||||
- [Add Project Member](https://docs.mem0.ai/api-reference/project/add-project-member): Add a member to a project
|
||||
- [Delete Project](https://docs.mem0.ai/api-reference/project/delete-project): Remove a project
|
||||
### Projects
|
||||
- [Create Project](https://docs.mem0.ai/api-reference/project/create-project) [Platform]: Use when creating a project inside an org.
|
||||
- [Get Projects](https://docs.mem0.ai/api-reference/project/get-projects) [Platform]: Use when listing projects.
|
||||
- [Get Project](https://docs.mem0.ai/api-reference/project/get-project) [Platform]: Use when fetching one project.
|
||||
- [Get Project Members](https://docs.mem0.ai/api-reference/project/get-project-members) [Platform]: Use when listing project members.
|
||||
- [Add Project Member](https://docs.mem0.ai/api-reference/project/add-project-member) [Platform]: Use when inviting a member to a project.
|
||||
- [Delete Project](https://docs.mem0.ai/api-reference/project/delete-project) [Platform]: Use when removing a project.
|
||||
|
||||
### Webhook APIs
|
||||
- [Create Webhook](https://docs.mem0.ai/api-reference/webhook/create-webhook): Register a new webhook endpoint
|
||||
- [Get Webhook](https://docs.mem0.ai/api-reference/webhook/get-webhook): Retrieve webhook configuration
|
||||
- [Update Webhook](https://docs.mem0.ai/api-reference/webhook/update-webhook): Modify webhook settings
|
||||
- [Delete Webhook](https://docs.mem0.ai/api-reference/webhook/delete-webhook): Remove a webhook
|
||||
### Webhooks
|
||||
- [Create Webhook](https://docs.mem0.ai/api-reference/webhook/create-webhook) [Platform]: Use when registering a webhook endpoint.
|
||||
- [Get Webhook](https://docs.mem0.ai/api-reference/webhook/get-webhook) [Platform]: Use when fetching webhook config.
|
||||
- [Update Webhook](https://docs.mem0.ai/api-reference/webhook/update-webhook) [Platform]: Use when modifying webhook settings.
|
||||
- [Delete Webhook](https://docs.mem0.ai/api-reference/webhook/delete-webhook) [Platform]: Use when removing a webhook.
|
||||
|
||||
## Skills & Plugins
|
||||
|
||||
Mem0 ships first-class integrations for AI coding editors and MCP-aware tools. When the user is in Claude Code, Cursor, Codex, or any MCP client, load this section first.
|
||||
|
||||
### Claude Code Skills (in-repo, not on docs.mem0.ai)
|
||||
|
||||
Source: https://github.com/mem0ai/mem0/tree/main/skills
|
||||
|
||||
- **skills/mem0** - Default Mem0 skill. Trigger on mentions of `MemoryClient`, "memory layer", personalization, or adding long-term memory to chatbots/agents. Covers Python SDK, TS SDK, and every framework integration.
|
||||
- **skills/mem0-cli** - Trigger on CLI / terminal / shell usage of Mem0.
|
||||
- **skills/mem0-vercel-ai-sdk** - Trigger when the stack includes `@mem0/vercel-ai-provider` or `createMem0`.
|
||||
|
||||
Each subdirectory is a Claude Code Skill (`SKILL.md` + supporting assets). Load only the one that matches the user's stack.
|
||||
|
||||
### Editor Plugin (shared glue)
|
||||
|
||||
Source: https://github.com/mem0ai/mem0/tree/main/mem0-plugin
|
||||
|
||||
The `mem0-plugin/` directory provides MCP server connection, lifecycle hooks, and skill bundling for Claude Code, Cursor, and Codex. It exposes 9 MCP tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`.
|
||||
|
||||
Editor-specific setup docs (already listed above under `## Integrations > AI Coding Tools`):
|
||||
|
||||
- `integrations/claude-code` [Both]
|
||||
- `integrations/cursor` [Both]
|
||||
- `integrations/codex` [Both]
|
||||
- `integrations/openclaw` [Both]
|
||||
|
||||
### MCP Endpoints
|
||||
|
||||
- Hosted MCP server: `https://mcp.mem0.ai` - requires Platform API key. See `platform/mem0-mcp`.
|
||||
- Self-hosted MCP server: ships with `openmemory/api/` (FastAPI) - runs against your own Qdrant + LLM stack.
|
||||
|
||||
## Community & Support
|
||||
|
||||
- [Contributing - Development](https://docs.mem0.ai/contributing/development): Guidelines for contributing to Mem0's open-source development
|
||||
- [Contributing - Documentation](https://docs.mem0.ai/contributing/documentation): Guidelines for contributing to Mem0's documentation
|
||||
- [Changelog](https://docs.mem0.ai/changelog): Detailed product updates and version history
|
||||
- [Contributing - Development](https://docs.mem0.ai/contributing/development) [Both]: Use when the user wants to contribute code.
|
||||
- [Contributing - Documentation](https://docs.mem0.ai/contributing/documentation) [Both]: Use when the user wants to contribute docs.
|
||||
|
||||
## Optional
|
||||
|
||||
Everything below is OSS-only provider configuration. Skip this entire section when the user is on Mem0 Platform (providers are managed server-side). When the user is self-hosting, load only the subsection that matches the provider they are configuring.
|
||||
|
||||
### LLM Providers [OSS]
|
||||
- [LLM Overview](https://docs.mem0.ai/components/llms/overview) [OSS]: Use when the user is choosing an LLM for memory extraction.
|
||||
- [LLM Configuration](https://docs.mem0.ai/components/llms/config) [OSS]: Use for the `llm` config schema.
|
||||
- [OpenAI](https://docs.mem0.ai/components/llms/models/openai) [OSS]: Use when the extraction LLM is OpenAI.
|
||||
- [Anthropic](https://docs.mem0.ai/components/llms/models/anthropic) [OSS]: Use when the extraction LLM is Claude.
|
||||
- [Azure OpenAI](https://docs.mem0.ai/components/llms/models/azure_openai) [OSS]: Use when the user is on Azure-hosted OpenAI.
|
||||
- [AWS Bedrock](https://docs.mem0.ai/components/llms/models/aws_bedrock) [OSS]: Use when the LLM runs through Bedrock.
|
||||
- [Google AI](https://docs.mem0.ai/components/llms/models/google_AI) [OSS]: Use when the LLM is Gemini.
|
||||
- [Groq](https://docs.mem0.ai/components/llms/models/groq) [OSS]: Use when the user wants Groq's low-latency inference.
|
||||
- [DeepSeek](https://docs.mem0.ai/components/llms/models/deepseek) [OSS]: Use when the LLM is DeepSeek.
|
||||
- [Mistral AI](https://docs.mem0.ai/components/llms/models/mistral_AI) [OSS]: Use when the LLM is Mistral.
|
||||
- [MiniMax](https://docs.mem0.ai/components/llms/models/minimax) [OSS]: Use when the LLM is MiniMax.
|
||||
- [xAI](https://docs.mem0.ai/components/llms/models/xAI) [OSS]: Use when the LLM is xAI Grok.
|
||||
- [Sarvam](https://docs.mem0.ai/components/llms/models/sarvam) [OSS]: Use for Indian-language Sarvam models.
|
||||
- [Together](https://docs.mem0.ai/components/llms/models/together) [OSS]: Use when the LLM runs on Together.
|
||||
- [Ollama](https://docs.mem0.ai/components/llms/models/ollama) [OSS]: Use when the LLM is a local Ollama model.
|
||||
- [LM Studio](https://docs.mem0.ai/components/llms/models/lmstudio) [OSS]: Use when the LLM is served from LM Studio.
|
||||
- [LiteLLM](https://docs.mem0.ai/components/llms/models/litellm) [OSS]: Use when multiplexing many providers behind LiteLLM.
|
||||
- [vLLM](https://docs.mem0.ai/components/llms/models/vllm) [OSS]: Use when self-hosting inference with vLLM.
|
||||
- [LangChain LLM](https://docs.mem0.ai/components/llms/models/langchain) [OSS]: Use when the LLM is wrapped behind a LangChain adapter.
|
||||
|
||||
### Embedding Providers [OSS]
|
||||
- [Embeddings Overview](https://docs.mem0.ai/components/embedders/overview) [OSS]: Use when choosing an embedding model.
|
||||
- [Embeddings Configuration](https://docs.mem0.ai/components/embedders/config) [OSS]: Use for the `embedder` config schema.
|
||||
- [OpenAI Embeddings](https://docs.mem0.ai/components/embedders/models/openai) [OSS]: Use when embeddings come from OpenAI.
|
||||
- [Azure OpenAI Embeddings](https://docs.mem0.ai/components/embedders/models/azure_openai) [OSS]: Use for Azure-hosted OpenAI embeddings.
|
||||
- [AWS Bedrock Embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock) [OSS]: Use for Bedrock-hosted embeddings.
|
||||
- [Google AI Embeddings](https://docs.mem0.ai/components/embedders/models/google_AI) [OSS]: Use for Gemini embeddings.
|
||||
- [Vertex AI Embeddings](https://docs.mem0.ai/components/embedders/models/vertexai) [OSS]: Use for Google Cloud Vertex AI embeddings.
|
||||
- [Hugging Face Embeddings](https://docs.mem0.ai/components/embedders/models/huggingface) [OSS]: Use for open-source HF embedding models.
|
||||
- [Ollama Embeddings](https://docs.mem0.ai/components/embedders/models/ollama) [OSS]: Use when embeddings run through local Ollama.
|
||||
- [LM Studio Embeddings](https://docs.mem0.ai/components/embedders/models/lmstudio) [OSS]: Use when embeddings run through LM Studio.
|
||||
- [Together Embeddings](https://docs.mem0.ai/components/embedders/models/together) [OSS]: Use when embeddings run on Together.
|
||||
- [LangChain Embeddings](https://docs.mem0.ai/components/embedders/models/langchain) [OSS]: Use when embeddings are wrapped behind a LangChain adapter.
|
||||
|
||||
### Vector Databases [OSS]
|
||||
- [Vector Database Overview](https://docs.mem0.ai/components/vectordbs/overview) [OSS]: Use when choosing a vector store.
|
||||
- [Vector Database Configuration](https://docs.mem0.ai/components/vectordbs/config) [OSS]: Use for the `vector_store` config schema.
|
||||
- [Qdrant](https://docs.mem0.ai/components/vectordbs/dbs/qdrant) [OSS]: Use as the default self-hosted vector store (best-tested).
|
||||
- [Chroma](https://docs.mem0.ai/components/vectordbs/dbs/chroma) [OSS]: Use when the user wants a lightweight embedded store.
|
||||
- [PGVector](https://docs.mem0.ai/components/vectordbs/dbs/pgvector) [OSS]: Use when Postgres is already in the stack.
|
||||
- [Milvus](https://docs.mem0.ai/components/vectordbs/dbs/milvus) [OSS]: Use for large-scale Milvus deployments.
|
||||
- [Pinecone](https://docs.mem0.ai/components/vectordbs/dbs/pinecone) [OSS]: Use when the user is on Pinecone managed.
|
||||
- [MongoDB](https://docs.mem0.ai/components/vectordbs/dbs/mongodb) [OSS]: Use when Mongo Atlas Vector Search is the backing store.
|
||||
- [Azure AI Search](https://docs.mem0.ai/components/vectordbs/dbs/azure) [OSS]: Use when the user is on Azure AI Search.
|
||||
- [Azure MySQL](https://docs.mem0.ai/components/vectordbs/dbs/azure_mysql) [OSS]: Use when vector search runs on Azure Database for MySQL.
|
||||
- [Redis](https://docs.mem0.ai/components/vectordbs/dbs/redis) [OSS]: Use when Redis Stack is the backing store.
|
||||
- [Valkey](https://docs.mem0.ai/components/vectordbs/dbs/valkey) [OSS]: Use when the user is on Valkey (Redis fork).
|
||||
- [Elasticsearch](https://docs.mem0.ai/components/vectordbs/dbs/elasticsearch) [OSS]: Use when Elasticsearch is the backing store.
|
||||
- [OpenSearch](https://docs.mem0.ai/components/vectordbs/dbs/opensearch) [OSS]: Use when OpenSearch is the backing store.
|
||||
- [Supabase](https://docs.mem0.ai/components/vectordbs/dbs/supabase) [OSS]: Use when Supabase with pgvector is the backing store.
|
||||
- [Upstash Vector](https://docs.mem0.ai/components/vectordbs/dbs/upstash-vector) [OSS]: Use for serverless Upstash Vector.
|
||||
- [Vectorize](https://docs.mem0.ai/components/vectordbs/dbs/vectorize) [OSS]: Use when the store is Cloudflare Vectorize.
|
||||
- [Vertex AI Vector Search](https://docs.mem0.ai/components/vectordbs/dbs/vertex_ai) [OSS]: Use when the store is Google Cloud Vertex Vector Search.
|
||||
- [Weaviate](https://docs.mem0.ai/components/vectordbs/dbs/weaviate) [OSS]: Use when Weaviate is the backing store.
|
||||
- [FAISS](https://docs.mem0.ai/components/vectordbs/dbs/faiss) [OSS]: Use for local FAISS-based similarity search.
|
||||
- [LangChain Vector Store](https://docs.mem0.ai/components/vectordbs/dbs/langchain) [OSS]: Use when the vector store is wrapped behind LangChain.
|
||||
- [Baidu](https://docs.mem0.ai/components/vectordbs/dbs/baidu) [OSS]: Use when the user is on Baidu Cloud vector service.
|
||||
- [Cassandra](https://docs.mem0.ai/components/vectordbs/dbs/cassandra) [OSS]: Use when Cassandra is the backing store.
|
||||
- [S3 Vectors](https://docs.mem0.ai/components/vectordbs/dbs/s3_vectors) [OSS]: Use for AWS S3 Vectors.
|
||||
- [Databricks](https://docs.mem0.ai/components/vectordbs/dbs/databricks) [OSS]: Use when the user is on Databricks with Delta Lake.
|
||||
- [Neptune Analytics](https://docs.mem0.ai/components/vectordbs/dbs/neptune_analytics) [OSS]: Use when the user is on AWS Neptune Analytics (graph + vector).
|
||||
- [Turbopuffer](https://docs.mem0.ai/components/vectordbs/dbs/turbopuffer) [OSS]: Use when the user is on Turbopuffer serverless.
|
||||
|
||||
### Rerankers [OSS]
|
||||
- [Reranker Overview](https://docs.mem0.ai/components/rerankers/overview) [OSS]: Use when the user wants to improve OSS search result quality.
|
||||
- [Reranker Configuration](https://docs.mem0.ai/components/rerankers/config) [OSS]: Use for the `reranker` config schema.
|
||||
- [Reranker Optimization](https://docs.mem0.ai/components/rerankers/optimization) [OSS]: Use when tuning reranker performance.
|
||||
- [Custom Reranker Prompts](https://docs.mem0.ai/components/rerankers/custom-prompts) [OSS]: Use when rewriting reranker prompts.
|
||||
- [Cohere Reranker](https://docs.mem0.ai/components/rerankers/models/cohere) [OSS]: Use for Cohere Rerank.
|
||||
- [Sentence Transformer Reranker](https://docs.mem0.ai/components/rerankers/models/sentence_transformer) [OSS]: Use for local cross-encoder rerankers.
|
||||
- [Hugging Face Reranker](https://docs.mem0.ai/components/rerankers/models/huggingface) [OSS]: Use for HF-hosted reranker models.
|
||||
- [LLM Reranker (prompt)](https://docs.mem0.ai/components/rerankers/models/llm) [OSS]: Use when the reranker is a prompted LLM (config guide).
|
||||
- [LLM Reranker](https://docs.mem0.ai/components/rerankers/models/llm_reranker) [OSS]: Use when the reranker is a prompted LLM (implementation reference).
|
||||
- [Zero Entropy Reranker](https://docs.mem0.ai/components/rerankers/models/zero_entropy) [OSS]: Use for the Zero Entropy reranker.
|
||||
|
||||
@@ -8,10 +8,6 @@ icon: "house"
|
||||
|
||||
Mem0 Open Source delivers the same adaptive memory engine as the platform, but packaged for teams that need to run everything on their own infrastructure. You own the stack, the data, and the customizations.
|
||||
|
||||
<Tip>
|
||||
Mem0 v1.0.0 brought rerankers, async-by-default clients, and Azure OpenAI support. See the <Link href="/changelog">release notes</Link> for the full rundown before upgrading.
|
||||
</Tip>
|
||||
|
||||
## What Mem0 OSS provides
|
||||
|
||||
- **Full control**: Tune every component, from LLMs to vector stores, inside your environment.
|
||||
|
||||
@@ -98,7 +98,7 @@ Learn how to search, update, and manage memories with full CRUD operations
|
||||
</Card>
|
||||
|
||||
<Card title="Advanced Features" icon="sparkles" href="/open-source/features/async-memory">
|
||||
Explore async support, graph memory, and multi-agent memory organization
|
||||
Explore async support and multi-agent memory organization
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
@@ -3,8 +3,6 @@ title: Group Chat
|
||||
description: 'Enable multi-participant conversations with automatic memory attribution to individual speakers'
|
||||
---
|
||||
|
||||
<Snippet file="paper-release.mdx" />
|
||||
|
||||
## Overview
|
||||
|
||||
The Group Chat feature enables Mem0 to process conversations involving multiple participants and automatically attribute memories to individual speakers. This allows for precise tracking of each participant's preferences, characteristics, and contributions in collaborative discussions, team meetings, or multi-agent conversations.
|
||||
|
||||
@@ -15,10 +15,6 @@ When working with large-scale memory stores, you need precise control over which
|
||||
* **Time-based queries**: Retrieve memories within specific date ranges
|
||||
* **Performance optimization**: Reduce query complexity by pre-filtering
|
||||
|
||||
<Callout type="info" icon="info-circle" color="#7A5DFF">
|
||||
Filters were introduced in v1.0.0 to provide precise control over memory retrieval.
|
||||
</Callout>
|
||||
|
||||
## Filter structure
|
||||
|
||||
Filters use a nested JSON structure with logical operators at the root:
|
||||
|
||||
@@ -8,10 +8,6 @@ icon: "cloud"
|
||||
|
||||
Mem0 is the memory engine that keeps conversations contextual so users never repeat themselves and your agents respond with continuity. Mem0 Platform delivers that experience as a fully managed service—scaling, securing, and enriching memories without any infrastructure work on your side.
|
||||
|
||||
<Tip>
|
||||
Mem0 v1.0.0 shipped rerankers, async-by-default behavior, and Azure OpenAI support. Catch the full list of changes in the <Link href="/changelog">release notes</Link>.
|
||||
</Tip>
|
||||
|
||||
## Why it matters
|
||||
|
||||
- **Personalized replies**: Memories persist across users and agents, cutting prompt bloat and repeat questions.
|
||||
|
||||
@@ -18,7 +18,7 @@ module.exports = {
|
||||
moduleNameMapper: {
|
||||
"^@/(.*)$": "<rootDir>/src/$1",
|
||||
},
|
||||
setupFiles: ["dotenv/config"],
|
||||
setupFiles: ["dotenv/config", "<rootDir>/jest.setup.ts"],
|
||||
testPathIgnorePatterns: ["/node_modules/", "/dist/"],
|
||||
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
|
||||
globals: {
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
import pkg from "./package.json";
|
||||
|
||||
(globalThis as any).__MEM0_SDK_VERSION__ = pkg.version;
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mem0ai",
|
||||
"version": "3.0.0",
|
||||
"version": "3.0.1",
|
||||
"description": "The Memory Layer For Your AI Apps",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @ts-nocheck
|
||||
import type { TelemetryClient, TelemetryOptions } from "./telemetry.types";
|
||||
|
||||
let version = "2.1.36";
|
||||
let version = __MEM0_SDK_VERSION__;
|
||||
|
||||
// Safely check for process.env in different environments
|
||||
let MEM0_TELEMETRY = true;
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
declare const __MEM0_SDK_VERSION__: string;
|
||||
@@ -4,7 +4,7 @@ import type {
|
||||
TelemetryEventData,
|
||||
} from "./telemetry.types";
|
||||
|
||||
let version = "2.1.34";
|
||||
let version = __MEM0_SDK_VERSION__;
|
||||
|
||||
// Safely check for process.env in different environments
|
||||
let MEM0_TELEMETRY = true;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { defineConfig } from "tsup";
|
||||
import pkg from "./package.json";
|
||||
|
||||
const external = [
|
||||
"openai",
|
||||
@@ -23,6 +24,10 @@ const external = [
|
||||
"natural",
|
||||
];
|
||||
|
||||
const define = {
|
||||
__MEM0_SDK_VERSION__: JSON.stringify(pkg.version),
|
||||
};
|
||||
|
||||
export default defineConfig([
|
||||
{
|
||||
entry: ["src/client/index.ts"],
|
||||
@@ -30,6 +35,7 @@ export default defineConfig([
|
||||
dts: true,
|
||||
sourcemap: true,
|
||||
external,
|
||||
define,
|
||||
},
|
||||
{
|
||||
entry: ["src/oss/src/index.ts"],
|
||||
@@ -38,5 +44,6 @@ export default defineConfig([
|
||||
dts: true,
|
||||
sourcemap: true,
|
||||
external,
|
||||
define,
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -13,7 +13,10 @@ class FastEmbedEmbedding(EmbeddingBase):
|
||||
super().__init__(config)
|
||||
|
||||
self.config.model = self.config.model or "thenlper/gte-large"
|
||||
self.dense_model = TextEmbedding(model_name = self.config.model)
|
||||
self.dense_model = TextEmbedding(model_name=self.config.model)
|
||||
|
||||
if not self.config.embedding_dims:
|
||||
self.config.embedding_dims = self.dense_model.embedding_size
|
||||
|
||||
def embed(self, text, memory_action: Optional[Literal["add", "search", "update"]] = None):
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check docs/llms.txt coverage against docs/**/*.mdx.
|
||||
|
||||
Two-way diff:
|
||||
- pages present in docs/ but not linked in docs/llms.txt -> "missing"
|
||||
- URLs linked in docs/llms.txt that point to no page -> "stale"
|
||||
|
||||
Modes:
|
||||
default read-only; exits 1 if any drift is found.
|
||||
--write appends placeholder entries for missing pages under a
|
||||
"## Unclassified - needs triage" H2 at the end of
|
||||
docs/llms.txt. Stale URLs are reported but never removed
|
||||
automatically (human decides whether a page was renamed
|
||||
or genuinely deleted). Exits 1 if anything was written,
|
||||
0 if the file was already in sync.
|
||||
|
||||
Exit codes:
|
||||
0 in sync, or --write mode completed (workflow continues to open a PR)
|
||||
1 read-only drift detected
|
||||
|
||||
The script has no third-party dependencies; stdlib only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
DOCS_DIR = REPO_ROOT / "docs"
|
||||
LLMS_TXT = DOCS_DIR / "llms.txt"
|
||||
IGNORE_FILE = REPO_ROOT / "scripts" / "llms-txt-ignore.txt"
|
||||
|
||||
BASE_URL = "https://docs.mem0.ai/"
|
||||
TRIAGE_HEADER = "## Unclassified - needs triage"
|
||||
URL_RE = re.compile(r"\(https://docs\.mem0\.ai/([^)\s#]*)")
|
||||
|
||||
|
||||
def load_ignore_prefixes() -> list[str]:
|
||||
if not IGNORE_FILE.exists():
|
||||
return []
|
||||
prefixes: list[str] = []
|
||||
for raw in IGNORE_FILE.read_text().splitlines():
|
||||
line = raw.strip()
|
||||
if line and not line.startswith("#"):
|
||||
prefixes.append(line)
|
||||
return prefixes
|
||||
|
||||
|
||||
def canonical_repo_pages(ignore_prefixes: list[str]) -> tuple[set[str], set[str]]:
|
||||
all_pages: set[str] = set()
|
||||
included_pages: set[str] = set()
|
||||
for path in DOCS_DIR.rglob("*.mdx"):
|
||||
rel = path.relative_to(DOCS_DIR).with_suffix("").as_posix()
|
||||
all_pages.add(rel)
|
||||
if not any(rel.startswith(p) for p in ignore_prefixes):
|
||||
included_pages.add(rel)
|
||||
return all_pages, included_pages
|
||||
|
||||
|
||||
def indexed_urls(text: str) -> set[str]:
|
||||
urls: set[str] = set()
|
||||
for match in URL_RE.finditer(text):
|
||||
path = match.group(1).rstrip("/")
|
||||
if path:
|
||||
urls.add(path)
|
||||
return urls
|
||||
|
||||
|
||||
def format_placeholder(page: str) -> str:
|
||||
title = page.rsplit("/", 1)[-1].replace("-", " ").replace("_", " ").title()
|
||||
return (
|
||||
f"- [{title}]({BASE_URL}{page}) [TODO: Platform|OSS|Both]: "
|
||||
"TODO - rewrite as 'Use when ...' and move into the correct section."
|
||||
)
|
||||
|
||||
|
||||
def append_triage_block(text: str, missing_pages: list[str]) -> str:
|
||||
entries = "\n".join(format_placeholder(p) for p in missing_pages)
|
||||
if TRIAGE_HEADER in text:
|
||||
return text.rstrip() + "\n" + entries + "\n"
|
||||
preamble = (
|
||||
"> New docs pages were detected by CI. For each entry below: replace "
|
||||
"the scope tag with `[Platform]`, `[OSS]`, or `[Both]`; rewrite the "
|
||||
"description as `Use when ...`; move it into the correct section; "
|
||||
"then delete this H2 once empty.\n"
|
||||
)
|
||||
return text.rstrip() + "\n\n" + TRIAGE_HEADER + "\n\n" + preamble + "\n" + entries + "\n"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--write",
|
||||
action="store_true",
|
||||
help="scaffold placeholder entries in docs/llms.txt for missing pages",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if not LLMS_TXT.exists():
|
||||
print(f"ERROR: {LLMS_TXT} not found.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
ignore_prefixes = load_ignore_prefixes()
|
||||
all_pages, included_pages = canonical_repo_pages(ignore_prefixes)
|
||||
text = LLMS_TXT.read_text()
|
||||
linked = indexed_urls(text)
|
||||
|
||||
missing = sorted(included_pages - linked)
|
||||
stale = sorted(linked - all_pages)
|
||||
|
||||
if missing:
|
||||
print(f"Pages missing from docs/llms.txt ({len(missing)}):")
|
||||
for p in missing:
|
||||
print(f" + {p}")
|
||||
if stale:
|
||||
print(f"\nURLs in docs/llms.txt with no matching .mdx page ({len(stale)}):")
|
||||
for p in stale:
|
||||
print(f" - {p}")
|
||||
print(
|
||||
"\n(Stale URLs are never auto-removed: check whether the page was "
|
||||
"renamed, and update the link by hand.)"
|
||||
)
|
||||
|
||||
if not missing and not stale:
|
||||
print("docs/llms.txt is in sync with docs/**/*.mdx.")
|
||||
return 0
|
||||
|
||||
if args.write:
|
||||
if missing:
|
||||
new_text = append_triage_block(text, missing)
|
||||
LLMS_TXT.write_text(new_text)
|
||||
print(
|
||||
f"\nAppended {len(missing)} placeholder entries under "
|
||||
f"'{TRIAGE_HEADER}' in docs/llms.txt."
|
||||
)
|
||||
else:
|
||||
print("\nNo additions to scaffold; stale URLs surfaced above require manual cleanup.")
|
||||
return 0
|
||||
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,11 @@
|
||||
# Page path prefixes (relative to docs/, without .mdx) that intentionally
|
||||
# stay out of docs/llms.txt. One prefix per line. Lines starting with '#'
|
||||
# are comments.
|
||||
#
|
||||
# Why each prefix is here:
|
||||
# _snippets/ — reusable MDX fragments, not standalone pages
|
||||
# templates/ — authoring templates for new docs, not user-facing
|
||||
# changelog/ — versioned release notes; one rollup link lives in the index
|
||||
_snippets/
|
||||
templates/
|
||||
changelog/
|
||||
@@ -12,7 +12,7 @@ description: >
|
||||
license: Apache-2.0
|
||||
metadata:
|
||||
author: mem0ai
|
||||
version: "1.0.0"
|
||||
version: "1.1.0"
|
||||
category: ai-memory
|
||||
tags: "cli, terminal, memory, ai, command-line"
|
||||
compatibility: Node.js 18+ (npm install -g @mem0/cli) or Python 3.10+ (pip install mem0-cli), MEM0_API_KEY env var
|
||||
@@ -134,7 +134,6 @@ Choose whichever runtime you already have installed. The behavior is the same.
|
||||
- **`--all` vs `--entity` delete modes:** `mem0 delete --all -u alice` deletes all memories for user alice. `mem0 delete --entity -u alice` deletes the entity itself AND all its memories (cascade). These are mutually exclusive modes.
|
||||
- **Entity ID resolution:** If you pass any explicit scope flag (e.g. `--user-id`), the CLI uses ONLY the explicit IDs and ignores config defaults. If no scope flags are given, all configured defaults apply.
|
||||
- **Stdin detection:** When no text argument is provided and input is piped (not a TTY), the CLI reads from stdin. Works with `add`, `search`, and `update`.
|
||||
- **Graph tri-state:** `--no-graph` takes precedence over `--graph`, which takes precedence over the config default (`defaults.enable_graph`).
|
||||
|
||||
## References
|
||||
|
||||
|
||||
@@ -77,12 +77,8 @@ Add a memory from text, messages, file, or stdin.
|
||||
| `--messages <json>` | string | - | Conversation messages as JSON array (e.g. `'[{"role":"user","content":"..."}]'`). |
|
||||
| `-f, --file <path>` | path | - | Read messages from a JSON file. |
|
||||
| `-m, --metadata <json>` | string | - | Custom metadata as JSON object (e.g. `'{"source":"cli"}'`). |
|
||||
| `--immutable` | boolean | false | Prevent future updates to this memory. |
|
||||
| `--no-infer` | boolean | false | Skip inference; store the text verbatim. |
|
||||
| `--expires <date>` | string | - | Expiration date in `YYYY-MM-DD` format. |
|
||||
| `--categories <cats>` | string | - | Categories as JSON array or comma-separated string. |
|
||||
| `--graph` | boolean | false | Enable graph memory extraction for this call. |
|
||||
| `--no-graph` | boolean | false | Disable graph memory extraction for this call. |
|
||||
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`, `quiet`. |
|
||||
|
||||
**Input priority:** `--file` > `--messages` > text argument > stdin (if piped and no text).
|
||||
@@ -134,13 +130,10 @@ Search memories by semantic query.
|
||||
| `--app-id <id>` | string | - | Filter by app. |
|
||||
| `--run-id <id>` | string | - | Filter by run. |
|
||||
| `-k, --top-k, --limit <n>` | integer | 10 | Maximum number of results to return. |
|
||||
| `--threshold <score>` | float | 0.3 | Minimum similarity score (0.0 to 1.0). |
|
||||
| `--threshold <score>` | float | 0.1 | Minimum similarity score (0.0 to 1.0). |
|
||||
| `--rerank` | boolean | false | Enable reranking for improved relevance (Platform only). |
|
||||
| `--keyword` | boolean | false | Use keyword search instead of semantic. |
|
||||
| `--filter <json>` | string | - | Advanced filter expression as JSON (AND/OR operators). |
|
||||
| `--fields <list>` | string | - | Comma-separated list of fields to return. |
|
||||
| `--graph` | boolean | false | Enable graph in search. |
|
||||
| `--no-graph` | boolean | false | Disable graph in search. |
|
||||
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`, `table`. |
|
||||
|
||||
**Examples:**
|
||||
@@ -200,8 +193,6 @@ List memories with optional filters and pagination.
|
||||
| `--category <name>` | string | - | Filter by category. |
|
||||
| `--after <date>` | string | - | Created after (YYYY-MM-DD). |
|
||||
| `--before <date>` | string | - | Created before (YYYY-MM-DD). |
|
||||
| `--graph` | boolean | false | Enable graph in listing. |
|
||||
| `--no-graph` | boolean | false | Disable graph in listing. |
|
||||
| `-o, --output <fmt>` | string | `table` | Output format: `text`, `json`, `table`. |
|
||||
|
||||
**Examples:**
|
||||
@@ -373,7 +364,7 @@ Get a single configuration value.
|
||||
|------|------|----------|-------------|
|
||||
| `key` | string | Yes | Dotted config key (e.g. `platform.api_key`, `defaults.user_id`). |
|
||||
|
||||
**Valid keys:** `platform.api_key`, `platform.base_url`, `defaults.user_id`, `defaults.agent_id`, `defaults.app_id`, `defaults.run_id`, `defaults.enable_graph`.
|
||||
**Valid keys:** `platform.api_key`, `platform.base_url`, `defaults.user_id`, `defaults.agent_id`, `defaults.app_id`, `defaults.run_id`.
|
||||
|
||||
API key values are always redacted in output.
|
||||
|
||||
@@ -404,7 +395,6 @@ Set a configuration value.
|
||||
```bash
|
||||
mem0 config set defaults.user_id alice
|
||||
mem0 config set platform.base_url https://api.mem0.ai
|
||||
mem0 config set defaults.enable_graph true
|
||||
```
|
||||
|
||||
---
|
||||
@@ -638,20 +628,6 @@ This applies to commands with `resolveIds: true`: `add`, `search`, `list`, `dele
|
||||
|
||||
---
|
||||
|
||||
## Graph Tri-State
|
||||
|
||||
The `enable_graph` parameter follows a three-level precedence:
|
||||
|
||||
```
|
||||
--no-graph (explicit disable) > --graph (explicit enable) > config default
|
||||
```
|
||||
|
||||
If `--no-graph` is passed, graph is disabled regardless of other settings. If `--graph` is passed (without `--no-graph`), graph is enabled. If neither is passed, the config value `defaults.enable_graph` is used.
|
||||
|
||||
This applies to commands with `resolveGraph: true`: `add`, `search`, `list`.
|
||||
|
||||
---
|
||||
|
||||
## Filter Building
|
||||
|
||||
For `search` and `list`, entity IDs and additional filters are composed into the API filter structure:
|
||||
|
||||
@@ -24,8 +24,7 @@ The restricted permissions ensure API keys are not world-readable.
|
||||
"user_id": "",
|
||||
"agent_id": "",
|
||||
"app_id": "",
|
||||
"run_id": "",
|
||||
"enable_graph": false
|
||||
"run_id": ""
|
||||
},
|
||||
"platform": {
|
||||
"api_key": "",
|
||||
@@ -43,7 +42,6 @@ The restricted permissions ensure API keys are not world-readable.
|
||||
| `defaults.agent_id` | string | `""` | Default agent ID for scoping commands. |
|
||||
| `defaults.app_id` | string | `""` | Default app ID for scoping commands. |
|
||||
| `defaults.run_id` | string | `""` | Default run ID for scoping commands. |
|
||||
| `defaults.enable_graph` | boolean | `false` | Default graph memory extraction toggle. |
|
||||
| `platform.api_key` | string | `""` | API key for the Mem0 Platform. |
|
||||
| `platform.base_url` | string | `"https://api.mem0.ai"` | Base URL for API requests. |
|
||||
|
||||
@@ -127,7 +125,6 @@ Reads a single configuration value. The key uses dotted notation.
|
||||
```bash
|
||||
mem0 config get platform.api_key # prints: m0-x...xxxx (redacted)
|
||||
mem0 config get defaults.user_id # prints: alice
|
||||
mem0 config get defaults.enable_graph # prints: false
|
||||
```
|
||||
|
||||
**Valid keys:**
|
||||
@@ -137,7 +134,6 @@ mem0 config get defaults.enable_graph # prints: false
|
||||
- `defaults.agent_id`
|
||||
- `defaults.app_id`
|
||||
- `defaults.run_id`
|
||||
- `defaults.enable_graph`
|
||||
|
||||
Unknown keys print an error message.
|
||||
|
||||
@@ -148,7 +144,6 @@ Sets a configuration value and saves the config file.
|
||||
```bash
|
||||
mem0 config set defaults.user_id alice
|
||||
mem0 config set platform.base_url https://api.mem0.ai
|
||||
mem0 config set defaults.enable_graph true
|
||||
```
|
||||
|
||||
**Type coercion:**
|
||||
@@ -178,20 +173,6 @@ Environment variables override config file values but are overridden by CLI flag
|
||||
| `MEM0_AGENT_ID` | `defaults.agent_id` | string | `""` |
|
||||
| `MEM0_APP_ID` | `defaults.app_id` | string | `""` |
|
||||
| `MEM0_RUN_ID` | `defaults.run_id` | string | `""` |
|
||||
| `MEM0_ENABLE_GRAPH` | `defaults.enable_graph` | boolean | `false` |
|
||||
|
||||
### Boolean Parsing for `MEM0_ENABLE_GRAPH`
|
||||
|
||||
Accepted truthy values (case-insensitive): `"true"`, `"1"`, `"yes"`. Everything else is treated as `false`.
|
||||
|
||||
```bash
|
||||
export MEM0_ENABLE_GRAPH=true # enabled
|
||||
export MEM0_ENABLE_GRAPH=1 # enabled
|
||||
export MEM0_ENABLE_GRAPH=yes # enabled
|
||||
export MEM0_ENABLE_GRAPH=false # disabled
|
||||
export MEM0_ENABLE_GRAPH=0 # disabled
|
||||
export MEM0_ENABLE_GRAPH="" # disabled
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -200,8 +181,8 @@ export MEM0_ENABLE_GRAPH="" # disabled
|
||||
Configuration values are resolved in this order (highest priority first):
|
||||
|
||||
```
|
||||
1. CLI flags --api-key, --user-id, --base-url, --graph, --no-graph, etc.
|
||||
2. Environment vars MEM0_API_KEY, MEM0_USER_ID, MEM0_ENABLE_GRAPH, etc.
|
||||
1. CLI flags --api-key, --user-id, --base-url, etc.
|
||||
2. Environment vars MEM0_API_KEY, MEM0_USER_ID, etc.
|
||||
3. Config file ~/.mem0/config.json
|
||||
4. Defaults Hardcoded defaults (empty strings, false, https://api.mem0.ai)
|
||||
```
|
||||
@@ -241,4 +222,3 @@ The `config get` and `config set` commands use dotted key paths. Here is the ful
|
||||
| `defaults.agent_id` | defaults | agent_id |
|
||||
| `defaults.app_id` | defaults | app_id |
|
||||
| `defaults.run_id` | defaults | run_id |
|
||||
| `defaults.enable_graph` | defaults | enable_graph |
|
||||
|
||||
@@ -12,7 +12,7 @@ description: >
|
||||
license: Apache-2.0
|
||||
metadata:
|
||||
author: mem0ai
|
||||
version: "1.0.0"
|
||||
version: "1.1.0"
|
||||
category: ai-memory
|
||||
tags: "vercel, ai-sdk, memory, nextjs, typescript, provider"
|
||||
compatibility: Node.js 18+, npm install @mem0/vercel-ai-provider, Vercel AI SDK v5 (ai package), MEM0_API_KEY + LLM provider API key
|
||||
@@ -47,16 +47,16 @@ import { createMem0 } from "@mem0/vercel-ai-provider";
|
||||
|
||||
const mem0 = createMem0();
|
||||
const { text } = await generateText({
|
||||
model: mem0("gpt-4-turbo", { user_id: "alice" }),
|
||||
model: mem0("gpt-5-mini", { user_id: "alice" }),
|
||||
prompt: "Recommend a restaurant",
|
||||
});
|
||||
```
|
||||
|
||||
What happens under the hood:
|
||||
1. The prompt is sent to Mem0 search (`POST /v2/memories/search/`) to retrieve relevant memories
|
||||
1. The prompt is sent to Mem0 search (`POST /v3/memories/search/`) to retrieve relevant memories
|
||||
2. Retrieved memories are injected as a system message at the start of the prompt
|
||||
3. The underlying LLM (e.g., OpenAI gpt-4-turbo) generates a response using the enriched prompt
|
||||
4. The conversation is stored back to Mem0 (`POST /v1/memories/`) as a fire-and-forget async call (no await)
|
||||
3. The underlying LLM (e.g., OpenAI gpt-5-mini) generates a response using the enriched prompt
|
||||
4. The conversation is stored back to Mem0 (`POST /v3/memories/add/`) as a fire-and-forget async call (no await)
|
||||
|
||||
## Pattern 2: Standalone Utilities
|
||||
|
||||
@@ -77,7 +77,7 @@ const memories = await retrieveMemories(prompt, {
|
||||
|
||||
// Generate using any provider with injected memories
|
||||
const { text } = await generateText({
|
||||
model: openai("gpt-4-turbo"),
|
||||
model: openai("gpt-5-mini"),
|
||||
prompt,
|
||||
system: memories,
|
||||
});
|
||||
@@ -102,7 +102,7 @@ import { createMem0 } from "@mem0/vercel-ai-provider";
|
||||
|
||||
const mem0 = createMem0();
|
||||
const result = streamText({
|
||||
model: mem0("gpt-4-turbo", { user_id: "alice" }),
|
||||
model: mem0("gpt-5-mini", { user_id: "alice" }),
|
||||
prompt: "What should I cook for dinner?",
|
||||
});
|
||||
|
||||
@@ -128,7 +128,7 @@ Select a provider when creating the Mem0 instance:
|
||||
```typescript
|
||||
const mem0 = createMem0({ provider: "anthropic" });
|
||||
const { text } = await generateText({
|
||||
model: mem0("claude-sonnet-4-20250514", { user_id: "alice" }),
|
||||
model: mem0("gpt-5-mini", { user_id: "alice" }),
|
||||
prompt: "Hello!",
|
||||
});
|
||||
```
|
||||
@@ -139,7 +139,7 @@ const { text } = await generateText({
|
||||
|
||||
```
|
||||
User prompt
|
||||
--> searchInternalMemories (POST /v2/memories/search/)
|
||||
--> searchInternalMemories (POST /v3/memories/search/)
|
||||
--> memories injected as system message at start of prompt
|
||||
--> underlying LLM generates response (doGenerate or doStream)
|
||||
--> processMemories fires addMemories as fire-and-forget (no await)
|
||||
@@ -161,7 +161,7 @@ User controls each step:
|
||||
| Function | Returns | Use when |
|
||||
|----------|---------|----------|
|
||||
| `retrieveMemories` | Formatted system prompt **string** | Injecting directly into `system` parameter |
|
||||
| `getMemories` | Raw memory **array** (or full response if `enable_graph`) | Processing memories programmatically |
|
||||
| `getMemories` | Raw memory **array** | Processing memories programmatically |
|
||||
| `searchMemories` | Full search **response** (results + relations) | Need relations, scores, metadata |
|
||||
| `addMemories` | API response | Storing new messages to Mem0 |
|
||||
|
||||
@@ -171,7 +171,6 @@ All four accept `LanguageModelV2Prompt | string` as the first argument and optio
|
||||
|
||||
- **Always provide `user_id`** (or `agent_id`/`app_id`/`run_id`) for consistent memory retrieval. Without an entity identifier, memories cannot be scoped.
|
||||
- **Standalone utilities require explicit API key**: pass `mem0ApiKey` in the config object, or set the `MEM0_API_KEY` environment variable.
|
||||
- **Graph memories**: set `enable_graph: true` in the config to retrieve graph relations alongside text memories. When enabled, `getMemories` returns the full response (with `results` and `relations`), not just the array.
|
||||
- **This uses Vercel AI SDK v5** (LanguageModelV2 / ProviderV2 interfaces). It is not compatible with AI SDK v3 or v4.
|
||||
- **`processMemories` fires `addMemories` as fire-and-forget** (`.then()` without `await`). Memory storage happens asynchronously and does not block the LLM response.
|
||||
- **The `"gemini"` alias** exists in the provider switch but is NOT in the `supportedProviders` list. Use `"google"` instead.
|
||||
|
||||
@@ -79,8 +79,7 @@ async function retrieveMemories(
|
||||
1. Flattens the prompt to a plain string (extracts text from `LanguageModelV2Prompt` parts)
|
||||
2. Calls `searchInternalMemories` (`POST /v2/memories/search/`)
|
||||
3. Formats each memory as `"Memory: {memory.memory}\n\n"`
|
||||
4. If `enable_graph: true`, also appends graph relations as `"Relation: {source} -> {relationship} -> {target}\n\n"`
|
||||
5. Wraps everything in a system prompt preamble
|
||||
4. Wraps everything in a system prompt preamble
|
||||
|
||||
**Returns:** A **string** containing the formatted system prompt with embedded memories. Returns `""` (empty string) if no memories found.
|
||||
|
||||
@@ -91,17 +90,13 @@ System Message: These are the memories I have stored. Give more weightage to the
|
||||
Memory: User loves Italian food
|
||||
|
||||
Memory: User is vegetarian
|
||||
|
||||
HERE ARE THE GRAPHS RELATIONS FOR THE PREFERENCES OF THE USER:
|
||||
|
||||
Relation: Alice -> likes -> Italian cuisine
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## `getMemories(prompt, config?)`
|
||||
|
||||
Retrieves memories and returns the **raw memory array** (or full response if graph is enabled).
|
||||
Retrieves memories and returns the **raw memory array**.
|
||||
|
||||
```typescript
|
||||
import { getMemories } from "@mem0/vercel-ai-provider";
|
||||
@@ -111,14 +106,6 @@ const memories = await getMemories("What are my preferences?", {
|
||||
mem0ApiKey: "m0-xxx",
|
||||
});
|
||||
// Returns: [{ memory: "User loves Italian food", id: "...", ... }, ...]
|
||||
|
||||
// With graph enabled:
|
||||
const graphMemories = await getMemories("What are my preferences?", {
|
||||
user_id: "alice",
|
||||
mem0ApiKey: "m0-xxx",
|
||||
enable_graph: true,
|
||||
});
|
||||
// Returns: { results: [...], relations: [...] }
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
@@ -140,10 +127,9 @@ async function getMemories(
|
||||
**Behavior:**
|
||||
1. Flattens the prompt to a plain string
|
||||
2. Calls `searchInternalMemories` (`POST /v2/memories/search/`)
|
||||
3. If `enable_graph` is **not** set: returns `memories.results` (the array of memory objects)
|
||||
4. If `enable_graph` is set: returns the full response object (with both `results` and `relations`)
|
||||
3. Returns `memories.results` (the array of memory objects)
|
||||
|
||||
**Returns:** Memory object array, or full response object when graph is enabled.
|
||||
**Returns:** Memory object array.
|
||||
|
||||
---
|
||||
|
||||
@@ -184,7 +170,7 @@ async function searchMemories(
|
||||
|
||||
**Returns:** The complete API response object. On error, returns `[]`.
|
||||
|
||||
**Note:** Unlike `getMemories`, this always returns the full response regardless of `enable_graph` setting.
|
||||
**Note:** Unlike `getMemories`, this always returns the full response.
|
||||
|
||||
---
|
||||
|
||||
@@ -193,8 +179,8 @@ async function searchMemories(
|
||||
| Function | Returns | Use when |
|
||||
|----------|---------|----------|
|
||||
| `retrieveMemories` | Formatted system prompt **string** | Injecting directly into a `system` parameter for `generateText`/`streamText` |
|
||||
| `getMemories` | Memory **array** (or full response if `enable_graph`) | Processing memories programmatically (filtering, transforming, counting) |
|
||||
| `searchMemories` | Full API **response** (results + relations) | Need relations, similarity scores, or complete metadata regardless of graph setting |
|
||||
| `getMemories` | Memory **array** | Processing memories programmatically (filtering, transforming, counting) |
|
||||
| `searchMemories` | Full API **response** (results + relations) | Need relations, similarity scores, or complete metadata |
|
||||
| `addMemories` | API response | Storing new conversation messages as memories |
|
||||
|
||||
## Internal: `searchInternalMemories(query, config?, top_k?)`
|
||||
@@ -210,15 +196,13 @@ async function searchInternalMemories(
|
||||
```
|
||||
|
||||
**Behavior:**
|
||||
1. Builds an `OR` filter from entity identifiers (`user_id`, `app_id`, `agent_id`, `run_id`)
|
||||
2. Resolves org/project identifiers (`org_id` takes precedence over `org_name`)
|
||||
1. Builds a `filters` object from entity identifiers (`user_id`, `app_id`, `agent_id`, `run_id`)
|
||||
2. Resolves entity identifiers
|
||||
3. Loads the API key from `config.mem0ApiKey` or `MEM0_API_KEY` env var
|
||||
4. Calls `POST {host}/v2/memories/search/` with:
|
||||
- `query`: the search string
|
||||
- `filters`: the OR filter object
|
||||
- `filters`: the filter object with entity identifiers
|
||||
- `top_k`: from config or default 5
|
||||
- `version`: `"v2"`
|
||||
- `output_format`: `"v1.1"`
|
||||
- All other config fields spread into the request body
|
||||
|
||||
**Default host:** `https://api.mem0.ai`
|
||||
@@ -264,10 +248,6 @@ All fields are optional. Used across all utility functions.
|
||||
| `app_id` | `string` | -- | Scope memories to an application |
|
||||
| `agent_id` | `string` | -- | Scope memories to an agent |
|
||||
| `run_id` | `string` | -- | Scope memories to a session/run |
|
||||
| `org_name` | `string` | -- | Organization name (fallback if `org_id` not set) |
|
||||
| `project_name` | `string` | -- | Project name (fallback if `org_id` not set) |
|
||||
| `org_id` | `string` | -- | Organization ID (takes precedence) |
|
||||
| `project_id` | `string` | -- | Project ID |
|
||||
| `metadata` | `Record<string, any>` | -- | Custom metadata |
|
||||
| `filters` | `Record<string, any>` | -- | Custom search filters |
|
||||
| `infer` | `boolean` | -- | Enable inference |
|
||||
@@ -277,8 +257,4 @@ All fields are optional. Used across all utility functions.
|
||||
| `top_k` | `number` | `5` | Number of memories to retrieve |
|
||||
| `threshold` | `number` | -- | Minimum similarity score |
|
||||
| `rerank` | `boolean` | -- | Enable re-ranking |
|
||||
| `enable_graph` | `boolean` | -- | Enable graph memory (relations) |
|
||||
| `host` | `string` | `https://api.mem0.ai` | Custom API host |
|
||||
| `output_format` | `string` | -- | Output format version |
|
||||
| `filter_memories` | `boolean` | -- | Enable memory filtering |
|
||||
| `async_mode` | `boolean` | -- | Enable async processing |
|
||||
|
||||
@@ -9,8 +9,8 @@ Factory function that creates a `Mem0Provider` instance. This is the primary ent
|
||||
```typescript
|
||||
import { createMem0 } from "@mem0/vercel-ai-provider";
|
||||
|
||||
const mem0 = createMem0(); // defaults: provider "openai"
|
||||
const mem0 = createMem0({ provider: "anthropic" }); // use Anthropic as LLM backend
|
||||
const mem0 = createMem0(); // defaults: provider "openai"
|
||||
const mem0 = createMem0({ provider: "anthropic" }); // use Anthropic as LLM backend
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
@@ -39,7 +39,7 @@ interface Mem0Provider extends ProviderV2 {
|
||||
}
|
||||
```
|
||||
|
||||
- **Direct call** (`mem0("gpt-4-turbo", {...})`): creates a generic language model (neither chat nor completion mode forced).
|
||||
- **Direct call** (`mem0("gpt-5-mini", {...})`): creates a generic language model (neither chat nor completion mode forced).
|
||||
- **`chat()`**: creates a model with `modelType: "chat"` (note: in the current source, the chat constructor sets `modelType: "completion"` -- this appears to be a bug; functionally equivalent to `completion()` at present).
|
||||
- **`completion()`**: creates a model with `modelType: "completion"`.
|
||||
- **`languageModel()`**: alias for the generic model (same as direct call).
|
||||
@@ -73,7 +73,7 @@ interface Mem0ProviderSettings {
|
||||
| `provider` | Which LLM backend to use | `"openai"`, `"anthropic"`, `"google"`, `"groq"`, `"cohere"` |
|
||||
| `mem0ApiKey` | Mem0 Platform API key | `"m0-xxx"` |
|
||||
| `apiKey` | LLM provider API key | `"sk-xxx"` (OpenAI), `"sk-ant-xxx"` (Anthropic) |
|
||||
| `mem0Config` | Default Mem0 settings for all calls | `{ user_id: "alice", enable_graph: true }` |
|
||||
| `mem0Config` | Default Mem0 settings for all calls | `{ user_id: "alice" }` |
|
||||
| `config` | Provider-specific SDK settings | `{ organization: "org-xxx" }` for OpenAI |
|
||||
| `baseURL` | Override LLM provider base URL | `"https://my-proxy.example.com"` |
|
||||
|
||||
@@ -85,7 +85,7 @@ A pre-configured instance using default settings (OpenAI provider, no API keys s
|
||||
import { mem0 } from "@mem0/vercel-ai-provider";
|
||||
|
||||
const { text } = await generateText({
|
||||
model: mem0("gpt-4-turbo", { user_id: "alice" }),
|
||||
model: mem0("gpt-5-mini", { user_id: "alice" }),
|
||||
prompt: "Hello",
|
||||
});
|
||||
```
|
||||
@@ -102,10 +102,6 @@ interface Mem0ConfigSettings {
|
||||
app_id?: string; // Scope memories to an application
|
||||
agent_id?: string; // Scope memories to an agent
|
||||
run_id?: string; // Scope memories to a specific run/session
|
||||
org_name?: string; // Organization name (used if org_id not set)
|
||||
project_name?: string; // Project name (used if org_id not set)
|
||||
org_id?: string; // Organization ID (takes precedence over org_name)
|
||||
project_id?: string; // Project ID (takes precedence over project_name)
|
||||
metadata?: Record<string, any>; // Custom metadata attached to memories
|
||||
filters?: Record<string, any>; // Custom filters for memory search
|
||||
infer?: boolean; // Enable inference during memory operations
|
||||
@@ -113,13 +109,9 @@ interface Mem0ConfigSettings {
|
||||
page_size?: number; // Pagination: results per page
|
||||
mem0ApiKey?: string; // Mem0 API key (overrides provider-level key)
|
||||
top_k?: number; // Number of memories to retrieve (default: 5)
|
||||
threshold?: number; // Minimum similarity score for retrieval
|
||||
rerank?: boolean; // Enable re-ranking of search results
|
||||
enable_graph?: boolean; // Enable graph memory (returns relations)
|
||||
threshold?: number; // Minimum similarity score for retrieval (default: 0.1)
|
||||
rerank?: boolean; // Enable re-ranking of search results (default: false)
|
||||
host?: string; // Custom Mem0 API host (default: "https://api.mem0.ai")
|
||||
output_format?: string; // Output format version
|
||||
filter_memories?: boolean; // Enable memory filtering
|
||||
async_mode?: boolean; // Enable async processing of memory operations
|
||||
}
|
||||
```
|
||||
|
||||
@@ -138,9 +130,9 @@ This means a `Mem0ChatConfig` has all fields from both `Mem0ConfigSettings` and
|
||||
Alias for `Mem0ConfigSettings`. Passed as the second argument when creating a model:
|
||||
|
||||
```typescript
|
||||
mem0("gpt-4-turbo", { user_id: "alice", enable_graph: true })
|
||||
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
// This object is Mem0ChatSettings
|
||||
mem0("gpt-5-mini", { user_id: "alice" })
|
||||
// ^^^^^^^^^^^^^^^^^^
|
||||
// This object is Mem0ChatSettings
|
||||
```
|
||||
|
||||
## `LLMProviderSettings` Type
|
||||
@@ -188,8 +180,8 @@ An alternative exported class that creates models directly without the callable-
|
||||
import { Mem0 } from "@mem0/vercel-ai-provider";
|
||||
|
||||
const mem0 = new Mem0({ provider: "openai" });
|
||||
const chatModel = mem0.chat("gpt-4-turbo", { user_id: "alice" });
|
||||
const completionModel = mem0.completion("gpt-3.5-turbo-instruct");
|
||||
const chatModel = mem0.chat("gpt-5-mini", { user_id: "alice" });
|
||||
const completionModel = mem0.completion("gpt-5-mini");
|
||||
```
|
||||
|
||||
The facade defaults its base URL to `"http://127.0.0.1:11434/api"` (Ollama-style) rather than `"http://api.openai.com"`. It always uses `"openai"` as the provider for created models.
|
||||
@@ -210,7 +202,7 @@ class Mem0GenericLanguageModel implements LanguageModelV2 {
|
||||
readonly supportedUrls: Record<string, RegExp[]> = { '*': [/.*/] };
|
||||
|
||||
provider: string; // e.g., "openai"
|
||||
modelId: string; // e.g., "gpt-4-turbo"
|
||||
modelId: string; // e.g., "gpt-5-mini"
|
||||
settings: Mem0ChatSettings;
|
||||
config: Mem0ChatConfig;
|
||||
|
||||
@@ -230,10 +222,12 @@ Both `doGenerate` and `doStream` follow the same internal flow:
|
||||
4. Delegate to the underlying model's `doGenerate` or `doStream`
|
||||
5. Return the result
|
||||
|
||||
**Note:** Entity identifier fields use snake_case (`user_id`, `app_id`, `agent_id`, `run_id`) to match the Mem0 API.
|
||||
|
||||
## Type: `Mem0ChatModelId`
|
||||
|
||||
```typescript
|
||||
type Mem0ChatModelId = string & NonNullable<unknown>;
|
||||
```
|
||||
|
||||
Any non-null string. The model ID is passed through to the underlying provider (e.g., `"gpt-4-turbo"`, `"claude-sonnet-4-20250514"`, `"gemini-pro"`).
|
||||
Any non-null string. The model ID is passed through to the underlying provider (e.g., `"gpt-5-mini"`, `"gemini-pro"`).
|
||||
|
||||
@@ -13,7 +13,7 @@ import { createMem0 } from "@mem0/vercel-ai-provider";
|
||||
const mem0 = createMem0();
|
||||
|
||||
const { text } = await generateText({
|
||||
model: mem0("gpt-4-turbo", { user_id: "alice" }),
|
||||
model: mem0("gpt-5-mini", { user_id: "alice" }),
|
||||
prompt: "Recommend a restaurant based on my preferences",
|
||||
});
|
||||
|
||||
@@ -33,7 +33,7 @@ import { createMem0 } from "@mem0/vercel-ai-provider";
|
||||
const mem0 = createMem0();
|
||||
|
||||
const result = streamText({
|
||||
model: mem0("gpt-4-turbo", { user_id: "alice" }),
|
||||
model: mem0("gpt-5-mini", { user_id: "alice" }),
|
||||
prompt: "What should I cook for dinner tonight?",
|
||||
});
|
||||
|
||||
@@ -53,17 +53,17 @@ import { openai } from "@ai-sdk/openai";
|
||||
import { generateText } from "ai";
|
||||
import { retrieveMemories, addMemories } from "@mem0/vercel-ai-provider";
|
||||
|
||||
const userId = "alice";
|
||||
const user_id = "alice";
|
||||
const prompt = "Suggest a weekend trip";
|
||||
|
||||
// Step 1: Retrieve memories as a formatted system prompt
|
||||
const memories = await retrieveMemories(prompt, {
|
||||
user_id: userId,
|
||||
user_id: user_id,
|
||||
});
|
||||
|
||||
// Step 2: Generate with the memories injected as system context
|
||||
const { text } = await generateText({
|
||||
model: openai("gpt-4-turbo"),
|
||||
model: openai("gpt-5-mini"),
|
||||
prompt,
|
||||
system: memories,
|
||||
});
|
||||
@@ -76,7 +76,7 @@ await addMemories(
|
||||
{ role: "user", content: [{ type: "text", text: prompt }] },
|
||||
{ role: "assistant", content: [{ type: "text", text }] },
|
||||
],
|
||||
{ user_id: userId }
|
||||
{ user_id: user_id }
|
||||
);
|
||||
```
|
||||
|
||||
@@ -121,7 +121,7 @@ import { z } from "zod";
|
||||
const mem0 = createMem0();
|
||||
|
||||
const { object } = await generateObject({
|
||||
model: mem0("gpt-4-turbo", { user_id: "alice" }),
|
||||
model: mem0("gpt-5-mini", { user_id: "alice" }),
|
||||
prompt: "Suggest a meal plan for today",
|
||||
schema: z.object({
|
||||
breakfast: z.string(),
|
||||
@@ -138,53 +138,7 @@ console.log(object);
|
||||
|
||||
The `defaultObjectGenerationMode` is `"json"`, so structured output works out of the box.
|
||||
|
||||
## 6. Graph Memory Enabled
|
||||
|
||||
Retrieve both text memories and entity relationship graphs.
|
||||
|
||||
```typescript
|
||||
import { generateText } from "ai";
|
||||
import { createMem0 } from "@mem0/vercel-ai-provider";
|
||||
|
||||
const mem0 = createMem0();
|
||||
|
||||
const { text } = await generateText({
|
||||
model: mem0("gpt-4-turbo", {
|
||||
user_id: "alice",
|
||||
enable_graph: true,
|
||||
}),
|
||||
prompt: "What connections do you know about between my friends?",
|
||||
});
|
||||
|
||||
console.log(text);
|
||||
```
|
||||
|
||||
With `enable_graph: true`, the system prompt includes both:
|
||||
- **Text memories**: `"Memory: Alice is friends with Bob"`
|
||||
- **Graph relations**: `"Relation: Alice -> friends_with -> Bob"`
|
||||
|
||||
### Using graph with standalone utilities
|
||||
|
||||
```typescript
|
||||
import { getMemories, searchMemories } from "@mem0/vercel-ai-provider";
|
||||
|
||||
// getMemories with graph returns the full response
|
||||
const graphResult = await getMemories("my social connections", {
|
||||
user_id: "alice",
|
||||
enable_graph: true,
|
||||
});
|
||||
console.log(graphResult.results); // memory objects
|
||||
console.log(graphResult.relations); // graph relations
|
||||
|
||||
// searchMemories always returns the full response
|
||||
const fullResponse = await searchMemories("my social connections", {
|
||||
user_id: "alice",
|
||||
});
|
||||
console.log(fullResponse.results);
|
||||
console.log(fullResponse.relations);
|
||||
```
|
||||
|
||||
## 7. Multi-Provider Setup
|
||||
## 6. Multi-Provider Setup
|
||||
|
||||
Configure different LLM providers with the wrapped model.
|
||||
|
||||
@@ -194,7 +148,7 @@ Configure different LLM providers with the wrapped model.
|
||||
import { createMem0 } from "@mem0/vercel-ai-provider";
|
||||
|
||||
const mem0 = createMem0(); // defaults to "openai"
|
||||
const model = mem0("gpt-4-turbo", { user_id: "alice" });
|
||||
const model = mem0("gpt-5-mini", { user_id: "alice" });
|
||||
```
|
||||
|
||||
### Anthropic
|
||||
@@ -235,7 +189,7 @@ const mem0 = createMem0({
|
||||
});
|
||||
```
|
||||
|
||||
## 8. Next.js API Route Integration
|
||||
## 7. Next.js API Route Integration
|
||||
|
||||
A POST handler that uses the wrapped model in a Next.js App Router API route.
|
||||
|
||||
@@ -247,12 +201,12 @@ import { createMem0 } from "@mem0/vercel-ai-provider";
|
||||
const mem0 = createMem0();
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const { messages, userId } = await req.json();
|
||||
const { messages, user_id } = await req.json();
|
||||
|
||||
const lastMessage = messages[messages.length - 1];
|
||||
|
||||
const result = streamText({
|
||||
model: mem0("gpt-4-turbo", { user_id: userId }),
|
||||
model: mem0("gpt-5-mini", { user_id }),
|
||||
prompt: lastMessage.content,
|
||||
});
|
||||
|
||||
@@ -269,17 +223,17 @@ import { streamText } from "ai";
|
||||
import { retrieveMemories, addMemories } from "@mem0/vercel-ai-provider";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const { messages, userId } = await req.json();
|
||||
const { messages, user_id } = await req.json();
|
||||
const lastMessage = messages[messages.length - 1];
|
||||
|
||||
// Retrieve relevant memories
|
||||
const memories = await retrieveMemories(lastMessage.content, {
|
||||
user_id: userId,
|
||||
user_id,
|
||||
});
|
||||
|
||||
// Stream the response
|
||||
const result = streamText({
|
||||
model: openai("gpt-4-turbo"),
|
||||
model: openai("gpt-5-mini"),
|
||||
prompt: lastMessage.content,
|
||||
system: memories,
|
||||
});
|
||||
@@ -291,7 +245,7 @@ export async function POST(req: Request) {
|
||||
{ role: "user", content: [{ type: "text", text: lastMessage.content }] },
|
||||
{ role: "assistant", content: [{ type: "text", text }] },
|
||||
],
|
||||
{ user_id: userId }
|
||||
{ user_id }
|
||||
);
|
||||
});
|
||||
|
||||
@@ -299,7 +253,7 @@ export async function POST(req: Request) {
|
||||
}
|
||||
```
|
||||
|
||||
## 9. How Memory Processing Works Internally
|
||||
## 8. How Memory Processing Works Internally
|
||||
|
||||
### Wrapped model flow (doGenerate / doStream)
|
||||
|
||||
@@ -308,10 +262,10 @@ export async function POST(req: Request) {
|
||||
2. processMemories(messagesPrompts, mem0Config):
|
||||
a. addMemories(messagesPrompts, mem0Config)
|
||||
--> fire-and-forget: .then().catch(), NO await
|
||||
--> POST /v1/memories/ with converted messages
|
||||
--> POST /v3/memories/add/ with converted messages
|
||||
b. await getMemories(messagesPrompts, mem0Config)
|
||||
--> POST /v2/memories/search/ with flattened prompt
|
||||
--> returns memory array (or {results, relations} if enable_graph)
|
||||
--> POST /v3/memories/search/ with flattened prompt
|
||||
--> returns memory array
|
||||
c. Format memories into system message string
|
||||
d. Prepend system message to messagesPrompts array
|
||||
e. Return { memories, messagesPrompts }
|
||||
@@ -337,7 +291,7 @@ The memories are injected as a system message at position 0 of the prompt array:
|
||||
}
|
||||
```
|
||||
|
||||
## 10. Custom Configuration
|
||||
## 9. Custom Configuration
|
||||
|
||||
### Custom Mem0 API host
|
||||
|
||||
@@ -358,32 +312,15 @@ const memories = await retrieveMemories(prompt, {
|
||||
});
|
||||
```
|
||||
|
||||
### Organization and project scoping
|
||||
|
||||
```typescript
|
||||
const mem0 = createMem0();
|
||||
const { text } = await generateText({
|
||||
model: mem0("gpt-4-turbo", {
|
||||
user_id: "alice",
|
||||
org_id: "org-123",
|
||||
project_id: "proj-456",
|
||||
}),
|
||||
prompt: "Hello",
|
||||
});
|
||||
```
|
||||
|
||||
Note: `org_id` takes precedence over `org_name`. If `org_id` is set, `org_name` and `project_name` are not sent in the request.
|
||||
|
||||
### Memory filtering and ranking
|
||||
|
||||
```typescript
|
||||
const mem0 = createMem0();
|
||||
const model = mem0("gpt-4-turbo", {
|
||||
const model = mem0("gpt-5-mini", {
|
||||
user_id: "alice",
|
||||
top_k: 10, // retrieve up to 10 memories (default: 5)
|
||||
threshold: 0.8, // only memories with score >= 0.8
|
||||
rerank: true, // enable re-ranking of results
|
||||
filter_memories: true,
|
||||
rerank: true, // enable re-ranking of results
|
||||
});
|
||||
```
|
||||
|
||||
@@ -409,14 +346,13 @@ Set defaults at the provider level that apply to every model created:
|
||||
const mem0 = createMem0({
|
||||
mem0Config: {
|
||||
user_id: "alice",
|
||||
enable_graph: true,
|
||||
top_k: 10,
|
||||
},
|
||||
});
|
||||
|
||||
// These calls inherit user_id, enable_graph, and top_k from mem0Config
|
||||
// These calls inherit user_id and top_k from mem0Config
|
||||
const { text } = await generateText({
|
||||
model: mem0("gpt-4-turbo"),
|
||||
model: mem0("gpt-5-mini"),
|
||||
prompt: "Hello",
|
||||
});
|
||||
```
|
||||
@@ -425,7 +361,7 @@ Per-call settings (passed as the second argument to `mem0()`) are merged on top
|
||||
|
||||
```typescript
|
||||
// Override user_id for this specific call
|
||||
const model = mem0("gpt-4-turbo", { user_id: "bob" });
|
||||
const model = mem0("gpt-5-mini", { user_id: "bob" });
|
||||
```
|
||||
|
||||
The merge order is: `config.mem0Config` (provider defaults) < `settings` (per-call overrides).
|
||||
|
||||
@@ -15,10 +15,10 @@ description: >
|
||||
license: Apache-2.0
|
||||
metadata:
|
||||
author: mem0ai
|
||||
version: "2.0.0"
|
||||
version: "3.0.0"
|
||||
category: ai-memory
|
||||
tags: "memory, personalization, ai, python, typescript, vector-search"
|
||||
compatibility: Requires Python 3.10+ or Node.js 18+, pip install mem0ai or npm install mem0ai, MEM0_API_KEY env var (Platform), and internet access to api.mem0.ai
|
||||
compatibility: Requires Python 3.10+ or Node.js 18+, pip install mem0ai or npm install mem0ai, MEM0_API_KEY env var (Platform), and internet access to api.mem0.ai. SDK v3 with v2 compatibility mode available.
|
||||
---
|
||||
|
||||
# Mem0 Platform Integration
|
||||
@@ -77,14 +77,14 @@ client.add(messages, user_id="alice")
|
||||
|
||||
### Search memories
|
||||
```python
|
||||
results = client.search("dietary preferences", user_id="alice")
|
||||
results = client.search("dietary preferences", filters={"user_id": "alice"})
|
||||
for mem in results.get("results", []):
|
||||
print(mem["memory"])
|
||||
```
|
||||
|
||||
### Get all memories
|
||||
```python
|
||||
all_memories = client.get_all(user_id="alice")
|
||||
all_memories = client.get_all(filters={"user_id": "alice"})
|
||||
```
|
||||
|
||||
### Update a memory
|
||||
@@ -109,12 +109,12 @@ openai = OpenAI()
|
||||
|
||||
def chat(user_input: str, user_id: str) -> str:
|
||||
# 1. Retrieve relevant memories
|
||||
memories = mem0.search(user_input, user_id=user_id)
|
||||
memories = mem0.search(user_input, filters={"user_id": user_id})
|
||||
context = "\n".join([m["memory"] for m in memories.get("results", [])])
|
||||
|
||||
# 2. Generate response with memory context
|
||||
response = openai.chat.completions.create(
|
||||
model="gpt-4.1-nano-2025-04-14",
|
||||
model="gpt-5-mini",
|
||||
messages=[
|
||||
{"role": "system", "content": f"User context:\n{context}"},
|
||||
{"role": "user", "content": user_input},
|
||||
@@ -132,11 +132,20 @@ def chat(user_input: str, user_id: str) -> str:
|
||||
|
||||
## Common edge cases
|
||||
|
||||
- **Search returns empty:** Memories process asynchronously. Wait 2-3s after `add()` before searching. Also verify `user_id` matches exactly (case-sensitive).
|
||||
- **Search returns empty:** Memories process asynchronously. Wait 2-3s after `add()` before searching. Also verify `user_id` matches exactly (case-sensitive) and use `filters={"user_id": "..."}` syntax.
|
||||
- **AND filter with user_id + agent_id returns empty:** Entities are stored separately. Use `OR` instead, or query separately.
|
||||
- **Duplicate memories:** Don't mix `infer=True` (default) and `infer=False` for the same data. Stick to one mode.
|
||||
- **Wrong import:** Always use `from mem0 import MemoryClient` (or `AsyncMemoryClient` for async). Do not use `from mem0 import Memory`.
|
||||
- **Immutable memories:** Cannot be updated or deleted once created. Use `client.history(memory_id)` to track changes over time.
|
||||
- **v3 defaults:** `top_k=20`, `threshold=0.1`, `rerank=False`. Adjust as needed for your use case.
|
||||
|
||||
## v2 Compatibility
|
||||
|
||||
If you're using SDK v2.x, note these differences:
|
||||
- **Entity IDs:** Pass `user_id` as top-level kwarg to `search()` instead of inside `filters`
|
||||
- **Defaults:** `top_k=100`, no threshold, `rerank=True`
|
||||
- **Graph memory:** Available via `enable_graph=True`
|
||||
|
||||
See the [migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for details.
|
||||
|
||||
## Live documentation search
|
||||
|
||||
|
||||
@@ -46,18 +46,16 @@ Both read from `MEM0_API_KEY` env var if no key provided.
|
||||
```python
|
||||
# Python: kwargs
|
||||
client.add(messages, user_id="alice", metadata={"source": "chat"})
|
||||
client.search("query", user_id="alice", top_k=5, rerank=True)
|
||||
client.search("query", filters={"user_id": "alice"}, top_k=5, rerank=True)
|
||||
```
|
||||
|
||||
```typescript
|
||||
// TypeScript: options object
|
||||
await client.add(messages, { user_id: 'alice', metadata: { source: 'chat' } });
|
||||
await client.search('query', { user_id: 'alice', top_k: 5, rerank: true });
|
||||
// TypeScript: options object with camelCase for top-level params, snake_case for filter keys
|
||||
await client.add(messages, { userId: 'alice', metadata: { source: 'chat' } });
|
||||
await client.search('query', { filters: { user_id: 'alice' }, topK: 5, rerank: true });
|
||||
```
|
||||
|
||||
**Important:** Both use `snake_case` for API parameter names (`user_id`, `agent_id`, `top_k`, etc.). Only method names differ.
|
||||
|
||||
Exception: OSS TypeScript uses `camelCase` for config params (`userId`, `agentId`, `runId`).
|
||||
**v3:** Python uses `snake_case` everywhere. TypeScript uses `camelCase` for top-level params (`userId`, `topK`) but `snake_case` for filter keys (`user_id`, `agent_id`).
|
||||
|
||||
## Architectural Differences
|
||||
|
||||
@@ -97,10 +95,8 @@ These methods exist in Python but not TypeScript:
|
||||
| Python config key | TypeScript config key |
|
||||
|-------------------|----------------------|
|
||||
| `vector_store` | `vectorStore` |
|
||||
| `graph_store` | `graphStore` |
|
||||
| `history_db_path` | `historyDbPath` |
|
||||
| `custom_instructions` | `customInstructions` |
|
||||
| `enable_graph` | `enableGraph` |
|
||||
|
||||
## OSS Scope Parameter Naming
|
||||
|
||||
@@ -110,16 +106,24 @@ These methods exist in Python but not TypeScript:
|
||||
| `agent_id="bot"` | `agentId: 'bot'` |
|
||||
| `run_id="session"` | `runId: 'session'` |
|
||||
|
||||
## Entity ID Passing (v3)
|
||||
|
||||
| Method | Python | TypeScript |
|
||||
|--------|--------|------------|
|
||||
| add() | Top-level: `user_id="alice"` | Top-level: `{ userId: 'alice' }` |
|
||||
| search() | In filters: `filters={"user_id": "alice"}` | In filters: `{ filters: { user_id: 'alice' } }` |
|
||||
| get_all() | In filters: `filters={"user_id": "alice"}` | In filters: `{ filters: { user_id: 'alice' } }` |
|
||||
|
||||
## Common Gotcha
|
||||
|
||||
When searching/filtering, **both SDKs use `snake_case`** for filter keys:
|
||||
When searching/filtering, both Python and TypeScript use `snake_case` for filter keys. TypeScript only uses `camelCase` for top-level method parameters:
|
||||
|
||||
```python
|
||||
# Python
|
||||
filters = {"AND": [{"user_id": "alice"}, {"categories": {"contains": "health"}}]}
|
||||
# Python - snake_case in filters
|
||||
results = client.search("query", filters={"user_id": "alice"})
|
||||
```
|
||||
|
||||
```typescript
|
||||
// TypeScript -- same snake_case in filter objects!
|
||||
const filters = { AND: [{ user_id: 'alice' }, { categories: { contains: 'health' } }] };
|
||||
// TypeScript - snake_case in filters, camelCase for top-level params
|
||||
const results = await client.search('query', { filters: { user_id: 'alice' }, topK: 20 });
|
||||
```
|
||||
|
||||
@@ -41,23 +41,18 @@ const messages = [
|
||||
{ role: 'user', content: "I'm a vegetarian and allergic to nuts." },
|
||||
{ role: 'assistant', content: "Got it! I'll remember that." },
|
||||
];
|
||||
await client.add(messages, { user_id: 'alice' });
|
||||
await client.add(messages, { userId: 'alice' });
|
||||
```
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `messages` | `Message[]` | Array of `{role, content}` objects |
|
||||
| `options.user_id` | string | User identifier |
|
||||
| `options.agent_id` | string | Agent identifier |
|
||||
| `options.app_id` | string | Application identifier |
|
||||
| `options.run_id` | string | Session identifier |
|
||||
| `options.userId` | string | User identifier |
|
||||
| `options.agentId` | string | Agent identifier |
|
||||
| `options.appId` | string | Application identifier |
|
||||
| `options.runId` | string | Session identifier |
|
||||
| `options.metadata` | object | Custom key-value pairs |
|
||||
| `options.enable_graph` | boolean | Activate knowledge graph |
|
||||
| `options.infer` | boolean | If false, store raw text (default: true) |
|
||||
| `options.immutable` | boolean | Prevent future modification |
|
||||
| `options.expiration_date` | string | Auto-expiry (`YYYY-MM-DD`) |
|
||||
| `options.includes` | string | Preference filter for inclusion |
|
||||
| `options.excludes` | string | Preference filter for exclusion |
|
||||
|
||||
**Returns:** `Promise<any>` -- list of events
|
||||
|
||||
@@ -66,7 +61,7 @@ await client.add(messages, { user_id: 'alice' });
|
||||
Search memories by semantic similarity.
|
||||
|
||||
```typescript
|
||||
const results = await client.search('dietary preferences', { user_id: 'alice' });
|
||||
const results = await client.search('dietary preferences', { filters: { user_id: 'alice' }, topK: 20 });
|
||||
for (const mem of results.results) {
|
||||
console.log(mem.memory, mem.score);
|
||||
}
|
||||
@@ -75,17 +70,12 @@ for (const mem of results.results) {
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `query` | string | Natural language search query |
|
||||
| `options.user_id` | string | Filter by user |
|
||||
| `options.agent_id` | string | Filter by agent |
|
||||
| `options.filters` | object | V2 filter object (`AND`/`OR`/`NOT`) |
|
||||
| `options.top_k` | number | Number of results (default: 10) |
|
||||
| `options.rerank` | boolean | Enable semantic reranking |
|
||||
| `options.threshold` | number | Minimum similarity (default: 0.3) |
|
||||
| `options.keyword_search` | boolean | Enable keyword search |
|
||||
| `options.enable_graph` | boolean | Include graph relations |
|
||||
| `options.filter_memories` | boolean | Precision filtering |
|
||||
| `options.filters` | object | Filter object with entity IDs (`user_id`, `agent_id`, etc.) and/or `AND`/`OR`/`NOT` conditions |
|
||||
| `options.topK` | number | Number of results (default: 20) |
|
||||
| `options.rerank` | boolean | Enable semantic reranking (default: false) |
|
||||
| `options.threshold` | number | Minimum similarity (default: 0.1) |
|
||||
|
||||
**Returns:** `Promise<SearchResult>` -- `{results: [{id, memory, score, ...}], relations: [...]}`
|
||||
**Returns:** `Promise<SearchResult>` -- `{results: [{id, memory, score, ...}]}`
|
||||
|
||||
#### get(memoryId)
|
||||
|
||||
@@ -98,7 +88,7 @@ const memory = await client.get('ea925981-...');
|
||||
Retrieve all memories. Requires at least one entity identifier in filters.
|
||||
|
||||
```typescript
|
||||
const memories = await client.getAll({ user_id: 'alice' });
|
||||
const memories = await client.getAll({ filters: { user_id: 'alice' } });
|
||||
// With filters
|
||||
const filtered = await client.getAll({
|
||||
filters: { AND: [{ user_id: 'alice' }, { categories: { contains: 'health' } }] },
|
||||
@@ -107,11 +97,9 @@ const filtered = await client.getAll({
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `options.user_id` | string | Filter by user |
|
||||
| `options.filters` | object | V2 filter object |
|
||||
| `options.filters` | object | Filter object with entity IDs (`user_id`, `agent_id`, etc.) and/or `AND`/`OR`/`NOT` conditions |
|
||||
| `options.page` | number | Page number |
|
||||
| `options.page_size` | number | Results per page |
|
||||
| `options.enable_graph` | boolean | Include graph relations |
|
||||
| `options.pageSize` | number | Results per page |
|
||||
|
||||
#### update(memoryId, data)
|
||||
|
||||
@@ -136,14 +124,14 @@ await client.delete('ea925981-...');
|
||||
#### deleteAll(options?)
|
||||
|
||||
```typescript
|
||||
await client.deleteAll({ user_id: 'alice' });
|
||||
await client.deleteAll({ userId: 'alice' });
|
||||
```
|
||||
|
||||
#### history(memoryId)
|
||||
|
||||
```typescript
|
||||
const history = await client.history('ea925981-...');
|
||||
// Returns: [{previous_value, new_value, action, timestamps}]
|
||||
// Returns: [{previousValue, newValue, action, timestamps}]
|
||||
```
|
||||
|
||||
---
|
||||
@@ -179,8 +167,8 @@ const users = await client.users();
|
||||
#### deleteUser(data) / deleteUsers(data)
|
||||
|
||||
```typescript
|
||||
await client.deleteUser({ user_id: 'alice' }); // Single entity
|
||||
await client.deleteUsers({ agent_id: 'bot-1' }); // Flexible
|
||||
await client.deleteUser({ userId: 'alice' }); // Single entity
|
||||
await client.deleteUsers({ agentId: 'bot-1' }); // Flexible
|
||||
```
|
||||
|
||||
---
|
||||
@@ -189,13 +177,12 @@ await client.deleteUsers({ agent_id: 'bot-1' }); // Flexible
|
||||
|
||||
```typescript
|
||||
// Get project config
|
||||
const config = await client.getProject({ fields: ['custom_categories'] });
|
||||
const config = await client.getProject({ fields: ['customCategories'] });
|
||||
|
||||
// Update project settings
|
||||
await client.updateProject({
|
||||
custom_instructions: 'Extract dietary preferences and health info',
|
||||
custom_categories: [{ health: 'Medical and dietary info' }],
|
||||
enable_graph: true,
|
||||
customInstructions: 'Extract dietary preferences and health info',
|
||||
customCategories: [{ health: 'Medical and dietary info' }],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -205,25 +192,25 @@ await client.updateProject({
|
||||
|
||||
```typescript
|
||||
// List
|
||||
const webhooks = await client.getWebhooks({ project_id: 'proj_123' });
|
||||
const webhooks = await client.getWebhooks({ projectId: 'proj_123' });
|
||||
|
||||
// Create
|
||||
const webhook = await client.createWebhook({
|
||||
url: 'https://your-app.com/webhook',
|
||||
name: 'Memory Logger',
|
||||
project_id: 'proj_123',
|
||||
event_types: ['memory_add', 'memory_update'],
|
||||
projectId: 'proj_123',
|
||||
eventTypes: ['memory_add', 'memory_update'],
|
||||
});
|
||||
|
||||
// Update
|
||||
await client.updateWebhook({
|
||||
webhook_id: 'wh_123',
|
||||
webhookId: 'wh_123',
|
||||
name: 'Updated Logger',
|
||||
url: 'https://new-url.com',
|
||||
});
|
||||
|
||||
// Delete
|
||||
await client.deleteWebhook({ webhook_id: 'wh_123' });
|
||||
await client.deleteWebhook({ webhookId: 'wh_123' });
|
||||
```
|
||||
|
||||
---
|
||||
@@ -232,9 +219,9 @@ await client.deleteWebhook({ webhook_id: 'wh_123' });
|
||||
|
||||
```typescript
|
||||
await client.feedback({
|
||||
memory_id: 'mem-123',
|
||||
memoryId: 'mem-123',
|
||||
feedback: 'POSITIVE',
|
||||
feedback_reason: 'Accurately captured preference',
|
||||
feedbackReason: 'Accurately captured preference',
|
||||
});
|
||||
```
|
||||
|
||||
@@ -248,7 +235,7 @@ const exportReq = await client.createMemoryExport({
|
||||
filters: { user_id: 'alice' },
|
||||
});
|
||||
|
||||
const result = await client.getMemoryExport({ memory_export_id: exportReq.id });
|
||||
const result = await client.getMemoryExport({ memoryExportId: exportReq.id });
|
||||
```
|
||||
|
||||
---
|
||||
@@ -259,14 +246,12 @@ Key interfaces from `mem0.types.ts`:
|
||||
|
||||
```typescript
|
||||
interface Message { role: string; content: string; }
|
||||
interface Memory { id: string; memory: string; user_id: string; categories: string[]; score?: number; /* ... */ }
|
||||
interface MemoryOptions { user_id?: string; agent_id?: string; app_id?: string; run_id?: string; metadata?: object; /* ... */ }
|
||||
interface SearchOptions { user_id?: string; filters?: object; top_k?: number; rerank?: boolean; threshold?: number; /* ... */ }
|
||||
interface MemoryHistory { id: string; memory_id: string; previous_value: string; new_value: string; action: string; /* ... */ }
|
||||
interface FeedbackPayload { memory_id: string; feedback: string; feedback_reason?: string; }
|
||||
interface WebhookCreatePayload { url: string; name: string; project_id: string; event_types: string[]; }
|
||||
enum OutputFormat { v1_0 = 'v1.0', v1_1 = 'v1.1' }
|
||||
enum API_VERSION { v1 = 'v1', v2 = 'v2' }
|
||||
interface Memory { id: string; memory: string; userId: string; categories: string[]; score?: number; /* ... */ }
|
||||
interface MemoryOptions { userId?: string; agentId?: string; appId?: string; runId?: string; metadata?: object; /* ... */ }
|
||||
interface SearchOptions { filters?: object; topK?: number; rerank?: boolean; threshold?: number; /* ... */ }
|
||||
interface MemoryHistory { id: string; memoryId: string; previousValue: string; newValue: string; action: string; /* ... */ }
|
||||
interface FeedbackPayload { memoryId: string; feedback: string; feedbackReason?: string; }
|
||||
interface WebhookCreatePayload { url: string; name: string; projectId: string; eventTypes: string[]; }
|
||||
```
|
||||
|
||||
---
|
||||
@@ -296,7 +281,7 @@ const config = {
|
||||
llm: {
|
||||
provider: 'openai', // openai, groq, anthropic, google, ollama, lmstudio, mistral, azure
|
||||
config: {
|
||||
model: 'gpt-4o-mini',
|
||||
model: 'gpt-5-mini',
|
||||
apiKey: 'sk-xxx',
|
||||
},
|
||||
},
|
||||
@@ -315,17 +300,8 @@ const config = {
|
||||
port: 6333,
|
||||
},
|
||||
},
|
||||
graphStore: { // Optional
|
||||
provider: 'neo4j',
|
||||
config: {
|
||||
url: 'neo4j://localhost:7687',
|
||||
username: 'neo4j',
|
||||
password: 'password',
|
||||
},
|
||||
},
|
||||
historyDbPath: 'history.db',
|
||||
customPrompt: '...',
|
||||
enableGraph: false,
|
||||
customInstructions: '...',
|
||||
disableHistory: false,
|
||||
};
|
||||
|
||||
@@ -363,17 +339,14 @@ await m.add([
|
||||
#### search(query, config)
|
||||
|
||||
```typescript
|
||||
const results = await m.search('dietary preferences', { userId: 'alice', limit: 5 });
|
||||
const results = await m.search('dietary preferences', { filters: { user_id: 'alice' }, topK: 5 });
|
||||
```
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `query` | string | Search query |
|
||||
| `config.userId` | string | Filter by user |
|
||||
| `config.agentId` | string | Filter by agent |
|
||||
| `config.runId` | string | Filter by run |
|
||||
| `config.limit` | number | Max results (default: 100) |
|
||||
| `config.filters` | object | Advanced filters |
|
||||
| `config.filters` | object | Filter object with entity IDs (`user_id`, `agent_id`, `run_id`, etc.) |
|
||||
| `config.topK` | number | Max results (default: 20) |
|
||||
|
||||
#### get(memoryId) / getAll(config) / update(memoryId, data) / delete(memoryId) / deleteAll(config) / history(memoryId)
|
||||
|
||||
@@ -401,12 +374,45 @@ await m.reset();
|
||||
| **Auth** | API key required (`MEM0_API_KEY`) | No API key -- config-based |
|
||||
| **Execution** | API calls to `api.mem0.ai` | Local execution |
|
||||
| **Infrastructure** | Fully managed | Self-managed vector DB, embedder, LLM |
|
||||
| **Param style** | `snake_case` in options (`user_id`) | `camelCase` in config (`userId`) |
|
||||
| **Param style** | Top-level: `camelCase` (`userId`, `topK`), filter keys: `snake_case` (`user_id`) | Top-level: `camelCase` (`userId`, `topK`), filter keys: `snake_case` (`user_id`) |
|
||||
| **Batch ops** | `batchUpdate`, `batchDelete` | Not available |
|
||||
| **Webhooks** | Full CRUD | Not available |
|
||||
| **Export** | `createMemoryExport` | Not available |
|
||||
| **Feedback** | `feedback()` | Not available |
|
||||
| **Project mgmt** | `getProject`, `updateProject` | Not available |
|
||||
| **User listing** | `users()`, `deleteUser()` | Not available |
|
||||
| **Graph store** | Platform-managed | Self-managed (Neo4j) |
|
||||
| **History** | Platform-managed | SQLite (configurable) |
|
||||
|
||||
---
|
||||
|
||||
## v2 Compatibility
|
||||
|
||||
If you're using SDK v2.x:
|
||||
|
||||
**Naming Changes:**
|
||||
- Top-level params now use camelCase: `topK`, `rerank` (not `top_k`)
|
||||
- Filter keys use snake_case: `user_id`, `agent_id`
|
||||
- OSS: `limit` renamed to `topK`
|
||||
|
||||
**API Changes:**
|
||||
```typescript
|
||||
// v2 - top-level entity IDs, snake_case
|
||||
await client.search("query", { user_id: "alice", top_k: 20 });
|
||||
|
||||
// v3 - filters object with snake_case keys, camelCase top-level params
|
||||
await client.search("query", { filters: { user_id: "alice" }, topK: 20 });
|
||||
```
|
||||
|
||||
**Default Changes:**
|
||||
| Param | v2 | v3 |
|
||||
|-------|----|----|
|
||||
| `topK` | 100 | 20 |
|
||||
| `threshold` | none | 0.1 |
|
||||
| `rerank` | true | false |
|
||||
|
||||
**Removed:**
|
||||
- `OutputFormat` and `API_VERSION` enums
|
||||
- `organizationId`, `projectId` from constructor
|
||||
- `enableGraph`, `asyncMode`, `outputFormat`, `immutable`, `expirationDate`, `filterMemories`, `batchSize`, `forceAddOnly`, `includes`, `excludes`, `keywordSearch`
|
||||
|
||||
See the [v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for details.
|
||||
|
||||
@@ -36,7 +36,7 @@ client = AsyncMemoryClient(api_key="m0-xxx")
|
||||
|
||||
# Or use as context manager
|
||||
async with AsyncMemoryClient(api_key="m0-xxx") as client:
|
||||
results = await client.search("query", user_id="alice")
|
||||
results = await client.search("query", filters={"user_id": "alice"})
|
||||
```
|
||||
|
||||
Same methods as `MemoryClient`, all `async`/`await`. Supports async context manager.
|
||||
@@ -65,25 +65,19 @@ client.add(messages, user_id="alice")
|
||||
| `app_id` | str | None | Application identifier |
|
||||
| `run_id` | str | None | Session/run identifier |
|
||||
| `metadata` | dict | None | Custom key-value pairs |
|
||||
| `enable_graph` | bool | None | Activate knowledge graph extraction |
|
||||
| `infer` | bool | True | If False, store raw text without LLM inference |
|
||||
| `immutable` | bool | None | If True, prevents future modification |
|
||||
| `expiration_date` | str | None | Auto-expiry date (`YYYY-MM-DD`) |
|
||||
| `includes` | str | None | Preference filter for inclusion |
|
||||
| `excludes` | str | None | Preference filter for exclusion |
|
||||
| `async_mode` | bool | True | If False, wait for processing to complete |
|
||||
| `custom_categories` | list | None | Override project categories |
|
||||
| `custom_instructions` | str | None | Override extraction instructions |
|
||||
| `timestamp` | int \| float \| str | None | Custom timestamp (Unix epoch or ISO 8601) |
|
||||
|
||||
**Returns:** `dict` -- list of events: `[{"id": "...", "event": "ADD|UPDATE|DELETE", "data": {"memory": "..."}}]`
|
||||
**Returns:** `dict` -- list of events: `[{"id": "...", "event": "ADD", "data": {"memory": "..."}}]`
|
||||
|
||||
#### search(query, **kwargs)
|
||||
|
||||
Search memories by semantic similarity.
|
||||
|
||||
```python
|
||||
results = client.search("dietary preferences", user_id="alice")
|
||||
results = client.search("dietary preferences", filters={"user_id": "alice"})
|
||||
for mem in results.get("results", []):
|
||||
print(mem["memory"], mem["score"])
|
||||
```
|
||||
@@ -91,20 +85,14 @@ for mem in results.get("results", []):
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `query` | str | required | Natural language search query |
|
||||
| `user_id` | str | None | Filter by user |
|
||||
| `agent_id` | str | None | Filter by agent |
|
||||
| `app_id` | str | None | Filter by app |
|
||||
| `filters` | dict | None | Filter object with entity IDs and/or `AND`/`OR`/`NOT` conditions (e.g., `{"user_id": "alice"}`) |
|
||||
| `top_k` | int | 10 | Number of results |
|
||||
| `filters` | dict | None | V2 filter object (`AND`/`OR`/`NOT`) |
|
||||
| `rerank` | bool | None | Enable deep semantic reranking (+150-200ms) |
|
||||
| `threshold` | float | 0.3 | Minimum similarity score |
|
||||
| `keyword_search` | bool | None | Enable keyword-based search (+10ms) |
|
||||
| `enable_graph` | bool | None | Include graph relations in results |
|
||||
| `filter_memories` | bool | None | Precision filtering, removes low-relevance (+200-300ms) |
|
||||
| `rerank` | bool | False | Enable deep semantic reranking (+150-200ms) |
|
||||
| `threshold` | float | 0.1 | Minimum similarity score |
|
||||
| `fields` | list | None | Specific fields to return |
|
||||
| `categories` | list | None | Filter by category |
|
||||
|
||||
**Returns:** `dict` -- `{"results": [{id, memory, user_id, categories, score, created_at, ...}], "relations": [...]}`
|
||||
**Returns:** `dict` -- `{"results": [{id, memory, user_id, categories, score, created_at, ...}]}`
|
||||
|
||||
#### get(memory_id)
|
||||
|
||||
@@ -121,27 +109,23 @@ memory = client.get(memory_id="ea925981-...")
|
||||
Retrieve all memories with optional filtering. Requires at least one entity identifier.
|
||||
|
||||
```python
|
||||
memories = client.get_all(user_id="alice")
|
||||
# With filters
|
||||
memories = client.get_all(filters={"user_id": "alice"})
|
||||
# With compound filters
|
||||
memories = client.get_all(filters={"AND": [{"user_id": "alice"}, {"categories": {"contains": "health"}}]})
|
||||
```
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `user_id` | str | None | Filter by user |
|
||||
| `agent_id` | str | None | Filter by agent |
|
||||
| `app_id` | str | None | Filter by app |
|
||||
| `filters` | dict | None | Filter object with entity IDs and/or `AND`/`OR`/`NOT` conditions |
|
||||
| `top_k` | int | None | Limit results |
|
||||
| `page` | int | None | Page number |
|
||||
| `page_size` | int | None | Results per page |
|
||||
| `filters` | dict | None | V2 filter object |
|
||||
| `enable_graph` | bool | None | Include graph relations |
|
||||
|
||||
**Returns:** `dict` -- `{"results": [...]}`
|
||||
|
||||
#### update(memory_id, text=None, metadata=None, timestamp=None)
|
||||
|
||||
Update a memory's content, metadata, or timestamp. At least one parameter required. Cannot update immutable memories.
|
||||
Update a memory's content, metadata, or timestamp. At least one parameter required.
|
||||
|
||||
```python
|
||||
client.update("ea925981-...", text="Updated: vegan since 2024")
|
||||
@@ -320,11 +304,10 @@ config = client.project.get(fields=["custom_categories", "custom_instructions"])
|
||||
client.project.update(
|
||||
custom_instructions="Extract dietary preferences and health info",
|
||||
custom_categories=[{"health": "Medical and dietary info"}],
|
||||
enable_graph=True,
|
||||
multilingual=True,
|
||||
)
|
||||
|
||||
# Create/delete project (requires org_id)
|
||||
# Create/delete project
|
||||
client.project.create(name="My Project", description="...")
|
||||
client.project.delete()
|
||||
|
||||
@@ -362,7 +345,7 @@ config = {
|
||||
"llm": {
|
||||
"provider": "openai", # openai, groq, azure, ollama, lmstudio, google, anthropic, mistral
|
||||
"config": {
|
||||
"model": "gpt-4o-mini",
|
||||
"model": "gpt-5-mini",
|
||||
"api_key": "sk-xxx",
|
||||
}
|
||||
},
|
||||
@@ -381,18 +364,8 @@ config = {
|
||||
"port": 6333,
|
||||
}
|
||||
},
|
||||
"graph_store": { # Optional
|
||||
"provider": "neo4j",
|
||||
"config": {
|
||||
"url": "neo4j://localhost:7687",
|
||||
"username": "neo4j",
|
||||
"password": "password",
|
||||
}
|
||||
},
|
||||
"history_db_path": "history.db", # SQLite path for change history
|
||||
"custom_instructions": "...", # Custom LLM prompt for extraction
|
||||
"custom_update_memory_prompt": "...", # Custom LLM prompt for updates
|
||||
"enable_graph": False, # Enable graph memory
|
||||
"custom_instructions": "...", # Custom LLM prompt for extraction
|
||||
}
|
||||
|
||||
m = Memory.from_config(config)
|
||||
@@ -403,7 +376,7 @@ m = Memory.from_config(config)
|
||||
```python
|
||||
with Memory(config) as m:
|
||||
m.add("I prefer dark mode", user_id="alice")
|
||||
results = m.search("preferences", user_id="alice")
|
||||
results = m.search("preferences", filters={"user_id": "alice"})
|
||||
# SQLite connections released automatically
|
||||
```
|
||||
|
||||
@@ -425,12 +398,14 @@ At least one of `user_id`, `agent_id`, `run_id` required.
|
||||
|
||||
**Returns:** `{"results": [...], "relations": [...]}`
|
||||
|
||||
#### search(query, *, user_id, agent_id, run_id, limit=100, filters=None, threshold=None, rerank=True)
|
||||
#### search(query, *, filters=None, top_k=20, threshold=0.1, rerank=False)
|
||||
|
||||
```python
|
||||
results = m.search("dietary preferences", user_id="alice", limit=5)
|
||||
results = m.search("dietary preferences", filters={"user_id": "alice"}, top_k=5)
|
||||
```
|
||||
|
||||
Entity IDs (`user_id`, `agent_id`, `run_id`) must be passed inside the `filters` dict.
|
||||
|
||||
Supports filter operators: `eq`, `ne`, `in`, `nin`, `gt`, `gte`, `lt`, `lte`, `contains`, `not_contains`.
|
||||
|
||||
#### get(memory_id) / get_all(**kwargs) / update(memory_id, data, metadata=None) / delete(memory_id) / delete_all(**kwargs) / history(memory_id)
|
||||
@@ -456,7 +431,7 @@ from mem0 import AsyncMemory
|
||||
|
||||
m = AsyncMemory(config)
|
||||
await m.add("text", user_id="alice")
|
||||
results = await m.search("query", user_id="alice")
|
||||
results = await m.search("query", filters={"user_id": "alice"})
|
||||
```
|
||||
|
||||
---
|
||||
@@ -469,13 +444,44 @@ results = await m.search("query", user_id="alice")
|
||||
| **Auth** | API key required (`MEM0_API_KEY`) | No API key -- config-based |
|
||||
| **Execution** | API calls to `api.mem0.ai` | Local execution |
|
||||
| **Infrastructure** | Fully managed | Self-managed vector DB, embedder, LLM |
|
||||
| **Entity filtering** | `filters={"user_id": "..."}` | `filters={"user_id": "..."}` |
|
||||
| **Batch ops** | `batch_update`, `batch_delete` | Not available |
|
||||
| **Webhooks** | Full CRUD | Not available |
|
||||
| **Export** | `create_memory_export`, `get_memory_export` | Not available |
|
||||
| **Feedback** | `feedback()` | Not available |
|
||||
| **Project mgmt** | `client.project.*` | Not available |
|
||||
| **User listing** | `users()`, `delete_users()` | Not available |
|
||||
| **Custom prompts** | Via project settings | Direct config |
|
||||
| **Graph store** | Platform-managed | Self-managed (Neo4j) |
|
||||
| **Custom prompts** | Via project settings | Direct config (`custom_instructions`) |
|
||||
| **History** | Platform-managed | SQLite (configurable) |
|
||||
| **Async** | `AsyncMemoryClient` | `AsyncMemory` |
|
||||
|
||||
---
|
||||
|
||||
## v2 Compatibility
|
||||
|
||||
If you're using SDK v2.x or the v2 API:
|
||||
|
||||
**API Changes:**
|
||||
- **Entity IDs in search/get_all:** Pass `user_id`, `agent_id` as top-level kwargs instead of inside `filters`
|
||||
```python
|
||||
# v2
|
||||
results = client.search("query", user_id="alice")
|
||||
# v3
|
||||
results = client.search("query", filters={"user_id": "alice"})
|
||||
```
|
||||
- **add() returns:** v2 returns ADD, UPDATE, DELETE events; v3 returns ADD only
|
||||
|
||||
**Default Changes:**
|
||||
| Param | v2 | v3 |
|
||||
|-------|----|----|
|
||||
| `top_k` | 100 | 20 |
|
||||
| `threshold` | None | 0.1 |
|
||||
| `rerank` | True | False |
|
||||
|
||||
**Removed Parameters:**
|
||||
- Constructor: `org_id`, `project_id`
|
||||
- add(): `async_mode`, `output_format`, `enable_graph`, `immutable`, `expiration_date`, `filter_memories`, `batch_size`, `force_add_only`, `includes`, `excludes`, `keyword_search`
|
||||
- search()/get_all(): `enable_graph`
|
||||
- Config: `enable_graph`, `graph_store`, `custom_fact_extraction_prompt` (renamed to `custom_instructions`)
|
||||
|
||||
See the [v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for full details.
|
||||
|
||||
@@ -8,13 +8,15 @@ All endpoints require: `Authorization: Token <MEM0_API_KEY>`
|
||||
|
||||
| Operation | Method | URL |
|
||||
|-----------|--------|-----|
|
||||
| Add Memories | `POST` | `/v1/memories/` |
|
||||
| Search Memories | `POST` | `/v2/memories/search/` |
|
||||
| Get All Memories | `POST` | `/v2/memories/` |
|
||||
| Add Memories | `POST` | `/v3/memories/add/` |
|
||||
| Search Memories | `POST` | `/v3/memories/search/` |
|
||||
| Get All Memories | `POST` | `/v3/memories/` |
|
||||
| Get Single Memory | `GET` | `/v1/memories/{memory_id}/` |
|
||||
| Update Memory | `PUT` | `/v1/memories/{memory_id}/` |
|
||||
| Delete Memory | `DELETE` | `/v1/memories/{memory_id}/` |
|
||||
|
||||
Note: v1/v2 endpoints still work (backward compatible).
|
||||
|
||||
## Memory Object Structure
|
||||
|
||||
| Field | Type | Description |
|
||||
@@ -27,8 +29,6 @@ All endpoints require: `Authorization: Token <MEM0_API_KEY>`
|
||||
| `run_id` | string (nullable) | Run/session identifier |
|
||||
| `metadata` | object | Custom key-value pairs |
|
||||
| `categories` | array of strings | Auto-assigned category tags |
|
||||
| `immutable` | boolean | If true, prevents modification |
|
||||
| `expiration_date` | datetime (nullable) | Auto-expiry date |
|
||||
| `hash` | string | Content hash |
|
||||
| `created_at` | datetime | Creation timestamp |
|
||||
| `updated_at` | datetime | Last modification timestamp |
|
||||
@@ -50,10 +50,9 @@ Memories can be scoped to different levels:
|
||||
|
||||
## Processing Model
|
||||
|
||||
- Memories are processed **asynchronously by default** (`async_mode=true`)
|
||||
- Add responses return queued events (`ADD`, `UPDATE`, `DELETE`) for tracking
|
||||
- Set `async_mode=false` for synchronous processing when needed
|
||||
- Graph metadata is processed asynchronously -- use `get_all()` for complete graph data
|
||||
- Memories are processed **asynchronously** (v3 default)
|
||||
- Add responses return queued `ADD` events only (v3 is ADD-only, no UPDATE/DELETE)
|
||||
- Poll status via `GET /v1/event/{event_id}/`
|
||||
|
||||
## Filter System
|
||||
|
||||
@@ -106,19 +105,17 @@ Root must be `AND`, `OR`, or `NOT`. Simple shorthand `{"user_id": "alice"}` also
|
||||
|
||||
## Response Formats
|
||||
|
||||
### Add Response
|
||||
### Add Response (v3)
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": "mem_01JF8ZS4Y0R0SPM13R5R6H32CJ",
|
||||
"event": "ADD",
|
||||
"data": { "memory": "The user moved to Austin in 2025." }
|
||||
}
|
||||
]
|
||||
{
|
||||
"message": "Memory processing has been queued for background execution",
|
||||
"status": "PENDING",
|
||||
"event_id": "evt-uuid"
|
||||
}
|
||||
```
|
||||
|
||||
Event types: `ADD`, `UPDATE`, `DELETE`. A single add can trigger multiple events.
|
||||
v3 is ADD-only. No UPDATE or DELETE events.
|
||||
|
||||
### Search Response
|
||||
|
||||
@@ -137,4 +134,17 @@ Event types: `ADD`, `UPDATE`, `DELETE`. A single add can trigger multiple events
|
||||
}
|
||||
```
|
||||
|
||||
With `enable_graph=true`, includes additional `relations` array with entity relationships.
|
||||
In v3, `score` is a combined multi-signal relevance score.
|
||||
|
||||
### Get All Response (v3)
|
||||
|
||||
```json
|
||||
{
|
||||
"count": 123,
|
||||
"next": "https://api.mem0.ai/v3/memories/?page=2&page_size=50",
|
||||
"previous": null,
|
||||
"results": [...]
|
||||
}
|
||||
```
|
||||
|
||||
v3 returns paginated envelope. Use `page` and `page_size` query params.
|
||||
|
||||
@@ -25,9 +25,9 @@ User Input → Retrieve relevant memories → Enrich LLM prompt → Generate res
|
||||
|
||||
Mem0 handles the complexity of extraction, deduplication, conflict resolution, and semantic retrieval so your application only needs to call `search()` and `add()`.
|
||||
|
||||
**Dual storage architecture:**
|
||||
**Storage architecture:**
|
||||
- **Vector store**: Embeddings for semantic similarity search
|
||||
- **Graph store** (optional): Entity nodes and relationship edges for structured knowledge
|
||||
- **Entity store**: Automatic entity linking for relationship-aware retrieval
|
||||
|
||||
---
|
||||
|
||||
@@ -40,41 +40,32 @@ Messages In
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ 1. EXTRACTION │ LLM analyzes messages, extracts key facts
|
||||
│ 1. EXTRACTION │ Single LLM call extracts all distinct new facts
|
||||
│ (infer=True) │ If infer=False, stores raw text as-is
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ 2. CONFLICT │ Checks existing memories for duplicates
|
||||
│ RESOLUTION │ Latest truth wins (newer overrides older)
|
||||
│ │ Only runs when infer=True
|
||||
│ 2. DEDUPLICATION │ Hash-based dedup (MD5 prevents exact duplicates)
|
||||
│ │ No UPDATE/DELETE - v3 is ADD-only
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ 3. STORAGE │ Generates embeddings → vector store
|
||||
│ │ Optional: entity extraction → graph store
|
||||
│ │ Indexes metadata, categories, timestamps
|
||||
│ 3. STORAGE │ Batch embed → vector store
|
||||
│ │ Entity extraction → entity store
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
Memory Object
|
||||
(id, memory, categories, structured_attributes)
|
||||
```
|
||||
|
||||
### Processing modes
|
||||
### Processing (v3)
|
||||
|
||||
**Async (default, `async_mode=True`):**
|
||||
- API returns immediately: `{"status": "PENDING", "event_id": "..."}`
|
||||
- Processing happens in background
|
||||
v3 processes memories asynchronously by default:
|
||||
- API returns immediately: `{"status": "PENDING", "event_id": "evt-..."}`
|
||||
- Poll status via `GET /v1/event/{event_id}/`
|
||||
- Use webhooks for completion notifications
|
||||
- Best for: high-throughput, non-blocking workflows
|
||||
|
||||
**Sync (`async_mode=False`):**
|
||||
- API waits for full processing
|
||||
- Returns complete memory object with `id`, `event`, `memory`
|
||||
- Best for: real-time access immediately after add
|
||||
|
||||
### Extraction modes
|
||||
|
||||
@@ -93,7 +84,7 @@ Messages In
|
||||
|
||||
---
|
||||
|
||||
## Retrieval Pipeline
|
||||
## Retrieval Pipeline (v3)
|
||||
|
||||
### What happens when you call `client.search()`
|
||||
|
||||
@@ -102,45 +93,37 @@ Query In
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ 1. QUERY EMBEDDING │ Convert query to vector representation
|
||||
│ 1. PREPROCESSING │ Lemmatize keywords, extract entities
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ 2. VECTOR SEARCH │ Cosine similarity across stored embeddings
|
||||
│ │ Scoped by filters (user_id, agent_id, etc.)
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼ (optional enhancements)
|
||||
┌─────────────────────┐
|
||||
│ 3a. KEYWORD SEARCH │ Expands results with specific terms (+10ms)
|
||||
│ 3b. RERANKING │ Deep semantic reordering (+150-200ms)
|
||||
│ 3c. FILTER MEMORIES │ Precision filtering, removes low-relevance (+200-300ms)
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼ (if enable_graph=True)
|
||||
┌─────────────────────┐
|
||||
│ 4. GRAPH LOOKUP │ Finds entity relationships
|
||||
│ │ Appends relations WITHOUT reranking vector results
|
||||
│ 2. PARALLEL SCORING │ Semantic search (vector similarity)
|
||||
│ │ BM25 keyword search (term matching)
|
||||
│ │ Entity matching (entity graph boost)
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
Results + Relations
|
||||
┌─────────────────────┐
|
||||
│ 3. SCORE FUSION │ Combine signals into single score
|
||||
│ │ Optional: rerank=True for deep reordering
|
||||
└─────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
Results (combined score per memory)
|
||||
```
|
||||
|
||||
### Retrieval enhancement combinations
|
||||
### v3 Search Defaults
|
||||
|
||||
| Configuration | Latency | Best for |
|
||||
|--------------|---------|----------|
|
||||
| Base search only | ~100ms | Simple lookups |
|
||||
| `keyword_search=True` | ~110ms | Entity-heavy queries, broad coverage |
|
||||
| `rerank=True` | ~250-300ms | User-facing results, top-N precision |
|
||||
| `keyword_search=True` + `rerank=True` | ~310ms | Balanced (recommended for most apps) |
|
||||
| `rerank=True` + `filter_memories=True` | ~400-500ms | Safety-critical, production systems |
|
||||
| Parameter | Default | Notes |
|
||||
|-----------|---------|-------|
|
||||
| `top_k` | 20 | Was 100 in v2 |
|
||||
| `threshold` | 0.1 | Was None in v2 |
|
||||
| `rerank` | False | Was True in v2 |
|
||||
|
||||
### Implicit null scoping
|
||||
|
||||
When you search with `user_id="alice"` only, Mem0 returns memories where `agent_id`, `app_id`, and `run_id` are all null. This prevents cross-scope leakage by default.
|
||||
When you search with `filters={"user_id": "alice"}` only, Mem0 returns memories where `agent_id`, `app_id`, and `run_id` are all null. This prevents cross-scope leakage by default.
|
||||
|
||||
To include memories with non-null fields, use explicit filters:
|
||||
```python
|
||||
@@ -150,53 +133,23 @@ filters={"OR": [{"user_id": "alice"}]}
|
||||
|
||||
---
|
||||
|
||||
## Memory Lifecycle
|
||||
## Memory Lifecycle (v3)
|
||||
|
||||
```
|
||||
CREATE ──→ ACTIVE ──→ UPDATE ──→ ACTIVE
|
||||
│ │ │
|
||||
│ ▼ ▼
|
||||
│ EXPIRED EXPIRED
|
||||
│ (still stored, (still stored,
|
||||
│ not retrieved) not retrieved)
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
DELETE DELETE DELETE
|
||||
(permanent)
|
||||
```
|
||||
v3 uses ADD-only extraction. Memories accumulate over time rather than being consolidated.
|
||||
|
||||
### Creation
|
||||
- Triggered by `client.add(messages, user_id="...")`
|
||||
- Messages processed through extraction → conflict resolution → storage
|
||||
- Gets unique UUID, `created_at` timestamp
|
||||
- Optional: custom `timestamp`, `expiration_date`, `metadata`, `immutable`
|
||||
- `client.add(messages, user_id="...")`
|
||||
- Single-pass extraction → deduplication → storage
|
||||
- Returns `{"event_id": "...", "status": "PENDING"}`
|
||||
|
||||
### Updates
|
||||
- `client.update(memory_id, text="...")` replaces text and reindexes
|
||||
- `client.batch_update([...])` for up to 1000 memories at once
|
||||
- Immutable memories (`immutable=True`) cannot be updated — must delete and re-add
|
||||
|
||||
### Deduplication
|
||||
- Automatic during `add()` with `infer=True`
|
||||
- Conflict resolution merges duplicate facts
|
||||
- Latest truth wins when contradictions detected
|
||||
- Prevents memory bloat from repeated information
|
||||
|
||||
### Expiration
|
||||
- Optional `expiration_date` parameter (ISO 8601 or `YYYY-MM-DD`)
|
||||
- After expiration: memory NOT returned in searches but remains in storage
|
||||
- Useful for time-sensitive info (events, temporary preferences, session state)
|
||||
- `client.update(memory_id, text="...")` replaces text
|
||||
- Batch: `client.batch_update([...])`
|
||||
|
||||
### Deletion
|
||||
- Single: `client.delete(memory_id)` — permanent, no recovery
|
||||
- Batch: `client.batch_delete([memory_ids])` — up to 1000
|
||||
- Bulk: `client.delete_all(user_id="alice")` — all memories for entity
|
||||
- `delete_all()` without filters raises error to prevent accidental data loss
|
||||
|
||||
### History tracking
|
||||
- `client.history(memory_id)` returns version timeline
|
||||
- Shows all changes: `{previous_value, new_value, action, timestamps}`
|
||||
- Useful for audit trails and debugging
|
||||
- Single: `client.delete(memory_id)`
|
||||
- Batch: `client.batch_delete([...])`
|
||||
- Bulk: `client.delete_all(filters={"user_id": "alice"})`
|
||||
|
||||
---
|
||||
|
||||
@@ -214,8 +167,6 @@ DELETE DELETE DELETE
|
||||
"categories": ["health", "preferences"],
|
||||
"created_at": "2025-03-12T12:34:56Z",
|
||||
"updated_at": "2025-03-12T12:34:56Z",
|
||||
"expiration_date": null,
|
||||
"immutable": false,
|
||||
"structured_attributes": {
|
||||
"day": 12, "month": 3, "year": 2025,
|
||||
"hour": 12, "minute": 34,
|
||||
@@ -239,8 +190,6 @@ DELETE DELETE DELETE
|
||||
| `categories` | array | Auto-assigned or custom category tags |
|
||||
| `created_at` | datetime | Creation timestamp |
|
||||
| `updated_at` | datetime | Last modification timestamp |
|
||||
| `expiration_date` | datetime | Auto-expiry date (stops retrieval, data persists) |
|
||||
| `immutable` | boolean | If true, prevents modification |
|
||||
| `structured_attributes` | object | Temporal breakdown for time-based queries |
|
||||
| `score` | float | Semantic similarity (search results only, 0-1) |
|
||||
|
||||
@@ -322,7 +271,7 @@ Mem0 supports three layers of memory, from shortest to longest lived:
|
||||
```python
|
||||
def chat(user_input: str, user_id: str, session_id: str) -> str:
|
||||
# 1. Retrieve user memories (long-term preferences)
|
||||
user_mems = mem0.search(user_input, user_id=user_id)
|
||||
user_mems = mem0.search(user_input, filters={"user_id": user_id})
|
||||
|
||||
# 2. Retrieve session memories (current task context)
|
||||
session_mems = mem0.search(user_input, filters={
|
||||
@@ -350,18 +299,13 @@ def chat(user_input: str, user_id: str, session_id: str) -> str:
|
||||
|
||||
| Operation | Typical Latency |
|
||||
|-----------|----------------|
|
||||
| Base vector search | ~100ms |
|
||||
| + keyword_search | +10ms |
|
||||
| Hybrid search (v3 default) | ~100-150ms |
|
||||
| + reranking | +150-200ms |
|
||||
| + filter_memories | +200-300ms |
|
||||
| Add (async, default) | < 50ms response, background processing |
|
||||
| Add (sync) | 500ms-2s depending on extraction complexity |
|
||||
| Graph operations | Slight overhead for large stores |
|
||||
| Add (async) | < 50ms response |
|
||||
|
||||
### Processing
|
||||
|
||||
- **Async mode (default):** Returns immediately, processes in background
|
||||
- **Sync mode:** Waits for full extraction + storage pipeline
|
||||
- **Async (default):** Returns immediately, processes in background
|
||||
- **Batch operations:** Up to 1000 memories per batch_update/batch_delete
|
||||
- **Webhooks:** Real-time notifications when async processing completes
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ Additional platform capabilities beyond core CRUD operations.
|
||||
## Table of Contents
|
||||
|
||||
- [Advanced Retrieval](#advanced-retrieval)
|
||||
- [Graph Memory](#graph-memory)
|
||||
- [Entity Linking](#entity-linking)
|
||||
- [Custom Categories](#custom-categories)
|
||||
- [Custom Instructions](#custom-instructions)
|
||||
- [Criteria Retrieval](#criteria-retrieval)
|
||||
@@ -18,124 +18,58 @@ Additional platform capabilities beyond core CRUD operations.
|
||||
|
||||
## Advanced Retrieval
|
||||
|
||||
Three enhancement options for tuning search precision, recall, and latency.
|
||||
### Hybrid Search (v3 Default)
|
||||
|
||||
### Keyword Search (`keyword_search=True`)
|
||||
v3 uses multi-signal hybrid search combining:
|
||||
- **Semantic search** (vector similarity)
|
||||
- **BM25 keyword search** (normalized term matching)
|
||||
- **Entity matching** (entity graph boost)
|
||||
|
||||
Expands results to include memories with specific terms, names, and technical keywords.
|
||||
|
||||
- Latency: +10ms
|
||||
- Recall: Significantly increased
|
||||
- Best for: entity-heavy queries, comprehensive coverage
|
||||
This is automatic — no configuration needed.
|
||||
|
||||
### Reranking (`rerank=True`)
|
||||
|
||||
Deep semantic reordering of results — most relevant first.
|
||||
|
||||
- Latency: +150-200ms
|
||||
- Accuracy: Significantly improved
|
||||
- Default: `False` (was `True` in v2)
|
||||
- Best for: user-facing results, top-N precision
|
||||
|
||||
### Filter Memories (`filter_memories=True`)
|
||||
|
||||
Precision filtering — removes low-relevance results entirely.
|
||||
|
||||
- Latency: +200-300ms
|
||||
- Precision: Maximized
|
||||
- Best for: safety-critical applications, production systems
|
||||
|
||||
### Recommended Combinations
|
||||
|
||||
**Python:**
|
||||
```python
|
||||
# Fast & broad
|
||||
results = client.search(query, keyword_search=True, user_id="user123")
|
||||
|
||||
# Balanced (recommended for most apps)
|
||||
results = client.search(query, keyword_search=True, rerank=True, user_id="user123")
|
||||
|
||||
# High precision (critical apps)
|
||||
results = client.search(query, rerank=True, filter_memories=True, user_id="user123")
|
||||
results = client.search(query, filters={"user_id": "user123"}, rerank=True)
|
||||
```
|
||||
|
||||
**TypeScript:**
|
||||
```typescript
|
||||
const results = await client.search(query, {
|
||||
user_id: 'user123',
|
||||
keyword_search: true,
|
||||
filters: { user_id: 'user123' },
|
||||
rerank: true,
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Graph Memory
|
||||
## Entity Linking
|
||||
|
||||
Entity-level knowledge graph that creates relationships between memories.
|
||||
v3 replaces graph memory with built-in entity linking. Entities (proper nouns, quoted text, compound noun phrases) are automatically extracted and linked across memories.
|
||||
|
||||
### How It Works
|
||||
|
||||
1. **Extraction**: LLM analyzes conversation and identifies entities and relationships
|
||||
2. **Storage**: Embeddings go to vector store; entity nodes and edges go to graph store
|
||||
3. **Retrieval**: Vector search returns semantic matches; graph relations are appended to results
|
||||
1. **Extraction**: During `add()`, entities are automatically extracted from memory text
|
||||
2. **Storage**: Entities are stored in a parallel collection (`{collection}_entities`)
|
||||
3. **Retrieval**: During `search()`, query entities are matched and used to boost relevant memories
|
||||
|
||||
Graph relations **augment** vector results without reordering them. Vector similarity always determines hit sequence.
|
||||
Entity linking is automatic — no configuration required. The boost is folded into the combined `score` on each result.
|
||||
|
||||
### Enabling Graph Memory
|
||||
### v2 Migration Note
|
||||
|
||||
**Per request:**
|
||||
```python
|
||||
client.add(messages, user_id="alice", enable_graph=True)
|
||||
client.search("query", user_id="alice", enable_graph=True)
|
||||
client.get_all(filters={"AND": [{"user_id": "alice"}]}, enable_graph=True)
|
||||
```
|
||||
If you were using `enable_graph=True` in v2:
|
||||
- Remove `enable_graph` from all API calls
|
||||
- Remove `graph_store` from OSS configuration
|
||||
- Entity relationships are now consumed through retrieval ranking, not exposed as a separate `relations` array
|
||||
|
||||
**Project-level (default for all operations):**
|
||||
```python
|
||||
client.project.update(enable_graph=True)
|
||||
```
|
||||
|
||||
```javascript
|
||||
await client.updateProject({ enable_graph: true });
|
||||
```
|
||||
|
||||
### Relation Structure
|
||||
|
||||
Each relation in the response contains:
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `source` | string | Source entity name |
|
||||
| `source_type` | string | Source entity type (e.g., "Person") |
|
||||
| `relationship` | string | Relationship label (e.g., "lives_in") |
|
||||
| `target` | string | Target entity name |
|
||||
| `target_type` | string | Target entity type (e.g., "City") |
|
||||
| `score` | number | Confidence score |
|
||||
|
||||
**Example:**
|
||||
```json
|
||||
{
|
||||
"relations": [
|
||||
{
|
||||
"source": "Joseph",
|
||||
"source_type": "Person",
|
||||
"relationship": "lives_in",
|
||||
"target": "Seattle",
|
||||
"target_type": "City",
|
||||
"score": 0.92
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Technical Notes
|
||||
|
||||
- Graph Memory adds processing time; see docs for current plan availability
|
||||
- Works optimally with rich conversation histories containing entity relationships
|
||||
- Best suited for long-running assistants tracking evolving information
|
||||
- Graph writes and reads toggle independently per request
|
||||
- Multi-agent context supported via `user_id`, `agent_id`, `run_id` scoping
|
||||
- Add operations are asynchronous; graph metadata may not be immediately available
|
||||
See the [v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for details.
|
||||
|
||||
---
|
||||
|
||||
@@ -160,7 +94,7 @@ client.project.update(custom_categories=new_categories)
|
||||
```
|
||||
|
||||
```javascript
|
||||
await client.updateProject({ custom_categories: new_categories });
|
||||
await client.updateProject({ customCategories: newCategories });
|
||||
```
|
||||
|
||||
**Retrieve active categories:**
|
||||
@@ -185,7 +119,7 @@ client.project.update(custom_instructions="Your guidelines here...")
|
||||
```
|
||||
|
||||
```javascript
|
||||
await client.updateProject({ custom_instructions: "Your guidelines here..." });
|
||||
await client.updateProject({ customInstructions: "Your guidelines here..." });
|
||||
```
|
||||
|
||||
### Template Structure
|
||||
@@ -229,7 +163,7 @@ client.project.update(retrieval_criteria=retrieval_criteria)
|
||||
|
||||
```typescript
|
||||
await client.updateProject({
|
||||
retrieval_criteria: [
|
||||
retrievalCriteria: [
|
||||
{ name: 'joy', description: 'Positive emotions', weight: 3 },
|
||||
{ name: 'urgency', description: 'Time-sensitive items', weight: 4 },
|
||||
],
|
||||
@@ -281,7 +215,7 @@ for item in feedback_data:
|
||||
```typescript
|
||||
await client.feedback('mem-123', {
|
||||
feedback: 'POSITIVE',
|
||||
feedback_reason: 'Accurately captured dietary preference',
|
||||
feedbackReason: 'Accurately captured dietary preference',
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ from langchain_core.messages import SystemMessage, HumanMessage
|
||||
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
||||
from mem0 import MemoryClient
|
||||
|
||||
llm = ChatOpenAI(model="gpt-4.1-nano-2025-04-14")
|
||||
llm = ChatOpenAI(model="gpt-5-mini")
|
||||
mem0 = MemoryClient()
|
||||
|
||||
prompt = ChatPromptTemplate.from_messages([
|
||||
@@ -128,7 +128,7 @@ import { createMem0 } from "@mem0/vercel-ai-provider";
|
||||
|
||||
const mem0 = createMem0();
|
||||
const { text } = await generateText({
|
||||
model: mem0("gpt-4-turbo", { user_id: "borat" }),
|
||||
model: mem0("gpt-5-mini", { user_id: "borat" }),
|
||||
prompt: "Suggest me a good car to buy!",
|
||||
});
|
||||
```
|
||||
@@ -167,7 +167,7 @@ agent = Agent(
|
||||
Use search_memory to recall past conversations.
|
||||
Use save_memory to store important information.""",
|
||||
tools=[search_memory, save_memory],
|
||||
model="gpt-4.1-nano-2025-04-14"
|
||||
model="gpt-5-mini"
|
||||
)
|
||||
|
||||
result = Runner.run_sync(agent, "I love Italian food and I'm planning a trip to Rome next month")
|
||||
@@ -183,21 +183,21 @@ travel_agent = Agent(
|
||||
name="Travel Planner",
|
||||
instructions="You are a travel planning specialist. Use search_memory and save_memory tools.",
|
||||
tools=[search_memory, save_memory],
|
||||
model="gpt-4.1-nano-2025-04-14"
|
||||
model="gpt-5-mini"
|
||||
)
|
||||
|
||||
health_agent = Agent(
|
||||
name="Health Advisor",
|
||||
instructions="You are a health and wellness advisor. Use search_memory and save_memory tools.",
|
||||
tools=[search_memory, save_memory],
|
||||
model="gpt-4.1-nano-2025-04-14"
|
||||
model="gpt-5-mini"
|
||||
)
|
||||
|
||||
triage_agent = Agent(
|
||||
name="Personal Assistant",
|
||||
instructions="""Route travel questions to Travel Planner, health questions to Health Advisor.""",
|
||||
handoffs=[travel_agent, health_agent],
|
||||
model="gpt-4.1-nano-2025-04-14"
|
||||
model="gpt-5-mini"
|
||||
)
|
||||
|
||||
result = Runner.run_sync(triage_agent, "Plan a healthy meal for my Italy trip")
|
||||
@@ -254,7 +254,7 @@ from langchain_openai import ChatOpenAI
|
||||
from mem0 import MemoryClient
|
||||
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
|
||||
|
||||
llm = ChatOpenAI(model="gpt-4")
|
||||
llm = ChatOpenAI(model="gpt-5-mini")
|
||||
mem0 = MemoryClient()
|
||||
|
||||
class State(TypedDict):
|
||||
@@ -319,7 +319,7 @@ memory = Mem0Memory.from_client(
|
||||
from llama_index.core.agent import FunctionCallingAgent
|
||||
from llama_index.llms.openai import OpenAI
|
||||
|
||||
llm = OpenAI(model="gpt-4")
|
||||
llm = OpenAI(model="gpt-5-mini")
|
||||
agent = FunctionCallingAgent.from_tools(
|
||||
tools=[],
|
||||
llm=llm,
|
||||
@@ -352,7 +352,7 @@ USER_ID = "alice"
|
||||
|
||||
agent = ConversableAgent(
|
||||
"chatbot",
|
||||
llm_config={"config_list": [{"model": "gpt-4", "api_key": os.environ["OPENAI_API_KEY"]}]},
|
||||
llm_config={"config_list": [{"model": "gpt-5-mini", "api_key": os.environ["OPENAI_API_KEY"]}]},
|
||||
code_execution_config=False,
|
||||
human_input_mode="NEVER",
|
||||
)
|
||||
|
||||
@@ -59,11 +59,11 @@ const messages = [
|
||||
{"role": "user", "content": "I'm a vegetarian and allergic to nuts."},
|
||||
{"role": "assistant", "content": "Got it! I'll remember your dietary preferences."}
|
||||
];
|
||||
await client.add(messages, { user_id: "user123" });
|
||||
await client.add(messages, { userId: "user123" });
|
||||
|
||||
// Search memories
|
||||
const results = await client.search("What are my dietary restrictions?", {
|
||||
user_id: "user123"
|
||||
filters: { user_id: "user123" }
|
||||
});
|
||||
console.log(results);
|
||||
```
|
||||
|
||||
@@ -40,16 +40,12 @@ client.add(messages, user_id="alice")
|
||||
|
||||
# With metadata
|
||||
client.add(messages, user_id="alice", metadata={"source": "onboarding"})
|
||||
|
||||
# With graph memory
|
||||
client.add(messages, user_id="alice", enable_graph=True)
|
||||
```
|
||||
|
||||
**TypeScript:**
|
||||
```typescript
|
||||
await client.add(messages, { user_id: "alice" });
|
||||
await client.add(messages, { user_id: "alice", metadata: { source: "onboarding" } });
|
||||
await client.add(messages, { user_id: "alice", enable_graph: true });
|
||||
await client.add(messages, { userId: "alice" });
|
||||
await client.add(messages, { userId: "alice", metadata: { source: "onboarding" } });
|
||||
```
|
||||
|
||||
### Parameters
|
||||
@@ -61,32 +57,14 @@ await client.add(messages, { user_id: "alice", enable_graph: true });
|
||||
| `agent_id` | string | Agent identifier |
|
||||
| `run_id` | string | Session identifier |
|
||||
| `metadata` | object | Custom key-value pairs |
|
||||
| `enable_graph` | boolean | Activate knowledge graph |
|
||||
| `infer` | boolean | If `false`, store raw text without inference (default: `true`) |
|
||||
| `immutable` | boolean | Prevents modification after creation |
|
||||
| `expiration_date` | string | Auto-expiry date (`YYYY-MM-DD`) |
|
||||
| `includes` | string | Preference filters for inclusion |
|
||||
| `excludes` | string | Preference filters for exclusion |
|
||||
| `async_mode` | boolean | Async processing (default: `true`). Set `false` to wait |
|
||||
|
||||
### Advanced Add Options
|
||||
|
||||
```python
|
||||
# Immutable -- cannot be modified or overwritten
|
||||
client.add(messages, user_id="alice", immutable=True)
|
||||
|
||||
# Expiring memory
|
||||
client.add(messages, user_id="alice", expiration_date="2025-12-31")
|
||||
|
||||
# Selective extraction
|
||||
client.add(messages, user_id="alice", includes="dietary preferences", excludes="payment info")
|
||||
|
||||
# Agent + session scoping
|
||||
client.add(messages, user_id="alice", agent_id="nutrition-agent", run_id="session-456")
|
||||
|
||||
# Synchronous processing (wait for completion)
|
||||
client.add(messages, user_id="alice", async_mode=False)
|
||||
|
||||
# Raw text -- skip LLM inference
|
||||
client.add(
|
||||
[{"role": "user", "content": "User prefers dark mode."}],
|
||||
@@ -101,7 +79,7 @@ client.add(
|
||||
|
||||
**Python:**
|
||||
```python
|
||||
results = client.search("dietary preferences?", user_id="alice")
|
||||
results = client.search("dietary preferences?", filters={"user_id": "alice"})
|
||||
|
||||
# With filters and reranking
|
||||
results = client.search(
|
||||
@@ -111,20 +89,14 @@ results = client.search(
|
||||
rerank=True,
|
||||
threshold=0.5
|
||||
)
|
||||
|
||||
# With graph relations
|
||||
results = client.search("colleagues", user_id="alice", enable_graph=True)
|
||||
|
||||
# Keyword search
|
||||
results = client.search("vegetarian", user_id="alice", keyword_search=True)
|
||||
```
|
||||
|
||||
**TypeScript:**
|
||||
```typescript
|
||||
const results = await client.search("dietary preferences", { user_id: "alice" });
|
||||
const results = await client.search("dietary preferences", { filters: { user_id: "alice" } });
|
||||
const results = await client.search("work experience", {
|
||||
filters: { AND: [{ user_id: "alice" }, { categories: { contains: "professional_details" } }] },
|
||||
top_k: 5,
|
||||
topK: 5,
|
||||
rerank: true,
|
||||
});
|
||||
```
|
||||
@@ -134,19 +106,17 @@ const results = await client.search("work experience", {
|
||||
| Name | Type | Description |
|
||||
|------|------|-------------|
|
||||
| `query` | string | Natural language search query |
|
||||
| `user_id` | string | Filter by user |
|
||||
| `filters` | object | V2 filter object (AND/OR operators) |
|
||||
| `top_k` | number | Number of results (default: 10) |
|
||||
| `rerank` | boolean | Enable reranking for better relevance |
|
||||
| `threshold` | number | Minimum similarity score (default: 0.3) |
|
||||
| `keyword_search` | boolean | Use keyword-based search |
|
||||
| `enable_graph` | boolean | Include graph relations |
|
||||
| `filters` | object | Filter object (AND/OR operators). Use `{"user_id": "..."}` to filter by user |
|
||||
| `top_k` | number | Number of results (default: 10 for Platform) |
|
||||
| `rerank` | boolean | Enable reranking for better relevance (default: `false`) |
|
||||
| `threshold` | number | Minimum similarity score (default: 0.1) |
|
||||
|
||||
### Common Filter Patterns
|
||||
|
||||
**Python:**
|
||||
```python
|
||||
# Single user (shorthand)
|
||||
client.search("query", user_id="alice")
|
||||
# Single user filter
|
||||
filters={"user_id": "alice"}
|
||||
|
||||
# OR across agents
|
||||
filters={"OR": [{"user_id": "alice"}, {"agent_id": {"in": ["travel-agent", "sports-agent"]}}]}
|
||||
@@ -179,6 +149,21 @@ filters={"AND": [
|
||||
]}
|
||||
```
|
||||
|
||||
**TypeScript:**
|
||||
```typescript
|
||||
// Single user filter
|
||||
filters: { user_id: "alice" }
|
||||
|
||||
// OR across agents
|
||||
filters: { OR: [{ user_id: "alice" }, { agent_id: { in: ["travel-agent", "sports-agent"] } }] }
|
||||
|
||||
// Category filtering (partial match)
|
||||
filters: { AND: [{ user_id: "alice" }, { categories: { contains: "finance" } }] }
|
||||
|
||||
// Category filtering (exact match)
|
||||
filters: { AND: [{ user_id: "alice" }, { categories: { in: ["personal_information"] } }] }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## get() / getAll() -- Retrieve Memories
|
||||
@@ -189,7 +174,7 @@ filters={"AND": [
|
||||
memory = client.get(memory_id="ea925981-...")
|
||||
|
||||
# All memories for a user
|
||||
memories = client.get_all(filters={"AND": [{"user_id": "alice"}]})
|
||||
memories = client.get_all(filters={"user_id": "alice"})
|
||||
|
||||
# With date range
|
||||
memories = client.get_all(
|
||||
@@ -198,15 +183,12 @@ memories = client.get_all(
|
||||
{"created_at": {"gte": "2024-07-01", "lte": "2024-07-31"}}
|
||||
]}
|
||||
)
|
||||
|
||||
# With graph data
|
||||
memories = client.get_all(filters={"AND": [{"user_id": "alice"}]}, enable_graph=True)
|
||||
```
|
||||
|
||||
**TypeScript:**
|
||||
```typescript
|
||||
const memory = await client.get("ea925981-...");
|
||||
const memories = await client.getAll({ filters: { AND: [{ user_id: "alice" }] } });
|
||||
const memories = await client.getAll({ filters: { user_id: "alice" } });
|
||||
```
|
||||
|
||||
**Note:** `get_all` requires at least one of `user_id`, `agent_id`, `app_id`, or `run_id` in filters.
|
||||
@@ -226,8 +208,6 @@ client.update(memory_id="ea925981-...", text="Updated", metadata={"verified": Tr
|
||||
await client.update("ea925981-...", { text: "Updated: vegan since 2024" });
|
||||
```
|
||||
|
||||
Cannot update immutable memories.
|
||||
|
||||
---
|
||||
|
||||
## delete() / deleteAll() -- Remove Memories
|
||||
@@ -241,7 +221,7 @@ client.delete_all(user_id="alice") # Irreversible bulk delete
|
||||
**TypeScript:**
|
||||
```typescript
|
||||
await client.delete("ea925981-...");
|
||||
await client.deleteAll({ user_id: "alice" });
|
||||
await client.deleteAll({ userId: "alice" });
|
||||
```
|
||||
|
||||
---
|
||||
@@ -301,10 +281,73 @@ data = client.get_memory_export(memory_export_id=export["id"])
|
||||
2. **SQL operators rejected** -- use `gte`, `lt`, etc. Not `>=`, `<`.
|
||||
3. **Metadata filtering is limited** -- only top-level keys with `eq`, `contains`, `ne`.
|
||||
4. **Wildcard `*` excludes null** -- only matches non-null values.
|
||||
5. **Default threshold is 0.3** -- increase for stricter matching.
|
||||
5. **Default threshold is 0.1** -- increase for stricter matching.
|
||||
6. **Async processing** -- memories process asynchronously. Wait 2-3s after `add()` before searching.
|
||||
7. **Immutable memories** -- cannot be updated or deleted once created.
|
||||
|
||||
## Naming Conventions
|
||||
|
||||
Python uses `snake_case` (`user_id`, `memory_id`, `get_all`). TypeScript uses `camelCase` for methods (`getAll`, `deleteAll`, `batchUpdate`) but `snake_case` for API parameters (`user_id`, `agent_id`).
|
||||
Python uses `snake_case` everywhere (`user_id`, `memory_id`, `get_all`). TypeScript uses `camelCase` for methods (`getAll`, `deleteAll`, `batchUpdate`) and top-level parameters (`userId`, `topK`, `pageSize`), but filter keys use `snake_case` (`user_id`, `agent_id`).
|
||||
|
||||
---
|
||||
|
||||
## v2 to v3 Migration
|
||||
|
||||
### Breaking Changes in v3
|
||||
|
||||
**1. Entity IDs in search() and getAll()**
|
||||
|
||||
v3 requires entity IDs (`user_id`, `agent_id`, `run_id`) inside `filters` instead of as top-level parameters:
|
||||
|
||||
```python
|
||||
# v2 (deprecated)
|
||||
client.search("query", user_id="alice")
|
||||
client.get_all(user_id="alice")
|
||||
|
||||
# v3
|
||||
client.search("query", filters={"user_id": "alice"})
|
||||
client.get_all(filters={"user_id": "alice"})
|
||||
```
|
||||
|
||||
```typescript
|
||||
// v2 (deprecated)
|
||||
await client.search("query", { user_id: "alice" });
|
||||
await client.getAll({ user_id: "alice" });
|
||||
|
||||
// v3
|
||||
await client.search("query", { filters: { user_id: "alice" } });
|
||||
await client.getAll({ filters: { user_id: "alice" } });
|
||||
```
|
||||
|
||||
**2. TypeScript Parameter Naming**
|
||||
|
||||
v3 TypeScript uses camelCase for all parameters:
|
||||
|
||||
| v2 | v3 |
|
||||
|----|-----|
|
||||
| `user_id` | `userId` |
|
||||
| `agent_id` | `agentId` |
|
||||
| `run_id` | `runId` |
|
||||
| `top_k` | `topK` |
|
||||
| `page_size` | `pageSize` |
|
||||
|
||||
**3. Default Values Changed**
|
||||
|
||||
| Parameter | v2 Default | v3 Default |
|
||||
|-----------|------------|------------|
|
||||
| `threshold` | 0.3 | 0.1 |
|
||||
| `rerank` | (not specified) | `false` |
|
||||
|
||||
**4. Removed Parameters**
|
||||
|
||||
The following parameters are no longer supported:
|
||||
|
||||
| Parameter | Status |
|
||||
|-----------|--------|
|
||||
| `enable_graph` | Removed from add/search/getAll |
|
||||
| `keyword_search` | Removed from search |
|
||||
| `filter_memories` | Removed |
|
||||
| `immutable` | Removed from add |
|
||||
| `expiration_date` | Removed from add |
|
||||
| `includes` | Removed from add |
|
||||
| `excludes` | Removed from add |
|
||||
| `async_mode` | Removed from add |
|
||||
|
||||
@@ -39,7 +39,7 @@ Use these known facts about the user to personalize your response:
|
||||
{context if context else 'No prior context yet.'}"""
|
||||
|
||||
response = openai_client.chat.completions.create(
|
||||
model="gpt-4.1-nano-2025-04-14",
|
||||
model="gpt-5-mini",
|
||||
messages=[
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_input},
|
||||
@@ -72,14 +72,14 @@ const openai = new OpenAI();
|
||||
|
||||
async function chat(userInput: string, userId: string): Promise<string> {
|
||||
// 1. Retrieve relevant memories
|
||||
const memories = await mem0.search(userInput, { user_id: userId });
|
||||
const memories = await mem0.search(userInput, { filters: { user_id: userId } });
|
||||
const context = memories.results
|
||||
?.map((m: any) => `- ${m.memory}`)
|
||||
.join('\n') || 'No prior context yet.';
|
||||
|
||||
// 2. Generate response with memory context
|
||||
const response = await openai.chat.completions.create({
|
||||
model: 'gpt-4.1-nano-2025-04-14',
|
||||
model: 'gpt-5-mini',
|
||||
messages: [
|
||||
{ role: 'system', content: `You are Ray, a personal fitness coach.\nUser context:\n${context}` },
|
||||
{ role: 'user', content: userInput },
|
||||
@@ -90,7 +90,7 @@ async function chat(userInput: string, userId: string): Promise<string> {
|
||||
// 3. Store interaction
|
||||
await mem0.add(
|
||||
[{ role: 'user', content: userInput }, { role: 'assistant', content: reply }],
|
||||
{ user_id: userId }
|
||||
{ userId: userId }
|
||||
);
|
||||
return reply;
|
||||
}
|
||||
@@ -182,7 +182,7 @@ await client.updateProject({
|
||||
async function logInteraction(userId: string, message: string, priority = 'normal') {
|
||||
await client.add(
|
||||
[{ role: 'user', content: message }],
|
||||
{ user_id: userId, metadata: { priority, source: 'support_chat' } }
|
||||
{ userId: userId, metadata: { priority, source: 'support_chat' } }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -230,7 +230,7 @@ def consult(user_id: str, question: str) -> str:
|
||||
context = "\n".join([f"- {m['memory']}" for m in memories.get("results", [])])
|
||||
|
||||
response = openai_client.chat.completions.create(
|
||||
model="gpt-4.1-nano-2025-04-14",
|
||||
model="gpt-5-mini",
|
||||
messages=[
|
||||
{"role": "system", "content": f"You are a health coach. Patient context:\n{context}"},
|
||||
{"role": "user", "content": question},
|
||||
@@ -264,20 +264,20 @@ const openai = new OpenAI();
|
||||
async function savePatientInfo(userId: string, info: string) {
|
||||
await mem0.add(
|
||||
[{ role: 'user', content: info }],
|
||||
{ user_id: userId, run_id: 'healthcare_session', metadata: { type: 'patient_information' } }
|
||||
{ userId: userId, runId: 'healthcare_session', metadata: { type: 'patient_information' } }
|
||||
);
|
||||
}
|
||||
|
||||
async function consult(userId: string, question: string): Promise<string> {
|
||||
const memories = await mem0.search(question, {
|
||||
user_id: userId,
|
||||
top_k: 5,
|
||||
filters: { user_id: userId },
|
||||
topK: 5,
|
||||
threshold: 0.7,
|
||||
});
|
||||
const context = memories.results?.map((m: any) => `- ${m.memory}`).join('\n') || '';
|
||||
|
||||
const response = await openai.chat.completions.create({
|
||||
model: 'gpt-4.1-nano-2025-04-14',
|
||||
model: 'gpt-5-mini',
|
||||
messages: [
|
||||
{ role: 'system', content: `You are a health coach. Patient context:\n${context}` },
|
||||
{ role: 'user', content: question },
|
||||
@@ -287,7 +287,7 @@ async function consult(userId: string, question: string): Promise<string> {
|
||||
|
||||
await mem0.add(
|
||||
[{ role: 'user', content: question }, { role: 'assistant', content: reply }],
|
||||
{ user_id: userId, run_id: 'healthcare_session' }
|
||||
{ userId: userId, runId: 'healthcare_session' }
|
||||
);
|
||||
return reply;
|
||||
}
|
||||
@@ -333,7 +333,7 @@ def draft_content(user_id: str, topic: str) -> str:
|
||||
style_context = "\n".join([f"- {m['memory']}" for m in prefs.get("results", [])])
|
||||
|
||||
response = openai_client.chat.completions.create(
|
||||
model="gpt-4.1-nano-2025-04-14",
|
||||
model="gpt-5-mini",
|
||||
messages=[
|
||||
{"role": "system", "content": f"Write content matching these style preferences:\n{style_context}"},
|
||||
{"role": "user", "content": f"Write a blog post about: {topic}"},
|
||||
@@ -359,7 +359,7 @@ const openai = new OpenAI();
|
||||
async function storePreferences(userId: string, preferences: string) {
|
||||
await mem0.add(
|
||||
[{ role: 'user', content: preferences }],
|
||||
{ user_id: userId, run_id: 'editing_session', metadata: { type: 'preferences' } }
|
||||
{ userId: userId, runId: 'editing_session', metadata: { type: 'preferences' } }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -370,7 +370,7 @@ async function draftContent(userId: string, topic: string): Promise<string> {
|
||||
const styleContext = prefs.results?.map((m: any) => `- ${m.memory}`).join('\n') || '';
|
||||
|
||||
const response = await openai.chat.completions.create({
|
||||
model: 'gpt-4.1-nano-2025-04-14',
|
||||
model: 'gpt-5-mini',
|
||||
messages: [
|
||||
{ role: 'system', content: `Write content matching these preferences:\n${styleContext}` },
|
||||
{ role: 'user', content: `Write a blog post about: ${topic}` },
|
||||
@@ -465,10 +465,10 @@ async function storeScopedMemory(
|
||||
userId: string, agentId: string, runId: string, appId: string
|
||||
) {
|
||||
await client.add(messages, {
|
||||
user_id: userId,
|
||||
agent_id: agentId,
|
||||
run_id: runId,
|
||||
app_id: appId,
|
||||
userId: userId,
|
||||
agentId: agentId,
|
||||
runId: runId,
|
||||
appId: appId,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -520,7 +520,7 @@ def personalized_search(user_id: str, query: str, search_results: list) -> str:
|
||||
user_context = "\n".join([f"- {m['memory']}" for m in memories.get("results", [])])
|
||||
|
||||
response = openai_client.chat.completions.create(
|
||||
model="gpt-4.1-nano-2025-04-14",
|
||||
model="gpt-5-mini",
|
||||
messages=[
|
||||
{"role": "system", "content": f"Personalize search results using user context:\n{user_context}"},
|
||||
{"role": "user", "content": f"Query: {query}\n\nSearch results:\n{search_results}"},
|
||||
@@ -551,11 +551,11 @@ const mem0 = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! });
|
||||
const openai = new OpenAI();
|
||||
|
||||
async function personalizedSearch(userId: string, query: string, searchResults: string[]): Promise<string> {
|
||||
const memories = await mem0.search(query, { user_id: userId, top_k: 5 });
|
||||
const memories = await mem0.search(query, { filters: { user_id: userId }, topK: 5 });
|
||||
const context = memories.results?.map((m: any) => `- ${m.memory}`).join('\n') || '';
|
||||
|
||||
const response = await openai.chat.completions.create({
|
||||
model: 'gpt-4.1-nano-2025-04-14',
|
||||
model: 'gpt-5-mini',
|
||||
messages: [
|
||||
{ role: 'system', content: `Personalize results using user context:\n${context}` },
|
||||
{ role: 'user', content: `Query: ${query}\nResults: ${searchResults.join(', ')}` },
|
||||
@@ -563,7 +563,7 @@ async function personalizedSearch(userId: string, query: string, searchResults:
|
||||
});
|
||||
const reply = response.choices[0].message.content!;
|
||||
|
||||
await mem0.add([{ role: 'user', content: query }], { user_id: userId });
|
||||
await mem0.add([{ role: 'user', content: query }], { userId: userId });
|
||||
return reply;
|
||||
}
|
||||
```
|
||||
@@ -631,14 +631,14 @@ const client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! });
|
||||
async function storeEmail(userId: string, sender: string, subject: string, body: string, date: string) {
|
||||
await client.add(
|
||||
[{ role: 'user', content: `Email from ${sender}: ${subject}\n\n${body}` }],
|
||||
{ user_id: userId, metadata: { email_type: 'incoming', sender, subject, date } }
|
||||
{ userId: userId, metadata: { email_type: 'incoming', sender, subject, date } }
|
||||
);
|
||||
}
|
||||
|
||||
async function searchEmails(userId: string, query: string) {
|
||||
return client.search(query, {
|
||||
filters: { AND: [{ user_id: userId }, { categories: { contains: 'email' } }] },
|
||||
top_k: 10,
|
||||
topK: 10,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||