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

# Use AutoPilot for sandboxes from any language

> Choose a provider for each new sandbox and report sandboxes starting and stopping with two REST calls, from Python or any other language.

[AutoPilot for sandboxes](https://docs.costgraph.ai/costgraph/autopilot/sandboxes.md) works through two
REST endpoints that the TypeScript package `@costgraph/computesdk` calls for
you. From Python or any other language, call them directly:

1. Before you create a sandbox, ask CostGraph which of your providers to try
   first with `POST /api/v1/tenant/sandboxes/route`.
2. When a sandbox starts, stops, or fails to start, report it with
   `POST /api/v1/tenant/sandboxes/events`.

You can report sandboxes without routing them. CostGraph then tracks their cost,
and they stay on the providers you chose. These endpoints are for code that
holds its own provider keys. To have CostGraph start sandboxes on the accounts
your team connected on Integrations, refer to
[Run sandboxes on your connected accounts](https://docs.costgraph.ai/costgraph/autopilot/sandboxes-connected.md).

## Requirements

* A CostGraph API key with the `sandbox:route` scope. Create it in
  **Settings > API Keys**.
* Your provider names as ComputeSDK spells them, such as `e2b`, `daytona`,
  `modal`, and `vercel`. CostGraph prices providers by these names.

Send the key in the `X-API-Key` header to `https://api.costgraph.ai`. Responses
wrap their payload in `data`. Refer to the
[CostGraph API introduction](https://docs.costgraph.ai/api-reference/costgraph/introduction.md) for
authentication and the tenant header.

## Choose a provider

Send the size of the new sandbox and your providers in your preferred order.
The first provider is the baseline.

```shell theme={null}
curl https://api.costgraph.ai/api/v1/tenant/sandboxes/route \
  -H "X-API-Key: $COSTGRAPH_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"size_class": "md", "providers": ["e2b", "daytona"]}'
```

The request takes the following fields.

| Field | Description |
| - | - |
| `providers` | Required. Your provider names in your order. Only the first 20 are priced. |
| `size_class` | One of the [sizes](https://docs.costgraph.ai/costgraph/autopilot/sandboxes.md#sizes), from `xs` to `2xl`. |
| `vcpus`, `memory_mib` | A size that is not a standard size. `size_class` wins when you send both. |
| `default_size` | Set to `true` for a sandbox without a size, to price each provider at its own default size. |
| `policy` | `cheapest`, `balanced`, or `fastest`, to override your team's policy for this sandbox. |

The response lists the order to try your providers in. The following example
shows one candidate, with illustrative numbers.

```json theme={null}
{
  "data": {
    "decision_id": "6f1c2a9e-0b7d-4c41-9a53-2f7f4f0f9b11",
    "provider": "daytona",
    "order": ["daytona", "e2b"],
    "reason": "cheapest",
    "expected_seconds": 600,
    "enforced_budget": false,
    "candidates": [
      {
        "provider": "daytona",
        "priced": true,
        "price_per_hour": 0.0828,
        "expected_cost": 0.0138,
        "benchmark_startup_p50_ms": 412,
        "observed_startup_p50_ms": null,
        "startup_source": "benchmark"
      }
    ]
  }
}
```

Try the providers in `order` until one creates the sandbox. Send `decision_id`
back with the sandbox's `started` event. `candidates` holds each provider's
price, expected cost, and start figures, as described in
[Expected cost and start time](https://docs.costgraph.ai/costgraph/autopilot/sandboxes.md#expected-cost-and-start-time).
The [routing endpoint reference](https://docs.costgraph.ai/api-reference/sandboxes/choose-the-provider-for-a-new-sandbox.md)
lists every field and the full order within each policy.

### Reasons

`reason` takes one of the following values.

| Reason | Meaning |
| - | - |
| `cheapest`, `balanced`, `fastest` | The policy moved another provider ahead of the baseline. |
| `no_better_candidate` | No provider fits the policy better than the baseline. |
| `off` | AutoPilot for sandboxes is off. The order is yours. |
| `no_size` | The request had no size and no `default_size`. The order is yours. |
| `baseline_not_priced` | Your first provider has no list price for the size. The order is yours. |
| `budget_exceeded` | A budget set to stop sandboxes is over and covers every provider you sent. `budget_name` names it. Do not start the sandbox. |
| `billing_required` | Your organization's billing needs attention. The order is yours, and `billing_url` links to your billing settings. |
| `rate_limited`, `error` | CostGraph could not choose this time. The order is yours. |

While AutoPilot is off, CostGraph still records each answer, so the
**Sandboxes** tab can show what routing would change.

### Use a short timeout and fall back

The route endpoint answers `200` with your own order whenever it cannot choose.
It answers `400` for an empty `providers` list or invalid JSON, and `403` when
the key lacks the `sandbox:route` scope.

Give the call a short timeout, such as 300 ms. If it times out or fails, create
the sandbox in your own provider order. To avoid a call before every sandbox,
reuse an answer for a few minutes for the same size and provider list.

When `enforced_budget` is `true`, your team has a budget set to stop sandboxes.
Do not start a sandbox while you cannot reach the route endpoint. Refer to the
`enforce` field of [Create a budget](https://docs.costgraph.ai/api-reference/budgets/create-a-budget.md).

## Report sandboxes starting and stopping

Send up to 100 events in one call.

```shell theme={null}
curl https://api.costgraph.ai/api/v1/tenant/sandboxes/events \
  -H "X-API-Key: $COSTGRAPH_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [
      {
        "type": "started",
        "provider": "daytona",
        "sandbox_id": "sbx_123",
        "at": "2026-11-05T12:00:00Z",
        "create_requested_at": "2026-11-05T11:59:58Z",
        "decision_id": "6f1c2a9e-0b7d-4c41-9a53-2f7f4f0f9b11",
        "size_class": "md",
        "metadata": { "agent": "researcher", "run": "run-42" }
      },
      { "type": "stopped", "provider": "daytona", "sandbox_id": "sbx_123", "at": "2026-11-05T12:07:30Z", "reason": "destroyed" },
      { "type": "failed", "provider": "e2b", "at": "2026-11-05T11:59:57Z", "failure_class": "capacity", "detail": "no capacity in region" }
    ]
  }'
```

The response counts the recorded events and lists the rejected ones, as in
`{"data": {"accepted": 3, "rejected": []}}`. Each event takes the following
fields.

| Field | Description |
| - | - |
| `type` | Required. `started`, `stopped`, or `failed`. |
| `provider` | Required. The provider name. |
| `sandbox_id` | The provider's sandbox ID. Required except on `failed`. |
| `at` | The event time in RFC 3339 format. It defaults to now, and a time older than 24 hours counts as 24 hours ago. |
| `create_requested_at` | On `started`, when you sent the create request. AutoPilot measures start time from it. |
| `decision_id` | On `started`, the `decision_id` from the routing answer. It links the sandbox to the answer for savings. |
| `size_class`, or `vcpus` and `memory_mib` | On `started`, the sandbox size. Without one, CostGraph uses the size from `decision_id`, then the provider's default size. |
| `metadata` | On `started`, up to 20 string tags such as `agent`, `run`, and `customer`. Keys can be up to 64 characters and values up to 256. |
| `reason` | On `stopped`, `destroyed` when you ended the sandbox, `timeout` when the provider ended it, or `lost`. |
| `failure_class` | Required on `failed`. `quota`, `capacity`, `auth`, `timeout`, or `other`. |
| `detail` | On `failed`, the provider's error text, up to 2,000 characters. |

CostGraph ignores a repeated `started` or `stopped` event for the same sandbox,
and keeps a stop that arrives before its start for up to 2 days. An invalid
event is listed in `rejected` with its `index` and `problem`, and the others
are recorded. Too many requests answer `429`.

Send a `failed` event for each create a provider refuses, because failed starts
lower the provider's success rate. Send a `stopped` event for every sandbox you
end. A sandbox without one shows as running until its run time reaches 24
hours.

## Python example

The following example uses the `requests` library. `create_sandbox` stands for
your own code. It tries each provider in the order it receives and returns the
provider that created the sandbox and the sandbox's ID.

```python theme={null}
import os
from datetime import datetime, timezone

import requests

API = "https://api.costgraph.ai/api/v1/tenant/sandboxes"
HEADERS = {"X-API-Key": os.environ["COSTGRAPH_API_KEY"]}
PROVIDERS = ["e2b", "daytona"]


def choose_order(size_class: str) -> tuple[list[str], str]:
    try:
        response = requests.post(
            f"{API}/route",
            headers=HEADERS,
            json={"size_class": size_class, "providers": PROVIDERS},
            timeout=0.3,
        )
        response.raise_for_status()
        data = response.json()["data"]
    except (requests.RequestException, KeyError, ValueError):
        return PROVIDERS, ""
    if data["reason"] == "budget_exceeded":
        raise RuntimeError(f"Budget {data.get('budget_name')} is over")
    return data["order"], data["decision_id"]


def report(event: dict) -> None:
    event["at"] = datetime.now(timezone.utc).isoformat()
    try:
        requests.post(f"{API}/events", headers=HEADERS, json={"events": [event]}, timeout=5)
    except requests.RequestException:
        pass


order, decision_id = choose_order("md")
requested_at = datetime.now(timezone.utc).isoformat()
provider, sandbox_id = create_sandbox(order, size_class="md")
started = {
    "type": "started",
    "provider": provider,
    "sandbox_id": sandbox_id,
    "create_requested_at": requested_at,
    "size_class": "md",
    "metadata": {"agent": "researcher", "run": "run-42"},
}
if decision_id:
    started["decision_id"] = decision_id
report(started)

report({"type": "stopped", "provider": provider, "sandbox_id": sandbox_id, "reason": "destroyed"})
```

Call the final `report` when you destroy the sandbox. In a busy service, queue
events and send them in batches of up to 100. If your team has a budget set to
stop sandboxes, raise in the `except` branch instead of falling back.

## Read settings and results

The **Sandboxes** tab reads the following endpoints. You can call them with an
API key that has the `focus:read` scope, or as a signed-in member.

| Endpoint | Returns |
| - | - |
| [`GET /api/v1/tenant/sandboxes/autopilot/settings`](https://docs.costgraph.ai/api-reference/sandboxes/read-autopilot-for-sandboxes-settings) | Whether routing is on, the `policy`, `ready_timeout_seconds`, and `enforced_budget`. |
| [`GET /api/v1/tenant/sandboxes/autopilot/summary`](https://docs.costgraph.ai/api-reference/sandboxes/autopilot-for-sandboxes-summary) | The totals, cost by provider and by tag, and failed starts per provider. |
| [`GET /api/v1/tenant/sandboxes/autopilot/runs`](https://docs.costgraph.ai/api-reference/sandboxes/list-sandboxes) | Every sandbox in the period, newest first, with its stop reason and how its provider was chosen. |
| `GET /api/v1/tenant/sandboxes/autopilot/agent-runs` | The sandbox cost, model cost, and total of each agent run. |

These endpoints take `from` and `to` as `YYYY-MM-DD`, where `to` is the day
after the last day. The default period is the last 30 days.

Admins signed in to CostGraph can change settings with
[`PUT /api/v1/tenant/sandboxes/autopilot/settings`](https://docs.costgraph.ai/api-reference/sandboxes/change-autopilot-for-sandboxes-settings).
Send `enabled` and, optionally, `policy` and `ready_timeout_seconds`. Fields
you leave out keep their current values. `ready_timeout_seconds` applies only
to sandboxes CostGraph starts. Refer to
[Readiness limit](https://docs.costgraph.ai/costgraph/autopilot/sandboxes-connected.md#readiness-limit).

```json theme={null}
{"enabled": true, "policy": "balanced", "ready_timeout_seconds": 45}
```


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