Skip to main content
HopX sandboxes support multiple programming languages for code execution. Each language has specific features, pre-installed packages, and capabilities.

Overview

HopX currently supports the following languages:
  • Python - Full-featured Python environment with data science libraries
  • JavaScript/Node.js - Modern JavaScript runtime with npm support
  • Bash - Shell scripting and command execution
  • Go - Go programming language runtime
Language support depends on the template you use. The code-interpreter template includes Python, JavaScript, and Bash. Other templates may support different language combinations.

Python

Python is the most feature-rich language in HopX sandboxes, with extensive pre-installed packages for data science, web development, and automation.

Version

  • Python 3.11+ (varies by template)

Pre-installed Packages

Common packages available in most Python templates:
  • Data Science: pandas, numpy, matplotlib, scipy, scikit-learn
  • Web: requests, httpx, flask, fastapi
  • Utilities: beautifulsoup4, ipykernel, jupyter-client
  • System: git, curl, wget, vim, nano

Features

  • Rich Output Capture: Automatically captures matplotlib plots, pandas DataFrames, and other visualizations
  • IPython Kernel: Interactive Python execution with Jupyter kernel support
  • Package Installation: Install additional packages with pip
  • File Operations: Full filesystem access for reading/writing files
  • Environment Variables: Access via os.getenv() or os.environ

Example

from hopx_ai import Sandbox
from hopx_ai.exceptions import APIError, ResourceLimitError

try:
    sandbox = Sandbox.create(template="code-interpreter")
    
    # Execute Python code
    result = sandbox.run_code("""
    import pandas as pd
    import matplotlib.pyplot as plt
    
    data = {'x': [1, 2, 3, 4], 'y': [1, 4, 9, 16]}
    df = pd.DataFrame(data)
    print(df.describe())
    
    plt.plot(df['x'], df['y'])
    plt.savefig('/tmp/plot.png')
    """, language="python")
    
    print(result.stdout)
    # Rich outputs (plots, DataFrames) are automatically captured
    
    sandbox.kill()
except APIError as e:
    print(f"API error: {e}")
