LLM Sandbox

0.3.38 · active · verified Wed Apr 15

LLM Sandbox is a lightweight and portable Python library designed to run large language model (LLM) generated code in a safe and isolated environment. It supports various container backends like Docker, Kubernetes, and Podman, and offers multi-language execution (Python, JavaScript, Java, C++, Go, R). The project sees frequent minor releases, addressing features, fixes, and security enhancements, and now supports the Model Context Protocol (MCP) server for direct AI assistant integration.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a `SandboxSession` for Python, execute code, and optionally specify libraries. It includes error handling for common setup issues like the container backend not running.

import os
from llm_sandbox import SandboxSession

# Ensure Docker or another backend is running and accessible
# For a simple test, ensure `llm-sandbox[docker]` is installed.

try:
    with SandboxSession(lang="python") as session:
        print("Running Python code in sandbox...")
        result = session.run(
            "import math\nprint(math.factorial(5))"
        )
        print(f"Sandbox Output: {result.stdout.strip()}")
        if result.stderr:
            print(f"Sandbox Error: {result.stderr.strip()}")

        print("\nRunning Python code with a library (numpy)...")
        # Requires numpy to be installed in the sandbox environment, 
        # or configured for on-the-fly installation. The default image often includes it.
        result_numpy = session.run(
            "import numpy as np\nprint(np.mean([1, 2, 3, 4]))", 
            libraries=["numpy"]
        )
        print(f"Sandbox NumPy Output: {result_numpy.stdout.strip()}")
        if result_numpy.stderr:
            print(f"Sandbox NumPy Error: {result_numpy.stderr.strip()}")

except Exception as e:
    print(f"An error occurred during sandbox execution: {e}")
    print("Ensure your container backend (e.g., Docker) is running and configured correctly.")

view raw JSON →