# Partner API reference

Every call your backend makes to train, download and deploy models on Arena, with the fields each one takes and what it returns. The API is the same on hosted Arena and on a self-hosted tenant. For a walk through one model end to end, start with [Your first model](first-model.md).

The `arena` CLI and the Python client call this same API. If your backend is in Python, the client in [Python](#python) saves you writing the HTTP yourself.

## Authentication

AgileRL issues an API host and one organisation key. On a self-hosted tenant, your operator gives you the tenant’s host and key.

| Item             | Example                                            |
|------------------|----------------------------------------------------|
| API host         | `https://arena.agilerl.com`, or your tenant’s host |
| Organisation key | `arena_org_<uuid>_<secret>`                        |

Every request carries two headers. `Authorization` is the organisation key with the `Bearer` prefix. `X-External-User-Id` is the ID your product already uses for the person making the request. Send the same value for that person on every call; the first time Arena sees a new one, it creates a matching user.

```text
Authorization: Bearer arena_org_11111111-2222-3333-4444-555555555555_k7mN9pQ2rS4tU6vW
X-External-User-Id: user-42
```

```bash
export ARENA_BASE="https://arena.agilerl.com"
export ARENA_ORG_KEY="arena_org_11111111-2222-3333-4444-555555555555_k7mN9pQ2rS4tU6vW"
export ARENA_USER="user-42"
```

Training calls are under `/api/cli/v1/…`. Model download is under `/api/internal/partners/…`. Both take the same headers.

Most `/api/cli/v1` replies look like `{ "ok": true, "data": … }`. The default training spec, the model list, model info and every `/api/internal/partners` route return the JSON object itself, without that wrapper.

Submit and environment upload stream one JSON object per line. Read the stream until `"status"` is `completed` or `failed`.

A `429` with `Retry-After` (seconds) means slow down. A job that belongs to another organisation returns `404`.

Keep the key on your backend. Never send it to a browser.

## Order of calls

1. `GET /api/cli/v1/resources`: confirms the key and lists GPU types.
2. `POST /api/cli/v1/datasets/create`.
3. Only to train against an environment instead of a dataset: `POST /api/cli/v1/environments/create-and-validate`.
4. `POST /api/cli/v1/projects/create`.
5. `GET /api/cli/v1/models` or `POST /api/cli/v1/models/info`.
6. `GET /api/cli/v1/experiments/run-spec/default`.
7. Set `algorithm.batch_size`, `algorithm.lr`, `network.max_context_length` and `training.checkpoint_export` on that body, and optionally `training.max_steps`.
8. `POST /api/cli/v1/experiments/jobs/submit`. The `experiment_name` you send is the handle for later calls.
9. `GET /api/cli/v1/experiments/jobs/checkpoints`, repeated until `data[]` has a row.
10. `POST /api/internal/partners/checkpoint-exports` with `{ "experimentName", "steps" }`, then fetch each `urls[]` entry and check `files[].bytes` and `files[].sha256`.
11. Optional, to serve the model: `POST /api/cli/v1/inference/deploy`, then `GET /api/cli/v1/inference/deployments/one?name=…` until `status` is `Deployed`.

## GPU type

A resource is a machine: GPU count, memory and, on hosted Arena, an hourly cost. Listing them is a good first call because it also confirms the key.

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/resources" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}"
```

```json
{
  "ok": true,
  "data": {
    "gpuTypes": [
      { "gpuType": "h100-80", "gpusPerNode": [1, 8], "numGpus": [1, 8] }
    ]
  }
}
```

Each entry is a GPU type that submit accepts as `gpu_type`, with the GPUs one node has and the totals you can ask for as `num_gpus`. The list is for language model training; add `?algorithm=<name>` for another algorithm. `GET /api/cli/v1/resources/list` returns the same payload.

Submit does not take a resource or a node count. Arena estimates the run’s GPU memory and picks the cheapest machines and node count that fit. To steer the pick, send `num_gpus` (GPUs in total), `gpu_type`, or both; Arena still picks only among layouts that fit. See [Submit](#submit).

On a self-hosted tenant the list holds only the tenant’s reserved GPUs, and Arena charges nothing for them.

## Data

Training data is a table. The `category` decides what each row means:

| `category`   | Each row                          | Mapping keys                   |
|--------------|-----------------------------------|--------------------------------|
| `reasoning`  | Question and reference answer     | `question`, `answer`           |
| `sft`        | Prompt and the reply to copy      | `prompt`, `target`             |
| `preference` | Prompt, better reply, worse reply | `prompt`, `chosen`, `rejected` |

[Upload a dataset](../guides/upload-a-dataset.md) describes each format in more detail.

`column_mapping` uses Arena’s names as keys and your column names as values. If your file has `instruction` and `response`, send `{"prompt":"instruction","target":"response"}`.

Send the file and the fields in one `multipart/form-data` request. On hosted Arena the upload can be up to 1 GB. On a self-hosted tenant the stored file can be at most 64 MiB, and Hugging Face datasets and dataset search return `400 huggingface_offline`, since the tenant has no internet access.

### Parquet folders

Hugging Face datasets often ship several `.parquet` files in folders. Arena names the **config** from the folder left after shared prefixes:

- `main/train-00000-of-00001.parquet` becomes config `main`. Train or test comes from the file name.
- `train-00000-of-00001.parquet` at the top of the upload becomes config `default`.
- A wrapping folder is dropped: `gsm8k/main/train-00000-of-00001.parquet` is treated as `main/…`.

Folders named `train/` and `test/` become two configs, not two splits. Put the split in the file name instead, for example `train-00000-of-00001.parquet`.

If the upload has more than one config, send form field `config` (for example `main`). Send each parquet file as its own `file` part, with the part filename set to its relative path. When the chosen config has several splits, Arena trains on `train`, or on the only split when there is one. Several splits with none named `train` fail the upload.

A single CSV also works. A part counts as parquet if its name ends in `.parquet`, its type is `application/vnd.apache.parquet` or `application/parquet`, or its bytes start with `PAR1`.

### SFT

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/datasets/create" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -F "name=support-tickets-sft" \
  -F "category=sft" \
  -F "description=Support replies for supervised fine-tune" \
  -F 'column_mapping={"prompt":"instruction","target":"response"}' \
  -F "config=main" \
  -F "file=@./main/train-00000-of-00001.parquet;filename=main/train-00000-of-00001.parquet;type=application/vnd.apache.parquet"
```

```json
{
  "ok": true,
  "data": {
    "name": "support-tickets-sft",
    "category": "sft",
    "uploaded": true,
    "is_ready": true,
    "hf_dataset_id": null
  }
}
```

Submit once `is_ready` is `true`. If the reply has `missing_columns`, fix `column_mapping` and upload again. A `400` from parsing or column mapping leaves no dataset behind.

On a self-hosted tenant, an upload while the GPU cluster is offline returns `409 gpu_cluster_unavailable` and creates no dataset. Upload again once the cluster is back.

### Reasoning

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/datasets/create" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -F "name=math-word-problems" \
  -F "category=reasoning" \
  -F 'column_mapping={"question":"question","answer":"answer"}' \
  -F "file=@./train-00000-of-00001.parquet;filename=train-00000-of-00001.parquet;type=application/vnd.apache.parquet"
```

### Preference

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/datasets/create" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -F "name=assistant-prefs" \
  -F "category=preference" \
  -F 'column_mapping={"prompt":"prompt","chosen":"chosen","rejected":"rejected"}' \
  -F "file=@./main/train-00000-of-00001.parquet;filename=main/train-00000-of-00001.parquet;type=application/vnd.apache.parquet"
```

### Check, list and delete datasets

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/datasets/exists?name=support-tickets-sft" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}"
```

```json
{ "ok": true, "data": { "exists": true, "datasetType": "sft" } }
```

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/datasets" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}"
```

```json
{
  "ok": true,
  "data": [
    {
      "name": "support-tickets-sft",
      "hf_dataset_id": null,
      "category": "sft",
      "training_row_count": 1200
    }
  ]
}
```

`training_row_count` is `null` until Arena has counted the rows. On hosted Arena, `?search=gsm8k` searches the Hugging Face Hub.

```bash
curl -sS -X DELETE "${ARENA_BASE}/api/cli/v1/datasets/delete" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" \
  -d '{"name":"support-tickets-sft"}'
```

## Environments

An environment is Python code that plays out a task with the model, instead of a table of examples. Skip this section when you train on a dataset. [Upload an environment](../guides/upload-an-environment.md) explains how to write one.

Upload a gzip of the package with its `requirements.txt`. The reply is a status stream while Arena installs the packages and checks the code.

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/environments/create-and-validate" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -F "name=ticket-sim" \
  -F "version=v1" \
  -F "multi_agent=false" \
  -F "language_based=true" \
  -F "do_rollouts=true" \
  -F "description=Turn-based support sim" \
  -F "file=@./ticket_sim.tar.gz;type=application/gzip" \
  -F "env_config=@./env_config.yaml;type=application/x-yaml" \
  -F "requirements=@./requirements.txt;type=text/plain"
```

Send `env_config` and `requirements` every time; empty files are fine. If the tarball has one environment class, you can leave out `entrypoint` and Arena stores the name it finds.

List environments and the entrypoints Arena found:

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/environments" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}"

curl -sS "${ARENA_BASE}/api/cli/v1/environments/entrypoints?name=ticket-sim&version=v1" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}"
```

`data` is an array of strings such as `["env:TicketEnv"]`. Only those strings are valid entrypoints for that upload; any other name is `INVALID_ENTRYPOINT`. Send one as `gymEnvEntrypoint` on the default spec query, and as `entrypoint` when you validate the version again.

To validate a stored version again, send JSON:

```bash
curl -sS -X POST "${ARENA_BASE}/api/cli/v1/environments/validate" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" \
  -d '{"name":"ticket-sim","version":"v1","entrypoint":"env:TicketEnv","do_rollouts":false}'
```

`name` is required; `version`, `entrypoint` and `do_rollouts` are optional. Multipart on this route returns `415`.

Point a training spec at the environment once `validated` is `true`. `?include_arena=true` on the list adds Arena’s built-in environments.

## Projects

A project groups training runs.

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/projects/create" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "post-train",
    "description": "Partner post-training"
  }'
