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 unsafe Python expressions only once (#4197)

Tao Sundb2685b75cb2
diff --git a/camel/interpreters/internal_python_interpreter.py b/camel/interpreters/internal_python_interpreter.py
index badfcfd17..41de0113c 100644
--- a/camel/interpreters/internal_python_interpreter.py
+++ b/camel/interpreters/internal_python_interpreter.py
@@ -188,20 +188,17 @@ class InternalPythonInterpreter(BaseInterpreter):
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
+ try:
+ compiled_code = compile(code, "<string>", "eval")
+ except SyntaxError:
+ with contextlib.redirect_stdout(output_buffer):
+ exec(code, self.action_space)
+ return output_buffer.getvalue()
- return result
+ with contextlib.redirect_stdout(output_buffer):
+ result = eval(compiled_code, self.action_space)
+ return output_buffer.getvalue() or str(result)
else:
return str(self.execute(code))
diff --git a/test/interpreters/test_python_interpreter.py b/test/interpreters/test_python_interpreter.py
index cb14f9b20..d975daed9 100644
--- a/test/interpreters/test_python_interpreter.py
+++ b/test/interpreters/test_python_interpreter.py
@@ -362,6 +362,16 @@ def test_unsafe_mode_eval(unsafe_interpreter):
assert result == "3"
+def test_unsafe_mode_eval_executes_once(unsafe_interpreter):
+ values = []
+ unsafe_interpreter.update_action_space({"values": values})
+
+ result = unsafe_interpreter.run("values.append(1)", code_type="python")
+
+ assert result == "None"
+ assert values == [1]
+
+
def test_unsafe_mode_exec(unsafe_interpreter):
# Test print statement
result = unsafe_interpreter.run("print('hello world')", code_type="python")