Skip to content

LocalCommandLineCodeExecutor

autogen.coding.LocalCommandLineCodeExecutor #

LocalCommandLineCodeExecutor(timeout=60, virtual_env_context=None, work_dir=Path(), functions=[], functions_module='functions', execution_policies=None)

Bases: CodeExecutor

(Experimental) A code executor class that executes or saves LLM generated code a local command line environment.

This will execute or save LLM generated code on the local machine.

Each code block is saved as a file in the working directory. Depending on the execution policy, the code may be executed in a separate process. The code blocks are executed or save in the order they are received. Command line code is sanitized against a list of dangerous commands to prevent self-destructive commands from being executed, which could potentially affect the user's environment. Supported languages include Python, shell scripts (bash, shell, sh), PowerShell (pwsh, powershell, ps1), HTML, CSS, and JavaScript. Execution policies determine whether each language's code blocks are executed or saved only.

Execution with a Python virtual environment#

A python virtual env can be used to execute code and install dependencies. This has the added benefit of not polluting the base environment with unwanted modules.

from autogen.code_utils import create_virtual_env
from autogen.coding import LocalCommandLineCodeExecutor

venv_dir = ".venv"
venv_context = create_virtual_env(venv_dir)

executor = LocalCommandLineCodeExecutor(virtual_env_context=venv_context)

PARAMETER DESCRIPTION
timeout

The timeout for code execution, default is 60 seconds.

TYPE: int DEFAULT: 60

virtual_env_context

The virtual environment context to use.

TYPE: Optional[SimpleNamespace] DEFAULT: None

work_dir

The working directory for code execution, defaults to the current directory.

TYPE: Union[Path, str] DEFAULT: Path()

functions

A list of callable functions available to the executor.

TYPE: List[Union[FunctionWithRequirements[Any, A], Callable[..., Any], FunctionWithRequirementsStr]] DEFAULT: []

functions_module

The module name under which functions are accessible.

TYPE: str DEFAULT: 'functions'

execution_policies

A dictionary mapping languages to execution policies (True for execution, False for saving only). Defaults to class-wide DEFAULT_EXECUTION_POLICY.

TYPE: Optional[Dict[str, bool]] DEFAULT: None

Source code in autogen/coding/local_commandline_code_executor.py
def __init__(
    self,
    timeout: int = 60,
    virtual_env_context: Optional[SimpleNamespace] = None,
    work_dir: Union[Path, str] = Path(),
    functions: list[Union[FunctionWithRequirements[Any, A], Callable[..., Any], FunctionWithRequirementsStr]] = [],
    functions_module: str = "functions",
    execution_policies: Optional[dict[str, bool]] = None,
):
    """(Experimental) A code executor class that executes or saves LLM generated code a local command line
    environment.

    **This will execute or save LLM generated code on the local machine.**

    Each code block is saved as a file in the working directory. Depending on the execution policy,
    the code may be executed in a separate process.
    The code blocks are executed or save in the order they are received.
    Command line code is sanitized against a list of dangerous commands to prevent self-destructive commands from being executed,
    which could potentially affect the user's environment. Supported languages include Python, shell scripts (bash, shell, sh),
    PowerShell (pwsh, powershell, ps1), HTML, CSS, and JavaScript.
    Execution policies determine whether each language's code blocks are executed or saved only.

    ## Execution with a Python virtual environment
    A python virtual env can be used to execute code and install dependencies. This has the added benefit of not polluting the
    base environment with unwanted modules.
    ```python
    from autogen.code_utils import create_virtual_env
    from autogen.coding import LocalCommandLineCodeExecutor

    venv_dir = ".venv"
    venv_context = create_virtual_env(venv_dir)

    executor = LocalCommandLineCodeExecutor(virtual_env_context=venv_context)
    ```

    Args:
        timeout (int): The timeout for code execution, default is 60 seconds.
        virtual_env_context (Optional[SimpleNamespace]): The virtual environment context to use.
        work_dir (Union[Path, str]): The working directory for code execution, defaults to the current directory.
        functions (List[Union[FunctionWithRequirements[Any, A], Callable[..., Any], FunctionWithRequirementsStr]]): A list of callable functions available to the executor.
        functions_module (str): The module name under which functions are accessible.
        execution_policies (Optional[Dict[str, bool]]): A dictionary mapping languages to execution policies (True for execution, False for saving only). Defaults to class-wide DEFAULT_EXECUTION_POLICY.
    """
    if timeout < 1:
        raise ValueError("Timeout must be greater than or equal to 1.")

    if isinstance(work_dir, str):
        work_dir = Path(work_dir)

    if not functions_module.isidentifier():
        raise ValueError("Module name must be a valid Python identifier")

    self._functions_module = functions_module

    work_dir.mkdir(exist_ok=True)

    self._timeout = timeout
    self._work_dir: Path = work_dir
    self._virtual_env_context: Optional[SimpleNamespace] = virtual_env_context

    self._functions = functions
    # Setup could take some time so we intentionally wait for the first code block to do it.
    if len(functions) > 0:
        self._setup_functions_complete = False
    else:
        self._setup_functions_complete = True

    self.execution_policies = self.DEFAULT_EXECUTION_POLICY.copy()
    if execution_policies is not None:
        self.execution_policies.update(execution_policies)

