Skip to content

Code Execution API

The Code Execution API enables secure execution of Python code in an isolated sandbox environment. This endpoint is ideal for:

  • Data Analysis: Process and analyze datasets using pandas, numpy, and other scientific libraries
  • Mathematical Calculations: Perform complex computations and statistical analysis
  • Visualization: Generate plots and charts using matplotlib and seaborn
  • Code Validation: Test and validate Python code snippets safely
  • Educational Tools: Run student code submissions in a controlled environment

All code executes in a Docker-based sandbox with:

  • Network isolation (no external network access)
  • Read-only filesystem
  • Restricted system calls and module imports
  • Execution as unprivileged user (nobody:nogroup)
  • Pre-execution security scanning for malicious patterns
  • Resource limits (CPU, memory, timeout)

Currently supported: Python only

The sandbox environment includes commonly used Python libraries:

  • Scientific Computing: numpy, pandas, scipy
  • Visualization: matplotlib, seaborn
  • Utilities: Standard library modules (json, math, re, datetime, etc.)

All libraries are pre-installed in the container image for optimal performance.


Endpoint to execute Python code in a secure sandbox environment.

POST https://api.relax.ai/v1/tools/code

from relaxai import Relaxai
client = Relaxai(
api_key = RELAX_API_KEY,
)
response = client.tools.execute_code(
code="print(2**2)",
lang="python",
timeout=30
)
print(response.stdout) # Output: 4
import Relaxai from 'relaxai';
const client = new Relaxai({
apiKey: RELAX_API_KEY,
});
const toolResponse = await client.tools.executeCode({
code: 'print(2**2)',
lang: 'python',
timeout: 30
});
console.log(toolResponse.stdout); // Output: 4
package main
import (
"context"
"fmt"
"github.com/relax-ai/go-sdk"
"github.com/relax-ai/go-sdk/option"
)
func main() {
client := relaxai.NewClient(
option.WithAPIKey("RELAX_API_KEY"),
)
toolResponse, err := client.Tools.ExecuteCode(context.TODO(), relaxai.ToolExecuteCodeParams{
ToolRequest: relaxai.ToolRequestParam{
Code: "print(2**2)",
Lang: "python",
Timeout: 30,
},
})
if err != nil {
panic(err.Error())
}
fmt.Printf("%+v
", toolResponse.Stdout)
}
Terminal window
curl https://api.relax.ai/v1/tools/code \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $RELAX_API_KEY" \
-H "x-relaxai-userid: user-123" \
-d '{
"code": "print(2**2)",
"lang": "python",
"timeout": 30
}'

Returns an execution result object containing the output, errors, and execution metadata.


Successful Execution Response
{
"success": true,
"stdout": "4\n",
"stderr": "",
"exit_code": 0,
"execution_time": 0.15,
"security_checked": true,
"violations": [],
"plots": []
}

FieldTypeDescription
successbooleanIndicates whether the code executed successfully (true) or failed due to errors or security violations (false).
stdoutstringThe standard output from the code execution. Contains all printed output and results.
stderrstringThe standard error output. Contains error messages, warnings, and stack traces from failed executions.
exit_codeintegerThe process exit code. 0 indicates successful execution, -1 indicates execution failure or security violation.
execution_timefloatThe total execution time in seconds, including security checks and code execution.
security_checkedbooleanAlways true. Indicates that pre-execution security scanning was performed.
violationsarray of stringsList of security policy violations detected during pre-execution scanning. Empty array if no violations found.
plotsarray of objectsArray of generated matplotlib/seaborn plots. Each object contains: content_base64 (string) - Base64-encoded plot image, format (string) - Image format (e.g., “png”), filename (string) - Suggested filename (e.g., “plot_1.png”).

The following parameters can be included in the request body:


ParameterTypeRequiredDescription
codestringYesThe Python code to execute. Must be valid Python syntax. Maximum length: 50,000 characters (50KB). Cannot contain null bytes or be empty/whitespace-only.
langstringYesProgramming language of the code. Only “python” is currently supported.

