Introduction & AI Agent Use Cases

The Python Sandbox API provides a highly secure environment to run Python code remotely. It is engineered specifically to act as a code interpreter and function-calling tool for Large Language Models (LLMs).

🎯 Built for AI Function Calling (Tool Use)

Provide this API as a tool to LLMs (like GPT-4, Claude, or Gemini). When the AI needs to process data, generate PDFs, manipulate images, or run complex algorithms, it can dynamically write a Python script, construct the JSON payload, send it to this API, and parse the resulting stdout or files—all in a secure container.

Each request runs in a temporary, isolated environment with strict resource constraints. You can upload files via Base64, execute AI-generated scripts to process those files, and retrieve the output seamlessly in a single synchronous API call.

Base URL & Rate Limits

All API requests are made to the base URL.

Limit Type Value Description
Requests Per Minute 5 RPM Maximum requests allowed in a 60-second window.
Requests Per Day 30 RPD Total daily request quota, resetting at UTC midnight.
Server Concurrency 5 Simultaneous executions allowed. Ensure your AI agents implement retry logic for 503 errors.

Execution & Resource Limits

To maintain a secure and stable environment for remote execution, the following resource limits are strictly enforced:

Resource Limit Description
Execution Timeout 10 seconds Script will be forcibly terminated if it exceeds time.
Max Code Length 2000 chars Prompt your AI to write concise scripts.
Max Attachments 2 files Maximum files uploaded per execution.
Max File Size 8 MB Each attached file must remain under 8 megabytes.

Security & Sandbox Model

Because this API executes arbitrary code, it employs an aggressive sandboxing strategy:

  • No Network Access: Scripts cannot make outbound network requests.
  • Filesystem Isolation: Code executes inside a temporary directory.
  • Import Restrictions: Only a curated list of safe libraries is available (e.g., os, subprocess are forbidden).
  • Ephemeral Environment: The sandbox directory is permanently destroyed instantly after the HTTP request concludes.

Making Requests

All requests to the /execute endpoint must be a POST request containing a JSON payload.

curl -X POST  \
-H "Content-Type: application/json" \
-d '{
  "code": "import numpy as np\nprint(\"AI computed:\", np.mean([10, 20, 30]))"
}'
import requests

url = ""
payload = {
    "code": "import numpy as np\nprint('AI computed:', np.mean([10, 20, 30]))"
}

response = requests.post(url, json=payload)
print(response.json())
const axios = require('axios');

async function runCode() {
  const response = await axios.post('', {
    code: "import numpy as np\nprint('AI computed:', np.mean([10, 20, 30]))"
  });
  console.log(response.data);
}
runCode();

Endpoint Details: POST /execute

View JSON Request Schema
{
  "type": "object",
  "required": ["code"],
  "properties": {
    "code": { "type": "string", "maxLength": 2000 },
    "stdin_data": { "type": "string" },
    "attachments": {
      "type": "array",
      "maxItems": 2,
      "items": {
        "type": "object",
        "properties": {
          "filename": { "type": "string" },
          "content_base_64": { "type": "string" }
        }
      }
    },
    "return_files": { "type": "array", "items": { "type": "string" } }
  }
}

Allowed AI Libraries

Agents can import from a curated list of modules. Banned modules trigger a ForbiddenImportError.

Category Allowed Modules
Data Science & Math numpy, math, statistics, random
Media Generation PIL (Pillow), reportlab, fpdf
Data Structures collections, itertools, json, base64

Complete Example: LLM File Processing

This comprehensive workflow demonstrates how an application processes an image file by sending structured execution tasks to the sandbox directory. The examples below convert a local image to base64, transmit it along with processing instructions, save the modified image returned by the sandbox server, and archive the full API response structure into a local JSON file.

import requests
import base64
import json

API_URL = ''

# 1. Read the local asset file and encode it to Base64
try:
    with open('my_photo.jpg', "rb") as image_file:
        b64_content = base64.b64encode(image_file.read()).decode('utf-8')
except FileNotFoundError:
    print("Please ensure 'my_photo.jpg' exists in your execution context.")
    exit()

# 2. Package sandbox script instructions along with data attachments
payload = {
    "code": "from PIL import Image\nwith Image.open('in.jpg') as img:\n  img.convert('L').save('out.png')",
    "attachments": [{"filename": "in.jpg", "content_base_64": b64_content}],
    "return_files": ["out.png"]
}

# 3. Transmit request payload synchronously to the remote pipeline
response = requests.post(API_URL, json=payload)

# 4. Process pipeline response structural variables
if response.status_code == 200:
    response_data = response.json()
    
    # Save the absolute JSON response metadata locally for layout reference
    with open('response_schema.json', 'w') as json_log:
        json.dump(response_data, json_log, indent=2)
    print("Output schema written cleanly to 'response_schema.json'")

    execution_details = response_data.get('execution_details', {})
    
    # If the targeted file key is present in output array, decode and archive
    output_files = execution_details.get('output_files', {})
    if 'out.png' in output_files:
        result_data = base64.b64decode(output_files['out.png']['content_base64'])
        with open('result.png', "wb") as image_output:
            image_output.write(result_data)
        print("Success! Processed sandboxed image saved safely to 'result.png'")
else:
    print(f"Server rejected processing pipeline. Error code: {response.status_code}")
const axios = require('axios');
const fs = require('fs');

const API_URL = '';

async function processRemoteImage() {
  try {
    // 1. Read the local asset file and encode it to Base64
    if (!fs.existsSync('my_photo.jpg')) {
      console.error("Please ensure 'my_photo.jpg' exists in your execution context.");
      return;
    }
    const b64Content = fs.readFileSync('my_photo.jpg', { encoding: 'base64' });

    // 2. Package sandbox script instructions along with data attachments
    const payload = {
      code: "from PIL import Image\nwith Image.open('in.jpg') as img:\n  img.convert('L').save('out.png')",
      attachments: [{ filename: "in.jpg", content_base_64: b64Content }],
      return_files: ["out.png"]
    };

    // 3. Transmit request payload synchronously to the remote pipeline
    const response = await axios.post(API_URL, payload);
    const responseData = response.data;

    // 4. Save the absolute JSON response metadata locally for layout reference
    fs.writeFileSync('response_schema.json', JSON.stringify(responseData, null, 2));
    console.log("Output schema written cleanly to 'response_schema.json'");

    const executionDetails = responseData.execution_details || {};
    const outputFiles = executionDetails.output_files || {};

    // If the targeted file key is present in output array, decode and archive
    if (outputFiles['out.png']) {
      const resultBuffer = Buffer.from(outputFiles['out.png'].content_base64, 'base64');
      fs.writeFileSync('result.png', resultBuffer);
      console.log("Success! Processed sandboxed image saved safely to 'result.png'");
    }
  } catch (error) {
    console.error("Pipeline failure:", error.response ? error.response.data : error.message);
  }
}

processRemoteImage();

Workflow Summary Metrics

When you run either of the workflows above, the script follows this clear order of operations to maximize visibility into execution results:

  • Data Transformation: Converts a local image into an standard string representation for clean REST transmission.
  • Instruction Delivery: Wraps the sandboxed manipulation commands alongside data matrices in the request payload.
  • Format Inspection logging: The full payload response array is automatically dumped into a file named response_schema.json, enabling quick investigation into stdout metrics, resource utilization, and parsing variables.
  • Reconstruct Assets: Extracts targeted generated media parameters from the response mapping array and returns a functional data asset locally.

Meet the Developer

Developer Avatar

Loading Profile...

Fetching developer profile from GitHub...