https://github.com/biocypher/biocage

Fast, secure, and practical Python sandbox designed specifically for safely executing code generated by LLMs

https://github.com/biocypher/biocage

Science Score: 26.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (17.3%) to scientific vocabulary
Last synced: 11 months ago · JSON representation

Repository

Fast, secure, and practical Python sandbox designed specifically for safely executing code generated by LLMs

Basic Info
  • Host: GitHub
  • Owner: biocypher
  • License: mit
  • Language: Python
  • Default Branch: main
  • Homepage:
  • Size: 1.41 MB
Statistics
  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • Open Issues: 0
  • Releases: 0
Created about 1 year ago · Last pushed about 1 year ago
Metadata Files
Readme Contributing License

README.md

BioCage

BioCage Logo

Release Build status Coverage Commit activity License

⚠️ DEVELOPMENT STATUS: This library is currently under active development and is not ready for use. Stay tuned for updates!

BioCage is a fast, secure, and practical Python sandbox designed specifically for safely executing code generated by Large Language Models (LLMs). It provides a robust containerized environment that isolates code execution while maintaining state persistence and file system integration.

🎯 Why BioCage?

BioCage addresses critical needs:

  • 🔒 Security: Complete isolation through Docker with no network access and restricted file system
  • 🧠 State Persistence: Variables, imports, and functions persist across multiple executions
  • 📁 File Integration: Seamlessly expose files and directories to the sandbox
  • ⚡ Performance: Fast startup times with optimized container management
  • 🛡️ Reliability: Comprehensive error handling with detailed diagnostics
  • 🔧 Flexibility: Support for both ephemeral and persistent execution modes

✨ Key Features

🔒 Security First

  • Complete Docker containerization with no host system access
  • Network isolation (disabled by default)
  • Resource limits (memory, CPU, execution time)
  • Read-only filesystem with controlled write access
  • Safe execution of potentially malicious AI-generated code

🧠 Intelligent State Management

  • Variable persistence across executions
  • Import persistence - no need to re-import libraries
  • Function and class definitions remain available
  • DataFrame modifications persist between runs
  • Session-based workflows for complex data processing

📁 Advanced File System Integration

  • File exposure: Mount individual files from host to container
  • Directory exposure: Mount directories with read-only or read-write access
  • Temporary file creation: Create files accessible within the sandbox
  • Automatic cleanup: Files and mounts cleaned up after execution

⚡ Performance Optimized

  • Pre-built images with common data science libraries
  • Fast container startup and execution
  • Efficient resource usage with proper limits
  • Minimal overhead for code execution

🚀 Quick Start

Installation

bash pip install biocage

Basic Usage

```python from biocage import BioCageManager

Simple one-time execution

with BioCageManager() as sandbox: result = sandbox.run('print("Hello from BioCage!")') print(result.stdout) # "Hello from BioCage!" ```

State Persistence Example

```python

Variables and imports persist across executions

sandbox = BioCageManager() sandbox.start_container()

try: # Set up your environment once sandbox.run(""" import pandas as pd import numpy as np

# Define helper functions
def analyze_data(data):
    return {
        'mean': np.mean(data),
        'std': np.std(data),
        'count': len(data)
    }

# Initialize data
df = pd.DataFrame({
    'values': np.random.randn(1000),
    'category': np.random.choice(['A', 'B', 'C'], 1000)
})
""")

# Use the environment in subsequent executions
result = sandbox.run("""
# Everything from previous execution is still available
stats = analyze_data(df['values'])
print(f"Data statistics: {stats}")

# Modify the DataFrame
df['squared'] = df['values'] ** 2
print(f"DataFrame shape: {df.shape}")
""")

print(result.stdout)

finally: sandbox.stop_container() ```

File and Directory Integration

```python

Expose files and directories to the sandbox

with BioCageManager().configurecontextmanager( exposefiles={ "/path/to/data.csv": "/app/data/input.csv", "/path/to/config.json": "/app/config/settings.json" }, exposedirectories={ "/path/to/models": "/app/models" # Read-only }, exposedirectoriesrw={ "./output": "/app/output" # Read-write } ) as sandbox:

result = sandbox.run("""
import pandas as pd
import json
import os

# Read exposed files
df = pd.read_csv('/app/data/input.csv')
with open('/app/config/settings.json', 'r') as f:
    config = json.load(f)

# List available models
models = os.listdir('/app/models')
print(f"Available models: {models}")

# Process data and save results
summary = df.describe()
summary.to_csv('/app/output/analysis_results.csv')

# Save processing log
with open('/app/output/log.txt', 'w') as f:
    f.write(f"Processed {len(df)} rows with config: {config}")

print(f"Processed {len(df)} rows successfully")
""")

print(result.stdout)

```

