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: vector retriever (#467)

Wendong-Fan3f3960097ae2
diff --git a/camel/retrievers/__init__.py b/camel/retrievers/__init__.py
new file mode 100644
index 000000000..e35c092e7
--- /dev/null
+++ b/camel/retrievers/__init__.py
@@ -0,0 +1,20 @@
+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========
+from .base import BaseRetriever
+from .vector_retriever import VectorRetriever
+
+__all__ = [
+ 'BaseRetriever',
+ 'VectorRetriever',
+]
diff --git a/camel/retrievers/base.py b/camel/retrievers/base.py
new file mode 100644
index 000000000..8d27a988c
--- /dev/null
+++ b/camel/retrievers/base.py
@@ -0,0 +1,57 @@
+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========
+from abc import ABC, abstractmethod
+from typing import Any, Dict, List
+
+DEFAULT_TOP_K_RESULTS = 1
+
+
+class BaseRetriever(ABC):
+ r"""Abstract base class for implementing various types of information
+ retrievers.
+ """
+
+ @abstractmethod
+ def __init__(self) -> None:
+ pass
+
+ @abstractmethod
+ def process(self, content_input_path: str, **kwargs: Any) -> None:
+ r"""
+ Processes content. Subclasses should implement this
+ method according to their specific needs.
+
+ Args:
+ content_input_path (str): The path or URL of the content to
+ process.
+ **kwargs (Any): Flexible keyword arguments for additional
+ parameters.
+ """
+ pass
+
+ @abstractmethod
+ def query(self, query: str, top_k: int = DEFAULT_TOP_K_RESULTS,
+ **kwargs: Any) -> List[Dict[str, Any]]:
+ r"""Query the results. Subclasses should implement this
+ method according to their specific needs.
+
+ Args:
+ query (str): Query string for information retriever.
+ top_k (int, optional): The number of top results to return during
+ retriever. Must be a positive integer. Defaults to
+ `DEFAULT_TOP_K_RESULTS`.
+ **kwargs (Any): Flexible keyword arguments for additional
+ parameters, like `similarity_threshold`.
+ """
+ pass
diff --git a/camel/retrievers/vector_retriever.py b/camel/retrievers/vector_retriever.py
new file mode 100644
index 000000000..4646b15f3
--- /dev/null
+++ b/camel/retrievers/vector_retriever.py
@@ -0,0 +1,151 @@
+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========
+from typing import Any, Dict, List, Optional
+
+from camel.embeddings import BaseEmbedding, OpenAIEmbedding
+from camel.functions import UnstructuredModules
+from camel.retrievers import BaseRetriever
+from camel.storages import BaseVectorStorage, VectorDBQuery, VectorRecord
+
+DEFAULT_TOP_K_RESULTS = 1
+DEFAULT_SIMILARITY_THRESHOLD = 0.75
+
+
+class VectorRetriever(BaseRetriever):
+ r"""An implementation of the `BaseRetriever` by using vector storage and
+ embedding model.
+
+ This class facilitates the retriever of relevant information using a
+ query-based approach, backed by vector embeddings.
+
+ Attributes:
+ embedding_model (BaseEmbedding): Embedding model used to generate
+ vector embeddings.
+ """
+
+ def __init__(self,
+ embedding_model: Optional[BaseEmbedding] = None) -> None:
+ r"""Initializes the retriever class with an optional embedding model.
+
+ Args:
+ embedding_model (Optional[BaseEmbedding]): The embedding model
+ instance. Defaults to `OpenAIEmbedding` if not provided.
+ """
+ self.embedding_model = embedding_model or OpenAIEmbedding()
+
+ def process( # type: ignore
+ self, content_input_path: str, storage: BaseVectorStorage,
+ **kwargs: Any) -> None:
+ r""" Processes content from a file or URL, divides it into chunks by
+ using `Unstructured IO`, and stores their embeddings in the specified
+ vector storage.
+
+ Args:
+ content_input_path (str): File path or URL of the content to be
+ processed.
+ storage (BaseVectorStorage): Vector storage to store the
+ embeddings.
+ **kwargs (Any): Additional keyword arguments for elements chunking.
+ """
+ unstructured_modules = UnstructuredModules()
+ elements = unstructured_modules.parse_file_or_url(content_input_path)
+ chunks = unstructured_modules.chunk_elements(
+ chunk_type="chunk_by_title", elements=elements, **kwargs)
+ # Iterate to process and store embeddings, set batch of 50
+ for i in range(0, len(chunks), 50):
+ batch_chunks = chunks[i:i + 50]
+ batch_vectors = self.embedding_model.embed_list(
+ objs=[str(chunk) for chunk in batch_chunks])
+
+ records = []
+ # Prepare the payload for each vector record, includes the content
+ # path, chunk metadata, and chunk text
+ for vector, chunk in zip(batch_vectors, batch_chunks):
+ content_path_info = {"content path": content_input_path}
+ chunk_metadata = {"metadata": chunk.metadata.to_dict()}
+ chunk_text = {"text": str(chunk)}
+ combined_dict = {
+ **content_path_info,
+ **chunk_metadata,
+ **chunk_text
+ }
+
+ records.append(
+ VectorRecord(vector=vector, payload=combined_dict))
+
+ storage.add(records=records)
+
+ def query( # type: ignore
+ self, query: str, storage: BaseVectorStorage,
+ top_k: int = DEFAULT_TOP_K_RESULTS,
+ similarity_threshold: float = DEFAULT_SIMILARITY_THRESHOLD,
+ **kwargs: Any) -> List[Dict[str, Any]]:
+ r"""Executes a query in vector storage and compiles the retrieved
+ results into a dictionary.
+
+ Args:
+ query (str): Query string for information retriever.
+ storage (BaseVectorStorage): Vector storage to query.
+ top_k (int, optional): The number of top results to return during
+ retriever. Must be a positive integer. Defaults to 1.
+ similarity_threshold (float, optional): The similarity threshold
+ for filtering results. Defaults to 0.75.
+ **kwargs (Any): Additional keyword arguments for vector storage
+ query.
+
+ Returns:
+ List[Dict[str, Any]]: Concatenated list of the query results.
+
+ Raises:
+ ValueError: If 'top_k' is less than or equal to 0, if vector
+ storage is empty, if payload of vector storage is None.
+ """
+
+ if top_k <= 0:
+ raise ValueError("top_k must be a positive integer.")
+
+ # Load the storage incase it's hosted remote
+ storage.load()
+
+ query_vector = self.embedding_model.embed(obj=query)
+ db_query = VectorDBQuery(query_vector=query_vector, top_k=top_k)
+ query_results = storage.query(query=db_query, **kwargs)
+
+ if query_results[0].record.payload is None:
+ raise ValueError("Payload of vector storage is None, please check"
+ " the collection.")
+
+ # format the results
+ formatted_results = []
+ for result in query_results:
+ if (result.similarity >= similarity_threshold
+ and result.record.payload is not None):
+ result_dict = {
+ 'similarity score': str(result.similarity),
+ 'content path':
+ result.record.payload.get('content path', ''),
+ 'metadata': result.record.payload.get('metadata', {}),
+ 'text': result.record.payload.get('text', '')
+ }
+ formatted_results.append(result_dict)
+
+ content_path = query_results[0].record.payload.get('content path', '')
+
+ if not formatted_results:
+ return [{
+ 'text':
+ f"""No suitable information retrieved from {content_path} \
+ with similarity_threshold = {similarity_threshold}."""
+ }]
+ return formatted_results
diff --git a/camel/storages/vectordb_storages/base.py b/camel/storages/vectordb_storages/base.py
index f0ca8ba54..b63f55326 100644
--- a/camel/storages/vectordb_storages/base.py
+++ b/camel/storages/vectordb_storages/base.py
@@ -161,6 +161,11 @@ class BaseVectorStorage(ABC):
r"""Remove all vectors from the storage."""
pass
+ @abstractmethod
+ def load(self) -> None:
+ r"""Load the collection hosted on cloud service."""
+ pass
+
@property
@abstractmethod
def client(self) -> Any:
diff --git a/camel/storages/vectordb_storages/milvus.py b/camel/storages/vectordb_storages/milvus.py
index 3615ef359..d2f8798a2 100644
--- a/camel/storages/vectordb_storages/milvus.py
+++ b/camel/storages/vectordb_storages/milvus.py
@@ -335,9 +335,8 @@ class MilvusStorage(BaseVectorStorage):
for point in search_result:
query_results.append(
VectorDBQueryResult.construct( # type: ignore
- similarity=(1 - point[0]['distance']),
- id=str(point[0]['id']),
- payload={'message': point[0]['entity'].get('payload')},
+ similarity=(point[0]['distance']), id=str(point[0]['id']),
+ payload=(point[0]['entity'].get('payload')),
vector=point[0]['entity'].get('vector')))
return query_results
@@ -350,6 +349,10 @@ class MilvusStorage(BaseVectorStorage):
self._delete_collection(self.collection_name)
self._create_collection(collection_name=self.collection_name)
+ def load(self) -> None:
+ r"""Load the collection hosted on cloud service."""
+ self._client.load_collection(self.collection_name)
+
@property
def client(self) -> Any:
r"""Provides direct access to the Milvus client. This property allows
diff --git a/camel/storages/vectordb_storages/qdrant.py b/camel/storages/vectordb_storages/qdrant.py
index dd06707ff..0381a789d 100644
--- a/camel/storages/vectordb_storages/qdrant.py
+++ b/camel/storages/vectordb_storages/qdrant.py
@@ -355,6 +355,10 @@ class QdrantStorage(BaseVectorStorage):
distance=self.distance,
)
+ def load(self) -> None:
+ r"""Load the collection hosted on cloud service."""
+ pass
+
@property
def client(self) -> Any:
r"""Provides access to the underlying vector database client."""
diff --git a/test/retrievers/test_vector_retriever.py b/test/retrievers/test_vector_retriever.py
new file mode 100644
index 000000000..8b66e3391
--- /dev/null
+++ b/test/retrievers/test_vector_retriever.py
@@ -0,0 +1,92 @@
+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+
+from camel.embeddings import OpenAIEmbedding
+from camel.retrievers import VectorRetriever
+
+# Mock classes for dependencies
+MockBaseEmbedding = Mock()
+MockBaseVectorStorage = Mock()
+MockUnstructuredModules = Mock()
+
+
+def mock_embedding_model():
+ return MockBaseEmbedding()
+
+
+def mock_vector_storage():
+ return MockBaseVectorStorage()
+
+
+def vector_retriever(mock_embedding_model):
+ return VectorRetriever(embedding_model=mock_embedding_model)
+
+
+# Test initialization with a custom embedding model
+def test_initialization_with_custom_embedding(vector_retriever,
+ mock_embedding_model):
+ assert vector_retriever.embedding_model == mock_embedding_model
+
+
+# Test initialization with default embedding model
+def test_initialization_with_default_embedding():
+ retriever = VectorRetriever()
+ assert isinstance(retriever.embedding_model, OpenAIEmbedding)
+
+
+# Test process method
+@patch('camel.retrievers.vector_retriever.UnstructuredModules')
+def test_process(mock_unstructured_modules, vector_retriever,
+ mock_vector_storage):
+ # Create a mock chunk with metadata
+ mock_chunk = MagicMock()
+ mock_chunk.metadata.to_dict.return_value = {'mock_key': 'mock_value'}
+
+ # Setup mock behavior
+ mock_unstructured_instance = mock_unstructured_modules.return_value
+ mock_unstructured_instance.parse_file_or_url.return_value = [
+ "mock_element"
+ ]
+ mock_unstructured_instance.chunk_elements.return_value = [mock_chunk]
+
+ vector_retriever.embedding_model.embed_list.return_value = [[
+ 0.1, 0.2, 0.3
+ ]]
+
+ vector_retriever.process("mock_path", mock_vector_storage)
+
+ # Assert that methods are called as expected
+ mock_unstructured_instance.parse_file_or_url.assert_called_once_with(
+ "mock_path")
+ mock_unstructured_instance.chunk_elements.assert_called_once()
+ mock_vector_storage.add.assert_called_once()
+
+
+# Test query_and_compile_results method
+def test_query(vector_retriever, mock_vector_storage):
+ # Setup mock behavior for vector storage query
+ mock_vector_storage.query.return_value = [
+ Mock(similarity=0.8, record=Mock(payload={"text": "mock_result"}))
+ ]
+
+ result = vector_retriever.query("mock_query", mock_vector_storage)
+
+ # Assert that the result is as expected
+ assert any(d.get('text') == 'mock_result' for d in result)