Skip to main content
This guide covers advanced use cases and real-world examples for Hopx Sandboxes, including data analysis pipelines, API testing frameworks, ML model training, and complex multi-step workflows.

Data Analysis Pipeline

For comprehensive data analysis workflows, see the Data Analysis Pipeline Tutorial. The tutorial covers:
  • Multi-step data processing workflows
  • Statistical analysis and visualization generation
  • Report creation and export
  • Production-ready pipeline patterns with error handling
  • Best practices for resource allocation and performance optimization

Data Analysis Pipeline Tutorial

Learn to build complete data analysis workflows step-by-step

API Testing Framework

Create an automated API testing framework:
  • Python
  • JavaScript/TypeScript
with Sandbox.create(template="code-interpreter", api_key=API_KEY) as sandbox:
    # Create test suite
    sandbox.files.write("/workspace/test_api.py", """
import requests
import json

def test_get_endpoint():
\"\"\"Test GET endpoint\"\"\"
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
assert response.status_code == 200
assert 'userId' in response.json()
print("✅ GET test passed")

def test_post_endpoint():
\"\"\"Test POST endpoint\"\"\"
data = {'title': 'Test', 'body': 'Test body', 'userId': 1}
response = requests.post(
    'https://jsonplaceholder.typicode.com/posts',
    json=data
)
assert response.status_code == 201
print("✅ POST test passed")

def test_error_handling():
\"\"\"Test error handling\"\"\"
response = requests.get('https://jsonplaceholder.typicode.com/posts/999999')
assert response.status_code == 404
print("✅ Error handling test passed")

if __name__ == '__main__':
test_get_endpoint()
test_post_endpoint()
test_error_handling()
print("\\n🎉 All tests passed!")
    """)
    
    # Install dependencies
    sandbox.commands.run("pip install requests --quiet")
    
    # Run tests
    result = sandbox.run_code("exec(open('/workspace/test_api.py').read())")
    print(f"Test results:\n{result.stdout}")
    
    print("API testing complete!")

ML Model Training

Train machine learning models:
  • Python
  • JavaScript/TypeScript
with Sandbox.create(template="code-interpreter", api_key=API_KEY) as sandbox:
    result = sandbox.run_code("""
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import pickle

# Load data
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2, random_state=42
)

print(f"Training samples: {len(X_train)}")
print(f"Test samples: {len(X_test)}")

# Train model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# Evaluate
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)

print(f"\\nModel accuracy: {accuracy:.2%}")

# Save model
with open('/workspace/model.pkl', 'wb') as f:
pickle.dump(model, f)

print("✅ Model saved to /workspace/model.pkl")
    """, timeout=120)
    
    print(result.stdout)
    
    print("ML training complete!")

Multi-Step Workflow

Build complex multi-step workflows with dependencies:
  • Python
  • JavaScript/TypeScript
with Sandbox.create(template="code-interpreter", api_key=API_KEY) as sandbox:
    # Step 1: Fetch data
    print("Step 1: Fetch data...")
    sandbox.run_code("""
import requests
data = requests.get('https://jsonplaceholder.typicode.com/posts').json()
print(f"Fetched {len(data)} posts")

import json
with open('/workspace/posts.json', 'w') as f:
json.dump(data, f)
    """)
    
    # Step 2: Process data
    print("Step 2: Process data...")
    sandbox.run_code("""
import json
with open('/workspace/posts.json') as f:
posts = json.load(f)

# Extract titles
titles = [p['title'] for p in posts]

# Word frequency
from collections import Counter
all_words = ' '.join(titles).lower().split()
word_freq = Counter(all_words).most_common(10)

print("Top 10 words:")
for word, count in word_freq:
print(f"  {word}: {count}")

# Save analysis
with open('/workspace/analysis.json', 'w') as f:
json.dump({'word_freq': dict(word_freq)}, f)
    """)
    
    # Step 3: Generate visualization
    print("Step 3: Generate visualization...")
    sandbox.run_code("""
import json
import matplotlib.pyplot as plt

with open('/workspace/analysis.json') as f:
data = json.load(f)

words = list(data['word_freq'].keys())
counts = list(data['word_freq'].values())

plt.figure(figsize=(12, 6))
plt.bar(words, counts)
plt.xlabel('Words')
plt.ylabel('Frequency')
plt.title('Top 10 Most Common Words')
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig('/workspace/word_freq.png')

print("✅ Visualization saved!")
    """)
    
    # Step 4: Create summary
    print("Step 4: Create summary...")
    result = sandbox.run_code("""
import json

with open('/workspace/posts.json') as f:
posts = json.load(f)

with open('/workspace/analysis.json') as f:
analysis = json.load(f)

summary = {
'total_posts': len(posts),
'unique_users': len(set(p['userId'] for p in posts)),
'avg_title_length': sum(len(p['title']) for p in posts) / len(posts),
'top_words': analysis['word_freq']
}

print("=" * 50)
print("WORKFLOW SUMMARY")
print("=" * 50)
print(f"Total posts: {summary['total_posts']}")
print(f"Unique users: {summary['unique_users']}")
print(f"Avg title length: {summary['avg_title_length']:.1f}")
print("\\nTop words:", list(summary['top_words'].keys())[:5])
    """)
    
    print(result.stdout)
    
    print("\nMulti-step workflow complete!")

Error Recovery Pattern

Implement robust error handling and recovery:
  • Python
  • JavaScript/TypeScript
max_retries = 3
sandbox = None

try:
    # Create sandbox with retry logic
    for attempt in range(max_retries):
        try:
            sandbox = Sandbox.create(
                template="code-interpreter",
                api_key=API_KEY
            )
            print(f"✅ Sandbox created (attempt {attempt + 1})")
            break
        except Exception as e:
            if attempt < max_retries - 1:
                print(f"⚠️  Attempt {attempt + 1} failed, retrying...")
            else:
                raise
    
    # Execute code with error handling
    try:
        result = sandbox.run_code("""
try:
# This will fail
1 / 0
except ZeroDivisionError:
print("✅ Caught division by zero, continuing...")
result = None

# Continue with valid operations
print("✅ Workflow continues after error")
        """)
        
        print(result.stdout)
        
    except Exception as e:
        print(f"⚠️  Code execution failed: {e}")
        print("   Attempting recovery...")
        
        # Fallback logic
        result = sandbox.run_code('print("Fallback execution")')
        print(f"✅ Recovered: {result.stdout}")
    
    print("✅ Error recovery complete!")
    
finally:
    if sandbox:
        sandbox.kill()
        print("✅ Sandbox cleaned up")

Next Steps