Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

feat: add PgVectorStorage implementation for PostgreSQL with pgvector support (#2727)

Lei Zhangaab1fa15a6e2
diff --git a/camel/storages/__init__.py b/camel/storages/__init__.py
index 1513f672e..56f5b70be 100644
--- a/camel/storages/__init__.py
+++ b/camel/storages/__init__.py
@@ -30,6 +30,7 @@ from .vectordb_storages.chroma import ChromaStorage
from .vectordb_storages.faiss import FaissStorage
from .vectordb_storages.milvus import MilvusStorage
from .vectordb_storages.oceanbase import OceanBaseStorage
+from .vectordb_storages.pgvector import PgVectorStorage
from .vectordb_storages.qdrant import QdrantStorage
from .vectordb_storages.tidb import TiDBStorage
from .vectordb_storages.weaviate import WeaviateStorage
@@ -53,5 +54,6 @@ __all__ = [
'Mem0Storage',
'OceanBaseStorage',
'WeaviateStorage',
+ 'PgVectorStorage',
'ChromaStorage',
]
diff --git a/camel/storages/vectordb_storages/__init__.py b/camel/storages/vectordb_storages/__init__.py
index 87bfc278e..b01135580 100644
--- a/camel/storages/vectordb_storages/__init__.py
+++ b/camel/storages/vectordb_storages/__init__.py
@@ -23,6 +23,7 @@ from .chroma import ChromaStorage
from .faiss import FaissStorage
from .milvus import MilvusStorage
from .oceanbase import OceanBaseStorage
+from .pgvector import PgVectorStorage
from .qdrant import QdrantStorage
from .tidb import TiDBStorage
from .weaviate import WeaviateStorage
@@ -40,4 +41,5 @@ __all__ = [
'WeaviateStorage',
'VectorRecord',
'VectorDBStatus',
+ 'PgVectorStorage',
]
diff --git a/camel/storages/vectordb_storages/pgvector.py b/camel/storages/vectordb_storages/pgvector.py
new file mode 100644
index 000000000..7e5f0736d
--- /dev/null
+++ b/camel/storages/vectordb_storages/pgvector.py
@@ -0,0 +1,349 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+
+import json
+from typing import Any, Dict, List, Optional
+
+from camel.logger import get_logger
+from camel.storages.vectordb_storages import (
+ BaseVectorStorage,
+ VectorDBQuery,
+ VectorDBQueryResult,
+ VectorDBStatus,
+ VectorRecord,
+)
+from camel.types import VectorDistance
+from camel.utils import dependencies_required
+
+logger = get_logger(__name__)
+
+
+class PgVectorStorage(BaseVectorStorage):
+ r"""PgVectorStorage is an implementation of BaseVectorStorage for
+ PostgreSQL with pgvector extension.
+
+ This class provides methods to add, delete, query, and manage vector
+ records in a PostgreSQL database using the pgvector extension.
+ It supports different distance metrics for similarity search.
+
+ Args:
+ vector_dim (int): The dimension of the vectors to be stored.
+ conn_info (Dict[str, Any]): Connection information for
+ psycopg2.connect.
+ table_name (str, optional): Name of the table to store vectors.
+ (default: :obj:`None`)
+ distance (VectorDistance, optional): Distance metric for vector
+ comparison. (default: :obj:`VectorDistance.COSINE`)
+ """
+
+ @dependencies_required('psycopg', 'pgvector')
+ def __init__(
+ self,
+ vector_dim: int,
+ conn_info: Dict[str, Any],
+ table_name: Optional[str] = None,
+ distance: VectorDistance = VectorDistance.COSINE,
+ **kwargs: Any,
+ ) -> None:
+ r"""Initialize PgVectorStorage.
+
+ Args:
+ vector_dim (int): The dimension of the vectors.
+ conn_info (Dict[str, Any]): Connection info for psycopg2.connect.
+ table_name (str, optional): Table name. (default: :obj:`None`)
+ distance (VectorDistance, optional): Distance metric.
+ (default: :obj:`VectorDistance.COSINE`)
+ """
+ import psycopg
+ from pgvector.psycopg import register_vector
+
+ if vector_dim <= 0:
+ raise ValueError("vector_dim must be positive")
+
+ self.vector_dim = vector_dim
+ self.conn_info = conn_info
+ self.table_name = table_name or 'vectors'
+ self.distance = distance
+
+ try:
+ self._conn = psycopg.connect(**conn_info)
+ register_vector(self._conn)
+ self._ensure_table()
+ self._ensure_index()
+ except Exception as e:
+ logger.error(f"Failed to initialize PgVectorStorage: {e}")
+ raise
+
+ def _ensure_table(self) -> None:
+ r"""Ensure the vector table exists in the database.
+ Creates the table if it does not exist.
+ """
+ try:
+ from psycopg.sql import SQL, Identifier, Literal
+
+ with self._conn.cursor() as cur:
+ query = SQL("""
+ CREATE TABLE IF NOT EXISTS {table} (
+ id VARCHAR PRIMARY KEY,
+ vector vector({dim}),
+ payload JSONB
+ )
+ """).format(
+ table=Identifier(self.table_name),
+ dim=Literal(self.vector_dim),
+ )
+ cur.execute(query)
+ self._conn.commit()
+ except Exception as e:
+ logger.error(f"Failed to create table {self.table_name}: {e}")
+ raise
+
+ def _ensure_index(self) -> None:
+ r"""Ensure vector similarity search index exists for better
+ performance.
+ """
+ try:
+ from psycopg.sql import SQL, Identifier
+
+ with self._conn.cursor() as cur:
+ index_name = f"{self.table_name}_vector_idx"
+ query = SQL("""
+ CREATE INDEX IF NOT EXISTS {index_name}
+ ON {table}
+ USING hnsw (vector vector_cosine_ops)
+ """).format(
+ index_name=Identifier(index_name),
+ table=Identifier(self.table_name),
+ )
+ cur.execute(query)
+ self._conn.commit()
+ except Exception as e:
+ logger.warning(f"Failed to create vector index: {e}")
+
+ def add(self, records: List[VectorRecord], **kwargs: Any) -> None:
+ r"""Add or update vector records in the database.
+
+ Args:
+ records (List[VectorRecord]): List of vector records to
+ add or update.
+ """
+ if not records:
+ return
+
+ try:
+ with self._conn.cursor() as cur:
+ # Use batch insert for better performance
+ batch_data = []
+ for rec in records:
+ if len(rec.vector) != self.vector_dim:
+ raise ValueError(
+ f"Vector dimension mismatch: expected "
+ f"{self.vector_dim}, got {len(rec.vector)}"
+ )
+
+ batch_data.append(
+ (
+ rec.id,
+ rec.vector,
+ json.dumps(rec.payload)
+ if rec.payload is not None
+ else None,
+ )
+ )
+
+ # Use executemany for efficient batch insert
+ from psycopg.sql import SQL, Identifier
+
+ query = SQL("""
+ INSERT INTO {table} (id, vector, payload)
+ VALUES (%s, %s, %s)
+ ON CONFLICT (id) DO UPDATE SET
+ vector=EXCLUDED.vector,
+ payload=EXCLUDED.payload
+ """).format(table=Identifier(self.table_name))
+
+ cur.executemany(query, batch_data)
+ self._conn.commit()
+ except Exception as e:
+ self._conn.rollback()
+ logger.error(f"Failed to add records: {e}")
+ raise
+
+ def delete(self, ids: List[str], **kwargs: Any) -> None:
+ r"""Delete vector records from the database by their IDs.
+
+ Args:
+ ids (List[str]): List of record IDs to delete.
+ """
+ from psycopg.sql import SQL, Identifier
+
+ if not ids:
+ return
+
+ try:
+ with self._conn.cursor() as cur:
+ query = SQL("DELETE FROM {table} WHERE id = ANY(%s)").format(
+ table=Identifier(self.table_name)
+ )
+ cur.execute(query, (ids,))
+ self._conn.commit()
+ except Exception as e:
+ self._conn.rollback()
+ logger.error(f"Failed to delete records: {e}")
+ raise
+
+ def query(
+ self, query: VectorDBQuery, **kwargs: Any
+ ) -> List[VectorDBQueryResult]:
+ r"""Query the database for the most similar vectors to the given
+ query vector.
+
+ Args:
+ query (VectorDBQuery): Query object containing the query
+ vector and top_k.
+ **kwargs (Any): Additional keyword arguments for the query.
+
+ Returns:
+ List[VectorDBQueryResult]: List of query results sorted by
+ similarity.
+ """
+ if len(query.query_vector) != self.vector_dim:
+ raise ValueError(
+ f"Query vector dimension mismatch: "
+ f"expected {self.vector_dim}, got {len(query.query_vector)}"
+ )
+
+ try:
+ with self._conn.cursor() as cur:
+ # Fix distance metric mapping
+ metric_info = {
+ VectorDistance.COSINE: ('<=>', 'ASC'), # Cosine distance
+ VectorDistance.EUCLIDEAN: (
+ '<->',
+ 'ASC',
+ ), # Euclidean distance
+ VectorDistance.DOT: (
+ '<#>',
+ 'DESC',
+ ), # Negative dot product (higher is better)
+ }
+
+ if self.distance not in metric_info:
+ raise ValueError(
+ f"Unsupported distance metric: {self.distance}"
+ )
+
+ metric, order = metric_info[self.distance]
+
+ from psycopg.sql import SQL, Identifier, Literal
+
+ query_sql = SQL("""
+ SELECT id, vector, payload, (vector {} %s::vector)
+ AS similarity
+ FROM {}
+ ORDER BY similarity {}
+ LIMIT %s
+ """).format(
+ Literal(metric),
+ Identifier(self.table_name),
+ Literal(order),
+ )
+
+ cur.execute(query_sql, (query.query_vector, query.top_k))
+ results = []
+ for row in cur.fetchall():
+ id, vector, payload, similarity = row
+ results.append(
+ VectorDBQueryResult.create(
+ similarity=float(similarity),
+ vector=list(vector),
+ id=id,
+ payload=payload,
+ )
+ )
+ return results
+ except Exception as e:
+ logger.error(f"Failed to query vectors: {e}")
+ raise
+
+ def status(self, **kwargs: Any) -> VectorDBStatus:
+ r"""Get the status of the vector database, including vector
+ dimension and count.
+
+ Args:
+ **kwargs (Any): Additional keyword arguments for the query.
+
+ Returns:
+ VectorDBStatus: Status object with vector dimension and count.
+ """
+ try:
+ with self._conn.cursor() as cur:
+ from psycopg.sql import SQL, Identifier
+
+ query = SQL('SELECT COUNT(*) FROM {}').format(
+ Identifier(self.table_name)
+ )
+ cur.execute(query)
+ result = cur.fetchone()
+ count = result[0] if result else 0
+ return VectorDBStatus(
+ vector_dim=self.vector_dim, vector_count=count
+ )
+ except Exception as e:
+ logger.error(f"Failed to get status: {e}")
+ raise
+
+ def clear(self) -> None:
+ r"""Remove all vectors from the storage by truncating the table."""
+ try:
+ with self._conn.cursor() as cur:
+ from psycopg.sql import SQL, Identifier
+
+ query = SQL("TRUNCATE TABLE {table}").format(
+ table=Identifier(self.table_name)
+ )
+ cur.execute(query)
+ self._conn.commit()
+ except Exception as e:
+ self._conn.rollback()
+ logger.error(f"Failed to clear table: {e}")
+ raise
+
+ def load(self) -> None:
+ r"""Load the collection hosted on cloud service (no-op for pgvector).
+ This method is provided for interface compatibility.
+ """
+ # For PostgreSQL local/managed instances, no loading is required
+ pass
+
+ def close(self) -> None:
+ r"""Close the database connection."""
+ if hasattr(self, '_conn') and self._conn:
+ try:
+ self._conn.close()
+ except Exception as e:
+ logger.warning(f"Error closing connection: {e}")
+
+ def __del__(self) -> None:
+ r"""Ensure connection is closed when object is destroyed."""
+ self.close()
+
+ @property
+ def client(self) -> Any:
+ r"""Provides access to the underlying vector database client.
+
+ Returns:
+ Any: The underlying psycopg connection object.
+ """
+ return self._conn
diff --git a/docs/get_started/installation.md b/docs/get_started/installation.md
index 775c5eb0d..1f2120c8b 100644
--- a/docs/get_started/installation.md
+++ b/docs/get_started/installation.md
@@ -47,7 +47,7 @@ CAMEL-AI supports multiple installation methods to suit different development wo
- `model_platforms`: OpenAI, Google, Mistral, Anthropic Claude, Cohere etc.
- `huggingface`: Transformers, Diffusers, Accelerate, Datasets, PyTorch etc.
- `rag`: Sentence Transformers, Qdrant, Milvus, TiDB, BM25, OceanBase, Weaviate, chroma etc.
- - `storage`: Neo4j, Redis, Azure Blob, Google Cloud Storage, AWS S3 etc.
+ - `storage`: Neo4j, Redis, Azure Blob, Google Cloud Storage, AWS S3 etc, Pgvector.
- `web_tools`: DuckDuckGo, Wikipedia, WolframAlpha, Google Maps, Weather API etc.
- `document_tools`: PDF, Word, OpenAPI, BeautifulSoup, Unstructured etc.
- `media_tools`: Image Processing, Audio Processing, YouTube Download, FFmpeg etc.
diff --git a/docs/key_modules/storages.md b/docs/key_modules/storages.md
index 35514a398..9ea733749 100644
--- a/docs/key_modules/storages.md
+++ b/docs/key_modules/storages.md
@@ -63,6 +63,10 @@ The <b>Storage</b> module in CAMEL-AI gives you a **unified interface for saving
**ChromaStorage**
- For [ChromaDB](https://www.trychroma.com/) (AI-native open-source embedding database)
- Simple API, scales from notebook to production
+
+ **PgVectorStorage**
+ - For [PostgreSQL with pgvector](https://github.com/pgvector/pgvector) (open-source vector engine)
+ - Leverages PostgreSQL for vector search
</Accordion>
<Accordion title="Graph Storages" icon="chart-waterfall">
diff --git a/examples/storages/pgvector_storage.py b/examples/storages/pgvector_storage.py
new file mode 100644
index 000000000..07b413732
--- /dev/null
+++ b/examples/storages/pgvector_storage.py
@@ -0,0 +1,111 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+
+import random
+
+from camel.storages.vectordb_storages import (
+ PgVectorStorage,
+ VectorDBQuery,
+ VectorRecord,
+)
+
+"""
+Before running this example, you need to setup a PostgreSQL instance with
+the pgvector extension:
+
+1. Install PostgreSQL and pgvector extension:
+ https://github.com/pgvector/pgvector#installation
+
+2. Create a database and enable the extension:
+ CREATE EXTENSION IF NOT EXISTS vector;
+
+3. Install required Python packages:
+ pip install psycopg[binary] pgvector psycopg-binary
+
+The connection parameters should include:
+- host
+- port
+- user
+- password
+- dbname
+"""
+
+# Replace these with your PostgreSQL connection parameters
+PG_CONN_INFO = {
+ "host": "127.0.0.1",
+ "port": 5432,
+ "user": "postgres",
+ "password": "postgres",
+ "dbname": "postgres",
+}
+
+
+def main():
+ # Create an instance of PgVectorStorage with dimension = 4
+ pg_storage = PgVectorStorage(
+ vector_dim=4,
+ conn_info=PG_CONN_INFO,
+ table_name="my_pgvector_table",
+ # distance can be omitted for default (cosine)
+ )
+
+ # Get database status
+ status = pg_storage.status()
+ print(f"Vector dimension: {status.vector_dim}")
+ print(f"Initial vector count: {status.vector_count}")
+
+ # Generate and add a larger number of vectors using batching
+ print("\nAdding vectors in batches...")
+ random.seed(20240624)
+
+ # Create a large batch of vector records
+ large_batch = []
+ for i in range(1000):
+ large_batch.append(
+ VectorRecord(
+ vector=[random.uniform(-1, 1) for _ in range(4)],
+ payload={'idx': i, 'batch': 'example'},
+ )
+ )
+
+ # Add vectors with automatic batching (batch_size=100)
+ pg_storage.add(large_batch)
+
+ # Check updated status
+ status = pg_storage.status()
+ print(f"Vector count after adding batch: {status.vector_count}")
+
+ # Generate a query vector and search for similar vectors
+ print("\nQuerying similar vectors...")
+ query_vector = [random.uniform(-1, 1) for _ in range(4)]
+ query_results = pg_storage.query(
+ VectorDBQuery(query_vector=query_vector, top_k=5)
+ )
+
+ # Display results
+ for i, result in enumerate(query_results):
+ print(f"Result {i+1}:")
+ print(f" ID: {result.record.id}")
+ print(f" Payload: {result.record.payload}")
+ print(f" Similarity: {result.similarity}")
+
+ # Clear all vectors when done
+ print("\nClearing vectors...")
+ pg_storage.clear()
+ status = pg_storage.status()
+ print(f"Vector count after clearing: {status.vector_count}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pyproject.toml b/pyproject.toml
index debf87adf..665060083 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -212,6 +212,8 @@ storage = [
"mem0ai>=0.1.73",
"pyobvector>=0.1.18",
"weaviate-client>=4.15.0",
+ "psycopg[binary]>=3.1.18,<4",
+ "pgvector>=0.2.4,<0.3",
"chromadb>=0.6.0,<1.0.0",
]
owl = [
@@ -384,6 +386,8 @@ all = [
"Flask>=2.0",
"rlcard>=1.0.0,<1.3.0",
"pytesseract>=0.3.13",
+ "psycopg[binary]>=3.1.18,<4",
+ "pgvector>=0.2.4,<0.3",
"chromadb>=0.6.0,<1.0.0",
]
@@ -582,6 +586,9 @@ module = [
"cv2",
"rlcard.*",
"pytesseract",
+ "psycopg.*",
+ "pgvecto.*",
+ "pgvector.*",
]
ignore_missing_imports = true
diff --git a/test/storages/vector_storages/test_pgvector.py b/test/storages/vector_storages/test_pgvector.py
new file mode 100644
index 000000000..e2ff0d28a
--- /dev/null
+++ b/test/storages/vector_storages/test_pgvector.py
@@ -0,0 +1,141 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from camel.storages import VectorDBQuery, VectorRecord
+from camel.storages.vectordb_storages.pgvector import PgVectorStorage
+from camel.types import VectorDistance
+
+
+def mock_pgvector_conn():
+ mock_conn = MagicMock()
+ mock_cursor = MagicMock()
+ mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
+ return mock_conn, mock_cursor
+
+
+@patch("psycopg.connect")
+@patch("pgvector.psycopg.register_vector")
+def test_pgvector_init(mock_register, mock_connect, mock_pgvector_conn):
+ mock_conn, _ = mock_pgvector_conn
+ mock_connect.return_value = mock_conn
+ storage = PgVectorStorage(
+ vector_dim=4,
+ conn_info={"host": "localhost"},
+ table_name="test_vectors",
+ distance=VectorDistance.COSINE,
+ )
+ assert storage.vector_dim == 4
+ assert storage.table_name == "test_vectors"
+ assert storage.distance == VectorDistance.COSINE
+ mock_register.assert_called_once()
+ mock_connect.assert_called_once()
+
+
+def test_pgvector_add(mock_pgvector_conn):
+ mock_conn, mock_cursor = mock_pgvector_conn
+ with (
+ patch("psycopg.connect", return_value=mock_conn),
+ patch("pgvector.psycopg.register_vector"),
+ ):
+ storage = PgVectorStorage(4, {"host": "localhost"})
+ mock_cursor.executemany.reset_mock()
+ records = [
+ VectorRecord(
+ id="1", vector=[0.1, 0.2, 0.3, 0.4], payload={"a": 1}
+ ),
+ VectorRecord(
+ id="2", vector=[0.5, 0.6, 0.7, 0.8], payload={"b": 2}
+ ),
+ ]
+ storage.add(records)
+ assert mock_cursor.executemany.call_count == 1
+ mock_conn.commit.assert_called()
+
+
+def test_pgvector_query(mock_pgvector_conn):
+ mock_conn, mock_cursor = mock_pgvector_conn
+ mock_cursor.fetchall.return_value = [
+ ("1", [0.1, 0.2, 0.3, 0.4], {"a": 1}, 0.01),
+ ]
+ with (
+ patch("psycopg.connect", return_value=mock_conn),
+ patch("pgvector.psycopg.register_vector"),
+ ):
+ storage = PgVectorStorage(4, {"host": "localhost"})
+ mock_cursor.execute.reset_mock()
+ query = VectorDBQuery(query_vector=[0.1, 0.2, 0.3, 0.4], top_k=1)
+ results = storage.query(query)
+ assert len(results) == 1
+ assert results[0].record.id == "1"
+ assert results[0].record.vector == [0.1, 0.2, 0.3, 0.4]
+ assert results[0].record.payload == {"a": 1}
+ assert results[0].similarity == 0.01
+
+
+def test_pgvector_delete(mock_pgvector_conn):
+ mock_conn, mock_cursor = mock_pgvector_conn
+ with (
+ patch("psycopg.connect", return_value=mock_conn),
+ patch("pgvector.psycopg.register_vector"),
+ ):
+ storage = PgVectorStorage(4, {"host": "localhost"})
+ mock_cursor.execute.reset_mock()
+ storage.delete(["1", "2"])
+ mock_cursor.execute.assert_called_once()
+ mock_conn.commit.assert_called()
+
+
+def test_pgvector_status(mock_pgvector_conn):
+ mock_conn, mock_cursor = mock_pgvector_conn
+ mock_cursor.fetchone.return_value = [5]
+ with (
+ patch("psycopg.connect", return_value=mock_conn),
+ patch("pgvector.psycopg.register_vector"),
+ ):
+ storage = PgVectorStorage(4, {"host": "localhost"})
+ mock_cursor.execute.reset_mock()
+ status = storage.status()
+ assert status.vector_dim == 4
+ assert status.vector_count == 5
+
+
+def test_pgvector_clear(mock_pgvector_conn):
+ mock_conn, mock_cursor = mock_pgvector_conn
+ with (
+ patch("psycopg.connect", return_value=mock_conn),
+ patch("pgvector.psycopg.register_vector"),
+ ):
+ storage = PgVectorStorage(4, {"host": "localhost"})
+ mock_cursor.execute.reset_mock()
+ storage.clear()
+ mock_cursor.execute.assert_called_once()
+ mock_conn.commit.assert_called()
+
+
+def test_pgvector_empty_add_delete(mock_pgvector_conn):
+ mock_conn, mock_cursor = mock_pgvector_conn
+ with (
+ patch("psycopg.connect", return_value=mock_conn),
+ patch("pgvector.psycopg.register_vector"),
+ ):
+ storage = PgVectorStorage(4, {"host": "localhost"})
+ mock_cursor.execute.reset_mock()
+ storage.add([])
+ storage.delete([])
+ # Should not call execute for empty add/delete
+ assert not mock_cursor.execute.called
diff --git a/uv.lock b/uv.lock
index e8bf9c461..e4e2d0281 100644
--- a/uv.lock
+++ b/uv.lock
@@ -716,10 +716,12 @@ all = [
{ name = "openpyxl" },
{ name = "pandas" },
{ name = "pandasai" },
+ { name = "pgvector" },
{ name = "playwright" },
{ name = "prance" },
{ name = "praw" },
{ name = "pre-commit" },
+ { name = "psycopg", extra = ["binary"] },
{ name = "pyautogui" },
{ name = "pydub" },
{ name = "pygithub" },
@@ -961,6 +963,8 @@ storage = [
{ name = "mem0ai" },
{ name = "nebula3-python" },
{ name = "neo4j" },
+ { name = "pgvector" },
+ { name = "psycopg", extra = ["binary"] },
{ name = "pymilvus" },
{ name = "pyobvector" },
{ name = "pytidb-experimental" },
@@ -1172,6 +1176,8 @@ requires-dist = [
{ name = "pandasai", marker = "extra == 'document-tools'", specifier = ">=2.3.0,<3" },
{ name = "pandasai", marker = "extra == 'owl'", specifier = ">=2.3.0,<3" },
{ name = "pandasai", marker = "extra == 'rag'", specifier = ">=2.3.0,<3" },
+ { name = "pgvector", marker = "extra == 'all'", specifier = ">=0.2.4,<0.3" },
+ { name = "pgvector", marker = "extra == 'storage'", specifier = ">=0.2.4,<0.3" },
{ name = "pillow", specifier = ">=10.1.0,<11.0.0" },
{ name = "playwright", marker = "extra == 'all'", specifier = ">=1.50.0" },
{ name = "playwright", marker = "extra == 'owl'", specifier = ">=1.50.0" },
@@ -1184,6 +1190,8 @@ requires-dist = [
{ name = "pre-commit", marker = "extra == 'all'", specifier = ">=3,<4" },
{ name = "pre-commit", marker = "extra == 'dev'", specifier = ">=3,<4" },
{ name = "psutil", specifier = ">=5.9.8,<6" },
+ { name = "psycopg", extras = ["binary"], marker = "extra == 'all'", specifier = ">=3.1.18,<4" },
+ { name = "psycopg", extras = ["binary"], marker = "extra == 'storage'", specifier = ">=3.1.18,<4" },
{ name = "pyautogui", marker = "extra == 'all'", specifier = ">=0.9.54,<0.10" },
{ name = "pyautogui", marker = "extra == 'owl'", specifier = ">=0.9.54,<0.10" },
{ name = "pydantic", specifier = ">=2.10.6" },
@@ -5150,6 +5158,17 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" },
]
+[[package]]
+name = "pgvector"
+version = "0.2.5"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/29/bb/4686b1090a7c68fa367e981130a074dc6c1236571d914ffa6e05c882b59d/pgvector-0.2.5-py2.py3-none-any.whl", hash = "sha256:5e5e93ec4d3c45ab1fa388729d56c602f6966296e19deee8878928c6d567e41b", size = 9638, upload-time = "2024-02-07T19:35:03.8Z" },
+]
+
[[package]]
name = "pillow"
version = "10.4.0"
@@ -5455,6 +5474,64 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/05/33/2d74d588408caedd065c2497bdb5ef83ce6082db01289a1e1147f6639802/psutil-5.9.8-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:d16bbddf0693323b8c6123dd804100241da461e41d6e332fb0ba6058f630f8c8", size = 249898, upload-time = "2024-01-19T20:47:59.238Z" },
]
+[[package]]
+name = "psycopg"
+version = "3.2.9"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions" },
+ { name = "tzdata", marker = "sys_platform == 'win32'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/27/4a/93a6ab570a8d1a4ad171a1f4256e205ce48d828781312c0bbaff36380ecb/psycopg-3.2.9.tar.gz", hash = "sha256:2fbb46fcd17bc81f993f28c47f1ebea38d66ae97cc2dbc3cad73b37cefbff700", size = 158122, upload-time = "2025-05-13T16:11:15.533Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/44/b0/a73c195a56eb6b92e937a5ca58521a5c3346fb233345adc80fd3e2f542e2/psycopg-3.2.9-py3-none-any.whl", hash = "sha256:01a8dadccdaac2123c916208c96e06631641c0566b22005493f09663c7a8d3b6", size = 202705, upload-time = "2025-05-13T16:06:26.584Z" },
+]
+
+[package.optional-dependencies]
+binary = [
+ { name = "psycopg-binary", marker = "implementation_name != 'pypy'" },
+]
+
+[[package]]
+name = "psycopg-binary"
+version = "3.2.9"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b6/ce/d677bc51f9b180986e5515268603519cee682eb6b5e765ae46cdb8526579/psycopg_binary-3.2.9-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:528239bbf55728ba0eacbd20632342867590273a9bacedac7538ebff890f1093", size = 4033081, upload-time = "2025-05-13T16:06:29.666Z" },
+ { url = "https://files.pythonhosted.org/packages/de/f4/b56263eb20dc36d71d7188622872098400536928edf86895736e28546b3c/psycopg_binary-3.2.9-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e4978c01ca4c208c9d6376bd585e2c0771986b76ff7ea518f6d2b51faece75e8", size = 4082141, upload-time = "2025-05-13T16:06:33.81Z" },
+ { url = "https://files.pythonhosted.org/packages/68/47/5316c3b0a2b1ff5f1d440a27638250569994534874a2ce88bf24f5c51c0f/psycopg_binary-3.2.9-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1ed2bab85b505d13e66a914d0f8cdfa9475c16d3491cf81394e0748b77729af2", size = 4678993, upload-time = "2025-05-13T16:06:36.309Z" },
+ { url = "https://files.pythonhosted.org/packages/53/24/b2c667b59f07fd7d7805c0c2074351bf2b98a336c5030d961db316512ffb/psycopg_binary-3.2.9-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:799fa1179ab8a58d1557a95df28b492874c8f4135101b55133ec9c55fc9ae9d7", size = 4500117, upload-time = "2025-05-13T16:06:38.847Z" },
+ { url = "https://files.pythonhosted.org/packages/ae/91/a08f8878b0fe0b34b083c149df950bce168bc1b18b2fe849fa42bf4378d4/psycopg_binary-3.2.9-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:bb37ac3955d19e4996c3534abfa4f23181333974963826db9e0f00731274b695", size = 4766985, upload-time = "2025-05-13T16:06:42.502Z" },
+ { url = "https://files.pythonhosted.org/packages/10/be/3a45d5b7d8f4c4332fd42465f2170b5aef4d28a7c79e79ac7e5e1dac74d7/psycopg_binary-3.2.9-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:001e986656f7e06c273dd4104e27f4b4e0614092e544d950c7c938d822b1a894", size = 4461990, upload-time = "2025-05-13T16:06:45.971Z" },
+ { url = "https://files.pythonhosted.org/packages/03/ce/20682b9a4fc270d8dc644a0b16c1978732146c6ff0abbc48fbab2f4a70aa/psycopg_binary-3.2.9-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:fa5c80d8b4cbf23f338db88a7251cef8bb4b68e0f91cf8b6ddfa93884fdbb0c1", size = 3777947, upload-time = "2025-05-13T16:06:49.134Z" },
+ { url = "https://files.pythonhosted.org/packages/07/5c/f6d486e00bcd8709908ccdd436b2a190d390dfd61e318de4060bc6ee2a1e/psycopg_binary-3.2.9-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:39a127e0cf9b55bd4734a8008adf3e01d1fd1cb36339c6a9e2b2cbb6007c50ee", size = 3337502, upload-time = "2025-05-13T16:06:51.378Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/a1/086508e929c0123a7f532840bb0a0c8a1ebd7e06aef3ee7fa44a3589bcdf/psycopg_binary-3.2.9-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:fb7599e436b586e265bea956751453ad32eb98be6a6e694252f4691c31b16edb", size = 3440809, upload-time = "2025-05-13T16:06:54.552Z" },
+ { url = "https://files.pythonhosted.org/packages/40/f2/3a347a0f894355a6b173fca2202eca279b6197727b24e4896cf83f4263ee/psycopg_binary-3.2.9-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5d2c9fe14fe42b3575a0b4e09b081713e83b762c8dc38a3771dd3265f8f110e7", size = 3497231, upload-time = "2025-05-13T16:06:58.858Z" },
+ { url = "https://files.pythonhosted.org/packages/18/31/0845a385eb6f4521b398793293b5f746a101e80d5c43792990442d26bc2e/psycopg_binary-3.2.9-cp310-cp310-win_amd64.whl", hash = "sha256:7e4660fad2807612bb200de7262c88773c3483e85d981324b3c647176e41fdc8", size = 2936845, upload-time = "2025-05-13T16:07:02.712Z" },
+ { url = "https://files.pythonhosted.org/packages/b6/84/259ea58aca48e03c3c793b4ccfe39ed63db7b8081ef784d039330d9eed96/psycopg_binary-3.2.9-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:2504e9fd94eabe545d20cddcc2ff0da86ee55d76329e1ab92ecfcc6c0a8156c4", size = 4040785, upload-time = "2025-05-13T16:07:07.569Z" },
+ { url = "https://files.pythonhosted.org/packages/25/22/ce58ffda2b7e36e45042b4d67f1bbd4dd2ccf4cfd2649696685c61046475/psycopg_binary-3.2.9-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:093a0c079dd6228a7f3c3d82b906b41964eaa062a9a8c19f45ab4984bf4e872b", size = 4087601, upload-time = "2025-05-13T16:07:11.75Z" },
+ { url = "https://files.pythonhosted.org/packages/c6/4f/b043e85268650c245025e80039b79663d8986f857bc3d3a72b1de67f3550/psycopg_binary-3.2.9-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:387c87b51d72442708e7a853e7e7642717e704d59571da2f3b29e748be58c78a", size = 4676524, upload-time = "2025-05-13T16:07:17.038Z" },
+ { url = "https://files.pythonhosted.org/packages/da/29/7afbfbd3740ea52fda488db190ef2ef2a9ff7379b85501a2142fb9f7dd56/psycopg_binary-3.2.9-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d9ac10a2ebe93a102a326415b330fff7512f01a9401406896e78a81d75d6eddc", size = 4495671, upload-time = "2025-05-13T16:07:21.709Z" },
+ { url = "https://files.pythonhosted.org/packages/ea/eb/df69112d18a938cbb74efa1573082248437fa663ba66baf2cdba8a95a2d0/psycopg_binary-3.2.9-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:72fdbda5b4c2a6a72320857ef503a6589f56d46821592d4377c8c8604810342b", size = 4768132, upload-time = "2025-05-13T16:07:25.818Z" },
+ { url = "https://files.pythonhosted.org/packages/76/fe/4803b20220c04f508f50afee9169268553f46d6eed99640a08c8c1e76409/psycopg_binary-3.2.9-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f34e88940833d46108f949fdc1fcfb74d6b5ae076550cd67ab59ef47555dba95", size = 4458394, upload-time = "2025-05-13T16:07:29.148Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/0f/5ecc64607ef6f62b04e610b7837b1a802ca6f7cb7211339f5d166d55f1dd/psycopg_binary-3.2.9-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:a3e0f89fe35cb03ff1646ab663dabf496477bab2a072315192dbaa6928862891", size = 3776879, upload-time = "2025-05-13T16:07:32.503Z" },
+ { url = "https://files.pythonhosted.org/packages/c8/d8/1c3d6e99b7db67946d0eac2cd15d10a79aa7b1e3222ce4aa8e7df72027f5/psycopg_binary-3.2.9-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:6afb3e62f2a3456f2180a4eef6b03177788df7ce938036ff7f09b696d418d186", size = 3333329, upload-time = "2025-05-13T16:07:35.555Z" },
+ { url = "https://files.pythonhosted.org/packages/d7/02/a4e82099816559f558ccaf2b6945097973624dc58d5d1c91eb1e54e5a8e9/psycopg_binary-3.2.9-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:cc19ed5c7afca3f6b298bfc35a6baa27adb2019670d15c32d0bb8f780f7d560d", size = 3435683, upload-time = "2025-05-13T16:07:37.863Z" },
+ { url = "https://files.pythonhosted.org/packages/91/e4/f27055290d58e8818bed8a297162a096ef7f8ecdf01d98772d4b02af46c4/psycopg_binary-3.2.9-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:bc75f63653ce4ec764c8f8c8b0ad9423e23021e1c34a84eb5f4ecac8538a4a4a", size = 3497124, upload-time = "2025-05-13T16:07:40.567Z" },
+ { url = "https://files.pythonhosted.org/packages/67/3d/17ed07579625529534605eeaeba34f0536754a5667dbf20ea2624fc80614/psycopg_binary-3.2.9-cp311-cp311-win_amd64.whl", hash = "sha256:3db3ba3c470801e94836ad78bf11fd5fab22e71b0c77343a1ee95d693879937a", size = 2939520, upload-time = "2025-05-13T16:07:45.467Z" },
+ { url = "https://files.pythonhosted.org/packages/29/6f/ec9957e37a606cd7564412e03f41f1b3c3637a5be018d0849914cb06e674/psycopg_binary-3.2.9-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:be7d650a434921a6b1ebe3fff324dbc2364393eb29d7672e638ce3e21076974e", size = 4022205, upload-time = "2025-05-13T16:07:48.195Z" },
+ { url = "https://files.pythonhosted.org/packages/6b/ba/497b8bea72b20a862ac95a94386967b745a472d9ddc88bc3f32d5d5f0d43/psycopg_binary-3.2.9-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6a76b4722a529390683c0304501f238b365a46b1e5fb6b7249dbc0ad6fea51a0", size = 4083795, upload-time = "2025-05-13T16:07:50.917Z" },
+ { url = "https://files.pythonhosted.org/packages/42/07/af9503e8e8bdad3911fd88e10e6a29240f9feaa99f57d6fac4a18b16f5a0/psycopg_binary-3.2.9-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:96a551e4683f1c307cfc3d9a05fec62c00a7264f320c9962a67a543e3ce0d8ff", size = 4655043, upload-time = "2025-05-13T16:07:54.857Z" },
+ { url = "https://files.pythonhosted.org/packages/28/ed/aff8c9850df1648cc6a5cc7a381f11ee78d98a6b807edd4a5ae276ad60ad/psycopg_binary-3.2.9-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:61d0a6ceed8f08c75a395bc28cb648a81cf8dee75ba4650093ad1a24a51c8724", size = 4477972, upload-time = "2025-05-13T16:07:57.925Z" },
+ { url = "https://files.pythonhosted.org/packages/5c/bd/8e9d1b77ec1a632818fe2f457c3a65af83c68710c4c162d6866947d08cc5/psycopg_binary-3.2.9-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ad280bbd409bf598683dda82232f5215cfc5f2b1bf0854e409b4d0c44a113b1d", size = 4737516, upload-time = "2025-05-13T16:08:01.616Z" },
+ { url = "https://files.pythonhosted.org/packages/46/ec/222238f774cd5a0881f3f3b18fb86daceae89cc410f91ef6a9fb4556f236/psycopg_binary-3.2.9-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:76eddaf7fef1d0994e3d536ad48aa75034663d3a07f6f7e3e601105ae73aeff6", size = 4436160, upload-time = "2025-05-13T16:08:04.278Z" },
+ { url = "https://files.pythonhosted.org/packages/37/78/af5af2a1b296eeca54ea7592cd19284739a844974c9747e516707e7b3b39/psycopg_binary-3.2.9-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:52e239cd66c4158e412318fbe028cd94b0ef21b0707f56dcb4bdc250ee58fd40", size = 3753518, upload-time = "2025-05-13T16:08:07.567Z" },
+ { url = "https://files.pythonhosted.org/packages/ec/ac/8a3ed39ea069402e9e6e6a2f79d81a71879708b31cc3454283314994b1ae/psycopg_binary-3.2.9-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:08bf9d5eabba160dd4f6ad247cf12f229cc19d2458511cab2eb9647f42fa6795", size = 3313598, upload-time = "2025-05-13T16:08:09.999Z" },
+ { url = "https://files.pythonhosted.org/packages/da/43/26549af068347c808fbfe5f07d2fa8cef747cfff7c695136172991d2378b/psycopg_binary-3.2.9-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1b2cf018168cad87580e67bdde38ff5e51511112f1ce6ce9a8336871f465c19a", size = 3407289, upload-time = "2025-05-13T16:08:12.66Z" },
+ { url = "https://files.pythonhosted.org/packages/67/55/ea8d227c77df8e8aec880ded398316735add8fda5eb4ff5cc96fac11e964/psycopg_binary-3.2.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:14f64d1ac6942ff089fc7e926440f7a5ced062e2ed0949d7d2d680dc5c00e2d4", size = 3472493, upload-time = "2025-05-13T16:08:15.672Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/02/6ff2a5bc53c3cd653d281666728e29121149179c73fddefb1e437024c192/psycopg_binary-3.2.9-cp312-cp312-win_amd64.whl", hash = "sha256:7a838852e5afb6b4126f93eb409516a8c02a49b788f4df8b6469a40c2157fa21", size = 2927400, upload-time = "2025-05-13T16:08:18.652Z" },
+]
+
[[package]]
name = "ptyprocess"
version = "0.7.0"
@@ -7891,6 +7968,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/17/69/cd203477f944c353c31bade965f880aa1061fd6bf05ded0726ca845b6ff7/typing_inspection-0.4.1-py3-none-any.whl", hash = "sha256:389055682238f53b04f7badcb49b989835495a96700ced5dab2d8feae4b26f51", size = 14552, upload-time = "2025-05-21T18:55:22.152Z" },
]
+[[package]]
+name = "tzdata"
+version = "2025.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/95/32/1a225d6164441be760d75c2c42e2780dc0873fe382da3e98a2e1e48361e5/tzdata-2025.2.tar.gz", hash = "sha256:b60a638fcc0daffadf82fe0f57e53d06bdec2f36c4df66280ae79bce6bd6f2b9", size = 196380, upload-time = "2025-03-23T13:54:43.652Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5c/23/c7abc0ca0a1526a0774eca151daeb8de62ec457e77262b66b359c3c7679e/tzdata-2025.2-py2.py3-none-any.whl", hash = "sha256:1a403fada01ff9221ca8044d701868fa132215d84beb92242d9acd2147f667a8", size = 347839, upload-time = "2025-03-23T13:54:41.845Z" },
+]
+
[[package]]
name = "uc-micro-py"
version = "1.0.3"