🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
feat: Qdrant enhancement (#1147)
koch3092c11f497bf0a4
diff --git a/camel/storages/vectordb_storages/qdrant.py b/camel/storages/vectordb_storages/qdrant.pyindex 828f2be95..0aa7d38dd 100644--- a/camel/storages/vectordb_storages/qdrant.py+++ b/camel/storages/vectordb_storages/qdrant.py@@ -11,8 +11,12 @@# See the License for the specific language governing permissions and# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========+import loggingfrom datetime import datetime-from typing import Any, Dict, List, Optional, Tuple, Union, cast+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, cast++if TYPE_CHECKING:+ from qdrant_client import QdrantClientfrom camel.storages.vectordb_storages import (BaseVectorStorage,@@ -25,6 +29,7 @@ from camel.types import VectorDistancefrom camel.utils import dependencies_required_qdrant_local_client_map: Dict[str, Tuple[Any, int]] = {}+logger = logging.getLogger(__name__)class QdrantStorage(BaseVectorStorage):@@ -107,7 +112,13 @@ class QdrantStorage(BaseVectorStorage):hasattr(self, "delete_collection_on_del")and self.delete_collection_on_del):- self._delete_collection(self.collection_name)+ try:+ self._delete_collection(self.collection_name)+ except RuntimeError as e:+ logger.error(+ f"Failed to delete collection"+ f" '{self.collection_name}': {e}"+ )def _create_client(self,@@ -244,6 +255,10 @@ class QdrantStorage(BaseVectorStorage):"config": collection_info.config,}+ def close_client(self, **kwargs):+ r"""Closes the client connection to the Qdrant storage."""+ self._client.close(**kwargs)+def add(self,records: List[VectorRecord],@@ -273,36 +288,124 @@ class QdrantStorage(BaseVectorStorage):f"{op_info}.")- def delete(- self,- ids: List[str],- **kwargs: Any,+ def update_payload(+ self, ids: List[str], payload: Dict[str, Any], **kwargs: Any) -> None:- r"""Deletes a list of vectors identified by their IDs from the storage.+ r"""Updates the payload of the vectors identified by their IDs.Args:ids (List[str]): List of unique identifiers for the vectors to be- deleted.+ updated.+ payload (Dict[str, Any]): List of payloads to be updated.**kwargs (Any): Additional keyword arguments.Raises:- RuntimeError: If there is an error during the deletion process.+ RuntimeError: If there is an error during the update process."""from qdrant_client.http.models import PointIdsList, UpdateStatuspoints = cast(List[Union[str, int]], ids)- op_info = self._client.delete(++ op_info = self._client.set_payload(collection_name=self.collection_name,- points_selector=PointIdsList(points=points),- wait=True,+ payload=payload,+ points=PointIdsList(points=points),**kwargs,)if op_info.status != UpdateStatus.COMPLETED:raise RuntimeError(- "Failed to delete vectors in Qdrant, operation info: "+ "Failed to update payload in Qdrant, operation info: "f"{op_info}")+ def delete_collection(self) -> None:+ r"""Deletes the entire collection in the Qdrant storage."""+ self._delete_collection(self.collection_name)++ def delete(+ self,+ ids: Optional[List[str]] = None,+ payload_filter: Optional[Dict[str, Any]] = None,+ **kwargs: Any,+ ) -> None:+ r"""Deletes points from the collection based on either IDs or payload+ filters.++ Args:+ ids (Optional[List[str]], optional): List of unique identifiers+ for the vectors to be deleted.+ payload_filter (Optional[Dict[str, Any]], optional): A filter for+ the payload to delete points matching specific conditions. If+ `ids` is provided, `payload_filter` will be ignored unless both+ are combined explicitly.+ **kwargs (Any): Additional keyword arguments pass to `QdrantClient.+ delete`.++ Examples:+ >>> # Delete points with IDs "1", "2", and "3"+ >>> storage.delete(ids=["1", "2", "3"])+ >>> # Delete points with payload filter+ >>> storage.delete(payload_filter={"name": "Alice"})++ Raises:+ ValueError: If neither `ids` nor `payload_filter` is provided.+ RuntimeError: If there is an error during the deletion process.++ Notes:+ - If `ids` is provided, the points with these IDs will be deleted+ directly, and the `payload_filter` will be ignored.+ - If `ids` is not provided but `payload_filter` is, then points+ matching the `payload_filter` will be deleted.+ """+ from qdrant_client.http.models import (+ Condition,+ FieldCondition,+ Filter,+ MatchValue,+ PointIdsList,+ UpdateStatus,+ )++ if not ids and not payload_filter:+ raise ValueError(+ "You must provide either `ids` or `payload_filter` to delete "+ "points."+ )++ if ids:+ op_info = self._client.delete(+ collection_name=self.collection_name,+ points_selector=PointIdsList(+ points=cast(List[Union[int, str]], ids)+ ),+ **kwargs,+ )+ if op_info.status != UpdateStatus.COMPLETED:+ raise RuntimeError(+ "Failed to delete vectors in Qdrant, operation info: "+ f"{op_info}"+ )++ if payload_filter:+ filter_conditions = [+ FieldCondition(key=key, match=MatchValue(value=value))+ for key, value in payload_filter.items()+ ]++ op_info = self._client.delete(+ collection_name=self.collection_name,+ points_selector=Filter(+ must=cast(List[Condition], filter_conditions)+ ),+ **kwargs,+ )++ if op_info.status != UpdateStatus.COMPLETED:+ raise RuntimeError(+ "Failed to delete vectors in Qdrant, operation info: "+ f"{op_info}"+ )+def status(self) -> VectorDBStatus:status = self._get_collection_info(self.collection_name)return VectorDBStatus(@@ -313,6 +416,7 @@ class QdrantStorage(BaseVectorStorage):def query(self,query: VectorDBQuery,+ filter_conditions: Optional[Dict[str, Any]] = None,**kwargs: Any,) -> List[VectorDBQueryResult]:r"""Searches for similar vectors in the storage based on the provided@@ -321,31 +425,50 @@ class QdrantStorage(BaseVectorStorage):Args:query (VectorDBQuery): The query object containing the searchvector and the number of top similar vectors to retrieve.+ filter_conditions (Optional[Dict[str, Any]], optional): A+ dictionary specifying conditions to filter the query results.**kwargs (Any): Additional keyword arguments.Returns:List[VectorDBQueryResult]: A list of vectors retrieved from thestorage based on similarity to the query vector."""- # TODO: filter+ from qdrant_client.http.models import (+ Condition,+ FieldCondition,+ Filter,+ MatchValue,+ )++ # Construct filter if filter_conditions is provided+ search_filter = None+ if filter_conditions:+ must_conditions = [+ FieldCondition(key=key, match=MatchValue(value=value))+ for key, value in filter_conditions.items()+ ]+ search_filter = Filter(must=cast(List[Condition], must_conditions))++ # Execute the search with optional filtersearch_result = self._client.search(collection_name=self.collection_name,query_vector=query.query_vector,with_payload=True,with_vectors=True,limit=query.top_k,+ query_filter=search_filter,**kwargs,)- query_results = []- for point in search_result:- query_results.append(- VectorDBQueryResult.create(- similarity=point.score,- id=str(point.id),- payload=point.payload,- vector=point.vector, # type: ignore[arg-type]- )++ query_results = [+ VectorDBQueryResult.create(+ similarity=point.score,+ id=str(point.id),+ payload=point.payload,+ vector=point.vector, # type: ignore[arg-type])+ for point in search_result+ ]return query_results@@ -363,6 +486,6 @@ class QdrantStorage(BaseVectorStorage):pass@property- def client(self) -> Any:+ def client(self) -> "QdrantClient":r"""Provides access to the underlying vector database client."""return self._clientdiff --git a/test/storages/vector_storages/test_qdrant.py b/test/storages/vector_storages/test_qdrant.pyindex c404cad89..e6229a510 100644--- a/test/storages/vector_storages/test_qdrant.py+++ b/test/storages/vector_storages/test_qdrant.py@@ -15,84 +15,132 @@import shutilimport tempfile+import pytest+from camel.storages import QdrantStorage, VectorDBQuery, VectorRecord+from camel.types import VectorDistance-def test_multiple_local_clients() -> None:[email protected](scope="function")+def temp_storage():tmpdir = tempfile.mkdtemp()- storage1 = QdrantStorage(- vector_dim=4,- path=tmpdir,- collection_name="collection1",- delete_collection_on_del=True,- )- storage2 = QdrantStorage(+ storage = QdrantStorage(vector_dim=4,path=tmpdir,- collection_name="collection2",- delete_collection_on_del=True,+ collection_name="test_collection",)+ yield storage+ storage.delete_collection()+ storage.close_client()+ shutil.rmtree(tmpdir)- # Add vectors to storage1- vectors1 = [- VectorRecord(vector=[0.1, 0.1, 0.1, 0.1]),- VectorRecord(vector=[0.1, -0.1, -0.1, 0.1]),- ]- storage1.add(records=vectors1)-- # Add vectors to storage2- vectors2 = [- VectorRecord(- vector=[-0.1, 0.1, -0.1, 0.1],- payload={"message": "text"},- ),- VectorRecord(- vector=[-0.1, 0.1, 0.1, 0.1],- payload={"message": "text", "number": 1},- ),++def test_add_and_query_vectors(temp_storage):+ vectors = [+ VectorRecord(vector=[0.2, 0.2, 0.2, 0.2], payload={"label": "A"}),+ VectorRecord(vector=[-0.2, -0.2, -0.2, -0.2], payload={"label": "B"}),]- storage2.add(records=vectors2)+ temp_storage.add(records=vectors)- # Query and check results from storage1- query1 = VectorDBQuery(query_vector=[1.0, 1.0, 1.0, 1.0], top_k=1)- result1 = storage1.query(query1)- assert result1[0].record.id == vectors1[0].id+ assert temp_storage.status().vector_count == 2- # Query and check results from storage2- query2 = VectorDBQuery(query_vector=[-1.0, 1.0, -1.0, 1.0], top_k=1)- result2 = storage2.query(query2)- assert result2[0].record.id == vectors2[0].id- assert result2[0].record.payload == {"message": "text"}+ query = VectorDBQuery(query_vector=[0.2, 0.2, 0.2, 0.2], top_k=1)+ result = temp_storage.query(query)+ assert len(result) == 1+ assert result[0].record.payload["label"] == "A"- # Clear and check status for each storage- storage1.clear()- status1 = storage1.status()- assert status1.vector_count == 0- storage2.clear()- status2 = storage2.status()- assert status2.vector_count == 0+def test_query_with_filter(temp_storage):+ vector1 = VectorRecord(vector=[0.3, 0.3, 0.3, 0.3], payload={"label": "A"})+ vector2 = VectorRecord(+ vector=[-0.3, -0.3, -0.3, -0.3], payload={"label": "B"}+ )+ temp_storage.add(records=[vector1, vector2])++ query = VectorDBQuery(query_vector=[0.3, 0.3, 0.3, 0.3], top_k=2)+ result = temp_storage.query(query, filter_conditions={"label": "A"})+ assert len(result) == 1+ assert result[0].record.payload["label"] == "A"++ result2 = temp_storage.query(query, filter_conditions={"label": "B"})+ assert len(result2) == 1+ assert result2[0].record.payload["label"] == "B"+++def test_update_payload(temp_storage):+ vector = VectorRecord(vector=[0.5, 0.5, 0.5, 0.5], payload={"label": "C"})+ temp_storage.add(records=[vector])++ temp_storage.update_payload(ids=[vector.id], payload={"label": "Updated"})+ query = VectorDBQuery(query_vector=[0.5, 0.5, 0.5, 0.5], top_k=1)+ result = temp_storage.query(query)+ assert result[0].record.payload["label"] == "Updated"++ # Verify original label is no longer present+ result2 = temp_storage.query(query, filter_conditions={"label": "C"})+ assert len(result2) == 0+++def test_delete_vectors(temp_storage):+ vector1 = VectorRecord(vector=[0.6, 0.6, 0.6, 0.6], payload={"group": "X"})+ vector2 = VectorRecord(+ vector=[-0.6, -0.6, -0.6, -0.6], payload={"group": "Y"}+ )+ temp_storage.add(records=[vector1, vector2])++ temp_storage.delete(ids=[vector1.id])++ all_vectors = temp_storage.query(+ VectorDBQuery(query_vector=[0.0, 0.0, 0.0, 0.0], top_k=10)+ )+ assert all(v.record.id != vector1.id for v in all_vectors)++ temp_storage.delete(payload_filter={"group": "Y"})+ assert temp_storage.status().vector_count == 0- shutil.rmtree(tmpdir)+def test_clear_collection(temp_storage):+ vector1 = VectorRecord(vector=[1.0, 1.0, 1.0, 1.0])+ vector2 = VectorRecord(vector=[-1.0, -1.0, -1.0, -1.0])+ temp_storage.add(records=[vector1, vector2])-def test_existing_collection():+ temp_storage.clear()+ assert temp_storage.status().vector_count == 0+++def test_different_distance_metrics():tmpdir = tempfile.mkdtemp()storage = QdrantStorage(vector_dim=4,path=tmpdir,- collection_name="test_collection",+ collection_name="test_collection_distance_metric",+ distance=VectorDistance.EUCLIDEAN,+ delete_collection_on_del=True,)++ vector1 = VectorRecord(vector=[0.0, 0.0, 0.0, 0.0])+ vector2 = VectorRecord(vector=[1.0, 1.0, 1.0, 1.0])+ storage.add(records=[vector1, vector2])++ query = VectorDBQuery(query_vector=[0.1, 0.1, 0.1, 0.1], top_k=2)+ result = storage.query(query)+ assert result[0].record.id == vector1.id++ storage.close_client()+ shutil.rmtree(tmpdir)+++def test_delete_collection(temp_storage):vectors = [- VectorRecord(vector=[0.1, 0.1, 0.1, 0.1]),- VectorRecord(vector=[0.1, -0.1, -0.1, 0.1]),+ VectorRecord(vector=[0.2, 0.2, 0.2, 0.2], payload={"label": "A"}),+ VectorRecord(vector=[-0.2, -0.2, -0.2, -0.2], payload={"label": "B"}),]- storage.add(records=vectors)- assert storage.status().vector_count == 2+ temp_storage.add(records=vectors)- storage2 = QdrantStorage(- vector_dim=4,- path=tmpdir,- collection_name="test_collection",+ assert temp_storage.status().vector_count == 2++ temp_storage.delete_collection()++ assert not temp_storage.client.collection_exists(+ temp_storage.collection_name)- assert storage2.status().vector_count == 2