🐫 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: simplify creating agent using str, add examples (#1699)
Xiaotian Jin8ef873eb402d
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex c2d6c6645..2df0620f1 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -28,6 +28,7 @@ from typing import (List,Optional,Set,+ Tuple,Type,Union,)@@ -78,7 +79,6 @@ from camel.utils import get_model_encodingif TYPE_CHECKING:from camel.terminators import ResponseTerminator-logger = logging.getLogger(__name__)# AgentOps decorator setting@@ -110,10 +110,17 @@ class ChatAgent(BaseAgent):Args:system_message (Union[BaseMessage, str], optional): The system message- for the chat agent.- model (BaseModelBackend, optional): The model backend to use for- generating responses. (default: :obj:`ModelPlatformType.DEFAULT`- with `ModelType.DEFAULT`)+ for the chat agent. (default: :obj:`None`)+ model (Union[BaseModelBackend, Tuple[str, str], str, ModelType,+ Tuple[ModelPlatformType, ModelType], List[BaseModelBackend],+ List[str], List[ModelType], List[Tuple[str, str]],+ List[Tuple[ModelPlatformType, ModelType]]], optional):+ The model backend(s) to use. Can be a single instance,+ a specification (string, enum, tuple), or a list of instances+ or specifications to be managed by `ModelManager`. If a list of+ specifications (not `BaseModelBackend` instances) is provided,+ they will be instantiated using `ModelFactory`. (default:+ :obj:`ModelPlatformType.DEFAULT` with `ModelType.DEFAULT`)memory (AgentMemory, optional): The agent memory for managing chatmessages. If `None`, a :obj:`ChatHistoryMemory` will be used.(default: :obj:`None`)@@ -150,7 +157,18 @@ class ChatAgent(BaseAgent):self,system_message: Optional[Union[BaseMessage, str]] = None,model: Optional[- Union[BaseModelBackend, List[BaseModelBackend]]+ Union[+ BaseModelBackend,+ Tuple[str, str],+ str,+ ModelType,+ Tuple[ModelPlatformType, ModelType],+ List[BaseModelBackend],+ List[str],+ List[ModelType],+ List[Tuple[str, str]],+ List[Tuple[ModelPlatformType, ModelType]],+ ]] = None,memory: Optional[AgentMemory] = None,message_window_size: Optional[int] = None,@@ -165,19 +183,14 @@ class ChatAgent(BaseAgent):single_iteration: bool = False,agent_id: Optional[str] = None,) -> None:- # Set up model backend+ # Resolve model backends and set up model manager+ resolved_models = self._resolve_models(model)self.model_backend = ModelManager(- (- model- if model is not None- else ModelFactory.create(- model_platform=ModelPlatformType.DEFAULT,- model_type=ModelType.DEFAULT,- )- ),+ resolved_models,scheduling_strategy=scheduling_strategy,)self.model_type = self.model_backend.model_type+# Assign unique IDself.agent_id = agent_id if agent_id else str(uuid.uuid4())@@ -247,6 +260,137 @@ class ChatAgent(BaseAgent):for terminator in self.response_terminators:terminator.reset()+ def _resolve_models(+ self,+ model: Optional[+ Union[+ BaseModelBackend,+ Tuple[str, str],+ str,+ ModelType,+ Tuple[ModelPlatformType, ModelType],+ List[BaseModelBackend],+ List[str],+ List[ModelType],+ List[Tuple[str, str]],+ List[Tuple[ModelPlatformType, ModelType]],+ ]+ ],+ ) -> Union[BaseModelBackend, List[BaseModelBackend]]:+ r"""Resolves model specifications into model backend instances.++ This method handles various input formats for model specifications and+ returns the appropriate model backend(s).++ Args:+ model: Model specification in various formats including single+ model, list of models, or model type specifications.++ Returns:+ Union[BaseModelBackend, List[BaseModelBackend]]: Resolved model+ backend(s).++ Raises:+ TypeError: If the model specification format is not supported.+ """+ if model is None:+ # Default single model if none provided+ return ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+ )+ elif isinstance(model, BaseModelBackend):+ # Already a single pre-instantiated model+ return model+ elif isinstance(model, list):+ return self._resolve_model_list(model)+ elif isinstance(model, (ModelType, str)):+ # Single string or ModelType -> use default platform+ model_platform = ModelPlatformType.DEFAULT+ model_type = model+ logger.warning(+ f"Model type '{model_type}' provided without a platform. "+ f"Using platform '{model_platform}'. Note: platform "+ "is not automatically inferred based on model type."+ )+ return ModelFactory.create(+ model_platform=model_platform,+ model_type=model_type,+ )+ elif isinstance(model, tuple) and len(model) == 2:+ # Single tuple (platform, type)+ model_platform, model_type = model # type: ignore[assignment]+ return ModelFactory.create(+ model_platform=model_platform,+ model_type=model_type,+ )+ else:+ raise TypeError(+ f"Unsupported type for model parameter: {type(model)}"+ )++ def _resolve_model_list(+ self, model_list: list+ ) -> Union[BaseModelBackend, List[BaseModelBackend]]:+ r"""Resolves a list of model specifications into model backend+ instances.++ Args:+ model_list (list): List of model specifications in various formats.++ Returns:+ Union[BaseModelBackend, List[BaseModelBackend]]: Resolved model+ backend(s).++ Raises:+ TypeError: If the list elements format is not supported.+ """+ if not model_list: # Handle empty list+ logger.warning(+ "Empty list provided for model, using default model."+ )+ return ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+ )+ elif isinstance(model_list[0], BaseModelBackend):+ # List of pre-instantiated models+ return model_list # type: ignore[return-value]+ elif isinstance(model_list[0], (str, ModelType)):+ # List of strings or ModelTypes -> use default platform+ model_platform = ModelPlatformType.DEFAULT+ logger.warning(+ f"List of model types {model_list} provided without "+ f"platforms. Using platform '{model_platform}' for all. "+ "Note: platform is not automatically inferred based on "+ "model type."+ )+ resolved_models_list = []+ for model_type_item in model_list:+ resolved_models_list.append(+ ModelFactory.create(+ model_platform=model_platform,+ model_type=model_type_item, # type: ignore[arg-type]+ )+ )+ return resolved_models_list+ elif isinstance(model_list[0], tuple) and len(model_list[0]) == 2:+ # List of tuples (platform, type)+ resolved_models_list = []+ for model_spec in model_list:+ platform, type_ = model_spec[0], model_spec[1] # type: ignore[index]+ resolved_models_list.append(+ ModelFactory.create(+ model_platform=platform, model_type=type_+ )+ )+ return resolved_models_list+ else:+ raise TypeError(+ "Unsupported type for list elements in model: "+ f"{type(model_list[0])}"+ )+@propertydef system_message(self) -> Optional[BaseMessage]:r"""Returns the system message for the agent."""diff --git a/camel/models/model_factory.py b/camel/models/model_factory.pyindex 79ea7c0b8..424b5c482 100644--- a/camel/models/model_factory.py+++ b/camel/models/model_factory.py@@ -64,8 +64,8 @@ class ModelFactory:@staticmethoddef create(- model_platform: ModelPlatformType,- model_type: Union[ModelType, str],+ model_platform: Union[ModelPlatformType, str],+ model_type: Union[ModelType, str, UnifiedModelType],model_config_dict: Optional[Dict] = None,token_counter: Optional[BaseTokenCounter] = None,api_key: Optional[str] = None,@@ -75,10 +75,12 @@ class ModelFactory:r"""Creates an instance of `BaseModelBackend` of the specified type.Args:- model_platform (ModelPlatformType): Platform from which the model- originates.- model_type (Union[ModelType, str]): Model for which a- backend is created. Can be a `str` for open source platforms.+ model_platform (Union[ModelPlatformType, str]): Platform from+ which the model originates. Can be a string or+ ModelPlatformType enum.+ model_type (Union[ModelType, str, UnifiedModelType]): Model for+ which a backend is created. Can be a string, ModelType enum, or+ UnifiedModelType.model_config_dict (Optional[Dict]): A dictionary that will be fedinto the backend constructor. (default: :obj:`None`)token_counter (Optional[BaseTokenCounter], optional): Token@@ -99,6 +101,21 @@ class ModelFactory:Raises:ValueError: If there is no backend for the model."""+ # Convert string to ModelPlatformType enum if needed+ if isinstance(model_platform, str):+ try:+ model_platform = ModelPlatformType(model_platform)+ except ValueError:+ raise ValueError(f"Unknown model platform: {model_platform}")++ # Convert string to ModelType enum or UnifiedModelType if needed+ if isinstance(model_type, str):+ try:+ model_type = ModelType(model_type)+ except ValueError:+ # If not in ModelType, create a UnifiedModelType+ model_type = UnifiedModelType(model_type)+model_class: Optional[Type[BaseModelBackend]] = Nonemodel_type = UnifiedModelType(model_type)diff --git a/docs/key_modules/agents.md b/docs/key_modules/agents.mdindex 5bfa11794..5ea267a1b 100644--- a/docs/key_modules/agents.md+++ b/docs/key_modules/agents.md@@ -62,7 +62,48 @@ agent = ChatAgent(system_message="You are a helpful assistant.")response = agent.step("Hello, can you help me?")```-### 3.2. Using Tools with Chat Agent+### 3.2. Simplified Agent Creation+The `ChatAgent` supports multiple ways to specify the model:++```python+from camel.agents import ChatAgent+from camel.models import ModelFactory+from camel.types import ModelPlatformType, ModelType++# Method 1: Using just a string for the model name (default model platform is used)+agent_1 = ChatAgent("You are a helpful assistant.", model="gpt-4o-mini")++# Method 2: Using a ModelType enum (default model platform is used)+agent_2 = ChatAgent("You are a helpful assistant.", model=ModelType.GPT_4O_MINI)++# Method 3: Using a tuple of strings (platform, model)+agent_3 = ChatAgent("You are a helpful assistant.", model=("openai", "gpt-4o-mini"))++# Method 4: Using a tuple of enums+agent_4 = ChatAgent(+ "You are a helpful assistant.",+ model=(ModelPlatformType.ANTHROPIC, ModelType.CLAUDE_3_5_SONNET),+)++# Method 5: Using default model platform and default model type when none is specified+agent_5 = ChatAgent("You are a helpful assistant.")++# Method 6: Using a pre-created model with ModelFactory (original approach)+model = ModelFactory.create(+ model_platform=ModelPlatformType.OPENAI, # Using enum+ model_type=ModelType.GPT_4O_MINI, # Using enum+)+agent_6 = ChatAgent("You are a helpful assistant.", model=model)++# Method 7: Using ModelFactory with string parameters+model = ModelFactory.create(+ model_platform="openai", # Using string+ model_type="gpt-4o-mini", # Using string+)+agent_7 = ChatAgent("You are a helpful assistant.", model=model)+```++### 3.3. Using Tools with Chat Agent```pythonfrom camel.agents import ChatAgentfrom camel.toolkits import FunctionTool@@ -78,7 +119,7 @@ agent = ChatAgent(tools=[calculator])response = agent.step("What is 5 + 3?")```-### 3.3. Structured Output+### 3.4. Structured Output```pythonfrom pydantic import BaseModelfrom typing import List@@ -109,6 +150,12 @@ response = agent.step("List benefits of exercise", response_format=ResponseForma- Use structured outputs when specific response formats are needed- Handle async operations properly when dealing with long-running tasks+### 4.4. Model Specification+- Use the simplified model specification methods for cleaner code+- For default platform models, just specify the model name as a string+- For specific platforms, use the tuple format (platform, model)+- Use enums for better type safety and IDE support+## 5. Advanced Features### 5.1. Model Schedulingdiff --git a/examples/agent/agent_step_with_reasoning.py b/examples/agents/agent_step_with_reasoning.pysimilarity index 98%rename from examples/agent/agent_step_with_reasoning.pyrename to examples/agents/agent_step_with_reasoning.pyindex 1dcaa298b..8782cb412 100644--- a/examples/agent/agent_step_with_reasoning.py+++ b/examples/agents/agent_step_with_reasoning.py@@ -85,7 +85,7 @@ LeBron continues to play at a high level, consistently being a key player for hi# 3rd run: the response with thinking (agent fails to choose the best candidate above the threshold, let the user decide)-response_with_think2 = openai_agent.step(+response_with_think_2 = openai_agent.step(usr_msg,reason_params=dict(choices=3,@@ -93,7 +93,7 @@ response_with_think2 = openai_agent.step(),)-print(response_with_think2.msgs[0].content)+print(response_with_think_2.msgs[0].content)# flake8: noqa: E501"""===============================================================================diff --git a/examples/agents/create_chat_agent.py b/examples/agents/create_chat_agent.pynew file mode 100644index 000000000..77fdbe7fa--- /dev/null+++ b/examples/agents/create_chat_agent.py@@ -0,0 +1,69 @@+# ========= 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++# Method 1: Initialize the agent with just a string (model name)+# This uses the default platform (OpenAI)+agent_1 = ChatAgent("You are a helpful assistant.", model="gpt-4o-mini")++# Method 2: Initialize with just a `enum` for model type.+agent_2 = ChatAgent(+ "You are a helpful assistant.",+ model=ModelType.GPT_4O_MINI,+)++# Method 3: Initialize the agent with a tuple (platform, model)+agent_3 = ChatAgent(+ "You are a helpful assistant.",+ model=("anthropic", "claude-3-5-sonnet-latest"),+)++# Method 4: Initialize the agent with a `tuple` of `enum`+agent_4 = ChatAgent(+ "You are a helpful assistant.",+ model=(ModelPlatformType.ANTHROPIC, ModelType.CLAUDE_3_5_SONNET),+)++# Method 5: Default model when none is specified.+agent_5 = ChatAgent("You are a helpful assistant.")++# Method 6: Initialize with a pre-created model (original approach)+model = ModelFactory.create(+ model_platform=ModelPlatformType.OPENAI, # Using enum+ model_type=ModelType.GPT_4O_MINI, # Using enum+)+agent_6 = ChatAgent("You are a helpful assistant.", model=model)++# Method 7: Initialize with a pre-created model using strings+model = ModelFactory.create(+ model_platform="openai", # Using string+ model_type="gpt-4o-mini", # Using string+)+agent_7 = ChatAgent("You are a helpful assistant.", model=model)+++# Test with a simple question with agent3(Anthropic, claude-3-5-sonnet-latest)+user_msg = "Which model are you?"++# Get the response from one of the agents+response = agent_3.step(user_msg)+print("Response from agent3:")+print(response.msgs[0].content)+"""+Response from agent3:+I am Claude, an AI assistant created by Anthropic. I aim to be direct and honest about what I am.+""" # noqa: E501diff --git a/examples/agent/repo_agent.py b/examples/agents/repo_agent.pysimilarity index 100%rename from examples/agent/repo_agent.pyrename to examples/agents/repo_agent.pydiff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.pyindex c5f4b1c22..a54b17e7c 100644--- a/test/agents/test_chat_agent.py+++ b/test/agents/test_chat_agent.py@@ -35,7 +35,7 @@ from camel.configs import ChatGPTConfigfrom camel.generators import SystemMessageGeneratorfrom camel.memories import MemoryRecordfrom camel.messages import BaseMessage-from camel.models import ModelFactory+from camel.models import AnthropicModel, ModelFactory, OpenAIModelfrom camel.terminators import ResponseWordsTerminatorfrom camel.toolkits import (FunctionTool,@@ -1297,3 +1297,49 @@ def test_chat_agent_vision(step_call_count=3):assert (agent_response.msgs[0].content == "Yes."), f"Error in calling round {i+1}"++[email protected]_backend+def test_chat_agent_creation_methods():+ r"""Test different ways to create a ChatAgent with various model+ specifications.+ """+ # Method 1: Initialize with just a string (model name)+ agent_1 = ChatAgent("You are a helpful assistant.", model="gpt-4o-mini")+ assert agent_1.model_type.value == "gpt-4o-mini"+ assert isinstance(agent_1.model_backend.models[0], OpenAIModel)++ # Method 2: Initialize with just a ModelType enum+ agent_2 = ChatAgent(+ "You are a helpful assistant.", model=ModelType.GPT_4O_MINI+ )+ assert agent_2.model_type.value == "gpt-4o-mini"+ assert isinstance(agent_2.model_backend.models[0], OpenAIModel)++ # Method 3: Initialize with a tuple of strings (platform, model)+ agent_3 = ChatAgent(+ "You are a helpful assistant.",+ model=("anthropic", "claude-3-5-sonnet-latest"),+ )+ assert agent_3.model_type.value == "claude-3-5-sonnet-latest"+ assert (+ agent_3.model_backend.models[0].model_type.value+ == "claude-3-5-sonnet-latest"+ )+ assert isinstance(agent_3.model_backend.models[0], AnthropicModel)++ # Method 4: Initialize with a tuple of enums+ agent_4 = ChatAgent(+ "You are a helpful assistant.",+ model=(ModelPlatformType.ANTHROPIC, ModelType.CLAUDE_3_5_SONNET),+ )+ assert agent_4.model_type.value == "claude-3-5-sonnet-latest"+ assert isinstance(agent_4.model_backend.models[0], AnthropicModel)++ # Method 5: Default model when none is specified+ agent_5 = ChatAgent("You are a helpful assistant.")+ assert agent_5.model_type.value == ModelType.DEFAULT.value++ # All agents should have the same system message+ for agent in [agent_1, agent_2, agent_3, agent_4, agent_5]:+ assert "You are a helpful assistant." in agent.system_message.content