Temporary File Creation

```python with BioCageManager() as sandbox: # Create temporary files with custom content csv_data = """name,age,city Alice,25,New York Bob,30,San Francisco Charlie,35,Boston"""

csv_path = sandbox.create_temp_file(csv_data, suffix=".csv")

result = sandbox.run(f"""
import pandas as pd

# Load and analyze the temporary file
df = pd.read_csv('{csv_path}')
print(f"Loaded {len(df)} rows")
print(df.to_string())

# Calculate statistics
avg_age = df['age'].mean()
print(f"Average age: {avg_age:.1f}")
""")

print(result.stdout)
# Temporary files automatically cleaned up

```

🔧 Advanced Features

Resource Management

```python

Configure container resources

sandbox = BioCageManager() sandbox.startcontainer( memorylimit="4g", # 4GB memory limit cpulimit="8.0", # 8 CPU cores networkaccess=False # Disabled by default for security )

Monitor container information

info = sandbox.getcontainerinfo() print(f"Container ID: {info['containerid'][:12]}") print(f"Running: {info['isrunning']}") print(f"Exposed paths: {len(info['exposed_paths'])}")

sandbox.stop_container() ```

Error Handling and Debugging

```python def safeexecute(code, description=""): """Execute code with comprehensive error handling.""" with BioCageManager() as sandbox: result = sandbox.run(code, timeout=30, shutdownon_failure=False)

    if result.success:
        return f"✅ {description}: {result.stdout.strip()}"
    else:
        # Categorize errors for better debugging
        stderr_lower = result.stderr.lower()
        if "syntaxerror" in stderr_lower:
            return f"❌ Syntax Error: {result.stderr}\n💡 Check parentheses, quotes, and indentation"
        elif "nameerror" in stderr_lower:
            return f"❌ Name Error: {result.stderr}\n💡 Variable not defined"
        elif "importerror" in stderr_lower:
            return f"❌ Import Error: {result.stderr}\n💡 Module not available"
        else:
            return f"❌ {description} failed: {result.stderr.strip()}"

Test different scenarios

print(safeexecute("print('Hello World!')", "Basic execution")) print(safeexecute("print(undefinedvar)", "Variable error")) print(safeexecute("import nonexistent_module", "Import error")) ```

Multi-Step Data Analysis Workflow

```python def dataanalysispipeline(datapath, outputdir): """Complete data analysis with state persistence."""

with BioCageManager().configure_context_manager(
    memory_limit="4g",
    expose_files={data_path: "/app/data/dataset.csv"},
    expose_directories_rw={output_dir: "/app/output"}
) as sandbox:

    # Step 1: Load and explore
    sandbox.run("""
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt

    df = pd.read_csv('/app/data/dataset.csv')
    print(f"Dataset shape: {df.shape}")
    print(f"Columns: {list(df.columns)}")
    """)

    # Step 2: Clean data (state persists)
    sandbox.run("""
    df_clean = df.dropna()
    print(f"After cleaning: {df_clean.shape}")

    with open('/app/output/cleaning_report.txt', 'w') as f:
        f.write(f"Original: {df.shape}\\nCleaned: {df_clean.shape}\\n")
    """)

    # Step 3: Analysis (all variables still available)
    result = sandbox.run("""
    summary = df_clean.describe()
    summary.to_csv('/app/output/summary_statistics.csv')

    print(f"Analysis completed for {len(df_clean)} rows")
    """)

    return result.stdout

Usage

result = dataanalysispipeline('/path/to/data.csv', './output')

```

📋 Execution Results

All executions return a comprehensive SandboxExecutionResult object:

