Skip to content
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

Add Upstash Vector Index support #1941

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/components/vectordbs/config.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Config in mem0 is a dictionary that specifies the settings for your vector datab

The config is defined as a Python dictionary with two main keys:
- `vector_store`: Specifies the vector database provider and its configuration
- `provider`: The name of the vector database (e.g., "chroma", "pgvector", "qdrant", "milvus")
- `provider`: The name of the vector database (e.g., "chroma", "pgvector", "qdrant", "milvus", "upstash_vector")
- `config`: A nested dictionary containing provider-specific settings

## How to Use Config
Expand Down
41 changes: 41 additions & 0 deletions docs/components/vectordbs/dbs/upstash-vector.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
[Upstash Vector](https://upstash.com/docs/vector) is a serverless vector database designed for working with vector embeddings.

<Note>
Currently, Mem0 does not support for Upstash Vector embedding models.
So you can use Upstash Vector only as a vector database provider.
</Note>

### Usage

```python
import os
from mem0 import Memory

os.environ["OPENAI_API_KEY"] = "sk-xx"
os.environ["UPSTASH_VECTOR_REST_URL"] = "..."
os.environ["UPSTASH_VECTOR_REST_TOKEN"] = "..."

config = {
"vector_store": {
"provider": "upstash_vector",
}
}

m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
```

### Config

Here are the parameters available for configuring Upstash Vector:

| Parameter | Description | Default Value |
| --- | --- | --- |
| `url` | URL for the Upstash Vector index | `None` |
| `token` | Token for the Upstash Vector index | `None` |
| `client` | An `upstash_vector.Index` instance | `None` |
| `namespace` | The default namespace used | `None` |

<Note>
When `url` and `token` are not provided, the `UPSTASH_VECTOR_REST_URL` and `UPSTASH_VECTOR_REST_TOKEN` environment variables are used.
</Note>
1 change: 1 addition & 0 deletions docs/components/vectordbs/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ See the list of supported vector databases below.
<Card title="Qdrant" href="/components/vectordbs/dbs/qdrant"></Card>
<Card title="Chroma" href="/components/vectordbs/dbs/chroma"></Card>
<Card title="Pgvector" href="/components/vectordbs/dbs/pgvector"></Card>
<Card title="Upstash Vector" href="/components/vectordbs/dbs/upstash-vector"></Card>
</CardGroup>

## Usage
Expand Down
3 changes: 2 additions & 1 deletion docs/mint.json
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,8 @@
"components/vectordbs/dbs/chroma",
"components/vectordbs/dbs/pgvector",
"components/vectordbs/dbs/qdrant",
"components/vectordbs/dbs/milvus"
"components/vectordbs/dbs/milvus",
"components/vectordbs/dbs/upstash-vector"
]
}
]
Expand Down
16 changes: 7 additions & 9 deletions mem0/client/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,12 @@ class MemoryClient:
"""

def __init__(
self,
api_key: Optional[str] = None,
host: Optional[str] = None,
organization: Optional[str] = None,
project: Optional[str] = None
):
self,
api_key: Optional[str] = None,
host: Optional[str] = None,
organization: Optional[str] = None,
project: Optional[str] = None,
):
"""Initialize the MemoryClient.

Args:
Expand Down Expand Up @@ -271,9 +271,7 @@ def delete_users(self) -> Dict[str, str]:
params = {"org_name": self.organization, "project_name": self.project}
entities = self.users()
for entity in entities["results"]:
response = self.client.delete(
f"/v1/entities/{entity['type']}/{entity['id']}/", params=params
)
response = self.client.delete(f"/v1/entities/{entity['type']}/{entity['id']}/", params=params)
response.raise_for_status()

capture_client_event("client.delete_users", self)
Expand Down
30 changes: 30 additions & 0 deletions mem0/configs/vector_stores/upstash_vector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import os
from typing import Any, ClassVar, Dict, Optional

from pydantic import BaseModel, Field, model_validator


class UpstashVectorConfig(BaseModel):
from upstash_vector import Index

Index: ClassVar[type] = Index

url: Optional[str] = Field(None, description="URL for Upstash Vector index")
token: Optional[str] = Field(None, description="Token for Upstash Vector index")
client: Optional[Index] = Field(None, description="Existing `upstash_vector.Index` client instance")
namespace: Optional[str] = Field(None, description="Default namespace for the index")

@model_validator(mode="before")
@classmethod
def check_credentials_or_client(cls, values: Dict[str, Any]) -> Dict[str, Any]:
client = values.get("client")
url = values.get("url") or os.environ.get("UPSTASH_VECTOR_REST_URL")
token = values.get("token") or os.environ.get("UPSTASH_VECTOR_REST_TOKEN")

if not client and not (url and token):
raise ValueError("Either a client or URL and token must be provided.")
return values

model_config = {
"arbitrary_types_allowed": True,
}
3 changes: 2 additions & 1 deletion mem0/embeddings/gemini.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
from typing import Optional

import google.generativeai as genai

from mem0.configs.embeddings.base import BaseEmbedderConfig
Expand Down Expand Up @@ -27,4 +28,4 @@ def embed(self, text):
"""
text = text.replace("\n", " ")
response = genai.embed_content(model=self.config.model, content=text)
return response['embedding']
return response["embedding"]
2 changes: 1 addition & 1 deletion mem0/embeddings/huggingface.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ def embed(self, text):
Returns:
list: The embedding vector.
"""
return self.model.encode(text, convert_to_numpy = True).tolist()
return self.model.encode(text, convert_to_numpy=True).tolist()
4 changes: 3 additions & 1 deletion mem0/llms/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ def __init__(self, config: Optional[BaseLlmConfig] = None):
if os.environ.get("OPENROUTER_API_KEY"): # Use OpenRouter
self.client = OpenAI(
api_key=os.environ.get("OPENROUTER_API_KEY"),
base_url=self.config.openrouter_base_url or os.getenv("OPENROUTER_API_BASE") or "https://openrouter.ai/api/v1",
base_url=self.config.openrouter_base_url
or os.getenv("OPENROUTER_API_BASE")
or "https://openrouter.ai/api/v1",
)
else:
api_key = self.config.api_key or os.getenv("OPENAI_API_KEY")
Expand Down
27 changes: 21 additions & 6 deletions mem0/memory/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import logging
import uuid
import warnings
from collections import defaultdict
from datetime import datetime
from typing import Any, Dict

Expand Down Expand Up @@ -37,7 +36,12 @@ def __init__(self, config: MemoryConfig = MemoryConfig()):
)
self.llm = LlmFactory.create(self.config.llm.provider, self.config.llm.config)
self.db = SQLiteManager(self.config.history_db_path)
self.collection_name = self.config.vector_store.config.collection_name

if hasattr(self.config.vector_store.config, "collection_name"):
self.collection_name = self.config.vector_store.config.collection_name
else:
self.collection_name = None

self.version = self.config.version

self.enable_graph = False
Expand Down Expand Up @@ -195,7 +199,12 @@ def _add_to_vector_store(self, messages, metadata, filters):
}
)
elif resp["event"] == "UPDATE":
self._update_memory(memory_id=resp["id"], data=resp["text"], existing_embeddings=new_message_embeddings, metadata=metadata)
self._update_memory(
memory_id=resp["id"],
data=resp["text"],
existing_embeddings=new_message_embeddings,
metadata=metadata,
)
returned_memories.append(
{
"id": resp["id"],
Expand Down Expand Up @@ -304,10 +313,14 @@ def get_all(self, user_id=None, agent_id=None, run_id=None, limit=100):
with concurrent.futures.ThreadPoolExecutor() as executor:
future_memories = executor.submit(self._get_all_from_vector_store, filters, limit)
future_graph_entities = (
executor.submit(self.graph.get_all, filters, limit) if self.version == "v1.1" and self.enable_graph else None
executor.submit(self.graph.get_all, filters, limit)
if self.version == "v1.1" and self.enable_graph
else None
)

concurrent.futures.wait([future_memories, future_graph_entities] if future_graph_entities else [future_memories])
concurrent.futures.wait(
[future_memories, future_graph_entities] if future_graph_entities else [future_memories]
)

all_memories = future_memories.result()
graph_entities = future_graph_entities.result() if future_graph_entities else None
Expand Down Expand Up @@ -399,7 +412,9 @@ def search(self, query, user_id=None, agent_id=None, run_id=None, limit=100, fil
else None
)

concurrent.futures.wait([future_memories, future_graph_entities] if future_graph_entities else [future_memories])
concurrent.futures.wait(
[future_memories, future_graph_entities] if future_graph_entities else [future_memories]
)

original_memories = future_memories.result()
graph_entities = future_graph_entities.result() if future_graph_entities else None
Expand Down
1 change: 1 addition & 0 deletions mem0/utils/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ class VectorStoreFactory:
"chroma": "mem0.vector_stores.chroma.ChromaDB",
"pgvector": "mem0.vector_stores.pgvector.PGVector",
"milvus": "mem0.vector_stores.milvus.MilvusDB",
"upstash_vector": "mem0.vector_stores.upstash_vector.UpstashVector",
}

@classmethod
Expand Down
3 changes: 2 additions & 1 deletion mem0/vector_stores/configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

class VectorStoreConfig(BaseModel):
provider: str = Field(
description="Provider of the vector store (e.g., 'qdrant', 'chroma')",
description="Provider of the vector store (e.g., 'qdrant', 'chroma', 'upstash_vector')",
default="qdrant",
)
config: Optional[Dict] = Field(description="Configuration for the specific vector store", default=None)
Expand All @@ -15,6 +15,7 @@ class VectorStoreConfig(BaseModel):
"chroma": "ChromaDbConfig",
"pgvector": "PGVectorConfig",
"milvus": "MilvusDBConfig",
"upstash_vector": "UpstashVectorConfig",
}

@model_validator(mode="after")
Expand Down
Loading