Overview
An AI code interpreter allows users to write and execute code in a safe, isolated environment. This tutorial shows you how to:- Create sandboxes for code execution
- Execute Python and JavaScript code safely
- Handle errors and stream output
- Capture rich outputs (plots, images, tables)
- Clean up resources automatically
Prerequisites
- Python SDK installed (
pip install hopx-ai) - API key configured (see Authentication)
- Basic understanding of Python async/await
Step 1: Basic Code Execution
Start with a simple code execution function:- Python
- JavaScript/TypeScript
Step 2: Add Error Handling
Handle errors gracefully:- Python
- JavaScript/TypeScript
Step 3: Stream Output in Real-Time
Stream execution output for better user experience:- Python
- JavaScript/TypeScript
Step 4: Capture Rich Outputs
Capture plots, images, and DataFrames automatically:- Python
- JavaScript/TypeScript
Step 5: Complete Implementation
Here’s a complete AI code interpreter class:- Python
- JavaScript/TypeScript
Best Practices
✅ DO: Always Clean Up Sandboxes
✅ DO: Always Clean Up Sandboxes
Always delete sandboxes after use to avoid unnecessary costs:
- Python
- JavaScript/TypeScript
✅ DO: Set Timeouts
✅ DO: Set Timeouts
Always set reasonable timeouts to prevent hanging executions:
✅ DO: Handle Errors Gracefully
✅ DO: Handle Errors Gracefully
Provide clear error messages to users:
❌ DON'T: Reuse Sandboxes Across Users
❌ DON'T: Reuse Sandboxes Across Users
Create a new sandbox for each user session to ensure isolation:

