Skip to main content
Learn effective debugging techniques for troubleshooting sandbox operations.

Enable Debug Logging

Enable debug logging to see detailed operation information:
  • Python
  • JavaScript/TypeScript
import logging
from hopx_ai import Sandbox

# Enable debug logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('hopx-ai')
logger.setLevel(logging.DEBUG)

# Now all operations will log debug information
sandbox = Sandbox.create(template="code-interpreter")
result = sandbox.run_code("print('Hello')")

Capture Request IDs

Always capture request IDs for support tickets:
  • Python
  • JavaScript/TypeScript
from hopx_ai import Sandbox
from hopx_ai.errors import HopxError
import logging

logger = logging.getLogger(__name__)

def execute_with_tracking(code: str):
    """Execute code and track request IDs"""
    try:
        with Sandbox.create(template="code-interpreter") as sandbox:
            result = sandbox.run_code(code)
            return result
    except HopxError as e:
        # Log request ID for support
        logger.error(f"Error: {e.message}")
        if e.request_id:
            logger.error(f"Request ID: {e.request_id}")
            # Include in support ticket
        raise

# Example
try:
    result = execute_with_tracking("print('Hello')")
except Exception as e:
    logger.exception("Failed to execute")

Inspect Sandbox State

Inspect sandbox state to understand what’s happening:
  • Python
  • JavaScript/TypeScript
from hopx_ai import Sandbox

def inspect_sandbox(sandbox: Sandbox):
    """Inspect sandbox state"""
    info = sandbox.get_info()
    
    print(f"Sandbox ID: {info.sandbox_id}")
    print(f"Status: {info.status}")
    print(f"Template: {info.template_name}")
    print(f"Region: {info.region}")
    print(f"Resources: {info.vcpu} vCPU, {info.memory_mb}MB RAM")
    
    # Get metrics
    metrics = sandbox.get_metrics()
    print(f"CPU: {metrics.cpu_percent}%")
    print(f"Memory: {metrics.memory_used_mb}/{metrics.memory_total_mb} MB")
    
    # List files
    files = sandbox.files.list("/workspace")
    print(f"Files in /workspace: {len(files)}")

with Sandbox.create(template="code-interpreter") as sandbox:
    inspect_sandbox(sandbox)

Test Code Locally First

Test code locally before executing in sandbox:
  • Python
  • JavaScript/TypeScript
# Test code locally first
def test_code_locally(code: str):
    """Test code locally before sandbox execution"""
    try:
        # Test syntax
        compile(code, '<string>', 'exec')
        print("✅ Syntax is valid")
        
        # Test execution (if safe)
        # exec(code)  # Only if code is safe to run locally
        
        return True
    except SyntaxError as e:
        print(f"❌ Syntax error: {e}")
        return False
    except Exception as e:
        print(f"⚠️  Runtime error: {e}")
        return False

# Example
code = """
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3]})
print(df)
"""

if test_code_locally(code):
    # Execute in sandbox
    from hopx_ai import Sandbox
    with Sandbox.create(template="code-interpreter") as sandbox:
        result = sandbox.run_code(code)

Debug Code Execution

Debug code execution step by step:
  • Python
  • JavaScript/TypeScript
from hopx_ai import Sandbox

def debug_code_execution(code: str):
    """Debug code execution step by step"""
    with Sandbox.create(template="code-interpreter") as sandbox:
        # Step 1: Check sandbox is ready
        info = sandbox.get_info()
        print(f"✅ Sandbox ready: {info.status}")
        
        # Step 2: Test simple code first
        test_result = sandbox.run_code("print('Test')")
        print(f"✅ Test execution: {test_result.success}")
        
        # Step 3: Execute actual code
        result = sandbox.run_code(code)
        
        # Step 4: Check results
        print(f"✅ Execution success: {result.success}")
        if result.stdout:
            print(f"📤 Output: {result.stdout[:200]}")
        if result.stderr:
            print(f"⚠️  Errors: {result.stderr[:200]}")
        
        return result

# Example
code = """
x = 10
y = 20
print(f"Sum: {x + y}")
"""

result = debug_code_execution(code)

Debugging Checklist

  • API key is set and valid
  • Template name is correct
  • Code syntax is valid
  • Dependencies are available
  • Check sandbox status
  • Monitor resource usage
  • Check execution output
  • Capture request IDs
  • Verify results
  • Check error messages
  • Review logs
  • Clean up resources

Next Steps