smolagents documentation

Python code executors

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v1.24.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Python code executors

Python executors are responsible for running the code generated by code agents in a controlled environment. Since agents dynamically generate and execute Python code to accomplish tasks, choosing the right executor is critical for both functionality and security.

To learn more about code execution and its risks, make sure to read the Secure code execution tutorial. This reference contains the API docs for the underlying classes: the base PythonExecutor interface and all available executor implementations.

Python executor

class smolagents.PythonExecutor

< >

( )

Local Python executor

class smolagents.LocalPythonExecutor

< >

( additional_authorized_imports: list max_print_outputs_length: int | None = None additional_functions: dict[str, collections.abc.Callable] | None = None timeout_seconds: int | None = 30 )

Parameters

  • additional_authorized_imports (list[str]) — Additional authorized imports for the executor.
  • max_print_outputs_length (int, defaults to DEFAULT_MAX_LEN_OUTPUT=50_000) — Maximum length of the print outputs.
  • additional_functions (dict[str, Callable], optional) — Additional Python functions to be added to the executor.
  • timeout_seconds (int, optional, defaults to MAX_EXECUTION_TIME_SECONDS) — Maximum time in seconds allowed for code execution. Set to None to disable timeout.

Executor of Python code in a local environment.

This executor evaluates Python code with restricted access to imports and built-in functions, making it suitable for running untrusted code. It maintains state between executions, allows for custom tools and functions to be made available to the code, and captures print outputs separately from return values.

Remote Python executors

class smolagents.remote_executors.RemotePythonExecutor

< >

( additional_imports: list logger allow_pickle: bool = False )

Parameters

  • additional_imports (list[str]) — Additional Python packages to install.
  • logger (Logger) — Logger to use for output and errors.
  • allow_pickle (bool, default False) — Whether to allow pickle serialization for objects that cannot be safely serialized to JSON.

    • False (default, recommended): Only safe JSON serialization is used. Raises error if object cannot be safely serialized.
    • True (legacy mode): Tries safe JSON serialization first, falls back to pickle with warning if needed.

    Security Warning: Pickle deserialization can execute arbitrary code. Only set allow_pickle=True if you fully trust the execution environment and need backward compatibility with custom types.

Executor of Python code in a remote environment.

run_code_raise_errors

< >

( code: str ) CodeOutput

Parameters

  • code (str) — Python code to execute.

Returns

CodeOutput

Code output containing the result, logs, and whether it is the final answer.

Execute Python code in the remote environment and return the result.

send_variables

< >

( variables: dict )

Send variables to the kernel namespace using SafeSerializer.

Uses prefix-based format (“safe:…” or “pickle:…”). When allow_pickle=False, only safe JSON serialization is allowed. When allow_pickle=True, pickle fallback is enabled for complex types.

BlaxelExecutor

class smolagents.BlaxelExecutor

< >

( additional_imports: list logger allow_pickle: bool = False sandbox_name: str | None = None image: str = 'blaxel/jupyter-notebook' memory: int = 4096 ttl: str | None = None region: typing.Optional[str] = None )

Parameters

  • additional_imports (list[str]) — Additional Python packages to install.
  • logger (Logger) — Logger to use for output and errors.
  • allow_pickle (bool, default False) — Whether to allow pickle serialization for objects that cannot be safely serialized to JSON.

    • False (default, recommended): Only safe JSON serialization is used. Raises error if object cannot be safely serialized.
    • True (legacy mode): Tries safe JSON serialization first, falls back to pickle with warning if needed.

    Security Warning: Pickle deserialization can execute arbitrary code. Only set allow_pickle=True if you fully trust the execution environment and need backward compatibility with custom types.

  • sandbox_name (str, optional) — Name for the sandbox. Defaults to “smolagent-executor”.
  • image (str, default "blaxel/jupyter-notebook") — Docker image to use.
  • memory (int, default 4096) — Memory allocation in MB.
  • ttl (str, optional) — Time to live in seconds.
  • region (str, optional) — Deployment region. If not specified, Blaxel chooses default.

Remote Python code executor in a Blaxel sandbox.

Blaxel provides fast-launching virtual machines that start from hibernation in under 25ms and scale back to zero after inactivity while maintaining memory state.

cleanup

< >

( )

Sync wrapper to clean up sandbox and resources.

delete

< >

( )

Ensure cleanup on deletion.

install_packages

< >

( additional_imports: list )

Helper method to install packages asynchronously.

run_code_raise_errors

< >

( code: str ) CodeOutput

Parameters

  • code (str) — Python code to execute.

Returns

CodeOutput

Code output containing the result, logs, and whether it is the final answer.

Execute Python code in the Blaxel sandbox and return the result.

E2BExecutor

class smolagents.E2BExecutor

< >

( additional_imports: list logger allow_pickle: bool = False **kwargs )

Parameters

  • additional_imports (list[str]) — Additional Python packages to install.
  • logger (Logger) — Logger to use for output and errors.
  • allow_pickle (bool, default False) — Whether to allow pickle serialization for objects that cannot be safely serialized to JSON.

    • False (default, recommended): Only safe JSON serialization is used. Raises error if object cannot be safely serialized.
    • True (legacy mode): Tries safe JSON serialization first, falls back to pickle with warning if needed.

    Security Warning: Pickle deserialization can execute arbitrary code. Only set allow_pickle=True if you fully trust the execution environment and need backward compatibility with custom types.

  • **kwargs — Additional keyword arguments to pass to the E2B Sandbox instantiation.

Remote Python code executor in an E2B sandbox.

cleanup

< >

( )

Clean up the E2B sandbox and resources.

run_code_raise_errors

