### Installation of AICodeSandbox via Git Clone Source: https://github.com/typper-io/ai-code-sandbox/blob/main/README.md Instructions for cloning the AICodeSandbox repository from GitHub and navigating into the project directory. ```bash git clone https://github.com/typper-io/ai-code-sandbox.git cd ai-code-sandbox ``` -------------------------------- ### Installing Python Dependencies for AICodeSandbox Source: https://github.com/typper-io/ai-code-sandbox/blob/main/README.md Command to install all required Python packages for AICodeSandbox using pip and a requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Initialize AICodeSandbox Constructor in Python Source: https://context7.com/typper-io/ai-code-sandbox/llms.txt Initializes a secure Docker-based sandbox environment. It allows for configurable resource limits (memory, CPU), network isolation, and optional installation of custom Python packages. The constructor creates a temporary Docker container that runs in detached mode, ready for code execution commands. ```python from ai_code_sandbox import AICodeSandbox # Basic sandbox with default settings (100MB memory, 50% CPU, no network) sandbox = AICodeSandbox() # Sandbox with custom packages for data science work sandbox_ml = AICodeSandbox( packages=["numpy", "pandas", "scikit-learn"], mem_limit="512m", cpu_quota=100000 # Full CPU access ) # Sandbox with custom Docker image and network access sandbox_custom = AICodeSandbox( custom_image="python:3.11-slim", packages=["requests", "beautifulsoup4"], network_mode="bridge", # Enable network access mem_limit="256m", cpu_period=100000, cpu_quota=75000 # 75% CPU limit ) # Always close sandboxes when done sandbox.close() sandbox_ml.close() sandbox_custom.close() ``` -------------------------------- ### Dockerfile for Running AICodeSandbox within Docker Source: https://github.com/typper-io/ai-code-sandbox/blob/main/README.md A Dockerfile configured to run AICodeSandbox inside a Docker container using Docker-in-Docker (DinD). It installs Python, pip, and the necessary AICodeSandbox dependencies, preparing the environment for execution. ```dockerfile FROM docker:dind RUN apk add --no-cache python3 py3-pip WORKDIR /app COPY requirements.txt . COPY README.md . COPY ai_code_sandbox/ ./ai_code_sandbox/ COPY setup.py . RUN python3 -m venv /app/venv ENV PATH="/app/venv/bin:$PATH" RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt RUN pip3 install -e . COPY example.py . CMD ["python3", "example.py"] ``` -------------------------------- ### Create Sandbox, Write Data, Run ML Code, and Read Results Source: https://context7.com/typper-io/ai-code-sandbox/llms.txt This snippet demonstrates the full lifecycle of using the AICodeSandbox. It initializes a sandbox with specified ML packages, writes a CSV file containing training data, executes Python code to train a RandomForestClassifier, and then reads the resulting model performance metrics from a JSON file. The sandbox is automatically closed in a finally block to ensure resource cleanup. ```python sandbox = AICodeSandbox( packages=["numpy", "pandas", "scikit-learn"], mem_limit="512m", cpu_quota=100000 ) try: # Write training data to sandbox sandbox.write_file("/app/data/training.csv", """feature1,feature2,feature3,label 1.2,3.4,5.6,0 2.3,4.5,6.7,1 3.4,5.6,7.8,0 4.5,6.7,8.9,1 5.6,7.8,9.0,0 6.7,8.9,10.1,1 7.8,9.0,11.2,0 8.9,10.1,12.3,1 9.0,11.2,13.4,0 10.1,12.3,14.5,1""") # Run ML training code result = sandbox.run_code(""" import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, classification_report import json # Load data df = pd.read_csv('/app/data/training.csv') X = df[['feature1', 'feature2', 'feature3']] y = df['label'] # Split data X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42 ) # Train model model = RandomForestClassifier(n_estimators=10, random_state=42) model.fit(X_train, y_train) # Evaluate predictions = model.predict(X_test) accuracy = accuracy_score(y_test, predictions) # Save results results = { "accuracy": float(accuracy), "feature_importances": model.feature_importances_.tolist(), "predictions": predictions.tolist() } with open('/app/results/model_output.json', 'w') as f: json.dump(results, f, indent=2) print(f"Model trained successfully!") print(f"Accuracy: {accuracy:.2%}") print(f"Feature importances: {model.feature_importances_}") """) print("Training output:") print(result) # Read the results file model_results = sandbox.read_file("/app/results/model_output.json") print("\nModel results JSON:") print(model_results) finally: sandbox.close() ``` -------------------------------- ### Basic Usage of AICodeSandbox for AI/ML Code Execution Source: https://github.com/typper-io/ai-code-sandbox/blob/main/README.md Demonstrates how to initialize AICodeSandbox with common AI/ML packages and execute a Python code snippet for model training and evaluation within the isolated environment. It includes error handling and ensures sandbox cleanup. ```python from ai_code_sandbox import AICodeSandbox # Create a sandbox with common AI/ML packages sandbox = AICodeSandbox(packages=["numpy", "pandas", "scikit-learn", "tensorflow"]) try: # Run some AI-generated code in the sandbox code = """ import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense # Generate some dummy data X = np.random.rand(1000, 10) y = np.random.randint(0, 2, 1000) # Split the data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # Create a simple neural network model = Sequential([ Dense(64, activation='relu', input_shape=(10,)), Dense(32, activation='relu'), Dense(1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Train the model history = model.fit(X_train, y_train, epochs=10, validation_split=0.2, verbose=0) # Evaluate the model loss, accuracy = model.evaluate(X_test, y_test, verbose=0) print(f"Test accuracy: {accuracy:.4f}") """ result = sandbox.run_code(code) print(result) finally: # Always close the sandbox to clean up resources sandbox.close() ``` -------------------------------- ### Docker Compose Configuration for AICodeSandbox Service Source: https://github.com/typper-io/ai-code-sandbox/blob/main/README.md A docker-compose.yml file to set up and run the AICodeSandbox service. It defines the build context, mounts the Docker socket for DinD, sets privileged mode, and configures necessary environment variables. ```yaml version: '3.8' services: ai_sandbox: build: . volumes: - /var/run/docker.sock:/var/run/docker.sock privileged: true environment: - DOCKER_TLS_CERTDIR="" ``` -------------------------------- ### Write Files to Sandbox Source: https://context7.com/typper-io/ai-code-sandbox/llms.txt The `write_file` method creates or overwrites files in the sandbox. It supports string and bytes content and automatically creates parent directories. This is useful for setting up configurations, scripts, or data files within the isolated environment. ```python from ai_code_sandbox import AICodeSandbox sandbox = AICodeSandbox() try: # Write a simple text file sandbox.write_file("/app/config.txt", "debug=true\nlog_level=INFO") # Write a Python script file sandbox.write_file("/app/scripts/process.py", """ import sys def process_data(data): return [x * 2 for x in data] if __name__ == "__main__": result = process_data([1, 2, 3, 4, 5]) print(f"Processed: {result}") """) # Write a JSON configuration file (nested directory created automatically) sandbox.write_file("/app/data/config.json", """{ "name": "sandbox-app", "version": "1.0.0", "settings": { "timeout": 30, "retries": 3 } }""") # Write binary content binary_data = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR" sandbox.write_file("/app/assets/image.bin", binary_data) # Execute the written script result = sandbox.run_code(""" exec(open('/app/scripts/process.py').read()) """) print(result) # Output: Processed: [2, 4, 6, 8, 10] finally: sandbox.close() ``` -------------------------------- ### Read Files from Sandbox Source: https://context7.com/typper-io/ai-code-sandbox/llms.txt The `read_file` method retrieves file contents from the sandbox as a UTF-8 decoded string. It handles text and binary files and raises an error if the file is not found or inaccessible. This is essential for extracting results or data generated within the sandbox. ```python from ai_code_sandbox import AICodeSandbox sandbox = AICodeSandbox() try: # Write files first sandbox.write_file("/app/data.txt", "Line 1\nLine 2\nLine 3") sandbox.write_file("/app/results.csv", "name,value\nalpha,100\nbeta,200") # Read file contents data_content = sandbox.read_file("/app/data.txt") print("Data file contents:") print(data_content) # Output: # Line 1 # Line 2 # Line 3 # Read CSV file csv_content = sandbox.read_file("/app/results.csv") print("\nCSV contents:") print(csv_content) # Output: # name,value # alpha,100 # beta,200 # Run code that creates output, then read it sandbox.run_code(""" with open('/app/output.txt', 'w') as f: for i in range(5): f.write(f"Result {i}: {i * 10}\n") """) output = sandbox.read_file("/app/output.txt") print("\nGenerated output:") print(output) # Output: # Result 0: 0 # Result 1: 10 # Result 2: 20 # Result 3: 30 # Result 4: 40 # Handle file not found try: sandbox.read_file("/nonexistent/file.txt") except Exception as e: print(f"\nError reading file: {e}") # Output: Error reading file: Failed to read file: cat: /nonexistent/file.txt: No such file or directory finally: sandbox.close() ``` -------------------------------- ### Execute Python Code with run_code Method in Python Source: https://context7.com/typper-io/ai-code-sandbox/llms.txt Executes Python code within the isolated sandbox container and returns the output. This method supports passing environment variables to the execution context. It handles both successful output and error messages, returning an exit code. ```python from ai_code_sandbox import AICodeSandbox sandbox = AICodeSandbox(packages=["numpy"]) try: # Simple code execution result = sandbox.run_code(""" print("Hello from the sandbox!") x = 5 + 3 print(f"Result: {x}") """) print(result) # Output: # Hello from the sandbox! # Result: 8 # Code execution with environment variables result_with_env = sandbox.run_code( code=""" import os api_key = os.environ.get('API_KEY') debug = os.environ.get('DEBUG_MODE') print(f"API Key: {api_key}") print(f"Debug Mode: {debug}") """, env_vars={ "API_KEY": "sk-sandbox-12345", "DEBUG_MODE": "true" } ) print(result_with_env) # Output: # API Key: sk-sandbox-12345 # Debug Mode: true # Execute numpy code numpy_result = sandbox.run_code(""" import numpy as np arr = np.array([1, 2, 3, 4, 5]) print(f"Array: {arr}") print(f"Mean: {arr.mean()}") print(f"Sum: {arr.sum()}") """) print(numpy_result) # Output: # Array: [1 2 3 4 5] # Mean: 3.0 # Sum: 15 # Error handling - code with errors returns error message error_result = sandbox.run_code(""" x = 1 / 0 # Division by zero """) print(error_result) # Output: Error (exit code 1): ZeroDivisionError: division by zero finally: sandbox.close() ``` -------------------------------- ### Close Sandbox Resources Source: https://context7.com/typper-io/ai-code-sandbox/llms.txt The `close` method is crucial for releasing all Docker resources associated with the sandbox, including stopping and removing the container and any temporary images. It must be called to prevent resource leaks, typically using a `try...finally` block or a context manager. ```python from ai_code_sandbox import AICodeSandbox # Using try/finally pattern for guaranteed cleanup sandbox = AICodeSandbox(packages=["requests"]) try: result = sandbox.run_code(""" print("Executing in sandbox...") """) print(result) finally: sandbox.close() # Always called, even if code raises exception # Using context manager pattern (manual implementation) class SandboxContext: def __init__(self, **kwargs): self.sandbox = AICodeSandbox(**kwargs) def __enter__(self): return self.sandbox def __exit__(self, exc_type, exc_val, exc_tb): self.sandbox.close() return False # Usage with context manager wrapper with SandboxContext(packages=["numpy"]) as sandbox: result = sandbox.run_code(""" import numpy as np print(np.array([1, 2, 3]).sum()) """) print(result) # Output: 6 # Sandbox automatically closed after exiting the with block ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.