Skip to content

armgit / camel

Public Imported from GitHub
0

๐Ÿซ CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

feat: Add MessageAgentTool for agent communication #2767 (#2771)

LIHUAc314f2e21a33
diff --git a/camel/toolkits/message_agent_toolkit.py b/camel/toolkits/message_agent_toolkit.py
new file mode 100644
index 000000000..d3ef2397c
--- /dev/null
+++ b/camel/toolkits/message_agent_toolkit.py
@@ -0,0 +1,172 @@
+# ========= 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, Any, Dict, List, Optional
+
+from camel.logger import get_logger
+from camel.toolkits.base import BaseToolkit
+from camel.toolkits.function_tool import FunctionTool
+
+if TYPE_CHECKING:
+ from camel.agents import ChatAgent
+else:
+ # For runtime, use Any to avoid circular import issues
+ ChatAgent = Any
+
+logger = get_logger(__name__)
+
+
+class MessageAgentTool(BaseToolkit):
+ r"""A toolkit for agent-to-agent communication.
+
+ This toolkit allows agents to send messages to other agents by their IDs
+ and receive responses, enabling multi-agent collaboration.
+
+ Args:
+ agents (Optional[Dict[str, ChatAgent]], optional): Dictionary mapping
+ agent IDs to ChatAgent instances. (default: :obj:`None`)
+ timeout (Optional[float], optional): Maximum execution time allowed for
+ toolkit operations in seconds. If None, no timeout is applied.
+ (default: :obj:`None`)
+ """
+
+ def __init__(
+ self,
+ agents: Optional[Dict[str, ChatAgent]] = None,
+ timeout: Optional[float] = None,
+ ) -> None:
+ super().__init__(timeout=timeout)
+ self.agents = agents or {}
+ logger.info(
+ f"MessageAgentTool initialized with {len(self.agents)} agents"
+ )
+
+ def register_agent(self, agent_id: str, agent: ChatAgent) -> str:
+ r"""Register a new agent for communication.
+
+ Args:
+ agent_id (str): Unique identifier for the agent.
+ agent (ChatAgent): The ChatAgent instance to register.
+
+ Returns:
+ str: Confirmation message.
+ """
+ if agent_id in self.agents:
+ logger.warning(f"Agent {agent_id} already exists, overwriting")
+
+ self.agents[agent_id] = agent
+ logger.info(f"Registered agent: {agent_id}")
+ return f"Agent {agent_id} registered successfully"
+
+ def message_agent(self, message: str, receiver_agent_id: str) -> str:
+ r"""Send a message to another agent and get the response.
+
+ Args:
+ message (str): The message to send to the target agent.
+ receiver_agent_id (str): Unique identifier of the target agent.
+
+ Returns:
+ str: Response from the target agent or error message if the
+ operation fails.
+ """
+ if receiver_agent_id not in self.agents:
+ error_message = f"Agent {receiver_agent_id} not found"
+ logger.error(error_message)
+ return f"Error: {error_message}"
+
+ try:
+ target_agent = self.agents[receiver_agent_id]
+ logger.info(
+ f"Sending message to agent {receiver_agent_id}: "
+ f"{message[:50]}..."
+ )
+
+ response = target_agent.step(message)
+
+ # Extract response content based on response type
+ if hasattr(response, 'msgs') and response.msgs:
+ response_content = response.msgs[0].content
+ else:
+ response_content = str(response)
+
+ logger.info(
+ f"Received response from {receiver_agent_id}: "
+ f"{response_content[:50]}..."
+ )
+ return response_content
+
+ except Exception as e:
+ error_message = (
+ f"Failed to communicate with agent {receiver_agent_id}: {e!s}"
+ )
+ logger.error(error_message)
+ return f"Error: {error_message}"
+
+ def list_available_agents(self) -> str:
+ r"""List all registered agents and their IDs.
+
+ Returns:
+ str: Formatted list of registered agent IDs or message if no
+ agents are registered.
+ """
+ if not self.agents:
+ return "No agents registered"
+
+ agent_list = ", ".join(self.agents.keys())
+ logger.info(f"Listed agents: {agent_list}")
+ return f"Available agents: {agent_list}"
+
+ def remove_agent(self, agent_id: str) -> str:
+ r"""Remove an agent from the communication registry.
+
+ Args:
+ agent_id (str): Unique identifier of the agent to remove.
+
+ Returns:
+ str: Confirmation message or error message if agent not found.
+ """
+ if agent_id not in self.agents:
+ error_message = f"Agent {agent_id} not found"
+ logger.error(error_message)
+ return f"Error: {error_message}"
+
+ del self.agents[agent_id]
+ logger.info(f"Removed agent: {agent_id}")
+ return f"Agent {agent_id} removed successfully"
+
+ def get_agent_count(self) -> str:
+ r"""Get the number of registered agents.
+
+ Returns:
+ str: Number of currently registered agents.
+ """
+ count = len(self.agents)
+ logger.info(f"Agent count requested: {count}")
+ return f"Total registered agents: {count}"
+
+ def get_tools(self) -> List[FunctionTool]:
+ r"""Returns a list of FunctionTool objects representing the
+ communication functions in the toolkit.
+
+ Returns:
+ List[FunctionTool]: A list of FunctionTool objects for agent
+ communication and management.
+ """
+ return [
+ FunctionTool(self.message_agent),
+ FunctionTool(self.register_agent),
+ FunctionTool(self.list_available_agents),
+ FunctionTool(self.remove_agent),
+ FunctionTool(self.get_agent_count),
+ ]
diff --git a/examples/toolkits/message_agent_toolkit.py b/examples/toolkits/message_agent_toolkit.py
new file mode 100644
index 000000000..d4803878b
--- /dev/null
+++ b/examples/toolkits/message_agent_toolkit.py
@@ -0,0 +1,233 @@
+# ========= 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. =========
+
+"""
+Example demonstrating the usage of MessageAgentTool for agent communication.
+
+This example shows how to:
+1. Create multiple specialized agents
+2. Set up communication between them using MessageAgentTool
+3. Coordinate agents through a manager agent
+4. Handle multi-step collaborative tasks
+"""
+
+import os
+
+from camel.agents import ChatAgent
+from camel.messages import BaseMessage
+from camel.models import ModelFactory
+from camel.toolkits.message_agent_toolkit import MessageAgentTool
+from camel.types import ModelPlatformType, ModelType
+
+
+def main():
+ """Demonstrate MessageAgentTool usage with multiple specialized agents."""
+
+ # Ensure you have your OpenAI API key set up
+ if not os.getenv("OPENAI_API_KEY"):
+ print("Please set your OPENAI_API_KEY environment variable.")
+ return
+
+ print("๐Ÿค– Setting up Multi-Agent Communication Example")
+ print("=" * 50)
+
+ # Create model backend
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4O_MINI,
+ model_config_dict={"temperature": 0.1},
+ )
+
+ # Create specialized agents
+ print("๐Ÿ“ Creating specialized agents...")
+
+ # Data Analyst Agent
+ analyst_system_message = BaseMessage.make_assistant_message(
+ role_name="Data Analyst",
+ content="""You are a data analyst agent. Your role is to:
+ - Analyze data and identify patterns
+ - Provide insights and recommendations
+ - Create summaries of analytical findings
+ - Respond concisely and focus on key insights.""",
+ )
+ analyst_agent = ChatAgent(
+ system_message=analyst_system_message, model=model
+ )
+
+ # Technical Writer Agent
+ writer_system_message = BaseMessage.make_assistant_message(
+ role_name="Technical Writer",
+ content="""You are a technical writer agent. Your role is to:
+ - Transform technical analysis into clear, readable reports
+ - Create well-structured documentation
+ - Make complex information accessible
+ - Write in a professional but engaging tone.""",
+ )
+ writer_agent = ChatAgent(system_message=writer_system_message, model=model)
+
+ # Research Agent
+ researcher_system_message = BaseMessage.make_assistant_message(
+ role_name="Research Agent",
+ content="""You are a research agent. Your role is to:
+ - Gather information on specific topics
+ - Provide comprehensive background research
+ - Identify relevant trends and context
+ - Support analysis with additional data points.""",
+ )
+ researcher_agent = ChatAgent(
+ system_message=researcher_system_message, model=model
+ )
+
+ # Create MessageAgentTool and register agents
+ print("๐Ÿ”— Setting up agent communication...")
+ communication_tool = MessageAgentTool(
+ {
+ "analyst": analyst_agent,
+ "writer": writer_agent,
+ "researcher": researcher_agent,
+ }
+ )
+
+ # Create Manager Agent with communication capabilities
+ manager_system_message = BaseMessage.make_assistant_message(
+ role_name="Project Manager",
+ content="""You are a project manager that coordinates other agents.
+ You have access to message_agent() function to communicate with:
+ - "analyst": For data analysis tasks
+ - "writer": For creating reports and documentation
+ - "researcher": For gathering additional information
+
+ Break down complex tasks and delegate appropriately to other agents.
+ Coordinate their work to produce comprehensive results.""",
+ )
+
+ manager_agent = ChatAgent(
+ system_message=manager_system_message,
+ model=model,
+ tools=communication_tool.get_tools(),
+ )
+
+ print("โœ… All agents set up successfully!")
+ print(f"๐Ÿ“Š Agent registry: {communication_tool.list_available_agents()}")
+ print()
+
+ # Example 1: Simple agent-to-agent communication
+ print("๐Ÿ”„ Example 1: Direct Agent Communication")
+ print("-" * 40)
+
+ # Direct message to analyst
+ message = (
+ "Analyze the trend: Sales increased 25% in Q1, 15% in Q2, "
+ "and 10% in Q3. What insights can you provide?"
+ )
+ analyst_response = communication_tool.message_agent(message, "analyst")
+ print(f"๐Ÿ’ผ Analyst Response: {analyst_response}")
+ print()
+
+ # Pass analyst result to writer
+ writer_message = (
+ f"Please create a professional summary report based on this "
+ f"analysis: {analyst_response}"
+ )
+ writer_response = communication_tool.message_agent(
+ writer_message, "writer"
+ )
+ print(f"๐Ÿ“ Writer Response: {writer_response}")
+ print()
+
+ # Example 2: Manager coordinating multiple agents
+ print("๐Ÿ”„ Example 2: Manager-Coordinated Multi-Agent Task")
+ print("-" * 40)
+
+ complex_task = """
+ We need a comprehensive report on the impact of remote work.
+ Please coordinate with the team to:
+ 1. Research current trends and studies on remote work productivity
+ 2. Analyze the key factors affecting productivity
+ 3. Create a professional report summarizing the findings
+ """
+
+ print(f"๐Ÿ“‹ Task: {complex_task}")
+ print()
+
+ # Manager coordinates the task
+ manager_response = manager_agent.step(complex_task)
+ print(f"๐Ÿ‘จโ€๐Ÿ’ผ Manager Coordination: {manager_response.msgs[0].content}")
+ print()
+
+ # Example 3: Agent management operations
+ print("๐Ÿ”„ Example 3: Agent Management Operations")
+ print("-" * 40)
+
+ # Add a new agent dynamically
+ qa_system_message = BaseMessage.make_assistant_message(
+ role_name="QA Specialist",
+ content=(
+ "You are a quality assurance specialist. "
+ "Review work for accuracy and completeness."
+ ),
+ )
+ qa_agent = ChatAgent(system_message=qa_system_message, model=model)
+
+ # Register the new agent
+ registration_result = communication_tool.register_agent(
+ "qa_specialist", qa_agent
+ )
+ print(f"+ Registration: {registration_result}")
+
+ # List all agents
+ print(
+ f"๐Ÿ“‹ Updated agent list: {communication_tool.list_available_agents()}"
+ )
+
+ # Get agent count
+ print(f"๐Ÿ”ข Agent count: {communication_tool.get_agent_count()}")
+
+ # Use the new agent
+ qa_message = (
+ "Please review this for quality: "
+ "'The report shows good trends in productivity metrics.'"
+ )
+ qa_response = communication_tool.message_agent(qa_message, "qa_specialist")
+ print(f"๐Ÿ” QA Response: {qa_response}")
+
+ # Remove an agent
+ removal_result = communication_tool.remove_agent("qa_specialist")
+ print(f"- Removal: {removal_result}")
+ print(f"๐Ÿ“‹ Final agent list: {communication_tool.list_available_agents()}")
+ print()
+
+ # Example 4: Error handling
+ print("๐Ÿ”„ Example 4: Error Handling")
+ print("-" * 40)
+
+ # Try to message non-existent agent
+ error_response = communication_tool.message_agent(
+ "Hello", "nonexistent_agent"
+ )
+ print(f"โŒ Error handling: {error_response}")
+ print()
+
+ print("๐ŸŽ‰ MessageAgentTool demonstration completed!")
+ print("This example showed:")
+ print(" โœ“ Creating specialized agents")
+ print(" โœ“ Setting up agent communication")
+ print(" โœ“ Direct agent-to-agent messaging")
+ print(" โœ“ Manager-coordinated multi-agent tasks")
+ print(" โœ“ Dynamic agent registration and removal")
+ print(" โœ“ Error handling for robust operation")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/toolkits/test_message_agent_toolkit.py b/test/toolkits/test_message_agent_toolkit.py
new file mode 100644
index 000000000..466d80502
--- /dev/null
+++ b/test/toolkits/test_message_agent_toolkit.py
@@ -0,0 +1,245 @@
+# ========= 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 unittest.mock import Mock
+
+from camel.toolkits.message_agent_toolkit import MessageAgentTool
+
+
+class TestMessageAgentTool:
+ """Test cases for MessageAgentTool."""
+
+ def test_initialization_empty(self):
+ """Test MessageAgentTool initialization with no agents."""
+ toolkit = MessageAgentTool()
+ assert toolkit.agents == {}
+ assert len(toolkit.agents) == 0
+
+ def test_initialization_with_agents(self):
+ """Test MessageAgentTool initialization with predefined agents."""
+ mock_agent1 = Mock()
+ mock_agent2 = Mock()
+ agents = {"agent1": mock_agent1, "agent2": mock_agent2}
+
+ toolkit = MessageAgentTool(agents=agents)
+ assert toolkit.agents == agents
+ assert len(toolkit.agents) == 2
+
+ def test_register_agent_new(self):
+ """Test registering a new agent."""
+ toolkit = MessageAgentTool()
+ mock_agent = Mock()
+
+ result = toolkit.register_agent("test_agent", mock_agent)
+
+ assert "test_agent" in toolkit.agents
+ assert toolkit.agents["test_agent"] == mock_agent
+ assert "registered successfully" in result.lower()
+
+ def test_register_agent_overwrite(self):
+ """Test overwriting an existing agent."""
+ mock_agent1 = Mock()
+ mock_agent2 = Mock()
+ toolkit = MessageAgentTool({"existing_agent": mock_agent1})
+
+ result = toolkit.register_agent("existing_agent", mock_agent2)
+
+ assert toolkit.agents["existing_agent"] == mock_agent2
+ assert "registered successfully" in result.lower()
+
+ def test_message_agent_success(self):
+ """Test successful message sending to an agent."""
+ mock_agent = Mock()
+ mock_response = Mock()
+ mock_response.msgs = [Mock(content="Hello back!")]
+ mock_agent.step.return_value = mock_response
+
+ toolkit = MessageAgentTool({"target_agent": mock_agent})
+
+ result = toolkit.message_agent("Hello", "target_agent")
+
+ mock_agent.step.assert_called_once_with("Hello")
+ assert result == "Hello back!"
+
+ def test_message_agent_success_string_response(self):
+ """Test successful message sending with string response."""
+ mock_agent = Mock()
+ mock_agent.step.return_value = "Simple string response"
+
+ toolkit = MessageAgentTool({"target_agent": mock_agent})
+
+ result = toolkit.message_agent("Hello", "target_agent")
+
+ mock_agent.step.assert_called_once_with("Hello")
+ assert result == "Simple string response"
+
+ def test_message_agent_not_found(self):
+ """Test messaging a non-existent agent."""
+ toolkit = MessageAgentTool()
+
+ result = toolkit.message_agent("Hello", "nonexistent_agent")
+
+ assert "Error" in result
+ assert "not found" in result
+
+ def test_message_agent_communication_error(self):
+ """Test handling communication errors."""
+ mock_agent = Mock()
+ mock_agent.step.side_effect = Exception("Communication failed")
+
+ toolkit = MessageAgentTool({"error_agent": mock_agent})
+
+ result = toolkit.message_agent("Hello", "error_agent")
+
+ assert "Error" in result
+ assert "Failed to communicate" in result
+ assert "Communication failed" in result
+
+ def test_list_available_agents_empty(self):
+ """Test listing agents when none are registered."""
+ toolkit = MessageAgentTool()
+
+ result = toolkit.list_available_agents()
+
+ assert "No agents registered" in result
+
+ def test_list_available_agents_with_agents(self):
+ """Test listing agents when multiple agents are registered."""
+ mock_agent1 = Mock()
+ mock_agent2 = Mock()
+ agents = {"agent1": mock_agent1, "agent2": mock_agent2}
+ toolkit = MessageAgentTool(agents)
+
+ result = toolkit.list_available_agents()
+
+ assert "Available agents:" in result
+ assert "agent1" in result
+ assert "agent2" in result
+
+ def test_remove_agent_success(self):
+ """Test successfully removing an agent."""
+ mock_agent = Mock()
+ toolkit = MessageAgentTool({"test_agent": mock_agent})
+
+ result = toolkit.remove_agent("test_agent")
+
+ assert "test_agent" not in toolkit.agents
+ assert "removed successfully" in result.lower()
+
+ def test_remove_agent_not_found(self):
+ """Test removing a non-existent agent."""
+ toolkit = MessageAgentTool()
+
+ result = toolkit.remove_agent("nonexistent_agent")
+
+ assert "Error" in result
+ assert "not found" in result
+
+ def test_get_agent_count_empty(self):
+ """Test getting agent count when no agents are registered."""
+ toolkit = MessageAgentTool()
+
+ result = toolkit.get_agent_count()
+
+ assert "Total registered agents: 0" in result
+
+ def test_get_agent_count_with_agents(self):
+ """Test getting agent count with multiple agents."""
+ mock_agent1 = Mock()
+ mock_agent2 = Mock()
+ mock_agent3 = Mock()
+ agents = {
+ "agent1": mock_agent1,
+ "agent2": mock_agent2,
+ "agent3": mock_agent3,
+ }
+ toolkit = MessageAgentTool(agents)
+
+ result = toolkit.get_agent_count()
+
+ assert "Total registered agents: 3" in result
+
+ def test_get_tools_returns_correct_functions(self):
+ """Test that get_tools returns all expected function tools."""
+ toolkit = MessageAgentTool()
+
+ tools = toolkit.get_tools()
+
+ assert len(tools) == 5
+ tool_names = [tool.get_function_name() for tool in tools]
+
+ expected_functions = [
+ "message_agent",
+ "register_agent",
+ "list_available_agents",
+ "remove_agent",
+ "get_agent_count",
+ ]
+
+ for expected_func in expected_functions:
+ assert expected_func in tool_names
+
+ def test_timeout_parameter(self):
+ """Test initialization with timeout parameter."""
+ toolkit = MessageAgentTool(timeout=30.0)
+
+ assert toolkit.timeout == 30.0
+
+ def test_agent_registration_flow(self):
+ """Test complete agent registration and communication flow."""
+ # Create toolkit
+ toolkit = MessageAgentTool()
+
+ # Register multiple agents
+ mock_agent1 = Mock()
+ mock_agent2 = Mock()
+
+ # Set up mock responses
+ mock_response1 = Mock()
+ mock_response1.msgs = [Mock(content="Response from agent 1")]
+ mock_agent1.step.return_value = mock_response1
+
+ mock_response2 = Mock()
+ mock_response2.msgs = [Mock(content="Response from agent 2")]
+ mock_agent2.step.return_value = mock_response2
+
+ # Register agents
+ toolkit.register_agent("agent1", mock_agent1)
+ toolkit.register_agent("agent2", mock_agent2)
+
+ # Test agent count
+ count_result = toolkit.get_agent_count()
+ assert "2" in count_result
+
+ # Test listing agents
+ list_result = toolkit.list_available_agents()
+ assert "agent1" in list_result
+ assert "agent2" in list_result
+
+ # Test messaging agents
+ response1 = toolkit.message_agent("Hello agent 1", "agent1")
+ assert response1 == "Response from agent 1"
+
+ response2 = toolkit.message_agent("Hello agent 2", "agent2")
+ assert response2 == "Response from agent 2"
+
+ # Test removing agent
+ remove_result = toolkit.remove_agent("agent1")
+ assert "removed successfully" in remove_result.lower()
+ assert "agent1" not in toolkit.agents
+ assert "agent2" in toolkit.agents
+
+ # Test final count
+ final_count = toolkit.get_agent_count()
+ assert "1" in final_count