Execute_python: How AI Safely Executes Code in an Isolated Sandbox

Introduction

Modern AI models, such as GPT-4, can not only generate text but also execute Python code. This opens up new possibilities for automation, data analysis, and solving complex tasks. However, running code generated by a neural network carries risks: from syntax errors to malicious actions. This is where execute_python comes into play—a mechanism that allows AI to generate, check, and execute code in an isolated environment called a sandbox. In this article, we will break down how it works, what technologies ensure security, and why it is important for developers.

What is execute_python?

Execute_python is a function or API that allows an AI model to execute Python scripts in real time. Instead of just offering a text-based solution, the model can run the code, process data, and return the result. This is especially useful for:

  • Mathematical calculations — complex formulas, statistics.
  • Data processing — filtering, sorting, visualization.
  • Algorithm testing — verifying logic before implementation.
  • Working with APIs — fetching and analyzing external data.

How does it work?

  1. Code generation: The AI writes a Python script based on the user's request.
  2. Security check: The code undergoes static analysis for dangerous commands (e.g., os.system, subprocess.Popen).
  3. Execution in a sandbox: The code runs in an isolated environment that restricts access to the file system, network, and system resources.
  4. Return of result: The user receives stdout, stderr, or execution errors.

Why is a sandbox needed?

A sandbox is an isolated environment that prevents the code from affecting the main system. Without it, the AI could accidentally delete files, execute malicious commands, or overload the server. The main principles:

  • Privilege restriction: The code runs under a user with minimal privileges.
  • Process isolation: Technologies like Docker, Firejail, or chroot are used.
  • Monitoring: Memory, CPU, and disk space usage are tracked.
  • Timeouts: Execution is interrupted if the code runs too long.

Example of a Docker-based sandbox

import docker

def run_in_sandbox(code: str) -> str:
    client = docker.from_env()
    container = client.containers.run(
        "python:3.9",
        command=f"python -c '{code}'",
        mem_limit="256m",
        cpu_quota=50000,
        network_disabled=True,
        read_only=True,
        remove=True
    )
    return container.decode("utf-8")

This code creates a temporary container that executes the script and is automatically removed. The network is disabled, memory and CPU are limited, and the file system operates in read-only mode.

Security of execute_python

Security is a key issue when executing code from AI. Here are the measures modern systems use:

1. Static code analysis

Before execution, the code is checked for prohibited constructs. For example:

import ast
import sys

BLACKLIST = {"os", "subprocess", "shutil", "sys.exit"}

def check_code(code: str) -> bool:
    try:
        tree = ast.parse(code)
        for node in ast.walk(tree):
            if isinstance(node, ast.Call):
                if isinstance(node.func, ast.Attribute):
                    if node.func.attr in BLACKLIST:
                        return False
        return True
    except SyntaxError:
        return False

2. Resource limits

  • CPU: Quotas on processor time (e.g., 1 core).
  • Memory: RAM limit (usually 256-512 MB).
  • Disk: Prohibition on writing to system directories.
  • Network: Blocking all ports except allowed ones.

3. Isolation with Firejail

Firejail is a utility for

← All posts

Comments