🐫 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
Add Volcano Engine integration support (for owl) (#1813)
Ruby-a07492e16f6ca93
diff --git a/camel/models/__init__.py b/camel/models/__init__.pyindex 8d4c241df..4d539ce61 100644--- a/camel/models/__init__.py+++ b/camel/models/__init__.py@@ -37,9 +37,11 @@ from .qwen_model import QwenModelfrom .reka_model import RekaModelfrom .samba_model import SambaModelfrom .sglang_model import SGLangModel+from .siliconflow_model import SiliconFlowModelfrom .stub_model import StubModelfrom .togetherai_model import TogetherAIModelfrom .vllm_model import VLLMModel+from .volcano_model import VolcanoModelfrom .yi_model import YiModelfrom .zhipuai_model import ZhipuAIModel@@ -76,4 +78,6 @@ __all__ = ['MoonshotModel','AIMLModel','BaseAudioModel',+ 'SiliconFlowModel',+ 'VolcanoModel',]diff --git a/camel/models/model_factory.py b/camel/models/model_factory.pyindex eabdab58f..3f0337c47 100644--- a/camel/models/model_factory.py+++ b/camel/models/model_factory.py@@ -37,6 +37,7 @@ from camel.models.siliconflow_model import SiliconFlowModelfrom camel.models.stub_model import StubModelfrom camel.models.togetherai_model import TogetherAIModelfrom camel.models.vllm_model import VLLMModel+from camel.models.volcano_model import VolcanoModelfrom camel.models.yi_model import YiModelfrom camel.models.zhipuai_model import ZhipuAIModelfrom camel.types import ModelPlatformType, ModelType, UnifiedModelType@@ -107,6 +108,8 @@ class ModelFactory:model_class = SiliconFlowModelelif model_platform.is_aiml:model_class = AIMLModel+ elif model_platform.is_volcano:+ model_class = VolcanoModelelif model_platform.is_openai and model_type.is_openai:model_class = OpenAIModeldiff --git a/camel/models/volcano_model.py b/camel/models/volcano_model.pynew file mode 100644index 000000000..9f9bda693--- /dev/null+++ b/camel/models/volcano_model.py@@ -0,0 +1,103 @@+# ========= 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 pydantic import BaseModel++from camel.configs import OPENAI_API_PARAMS+from camel.messages import OpenAIMessage+from camel.models.openai_compatible_model import OpenAICompatibleModel+from camel.types import ChatCompletion, ModelType+from camel.utils import (+ BaseTokenCounter,+ OpenAITokenCounter,+ api_keys_required,+)+++class VolcanoModel(OpenAICompatibleModel):+ r"""Volcano Engine API in a unified BaseModelBackend interface.++ Args:+ model_type (Union[ModelType, str]): Model for which a backend is+ created.+ model_config_dict (Optional[Dict[str, Any]], optional): A dictionary+ that will be fed into the API call. If+ :obj:`None`, :obj:`{}` will be used. (default: :obj:`None`)+ api_key (Optional[str], optional): The API key for authenticating with+ the Volcano Engine service. (default: :obj:`None`)+ url (Optional[str], optional): The url to the Volcano Engine service.+ (default: :obj:`https://ark.cn-beijing.volces.com/api/v3`)+ token_counter (Optional[BaseTokenCounter], optional): Token counter to+ use for the model. If not provided, :obj:`OpenAITokenCounter`+ will be used. (default: :obj:`None`)+ """++ @api_keys_required(+ [+ ("api_key", "VOLCANO_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,+ ) -> None:+ if model_config_dict is None:+ model_config_dict = {}++ api_key = api_key or os.environ.get("VOLCANO_API_KEY")+ url = (+ url+ or os.environ.get("VOLCANO_API_BASE_URL")+ or "https://ark.cn-beijing.volces.com/api/v3"+ )++ super().__init__(+ model_type, model_config_dict, api_key, url, token_counter+ )++ @property+ def token_counter(self) -> BaseTokenCounter:+ r"""Initialize the token counter for the model backend.++ Returns:+ BaseTokenCounter: The token counter following the model's+ tokenization style.+ """+ if not self._token_counter:+ # Use OpenAI token counter as an approximation+ self._token_counter = OpenAITokenCounter(ModelType.GPT_4O_MINI)+ return self._token_counter++ def check_model_config(self):+ r"""Check whether the model configuration is valid for Volcano+ model backends.++ Raises:+ ValueError: If the model configuration dictionary contains any+ unexpected arguments to Volcano API.+ """+ # Using OpenAI API params as Volcano Engine API is OpenAI-compatible+ for param in self.model_config_dict:+ if param not in OPENAI_API_PARAMS:+ raise ValueError(+ f"Unexpected argument `{param}` is "+ "input into Volcano model backend."+ )\ No newline at end of filediff --git a/camel/types/enums.py b/camel/types/enums.pyindex 1fc5cacbe..bbf6051cc 100644--- a/camel/types/enums.py+++ b/camel/types/enums.py@@ -889,6 +889,7 @@ class ModelPlatformType(Enum):MOONSHOT = "moonshot"SILICONFLOW = "siliconflow"AIML = "aiml"+ VOLCANO = "volcano"@propertydef is_openai(self) -> bool:@@ -1011,6 +1012,11 @@ class ModelPlatformType(Enum):r"""Returns whether this platform is AIML."""return self is ModelPlatformType.AIML+ @property+ def is_volcano(self) -> bool:+ r"""Returns whether this platform is volcano."""+ return self is ModelPlatformType.VOLCANO+class AudioModelType(Enum):TTS_1 = "tts-1"diff --git a/examples/models/role_playing_with_volcano.py b/examples/models/role_playing_with_volcano.pynew file mode 100644index 000000000..127486235--- /dev/null+++ b/examples/models/role_playing_with_volcano.py@@ -0,0 +1,135 @@+# ========= 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 Dict, List, Optional, Tuple++from camel.societies import RolePlaying+from camel.configs import ChatGPTConfig+from camel.models import ModelFactory+from camel.types import ModelPlatformType+from camel.utils import print_text_animated++"""+Please set the below environment variable before running this example:+export VOLCANO_API_KEY="your_volcano_api_key"++This example demonstrates how to use Volcano Engine API with DeepSeek models+for role-playing in CAMEL.+"""+++def main(+ assistant_role_name: str = "Python Programmer",+ user_role_name: str = "Stock Market Trader",+ task_prompt: str = (+ "Develop a Python script that analyzes historical stock data "+ "and identifies potential buying opportunities based on "+ "technical indicators."+ ),+ with_task_specify: bool = True,+ model_config_dict: Optional[Dict] = None,+) -> Tuple[List[Dict], List[Dict]]:+ """Run a role-playing session with Volcano Engine API.++ Args:+ assistant_role_name: The role name of the assistant.+ user_role_name: The role name of the user.+ task_prompt: The task prompt.+ with_task_specify: Whether to specify the task.+ model_config_dict: The model configuration dictionary.++ Returns:+ A tuple of assistant and user message lists.+ """+ if model_config_dict is None:+ model_config_dict = ChatGPTConfig(+ temperature=0.2,+ max_tokens=1024,+ ).as_dict()++ # Check if VOLCANO_API_KEY is set+ api_key = os.environ.get("VOLCANO_API_KEY")+ if not api_key:+ raise ValueError(+ "VOLCANO_API_KEY environment variable is not set. "+ "Please set it before running this example."+ )++ # Create models for assistant and user+ assistant_model = ModelFactory.create(+ model_platform=ModelPlatformType.VOLCANO,+ model_type="deepseek-r1-250120",+ model_config_dict=model_config_dict,+ )++ user_model = ModelFactory.create(+ model_platform=ModelPlatformType.VOLCANO,+ model_type="deepseek-r1-250120",+ model_config_dict=model_config_dict,+ )++ # Create a role-playing session+ role_playing = RolePlaying(+ assistant_role_name=assistant_role_name,+ user_role_name=user_role_name,+ assistant_agent_kwargs={"model": assistant_model},+ user_agent_kwargs={"model": user_model},+ task_prompt=task_prompt,+ with_task_specify=with_task_specify,+ )++ # Start the role-playing session+ print(+ f"Running role-playing with Volcano Engine API (DeepSeek-R1)...\n"+ f"Assistant Role: {assistant_role_name}\n"+ f"User Role: {user_role_name}\n"+ f"Task: {task_prompt}\n"+ )++ # Start the chat+ chat_history = []+ n = 0+ input_msg = role_playing.init_chat() # Initialize the chat+ while n < 10:+ n += 1+ assistant_response, user_response = role_playing.step(input_msg) # Provide input_msg+ if assistant_response is None or user_response is None:+ break++ chat_history.append(+ {+ "role": "assistant",+ "content": assistant_response.msg.content,+ }+ )+ chat_history.append(+ {"role": "user", "content": user_response.msg.content}+ )++ print_text_animated(f"Assistant ({assistant_role_name}):\n")+ print_text_animated(f"{assistant_response.msg.content}\n")+ print_text_animated(f"User ({user_role_name}):\n")+ print_text_animated(f"{user_response.msg.content}\n")++ if "<CAMEL_TASK_DONE>" in user_response.msg.content:+ break++ input_msg = assistant_response.msg # Update input_msg for the next step++ # return role_playing.assistant_agent.chat_history, role_playing.user_agent.chat_history+++if __name__ == "__main__":+ main()\ No newline at end of filediff --git a/examples/models/volcano_model_example.py b/examples/models/volcano_model_example.pynew file mode 100644index 000000000..5be17b7e1--- /dev/null+++ b/examples/models/volcano_model_example.py@@ -0,0 +1,47 @@+# ========= 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.models import ModelFactory+from camel.types import ModelPlatformType++"""+Please set the below environment variable before running this example:+export VOLCANO_API_KEY="your_volcano_api_key"++Volcano Engine API supports various models including DeepSeek models.+This example uses the DeepSeek-R1 model.+"""++# Create a model using ModelFactory+model = ModelFactory.create(+ model_platform=ModelPlatformType.VOLCANO,+ model_type="deepseek-r1-250120", # DeepSeek-R1 model+ model_config_dict={+ "temperature": 0.2,+ "max_tokens": 1024,+ },+)++# Define system message+sys_msg = "You are a helpful assistant."++# Set agent+camel_agent = ChatAgent(system_message=sys_msg, model=model)++user_msg = """How many r in strawberry."""++# Get response information+response = camel_agent.step(user_msg)+print(response.msgs[0].content)\ No newline at end of filediff --git a/test/models/test_volcano_model.py b/test/models/test_volcano_model.pynew file mode 100644index 000000000..207486b52--- /dev/null+++ b/test/models/test_volcano_model.py@@ -0,0 +1,47 @@+# ========= 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.models import VolcanoModel+from camel.types import ModelType+from camel.utils import OpenAITokenCounter++[email protected]_backend+def test_volcano_model():+ # Using a string model type since Volcano supports various models+ model_type = "deepseek-r1-250120"+ model = VolcanoModel(model_type)+ assert model.model_type == model_type+ assert model.model_config_dict == {}+ assert isinstance(model.token_counter, OpenAITokenCounter)++[email protected]_backend+def test_volcano_model_unexpected_argument():+ model_type = "deepseek-r1-250120"+ model_config_dict = {"model_path": "vicuna-7b-v1.5"}++ with pytest.raises(+ ValueError,+ match=re.escape(+ (+ "Unexpected argument `model_path` is "+ "input into Volcano model backend."+ )+ ),+ ):+ _ = VolcanoModel(model_type, model_config_dict)\ No newline at end of file