Skip to main content
The Hopx JavaScript SDK provides powerful code execution capabilities with support for multiple programming languages, rich output capture, and streaming execution.

Basic Execution

runCode()

Execute code synchronously and wait for results.
const result = await sandbox.runCode('print("Hello, World!")');
console.log(result.stdout);
console.log(result.stderr);
console.log(`Exit code: ${result.exit_code}`);
console.log(`Execution time: ${result.execution_time}s`);
Method Signature:
async runCode(
  code: string,
  options?: CodeExecutionOptions
): Promise<ExecutionResult>
Options:
interface CodeExecutionOptions {
  language?: string;        // 'python', 'javascript', 'bash', 'go'
  timeout?: number;        // Timeout in seconds (default: 60)
  workingDir?: string;     // Working directory (default: '/workspace')
  env?: Record<string, string>;  // Environment variables
  rich?: boolean;          // Capture rich outputs (default: false)
}

ExecutionResult

The ExecutionResult object contains execution results:
interface ExecutionResult {
  stdout: string;              // Standard output
  stderr: string;              // Standard error
  exit_code: number;          // Exit code (0 = success)
  execution_time: number;      // Execution time in seconds
  rich_outputs?: RichOutput[]; // Rich outputs (if rich: true)
}
Example:
const result = await sandbox.runCode('print("Hello")');
if (result.exit_code === 0) {
  console.log('Execution succeeded!');
  console.log(`Output: ${result.stdout}`);
} else {
  console.log(`Execution failed: ${result.stderr}`);
  console.log(`Exit code: ${result.exit_code}`);
}

Supported Languages

Python

const result = await sandbox.runCode(
  `
import pandas as pd
df = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
print(df)
`,
  { language: 'python' }
);

JavaScript (Node.js)

const result = await sandbox.runCode(
  `
const fs = require('fs');
const data = fs.readFileSync('/workspace/data.txt', 'utf8');
console.log(data);
`,
  { language: 'javascript' }
);

Bash

const result = await sandbox.runCode(
  `
#!/bin/bash
echo "Hello from Bash!"
ls -la /workspace
`,
  { language: 'bash' }
);

Go

const result = await sandbox.runCode(
  `
package main
import "fmt"
func main() {
    fmt.Println("Hello from Go!")
}
`,
  { language: 'go' }
);

Rich Outputs

Enable rich output capture to automatically capture plots, DataFrames, and other visual outputs:
const result = await sandbox.runCode(
  `
import matplotlib.pyplot as plt
import pandas as pd

# Create DataFrame
df = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
print(df)

# Create plot
plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig('/workspace/plot.png')
`,
  { rich: true }
);

// Access rich outputs
console.log(`Captured ${result.rich_outputs?.length || 0} rich outputs`);
for (const output of result.rich_outputs || []) {
  console.log(`Type: ${output.type}`);
  console.log(`Path: ${output.path}`);
  if (output.type === 'image') {
    // Download image
    const imgData = await sandbox.files.readBytes(output.path);
    await fs.promises.writeFile('plot.png', imgData);
  }
}

Environment Variables

Pass environment variables for a specific execution:
const result = await sandbox.runCode(
  'import os; print(os.environ.get("API_KEY"))',
  {
    env: {
      API_KEY: 'sk-test-123',
      DEBUG: 'true'
    }
  }
);

Working Directory

Specify a custom working directory:
// Create directory
await sandbox.files.mkdir('/workspace/project');

// Execute code in that directory
const result = await sandbox.runCode(
  'import os; print(os.getcwd())',
  { workingDir: '/workspace/project' }
);
// Output: /workspace/project

Timeouts

Set custom timeouts for long-running code:
// Long-running computation
const result = await sandbox.runCode(
  `
import time
for i in range(100):
    print(f"Step {i}")
    time.sleep(0.1)
`,
  { timeout: 300 }  // 5 minutes
);

Error Handling

Handle execution errors:
import { CodeExecutionError } from '@hopx-ai/sdk';

try {
  const result = await sandbox.runCode('invalid python syntax here');
} catch (error) {
  if (error instanceof CodeExecutionError) {
    console.log(`Code execution failed: ${error.message}`);
    console.log(`Language: ${error.language}`);
  } else {
    console.log(`Unexpected error: ${error}`);
  }
}

Examples

Data Analysis

const result = await sandbox.runCode(
  `
import pandas as pd
import numpy as np

# Load data
df = pd.DataFrame({
    "x": np.random.randn(100),
    "y": np.random.randn(100)
})

# Analyze
print(f"Mean x: {df['x'].mean()}")
print(f"Mean y: {df['y'].mean()}")
print(f"Correlation: {df['x'].corr(df['y'])}")
`,
  { rich: true }
);