◢ build log

Building a Safe Code Interpreter for AI Agents

Learn how to build a secure, isolated code execution environment for your AI agents to safely run and validate their generated code.

AI agents need to execute code to solve complex problems. They can write scripts to analyze data, interact with APIs, or perform intricate calculations. Giving an agent the ability to run code extends its capabilities beyond what a large language model alone can do.

However, letting an AI agent execute arbitrary code directly on your system is a significant security risk. You need a controlled environment. This means a sandbox that protects your infrastructure from potentially malicious or buggy code the agent might generate. It also ensures consistent resource usage and predictable outcomes.

Why Agents Need Code Execution

LLMs are powerful, but they operate on text. They excel at reasoning, generating ideas, and writing code. But they cannot run that code. They cannot check if it works, debug errors, or interact with real-world systems directly through execution.

Code execution bridges this gap. An agent can generate a Python script to fetch data from a database, process it, and then summarize the results. Without execution, the agent can only imagine the outcome. With it, the agent gets real feedback. It learns whether its code is correct, efficient, or if it needs to adjust its approach.

This is crucial for tasks requiring precision, data validation, or interaction with external tools. It turns an agent from a code writer into a code developer.

The Risks of Uncontrolled Execution

Running code from an AI agent without safeguards is dangerous. Consider these points:

  • Security Vulnerabilities: An agent might inadvertently (or, in a hypothetical adversarial scenario, intentionally) generate code that accesses sensitive files, deletes data, or makes unauthorized network requests. This is the risk of arbitrary code execution.
  • Resource Exhaustion: Code could enter an infinite loop, consume all available CPU, or fill up memory. This can crash your server or make it unresponsive.
  • Unintended Side Effects: A script might modify system configurations, install unwanted packages, or leave behind temporary files that clutter the environment.
  • Data Leakage: Code could exfiltrate data from your system if it has network access.

Your goal is to provide enough capability for the agent to do its job, but not so much that it can harm your system.

Core Components of a Safe Environment

Building a safe execution environment requires several key elements:

Isolation

The code must run in isolation from your host system. Docker containers are an excellent choice for this. They provide lightweight, portable, and isolated environments. Virtual machines (VMs) are another option for stronger isolation but come with more overhead.

Resource Limits

Limit the CPU, memory, and execution time available to the running code. This prevents runaway processes from consuming all your server's resources. If a script exceeds these limits, it should be terminated gracefully.

Restricted Access

Control what the code can access. This includes:

  • Filesystem: Mount only necessary directories, and make them read-only if possible. Prevent access to system files.
  • Network: Restrict outbound network calls. Allow only specific domains or ports if the agent needs to interact with external APIs.
  • System Calls: Use tools like seccomp (Secure Computing mode) in Linux to filter and restrict the system calls a process can make.

Input/Output Capture

You need to capture the standard output (stdout) and standard error (stderr) of the executed code. This is how the agent gets feedback. The output might be the result of a calculation, a data summary, or an error message.

Building Blocks: Docker Containers

Docker simplifies the creation of isolated execution environments. Here's a basic approach:

First, define a Dockerfile for your execution environment. For Python, it might look like this:

FROM python:3.10-slim-buster
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
CMD ["python", "script.py"]

This creates a minimal Python environment. You can pre-install common libraries in requirements.txt that your agent frequently uses.

To execute code, your host application will:

  1. Receive the generated code from the AI agent.
  2. Write this code to a temporary file (e.g., script.py).
  3. Mount this file into the Docker container.
  4. Run the container with strict resource limits.

Implementing Code Execution Logic

Your application code (e.g., a Python backend service) will orchestrate the Docker execution. Here's a conceptual Python example using subprocess:

import subprocess
import os
import tempfile

