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

Fix default action space bug in `CodePrompt` (#417)

Guohao Li78b7046adfe6
diff --git a/camel/prompts/base.py b/camel/prompts/base.py
index 84dae1fce..4e47a8976 100644
--- a/camel/prompts/base.py
+++ b/camel/prompts/base.py
@@ -180,7 +180,7 @@ class CodePrompt(TextPrompt):
Args:
interpreter (PythonInterpreter, optional): interpreter to be used
during code execution. (default: :obj:`None`)
- user_variable (Optional[Dict[str, Any]]): varibales that can be
+ user_variable (Optional[Dict[str, Any]]): variables that can be
used in the code, which applying fuzzy matching, such as images
or documents. (default: :obj:`None`)
@@ -193,7 +193,9 @@ class CodePrompt(TextPrompt):
"""
# NOTE: Only supports Python code for now.
if not interpreter:
- interpreter = PythonInterpreter(action_space=globals())
+ action_space = {}
+ action_space.update({"print": print, "enumerate": enumerate})
+ interpreter = PythonInterpreter(action_space=action_space)
execution_res = interpreter.execute(self, fuzz_state=user_variable,
keep_state=True)
return execution_res, interpreter
diff --git a/camel/utils/python_interpreter.py b/camel/utils/python_interpreter.py
index a7bfc13fd..f437fe012 100644
--- a/camel/utils/python_interpreter.py
+++ b/camel/utils/python_interpreter.py
@@ -77,14 +77,17 @@ class PythonInterpreter():
importable. Any other import statements will be rejected. The
module and its submodule or function name are separated by a period
(:obj:`.`). (default: :obj:`None`)
+ raise_error (bool, optional): Raise error if the interpreter fails.
"""
def __init__(self, action_space: Dict[str, Any],
- import_white_list: Optional[List[str]] = None) -> None:
+ import_white_list: Optional[List[str]] = None,
+ raise_error: bool = False) -> None:
self.action_space = action_space
self.state = self.action_space.copy()
self.fuzz_state: Dict[str, Any] = {}
self.import_white_list = import_white_list or []
+ self.raise_error = raise_error
def execute(self, code: str, state: Optional[Dict[str, Any]] = None,
fuzz_state: Optional[Dict[str, Any]] = None,
@@ -95,9 +98,9 @@ class PythonInterpreter():
code (str): Generated python code to be executed.
state (Optional[Dict[str, Any]], optional): External variables that
may be used in the generated code. (default: :obj:`None`)
- fuzz_state (Optional[Dict[str, Any]], optional): External varibles
- that do not have certain varible names. The interpreter will
- use fuzzy matching to access these varibales. For example, if
+ fuzz_state (Optional[Dict[str, Any]], optional): External variables
+ that do not have certain variable names. The interpreter will
+ use fuzzy matching to access these variables. For example, if
:obj:`fuzz_state` has a variable :obj:`image`, the generated
code can use :obj:`input_image` to access it. (default:
:obj:`None`)
@@ -120,7 +123,11 @@ class PythonInterpreter():
try:
expression = ast.parse(code)
except SyntaxError as e:
- raise InterpreterError(f"Syntax error in code: {e}")
+ if self.raise_error:
+ raise InterpreterError(f"Syntax error in code: {e}")
+ else:
+ import traceback
+ return traceback.format_exc()
result = None
for idx, node in enumerate(expression.body):
@@ -133,7 +140,11 @@ class PythonInterpreter():
f"See:\n{e}")
# More information can be provided by `ast.unparse()`,
# which is new in python 3.9.
- raise InterpreterError(msg)
+ if self.raise_error:
+ raise InterpreterError(msg)
+ else:
+ import traceback
+ return traceback.format_exc()
if line_result is not None:
result = line_result
diff --git a/docs/get_started/code_prompt.md b/docs/get_started/code_prompt.md
index be3acfc15..3b87a7696 100644
--- a/docs/get_started/code_prompt.md
+++ b/docs/get_started/code_prompt.md
@@ -15,10 +15,10 @@ from camel.prompts import CodePrompt
To create a `CodePrompt` instance, you can simply instantiate the class, providing the code string and the code type as an input argument.
```python
-code_prompt = CodePrompt("print('Hello, World!')", code_type="python")
+code_prompt = CodePrompt("a = 1 + 1", code_type="python")
```
-In this example, we create a `CodePrompt` instance with the code string `"print('Hello, World!')"`. We also specify the code type as `"python"`. The code type can be set to `None` if not needed.
+In this example, we create a `CodePrompt` instance with the code string `"a = 1 + 1"`. We also specify the code type as `"python"`. The code type can be set to `None` if not needed.
## Accessing the Code and Code Type
@@ -29,10 +29,10 @@ Once you have a `CodePrompt` instance, you can access the code string and code t
```python
print(code_prompt)
->>> "print('Hello, World!')"
+# >>> "a = 1 + 1"
print(code_prompt.code_type)
->>> "python"
+# >>> "python"
```
## Modifying the Code Type
@@ -40,44 +40,47 @@ print(code_prompt.code_type)
If you need to change the code type associated with a `CodePrompt` instance, you can use the `set_code_type` method. This method takes a code type as a parameter and updates the code type of the instance.
```python
-code_prompt = CodePrompt("print('Hello, World!')")
+code_prompt = CodePrompt("a = 1 + 1")
print(code_prompt.code_type)
->>> None
+# >>> None
code_prompt.set_code_type("python")
print(code_prompt.code_type)
->>> "python"
+# >>> "python"
```
In this example, we change the code type of the `CodePrompt` instance from `None` to `"python"`.
## Executing the Code
-The `CodePrompt` class provides a method called `execute` that allows you to execute the code string associated with the prompt. It returns a tuple containing the output string and local variables.
+The `CodePrompt` class provides a method called `execute` that allows you to execute the code string associated with the prompt. It returns a tuple containing the value of the last statement in the code and the interpreter.
```python
-CodePrompt("a = 1\nprint('Hello, World!')", code_type="python")
-output, variables = code_prompt.execute()
+code_prompt = CodePrompt("a = 1 + 1\nb = a + 1", code_type="python")
+output, interpreter = code_prompt.execute()
print(output)
->>> "Hello, World!\n"
+# >>> 3
-print(variables)
->>> {"a": 1}
+print(interpreter.state['a'])
+# >>> 2
+
+print(interpreter.state['b'])
+# >>> 3
```
-In this example, we execute the code prompt and store the output string in the `output` variable and the local variables in the `variables` dictionary.
+In this example, we execute the code prompt and inspect the state of variables `a` and `b`.
## Handling Execution Errors
-If there is an error during the code execution, the `execute` method catches the error and returns the traceback string. If there is no error, the method returns the output string and local variables.
+If there is an error during the code execution, the `execute` method catches the error and returns the traceback.
```python
code_prompt = CodePrompt("print('Hello, World!'")
-traceback_str, _ = code_prompt.execute()
-assert "SyntaxError" in traceback_str
->>> True
+traceback, _ = code_prompt.execute()
+assert "SyntaxError" in traceback
+# >>> True
```
-In this example, the code string has a syntax error where a right bracket `)` is missing, and the `execute` method returns the traceback string indicating the error.
+In this example, the code string has a syntax error where a right bracket `)` is missing, and the `execute` method returns the traceback indicating the error.
That's it! You have went through the basics of using the `CodePrompt` class. You can now create code prompts, access the code and code type, modify the code type if needed, and execute the code.
\ No newline at end of file
diff --git a/test/prompts/test_prompt_base.py b/test/prompts/test_prompt_base.py
index ec77aeefe..58c507600 100644
--- a/test/prompts/test_prompt_base.py
+++ b/test/prompts/test_prompt_base.py
@@ -152,7 +152,8 @@ def test_code_prompt_execute(capsys):
def test_code_prompt_execute_error():
code_prompt = CodePrompt("print('Hello, World!'", code_type="python")
- interpreter = PythonInterpreter(action_space={"print": print})
+ interpreter = PythonInterpreter(action_space={"print": print},
+ raise_error=True)
with pytest.raises(InterpreterError) as e:
_, _ = code_prompt.execute(interpreter=interpreter)
assert e.value.args[0].startswith("Syntax error in code:")
diff --git a/test/utils/test_python_interpreter.py b/test/utils/test_python_interpreter.py
index d5f688559..f7a815fce 100644
--- a/test/utils/test_python_interpreter.py
+++ b/test/utils/test_python_interpreter.py
@@ -28,7 +28,7 @@ def interpreter():
action_space = {"action1": action_function, "str": str}
white_list = ["torch", "numpy.array", "openai"]
return PythonInterpreter(action_space=action_space,
- import_white_list=white_list)
+ import_white_list=white_list, raise_error=True)
def test_state_update(interpreter: PythonInterpreter):