š« 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
Refactor `BaseMessage` add `CodePrompt` (#139)
Guohao Li603ec9b5e0e0
diff --git a/camel/messages.py b/camel/messages.pydeleted file mode 100644index 06bd81a5b..000000000--- a/camel/messages.py+++ /dev/null@@ -1,279 +0,0 @@-# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========-from dataclasses import dataclass-from typing import Dict, Optional, Union--from .typing import RoleType--OpenAISystemMessage = Dict[str, str]-OpenAIAssistantMessage = Dict[str, str]-OpenAIUserMessage = Dict[str, str]-OpenAIChatMessage = Union[OpenAIUserMessage, OpenAIAssistantMessage]-OpenAIMessage = Union[OpenAISystemMessage, OpenAIChatMessage]---@dataclass-class 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: str- role_type: RoleType- meta_dict: Optional[Dict[str, str]]- role: str- content: 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.role- if role not in {"system", "user", "assistant"}:- raise ValueError(f"Unrecognized role: {role}")- return {"role": role, "content": self.content}-- def to_openai_chat_message(- 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.role- if 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,- **(self.meta_dict or {}),- "role": self.role,- "content": self.content,- }---@dataclass-class 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: str- role_type: RoleType- meta_dict: Optional[Dict[str, str]] = None- role: str = "system"- content: str = ""---@dataclass-class 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: str- role_type: RoleType = RoleType.ASSISTANT- meta_dict: Optional[Dict[str, str]] = None- role: str = "system"- content: str = ""---@dataclass-class 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: str- role_type: RoleType = RoleType.USER- meta_dict: Optional[Dict[str, str]] = None- role: str = "system"- content: str = ""---@dataclass-class 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: str- role_type: RoleType- meta_dict: Optional[Dict[str, str]]- role: str- content: str = ""---@dataclass-class 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: str- role_type: RoleType = RoleType.ASSISTANT- meta_dict: Optional[Dict[str, str]] = None- role: str = "assistant"- content: str = ""---@dataclass-class 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: str- role_type: RoleType = RoleType.USER- meta_dict: Optional[Dict[str, str]] = None- role: str = "user"- content: str = ""---MessageType = Union[BaseMessage, SystemMessage, AssistantSystemMessage,- UserSystemMessage, ChatMessage, AssistantChatMessage,- UserChatMessage]-SystemMessageType = Union[SystemMessage, AssistantSystemMessage,- UserSystemMessage]-ChatMessageType = Union[ChatMessage, AssistantChatMessage, UserChatMessage]diff --git a/camel/messages/__init__.py b/camel/messages/__init__.pynew file mode 100644index 000000000..4fe78e329--- /dev/null+++ b/camel/messages/__init__.py@@ -0,0 +1,53 @@+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========+from typing import Dict, Union++OpenAISystemMessage = Dict[str, str]+OpenAIAssistantMessage = Dict[str, str]+OpenAIUserMessage = Dict[str, str]+OpenAIChatMessage = Union[OpenAIUserMessage, OpenAIAssistantMessage]+OpenAIMessage = Union[OpenAISystemMessage, OpenAIChatMessage]++from .base import BaseMessage # noqa: E402+from .system_messages import ( # noqa: E402+ SystemMessage, AssistantSystemMessage, UserSystemMessage,+)+from .chat_messages import ( # noqa: E402+ ChatMessage, AssistantChatMessage, UserChatMessage,+)++MessageType = Union[BaseMessage, SystemMessage, AssistantSystemMessage,+ UserSystemMessage, ChatMessage, AssistantChatMessage,+ UserChatMessage]+SystemMessageType = Union[SystemMessage, AssistantSystemMessage,+ UserSystemMessage]+ChatMessageType = Union[ChatMessage, AssistantChatMessage, UserChatMessage]++__all__ = [+ 'OpenAISystemMessage',+ 'OpenAIAssistantMessage',+ 'OpenAIUserMessage',+ 'OpenAIChatMessage',+ 'OpenAIMessage',+ 'BaseMessage',+ 'SystemMessage',+ 'AssistantSystemMessage',+ 'UserSystemMessage',+ 'ChatMessage',+ 'AssistantChatMessage',+ 'UserChatMessage',+ 'MessageType',+ 'SystemMessageType',+ 'ChatMessageType',+]diff --git a/camel/messages/base.py b/camel/messages/base.pynew file mode 100644index 000000000..89c951ebd--- /dev/null+++ b/camel/messages/base.py@@ -0,0 +1,334 @@+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========+from dataclasses import dataclass+from typing import Any, Dict, List, Optional, Tuple, Type, Union++from camel.messages import (+ OpenAIAssistantMessage,+ OpenAIChatMessage,+ OpenAIMessage,+ OpenAISystemMessage,+ OpenAIUserMessage,+)+from camel.prompts import CodePrompt, TextPrompt+from camel.typing import ModelType, RoleType+++@dataclass+class 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: str+ role_type: RoleType+ meta_dict: Optional[Dict[str, str]]+ role: str+ content: str++ def __getattribute__(self, name: str) -> Any:+ r"""Get attribute override to delegate string methods to the+ :obj:`content`.++ Args:+ name (str): The name of the attribute.++ Returns:+ Any: The attribute value.+ """+ delegate_methods = [+ method for method in dir(str) if not method.startswith('_')+ ]+ if name in delegate_methods:+ content = super().__getattribute__('content')+ if isinstance(content, str):+ content_method = getattr(content, name, None)+ if callable(content_method):++ def modify_arg(arg: Any) -> Any:+ r"""Modify the argument for delegate method.++ Args:+ arg (Any): The argument value.++ Returns:+ Any: The modified argument value.+ """+ if isinstance(arg, BaseMessage):+ return arg.content+ elif isinstance(arg, (list, tuple)):+ return type(arg)(modify_arg(item) for item in arg)+ else:+ return arg++ def wrapper(*args: Any, **kwargs: Any) -> Any:+ r"""Wrapper function for delegate method.++ Args:+ *args (Any): Variable length argument list.+ **kwargs (Any): Arbitrary keyword arguments.++ Returns:+ Any: The result of the delegate method.+ """+ modified_args = [modify_arg(arg) for arg in args]+ modified_kwargs = {+ k: modify_arg(v)+ for k, v in kwargs.items()+ }+ output = content_method(*modified_args,+ **modified_kwargs)+ return self._create_new_instance(output) if isinstance(+ output, str) else output++ return wrapper++ return super().__getattribute__(name)++ def _create_new_instance(self, content: str) -> "BaseMessage":+ r"""Create a new instance of the :obj:`BaseMessage` with updated+ content.++ Args:+ content (str): The new content value.++ Returns:+ BaseMessage: The new instance of :obj:`BaseMessage`.+ """+ return self.__class__(role_name=self.role_name,+ role_type=self.role_type,+ meta_dict=self.meta_dict, role=self.role,+ content=content)++ def __add__(self, other: Any) -> Union["BaseMessage", Any]:+ r"""Addition operator override for :obj:`BaseMessage`.++ Args:+ other (Any): The value to be added with.++ Returns:+ Union[BaseMessage, Any]: The result of the addition.+ """+ if isinstance(other, BaseMessage):+ combined_content = self.content.__add__(other.content)+ elif isinstance(other, str):+ combined_content = self.content.__add__(other)+ else:+ raise TypeError(+ f"Unsupported operand type(s) for +: '{type(self)}' and "+ f"'{type(other)}'")+ return self._create_new_instance(combined_content)++ def __mul__(self, other: Any) -> Union["BaseMessage", Any]:+ r"""Multiplication operator override for :obj:`BaseMessage`.++ Args:+ other (Any): The value to be multiplied with.++ Returns:+ Union[BaseMessage, Any]: The result of the multiplication.+ """+ if isinstance(other, int):+ multiplied_content = self.content.__mul__(other)+ return self._create_new_instance(multiplied_content)+ else:+ raise TypeError(+ f"Unsupported operand type(s) for *: '{type(self)}' and "+ f"'{type(other)}'")++ def __len__(self) -> int:+ r"""Length operator override for :obj:`BaseMessage`.++ Returns:+ int: The length of the content.+ """+ return len(self.content)++ def __contains__(self, item: str) -> bool:+ r"""Contains operator override for :obj:`BaseMessage`.++ Args:+ item (str): The item to check for containment.++ Returns:+ bool: :obj:`True` if the item is contained in the content,+ :obj:`False` otherwise.+ """+ return item in self.content++ def token_len(self, model: ModelType = ModelType.GPT_3_5_TURBO) -> int:+ r"""Calculate the token length of the message for the specified model.++ Args:+ model (ModelType, optional): The model type to calculate the token+ length. (default: :obj:`ModelType.GPT_3_5_TURBO`)++ Returns:+ int: The token length of the message.+ """+ from camel.utils import num_tokens_from_messages+ return num_tokens_from_messages([self.to_openai_chat_message()], model)++ def extract_text_and_code_prompts(+ self) -> Tuple[List[TextPrompt], List[CodePrompt]]:+ r"""Extract text and code prompts from the message content.++ Returns:+ Tuple[List[TextPrompt], List[CodePrompt]]: A tuple containing a+ list of text prompts and a list of code prompts extracted+ from the content.+ """+ text_prompts: List[TextPrompt] = []+ code_prompts: List[CodePrompt] = []++ lines = self.content.split("\n")+ idx = 0+ start_idx = 0+ while idx < len(lines):+ while idx < len(lines) and (+ not lines[idx].lstrip().startswith("```")):+ idx += 1+ text = "\n".join(lines[start_idx:idx]).strip()+ text_prompts.append(TextPrompt(text))++ if idx >= len(lines):+ break++ code_type = lines[idx].strip()[3:].strip()+ idx += 1+ start_idx = idx+ while not lines[idx].lstrip().startswith("```"):+ idx += 1+ code = "\n".join(lines[start_idx:idx]).strip()+ code_prompts.append(CodePrompt(code, code_type=code_type))++ idx += 1+ start_idx = idx++ return text_prompts, code_prompts++ def to_user_chat_message(self) -> Type["UserChatMessage"]: # noqa: F821+ r"""Converts the message to a :obj:`UserChatMessage` object.++ Returns:+ UserChatMessage: The converted :obj:`UserChatMessage` object.+ """+ from camel.messages.chat_messages import UserChatMessage++ 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) -> Type["AssistantChatMessage"]: # noqa: F821+ r"""Converts the message to an :obj:`AssistantChatMessage` object.++ Returns:+ AssistantChatMessage: The converted :obj:`AssistantChatMessage`+ object.+ """+ from camel.messages.chat_messages import AssistantChatMessage++ 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.role+ if role not in {"system", "user", "assistant"}:+ raise ValueError(f"Unrecognized role: {role}")+ return {"role": role, "content": self.content}++ def to_openai_chat_message(+ 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.role+ if 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,+ **(self.meta_dict or {}),+ "role": self.role,+ "content": self.content,+ }diff --git a/camel/messages/chat_messages.py b/camel/messages/chat_messages.pynew file mode 100644index 000000000..023f07bad--- /dev/null+++ b/camel/messages/chat_messages.py@@ -0,0 +1,80 @@+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========+from dataclasses import dataclass+from typing import Dict, Optional++from camel.messages import BaseMessage+from camel.typing import RoleType+++@dataclass+class 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: str+ role_type: RoleType+ meta_dict: Optional[Dict[str, str]]+ role: str+ content: str = ""+++@dataclass+class 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: str+ role_type: RoleType = RoleType.ASSISTANT+ meta_dict: Optional[Dict[str, str]] = None+ role: str = "assistant"+ content: str = ""+++@dataclass+class 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: str+ role_type: RoleType = RoleType.USER+ meta_dict: Optional[Dict[str, str]] = None+ role: str = "user"+ content: str = ""diff --git a/camel/messages/system_messages.py b/camel/messages/system_messages.pynew file mode 100644index 000000000..5a4cc9185--- /dev/null+++ b/camel/messages/system_messages.py@@ -0,0 +1,81 @@+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========+from dataclasses import dataclass+from typing import Dict, Optional++from camel.messages import BaseMessage+from camel.typing import RoleType+++@dataclass+class 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: str+ role_type: RoleType+ meta_dict: Optional[Dict[str, str]] = None+ role: str = "system"+ content: str = ""+++@dataclass+class 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: str+ role_type: RoleType = RoleType.ASSISTANT+ meta_dict: Optional[Dict[str, str]] = None+ role: str = "system"+ content: str = ""+++@dataclass+class 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: str+ role_type: RoleType = RoleType.USER+ meta_dict: Optional[Dict[str, str]] = None+ role: str = "system"+ content: str = ""diff --git a/camel/prompts/__init__.py b/camel/prompts/__init__.pyindex a728c32d5..35fde16d6 100644--- a/camel/prompts/__init__.py+++ b/camel/prompts/__init__.py@@ -11,7 +11,7 @@# See the License for the specific language governing permissions and# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========-from .base import TextPrompt, TextPromptDict+from .base import TextPrompt, CodePrompt, TextPromptDictfrom .ai_society import AISocietyPromptTemplateDictfrom .code import CodePromptTemplateDictfrom .misalignment import MisalignmentPromptTemplateDict@@ -23,6 +23,7 @@ from .prompt_templates import PromptTemplateGenerator__all__ = ['TextPrompt',+ 'CodePrompt','TextPromptDict','AISocietyPromptTemplateDict','CodePromptTemplateDict',diff --git a/camel/prompts/base.py b/camel/prompts/base.pyindex a2b1aabcf..776a7c629 100644--- a/camel/prompts/base.py+++ b/camel/prompts/base.py@@ -12,29 +12,31 @@# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========import inspect-from typing import Any, Callable, Dict, Set, TypeVar, Union+from typing import Any, Callable, Dict, Optional, Set, Tuple, TypeVar, Unionfrom camel.typing import RoleType-from camel.utils import get_prompt_template_key_wordsT = TypeVar('T')-def return_text_prompt(- func: Callable) -> Callable[..., Union['TextPrompt', tuple]]:- r"""Decorator that converts the return value of a function to a- :obj:`TextPrompt` instance if it's a string.+def return_prompt_wrapper(+ cls: T,+ func: Callable,+) -> Callable[..., Union[T, tuple]]:+ r"""Wrapper that converts the return value of a function to an input+ class instance if it's a string.Args:+ cls (type): The class to convert to.func (Callable): The function to decorate.Returns:- Callable[..., Union[TextPrompt, tuple]]: Decorated function that- returns a :obj:`TextPrompt` instance if the return value is a+ Callable[..., Union[T, tuple]]: Decorated function that+ returns the decorated class instance if the return value is astring."""- def wrapper(*args: Any, **kwargs: Any) -> Union['TextPrompt', tuple]:+ def wrapper(*args: Any, **kwargs: Any) -> Union[T, tuple]:r"""Wrapper function that performs the conversion to :obj:`TextPrompt`instance.@@ -46,13 +48,12 @@ def return_text_prompt(Union[TextPrompt, tuple]: The converted return value."""result = func(*args, **kwargs)- if isinstance(result, str) and not isinstance(result, TextPrompt):- return TextPrompt(result)+ if isinstance(result, str) and not isinstance(result, cls):+ return cls(result)elif isinstance(result, tuple):new_result = tuple(- TextPrompt(item) if isinstance(item, str)- and not isinstance(item, TextPrompt) else item- for item in result)+ cls(item) if isinstance(item, str)+ and not isinstance(item, cls) else item for item in result)return new_resultreturn result@@ -63,7 +64,7 @@ def return_text_prompt(return wrapper-def wrap_text_prompt_functions(cls: T) -> T:+def wrap_prompt_functions(cls: T) -> T:r"""Decorator that wraps functions of a class inherited from :obj:`str`with the :obj:`return_text_prompt` decorator.@@ -78,11 +79,11 @@ def wrap_text_prompt_functions(cls: T) -> T:attr_value = getattr(cls, attr_name)if callable(attr_value) and attr_name not in excluded_attrs:if inspect.isroutine(attr_value):- setattr(cls, attr_name, return_text_prompt(attr_value))+ setattr(cls, attr_name, return_prompt_wrapper(cls, attr_value))return cls-@wrap_text_prompt_functions+@wrap_prompt_functionsclass TextPrompt(str):r"""A class that represents a text prompt. The :obj:`TextPrompt` classextends the built-in :obj:`str` class to provide a property for retrieving@@ -97,6 +98,7 @@ class TextPrompt(str):def key_words(self) -> Set[str]:r"""Returns a set of strings representing the key words in the prompt."""+ from camel.utils import get_prompt_template_key_wordsreturn get_prompt_template_key_words(self)def format(self, *args: Any, **kwargs: Any) -> 'TextPrompt':@@ -117,6 +119,90 @@ class TextPrompt(str):return TextPrompt(super().format(*args, **default_kwargs))+@wrap_prompt_functions+class CodePrompt(TextPrompt):+ r"""A class that represents a code prompt. It extends the :obj:`TextPrompt`+ class with a :obj:`code_type` property.++ Args:+ code_string (str): The code string for the prompt.+ code_type (str, optional): The type of code. Defaults to None.+ """++ def __new__(cls, *args: Any, **kwargs: Any) -> 'CodePrompt':+ r"""Creates a new instance of the :obj:`CodePrompt` class.++ Args:+ *args (Any): Positional arguments.+ **kwargs (Any): Keyword arguments.++ Returns:+ CodePrompt: The created :obj:`CodePrompt` instance.+ """+ code_type = kwargs.pop('code_type', None)+ instance = super().__new__(cls, *args, **kwargs)+ instance._code_type = code_type+ return instance++ @property+ def code_type(self) -> Optional[str]:+ r"""Returns the type of code.++ Returns:+ Optional[str]: The type of code.+ """+ return self._code_type++ def set_code_type(self, code_type: str) -> None:+ r"""Sets the type of code.++ Args:+ code_type (str): The type of code.+ """+ self._code_type = code_type++ def execute(self, global_vars: Dict = None) -> Tuple[str, Optional[Dict]]:+ r"""Executes the code string. If there is an error, the error is caught+ and the traceback is returned. Otherwise, the output string and local+ variables are returned.++ Args:+ global_vars (Dict, optional): Global variables to be used during+ code execution. (default: :obj:`None`)++ Returns:+ Tuple[str, Optional[Dict]]: A tuple containing the output string+ and local variables.+ """+ # NOTE: Only supports Python code for now.+ try:+ # Execute the code string+ import io+ import sys+ output_str = io.StringIO()+ sys.stdout = output_str++ global_vars = global_vars or globals()+ local_vars = {}+ exec(+ self,+ global_vars,+ local_vars,+ )+ sys.stdout = sys.__stdout__+ output_str.seek(0)++ # If there was no error, return the output and local variables+ return output_str.read(), local_vars++ except Exception:+ import traceback+ traceback_str = traceback.format_exc()+ sys.stdout = sys.__stdout__+ # If there was an error, return the traceback+ return traceback_str, None++# flake8: noqa :E501class TextPromptDict(Dict[Any, TextPrompt]):r"""A dictionary class that maps from key to :obj:`TextPrompt` object.diff --git a/test/messages/test_chat_message.py b/test/messages/test_chat_message.pynew file mode 100644index 000000000..101284cb1--- /dev/null+++ b/test/messages/test_chat_message.py@@ -0,0 +1,116 @@+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========+import pytest++from camel.messages import AssistantChatMessage, ChatMessage, UserChatMessage+from camel.typing import RoleType+++def chat_message() -> ChatMessage:+ return ChatMessage(+ role_name="test_role",+ role_type=RoleType.ASSISTANT,+ meta_dict=None,+ role="assistant",+ content="test chat message",+ )+++def assistant_chat_message() -> AssistantChatMessage:+ return AssistantChatMessage(+ role_name="test_assistant",+ role_type=RoleType.ASSISTANT,+ meta_dict=None,+ content="test assistant chat message",+ )+++def user_chat_message() -> UserChatMessage:+ return UserChatMessage(+ role_name="test_user",+ role_type=RoleType.USER,+ meta_dict=None,+ content="test user chat message",+ )+++def test_chat_message(chat_message: ChatMessage) -> None:+ role_name = "test_role"+ role_type = RoleType.ASSISTANT+ meta_dict = None+ role = "assistant"+ content = "test chat message"++ assert chat_message.role_name == role_name+ assert chat_message.role_type == role_type+ assert chat_message.meta_dict == meta_dict+ assert chat_message.role == role+ assert chat_message.content == content++ dictionary = chat_message.to_dict()+ assert dictionary == {+ "role_name": role_name,+ "role_type": role_type.name,+ **(meta_dict or {}),+ "role": role,+ "content": content,+ }+++def test_assistant_chat_message(+ assistant_chat_message: AssistantChatMessage) -> None:+ role_name = "test_assistant"+ role_type = RoleType.ASSISTANT+ meta_dict = None+ content = "test assistant chat message"++ assert assistant_chat_message.role_name == role_name+ assert assistant_chat_message.role_type == role_type+ assert assistant_chat_message.meta_dict == meta_dict+ assert assistant_chat_message.role == "assistant"+ assert assistant_chat_message.content == content++ dictionary = assistant_chat_message.to_dict()+ assert dictionary == {+ "role_name": role_name,+ "role_type": role_type.name,+ **(meta_dict or {}),+ "role": "assistant",+ "content": content,+ }+++def test_user_chat_message(user_chat_message: UserChatMessage) -> None:+ role_name = "test_user"+ role_type = RoleType.USER+ meta_dict = None+ content = "test user chat message"++ assert user_chat_message.role_name == role_name+ assert user_chat_message.role_type == role_type+ assert user_chat_message.meta_dict == meta_dict+ assert user_chat_message.role == "user"+ assert user_chat_message.content == content++ dictionary = user_chat_message.to_dict()+ assert dictionary == {+ "role_name": role_name,+ "role_type": role_type.name,+ **(meta_dict or {}),+ "role": "user",+ "content": content,+ }diff --git a/test/test_messages.py b/test/messages/test_message_base.pysimilarity index 66%rename from test/test_messages.pyrename to test/messages/test_message_base.pyindex 4a23c97ca..e559afd86 100644--- a/test/test_messages.py+++ b/test/messages/test_message_base.py@@ -13,7 +13,8 @@# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========import pytest-from camel.messages import BaseMessage, SystemMessage+from camel.messages import BaseMessage+from camel.prompts import CodePrompt, TextPromptfrom camel.typing import RoleType@@ -28,14 +29,62 @@ def base_message() -> BaseMessage:)-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_get_attribute(base_message: BaseMessage):+ assert base_message.upper().content == "TEST CONTENT"+ assert base_message.startswith("test")+++def test_base_message_addition_operator(base_message: BaseMessage):+ new_message = base_message + "!"+ assert new_message.content == "test content!"+++def test_base_message_multiplication_operator(base_message: BaseMessage):+ new_message = base_message * 3+ assert new_message.content == "test contenttest contenttest content"+++def test_base_message_length_operator(base_message: BaseMessage):+ assert len(base_message) == 12+++def test_base_message_contains_operator(base_message: BaseMessage):+ assert "test" in base_message+ assert "foo" not in base_message+++def test_base_message_token_len(base_message: BaseMessage):+ token_len = base_message.token_len()+ assert isinstance(token_len, int)+ assert token_len == 9+++def test_extract_text_and_code_prompts():+ base_message = BaseMessage(+ role_name="test_role_name", role_type=RoleType.USER, meta_dict=dict(),+ role="user", content="This is a text prompt.\n\n"+ "```python\nprint('This is a code prompt')\n```")+ text_prompts, code_prompts = base_message.extract_text_and_code_prompts()++ assert len(text_prompts) == 1+ assert isinstance(text_prompts[0], TextPrompt)+ assert text_prompts[0] == "This is a text prompt."++ assert len(code_prompts) == 1+ assert isinstance(code_prompts[0], CodePrompt)+ assert code_prompts[0] == "print('This is a code prompt')"+ assert code_prompts[0].code_type == "python"+++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_dictdef test_base_message():@@ -93,48 +142,3 @@ def test_base_message():**(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_dictdiff --git a/test/messages/test_system_message.py b/test/messages/test_system_message.pynew file mode 100644index 000000000..00d0974d8--- /dev/null+++ b/test/messages/test_system_message.py@@ -0,0 +1,61 @@+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========+import pytest++from camel.messages import SystemMessage+from camel.typing import RoleType+++def system_message() -> SystemMessage:+ return SystemMessage(+ role_name="test_assistant",+ role_type=RoleType.ASSISTANT,+ meta_dict=None,+ content="test system message",+ )+++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_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_dictdiff --git a/test/prompts/test_base.py b/test/prompts/test_prompt_base.pysimilarity index 69%rename from test/prompts/test_base.pyrename to test/prompts/test_prompt_base.pyindex 3ab4a2311..0ce16266c 100644--- a/test/prompts/test_base.py+++ b/test/prompts/test_prompt_base.py@@ -12,30 +12,31 @@# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========from camel.prompts.base import (+ CodePrompt,TextPrompt,TextPromptDict,- return_text_prompt,- wrap_text_prompt_functions,+ return_prompt_wrapper,+ wrap_prompt_functions,)-def test_return_text_prompt_decorator():+def test_return_prompt_wrapper():- @return_text_promptdef my_function():return "Hello, world!"+ my_function = return_prompt_wrapper(TextPrompt, my_function)result = my_function()assert isinstance(result, TextPrompt)assert str(result) == "Hello, world!"-def test_return_text_prompt_decorator_with_tuple():+def test_return_prompt_wrapper_with_tuple():- @return_text_promptdef my_function():return ("Hello, {name}!", "Welcome, {name}!")+ my_function = return_prompt_wrapper(TextPrompt, my_function)result = my_function()assert isinstance(result, tuple)assert all(isinstance(item, TextPrompt) for item in result)@@ -43,11 +44,11 @@ def test_return_text_prompt_decorator_with_tuple():assert str(result[1]) == "Welcome, {name}!"-def test_wrap_text_prompt_functions():+def test_wrap_prompt_functions():# Example class for testingclass MyClass:- def __init__(self):+ def __init__(self, *args, **kwargs):passdef my_function(self):@@ -57,7 +58,7 @@ def test_wrap_text_prompt_functions():return "Goodbye, World!"# Decorate the class with the wrapper function- @wrap_text_prompt_functions+ @wrap_prompt_functionsclass MyDecoratedClass(MyClass):pass@@ -65,8 +66,8 @@ def test_wrap_text_prompt_functions():obj = MyDecoratedClass()# Check if the functions are wrapped correctly- assert isinstance(obj.my_function(), TextPrompt)- assert isinstance(obj.my_other_function(), TextPrompt)+ assert isinstance(obj.my_function(), MyDecoratedClass)+ assert isinstance(obj.my_other_function(), MyDecoratedClass)def test_text_prompt_key_words():@@ -115,3 +116,31 @@ def test_text_prompt_dict():prompt_dict = TextPromptDict()prompt_dict['test'] = TextPrompt('test')assert prompt_dict['test'] == TextPrompt('test')+++def test_code_prompt_initialization():+ code_prompt = CodePrompt("print('Hello, World!')", code_type="python")+ assert code_prompt == "print('Hello, World!')"+ assert code_prompt.code_type == "python"+++def test_code_prompt_missing_code_type():+ code_prompt = CodePrompt("print('Hello, World!')")+ assert code_prompt.code_type is None+++def test_code_prompt_set_code_type():+ code_prompt = CodePrompt("print('Hello, World!')")+ code_prompt.set_code_type("python")+ assert code_prompt.code_type == "python"+++def test_code_prompt_execute():+ code_prompt = CodePrompt("a = 1\nprint('Hello, World!')")+ assert code_prompt.execute() == ("Hello, World!\n", {"a": 1})+++def test_code_prompt_execute_error():+ code_prompt = CodePrompt("print('Hello, World!'")+ traceback_str, _ = code_prompt.execute()+ assert "SyntaxError" in traceback_str