```

Projects created here are always for language-model runs: `llm_based` is ignored.

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/projects" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}"
```

A duplicate name returns `400` `The project 'post-train' already exists.` List your projects and reuse them.

## Base models

Runs start from a base model in Arena’s catalogue. On a self-hosted tenant the catalogue is the models your operator registered ([Base models](self-hosted/models.md)).

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/models" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}"
```

The reply is a JSON array, one entry per model. Here it is with `lora_info` trimmed to four of the model’s layers:

```json
[
  {
    "model_name": "Qwen/Qwen3.5-4B",
    "architecture": "hybrid",
    "num_params": 4539265536,
    "lora_info": {
      "q_proj": [
        {
          "count": 8,
          "in_features": 2560,
          "kind": "module",
          "out_features": 8192,
          "scope": "model.language_model.layers.self_attn",
          "type": "Linear"
        }
      ],
      "k_proj": [
        {
          "count": 8,
          "in_features": 2560,
          "kind": "module",
          "out_features": 1024,
          "scope": "model.language_model.layers.self_attn",
          "type": "Linear"
        }
      ],
      "v_proj": [
        {
          "count": 8,
          "in_features": 2560,
          "kind": "module",
          "out_features": 1024,
          "scope": "model.language_model.layers.self_attn",
          "type": "Linear"
        }
      ],
      "o_proj": [
        {
          "count": 8,
          "in_features": 4096,
          "kind": "module",
          "out_features": 2560,
          "scope": "model.language_model.layers.self_attn",
          "type": "Linear"
        }
      ]
    },
    "max_context_length": 262144,
    "lora_ranks": [1, 8, 16, 32],
    "status": "live",
    "modalities": ["text", "vision"]
  }
]
```

`lora_info` lists the layers LoRA can adapt. LoRA trains a small extra set of weights on top of the base model. Its sizes (`lora_r`, `lora_alpha`, `lora_dropout`) are set later, in `network.lora_config` on the spec.

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/models/info" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" \
  -d '{"model_name":"Qwen/Qwen3.5-4B"}'
```

The reply, with `lora_info` trimmed the same way:

```json
{
  "modules": ["down_proj", "gate_proj", "in_proj_a", "in_proj_b", "in_proj_qkv", "in_proj_z", "k_proj", "linear_fc1", "linear_fc2", "o_proj", "out_proj", "q_proj", "qkv", "up_proj", "v_proj"],
  "parameters": [],
  "lora_info": {
    "q_proj": [
      {
        "count": 8,
        "in_features": 2560,
        "kind": "module",
        "out_features": 8192,
        "scope": "model.language_model.layers.self_attn",
        "type": "Linear"
      }
    ],
    "k_proj": [
      {
        "count": 8,
        "in_features": 2560,
        "kind": "module",
        "out_features": 1024,
        "scope": "model.language_model.layers.self_attn",
        "type": "Linear"
      }
    ],
    "v_proj": [
      {
        "count": 8,
        "in_features": 2560,
        "kind": "module",
        "out_features": 1024,
        "scope": "model.language_model.layers.self_attn",
        "type": "Linear"
      }
    ],
    "o_proj": [
      {
        "count": 8,
        "in_features": 4096,
        "kind": "module",
        "out_features": 2560,
        "scope": "model.language_model.layers.self_attn",
        "type": "Linear"
      }
    ]
  },
  "num_params": 4539265536,
  "max_context_length": 262144,
  "lora_ranks": [1, 8, 16, 32]
}
```

Pass `model_name` into the spec query exactly as listed. An unknown name returns `404`. Empty `modules` and `parameters` means the catalogue entry is incomplete; contact AgileRL.

## Default training spec

Arena builds the training JSON from an algorithm, a dataset and a base model. The reply is the starting point for `manifest` on submit. The field names are in the [run spec schema](../cli/manifest-schema.md), and the algorithms are described in [Algorithms](../reference/algorithms.md).

