For AI agent developers

Build AI agents that actually run code

The agent generates code. SandboxAPI runs it. The agent reads the output, fixes errors, installs missing packages, and iterates until the task is done. The same loop a human runs — at machine speed.

The canonical agent pattern

Most "AI runs code" demos break the moment the model needs to install a package, debug a traceback, or hold state across turns. With stateful sessions, that loop just works.

1

Agent generates code

The LLM writes Python that uses pandas to summarize a CSV.

2

Agent calls the session execute endpoint

SandboxAPI runs the code in an isolated gVisor sandbox. Returns ModuleNotFoundError: No module named 'pandas'.

3

Agent reads the error and calls the session package-install endpoint

POST /v1/sessions/{id}/install with {"manager":"pip","packages":["pandas","numpy"]} uses the managed install proxy after its isolation and mirror/OSV readiness checks pass. The endpoint installs direct artifacts only, so the agent lists every required package explicitly.

4

Agent retries — same session, same files

The files and installed packages from earlier steps are still available. The retry succeeds. Output goes back to the user.

Why sessions matter: Without stateful sessions, the agent has to re-do every step from scratch on every retry. With sessions, files and installed packages survive between calls, so each iteration builds on the last — exactly how a human would debug.

Code example: OpenAI tool calling + the REST API

Here's the entire wiring you need. The agent picks the tool, a small requests helper calls SandboxAPI through RapidAPI, and the result goes back to the model. There is no official SDK yet; the REST API is the contract. Wrap it in a loop and you have a code interpreter.

import json
import os

import requests
from openai import OpenAI

BASE = "https://sandboxapi.p.rapidapi.com"
HEADERS = {
    "X-RapidAPI-Key": os.environ["RAPIDAPI_KEY"],
    "X-RapidAPI-Host": "sandboxapi.p.rapidapi.com",
    "Content-Type": "application/json",
}

def api(method, path, **body):
    resp = requests.request(method, BASE + path, headers=HEADERS, json=body or None, timeout=180)
    resp.raise_for_status()
    return resp.json() if resp.content else {}

client = OpenAI()

# Sessions need PRO, ULTRA, or MEGA. Files under /home/sandbox and installed
# packages persist across calls; each call starts a fresh Python process.
session = api("POST", "/v1/sessions", language="python3", idle_ttl=600)

tools = [
  {
    "type": "function",
    "function": {
      "name": "execute_python",
      "description": "Run Python in a sandbox session. Files under /home/sandbox persist across calls; variables do not.",
      "parameters": {
        "type": "object",
        "properties": {"code": {"type": "string"}},
        "required": ["code"],
      },
    },
  },
  {
    "type": "function",
    "function": {
      "name": "install_packages",
      "description": "Install direct pip artifacts in the current session; include every required dependency explicitly.",
      "parameters": {
        "type": "object",
        "properties": {"packages": {"type": "array", "items": {"type": "string"}}},
        "required": ["packages"],
      },
    },
  },
]

messages = [{"role": "user", "content": "Read the CSV at /home/sandbox/sales.csv and report total revenue."}]

try:
    while True:
        resp = client.chat.completions.create(model="gpt-4o", messages=messages, tools=tools)
        msg = resp.choices[0].message
        messages.append(msg.model_dump())
        if not msg.tool_calls:
            print(msg.content)
            break
        for call in msg.tool_calls:
            args = json.loads(call.function.arguments)
            if call.function.name == "execute_python":
                result = api("POST", f"/v1/sessions/{session['id']}/execute", code=args["code"], timeout=60)
                content = result["stdout"] + (("\n" + result["stderr"]) if result["stderr"] else "")
            else:
                api("POST", f"/v1/sessions/{session['id']}/install", manager="pip", packages=args["packages"])
                content = "Installed " + ", ".join(args["packages"])
            messages.append({"role": "tool", "tool_call_id": call.id, "content": content})
finally:
    api("DELETE", f"/v1/sessions/{session['id']}")

Why SandboxAPI fits AI agents

Common patterns

Code interpreter for any LLM

Wrap the REST calls in two tool definitions (execute_python, install_packages) and you have a fully-featured code interpreter for any model that supports function calling.

Self-correcting agent

When the LLM produces broken code, the traceback feeds back as the next message. With sessions, files and installed packages from earlier attempts are still there, so the fix builds on prior work.

Multi-language pipelines

The agent can drop down to Bash to inspect a file, switch to Python to analyze it, and produce a JSON output. Use one session per language, within your plan's concurrent-session ceiling (PRO 2, ULTRA 5, MEGA 8, subject to shared host capacity). Every session call is a billed request.

Auto-grading agent demos

Building a "show me you can solve LeetCode" demo? Run a small harness inside the sandbox, print JSON with passed/total counts, and let the agent inspect stdout for the verdict.

Start building free

Basic costs $0 and includes 500 requests per RapidAPI subscription period for demos and prototypes. Recommended Pro adds up to 2 concurrent sessions and stable pip/npm installation; Ultra raises the per-account ceiling to 5 and supports 300s production async jobs. Mega serves high-volume teams with 200,000 requests per RapidAPI subscription period, 150s sync/session work, 600s production async jobs, up to 200 accepted items per batch, and up to 8 concurrent sessions per RapidAPI account. Batch items run through bounded workers within a 150-second wall under RapidAPI's 180-second gateway maximum. Session caps are per-RapidAPI-account ceilings. Shared service capacity is not reserved; during saturation, session creation may return HTTP 503 with Retry-After.

Start with Basic (free) MCP integration guide