AGENT SANDBOX DOCS

Quick Start

Choose how you want to integrate with Agent Sandbox. Pick the method that matches your setup.

A

OpenClaw Bot

Install the plugin directly through the OpenClaw plugin system.

$ openclaw plugins install @agentsandbox/openclaw-agentsandbox
$ openclaw gateway restart
$ openclaw models auth login --provider agentsandbox

01 — Install the Agent Sandbox plugin

02 — Restart the gateway to load the plugin

03 — Authenticate via Google Sign-In

B

Claude Code, Codex & Other Agents

Paste this prompt into your coding agent and it will handle the rest.

Read https://agentsandbox.co/skill.md and follow the instructions to start using Agent Sandbox
Claude CodeCodexCursorWindsurfCline
C

Direct API

Sign up or log in to get an API key manually.

Set API Key
export AGENT_SANDBOX_API="sk-sandbox-..."

Run Your First Sandbox

Once you're set up via any method above, execute your first code:

curl -X POST https://api.agentsandbox.co/v1/execute \
  -H "Authorization: Bearer $AGENT_SANDBOX_API" \
  -H "Content-Type: application/json" \
  -d '{
    "language": "python",
    "code": "print(2 + 3)"
  }'

Questions? We'd love to hear from you.

Connect with Founders
MENU
LLM Optimized Context

This content is optimized for Large Language Models. Copy and paste this into ChatGPT, Claude, or other assistants to give them full context on the Agent Sandbox SDK.

# Agent Sandbox Documentation

Base URL: https://api.agentsandbox.co
All endpoints require: Authorization: Bearer <API-KEY>

## Quick Start

1. **Install the Python SDK (Recommended)**
   `pip install agentsandbox-sdk`

2. **Run Your First Sandbox**
   ```python
   from agentsandbox import AgentSandbox
   client = AgentSandbox(api_key="sk-sandbox-...")  # Or set AGENTSANDBOX_API_KEY env var
   result = client.run("print(2 + 3)")
   print(result.stdout)  # 5
   ```

## AgentSandbox Python SDK

Install: `pip install agentsandbox-sdk`

### Basic Usage
```python
from agentsandbox import AgentSandbox, Language

client = AgentSandbox()  # Uses AGENTSANDBOX_API_KEY env var

# Python execution
result = client.run("print(1 + 1)")
print(result.stdout)  # 2
print(result.success)  # True

# Bash execution
result = client.run("echo 'Hello' && ls", language=Language.BASH)
```

### Environment Variables
```python
result = client.run(
    "import os; print(os.environ['MY_VAR'])",
    env_vars={"MY_VAR": "hello"}
)
```

### File Operations
```python
# Upload
uploaded = client.files.upload(b"data content", filename="data.csv")

# Inject into execution
result = client.run(
    "print(open('/workspace/data.csv').read())",
    file_ids=[uploaded.file_id]
)

# Download
content = client.files.download(uploaded.file_id)

# Delete
client.files.delete(uploaded.file_id)
```

### Sessions (Persistent Workspace)
```python
with client.sessions.context() as session:
    # Write file in first execution
    client.run("open('/workspace/data.txt', 'w').write('hello')", session_id=session.session_id)

    # Read file in next execution (same session)
    result = client.run("print(open('/workspace/data.txt').read())", session_id=session.session_id)
    print(result.stdout)  # hello
# Session auto-deleted
```

### Async Client
```python
from agentsandbox import AsyncAgentSandbox

async with AsyncAgentSandbox() as client:
    result = await client.run("print('async!')")
```

### Error Handling
```python
from agentsandbox import AgentSandbox, AuthenticationError, NotFoundError, ValidationError

try:
    result = client.run("print('hello')")
except AuthenticationError:
    print("Invalid API key")
except NotFoundError:
    print("Resource not found")
except ValidationError as e:
    print(f"Invalid request: {e.message}")
```

### SDK Resources
- `client.run(code, language, session_id, env_vars, file_ids)` — Execute code
- `client.sessions.create/list/get/delete/context` — Session management
- `client.sessions.inject_files(session_id, file_ids)` — Inject files into session
- `client.files.upload/download/download_to/list/list_all/delete` — File operations

## REST API Reference

### POST /v1/execute
Execute Python or Bash code.

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| language | string | Yes | "python" or "bash" |
| code | string | Yes | Code to execute |
| session_id | string | No | Session ID for persistent sandbox |
| env_vars | object | No | Environment variables to inject |
| file_ids | string[] | No | File IDs to inject into /workspace |

**Response 200:**
```json
{
  "session_id": "abc-123",
  "stdout": "5\n",
  "stderr": "",
  "return_code": 0,
  "files": [{ "file_id": "file-xyz", "filename": "output.png" }]
}
```

### Sessions
- POST /v1/sessions — Create session (optional: env_vars, file_ids)
- GET /v1/sessions — List sessions
- GET /v1/sessions/{id} — Get session
- DELETE /v1/sessions/{id} — Delete session
- POST /v1/sessions/{id}/files — Inject files into session

### Files
- POST /v1/files — Upload file (multipart/form-data)
- GET /v1/files — List files (query: limit, offset)
- GET /v1/files/{id} — Download file
- DELETE /v1/files/{id} — Delete file

## Error Codes
| Code | Meaning |
|------|---------|
| 401 | Missing or invalid API key |
| 403 | Not authorized for resource |
| 404 | Resource not found |
| 422 | Validation error |
| 500 | Server error |
| 503 | Service unavailable |

## OpenAI Integration (Using SDK)
```python
import json
from openai import OpenAI
from agentsandbox import AgentSandbox, Language

openai_client = OpenAI()
sandbox = AgentSandbox()  # Uses AGENTSANDBOX_API_KEY env var

tools = [{
    "type": "function",
    "function": {
        "name": "execute_code",
        "description": "Execute Python or Bash code in a sandboxed environment.",
        "parameters": {
            "type": "object",
            "properties": {
                "language": {"type": "string", "enum": ["python", "bash"]},
                "code": {"type": "string"}
            },
            "required": ["language", "code"]
        }
    }
}]

messages = [{"role": "user", "content": "What is the 50th Fibonacci number?"}]
response = openai_client.chat.completions.create(model="gpt-4o", messages=messages, tools=tools)
message = response.choices[0].message

if message.tool_calls:
    tool_call = message.tool_calls[0]
    args = json.loads(tool_call.function.arguments)

    # Use SDK instead of raw HTTP
    lang = Language.PYTHON if args["language"] == "python" else Language.BASH
    result = sandbox.run(args["code"], language=lang)

    messages.append(message)
    messages.append({
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": json.dumps({
            "stdout": result.stdout,
            "stderr": result.stderr,
            "return_code": result.return_code,
            "success": result.success,
        })
    })
    final = openai_client.chat.completions.create(model="gpt-4o", messages=messages)
    print(final.choices[0].message.content)
```

### Multi-Turn with Persistent Sessions
```python
with sandbox.sessions.context() as session:
    session_id = session.session_id

    # Each execution shares the same /workspace
    result = sandbox.run(code, language=lang, session_id=session_id)
# Session auto-cleaned
```