Skip to content

Commit 9ae23f9

Browse files
authored
Add Faiss Support (#2461)
1 parent cbecbb7 commit 9ae23f9

File tree

9 files changed

+893
-2
lines changed

9 files changed

+893
-2
lines changed

Makefile

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ install:
1313
install_all:
1414
poetry install
1515
poetry run pip install groq together boto3 litellm ollama chromadb weaviate weaviate-client sentence_transformers vertexai \
16-
google-generativeai elasticsearch opensearch-py vecs pinecone pinecone-text
16+
google-generativeai elasticsearch opensearch-py vecs pinecone pinecone-text faiss-cpu
1717

1818
# Format code with ruff
1919
format:
+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
[FAISS](https://github.com/facebookresearch/faiss) is a library for efficient similarity search and clustering of dense vectors. It is designed to work with large-scale datasets and provides a high-performance search engine for vector data. FAISS is optimized for memory usage and search speed, making it an excellent choice for production environments.
2+
3+
### Usage
4+
5+
```python
6+
import os
7+
from mem0 import Memory
8+
9+
os.environ["OPENAI_API_KEY"] = "sk-xx"
10+
11+
config = {
12+
"vector_store": {
13+
"provider": "faiss",
14+
"config": {
15+
"collection_name": "test",
16+
"path": "/tmp/faiss_memories",
17+
"distance_strategy": "euclidean"
18+
}
19+
}
20+
}
21+
22+
m = Memory.from_config(config)
23+
messages = [
24+
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
25+
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
26+
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
27+
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
28+
]
29+
m.add(messages, user_id="alice", metadata={"category": "movies"})
30+
```
31+
32+
### Installation
33+
34+
To use FAISS in your mem0 project, you need to install the appropriate FAISS package for your environment:
35+
36+
```bash
37+
# For CPU version
38+
pip install faiss-cpu
39+
40+
# For GPU version (requires CUDA)
41+
pip install faiss-gpu
42+
```
43+
44+
### Config
45+
46+
Here are the parameters available for configuring FAISS:
47+
48+
| Parameter | Description | Default Value |
49+
| --- | --- | --- |
50+
| `collection_name` | The name of the collection | `mem0` |
51+
| `path` | Path to store FAISS index and metadata | `/tmp/faiss/<collection_name>` |
52+
| `distance_strategy` | Distance metric strategy to use (options: 'euclidean', 'inner_product', 'cosine') | `euclidean` |
53+
| `normalize_L2` | Whether to normalize L2 vectors (only applicable for euclidean distance) | `False` |
54+
55+
### Performance Considerations
56+
57+
FAISS offers several advantages for vector search:
58+
59+
1. **Efficiency**: FAISS is optimized for memory usage and speed, making it suitable for large-scale applications.
60+
2. **Offline Support**: FAISS works entirely locally, with no need for external servers or API calls.
61+
3. **Storage Options**: Vectors can be stored in-memory for maximum speed or persisted to disk.
62+
4. **Multiple Index Types**: FAISS supports different index types optimized for various use cases (though mem0 currently uses the basic flat index).
63+
64+
### Distance Strategies
65+
66+
FAISS in mem0 supports three distance strategies:
67+
68+
- **euclidean**: L2 distance, suitable for most embedding models
69+
- **inner_product**: Dot product similarity, useful for some specialized embeddings
70+
- **cosine**: Cosine similarity, best for comparing semantic similarity regardless of vector magnitude
71+
72+
When using `cosine` or `inner_product` with normalized vectors, you may want to set `normalize_L2=True` for better results.

docs/components/vectordbs/overview.mdx

+1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ See the list of supported vector databases below.
2727
<Card title="Supabase" href="/components/vectordbs/dbs/supabase"></Card>
2828
<Card title="Vertex AI Vector Search" href="/components/vectordbs/dbs/vertex_ai_vector_search"></Card>
2929
<Card title="Weaviate" href="/components/vectordbs/dbs/weaviate"></Card>
30+
<Card title="FAISS" href="/components/vectordbs/dbs/faiss"></Card>
3031
</CardGroup>
3132

3233
## Usage

mem0/configs/vector_stores/faiss.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from typing import Any, Dict, Optional
2+
3+
from pydantic import BaseModel, Field, model_validator
4+
5+
6+
class FAISSConfig(BaseModel):
7+
collection_name: str = Field("mem0", description="Default name for the collection")
8+
path: Optional[str] = Field(None, description="Path to store FAISS index and metadata")
9+
distance_strategy: str = Field(
10+
"euclidean", description="Distance strategy to use. Options: 'euclidean', 'inner_product', 'cosine'"
11+
)
12+
normalize_L2: bool = Field(
13+
False, description="Whether to normalize L2 vectors (only applicable for euclidean distance)"
14+
)
15+
16+
@model_validator(mode="before")
17+
@classmethod
18+
def validate_distance_strategy(cls, values: Dict[str, Any]) -> Dict[str, Any]:
19+
distance_strategy = values.get("distance_strategy")
20+
if distance_strategy and distance_strategy not in ["euclidean", "inner_product", "cosine"]:
21+
raise ValueError("Invalid distance_strategy. Must be one of: 'euclidean', 'inner_product', 'cosine'")
22+
return values
23+
24+
@model_validator(mode="before")
25+
@classmethod
26+
def validate_extra_fields(cls, values: Dict[str, Any]) -> Dict[str, Any]:
27+
allowed_fields = set(cls.model_fields.keys())
28+
input_fields = set(values.keys())
29+
extra_fields = input_fields - allowed_fields
30+
if extra_fields:
31+
raise ValueError(
32+
f"Extra fields not allowed: {', '.join(extra_fields)}. Please input only the following fields: {', '.join(allowed_fields)}"
33+
)
34+
return values
35+
36+
model_config = {
37+
"arbitrary_types_allowed": True,
38+
}

mem0/utils/factory.py

+1
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ class VectorStoreFactory:
7676
"opensearch": "mem0.vector_stores.opensearch.OpenSearchDB",
7777
"supabase": "mem0.vector_stores.supabase.Supabase",
7878
"weaviate": "mem0.vector_stores.weaviate.Weaviate",
79+
"faiss": "mem0.vector_stores.faiss.FAISS",
7980
}
8081

8182
@classmethod

mem0/vector_stores/configs.py

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ class VectorStoreConfig(BaseModel):
2323
"opensearch": "OpenSearchConfig",
2424
"supabase": "SupabaseConfig",
2525
"weaviate": "WeaviateConfig",
26+
"faiss": "FAISSConfig",
2627
}
2728

2829
@model_validator(mode="after")

0 commit comments

Comments
 (0)