Skip to main content

Python SDK for the AgentSandbox API - sandbox execution service for Python/Bash code

Project description

AgentSandbox Python SDK

A modern Python SDK for the AgentSandbox API - execute Python and Bash code in isolated sandbox environments.

Installation

pip install agentsandbox

Quick Start

from agentsandbox import AgentSandbox

# Initialize the client
client = AgentSandbox(api_key="your-api-key")
# Or set AGENTSANDBOX_API_KEY environment variable

# Execute Python code
result = client.run("print('Hello, World!')")
print(result.stdout)  # Hello, World!
print(result.exit_code)  # 0

Features

  • Sync and Async clients - Use AgentSandbox or AsyncAgentSandbox
  • Session management - Persistent /workspace directory across executions
  • File operations - Upload, download, and manage files
  • Environment variables - Inject env vars into sandbox executions
  • File injection - Pre-load files into /workspace before execution
  • Context managers - Automatic resource cleanup
  • Pydantic models - Full type hints and validation

Usage

Basic Execution

from agentsandbox import AgentSandbox, Language

client = AgentSandbox(api_key="your-api-key")

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

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

Environment Variables

Inject environment variables into the sandbox:

result = client.run(
    """
import os
print(os.environ['API_KEY'])
print(os.environ['DEBUG'])
""",
    env_vars={"API_KEY": "secret123", "DEBUG": "true"}
)

File Injection

Inject files into /workspace before execution:

# Upload a file first
uploaded = client.files.upload(b"name,value\nfoo,1\nbar,2", filename="data.csv")

# Inject file into execution
result = client.run(
    """
import pandas as pd
df = pd.read_csv('/workspace/data.csv')
print(df)
""",
    file_ids=[uploaded.file_id]
)

# Clean up
client.files.delete(uploaded.file_id)

Sessions with Persistent Workspace

Important: Each run() call executes in a fresh process. In-memory variables do NOT persist between executions. Sessions provide a persistent /workspace directory for sharing state via files.

with client.sessions.context() as session:
    sid = session.session_id

    # Write state to a file (persists in session)
    client.run("""
import json
with open('/workspace/state.json', 'w') as f:
    json.dump({'counter': 42}, f)
""", session_id=sid)

    # Read state from file in next execution
    result = client.run("""
import json
with open('/workspace/state.json') as f:
    data = json.load(f)
print(data['counter'])
""", session_id=sid)
    print(result.stdout)  # 42

# Session is automatically deleted here

Sessions with Pre-loaded Files and Env Vars

Create sessions with files and environment variables pre-configured:

# Upload files
config = client.files.upload(b"db_host=localhost", filename="config.txt")
data = client.files.upload(b"id,name\n1,Alice", filename="users.csv")

# Create session with files and env vars pre-loaded
with client.sessions.context(
    file_ids=[config.file_id, data.file_id],
    env_vars={"APP_ENV": "production"}
) as session:
    result = client.run(
        "import os; print(os.listdir('/workspace'))",
        session_id=session.session_id
    )
    print(result.stdout)  # ['config.txt', 'users.csv']

# Clean up files
client.files.delete(config.file_id)
client.files.delete(data.file_id)

Inject Files into Existing Sessions

# Create a session
session = client.sessions.create()

# Upload a file
uploaded = client.files.upload(b"data content", filename="data.txt")

# Inject file into the existing session
client.sessions.inject_files(session.session_id, [uploaded.file_id])

# Now the file is available in the session's /workspace
result = client.run(
    "print(open('/workspace/data.txt').read())",
    session_id=session.session_id
)

# Clean up
client.sessions.delete(session.session_id)
client.files.delete(uploaded.file_id)

File Operations

# Upload a file from path
uploaded = client.files.upload("/path/to/data.csv")
print(f"Uploaded: {uploaded.file_id}")

# Upload from bytes
uploaded = client.files.upload(
    b"name,value\nfoo,1",
    filename="data.csv",
    content_type="text/csv"
)

# List files with pagination
files = client.files.list(limit=20, offset=0)
print(f"Total: {files.total}")

# Iterate all files (auto-pagination)
for file in client.files.list_all():
    print(f"  - {file.filename} ({file.size_bytes} bytes)")

# Download a file
content = client.files.download(file_id)
# Or download to disk
client.files.download_to(file_id, "/path/to/save.csv")

# Delete a file
client.files.delete(file_id)

Async Client

import asyncio
from agentsandbox import AsyncAgentSandbox

