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

chore: Unify api decorator (#663)

Wendong-Fan67bcfa4ddf65
diff --git a/camel/embeddings/openai_embedding.py b/camel/embeddings/openai_embedding.py
index 281467e58..9a6743912 100644
--- a/camel/embeddings/openai_embedding.py
+++ b/camel/embeddings/openai_embedding.py
@@ -20,7 +20,7 @@ from openai import NOT_GIVEN, NotGiven, OpenAI
from camel.embeddings.base import BaseEmbedding
from camel.types import EmbeddingModelType
-from camel.utils import model_api_key_required
+from camel.utils import api_keys_required
class OpenAIEmbedding(BaseEmbedding[str]):
@@ -58,7 +58,7 @@ class OpenAIEmbedding(BaseEmbedding[str]):
self._api_key = api_key or os.environ.get("OPENAI_API_KEY")
self.client = OpenAI(timeout=60, max_retries=3, api_key=self._api_key)
- @model_api_key_required
+ @api_keys_required("OPENAI_API_KEY")
def embed_list(
self,
objs: list[str],
diff --git a/camel/models/anthropic_model.py b/camel/models/anthropic_model.py
index 153343bd6..4d5d33554 100644
--- a/camel/models/anthropic_model.py
+++ b/camel/models/anthropic_model.py
@@ -23,7 +23,7 @@ from camel.types import ChatCompletion, ModelType
from camel.utils import (
AnthropicTokenCounter,
BaseTokenCounter,
- model_api_key_required,
+ api_keys_required,
)
@@ -98,7 +98,7 @@ class AnthropicModel(BaseModelBackend):
"""
return self.client.count_tokens(prompt)
- @model_api_key_required
+ @api_keys_required("ANTHROPIC_API_KEY")
def run(
self,
messages: List[OpenAIMessage],
diff --git a/camel/models/nemotron_model.py b/camel/models/nemotron_model.py
index 10e337b41..faf461199 100644
--- a/camel/models/nemotron_model.py
+++ b/camel/models/nemotron_model.py
@@ -20,7 +20,7 @@ from camel.messages import OpenAIMessage
from camel.types import ChatCompletion, ModelType
from camel.utils import (
BaseTokenCounter,
- model_api_key_required,
+ api_keys_required,
)
@@ -59,7 +59,7 @@ class NemotronModel:
)
self._token_counter: Optional[BaseTokenCounter] = None
- @model_api_key_required
+ @api_keys_required("NVIDIA_API_KEY")
def run(
self,
messages: List[OpenAIMessage],
diff --git a/camel/models/openai_model.py b/camel/models/openai_model.py
index a25876b99..4baed2753 100644
--- a/camel/models/openai_model.py
+++ b/camel/models/openai_model.py
@@ -23,7 +23,7 @@ from camel.types import ChatCompletion, ChatCompletionChunk, ModelType
from camel.utils import (
BaseTokenCounter,
OpenAITokenCounter,
- model_api_key_required,
+ api_keys_required,
)
@@ -72,7 +72,7 @@ class OpenAIModel(BaseModelBackend):
self._token_counter = OpenAITokenCounter(self.model_type)
return self._token_counter
- @model_api_key_required
+ @api_keys_required("OPENAI_API_KEY")
def run(
self,
messages: List[OpenAIMessage],
diff --git a/camel/models/zhipuai_model.py b/camel/models/zhipuai_model.py
index 2011d828a..32d402d5a 100644
--- a/camel/models/zhipuai_model.py
+++ b/camel/models/zhipuai_model.py
@@ -24,7 +24,7 @@ from camel.types import ChatCompletion, ChatCompletionChunk, ModelType
from camel.utils import (
BaseTokenCounter,
OpenAITokenCounter,
- model_api_key_required,
+ api_keys_required,
)
@@ -65,7 +65,7 @@ class ZhipuAIModel(BaseModelBackend):
)
self._token_counter: Optional[BaseTokenCounter] = None
- @model_api_key_required
+ @api_keys_required("ZHIPUAI_API_KEY")
def run(
self,
messages: List[OpenAIMessage],
diff --git a/camel/utils/__init__.py b/camel/utils/__init__.py
index c2f3fd4a3..26e793123 100644
--- a/camel/utils/__init__.py
+++ b/camel/utils/__init__.py
@@ -24,7 +24,6 @@ from .commons import (
get_system_information,
get_task_list,
is_docker_running,
- model_api_key_required,
print_text_animated,
text_extract_from_web,
to_pascal,
@@ -40,7 +39,6 @@ from .token_counting import (
)
__all__ = [
- 'model_api_key_required',
'print_text_animated',
'get_prompt_template_key_words',
'get_first_int',
diff --git a/camel/utils/commons.py b/camel/utils/commons.py
index 72f40103d..7deac6b66 100644
--- a/camel/utils/commons.py
+++ b/camel/utils/commons.py
@@ -31,48 +31,6 @@ from camel.types import TaskType
F = TypeVar('F', bound=Callable[..., Any])
-def model_api_key_required(func: F) -> F:
- r"""Decorator that checks if the API key is available either as an
- environment variable or passed directly for a model.
-
- Args:
- func (callable): The function to be wrapped.
-
- Returns:
- callable: The decorated function.
-
- Raises:
- ValueError: If the API key is not found, either as an environment
- variable or directly passed.
-
- Note:
- Supported model type: `OpenAI` and `Anthropic`.
- """
-
- @wraps(func)
- def wrapper(self, *args, **kwargs):
- if self.model_type.is_openai:
- if not self._api_key and 'OPENAI_API_KEY' not in os.environ:
- raise ValueError('OpenAI API key not found.')
- return func(self, *args, **kwargs)
- elif self.model_type.is_zhipuai:
- if 'ZHIPUAI_API_KEY' not in os.environ:
- raise ValueError('ZhiPuAI API key not found.')
- return func(self, *args, **kwargs)
- elif self.model_type.is_anthropic:
- if not self._api_key and 'ANTHROPIC_API_KEY' not in os.environ:
- raise ValueError('Anthropic API key not found.')
- return func(self, *args, **kwargs)
- elif self.model_type.is_nvidia:
- if not self._api_key and 'NVIDIA_API_KEY' not in os.environ:
- raise ValueError('NVIDIA API key not found.')
- return func(self, *args, **kwargs)
- else:
- raise ValueError('Unsupported model type.')
-
- return cast(F, wrapper)
-
-
def print_text_animated(text, delay: float = 0.02, end: str = ""):
r"""Prints the given text with an animated effect.
@@ -261,7 +219,7 @@ def is_module_available(module_name: str) -> bool:
def api_keys_required(*required_keys: str) -> Callable[[F], F]:
r"""A decorator to check if the required API keys are
- present in the environment variables.
+ presented in the environment variables or as an instance attribute.
Args:
required_keys (str): The required API keys to be checked.
@@ -272,7 +230,7 @@ def api_keys_required(*required_keys: str) -> Callable[[F], F]:
Raises:
ValueError: If any of the required API keys are missing in the
- environment variables.
+ environment variables and the instance attribute.
Example:
::
@@ -284,13 +242,18 @@ def api_keys_required(*required_keys: str) -> Callable[[F], F]:
def decorator(func: F) -> F:
@wraps(func)
- def wrapper(*args: Any, **kwargs: Any) -> Any:
- missing_keys = [k for k in required_keys if k not in os.environ]
- if missing_keys:
+ def wrapper(self, *args: Any, **kwargs: Any) -> Any:
+ missing_environment_keys = [
+ k for k in required_keys if k not in os.environ
+ ]
+ if (
+ not getattr(self, '_api_key', None)
+ and missing_environment_keys
+ ):
raise ValueError(
- f"Missing API keys: {', '.join(missing_keys)}"
+ f"Missing API keys: {', '.join(missing_environment_keys)}"
)
- return func(*args, **kwargs)
+ return func(self, *args, **kwargs)
return cast(F, wrapper)
diff --git a/test/utils/test_commons.py b/test/utils/test_commons.py
index 701e7886a..9ce859fc0 100644
--- a/test/utils/test_commons.py
+++ b/test/utils/test_commons.py
@@ -68,25 +68,64 @@ def test_dependencies_required(monkeypatch):
assert "Missing required modules: some_module_not_exist" in str(exc.value)
-def test_api_keys_required():
+def setup_env_vars():
+ original_env = os.environ.copy()
os.environ['API_KEY_1'] = 'API_KEY_1_VALUE'
os.environ['API_KEY_2'] = 'API_KEY_2_VALUE'
+ yield
+ os.environ.clear()
+ os.environ.update(original_env)
- @api_keys_required('API_KEY_1', 'API_KEY_2')
- def mock_api_keys_exist():
- return True
- assert True if mock_api_keys_exist() else False
+def test_api_keys_required(setup_env_vars):
+ class MockClass:
+ @api_keys_required('API_KEY_1', 'API_KEY_2')
+ def mock_api_keys_exist(self):
+ return True
- @api_keys_required('API_KEY_1', 'API_KEY_2', 'API_KEY_3')
- def mock_api_keys_not_exist():
- return True
+ @api_keys_required('API_KEY_1', 'API_KEY_2', 'API_KEY_3')
+ def mock_api_keys_not_exist(self):
+ return True
- with pytest.raises(ValueError) as exc:
- mock_api_keys_not_exist()
+ mock_instance = MockClass()
+
+ # Test case where all required API keys are present
+ assert mock_instance.mock_api_keys_exist() is True
+ # Test case where some required API keys are missing
+ with pytest.raises(ValueError) as exc:
+ mock_instance.mock_api_keys_not_exist()
assert "Missing API keys: API_KEY_3" in str(exc.value)
+ # Test case with no API keys set
+ os.environ.clear()
+ with pytest.raises(ValueError) as exc:
+ mock_instance.mock_api_keys_exist()
+ assert "Missing API keys: API_KEY_1, API_KEY_2" in str(exc.value)
+
+
+def test_api_keys_required_empty(setup_env_vars):
+ class MockClass:
+ @api_keys_required()
+ def mock_no_keys_required(self):
+ return True
+
+ mock_instance = MockClass()
+ assert mock_instance.mock_no_keys_required() is True
+
+
+def test_api_keys_required_non_existent(setup_env_vars):
+ class MockClass:
+ @api_keys_required('NON_EXISTENT_KEY')
+ def mock_non_existent_key(self):
+ return True
+
+ mock_instance = MockClass()
+ with pytest.raises(ValueError) as exc:
+ mock_instance.mock_non_existent_key()
+ assert "Missing API keys: NON_EXISTENT_KEY" in str(exc.value)
+
def test_get_system_information():
# Call the function