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: execute python code in unsafe mode (#1480)

Xiaotian Jine6a890e32799
diff --git a/camel/interpreters/internal_python_interpreter.py b/camel/interpreters/internal_python_interpreter.py
index 2a250b443..0eb08b9d4 100644
--- a/camel/interpreters/internal_python_interpreter.py
+++ b/camel/interpreters/internal_python_interpreter.py
@@ -73,7 +73,8 @@ class InternalPythonInterpreter(BaseInterpreter):
module and its submodule or function name are separated by a period
(:obj:`.`). (default: :obj:`None`)
unsafe_mode (bool, optional): If `True`, the interpreter runs the code
- by `eval()` without any security check. (default: :obj:`False`)
+ by `eval()` or `exec()` without any security check.
+ (default: :obj:`False`)
raise_error (bool, optional): Raise error if the interpreter fails.
(default: :obj:`False`)
"""
@@ -102,9 +103,9 @@ class InternalPythonInterpreter(BaseInterpreter):
type is supported, and then executes the code. If `unsafe_mode` is
set to `False`, the code is executed in a controlled environment using
the `execute` method. If `unsafe_mode` is `True`, the code is executed
- using `eval()` with the action space as the global context. An
- `InterpreterError` is raised if the code type is unsupported or if any
- runtime error occurs during execution.
+ using `eval()` or `exec()` with the action space as the global context.
+ An `InterpreterError` is raised if the code type is unsupported or if
+ any runtime error occurs during execution.
Args:
code (str): The python code to be executed.
@@ -125,10 +126,26 @@ class InternalPythonInterpreter(BaseInterpreter):
f"`{self.__class__.__name__}` only supports "
f"{', '.join(self._CODE_TYPES)}."
)
- if not self.unsafe_mode:
- return str(self.execute(code))
+ if self.unsafe_mode:
+ import contextlib
+ import io
+
+ # Try to execute first and capture stdout
+ output_buffer = io.StringIO()
+ with contextlib.redirect_stdout(output_buffer):
+ exec(code, self.action_space)
+ result = output_buffer.getvalue()
+
+ # If no output was captured, try to evaluate the code
+ if not result:
+ try:
+ result = str(eval(code, self.action_space))
+ except (SyntaxError, NameError):
+ result = "" # If eval fails, return empty string
+
+ return result
else:
- return str(eval(code, self.action_space))
+ return str(self.execute(code))
def update_action_space(self, action_space: Dict[str, Any]) -> None:
r"""Updates action space for *python* interpreter."""
diff --git a/examples/interpreters/internal_python_interpreter.py b/examples/interpreters/internal_python_interpreter.py
new file mode 100644
index 000000000..53545041c
--- /dev/null
+++ b/examples/interpreters/internal_python_interpreter.py
@@ -0,0 +1,40 @@
+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+
+from camel.interpreters import InternalPythonInterpreter
+
+safe_interpreter = InternalPythonInterpreter()
+unsafe_interpreter = InternalPythonInterpreter(unsafe_mode=True)
+
+safe_result = safe_interpreter.execute(
+ "x = input_variable", state={"input_variable": 10}
+)
+print(safe_result)
+
+'''
+===============================================================================
+10
+===============================================================================
+'''
+
+unsafe_result = unsafe_interpreter.run(
+ "[x * 2 for x in range(3)]", code_type="python"
+)
+print(unsafe_result)
+
+'''
+===============================================================================
+[0, 2, 4]
+===============================================================================
+'''
diff --git a/test/interpreters/test_python_interpreter.py b/test/interpreters/test_python_interpreter.py
index 4da241bd6..e6fc15f70 100644
--- a/test/interpreters/test_python_interpreter.py
+++ b/test/interpreters/test_python_interpreter.py
@@ -294,3 +294,81 @@ x += 1"""
"Evaluation of the code stopped at node 1. See:"
"\nAugAssign is not supported."
)
+
+
+def unsafe_interpreter():
+ interpreter = InternalPythonInterpreter()
+ interpreter.unsafe_mode = True
+ return interpreter
+
+
+def test_unsafe_mode_eval(unsafe_interpreter):
+ # Test basic arithmetic
+ result = unsafe_interpreter.run("2 + 2", code_type="python")
+ assert result == "4"
+
+ # Test string operations
+ result = unsafe_interpreter.run("'hello' + ' world'", code_type="python")
+ assert result == "hello world"
+
+ # Test built-in functions
+ result = unsafe_interpreter.run("len([1, 2, 3])", code_type="python")
+ assert result == "3"
+
+
+def test_unsafe_mode_exec(unsafe_interpreter):
+ # Test print statement
+ result = unsafe_interpreter.run("print('hello world')", code_type="python")
+ assert result == "hello world\n" # exec returns captured stdout
+
+ # Test multiple print statements
+ code = """
+print('line 1')
+print('line 2')
+"""
+ result = unsafe_interpreter.run(code, code_type="python")
+ assert result == "line 1\nline 2\n" # exec returns captured stdout
+
+ # Test variable assignment without print
+ code = """
+x = 42
+y = x * 2
+"""
+ result = unsafe_interpreter.run(code, code_type="python")
+ assert result == "" # exec returns empty string when no stdout
+
+ # Test variable assignment with print
+ code = """
+x = 42
+print(f'The value is {x}')
+"""
+ result = unsafe_interpreter.run(code, code_type="python")
+ assert result == "The value is 42\n" # exec returns captured stdout
+
+
+def test_unsafe_mode_complex_operations(unsafe_interpreter):
+ # Test list comprehension with eval
+ result = unsafe_interpreter.run(
+ "[x * 2 for x in range(3)]", code_type="python"
+ )
+ assert result == "[0, 2, 4]" # eval returns str of result
+
+ # Test function definition and execution
+ code = """
+def greet(name):
+ print(f'Hello, {name}!')
+greet('World')
+"""
+ result = unsafe_interpreter.run(code, code_type="python")
+ assert result == "Hello, World!\n" # exec returns captured stdout
+
+ # Test multiple operations with variable scope
+ code = """
+total = 0
+for i in range(5):
+ total += i
+print(f'Sum: {total}')
+"""
+ result = unsafe_interpreter.run(code, code_type="python")
+ assert result == "Sum: 10\n" # exec returns captured stdout