Describe and explain in detail how is main, NON-graph storage is organized in mem0
Assistant
In mem0, the main non-graph storage is organized using a combination of SQLite (or other relational databases) for recording memory history and vector stores for embedding and searching memories. Here's a detailed breakdown of how the main storage is designed and functions:
1. SQLite for Memory History
Purpose:
SQLite is used to track the history of memory operations (e.g., additions, updates, deletions). This ensures that every change to a memory is logged, providing an audit trail.
Key File:
storage.py
Schema:
The SQLite database has a table called history with the following schema:
id (TEXT): Unique identifier for the history entry.
memory_id (TEXT): Identifier for the memory this history entry is associated with.
old_memory (TEXT): The previous value of the memory (if applicable).
new_memory (TEXT): The new value of the memory (if applicable).
new_value (TEXT): Additional value for the memory (e.g., embeddings).
event (TEXT): The type of event (e.g., ADD, UPDATE, DELETE).
created_at (DATETIME): Timestamp when the history entry was created.
updated_at (DATETIME): Timestamp when the history entry was last updated.
is_deleted (INTEGER): Flag indicating whether the memory has been deleted (1 for deleted, 0 otherwise).
Functionality:
Migration: The _migrate_history_table function ensures that the history table schema is always up-to-date. If the schema changes, it renames the existing table, creates a new one, and migrates the old data.
Add History: The add_history method inserts a new record into the history table whenever a memory is added, updated, or deleted.
Retrieve History: The method retrieves the history of changes for a specific .
User
Is it possible to re-implement the storage model in the way that uses vector storage, but the custom one built upon SQLite (so vector embeddings are stored in SQLite database) without reducing the accuracy of the search?
Assistant
User
Please try now to fully implement this using either Python or Rust with interfaces to Python; optionally, you can try to use C, but the main environment where this will be used is Python so it is recommended to use Python for full, detailed production-ready implementation
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Reset: The reset method allows dropping and recreating the history table, clearing all stored history data.
2. Vector Store for Memory Embeddings
Purpose:
The vector store is used to store embeddings (numerical representations) of memories, which enable efficient similarity searches. This storage layer powers the retrieval of memories based on their semantic similarity to a query.
Key Components:
Memory Embeddings: Represent memories as vectorized data.
Metadata: Additional information (e.g., user_id, agent_id, run_id) is stored alongside embeddings to allow filtering and retrieval.
Vector Search: Supports similarity-based searches using embeddings.
Interaction:
The vector store is abstracted through the VectorStoreFactory, which allows mem0 to support different vector database providers (e.g., Pinecone, Weaviate, or in-memory implementations). The specific provider is configurable via the MemoryConfig.
3. Data Flow and Organization
Memory Operations:
The main memory-related operations are implemented in the main.py file, where the Memory class integrates SQLite and the vector store:
Adding New Memory:
Input: A user provides unstructured text (e.g., "I love playing tennis on weekends").
Fact Extraction:
The text is processed using an LLM to extract facts (concise, structured information).
Example: "Likes playing tennis on weekends."
Embedding:
The extracted facts are converted into vector embeddings using the configured embedding model (e.g., OpenAI embeddings).
Storage:
SQLite: A new history entry is created with the ADD event.
Vector Store: The embeddings are stored with metadata (e.g., user_id, agent_id).
Updating Memory:
The existing memory is retrieved from the vector store.
The new data is embedded, and the vector store is updated.
A history entry is added in SQLite with the UPDATE event, recording the old and new values.
Retrieving Memories:
Query Processing:
Input queries are embedded using the same embedding model.
Example: "What are my hobbies?" → Embedding vector.
Vector Search:
The vector store performs a similarity search to find relevant memories.
Filters (e.g., user_id, agent_id) can narrow the search scope.
Results are returned as a list of memory items, including their metadata.
Deleting Memory:
The memory is deleted from the vector store.
A history entry with the DELETE event is added in SQLite.
Viewing History:
The history method retrieves all changes for a specific memory from SQLite.
4. Hybrid Approach
Mem0's design combines the strengths of both relational databases and vector stores:
Relational Database (SQLite):
Tracks memory changes (auditing and debugging).
Provides a structured history of memory operations.
Vector Store:
Enables efficient similarity-based searches.
Stores embeddings and metadata for retrieval.
This hybrid design ensures both operational transparency and high-performance memory retrieval.
The vector store allows efficient storage and retrieval of high-dimensional data, making it scalable for large datasets.
Traceability:
SQLite provides a complete history of memory changes, making debugging and auditing easier.
Personalization:
Metadata allows memories to be filtered and retrieved based on user or session identifiers.
Performance:
The hybrid approach ensures that both relational and similarity-based queries are optimized.
Flexibility:
The modular design supports different vector store backends and embedding models.
7. Conclusion
The main non-graph storage in mem0 is a hybrid system that leverages SQLite for memory history and vector stores for embeddings and similarity searches. Together, they provide a robust, efficient, and flexible memory storage solution tailored for personalized AI applications.
Yes, it is possible to re-implement the storage model using a custom vector storage built on SQLite without reducing the accuracy of the search. SQLite, while primarily a relational database, can be extended to support vector-based operations with efficient similarity search capabilities. This approach requires leveraging SQLite's custom extensions or user-defined functions, combined with optimizations for handling high-dimensional data.
Below are details on how this can be achieved:
1. Storing Vector Embeddings in SQLite
SQLite can store vector embeddings as arrays inside a table. A schema for storing embeddings might look like this:
Example Schema:
sql
CREATE TABLE vectors (
id TEXT PRIMARY KEY, -- Unique identifier for each vector
embedding BLOB NOT NULL, -- Vector embedding stored as a binary blob
metadata TEXT, -- Optional metadata stored as JSON
user_id TEXT, -- User identifier for filtering
created_at DATETIME -- Timestamp for recency filtering
);
Conversion of Embeddings:
Python to SQLite: Convert vector embeddings (typically numpy arrays) into binary blobs before storing them.
SQLite to Python: Convert binary blobs back to numpy arrays during retrieval.
python
def fetch_vector(cursor, id):
cursor.execute("SELECT embedding FROM vectors WHERE id = ?", (id,))
row = cursor.fetchone()
return np.frombuffer(row[0], dtype=np.float32)
2. Performing Similarity Search in SQLite
The accuracy of a search depends on the ability to compute the similarity between vectors efficiently. For this, we can extend SQLite to perform vector similarity calculations like cosine similarity or Euclidean distance.
Approaches for Vector Similarity Search:
Custom SQLite Extensions:
Use the SQLite C API to create a custom extension that computes similarity metrics (e.g., cosine similarity, dot product) directly in SQL.
Example: Implement a function cosine_similarity() in C or Python (with tools like sqlite3-pysqlite).
Example SQL Query:
sql
SELECT id, metadata, cosine_similarity(embedding, ?) AS similarity
FROM vectors
WHERE user_id = ?
ORDER BY similarity DESC
LIMIT 5;
In this query, the cosine_similarity(embedding, ?) function computes the similarity between a stored embedding and a query embedding.
Using SQLite's Virtual Tables:
SQLite supports virtual tables, which allow you to build custom table-like structures with specialized indexing or functionality. This is ideal for vector search.
Implement Approximate Nearest Neighbor (ANN) search using specialized indexes (e.g., KD-Trees or HNSW).
Store embeddings as arrays and use ANN algorithms for similarity search.
Example with SQLite VSS (Vector Similarity Search extension):
sql
CREATE VIRTUAL TABLE vectors USING vss(cosine(embedding(128)));
Query:
sql
SELECT id, metadata
FROM vectors
WHERE vss_search(embedding, ?, 5); -- Search for top 5 similar vectors
Precomputing and Indexing for Optimization:
Precompute norms or distances (e.g., L2 norm) and store them in separate columns for faster retrieval.
Use SQLite's indexing features to filter candidates before performing similarity calculations.
Example:
sql
CREATE INDEX idx_user_id ON vectors(user_id);
3. Maintaining Search Accuracy
Challenges:
High-Dimensional Data:
SQLite is not optimized for high-dimensional vector math by default, so performance might degrade for very large datasets or vectors with high dimensions (e.g., >512).
ANN vs. Exact Search:
ANN (Approximate Nearest Neighbor) methods, often used in dedicated vector databases like Pinecone or Weaviate, sacrifice a small amount of accuracy for faster results.
Solutions:
Exact Search:
Use brute-force similarity computation for small-to-medium datasets (e.g., <100k vectors). This ensures full accuracy by comparing the query vector with all stored vectors.
Example:
sql
SELECT id, metadata, cosine_similarity(embedding, ?) AS similarity
FROM vectors
ORDER BY similarity DESC
LIMIT 10;
Hybrid Exact + ANN:
Implement a hybrid approach where:
An ANN index narrows down candidates (e.g., top 50).
Exact similarity is computed on these candidates for the final results.
Dimensionality Reduction:
Reduce vector dimensions using techniques like PCA or SVD before storing embeddings. This can improve search performance while preserving accuracy.
Batch Preprocessing:
Precompute pairwise distances or similarity scores for frequently queried vectors and cache them in SQLite.
4. Scalability and Performance
To ensure scalability while maintaining accuracy:
Sharding:
Divide the dataset into smaller, isolated databases based on user IDs, domains, etc.
Caching:
Cache frequently retrieved results in memory to reduce SQLite query overhead.
Hybrid Storage:
Use SQLite for metadata and small datasets, and offload large-scale vector operations to a more specialized vector database when necessary.
5. Conclusion
Re-implementing mem0's vector storage using SQLite is absolutely feasible without sacrificing accuracy, provided the following are addressed:
Efficient similarity search: Achieved with custom extensions or virtual tables.
Optimized storage: Embeddings stored as binary blobs or arrays.
Scalability: Managed via sharding, caching, or hybrid approaches.
This solution is ideal for developers who prefer the simplicity of SQLite while retaining the power of semantic search.
Below is a production-ready Python implementation of a custom vector store built on SQLite for storing and searching vector embeddings. This implementation ensures compatibility with Python-based environments and provides robust, efficient, and accurate vector similarity search functionality. It also supports cosine similarity computations directly within SQLite.
Step 1: Install Dependencies
We'll use sqlite3 (built into Python) and numpy for handling vectors.
bash
pip install numpy
Step 2: Design the Vector Store
The vector store is implemented using SQLite for storage and custom Python functions for similarity computation. Embeddings are stored as binary blobs in the SQLite database.
Code Implementation
python
import sqlite3
import numpy as np
from typing import List, Tuple, Optional
class SQLiteVectorStore:
def __init__(self, db_path: str, vector_dim: int):
"""
Initialize the SQLite vector store.
Args:
db_path (str): Path to the SQLite database file.
vector_dim (int): Dimensionality of the vector embeddings.
"""
self.db_path = db_path
self.vector_dim = vector_dim
self._connect()
self._create_table()
def _connect(self):
"""Establish a connection to the SQLite database."""
self.conn = sqlite3.connect(self.db_path, check_same_thread=False)
self.conn.create_function("cosine_similarity", 2, self._cosine_similarity)
def _create_table(self):
"""Create the table for storing vectors."""
create_table_query = """
CREATE TABLE IF NOT EXISTS vectors (
id TEXT PRIMARY KEY,
embedding BLOB NOT NULL,
metadata TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
"""
self.conn.execute(create_table_query)
self.conn.commit()
def _cosine_similarity(self, vec1_blob: bytes, vec2_blob: bytes) -> float:
"""
Compute the cosine similarity between two vectors stored as binary blobs.
Args:
vec1_blob (bytes): Binary blob of the first vector.
vec2_blob (bytes): Binary blob of the second vector.
Returns:
float: Cosine similarity score.
"""
vec1 = np.frombuffer(vec1_blob, dtype=np.float32)
vec2 = np.frombuffer(vec2_blob, dtype=np.float32)
norm1 = np.linalg.norm(vec1)
norm2 = np.linalg.norm(vec2)
if norm1 == 0 or norm2 == 0:
return 0.0
return float(np.dot(vec1, vec2) / (norm1 * norm2))
def insert(self, vector_id: str, embedding: np.ndarray, metadata: Optional[dict] = None):
"""
Insert a new vector into the store.
Args:
vector_id (str): Unique identifier for the vector.
embedding (np.ndarray): Vector embedding to store.
metadata (dict, optional): Additional metadata to store with the vector.
"""
if embedding.shape[0] != self.vector_dim:
raise ValueError(f"Embedding must have dimension {self.vector_dim}, got {embedding.shape[0]}")
embedding_blob = embedding.astype(np.float32).tobytes()
metadata_json = json.dumps(metadata) if metadata else None
insert_query = """
INSERT INTO vectors (id, embedding, metadata)
VALUES (?, ?, ?);
"""
self.conn.execute(insert_query, (vector_id, embedding_blob, metadata_json))
self.conn.commit()
def search(self, query_embedding: np.ndarray, top_k: int = 5) -> List[Tuple[str, float, Optional[dict]]]:
"""
Search for the top-k most similar vectors to the query embedding.
Args:
query_embedding (np.ndarray): Query vector embedding.
top_k (int): Number of top results to return.
Returns:
List[Tuple[str, float, Optional[dict]]]: List of (vector_id, similarity_score, metadata).
"""
if query_embedding.shape[0] != self.vector_dim:
raise ValueError(f"Query embedding must have dimension {self.vector_dim}, got {query_embedding.shape[0]}")
query_blob = query_embedding.astype(np.float32).tobytes()
search_query = f"""
SELECT id, cosine_similarity(embedding, ?) AS similarity, metadata
FROM vectors
ORDER BY similarity DESC
LIMIT {top_k};
"""
results = self.conn.execute(search_query, (query_blob,)).fetchall()
return [(row[0], row[1], json.loads(row[2]) if row[2] else None) for row in results]
def delete(self, vector_id: str):
"""
Delete a vector from the store.
Args:
vector_id (str): ID of the vector to delete.
"""
delete_query = "DELETE FROM vectors WHERE id = ?;"
self.conn.execute(delete_query, (vector_id,))
self.conn.commit()
def update(self, vector_id: str, embedding: Optional[np.ndarray] = None, metadata: Optional[dict] = None):
"""
Update a vector's embedding or metadata.
Args:
vector_id (str): Unique identifier for the vector to update.
embedding (np.ndarray, optional): New embedding to update.
metadata (dict, optional): New metadata to update.
"""
update_query = "UPDATE vectors SET "
params = []
if embedding is not None:
if embedding.shape[0] != self.vector_dim:
raise ValueError(f"Embedding must have dimension {self.vector_dim}, got {embedding.shape[0]}")
update_query += "embedding = ?, "
params.append(embedding.astype(np.float32).tobytes())
if metadata is not None:
update_query += "metadata = ?, "
params.append(json.dumps(metadata))
update_query = update_query.rstrip(", ")
update_query += " WHERE id = ?;"
params.append(vector_id)
self.conn.execute(update_query, tuple(params))
self.conn.commit()
def close(self):
"""Close the SQLite connection."""
self.conn.close()
# Example Usage
if __name__ == "__main__":
import json
# Initialize vector store
vector_store = SQLiteVectorStore(db_path="vectors.db", vector_dim=128)
# Insert vectors
vector_store.insert("vec1", np.random.rand(128), {"user_id": "user1", "category": "sports"})
vector_store.insert("vec2", np.random.rand(128), {"user_id": "user2", "category": "music"})
# Search for similar vectors
query = np.random.rand(128)
results = vector_store.search(query, top_k=3)
print("Search Results:", results)
# Update a vector
vector_store.update("vec1", metadata={"user_id": "user1", "category": "updated_sports"})
# Delete a vector
vector_store.delete("vec2")
# Close the connection
vector_store.close()
Explanation
Storage of Embeddings:
Embeddings are stored as binary blobs in the embedding column.
Metadata is stored as JSON text in the metadata column.
Cosine Similarity Function:
A custom SQLite function, cosine_similarity, computes the similarity between stored embeddings and a query embedding.
Search Workflow:
The query embedding is converted to a binary blob.
SQLite computes cosine similarity for each stored embedding and orders the results by similarity.
Operations:
Insert: Adds new embeddings with metadata.
Search: Retrieves the top-k similar embeddings.
Update: Updates embeddings or metadata.
Delete: Removes embeddings by ID.
Advantages
Accuracy: Exact cosine similarity ensures no reduction in search accuracy.