> ## Documentation Index
> Fetch the complete documentation index at: https://docs.primeintellect.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> Sync and async clients, fleets, and error handling

The SDK ships two clients with identical methods: `SandboxClient` for synchronous scripts and `AsyncSandboxClient` for concurrent workloads. Both are importable from `prime_sandboxes`. Every feature page shows the sync client; the async client takes the same calls with `await`.

## Sync client

```python theme={null}
from prime_sandboxes import SandboxClient, CreateSandboxRequest, APIClient

client = SandboxClient(APIClient())

sandbox = client.create(
    CreateSandboxRequest(name="sdk-demo", docker_image="python:3.11-slim")
)
client.wait_for_creation(sandbox.id)
print(client.execute_command(sandbox.id, "python -c 'print(42)'").stdout)
client.delete(sandbox.id)
```

## Async client

```python theme={null}
import asyncio
from prime_sandboxes import AsyncSandboxClient, CreateSandboxRequest

async def main() -> None:
    async with AsyncSandboxClient() as sandboxes:
        sandbox = await sandboxes.create(
            CreateSandboxRequest(name="sdk-demo", docker_image="python:3.11-slim")
        )
        await sandboxes.wait_for_creation(sandbox.id)
        result = await sandboxes.execute_command(sandbox.id, "python -c 'print(42)'")
        print(result.stdout.strip())
        await sandboxes.delete(sandbox.id)

asyncio.run(main())
```

## Launch a fleet

```python theme={null}
async def create_many(images: list[str]) -> None:
    async with AsyncSandboxClient() as sandboxes:
        requests = [
            CreateSandboxRequest(
                name=f"batch-{i}", docker_image=image, idempotency_key=f"batch-{i}"
            )
            for i, image in enumerate(images, start=1)
        ]
        created = await asyncio.gather(*[sandboxes.create(req) for req in requests])
        await sandboxes.bulk_wait_for_creation([sbx.id for sbx in created])
        print("Ready:", ", ".join(sbx.name for sbx in created))
```

`bulk_wait_for_creation` polls via the list endpoint, backing off automatically if the API throttles you. `idempotency_key` makes create retries safe. Tear down with [`bulk_delete`](./lifecycle#delete).

For a full script, see `prime/examples/sandbox_async_demo.py`.

## Error handling

All exceptions are importable directly from `prime_sandboxes`.

### Sandbox lifecycle errors

Raised when a sandbox is no longer `RUNNING`. `SandboxOOMError`, `SandboxTimeoutError`, and `SandboxImagePullError` are subclasses of `SandboxNotRunningError`, so catch the base class for broad handling.

| Exception | Cause | Typical Fix |
| - | - | - |
| `SandboxNotRunningError` | Operation attempted on a non-running sandbox (terminated, errored, or timed out) | Check sandbox status before operating on it |
| `SandboxOOMError` | Sandbox killed due to out-of-memory | Increase `memory_gb` in `CreateSandboxRequest` or optimize memory usage |
| `SandboxTimeoutError` | Sandbox exceeded its `timeout_minutes` and was terminated | Increase the timeout or split work into smaller tasks |
| `SandboxImagePullError` | Docker image could not be pulled | Verify the image name, tag, and that you can access the image |

### Operation errors

Raised when the sandbox is still running but the operation itself fails.

| Exception | Cause | Typical Fix |
| - | - | - |
| `CommandTimeoutError` | `execute_command` exceeded its `timeout` parameter | Increase the per-command timeout, or use `start_background_job` for long tasks |
| `UploadTimeoutError` | File upload timed out | Check network conditions; pass a larger `timeout` for big files |
| `DownloadTimeoutError` | File download timed out | Check file size and network conditions |
| `SandboxFileNotFoundError` | File does not exist at the given path | Check the path before uploading, downloading, or reading |
| `SandboxFileTooLargeError` | Read exceeded the read size limit | Use `download_file` instead of `read_file` for large files |

### API errors

| Exception | Cause | Typical Fix |
| - | - | - |
| `APIError` | Base class for all API errors (non-2xx response, malformed response, network failure) | Inspect the error message for details |
| `UnauthorizedError` | Invalid or expired API key (HTTP 401) | Check `PRIME_API_KEY` or re-run `prime login` |
| `PaymentRequiredError` | Insufficient balance (HTTP 402) | Top up your account balance |
| `APITimeoutError` | API request timed out before receiving a response | Retry the request; check network connectivity |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.