Python Execution
Execute Python code with the Code Interpreter
Python Execution
Run Python code in a sandboxed environment with full access to popular libraries. The Code Interpreter comes pre-installed with common data science and utility packages, and you can install additional packages on the fly with pip.
Basic Execution
import { CodeInterpreter } from "vibengine";
const sandbox = await CodeInterpreter.create({
apiKey: process.env.VE_API_KEY,
});
const execution = await sandbox.runCode(`
x = 10
y = 20
print(f"The sum of {x} and {y} is {x + y}")
`);
console.log(execution.text); // "The sum of 10 and 20 is 30"
await sandbox.kill();import os
from vibengine import CodeInterpreter
sandbox = CodeInterpreter.create(api_key=os.environ["VE_API_KEY"])
execution = sandbox.run_code("""
x = 10
y = 20
print(f"The sum of {x} and {y} is {x + y}")
""")
print(execution.text) # "The sum of 10 and 20 is 30"
sandbox.kill()Installing Packages at Runtime
You can install any pip package inside the sandbox. Installed packages persist for the lifetime of the sandbox.
const execution = await sandbox.runCode(`
!pip install requests
import requests
response = requests.get("https://api.vibengine.ai/health")
print(response.status_code)
`);
console.log(execution.text); // "200"execution = sandbox.run_code("""
!pip install requests
import requests
response = requests.get("https://api.vibengine.ai/health")
print(response.status_code)
""")
print(execution.text) # "200"Packages like pandas, numpy, matplotlib, and scipy are pre-installed. You only need to pip install less common packages.
Handling Stdout and Stderr
The execution result separates standard output and standard error for precise control.
const execution = await sandbox.runCode(`
import sys
print("Processing data...")
print("Warning: column age has 3 missing values", file=sys.stderr)
print("Done. 97 rows processed.")
`);
console.log(execution.text);
// "Processing data...\nDone. 97 rows processed."
console.log(execution.logs.stdout);
// ["Processing data...", "Done. 97 rows processed."]
console.log(execution.logs.stderr);
// ["Warning: column age has 3 missing values"]execution = sandbox.run_code("""
import sys
print("Processing data...")
print("Warning: column age has 3 missing values", file=sys.stderr)
print("Done. 97 rows processed.")
""")
print(execution.text)
# "Processing data...\nDone. 97 rows processed."
print(execution.logs.stdout)
# ["Processing data...", "Done. 97 rows processed."]
print(execution.logs.stderr)
# ["Warning: column age has 3 missing values"]Error Handling
When code raises an exception, the error details are captured in the result object.
const execution = await sandbox.runCode(`
data = [1, 2, 3]
print(data[10])
`);
if (execution.error) {
console.log(execution.error.name); // "IndexError"
console.log(execution.error.message); // "list index out of range"
console.log(execution.error.traceback); // Full traceback string
}execution = sandbox.run_code("""
data = [1, 2, 3]
print(data[10])
""")
if execution.error:
print(execution.error.name) # "IndexError"
print(execution.error.message) # "list index out of range"
print(execution.error.traceback) # Full traceback stringWorking with Pandas DataFrames
The sandbox comes with pandas pre-installed. DataFrames render as rich output automatically.
const execution = await sandbox.runCode(`
import pandas as pd
data = {
"name": ["Alice", "Bob", "Charlie", "Diana"],
"score": [92, 87, 95, 78],
"grade": ["A", "B+", "A", "C+"],
}
df = pd.DataFrame(data)
print(df.describe())
print(f"\\nTop scorer: {df.loc[df[score].idxmax(), name]}")
`);
console.log(execution.text);
// Prints summary statistics and "Top scorer: Charlie"execution = sandbox.run_code("""
import pandas as pd
data = {
"name": ["Alice", "Bob", "Charlie", "Diana"],
"score": [92, 87, 95, 78],
"grade": ["A", "B+", "A", "C+"],
}
df = pd.DataFrame(data)
print(df.describe())
print(f"\\nTop scorer: {df.loc[df[score].idxmax(), name]}")
""")
print(execution.text)
# Prints summary statistics and "Top scorer: Charlie"Persistent State Across Executions
Variables defined in one execution are available in subsequent executions within the same sandbox session.
await sandbox.runCode("scores = [92, 87, 95, 78]");
const execution = await sandbox.runCode(`
average = sum(scores) / len(scores)
print(f"Average score: {average}")
`);
console.log(execution.text); // "Average score: 88.0"sandbox.run_code("scores = [92, 87, 95, 78]")
execution = sandbox.run_code("""
average = sum(scores) / len(scores)
print(f"Average score: {average}")
""")
print(execution.text) # "Average score: 88.0"State is tied to the sandbox instance. Once you call kill(), all variables and installed packages are lost.