š« 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: Integrate Gemini 1.5 (#647)
Asher-hssbf270f32eaed
diff --git a/camel/agents/task_agent.py b/camel/agents/task_agent.pyindex cffaa281f..b9b93969e 100644--- a/camel/agents/task_agent.py+++ b/camel/agents/task_agent.py@@ -100,7 +100,6 @@ class TaskSpecifyAgent(ChatAgent):if meta_dict is not None:task_specify_prompt = task_specify_prompt.format(**meta_dict)-task_msg = BaseMessage.make_user_message(role_name="Task Specifier", content=task_specify_prompt)diff --git a/camel/configs/__init__.py b/camel/configs/__init__.pyindex bedcf0e95..dac32a3e6 100644--- a/camel/configs/__init__.py+++ b/camel/configs/__init__.py@@ -13,6 +13,10 @@# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========from .anthropic_config import ANTHROPIC_API_PARAMS, AnthropicConfigfrom .base_config import BaseConfig+from .gemini_config import (+ Gemini_API_PARAMS,+ GeminiConfig,+)from .litellm_config import LITELLM_API_PARAMS, LiteLLMConfigfrom .ollama_config import OLLAMA_API_PARAMS, OllamaConfigfrom .openai_config import (@@ -35,4 +39,6 @@ __all__ = ['OLLAMA_API_PARAMS','ZhipuAIConfig','ZHIPUAI_API_PARAMS',+ 'GeminiConfig',+ 'Gemini_API_PARAMS',]diff --git a/camel/configs/gemini_config.py b/camel/configs/gemini_config.pynew file mode 100644index 000000000..8e5c39939--- /dev/null+++ b/camel/configs/gemini_config.py@@ -0,0 +1,97 @@+# =========== 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 collections.abc import Iterable+from dataclasses import asdict, dataclass+from typing import Optional++from camel.configs.base_config import BaseConfig+++@dataclass(frozen=True)+class GeminiConfig(BaseConfig):+ r"""A simple dataclass used to configure the generation parameters of+ `GenerativeModel.generate_content`.++ Args:+ candidate_count (int, optional): Number of responses to return.+ stop_sequences (Iterable[str], optional): The set of character+ sequences (up to 5) that will stop output generation. If specified+ the API will stop at the first appearance of a stop sequence.+ The stop sequence will not be included as part of the response.+ max_output_tokens (int, optional): The maximum number of tokens to+ include in a candidate. If unset, this will default to+ output_token_limit specified in the model's specification.+ temperature (float, optional): Controls the randomness of the output.+ Note: The default value varies by model, see the+ `Model.temperature` attribute of the `Model` returned+ the `genai.get_model` function. Values can range from [0.0,1.0],+ inclusive. A value closer to 1.0 will produce responses that are+ more varied and creative, while a value closer to 0.0 will+ typically result in more straightforward responses from the model.+ top_p (int, optional): The maximum cumulative probability of tokens to+ consider when sampling. The model uses combined Top-k and nucleus+ sampling. Tokens are sorted based on their assigned probabilities+ so that only the most likely tokens are considered. Top-k sampling+ directly limits the maximum number of tokens to consider, while+ Nucleus sampling limits number of tokens+ based on the cumulative probability. Note: The default value varies+ by model, see the `Model.top_p` attribute of the `Model` returned+ the `genai.get_model` function.+ top_k (int, optional): The maximum number of tokens to consider when+ sampling. The model uses combined Top-k and nucleus sampling.Top-k+ sampling considers the set of `top_k` most probable tokens.+ Defaults to 40. Note: The default value varies by model, see the+ `Model.top_k` attribute of the `Model` returned the+ `genai.get_model` function.+ response_mime_type (str, optional): Output response mimetype of the+ generated candidate text. Supported mimetype:+ `text/plain`: (default) Text output.+ `application/json`: JSON response in the candidates.+ response_schema (Schema, optional): Specifies the format of the+ JSON requested if response_mime_type is `application/json`.+ safety_settings (SafetySettingOptions, optional):+ Overrides for the model's safety settings.+ tools (FunctionLibraryType, optional):+ `protos.Tools` more info coming soon.+ tool_config (ToolConfigType, optional):+ more info coming soon.+ request_options (RequestOptionsType, optional):+ Options for the request.+ """++ from google.generativeai.protos import Schema+ from google.generativeai.types.content_types import (+ FunctionLibraryType,+ ToolConfigType,+ )+ from google.generativeai.types.helper_types import RequestOptionsType+ from google.generativeai.types.safety_types import SafetySettingOptions++ candidate_count: Optional[int] = None+ stop_sequences: Optional[Iterable[str]] = None+ max_output_tokens: Optional[int] = None+ temperature: Optional[float] = None+ top_p: Optional[float] = None+ top_k: Optional[int] = None+ response_mime_type: Optional[str] = None+ response_schema: Optional[Schema] = None+ safety_settings: Optional[SafetySettingOptions] = None+ tools: Optional[FunctionLibraryType] = None+ tool_config: Optional[ToolConfigType] = None+ request_options: Optional[RequestOptionsType] = None+++Gemini_API_PARAMS = {param for param in asdict(GeminiConfig()).keys()}diff --git a/camel/models/__init__.py b/camel/models/__init__.pyindex 48e41ddc9..be1be4fc0 100644--- a/camel/models/__init__.py+++ b/camel/models/__init__.py@@ -13,6 +13,7 @@# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========from .anthropic_model import AnthropicModelfrom .base_model import BaseModelBackend+from .gemini_model import GeminiModelfrom .litellm_model import LiteLLMModelfrom .model_factory import ModelFactoryfrom .nemotron_model import NemotronModel@@ -35,4 +36,5 @@ __all__ = ['OpenAIAudioModels','NemotronModel','OllamaModel',+ 'GeminiModel',]diff --git a/camel/models/gemini_model.py b/camel/models/gemini_model.pynew file mode 100644index 000000000..8a497a786--- /dev/null+++ b/camel/models/gemini_model.py@@ -0,0 +1,203 @@+# =========== 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 TYPE_CHECKING, Any, Dict, List, Optional++from camel.configs import Gemini_API_PARAMS+from camel.messages import OpenAIMessage+from camel.models import BaseModelBackend+from camel.types import (+ ChatCompletion,+ ChatCompletionMessage,+ Choice,+ ModelType,+)+from camel.utils import (+ BaseTokenCounter,+ GeminiTokenCounter,+ api_keys_required,+)++if TYPE_CHECKING:+ from google.generativeai.types import ContentsType, GenerateContentResponse+++class GeminiModel(BaseModelBackend):+ r"""Gemini API in a unified BaseModelBackend interface."""++ # NOTE: Currently "stream": True is not supported with Gemini due to the+ # limitation of the current camel design.++ def __init__(+ self,+ model_type: ModelType,+ model_config_dict: Dict[str, Any],+ api_key: Optional[str] = None,+ url: Optional[str] = None,+ ) -> None:+ r"""Constructor for Gemini backend.++ Args:+ model_type (ModelType): Model for which a backend is created.+ model_config_dict (Dict[str, Any]): A dictionary that will+ be fed into generate_content().+ api_key (Optional[str]): The API key for authenticating with the+ gemini service. (default: :obj:`None`)+ url (Optional[str]): The url to the gemini service.+ """+ import os++ import google.generativeai as genai+ from google.generativeai.types.generation_types import GenerationConfig++ super().__init__(model_type, model_config_dict, api_key, url)+ self._api_key = api_key or os.environ.get("GOOGLE_API_KEY")+ genai.configure(api_key=self._api_key)+ self._client = genai.GenerativeModel(self.model_type.value)+ self._token_counter: Optional[BaseTokenCounter] = None+ keys = list(self.model_config_dict.keys())+ generation_config_dict = {+ k: self.model_config_dict.pop(k)+ for k in keys+ if hasattr(GenerationConfig, k)+ }+ generation_config = genai.types.GenerationConfig(+ **generation_config_dict+ )+ self.model_config_dict["generation_config"] = generation_config++ @property+ def token_counter(self) -> BaseTokenCounter:+ if not self._token_counter:+ self._token_counter = GeminiTokenCounter(self.model_type)+ return self._token_counter++ @api_keys_required("GOOGLE_API_KEY")+ def run(+ self,+ messages: List[OpenAIMessage],+ ) -> ChatCompletion:+ r"""Runs inference of Gemini model.+ This method can handle multimodal input++ Args:+ messages: Message list or Message with the chat history+ in OpenAi format.++ Returns:+ response: A ChatCompletion object formatted for the OpenAI API.+ """+ response = self._client.generate_content(+ contents=self.to_gemini_req(messages),+ **self.model_config_dict,+ )+ response.resolve()+ return self.to_openai_response(response)++ def check_model_config(self):+ r"""Check whether the model configuration contains any+ unexpected arguments to Gemini API.++ Raises:+ ValueError: If the model configuration dictionary contains any+ unexpected arguments to OpenAI API.+ """+ if self.model_config_dict is not None:+ for param in self.model_config_dict:+ if param not in Gemini_API_PARAMS:+ raise ValueError(+ f"Unexpected argument `{param}` is "+ "input into Gemini model backend."+ )++ @property+ def stream(self) -> bool:+ r"""Returns whether the model is in stream mode,+ which sends partial results each time.++ Returns:+ bool: Whether the model is in stream mode.+ """+ return self.model_config_dict.get('stream', False)++ def to_gemini_req(self, messages: List[OpenAIMessage]) -> 'ContentsType':+ r"""Converts the request from the OpenAI API format to+ the Gemini API request format.++ Args:+ messages: The request object from the OpenAI API.++ Returns:+ converted_messages: A list of messages formatted for Gemini API.+ """+ # role reference+ # https://ai.google.dev/api/python/google/generativeai/protos/Content+ converted_messages = []+ for message in messages:+ role = message.get('role')+ if role == 'assistant':+ role_to_gemini = 'model'+ else:+ role_to_gemini = 'user'+ converted_message = {+ "role": role_to_gemini,+ "parts": message.get("content"),+ }+ converted_messages.append(converted_message)+ return converted_messages++ def to_openai_response(+ self,+ response: 'GenerateContentResponse',+ ) -> ChatCompletion:+ r"""Converts the response from the Gemini API to the OpenAI API+ response format.++ Args:+ response: The response object returned by the Gemini API++ Returns:+ openai_response: A ChatCompletion object formatted for+ the OpenAI API.+ """+ import time+ import uuid++ openai_response = ChatCompletion(+ id=f"chatcmpl-{uuid.uuid4().hex!s}",+ object="chat.completion",+ created=int(time.time()),+ model=self.model_type.value,+ choices=[],+ )+ for i, candidate in enumerate(response.candidates):+ content = ""+ if candidate.content and len(candidate.content.parts) > 0:+ content = candidate.content.parts[0].text+ finish_reason = candidate.finish_reason+ finish_reason_mapping = {+ "FinishReason.STOP": "stop",+ "FinishReason.SAFETY": "content_filter",+ "FinishReason.RECITATION": "content_filter",+ "FinishReason.MAX_TOKENS": "length",+ }+ finish_reason = finish_reason_mapping.get(finish_reason, "stop")+ choice = Choice(+ index=i,+ message=ChatCompletionMessage(+ role="assistant", content=content+ ),+ finish_reason=finish_reason,+ )+ openai_response.choices.append(choice)+ return openai_responsediff --git a/camel/models/model_factory.py b/camel/models/model_factory.pyindex b56f9df2d..da1cfd234 100644--- a/camel/models/model_factory.py+++ b/camel/models/model_factory.py@@ -15,6 +15,7 @@ from typing import Any, Dict, Optional, Unionfrom camel.models.anthropic_model import AnthropicModelfrom camel.models.base_model import BaseModelBackend+from camel.models.gemini_model import GeminiModelfrom camel.models.litellm_model import LiteLLMModelfrom camel.models.ollama_model import OllamaModelfrom camel.models.open_source_model import OpenSourceModel@@ -59,7 +60,6 @@ class ModelFactory:BaseModelBackend: The initialized backend."""model_class: Any-if isinstance(model_type, ModelType):if model_platform.is_open_source and model_type.is_open_source:model_class = OpenSourceModel@@ -70,6 +70,8 @@ class ModelFactory:model_class = AnthropicModelelif model_platform.is_zhipuai and model_type.is_zhipuai:model_class = ZhipuAIModel+ elif model_platform.is_gemini and model_type.is_gemini:+ model_class = GeminiModelelif model_type == ModelType.STUB:model_class = StubModelelse:@@ -90,5 +92,4 @@ class ModelFactory:)else:raise ValueError(f"Invalid model type `{model_type}` provided.")-return model_class(model_type, model_config_dict, api_key, url)diff --git a/camel/types/enums.py b/camel/types/enums.pyindex f3b1328d3..e13d3163d 100644--- a/camel/types/enums.py+++ b/camel/types/enums.py@@ -58,6 +58,10 @@ class ModelType(Enum):# Nvidia modelsNEMOTRON_4_REWARD = "nvidia/nemotron-4-340b-reward"+ # Gemini models+ GEMINI_1_5_FLASH = "gemini-1.5-flash"+ GEMINI_1_5_PRO = "gemini-1.5-pro"+@propertydef value_for_tiktoken(self) -> str:return (@@ -126,6 +130,10 @@ class ModelType(Enum):ModelType.NEMOTRON_4_REWARD,}+ @property+ def is_gemini(self) -> bool:+ return self in {ModelType.GEMINI_1_5_FLASH, ModelType.GEMINI_1_5_PRO}+@propertydef token_limit(self) -> int:r"""Returns the maximum token limit for a given model.@@ -142,6 +150,10 @@ class ModelType(Enum):return 128000elif self is ModelType.GPT_4O:return 128000+ elif self == ModelType.GEMINI_1_5_FLASH:+ return 1048576+ elif self == ModelType.GEMINI_1_5_PRO:+ return 1048576elif self == ModelType.GLM_4_OPEN_SOURCE:return 8192elif self == ModelType.GLM_3_TURBO:@@ -331,6 +343,7 @@ class ModelPlatformType(Enum):LITELLM = "litellm"ZHIPU = "zhipuai"DEFAULT = "default"+ GEMINI = "gemini"@propertydef is_openai(self) -> bool:@@ -367,6 +380,11 @@ class ModelPlatformType(Enum):r"""Returns whether this platform is opensource."""return self is ModelPlatformType.OPENSOURCE+ @property+ def is_gemini(self) -> bool:+ r"""Returns whether this platform is Gemini."""+ return self is ModelPlatformType.GEMINI+class AudioModelType(Enum):TTS_1 = "tts-1"diff --git a/camel/utils/__init__.py b/camel/utils/__init__.pyindex 26e793123..bb99a2e8d 100644--- a/camel/utils/__init__.py+++ b/camel/utils/__init__.py@@ -32,6 +32,7 @@ from .constants import Constantsfrom .token_counting import (AnthropicTokenCounter,BaseTokenCounter,+ GeminiTokenCounter,LiteLLMTokenCounter,OpenAITokenCounter,OpenSourceTokenCounter,@@ -60,4 +61,5 @@ __all__ = ['dependencies_required','api_keys_required','is_docker_running',+ 'GeminiTokenCounter',]diff --git a/camel/utils/token_counting.py b/camel/utils/token_counting.pyindex 49a4df0d8..0a63d821f 100644--- a/camel/utils/token_counting.py+++ b/camel/utils/token_counting.py@@ -342,6 +342,40 @@ class AnthropicTokenCounter(BaseTokenCounter):return num_tokens+class GeminiTokenCounter(BaseTokenCounter):+ def __init__(self, model_type: ModelType):+ r"""Constructor for the token counter for Gemini models."""+ import google.generativeai as genai++ self.model_type = model_type+ self._client = genai.GenerativeModel(self.model_type.value)++ def count_tokens_from_messages(self, messages: List[OpenAIMessage]) -> int:+ r"""Count number of tokens in the provided message list using+ loaded tokenizer specific for this type of model.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ int: Number of tokens in the messages.+ """+ converted_messages = []+ for message in messages:+ role = message.get('role')+ if role == 'assistant':+ role_to_gemini = 'model'+ else:+ role_to_gemini = 'user'+ converted_message = {+ "role": role_to_gemini,+ "parts": message.get("content"),+ }+ converted_messages.append(converted_message)+ return self._client.count_tokens(converted_messages).total_tokens++class LiteLLMTokenCounter:def __init__(self, model_type: str):r"""Constructor for the token counter for LiteLLM models.diff --git a/examples/models/gemini_model_example.py b/examples/models/gemini_model_example.pynew file mode 100644index 000000000..8e470a440--- /dev/null+++ b/examples/models/gemini_model_example.py@@ -0,0 +1,52 @@+# =========== 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 camel.agents import ChatAgent+from camel.configs import GeminiConfig+from camel.messages import BaseMessage+from camel.models import ModelFactory+from camel.types import ModelPlatformType, ModelType++model = ModelFactory.create(+ model_platform=ModelPlatformType.GEMINI,+ model_type=ModelType.GEMINI_1_5_PRO,+ model_config_dict=GeminiConfig(temperature=0.2).__dict__,+)++# Define system message+sys_msg = BaseMessage.make_assistant_message(+ role_name="Assistant",+ content="You are a helpful assistant.",+)++# Set agent+camel_agent = ChatAgent(system_message=sys_msg, model=model)++user_msg = BaseMessage.make_user_message(+ role_name="User",+ content="""Say hi to CAMEL AI, one open-source community dedicated to the+ study of autonomous and communicative agents.""",+)++# Get response information+response = camel_agent.step(user_msg)+print(response.msgs[0].content)+'''+===============================================================================+Hi CAMEL AI! š++It's great to see a community dedicated to the fascinating field of autonomous+and communicative agents. I'm excited to see what groundbreaking work you're+doing in this area. Keep up the great work! š¤+===============================================================================+'''diff --git a/examples/models/role_playing_with_gemini.py b/examples/models/role_playing_with_gemini.pynew file mode 100644index 000000000..fdb4e8cda--- /dev/null+++ b/examples/models/role_playing_with_gemini.py@@ -0,0 +1,102 @@+# =========== 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 colorama import Fore++from camel.configs import GeminiConfig+from camel.models import ModelFactory+from camel.societies import RolePlaying+from camel.types import ModelPlatformType, ModelType+from camel.utils import print_text_animated+++def main(model_type=None) -> None:+ task_prompt = "Develop a trading bot for the stock market"++ agent_kwargs = {+ role: ModelFactory.create(+ model_platform=ModelPlatformType.GEMINI,+ model_type=model_type,+ model_config_dict=GeminiConfig().__dict__,+ )+ for role in ["assistant", "user", "task-specify"]+ }++ role_play_session = RolePlaying(+ assistant_role_name="Python Programmer",+ assistant_agent_kwargs={'model': agent_kwargs["assistant"]},+ user_role_name="Stock Trader",+ user_agent_kwargs={'model': agent_kwargs["assistant"]},+ task_prompt=task_prompt,+ with_task_specify=True,+ task_specify_agent_kwargs={'model': agent_kwargs["task-specify"]},+ )++ print(+ Fore.GREEN+ + f"AI Assistant sys message:\n{role_play_session.assistant_sys_msg}\n"+ )+ print(+ Fore.BLUE + f"AI User sys message:\n{role_play_session.user_sys_msg}\n"+ )++ print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")+ print(+ Fore.CYAN+ + "Specified task prompt:"+ + f"\n{role_play_session.specified_task_prompt}\n"+ )+ print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")++ chat_turn_limit, n = 50, 0+ input_msg = role_play_session.init_chat()+ while n < chat_turn_limit:+ n += 1+ assistant_response, user_response = role_play_session.step(input_msg)++ if assistant_response.terminated:+ print(+ Fore.GREEN+ + (+ "AI Assistant terminated. Reason: "+ f"{assistant_response.info['termination_reasons']}."+ )+ )+ break+ if user_response.terminated:+ print(+ Fore.GREEN+ + (+ "AI User terminated. "+ f"Reason: {user_response.info['termination_reasons']}."+ )+ )+ break++ print_text_animated(+ Fore.BLUE + f"AI User:\n\n{user_response.msg.content}\n"+ )+ print_text_animated(+ Fore.GREEN + "AI Assistant:\n\n"+ f"{assistant_response.msg.content}\n"+ )++ if "CAMEL_TASK_DONE" in user_response.msg.content:+ break++ input_msg = assistant_response.msg+++if __name__ == "__main__":+ main(model_type=ModelType.GEMINI_1_5_FLASH)diff --git a/poetry.lock b/poetry.lockindex 8d0e015ee..dffe71ef3 100644--- a/poetry.lock+++ b/poetry.lock@@ -423,6 +423,17 @@ charset-normalizer = ["charset-normalizer"]html5lib = ["html5lib"]lxml = ["lxml"]+[[package]]+name = "cachetools"+version = "5.3.3"+description = "Extensible memoizing collections and decorators"+optional = true+python-versions = ">=3.7"+files = [+ {file = "cachetools-5.3.3-py3-none-any.whl", hash = "sha256:0abad1021d3f8325b2fc1d2e9c8b9c9d57b04c3932657a72465447332c24d945"},+ {file = "cachetools-5.3.3.tar.gz", hash = "sha256:ba29e2dfa0b8b556606f097407ed1aa62080ee108ab0dc5ec9d6a723a007d105"},+]+[[package]]name = "certifi"version = "2024.7.4"@@ -1649,6 +1660,150 @@ files = [{file = "geojson-2.5.0.tar.gz", hash = "sha256:6e4bb7ace4226a45d9c8c8b1348b3fc43540658359f93c3f7e03efa9f15f658a"},]+[[package]]+name = "google-ai-generativelanguage"+version = "0.6.4"+description = "Google Ai Generativelanguage API client library"+optional = true+python-versions = ">=3.7"+files = [+ {file = "google-ai-generativelanguage-0.6.4.tar.gz", hash = "sha256:1750848c12af96cb24ae1c3dd05e4bfe24867dc4577009ed03e1042d8421e874"},+ {file = "google_ai_generativelanguage-0.6.4-py3-none-any.whl", hash = "sha256:730e471aa549797118fb1c88421ba1957741433ada575cf5dd08d3aebf903ab1"},+]++[package.dependencies]+google-api-core = {version = ">=1.34.1,<2.0.dev0 || >=2.11.dev0,<3.0.0dev", extras = ["grpc"]}+google-auth = ">=2.14.1,<2.24.0 || >2.24.0,<2.25.0 || >2.25.0,<3.0.0dev"+proto-plus = ">=1.22.3,<2.0.0dev"+protobuf = ">=3.19.5,<3.20.0 || >3.20.0,<3.20.1 || >3.20.1,<4.21.0 || >4.21.0,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4.21.3 || >4.21.3,<4.21.4 || >4.21.4,<4.21.5 || >4.21.5,<5.0.0dev"++[[package]]+name = "google-api-core"+version = "2.19.1"+description = "Google API client core library"+optional = true+python-versions = ">=3.7"+files = [+ {file = "google-api-core-2.19.1.tar.gz", hash = "sha256:f4695f1e3650b316a795108a76a1c416e6afb036199d1c1f1f110916df479ffd"},+ {file = "google_api_core-2.19.1-py3-none-any.whl", hash = "sha256:f12a9b8309b5e21d92483bbd47ce2c445861ec7d269ef6784ecc0ea8c1fa6125"},+]++[package.dependencies]+google-auth = ">=2.14.1,<3.0.dev0"+googleapis-common-protos = ">=1.56.2,<2.0.dev0"+grpcio = [+ {version = ">=1.33.2,<2.0dev", optional = true, markers = "python_version < \"3.11\" and extra == \"grpc\""},+ {version = ">=1.49.1,<2.0dev", optional = true, markers = "python_version >= \"3.11\" and extra == \"grpc\""},+]+grpcio-status = [+ {version = ">=1.33.2,<2.0.dev0", optional = true, markers = "python_version < \"3.11\" and extra == \"grpc\""},+ {version = ">=1.49.1,<2.0.dev0", optional = true, markers = "python_version >= \"3.11\" and extra == \"grpc\""},+]+proto-plus = ">=1.22.3,<2.0.0dev"+protobuf = ">=3.19.5,<3.20.0 || >3.20.0,<3.20.1 || >3.20.1,<4.21.0 || >4.21.0,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4.21.3 || >4.21.3,<4.21.4 || >4.21.4,<4.21.5 || >4.21.5,<6.0.0.dev0"+requests = ">=2.18.0,<3.0.0.dev0"++[package.extras]+grpc = ["grpcio (>=1.33.2,<2.0dev)", "grpcio (>=1.49.1,<2.0dev)", "grpcio-status (>=1.33.2,<2.0.dev0)", "grpcio-status (>=1.49.1,<2.0.dev0)"]+grpcgcp = ["grpcio-gcp (>=0.2.2,<1.0.dev0)"]+grpcio-gcp = ["grpcio-gcp (>=0.2.2,<1.0.dev0)"]++[[package]]+name = "google-api-python-client"+version = "2.136.0"+description = "Google API Client Library for Python"+optional = true+python-versions = ">=3.7"+files = [+ {file = "google-api-python-client-2.136.0.tar.gz", hash = "sha256:161c722c8864e7ed39393e2b7eea76ef4e1c933a6a59f9d7c70409b6635f225d"},+ {file = "google_api_python_client-2.136.0-py2.py3-none-any.whl", hash = "sha256:5a554c8b5edf0a609b905d89d7ced82e8f6ac31da1e4d8d5684ef63dbc0e49f5"},+]++[package.dependencies]+google-api-core = ">=1.31.5,<2.0.dev0 || >2.3.0,<3.0.0.dev0"+google-auth = ">=1.32.0,<2.24.0 || >2.24.0,<2.25.0 || >2.25.0,<3.0.0.dev0"+google-auth-httplib2 = ">=0.2.0,<1.0.0"+httplib2 = ">=0.19.0,<1.dev0"+uritemplate = ">=3.0.1,<5"++[[package]]+name = "google-auth"+version = "2.31.0"+description = "Google Authentication Library"+optional = true+python-versions = ">=3.7"+files = [+ {file = "google-auth-2.31.0.tar.gz", hash = "sha256:87805c36970047247c8afe614d4e3af8eceafc1ebba0c679fe75ddd1d575e871"},+ {file = "google_auth-2.31.0-py2.py3-none-any.whl", hash = "sha256:042c4702efa9f7d3c48d3a69341c209381b125faa6dbf3ebe56bc7e40ae05c23"},+]++[package.dependencies]+cachetools = ">=2.0.0,<6.0"+pyasn1-modules = ">=0.2.1"+rsa = ">=3.1.4,<5"++[package.extras]+aiohttp = ["aiohttp (>=3.6.2,<4.0.0.dev0)", "requests (>=2.20.0,<3.0.0.dev0)"]+enterprise-cert = ["cryptography (==36.0.2)", "pyopenssl (==22.0.0)"]+pyopenssl = ["cryptography (>=38.0.3)", "pyopenssl (>=20.0.0)"]+reauth = ["pyu2f (>=0.1.5)"]+requests = ["requests (>=2.20.0,<3.0.0.dev0)"]++[[package]]+name = "google-auth-httplib2"+version = "0.2.0"+description = "Google Authentication Library: httplib2 transport"+optional = true+python-versions = "*"+files = [+ {file = "google-auth-httplib2-0.2.0.tar.gz", hash = "sha256:38aa7badf48f974f1eb9861794e9c0cb2a0511a4ec0679b1f886d108f5640e05"},+ {file = "google_auth_httplib2-0.2.0-py2.py3-none-any.whl", hash = "sha256:b65a0a2123300dd71281a7bf6e64d65a0759287df52729bdd1ae2e47dc311a3d"},+]++[package.dependencies]+google-auth = "*"+httplib2 = ">=0.19.0"++[[package]]+name = "google-generativeai"+version = "0.6.0"+description = "Google Generative AI High level API client library and tools."+optional = true+python-versions = ">=3.9"+files = [+ {file = "google_generativeai-0.6.0-py3-none-any.whl", hash = "sha256:ba1d3b826b872bffe330aaac0dc6de2f0e4610df861c8ce7ec6433771611b676"},+]++[package.dependencies]+google-ai-generativelanguage = "0.6.4"+google-api-core = "*"+google-api-python-client = "*"+google-auth = ">=2.15.0"+protobuf = "*"+pydantic = "*"+tqdm = "*"+typing-extensions = "*"++[package.extras]+dev = ["Pillow", "absl-py", "black", "ipython", "nose2", "pandas", "pytype", "pyyaml"]++[[package]]+name = "googleapis-common-protos"+version = "1.63.2"+description = "Common protobufs used in Google APIs"+optional = true+python-versions = ">=3.7"+files = [+ {file = "googleapis-common-protos-1.63.2.tar.gz", hash = "sha256:27c5abdffc4911f28101e635de1533fb4cfd2c37fbaa9174587c799fac90aa87"},+ {file = "googleapis_common_protos-1.63.2-py2.py3-none-any.whl", hash = "sha256:27a2499c7e8aff199665b22741997e485eccc8645aa9176c7c988e6fae507945"},+]++[package.dependencies]+protobuf = ">=3.20.2,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4.21.3 || >4.21.3,<4.21.4 || >4.21.4,<4.21.5 || >4.21.5,<6.0.0.dev0"++[package.extras]+grpc = ["grpcio (>=1.44.0,<2.0.0.dev0)"]+[[package]]name = "googlemaps"version = "4.10.0"@@ -1781,6 +1936,22 @@ files = [[package.extras]protobuf = ["grpcio-tools (>=1.63.0)"]+[[package]]+name = "grpcio-status"+version = "1.62.2"+description = "Status proto mapping for gRPC"+optional = true+python-versions = ">=3.6"+files = [+ {file = "grpcio-status-1.62.2.tar.gz", hash = "sha256:62e1bfcb02025a1cd73732a2d33672d3e9d0df4d21c12c51e0bbcaf09bab742a"},+ {file = "grpcio_status-1.62.2-py3-none-any.whl", hash = "sha256:206ddf0eb36bc99b033f03b2c8e95d319f0044defae9b41ae21408e7e0cda48f"},+]++[package.dependencies]+googleapis-common-protos = ">=1.5.5"+grpcio = ">=1.62.2"+protobuf = ">=4.21.6"+[[package]]name = "grpcio-tools"version = "1.62.2"@@ -1907,6 +2078,20 @@ http2 = ["h2 (>=3,<5)"]socks = ["socksio (==1.*)"]trio = ["trio (>=0.22.0,<0.26.0)"]+[[package]]+name = "httplib2"+version = "0.22.0"+description = "A comprehensive HTTP client library."+optional = true+python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"+files = [+ {file = "httplib2-0.22.0-py3-none-any.whl", hash = "sha256:14ae0a53c1ba8f3d37e9e27cf37eabb0fb9980f435ba405d546948b009dd64dc"},+ {file = "httplib2-0.22.0.tar.gz", hash = "sha256:d7a10bc5ef5ab08322488bde8c726eeee5c8618723fdb399597ec58f3d82df81"},+]++[package.dependencies]+pyparsing = {version = ">=2.4.2,<3.0.0 || >3.0.0,<3.0.1 || >3.0.1,<3.0.2 || >3.0.2,<3.0.3 || >3.0.3,<4", markers = "python_version > \"3.0\""}+[[package]]name = "httptools"version = "0.6.1"@@ -2575,13 +2760,13 @@ files = [[[package]]name = "litellm"-version = "1.41.7"+version = "1.41.8"description = "Library to easily interface with LLM API providers"optional = truepython-versions = "!=2.7.*,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,!=3.7.*,>=3.8"files = [- {file = "litellm-1.41.7-py3-none-any.whl", hash = "sha256:48806706b26c558299beb93e6f5011b3afa5cd10690d41ef9d8765e4bd83b538"},- {file = "litellm-1.41.7.tar.gz", hash = "sha256:f2ae4544fd98f936510b4ae85191c7b92f249ad395f6056ff6dad03640838b3f"},+ {file = "litellm-1.41.8-py3-none-any.whl", hash = "sha256:57e2968f71445991a403cb029a011b7f454bee1d574881828e52f088092061df"},+ {file = "litellm-1.41.8.tar.gz", hash = "sha256:48914b57ca6d71253f1e9b8d4bde306b2d0dfa506339432a9ba676f896b5ba24"},][package.dependencies]@@ -2962,7 +3147,6 @@ python-versions = ">=3.7"files = [{file = "milvus_lite-2.4.7-py3-none-macosx_10_9_x86_64.whl", hash = "sha256:c828190118b104b05b8c8e0b5a4147811c86b54b8fb67bc2e726ad10fc0b544e"},{file = "milvus_lite-2.4.7-py3-none-macosx_11_0_arm64.whl", hash = "sha256:e1537633c39879714fb15082be56a4b97f74c905a6e98e302ec01320561081af"},- {file = "milvus_lite-2.4.7-py3-none-manylinux2014_aarch64.whl", hash = "sha256:fcb909d38c83f21478ca9cb500c84264f988c69f62715ae9462e966767fb76dd"},{file = "milvus_lite-2.4.7-py3-none-manylinux2014_x86_64.whl", hash = "sha256:f016474d663045787dddf1c3aad13b7d8b61fd329220318f858184918143dcbf"},]@@ -3708,7 +3892,6 @@ optional = truepython-versions = ">=3.6"files = [{file = "opencv-python-4.10.0.84.tar.gz", hash = "sha256:72d234e4582e9658ffea8e9cae5b63d488ad06994ef12d81dc303b17472f3526"},- {file = "opencv_python-4.10.0.84-cp37-abi3-macosx_11_0_arm64.whl", hash = "sha256:fc182f8f4cda51b45f01c64e4cbedfc2f00aff799debebc305d8d0210c43f251"},{file = "opencv_python-4.10.0.84-cp37-abi3-macosx_12_0_x86_64.whl", hash = "sha256:71e575744f1d23f79741450254660442785f45a0797212852ee5199ef12eed98"},{file = "opencv_python-4.10.0.84-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:09a332b50488e2dda866a6c5573ee192fe3583239fb26ff2f7f9ceb0bc119ea6"},{file = "opencv_python-4.10.0.84-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9ace140fc6d647fbe1c692bcb2abce768973491222c067c131d80957c595b71f"},@@ -4145,6 +4328,23 @@ nodeenv = ">=0.11.1"pyyaml = ">=5.1"virtualenv = ">=20.10.0"+[[package]]+name = "proto-plus"+version = "1.24.0"+description = "Beautiful, Pythonic protocol buffers."+optional = true+python-versions = ">=3.7"+files = [+ {file = "proto-plus-1.24.0.tar.gz", hash = "sha256:30b72a5ecafe4406b0d339db35b56c4059064e69227b8c3bda7462397f966445"},+ {file = "proto_plus-1.24.0-py3-none-any.whl", hash = "sha256:402576830425e5f6ce4c2a6702400ac79897dab0b4343821aa5188b0fab81a12"},+]++[package.dependencies]+protobuf = ">=3.19.0,<6.0.0dev"++[package.extras]+testing = ["google-api-core (>=1.31.5)"]+[[package]]name = "protobuf"version = "4.25.3"@@ -4242,6 +4442,31 @@ files = [[package.dependencies]numpy = ">=1.16.6"+[[package]]+name = "pyasn1"+version = "0.6.0"+description = "Pure-Python implementation of ASN.1 types and DER/BER/CER codecs (X.208)"+optional = true+python-versions = ">=3.8"+files = [+ {file = "pyasn1-0.6.0-py2.py3-none-any.whl", hash = "sha256:cca4bb0f2df5504f02f6f8a775b6e416ff9b0b3b16f7ee80b5a3153d9b804473"},+ {file = "pyasn1-0.6.0.tar.gz", hash = "sha256:3a35ab2c4b5ef98e17dfdec8ab074046fbda76e281c5a706ccd82328cfc8f64c"},+]++[[package]]+name = "pyasn1-modules"+version = "0.4.0"+description = "A collection of ASN.1-based protocols modules"+optional = true+python-versions = ">=3.8"+files = [+ {file = "pyasn1_modules-0.4.0-py3-none-any.whl", hash = "sha256:be04f15b66c206eed667e0bb5ab27e2b1855ea54a842e5037738099e8ca4ae0b"},+ {file = "pyasn1_modules-0.4.0.tar.gz", hash = "sha256:831dbcea1b177b28c9baddf4c6d1013c24c3accd14a1873fffaa6a2e905f17b6"},+]++[package.dependencies]+pyasn1 = ">=0.4.6,<0.7.0"+[[package]]name = "pycocotools"version = "2.0.8"@@ -4589,7 +4814,6 @@ python-versions = ">=3.8"files = [{file = "PyMuPDFb-1.24.6-py3-none-macosx_10_9_x86_64.whl", hash = "sha256:21e3ed890f736def68b9a031122ae1fb854d5cb9a53aa144b6e2ca3092416a6b"},{file = "PyMuPDFb-1.24.6-py3-none-macosx_11_0_arm64.whl", hash = "sha256:8704d2dfadc9448ce184597d8b0f9c30143e379ac948a517f9c4db7c0c71ed51"},- {file = "PyMuPDFb-1.24.6-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:01662584d5cfa7a91f77585f13fc23a12291cfd76a57e0a28dd5a56bf521cb2c"},{file = "PyMuPDFb-1.24.6-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e1f7657353529ae3f88575c83ee49eac9adea311a034b9c97248a65cee7df0e5"},{file = "PyMuPDFb-1.24.6-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:cebc2cedb870d1e1168e2f502eb06f05938f6df69103b0853a2b329611ec19a7"},{file = "PyMuPDFb-1.24.6-py3-none-win32.whl", hash = "sha256:ac4b865cd1e239db04674f85e02844a0e405f8255ee7a74dfee0d86aad0d3576"},@@ -5540,6 +5764,20 @@ files = [{file = "rpds_py-0.18.1.tar.gz", hash = "sha256:dc48b479d540770c811fbd1eb9ba2bb66951863e448efec2e2c102625328e92f"},]+[[package]]+name = "rsa"+version = "4.9"+description = "Pure-Python RSA implementation"+optional = true+python-versions = ">=3.6,<4"+files = [+ {file = "rsa-4.9-py3-none-any.whl", hash = "sha256:90260d9058e514786967344d0ef75fa8727eed8a7d2e43ce9f4bcf1b536174f7"},+ {file = "rsa-4.9.tar.gz", hash = "sha256:e38464a49c6c85d7f1351b0126661487a7e0a14a50f1675ec50eb34d4f20ef21"},+]++[package.dependencies]+pyasn1 = ">=0.1.3"+[[package]]name = "ruamel-yaml"version = "0.18.6"@@ -7121,6 +7359,17 @@ files = [packaging = ">=21.3"Pillow = ">=8.0.0"+[[package]]+name = "uritemplate"+version = "4.1.1"+description = "Implementation of RFC 6570 URI Templates"+optional = true+python-versions = ">=3.6"+files = [+ {file = "uritemplate-4.1.1-py2.py3-none-any.whl", hash = "sha256:830c08b8d99bdd312ea4ead05994a38e8936266f84b9a7878232db50b044e02e"},+ {file = "uritemplate-4.1.1.tar.gz", hash = "sha256:4346edfc5c3b79f694bccd6d6099a322bbeb628dbf2cd86eea55a456ce5124f0"},+]+[[package]]name = "urllib3"version = "2.2.2"@@ -7783,12 +8032,12 @@ doc = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "rst.linketest = ["big-O", "importlib-resources", "jaraco.functools", "jaraco.itertools", "jaraco.test", "more-itertools", "pytest (>=6,!=8.1.*)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-ignore-flaky", "pytest-mypy", "pytest-ruff (>=0.2.1)"][extras]-all = ["PyMuPDF", "accelerate", "beautifulsoup4", "cohere", "datasets", "diffusers", "discord.py", "docker", "docx2txt", "duckduckgo-search", "googlemaps", "imageio", "litellm", "neo4j", "newspaper3k", "openapi-spec-validator", "opencv-python", "pillow", "prance", "pyTelegramBotAPI", "pydub", "pygithub", "pymilvus", "pyowm", "qdrant-client", "rank-bm25", "redis", "requests_oauthlib", "sentence-transformers", "sentencepiece", "slack-sdk", "soundfile", "torch", "transformers", "unstructured", "wikipedia", "wolframalpha"]+all = ["PyMuPDF", "accelerate", "beautifulsoup4", "cohere", "datasets", "diffusers", "discord.py", "docker", "docx2txt", "duckduckgo-search", "google-generativeai", "googlemaps", "imageio", "litellm", "neo4j", "newspaper3k", "openapi-spec-validator", "opencv-python", "pillow", "prance", "pyTelegramBotAPI", "pydub", "pygithub", "pymilvus", "pyowm", "qdrant-client", "rank-bm25", "redis", "requests_oauthlib", "sentence-transformers", "sentencepiece", "slack-sdk", "soundfile", "torch", "transformers", "unstructured", "wikipedia", "wolframalpha"]encoders = ["sentence-transformers"]graph-storages = ["neo4j"]huggingface-agent = ["accelerate", "datasets", "diffusers", "opencv-python", "sentencepiece", "soundfile", "torch", "transformers"]kv-stroages = ["redis"]-model-platforms = ["litellm"]+model-platforms = ["google-generativeai", "litellm"]retrievers = ["cohere", "rank-bm25"]test = ["mock", "pytest", "pytest-asyncio"]tools = ["PyMuPDF", "beautifulsoup4", "discord.py", "docker", "docx2txt", "duckduckgo-search", "googlemaps", "imageio", "newspaper3k", "openapi-spec-validator", "pillow", "prance", "pyTelegramBotAPI", "pydub", "pygithub", "pyowm", "requests_oauthlib", "slack-sdk", "unstructured", "wikipedia", "wolframalpha"]@@ -7797,4 +8046,4 @@ vector-databases = ["pymilvus", "qdrant-client"][metadata]lock-version = "2.0"python-versions = ">=3.9.0,<3.12"-content-hash = "d51d829d24001375a00fb3e38f3334043b977dcc45cabaf8361c2461deba4347"+content-hash = "9910b484652705430285da59931b5fa7749a9dcd89ccf9ecd046f1762f4e81ca"diff --git a/pyproject.toml b/pyproject.tomlindex 19db9dd19..14e77c130 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -43,6 +43,7 @@ pillow ="^10.2.0"# model-platformslitellm = { version = "^1.38.1", optional = true }+google-generativeai = { version = "^0.6.0", optional = true }# huggingface-agenttransformers = { version = "^4", optional = true }@@ -104,6 +105,7 @@ test = ["pytest", "mock", "pytest-asyncio"]model-platforms = ["litellm",+ "google-generativeai",]huggingface-agent = [@@ -210,6 +212,7 @@ all = ["litellm",# kv-storages"redis",+ "google-generativeai",][tool.poetry.group.dev]@@ -335,5 +338,7 @@ module = ["pyTelegramBotAPI","discord.py","docker.*",+ "google.*",+ "google-generativeai",]ignore_missing_imports = truediff --git a/test/models/test_gemini_model.py b/test/models/test_gemini_model.pynew file mode 100644index 000000000..08d246549--- /dev/null+++ b/test/models/test_gemini_model.py@@ -0,0 +1,60 @@+# =========== 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. ===========+import re++import pytest++from camel.configs import GeminiConfig, OpenSourceConfig+from camel.models import GeminiModel+from camel.types import ModelType+from camel.utils import GeminiTokenCounter++[email protected]_backend+ "model_type",+ [+ ModelType.GEMINI_1_5_FLASH,+ ModelType.GEMINI_1_5_PRO,+ ],+)+def test_gemini_model(model_type):+ model_config_dict = GeminiConfig().__dict__+ model = GeminiModel(model_type, model_config_dict)+ assert model.model_type == model_type+ assert model.model_config_dict == model_config_dict+ assert isinstance(model.token_counter, GeminiTokenCounter)+ assert isinstance(model.model_type.value_for_tiktoken, str)+ assert isinstance(model.model_type.token_limit, int)++[email protected]_backend+def test_gemini_model_unexpected_argument():+ model_type = ModelType.GEMINI_1_5_FLASH+ model_config = OpenSourceConfig(+ model_path="vicuna-7b-v1.5",+ server_url="http://localhost:8000/v1",+ )+ model_config_dict = model_config.__dict__++ with pytest.raises(+ ValueError,+ match=re.escape(+ (+ "Unexpected argument `model_path` is "+ "input into Gemini model backend."+ )+ ),+ ):+ _ = GeminiModel(model_type, model_config_dict)