```python result = sandbox.run('print("Hello"); import sys; print(sys.version)')

print(f"Success: {result.success}") # True/False print(f"Output: {result.stdout}") # "Hello\n3.11.0..." print(f"Errors: {result.stderr}") # Any error messages print(f"Exit code: {result.exitcode}") # 0 for success print(f"Time: {result.executiontime:.3f}s") # Execution duration

Convert to dictionary for JSON serialization

resultdict = result.todict() ```

🐳 Docker Usage

You can also use BioCage directly with Docker:

```bash

Execute code via stdin

echo 'print("Hello from BioCage!")' | docker run --rm -i biocage:latest

Execute via environment variable

docker run --rm -e PYTHONCODE="import numpy as np; print(np.version_)" biocage:latest

With resource limits

docker run --rm -i --memory="1g" --cpus="2.0" biocage:latest ```

🏗️ Building Custom Images

Customize the Docker environment for your specific needs:

  1. Edit dependencies in python_docker/pyproject.toml: toml [project] dependencies = [ "numpy>=1.24.0", "pandas>=2.0.0", "scikit-learn>=1.3.0", "your-custom-package>=1.0.0", ]

  2. Generate requirements and build: bash cd python_docker uv pip compile pyproject.toml -o requirements.txt ./build.sh

🛡️ Security Features

BioCage is designed with security as a first-class concern:

  • Container Isolation: Complete separation from host system
  • No Network Access: Internet disabled by default during execution
  • Resource Limits: Memory, CPU, and execution time controls
  • Read-Only Filesystem: Prevents unauthorized file modifications
  • Timeout Controls: Automatic termination of long-running processes
  • Privilege Restrictions: Containers run with minimal privileges

🎯 Use Cases

AI/LLM Integration

  • Code Generation: Safely execute AI-generated Python code
  • Interactive Assistants: Build chatbots that can run and debug code
  • Automated Testing: Validate generated code snippets

Education & Training

  • Online Learning: Secure code execution for student submissions
  • Coding Challenges: Isolated environment for competitive programming
  • Tutorial Platforms: Interactive Python learning experiences

Research & Development

  • Experiment Automation: Reproducible research environments
  • Data Processing: Secure analysis of sensitive datasets
  • Algorithm Testing: Isolated testing of new algorithms

Development Workflows

  • CI/CD Pipelines: Safe testing of code changes
  • Code Review: Automated validation of pull requests
  • Prototyping: Quick testing of code concepts

📚 Documentation

🔗 Links

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details on how to get started.


BioCage: Safe, stateful, and powerful Python execution for the AI era.

Owner

  • Name: biocypher
  • Login: biocypher
  • Kind: organization

GitHub Events

Total
  • Issues event: 2
  • Watch event: 1
  • Push event: 2
  • Create event: 1
Last Year
  • Issues event: 2
  • Watch event: 1
  • Push event: 2
  • Create event: 1

Committers

Last synced: about 1 year ago

All Time
  • Total Commits: 20
  • Total Committers: 1
  • Avg Commits per committer: 20.0
  • Development Distribution Score (DDS): 0.0
Past Year
  • Commits: 20
  • Committers: 1
  • Avg Commits per committer: 20.0
  • Development Distribution Score (DDS): 0.0
Top Committers
Name Email Commits
Francesco Carli f****4@g****m 20

Issues and Pull Requests

Last synced: about 1 year ago

All Time
  • Total issues: 0
  • Total pull requests: 0
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Total issue authors: 0
  • Total pull request authors: 0
  • Average comments per issue: 0
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 0
  • Pull requests: 0
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Issue authors: 0
  • Pull request authors: 0
  • Average comments per issue: 0
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • fcarli (1)
Pull Request Authors
Top Labels
Issue Labels
Pull Request Labels

Dependencies

Dockerfile docker
  • python 3.12-slim build
python_docker/Dockerfile docker
  • python 3.11-slim build
python_docker/docker-compose.yml docker
  • biocage latest
pyproject.toml pypi
  • langchain >=0.3.25
  • langchain-google-genai >=2.1.5
  • langgraph >=0.4.8
python_docker/pyproject.toml pypi
  • numpy >=2.2.6
  • pandas >=2.2.3
python_docker/requirements.txt pypi
  • numpy ==2.3.0
  • pandas ==2.3.0
  • python-dateutil ==2.9.0.post0
  • pytz ==2025.2
  • six ==1.17.0
  • tzdata ==2025.2
uv.lock pypi
  • 113 dependencies