E2B provider for ComputeSDK - cloud sandboxes with full Linux environments, filesystem access, and microVM isolation
npm install @computesdk/e2bE2B provider for ComputeSDK - Execute code in secure, isolated E2B sandboxes with full filesystem and terminal support.
``bash`
npm install @computesdk/e2b
1. Get your E2B API key from e2b.dev
2. Set the environment variable:
`bash`
export E2B_API_KEY=e2b_your_api_key_here
Use the gateway for zero-config auto-detection:
`typescript
import { compute } from 'computesdk';
// Auto-detects E2B from E2B_API_KEY environment variable
const sandbox = await compute.sandbox.create();
const result = await sandbox.runCode(
import pandas as pd
print(pd.__version__));
console.log(result.stdout);
await sandbox.destroy();
`
For direct SDK usage without the gateway:
`typescript
import { e2b } from '@computesdk/e2b';
const compute = e2b({ apiKey: process.env.E2B_API_KEY });
const sandbox = await compute.sandbox.create();
const result = await sandbox.runCode(
import pandas as pd
import numpy as np
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = pd.DataFrame(data)
print(df)
print(f"Sum: {df.sum().sum()}"));
console.log(result.stdout);
await sandbox.destroy();
`
`bash`
export E2B_API_KEY=e2b_your_api_key_here
`typescript`
interface E2BConfig {
/* E2B API key - if not provided, will use E2B_API_KEY env var /
apiKey?: string;
/* Default runtime environment /
runtime?: 'python' | 'node';
/* Execution timeout in milliseconds /
timeout?: number;
}
- ✅ Code Execution - Python and Node.js runtime support
- ✅ Command Execution - Run shell commands in sandbox
- ✅ Filesystem Operations - Full file system access via E2B API
- ✅ Terminal Support - Interactive PTY terminals
- ✅ Auto Runtime Detection - Automatically detects Python vs Node.js
- ✅ Data Science Ready - Pre-installed pandas, numpy, matplotlib, etc.
`typescript
// Execute Python code
const result = await sandbox.runCode(
import json
data = {"message": "Hello from Python"}
print(json.dumps(data)), 'python');
// Execute Node.js code
const result = await sandbox.runCode(
const data = { message: "Hello from Node.js" };
console.log(JSON.stringify(data));, 'node');
// Auto-detection (based on code patterns)
const result = await sandbox.runCode('print("Auto-detected as Python")');
`
`typescript
// List files
const result = await sandbox.runCommand('ls', ['-la']);
// Install packages
const result = await sandbox.runCommand('pip', ['install', 'requests']);
// Run scripts
const result = await sandbox.runCommand('python', ['script.py']);
`
`typescript
// Write file
await sandbox.filesystem.writeFile('/tmp/hello.py', 'print("Hello World")');
// Read file
const content = await sandbox.filesystem.readFile('/tmp/hello.py');
// Create directory
await sandbox.filesystem.mkdir('/tmp/data');
// List directory contents
const files = await sandbox.filesystem.readdir('/tmp');
// Check if file exists
const exists = await sandbox.filesystem.exists('/tmp/hello.py');
// Remove file or directory
await sandbox.filesystem.remove('/tmp/hello.py');
`
`typescript
// Create terminal
const terminal = await sandbox.terminal.create({
command: 'bash',
cols: 80,
rows: 24,
onData: (data: Uint8Array) => {
const output = new TextDecoder().decode(data);
console.log('Terminal output:', output);
}
});
// Write to terminal
await terminal.write('echo "Hello Terminal!"\n');
// Resize terminal
await terminal.resize(120, 30);
// Kill terminal
await terminal.kill();
// List all terminals
const terminals = await sandbox.terminal.list();
// Get terminal by ID
const existingTerminal = await sandbox.terminal.getById('terminal-id');
`
`typescript
// Get sandbox info
const info = await sandbox.getInfo();
console.log(info.id, info.status, info.createdAt);
// Destroy sandbox
await sandbox.destroy();
`
The provider automatically detects the runtime based on code patterns:
Python indicators:
- print( statementsimport
- statements def
- function definitionsf"
- Python-specific syntax (, __, etc.)
Default: Node.js for all other cases
`typescript
import { e2b } from '@computesdk/e2b';
try {
const compute = e2b({ apiKey: process.env.E2B_API_KEY });
const sandbox = await compute.sandbox.create();
const result = await sandbox.runCode('invalid code');
} catch (error) {
if (error.message.includes('Missing E2B API key')) {
console.error('Set E2B_API_KEY environment variable');
} else if (error.message.includes('Invalid E2B API key format')) {
console.error('E2B API keys should start with "e2b_"');
} else if (error.message.includes('authentication failed')) {
console.error('Check your E2B API key');
} else if (error.message.includes('quota exceeded')) {
console.error('E2B usage limits reached');
}
}
`
`typescript
import { e2b } from '@computesdk/e2b';
const compute = e2b({ apiKey: process.env.E2B_API_KEY });
const sandbox = await compute.sandbox.create();
// Create project structure
await sandbox.filesystem.mkdir('/analysis');
await sandbox.filesystem.mkdir('/analysis/data');
await sandbox.filesystem.mkdir('/analysis/output');
// Write input data
const csvData = name,age,city
Alice,25,New York
Bob,30,San Francisco
Charlie,35,Chicago;
await sandbox.filesystem.writeFile('/analysis/data/people.csv', csvData);
// Process data with Python
const result = await sandbox.runCode(
import pandas as pd
import matplotlib.pyplot as plt
import json
with open('/analysis/output/results.json', 'w') as f:
json.dump(results, f, indent=2)
print("Results saved!"));
console.log(result.stdout);
// Read the results
const results = await sandbox.filesystem.readFile('/analysis/output/results.json');
console.log('Analysis results:', JSON.parse(results));
// Check if chart was created
const chartExists = await sandbox.filesystem.exists('/analysis/output/age_chart.png');
console.log('Chart created:', chartExists);
await sandbox.destroy();
`
`typescript
import { e2b } from '@computesdk/e2b';
const compute = e2b({ apiKey: process.env.E2B_API_KEY });
const sandbox = await compute.sandbox.create();
// Create interactive Python terminal
const terminal = await sandbox.terminal.create({
command: 'python3',
cols: 80,
rows: 24,
onData: (data: Uint8Array) => {
const output = new TextDecoder().decode(data);
process.stdout.write(output); // Forward to console
}
});
// Send Python commands
await terminal.write('import numpy as np\n');
await terminal.write('import pandas as pd\n');
await terminal.write('print("Libraries loaded!")\n');
await terminal.write('data = np.array([1, 2, 3, 4, 5])\n');
await terminal.write('print(f"Mean: {data.mean()}")\n');
await terminal.write('exit()\n');
// Wait for commands to execute
await new Promise(resolve => setTimeout(resolve, 2000));
await terminal.kill();
await sandbox.destroy();
`
`typescript
import { e2b } from '@computesdk/e2b';
const compute = e2b({ apiKey: process.env.E2B_API_KEY });
const sandbox = await compute.sandbox.create({ timeout: 600000 }); // 10 minutes for ML tasks
// Create ML project structure
await sandbox.filesystem.mkdir('/ml-project');
await sandbox.filesystem.mkdir('/ml-project/data');
await sandbox.filesystem.mkdir('/ml-project/models');
// Generate and process data
const result = await sandbox.runCode(
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
import joblib
print(f"Dataset shape: {df.shape}")
print("\\nDataset info:")
print(df.describe())
print(f"\\nModel Performance:")
print(f"MSE: {mse:.4f}")
print(f"R²: {r2:.4f}")
import json
with open('/ml-project/results.json', 'w') as f:
json.dump(results, f, indent=2)
print("Results saved!"));
console.log(result.stdout);
// Read the results
const results = await sandbox.filesystem.readFile('/ml-project/results.json');
console.log('ML Results:', JSON.parse(results));
// Verify model file exists
const modelExists = await sandbox.filesystem.exists('/ml-project/models/linear_model.pkl');
console.log('Model saved:', modelExists);
await sandbox.destroy();
`
1. Resource Management: Always destroy sandboxes when done to free resources
2. Error Handling: Use try-catch blocks for robust error handling
3. Timeouts: Set appropriate timeouts for long-running tasks
4. File Organization: Use the filesystem API to organize project files
5. Terminal Sessions: Clean up terminal sessions with terminal.kill()`
6. API Key Security: Never commit API keys to version control
- Sandbox Listing: E2B doesn't support listing all sandboxes (each is managed individually)
- Memory Limits: Subject to E2B sandbox memory constraints
- Network Access: Limited outbound network access
- File Persistence: Files are not persisted between sandbox sessions
- Execution Time: Subject to E2B timeout limits
- E2B Documentation
- ComputeSDK Issues
- E2B Support
MIT