Tutorial Lengkap E2B Code Interpreter: Eksekusi Kode yang Aman untuk Aplikasi AI
E2B Code Interpreter adalah platform sandboxed code execution yang memungkinkan aplikasi AI menjalankan kode secara aman di lingkungan terisolasi. Dalam tutorial ini, kita akan mempelajari cara menggunakan E2B untuk membangun aplikasi AI yang dapat mengeksekusi kode Python, menghasilkan visualisasi, dan memproses data secara real-time.
Apa Itu E2B?
E2B (Environment to Binary) adalah platform cloud yang menyediakan sandbox untuk eksekusi kode. Sandbox ini berjalan di microVM yang terisolasi, sehingga kode yang dijalankan tidak akan mempengaruhi sistem host. E2B sangat berguna untuk membangun AI agent yang perlu menjalankan kode, code interpreter, data analysis tool, dan aplikasi AI interaktif lainnya.
Keunggulan utama E2B:
- Keamanan: Setiap sandbox berjalan di microVM terisolasi dengan filesystem dan network terpisah
- Kecepatan: Sandbox bisa di-spin up dalam hitungan milidetik
- Fleksibilitas: Mendukung Python, JavaScript, R, dan bahasa lainnya
- Integrasi: SDK tersedia untuk Python dan JavaScript/TypeScript
- Persistensi: Mendukung upload/download file dan persistensi data antar eksekusi
Instalasi
Prasyarat
Sebelum memulai, pastikan Anda memiliki:
- Python 3.8+ atau Node.js 18+
- Akun E2B (gratis untuk penggunaan dasar)
- API key dari dashboard E2B
Instalasi Python SDK
pip install e2b-code-interpreter
Instalasi JavaScript/TypeScript SDK
npm install @e2b/code-interpreter
Mendapatkan API Key
export E2BAPIKEY="e2bxxxxxxxxxxxxxxxxxxxx"
Atau buat file .env:
E2BAPIKEY=e2bxxxxxxxxxxxxxxxxxxxx
Basic Usage
Menjalankan Kode Python Sederhana
Berikut contoh dasar menjalankan kode Python di sandbox E2B:
from e2bcodeinterpreter import Sandbox
Buat sandbox baru
sandbox = Sandbox()
Jalankan kode Python
execution = sandbox.runcode("print('Hello from E2B sandbox!')")
Ambil output
print(execution.text) # Output: Hello from E2B sandbox!
Tutup sandbox setelah selesai
sandbox.close()
Menggunakan Context Manager
Cara yang lebih idiomatis menggunakan context manager:
from e2bcodeinterpreter import Sandbox
with Sandbox() as sandbox:
execution = sandbox.run
code("""
import sys
print(f"Python version: {sys.version}")
print(f"Platform: {sys.platform}")
""")
print(execution.text)
Menjalankan Multiple Cell
Anda bisa menjalankan beberapa blok kode secara berurutan, dan state akan dipertahankan antar eksekusi:
from e2bcodeinterpreter import Sandbox
with Sandbox() as sandbox:
# Cell 1: Definisikan variabel
sandbox.runcode("""
x = 10
y = 20
data = [1, 2, 3, 4, 5]
""")
# Cell 2: Gunakan variabel dari cell sebelumnya
execution = sandbox.runcode("""
result = x + y
filtered = [d for d in data if d > 2]
print(f"Sum: {result}")
print(f"Filtered: {filtered}")
""")
print(execution.text)
# Output:
# Sum: 30
# Filtered: [3, 4, 5]
Error Handling
E2B menyediakan informasi error yang detail:
from e2bcodeinterpreter import Sandbox
with Sandbox() as sandbox:
execution = sandbox.runcode("""
Kode ini akan menghasilkan error
result = 1 / 0
""")
if execution.error:
print(f"Error type: {execution.error.name}")
print(f"Error message: {execution.error.value}")
print(f"Traceback: {execution.error.traceback}")
else:
print(execution.text)
Bekerja dengan File
Upload File ke Sandbox
from e2bcodeinterpreter import Sandbox
with Sandbox() as sandbox:
# Upload file dari local filesystem
with open("data.csv", "rb") as f:
sandbox.files.write("/home/user/data.csv", f.read())
# Verifikasi file sudah ter-upload
execution = sandbox.run
code("""
import os
files = os.listdir('/home/user/')
print(files)
""")
print(execution.text)
Download File dari Sandbox
from e2bcodeinterpreter import Sandbox
with Sandbox() as sandbox:
# Generate file di sandbox
sandbox.runcode("""
import json
data = {
"users": [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25}
]
}
with open('/home/user/output.json', 'w') as f:
json.dump(data, f, indent=2)
""")
# Download file dari sandbox
content = sandbox.files.read("/home/user/output.json")
print(content.decode('utf-8'))
Mengelola Direktori
from e2bcodeinterpreter import Sandbox
with Sandbox() as sandbox:
# Buat direktori
sandbox.files.make
dir("/home/user/project")
# List isi direktori
files = sandbox.files.list("/home/user/")
for f in files:
print(f"{f.name} - {'dir' if f.isdir else 'file'}")
Membuat Visualisasi
Salah satu fitur paling berguna E2B adalah kemampuan menghasilkan chart dan visualisasi:
Matplotlib Chart
from e2bcodeinterpreter import Sandbox
with Sandbox() as sandbox:
execution = sandbox.run
code("""
import matplotlib.pyplot as plt
import numpy as np
Generate data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
Buat plot
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y1, label='sin(x)', color='blue', linewidth=2)
ax.plot(x, y2, label='cos(x)', color='red', linewidth=2)
ax.setxlabel('x')
ax.setylabel('y')
ax.settitle('Trigonometric Functions')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tightlayout()
plt.show()
""")
# Ambil hasil chart sebagai gambar
for result in execution.results:
if hasattr(result, 'png'):
# Simpan sebagai file PNG
with open("chart.png", "wb") as f:
import base64
f.write(base64.b64decode(result.png))
print("Chart saved to chart.png")
Data Analysis dengan Pandas
from e2bcodeinterpreter import Sandbox
with Sandbox() as sandbox:
execution = sandbox.runcode("""
import pandas as pd
import matplotlib.pyplot as plt
Buat sample dataset
data = {
'Bulan': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
'Revenue': [15000, 18000, 22000, 19000, 25000, 28000],
'Expenses': [12000, 13000, 15000, 14000, 16000, 17000]
}
df = pd.DataFrame(data)
Hitung profit
df['Profit'] = df['Revenue'] - df['Expenses']
Tampilkan statistik
print("=== Financial Summary ===")
print(f"Total Revenue: ${df['Revenue'].sum():,.0f}")
print(f"Total Expenses: ${df['Expenses'].sum():,.0f}")
print(f"Total Profit: ${df['Profit'].sum():,.0f}")
print(f"Average Monthly Profit: ${df['Profit'].mean():,.0f}")
print()
print(df.tostring(index=False))
Buat visualization
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
Bar chart
x = range(len(df))
width = 0.35
axes[0].bar([i - width/2 for i in x], df['Revenue'], width, label='Revenue', color='#2196F3')
axes[0].bar([i + width/2 for i in x], df['Expenses'], width, label='Expenses', color='#FF5722')
axes[0].setxticks(x)
axes[0].setxticklabels(df['Bulan'])
axes[0].settitle('Revenue vs Expenses')
axes[0].legend()
axes[0].setylabel('Amount ($)')
Line chart untuk profit
axes[1].plot(df['Bulan'], df['Profit'], marker='o', linewidth=2, color='#4CAF50')
axes[1].fillbetween(range(len(df)), df['Profit'], alpha=0.3, color='#4CAF50')
axes[1].settitle('Monthly Profit Trend')
axes[1].setylabel('Profit ($)')
plt.tightlayout()
plt.show()
""")
print(execution.text)
Advanced Usage
Integrasi dengan OpenAI
Contoh membangun AI assistant yang bisa mengeksekusi kode:
import openai
from e2bcodeinterpreter import Sandbox
client = openai.OpenAI()
def runaicodeinterpreter(userquery: str) -> str:
"""AI assistant yang bisa menulis dan menjalankan kode."""
# Step 1: Minta AI generate kode
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": (
"You are a data analyst. When asked a question, "
"write Python code to answer it. "
"Only output the Python code, no explanations."
)
},
{"role": "user", "content": userquery}
]
)
code = response.choices[0].message.content
# Bersihkan markdown code blocks jika ada
code = code.replace("
python", "").replace("``", "").strip()
# Step 2: Jalankan kode di E2B sandbox
with Sandbox() as sandbox:
execution = sandbox.runcode(code)
if execution.error:
return f"Error: {execution.error.value}"
return execution.text
Contoh penggunaan
result = runaicodeinterpreter(
"Calculate the first 20 Fibonacci numbers and show their growth rate"
)
print(result)
Integrasi dengan Anthropic Claude
python
import anthropic
from e2bcodeinterpreter import Sandbox
client = anthropic.Anthropic()
tools = [
{
"name": "executepython",
"description": "Execute Python code in a secure sandbox environment",
"inputschema": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "Python code to execute"
}
},
"required": ["code"]
}
}
]
def chatwithcodeexecution(usermessage: str):
"""Chat dengan Claude yang bisa eksekusi kode."""
messages = [{"role": "user", "content": usermessage}]
response = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=4096,
tools=tools,
messages=messages
)
# Proses tool calls
with Sandbox() as sandbox:
while response.stopreason == "tooluse":
toolresults = []
for block in response.content:
if block.type == "tooluse":
if block.name == "executepython":
execution = sandbox.runcode(block.input["code"])
result = execution.text if not execution.error else f"Error: {execution.error.value}"
toolresults.append({
"type": "toolresult",
"tooluseid": block.id,
"content": result
})
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": toolresults})
response = client.messages.create(
model="claude-sonnet-4-6",
maxtokens=4096,
tools=tools,
messages=messages
)
# Ambil respons teks final
for block in response.content:
if hasattr(block, "text"):
return block.text
result = chatwithcodeexecution(
"Analisis distribusi bilangan prima dari 1 sampai 1000. Buat visualisasinya."
)
print(result)
Custom Sandbox Template
Anda bisa membuat custom template dengan package pre-installed:
bash
Install E2B CLI
npm install -g @e2b/cli
Login
e2b auth login
Buat template baru
e2b template init --name "data-science-sandbox"
Edit
e2b.Dockerfile:
dockerfile
FROM e2b/code-interpreter:latest
Install package tambahan
RUN pip install scikit-learn xgboost lightgbm seaborn plotly
Install system dependencies
RUN apt-get update && apt-get install -y ffmpeg libsm6 libxext6
Build dan push template:
bash
e2b template build
Gunakan custom template:
python
from e2bcodeinterpreter import Sandbox
Gunakan custom template
with Sandbox(template="data-science-sandbox") as sandbox:
execution = sandbox.runcode("""
import sklearn
import xgboost
print(f"scikit-learn: {sklearn.version}")
print(f"XGBoost: {xgboost.version}")
""")
print(execution.text)
Streaming Output
Untuk long-running code, gunakan streaming untuk mendapatkan output secara real-time:
python
from e2bcodeinterpreter import Sandbox
with Sandbox() as sandbox:
execution = sandbox.runcode(
"""
import time
for i in range(10):
print(f"Processing step {i+1}/10...")
time.sleep(1)
print("Done!")
""",
onstdout=lambda output: print(f"[STDOUT] {output.line}"),
onstderr=lambda output: print(f"[STDERR] {output.line}")
)
Timeout dan Resource Management
python
from e2bcodeinterpreter import Sandbox
Sandbox dengan custom timeout (dalam detik)
with Sandbox(timeout=300) as sandbox: # 5 menit timeout
execution = sandbox.runcode(
"""
import time
Proses yang memakan waktu
time.sleep(10)
print("Long process completed!")
""",
timeout=60 # Timeout per eksekusi: 60 detik
)
print(execution.text)
Install Package saat Runtime
python
from e2bcodeinterpreter import Sandbox
with Sandbox() as sandbox:
# Install package menggunakan pip
sandbox.runcode("!pip install requests beautifulsoup4")
# Gunakan package yang baru di-install
execution = sandbox.runcode("""
import requests
from bs4 import BeautifulSoup
response = requests.get('https://httpbin.org/json')
data = response.json()
print(f"Status: {response.statuscode}")
print(f"Data: {data}")
""")
print(execution.text)
Membangun Data Analysis Agent
Berikut contoh lengkap membangun agent analisis data menggunakan E2B:
python
from e2bcodeinterpreter import Sandbox
import json
class DataAnalysisAgent:
def init(self):
self.sandbox = Sandbox()
self.setupenvironment()
def setupenvironment(self):
"""Setup environment dengan library yang diperlukan."""
self.sandbox.runcode("""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
plt.style.use('seaborn-v08-whitegrid')
print("Environment ready!")
""")
def loadcsv(self, csvcontent: str, filename: str = "data.csv"):
"""Load data CSV ke sandbox."""
self.sandbox.files.write(f"/home/user/{filename}", csvcontent.encode())
execution = self.sandbox.runcode(f"""
df = pd.readcsv('/home/user/{filename}')
print(f"Loaded {{len(df)}} rows, {{len(df.columns)}} columns")
print(f"Columns: {{list(df.columns)}}")
print()
print(df.head())
""")
return execution.text
def analyze(self, question: str):
"""Jalankan analisis berdasarkan pertanyaan."""
execution = self.sandbox.runcode(f"""
Analisis: {question}
print("=== Data Overview ===")
print(f"Shape: {{df.shape}}")
print()
print("=== Statistical Summary ===")
print(df.describe())
print()
print("=== Missing Values ===")
print(df.isnull().sum())
""")
return execution.text
def createchart(self, chartcode: str):
"""Generate chart di sandbox."""
execution = self.sandbox.runcode(chartcode)
results = []
for result in execution.results:
if hasattr(result, 'png'):
results.append(result.png)
return results
def close(self):
"""Tutup sandbox."""
self.sandbox.close()
Contoh penggunaan
agent = DataAnalysisAgent()
Load data
csvdata = """name,age,salary,department
Alice,30,75000,Engineering
Bob,25,55000,Marketing
Charlie,35,90000,Engineering
Diana,28,62000,Sales
Eve,32,85000,Engineering
Frank,27,58000,Marketing
"""
print(agent.loadcsv(csvdata))
print(agent.analyze("What is the salary distribution?"))
agent.close()
Best Practices
1. Selalu Gunakan Context Manager
python
Baik - sandbox otomatis ditutup
with Sandbox() as sandbox:
sandbox.runcode("print('hello')")
Kurang baik - bisa lupa menutup sandbox
sandbox = Sandbox()
sandbox.runcode("print('hello')")
sandbox.close() # Jangan lupa!
2. Handle Error dengan Baik
python
from e2bcodeinterpreter import Sandbox
with Sandbox() as sandbox:
execution = sandbox.runcode(usercode)
if execution.error:
# Log error untuk debugging
print(f"Execution failed: {execution.error.name}")
print(f"Message: {execution.error.value}")
# Jangan expose traceback lengkap ke end user
else:
# Proses hasil
processoutput(execution.text)
3. Batasi Timeout untuk User Code
python
with Sandbox() as sandbox:
# Jangan biarkan user code berjalan tanpa batas
execution = sandbox.runcode(
untrustedcode,
timeout=30 # Maksimal 30 detik
)
4. Validasi Input Sebelum Eksekusi
python
import re
FORBIDDENPATTERNS = [
r'os\.system',
r'subprocess',
r'shutil\.rmtree',
r'open\(./etc/',
]
def validatecode(code: str) -> bool:
"""Validasi kode sebelum dieksekusi di sandbox."""
for pattern in FORBIDDENPATTERNS:
if re.search(pattern, code):
return False
return True
with Sandbox() as sandbox:
if validatecode(usercode):
execution = sandbox.runcode(usercode)
else:
print("Code contains forbidden patterns")
5. Gunakan Custom Template untuk Production
Untuk production, buat custom template agar tidak perlu install package setiap kali membuat sandbox baru. Ini menghemat waktu startup dan biaya.
6. Monitor Resource Usage
python
with Sandbox() as sandbox:
execution = sandbox.runcode("""
import psutil
import os
Cek memory usage
memory = psutil.virtualmemory()
print(f"Total Memory: {memory.total / (10243):.1f} GB")
print(f"Available: {memory.available / (10243):.1f} GB")
print(f"Used: {memory.percent}%")
Cek disk usage
disk = psutil.diskusage('/')
print(f"\\nDisk Total: {disk.total / (10243):.1f} GB")
print(f"Disk Used: {disk.used / (10243):.1f} GB")
print(f"Disk Free: {disk.free / (10243):.1f} GB")
""")
print(execution.text)
``
Perbandingan dengan Alternatif Lain
| Fitur | E2B | Modal | Docker | AWS Lambda |
|-------|-----|-------|--------|------------|
| Startup time | ~150ms | ~1s | ~2-5s | ~100-500ms |
| Sandbox isolation | MicroVM | Container | Container | Firecracker |
| Pre-installed packages | Python + DS libs | Custom | Custom | Layer-based |
| File I/O | Ya | Ya | Ya | Terbatas |
| Visualization support | Built-in | Manual | Manual | Tidak |
| Pricing model | Per sandbox/menit | Per compute | Self-hosted | Per request |
| AI SDK integration | Native | SDK | Manual | Manual |
Kesimpulan
E2B Code Interpreter adalah solusi yang sangat baik untuk membangun aplikasi AI yang membutuhkan eksekusi kode secara aman. Dengan sandbox berbasis microVM, Anda mendapatkan isolasi yang kuat tanpa mengorbankan kecepatan. Integrasi native dengan berbagai LLM provider membuatnya ideal untuk membangun AI agent, code interpreter, dan data analysis tool.
Hal-hal penting yang perlu diingat:
Dengan panduan ini, Anda sudah siap membangun aplikasi AI yang bisa mengeksekusi kode secara aman dan efisien menggunakan E2B Code Interpreter.