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.
Agent generates code
The LLM writes Python that uses pandas to summarize a CSV.
Agent calls the session execute endpoint
SandboxAPI runs the code in an isolated gVisor sandbox. Returns ModuleNotFoundError: No module named 'pandas'.
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.
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.
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
- Sessions — files and installed packages persist between tool calls. The agent doesn't re-do setup work.
- Controlled package install — stable pip/npm direct artifacts install from the curated cache through a separate short-lived installer only after firewall/topology and mirror/OSV readiness checks pass. pip accepts cached wheels only with
--only-binary=:all: --no-deps --no-build-isolation; source distributions are rejected. npm uses validatednpm pack --ignore-scriptsextraction with dependency and lifecycle-script metadata stripped. Callers list each required package explicitly. The endpoint fails closed otherwise, and this path stays separate from execution egress. - Modern runtimes — Python 3.12, Node 22, TypeScript 5.6.3 via esbuild, Go 1.22, Java 21, GCC 12 for C/C++, and Bash 5.2.
- gVisor isolation — when an agent generates code, you don't trust the code. We don't either.
- RapidAPI-backed MCP — four stateless tools for Claude Code, Codex, Cursor, VS Code, and Antigravity, authenticated with your RapidAPI key. See the client setup guide.
- Streaming output — show the agent's stdout in real time as long-running scripts execute.
- Controlled API access — paid API requests can opt in to managed public HTTPS with
network.enabled. Ultra and Mega can optionally restrict destinations with exact or explicit wildcardallowed_domainsrules; Basic and playground workloads remain network-disabled.
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.