🐫 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 ModelManager to schedule calls between different model backend (#1190)
RomanPryima11f5521242c6d
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex 9d6c45853..d4ca76938 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -21,6 +21,7 @@ from collections import defaultdictfrom typing import (TYPE_CHECKING,Any,+ Callable,Dict,List,Optional,@@ -41,7 +42,12 @@ from camel.memories import (ScoreBasedContextCreator,)from camel.messages import BaseMessage, FunctionCallingMessage, OpenAIMessage-from camel.models import BaseModelBackend, ModelFactory+from camel.models import (+ BaseModelBackend,+ ModelFactory,+ ModelManager,+ ModelProcessingError,+)from camel.responses import ChatAgentResponsefrom camel.types import (ChatCompletion,@@ -145,12 +151,16 @@ class ChatAgent(BaseAgent):response_terminators (List[ResponseTerminator], optional): List of:obj:`ResponseTerminator` bind to one chat agent.(default: :obj:`None`)+ scheduling_strategy (str): name of function that defines how to select+ the next model in ModelManager. (default: :str:`round_robin`)"""def __init__(self,system_message: Optional[Union[BaseMessage, str]] = None,- model: Optional[BaseModelBackend] = None,+ model: Optional[+ Union[BaseModelBackend, List[BaseModelBackend]]+ ] = None,memory: Optional[AgentMemory] = None,message_window_size: Optional[int] = None,token_limit: Optional[int] = None,@@ -158,6 +168,7 @@ class ChatAgent(BaseAgent):tools: Optional[List[FunctionTool]] = None,external_tools: Optional[List[FunctionTool]] = None,response_terminators: Optional[List[ResponseTerminator]] = None,+ scheduling_strategy: str = "round_robin",) -> None:if isinstance(system_message, str):system_message = BaseMessage.make_assistant_message(@@ -172,13 +183,14 @@ class ChatAgent(BaseAgent):self.role_type: RoleType = (getattr(system_message, 'role_type', None) or RoleType.ASSISTANT)- self.model_backend: BaseModelBackend = (+ self.model_backend = ModelManager(modelif model is not Noneelse ModelFactory.create(model_platform=ModelPlatformType.DEFAULT,model_type=ModelType.DEFAULT,- )+ ),+ scheduling_strategy=scheduling_strategy,)self.model_type = self.model_backend.model_type@@ -945,8 +957,32 @@ class ChatAgent(BaseAgent):str,]:r"""Internal function for agent step model response."""++ response = None# Obtain the model's response- response = self.model_backend.run(openai_messages)+ for _ in range(len(self.model_backend.models)):+ try:+ response = self.model_backend.run(openai_messages)+ break+ except Exception as exc:+ logger.error(+ f"An error occurred while running model "+ f"{self.model_backend.model_type}, "+ f"index: {self.model_backend.current_model_index}",+ exc_info=exc,+ )+ continue+ if not response:+ raise ModelProcessingError(+ "Unable to process messages: none of the provided models "+ "run succesfully."+ )++ logger.info(+ f"Model {self.model_backend.model_type}, "+ f"index {self.model_backend.current_model_index}, "+ f"processed these messages: {openai_messages}"+ )if isinstance(response, ChatCompletion):output_messages, finish_reasons, usage_dict, response_id = (@@ -1298,6 +1334,15 @@ class ChatAgent(BaseAgent):)return usage_dict+ def add_model_scheduling_strategy(self, name: str, strategy_fn: Callable):+ r"""Add a scheduling strategy method provided by user to ModelManger.++ Args:+ name (str): The name of the strategy.+ strategy_fn (Callable): The scheduling strategy function.+ """+ self.model_backend.add_strategy(name, strategy_fn)+def __repr__(self) -> str:r"""Returns a string representation of the :obj:`ChatAgent`.diff --git a/camel/models/__init__.py b/camel/models/__init__.pyindex b0538b60e..d5be95679 100644--- a/camel/models/__init__.py+++ b/camel/models/__init__.py@@ -21,6 +21,7 @@ from .groq_model import GroqModelfrom .litellm_model import LiteLLMModelfrom .mistral_model import MistralModelfrom .model_factory import ModelFactory+from .model_manager import ModelManager, ModelProcessingErrorfrom .nemotron_model import NemotronModelfrom .ollama_model import OllamaModelfrom .openai_audio_models import OpenAIAudioModels@@ -46,6 +47,7 @@ __all__ = ['ZhipuAIModel','CohereModel','ModelFactory',+ 'ModelManager','LiteLLMModel','OpenAIAudioModels','NemotronModel',@@ -58,5 +60,6 @@ __all__ = ['TogetherAIModel','YiModel','QwenModel',+ 'ModelProcessingError','DeepSeekModel',]diff --git a/camel/models/model_manager.py b/camel/models/model_manager.pynew file mode 100644index 000000000..3e324d0ed--- /dev/null+++ b/camel/models/model_manager.py@@ -0,0 +1,212 @@+# ========= 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 logging+from itertools import cycle+from random import choice+from typing import (+ Any,+ Callable,+ Dict,+ List,+ Union,+)++from openai import Stream++from camel.messages import OpenAIMessage+from camel.models.base_model import BaseModelBackend+from camel.types import (+ ChatCompletion,+ ChatCompletionChunk,+ UnifiedModelType,+)+from camel.utils import BaseTokenCounter++logger = logging.getLogger(__name__)+++class ModelProcessingError(Exception):+ r"""Raised when an error occurs during model processing."""++ pass+++class ModelManager:+ r"""ModelManager choosing a model from provided list.+ Models are picked according to defined strategy.++ Args:+ models(Union[BaseModelBackend, List[BaseModelBackend]]):+ model backend or list of model backends+ (e.g., model instances, APIs)+ scheduling_strategy (str): name of function that defines how+ to select the next model. (default: :str:`round_robin`)+ """++ def __init__(+ self,+ models: Union[BaseModelBackend, List[BaseModelBackend]],+ scheduling_strategy: str = "round_robin",+ ):+ if isinstance(models, list):+ self.models = models+ else:+ self.models = [models]+ self.models_cycle = cycle(self.models)+ self.current_model = self.models[0]++ # Set the scheduling strategy; default is round-robin+ try:+ self.scheduling_strategy = getattr(self, scheduling_strategy)+ except AttributeError:+ logger.warning(+ f"Provided strategy: {scheduling_strategy} is not implemented."+ f"Using default 'round robin'"+ )+ self.scheduling_strategy = self.round_robin++ @property+ def model_type(self) -> UnifiedModelType:+ r"""Return type of the current model.++ Returns:+ Union[ModelType, str]: Current model type.+ """+ return self.current_model.model_type++ @property+ def model_config_dict(self) -> Dict[str, Any]:+ r"""Return model_config_dict of the current model.++ Returns:+ Dict[str, Any]: Config dictionary of the current model.+ """+ return self.current_model.model_config_dict++ @model_config_dict.setter+ def model_config_dict(self, model_config_dict: Dict[str, Any]):+ r"""Set model_config_dict to the current model.++ Args:+ model_config_dict (Dict[str, Any]): Config dictionary to be set at+ current model.+ """+ self.current_model.model_config_dict = model_config_dict++ @property+ def current_model_index(self) -> int:+ r"""Return the index of current model in self.models list.++ Returns:+ int: index of current model in given list of models.+ """+ return self.models.index(self.current_model)++ @property+ def token_limit(self):+ r"""Returns the maximum token limit for current model.++ This method retrieves the maximum token limit either from the+ `model_config_dict` or from the model's default token limit.++ Returns:+ int: The maximum token limit for the given model.+ """+ return self.current_model.token_limit++ @property+ def token_counter(self) -> BaseTokenCounter:+ r"""Return token_counter of the current model.++ Returns:+ BaseTokenCounter: The token counter following the model's+ tokenization style.+ """+ return self.current_model.token_counter++ def add_strategy(self, name: str, strategy_fn: Callable):+ r"""Add a scheduling strategy method provided by user in case when none+ of existent strategies fits.+ When custom strategy is provided, it will be set as+ "self.scheduling_strategy" attribute.++ Args:+ name (str): The name of the strategy.+ strategy_fn (Callable): The scheduling strategy function.+ """+ if not callable(strategy_fn):+ raise ValueError("strategy_fn must be a callable function.")+ setattr(self, name, strategy_fn.__get__(self))+ self.scheduling_strategy = getattr(self, name)+ logger.info(f"Custom strategy '{name}' added.")++ # Strategies+ def round_robin(self) -> BaseModelBackend:+ r"""Return models one by one in simple round-robin fashion.++ Returns:+ BaseModelBackend for processing incoming messages.+ """+ return next(self.models_cycle)++ def always_first(self) -> BaseModelBackend:+ r"""Always return the first model from self.models.++ Returns:+ BaseModelBackend for processing incoming messages.+ """+ return self.models[0]++ def random_model(self) -> BaseModelBackend:+ r"""Return random model from self.models list.++ Returns:+ BaseModelBackend for processing incoming messages.+ """+ return choice(self.models)++ def run(+ self, messages: List[OpenAIMessage]+ ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:+ r"""Process a list of messages by selecting a model based on+ the scheduling strategy.+ Sends the entire list of messages to the selected model,+ and returns a single response.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat+ history in OpenAI API format.++ Returns:+ Union[ChatCompletion, Stream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `Stream[ChatCompletionChunk]` in the stream mode.+ """+ self.current_model = self.scheduling_strategy()++ # Pass all messages to the selected model and get the response+ try:+ response = self.current_model.run(messages)+ except Exception as exc:+ logger.error(f"Error processing with model: {self.current_model}")+ if self.scheduling_strategy == self.always_first:+ self.scheduling_strategy = self.round_robin+ logger.warning(+ "The scheduling strategy has been changed to 'round_robin'"+ )+ # Skip already used one+ self.current_model = self.scheduling_strategy()+ raise exc+ return responsediff --git a/examples/models/model_manger.py b/examples/models/model_manger.pynew file mode 100644index 000000000..0ce9ec6e4--- /dev/null+++ b/examples/models/model_manger.py@@ -0,0 +1,79 @@+# ========= 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, ModelType++# Use two different models for ModelManager++model1 = ModelFactory.create(+ model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,+ model_type="grok-beta",+ api_key="xai-...",+ url="https://api.x.ai/v1",+ model_config_dict={"max_tokens": 2000},+)++model2 = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+ model_config_dict={"temperature": 0.4},+)++assistant_sys_msg = "Testing two models in ModelManager"++agent = ChatAgent(+ assistant_sys_msg,+ model=[model1, model2],+ scheduling_strategy="random_model",+)++# scheduling_strategy can be one of+# "round_robin, "always_first", "random_model"+++# For using a custom scheduling_strategy. After ChatAgent initialization,+# custom callable need to be provided to agent.add_strategy method+++def custom_strategy(self):+ r"""Custom strategy implementation."""+ return self.models[-1]+++agent.add_model_scheduling_strategy("custom", custom_strategy)+++user_msg = """What is the meaning of life, the universe, and everything?"""++assistant_response = agent.step(user_msg)+print(assistant_response.msg.content)++"""+===============================================================================+The phrase "the meaning of life, the universe, and everything" is famously+associated with Douglas Adams' science fiction series "The Hitchhiker's Guide+to the Galaxy." In the story, a group of hyper-intelligent beings builds a+supercomputer named Deep Thought to calculate the answer to the ultimate+question of life, the universe, and everything. After much contemplation, the+computer reveals that the answer is simply the number 42, though the actual+question remains unknown.++This has led to various interpretations and discussions about the nature of+existence, purpose, and the search for meaning in life. Ultimately, the+meaning of life can vary greatly from person to person, shaped by individual+beliefs, experiences, and values.+===============================================================================+"""diff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.pyindex b7ac6d4ff..b2ad4b90f 100644--- a/test/agents/test_chat_agent.py+++ b/test/agents/test_chat_agent.py@@ -688,7 +688,7 @@ def test_chat_agent_vision():image_detail="low",)# Mock the OpenAI model return value:- agent.model_backend = Mock()+ agent.model_backend.run = Mock()agent.model_backend.run.return_value = ChatCompletion(id="mock_vision_id",choices=[diff --git a/test/models/test_model_manager.py b/test/models/test_model_manager.pynew file mode 100644index 000000000..8ed79678b--- /dev/null+++ b/test/models/test_model_manager.py@@ -0,0 +1,97 @@+# ========= 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 TYPE_CHECKING, List++import pytest+from mock import Mock+from openai.types.chat.chat_completion_system_message_param import (+ ChatCompletionSystemMessageParam,+)++from camel.models import BaseModelBackend+from camel.models.model_manager import ModelManager++[email protected]_backend+ "models_number, strategy, calls_count, times_each_model_called",+ [+ (1, "round_robin", 9, 9),+ (3, "round_robin", 9, 3),+ (1, "not_existent", 9, 9),+ (3, "not_existent", 9, 3),+ (3, "always_first", 9, 9),+ (3, "random_model", 9, 9),+ ],+)+def test_model_manager(+ models_number: int,+ strategy: str,+ calls_count: int,+ times_each_model_called: int,+):+ models = (+ [Mock(run=Mock()) for _ in range(models_number)]+ if models_number > 1+ else Mock()+ )++ if TYPE_CHECKING:+ assert type(models) == List[BaseModelBackend]+ messages: List = []+ for _ in range(calls_count):+ msg = "message"+ if TYPE_CHECKING:+ assert type(msg) == ChatCompletionSystemMessageParam+ messages.append(msg)+ model_manager = ModelManager(models, scheduling_strategy=strategy)++ assert isinstance(model_manager.models, list)+ assert len(model_manager.models) == models_number+ assert model_manager.current_model_index == 0+ for _ in range(calls_count):+ model_manager.run(messages)++ if strategy in ("not_existent", "round_robin"):+ assert model_manager.scheduling_strategy.__name__ == "round_robin"+ for model in model_manager.models:+ if TYPE_CHECKING:+ assert isinstance(model.run, Mock)+ assert model.run.call_count == times_each_model_called+ if strategy == "always_first":+ assert model_manager.scheduling_strategy.__name__ == "always_first"+ assert models[0].run.call_count == times_each_model_called++ if strategy == "random_model":+ assert model_manager.scheduling_strategy.__name__ == "random_model"+ total_calls = 0+ for model in model_manager.models:+ if TYPE_CHECKING:+ assert isinstance(model.run, Mock)+ total_calls += model.run.call_count+ assert total_calls == times_each_model_called+++def test_model_manager_always_first_turns_into_round_robin():+ models = [Mock(run=Mock(side_effect=Exception())) for _ in range(3)]+ model_manager = ModelManager(models, scheduling_strategy="always_first")+ assert model_manager.scheduling_strategy.__name__ == "always_first"+ assert model_manager.current_model_index == 0+ with pytest.raises(Exception): # noqa: B017+ model_manager.run(["message"])+ assert model_manager.scheduling_strategy.__name__ == "round_robin"+ with pytest.raises(Exception): # noqa: B017+ model_manager.run(["message"])+ assert model_manager.current_model_index == 1