🐫 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 `EmbodiedAgent` and modify tests (#155)
Daniel Xu07957bfe55f2
diff --git a/camel/agents/embodied_agent.py b/camel/agents/embodied_agent.pyindex 280501f4c..b9f4a7146 100644--- a/camel/agents/embodied_agent.py+++ b/camel/agents/embodied_agent.py@@ -77,75 +77,6 @@ class EmbodiedAgent(ChatAgent):for action in self.action_space])- @staticmethod- def execute_code(code_string: str, global_vars: Dict = None) -> str:- r"""Executes the given code string.-- Args:- code_string (str): The code string to execute.- global_vars (Dict, optional): The global variables to use during- code execution. (default: :obj:`None`)-- Returns:- str: The execution results.- """- # TODO: Refactor this with `CodePrompt.execute`.- 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(- code_string,- global_vars,- local_vars,- )- sys.stdout = sys.__stdout__- output_str.seek(0)-- # If there was no error, return the output- return (f"- Python standard output:\n{output_str.read()}\n"- f"- Local variables:\n{str(local_vars)}")- except Exception:- import traceback- traceback_str = traceback.format_exc()- sys.stdout = sys.__stdout__- # If there was an error, return the error message- return f"Traceback:\n{traceback_str}"-- @staticmethod- def get_explanation_and_code(- text_prompt: str) -> Tuple[str, Optional[str]]:- r"""Extracts the explanation and code from the text prompt.-- Args:- text_prompt (str): The text prompt containing the explanation and- code.-- Returns:- Tuple[str, Optional[str]]: The extracted explanation and code.- """- # TODO: Refactor this with `BaseMessage.extract_text_and_code_prompts`.- lines = text_prompt.split("\n")- idx = 0- while idx < len(lines) and not lines[idx].lstrip().startswith("```"):- idx += 1- explanation = "\n".join(lines[:idx]).strip()- if idx == len(lines):- return explanation, None-- idx += 1- start_idx = idx- while not lines[idx].lstrip().startswith("```"):- idx += 1- code = "\n".join(lines[start_idx:idx]).strip()-- return explanation, code-def step(self,input_message: ChatMessage,@@ -169,20 +100,30 @@ class EmbodiedAgent(ChatAgent):# NOTE: Only single output messages are supportedoutput_message = output_messages[0]- explanation, code = self.get_explanation_and_code(- output_message.content)- if self.verbose:- print_text_animated(self.logger_color +- f"> Explanation:\n{explanation}")- print_text_animated(self.logger_color + f"> Code:\n{code}")+ explanations_list, codes_list =\+ output_message.extract_text_and_code_prompts()- if code is not None:- global_vars = {action.name: action for action in self.action_space}- executed_results = self.execute_code(code, global_vars)- output_message.content += (- f"\n> Executed Results:\n{executed_results}")+ if self.verbose:+ for explanation, code in zip(explanations_list, codes_list):+ print_text_animated(self.logger_color ++ f"> Explanation:\n{explanation}")+ print_text_animated(self.logger_color + f"> Code:\n{code}")++ if len(explanation) > len(code):+ print_text_animated(self.logger_color ++ f"> Explanation:\n{explanation}")++ if codes_list is not None:+ output_message.content = "\n> Executed Results:"+ for code in codes_list:+ global_vars = {+ action.name: action+ for action in self.action_space+ }+ executed_results = code.execute(global_vars)+ output_message.content += (f"\n{executed_results}")# TODO: Handle errorsinput_message.content += (- f"\n> Embodied Actions:\n{output_message.content}")+ Fore.RESET + f"\n> Embodied Actions:\n{output_message.content}")return input_message, terminated, infodiff --git a/test/agents/test_embodied_agent.py b/test/agents/test_embodied_agent.pyindex 18e6d2309..36119445b 100644--- a/test/agents/test_embodied_agent.py+++ b/test/agents/test_embodied_agent.py@@ -34,22 +34,6 @@ def test_get_action_space_prompt():assert agent.get_action_space_prompt().startswith(expected_prompt)-def test_execute_code():- code_string = "print('Hello, world!')"- expected_output = (- "- Python standard output:\nHello, world!\n\n- Local variables:\n{}")- assert EmbodiedAgent.execute_code(code_string) == expected_output---def test_get_explanation_and_code():- text_prompt = (- "This is an explanation.\n\n```python\nprint('Hello, world!')\n```")- expected_explanation = "This is an explanation."- expected_code = "print('Hello, world!')"- assert EmbodiedAgent.get_explanation_and_code(text_prompt) == (- expected_explanation, expected_code)--@pytest.mark.slow@pytest.mark.full_test_only@openai_api_key_requireddiff --git a/test/messages/test_message_base.py b/test/messages/test_message_base.pyindex e559afd86..2a308985c 100644--- a/test/messages/test_message_base.py+++ b/test/messages/test_message_base.py@@ -63,17 +63,24 @@ 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```")+ "```python\nprint('This is a code prompt')\n```\n"+ "This is another text prompt.\n\n"+ "```c\nprintf(\"This is another code prompt\");\n```")text_prompts, code_prompts = base_message.extract_text_and_code_prompts()- assert len(text_prompts) == 1+ assert len(text_prompts) == 2assert isinstance(text_prompts[0], TextPrompt)+ assert isinstance(text_prompts[1], TextPrompt)assert text_prompts[0] == "This is a text prompt."+ assert text_prompts[1] == "This is another text prompt."- assert len(code_prompts) == 1+ assert len(code_prompts) == 2assert isinstance(code_prompts[0], CodePrompt)+ assert isinstance(code_prompts[1], CodePrompt)assert code_prompts[0] == "print('This is a code prompt')"+ assert code_prompts[1] == "printf(\"This is another code prompt\");"assert code_prompts[0].code_type == "python"+ assert code_prompts[1].code_type == "c"def test_base_message_to_dict(base_message: BaseMessage) -> None: