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

enhance: add more builtin operations in python interpreter (#2706)

EmptyRabbit847268f9be75
diff --git a/camel/interpreters/internal_python_interpreter.py b/camel/interpreters/internal_python_interpreter.py
index fd0872ae3..ad02372e2 100644
--- a/camel/interpreters/internal_python_interpreter.py
+++ b/camel/interpreters/internal_python_interpreter.py
@@ -79,6 +79,9 @@ class InternalPythonInterpreter(BaseInterpreter):
(default: :obj:`False`)
raise_error (bool, optional): Raise error if the interpreter fails.
(default: :obj:`False`)
+ allow_builtins (bool, optional): If `True`, safe built-in functions
+ like print, len, str, etc. are added to the action space.
+ (default: :obj:`True`)
"""
_CODE_TYPES: ClassVar[List[str]] = ["python", "py", "python3", "python2"]
@@ -89,16 +92,62 @@ class InternalPythonInterpreter(BaseInterpreter):
import_white_list: Optional[List[str]] = None,
unsafe_mode: bool = False,
raise_error: bool = False,
+ allow_builtins: bool = True,
) -> None:
self.action_space = action_space or dict()
- # Add print to action space
- self.action_space['print'] = print
self.state = self.action_space.copy()
self.fuzz_state: Dict[str, Any] = dict()
self.import_white_list = import_white_list or list()
self.raise_error = raise_error
self.unsafe_mode = unsafe_mode
+ # Add safe built-in functions if allowed
+ if allow_builtins:
+ self._add_safe_builtins()
+
+ def _add_safe_builtins(self):
+ r"""Add safe built-in functions to the action space."""
+ safe_builtins = {
+ 'print': print,
+ 'len': len,
+ 'str': str,
+ 'int': int,
+ 'float': float,
+ 'bool': bool,
+ 'list': list,
+ 'dict': dict,
+ 'tuple': tuple,
+ 'set': set,
+ 'abs': abs,
+ 'min': min,
+ 'max': max,
+ 'sum': sum,
+ 'sorted': sorted,
+ 'reversed': reversed,
+ 'enumerate': enumerate,
+ 'zip': zip,
+ 'range': range,
+ 'round': round,
+ 'type': type,
+ 'isinstance': isinstance,
+ 'hasattr': hasattr,
+ 'getattr': getattr,
+ 'setattr': setattr,
+ 'dir': dir,
+ 'help': help,
+ 'map': map,
+ 'filter': filter,
+ 'any': any,
+ 'all': all,
+ 'ord': ord,
+ 'chr': chr,
+ 'bin': bin,
+ 'oct': oct,
+ 'hex': hex,
+ }
+ self.action_space.update(safe_builtins)
+ self.state.update(safe_builtins)
+
def run(self, code: str, code_type: str = "python") -> str:
r"""Executes the given code with specified code type in the
interpreter.
diff --git a/docs/mintlify/reference/camel.interpreters.internal_python_interpreter.mdx b/docs/mintlify/reference/camel.interpreters.internal_python_interpreter.mdx
index 6eed40980..65e892868 100644
--- a/docs/mintlify/reference/camel.interpreters.internal_python_interpreter.mdx
+++ b/docs/mintlify/reference/camel.interpreters.internal_python_interpreter.mdx
@@ -50,6 +50,7 @@ Modifications copyright (C) 2023 CAMEL-AI.org
- **import_white_list** (List[str], optional): A list that stores the Python modules or functions that can be imported in the code. All submodules and functions of the modules listed in this list are 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`)
- **unsafe_mode** (bool, optional): If `True`, the interpreter runs the code by `eval()` or `exec()` without any security check. (default: :obj:`False`)
- **raise_error** (bool, optional): Raise error if the interpreter fails. (default: :obj:`False`)
+- **allow_builtins** (bool, optional): If `True`, safe built-in functions like print, len, str, etc. are added to the action space. (default: :obj:`True`)
<a id="camel.interpreters.internal_python_interpreter.InternalPythonInterpreter.__init__"></a>
@@ -61,10 +62,21 @@ def __init__(
action_space: Optional[Dict[str, Any]] = None,
import_white_list: Optional[List[str]] = None,
unsafe_mode: bool = False,
- raise_error: bool = False
+ raise_error: bool = False,
+ allow_builtins: bool = True
):
```
+<a id="camel.interpreters.internal_python_interpreter.InternalPythonInterpreter._add_safe_builtins"></a>
+
+### _add_safe_builtins
+
+```python
+def _add_safe_builtins(self):
+```
+
+Add safe built-in functions to the action space.
+
<a id="camel.interpreters.internal_python_interpreter.InternalPythonInterpreter.run"></a>
### run
diff --git a/examples/workforce/eigent.py b/examples/workforce/eigent.py
index b196bac65..24e3b53c9 100644
--- a/examples/workforce/eigent.py
+++ b/examples/workforce/eigent.py
@@ -377,10 +377,10 @@ async def main():
new_worker_agent_kwargs = {"model": model_backend}
# Create agents using factory functions
- search_agent = search_agent_factory(
+ search_agent = search_agent_factory(model_backend, task_id)
+ developer_agent = developer_agent_factory(
model_backend, task_id, edgeone_pages_mcp_toolkit
)
- developer_agent = developer_agent_factory(model_backend, task_id)
document_agent = document_agent_factory(model_backend, task_id)
multi_modal_agent = multi_modal_agent_factory(model_backend, task_id)
diff --git a/test/interpreters/test_python_interpreter.py b/test/interpreters/test_python_interpreter.py
index 63f72bba6..ee2774b2b 100644
--- a/test/interpreters/test_python_interpreter.py
+++ b/test/interpreters/test_python_interpreter.py
@@ -298,6 +298,12 @@ x += 1"""
)
+def test_allow_builtins(interpreter: InternalPythonInterpreter):
+ code = "res = len([0, 1])"
+ execution_res = interpreter.execute(code)
+ assert execution_res == 2
+
+
@pytest.fixture
def unsafe_interpreter():
interpreter = InternalPythonInterpreter()
@@ -374,3 +380,21 @@ print(f'Sum: {total}')
"""
result = unsafe_interpreter.run(code, code_type="python")
assert result == "Sum: 10\n" # exec returns captured stdout
+
+
+def not_allow_builtins_interpreter():
+ interpreter = InternalPythonInterpreter(
+ raise_error=True, allow_builtins=False
+ )
+ return interpreter
+
+
+def test_not_allow_builtins(
+ not_allow_builtins_interpreter: InternalPythonInterpreter,
+):
+ code = "res = len([0, 1])"
+ with pytest.raises(InterpreterError) as e:
+ not_allow_builtins_interpreter.execute(code)
+ exec_msg = e.value.args[0]
+ assert "The variable `len` is not defined." in exec_msg