| `algorithm`    | Data                                                                             | Submit body                                                                   |
|----------------|----------------------------------------------------------------------------------|-------------------------------------------------------------------------------|
| `SFT`          | `sft` dataset                                                                    | JSON                                                                          |
| `DPO`          | `preference` dataset                                                             | JSON                                                                          |
| `CISPO`        | `reasoning` dataset, or an environment                                           | Multipart with `reward_file` on a reasoning dataset; JSON with an environment |
| `GRPO`         | Same as CISPO                                                                    | Same as CISPO                                                                 |
| `GSPO`         | Same as CISPO                                                                    | Same as CISPO                                                                 |
| `LLMPPO`       | `reasoning` dataset (`advantage_granularity` `token`) or an environment (`turn`) | `reward_file` on a reasoning dataset                                          |
| `LLMREINFORCE` | Same as LLMPPO                                                                   | Same as LLMPPO                                                                |

Query parameters: `algorithm` (required), `datasetName`, `pretrainedModelNameOrPath`. For an environment, send `gymEnv`, `gymEnvVersion` and `gymEnvEntrypoint` instead of `datasetName`. `gymEnvEntrypoint` is a name from the entrypoints list, and when you send it, `gymEnv` and `gymEnvVersion` (`v1` and `1` both work) are required too. Optional `field` returns one section (`algorithm`, `environment`, `network`, `training`, …).

```bash
curl -sS -G "${ARENA_BASE}/api/cli/v1/experiments/run-spec/default" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  --data-urlencode "algorithm=CISPO" \
  --data-urlencode "datasetName=math-word-problems" \
  --data-urlencode "pretrainedModelNameOrPath=Qwen/Qwen3.5-4B"
```

For SFT, send `algorithm=SFT` with an `sft` dataset; for DPO, `algorithm=DPO` with a `preference` dataset. The reply:

```json
{
  "algorithm": {
    "adv_filter_eps": 0.0,
    "adv_norm": "mean_only",
    "advantage_granularity": "auto",
    "answer_continuation": false,
    "beta": 0.001,
    "calc_position_embeddings": true,
    "clip_coef": 0.2,
    "filter_zero_adv": false,
    "group_size": 8,
    "kl_clamp": 10.0,
    "loss_norm": "accumulation_window",
    "loss_type": "cispo",
    "lr": 5e-07,
    "max_grad_norm": 0.1,
    "min_p": 0.0,
    "name": "CISPO",
    "off_policy_sequence_mask_threshold": 0.03,
    "off_policy_token_mask_bounds": [
      0.5,
      5.0
    ],
    "repetition_penalty": 1.0,
    "seed": 42,
    "temperature": 0.9,
    "top_k": 50,
    "top_p": 1.0,
    "turn_advantage_trajectory_fallback": true,
    "update_epochs": 1,
    "use_bias_correction_kl": true,
    "use_kl_advantage_shaping": false,
    "use_separate_reference_adapter": true,
    "vllm_config": {
      "frequency_penalty": 0.0,
      "presence_penalty": 0.0
    },
    "vllm_engine_args": {},
    "vllm_importance_sampling_cap": 2.0,
    "vllm_max_clip_fraction": 0.02,
    "vllm_max_logprob_gap": 0.1,
    "whiten_advantages": false
  },
  "apiVersion": "agilerl.com/v1",
  "environment": {
    "action_error_field": "",
    "adaptive_task_sampling": true,
    "apply_chat_template": true,
    "chat_template_kwargs": {},
    "columns": {
      "answer": "answer",
      "question": "question"
    },
    "dataset": "math-word-problems",
    "env_services": [],
    "env_session_ports": {},
    "env_type": "rollout",
    "env_vars": {},
    "max_reward": 1.0,
    "max_turns": 1,
    "name": "math-word-problems",
    "num_envs": 1,
    "prompt_template": {
      "system_prompt": "A conversation between User and Assistant. The user asks a question, and the Assistant solves it. The assistant first thinks about the reasoning process in the mind and then provides the user with the answer. The reasoning process and answer are enclosed within <think> </think> and <answer> </answer> tags, respectively, i.e., <think> reasoning process here </think><answer> answer here </answer>",
      "user_prompt": "Answer the following question as accurately, clearly, and concisely as possible.\n\nQuestion: {question}\n"
    },
    "repeat_system_prompt": false,
    "restart_keep_turns": 0,
    "restart_older_images": true,
    "restart_older_obs_field": "",
    "rubric_file_path": "reward.py",
    "strict_chat_template_boundary": true,
    "task_family_prior_strength": 1.0,
    "train_test_split": 0.9
  },
  "network": {
    "lora_config": {
      "lora_alpha": 32,
      "lora_dropout": 0.0,
      "lora_r": 16,
      "task_type": "CAUSAL_LM"
    },
    "max_context_length": 262144,
    "pretrained_model_name_or_path": "Qwen/Qwen3.5-4B"
  },
  "replay_buffer": {
    "drop_uninformative_groups": true,
    "group_replay_max_age": 20,
    "kind": "llm",
    "max_rollout_version_lag": 2,
    "max_size": 10000
  },
  "training": {
    "checkpoint_optimizer": true,
    "eval_greedy": true,
    "eval_loop": 1,
    "eval_samples_per_task": 0,
    "evaluation_interval": 10,
    "evo_steps": 20,
    "overwrite_checkpoints": false,
    "pop_size": 1,
    "reporting_interval": 1,
    "rollout_version_stamp": "oldest_turn"
  }
}
```

Language model replies include `network.lora_config`: `lora_r` 16, `lora_alpha` 32, `lora_dropout` 0.0 and `task_type` `CAUSAL_LM`. Keep it as Arena filled it. Arena trains LoRA on the catalogue’s modules for the model and drops any `target_modules` you send. For `network.lora_config.target_parameters`, an explicit `[]` means no LoRA on mixture-of-experts expert weights; leave the key out or send `null` to fill it from the catalogue.

Before submitting, change only these fields and keep the rest of the reply:

| Field                           | Example                                                                                       |
|---------------------------------|-----------------------------------------------------------------------------------------------|
| `algorithm.batch_size`          | `8`                                                                                           |
| `algorithm.lr`                  | `0.0001`                                                                                      |
| `network.max_context_length`    | `2048`                                                                                        |
| `training.checkpoint_export`    | `{ "format": "merged", "trigger": "final" }` or `{ "format": "adapter", "trigger": "final" }` |
| `training.max_steps` (optional) | `500`                                                                                         |

Arena checks them on validate and on submit:

