-
Notifications
You must be signed in to change notification settings - Fork 929
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mem0 Integration: Add mem0 as memory provider for RAG #914
Draft
Dev-Khant
wants to merge
2
commits into
meta-llama:main
Choose a base branch
from
Dev-Khant:mem0-integration
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
18 changes: 18 additions & 0 deletions
18
llama_stack/providers/remote/tool_runtime/mem0_memory/__init__.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
# All rights reserved. | ||
# | ||
# This source code is licensed under the terms described in the LICENSE file in | ||
# the root directory of this source tree. | ||
|
||
from typing import Any, Dict | ||
|
||
from llama_stack.providers.datatypes import Api | ||
|
||
from .config import Mem0ToolRuntimeConfig | ||
from .memory import Mem0MemoryToolRuntimeImpl | ||
|
||
|
||
async def get_adapter_impl(config: Mem0ToolRuntimeConfig, _deps): | ||
impl = Mem0MemoryToolRuntimeImpl(config) | ||
await impl.initialize() | ||
return impl |
19 changes: 19 additions & 0 deletions
19
llama_stack/providers/remote/tool_runtime/mem0_memory/config.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
# All rights reserved. | ||
# | ||
# This source code is licensed under the terms described in the LICENSE file in | ||
# the root directory of this source tree. | ||
|
||
from typing import Optional | ||
|
||
from pydantic import BaseModel | ||
|
||
|
||
class Mem0ToolRuntimeConfig(BaseModel): | ||
"""Configuration for Mem0 Tool Runtime""" | ||
|
||
host: Optional[str] = "https://api.mem0.ai" | ||
api_key: Optional[str] = None | ||
top_k: int = 10 | ||
org_id: Optional[str] = None | ||
project_id: Optional[str] = None |
227 changes: 227 additions & 0 deletions
227
llama_stack/providers/remote/tool_runtime/mem0_memory/memory.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,227 @@ | ||
# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
# All rights reserved. | ||
# | ||
# This source code is licensed under the terms described in the LICENSE file in | ||
# the root directory of this source tree. | ||
|
||
import asyncio | ||
import logging | ||
import secrets | ||
import string | ||
import os | ||
from typing import Any, Dict, List, Optional | ||
|
||
from llama_stack.apis.common.content_types import ( | ||
InterleavedContent, | ||
TextContentItem, | ||
URL, | ||
) | ||
from llama_stack.apis.inference import Inference | ||
from llama_stack.apis.tools import ( | ||
RAGDocument, | ||
RAGQueryConfig, | ||
RAGQueryResult, | ||
RAGToolRuntime, | ||
ToolDef, | ||
ToolInvocationResult, | ||
ToolRuntime, | ||
) | ||
from llama_stack.apis.vector_io import QueryChunksResponse, VectorIO | ||
from llama_stack.providers.datatypes import ToolsProtocolPrivate | ||
from llama_stack.providers.utils.memory.vector_store import ( | ||
content_from_doc, | ||
make_overlapped_chunks, | ||
) | ||
|
||
from .config import Mem0ToolRuntimeConfig | ||
from llama_stack.providers.inline.tool_runtime.rag.context_retriever import generate_rag_query | ||
|
||
import requests | ||
from urllib.parse import urljoin | ||
import json | ||
|
||
log = logging.getLogger(__name__) | ||
|
||
|
||
def make_random_string(length: int = 8): | ||
return "".join( | ||
secrets.choice(string.ascii_letters + string.digits) for _ in range(length) | ||
) | ||
|
||
|
||
class Mem0MemoryToolRuntimeImpl(ToolsProtocolPrivate, ToolRuntime, RAGToolRuntime): | ||
def __init__( | ||
self, | ||
config: Mem0ToolRuntimeConfig, | ||
): | ||
self.config = config | ||
|
||
# Mem0 API configuration | ||
self.api_base_url = config.host | ||
self.api_key = config.api_key or os.getenv("MEM0_API_KEY") | ||
self.org_id = config.org_id | ||
self.project_id = config.project_id | ||
|
||
# Validate configuration | ||
if not self.api_key: | ||
raise ValueError("Mem0 API Key not provided") | ||
if (self.org_id is not None) != (self.project_id is not None): | ||
raise ValueError("Both org_id and project_id must be provided") | ||
|
||
# Setup headers | ||
self.headers = { | ||
"Authorization": f"Token {self.api_key}", | ||
"Content-Type": "application/json", | ||
} | ||
|
||
# Validate API key and connection | ||
self._validate_api_connection() | ||
|
||
def _validate_api_connection(self): | ||
"""Validate API key and connection by making a test request.""" | ||
try: | ||
params = {"org_id": self.org_id, "project_id": self.project_id} | ||
response = requests.get( | ||
urljoin(self.api_base_url, "/v1/ping/"), | ||
headers=self.headers, | ||
params=params, | ||
timeout=10 | ||
) | ||
response.raise_for_status() | ||
except requests.exceptions.RequestException as e: | ||
raise ValueError(f"Failed to validate Mem0 API connection: {str(e)}") | ||
|
||
async def initialize(self): | ||
pass | ||
|
||
async def shutdown(self): | ||
pass | ||
|
||
async def insert( | ||
self, | ||
documents: List[RAGDocument], | ||
vector_db_id: str, | ||
chunk_size_in_tokens: int = 512, | ||
) -> None: | ||
chunks = [] | ||
for doc in documents: | ||
content = await content_from_doc(doc) | ||
|
||
# Add to Mem0 memory via API | ||
try: | ||
payload = { | ||
"messages": [{"role": "user", "content": content}], | ||
"metadata": {"document_id": doc.document_id}, | ||
"user_id": vector_db_id, | ||
} | ||
if self.org_id and self.project_id: | ||
payload["org_id"] = self.org_id | ||
payload["project_id"] = self.project_id | ||
|
||
response = requests.post( | ||
urljoin(self.api_base_url, "/v1/memories/"), | ||
headers=self.headers, | ||
json=payload, | ||
timeout=60 | ||
) | ||
print(response.json()) | ||
response.raise_for_status() | ||
except requests.exceptions.RequestException as e: | ||
log.error(f"Failed to insert document to Mem0: {str(e)}") | ||
# Continue with vector store insertion even if Mem0 fails | ||
|
||
chunks.extend( | ||
make_overlapped_chunks( | ||
doc.document_id, | ||
content, | ||
chunk_size_in_tokens, | ||
chunk_size_in_tokens // 4, | ||
) | ||
) | ||
|
||
if not chunks: | ||
return | ||
|
||
async def query( | ||
self, | ||
content: InterleavedContent, | ||
vector_db_ids: List[str], | ||
query_config: Optional[RAGQueryConfig] = None, | ||
) -> RAGQueryResult: | ||
if not vector_db_ids: | ||
return RAGQueryResult(content=None) | ||
|
||
query_config = query_config or RAGQueryConfig() | ||
query = content | ||
print(query) | ||
|
||
# Search Mem0 memory via API | ||
mem0_chunks = [] | ||
for vector_db_id in vector_db_ids: | ||
try: | ||
payload = { | ||
"query": query, | ||
"user_id": vector_db_id | ||
} | ||
if self.org_id and self.project_id: | ||
payload["org_id"] = self.org_id | ||
payload["project_id"] = self.project_id | ||
|
||
response = requests.post( | ||
urljoin(self.api_base_url, "/v1/memories/search/"), | ||
headers=self.headers, | ||
json=payload, | ||
timeout=60 | ||
) | ||
print(response.json()) | ||
response.raise_for_status() | ||
|
||
mem0_results = response.json() | ||
mem0_chunks = [ | ||
TextContentItem( | ||
text=f"id:{result.get('metadata', {}).get('document_id', 'unknown')}; content:{result.get('memory', '')}" | ||
) | ||
for result in mem0_results | ||
] | ||
except requests.exceptions.RequestException as e: | ||
log.error(f"Failed to search Mem0: {str(e)}") | ||
# Continue with vector store search even if Mem0 fails | ||
|
||
if not mem0_chunks: | ||
return RAGQueryResult(content=None) | ||
|
||
return RAGQueryResult( | ||
content=[ | ||
TextContentItem( | ||
text="Here are the retrieved documents for relevant context:\n=== START-RETRIEVED-CONTEXT ===\n", | ||
), | ||
*mem0_chunks, | ||
TextContentItem( | ||
text="\n=== END-RETRIEVED-CONTEXT ===\n", | ||
), | ||
], | ||
) | ||
|
||
async def list_runtime_tools( | ||
self, tool_group_id: Optional[str] = None, mcp_endpoint: Optional[URL] = None | ||
) -> List[ToolDef]: | ||
# Parameters are not listed since these methods are not yet invoked automatically | ||
# by the LLM. The method is only implemented so things like /tools can list without | ||
# encountering fatals. | ||
return [ | ||
ToolDef( | ||
name="query_from_mem0", | ||
description="Retrieve context from mem0", | ||
), | ||
ToolDef( | ||
name="insert_into_mem0", | ||
description="Insert documents into mem0", | ||
), | ||
] | ||
|
||
async def invoke_tool( | ||
self, tool_name: str, kwargs: Dict[str, Any] | ||
) -> ToolInvocationResult: | ||
raise RuntimeError( | ||
"This toolgroup should not be called generically but only through specific methods of the RAGToolRuntime protocol" | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry for the late response. The problem is that we don't support multiple providers for
client.tool_runtime.rag_tool.insert
:llama-stack/llama_stack/distribution/routers/routers.py
Line 644 in bfc7921
To support this, we might need to add
provider_id
as an argument, similar toclient.vector_dbs.register
for example.However, I also think it might be time to rework this API
client.tool_runtime.rag_tool.insert
. Will need some time to think through this.