🐫 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: update aws_bedrock (#1194)
Asher-hssdad6e1ad318e
diff --git a/.env b/.envindex 2eb338bf3..3a5f4facd 100644--- a/.env+++ b/.env@@ -103,5 +103,8 @@# OpenBB Platform API (https://my.openbb.co/app/credentials)# OPENBB_TOKEN="Fill your API key here"+# AWS API (https://aws.amazon.com/)+# AWS_ACCESS_KEY_ID="Fill your Access Key ID here"+# AWS_SECRET_ACCESS_KEY="Fill your Secret Access Key here"# Bocha Platform API(https://open.bochaai.com)# BOCHA_API_KEY="Fill your API key here"\ No newline at end of filediff --git a/.github/workflows/build_package.yml b/.github/workflows/build_package.ymlindex 3e9abe561..c1b7189da 100644--- a/.github/workflows/build_package.yml+++ b/.github/workflows/build_package.yml@@ -104,6 +104,8 @@ jobs:GOOGLE_CLIENT_ID: "${{ secrets.GOOGLE_CLIENT_ID }}"GOOGLE_CLIENT_SECRET: "${{ secrets.GOOGLE_CLIENT_SECRET }}"PPIO_API_KEY: "${{ secrets.PPIO_API_KEY }}"+ BEDROCK_API_KEY: "${{ secrets.BEDROCK_API_KEY }}"+ BEDROCK_API_BASE_URL: "${{ secrets.BEDROCK_API_BASE_URL }}"run: |source test_venv/bin/activatepytest --fast-test-mode ./testdiff --git a/.github/workflows/pytest_package.yml b/.github/workflows/pytest_package.ymlindex 215c51f46..fddf2e711 100644--- a/.github/workflows/pytest_package.yml+++ b/.github/workflows/pytest_package.yml@@ -69,6 +69,8 @@ jobs:GOOGLE_CLIENT_ID: "${{ secrets.GOOGLE_CLIENT_ID }}"GOOGLE_CLIENT_SECRET: "${{ secrets.GOOGLE_CLIENT_SECRET }}"PPIO_API_KEY: "${{ secrets.PPIO_API_KEY }}"+ BEDROCK_API_KEY: "${{ secrets.BEDROCK_API_KEY }}"+ BEDROCK_API_BASE_URL: "${{ secrets.BEDROCK_API_BASE_URL }}"run: |source .venv/bin/activateuv pip install -e ".[all, dev, docs]"@@ -130,6 +132,8 @@ jobs:GOOGLE_CLIENT_ID: "${{ secrets.GOOGLE_CLIENT_ID }}"GOOGLE_CLIENT_SECRET: "${{ secrets.GOOGLE_CLIENT_SECRET }}"PPIO_API_KEY: "${{ secrets.PPIO_API_KEY }}"+ BEDROCK_API_KEY: "${{ secrets.BEDROCK_API_KEY }}"+ BEDROCK_API_BASE_URL: "${{ secrets.BEDROCK_API_BASE_URL }}"run: |source .venv/bin/activateuv pip install -e ".[all, dev, docs]"@@ -189,6 +193,8 @@ jobs:GOOGLE_CLIENT_ID: "${{ secrets.GOOGLE_CLIENT_ID }}"GOOGLE_CLIENT_SECRET: "${{ secrets.GOOGLE_CLIENT_SECRET }}"PPIO_API_KEY: "${{ secrets.PPIO_API_KEY }}"+ BEDROCK_API_KEY: "${{ secrets.BEDROCK_API_KEY }}"+ BEDROCK_API_BASE_URL: "${{ secrets.BEDROCK_API_BASE_URL }}"run: |source .venv/bin/activateuv pip install -e ".[all, dev, docs]"diff --git a/camel/configs/__init__.py b/camel/configs/__init__.pyindex 178a28aac..b0371ce9a 100644--- a/camel/configs/__init__.py+++ b/camel/configs/__init__.py@@ -14,6 +14,7 @@from .aiml_config import AIML_API_PARAMS, AIMLConfigfrom .anthropic_config import ANTHROPIC_API_PARAMS, AnthropicConfigfrom .base_config import BaseConfig+from .bedrock_config import BEDROCK_API_PARAMS, BedrockConfigfrom .cohere_config import COHERE_API_PARAMS, CohereConfigfrom .deepseek_config import DEEPSEEK_API_PARAMS, DeepSeekConfigfrom .gemini_config import Gemini_API_PARAMS, GeminiConfig@@ -81,6 +82,8 @@ __all__ = ['YI_API_PARAMS','QwenConfig','QWEN_API_PARAMS',+ 'BedrockConfig',+ 'BEDROCK_API_PARAMS','DeepSeekConfig','DEEPSEEK_API_PARAMS','PPIOConfig',diff --git a/camel/configs/bedrock_config.py b/camel/configs/bedrock_config.pynew file mode 100644index 000000000..279ccf5ab--- /dev/null+++ b/camel/configs/bedrock_config.py@@ -0,0 +1,36 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========+from typing import Optional++from camel.configs.base_config import BaseConfig+++class BedrockConfig(BaseConfig):+ r"""Defines the parameters for generating chat completions using Bedrock+ compatibility.++ Args:+ maxTokens (int, optional): The maximum number of tokens.+ temperatue (float, optional): Controls the randomness of the output.+ top_p (float, optional): Use nucleus sampling.+ top_k (int, optional): The number of top tokens to consider.+ """++ max_tokens: Optional[int] = None+ temperature: Optional[float] = None+ top_p: Optional[float] = None+ top_k: Optional[int] = None+++BEDROCK_API_PARAMS = {param for param in BedrockConfig.model_fields.keys()}diff --git a/camel/models/__init__.py b/camel/models/__init__.pyindex 0f77c3f0b..86236415d 100644--- a/camel/models/__init__.py+++ b/camel/models/__init__.py@@ -13,6 +13,7 @@# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========from .aiml_model import AIMLModelfrom .anthropic_model import AnthropicModel+from .aws_bedrock_model import AWSBedrockModelfrom .azure_openai_model import AzureOpenAIModelfrom .base_audio_model import BaseAudioModelfrom .base_model import BaseModelBackend@@ -76,6 +77,7 @@ __all__ = ['PPIOModel','YiModel','QwenModel',+ 'AWSBedrockModel','ModelProcessingError','DeepSeekModel','FishAudioModel',diff --git a/camel/models/aws_bedrock_model.py b/camel/models/aws_bedrock_model.pynew file mode 100644index 000000000..bee836ed4--- /dev/null+++ b/camel/models/aws_bedrock_model.py@@ -0,0 +1,111 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========++import os+from typing import Any, Dict, List, Optional, Type, Union++from openai import AsyncStream+from pydantic import BaseModel++from camel.configs import BEDROCK_API_PARAMS, BedrockConfig+from camel.messages import OpenAIMessage+from camel.models.openai_compatible_model import OpenAICompatibleModel+from camel.types import (+ ChatCompletion,+ ChatCompletionChunk,+ ModelType,+)+from camel.utils import BaseTokenCounter, api_keys_required+++class AWSBedrockModel(OpenAICompatibleModel):+ r"""AWS Bedrock API in a unified OpenAICompatibleModel interface.++ Args:+ model_type (Union[ModelType, str]): Model for which a backend is+ created.+ model_config_dict (Dict[str, Any], optional): A dictionary+ that will be fed into:obj:`openai.ChatCompletion.create()`.+ If:obj:`None`, :obj:`BedrockConfig().as_dict()` will be used.+ (default: :obj:`None`)+ api_key (str, optional): The API key for authenticating with+ the AWS Bedrock service. (default: :obj:`None`)+ url (str, optional): The url to the AWS Bedrock service.+ token_counter (BaseTokenCounter, optional): Token counter to+ use for the model. If not provided, :obj:`OpenAITokenCounter(+ ModelType.GPT_4O_MINI)` will be used.+ (default: :obj:`None`)+ timeout (Optional[float], optional): The timeout value in seconds for+ API calls. If not provided, will fall back to the MODEL_TIMEOUT+ environment variable or default to 180 seconds.+ (default: :obj:`None`)+ References:+ https://docs.aws.amazon.com/bedrock/latest/APIReference/welcome.html+ """++ @api_keys_required(+ [+ ("url", "BEDROCK_API_BASE_URL"),+ ("api_key", "BEDROCK_API_KEY"),+ ]+ )+ def __init__(+ self,+ model_type: Union[ModelType, str],+ model_config_dict: Optional[Dict[str, Any]] = None,+ api_key: Optional[str] = None,+ url: Optional[str] = None,+ token_counter: Optional[BaseTokenCounter] = None,+ timeout: Optional[float] = None,+ ) -> None:+ if model_config_dict is None:+ model_config_dict = BedrockConfig().as_dict()+ api_key = api_key or os.environ.get("BEDROCK_API_KEY")+ url = url or os.environ.get(+ "BEDROCK_API_BASE_URL",+ )+ timeout = timeout or float(os.environ.get("MODEL_TIMEOUT", 180))+ super().__init__(+ model_type=model_type,+ model_config_dict=model_config_dict,+ api_key=api_key,+ url=url,+ token_counter=token_counter,+ timeout=timeout,+ )++ async def _arun(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ raise NotImplementedError(+ "AWS Bedrock does not support async inference."+ )++ def check_model_config(self):+ r"""Check whether the input model configuration contains unexpected+ arguments.++ Raises:+ ValueError: If the model configuration dictionary contains any+ unexpected argument for this model class.+ """+ for param in self.model_config_dict:+ if param not in BEDROCK_API_PARAMS:+ raise ValueError(+ f"Invalid parameter '{param}' in model_config_dict. "+ f"Valid parameters are: {BEDROCK_API_PARAMS}"+ )diff --git a/camel/models/model_factory.py b/camel/models/model_factory.pyindex 8e13ec68b..aa6d6d24b 100644--- a/camel/models/model_factory.py+++ b/camel/models/model_factory.py@@ -18,6 +18,7 @@ import yamlfrom camel.models.aiml_model import AIMLModelfrom camel.models.anthropic_model import AnthropicModel+from camel.models.aws_bedrock_model import AWSBedrockModelfrom camel.models.azure_openai_model import AzureOpenAIModelfrom camel.models.base_model import BaseModelBackendfrom camel.models.cohere_model import CohereModel@@ -111,6 +112,8 @@ class ModelFactory:model_class = TogetherAIModelelif model_platform.is_litellm:model_class = LiteLLMModel+ elif model_platform.is_aws_bedrock:+ model_class = AWSBedrockModelelif model_platform.is_nvidia:model_class = NvidiaModelelif model_platform.is_siliconflow:diff --git a/camel/types/enums.py b/camel/types/enums.pyindex 2adeb50cb..3aa124498 100644--- a/camel/types/enums.py+++ b/camel/types/enums.py@@ -43,6 +43,15 @@ class ModelType(UnifiedModelType, Enum):GPT_4_1_MINI = "gpt-4.1-mini-2025-04-14"GPT_4_1_NANO = "gpt-4.1-nano-2025-04-14"+ AWS_CLAUDE_3_7_SONNET = "anthropic.claude-3-7-sonnet-20250219-v1:0"+ AWS_CLAUDE_3_5_SONNET = "anthropic.claude-3-5-sonnet-20241022-v2:0"+ AWS_CLAUDE_3_HAIKU = "anthropic.claude-3-haiku-20240307-v1:0"+ AWS_CLAUDE_3_SONNET = "anthropic.claude-3-sonnet-20240229-v1:0"+ AWS_DEEPSEEK_R1 = "us.deepseek.r1-v1:0"+ AWS_LLAMA_3_3_70B_INSTRUCT = "us.meta.llama3-3-70b-instruct-v1:0"+ AWS_LLAMA_3_2_90B_INSTRUCT = "us.meta.llama3-2-90b-instruct-v1:0"+ AWS_LLAMA_3_2_11B_INSTRUCT = "us.meta.llama3-2-11b-instruct-v1:0"+GLM_4 = "glm-4"GLM_4V = "glm-4v"GLM_4V_FLASH = "glm-4v-flash"@@ -337,6 +346,20 @@ class ModelType(UnifiedModelType, Enum):ModelType.GPT_4_1_NANO,}+ @property+ def is_aws_bedrock(self) -> bool:+ r"""Returns whether this type of models is an AWS Bedrock model."""+ return self in {+ ModelType.AWS_CLAUDE_3_7_SONNET,+ ModelType.AWS_CLAUDE_3_5_SONNET,+ ModelType.AWS_CLAUDE_3_HAIKU,+ ModelType.AWS_CLAUDE_3_SONNET,+ ModelType.AWS_DEEPSEEK_R1,+ ModelType.AWS_LLAMA_3_3_70B_INSTRUCT,+ ModelType.AWS_LLAMA_3_2_90B_INSTRUCT,+ ModelType.AWS_LLAMA_3_2_11B_INSTRUCT,+ }+@propertydef is_azure_openai(self) -> bool:r"""Returns whether this type of models is an OpenAI-released model@@ -765,6 +788,7 @@ class ModelType(UnifiedModelType, Enum):ModelType.PPIO_DEEPSEEK_V3_COMMUNITY,ModelType.PPIO_DEEPSEEK_R1,ModelType.PPIO_DEEPSEEK_V3,+ ModelType.AWS_DEEPSEEK_R1,}:return 64_000elif self in {@@ -811,6 +835,9 @@ class ModelType(UnifiedModelType, Enum):ModelType.GLM_4_AIR_0111,ModelType.GLM_4_FLASHX,ModelType.GLM_4_FLASH,+ ModelType.AWS_LLAMA_3_3_70B_INSTRUCT,+ ModelType.AWS_LLAMA_3_2_90B_INSTRUCT,+ ModelType.AWS_LLAMA_3_2_11B_INSTRUCT,}:return 128_000elif self in {@@ -841,6 +868,10 @@ class ModelType(UnifiedModelType, Enum):ModelType.CLAUDE_3_5_HAIKU,ModelType.CLAUDE_3_7_SONNET,ModelType.YI_MEDIUM_200K,+ ModelType.AWS_CLAUDE_3_5_SONNET,+ ModelType.AWS_CLAUDE_3_HAIKU,+ ModelType.AWS_CLAUDE_3_SONNET,+ ModelType.AWS_CLAUDE_3_7_SONNET,}:return 200_000elif self in {@@ -1034,6 +1065,7 @@ class ModelPlatformType(Enum):DEFAULT = os.getenv("DEFAULT_MODEL_PLATFORM_TYPE", "openai")OPENAI = "openai"+ AWS_BEDROCK = "aws-bedrock"AZURE = "azure"ANTHROPIC = "anthropic"GROQ = "groq"@@ -1075,6 +1107,11 @@ class ModelPlatformType(Enum):r"""Returns whether this platform is openai."""return self is ModelPlatformType.OPENAI+ @property+ def is_aws_bedrock(self) -> bool:+ r"""Returns whether this platform is aws-bedrock."""+ return self is ModelPlatformType.AWS_BEDROCK+@propertydef is_azure(self) -> bool:r"""Returns whether this platform is azure."""diff --git a/camel/types/unified_model_type.py b/camel/types/unified_model_type.pyindex f2ee08f50..21ca20f38 100644--- a/camel/types/unified_model_type.py+++ b/camel/types/unified_model_type.py@@ -63,6 +63,11 @@ class UnifiedModelType(str):r"""Returns whether the model is an OpenAI model."""return True+ @property+ def is_aws_bedrock(self) -> bool:+ r"""Returns whether the model is an AWS Bedrock model."""+ return True+@propertydef is_anthropic(self) -> bool:r"""Returns whether the model is an Anthropic model."""diff --git a/docs/key_modules/models.md b/docs/key_modules/models.mdindex 90589f089..ec152a39e 100644--- a/docs/key_modules/models.md+++ b/docs/key_modules/models.md@@ -37,6 +37,8 @@ CAMEL supports a wide range of models, including [OpenAI’s GPT series](https:/| **NVIDIA** | [supported models](https://docs.api.nvidia.com/nim/reference/llm-apis) || **AIML** | [supported models](https://docs.aimlapi.com/api-overview/model-database/text-models) || **ModelScope** | [supported models](https://www.modelscope.cn/docs/model-service/API-Inference/intro) |+| **AWS Bedrock** | [supported models](https://us-west-2.console.aws.amazon.com/bedrock/home?region=us-west-2#/) |+## 3. How to Use Models via API Callsdiff --git a/examples/models/aws_bedrock_model_example.py b/examples/models/aws_bedrock_model_example.pynew file mode 100644index 000000000..adeefee6c--- /dev/null+++ b/examples/models/aws_bedrock_model_example.py@@ -0,0 +1,45 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========++from camel.agents import ChatAgent+from camel.configs import BedrockConfig+from camel.models import ModelFactory+from camel.types import ModelPlatformType, ModelType++model = ModelFactory.create(+ model_platform=ModelPlatformType.AWS_BEDROCK,+ model_type=ModelType.AWS_LLAMA_3_3_70B_INSTRUCT,+ model_config_dict=BedrockConfig(temperature=0.2).as_dict(),+)++camel_agent = ChatAgent(model=model)++user_msg = """Say hi to CAMEL AI, one open-source community dedicated to the+ study of autonomous and communicative agents."""++response = camel_agent.step(user_msg)+print(response.msgs[0].content)+'''+===============================================================================+Hi CAMEL AI community! It's great to see a dedicated group of individuals+passionate about the study of autonomous and communicative agents. Your+open-source community is a fantastic platform for collaboration, knowledge+sharing, and innovation in this exciting field. I'm happy to interact with you+and provide assistance on any topics related to autonomous agents, natural+language processing, or artificial intelligence in general. Feel free to ask+me any questions, share your projects, or discuss the latest advancements in+the field. Let's explore the possibilities of autonomous and communicative+agents together!+===============================================================================+'''diff --git a/test/models/test_aws_bedrock_model.py b/test/models/test_aws_bedrock_model.pynew file mode 100644index 000000000..aa30d7936--- /dev/null+++ b/test/models/test_aws_bedrock_model.py@@ -0,0 +1,78 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========++import re++import pytest++from camel.configs import BedrockConfig+from camel.models import AWSBedrockModel+from camel.types import ModelType+from camel.utils import OpenAITokenCounter++[email protected]_backend+ "model_type",+ [+ ModelType.AWS_CLAUDE_3_7_SONNET,+ ModelType.AWS_CLAUDE_3_5_SONNET,+ ModelType.AWS_CLAUDE_3_HAIKU,+ ModelType.AWS_CLAUDE_3_SONNET,+ ModelType.AWS_DEEPSEEK_R1,+ ModelType.AWS_LLAMA_3_3_70B_INSTRUCT,+ ModelType.AWS_LLAMA_3_2_90B_INSTRUCT,+ ModelType.AWS_LLAMA_3_2_11B_INSTRUCT,+ ],+)+def test_aws_bedrock_model(model_type: ModelType):+ """Test AWSBedrockModel initialization with different model types."""+ model = AWSBedrockModel(model_type)+ assert model.model_type == model_type+ assert model.model_config_dict == BedrockConfig().as_dict()+ assert isinstance(model.token_counter, OpenAITokenCounter)+ assert isinstance(model.model_type.value_for_tiktoken, str)+ assert isinstance(model.model_type.token_limit, int)++[email protected]_backend+def test_aws_bedrock_model_unexpected_argument():+ """Test AWSBedrockModel with unexpected arguments."""+ model_type = ModelType.AWS_CLAUDE_3_HAIKU+ model_config_dict = {"model_path": "claude-3-haiku"}++ with pytest.raises(+ ValueError,+ match=re.escape(+ (+ "Invalid parameter 'model_path' in model_config_dict. "+ "Valid parameters are: "+ )+ + ".+" # Match any characters after the message start+ ),+ ):+ _ = AWSBedrockModel(model_type, model_config_dict)++[email protected]_backend+async def test_aws_bedrock_async_not_implemented():+ """Test AWSBedrockModel async method raising NotImplementedError."""+ model = AWSBedrockModel(ModelType.AWS_CLAUDE_3_HAIKU)++ with pytest.raises(+ NotImplementedError,+ match="AWS Bedrock does not support async inference."+ ):+ await model.agenerate("Test message")