- `network.max_context_length` is a power of 2 from 1024 up to the model’s `max_context_length` from [Base models](#base-models), or that maximum itself when it isn’t a power of 2. Otherwise `400`, for example `network.max_context_length must be a power of 2 between 1024 and 262144. Allowed: 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144`.
- `algorithm.batch_size` is a power of 2. The `400` lists the allowed values.
- `training.max_steps` must be at least `training.evo_steps` (20 for the language model algorithms). Language model runs are sized in steps; `training.num_epochs` returns `400`. Leave `max_steps` unset on a dataset run to train one pass over the dataset: the row count divided by `algorithm.batch_size`, rounded up.
- `training.checkpoint_export.format` `merged` gives the Hugging Face model in [Download the trained model](#download-the-trained-model); `adapter` gives a LoRA adapter. Without it, Arena uses `merged` with `trigger` `final`.

### Check a run fits

`POST /api/cli/v1/experiments/validate-run-spec` checks context length, batch size and whether the run fits a resource:

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/experiments/validate-run-spec" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" -d @run-spec.json
```

A run that doesn’t fit returns `400 run_does_not_fit`. When a larger node count of the same class holds it, `required.gpus` is the fewest GPUs that do and `required.num_nodes` is that layout’s node count:

```json
{
  "ok": false,
  "error": "run_does_not_fit",
  "message": "Resource class 'b300-8x1' does not fit this run at 1 node(s).",
  "required": { "gpus": 16, "num_nodes": 2, "gpu_memory_gb": 210.0 },
  "available": { "resource": "b300-8x1", "gpus": 8, "num_nodes": 1, "gpu_memory_gb": 260.0 }
}
```

When no node count of that class holds it, `required.gpus` and `required.num_nodes` are present and `null`, and `required.gpu_memory_gb` is what the run needs per GPU at the count it asked for. Branch on `null`. When the spec names no class and the miss is GPU memory, `message` is `No resource class has enough GPU memory for this run at N node(s).` and `available` is the closest class.

Show the result to your user with a suggestion: a smaller model, a shorter context, or a smaller batch.

A classic RL manifest (DQN, PPO, CQN, …) gets `410 classic_rl_gone`, as on quote and submit.

## Submit

`POST /api/cli/v1/experiments/jobs/submit`

| Field             | Required   | Example                                                       |
|-------------------|------------|---------------------------------------------------------------|
| `manifest`        | yes        | The spec from [Default training spec](#default-training-spec) |
| `project`         | yes        | `"post-train"` (`projectName` also works)                     |
| `experiment_name` | no         | `"cispo-qwen-4b-dev"`                                         |
| `num_gpus`        | no         | `4` (`numGpus` also works)                                    |
| `gpu_type`        | no         | `"h100-80"` (`gpuType` also works)                            |
| `idempotency_key` | no         | See [Retries](#retries)                                       |

Without `num_gpus` or `gpu_type`, Arena picks the cheapest GPU type and count that the run’s memory estimate fits. With `num_gpus`, it picks the cheapest type at that count; with `gpu_type`, the smallest count of that type that fits. A request that doesn’t fit fails, and with `num_gpus` the message names the smallest count that fits. An unknown `gpu_type` fails and lists the valid names. `resource_id` and `num_nodes` return `400`.

Arena trains on the dataset that `manifest.environment.dataset` names. Without `dataset`, it trains on what `environment.name` names, a registered dataset or an environment; the SFT example below sends only `name`. The default spec sets both to the dataset’s name. With `dataset` set, `name` is only a label, unless it names a different registered dataset: that returns `400` `environment.dataset is '<dataset>' but environment.name is '<name>', a different dataset. Set both to the dataset to train on, or remove environment.name.` A manifest with neither returns `400` `manifest.environment needs a name: set environment.dataset to a registered dataset, or environment.name`.

### SFT

```bash
curl -sS -N "${ARENA_BASE}/api/cli/v1/experiments/jobs/submit" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: user-42:sft-qwen-4b-dev:1" \
  -d '{
    "experiment_name": "sft-qwen-4b-dev",
    "project": "post-train",
    "manifest": {
      "algorithm": { "name": "SFT", "lr": 0.0001, "batch_size": 8 },
      "environment": { "name": "support-tickets-sft", "num_envs": 16 },
      "network": {
        "pretrained_model_name_or_path": "Qwen/Qwen3.5-4B",
        "max_context_length": 2048,
        "lora_config": { "lora_r": 16, "lora_alpha": 32, "lora_dropout": 0.0 }
      },
      "training": { "max_steps": 500, "eval_loop": 1 }
    }
  }'
```

The `manifest` here is shortened. Send the whole object from the default spec.

### Reasoning, with a reward file

CISPO, GRPO and GSPO on a reasoning dataset also need a Python module that scores answers. Send it as `reward_file`, with the spec as the `manifest` part:

```bash
curl -sS -N "${ARENA_BASE}/api/cli/v1/experiments/jobs/submit" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Idempotency-Key: user-42:cispo-qwen-4b-dev:1" \
  -F "experiment_name=cispo-qwen-4b-dev" \
  -F "project=post-train" \
  -F "manifest=@./cispo-run-spec.json;type=application/json" \
  -F "reward_file=@./reward.py;type=text/x-python"
```

`reward.py` defines `def reward_fn(question, answer, completion)` and returns a float. [Prompts and rewards](../guides/prompts-and-rewards.md) has examples. If the reward check fails, the stream’s `detail` includes `results` and `function_output`.

### Stream

```text
{"kind":"status","stage":"validation","status":"running","message":"Validating manifest for math-word-problems:latest with CISPO","timestamp":"2026-09-07T09:15:01Z"}
{"kind":"status","stage":"submission","status":"running","message":"Creating experiment","timestamp":"2026-09-07T09:15:02Z"}
{"kind":"status","stage":"submission","status":"running","message":"Submitting to scheduler","timestamp":"2026-09-07T09:15:04Z"}
{"kind":"status","stage":"submission","status":"completed","message":"Training job for 'cispo-qwen-4b-dev' submitted successfully","timestamp":"2026-09-07T09:15:05Z"}
```

A job that never reached GPUs ends like this:

```text
{"kind":"status","stage":"submission","status":"failed","message":"Job rejected","detail":{"error_code":"JOB_REJECTED"}}
```

That usually means an incomplete catalogue entry or a dataset that isn’t ready. Fix the cause, then submit again with a new `Idempotency-Key` or none.

On submit, `run_does_not_fit` and, on a self-hosted tenant, `gpu_cluster_unavailable` arrive as `detail.error_code` on the final `failed` line rather than as an HTTP status:

```json
{"stage":"submission","status":"failed","message":"Experiment submission failed: …","detail":{"error_code":"gpu_cluster_unavailable","cluster":"tenant-a-gpus"}}
```

### Retries

Send `Idempotency-Key` as a header, or `idempotency_key` in the JSON body. The value must be unique across the organisation, so prefix it with your user ID, for example `user-42:cispo-qwen-4b-dev:1`.

| Request                                                | Arena response                     |
|--------------------------------------------------------|------------------------------------|
| Same key and body, last time succeeded                 | Same experiment, no second GPU job |
| Same key and body, last time failed and can be retried | New experiment                     |
| Same key, different body                               | `409 idempotency_conflict`         |
| Same key, first call still running                     | `409 idempotency_in_progress`      |
| No key                                                 | Always a new job                   |

## Status, stop and resume

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/experiments/list?project=post-train" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}"
```

```json
{
  "ok": true,
  "data": [
    {
      "experiment_name": "cispo-qwen-4b-dev",
      "environment": "math-word-problems",
      "algorithm": "CISPO",
      "last_modified": "2026-09-07T10:02:11+00:00",
      "status": "Running",
      "status_label": "Running"
    }
  ]
}
```

`status` is one of the [experiment statuses](../reference/experiment-statuses.md): `Queued`, `Pending`, `Running`, `Stopping`, `Stopped`, `Succeeded` or `Failed`. A `Queued` job starts on its own when GPUs free up, in submit order; don’t retry it. `status_label` is the text Arena shows for the run: “Waiting for capacity” while it waits for GPUs, “Waiting for cluster upgrade” while its cluster’s agent upgrades, “Starting <gpu> GPUs (~N min)” while new machines start, then the cluster’s stage (`Scheduled`, `Deployed`, `Running`) while the job starts, otherwise `status`.

A `Failed` row also has `failure_reason`, one or two sentences on why the run stopped, such as `"Training stopped because your code raised an error: reward.py, line 8"`. Show it to the run’s owner.

```bash
curl -sS -X POST "${ARENA_BASE}/api/cli/v1/experiments/jobs/stop" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" \
  -d '{"experiment_name":"cispo-qwen-4b-dev"}'
```

A stop takes effect within seconds. Resume starts a new run from a checkpoint of an old one. `checkpoint` is `best`, `final` or a step number:

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/experiments/jobs/resume" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" \
  -d '{
    "experiment_name": "cispo-qwen-4b-dev",
    "checkpoint": "final",
    "new_name": "cispo-qwen-4b-dev-resume",
    "max_steps": 2000
  }'
