🐫 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: ChatAgent support api key as parameter (#551)
Wendong-Fanb4bbc197ef27
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex 2b7c28cd0..170d56b55 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -84,6 +84,9 @@ class ChatAgent(BaseAgent):responses. (default :obj:`ModelType.GPT_3_5_TURBO`)model_config (BaseConfig, optional): Configuration options for theLLM model. (default: :obj:`None`)+ api_key (str, optional): The API key for authenticating with the+ LLM service. Only OpenAI and Anthropic model supported (default:+ :obj:`None`)memory (AgentMemory, optional): The agent memory for managing chatmessages. If `None`, a :obj:`ChatHistoryMemory` will be used.(default: :obj:`None`)@@ -108,6 +111,7 @@ class ChatAgent(BaseAgent):system_message: BaseMessage,model_type: Optional[ModelType] = None,model_config: Optional[BaseConfig] = None,+ api_key: Optional[str] = None,memory: Optional[AgentMemory] = None,message_window_size: Optional[int] = None,token_limit: Optional[int] = None,@@ -133,9 +137,9 @@ class ChatAgent(BaseAgent):self.func_dict[func.get_function_name()] = func.funcself.model_config = model_config or ChatGPTConfig()-+ self._api_key = api_keyself.model_backend: BaseModelBackend = ModelFactory.create(- self.model_type, self.model_config.__dict__+ self.model_type, self.model_config.__dict__, self._api_key)self.model_token_limit = token_limit or self.model_backend.token_limitcontext_creator = ScoreBasedContextCreator(diff --git a/camel/embeddings/openai_embedding.py b/camel/embeddings/openai_embedding.pyindex 750998d7f..d9f148e54 100644--- a/camel/embeddings/openai_embedding.py+++ b/camel/embeddings/openai_embedding.py@@ -11,7 +11,8 @@# 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, List+import os+from typing import Any, List, Optionalfrom openai import OpenAI@@ -26,6 +27,8 @@ class OpenAIEmbedding(BaseEmbedding[str]):Args:model (OpenAiEmbeddingModel, optional): The model type to be used forgenerating embeddings. (default: :obj:`ModelType.ADA_2`)+ api_key (Optional[str]): The API key for authenticating with the+ OpenAI service. (default: :obj:`None`)Raises:RuntimeError: If an unsupported model type is specified.@@ -34,12 +37,14 @@ class OpenAIEmbedding(BaseEmbedding[str]):def __init__(self,model_type: EmbeddingModelType = EmbeddingModelType.ADA_2,+ api_key: Optional[str] = None,) -> None:if not model_type.is_openai:raise ValueError("Invalid OpenAI embedding model type.")self.model_type = model_typeself.output_dim = model_type.output_dim- self.client = OpenAI()+ 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)@api_key_requireddef embed_list(diff --git a/camel/models/anthropic_model.py b/camel/models/anthropic_model.pyindex 00b956849..792d3cd2f 100644--- a/camel/models/anthropic_model.py+++ b/camel/models/anthropic_model.py@@ -27,10 +27,24 @@ class AnthropicModel(BaseModelBackend):r"""Anthropic API in a unified BaseModelBackend interface."""def __init__(- self, model_type: ModelType, model_config_dict: Dict[str, Any]+ self,+ model_type: ModelType,+ model_config_dict: Dict[str, Any],+ api_key: Optional[str] = None,) -> None:+ r"""Constructor for Anthropic backend.++ Args:+ model_type (ModelType): Model for which a backend is created,+ one of GPT_* series.+ model_config_dict (Dict[str, Any]): A dictionary that will+ be fed into openai.ChatCompletion.create().+ api_key (Optional[str]): The API key for authenticating with the+ Anthropic service. (default: :obj:`None`)+ """super().__init__(model_type, model_config_dict)- self.client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])+ self._api_key = api_key or os.environ.get("ANTHROPIC_API_KEY")+ self.client = Anthropic(api_key=self._api_key)self._token_counter: Optional[BaseTokenCounter] = Nonedef _convert_response_from_anthropic_to_openai(self, response):diff --git a/camel/models/base_model.py b/camel/models/base_model.pyindex 8ae4ae79f..c61360f3a 100644--- a/camel/models/base_model.py+++ b/camel/models/base_model.py@@ -12,7 +12,7 @@# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========from abc import ABC, abstractmethod-from typing import Any, Dict, List, Union+from typing import Any, Dict, List, Optional, Unionfrom openai import Stream@@ -27,17 +27,23 @@ class BaseModelBackend(ABC):"""def __init__(- self, model_type: ModelType, model_config_dict: Dict[str, Any]+ self,+ model_type: ModelType,+ model_config_dict: Dict[str, Any],+ api_key: Optional[str] = None,) -> None:r"""Constructor for the model backend.Args:model_type (ModelType): Model for which a backend is created.model_config_dict (Dict[str, Any]): A config dictionary.+ api_key (Optional[str]): The API key for authenticating with the+ LLM service."""self.model_type = model_typeself.model_config_dict = model_config_dict+ self._api_key = api_keyself.check_model_config()@propertydiff --git a/camel/models/model_factory.py b/camel/models/model_factory.pyindex b44d4b626..bb0d82dcb 100644--- a/camel/models/model_factory.py+++ b/camel/models/model_factory.py@@ -11,7 +11,7 @@# 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+from typing import Any, Dict, Optionalfrom camel.models.anthropic_model import AnthropicModelfrom camel.models.base_model import BaseModelBackend@@ -30,7 +30,9 @@ class ModelFactory:@staticmethoddef create(- model_type: ModelType, model_config_dict: Dict+ model_type: ModelType,+ model_config_dict: Dict,+ api_key: Optional[str] = None,) -> BaseModelBackend:r"""Creates an instance of `BaseModelBackend` of the specified type.@@ -38,6 +40,8 @@ class ModelFactory:model_type (ModelType): Model for which a backend is created.model_config_dict (Dict): A dictionary that will be fed intothe backend constructor.+ api_key (Optional[str]): The API key for authenticating with the+ LLM service.Raises:ValueError: If there is not backend for the model.@@ -57,5 +61,5 @@ class ModelFactory:else:raise ValueError(f"Unknown model type `{model_type}` is input")- inst = model_class(model_type, model_config_dict)+ inst = model_class(model_type, model_config_dict, api_key)return instdiff --git a/camel/models/openai_model.py b/camel/models/openai_model.pyindex 039b50a3e..725c4eeb5 100644--- a/camel/models/openai_model.py+++ b/camel/models/openai_model.py@@ -27,7 +27,10 @@ class OpenAIModel(BaseModelBackend):r"""OpenAI API in a unified BaseModelBackend interface."""def __init__(- self, model_type: ModelType, model_config_dict: Dict[str, Any]+ self,+ model_type: ModelType,+ model_config_dict: Dict[str, Any],+ api_key: Optional[str] = None,) -> None:r"""Constructor for OpenAI backend.@@ -36,10 +39,15 @@ class OpenAIModel(BaseModelBackend):one of GPT_* series.model_config_dict (Dict[str, Any]): A dictionary that willbe fed into openai.ChatCompletion.create().+ api_key (Optional[str]): The API key for authenticating with the+ OpenAI service. (default: :obj:`None`)"""super().__init__(model_type, model_config_dict)url = os.environ.get('OPENAI_API_BASE_URL', None)- self._client = OpenAI(timeout=60, max_retries=3, base_url=url)+ self._api_key = api_key or os.environ.get("OPENAI_API_KEY")+ self._client = OpenAI(+ timeout=60, max_retries=3, base_url=url, api_key=self._api_key+ )self._token_counter: Optional[BaseTokenCounter] = None@propertydiff --git a/camel/models/stub_model.py b/camel/models/stub_model.pyindex 7c958665a..ad53649b3 100644--- a/camel/models/stub_model.py+++ b/camel/models/stub_model.py@@ -50,11 +50,15 @@ class StubModel(BaseModelBackend):model_type = ModelType.STUBdef __init__(- self, model_type: ModelType, model_config_dict: Dict[str, Any]+ self,+ model_type: ModelType,+ model_config_dict: Dict[str, Any],+ api_key: Optional[str] = None,) -> None:r"""All arguments are unused for the dummy model."""super().__init__(model_type, model_config_dict)self._token_counter: Optional[BaseTokenCounter] = None+ self._api_key = api_key@propertydef token_counter(self) -> BaseTokenCounter:diff --git a/camel/utils/commons.py b/camel/utils/commons.pyindex a0769cf54..2a36fbb8e 100644--- a/camel/utils/commons.py+++ b/camel/utils/commons.py@@ -58,8 +58,7 @@ def get_lazy_imported_types_module():def api_key_required(func: F) -> F:- r"""Decorator that checks if the OpenAI API key is available in the- environment variables.+ r"""Decorator that checks if the API key is available either as an environment variable or passed directly.Args:func (callable): The function to be wrapped.@@ -68,14 +67,14 @@ def api_key_required(func: F) -> F:callable: The decorated function.Raises:- ValueError: If the OpenAI API key is not found in the environment- variables.+ ValueError: If the API key is not found, either as an environment+ variable or directly passed."""@wraps(func)def wrapper(self, *args, **kwargs):if self.model_type.is_openai:- if 'OPENAI_API_KEY' not in os.environ:+ 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_anthropic: