Skip to content

Commit 457abde

Browse files
Create docs reference page for Python executors (#1987)
1 parent 440e919 commit 457abde

4 files changed

Lines changed: 131 additions & 74 deletions

File tree

docs/source/en/_toctree.yml

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,12 @@
4242
title: Async Applications with Agents
4343
- title: Reference
4444
sections:
45-
- local: reference/agents
46-
title: Agent-related objects
45+
- title: Agent-related objects
46+
sections:
47+
- title: Agents
48+
local: reference/agents
49+
- title: Python executors
50+
local: reference/python_executors
4751
- local: reference/models
4852
title: Model-related objects
4953
- title: Tools

docs/source/en/reference/agents.md

Lines changed: 0 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -54,35 +54,3 @@ Both require arguments `model` and list of tools `tools` at initialization.
5454
Smolagents use memory to store information across multiple steps.
5555

5656
[[autodoc]] smolagents.memory.AgentMemory
57-
58-
## Python code executors
59-
60-
[[autodoc]] smolagents.local_python_executor.PythonExecutor
61-
62-
### Local Python executor
63-
64-
[[autodoc]] smolagents.local_python_executor.LocalPythonExecutor
65-
66-
### Remote Python executors
67-
68-
[[autodoc]] smolagents.remote_executors.RemotePythonExecutor
69-
70-
#### BlaxelExecutor
71-
72-
[[autodoc]] smolagents.remote_executors.BlaxelExecutor
73-
74-
#### E2BExecutor
75-
76-
[[autodoc]] smolagents.remote_executors.E2BExecutor
77-
78-
#### ModalExecutor
79-
80-
[[autodoc]] smolagents.remote_executors.ModalExecutor
81-
82-
#### DockerExecutor
83-
84-
[[autodoc]] smolagents.remote_executors.DockerExecutor
85-
86-
#### WasmExecutor
87-
88-
[[autodoc]] smolagents.remote_executors.WasmExecutor
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Python code executors
2+
3+
Python executors are responsible for running the code generated by code agents in a controlled environment.
4+
Since agents dynamically generate and execute Python code to accomplish tasks, choosing the right executor is critical
5+
for both functionality and security.
6+
7+
To learn more about code execution and its risks, make sure to read the [Secure code execution](../tutorials/secure_code_execution)
8+
tutorial. This reference contains the API docs for the underlying classes: the base `PythonExecutor` interface and all
9+
available executor implementations.
10+
11+
## Python executor
12+
13+
[[autodoc]] smolagents.local_python_executor.PythonExecutor
14+
15+
## Local Python executor
16+
17+
[[autodoc]] smolagents.local_python_executor.LocalPythonExecutor
18+
19+
## Remote Python executors
20+
21+
[[autodoc]] smolagents.remote_executors.RemotePythonExecutor
22+
23+
### BlaxelExecutor
24+
25+
[[autodoc]] smolagents.remote_executors.BlaxelExecutor
26+
27+
### E2BExecutor
28+
29+
[[autodoc]] smolagents.remote_executors.E2BExecutor
30+
31+
### ModalExecutor
32+
33+
[[autodoc]] smolagents.remote_executors.ModalExecutor
34+
35+
### DockerExecutor
36+
37+
[[autodoc]] smolagents.remote_executors.DockerExecutor
38+
39+
### WasmExecutor
40+
41+
[[autodoc]] smolagents.remote_executors.WasmExecutor

src/smolagents/remote_executors.py

Lines changed: 84 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,20 @@
5454

5555

5656
class RemotePythonExecutor(PythonExecutor):
57+
"""
58+
Executor of Python code in a remote environment.
59+
60+
Args:
61+
additional_imports (`list[str]`): Additional Python packages to install.
62+
logger (`Logger`): Logger to use for output and errors.
63+
allow_pickle (`bool`, default `False`): Whether to allow pickle serialization for objects that cannot be safely serialized to JSON.
64+
- `False` (default, recommended): Only safe JSON serialization is used. Raises error if object cannot be safely serialized.
65+
- `True` (legacy mode): Tries safe JSON serialization first, falls back to pickle with warning if needed.
66+
67+
**Security Warning:** Pickle deserialization can execute arbitrary code. Only set `allow_pickle=True`
68+
if you fully trust the execution environment and need backward compatibility with custom types.
69+
"""
70+
5771
FINAL_ANSWER_EXCEPTION = "FinalAnswerException"
5872

5973
def __init__(
@@ -70,8 +84,13 @@ def __init__(
7084

7185
def run_code_raise_errors(self, code: str) -> CodeOutput:
7286
"""
73-
Execute code, return the result and output, also determining if
74-
the result is the final answer.
87+
Execute Python code in the remote environment and return the result.
88+
89+
Args:
90+
code (`str`): Python code to execute.
91+
92+
Returns:
93+
`CodeOutput`: Code output containing the result, logs, and whether it is the final answer.
7594
"""
7695
raise NotImplementedError
7796

@@ -318,18 +337,18 @@ def _deserialize_final_answer(encoded_value: str, allow_pickle: bool = True) ->
318337

319338
class E2BExecutor(RemotePythonExecutor):
320339
"""
321-
Executes Python code using E2B.
340+
Remote Python code executor in an E2B sandbox.
322341
323342
Args:
324-
additional_imports (`list[str]`): Additional imports to install.
325-
logger (`Logger`): Logger to use.
343+
additional_imports (`list[str]`): Additional Python packages to install.
344+
logger (`Logger`): Logger to use for output and errors.
326345
allow_pickle (`bool`, default `False`): Whether to allow pickle serialization for objects that cannot be safely serialized to JSON.
327346
- `False` (default, recommended): Only safe JSON serialization is used. Raises error if object cannot be safely serialized.
328347
- `True` (legacy mode): Tries safe JSON serialization first, falls back to pickle with warning if needed.
329348
330349
**Security Warning:** Pickle deserialization can execute arbitrary code. Only set `allow_pickle=True`
331350
if you fully trust the execution environment and need backward compatibility with custom types.
332-
**kwargs: Additional arguments to pass to the E2B Sandbox.
351+
**kwargs: Additional keyword arguments to pass to the E2B Sandbox instantiation.
333352
"""
334353

335354
def __init__(
@@ -356,6 +375,15 @@ def __init__(
356375
self.logger.log("E2B is running", level=LogLevel.INFO)
357376

358377
def run_code_raise_errors(self, code: str) -> CodeOutput:
378+
"""
379+
Execute Python code in the E2B sandbox and return the result.
380+
381+
Args:
382+
code (`str`): Python code to execute.
383+
384+
Returns:
385+
`CodeOutput`: Code output containing the result, logs, and whether it is the final answer.
386+
"""
359387
execution = self.sandbox.run_code(code)
360388
execution_logs = "\n".join([str(log) for log in execution.logs.stdout])
361389

@@ -517,7 +545,23 @@ def _create_kernel_http(crate_kernel_endpoint: str, logger, headers: Optional[di
517545

518546
class DockerExecutor(RemotePythonExecutor):
519547
"""
520-
Executes Python code using Jupyter Kernel Gateway in a Docker container.
548+
Remote Python code executor using Jupyter Kernel Gateway in a Docker container.
549+
550+
Args:
551+
additional_imports (`list[str]`): Additional Python packages to install.
552+
logger (`Logger`): Logger to use for output and errors.
553+
allow_pickle (`bool`, default `False`): Whether to allow pickle serialization for objects that cannot be safely serialized to JSON.
554+
- `False` (default, recommended): Only safe JSON serialization is used. Raises error if object cannot be safely serialized.
555+
- `True` (legacy mode): Tries safe JSON serialization first, falls back to pickle with warning if needed.
556+
557+
**Security Warning:** Pickle deserialization can execute arbitrary code. Only set `allow_pickle=True`
558+
if you fully trust the execution environment and need backward compatibility with custom types.
559+
host (`str`, default `"127.0.0.1"`): Host to bind to.
560+
port (`int`, default `8888`): Port to bind to.
561+
image_name (`str`, default `"jupyter-kernel"`): Name of the Docker image to use. If the image doesn't exist, it will be built.
562+
build_new_image (`bool`, default `True`): Whether to rebuild a new image even if it already exists.
563+
container_run_kwargs (`dict`, *optional*): Additional keyword arguments to pass to the Docker container run command.
564+
dockerfile_content (`str`, *optional*): Custom Dockerfile content. If `None`, uses default.
521565
"""
522566

523567
def __init__(
@@ -532,25 +576,6 @@ def __init__(
532576
container_run_kwargs: dict[str, Any] | None = None,
533577
dockerfile_content: str | None = None,
534578
):
535-
"""
536-
Initialize the Docker-based Jupyter Kernel Gateway executor.
537-
538-
Args:
539-
additional_imports: Additional imports to install.
540-
logger: Logger to use.
541-
allow_pickle (`bool`, default `False`): Whether to allow pickle serialization for objects that cannot be safely serialized to JSON.
542-
- `False` (default, recommended): Only safe JSON serialization is used. Raises error if object cannot be safely serialized.
543-
- `True` (legacy mode): Tries safe JSON serialization first, falls back to pickle with warning if needed.
544-
545-
**Security Warning:** Pickle deserialization can execute arbitrary code. Only set `allow_pickle=True`
546-
if you fully trust the execution environment and need backward compatibility with custom types.
547-
host: Host to bind to.
548-
port: Port to bind to.
549-
image_name: Name of the Docker image to use. If the image doesn't exist, it will be built.
550-
build_new_image: If True, the image will be rebuilt even if it already exists.
551-
container_run_kwargs: Additional keyword arguments to pass to the Docker container run command.
552-
dockerfile_content: Custom Dockerfile content. If None, uses default.
553-
"""
554579
super().__init__(additional_imports, logger, allow_pickle)
555580
try:
556581
import docker
@@ -639,6 +664,15 @@ def __init__(
639664
raise RuntimeError(f"Failed to initialize Jupyter kernel: {e}") from e
640665

641666
def run_code_raise_errors(self, code: str) -> CodeOutput:
667+
"""
668+
Execute Python code in the Docker container and return the result.
669+
670+
Args:
671+
code (`str`): Python code to execute.
672+
673+
Returns:
674+
`CodeOutput`: Code output containing the result, logs, and whether it is the final answer.
675+
"""
642676
from websocket import create_connection
643677

644678
with closing(create_connection(self.ws_url)) as ws:
@@ -678,20 +712,20 @@ def _wait_for_server(self):
678712

679713
class ModalExecutor(RemotePythonExecutor):
680714
"""
681-
Executes Python code using Modal.
715+
Remote Python code executor in a Modal sandbox.
682716
683717
Args:
684-
additional_imports: Additional imports to install.
718+
additional_imports (`list[str]`): Additional Python packages to install.
685719
logger (`Logger`): Logger to use for output and errors.
686720
allow_pickle (`bool`, default `False`): Whether to allow pickle serialization for objects that cannot be safely serialized to JSON.
687721
- `False` (default, recommended): Only safe JSON serialization is used. Raises error if object cannot be safely serialized.
688722
- `True` (legacy mode): Tries safe JSON serialization first, falls back to pickle with warning if needed.
689723
690724
**Security Warning:** Pickle deserialization can execute arbitrary code. Only set `allow_pickle=True`
691725
if you fully trust the execution environment and need backward compatibility with custom types.
692-
app_name (`str`): App name.
693-
port (`int`): Port for jupyter to bind to.
694-
create_kwargs (`dict`, optional): Keyword arguments to pass to creating the sandbox. See
726+
app_name (`str`, default `"smolagent-executor"`): App name.
727+
port (`int`, default `8888`): Port for jupyter to bind to.
728+
create_kwargs (`dict`, *optional*): Additional keyword arguments to pass to the Modal Sandbox create command. See
695729
`modal.Sandbox.create` [docs](https://modal.com/docs/reference/modal.Sandbox#create) for all the
696730
keyword arguments.
697731
"""
@@ -765,12 +799,22 @@ def __init__(
765799
self.installed_packages = self.install_packages(additional_imports)
766800

767801
def run_code_raise_errors(self, code: str) -> CodeOutput:
802+
"""
803+
Execute Python code in the Modal sandbox and return the result.
804+
805+
Args:
806+
code (`str`): Python code to execute.
807+
808+
Returns:
809+
`CodeOutput`: Code output containing the result, logs, and whether it is the final answer.
810+
"""
768811
from websocket import create_connection
769812

770813
with closing(create_connection(self.ws_url)) as ws:
771814
return _websocket_run_code_raise_errors(code, ws, self.logger, self.allow_pickle)
772815

773816
def cleanup(self):
817+
"""Clean up the Modal sandbox by terminating it."""
774818
if hasattr(self, "sandbox"):
775819
self.sandbox.terminate()
776820

@@ -802,7 +846,7 @@ def _strip_ansi_colors(cls, text: str) -> str:
802846

803847
class BlaxelExecutor(RemotePythonExecutor):
804848
"""
805-
Executes Python code using Blaxel sandboxes.
849+
Remote Python code executor in a Blaxel sandbox.
806850
807851
Blaxel provides fast-launching virtual machines that start from hibernation in under 25ms
808852
and scale back to zero after inactivity while maintaining memory state.
@@ -816,11 +860,11 @@ class BlaxelExecutor(RemotePythonExecutor):
816860
817861
**Security Warning:** Pickle deserialization can execute arbitrary code. Only set `allow_pickle=True`
818862
if you fully trust the execution environment and need backward compatibility with custom types.
819-
sandbox_name (`str`, optional): Name for the sandbox. Defaults to "smolagent-executor".
820-
image (`str`, optional): Docker image to use. Defaults to "blaxel/jupyter-notebook".
821-
memory (`int`, optional): Memory allocation in MB. Defaults to 4096.
822-
region (`str`, optional): Deployment region. If not specified, Blaxel chooses default.
823-
create_kwargs (`dict`, optional): Additional arguments for sandbox creation.
863+
sandbox_name (`str`, *optional*): Name for the sandbox. Defaults to "smolagent-executor".
864+
image (`str`, default `"blaxel/jupyter-notebook"`): Docker image to use.
865+
memory (`int`, default `4096`): Memory allocation in MB.
866+
ttl (`str`, *optional*): Time to live in seconds.
867+
region (`str`, *optional*): Deployment region. If not specified, Blaxel chooses default.
824868
"""
825869

826870
def __init__(
@@ -1036,10 +1080,10 @@ class WasmExecutor(RemotePythonExecutor):
10361080
10371081
**Security Warning:** Pickle deserialization can execute arbitrary code. Only set `allow_pickle=True`
10381082
if you fully trust the execution environment and need backward compatibility with custom types.
1039-
deno_path (`str`, optional): Path to the Deno executable. If not provided, will use "deno" from PATH.
1040-
deno_permissions (`list[str]`, optional): List of permissions to grant to the Deno runtime.
1083+
deno_path (`str`, default `"deno"`): Path to the Deno executable. If not provided, will use "deno" from PATH.
1084+
deno_permissions (`list[str]`, *optional*): List of permissions to grant to the Deno runtime.
10411085
Default is minimal permissions needed for execution.
1042-
timeout (`int`, optional): Timeout in seconds for code execution. Default is 60 seconds.
1086+
timeout (`int`, default `60`): Timeout in seconds for code execution
10431087
"""
10441088

10451089
def __init__(

0 commit comments

Comments
 (0)