```

`max_steps` is optional. It is the total step count from the start of the original run, so it must be greater than the checkpoint’s step.

The reply is JSON, not a stream like submit: `{"ok": true, "data": [{"submissionId": null}]}`. `submissionId` is `null` on this response. Read the new run’s status from `experiments/list`.

## Metrics

Metrics are the numbers the job logs, such as score and learning rate. `experiment_name` is required; `project` is optional.

```bash
curl -sS -G "${ARENA_BASE}/api/cli/v1/experiments/metrics" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  --data-urlencode "experiment_name=cispo-qwen-4b-dev" \
  --data-urlencode "project=post-train"
```

```json
{
  "ok": true,
  "data": [
    { "display_name": "Score", "category": "training" },
    { "display_name": "Learning Rate", "category": "hyperparam" }
  ]
}
```

`display_name` is the chart label. `category` is `training`, `hyperparam`, `network`, `resource` or `null`. With `details=true` the list comes back as `data.metrics`.

Add `preview_rows` (up to 50,000) to get the values as CSV instead. Send `metric=Score` for one column, repeat `metric` for several, or leave it out for all of them:

```bash
curl -sS -G "${ARENA_BASE}/api/cli/v1/experiments/metrics" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  --data-urlencode "experiment_name=cispo-qwen-4b-dev" \
  --data-urlencode "preview_rows=500" \
  --data-urlencode "metric=Score"
```

```text
Score
0.12
0.18
0.21
```

An empty list means nothing has been logged yet. Ask again after a short wait.

## Checkpoints

A checkpoint is a snapshot of the model at a training step. List them until a row appears; empty `data` means there is no snapshot yet.

```bash
curl -sS -G "${ARENA_BASE}/api/cli/v1/experiments/jobs/checkpoints" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  --data-urlencode "experiment_name=cispo-qwen-4b-dev"
```

```json
{
  "ok": true,
  "data": [
    {
      "steps": 500,
      "training_score": null,
      "evaluation_score": null,
      "size_mb": 14200.5
    }
  ]
}
```

`steps` is how far training had got, and is what you pass to download and deploy. If two snapshots share a step count, Arena keeps the newest. Scores are often `null` until metrics catch up. Rows sort by evaluation score when there is one, otherwise by `steps`, largest first. [Results and checkpoints](../guides/results-and-checkpoints.md) shows the same list in the web app.

## Download the trained model

1. Keep the `experiment_name` you sent on submit.
2. List checkpoints until `data[]` has a `steps` value.
3. POST an export with `{ "experimentName", "steps" }`, then fetch each `urls[]` entry.

Download replies have no `{ ok, data }` wrapper and use camelCase field names. `experiment_name` is also accepted in the request body. Add `projectName` when the same experiment name exists in more than one project.

```bash
curl -sS -X POST \
  "${ARENA_BASE}/api/internal/partners/checkpoint-exports" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" \
  -d '{"experimentName":"cispo-qwen-4b-dev","steps":500}'
```

Arena copies the files and returns HTTPS links that last about 15 minutes. If the checkpoint is 32 MiB or less, the POST reply already has `files` and `urls`. For a larger one, `state` is `queued` or `running` and `files` is empty; poll with GET until it completes. GET only reads the state; the POST starts the copy. There is one copy per organisation and checkpoint at a time: a second POST while it runs returns the same copy, and a POST after it completes reuses it and refreshes expired links.

```json
{
  "format": "hf_merged",
  "state": "running",
  "acceptRanges": "bytes",
  "files": [],
  "urls": []
}
```

```bash
curl -sS -G "${ARENA_BASE}/api/internal/partners/checkpoint-exports" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  --data-urlencode "experimentName=cispo-qwen-4b-dev" \
  --data-urlencode "steps=500"
```

| `state`                     | Next                                                           |
|-----------------------------|----------------------------------------------------------------|
| `queued` or `running`       | Wait a few seconds, GET again                                  |
| `complete`                  | Download `urls`                                                |
| `409 export_renew_required` | Renew, then download                                           |
| `failed` or `cancelled`     | POST the export again (cancel first if it was stuck `running`) |

Large models take minutes. Polling every few seconds is enough. When complete (trimmed; every `files[].key` has a matching `urls[]` entry):

```json
{
  "format": "hf_merged",
  "state": "complete",
  "acceptRanges": "bytes",
  "files": [
    {
      "key": "config.json",
      "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
      "bytes": 1240,
      "contentType": "application/json"
    },
    {
      "key": "model.safetensors",
      "sha256": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
      "bytes": 988000000,
      "contentType": "application/octet-stream"
    }
  ],
  "urls": [
    {
      "key": "config.json",
      "url": "https://storage.example/config.json?X-Amz-Expires=900&X-Amz-Signature=…",
      "expiresAt": "2026-09-07T10:20:00Z"
    },
    {
      "key": "model.safetensors",
      "url": "https://storage.example/model.safetensors?X-Amz-Expires=900&X-Amz-Signature=…",
      "expiresAt": "2026-09-07T10:20:00Z"
    }
  ]
}
```

A merged model has `config.json`, `generation_config.json`, `chat_template.jinja`, `tokenizer.json`, `tokenizer_config.json` and `model.safetensors` (or `model-0000N-of-0000M.safetensors` when it is sharded). On a self-hosted tenant the links point at the tenant’s object store.

If the links have expired, GET returns `409 export_renew_required`. Renew them:

```bash
curl -sS -X POST \
  "${ARENA_BASE}/api/internal/partners/checkpoint-exports/renew" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" \
  -d '{"experimentName":"cispo-qwen-4b-dev","steps":500}'
```

The reply is the same JSON with new `urls`. Links support ranges (`acceptRanges` is `bytes`), so a download can resume with `Range` or `curl -C -`:

```bash
curl -sS -C - -o config.json \
  "https://storage.example/config.json?X-Amz-Expires=900&X-Amz-Signature=…"

