🐫 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
Feature/multi lingual role play (#181)
MorphlingEdcde10f8e9206
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex 7e59808e4..774833286 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -63,6 +63,8 @@ class ChatAgent(BaseAgent):message_window_size (int, optional): The maximum number of previousmessages to include in the context window. If `None`, no windowingis performed. (default: :obj:`None`)+ output_language (str, optional): The language to be output by the+ agent. (default: :obj:`None`)"""def __init__(@@ -71,11 +73,15 @@ class ChatAgent(BaseAgent):model: Optional[ModelType] = None,model_config: Optional[Any] = None,message_window_size: Optional[int] = None,+ output_language: Optional[str] = None,) -> None:self.system_message: SystemMessage = system_messageself.role_name: str = system_message.role_nameself.role_type: RoleType = system_message.role_type+ self.output_language: Optional[str] = output_language+ if output_language is not None:+ self.set_output_language(self.output_language)self.model: ModelType = (model if model is not None elseModelType.GPT_3_5_TURBO)@@ -100,6 +106,25 @@ class ChatAgent(BaseAgent):self.init_messages()return self.stored_messages+ def set_output_language(self, output_language: str) -> SystemMessage:+ r"""Sets the output language for the system message. This method+ updates the output language for the system message. The output+ language determines the language in which the output text should be+ generated.++ Args:+ output_language (str): The desired output language.++ Returns:+ SystemMessage: The updated system message object.+ """+ self.output_language = output_language+ content = (self.system_message.content ++ ("\nRegardless of the input language, "+ f"you must output text in {output_language}."))+ self.system_message = self.system_message.create_new_instance(content)+ return self.system_message+def get_info(self,id: Optional[str],diff --git a/camel/agents/task_agent.py b/camel/agents/task_agent.pyindex 0d1e81cac..2a3a6369a 100644--- a/camel/agents/task_agent.py+++ b/camel/agents/task_agent.py@@ -39,6 +39,8 @@ class TaskSpecifyAgent(ChatAgent):the task. (default: :obj:`None`)word_limit (int): The word limit for the task prompt.(default: :obj:`50`)+ output_language (str, optional): The language to be output by the+ agent. (default: :obj:`None`)"""DEFAULT_WORD_LIMIT = 50@@ -49,6 +51,7 @@ class TaskSpecifyAgent(ChatAgent):model_config: Optional[Any] = None,task_specify_prompt: Optional[Union[str, TextPrompt]] = None,word_limit: int = DEFAULT_WORD_LIMIT,+ output_language: str = None,) -> None:if task_specify_prompt is None:@@ -67,7 +70,9 @@ class TaskSpecifyAgent(ChatAgent):role_type=RoleType.ASSISTANT,content="You can make a task more specific.",)- super().__init__(system_message, model, model_config)++ super().__init__(system_message, model, model_config,+ output_language=output_language)def step(self,@@ -121,12 +126,15 @@ class TaskPlannerAgent(ChatAgent):(default: :obj:`ModelType.GPT_3_5_TURBO`)model_config (Any): The configuration for the model.(default: :obj:`None`)+ output_language (str, optional): The language to be output by the+ agent. (default: :obj:`None`)"""def __init__(self,model: Optional[ModelType] = None,model_config: Any = None,+ output_language: str = None,) -> None:self.task_planner_prompt = TextPrompt(@@ -137,7 +145,9 @@ class TaskPlannerAgent(ChatAgent):role_type=RoleType.ASSISTANT,content="You are a helpful task planner.",)- super().__init__(system_message, model, model_config)++ super().__init__(system_message, model, model_config,+ output_language=output_language)def step(self,diff --git a/camel/messages/base.py b/camel/messages/base.pyindex ae7089e50..e28bd5a2f 100644--- a/camel/messages/base.py+++ b/camel/messages/base.py@@ -45,7 +45,7 @@ class BaseMessage:role: strcontent: str- def _create_new_instance(self, content: str) -> "BaseMessage":+ def create_new_instance(self, content: str) -> "BaseMessage":r"""Create a new instance of the :obj:`BaseMessage` with updatedcontent.@@ -77,7 +77,7 @@ class BaseMessage:raise TypeError(f"Unsupported operand type(s) for +: '{type(self)}' and "f"'{type(other)}'")- return self._create_new_instance(combined_content)+ return self.create_new_instance(combined_content)def __mul__(self, other: Any) -> Union["BaseMessage", Any]:r"""Multiplication operator override for :obj:`BaseMessage`.@@ -90,7 +90,7 @@ class BaseMessage:"""if isinstance(other, int):multiplied_content = self.content.__mul__(other)- return self._create_new_instance(multiplied_content)+ return self.create_new_instance(multiplied_content)else:raise TypeError(f"Unsupported operand type(s) for *: '{type(self)}' and "diff --git a/camel/societies/role_playing.py b/camel/societies/role_playing.pyindex 95b0c719a..cc98ef06d 100644--- a/camel/societies/role_playing.py+++ b/camel/societies/role_playing.py@@ -63,6 +63,8 @@ class RolePlaying:extend the system message meta dicts with. (default: :obj:`None`)extend_task_specify_meta_dict (Dict, optional): A dict to extend thetask specify meta dict with. (default: :obj:`None`)+ output_language (str, optional): The language to be output by the+ agents. (default: :obj:`None`)"""def __init__(@@ -85,6 +87,7 @@ class RolePlaying:sys_msg_generator_kwargs: Optional[Dict] = None,extend_sys_msg_meta_dicts: Optional[List[Dict]] = None,extend_task_specify_meta_dict: Optional[Dict] = None,+ output_language: str = None,) -> None:self.with_task_specify = with_task_specifyself.with_task_planner = with_task_planner@@ -104,6 +107,7 @@ class RolePlaying:task_specify_agent = TaskSpecifyAgent(self.model_type,task_type=self.task_type,+ output_language=output_language,**(task_specify_agent_kwargs or {}),)self.specified_task_prompt = task_specify_agent.step(@@ -117,6 +121,7 @@ class RolePlaying:if with_task_planner:task_planner_agent = TaskPlannerAgent(self.model_type,+ output_language=output_language,**(task_planner_agent_kwargs or {}),)self.planned_task_prompt = task_planner_agent.step(task_prompt)@@ -143,7 +148,7 @@ class RolePlaying:} for sys_msg_meta_dict, extend_sys_msg_meta_dict in zip(sys_msg_meta_dicts, extend_sys_msg_meta_dicts)]- self.assistant_sys_msg, self.user_sys_msg = (+ init_assistant_sys_msg, init_user_sys_msg = (sys_msg_generator.from_dicts(meta_dicts=sys_msg_meta_dicts,role_tuples=[@@ -153,15 +158,20 @@ class RolePlaying:))self.assistant_agent: ChatAgent = ChatAgent(- self.assistant_sys_msg,+ init_assistant_sys_msg,model_type,+ output_language=output_language,**(assistant_agent_kwargs or {}),)+ self.assistant_sys_msg = self.assistant_agent.system_message+self.user_agent: ChatAgent = ChatAgent(- self.user_sys_msg,+ init_user_sys_msg,model_type,+ output_language=output_language,**(user_agent_kwargs or {}),)+ self.user_sys_msg = self.user_agent.system_messageif with_critic_in_the_loop:if critic_role_name.lower() == "human":diff --git a/examples/ai_society/role_playing_multi_lingual.py b/examples/ai_society/role_playing_multi_lingual.pynew file mode 100644index 000000000..a25890b3d--- /dev/null+++ b/examples/ai_society/role_playing_multi_lingual.py@@ -0,0 +1,75 @@+# =========== 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 colorama import Fore++from camel.societies import RolePlaying+from camel.utils import print_text_animated+++def main(model_type=None) -> None:+ task_prompt = "Develop a trading bot for the stock market"+ role_play_session = RolePlaying(+ "Python Programmer",+ "Stock Trader",+ task_prompt=task_prompt,+ with_task_specify=True,+ model_type=model_type,+ output_language="Chinese", # Arabic, French, Spanish, ...+ )++ print(+ Fore.GREEN ++ f"AI Assistant sys message:\n{role_play_session.assistant_sys_msg}\n")+ print(Fore.BLUE ++ f"AI User sys message:\n{role_play_session.user_sys_msg}\n")++ print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")+ print(+ Fore.CYAN ++ f"Specified task prompt:\n{role_play_session.specified_task_prompt}\n")+ print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")++ chat_turn_limit, n = 50, 0+ input_assistant_msg, _ = role_play_session.init_chat()+ while n < chat_turn_limit:+ n += 1+ assistant_response, user_response = role_play_session.step(+ input_assistant_msg)++ input_assistant_msg = assistant_response.msg++ if assistant_response.terminated:+ print(Fore.GREEN ++ ("AI Assistant terminated. Reason: "+ f"{assistant_response.info['termination_reasons']}."))+ break+ if user_response.terminated:+ print(Fore.GREEN ++ ("AI User terminated. "+ f"Reason: {user_response.info['termination_reasons']}."))+ break++ print_text_animated(Fore.BLUE ++ f"AI User:\n\n{user_response.msg.content}\n")+ print_text_animated(Fore.GREEN + "AI Assistant:\n\n"+ f"{assistant_response.msg.content}\n")++ if "CAMEL_TASK_DONE" in user_response.msg.content:+ break+++if __name__ == "__main__":+ from camel.typing import ModelType++ main(ModelType.GPT_4)diff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.pyindex 9968cae34..53ad43465 100644--- a/test/agents/test_chat_agent.py+++ b/test/agents/test_chat_agent.py@@ -82,3 +82,27 @@ def test_chat_agent_multiple_return_messages(n):assistant_response = assistant.step(user_msg)assert assistant_response.msgs is not Noneassert len(assistant_response.msgs) == n++[email protected]_backend+def test_set_output_language():+ system_message = SystemMessage(role_name="assistant",+ role_type=RoleType.ASSISTANT,+ content="You are a help assistant.")+ agent = ChatAgent(system_message=system_message,+ model=ModelType.GPT_3_5_TURBO)+ assert agent.output_language is None++ # Set the output language to "Arabic"+ output_language = "Arabic"+ agent.set_output_language(output_language)++ # Check if the output language is set correctly+ assert agent.output_language == output_language++ # Verify that the system message is updated with the new output language+ updated_system_message = SystemMessage(+ role_name="assistant", role_type="assistant",+ content="You are a help assistant."+ "\nRegardless of the input language, you must output text in Arabic.")+ assert agent.system_message.content == updated_system_message.content