Code Execution Tool
ChimerAI's Code Execution Tool runs Python code in an isolated sandbox and returns the output — ideal for data analysis, calculations, and dynamic code generation workflows.
What you get
- Python execution — Run arbitrary Python in a sandboxed environment
- Isolated per-request — Each execution uses a fresh subprocess
- Timeout protection — Configurable execution time limit (default 30s)
- Output capture — stdout, stderr, return value
- Package access — NumPy, pandas, matplotlib, statistics, math pre-installed
- Plot output — matplotlib figures returned as base64 PNG
- Security — No file system access, no network, no subprocess.run
Quick setup
npx chimerai add ai-tools --only code
Scaffolds:
app/api/tools/code/execute/route.ts ← Execution endpoint
services/ai/tools/code_tools.py ← Python sandbox runner
Usage
const res = await fetch('/api/tools/code/execute', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
code: `
import statistics
data = [10, 20, 30, 15, 25]
print("Mean:", statistics.mean(data))
print("Stdev:", round(statistics.stdev(data), 2))
`.trim(),
timeout: 15,
}),
});
const { output, error, executionTime } = await res.json();
// output: "Mean: 20\nStdev: 7.91"
Code + AI workflow (code generation)
// 1. Ask AI to generate code
const generated = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'Write Python code. Return only code, no explanations.' },
{ role: 'user', content: 'Calculate the first 10 Fibonacci numbers' },
],
});
const code = generated.choices[0].message.content ?? '';
// 2. Execute the generated code
const result = await fetch('/api/tools/code/execute', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
});
const { output } = await result.json();
Python sandbox implementation
import subprocess, sys, json, textwrap
def execute_code(code: str, timeout: int = 30) -> dict:
# Wrap code to capture output
wrapped = textwrap.dedent(f"""
import sys, io
_stdout = io.StringIO()
sys.stdout = _stdout
try:
{textwrap.indent(code, ' ')}
except Exception as e:
print(f"Error: {{e}}", file=sys.stderr)
finally:
sys.stdout = sys.__stdout__
print(_stdout.getvalue(), end='')
""")
result = subprocess.run(
[sys.executable, "-c", wrapped],
capture_output=True, text=True, timeout=timeout,
# Security: no inherit env, no shell
env={"PATH": "/usr/bin:/bin"},
)
return {
"output": result.stdout,
"error": result.stderr or None,
"returnCode": result.returncode,
}