### Install Hopx Python SDK Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Installs the Hopx Python SDK using pip. This is the first step to using Hopx for code execution and sandbox management. ```bash pip install hopx-ai ``` -------------------------------- ### Multi-Step Workflow Execution in Hopx Sandbox (Node.js Example) Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Demonstrates executing a multi-step workflow, such as cloning a repository, installing dependencies, running tests, building, and retrieving artifacts, using Hopx sandboxes with a Node.js template. ```python from hopx_ai import Sandbox sandbox = Sandbox.create(template="nodejs", timeout_seconds=600) # Step 1: Clone repo and install dependencies sandbox.commands.run("git clone https://github.com/user/project.git /app") sandbox.commands.run("cd /app && npm install") # Step 2: Run tests result = sandbox.commands.run("cd /app && npm test") print(f"Tests: {'✅ PASSED' if result.exit_code == 0 else '❌ FAILED'}") # Step 3: Build sandbox.commands.run("cd /app && npm run build") # Step 4: Get build artifacts files = sandbox.files.list("/app/dist/") for file in files: print(f"Built: {file.name} ({file.size} bytes)") sandbox.kill() ``` -------------------------------- ### Build Custom Python Template Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Provides a comprehensive example of building a custom Docker image template using Python. It includes copying source files, installing dependencies, setting environment variables, and defining the start command with port waiting. ```python from hopx_ai import Template, wait_for_port from hopx_ai.template import BuildOptions # Define template template = ( Template() .from_python_image("3.11") .copy("requirements.txt", "/app/requirements.txt") .copy("src/", "/app/src/") .run("cd /app && pip install -r requirements.txt") .set_workdir("/app") .set_env("PORT", "8000") .set_start_cmd("python src/main.py", wait_for_port(8000)) ) # Build template result = await Template.build( template, BuildOptions( alias="my-python-app", api_key="your-api-key", on_log=lambda log: print(f"[{log['level']}] {log['message']}") ) ) print(f"Template ID: {result.template_id}") # Create sandbox from template sandbox = Sandbox.create(template_id=result.template_id) ``` -------------------------------- ### Desktop Automation with VNC (Python) Source: https://context7.com/hopx-ai/hopx/llms.txt Provides Python examples for controlling desktop applications via VNC. It covers starting VNC, mouse and keyboard operations, clipboard manipulation, taking screenshots, performing OCR, managing windows, and screen recording. ```python from hopx_ai import Sandbox sandbox = Sandbox.create(template='desktop-ubuntu') vnc_info = sandbox.desktop.start_vnc() print(f"VNC URL: {vnc_info.url}") print(f"VNC Port: {vnc_info.port}") print(f"Password: {vnc_info.password}") sandbox.desktop.mouse_click(x=100, y=200, button='left', clicks=1) sandbox.desktop.mouse_move(x=300, y=400) sandbox.desktop.mouse_drag(from_x=100, from_y=200, to_x=300, to_y=400) sandbox.desktop.mouse_scroll(x=150, y=150, delta_y=-5) sandbox.desktop.keyboard_type('hello world') sandbox.desktop.keyboard_press('Enter') sandbox.desktop.keyboard_combination(['Control', 'c']) sandbox.desktop.set_clipboard('copied text') clipboard_content = sandbox.desktop.get_clipboard() clipboard_history = sandbox.desktop.get_clipboard_history() screenshot = sandbox.desktop.screenshot() with open('screenshot.png', 'wb') as f: f.write(screenshot.data) region_screenshot = sandbox.desktop.screenshot_region(x=0, y=0, width=800, height=600) with open('region.png', 'wb') as f: f.write(region_screenshot) text = sandbox.desktop.ocr(x=0, y=0, width=1920, height=1080) element = sandbox.desktop.find_element('Submit Button') if element: sandbox.desktop.mouse_click(element.x, element.y) element = sandbox.desktop.wait_for('Loading Complete', timeout=30000) windows = sandbox.desktop.list_windows() if windows: window_id = windows[0].id sandbox.desktop.focus_window(window_id) sandbox.desktop.resize_window(window_id, width=1280, height=720) sandbox.desktop.minimize_window(window_id) sandbox.desktop.close_window(window_id) display_info = sandbox.desktop.get_display_info() sandbox.desktop.set_resolution(1920, 1080) available_resolutions = sandbox.desktop.get_available_resolutions() sandbox.desktop.start_recording(output_file='/workspace/recording.mp4') sandbox.desktop.stop_recording() recording_status = sandbox.desktop.get_recording_status() ``` -------------------------------- ### Set Up JavaScript SDK Development Environment Source: https://github.com/hopx-ai/hopx/blob/main/CONTRIBUTING.md Steps to set up the JavaScript SDK for development. This involves navigating to the JavaScript directory and installing project dependencies using npm. ```bash cd javascript npm install ``` -------------------------------- ### Desktop Automation (Premium) Source: https://github.com/hopx-ai/hopx/blob/main/javascript/README.md Premium feature examples including VNC connection, screenshot capture, mouse control, and keyboard input simulation. ```typescript // Get VNC info const vnc = await sandbox.desktop.getVNCInfo(); console.log(`Connect to: ${vnc.url}`); // Take screenshot const screenshot = await sandbox.desktop.screenshot(); // Returns Buffer // Control mouse await sandbox.desktop.mouseClick(100, 200); // Type text await sandbox.desktop.keyboardType('Hello, World!'); ``` -------------------------------- ### Set Up Python SDK Development Environment Source: https://github.com/hopx-ai/hopx/blob/main/CONTRIBUTING.md Steps to set up the Python SDK for development. This involves navigating to the Python directory and installing the package in editable mode with development dependencies. ```bash cd python pip install -e ".[dev]" ``` -------------------------------- ### Build Application Templates using Hopx SDK in TypeScript Source: https://context7.com/hopx-ai/hopx/llms.txt This code demonstrates building Node.js and Python ML application templates using the Hopx SDK, including setting up environments, installing dependencies, and starting commands. It covers pulling from various registries such as GCP, AWS ECR, and private ones, then building and creating VMs. Dependencies include the Hopx SDK library; inputs are configuration objects like API keys and env vars; outputs are build results and VM instances. Limitations include the need for valid credentials and network access to registries. ```typescript import { Template, waitForPort, waitForUrl, waitForFile } from '@hopx-ai/sdk'; // Build Node.js application template const template = new Template() .fromNodeImage('18') .copy('package.json', '/app/') .copy('src/', '/app/src/') .setWorkdir('/app') .npmInstall('express', 'axios', 'dotenv') .setEnv('NODE_ENV', 'production') .setEnv('PORT', '8080') .setStartCmd('npm start', waitForPort(8080)); // Build the template const buildResult = await Template.build(template, { alias: 'my-nodejs-app', apiKey: process.env.HOPX_API_KEY!, cpu: 2, memory: 2048, diskGB: 10, skipCache: false, contextPath: '.', onLog: (log) => console.log(`[${log.level}] ${log.message}`), onProgress: (progress) => console.log(`Progress: ${progress}%`) }); console.log(`Template ID: ${buildResult.templateID}`); console.log(`Build ID: ${buildResult.buildID}`); console.log(`Duration: ${buildResult.duration}s`); // Create VM from template const vm = await buildResult.createVM({ alias: 'instance-1', envVars: { DATABASE_URL: 'postgresql://localhost/mydb' } }); console.log(`VM created: ${vm.sandboxId}`); await vm.kill(); // Python ML template const mlTemplate = new Template() .fromPythonImage('3.11') .copy('requirements.txt', '/app/') .copy('models/', '/app/models/') .setWorkdir('/app') .pipInstall('torch', 'transformers', 'scikit-learn') .aptInstall('libgomp1') .setEnv('TRANSFORMERS_CACHE', '/workspace/cache') .setStartCmd('python train.py', waitForUrl('http://localhost:8080/health')); // Private registry templates const privateTemplate = new Template() .fromImage('ghcr.io/mycompany/api-server:v2.1.0', { username: 'github-user', password: 'ghp_token' }) .setEnv('LOG_LEVEL', 'info') .setStartCmd('./server'); // AWS ECR template const awsTemplate = new Template() .fromAWSRegistry('123456789.dkr.ecr.us-west-1.amazonaws.com/webapp:v3.0', { accessKeyId: process.env.AWS_ACCESS_KEY_ID!, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!, region: 'us-west-1' }) .setStartCmd('./webapp', waitForPort(8080)); // GCP template const gcpTemplate = new Template() .fromGCPRegistry('gcr.io/my-project/ml-model:v1', { serviceAccountJSON: './gcp-service-account.json' }) .setStartCmd('python serve.py'); ``` -------------------------------- ### Install Hopx SDK (Bash) Source: https://github.com/hopx-ai/hopx/blob/main/javascript/README.md This command installs the Hopx JavaScript/TypeScript SDK package using npm. It's a prerequisite for using the SDK in your Node.js or browser projects. ```bash npm install @hopx-ai/sdk ``` -------------------------------- ### Desktop Automation - VNC, Screenshot, Mouse, Keyboard Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Provides examples for desktop automation features, including retrieving VNC connection details, taking a screenshot, controlling the mouse cursor, and typing text using the keyboard. ```python # Get VNC info vnc = sandbox.desktop.get_vnc_info() print(f"Connect to: {vnc.url}") # Take screenshot screenshot = sandbox.desktop.screenshot() # Returns PNG bytes # Control mouse sandbox.desktop.mouse_click(100, 200) # Type text sandbox.desktop.keyboard_type("Hello, World!") ``` -------------------------------- ### Basic Hopx Sandbox Usage (TypeScript) Source: https://github.com/hopx-ai/hopx/blob/main/javascript/README.md A fundamental example of creating a Node.js sandbox, executing a simple console log command, and then cleaning up the sandbox. It shows how to specify the template and optionally provide an API key. ```typescript import { Sandbox } from '@hopx-ai/sdk'; // Create sandbox (~100ms) const sandbox = await Sandbox.create({ template: 'nodejs', // or 'python', 'go', 'rust', etc. apiKey: 'your-api-key' // or set HOPX_API_KEY env var }); // Execute code const result = await sandbox.runCode(` console.log('Node.js', process.version); console.log('Hello from Hopx!'); `); console.log(result.stdout); // Output: // Node.js v20.x.x // Hello from Hopx! // Cleanup await sandbox.kill(); ``` -------------------------------- ### Environment Variable Management Source: https://github.com/hopx-ai/hopx/blob/main/javascript/README.md Provides examples for setting, getting, and deleting environment variables in the sandbox, both individually and in bulk operations. ```typescript // Set single variable await sandbox.env.set('DATABASE_URL', 'postgresql://...'); // Set multiple await sandbox.env.setMany({ API_KEY: 'key123', DEBUG: 'true' }); // Get variable const value = await sandbox.env.get('API_KEY'); // Delete variable await sandbox.env.delete('DEBUG'); ``` -------------------------------- ### File Processing with Hopx Sandbox (Python Example) Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Illustrates uploading a file (e.g., CSV) to a Hopx sandbox, processing it with Python (using Pandas), saving the results, and downloading the processed file. ```python sandbox = Sandbox.create(template="python") # Upload data sandbox.files.write("/tmp/data.csv", csv_content) # Process it result = sandbox.run_code(""" import pandas as pd df = pd.read_csv('/tmp/data.csv') result = df.groupby('category').sum() result.to_csv('/tmp/output.csv') print(f"Processed {len(df)} rows") """) # Download result output = sandbox.files.read("/tmp/output.csv") print(output) sandbox.kill() ``` -------------------------------- ### Create and Manage Sandboxes (Python) Source: https://context7.com/hopx-ai/hopx/llms.txt Demonstrates how to create, manage, and interact with sandboxes using the Hopx Python SDK. Includes examples of creating, pausing, resuming, stopping, and deleting sandboxes, as well as listing existing sandboxes and connecting to them. ```python from hopx_ai import Sandbox import os # Create a new sandbox sandbox = Sandbox.create( template='code-interpreter', api_key=os.environ['HOPX_API_KEY'], timeout_seconds=300, internet_access=True, env_vars={'API_KEY': 'sk-test-123', 'DEBUG': 'true'} ) # Get sandbox information info = sandbox.get_info() print(f"Sandbox ID: {info.sandbox_id}") print(f"Status: {info.status}") print(f"Region: {info.region}") # Lifecycle management sandbox.pause() # Pause execution sandbox.resume() # Resume from pause sandbox.stop() # Stop sandbox (can restart) sandbox.start() # Restart stopped sandbox sandbox.kill() # Permanently delete sandbox # List all sandboxes sandboxes = Sandbox.list( api_key=os.environ['HOPX_API_KEY'], status='running', limit=10 ) for sb in sandboxes: print(f"{sb.sandbox_id}: {sb.status}") # Connect to existing sandbox existing = Sandbox.connect('sandbox-abc-123', api_key=os.environ['HOPX_API_KEY']) ``` -------------------------------- ### Python Unit Test Example Source: https://github.com/hopx-ai/hopx/blob/main/CONTRIBUTING.md A simple unit test for the Python SDK, demonstrating how to test sandbox creation and assert basic functionality. Follows standard Python testing practices. ```python def test_sandbox_creation(): """Test basic sandbox creation.""" sandbox = Sandbox.create(template="python") assert sandbox.sandbox_id is not None sandbox.kill() ``` -------------------------------- ### Custom Template Building Source: https://github.com/hopx-ai/hopx/blob/main/javascript/README.md Demonstrates creating custom sandbox templates with Node.js base image, file copying, dependency installation, and environment configuration. ```typescript import { Template, waitForPort } from '@hopx-ai/sdk'; // Define template const template = new Template() .fromNodeImage('20-alpine') .copy('package.json', '/app/package.json') .copy('src/', '/app/src/') .run('cd /app && npm install') .setWorkdir('/app') .setEnv('PORT', '3000') .setStartCmd('node src/index.js', waitForPort(3000)); // Build template const result = await Template.build(template, { alias: 'my-node-app', apiKey: 'your-api-key', onLog: (log) => console.log(`[${log.level}] ${log.message}`) }); console.log(`Template ID: ${result.templateID}`); // Create sandbox from template const sandbox = await Sandbox.create({ templateId: result.templateID }); ``` -------------------------------- ### Example Feature Request Structure Source: https://github.com/hopx-ai/hopx/blob/main/CONTRIBUTING.md A template for requesting new features, including use case, proposed solution, example API design, and alternatives considered. This facilitates clear communication and planning for new functionalities. ```markdown **Feature**: Support for custom Docker images **Use Case**: I want to use my own base images with pre-installed dependencies **Proposed API**: ```python template = Template.from_docker("my-registry.com/my-image:latest") ``` **Alternatives**: Use Template.run() to install dependencies each time (slower) **Additional Context**: Similar to E2B's custom templates ``` -------------------------------- ### Create and Manage Sandboxes (TypeScript) Source: https://context7.com/hopx-ai/hopx/llms.txt Demonstrates how to create, manage, and interact with sandboxes using the Hopx TypeScript/JavaScript SDK. Includes examples of creating, pausing, resuming, stopping, and deleting sandboxes, as well as listing existing sandboxes. ```typescript import { Sandbox } from '@hopx-ai/sdk'; // Create sandbox const sandbox = await Sandbox.create({ template: 'code-interpreter', apiKey: process.env.HOPX_API_KEY, timeoutSeconds: 300, internetAccess: true, envVars: { API_KEY: 'sk-test-123', DEBUG: 'true' } }); // Get information const info = await sandbox.getInfo(); console.log(`Sandbox ID: ${info.sandboxId}`); console.log(`Status: ${info.status}`); // Lifecycle operations await sandbox.pause(); await sandbox.resume(); await sandbox.stop(); await sandbox.start(); await sandbox.kill(); // List sandboxes const sandboxes = await Sandbox.list({ apiKey: process.env.HOPX_API_KEY, status: 'running', limit: 10 }); ``` -------------------------------- ### Execute Multi-Step Workflow in Sandbox (TypeScript) Source: https://github.com/hopx-ai/hopx/blob/main/javascript/README.md This snippet illustrates a multi-step workflow within a Hopx sandbox, including cloning a Git repository, installing dependencies, running tests, building the project, and listing build artifacts. It utilizes the `commands.run` and `files.list` methods of the Sandbox object. ```typescript import { Sandbox } from '@hopx-ai/sdk'; const sandbox = await Sandbox.create({ template: 'nodejs', timeoutSeconds: 600 }); // Step 1: Clone repo and install dependencies await sandbox.commands.run('git clone https://github.com/user/project.git /app'); await sandbox.commands.run('cd /app && npm install'); // Step 2: Run tests const testResult = await sandbox.commands.run('cd /app && npm test'); console.log(`Tests: ${testResult.exitCode === 0 ? '✅ PASSED' : '❌ FAILED'}`); // Step 3: Build await sandbox.commands.run('cd /app && npm run build'); // Step 4: Get build artifacts const files = await sandbox.files.list('/app/dist/'); files.forEach(file => { console.log(`Built: ${file.name} (${file.size} bytes)`); }); await sandbox.kill(); ``` -------------------------------- ### Environment Variable Management (Python) Source: https://context7.com/hopx-ai/hopx/llms.txt Dynamically manage environment variables within the sandbox without needing to restart the process. This includes setting and getting individual variables. The example is provided in Python. ```python sandbox.env.set('DATABASE_URL', 'postgresql://localhost/mydb') db_url = sandbox.env.get('DATABASE_URL') print(f"Database URL: {db_url}") ``` -------------------------------- ### Example Commit Message Formats Source: https://github.com/hopx-ai/hopx/blob/main/CONTRIBUTING.md A list of prefixes and their meanings for crafting conventional commit messages. This helps categorize commits and maintain a clear project history. ```markdown **Commit message format:** - `feat:` - New feature - `fix:` - Bug fix - `docs:` - Documentation changes - `test:` - Test changes - `refactor:` - Code refactoring - `perf:` - Performance improvements - `chore:` - Build/tooling changes ``` -------------------------------- ### Example Pull Request Titles Source: https://github.com/hopx-ai/hopx/blob/main/CONTRIBUTING.md Examples of pull request titles following a structured format, indicating the scope and type of change. This aids in quickly understanding the PR's purpose. ```markdown ``` feat(sandbox): add support for GPU sandboxes fix(files): handle large file uploads correctly docs(readme): improve quick start examples ``` ``` -------------------------------- ### Create sandbox and run simple code (Python, TypeScript) Source: https://github.com/hopx-ai/hopx/blob/main/README.md Demonstrates creating a Hopx sandbox, executing a one‑line script, printing the captured stdout, and terminating the sandbox. Works for both Python and TypeScript SDKs. Requires the respective SDK to be installed. ```python from hopx_ai import Sandbox\n\nsandbox = Sandbox.create(template=\"python\")\nresult = sandbox.run_code(\"print('Hello, Hopx!')\")\nprint(result.stdout) # \"Hello, Hopx!\"\nsandbox.kill() ``` ```typescript import { Sandbox } from '@hopx-ai/sdk';\n\nconst sandbox = await Sandbox.create({ template: 'nodejs' });\nconst result = await sandbox.runCode(\"console.log('Hello, Hopx!')\");\nconsole.log(result // \"Hello, Hopx!\"\nawait sandbox.kill(); ``` -------------------------------- ### Basic Hopx Sandbox Usage (JavaScript CommonJS) Source: https://github.com/hopx-ai/hopx/blob/main/javascript/README.md This example shows how to initialize and use the Hopx SDK in a JavaScript environment using CommonJS modules. It creates a Node.js sandbox, runs a simple command, prints the output, and then terminates the sandbox. ```javascript const { Sandbox } = require('@hopx-ai/sdk'); (async () => { const sandbox = await Sandbox.create({ template: 'nodejs' }); const result = await sandbox.runCode("console.log('Hello!')"); console.log(result.stdout); await sandbox.kill(); })(); ``` -------------------------------- ### Manage Environment Variables Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Illustrates how to set, get, and delete environment variables within the sandbox. Supports setting single or multiple variables at once. ```python # Set single variable sandbox.env.set("DATABASE_URL", "postgresql://...") # Set multiple sandbox.env.set_many({ "API_KEY": "key123", "DEBUG": "true" }) # Get variable value = sandbox.env.get("API_KEY") # Delete variable sandbox.env.delete("DEBUG") ``` -------------------------------- ### JavaScript Unit Test Example Source: https://github.com/hopx-ai/hopx/blob/main/CONTRIBUTING.md A basic unit test for the JavaScript SDK using a testing framework like Jest or Vitest. It demonstrates testing the creation and basic properties of a sandbox object. ```typescript describe('Sandbox', () => { it('should create a sandbox', async () => { const sandbox = await Sandbox.create({ template: 'nodejs' }); expect(sandbox.sandboxId).toBeDefined(); await sandbox.kill(); }); }); ``` -------------------------------- ### Sandbox Desktop Automation (TypeScript) Source: https://context7.com/hopx-ai/hopx/llms.txt This TypeScript code illustrates various desktop automation capabilities within a Hopx AI sandbox. It includes starting VNC, mouse and keyboard operations, clipboard management, taking screenshots, OCR, element finding, and window/display management. ```typescript import { Sandbox } from '@hopx-ai/sdk'; import * as fs from 'fs'; const sandbox = await Sandbox.create({ template: 'desktop-ubuntu' }); // Start VNC const vncInfo = await sandbox.desktop.startVnc(); console.log(`VNC URL: ${vncInfo.url}`); // Mouse operations await sandbox.desktop.mouseClick(100, 200, { button: 'left', clicks: 1 }); await sandbox.desktop.mouseMove(300, 400); await sandbox.desktop.mouseDrag(100, 200, 300, 400); await sandbox.desktop.mouseScroll(150, 150, -5); // Keyboard operations await sandbox.desktop.keyboardType('hello world'); await sandbox.desktop.keyboardPress('Enter'); await sandbox.desktop.keyboardCombination(['Control', 'c']); // Clipboard await sandbox.desktop.setClipboard('copied text'); const clipboard = await sandbox.desktop.getClipboard(); console.log(`Clipboard: ${clipboard}`); // Screenshot const screenshot = await sandbox.desktop.screenshot(); fs.writeFileSync('screenshot.png', screenshot.data); // OCR const text = await sandbox.desktop.ocr(0, 0, 1920, 1080); console.log(`Extracted: ${text}`); // Find and click element const element = await sandbox.desktop.findElement('Submit Button'); if (element) { await sandbox.desktop.mouseClick(element.x, element.y); } // Window management const windows = await sandbox.desktop.listWindows(); if (windows.length > 0) { await sandbox.desktop.focusWindow(windows[0].id); await sandbox.desktop.resizeWindow(windows[0].id, 1280, 720); } // Display management await sandbox.desktop.setResolution(1920, 1080); const displayInfo = await sandbox.desktop.getDisplayInfo(); console.log(`Resolution: ${displayInfo.width}x${displayInfo.height}`); await sandbox.desktop.stopVnc(); await sandbox.kill(); ``` -------------------------------- ### Execute Code with Rich Output Capture (Python) Source: https://context7.com/hopx-ai/hopx/llms.txt Demonstrates how to execute code within a Hopx sandbox and capture rich outputs, such as visualizations and structured data. This example uses Python with matplotlib and pandas. ```python from hopx_ai import Sandbox sandbox = Sandbox.create(template='code-interpreter') # Synchronous code execution result = sandbox.run_code( code=''' import matplotlib.pyplot as plt import pandas as pd import numpy as np # Create data x = np.linspace(0, 10, 100) y = np.sin(x) # Generate plot plt.figure(figsize=(10, 6)) plt.plot(x, y, 'b-', linewidth=2, label='sin(x)') plt.title('Sine Wave') plt.xlabel('X') plt.ylabel('sin(X)') plt.grid(True, alpha=0.3) plt.legend() plt.show() # Create DataFrame df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'Score': [95, 87, 92] }) display(df) print("Analysis complete!") ''', language='python', timeout=60, working_dir='/workspace', env={'JUPYTER_ENABLE': 'true'} ) # Access results print(f"Success: {result.success}") print(f"Exit code: {result.exit_code}") print(f"Execution time: {result.execution_time}s") print(f"Stdout: {result.stdout}") print(f"Stderr: {result.stderr}") ``` -------------------------------- ### Build Custom Sandbox Templates (Python) Source: https://context7.com/hopx-ai/hopx/llms.txt This Python code demonstrates how to build custom sandbox templates using the Hopx AI SDK. It covers creating Node.js, Python ML, private registry, and AWS ECR based templates, including dependency installation, environment variable configuration, and startup commands. ```python from hopx_ai import Template, wait_for_port, wait_for_url import os # Build Node.js application template template = ( Template() .from_node_image('18') .copy('package.json', '/app/') .copy('src/', '/app/src/') .set_workdir('/app') .npm_install('express', 'axios', 'dotenv') .set_env('NODE_ENV', 'production') .set_env('PORT', '8080') .set_start_cmd('npm start', ready_check=wait_for_port(8080)) ) # Build the template build_result = Template.build( template=template, alias='my-nodejs-app', api_key=os.environ['HOPX_API_KEY'], cpu=2, memory=2048, disk_gb=10, skip_cache=False, context_path='.', on_log=lambda log: print(f"[{log.level}] {log.message}"), on_progress=lambda progress: print(f"Progress: {progress}%") ) print(f"Template ID: {build_result.template_id}") print(f"Build ID: {build_result.build_id}") print(f"Duration: {build_result.duration}s") # Create VM from template vm = build_result.create_vm( alias='instance-1', env_vars={'DATABASE_URL': 'postgresql://localhost/mydb'} ) print(f"VM created: {vm.sandbox_id}") vm.kill() # Python ML template ml_template = ( Template() .from_python_image('3.11') .copy('requirements.txt', '/app/') .copy('models/', '/app/models/') .set_workdir('/app') .pip_install('torch', 'transformers', 'scikit-learn') .apt_install('libgomp1') .set_env('TRANSFORMERS_CACHE', '/workspace/cache') .set_start_cmd('python train.py', ready_check=wait_for_url('http://localhost:8080/health')) ) # Private registry template private_template = ( Template() .from_image( 'ghcr.io/mycompany/api-server:v2.1.0', auth={'username': 'github-user', 'password': 'ghp_token'} ) .set_env('LOG_LEVEL', 'info') .set_start_cmd('./server') ) # AWS ECR template aws_template = ( Template() .from_aws_registry( '123456789.dkr.ecr.us-west-1.amazonaws.com/webapp:v3.0', auth={ 'access_key_id': os.environ['AWS_ACCESS_KEY_ID'], 'secret_access_key': os.environ['AWS_SECRET_ACCESS_KEY'], 'region': 'us-west-1' } ) .set_start_cmd('./webapp', ready_check=wait_for_port(8080)) ) ``` -------------------------------- ### Check Sandbox Health and Get Metrics Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Shows how to check the operational status of the sandbox environment and retrieve performance metrics such as CPU usage, memory consumption, and disk space. ```python # Check health health = sandbox.get_health() print(health.status) # "healthy" # Get metrics metrics = sandbox.get_metrics() print(f"CPU: {metrics.cpu_percent}%") print(f"Memory: {metrics.memory_mb}MB") print(f"Disk: {metrics.disk_mb}MB") ``` -------------------------------- ### Process Files with Python Sandbox (TypeScript) Source: https://github.com/hopx-ai/hopx/blob/main/javascript/README.md This example demonstrates file processing using a Python sandbox. It involves uploading a CSV file (`csvContent`) to the sandbox, running a Python script to process it with pandas, and then downloading the resulting CSV file. ```typescript const sandbox = await Sandbox.create({ template: 'python' }); // Upload data await sandbox.files.write('/tmp/data.csv', csvContent); // Process it const result = await sandbox.runCode(` import pandas as pd df = pd.read_csv('/tmp/data.csv') result = df.groupby('category').sum() result.to_csv('/tmp/output.csv') print(f"Processed {len(df)} rows") `); // Download result const output = await sandbox.files.read('/tmp/output.csv'); console.log(output); await sandbox.kill(); ``` -------------------------------- ### Run multi‑step workflow with commands (TypeScript) Source: https://github.com/hopx-ai/hopx/blob/main/README.md Uses the TypeScript SDK to execute a series of shell commands inside the sandbox, such as cloning a repo, installing dependencies, and running tests. Shows how to check the exit code and report success. Suitable for CI‑like pipelines. ```typescript const sandbox = await Sandbox.create({ template: 'nodejs' });\n\nawait sandbox.commands.run('git clone https://github.com/user/repo /app');\nawait sandbox.commands.run('cd /app && npm install');\nconst result = await sandbox.commands.run('cd /app && npm test');\n\nconsole.log(result.exitCode === 0 ? '✅ PASSED' : '❌ FAILED'); ``` -------------------------------- ### Commit Changes with Conventional Commits Source: https://github.com/hopx-ai/hopx/blob/main/CONTRIBUTING.md Example of staging all changes and committing them using the conventional commit format. This format helps in automating changelog generation and understanding commit history. ```bash git add . git commit -m "feat: add support for custom templates" ``` -------------------------------- ### Manage Sandbox Environment Variables (Python) Source: https://context7.com/hopx-ai/hopx/llms.txt Demonstrates how to get, set, update, and delete environment variables within a Hopx AI sandbox. It also shows how to execute code that utilizes these environment variables. ```python all_vars = sandbox.env.get_all() for key, value in all_vars.items(): print(f"{key}={value}") sandbox.env.set_all({ 'API_KEY': 'sk-abc123', 'API_URL': 'https://api.example.com', 'DEBUG': 'true' }) sandbox.env.update({ 'NEW_VAR': 'new_value', 'ANOTHER_VAR': 'another_value' }) sandbox.env.delete('OLD_VAR') result = sandbox.run_code(''' import os print(f"API Key: {os.environ['API_KEY']}") print(f"Debug: {os.environ['DEBUG']}") ''') print(result.stdout) sandbox.kill() ``` -------------------------------- ### Example Bug Report Structure Source: https://github.com/hopx-ai/hopx/blob/main/CONTRIBUTING.md A template for reporting bugs, including essential details like SDK version, environment information, code to reproduce the issue, and expected vs. actual behavior. This helps developers diagnose and fix bugs efficiently. ```markdown **Description** File upload fails for files > 10MB **Environment** - SDK: Python 0.1.19 - OS: Ubuntu 22.04 - Python: 3.11 **Code to Reproduce** ```python sandbox = Sandbox.create(template="python") sandbox.files.write("/tmp/large.bin", "x" * 15_000_000) ``` **Expected**: File uploaded successfully **Actual**: Timeout error after 30s **Error Message** ``` TimeoutError: Request timed out after 30s ``` ``` -------------------------------- ### Manage Sandbox Environment Variables (TypeScript) Source: https://context7.com/hopx-ai/hopx/llms.txt Illustrates environment variable management in a Hopx AI sandbox using TypeScript, including getting, setting, updating, and deleting variables, as well as executing code that accesses them. ```typescript const sandbox = await Sandbox.create({ template: 'code-interpreter', envVars: { INITIAL_VAR: 'initial_value' } }); await sandbox.env.set('DATABASE_URL', 'postgresql://localhost/mydb'); const dbUrl = await sandbox.env.get('DATABASE_URL'); console.log(`Database URL: ${dbUrl}`); const allVars = await sandbox.env.getAll(); for (const [key, value] of Object.entries(allVars)) { console.log(`${key}=${value}`); } await sandbox.env.setAll({ API_KEY: 'sk-abc123', API_URL: 'https://api.example.com', DEBUG: 'true' }); await sandbox.env.update({ NEW_VAR: 'new_value', ANOTHER_VAR: 'another_value' }); await sandbox.env.delete('OLD_VAR'); const result = await sandbox.runCode(` import os print(f"API Key: {os.environ['API_KEY']}") print(f"Debug: {os.environ['DEBUG']}") `); await sandbox.kill(); ``` -------------------------------- ### File System Operations (Python & TypeScript) Source: https://context7.com/hopx-ai/hopx/llms.txt Perform various file system operations within the sandbox, including listing directory contents, creating directories, checking file existence, deleting files/directories, downloading, and uploading files. These examples show implementations in both Python and TypeScript. ```python files = sandbox.files.list('/workspace') for file_info in files: file_type = '📁' if file_info.is_dir else '📄' print(f"{file_type} {file_info.name}") print(f" Path: {file_info.path}") print(f" Size: {file_info.size_kb:.2f} KB") print(f" Modified: {file_info.modified_time}") print(f" Permissions: {file_info.permissions}") print(f" Extension: {file_info.extension}") sandbox.files.mkdir('/workspace/data') exists = sandbox.files.exists('/workspace/data.txt') print(f"File exists: {exists}") sandbox.files.remove('/workspace/data.txt') file_data = sandbox.files.download('/workspace/image.png') with open('downloaded_image.png', 'wb') as f: f.write(file_data) # Upload file (coming soon) # sandbox.files.upload('local_file.txt', '/workspace/remote_file.txt') ``` ```typescript const files = await sandbox.files.list('/workspace'); for (const file of files) { const icon = file.isDir ? '📁' : '📄'; console.log(`${icon} ${file.name}`); console.log(` Size: ${file.sizeKb} KB`); console.log(` Modified: ${file.modifiedTime}`); } await sandbox.files.write('/workspace/data.txt', 'Hello, Hopx!', { overwrite: true }); const content = await sandbox.files.read('/workspace/data.txt'); console.log(`Content: ${content}`); const binaryData = fs.readFileSync('local_image.png'); await sandbox.files.writeBytes('/workspace/image.png', binaryData); const binaryContent = await sandbox.files.readBytes('/workspace/image.png'); console.log(`Binary size: ${binaryContent.length} bytes`); await sandbox.files.mkdir('/workspace/data'); const exists = await sandbox.files.exists('/workspace/data.txt'); await sandbox.files.remove('/workspace/data.txt'); const fileData = await sandbox.files.download('/workspace/image.png'); fs.writeFileSync('downloaded_image.png', fileData); ``` -------------------------------- ### Basic Python Code Execution with Hopx Sandbox Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Demonstrates the basic usage of the Hopx Python SDK to create a sandbox, execute Python code, and print the output. It includes creating a sandbox, running code, and then cleaning up the sandbox. ```python from hopx_ai import Sandbox # Create sandbox (~100ms) sandbox = Sandbox.create( template="python", # or "nodejs", "go", "rust", etc. api_key="your-api-key" # or set HOPX_API_KEY env var ) # Execute code result = sandbox.run_code(""" import sys print(f"Python {sys.version}") print("Hello from Hopx!") """) print(result.stdout) # Output: # Python 3.11.x # Hello from Hopx! # Cleanup sandbox.kill() ``` -------------------------------- ### Authenticate Sandbox Creation Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Shows how to create a sandbox instance, optionally specifying the template and passing the API key directly in the constructor. ```python sandbox = Sandbox.create( template="python", api_key="your-api-key" ) ``` -------------------------------- ### List and Kill Processes Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Demonstrates how to list all running processes within the sandbox, displaying their PID, name, and CPU usage. Also shows how to terminate a specific process by its PID. ```python # List processes processes = sandbox.processes.list() for proc in processes: print(f"{proc.pid}: {proc.name} (CPU: {proc.cpu_percent}%)") # Kill process sandbox.processes.kill(1234) ``` -------------------------------- ### Initialize Sandbox in TypeScript Source: https://github.com/hopx-ai/hopx/blob/main/javascript/README.md Creates a new sandbox instance with Python template, executes code, retrieves sandbox info, and terminates the sandbox. Demonstrates basic sandbox lifecycle management. ```typescript import { Sandbox, ExecutionResult, SandboxInfo } from '@hopx-ai/sdk'; const sandbox = await Sandbox.create({ template: 'python' }); const result: ExecutionResult = await sandbox.runCode("print('Hello!')"); const info: SandboxInfo = await sandbox.getInfo(); console.log(`Status: ${info.status}`); console.log(`Output: ${result.stdout}`); await sandbox.kill(); ``` -------------------------------- ### File Operations (Write and Read) with Hopx Sandbox Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Demonstrates basic file management operations within a Hopx sandbox, specifically writing content to a file and then reading it back. ```python # Write files sandbox.files.write("/app/config.json", '{"key": "value"}') # Read files content = sandbox.files.read("/app/config.json") ``` -------------------------------- ### List and Delete Files in Sandbox Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Demonstrates how to list files in a directory and delete specific files within the sandbox environment. Assumes the 'sandbox' object is pre-initialized. ```python files = sandbox.files.list("/app/") for file in files: print(f"{file.name}: {file.size} bytes") sandbox.files.delete("/app/temp.txt") ``` -------------------------------- ### Run Commands Synchronously and Asynchronously Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Shows how to execute shell commands within the sandbox. Supports synchronous execution with result capturing and asynchronous execution for background tasks, with methods to retrieve results later. ```python # Run command synchronously result = sandbox.commands.run("ls -la /app") print(result.stdout) # Run in background cmd_id = sandbox.commands.run_async("python long_task.py") # ... do other work ... result = sandbox.commands.get_result(cmd_id) ``` -------------------------------- ### Set API Key for Authentication Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Demonstrates two ways to authenticate with the Hopx AI API: setting the HOPX_API_KEY environment variable in the shell, or passing the API key directly when creating a sandbox instance. ```bash export HOPX_API_KEY="your-api-key" ``` -------------------------------- ### Stream Code Execution Output using Hopx Sandbox in Python Source: https://context7.com/hopx-ai/hopx/llms.txt This code shows how to create a sandbox for code interpretation and stream execution outputs in real-time, including handling stdout, stderr, and rich outputs. It also covers file watching and interactive terminal connections for sending commands and receiving responses. Dependencies include the hopx_ai library; inputs are code strings and file paths; outputs are streamed messages and change events. Limitations include reliance on active WebSocket connections and sandbox availability. ```python from hopx_ai import Sandbox sandbox = Sandbox.create(template='code-interpreter') # Stream code execution for message in sandbox.run_code_stream( code=''' import time for i in range(5): print(f"Step {i+1}") time.sleep(1) print("Complete!") ''', language='python' ): if message.type == 'stdout': print(f"Output: {message.data}") elif message.type == 'stderr': print(f"Error: {message.data}") elif message.type == 'rich_output': print(f"Rich output: {message.data.type}") elif message.type == 'complete': print("Execution finished") print(f"Exit code: {message.exit_code}") # File watching for change in sandbox.watch_files('/workspace'): print(f"File change: {change.event_type}") print(f"Path: {change.path}") print(f"Timestamp: {change.timestamp}") # Interactive terminal terminal = sandbox.terminal.connect() # Send commands sandbox.terminal.send_input(terminal, 'ls -la\n') sandbox.terminal.send_input(terminal, 'cd /workspace\n') sandbox.terminal.send_input(terminal, 'python script.py\n') # Receive output for message in sandbox.terminal.output(terminal): if message.type == 'output': print(message.data, end='') elif message.type == 'exit': print(f"Terminal exited with code: {message.exit_code}") break ``` -------------------------------- ### Clone Hopx Repository Source: https://github.com/hopx-ai/hopx/blob/main/CONTRIBUTING.md Instructions to fork and clone the Hopx repository using Git. Assumes prior forking on GitHub. This is the initial step for any code contribution. ```bash # Fork the repository on GitHub, then: git clone https://github.com/YOUR_USERNAME/hopx.git cd hopx ``` -------------------------------- ### Generate and Capture Data Visualizations (TypeScript) Source: https://github.com/hopx-ai/hopx/blob/main/javascript/README.md This example shows how to generate data visualizations, specifically a PNG chart using the 'canvas' library within a Node.js sandbox. It captures the chart data as a Base64 encoded string from rich outputs. ```typescript // Generate charts and capture them automatically const code = ` const { createCanvas } = require('canvas'); const canvas = createCanvas(400, 300); const ctx = canvas.getContext('2d'); // Draw chart ctx.fillStyle = '#4CAF50'; ctx.fillRect(50, 100, 80, 150); ctx.fillRect(150, 50, 80, 200); ctx.fillRect(250, 80, 80, 170); console.log(canvas.toDataURL()); `; const sandbox = await Sandbox.create({ template: 'nodejs' }); const result = await sandbox.runCode(code); // Get PNG chart data if (result.richOutputs && result.richOutputs.length > 0) { const pngData = result.richOutputs[0].data; // Base64 PNG // Save or display the chart } await sandbox.kill(); ``` -------------------------------- ### Shell Command Execution (Python & TypeScript) Source: https://context7.com/hopx-ai/hopx/llms.txt Execute shell commands within the sandbox environment. This includes synchronous and background execution, setting timeouts, specifying working directories, and managing environment variables. Examples are provided for both Python and TypeScript. ```python result = sandbox.commands.run( command='ls -la /workspace', timeout=30, working_dir='/workspace', env={'MY_VAR': 'value'} ) print(f"Stdout: {result.stdout}") print(f"Stderr: {result.stderr}") print(f"Exit code: {result.exit_code}") print(f"Execution time: {result.execution_time}s") result = sandbox.commands.run('cd /workspace && npm install && npm test') bg_result = sandbox.commands.run_background( command='python server.py', timeout=300, working_dir='/app' ) print(f"Background process ID: {bg_result.process_id}") sandbox.commands.run('apt-get update && apt-get install -y curl') sandbox.commands.run('curl -O https://example.com/data.csv') result = sandbox.commands.run('python process_data.py') try: result = sandbox.commands.run('invalid-command') except Exception as e: print(f"Command failed: {e}") ``` ```typescript const result = await sandbox.commands.run('ls -la /workspace', { timeout: 30, workingDir: '/workspace', env: { MY_VAR: 'value' } }); console.log(`Stdout: ${result.stdout}`); console.log(`Stderr: ${result.stderr}`); console.log(`Exit code: ${result.exit_code}`); console.log(`Execution time: ${result.execution_time}s`); const bgResult = await sandbox.commands.runBackground('python server.py', { timeout: 300, workingDir: '/app' }); console.log(`Process ID: ${bgResult.process_id}`); await sandbox.commands.run('apt-get update && apt-get install -y curl'); await sandbox.commands.run('curl -O https://example.com/data.csv'); const processResult = await sandbox.commands.run('python process_data.py'); ``` -------------------------------- ### Code Execution in Multiple Languages with Hopx Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Shows how to execute code snippets in various languages (Python, JavaScript, Bash) directly using the `run_code` method, including setting environment variables. ```python # Python result = sandbox.run_code("print('Hello')", language="python") # JavaScript result = sandbox.run_code("console.log('Hello')", language="javascript") # Bash result = sandbox.run_code("echo 'Hello'", language="bash") # With environment variables result = sandbox.run_code( "import os; print(os.environ['API_KEY'])", env={"API_KEY": "secret"} ) ``` -------------------------------- ### Process Rich Outputs from Python Code Source: https://context7.com/hopx-ai/hopx/llms.txt This snippet demonstrates how to execute Python code that generates rich outputs such as PNG images and HTML tables, and how to process these outputs after execution. It relies on the @hopx-ai/sdk for sandbox management. ```python print(f"Rich outputs: {result.rich_count}") for output in result.rich_outputs: print(f" Type: {output.type}") if output.type == 'image/png': # Base64 encoded PNG image png_data = output.data['image/png'] print(f" PNG size: {len(png_data) / 1024:.1f} KB") elif output.type == 'text/html': # HTML table from pandas html = output.data['text/html'] print(f" HTML size: {len(html)} bytes") sandbox.kill() ``` -------------------------------- ### Async Python Code Execution with Hopx Sandbox Source: https://github.com/hopx-ai/hopx/blob/main/python/README.md Illustrates how to use the asynchronous version of the Hopx Sandbox (`AsyncSandbox`) for running code in an event-driven manner. This is suitable for applications using asyncio. ```python from hopx_ai import AsyncSandbox import asyncio async def main(): async with AsyncSandbox.create(template="python") as sandbox: result = await sandbox.run_code("print('Async!')") print(result.stdout) asyncio.run(main()) ```