diff --git a/docs/components/rerankers/config.mdx b/docs/components/rerankers/config.mdx index c69fb077b..87bd905d7 100644 --- a/docs/components/rerankers/config.mdx +++ b/docs/components/rerankers/config.mdx @@ -94,7 +94,7 @@ config = { "model": "gpt-4.1-nano-2025-04-14" } }, - "rerank": { + "reranker": { "provider": "zero_entropy", "config": { "model": "zerank-1", diff --git a/docs/components/rerankers/models/llm.mdx b/docs/components/rerankers/models/llm.mdx index c1e019215..ba61fe70d 100644 --- a/docs/components/rerankers/models/llm.mdx +++ b/docs/components/rerankers/models/llm.mdx @@ -3,6 +3,10 @@ title: LLM as Reranker description: 'Flexible reranking using LLMs' --- + +**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. + + 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", diff --git a/docs/components/rerankers/overview.mdx b/docs/components/rerankers/overview.mdx index d75202629..b33fde152 100644 --- a/docs/components/rerankers/overview.mdx +++ b/docs/components/rerankers/overview.mdx @@ -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 + +Reranking trades extra latency for better precision. Start once you have baseline search working and measure before/after relevance. + -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 - - -Reranking operates as a post-processing step and can significantly improve search relevance at the cost of additional latency and API calls. - - -## Supported Rerankers - -See the list of supported rerankers below. - - - - - - - - + + + + + + + -## 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. + + + + + diff --git a/docs/docs.json b/docs/docs.json index a394e3dd5..880e58e86 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -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" + } ] } ] diff --git a/docs/examples/aws_example.mdx b/docs/examples/aws_example.mdx index 33c4b9fe7..1918d5a05 100644 --- a/docs/examples/aws_example.mdx +++ b/docs/examples/aws_example.mdx @@ -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 diff --git a/docs/examples/aws_neptune_analytics_hybrid_store.mdx b/docs/examples/aws_neptune_analytics_hybrid_store.mdx index c1fba21db..e1e91cc84 100644 --- a/docs/examples/aws_neptune_analytics_hybrid_store.mdx +++ b/docs/examples/aws_neptune_analytics_hybrid_store.mdx @@ -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 diff --git a/docs/images/docs thumbnails/API.png b/docs/images/docs thumbnails/API.png new file mode 100644 index 000000000..b4aada88c Binary files /dev/null and b/docs/images/docs thumbnails/API.png differ diff --git a/docs/images/docs thumbnails/Cookbooks.png b/docs/images/docs thumbnails/Cookbooks.png new file mode 100644 index 000000000..0cf31c931 Binary files /dev/null and b/docs/images/docs thumbnails/Cookbooks.png differ diff --git a/docs/images/docs thumbnails/Integrations.png b/docs/images/docs thumbnails/Integrations.png new file mode 100644 index 000000000..937febcc9 Binary files /dev/null and b/docs/images/docs thumbnails/Integrations.png differ diff --git a/docs/images/docs thumbnails/Mem0 Open Source.png b/docs/images/docs thumbnails/Mem0 Open Source.png new file mode 100644 index 000000000..76a455401 Binary files /dev/null and b/docs/images/docs thumbnails/Mem0 Open Source.png differ diff --git a/docs/images/docs thumbnails/Mem0 OpenMemory.png b/docs/images/docs thumbnails/Mem0 OpenMemory.png new file mode 100644 index 000000000..dd6952584 Binary files /dev/null and b/docs/images/docs thumbnails/Mem0 OpenMemory.png differ diff --git a/docs/images/docs thumbnails/Mem0 Platform.png b/docs/images/docs thumbnails/Mem0 Platform.png new file mode 100644 index 000000000..3e2552f19 Binary files /dev/null and b/docs/images/docs thumbnails/Mem0 Platform.png differ diff --git a/docs/introduction.mdx b/docs/introduction.mdx index 3c3796ca2..295fe2540 100644 --- a/docs/introduction.mdx +++ b/docs/introduction.mdx @@ -6,7 +6,7 @@ mode: "custom" {/* debug: welcome-layout-v2 */} -
+

Build with mem0