except ResourceLimitError as e:
    print(f"Resource limit exceeded: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
Expected Output:
                x          y
count   4.000000   4.000000
mean    2.500000   7.500000
std     1.290994   6.454972
min     1.000000   1.000000
25%     1.750000   3.250000
50%     2.500000   6.500000
75%     3.250000  11.750000
max     4.000000  16.000000
Rich outputs (plots, DataFrames) are automatically captured in result.rich_outputs.

JavaScript/Node.js

JavaScript execution runs in a Node.js environment with access to npm packages and modern JavaScript features.

Version

  • Node.js 18+ (varies by template)

Pre-installed Packages

  • Runtime: Node.js with npm
  • Kernel: iJavaScript kernel for interactive execution
  • System Tools: Standard Unix utilities

Features

  • npm Support: Install packages with npm install
  • ES Modules: Support for modern ES6+ syntax
  • Rich Output: Can generate HTML, JSON, and text outputs
  • Async/Await: Full support for asynchronous operations
  • File System: Access to Node.js fs module

Example

import { Sandbox } from '@hopx-ai/sdk';
import { APIError, ResourceLimitError } from '@hopx-ai/sdk';

try {
  const sandbox = await Sandbox.create({ template: 'code-interpreter' });
  
  // Execute JavaScript code
  const result = await sandbox.runCode(`
  const fs = require('fs');
  const data = { message: 'Hello from Node.js!', timestamp: Date.now() };
  console.log(JSON.stringify(data, null, 2));
  
  // Write to file
  fs.writeFileSync('/tmp/output.json', JSON.stringify(data));
  `, { language: 'javascript' });
  
  console.log(result.stdout);
  
  await sandbox.kill();
} catch (error) {
  if (error instanceof APIError) {
    console.error(`API error: ${error.message}`);
  } else if (error instanceof ResourceLimitError) {
    console.error(`Resource limit exceeded: ${error.message}`);
  } else {
    console.error(`Unexpected error: ${error.message}`);
  }
}
Expected Output:
{
  "message": "Hello from Node.js!",
  "timestamp": 1706284800000
}

JavaScript-Specific Features

The JavaScript SDK includes some unique features:
  • IPython Kernel Support: sandbox.runIpython() method for interactive JavaScript execution
  • TypeScript Types: Full TypeScript support with type definitions
  • Async Generators: WebSocket streaming uses async generators (for await...of)

Bash

Bash provides shell scripting capabilities for system administration, automation, and command execution.

Features

  • Shell Commands: Execute any shell command or script
  • Pipelines: Support for command pipelines and redirection
  • Environment Variables: Access via $VARIABLE_NAME syntax
  • File Operations: Standard Unix file operations (cp, mv, rm, etc.)
  • Process Management: Background processes, job control

Example

from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Execute bash commands
result = sandbox.run_code("""
#!/bin/bash
echo "Current directory: $(pwd)"
echo "User: $(whoami)"
echo "Date: $(date)"

# List files
ls -la /workspace

# Process data
echo "1,2,3,4,5" | tr ',' '\\n' | awk '{sum+=$1} END {print "Sum:", sum}'
""", language="bash")

print(result.stdout)
Expected Output:
Current directory: /workspace
User: root
Date: Mon Jan 27 10:30:00 UTC 2025
total 8
drwxr-xr-x 2 root root 4096 Jan 27 10:30 .
drwxr-xr-x 3 root root 4096 Jan 27 10:30 ..
-rw-r--r-- 1 root root   42 Jan 27 10:30 data.txt
Sum: 15

Common Use Cases

  • Installing system packages with apt-get or yum
  • Running build scripts and automation tasks
  • Processing text files with grep, sed, awk
  • Managing files and directories
  • Running system diagnostics

Go

Go (Golang) support enables compilation and execution of Go programs in sandboxes.

Version

  • Go 1.21+ (varies by template)

Features

  • Compilation: Compile Go programs with go build
  • Standard Library: Full access to Go standard library
  • Modules: Support for Go modules and dependency management
  • Concurrency: Full support for goroutines and channels
  • Cross-compilation: Can compile for different platforms

Example

from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Execute Go code
result = sandbox.run_code("""
package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("Hello from Go!")
    fmt.Printf("Current time: %s\\n", time.Now().Format(time.RFC3339))
    
    // Simple goroutine example
    go func() {
        time.Sleep(1 * time.Second)
        fmt.Println("Goroutine completed!")
    }()
    
    time.Sleep(2 * time.Second)
}
""", language="go")

print(result.stdout)
Expected Output:
Hello from Go!
Current time: 2025-01-27T10:30:00Z  # Actual timestamp will vary
Goroutine completed!
The timestamp in the output will be the actual execution time, not a fixed value. The format follows RFC3339 (e.g., 2025-01-27T10:30:00Z).

Language-Specific Considerations

Execution Timeouts

Default timeouts vary by language and execution mode:
  • Synchronous execution: 30-60 seconds (configurable)
  • Background execution: Up to 300 seconds (5 minutes)
  • Async execution: Up to 3600 seconds (1 hour) with webhooks

Memory and Resources

  • Each sandbox has allocated CPU, memory, and disk resources
  • Resource limits are defined by the template
  • Monitor resource usage to avoid hitting limits

Package Installation

  • Python
  • JavaScript
  • Bash
# Install packages during execution
sandbox.run_code("""
import subprocess
subprocess.run(['pip', 'install', 'package-name'], check=True)
""", language="python")
Or use commands:
sandbox.commands.run("pip install package-name")

Environment Variables

All languages can access environment variables set in the sandbox:
  • Python
  • JavaScript
  • Bash
  • Go
import os
value = os.getenv('MY_VAR', 'default')

Choosing the Right Language

Data Science & Analytics

Use Python for data analysis, machine learning, and visualization. Pre-installed packages like pandas, numpy, and matplotlib make it ideal for data work.

Web Development

Use JavaScript for Node.js applications, API development, and web scraping. Full npm support enables rapid development.

System Automation

Use Bash for system administration, file processing, and automation scripts. Perfect for DevOps tasks.

High Performance

Use Go for concurrent programs, network services, and performance-critical applications. Excellent for building APIs and microservices.

Language Support by Template

Different templates support different languages. Check template details to see which languages are available:
from hopx_ai import Sandbox

# List available templates
templates = Sandbox.list_templates()

for template in templates:
    print(f"{template.name}: {template.language or 'Multiple'}")
Expected Output:
code-interpreter: Multiple
python-basic: Python
node-basic: JavaScript
ubuntu-base: Multiple
The actual templates and their languages may vary. Use Sandbox.list_templates() to see available templates in your account.

Next Steps