curl -sS -H "Range: bytes=0-10485759" -o shard.part0 \
  "https://storage.example/model.safetensors?X-Amz-Expires=900&X-Amz-Signature=…"
```

Check `files[].sha256` and `files[].bytes` for each file. If a link expires halfway through a file, renew and carry on from where you stopped.

If a copy is stuck `running`, cancel it and POST the export again:

```bash
curl -sS -X POST \
  "${ARENA_BASE}/api/internal/partners/checkpoint-exports/cancel" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" \
  -d '{"experimentName":"cispo-qwen-4b-dev","steps":500}'
```

Cancelling a queued or running copy deletes it, and its links stop working. Cancelling after `complete` returns the existing links, or `409 export_renew_required` if they have expired.

## Deploy the model

A deployment serves one checkpoint of a finished run behind an HTTPS endpoint. Every reply has the `{ "ok": true, "data": … }` wrapper and snake_case field names.

| Call                                       | Route                                        |
|--------------------------------------------|----------------------------------------------|
| Deploy, or redeploy another checkpoint     | `POST /api/cli/v1/inference/deploy`          |
| List                                       | `GET /api/cli/v1/inference/deployments/list` |
| Read one                                   | `GET /api/cli/v1/inference/deployments/one`  |
| Rename, describe, take offline, bring back | `PATCH /api/cli/v1/inference/deployments`    |
| Delete                                     | `DELETE /api/cli/v1/inference/deployments`   |

The deployment `name` is its handle. Names are unique in the organisation among deployments that haven’t been deleted; a clash returns `400` `A deployment with this name already exists in this organization`. An experiment has at most one enabled deployment, so deploying the same experiment again updates that deployment.

### Deploy

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/inference/deploy" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" \
  -d '{
    "experimentName": "sft-qwen-4b-dev",
    "name": "support-bot",
    "description": "Support replies, SFT on Qwen3.5 4B"
  }'
```