@@ -31,20 +31,64 @@ mode: "custom"
- - - Managed memory with production-scale infrastructure, ready in minutes. - +
@@ -54,18 +98,62 @@ mode: "custom"
- - - Production-ready tutorials that show how to ship memorable AI experiences. - + diff --git a/docs/llms.txt b/docs/llms.txt index c678ad44e..f3cbd5d69 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -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 diff --git a/docs/open-source/configuration.mdx b/docs/open-source/configuration.mdx index aa75f7b1b..8fbaab2fd 100644 --- a/docs/open-source/configuration.mdx +++ b/docs/open-source/configuration.mdx @@ -175,7 +175,7 @@ config = { m = Memory.from_config(config) ``` - + Learn how to use graph memory for relationship-based retrieval @@ -225,7 +225,7 @@ config = { } ``` - + Learn how reranking improves memory search accuracy @@ -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) diff --git a/docs/open-source/features/graph-memory.mdx b/docs/open-source/features/graph-memory.mdx new file mode 100644 index 000000000..0c403cf02 --- /dev/null +++ b/docs/open-source/features/graph-memory.mdx @@ -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. + + +**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 + + +## 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] +``` + + +Graph Memory complements your vector store. Keep both healthy to avoid blind spots. + + +## How It Works + + + +Mem0’s extraction LLM identifies entities, relationships, and timestamps from the conversation payload you send to `memory.add`. + + +Embeddings land in your configured vector database while nodes and edges flow into a Bolt-compatible graph backend (Neo4j, Memgraph, Neptune, or Kuzu). + + +`memory.search` first performs vector similarity, then follows connected nodes to boost (or filter) answers before optionally handing results to a reranker. + + + +## Quickstart (Neo4j Aura) + + +**Time to implement:** ~10 minutes · **Prerequisites:** Python 3.10+, Node.js 18+, Neo4j Aura DB (free tier) + + +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. + + + + + +```bash +pip install "mem0ai[graph]" +``` + + +```bash +export NEO4J_URL="neo4j+s://.databases.neo4j.io" +export NEO4J_USERNAME="neo4j" +export NEO4J_PASSWORD="your-password" +``` + + +```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"]) +``` + + + + + + +```bash +npm install mem0ai +``` + + +```bash +export NEO4J_URL="neo4j+s://.databases.neo4j.io" +export NEO4J_USERNAME="neo4j" +export NEO4J_PASSWORD="your-password" +``` + + +```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); +}); +``` + + + + + + +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. + + +## Operate Graph Memory Day-to-Day + + + + Guide which relationships become nodes and edges. + + +```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); +``` + + + + Keep noisy edges out of the graph by demanding higher extraction confidence. + +```python +config["graph_store"]["config"]["threshold"] = 0.75 +``` + + + 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) +``` + + + Separate or share context across agents and sessions with `user_id`, `agent_id`, and `run_id`. + + +```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" }); +``` + + + + + +Monitor graph growth, especially on free tiers, by periodically cleaning dormant nodes: `MATCH (n) WHERE n.lastSeen < date() - duration('P90D') DETACH DELETE n`. + + +## Troubleshooting + + + + Confirm Bolt connectivity is enabled, credentials match Aura, and your IP is allow-listed. Retry after confirming the URI format is `neo4j+s://...`. + + + Ensure the graph identifier matches the vector dimension used by your embedder and that the IAM role allows `neptune-graph:*DataViaQuery` actions. + + + Catch the provider error and retry with `enable_graph=False` so vector-only search keeps serving responses while the graph backend recovers. + + + +## 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. + + + + 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://", + username: "neo4j", + 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/). + + + 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). + + + 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://", + }, + }, +} + +m = Memory.from_config(config_dict=config) +``` + +Reference: [Neptune Analytics Guide](https://docs.aws.amazon.com/neptune/latest/analytics/). + + + 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": "", + "endpoint": "neptune-graph://", + }, + }, +} + +m = Memory.from_config(config_dict=config) +``` + +Reference: [Accessing Data in Neptune DB](https://docs.aws.amazon.com/neptune/latest/userguide/). + + + 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. + + + + + + + diff --git a/docs/open-source/features/overview.mdx b/docs/open-source/features/overview.mdx index b4522552c..5d4cd25d6 100644 --- a/docs/open-source/features/overview.mdx +++ b/docs/open-source/features/overview.mdx @@ -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 diff --git a/docs/open-source/features/reranker-search.mdx b/docs/open-source/features/reranker-search.mdx index 6ef34fdb5..ec8abc5ae 100644 --- a/docs/open-source/features/reranker-search.mdx +++ b/docs/open-source/features/reranker-search.mdx @@ -3,8 +3,8 @@ title: Reranker-Enhanced Search description: 'Improve search relevance with reranking models in Mem0 1.0.0 ' --- - -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. + +**Mem0 1.0.0+** supports reranker-enhanced search, letting specialized models reorder vector hits so you deliver the most relevant memories. ## 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']}") ``` + +Expect each result to include both the base vector score and an updated rerank score so you can compare quality improvements. + + ### Controlling Reranking ```python @@ -414,3 +426,18 @@ results = m.search("query", user_id="alice") # Automatically reranked Reranker-enhanced search significantly improves result relevance. Start with a local model and upgrade to API-based solutions as your needs grow. + + + + + diff --git a/docs/open-source/features/reranking.mdx b/docs/open-source/features/reranking.mdx index 6df935a6e..ef55e1433 100644 --- a/docs/open-source/features/reranking.mdx +++ b/docs/open-source/features/reranking.mdx @@ -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. - - -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. - - -## 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 + diff --git a/docs/open-source/graph_memory/features.mdx b/docs/open-source/graph_memory/features.mdx deleted file mode 100644 index 41800e6c5..000000000 --- a/docs/open-source/graph_memory/features.mdx +++ /dev/null @@ -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: - - - ```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); - ``` - - -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: - - diff --git a/docs/open-source/graph_memory/overview.mdx b/docs/open-source/graph_memory/overview.mdx deleted file mode 100644 index 126d4acb0..000000000 --- a/docs/open-source/graph_memory/overview.mdx +++ /dev/null @@ -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: - - -```bash Python -pip install "mem0ai[graph]" -``` - -```bash TypeScript -npm install mem0ai -``` - - -This command installs Mem0 along with the necessary dependencies for graph functionality. - -Try Graph Memory on Google Colab. - - Open In Colab - - - - - -## 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/). - -If you are using Neo4j locally, you need to install [APOC plugins](https://neo4j.com/labs/apoc/4.1/installation/). - -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: - - - -```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); -``` - - - -If you are using NodeSDK, you need to pass `enableGraph` as `true` in the `config` object. - - -### 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: - - - -```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) -``` - - -### 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: - - -```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://", - }, - }, -} - -m = Memory.from_config(config_dict=config) -``` - - -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: - - -```python Python -from mem0 import Memory - -config = { - "graph_store": { - "provider": "neptunedb", - "config": { - "collection_name": "", - "endpoint": "neptune-graph://", - }, - }, -} - -m = Memory.from_config(config_dict=config) -``` - - -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: - - -```python Python -config = { - "graph_store": { - "provider": "kuzu", - "config": { - "db": "/tmp/mem0-example.kuzu" - } - } -} -``` - - -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. - - -```python Python -config = { - "graph_store": { - "provider": "kuzu", - "config": { - "db": ":memory:" - } - } -} -``` - - -You can then use the above configuration in the usual way: - - -```python Python -from mem0 import Memory - -m = Memory.from_config(config_dict=config) -``` - - -## Graph Operations - -Mem0's graph memory supports the following operations: - -### Add Memories - - -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. - - - -```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'} -``` - - - -### Get all memories - - -```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' - } - ] -} -``` - - -### Search Memories - - -```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' - } - ] -} -``` - - - -### Delete all Memories - - -```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" }); -``` - - -## 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: - - - - - -```python Python -m.add("I like going to hikes", user_id="alice123") -``` - -```typescript TypeScript -memory.add("I like going to hikes", { userId: "alice123" }); -``` - -![Graph Memory Visualization](/images/graph_memory/graph_example1.png) - - - - - -```python Python -m.add("I love to play badminton", user_id="alice123") -``` - -```typescript TypeScript -memory.add("I love to play badminton", { userId: "alice123" }); -``` - - -![Graph Memory Visualization](/images/graph_memory/graph_example2.png) - - - - - - -```python Python -m.add("I hate playing badminton", user_id="alice123") -``` - -```typescript TypeScript -memory.add("I hate playing badminton", { userId: "alice123" }); -``` - - -![Graph Memory Visualization](/images/graph_memory/graph_example3.png) - - - - - - -```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" }); -``` - - -![Graph Memory Visualization](/images/graph_memory/graph_example4.png) - - - - - - -```python Python -m.add("My name is Alice", user_id="alice123") -``` - -```typescript TypeScript -memory.add("My name is Alice", { userId: "alice123" }); -``` - - -![Graph Memory Visualization](/images/graph_memory/graph_example5.png) - - - - - - -```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" }); -``` - - -![Graph Memory Visualization](/images/graph_memory/graph_example6.png) - - - - - - -```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" }); -``` - - -![Graph Memory Visualization](/images/graph_memory/graph_example7.png) - - - - - - -### Search Memories - - -```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'} - ] -} -``` - - -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) - - -```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'} - ] -} -``` - - -![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 - - -```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 -``` - - -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: - - diff --git a/docs/open-source/overview.mdx b/docs/open-source/overview.mdx index ea32abab3..158c66b62 100644 --- a/docs/open-source/overview.mdx +++ b/docs/open-source/overview.mdx @@ -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. - + Build relationship-aware memory with knowledge graph capabilities diff --git a/docs/v0x/examples/aws_example.mdx b/docs/v0x/examples/aws_example.mdx index e8355657e..ae664f2f6 100644 --- a/docs/v0x/examples/aws_example.mdx +++ b/docs/v0x/examples/aws_example.mdx @@ -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 diff --git a/docs/v0x/examples/aws_neptune_analytics_hybrid_store.mdx b/docs/v0x/examples/aws_neptune_analytics_hybrid_store.mdx index c1fba21db..e1e91cc84 100644 --- a/docs/v0x/examples/aws_neptune_analytics_hybrid_store.mdx +++ b/docs/v0x/examples/aws_neptune_analytics_hybrid_store.mdx @@ -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