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(storages): add dependencies_required/api_keys_required decorators to camel.storages (#4111)

nuthalapativarun5ff292d06477
diff --git a/camel/storages/key_value_storages/mem0_cloud.py b/camel/storages/key_value_storages/mem0_cloud.py
index bc81a9950..5ade9de28 100644
--- a/camel/storages/key_value_storages/mem0_cloud.py
+++ b/camel/storages/key_value_storages/mem0_cloud.py
@@ -22,6 +22,7 @@ from camel.memories.records import MemoryRecord
from camel.messages import BaseMessage
from camel.storages.key_value_storages import BaseKeyValueStorage
from camel.types import OpenAIBackendRole, RoleType
+from camel.utils import api_keys_required, dependencies_required
logger = logging.getLogger(__name__)
@@ -45,6 +46,12 @@ class Mem0Storage(BaseKeyValueStorage):
https://docs.mem0.ai
"""
+ @dependencies_required('mem0')
+ @api_keys_required(
+ [
+ ("api_key", "MEM0_API_KEY"),
+ ]
+ )
def __init__(
self,
agent_id: str,
@@ -52,22 +59,9 @@ class Mem0Storage(BaseKeyValueStorage):
user_id: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
- try:
- from mem0 import MemoryClient
- except ImportError as exc:
- logger.error(
- "Please install `mem0` first. You can install it by "
- "running `pip install mem0ai`."
- )
- raise exc
+ from mem0 import MemoryClient
self.api_key = api_key or os.getenv("MEM0_API_KEY")
- if not self.api_key:
- raise ValueError(
- "API key must be provided either through constructor "
- "or MEM0_API_KEY environment variable."
- )
-
self.client = MemoryClient(api_key=self.api_key)
self.agent_id = agent_id
self.user_id = user_id
diff --git a/camel/storages/key_value_storages/redis.py b/camel/storages/key_value_storages/redis.py
index cefbb7178..b4209fb5b 100644
--- a/camel/storages/key_value_storages/redis.py
+++ b/camel/storages/key_value_storages/redis.py
@@ -18,6 +18,7 @@ import logging
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from camel.storages.key_value_storages import BaseKeyValueStorage
+from camel.utils import dependencies_required
if TYPE_CHECKING:
from redis.asyncio import Redis
@@ -31,6 +32,7 @@ class RedisStorage(BaseKeyValueStorage):
persistence and high availability.
"""
+ @dependencies_required('redis')
def __init__(
self,
sid: str,
@@ -49,16 +51,9 @@ class RedisStorage(BaseKeyValueStorage):
configuration.
Raises:
- ImportError: If the `redis.asyncio` module is not installed.
+ ImportError: If the `redis` module is not installed.
"""
- try:
- import redis.asyncio as aredis
- except ImportError as exc:
- logger.error(
- "Please install `redis` first. You can install it by "
- "running `pip install redis`."
- )
- raise exc
+ import redis.asyncio as aredis
self._client: Optional[aredis.Redis] = None
self._url = url
diff --git a/camel/storages/object_storages/amazon_s3.py b/camel/storages/object_storages/amazon_s3.py
index f532569ef..03d1bc4c4 100644
--- a/camel/storages/object_storages/amazon_s3.py
+++ b/camel/storages/object_storages/amazon_s3.py
@@ -19,6 +19,7 @@ from warnings import warn
from camel.loaders import File, create_file_from_raw_bytes
from camel.storages.object_storages.base import BaseObjectStorage
+from camel.utils import dependencies_required
class AmazonS3Storage(BaseObjectStorage):
@@ -46,6 +47,7 @@ class AmazonS3Storage(BaseObjectStorage):
https://aws.amazon.com/cli/
"""
+ @dependencies_required('botocore')
def __init__(
self,
bucket_name: str,
diff --git a/camel/storages/object_storages/azure_blob.py b/camel/storages/object_storages/azure_blob.py
index 3357f159f..c555c52e6 100644
--- a/camel/storages/object_storages/azure_blob.py
+++ b/camel/storages/object_storages/azure_blob.py
@@ -18,6 +18,7 @@ from warnings import warn
from camel.loaders import File, create_file_from_raw_bytes
from camel.storages.object_storages.base import BaseObjectStorage
+from camel.utils import dependencies_required
class AzureBlobStorage(BaseObjectStorage):
@@ -34,6 +35,7 @@ class AzureBlobStorage(BaseObjectStorage):
https://azure.microsoft.com/en-us/products/storage/blobs
"""
+ @dependencies_required('azure.storage.blob')
def __init__(
self,
storage_account_name: str,
diff --git a/camel/storages/object_storages/google_cloud.py b/camel/storages/object_storages/google_cloud.py
index a60d6631f..fbb43c42e 100644
--- a/camel/storages/object_storages/google_cloud.py
+++ b/camel/storages/object_storages/google_cloud.py
@@ -17,6 +17,7 @@ from warnings import warn
from camel.loaders import File, create_file_from_raw_bytes
from camel.storages.object_storages.base import BaseObjectStorage
+from camel.utils import dependencies_required
class GoogleCloudStorage(BaseObjectStorage):
@@ -40,6 +41,7 @@ class GoogleCloudStorage(BaseObjectStorage):
https://cloud.google.com/docs/authentication/api-keys
"""
+ @dependencies_required('google.cloud.storage')
def __init__(
self,
bucket_name: str,
diff --git a/test/storages/test_storages_decorators.py b/test/storages/test_storages_decorators.py
new file mode 100644
index 000000000..f875c8ec1
--- /dev/null
+++ b/test/storages/test_storages_decorators.py
@@ -0,0 +1,90 @@
+# ========= Copyright 2023-2026 @ 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-2026 @ CAMEL-AI.org. All Rights Reserved. =========
+"""
+Test that the following decorators are correctly applied to camel.storages:
+@api_keys_required - should raise ValueError if value is missing
+@dependencies_required - should raise ImportError if package/module is missing
+"""
+
+from unittest.mock import patch
+
+import pytest
+
+fake_api_key = "fake_api_key"
+
+
+def _mock_missing(module_name: str):
+ """Patch is_module_available to return False for a specific module."""
+ original = __import__(
+ 'camel.utils.commons', fromlist=['is_module_available']
+ ).is_module_available
+
+ def fake(m):
+ if m == module_name:
+ return False
+ return original(m)
+
+ return patch('camel.utils.commons.is_module_available', side_effect=fake)
+
+
+def test_redis_storage_missing_dependency():
+ from camel.storages import RedisStorage
+
+ with _mock_missing('redis'):
+ with pytest.raises(ImportError, match="redis"):
+ RedisStorage(sid="test")
+
+
+def test_mem0_storage_missing_dependency():
+ from camel.storages.key_value_storages import Mem0Storage
+
+ with _mock_missing('mem0'):
+ with pytest.raises(ImportError, match="mem0"):
+ Mem0Storage(agent_id="test_agent", api_key=fake_api_key)
+
+
+def test_mem0_storage_missing_api_key():
+ from camel.storages.key_value_storages import Mem0Storage
+
+ with patch('camel.utils.commons.is_module_available', return_value=True):
+ with patch.dict('os.environ', {}, clear=True):
+ with pytest.raises(ValueError, match="MEM0_API_KEY"):
+ Mem0Storage(agent_id="test_agent")
+
+
+def test_amazon_s3_storage_missing_dependency():
+ from camel.storages.object_storages import AmazonS3Storage
+
+ with _mock_missing('botocore'):
+ with pytest.raises(ImportError, match="botocore"):
+ AmazonS3Storage(bucket_name="test-bucket")
+
+
+def test_azure_blob_storage_missing_dependency():
+ from camel.storages.object_storages import AzureBlobStorage
+
+ with _mock_missing('azure.storage.blob'):
+ with pytest.raises(ImportError, match=r"azure\.storage\.blob"):
+ AzureBlobStorage(
+ storage_account_name="test-account",
+ container_name="test-container",
+ )
+
+
+def test_google_cloud_storage_missing_dependency():
+ from camel.storages.object_storages import GoogleCloudStorage
+
+ with _mock_missing('google.cloud.storage'):
+ with pytest.raises(ImportError, match=r"google\.cloud\.storage"):
+ GoogleCloudStorage(bucket_name="test-bucket")