def execute_agent_code(code_string: str, timeout: int = 30) -> tuple[str, str, int]:
    # Create a temporary file to store the agent's code
    with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as temp_script_file:
        temp_script_file.write(code_string)
        script_path = temp_script_file.name

    container_name = f"agent_executor_{os.path.basename(script_path).replace('.', '_')}"

    try:
        # Build the Docker run command
        # --rm: Automatically remove the container when it exits
        # --network none: Disable network access (consider if agent needs internet)
        # --memory=100m: Limit memory to 100MB
        # --cpus=0.5: Limit CPU usage to 50%
        # -v {script_path}:/app/script.py: Mount the script into the container
        # -w /app: Set working directory inside container
        # python script.py: The command to run inside the container
        
        docker_command = [
            "docker", "run", "--rm", 
            "--network", "none", 
            "--memory", "100m", 
            "--cpus", "0.5",
            "-v", f"{script_path}:/app/script.py",
            "-w", "/app",
            "--name", container_name,
            "my-python-executor", # Name of your Docker image built from Dockerfile
            "python", "script.py"
        ]

        # Execute the Docker command
        result = subprocess.run(
            docker_command,
            capture_output=True,
            text=True,
            timeout=timeout, # Timeout for the subprocess itself
            check=False # Don't raise exception for non-zero exit codes
        )

        stdout = result.stdout.strip()
        stderr = result.stderr.strip()
        exit_code = result.returncode

        return stdout, stderr, exit_code

    except subprocess.TimeoutExpired:
        # Handle cases where the Docker command itself times out
        # This is separate from the container's internal execution timeout if any
        subprocess.run(["docker", "kill", container_name], capture_output=True)
        return "", "Execution timed out", 1
    except Exception as e:
        return "", f"Execution error: {e}", 1
    finally:
        # Clean up the temporary script file
        if os.path.exists(script_path):
            os.remove(script_path)

## Example usage:
## code_to_run = "print('Hello from agent'); import os; print(os.listdir('/'))"
## stdout, stderr, exit_code = execute_agent_code(code_to_run)
## print(f"STDOUT: {stdout}")
## print(f"STDERR: {stderr}")
## print(f"Exit Code: {exit_code}")

This execute_agent_code function takes the agent's code as a string, saves it, runs it in a Docker container with resource limits and network isolation, and returns the output. The my-python-executor image would be built from your Dockerfile.

Validation and Feedback Loop

Once the code executes, your application receives the stdout, stderr, and exit_code. This information is then passed back to the AI agent.

  • exit_code == 0: Typically indicates success. The stdout contains the expected result.
  • exit_code != 0: Indicates an error. The stderr will likely contain a traceback or error message.
  • Timeout: The code took too long. This suggests an inefficient algorithm or an infinite loop.

The agent uses this feedback to iterate. If it gets an error, it can analyze the stderr to debug its code and try again. This iterative refinement is a cornerstone of effective AI agent development.

Advanced Considerations

  • Language Agnostic: You can create different Docker images for different languages (Node.js, Go, etc.) and select the appropriate one based on the agent's generated code.
  • Pre-installed Libraries: For common tasks, pre-install frequently used libraries in your Docker image. This saves time and bandwidth during execution.
  • Stateful Execution: For some complex scenarios, you might need a more stateful environment where previous execution results persist. This is harder to secure and manage but can be achieved with persistent volumes or by keeping containers alive for a session. Approach with extreme caution.
  • Security Hardening: Beyond basic Docker flags, consider user namespaces, AppArmor/SELinux profiles, and more fine-grained seccomp filters for production systems.

Building a robust and secure code interpretation environment is a critical step in deploying powerful and reliable AI agents. It protects your infrastructure while empowering your agents to tackle real-world problems.

Where to go from here

Start by building a minimal Docker environment and a Python script to run simple commands within it. Gradually add resource limits and network restrictions. If you need help designing secure AI agent systems, consider AI consulting services.

  • ai agent code execution
  • safe code interpreter
  • docker sandbox ai
  • llm code execution environment
  • ai agent security
  • isolated code execution
  • agent code validation
  • ai development best practices
  • custom code interpreter
05 — execute

Ready to build
the future?

Join the developers learning to build with AI. New tutorials, tools and breakdowns every week — straight to your feed.

$ aidevguy --start --now_