SUPPORTED_LANGUAGES class-attribute #

SUPPORTED_LANGUAGES = ['bash', 'shell', 'sh', 'pwsh', 'powershell', 'ps1', 'python', 'javascript', 'html', 'css']

DEFAULT_EXECUTION_POLICY class-attribute #

DEFAULT_EXECUTION_POLICY = {'bash': True, 'shell': True, 'sh': True, 'pwsh': True, 'powershell': True, 'ps1': True, 'python': True, 'javascript': False, 'html': False, 'css': False}

FUNCTION_PROMPT_TEMPLATE class-attribute #

FUNCTION_PROMPT_TEMPLATE = 'You have access to the following user defined functions. They can be accessed from the module called `$module_name` by their function names.\n\nFor example, if there was a function called `foo` you could import it by writing `from $module_name import foo`\n\n$functions'

execution_policies instance-attribute #

execution_policies = copy()

functions_module property #

functions_module

(Experimental) The module name for the functions.

functions property #

functions

(Experimental) The functions that are available to the code executor.

timeout property #

timeout

(Experimental) The timeout for code execution.

work_dir property #

work_dir

(Experimental) The working directory for the code execution.

code_extractor property #

code_extractor

(Experimental) Export a code extractor that can be used by an agent.

format_functions_for_prompt #

format_functions_for_prompt(prompt_template=FUNCTION_PROMPT_TEMPLATE)

(Experimental) Format the functions for a prompt.

The template includes two variables: - $module_name: The module name. - $functions: The functions formatted as stubs with two newlines between each function.

PARAMETER DESCRIPTION
prompt_template

The prompt template. Default is the class default.

TYPE: str DEFAULT: FUNCTION_PROMPT_TEMPLATE

RETURNS DESCRIPTION
str

The formatted prompt.

TYPE: str

Source code in autogen/coding/local_commandline_code_executor.py
def format_functions_for_prompt(self, prompt_template: str = FUNCTION_PROMPT_TEMPLATE) -> str:
    """(Experimental) Format the functions for a prompt.

    The template includes two variables:
    - `$module_name`: The module name.
    - `$functions`: The functions formatted as stubs with two newlines between each function.

    Args:
        prompt_template (str): The prompt template. Default is the class default.

    Returns:
        str: The formatted prompt.
    """
    template = Template(prompt_template)
    return template.substitute(
        module_name=self._functions_module,
        functions="\n\n".join([to_stub(func) for func in self._functions]),
    )

sanitize_command staticmethod #

sanitize_command(lang, code)

Sanitize the code block to prevent dangerous commands. This approach acknowledges that while Docker or similar containerization/sandboxing technologies provide a robust layer of security, not all users may have Docker installed or may choose not to use it. Therefore, having a baseline level of protection helps mitigate risks for users who, either out of choice or necessity, run code outside of a sandboxed environment.

Source code in autogen/coding/local_commandline_code_executor.py
@staticmethod
def sanitize_command(lang: str, code: str) -> None:
    """Sanitize the code block to prevent dangerous commands.
    This approach acknowledges that while Docker or similar
    containerization/sandboxing technologies provide a robust layer of security,
    not all users may have Docker installed or may choose not to use it.
    Therefore, having a baseline level of protection helps mitigate risks for users who,
    either out of choice or necessity, run code outside of a sandboxed environment.
    """
    dangerous_patterns = [
        (r"\brm\s+-rf\b", "Use of 'rm -rf' command is not allowed."),
        (r"\bmv\b.*?\s+/dev/null", "Moving files to /dev/null is not allowed."),
        (r"\bdd\b", "Use of 'dd' command is not allowed."),
        (r">\s*/dev/sd[a-z][1-9]?", "Overwriting disk blocks directly is not allowed."),
        (r":\(\)\{\s*:\|\:&\s*\};:", "Fork bombs are not allowed."),
    ]
    if lang in ["bash", "shell", "sh"]:
        for pattern, message in dangerous_patterns:
            if re.search(pattern, code):
                raise ValueError(f"Potentially dangerous command detected: {message}")

execute_code_blocks #

execute_code_blocks(code_blocks)

(Experimental) Execute the code blocks and return the result.

PARAMETER DESCRIPTION
code_blocks

The code blocks to execute.

TYPE: List[CodeBlock]

RETURNS DESCRIPTION
CommandLineCodeResult

The result of the code execution.

TYPE: CommandLineCodeResult

Source code in autogen/coding/local_commandline_code_executor.py
def execute_code_blocks(self, code_blocks: list[CodeBlock]) -> CommandLineCodeResult:
    """(Experimental) Execute the code blocks and return the result.

    Args:
        code_blocks (List[CodeBlock]): The code blocks to execute.

    Returns:
        CommandLineCodeResult: The result of the code execution.
    """
    if not self._setup_functions_complete:
        self._setup_functions()
    return self._execute_code_dont_check_setup(code_blocks)

restart #

restart()

(Experimental) Restart the code executor.

Source code in autogen/coding/local_commandline_code_executor.py
def restart(self) -> None:
    """(Experimental) Restart the code executor."""
    warnings.warn("Restarting local command line code executor is not supported. No action is taken.")