agentscope.service.execute_code.exec_python module

Service to execute python code.

agentscope.service.execute_code.exec_python.execute_python_code(code: str, timeout: int | float | None = 300, use_docker: bool | str | None = None, maximum_memory_bytes: int | None = None) ServiceResponse[源代码]

Execute a piece of python code.

This function can run Python code provided in string format. It has the option to execute the code within a Docker container to provide an additional layer of security, especially important when running untrusted code.

WARNING: If use_docker is set to False, the code will be run directly in the host system’s environment. This poses a potential security risk if the code is untrusted. Only disable Docker if you are confident in the safety of the code being executed.

参数:
  • code (str, optional) – The Python code to be executed.

  • timeout (Optional[Union[int, float]], defaults to 300) – The maximum time (in seconds) allowed for the code to run. If the code execution time exceeds this limit, it will be terminated. Set to None for no time limit. Default is 300.

  • use_docker (Optional[Union[bool, str]], defaults to None) – Determines whether to execute the code within a Docker container. If False, the system’s native Python environment is used. When set to None, the function checks for Docker’s availability and uses it if present. When set to some string, will use the docker with string as the image name. Default is None.

  • maximum_memory_bytes (Optional[int], defaults to None) – The memory limit in bytes for the code execution. If not specified, there is no memory limit imposed.

返回:

A ServiceResponse containing two elements: output and error. Both output and error are strings that capture the standard output and standard error of the code execution, respectively.

返回类型:

ServiceResponse

备注

IPython-specific operations such as plt.show() for displaying matplotlib plots are currently not supported. This limitation stems from the non-interactive nature of the execution environment.

The argument timeout is not available in Windows OS, since the since signal.setitimer is only available in Unix.

agentscope.service.execute_code.exec_python.sys_python_guard(maximum_memory_bytes: int | None = None) None[源代码]

This disables various destructive functions and prevents the generated code from interfering with the test (e.g. fork bomb, killing other processes, removing filesystem files, etc.)

The implementation of this function are modified from https://github.com/openai/human-eval/blob/master/human_eval/execution.py