< >

( code: str ) CodeOutput

Parameters

  • code (str) — Python code to execute.

Returns

CodeOutput

Code output containing the result, logs, and whether it is the final answer.

Execute Python code in the E2B sandbox and return the result.

ModalExecutor

class smolagents.ModalExecutor

< >

( additional_imports: list logger allow_pickle: bool = False app_name: str = 'smolagent-executor' port: int = 8888 create_kwargs: typing.Optional[dict] = None )

Parameters

  • additional_imports (list[str]) — Additional Python packages to install.
  • logger (Logger) — Logger to use for output and errors.
  • allow_pickle (bool, default False) — Whether to allow pickle serialization for objects that cannot be safely serialized to JSON.

    • False (default, recommended): Only safe JSON serialization is used. Raises error if object cannot be safely serialized.
    • True (legacy mode): Tries safe JSON serialization first, falls back to pickle with warning if needed.

    Security Warning: Pickle deserialization can execute arbitrary code. Only set allow_pickle=True if you fully trust the execution environment and need backward compatibility with custom types.

  • app_name (str, default "smolagent-executor") — App name.
  • port (int, default 8888) — Port for jupyter to bind to.
  • create_kwargs (dict, optional) — Additional keyword arguments to pass to the Modal Sandbox create command. See modal.Sandbox.create docs for all the keyword arguments.

Remote Python code executor in a Modal sandbox.

cleanup

< >

( )

Clean up the Modal sandbox by terminating it.

delete

< >

( )

Ensure cleanup on deletion.

run_code_raise_errors

< >

( code: str ) CodeOutput

Parameters

  • code (str) — Python code to execute.

Returns

CodeOutput

Code output containing the result, logs, and whether it is the final answer.

Execute Python code in the Modal sandbox and return the result.

DockerExecutor

class smolagents.DockerExecutor

< >

( additional_imports: list logger allow_pickle: bool = False host: str = '127.0.0.1' port: int = 8888 image_name: str = 'jupyter-kernel' build_new_image: bool = True container_run_kwargs: dict[str, typing.Any] | None = None dockerfile_content: str | None = None )

Parameters

  • additional_imports (list[str]) — Additional Python packages to install.
  • logger (Logger) — Logger to use for output and errors.
  • allow_pickle (bool, default False) — Whether to allow pickle serialization for objects that cannot be safely serialized to JSON.

    • False (default, recommended): Only safe JSON serialization is used. Raises error if object cannot be safely serialized.
    • True (legacy mode): Tries safe JSON serialization first, falls back to pickle with warning if needed.

    Security Warning: Pickle deserialization can execute arbitrary code. Only set allow_pickle=True if you fully trust the execution environment and need backward compatibility with custom types.

  • host (str, default "127.0.0.1") — Host to bind to.
  • port (int, default 8888) — Port to bind to.
  • image_name (str, default "jupyter-kernel") — Name of the Docker image to use. If the image doesn’t exist, it will be built.
  • build_new_image (bool, default True) — Whether to rebuild a new image even if it already exists.
  • container_run_kwargs (dict, optional) — Additional keyword arguments to pass to the Docker container run command.
  • dockerfile_content (str, optional) — Custom Dockerfile content. If None, uses default.

Remote Python code executor using Jupyter Kernel Gateway in a Docker container.

cleanup

< >

( )

Clean up the Docker container and resources.

delete

< >

( )

Ensure cleanup on deletion.

run_code_raise_errors

< >

( code: str ) CodeOutput

Parameters

  • code (str) — Python code to execute.

Returns

CodeOutput

Code output containing the result, logs, and whether it is the final answer.

Execute Python code in the Docker container and return the result.

WasmExecutor

class smolagents.WasmExecutor

< >

( additional_imports: list logger allow_pickle: bool = False deno_path: str = 'deno' deno_permissions: list[str] | None = None timeout: int = 60 )

Parameters

  • additional_imports (list[str]) — Additional Python packages to install in the Pyodide environment.
  • logger (Logger) — Logger to use for output and errors.
  • allow_pickle (bool, default False) — Whether to allow pickle serialization for objects that cannot be safely serialized to JSON.

    • False (default, recommended): Only safe JSON serialization is used. Raises error if object cannot be safely serialized.
    • True (legacy mode): Tries safe JSON serialization first, falls back to pickle with warning if needed.

    Security Warning: Pickle deserialization can execute arbitrary code. Only set allow_pickle=True if you fully trust the execution environment and need backward compatibility with custom types.

  • deno_path (str, default "deno") — Path to the Deno executable. If not provided, will use “deno” from PATH.
  • deno_permissions (list[str], optional) — List of permissions to grant to the Deno runtime. Default is minimal permissions needed for execution.
  • timeout (int, default 60) — Timeout in seconds for code execution

Remote Python code executor in a sandboxed WebAssembly environment powered by Pyodide and Deno.

This executor combines Deno’s secure runtime with Pyodide’s WebAssembly‑compiled Python interpreter to deliver s trong isolation guarantees while enabling full Python execution.

cleanup

< >

( )

Clean up resources used by the executor.

delete

< >

( )

Ensure cleanup on deletion.

install_packages

< >

( additional_imports: list ) list[str]

Parameters

  • additional_imports (list[str]) — Package names to install.

Returns

list[str]

Installed packages.

Install additional Python packages in the Pyodide environment.

run_code_raise_errors

< >

( code: str ) CodeOutput

Parameters

  • code (str) — Python code to execute.

Returns

CodeOutput

Code output containing the result, logs, and whether it is the final answer.

Execute Python code in the Pyodide environment and return the result.

Update on GitHub