🐫 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
Fix update messages and add docstrings and tests (#90)
Guohao Li76ca54fc89ad
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex 5655079b3..d490b1511 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -10,6 +10,18 @@ from camel.utils import get_model_token_limit, num_tokens_from_messagesclass ChatAgent:+ r"""Class for managing conversations of CAMEL Chat Agents.++ Args:+ system_message (SystemMessage): The system message for the chat agent.+ model (ModelType, optional): The LLM model to use for generating+ responses. (default :obj:`ModelType.GPT_3_5_TURBO`)+ model_config (Any, optional): Configuration options for the LLM model.+ (default: :obj:`None`)+ message_window_size (int, optional): The maximum number of previous+ messages to include in the context window. If `None`, no windowing+ is performed. (default: :obj:`None`)+ """def __init__(self,@@ -18,6 +30,7 @@ class ChatAgent:model_config: Any = None,message_window_size: Optional[int] = None,) -> None:+self.system_message = system_messageself.role_name = system_message.role_nameself.role_type = system_message.role_type@@ -31,7 +44,13 @@ class ChatAgent:self.terminated = Falseself.init_messages()- def reset(self) -> None:+ def reset(self) -> List[MessageType]:+ r"""Resets the :obj:`ChatAgent` to its initial state and returns the+ stored messages.++ Returns:+ List[MessageType]: The stored messages.+ """self.terminated = Falseself.init_messages()return self.stored_messages@@ -43,6 +62,19 @@ class ChatAgent:termination_reasons: List[str],num_tokens: int,) -> Dict[str, Any]:+ r"""Returns a dictionary containing information about the chat session.++ Args:+ id (str, optional): The ID of the chat session.+ usage (Dict[str, int], optional): Information about the usage of+ the LLM model.+ termination_reasons (List[str]): The reasons for the termination of+ the chat session.+ num_tokens (int): The number of tokens used in the chat session.++ Returns:+ Dict[str, Any]: The chat session information.+ """return {"id": id,"usage": usage,@@ -51,9 +83,21 @@ class ChatAgent:}def init_messages(self) -> None:+ r"""Initializes the stored messages list with the initial system+ message.+ """self.stored_messages: List[MessageType] = [self.system_message]def update_messages(self, message: ChatMessage) -> List[ChatMessage]:+ r"""Updates the stored messages list with a new message.++ Args:+ message (ChatMessage): The new message to add to the stored+ messages.++ Returns:+ List[ChatMessage]: The updated stored messages.+ """self.stored_messages.append(message)return self.stored_messages@@ -62,6 +106,18 @@ class ChatAgent:self,input_message: ChatMessage,) -> Tuple[Optional[List[ChatMessage]], bool, Dict[str, Any]]:+ r"""Performs a single step in the chat session by generating a response+ to the input message.++ Args:+ input_message (ChatMessage): The input message to the agent.++ Returns:+ Tuple[Optional[List[ChatMessage]], bool, Dict[str, Any]]: A tuple+ containing the output messages, a boolean indicating whether+ the chat session has terminated, and information about the chat+ session.+ """messages = self.update_messages(input_message)if self.message_window_size is not None and len(messages) > self.message_window_size:@@ -90,7 +146,6 @@ class ChatAgent:],num_tokens,)- self.update_messages(output_messages[0])else:self.terminated = True@@ -106,4 +161,9 @@ class ChatAgent:return output_messages, self.terminated, infodef __repr__(self) -> str:+ r"""Returns a string representation of the :obj:`ChatAgent`.++ Returns:+ str: The string representation of the :obj:`ChatAgent`.+ """return f"ChatAgent({self.role_name}, {self.role_type}, {self.model})"diff --git a/camel/agents/role_playing.py b/camel/agents/role_playing.pyindex bcb894577..ea51e30f7 100644--- a/camel/agents/role_playing.py+++ b/camel/agents/role_playing.py@@ -142,7 +142,6 @@ class RolePlaying:content=(f"{self.user_sys_msg.content}. ""Now start to give me introductions one by one. ""Only reply with Instruction and Input."))- assistant_msg.role = "user"user_msg = UserChatMessage(role_name=self.user_sys_msg.role_name,content=f"{self.assistant_sys_msg.content}")@@ -175,7 +174,6 @@ class RolePlaying:else:processed_msg = messages[0]- processed_msg.role = "user"return processed_msgdef step(@@ -205,17 +203,20 @@ class RolePlaying:any additional user information."""user_msgs, user_terminated, user_info = self.user_agent.step(- assistant_msg)+ assistant_msg.to_user_chat_message())if user_terminated:return ((None, None, None), (None, user_terminated, user_info))user_msg = self.process_messages(user_msgs)+ self.user_agent.update_messages(user_msg)(assistant_msgs, assistant_terminated,- assistant_info) = self.assistant_agent.step(user_msg)+ assistant_info) = self.assistant_agent.step(+ user_msg.to_user_chat_message())if assistant_terminated:return ((None, assistant_terminated, assistant_info),(user_msg, user_terminated, user_info))assistant_msg = self.process_messages(assistant_msgs)+ self.assistant_agent.update_messages(assistant_msg)return ((assistant_msg, assistant_terminated, assistant_info),diff --git a/camel/human.py b/camel/human.pyindex a752357c3..47b0aeee6 100644--- a/camel/human.py+++ b/camel/human.py@@ -63,14 +63,12 @@ class Human:human_input = input(self.menu_color +f"Please enter your choice ([1-{len(self.options_dict)}]): ")+ print("\n")if human_input in self.options_dict:breakprint_text_animated(self.menu_color +"\n> Invalid choice. Please try again.\n")- print_text_animated(- self.menu_color + "\n> Your choice is:\n\n"- f"\x1b[3m{human_input}: {self.options_dict[human_input]}\x1b[0m")return human_inputdef parse_input(self, human_input: str,diff --git a/camel/messages.py b/camel/messages.pyindex 51b9ef35e..885a559aa 100644--- a/camel/messages.py+++ b/camel/messages.py@@ -12,13 +12,62 @@ OpenAIMessage = Union[OpenAISystemMessage, OpenAIChatMessage]@dataclassclass BaseMessage:+ r"""Base class for message objects used in CAMEL chat system.++ Args:+ role_name (str): The name of the user or assistant role.+ role_type (RoleType): The type of role, either+ :obj:`RoleType.ASSISTANT` or :obj:`RoleType.USER`.+ meta_dict (Optional[Dict[str, str]]): Additional metadata dictionary+ for the message.+ role (str): The role of the message in OpenAI chat system, either+ :obj:`"system"`, :obj:`"user"`, or :obj:`"assistant"`.+ content (str): The content of the message.+ """role_name: strrole_type: RoleTypemeta_dict: Optional[Dict[str, str]]role: strcontent: str+ def to_user_chat_message(self) -> "UserChatMessage":+ r"""Converts the message to a :obj:`UserChatMessage` object.++ Returns:+ UserChatMessage: The converted :obj:`UserChatMessage` object.+ """+ return UserChatMessage(+ role_name=self.role_name,+ role_type=self.role_type,+ meta_dict=self.meta_dict,+ content=self.content,+ )++ def to_assistant_chat_message(self) -> "AssistantChatMessage":+ r"""Converts the message to an :obj:`AssistantChatMessage` object.++ Returns:+ AssistantChatMessage: The converted :obj:`AssistantChatMessage`+ object.+ """+ return AssistantChatMessage(+ role_name=self.role_name,+ role_type=self.role_type,+ meta_dict=self.meta_dict,+ content=self.content,+ )+def to_openai_message(self, role: Optional[str] = None) -> OpenAIMessage:+ r"""Converts the message to an :obj:`OpenAIMessage` object.++ Args:+ role (Optional[str]): The role of the message in OpenAI chat+ system, either :obj:`"system"`, :obj:`"user"`, or+ obj:`"assistant"`. (default: :obj:`None`)++ Returns:+ OpenAIMessage: The converted :obj:`OpenAIMessage` object.+ """role = role or self.roleif role not in {"system", "user", "assistant"}:raise ValueError(f"Unrecognized role: {role}")@@ -28,21 +77,53 @@ class BaseMessage:self,role: Optional[str] = None,) -> OpenAIChatMessage:+ r"""Converts the message to an :obj:`OpenAIChatMessage` object.++ Args:+ role (Optional[str]): The role of the message in OpenAI chat+ system, either :obj:`"user"`, or :obj:`"assistant"`.+ (default: :obj:`None`)++ Returns:+ OpenAIChatMessage: The converted :obj:`OpenAIChatMessage` object.+ """role = role or self.roleif role not in {"user", "assistant"}:raise ValueError(f"Unrecognized role: {role}")return {"role": role, "content": self.content}def to_openai_system_message(self) -> OpenAISystemMessage:+ r"""Converts the message to an :obj:`OpenAISystemMessage` object.++ Returns:+ OpenAISystemMessage: The converted :obj:`OpenAISystemMessage`+ object.+ """return {"role": "system", "content": self.content}def to_openai_user_message(self) -> OpenAIUserMessage:+ r"""Converts the message to an :obj:`OpenAIUserMessage` object.++ Returns:+ OpenAIUserMessage: The converted :obj:`OpenAIUserMessage` object.+ """return {"role": "user", "content": self.content}def to_openai_assistant_message(self) -> OpenAIAssistantMessage:+ r"""Converts the message to an :obj:`OpenAIAssistantMessage` object.++ Returns:+ OpenAIAssistantMessage: The converted :obj:`OpenAIAssistantMessage`+ object.+ """return {"role": "assistant", "content": self.content}def to_dict(self) -> Dict:+ r"""Converts the message to a dictionary.++ Returns:+ dict: The converted dictionary.+ """return {"role_name": self.role_name,"role_type": self.role_type.name,@@ -54,6 +135,18 @@ class BaseMessage:@dataclassclass SystemMessage(BaseMessage):+ r"""Class for system messages used in CAMEL chat system.++ Args:+ role_name (str): The name of the user or assistant role.+ role_type (RoleType): The type of role, either+ :obj:`RoleType.ASSISTANT` or :obj:`RoleType.USER`.+ meta_dict (Optional[Dict[str, str]]): Additional metadata dictionary+ for the message.+ role (str): The role of the message in OpenAI chat system.+ (default: :obj:`"system"`)+ content (str): The content of the message. (default: :obj:`""`)+ """role_name: strrole_type: RoleTypemeta_dict: Optional[Dict[str, str]] = None@@ -63,6 +156,19 @@ class SystemMessage(BaseMessage):@dataclassclass AssistantSystemMessage(SystemMessage):+ r"""Class for system messages from the assistant used in the CAMEL chat+ system.++ Args:+ role_name (str): The name of the assistant role.+ role_type (RoleType): The type of role, always+ :obj:`RoleType.ASSISTANT`.+ meta_dict (Optional[Dict[str, str]]): Additional metadata dictionary+ for the message.+ role (str): The role of the message in OpenAI chat system.+ (default: :obj:`"system"`)+ content (str): The content of the message. (default: :obj:`""`)+ """role_name: strrole_type: RoleType = RoleType.ASSISTANTmeta_dict: Optional[Dict[str, str]] = None@@ -72,6 +178,17 @@ class AssistantSystemMessage(SystemMessage):@dataclassclass UserSystemMessage(SystemMessage):+ r"""Class for system messages from the user used in the CAMEL chat system.++ Args:+ role_name (str): The name of the user role.+ role_type (RoleType): The type of role, always :obj:`RoleType.USER`.+ meta_dict (Optional[Dict[str, str]]): Additional metadata dictionary+ for the message.+ role (str): The role of the message in OpenAI chat system.+ (default: :obj:`"system"`)+ content (str): The content of the message. (default: :obj:`""`)+ """role_name: strrole_type: RoleType = RoleType.USERmeta_dict: Optional[Dict[str, str]] = None@@ -81,6 +198,17 @@ class UserSystemMessage(SystemMessage):@dataclassclass ChatMessage(BaseMessage):+ r"""Base class for chat messages used in CAMEL chat system.++ Args:+ role_name (str): The name of the user or assistant role.+ role_type (RoleType): The type of role, either+ :obj:`RoleType.ASSISTANT` or :obj:`RoleType.USER`.+ meta_dict (Optional[Dict[str, str]]): Additional metadata dictionary+ for the message.+ role (str): The role of the message in OpenAI chat system.+ content (str): The content of the message. (default: :obj:`""`)+ """role_name: strrole_type: RoleTypemeta_dict: Optional[Dict[str, str]]@@ -90,6 +218,19 @@ class ChatMessage(BaseMessage):@dataclassclass AssistantChatMessage(ChatMessage):+ r"""Class for chat messages from the assistant role used in CAMEL chat+ system.++ Args:+ role_name (str): The name of the assistant role.+ role_type (RoleType): The type of role, always+ :obj:`RoleType.ASSISTANT`.+ meta_dict (Optional[Dict[str, str]]): Additional metadata dictionary+ for the message.+ role (str): The role of the message in OpenAI chat system.+ (default: :obj:`"assistant"`)+ content (str): The content of the message. (default: :obj:`""`)+ """role_name: strrole_type: RoleType = RoleType.ASSISTANTmeta_dict: Dict[str, str] = None@@ -99,6 +240,17 @@ class AssistantChatMessage(ChatMessage):@dataclassclass UserChatMessage(ChatMessage):+ r"""Class for chat messages from the user role used in CAMEL chat system.++ Args:+ role_name (str): The name of the user role.+ role_type (RoleType): The type of role, always :obj:`RoleType.USER`.+ meta_dict (Optional[Dict[str, str]]): Additional metadata dictionary+ for the message.+ role (str): The role of the message in OpenAI chat system.+ (default: :obj:`"user"`)+ content (str): The content of the message. (default: :obj:`""`)+ """role_name: strrole_type: RoleType = RoleType.USERmeta_dict: Dict[str, str] = Nonediff --git a/examples/ai_society/role_playing_with_human.py b/examples/ai_society/role_playing_with_human.pyindex f0d3b9458..71acb3e11 100644--- a/examples/ai_society/role_playing_with_human.py+++ b/examples/ai_society/role_playing_with_human.py@@ -6,13 +6,13 @@ from camel.utils import print_text_animateddef main() -> None:- task_prompt = "Develop a trading bot for the stock market"+ task_prompt = "Write a book about the future of AI Society"model_config = ChatGPTConfig(temperature=1.4, n=3)assistant_agent_kwargs = dict(model_config=model_config)user_agent_kwargs = dict(model_config=model_config)role_play_session = RolePlaying(- "Python Programmer",- "Stock Trader",+ "AGI",+ "Writer",task_prompt=task_prompt,with_task_specify=True,with_human_in_the_loop=True,diff --git a/examples/code/role_playing_multiprocess.py b/examples/code/role_playing_multiprocess.pyindex 727f66df1..1e36018b3 100644--- a/examples/code/role_playing_multiprocess.py+++ b/examples/code/role_playing_multiprocess.py@@ -29,7 +29,6 @@ def init_chat(content=(f"{user_sys_msg.content}. ""Now start to give me instructions one by one. ""Only reply with Instruction and Input."))- assistant_msg.role = "user"user_msg = UserChatMessage(role_name=user_agent.role_name,content=f"{assistant_sys_msg.content}")@@ -114,7 +113,8 @@ def generate_data(language_idx: int, language_name: str, domain_idx: int,while message_counter < max_num_messages:- user_msgs, user_terminated, user_info = user_agent.step(assistant_msg)+ user_msgs, user_terminated, user_info = user_agent.step(+ assistant_msg.to_user_chat_message())# Condition 1: User terminates the chatif user_terminated:@@ -124,11 +124,11 @@ def generate_data(language_idx: int, language_name: str, domain_idx: int,breakuser_msg = user_msgs[0]+ user_agent.update_messages(user_msg)print(f"User:\n{user_msg.content}\n")- user_msg.role = "user"assistant_msgs, assistant_terminated, assistant_info = (- assistant_agent.step(user_msg))+ assistant_agent.step(user_msg.to_user_chat_message()))# Condition 2: Assistant terminates the chatif assistant_terminated:@@ -138,8 +138,8 @@ def generate_data(language_idx: int, language_name: str, domain_idx: int,breakassistant_msg = assistant_msgs[0]+ assistant_agent.update_messages(assistant_msg)print(f"Assistant:\n{assistant_msg.content}\n")- assistant_msg.role = "user"# Condition 3: Break if user does not give instructionif user_no_instruct_word not in user_msg.content:diff --git a/test/test_messages.py b/test/test_messages.pynew file mode 100644index 000000000..1d211daba--- /dev/null+++ b/test/test_messages.py@@ -0,0 +1,127 @@+import pytest++from camel.messages import BaseMessage, SystemMessage+from camel.typing import RoleType+++def base_message() -> BaseMessage:+ return BaseMessage(+ role_name="test_user",+ role_type=RoleType.USER,+ meta_dict={"key": "value"},+ role="user",+ content="test content",+ )+++def system_message() -> SystemMessage:+ return SystemMessage(+ role_name="test_assistant",+ role_type=RoleType.ASSISTANT,+ meta_dict=None,+ content="test system message",+ )+++def test_base_message():+ role_name = "test_role_name"+ role_type = RoleType.USER+ meta_dict = {"key": "value"}+ role = "user"+ content = "test_content"++ message = BaseMessage(role_name=role_name, role_type=role_type,+ meta_dict=meta_dict, role=role, content=content)++ assert message.role_name == role_name+ assert message.role_type == role_type+ assert message.meta_dict == meta_dict+ assert message.role == role+ assert message.content == content++ user_message = message.to_user_chat_message()+ assert user_message.role_name == role_name+ assert user_message.role_type == role_type+ assert user_message.meta_dict == meta_dict+ assert user_message.role == "user"+ assert user_message.content == content++ assistant_message = message.to_assistant_chat_message()+ assert assistant_message.role_name == role_name+ assert assistant_message.role_type == role_type+ assert assistant_message.meta_dict == meta_dict+ assert assistant_message.role == "assistant"+ assert assistant_message.content == content++ openai_message = message.to_openai_message()+ assert openai_message == {"role": role, "content": content}++ openai_chat_message = message.to_openai_chat_message()+ assert openai_chat_message == {"role": role, "content": content}++ openai_system_message = message.to_openai_system_message()+ assert openai_system_message == {"role": "system", "content": content}++ openai_user_message = message.to_openai_user_message()+ assert openai_user_message == {"role": "user", "content": content}++ openai_assistant_message = message.to_openai_assistant_message()+ assert openai_assistant_message == {+ "role": "assistant",+ "content": content+ }++ dictionary = message.to_dict()+ assert dictionary == {+ "role_name": role_name,+ "role_type": role_type.name,+ **(meta_dict or {}), "role": role,+ "content": content+ }+++def test_system_message():+ role_name = "test_role_name"+ role_type = RoleType.USER+ meta_dict = {"key": "value"}+ content = "test_content"++ message = SystemMessage(role_name=role_name, role_type=role_type,+ meta_dict=meta_dict, content=content)++ assert message.role_name == role_name+ assert message.role_type == role_type+ assert message.meta_dict == meta_dict+ assert message.role == "system"+ assert message.content == content++ dictionary = message.to_dict()+ assert dictionary == {+ "role_name": role_name,+ "role_type": role_type.name,+ **(meta_dict or {}), "role": "system",+ "content": content+ }+++def test_base_message_to_dict(base_message: BaseMessage) -> None:+ expected_dict = {+ "role_name": "test_user",+ "role_type": "USER",+ "key": "value",+ "role": "user",+ "content": "test content",+ }+ assert base_message.to_dict() == expected_dict+++def test_system_message_to_dict(system_message: SystemMessage) -> None:+ expected_dict = {+ "role_name": "test_assistant",+ "role_type": "ASSISTANT",+ "role": "system",+ "content": "test system message",+ }+ assert system_message.to_dict() == expected_dict