The Code Execution API implements comprehensive security scanning and restrictions:


import pandas as pd
import numpy as np
# Create a sample dataset
data = {
'name': ['Alice', 'Bob', 'Charlie', 'David'],
'age': [25, 30, 35, 28],
'score': [85, 90, 78, 92]
}
df = pd.DataFrame(data)
# Calculate statistics
print(f"Average age: {df['age'].mean()}")
print(f"Average score: {df['score'].mean()}")
print(f"\nTop scorer: {df.loc[df['score'].idxmax(), 'name']}")

Response:

{
"success": true,
"stdout": "Average age: 29.5\nAverage score: 86.25\n\nTop scorer: David\n",
"stderr": "",
"exit_code": 0,
"execution_time": 0.28,
"security_checked": true,
"violations": [],
"plots": []
}

import matplotlib.pyplot as plt
import numpy as np
# Generate data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create plot
plt.figure(figsize=(10, 6))
plt.plot(x, y, label='sin(x)', color='blue', linewidth=2)
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Sine Wave')
plt.legend()
plt.grid(True)
plt.show()
print("Plot generated successfully!")

Response:

{
"success": true,
"stdout": "Plot generated successfully!\n",
"stderr": "",
"exit_code": 0,
"execution_time": 0.45,
"security_checked": true,
"violations": [],
"plots": [
{
"content_base64": "iVBORw0KGgoAAAANSUhEUgAAA...",
"format": "png",
"filename": "plot_1.png"
}
]
}

import numpy as np
from scipy import stats
# Generate random data
data = np.random.normal(100, 15, 1000)
# Calculate statistics
mean = np.mean(data)
std = np.std(data)
median = np.median(data)
# Perform t-test
t_stat, p_value = stats.ttest_1samp(data, 100)
print(f"Mean: {mean:.2f}")
print(f"Std Dev: {std:.2f}")
print(f"Median: {median:.2f}")
print(f"T-statistic: {t_stat:.4f}")
print(f"P-value: {p_value:.4f}")

Request:

{
"code": "import os\nos.system('ls -la')",
"lang": "python"
}

Response:

{
"success": false,
"stdout": "",
"stderr": "Security violations detected",
"exit_code": -1,
"execution_time": 0.05,
"security_checked": true,
"violations": [
"Operating system interface",
"os.system line execution"
],
"plots": []
}

Request:

{
"code": "result = 10 / 0",
"lang": "python"
}

Response:

{
"success": true,
"stdout": "",
"stderr": "Traceback (most recent call last):\n File \"<string>\", line 1, in <module>\nZeroDivisionError: division by zero\n",
"exit_code": 1,
"execution_time": 0.12,
"security_checked": true,
"violations": [],
"plots": []
}

Request:

{
"code": "print('Hello world'",
"lang": "python"
}

Response:

{
"success": true,
"stdout": "",
"stderr": " File \"<string>\", line 1\n print('Hello world'\n ^\nSyntaxError: unexpected EOF while parsing\n",
"exit_code": 1,
"execution_time": 0.08,
"security_checked": true,
"violations": [],
"plots": []
}

Request:

{
"code": "import time\ntime.sleep(100)",
"lang": "python",
"timeout": 5
}

Response:

{
"success": false,
"stdout": "",
"stderr": "Execution failed: Execution timeout exceeded",
"exit_code": -1,
"execution_time": 5.02,
"security_checked": true,
"violations": [],
"plots": []
}

  1. Optimize Code Execution Time

    • Keep code concise and efficient
    • Avoid unnecessary loops or computations
    • Use vectorized operations (numpy/pandas) when possible
  2. Handle Errors Gracefully

    • Check the success field before processing results
    • Parse stderr for error details when exit_code is non-zero
    • Check violations array for security issues
  3. Plot Handling

    • Decode base64 content to display plots
    • Check plots array length to detect if visualizations were generated
    • Use plt.show() to ensure plots are captured
  4. Security Awareness

    • Avoid using restricted modules (os, subprocess, etc.)
    • Do not attempt file system operations
    • Network requests will fail due to isolation