[docs] Welcome page thumbnail and reranker fix (#3660)

This commit is contained in:
Parth Sharma
2025-10-26 00:50:52 +05:30
committed by GitHub
parent 639d26e1ac
commit f98a17c716
24 changed files with 640 additions and 1048 deletions
+1 -1
View File
@@ -94,7 +94,7 @@ config = {
"model": "gpt-4.1-nano-2025-04-14"
}
},
"rerank": {
"reranker": {
"provider": "zero_entropy",
"config": {
"model": "zerank-1",
+11 -7
View File
@@ -3,6 +3,10 @@ title: LLM as Reranker
description: 'Flexible reranking using LLMs'
---
<Warning>
**This page has been superseded.** Please see [LLM Reranker](/components/rerankers/models/llm_reranker) for the complete and up-to-date documentation on using LLMs for reranking.
</Warning>
LLM-based reranker provides maximum flexibility by using any Large Language Model to score document relevance. This approach allows for custom prompts and domain-specific scoring logic.
## Supported LLM Providers
@@ -35,7 +39,7 @@ config = {
"model": "gpt-4o-mini"
}
},
"rerank": {
"reranker": {
"provider": "llm",
"config": {
"model": "gpt-4o-mini",
@@ -69,7 +73,7 @@ Score from 0.0 to 1.0 where:
Provide only a single numerical score between 0.0 and 1.0."""
config["rerank"]["config"]["scoring_prompt"] = custom_prompt
config["reranker"]["config"]["scoring_prompt"] = custom_prompt
```
## Usage Example
@@ -85,7 +89,7 @@ os.environ["OPENAI_API_KEY"] = "your-api-key"
config = {
"vector_store": {"provider": "chroma"},
"llm": {"provider": "openai", "config": {"model": "gpt-4o-mini"}},
"rerank": {
"reranker": {
"provider": "llm",
"config": {
"model": "gpt-4o-mini",
@@ -145,7 +149,7 @@ Consider:
Score from 0.0 to 1.0. Provide only the numerical score."""
config = {
"rerank": {
"reranker": {
"provider": "llm",
"config": {
"model": "gpt-4o-mini",
@@ -164,7 +168,7 @@ Use different LLM providers for reranking:
```python Python
# Using Anthropic Claude
anthropic_config = {
"rerank": {
"reranker": {
"provider": "llm",
"config": {
"model": "claude-3-haiku-20240307",
@@ -176,8 +180,8 @@ anthropic_config = {
# Using local Ollama model
ollama_config = {
"rerank": {
"provider": "llm",
"reranker": {
"provider": "llm",
"config": {
"model": "llama2:7b",
"provider": "ollama",
+68 -58
View File
@@ -1,68 +1,78 @@
---
title: Overview
description: 'Pick the right reranker path to boost Mem0 search relevance.'
---
Mem0 includes built-in support for various reranking providers to improve the relevance of memory search results. Rerankers post-process initial vector search results by re-scoring and re-ordering them using more sophisticated relevance models.
Mem0 rerankers rescore vector search hits so your agents surface the most relevant memories. Use this hub to decide when reranking helps, configure a provider, and fine-tune performance.
## Usage
<Info>
Reranking trades extra latency for better precision. Start once you have baseline search working and measure before/after relevance.
</Info>
To use a reranker:
1. **Configure**: Add a `rerank` configuration section in your memory config
2. **Search**: Reranking is automatically enabled for all searches (default: `rerank=True`)
If no reranker is configured, search results will rely on vector similarity scoring alone.
For comprehensive configuration parameters for each reranker, please refer to [Config](./config).
### Controlling Reranking Per Search
Once configured, reranking is enabled by default. You can control it per-search:
```python
# Reranking enabled (default)
results = memory.search("query", user_id="user1")
# Explicitly enable reranking
results = memory.search("query", user_id="user1", rerank=True)
# Disable reranking for this specific search
results = memory.search("query", user_id="user1", rerank=False)
```
## How Reranking Works
1. **Initial Search**: Vector similarity search retrieves candidate memories
2. **Reranking** (if enabled): Selected reranker re-scores candidates using advanced models
3. **Final Results**: Re-ordered results with both vector and rerank scores
<Note>
Reranking operates as a post-processing step and can significantly improve search relevance at the cost of additional latency and API calls.
</Note>
## Supported Rerankers
See the list of supported rerankers below.
<CardGroup cols={2}>
<Card title="Zero Entropy" href="/components/rerankers/models/zero_entropy" />
<Card title="Cohere" href="/components/rerankers/models/cohere" />
<Card title="Sentence Transformer" href="/components/rerankers/models/sentence_transformer" />
<Card title="Hugging Face" href="/components/rerankers/models/huggingface" />
<Card title="LLM-based" href="/components/rerankers/models/llm" />
<Card title="LLM Reranker" href="/components/rerankers/models/llm_reranker" />
<CardGroup cols={3}>
<Card
title="Understand Reranking"
description="See how reranker-enhanced search changes your retrieval flow."
icon="search"
href="/open-source/features/reranker-search"
/>
<Card
title="Configure Providers"
description="Add reranker blocks to your memory configuration."
icon="settings"
href="/components/rerankers/config"
/>
<Card
title="Optimize Performance"
description="Balance relevance, latency, and cost with tuning tactics."
icon="speedometer"
href="/components/rerankers/optimization"
/>
<Card
title="Custom Prompts"
description="Shape LLM-based reranking with tailored instructions."
icon="code"
href="/components/rerankers/custom-prompts"
/>
<Card
title="Zero Entropy Guide"
description="Adopt the managed neural reranker for production workloads."
icon="sparkles"
href="/components/rerankers/models/zero_entropy"
/>
<Card
title="Sentence Transformers"
description="Keep reranking on-device with cross-encoder models."
icon="cpu"
href="/components/rerankers/models/sentence_transformer"
/>
</CardGroup>
## When to Use Reranking
## Picking the Right Reranker
- **Improved Relevance**: When vector search alone doesn't provide sufficiently relevant results
- **Domain-Specific Queries**: For specialized terminology or context that benefits from advanced models
- **Quality vs Speed Trade-off**: When you can accept higher latency for better search quality
- **Production Systems**: Where search quality directly impacts user experience
- **API-first** when you need top quality and can absorb request costs (Cohere, Zero Entropy).
- **Self-hosted** for privacy-sensitive deployments that must stay on your hardware (Sentence Transformer, Hugging Face).
- **LLM-driven** when you need bespoke scoring logic or complex prompts.
- **Hybrid** by enabling reranking only on premium journeys to control spend.
Choose the reranker that best fits your use case:
- **Zero Entropy**: Best balance of speed and quality for general use
- **Cohere**: Enterprise-grade with excellent multilingual support
- **Sentence Transformer**: Local deployment for privacy-sensitive applications
- **Hugging Face**: Wide variety of pre-trained models for specialized use cases
- **LLM-based**: Maximum customization with custom prompts and logic
## Implementation Checklist
1. Confirm baseline search KPIs so you can measure uplift.
2. Select a provider and add the `reranker` block to your config.
3. Test latency impact with production-like query batches.
4. Decide whether to enable reranking globally or per-search via the `rerank` flag.
<CardGroup cols={2}>
<Card
title="Set Up Reranking"
description="Walk through the configuration fields and defaults."
icon="settings"
href="/components/rerankers/config"
/>
<Card
title="Example: Reranker Search"
description="Follow the feature guide to see reranking in action."
icon="rocket"
href="/open-source/features/reranker-search"
/>
</CardGroup>
+8 -17
View File
@@ -133,23 +133,15 @@
"icon": "server",
"pages": [
"open-source/features/overview",
"open-source/features/graph-memory",
"open-source/features/metadata-filtering",
"open-source/features/reranker-search",
"open-source/features/async-memory",
"open-source/features/openai_compatibility",
"open-source/features/multimodal-support",
"open-source/features/custom-fact-extraction-prompt",
"open-source/features/custom-update-memory-prompt",
"open-source/features/multimodal-support",
"open-source/features/rest-api",
"open-source/features/metadata-filtering",
"open-source/features/reranking",
"open-source/features/reranker-search"
]
},
{
"group": "Graph Memory",
"icon": "network-wired",
"pages": [
"open-source/graph_memory/overview",
"open-source/graph_memory/features"
"open-source/features/openai_compatibility"
]
},
{
@@ -255,6 +247,8 @@
"pages": [
"components/rerankers/overview",
"components/rerankers/config",
"components/rerankers/optimization",
"components/rerankers/custom-prompts",
{
"group": "Supported Rerankers",
"icon": "list",
@@ -263,12 +257,9 @@
"components/rerankers/models/sentence_transformer",
"components/rerankers/models/huggingface",
"components/rerankers/models/llm_reranker",
"components/rerankers/models/llm",
"components/rerankers/models/zero_entropy"
]
},
"components/rerankers/optimization",
"components/rerankers/custom-prompts"
}
]
}
]
+1 -1
View File
@@ -36,7 +36,7 @@ This sets up Mem0 with:
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
- [OpenSearch as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/opensearch)
- [Neptune Analytics as your graph store](https://docs.mem0.ai/open-source/graph_memory/overview#initialize-neptune-analytics)
- [Graph Memory guide](https://docs.mem0.ai/open-source/features/graph-memory)
```python
import boto3
@@ -36,7 +36,7 @@ This sets up Mem0 with:
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
- [Neptune Analytics as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/neptune_analytics)
- [Neptune Analytics as the graph store](https://docs.mem0.ai/open-source/graph_memory/overview#initialize-neptune-analytics).
- [Graph Memory guide](https://docs.mem0.ai/open-source/features/graph-memory).
```python
import boto3
Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

+113 -25
View File
@@ -6,7 +6,7 @@ mode: "custom"
{/* debug: welcome-layout-v2 */}
<div className="px-4 pt-16 pb-12 lg:pt-20 max-w-4xl mx-auto text-center space-y-4">
<div className="px-4 pt-16 pb-12 lg:pt-20 max-w-4xl mx-auto text-center space-y-6">
<h1 className="text-3xl lg:text-4xl font-bold text-gray-900 dark:text-zinc-50 tracking-tight mb-3">
Build with <span className="text-primary">mem0</span>
</h1>
@@ -31,20 +31,64 @@ mode: "custom"
</h2>
</div>
<CardGroup cols={3}>
<Card title="Mem0 Platform" icon="rocket" href="/platform/overview">
Managed memory with production-scale infrastructure, ready in minutes.
</Card>
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
<a
href="/platform/overview"
className="group flex h-full flex-col overflow-hidden rounded-2xl border border-zinc-800/40 bg-zinc-900/40 transition hover:border-primary/60 hover:bg-zinc-900"
>
<img
src="/images/docs%20thumbnails/Mem0%20Platform.png"
alt="Mem0 Platform thumbnail"
className="aspect-[4/3] w-full object-cover"
/>
<div className="flex flex-1 flex-col gap-3 px-5 pb-6 pt-5 text-left">
<h3 className="text-base font-semibold text-zinc-100 group-hover:text-primary">
Mem0 Platform
</h3>
<p className="text-sm text-zinc-400">
Managed memory with production-scale infrastructure, ready in minutes.
</p>
</div>
</a>
<Card title="Mem0 Open Source" icon="code-branch" href="/open-source/overview">
Self-host the Mem0 stack for full control over data, deployment, and customization.
</Card>
<a
href="/open-source/overview"
className="group flex h-full flex-col overflow-hidden rounded-2xl border border-zinc-800/40 bg-zinc-900/40 transition hover:border-primary/60 hover:bg-zinc-900"
>
<img
src="/images/docs%20thumbnails/Mem0%20Open%20Source.png"
alt="Mem0 Open Source thumbnail"
className="aspect-[4/3] w-full object-cover"
/>
<div className="flex flex-1 flex-col gap-3 px-5 pb-6 pt-5 text-left">
<h3 className="text-base font-semibold text-zinc-100 group-hover:text-primary">
Mem0 Open Source
</h3>
<p className="text-sm text-zinc-400">
Self-host the Mem0 stack for full control over data, deployment, and customization.
</p>
</div>
</a>
<Card title="OpenMemory" icon="brain" href="/openmemory/overview">
Workspace-based memory for teams collaborating across agents and projects.
</Card>
</CardGroup>
<a
href="/openmemory/overview"
className="group flex h-full flex-col overflow-hidden rounded-2xl border border-zinc-800/40 bg-zinc-900/40 transition hover:border-primary/60 hover:bg-zinc-900"
>
<img
src="/images/docs%20thumbnails/Mem0%20OpenMemory.png"
alt="OpenMemory thumbnail"
className="aspect-[4/3] w-full object-cover"
/>
<div className="flex flex-1 flex-col gap-3 px-5 pb-6 pt-5 text-left">
<h3 className="text-base font-semibold text-zinc-100 group-hover:text-primary">
OpenMemory
</h3>
<p className="text-sm text-zinc-400">
Workspace-based memory for teams collaborating across agents and projects.
</p>
</div>
</a>
</div>
</section>
<section className="px-4 pt-12 pb-20 max-w-6xl mx-auto space-y-4">
@@ -54,18 +98,62 @@ mode: "custom"
</h2>
</div>
<CardGroup cols={3}>
<Card title="Cookbooks" icon="book-open" href="/examples">
Production-ready tutorials that show how to ship memorable AI experiences.
</Card>
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
<a
href="/examples"
className="group flex h-full flex-col overflow-hidden rounded-2xl border border-zinc-800/40 bg-zinc-900/40 transition hover:border-primary/60 hover:bg-zinc-900"
>
<img
src="/images/docs%20thumbnails/Cookbooks.png"
alt="Cookbooks thumbnail"
className="aspect-[4/3] w-full object-cover"
/>
<div className="flex flex-1 flex-col gap-3 px-5 pb-6 pt-5 text-left">
<h3 className="text-base font-semibold text-zinc-100 group-hover:text-primary">
Cookbooks
</h3>
<p className="text-sm text-zinc-400">
Production-ready tutorials that show how to ship memorable AI experiences.
</p>
</div>
</a>
<Card title="Integrations" icon="plug" href="/integrations">
Connect Mem0 to LangChain, CrewAI, Vercel AI SDK, and 20+ partner frameworks.
</Card>
<a
href="/integrations"
className="group flex h-full flex-col overflow-hidden rounded-2xl border border-zinc-800/40 bg-zinc-900/40 transition hover:border-primary/60 hover:bg-zinc-900"
>
<img
src="/images/docs%20thumbnails/Integrations.png"
alt="Integrations thumbnail"
className="aspect-[4/3] w-full object-cover"
/>
<div className="flex flex-1 flex-col gap-3 px-5 pb-6 pt-5 text-left">
<h3 className="text-base font-semibold text-zinc-100 group-hover:text-primary">
Integrations
</h3>
<p className="text-sm text-zinc-400">
Connect Mem0 to LangChain, CrewAI, Vercel AI SDK, and 20+ partner frameworks.
</p>
</div>
</a>
<Card title="API reference" icon="terminal" href="/api-reference">
Explore every REST endpoint with payload examples and usage guidance.
</Card>
</CardGroup>
<a
href="/api-reference"
className="group flex h-full flex-col overflow-hidden rounded-2xl border border-zinc-800/40 bg-zinc-900/40 transition hover:border-primary/60 hover:bg-zinc-900"
>
<img
src="/images/docs%20thumbnails/API.png"
alt="API reference thumbnail"
className="aspect-[4/3] w-full object-cover"
/>
<div className="flex flex-1 flex-col gap-3 px-5 pb-6 pt-5 text-left">
<h3 className="text-base font-semibold text-zinc-100 group-hover:text-primary">
API reference
</h3>
<p className="text-sm text-zinc-400">
Explore every REST endpoint with payload examples and usage guidance.
</p>
</div>
</a>
</div>
</section>
+1 -1
View File
@@ -45,7 +45,7 @@ Key differentiators:
- [OpenAI Compatibility](https://docs.mem0.ai/open-source/features/openai_compatibility): Seamless integration with OpenAI-compatible APIs
- [Custom Fact Extraction](https://docs.mem0.ai/open-source/features/custom-fact-extraction-prompt): Tailor information extraction for specific use cases
- [REST API Server](https://docs.mem0.ai/open-source/features/rest-api): FastAPI-based server with core operations and OpenAPI documentation
- [Graph Memory Overview](https://docs.mem0.ai/open-source/graph_memory/overview): Build and query entity relationships using graph stores like Neo4j
- [Graph Memory Overview](https://docs.mem0.ai/open-source/features/graph-memory): Build and query entity relationships using graph stores like Neo4j
## Components
+3 -3
View File
@@ -175,7 +175,7 @@ config = {
m = Memory.from_config(config)
```
<Card title="Graph Memory Guide" icon="diagram-project" href="/open-source/graph_memory/overview">
<Card title="Graph Memory Guide" icon="diagram-project" href="/open-source/features/graph-memory">
Learn how to use graph memory for relationship-based retrieval
</Card>
@@ -225,7 +225,7 @@ config = {
}
```
<Card title="Reranking Guide" icon="arrow-up-arrow-down" href="/open-source/features/reranking">
<Card title="Reranker-Enhanced Search" icon="arrow-up-arrow-down" href="/open-source/features/reranker-search">
Learn how reranking improves memory search accuracy
</Card>
@@ -306,7 +306,7 @@ Common parameters (provider-specific options vary):
| `username` | Authentication username | "neo4j" |
| `password` | Authentication password | "your-password" |
**Learn more:** [Graph Memory Overview](/open-source/graph_memory/overview)
**Learn more:** [Graph Memory Overview](/open-source/features/graph-memory)
</Accordion>
+398
View File
@@ -0,0 +1,398 @@
---
title: Graph Memory
description: "Layer relationships onto Mem0 search so agents remember who did what, when, and with whom."
---
Graph Memory extends Mem0 by persisting nodes and edges alongside embeddings, so recalls stitch together people, places, and events instead of just keywords.
<Info icon="sparkles">
**You’ll use this when…**
- Conversation history mixes multiple actors and objects that vectors alone blur together
- Compliance or auditing demands a graph of who said what and when
- Agent teams need shared context without duplicating every memory in each run
</Info>
## How Graph Memory Maps Context
Mem0 extracts entities and relationships from every memory write, stores embeddings in your vector database, and mirrors relationships in a graph backend. On retrieval, vector search narrows candidates, then the graph supplies context and re-ranks results.
```mermaid
graph LR
A[Conversation] --> B(Extraction LLM)
B --> C[Vector Store]
B --> D[Graph Store]
E[Query] --> C
C --> F[Candidate Memories]
F --> D
D --> G[Contextual Recall]
```
<Info icon="lightbulb">
Graph Memory complements your vector store. Keep both healthy to avoid blind spots.
</Info>
## How It Works
<Steps>
<Step title="Extract people, places, and facts">
Mem0’s extraction LLM identifies entities, relationships, and timestamps from the conversation payload you send to `memory.add`.
</Step>
<Step title="Store vectors and edges together">
Embeddings land in your configured vector database while nodes and edges flow into a Bolt-compatible graph backend (Neo4j, Memgraph, Neptune, or Kuzu).
</Step>
<Step title="Blend graph context at search time">
`memory.search` first performs vector similarity, then follows connected nodes to boost (or filter) answers before optionally handing results to a reranker.
</Step>
</Steps>
## Quickstart (Neo4j Aura)
<Info icon="clock">
**Time to implement:** ~10 minutes · **Prerequisites:** Python 3.10+, Node.js 18+, Neo4j Aura DB (free tier)
</Info>
Provision a free [Neo4j Aura](https://neo4j.com/product/auradb/) instance, copy the Bolt URI, username, and password, then follow the language tab that matches your stack.
<Tabs>
<Tab title="Python">
<Steps>
<Step title="Install Mem0 with graph extras">
```bash
pip install "mem0ai[graph]"
```
</Step>
<Step title="Export Neo4j credentials">
```bash
export NEO4J_URL="neo4j+s://<your-instance>.databases.neo4j.io"
export NEO4J_USERNAME="neo4j"
export NEO4J_PASSWORD="your-password"
```
</Step>
<Step title="Add and recall a relationship">
```python
import os
from mem0 import Memory
config = {
"graph_store": {
"provider": "neo4j",
"config": {
"url": os.environ["NEO4J_URL"],
"username": os.environ["NEO4J_USERNAME"],
"password": os.environ["NEO4J_PASSWORD"],
"database": "neo4j",
}
}
}
memory = Memory.from_config(config)
conversation = [
{"role": "user", "content": "Alice met Bob at GraphConf 2025 in San Francisco."},
{"role": "assistant", "content": "Great! Logging that connection."},
]
memory.add(conversation, user_id="demo-user")
results = memory.search(
"Who did Alice meet at GraphConf?",
user_id="demo-user",
limit=3,
rerank=True,
)
for hit in results["results"]:
print(hit["memory"])
```
</Step>
</Steps>
</Tab>
<Tab title="TypeScript">
<Steps>
<Step title="Install the OSS SDK">
```bash
npm install mem0ai
```
</Step>
<Step title="Load Neo4j credentials">
```bash
export NEO4J_URL="neo4j+s://<your-instance>.databases.neo4j.io"
export NEO4J_USERNAME="neo4j"
export NEO4J_PASSWORD="your-password"
```
</Step>
<Step title="Enable graph memory and query it">
```typescript
import { Memory } from "mem0ai/oss";
const config = {
enableGraph: true,
graphStore: {
provider: "neo4j",
config: {
url: process.env.NEO4J_URL!,
username: process.env.NEO4J_USERNAME!,
password: process.env.NEO4J_PASSWORD!,
database: "neo4j",
},
},
};
const memory = new Memory(config);
const conversation = [
{ role: "user", content: "Alice met Bob at GraphConf 2025 in San Francisco." },
{ role: "assistant", content: "Great! Logging that connection." },
];
await memory.add(conversation, { userId: "demo-user" });
const results = await memory.search(
"Who did Alice meet at GraphConf?",
{ userId: "demo-user", limit: 3, rerank: true }
);
results.results.forEach((hit) => {
console.log(hit.memory);
});
```
</Step>
</Steps>
</Tab>
</Tabs>
<Info icon="check">
Expect to see **Alice met Bob at GraphConf 2025** in the output. In Neo4j Browser run `MATCH (p:Person)-[r]->(q:Person) RETURN p,r,q LIMIT 5;` to confirm the edge exists.
</Info>
## Operate Graph Memory Day-to-Day
<AccordionGroup>
<Accordion title="Refine extraction prompts">
Guide which relationships become nodes and edges.
<CodeGroup>
```python Python
import os
from mem0 import Memory
config = {
"graph_store": {
"provider": "neo4j",
"config": {
"url": os.environ["NEO4J_URL"],
"username": os.environ["NEO4J_USERNAME"],
"password": os.environ["NEO4J_PASSWORD"],
},
"custom_prompt": "Please only capture people, organisations, and project links.",
}
}
memory = Memory.from_config(config_dict=config)
```
```typescript TypeScript
import { Memory } from "mem0ai/oss";
const config = {
enableGraph: true,
graphStore: {
provider: "neo4j",
config: {
url: process.env.NEO4J_URL!,
username: process.env.NEO4J_USERNAME!,
password: process.env.NEO4J_PASSWORD!,
},
customPrompt: "Please only capture people, organisations, and project links.",
}
};
const memory = new Memory(config);
```
</CodeGroup>
</Accordion>
<Accordion title="Raise the confidence threshold">
Keep noisy edges out of the graph by demanding higher extraction confidence.
```python
config["graph_store"]["config"]["threshold"] = 0.75
```
</Accordion>
<Accordion title="Toggle graph writes per request">
Disable graph writes or reads when you only want vector behaviour.
```python
memory.add(messages, user_id="demo-user", enable_graph=False)
results = memory.search("marketing partners", user_id="demo-user", enable_graph=False)
```
</Accordion>
<Accordion title="Organize multi-agent graphs">
Separate or share context across agents and sessions with `user_id`, `agent_id`, and `run_id`.
<CodeGroup>
```typescript TypeScript
memory.add("I prefer Italian cuisine", { userId: "bob", agentId: "food-assistant" });
memory.add("I'm allergic to peanuts", { userId: "bob", agentId: "health-assistant" });
memory.add("I live in Seattle", { userId: "bob" });
const food = await memory.search("What food do I like?", { userId: "bob", agentId: "food-assistant" });
const allergies = await memory.search("What are my allergies?", { userId: "bob", agentId: "health-assistant" });
const location = await memory.search("Where do I live?", { userId: "bob" });
```
</CodeGroup>
</Accordion>
</AccordionGroup>
<Note>
Monitor graph growth, especially on free tiers, by periodically cleaning dormant nodes: `MATCH (n) WHERE n.lastSeen < date() - duration('P90D') DETACH DELETE n`.
</Note>
## Troubleshooting
<AccordionGroup>
<Accordion title="Neo4j connection refused">
Confirm Bolt connectivity is enabled, credentials match Aura, and your IP is allow-listed. Retry after confirming the URI format is `neo4j+s://...`.
</Accordion>
<Accordion title="Neptune Analytics rejects requests">
Ensure the graph identifier matches the vector dimension used by your embedder and that the IAM role allows `neptune-graph:*DataViaQuery` actions.
</Accordion>
<Accordion title="Graph store outage fallback">
Catch the provider error and retry with `enable_graph=False` so vector-only search keeps serving responses while the graph backend recovers.
</Accordion>
</AccordionGroup>
## Decision Points
- Select the graph store that fits your deployment (managed Aura vs. self-hosted Neo4j vs. AWS Neptune vs. local Kuzu).
- Decide when to enable graph writes per request; routine conversations may stay vector-only to save latency.
- Set a policy for pruning stale relationships so your graph stays fast and affordable.
## Provider setup
Choose your backend and expand the matching panel for configuration details and links.
<AccordionGroup>
<Accordion title="Neo4j Aura or self-hosted">
Install the APOC plugin for self-hosted deployments, then configure Mem0:
```typescript
import { Memory } from "mem0ai/oss";
const config = {
enableGraph: true,
graphStore: {
provider: "neo4j",
config: {
url: "neo4j+s://<HOST>",
username: "neo4j",
password: "<PASSWORD>",
}
}
};
const memory = new Memory(config);
```
Additional docs: [Neo4j Aura Quickstart](https://neo4j.com/docs/aura/), [APOC installation](https://neo4j.com/docs/apoc/current/installation/).
</Accordion>
<Accordion title="Memgraph (Docker)">
Run Memgraph Mage locally with schema introspection enabled:
```bash
docker run -p 7687:7687 memgraph/memgraph-mage:latest --schema-info-enabled=True
```
Then point Mem0 at the instance:
```python
from mem0 import Memory
config = {
"graph_store": {
"provider": "memgraph",
"config": {
"url": "bolt://localhost:7687",
"username": "memgraph",
"password": "your-password",
},
},
}
m = Memory.from_config(config_dict=config)
```
Learn more: [Memgraph Docs](https://memgraph.com/docs).
</Accordion>
<Accordion title="Amazon Neptune Analytics">
Match vector dimensions between Neptune and your embedder, enable public connectivity (if needed), and grant IAM permissions:
```python
from mem0 import Memory
config = {
"graph_store": {
"provider": "neptune",
"config": {
"endpoint": "neptune-graph://<GRAPH_ID>",
},
},
}
m = Memory.from_config(config_dict=config)
```
Reference: [Neptune Analytics Guide](https://docs.aws.amazon.com/neptune/latest/analytics/).
</Accordion>
<Accordion title="Amazon Neptune DB (with external vectors)">
Create a Neptune cluster, enable the public endpoint if you operate outside the VPC, and point Mem0 at the host:
```python
from mem0 import Memory
config = {
"graph_store": {
"provider": "neptunedb",
"config": {
"collection_name": "<VECTOR_COLLECTION_NAME>",
"endpoint": "neptune-graph://<HOST_ENDPOINT>",
},
},
}
m = Memory.from_config(config_dict=config)
```
Reference: [Accessing Data in Neptune DB](https://docs.aws.amazon.com/neptune/latest/userguide/).
</Accordion>
<Accordion title="Kuzu (embedded)">
Kuzu runs in-process, so supply a path (or `:memory:`) for the database file:
```python
config = {
"graph_store": {
"provider": "kuzu",
"config": {
"db": "/tmp/mem0-example.kuzu"
}
}
}
```
Kuzu will clear its state when using `:memory:` once the process exits. See the [Kuzu documentation](https://kuzudb.com/docs/) for advanced settings.
</Accordion>
</AccordionGroup>
<CardGroup cols={2}>
<Card
title="Enhanced Metadata Filtering"
description="Blend field-level filters with graph context to zero in on the right memories."
icon="funnel"
href="/open-source/features/metadata-filtering"
/>
<Card
title="Reranker-Enhanced Search"
description="Layer rerankers on top of vectors and graphs for the cleanest results."
icon="sparkles"
href="/open-source/features/reranker-search"
/>
</CardGroup>
+1 -1
View File
@@ -48,7 +48,7 @@ Choose your preferred approach:
## Next Steps
- Explore [specific features](./async-memory) in detail
- Learn about [graph memory](../graph_memory/overview) capabilities
- Learn about [graph memory](./graph-memory) capabilities
- Set up [vector databases](/components/vectordbs/overview) and [LLM integrations](/components/llms/overview)
- Check out our [examples](/examples) for practical implementations
- Join our [Discord community](https://mem0.dev/DiD) for support
+29 -2
View File
@@ -3,8 +3,8 @@ title: Reranker-Enhanced Search
description: 'Improve search relevance with reranking models in Mem0 1.0.0 '
---
<Info>
Reranker-enhanced search is available in **Mem0 1.0.0 ** and later versions. This feature significantly improves search relevance by using specialized reranking models to reorder search results.
<Info icon="sparkles">
**Mem0 1.0.0+** supports reranker-enhanced search, letting specialized models reorder vector hits so you deliver the most relevant memories.
</Info>
## Overview
@@ -40,6 +40,14 @@ m = Memory.from_config(config)
### Supported Providers
Mem0 supports multiple reranking providers. See the complete documentation for each:
- **[Cohere](../../components/rerankers/models/cohere)**: Enterprise-grade with multilingual support
- **[Sentence Transformer](../../components/rerankers/models/sentence_transformer)**: Local HuggingFace models
- **[Hugging Face](../../components/rerankers/models/huggingface)**: Custom models from HuggingFace
- **[LLM Reranker](../../components/rerankers/models/llm_reranker)**: Use any LLM for flexible scoring
- **[Zero Entropy](../../components/rerankers/models/zero_entropy)**: State-of-the-art neural reranking
#### Cohere Reranker
```python
@@ -123,6 +131,10 @@ for result in results["results"]:
print(f"Score: {result['score']}")
```
<Info icon="check">
Expect each result to include both the base vector score and an updated rerank score so you can compare quality improvements.
</Info>
### Controlling Reranking
```python
@@ -414,3 +426,18 @@ results = m.search("query", user_id="alice") # Automatically reranked
<Info>
Reranker-enhanced search significantly improves result relevance. Start with a local model and upgrade to API-based solutions as your needs grow.
</Info>
<CardGroup cols={2}>
<Card
title="Configure Rerankers"
description="Review provider fields, defaults, and environment variables."
icon="settings"
href="/components/rerankers/config"
/>
<Card
title="Build a Custom LLM Reranker"
description="Combine reranking with tailored prompts and scoring logic."
icon="sparkles"
href="/components/rerankers/models/llm_reranker"
/>
</CardGroup>
+2 -124
View File
@@ -1,128 +1,6 @@
---
title: Reranking
description: 'Improve memory search relevance with advanced reranking capabilities'
description: 'Redirect to the canonical reranker-enhanced search guide.'
---
## Overview
Reranking is an advanced feature that improves the relevance of memory search results by re-ordering them based on more sophisticated relevance scoring. After initial vector similarity search, rerankers use specialized models to provide more accurate relevance scores.
<Note>
Reranking operates as a post-processing step after the initial vector search. It takes the top results from vector similarity search and re-scores them using more advanced models or custom logic.
</Note>
## How It Works
1. **Vector Search**: Initial semantic similarity search retrieves candidate memories
2. **Reranking**: Selected reranker re-scores candidates using advanced models
3. **Final Results**: Re-ordered results with both vector and rerank scores
## Quick Start
Enable reranking by adding a `rerank` section to your memory configuration:
```python Python
from mem0 import Memory
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "my_memories",
"path": "./chroma_db"
}
},
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini"
}
},
"rerank": {
"provider": "zero_entropy",
"config": {
"model": "zerank-1",
"top_k": 5
}
}
}
memory = Memory.from_config(config)
# Add memories
messages = [
{"role": "user", "content": "I love Italian pasta, especially carbonara"},
{"role": "assistant", "content": "Carbonara is a classic Roman dish!"}
]
memory.add(messages, user_id="alice")
# Search with reranking - results automatically include rerank scores
results = memory.search("What Italian dishes does the user like?", user_id="alice")
for result in results['results']:
print(f"Memory: {result['memory']}")
print(f"Vector Score: {result['score']:.3f}")
print(f"Rerank Score: {result['rerank_score']:.3f}")
```
## Supported Providers
Mem0 supports multiple reranking providers:
- **[Zero Entropy](../../components/rerankers/models/zero_entropy)**: State-of-the-art neural reranking
- **[Cohere](../../components/rerankers/models/cohere)**: Enterprise-grade with multilingual support
- **[Sentence Transformer](../../components/rerankers/models/sentence_transformer)**: Local HuggingFace models
- **[LLM-based](../../components/rerankers/models/llm)**: Custom scoring using any LLM
## When to Use Reranking
Reranking is particularly effective for:
- **Improved Relevance**: When vector search alone doesn't provide sufficiently relevant results
- **Domain-Specific Queries**: Specialized terminology or context that benefits from advanced models
- **Customer Support**: Finding the most relevant help articles and documentation
- **Knowledge Management**: Better search results in internal knowledge bases
- **Personal AI Assistants**: More accurate memory recall for user queries
## Configuration Options
Each reranker has specific configuration options. See the [Rerankers Documentation](../../components/rerankers/overview) for detailed configuration parameters.
### Basic Configuration
```python Python
"rerank": {
"provider": "zero_entropy", # or "cohere", "sentence_transformer", "llm"
"config": {
"top_k": 5, # Limit results after reranking
"api_key": "your-key" # Provider-specific API key
}
}
```
### Controlling Reranking
You can enable or disable reranking per search:
```python Python
# Search with reranking (default when configured)
results = memory.search("query", user_id="alice", rerank=True)
# Search without reranking
results = memory.search("query", user_id="alice", rerank=False)
```
## Performance Considerations
- **Latency**: Reranking adds processing time but significantly improves relevance
- **Cost**: API-based rerankers (Zero Entropy, Cohere, LLM) have per-request costs
- **Local Options**: Sentence Transformer reranker runs locally with no API costs
- **Quality vs Speed**: Balance based on your application's requirements
## Next Steps
- Explore specific [reranker providers](../../components/rerankers/overview) and their capabilities
- Learn about [configuration options](../../components/rerankers/config) for fine-tuning
- Check out [Vector Stores](../../components/vectordbs/overview) for different storage backends
- See [Async Memory](./async-memory) for non-blocking reranking operations
<Redirect href="/open-source/features/reranker-search" />
@@ -1,56 +0,0 @@
---
title: Features
description: 'Graph Memory features'
icon: "sparkles"
iconType: "solid"
---
Graph Memory is a powerful feature that allows you to create and utilize complex relationships between pieces of information.
## Graph Memory Features
### Using Custom Prompts
You can specify a custom prompt that will be used to extract specific entities from the given input text. This allows for more targeted and relevant information extraction based on your needs. Here's an example of how to specify a custom prompt:
<CodeGroup>
```python Python
from mem0 import Memory
config = {
"graph_store": {
"provider": "neo4j",
"config": {
"url": "neo4j+s://xxx",
"username": "neo4j",
"password": "xxx"
},
"custom_prompt": "Please only extract entities containing sports related relationships and nothing else.",
}
}
m = Memory.from_config(config_dict=config)
```
```typescript TypeScript
import { Memory } from "mem0ai/oss";
const config = {
graphStore: {
provider: "neo4j",
config: {
url: "neo4j+s://xxx",
username: "neo4j",
password: "xxx",
},
customPrompt: "Please only extract entities containing sports related relationships and nothing else.",
}
}
const memory = new Memory(config);
```
</CodeGroup>
If you want to use a managed version of Mem0, please check out [Mem0](https://mem0.dev/pd). If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
-748
View File
@@ -1,748 +0,0 @@
---
title: Overview
description: 'Enhance your memory system with graph-based knowledge representation and retrieval'
icon: "network-wired"
iconType: "solid"
---
Mem0 now supports **Graph Memory**. With Graph Memory, you can create and utilize complex relationships between pieces of information, allowing for more nuanced and context-aware responses. This integration enables you to leverage the strengths of both vector-based and graph-based approaches, resulting in more accurate and comprehensive information retrieval and generation.
## Installation
To use Mem0 with Graph Memory support, install it using pip:
<CodeGroup>
```bash Python
pip install "mem0ai[graph]"
```
```bash TypeScript
npm install mem0ai
```
</CodeGroup>
This command installs Mem0 along with the necessary dependencies for graph functionality.
Try Graph Memory on Google Colab.
<a target="_blank" href="https://colab.research.google.com/drive/1PfIGVHnliIlG2v8cx0g45TF0US-jRPZ1?usp=sharing">
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
</a>
<iframe
width="100%"
height="400"
src="https://www.youtube.com/embed/u_ZAqNNVtXA"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
## Initialize Graph Memory
To initialize Graph Memory you'll need to set up your configuration with graph store providers. Currently, we support [Neo4j](#initialize-neo4j), [Memgraph](#initialize-memgraph), [Neptune Analytics](#initialize-neptune-analytics), [Neptune DB Cluster](#initialize-neptune-db),and [Kuzu](#initialize-kuzu) as graph store providers.
### Initialize Neo4j
You can setup [Neo4j](https://neo4j.com/) locally or use the hosted [Neo4j AuraDB](https://neo4j.com/product/auradb/).
<Note>If you are using Neo4j locally, you need to install [APOC plugins](https://neo4j.com/labs/apoc/4.1/installation/).</Note>
You can also customize the LLM for Graph Memory from the [Supported LLM list](https://docs.mem0.ai/components/llms/overview) with three levels of configuration:
1. **Main Configuration**: If `llm` is set in the main config, it will be used for all graph operations.
2. **Graph Store Configuration**: If `llm` is set in the graph_store config, it will override the main config `llm` and be used specifically for graph operations.
3. **Default Configuration**: If no custom LLM is set, the default LLM (`gpt-4.1-nano-2025-04-14) will be used for all graph operations.
Here's how you can do it:
<CodeGroup>
```python Python
from mem0 import Memory
config = {
"graph_store": {
"provider": "neo4j",
"config": {
"url": "neo4j+s://xxx",
"username": "neo4j",
"password": "xxx"
}
}
}
m = Memory.from_config(config_dict=config)
```
```typescript TypeScript
import { Memory } from "mem0ai/oss";
const config = {
enableGraph: true,
graphStore: {
provider: "neo4j",
config: {
url: "neo4j+s://xxx",
username: "neo4j",
password: "xxx",
}
}
}
const memory = new Memory(config);
```
```python Python (Advanced)
config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4.1-nano-2025-04-14",
"temperature": 0.2,
"max_tokens": 2000,
}
},
"graph_store": {
"provider": "neo4j",
"config": {
"url": "neo4j+s://xxx",
"username": "neo4j",
"password": "xxx"
},
"llm" : {
"provider": "openai",
"config": {
"model": "gpt-4.1-nano-2025-04-14",
"temperature": 0.0,
}
}
}
}
m = Memory.from_config(config_dict=config)
```
```typescript TypeScript (Advanced)
const config = {
llm: {
provider: "openai",
config: {
model: "gpt-4.1-nano-2025-04-14",
temperature: 0.2,
max_tokens: 2000,
}
},
enableGraph: true,
graphStore: {
provider: "neo4j",
config: {
url: "neo4j+s://xxx",
username: "neo4j",
password: "xxx",
},
llm: {
provider: "openai",
config: {
model: "gpt-4.1-nano-2025-04-14",
temperature: 0.0,
}
}
}
}
const memory = new Memory(config);
```
</CodeGroup>
<Note>
If you are using NodeSDK, you need to pass `enableGraph` as `true` in the `config` object.
</Note>
### Initialize Memgraph
Run Memgraph with Docker:
```bash
docker run -p 7687:7687 memgraph/memgraph-mage:latest --schema-info-enabled=True
```
The `--schema-info-enabled` flag is set to `True` for more performant schema generation.
Additional information can be found in the [Memgraph documentation](https://memgraph.com/docs).
You can also customize the LLM for Graph Memory from the [Supported LLM list](https://docs.mem0.ai/components/llms/overview) with three levels of configuration:
1. **Main Configuration**: If `llm` is set in the main config, it will be used for all graph operations.
2. **Graph Store Configuration**: If `llm` is set in the graph_store config, it will override the main config `llm` and be used specifically for graph operations.
3. **Default Configuration**: If no custom LLM is set, the default LLM (`gpt-4.1-nano-2025-04-142025-04-14) will be used for all graph operations.
Here's how you can do it:
<CodeGroup>
```python Python
from mem0 import Memory
config = {
"graph_store": {
"provider": "memgraph",
"config": {
"url": "bolt://localhost:7687",
"username": "memgraph",
"password": "xxx",
},
},
}
m = Memory.from_config(config_dict=config)
```
```python Python (Advanced)
config = {
"embedder": {
"provider": "openai",
"config": {"model": "text-embedding-3-large", "embedding_dims": 1536},
},
"graph_store": {
"provider": "memgraph",
"config": {
"url": "bolt://localhost:7687",
"username": "memgraph",
"password": "xxx"
}
}
}
m = Memory.from_config(config_dict=config)
```
</CodeGroup>
### Initialize Neptune Analytics
Note: You can use Neptune Analytics as part of an Amazon tech stack [Setup AWS Bedrock, AOSS, and Neptune](https://docs.mem0.ai/examples/aws_example#aws-bedrock-and-aoss)
Create an instance of Amazon Neptune Analytics in your AWS account following the [AWS documentation](https://docs.aws.amazon.com/neptune-analytics/latest/userguide/get-started.html).
- Public connectivity is not enabled by default, and if accessing from outside a VPC, it needs to be enabled.
- Once the Amazon Neptune Analytics instance is available, you will need the graph-identifier to connect.
- The Neptune Analytics instance must be created using the same vector dimensions as the embedding model creates. See: [Vector indexing in Neptune Analytics](https://docs.aws.amazon.com/neptune-analytics/latest/userguide/vector-index.html).
Ensure that you attach your AWS credentials with access to your Amazon Neptune Analytics resources by following the [Configuration and credentials precedence](https://docs.aws.amazon.com/cli/v1/userguide/cli-chap-configure.html#configure-precedence).
The IAM user or role making the request must have a policy attached that allows one of the following IAM actions in that neptune-graph:
- neptune-graph:ReadDataViaQuery
- neptune-graph:WriteDataViaQuery
- neptune-graph:DeleteDataViaQuery
User can also customize the LLM for Graph Memory from the [Supported LLM list](https://docs.mem0.ai/components/llms/overview) with three levels of configuration:
1. **Main Configuration**: If `llm` is set in the main config, it will be used for all graph operations.
2. **Graph Store Configuration**: If `llm` is set in the graph_store config, it will override the main config `llm` and be used specifically for graph operations.
3. **Default Configuration**: If no custom LLM is set, the default LLM (`gpt-4.1-nano-2025-04-14) will be used for all graph operations.
Here's how you can do it:
<CodeGroup>
```python Python
from mem0 import Memory
# Provided neptune-graph instance must have the same vector dimensions as the embedder provider.
config = {
"graph_store": {
"provider": "neptune",
"config": {
"endpoint": "neptune-graph://<GRAPH_ID>",
},
},
}
m = Memory.from_config(config_dict=config)
```
</CodeGroup>
Troubleshooting:
- For issues connecting to Amazon Neptune Analytics, please refer to the [Connecting to a graph guide](https://docs.aws.amazon.com/neptune-analytics/latest/userguide/gettingStarted-connecting.html).
- For issues related to authentication, refer to the [boto3 client configuration options](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html).
- For more details on how to connect, configure, and use the graph_memory graph store, see the Neptune Analytics example in our [AWS example guide](/examples/aws_example#aws-bedrock-and-aoss).
- The Neptune memory store uses AWS LangChain Python API to connect to Neptune instances. For additional configuration options for connecting to your Amazon Neptune Analytics instance, see [AWS LangChain API documentation](https://python.langchain.com/api_reference/aws/graphs/langchain_aws.graphs.neptune_graph.NeptuneAnalyticsGraph.html).
### Initialize Neptune DB
Note that Neptune DB does not support vectors, and this graph store provider requires a collection in the vector store to save entity vectors.
Create a cluster of Amazon DB instances in your AWS account following the [AWS documentation](https://docs.aws.amazon.com/neptune/latest/userguide/graph-get-started.html).
- Public connectivity is not enabled by default. To access the instance from outside a VPC, public connectivity needs to be enabled on the Neptune DB instance by following [Neptune Public Endpoints](https://docs.aws.amazon.com/neptune/latest/userguide/neptune-public-endpoints.html).
- Once the Amazon Neptune Cluster instance is available, you will need the graph host endpoint to connect.
- Neptune DB doesn't support vectors. The `collection_name` config field can be used to specify the vector store collection used to store vectors for the Neptune entities.
Ensure that you attach your AWS credentials with access to your Amazon Neptune Analytics resources by following the [Configuration and credentials precedence](https://docs.aws.amazon.com/cli/v1/userguide/cli-chap-configure.html#configure-precedence).
The IAM user or role making the request must have a policy attached that allows one of the following IAM actions in that neptune-db:
- neptune-db:ReadDataViaQuery
- neptune-db:WriteDataViaQuery
- neptune-db:DeleteDataViaQuery
User can also customize the LLM for Graph Memory from the [Supported LLM list](https://docs.mem0.ai/components/llms/overview) with three levels of configuration:
1. **Main Configuration**: If `llm` is set in the main config, it will be used for all graph operations.
2. **Graph Store Configuration**: If `llm` is set in the graph_store config, it will override the main config `llm` and be used specifically for graph operations.
3. **Default Configuration**: If no custom LLM is set, the default LLM (`gpt-4.1-nano-2025-04-14) will be used for all graph operations.
Here's how you can do it:
<CodeGroup>
```python Python
from mem0 import Memory
config = {
"graph_store": {
"provider": "neptunedb",
"config": {
"collection_name": "<VECTOR_COLLECTION_NAME>",
"endpoint": "neptune-graph://<HOST_ENDPOINT>",
},
},
}
m = Memory.from_config(config_dict=config)
```
</CodeGroup>
Troubleshooting:
- For issues connecting to Amazon Neptune Analytics, please refer to the [Accessing graph data in Amazon Neptune](https://docs.aws.amazon.com/neptune/latest/userguide/get-started-access-graph.html).
- For issues related to authentication, refer to the [boto3 client configuration options](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html).
- For more details on how to connect, configure, and use the graph_memory graph store, see the [Neptune DB example notebook](https://github.com/mem0ai/mem0/blob/main/examples/graph-db-demo/neptune-example.ipynb).
- The Neptune memory store uses AWS LangChain Python API to connect to Neptune instances. For additional configuration options for connecting to your Amazon Neptune Analytics instance, see [AWS LangChain API documentation](https://python.langchain.com/api_reference/aws/graphs/langchain_aws.graphs.neptune_graph.NeptuneGraph.html).
### Initialize Kuzu
[Kuzu](https://kuzudb.com) is a fully local in-process graph database system that runs openCypher queries. Kuzu comes embedded into the Python package and there is no additional setup required.
Kuzu needs a path to a file where it will store the graph database. For example:
<CodeGroup>
```python Python
config = {
"graph_store": {
"provider": "kuzu",
"config": {
"db": "/tmp/mem0-example.kuzu"
}
}
}
```
</CodeGroup>
Kuzu can also store its database in memory. Note that in this mode, all stored memories will be lost after the program has finished executing.
<CodeGroup>
```python Python
config = {
"graph_store": {
"provider": "kuzu",
"config": {
"db": ":memory:"
}
}
}
```
</CodeGroup>
You can then use the above configuration in the usual way:
<CodeGroup>
```python Python
from mem0 import Memory
m = Memory.from_config(config_dict=config)
```
</CodeGroup>
## Graph Operations
Mem0's graph memory supports the following operations:
### Add Memories
<Note>
Mem0 with Graph Memory supports "user_id", "agent_id", and "run_id" parameters. You can use any combination of these to organize your memories. Use "userId", "agentId", and "runId" in NodeSDK.
</Note>
<CodeGroup>
```python Python
# Using only user_id
m.add("I like pizza", user_id="alice")
# Using both user_id and agent_id
m.add("I like pizza", user_id="alice", agent_id="food-assistant")
# Using all three parameters for maximum organization
m.add("I like pizza", user_id="alice", agent_id="food-assistant", run_id="session-123")
```
```typescript TypeScript
// Using only userId
memory.add("I like pizza", { userId: "alice" });
// Using both userId and agentId
memory.add("I like pizza", { userId: "alice", agentId: "food-assistant" });
```
```json Output
{'message': 'ok'}
```
</CodeGroup>
### Get all memories
<CodeGroup>
```python Python
# Get all memories for a user
m.get_all(user_id="alice")
# Get all memories for a specific agent belonging to a user
m.get_all(user_id="alice", agent_id="food-assistant")
# Get all memories for a specific run/session
m.get_all(user_id="alice", run_id="session-123")
# Get all memories for a specific agent and run combination
m.get_all(user_id="alice", agent_id="food-assistant", run_id="session-123")
```
```typescript TypeScript
// Get all memories for a user
memory.getAll({ userId: "alice" });
// Get all memories for a specific agent belonging to a user
memory.getAll({ userId: "alice", agentId: "food-assistant" });
```
```json Output
{
'memories': [
{
'id': 'de69f426-0350-4101-9d0e-5055e34976a5',
'memory': 'Likes pizza',
'hash': '92128989705eef03ce31c462e198b47d',
'metadata': None,
'created_at': '2024-08-20T14:09:27.588719-07:00',
'updated_at': None,
'user_id': 'alice',
'agent_id': 'food-assistant'
}
],
'entities': [
{
'source': 'alice',
'relationship': 'likes',
'target': 'pizza'
}
]
}
```
</CodeGroup>
### Search Memories
<CodeGroup>
```python Python
# Search memories for a user
m.search("tell me my name.", user_id="alice")
# Search memories for a specific agent belonging to a user
m.search("tell me my name.", user_id="alice", agent_id="food-assistant")
# Search memories for a specific run/session
m.search("tell me my name.", user_id="alice", run_id="session-123")
# Search memories for a specific agent and run combination
m.search("tell me my name.", user_id="alice", agent_id="food-assistant", run_id="session-123")
```
```typescript TypeScript
// Search memories for a user
memory.search("tell me my name.", { userId: "alice" });
// Search memories for a specific agent belonging to a user
memory.search("tell me my name.", { userId: "alice", agentId: "food-assistant" });
```
```json Output
{
'memories': [
{
'id': 'de69f426-0350-4101-9d0e-5055e34976a5',
'memory': 'Likes pizza',
'hash': '92128989705eef03ce31c462e198b47d',
'metadata': None,
'created_at': '2024-08-20T14:09:27.588719-07:00',
'updated_at': None,
'user_id': 'alice',
'agent_id': 'food-assistant'
}
],
'entities': [
{
'source': 'alice',
'relationship': 'likes',
'target': 'pizza'
}
]
}
```
</CodeGroup>
### Delete all Memories
<CodeGroup>
```python Python
# Delete all memories for a user
m.delete_all(user_id="alice")
# Delete all memories for a specific agent belonging to a user
m.delete_all(user_id="alice", agent_id="food-assistant")
```
```typescript TypeScript
// Delete all memories for a user
memory.deleteAll({ userId: "alice" });
// Delete all memories for a specific agent belonging to a user
memory.deleteAll({ userId: "alice", agentId: "food-assistant" });
```
</CodeGroup>
## Example Usage
Here's an example of how to use Mem0's graph operations:
1. First, we'll add some memories for a user named Alice.
2. Then, we'll visualize how the graph evolves as we add more memories.
3. You'll see how entities and relationships are automatically extracted and connected in the graph.
### Add Memories
Below are the steps to add memories and visualize the graph:
<Steps>
<Step title="Add memory 'I like going to hikes'">
<CodeGroup>
```python Python
m.add("I like going to hikes", user_id="alice123")
```
```typescript TypeScript
memory.add("I like going to hikes", { userId: "alice123" });
```
</CodeGroup>
![Graph Memory Visualization](/images/graph_memory/graph_example1.png)
</Step>
<Step title="Add memory 'I love to play badminton'">
<CodeGroup>
```python Python
m.add("I love to play badminton", user_id="alice123")
```
```typescript TypeScript
memory.add("I love to play badminton", { userId: "alice123" });
```
</CodeGroup>
![Graph Memory Visualization](/images/graph_memory/graph_example2.png)
</Step>
<Step title="Add memory 'I hate playing badminton'">
<CodeGroup>
```python Python
m.add("I hate playing badminton", user_id="alice123")
```
```typescript TypeScript
memory.add("I hate playing badminton", { userId: "alice123" });
```
</CodeGroup>
![Graph Memory Visualization](/images/graph_memory/graph_example3.png)
</Step>
<Step title="Add memory 'My friend name is john and john has a dog named tommy'">
<CodeGroup>
```python Python
m.add("My friend name is john and john has a dog named tommy", user_id="alice123")
```
```typescript TypeScript
memory.add("My friend name is john and john has a dog named tommy", { userId: "alice123" });
```
</CodeGroup>
![Graph Memory Visualization](/images/graph_memory/graph_example4.png)
</Step>
<Step title="Add memory 'My name is Alice'">
<CodeGroup>
```python Python
m.add("My name is Alice", user_id="alice123")
```
```typescript TypeScript
memory.add("My name is Alice", { userId: "alice123" });
```
</CodeGroup>
![Graph Memory Visualization](/images/graph_memory/graph_example5.png)
</Step>
<Step title="Add memory 'John loves to hike and Harry loves to hike as well'">
<CodeGroup>
```python Python
m.add("John loves to hike and Harry loves to hike as well", user_id="alice123")
```
```typescript TypeScript
memory.add("John loves to hike and Harry loves to hike as well", { userId: "alice123" });
```
</CodeGroup>
![Graph Memory Visualization](/images/graph_memory/graph_example6.png)
</Step>
<Step title="Add memory 'My friend peter is the spiderman'">
<CodeGroup>
```python Python
m.add("My friend peter is the spiderman", user_id="alice123")
```
```typescript TypeScript
memory.add("My friend peter is the spiderman", { userId: "alice123" });
```
</CodeGroup>
![Graph Memory Visualization](/images/graph_memory/graph_example7.png)
</Step>
</Steps>
### Search Memories
<CodeGroup>
```python Python
m.search("What is my name?", user_id="alice123")
```
```typescript TypeScript
memory.search("What is my name?", { userId: "alice123" });
```
```json Output
{
'memories': [...],
'entities': [
{'source': 'alice123', 'relation': 'dislikes_playing','destination': 'badminton'},
{'source': 'alice123', 'relation': 'friend', 'destination': 'peter'},
{'source': 'alice123', 'relation': 'friend', 'destination': 'john'},
{'source': 'alice123', 'relation': 'has_name', 'destination': 'alice'},
{'source': 'alice123', 'relation': 'likes', 'destination': 'hiking'}
]
}
```
</CodeGroup>
The graph visualization below shows what nodes and relationships are fetched from the graph for the provided query.
![Graph Memory Visualization](/images/graph_memory/graph_example8.png)
<CodeGroup>
```python Python
m.search("Who is spiderman?", user_id="alice123")
```
```typescript TypeScript
memory.search("Who is spiderman?", { userId: "alice123" });
```
```json Output
{
'memories': [...],
'entities': [
{'source': 'peter', 'relation': 'identity','destination': 'spiderman'}
]
}
```
</CodeGroup>
![Graph Memory Visualization](/images/graph_memory/graph_example9.png)
> **Note:** The Graph Memory implementation is not standalone. You will be adding/retrieving memories to the vector store and the graph store simultaneously.
## Using Multiple Agents with Graph Memory
When working with multiple agents and sessions, you can use the `agent_id` and `run_id` parameters to organize memories by user, agent, and run context. This allows you to:
1. Create agent-specific knowledge graphs.
2. Share common knowledge between agents.
3. Isolate sensitive or specialized information to specific agents.
4. Track conversation sessions and runs separately.
5. Maintain context across different execution contexts.
### Example: Multi-Agent Setup
<CodeGroup>
```python Python
# Add memories for different agents
m.add("I prefer Italian cuisine", user_id="bob", agent_id="food-assistant")
m.add("I'm allergic to peanuts", user_id="bob", agent_id="health-assistant")
m.add("I live in Seattle", user_id="bob") # Shared across all agents
# Add memories for specific runs/sessions
m.add("Current session: discussing dinner plans", user_id="bob", agent_id="food-assistant", run_id="dinner-session-001")
m.add("Previous session: allergy consultation", user_id="bob", agent_id="health-assistant", run_id="health-session-001")
# Search within specific agent context
food_preferences = m.search("What food do I like?", user_id="bob", agent_id="food-assistant")
health_info = m.search("What are my allergies?", user_id="bob", agent_id="health-assistant")
location = m.search("Where do I live?", user_id="bob") # Searches across all agents
# Search within specific run context
current_session = m.search("What are we discussing?", user_id="bob", run_id="dinner-session-001")
```
```typescript TypeScript
// Add memories for different agents
memory.add("I prefer Italian cuisine", { userId: "bob", agentId: "food-assistant" });
memory.add("I'm allergic to peanuts", { userId: "bob", agentId: "health-assistant" });
memory.add("I live in Seattle", { userId: "bob" }); // Shared across all agents
// Search within specific agent context
const foodPreferences = memory.search("What food do I like?", { userId: "bob", agentId: "food-assistant" });
const healthInfo = memory.search("What are my allergies?", { userId: "bob", agentId: "health-assistant" });
const location = memory.search("Where do I live?", { userId: "bob" }); // Searches across all agents
```
</CodeGroup>
If you want to use a managed version of Mem0, please check out [Mem0](https://mem0.dev/pd). If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
+1 -1
View File
@@ -32,7 +32,7 @@ Choose your preferred SDK and get Mem0 running locally in minutes:
Mem0 Open Source offers powerful features for building production-grade AI applications with memory. From graph-based knowledge structures to flexible component configuration, you have full control over how memory works in your system.
<CardGroup cols={3}>
<Card title="Graph Memory" icon="network-wired" href="/open-source/graph_memory/overview">
<Card title="Graph Memory" icon="network-wired" href="/open-source/features/graph-memory">
Build relationship-aware memory with knowledge graph capabilities
</Card>
+1 -1
View File
@@ -36,7 +36,7 @@ This sets up Mem0 with:
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
- [OpenSearch as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/opensearch)
- [Neptune Analytics as your graph store](https://docs.mem0.ai/open-source/graph_memory/overview#initialize-neptune-analytics).
- [Graph Memory guide](https://docs.mem0.ai/open-source/features/graph-memory).
```python
import boto3
@@ -36,7 +36,7 @@ This sets up Mem0 with:
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
- [Neptune Analytics as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/neptune_analytics)
- [Neptune Analytics as the graph store](https://docs.mem0.ai/open-source/graph_memory/overview#initialize-neptune-analytics).
- [Graph Memory guide](https://docs.mem0.ai/open-source/features/graph-memory).
```python
import boto3