async def main():
    async with AsyncAgentSandbox(api_key="your-api-key") as client:
        # Basic execution with env vars
        result = await client.run(
            "import os; print(os.environ['MSG'])",
            env_vars={"MSG": "Hello async!"}
        )
        print(result.stdout)

        # Async session with pre-loaded files
        uploaded = await client.files.upload(b"async data", filename="data.txt")
        async with client.sessions.context(file_ids=[uploaded.file_id]) as session:
            result = await client.run(
                "print(open('/workspace/data.txt').read())",
                session_id=session.session_id
            )
        await client.files.delete(uploaded.file_id)

        # Async file iteration
        async for file in client.files.list_all():
            print(file.filename)

asyncio.run(main())

Error Handling

from agentsandbox import (
    AgentSandbox,
    AgentSandboxError,
    AuthenticationError,
    NotFoundError,
    ValidationError,
)

client = AgentSandbox(api_key="your-api-key")

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}")
except AgentSandboxError as e:
    print(f"API error [{e.status_code}]: {e.message}")

Execution Results

result = client.run("print('hello')")

print(result.session_id)   # Session ID (auto-generated if not provided)
print(result.stdout)       # Standard output
print(result.stderr)       # Standard error
print(result.return_code)  # Return code (0 = success)
print(result.exit_code)    # Alias for return_code
print(result.success)      # True if return_code == 0
print(result.files)        # List of files created in /workspace

Configuration

from agentsandbox import AgentSandbox

client = AgentSandbox(
    api_key="your-api-key",           # Or set AGENTSANDBOX_API_KEY env var
    base_url="https://custom.api.com", # Or set AGENTSANDBOX_BASE_URL env var
    timeout=120.0,                     # Request timeout in seconds
)

API Reference

Clients

  • AgentSandbox - Synchronous client
  • AsyncAgentSandbox - Asynchronous client

Resources

  • client.run(code, language, session_id, env_vars, file_ids) - Execute code (convenience method)
  • client.execute.create(...) - Execute code (full method)
  • client.sessions.create(env_vars, file_ids) - Create a session
  • client.sessions.list() - List sessions
  • client.sessions.get(id) - Get session details
  • client.sessions.delete(id) - Delete a session
  • client.sessions.inject_files(id, file_ids) - Inject files into session
  • client.sessions.context(env_vars, file_ids) - Context manager for session
  • client.files.upload(file, filename, content_type) - Upload a file
  • client.files.list(limit, offset) - List files (paginated)
  • client.files.list_all() - Iterate all files
  • client.files.download(id) - Download file content
  • client.files.download_to(id, path) - Download to disk
  • client.files.delete(id) - Delete a file
  • client.executions.get(id) - Get execution log

Types

  • Language - Enum: PYTHON, BASH
  • ExecuteResponse - Execution result
  • SessionInfo - Session details
  • FileInfo - File metadata
  • ExecutionLog - Detailed execution log

Exceptions

  • AgentSandboxError - Base exception
  • AuthenticationError - Invalid API key (401)
  • ForbiddenError - Access denied (403)
  • NotFoundError - Resource not found (404)
  • ValidationError - Invalid request (422)
  • RateLimitError - Rate limit exceeded (429)
  • ServerError - Server error (500)
  • ServiceUnavailableError - Service unavailable (503)

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

agentsandbox_sdk-0.1.0.tar.gz (18.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

agentsandbox_sdk-0.1.0-py3-none-any.whl (21.4 kB view details)

Uploaded Python 3

File details

Details for the file agentsandbox_sdk-0.1.0.tar.gz.

File metadata

  • Download URL: agentsandbox_sdk-0.1.0.tar.gz
  • Upload date:
  • Size: 18.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.19

File hashes

Hashes for agentsandbox_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 ac1f1c0962cc645a908e636a09633dc1a3a496623a4fd3f4c41dac434861a5ea
MD5 737f0144be12e0ce8ff7b189e390ae25
BLAKE2b-256 138fa269294c269bbf780d27fd963becf99f71f4a162532e6b734826d16fa3a0

See more details on using hashes here.

File details

Details for the file agentsandbox_sdk-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for agentsandbox_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a777157c00911e0fd85e42f6907e8fdd43ef9b89341ca694fff543d5674aa721
MD5 4b0280c659d00e31bd1c2bbf98538b1b
BLAKE2b-256 7c53a2c6f57adbeea711f0a35018466bee7aaa5b4b6155414035c85233e0ee5b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page