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

enhance: Add MessageAgentTool for agent communication PR2771 (#2805)

Wendong-Fan91f26e424a7a
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.py
index 8d4c033d6..cce3ef51c 100644
--- a/camel/toolkits/__init__.py
+++ b/camel/toolkits/__init__.py
@@ -83,6 +83,7 @@ from .google_drive_mcp_toolkit import GoogleDriveMCPToolkit
from .craw4ai_toolkit import Crawl4AIToolkit
from .markitdown_toolkit import MarkItDownToolkit
from .note_taking_toolkit import NoteTakingToolkit
+from .message_agent_toolkit import AgentCommunicationToolkit
__all__ = [
'BaseToolkit',
@@ -154,4 +155,5 @@ __all__ = [
'Crawl4AIToolkit',
'MarkItDownToolkit',
'NoteTakingToolkit',
+ 'AgentCommunicationToolkit',
]
diff --git a/camel/toolkits/message_agent_toolkit.py b/camel/toolkits/message_agent_toolkit.py
index d3ef2397c..2bd8d5fd7 100644
--- a/camel/toolkits/message_agent_toolkit.py
+++ b/camel/toolkits/message_agent_toolkit.py
@@ -12,47 +12,107 @@
# limitations under the License.
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+import json
+import time
+import uuid
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from camel.logger import get_logger
+from camel.messages import BaseMessage
from camel.toolkits.base import BaseToolkit
from camel.toolkits.function_tool import FunctionTool
+from camel.types import RoleType
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.
+class AgentMessage(BaseMessage):
+ r"""Represents a message between agents, extending BaseMessage.
- This toolkit allows agents to send messages to other agents by their IDs
- and receive responses, enabling multi-agent collaboration.
+ This class extends the standard CAMEL BaseMessage with additional
+ attributes needed for inter-agent communication.
+ """
+
+ def __init__(
+ self,
+ message_id: str,
+ sender_id: str,
+ receiver_id: str,
+ content: str,
+ timestamp: float,
+ reply_to: Optional[str] = None,
+ metadata: Optional[Dict[str, Any]] = None,
+ ):
+ # Initialize BaseMessage with standard fields
+ super().__init__(
+ role_name=sender_id,
+ role_type=RoleType.ASSISTANT,
+ meta_dict=metadata or {},
+ content=content,
+ )
+
+ # Add agent-specific fields
+ self.id = message_id
+ self.sender_id = sender_id
+ self.receiver_id = receiver_id
+ self.timestamp = timestamp
+ self.reply_to = reply_to
+ self.metadata = metadata or {}
+
+
+class AgentCommunicationToolkit(BaseToolkit):
+ r"""A toolkit for agent-to-agent communication in multi-agent systems.
+
+ Enables agents to send messages to each other with message history tracking
+ and integration with the CAMEL workforce system.
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`)
+ agents (Optional[Dict[str, ChatAgent]]): Dictionary mapping agent IDs
+ to ChatAgent instances. (default: :obj:`None`)
+ timeout (Optional[float]): Maximum execution time for operations in
+ seconds. (default: :obj:`None`)
+ max_message_history (int): Maximum messages to keep per agent.
+ (default: :obj:`100`)
+ get_response (bool): Whether to get responses from receiving agents
+ by default. (default: :obj:`False`)
+
+ Example:
+ >>> msg_toolkit = AgentCommunicationToolkit(get_response=False)
+ >>> msg_toolkit.register_agent("agent1", agent1)
+ >>> msg_toolkit.register_agent("agent2", agent2)
+ >>>
+ >>> # Add tools to agents
+ >>> for tool in msg_toolkit.get_tools():
+ ... agent1.add_tool(tool)
+ ... agent2.add_tool(tool)
"""
def __init__(
self,
- agents: Optional[Dict[str, ChatAgent]] = None,
+ agents: Optional[Dict[str, "ChatAgent"]] = None,
timeout: Optional[float] = None,
+ max_message_history: int = 100,
+ get_response: bool = False,
) -> None:
super().__init__(timeout=timeout)
self.agents = agents or {}
+ self.max_message_history = max_message_history
+ self.get_response = get_response
+
+ # Message management
+ self._message_history: Dict[str, List[AgentMessage]] = {}
+ self._conversation_threads: Dict[str, List[str]] = {}
+
logger.info(
- f"MessageAgentTool initialized with {len(self.agents)} agents"
+ f"AgentCommunicationToolkit initialized with {len(self.agents)} "
+ f"agents. "
+ f"Max history: {max_message_history}, Get response: {get_response}"
)
- def register_agent(self, agent_id: str, agent: ChatAgent) -> str:
+ def register_agent(self, agent_id: str, agent: "ChatAgent") -> str:
r"""Register a new agent for communication.
Args:
@@ -60,72 +120,398 @@ class MessageAgentTool(BaseToolkit):
agent (ChatAgent): The ChatAgent instance to register.
Returns:
- str: Confirmation message.
+ str: Confirmation message with registration details.
+
+ Raises:
+ ValueError: If agent_id is empty or agent is None.
"""
if agent_id in self.agents:
logger.warning(f"Agent {agent_id} already exists, overwriting")
self.agents[agent_id] = agent
+
+ # Initialize message history for new agent
+ if agent_id not in self._message_history:
+ self._message_history[agent_id] = []
+
logger.info(f"Registered agent: {agent_id}")
- return f"Agent {agent_id} registered successfully"
+ return (
+ f"Agent {agent_id} registered successfully. "
+ f"Total agents: {len(self.agents)}"
+ )
+
+ def _find_agent_id(self, agent_id: str) -> Optional[str]:
+ r"""Find agent ID with flexible matching (case-insensitive, partial
+ matches).
+ """
+ # First try exact match
+ if agent_id in self.agents:
+ return agent_id
+
+ # Try case-insensitive exact match
+ agent_id_lower = agent_id.lower()
+ for registered_id in self.agents.keys():
+ if registered_id.lower() == agent_id_lower:
+ return registered_id
+
+ # Try partial matching for common patterns like "writer_01" -> "Writer"
+ # Remove common suffixes and prefixes
+ clean_id = agent_id_lower
+
+ # Remove common patterns: _01, _123, _agent, etc.
+ import re
+
+ clean_id = re.sub(r'_\d+$', '', clean_id) # Remove trailing _numbers
+ clean_id = re.sub(r'_agent$', '', clean_id) # Remove trailing _agent
+ clean_id = re.sub(r'^agent_', '', clean_id) # Remove leading agent_
+
+ # Try to match cleaned ID
+ for registered_id in self.agents.keys():
+ if registered_id.lower() == clean_id:
+ return registered_id
+ # Also try if the registered ID starts with our cleaned ID
+ if registered_id.lower().startswith(clean_id):
+ return registered_id
- def message_agent(self, message: str, receiver_agent_id: str) -> str:
- r"""Send a message to another agent and get the response.
+ return None
+
+ def send_message(
+ self,
+ message: str,
+ receiver_id: str,
+ sender_id: str = "system",
+ reply_to: Optional[str] = None,
+ metadata_json: Optional[str] = None,
+ ) -> str:
+ r"""Sends a message to a specific agent.
+
+ This function allows one agent to communicate directly with another by
+ sending a message. The toolkit's get_response setting determines
+ whether to get an immediate response or just send a notification. To
+ get the `receiver_id` of the agent you want to communicate with, you
+ can use the `list_available_agents` tool.
Args:
- message (str): The message to send to the target agent.
- receiver_agent_id (str): Unique identifier of the target agent.
+ message (str): The content of the message to send.
+ receiver_id (str): The unique identifier of the agent to receive
+ the message. Use `list_available_agents()` to find the ID of
+ the agent you want to talk to.
+ sender_id (str): The unique identifier of the agent sending the
+ message. This is typically your agent's ID.
+ (default: :obj:`"system"`)
+ reply_to (Optional[str]): The ID of a previous message this new
+ message is a reply to. This helps create conversation threads.
+ (default: :obj:`None`)
+ metadata_json (Optional[str]): A JSON string containing extra
+ information about the message.
+ (default: :obj:`None`)
Returns:
- str: Response from the target agent or error message if the
- operation fails.
+ str: A confirmation that the message was sent. If the toolkit's
+ get_response setting is True, includes the response from the
+ receiving agent.
"""
- 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}"
+ if not message or not message.strip():
+ raise ValueError("Message content cannot be empty")
+
+ # Find the actual agent ID (case-insensitive)
+ actual_receiver_id = self._find_agent_id(receiver_id)
+ if not actual_receiver_id:
+ available_agents = ", ".join(self.agents.keys())
+ error_msg = (
+ f"Agent {receiver_id} not found. "
+ f"Available agents: {available_agents}"
+ )
+ logger.error(error_msg)
+ return f"Error: {error_msg}"
+
+ # Parse metadata from JSON string
+ metadata = {}
+ if metadata_json:
+ try:
+ metadata = json.loads(metadata_json)
+ if not isinstance(metadata, dict):
+ logger.warning(
+ "Metadata must be a JSON object, using empty dict"
+ )
+ metadata = {}
+ except json.JSONDecodeError:
+ logger.warning(
+ "Invalid JSON in metadata_json, using empty dict"
+ )
+ metadata = {}
+
+ # Create message
+ agent_message = AgentMessage(
+ message_id=str(uuid.uuid4()),
+ sender_id=sender_id,
+ receiver_id=actual_receiver_id, # Use the resolved agent ID
+ content=message,
+ timestamp=time.time(),
+ reply_to=reply_to,
+ metadata=metadata,
+ )
+
+ # Handle threading
+ if reply_to:
+ self._update_conversation_thread(reply_to, agent_message.id)
+
+ # Deliver message (with or without response)
+ return self._deliver_message(agent_message, self.get_response)
+ def _deliver_message(
+ self, message: AgentMessage, get_response: bool
+ ) -> str:
+ r"""Deliver a message to the target agent, optionally getting a
+ response.
+ """
try:
- target_agent = self.agents[receiver_agent_id]
+ target_agent = self.agents[message.receiver_id]
logger.info(
- f"Sending message to agent {receiver_agent_id}: "
- f"{message[:50]}..."
+ f"Delivering message {message.id} to agent "
+ f"{message.receiver_id}"
)
- response = target_agent.step(message)
+ self._add_to_history(message)
- # Extract response content based on response type
- if hasattr(response, 'msgs') and response.msgs:
- response_content = response.msgs[0].content
+ # Create a clear, structured message for the agent
+ structured_message = (
+ f"A message has been received from agent with "
+ f"ID '{message.sender_id}'.\n\n"
+ "--- Message Content ---\n"
+ f"{message.content}\n"
+ "--- End of Message ---"
+ )
+ response = target_agent.step(structured_message)
+
+ if get_response:
+ # Extract and return response content
+ if hasattr(response, 'msgs') and response.msgs:
+ response_content = response.msgs[0].content
+ else:
+ response_content = str(response)
+
+ logger.info(
+ f"Message {message.id} delivered with response. "
+ f"Response length: {len(response_content)}"
+ )
+
+ return (
+ f"Message {message.id} delivered to "
+ f"{message.receiver_id}. "
+ f"Response: {response_content[:100]}"
+ f"{'...' if len(response_content) > 100 else ''}"
+ )
else:
- response_content = str(response)
+ # Message delivered but response not requested
+ logger.info(
+ f"Message {message.id} delivered to agent "
+ f"{message.receiver_id} (response not requested)"
+ )
+
+ return (
+ f"Message {message.id} delivered to "
+ f"{message.receiver_id}. "
+ f"Message: '{message.content[:50]}"
+ f"{'...' if len(message.content) > 50 else ''}'"
+ )
- logger.info(
- f"Received response from {receiver_agent_id}: "
- f"{response_content[:50]}..."
+ except Exception as e:
+ error_msg = f"Failed to deliver message {message.id}: {e!s}"
+ logger.error(error_msg)
+ return f"Error: {error_msg}"
+
+ def broadcast_message(
+ self,
+ message: str,
+ sender_id: str = "system",
+ exclude_agents: Optional[List[str]] = None,
+ ) -> str:
+ r"""Sends a message to all other agents in the system.
+
+ This function is useful for making announcements or sending information
+ that every agent needs. The message will be sent to all registered
+ agents except for the sender and any agents specified in the
+ `exclude_agents` list.
+
+ Args:
+ message (str): The content of the message to broadcast.
+ sender_id (str): The unique identifier of the agent sending the
+ message. This is typically your agent's ID.
+ (default: :obj:`"system"`)
+ exclude_agents (Optional[List[str]]): A list of agent IDs to
+ exclude from the broadcast. The sender is automatically
+ excluded.
+ (default: :obj:`None`)
+
+ Returns:
+ str: A summary of the broadcast, showing which agents received the
+ message and their responses.
+ """
+ if not message or not message.strip():
+ return "Error: Message content cannot be empty"
+
+ exclude_set = set(exclude_agents or [])
+ if sender_id:
+ exclude_set.add(sender_id) # Don't send to self
+
+ target_agents = [
+ agent_id
+ for agent_id in self.agents.keys()
+ if agent_id not in exclude_set
+ ]
+
+ if not target_agents:
+ return "No target agents available for broadcast"
+
+ results = []
+ for agent_id in target_agents:
+ try:
+ result = self.send_message(
+ message=message,
+ receiver_id=agent_id,
+ sender_id=sender_id,
+ metadata_json='{"broadcast": true}',
+ )
+ results.append(f"{agent_id}: {result}")
+ except Exception as e:
+ results.append(f"{agent_id}: Error - {e}")
+
+ logger.info(f"Broadcast sent to {len(target_agents)} agents")
+ return "Broadcast completed. Results:\n" + "\n".join(results)
+
+ def get_message_history(
+ self, agent_id: str, limit: Optional[int] = None
+ ) -> str:
+ r"""Retrieves the message history for a specific agent.
+
+ This function allows you to see the messages sent and received by a
+ particular agent, which can be useful for understanding past
+ conversations. To get the `agent_id` for another agent, use the
+ `list_available_agents` tool. You can also use this tool to get
+ your own message history by providing your agent ID.
+
+ Args:
+ agent_id (str): The unique identifier of the agent whose message
+ history you want to retrieve. Use `list_available_agents()`
+ to find available agent IDs.
+ limit (Optional[int]): The maximum number of recent messages to
+ return. If not specified, it will return all messages up to
+ the system's limit.
+ (default: :obj:`None`)
+
+ Returns:
+ str: A formatted string containing the message history for the
+ specified agent, or an error if the agent is not found.
+ """
+ actual_agent_id = self._find_agent_id(agent_id)
+ if not actual_agent_id:
+ return f"No message history found for agent {agent_id}"
+
+ history = self._message_history.get(actual_agent_id, [])
+ if limit:
+ history = history[-limit:]
+
+ if not history:
+ return f"No messages in history for agent {agent_id}"
+
+ formatted_history = []
+ for msg in history:
+ timestamp_str = time.strftime(
+ '%Y-%m-%d %H:%M:%S', time.localtime(msg.timestamp)
+ )
+ formatted_history.append(
+ f"[{timestamp_str}] {msg.sender_id} -> {msg.receiver_id}: "
+ f"{msg.content[:100]}{'...' if len(msg.content) > 100 else ''}"
)
- return response_content
- except Exception as e:
- error_message = (
- f"Failed to communicate with agent {receiver_agent_id}: {e!s}"
+ return (
+ f"Message history for {agent_id} "
+ f"({len(formatted_history)} messages):\n"
+ + "\n".join(formatted_history)
+ )
+
+ def get_conversation_thread(self, message_id: str) -> str:
+ r"""Retrieves a full conversation thread based on a message ID.
+
+ When you send a message that is a reply to another, it creates a
+ conversation thread. This function lets you retrieve all messages
+ that are part of that thread. You can find message IDs in the
+ message history or from the output of the `send_message` tool.
+
+ Args:
+ message_id (str): The unique identifier of any message within the
+ conversation thread you want to retrieve.
+
+ Returns:
+ str: A formatted string containing all messages in the
+ conversation, sorted by time, or an error if the thread is
+ not found.
+ """
+ if message_id not in self._conversation_threads:
+ return f"No conversation thread found for message {message_id}"
+
+ thread_ids = self._conversation_threads[message_id]
+ thread_messages = []
+
+ # Find messages in history
+ for agent_history in self._message_history.values():
+ for msg in agent_history:
+ if msg.id in thread_ids:
+ thread_messages.append(msg)
+
+ # Sort by timestamp
+ thread_messages.sort(key=lambda x: x.timestamp)
+
+ if not thread_messages:
+ return f"No messages found in thread for {message_id}"
+
+ formatted_thread = []
+ for msg in thread_messages:
+ timestamp_str = time.strftime(
+ '%H:%M:%S', time.localtime(msg.timestamp)
+ )
+ formatted_thread.append(
+ f"[{timestamp_str}] {msg.sender_id}: {msg.content}"
)
- logger.error(error_message)
- return f"Error: {error_message}"
+
+ return (
+ f"Conversation thread ({len(formatted_thread)} messages):\n"
+ + "\n".join(formatted_thread)
+ )
def list_available_agents(self) -> str:
- r"""List all registered agents and their IDs.
+ r"""Lists all agents currently available for communication.
+
+ Call this function to discover which other agents are in the system
+ that you can communicate with. The returned list will contain the
+ unique IDs for each agent, which you can then use with tools like
+ `send_message` and `get_message_history`.
Returns:
- str: Formatted list of registered agent IDs or message if no
- agents are registered.
+ str: A formatted string listing the IDs and status of all
+ available agents.
"""
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}"
+ agent_info = []
+ for agent_id, agent in self.agents.items():
+ # Get message count for this agent
+ msg_count = len(self._message_history.get(agent_id, []))
+
+ # Check if agent has pause support
+ has_pause = hasattr(agent, 'pause_event')
+
+ status_info = f"Messages: {msg_count}"
+ if has_pause:
+ status_info += ", Workforce-compatible"
+
+ agent_info.append(f" - {agent_id}: {status_info}")
+
+ return f"Available agents ({len(self.agents)}):\n" + "\n".join(
+ agent_info
+ )
def remove_agent(self, agent_id: str) -> str:
r"""Remove an agent from the communication registry.
@@ -134,39 +520,89 @@ class MessageAgentTool(BaseToolkit):
agent_id (str): Unique identifier of the agent to remove.
Returns:
- str: Confirmation message or error message if agent not found.
+ str: Confirmation message with cleanup details.
"""
if agent_id not in self.agents:
- error_message = f"Agent {agent_id} not found"
- logger.error(error_message)
- return f"Error: {error_message}"
+ return f"Error: Agent {agent_id} not found"
del self.agents[agent_id]
+
+ # Keep message history for audit purposes but note agent removal
+ if agent_id in self._message_history:
+ logger.info(
+ f"Preserved {len(self._message_history[agent_id])} "
+ f"messages for removed agent {agent_id}"
+ )
+
logger.info(f"Removed agent: {agent_id}")
- return f"Agent {agent_id} removed successfully"
+ return (
+ f"Agent {agent_id} removed successfully. "
+ f"Remaining agents: {len(self.agents)}"
+ )
- def get_agent_count(self) -> str:
- r"""Get the number of registered agents.
+ def get_toolkit_status(self) -> str:
+ r"""Get comprehensive status of the message toolkit.
Returns:
- str: Number of currently registered agents.
+ str: Detailed status information including metrics and queue state.
"""
- count = len(self.agents)
- logger.info(f"Agent count requested: {count}")
- return f"Total registered agents: {count}"
+ total_messages = sum(
+ len(history) for history in self._message_history.values()
+ )
+
+ status_info = [
+ "AgentCommunicationToolkit Status:",
+ f" - Registered agents: {len(self.agents)}",
+ f" - Total message history: {total_messages}",
+ f" - Max history per agent: {self.max_message_history}",
+ ]
+
+ return "\n".join(status_info)
+
+ def _add_to_history(self, message: AgentMessage) -> None:
+ r"""Add a message to the history with size management."""
+ # Add to sender's history
+ sender_history = self._message_history.setdefault(
+ message.sender_id, []
+ )
+ sender_history.append(message)
+
+ # Add to receiver's history
+ receiver_history = self._message_history.setdefault(
+ message.receiver_id, []
+ )
+ receiver_history.append(message)
+
+ # Trim history if needed
+ for agent_id, history in self._message_history.items():
+ if len(history) > self.max_message_history:
+ self._message_history[agent_id] = history[
+ -self.max_message_history :
+ ]
+
+ def _update_conversation_thread(self, parent_id: str, new_id: str) -> None:
+ r"""Update conversation threading."""
+ if parent_id in self._conversation_threads:
+ self._conversation_threads[parent_id].append(new_id)
+ else:
+ self._conversation_threads[new_id] = [parent_id, new_id]
def get_tools(self) -> List[FunctionTool]:
r"""Returns a list of FunctionTool objects representing the
communication functions in the toolkit.
+ Note: Only includes functions that are safe and useful for LLMs to
+ call. Administrative functions like register_agent and remove_agent are
+ excluded as they should only be called programmatically.
+
Returns:
List[FunctionTool]: A list of FunctionTool objects for agent
communication and management.
"""
return [
- FunctionTool(self.message_agent),
- FunctionTool(self.register_agent),
+ FunctionTool(self.send_message),
+ FunctionTool(self.broadcast_message),
FunctionTool(self.list_available_agents),
- FunctionTool(self.remove_agent),
- FunctionTool(self.get_agent_count),
+ FunctionTool(self.get_message_history),
+ FunctionTool(self.get_conversation_thread),
]
diff --git a/examples/toolkits/message_agent_toolkit.py b/examples/toolkits/message_agent_toolkit.py
index d4803878b..000980522 100644
--- a/examples/toolkits/message_agent_toolkit.py
+++ b/examples/toolkits/message_agent_toolkit.py
@@ -11,223 +11,148 @@
# 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
+import asyncio
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
+from camel.societies.workforce import Workforce
+from camel.tasks import Task
+from camel.toolkits import AgentCommunicationToolkit
+
+
+def create_messaging_workforce():
+ r"""Create a workforce where agents can communicate with each other."""
+
+ # 1. Initialize the message toolkit
+ msg_toolkit = AgentCommunicationToolkit(max_message_history=100)
+
+ # 2. Create agents with specific roles
+ researcher = ChatAgent(
+ BaseMessage.make_assistant_message(
+ role_name="Researcher",
+ content=(
+ "You are a Research Specialist. ALWAYS use send_message to "
+ "share your findings with the writer. First use "
+ "list_available_agents to see who you can message, then "
+ "send your research findings to the writer."
+ ),
+ )
+ )
+
+ writer = ChatAgent(
+ BaseMessage.make_assistant_message(
+ role_name="Writer",
+ content=(
+ "You are a Content Writer. ALWAYS use send_message to "
+ "coordinate. After creating content, send it to the "
+ "reviewer for feedback. Use messaging tools to communicate "
+ "with team members."
+ ),
+ )
+ )
+
+ reviewer = ChatAgent(
+ BaseMessage.make_assistant_message(
+ role_name="Reviewer",
+ content=(
+ "You are a Content Reviewer. ALWAYS use send_message to "
+ "provide feedback to the writer. Use messaging tools to "
+ "coordinate and ensure quality. Send detailed feedback via "
+ "messages."
+ ),
+ )
+ )
+
+ # 3. Register agents with the message toolkit using role names that match
+ msg_toolkit.register_agent("Researcher", researcher)
+ msg_toolkit.register_agent("Writer", writer)
+ msg_toolkit.register_agent("Reviewer", reviewer)
+
+ # 4. Add messaging tools to each agent
+ message_tools = msg_toolkit.get_tools()
+ for agent in [researcher, writer, reviewer]:
+ for tool in message_tools:
+ agent.add_tool(tool)
+
+ # 5. Create workforce and add workers with matching names
+ workforce = Workforce("Content Creation Team")
+ workforce.add_single_agent_worker("Researcher", researcher)
+ workforce.add_single_agent_worker("Writer", writer)
+ workforce.add_single_agent_worker("Reviewer", reviewer)
+
+ return workforce, msg_toolkit
+
+
+async def demonstrate_coordination():
+ r"""Show how agents coordinate using messaging during task execution."""
+
+ print("🏗️ Setting up messaging-enabled workforce...")
+ workforce, msg_toolkit = create_messaging_workforce()
+
+ print("📋 Available agents:")
+ print(msg_toolkit.list_available_agents())
+
+ # Create a task that requires coordination
+ task = Task(
+ content=(
+ "IMPORTANT: You MUST use the messaging tools for coordination! "
+ "\n\nTask: Research and write a brief article about the "
+ "benefits of AI collaboration."
+ "\n\nRequired workflow:"
+ "\n1. Researcher: First use list_available_agents(), then "
+ "send_message() to share findings with writer"
+ "\n2. Writer: Use send_message() to send draft to reviewer for "
+ "feedback"
+ "\n3. Reviewer: Use send_message() to provide feedback to writer"
+ "\n\nYou MUST demonstrate inter-agent messaging capabilities!"
+ ),
+ id="collaborative_article_task",
)
- # Create MessageAgentTool and register agents
- print("🔗 Setting up agent communication...")
- communication_tool = MessageAgentTool(
- {
- "analyst": analyst_agent,
- "writer": writer_agent,
- "researcher": researcher_agent,
- }
- )
+ print(f"\n🎯 Processing coordinated task: {task.id}")
- # 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.""",
- )
+ # Process the task
+ result = await workforce.process_task_async(task)
- manager_agent = ChatAgent(
- system_message=manager_system_message,
- model=model,
- tools=communication_tool.get_tools(),
- )
+ print(f"\n✅ Task Status: {result.state}")
+ result_preview = result.result[:200] if result.result else "No result"
+ print(f"📄 Result Preview: {result_preview}...")
- print("✅ All agents set up successfully!")
- print(f"📊 Agent registry: {communication_tool.list_available_agents()}")
- print()
+ # Show message exchange that occurred
+ print("\n💬 Message Activity Summary:")
+ for agent_id in ["researcher", "writer", "reviewer"]:
+ history = msg_toolkit.get_message_history(agent_id, limit=5)
+ print(f"\n{agent_id.upper()}:")
+ print(history)
- # Example 1: Simple agent-to-agent communication
- print("🔄 Example 1: Direct Agent Communication")
- print("-" * 40)
+ print("\n📊 Final Toolkit Status:")
+ print(msg_toolkit.get_toolkit_status())
- # 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."
+ # Add a demonstration of manual messaging
+ print("\n🔧 Manual messaging demonstration:")
+ print("Sending a coordination message...")
+ manual_result = msg_toolkit.send_message(
+ message=(
+ "Great job everyone! The collaboration workflow is working "
+ "perfectly."
),
+ receiver_id="researcher",
+ sender_id="system",
)
- 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(f"Manual message result: {manual_result}")
- 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")
+ # Show updated history
+ print("\n📝 Updated message history:")
+ updated_history = msg_toolkit.get_message_history("researcher", limit=3)
+ print(updated_history)
if __name__ == "__main__":
- main()
+ print("🚀 AgentCommunicationToolkit + Workforce Quick Start")
+ print("=" * 60)
+
+ # Try workforce demo first
+ try:
+ asyncio.run(demonstrate_coordination())
+ except Exception as e:
+ print(f"⚠️ Workforce demo failed: {e}")
diff --git a/test/toolkits/test_message_agent_toolkit.py b/test/toolkits/test_message_agent_toolkit.py
index 466d80502..9dd52ad05 100644
--- a/test/toolkits/test_message_agent_toolkit.py
+++ b/test/toolkits/test_message_agent_toolkit.py
@@ -12,234 +12,196 @@
# 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()
-
+import json
+import time
+import uuid
+from unittest.mock import MagicMock
+
+import pytest
+
+from camel.agents import ChatAgent
+from camel.messages import BaseMessage
+from camel.toolkits.message_agent_toolkit import (
+ AgentCommunicationToolkit,
+ AgentMessage,
+)
+
+
+class TestAgentMessage:
+ r"""Test suite for the AgentMessage class."""
+
+ def test_agent_message_initialization(self):
+ r"""Test AgentMessage initialization with core parameters."""
+ message_id = str(uuid.uuid4())
+ sender_id = "agent1"
+ receiver_id = "agent2"
+ content = "Hello, this is a test message"
+ timestamp = time.time()
+
+ message = AgentMessage(
+ message_id=message_id,
+ sender_id=sender_id,
+ receiver_id=receiver_id,
+ content=content,
+ timestamp=timestamp,
+ )
+
+ assert message.id == message_id
+ assert message.sender_id == sender_id
+ assert message.receiver_id == receiver_id
+ assert message.content == content
+ assert message.timestamp == timestamp
+ assert isinstance(message, BaseMessage)
+
+
+class TestAgentCommunicationToolkit:
+ r"""Test suite for the AgentCommunicationToolkit class."""
+
+ @pytest.fixture
+ def mock_agent(self):
+ r"""Create a mock ChatAgent for testing."""
+ agent = MagicMock(spec=ChatAgent)
+ agent.step.return_value = MagicMock(
+ msgs=[MagicMock(content="Mock response")]
+ )
+ return agent
+
+ @pytest.fixture
+ def toolkit(self):
+ r"""Create a AgentCommunicationToolkit instance for testing."""
+ return AgentCommunicationToolkit()
+
+ @pytest.fixture
+ def toolkit_with_agents(self):
+ r"""Create a AgentCommunicationToolkit with pre-registered agents."""
+ agent1 = MagicMock(spec=ChatAgent)
+ agent1.step.return_value = MagicMock(
+ msgs=[MagicMock(content="Agent1 response")]
+ )
+
+ agent2 = MagicMock(spec=ChatAgent)
+ agent2.step.return_value = MagicMock(
+ msgs=[MagicMock(content="Agent2 response")]
+ )
+
+ toolkit = AgentCommunicationToolkit(
+ agents={"agent1": agent1, "agent2": agent2}
+ )
+ return toolkit
+
+ def test_register_agent(self, toolkit, mock_agent):
+ r"""Test agent registration."""
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()
+ def test_send_message_success(self, toolkit_with_agents):
+ r"""Test successful message sending."""
+ result = toolkit_with_agents.send_message(
+ message="Hello, agent2!",
+ receiver_id="agent2",
+ sender_id="agent1",
+ )
- 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)
+ assert "delivered" in result.lower()
+ assert "agent2" in result
+ assert len(toolkit_with_agents._message_history["agent1"]) == 1
+ assert len(toolkit_with_agents._message_history["agent2"]) == 1
+
+ def test_send_message_with_metadata(self, toolkit_with_agents):
+ r"""Test message sending with metadata."""
+ metadata = {"priority": "high"}
+ result = toolkit_with_agents.send_message(
+ message="Urgent message",
+ receiver_id="agent2",
+ sender_id="agent1",
+ metadata_json=json.dumps(metadata),
+ )
+
+ assert "delivered" in result.lower()
+ history = toolkit_with_agents._message_history["agent1"]
+ assert history[0].metadata == metadata
+
+ def test_send_message_agent_not_found(self, toolkit_with_agents):
+ r"""Test sending message to non-existent agent."""
+ result = toolkit_with_agents.send_message(
+ message="Hello",
+ receiver_id="nonexistent",
+ sender_id="agent1",
+ )
+
+ assert "error" in result.lower()
+ assert "not found" in result.lower()
+
+ def test_send_message_empty_content(self, toolkit_with_agents):
+ r"""Test sending message with empty content."""
+ with pytest.raises(
+ ValueError, match="Message content cannot be empty"
+ ):
+ toolkit_with_agents.send_message(
+ message="",
+ receiver_id="agent2",
+ sender_id="agent1",
+ )
+
+ def test_broadcast_message(self, toolkit_with_agents):
+ r"""Test broadcast message functionality."""
+ result = toolkit_with_agents.broadcast_message(
+ message="Broadcast to all",
+ sender_id="system",
+ )
+
+ assert "broadcast completed" in result.lower()
+ assert "agent1:" in result
+ assert "agent2:" in result
+
+ def test_get_message_history(self, toolkit_with_agents):
+ r"""Test retrieving message history."""
+ toolkit_with_agents.send_message("Hello", "agent2", "agent1")
+
+ result = toolkit_with_agents.get_message_history("agent1")
+
+ assert "message history" in result.lower()
+ assert "agent1" in result
+ assert "hello" in result.lower()
- result = toolkit.list_available_agents()
+ def test_list_available_agents(self, toolkit_with_agents):
+ r"""Test listing available agents."""
+ result = toolkit_with_agents.list_available_agents()
- assert "Available agents:" in result
+ assert "available agents" in result.lower()
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()
-
+ def test_get_tools_returns_function_tools(self, toolkit):
+ r"""Test that get_tools returns proper FunctionTool objects."""
tools = toolkit.get_tools()
assert len(tools) == 5
- tool_names = [tool.get_function_name() for tool in tools]
+ tool_names = [tool.func.__name__ for tool in tools]
- expected_functions = [
- "message_agent",
- "register_agent",
+ expected_tools = [
+ "send_message",
+ "broadcast_message",
"list_available_agents",
- "remove_agent",
- "get_agent_count",
+ "get_message_history",
+ "get_conversation_thread",
]
- 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"
+ for expected_tool in expected_tools:
+ assert expected_tool in tool_names
- response2 = toolkit.message_agent("Hello agent 2", "agent2")
- assert response2 == "Response from agent 2"
+ def test_message_history_size_management(self, toolkit_with_agents):
+ r"""Test message history size management."""
+ toolkit_with_agents.max_message_history = 3
- # 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
+ # Send more messages than the limit
+ for i in range(5):
+ toolkit_with_agents.send_message(
+ f"Message {i}", "agent2", "agent1"
+ )
- # Test final count
- final_count = toolkit.get_agent_count()
- assert "1" in final_count
+ history = toolkit_with_agents._message_history["agent1"]
+ assert len(history) == 3