| Field                | Required   | Notes                                                                                                                           |
|----------------------|------------|---------------------------------------------------------------------------------------------------------------------------------|
| `experimentName`     | yes        | `experiment_name` also works                                                                                                    |
| `projectName`        | no         | `project` also works. Needed when the experiment name exists in more than one project.                                          |
| `checkpoint`         | no         | Left out, `best` or `final`: the checkpoint with the most steps. A number: that `steps` value from [Checkpoints](#checkpoints). |
| `name`               | no         | Defaults to the experiment name                                                                                                 |
| `description`        | no         | Free text                                                                                                                       |
| `memoryScope`        | no         | `user` (default) or `organization`. See [Memory scope](#memory-scope).                                                          |
| `numGpus`, `gpuType` | no         | See [GPUs](#gpus)                                                                                                               |
```json
{
  "ok": true,
  "data": {
    "created": true,
    "redeployed": false,
    "unchanged": false,
    "deployment": {
      "name": "support-bot",
      "status": "Pending",
      "enabled": true,
      "experiment_name": "sft-qwen-4b-dev",
      "project_name": "post-train",
      "algorithm": "SFT",
      "url": "https://6604b462e6fb4523b68cb6f28117d9b8.deploy.example",
      "description": "Support replies, SFT on Qwen3.5 4B",
      "memory_scope": "user",
      "spec": {
        "url": "https://6604b462e6fb4523b68cb6f28117d9b8.deploy.example",
        "is_llm": true,
        "model": { "algorithm_name": "SFT" }
      }
    }
  }
}
```

A new deployment of a run trained on a dataset also returns `savedModel` (`name`, `description`, `source_checkpoint_steps`, `algorithm_name`). Exactly one of `created`, `redeployed` and `unchanged` is `true`:

| Flag         | Meaning                                                                                                                                                                                                                                                                   |
|--------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `created`    | New deployment                                                                                                                                                                                                                                                            |
| `redeployed` | The experiment already had an enabled deployment, or a stopped (not archived) one with the requested name, and this request changed it, for example to another `checkpoint`. A stopped deployment is enabled again. It keeps its name unless you send a different `name`. |
| `unchanged`  | Same request as last time. Nothing restarts.                                                                                                                                                                                                                              |

A redeploy without `description` keeps the stored one.

| Request                                            | Response                                                         |
|----------------------------------------------------|------------------------------------------------------------------|
| Empty `experimentName`                             | `400` `experiment_name is required`                              |
| Unknown experiment, or one in another organisation | `404`                                                            |
| No checkpoint yet                                  | `400` `No checkpoints found for experiment`                      |
| `checkpoint` is a step with no checkpoint          | `400` `No checkpoint registered at step 999 for this experiment` |
| `checkpoint` is any other word, such as `latest`   | `400` `checkpoint must be "best", "final", a step number, …`     |
| `memoryScope` not `user` or `organization`         | `422`, plain-text body                                           |
| Pay-as-you-go organisation without enough balance  | `403 spend_denied`                                               |

### Status

Poll `GET /deployments/one` until `status` is `Deployed`. That usually takes a minute and a half or more, depending on the checkpoint size.

```bash
curl -sS -G "${ARENA_BASE}/api/cli/v1/inference/deployments/one" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  --data-urlencode "name=support-bot"
```

The reply is the `deployment` object from deploy. Add `experimentName` and `projectName` to narrow the lookup. An unknown name, or a deployment in another organisation, returns `404`.

| `status`     | Meaning                                                                                                                                                                                                                                      |
|--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `Pending`    | Arena is copying the checkpoint and starting the server. A `Deployed` deployment drops back to `Pending` while its server stops answering health checks, and returns to `Deployed` when it recovers.                                         |
| `Deployed`   | The server at `url` answers its health check                                                                                                                                                                                                 |
| `Undeployed` | Not serving. With `enabled: false` it was taken offline (by `PATCH`, or because a pay-as-you-go balance ran out) and stays off until enabled again. With `enabled: true` it is an Enterprise deployment waiting for an operator to start it. |
| `Failed`     | The rollout failed                                                                                                                                                                                                                           |

### List

```bash
curl -sS "${ARENA_BASE}/api/cli/v1/inference/deployments/list" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}"
```

```json
{
  "ok": true,
  "data": [
    {
      "name": "support-bot",
      "status": "Deployed",
      "enabled": true,
      "experiment_name": "sft-qwen-4b-dev",
      "project_name": "post-train",
      "algorithm": "SFT",
      "url": "https://6604b462e6fb4523b68cb6f28117d9b8.deploy.example",
      "memory_scope": "user"
    }
  ]
}
```

Optional query parameters are `name`, `experimentName` and `projectName`. Deleted deployments are left out unless you send `archived=true`. Rows have no `description` or `spec`; read one deployment for those.

### Rename, take offline, bring back

```bash
curl -sS -X PATCH "${ARENA_BASE}/api/cli/v1/inference/deployments" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" \
  -d '{"name":"support-bot","newName":"support-bot-v1","description":"First SFT run","enabled":false}'
```

`name` finds the deployment (`experimentName` and `projectName` can narrow it). `newName` (or `new_name`), `description` and `enabled` are each optional. `enabled: false` takes the deployment offline and keeps it; `enabled: true` brings it back. The reply is the updated `deployment` object. To change the checkpoint, GPUs or memory scope, call deploy again.

### Delete

```bash
curl -sS -X DELETE -G "${ARENA_BASE}/api/cli/v1/inference/deployments" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" \
  -H "X-External-User-Id: ${ARENA_USER}" \
  --data-urlencode "name=support-bot-v1"
```

```json
{ "ok": true, "data": { "success": true } }
```

The deployment stops and is archived. Its name is free to use again, and it shows in the list only with `archived=true`. Deleting the same name again returns `404`.

### Memory scope

Language model deployments keep chat sessions. `user` keeps each caller’s sessions separate. `organization` shares them across the organisation, and only an organisation admin can set it. Users created through `X-External-User-Id` are members, so for them `memoryScope: "organization"` returns `403` `Only organization admins can set memory_scope to organization`. A redeploy without `memoryScope` keeps the stored scope.

### GPUs

Without `numGpus` or `gpuType`, a redeploy, including one that enables a stopped deployment again, keeps the deployment’s current machine. A new deployment of a run trained on the organisation’s own cluster, which includes every self-hosted tenant, runs on that cluster’s resource class. Any other new deployment gets the cheapest machine that Arena’s memory estimate says can serve the model. When Arena can’t size the model, the deploy returns `400` with the reason and the valid `gpuType` values and counts, for example `Arena can't size this run: <reason>. Choose a class with --gpu-type and --num-gpus to deploy it without sizing: h100-80 (1, 2, 8), l4 (1).` Send `numGpus` and `gpuType` to pick one.

`numGpus` is the GPU count on the one inference machine. `gpuType` is a short name from that list (`l4`, `h100-80`) or the serving catalogue name (`nvidia-l4`, `nvidia-h100-80gb`). Serving GPU types are a different list from the training ones in [GPU type](#gpu-type). With a matching `gpuType`, Arena picks the cheapest matching machine that holds 8 sequences at full context, or else the cheapest matching one that fits. Failures return `400`:

| Case                                 | Message                                                                                                     |
|--------------------------------------|-------------------------------------------------------------------------------------------------------------|
| Not a language model run             | `Only LLM deployments take numGpus and gpuType.`                                                            |
| Unknown GPU type                     | `Unknown gpu_type 'b200'. Valid GPU types: h100-80, l4.`                                                    |
| No machine has that count            | `No resource class offers 3 l4 GPU(s). l4 GPU counts offered: 1, 2, 4.`                                     |
| None of that count has enough memory | `No resource class has enough GPU memory for this run on 1 a100-80 GPU(s). a100-80 GPU counts that fit: 2.` |

### Calling the deployed model

The server at `url` takes `POST /generate` and `POST /generate_stream`; the request and reply bodies are in the [inference contract](../reference/inference-contract.md). It checks each request’s credentials with Arena before answering.

On a self-hosted tenant, `url` is on the API host: `https://<host>/api/deployments/<id>/inference`. Call it with the same two headers as every other call. Arena checks that the key’s organisation owns the deployment, then passes the request to the inference server with a one-minute credential for that deployment and that user in place of your key. A deployment that keeps memory per user keeps it per `X-External-User-Id`.

```bash
curl -sS "${DEPLOYMENT_URL}/generate" \
  -H "Authorization: Bearer ${ARENA_ORG_KEY}" -H "X-External-User-Id: ${ARENA_USER}" \
  -H "Content-Type: application/json" \
  -d '{"session_id":"ticket-4411","prompts":["My order has not arrived."],"params":{"max_new_tokens":256}}'
```

| Status                                                                 | Cause                                                                                                    |
|------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------|
| `401` `{"success": false, "error": "User is not authorized (OAuth2)"}` | The inference server could not check the call with the API. Check the API logs for `check-access denied` |
| `403`                                                                  | The key’s scope doesn’t cover inference                                                                  |
| `404`                                                                  | No deployment with that id in the key’s organisation, or it isn’t running                                |

On hosted Arena the inference server doesn’t yet accept an organisation key. Contact AgileRL if your product needs to call deployments there.

On a self-hosted tenant a running deployment holds its GPUs, so new training runs may wait as `Queued` until you take it offline.

## Errors

Coded errors have the body `{"ok": false, "error": "<code>", "message": "…"}`. On submit, coded errors arrive as `detail.error_code` on the stream’s final `failed` line.

| HTTP                            | Meaning                                                                                                                                                            | What to do                                                                                                                                                                                                                                 |
|---------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `400`                           | Bad field, file or mapping; `resource_id` or `num_nodes` on submit; export without `experimentName` and `steps`, or a shared experiment name without `projectName` | Fix the field named in `message`. `resource_id` comes from the `agilerl-arena` 1.x client; move to `agilerl`: `uv remove agilerl-arena && uv add agilerl`, or `pip uninstall -y agilerl-arena && pip install -U --force-reinstall agilerl` |
| `400 run_does_not_fit`          | The run can never fit the resource                                                                                                                                 | Change the run ([Check a run fits](#check-a-run-fits))                                                                                                                                                                                     |
| `400 huggingface_offline`       | Self-hosted: the request needed the Hugging Face Hub                                                                                                               | Upload the dataset file; use a model from `/models`                                                                                                                                                                                        |
| `401`                           | Key missing, wrong or revoked, or from another tenant                                                                                                              | Check `Authorization: Bearer arena_org_…`                                                                                                                                                                                                  |
| `403`                           | `organization member limit reached`                                                                                                                                | Contact AgileRL                                                                                                                                                                                                                            |
| `403 spend_denied`              | Deploy on a pay-as-you-go organisation without enough balance                                                                                                      | Contact AgileRL                                                                                                                                                                                                                            |
| `403`                           | Deploy with `memoryScope: "organization"`                                                                                                                          | Leave `memoryScope` out; partner users aren’t organisation admins                                                                                                                                                                          |
| `404`                           | Unknown name or `steps`, another organisation’s job, or GET export before POST                                                                                     | Check the experiment name, the checkpoint `steps` or the deployment `name`. Another organisation’s data is always `404`, never `403`.                                                                                                      |
| `409 gpu_cluster_unavailable`   | Self-hosted: the tenant’s GPU cluster is offline                                                                                                                   | Tell your user; ask your operator                                                                                                                                                                                                          |
| `409 idempotency_conflict`      | Same retry key, different body                                                                                                                                     | New key, or the original body                                                                                                                                                                                                              |
| `409 idempotency_in_progress`   | First submit with that key still running                                                                                                                           | Wait, then retry with the same key and body                                                                                                                                                                                                |
| `409 export_incomplete`         | The merge isn’t finished                                                                                                                                           | Wait, then POST the export again                                                                                                                                                                                                           |
| `409 export_renew_required`     | Links expired                                                                                                                                                      | POST renew, then GET the files                                                                                                                                                                                                             |
| `409 export_replay_unavailable` | Body had `"replay": true`                                                                                                                                          | POST the export with `experimentName` and `steps`                                                                                                                                                                                          |
| `413`                           | Upload over the size limit                                                                                                                                         | Use a smaller file                                                                                                                                                                                                                         |
| `415`                           | Multipart on `POST /environments/validate`                                                                                                                         | Send JSON                                                                                                                                                                                                                                  |
| `422`                           | JSON that doesn’t match the route, such as an unknown `memoryScope`                                                                                                | Fix the field named in the plain-text body                                                                                                                                                                                                 |
| `429`                           | Rate limit                                                                                                                                                         | Wait `Retry-After` seconds                                                                                                                                                                                                                 |
| `503 storage_unavailable`       | Self-hosted: the tenant’s object store can’t be reached                                                                                                            | Retry later; ask your operator                                                                                                                                                                                                             |

`JOB_REJECTED` on the submit stream means the job never reached GPUs. Check the model’s catalogue entry and that the dataset’s `is_ready` is `true`.

## Python

```bash
uv add agilerl
```

Without uv, `pip install agilerl` works too. The package supports Python 3.10 to 3.13. `ArenaClient` sends the same two headers as the HTTP above:

```python
from agilerl import ArenaClient

ArenaClient.configure(base_url="https://arena.agilerl.com")
client = ArenaClient(
    org_key="arena_org_11111111-2222-3333-4444-555555555555_k7mN9pQ2rS4tU6vW",
    external_user_id="user-42",
)

client.create_project("post-train", "Partner post-training")
client.create_dataset(
    name="support-tickets-sft",
    category="sft",
    file="./main",
    column_mapping={"prompt": "instruction", "target": "response"},
    config="main",
)
spec = client.get_default_run_spec(
    algorithm="SFT",
    dataset_name="support-tickets-sft",
    pretrained_model_name_or_path="Qwen/Qwen3.5-4B",
)
spec["algorithm"]["batch_size"] = 8
spec["algorithm"]["lr"] = 0.0001
spec["network"]["max_context_length"] = 2048
spec["training"]["checkpoint_export"] = {"format": "merged", "trigger": "final"}
spec["training"]["max_steps"] = 500
client.submit_experiment(
    manifest=spec,
    project="post-train",
    experiment_name="sft-qwen-4b-dev",
)
print(client.list_experiments(project="post-train"))
print(client.list_experiment_metric_names("sft-qwen-4b-dev"))
print(client.list_checkpoints("sft-qwen-4b-dev"))
```

### Host and credentials

The key and user ID can come from `ARENA_ORG_KEY` and `ARENA_EXTERNAL_USER_ID` instead of the constructor. Setting only one of the two raises `ArenaAuthError` when the client is built.

The host defaults to `https://arena.agilerl.com`. `ArenaClient.configure(base_url=…)` changes it for clients built afterwards and wins over `ARENA_BASE_URL`, which wins over the default. To point the same code at a self-hosted tenant, change only the host and the key.

### Replies and errors

Methods return the `data` part of `{ "ok": true, "data": … }` replies, and the JSON as it is for routes without the wrapper. Submit reads the whole stream and returns its final result; a `failed` line raises instead.

A `401` raises `ArenaAuthError`. Any other error status raises `ArenaAPIError`, which has `status_code` and `detail` (the server’s message). Dataset upload raises its subclass `ArenaValidationError`, and submit raises `ArenaTrainingError`. On `429` the client waits the `Retry-After` seconds (between 1 and 60) and tries again, up to five times, before raising.

```python
from agilerl.exceptions import ArenaAPIError

try:
    client.deploy_agent("sft-qwen-4b-dev", checkpoint="999")
except ArenaAPIError as err:
    print(err.status_code, err.detail)
```

### Deploy

```python
result = client.deploy_agent("sft-qwen-4b-dev", checkpoint="500")
print(result["created"], result["deployment"]["status"])

print(client.list_inference_deployments(experiment_name="sft-qwen-4b-dev"))

client.update_inference_deployment("sft-qwen-4b-dev", new_name="support-bot")
client.update_inference_deployment("support-bot", enabled=False)
client.delete_inference_deployment("support-bot")
```

`deploy_agent` sends `experiment_name`, `checkpoint`, and when given, `memory_scope`, `num_gpus` and `gpu_type`. `checkpoint` is a string: `"best"`, `"final"` or a step such as `"500"`; `None` deploys the checkpoint with the most steps. It takes no name or description, so a new deployment is named after the experiment; rename it with `update_inference_deployment(…, new_name=…)`.

`open_inference_agent(name)` returns an agent bound to the deployment’s `url`. It sends the client’s organisation key and external user ID, so on a self-hosted tenant `agent.generate(…)` works as in [Calling the deployed model](#calling-the-deployed-model). On hosted Arena its requests are refused.

### Methods and routes

| Method                                                                                                                | Route                                                                        |
|-----------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------|
| `list_resources(algorithm=…)`                                                                                         | `GET /resources/list`                                                        |
| `create_dataset(name=…, category=…, file=…, column_mapping=…, config=…)`                                              | `POST /datasets/create`                                                      |
| `dataset_exists(name)`, `list_datasets()`                                                                             | `GET /datasets/exists`, `GET /datasets`                                      |
| `delete_dataset(name, confirm=True)`                                                                                  | `DELETE /datasets/delete` (without `confirm=True` it asks on standard input) |
| `create_project(name, description)`, `list_projects()`, `delete_project(name)`                                        | `POST /projects/create`, `GET /projects`, `DELETE /projects/delete`          |
| `list_models()`, `get_model_info(model_name)`                                                                         | `GET /models`, `POST /models/info`                                           |
| `get_default_run_spec(algorithm, dataset_name=…, pretrained_model_name_or_path=…)`                                    | `GET /experiments/run-spec/default`                                          |
| `submit_experiment(manifest, project=…, experiment_name=…, num_gpus=…, gpu_type=…, reward_file=…, idempotency_key=…)` | `POST /experiments/jobs/submit`                                              |
| `list_experiments(project=…)`                                                                                         | `GET /experiments/list`                                                      |
| `stop_experiment(experiment_name)`                                                                                    | `POST /experiments/jobs/stop`                                                |
| `resume_experiment(experiment_name, max_steps=…, checkpoint=…, new_name=…)`                                           | `POST /experiments/jobs/resume`                                              |
| `list_experiment_metric_names(experiment_name, details=…)`                                                            | `GET /experiments/metrics`                                                   |
| `preview_experiment_metrics_csv(experiment_name, preview_rows=…, metrics=[…])`                                        | `GET /experiments/metrics` with `preview_rows`                               |
| `list_checkpoints(experiment_name)`                                                                                   | `GET /experiments/jobs/checkpoints`                                          |
| `deploy_agent(experiment_name, checkpoint=…, memory_scope=…, num_gpus=…, gpu_type=…)`                                 | `POST /inference/deploy`                                                     |
| `list_inference_deployments(name=…, experiment_name=…, project_name=…)`                                               | `GET /inference/deployments/list`                                            |
| `update_inference_deployment(name, new_name=…, description=…, enabled=…)`                                             | `PATCH /inference/deployments`                                               |
| `delete_inference_deployment(name)`                                                                                   | `DELETE /inference/deployments`                                              |

Routes are under `/api/cli/v1`. Download the trained model with the HTTP calls in [Download the trained model](#download-the-trained-model). The full client is documented in the [Python client reference](../cli/python-client.md).
