Training API reference

Every public endpoint of grad-server, generated from grad's spec/openapi.yaml: its fields, an example request and response, and the complete SDK call or CLI command that sends it, in the language you picked above.

The same API runs on grad local up, the Helm chart and, soon, Gradiated Cloud. Set GRADIATED_BASE_URL to your server (http://127.0.0.1:18787 for grad local up) and GRADIATED_API_KEY to a key; every /v1/* call sends it as Authorization: Bearer <key>. Authentication, scopes, idempotency, pagination and the error format are on the API overview; every error code is explained in Errors. A running server also serves this spec at /openapi.json.

Every sample sends the same values as its curl request, and grad's scripts/check-docs-snippets.py --compile type-checks each one against the SDK sources on grad 0.2.0-alpha.12, the current release (see 0.2.0-alpha.12; earlier Go and Rust signature changes are under 0.2.0-alpha.8).

spec 0.2.0-alpha.16

Auth#

Identify the authenticated caller, workspace, and server mode#

GET/v1/whoami

Returns

200 WhoamiResponse Authenticated identity and server capabilities.

6 fields
  • workspace_idstringrequired

    Authenticated workspace id.

  • workspace_namestringrequirednullable

    Workspace display name when available, else null.

  • auth_kindstringrequired

    How the request authenticated (e.g. "api_key", "session", "dev", "worker").

  • deployment_modeDeploymentModerequired

    Whether this server is Gradiated Cloud (cloud) or a self-hosted deployment (self-hosted).

    "cloud""self-hosted"

  • capabilitiesWhoamiCapabilitiesrequired
    1 child fields
    • inference_evalsbooleanrequired

      Whether server-side evals, LLM judges, and prompt-labeling evals are enabled on this server.

  • console_urlstringnullable

    The web console's runs page for this workspace when GRAD_CONSOLE_URL is configured; null otherwise. grad ui opens it on Gradiated Cloud.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
me = client.whoami()
print(me.workspace_id, me.auth_kind, me.deployment_mode)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "workspace_id": "ws_e2e",
  "workspace_name": null,
  "auth_kind": "api_key",
  "deployment_mode": "self-hosted",
  "capabilities": {
    "inference_evals": true
  }
}

Datasets#

List datasets#

GET/v1/datasets

Newest first.

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • qstring≤ 200 chars

    Only items whose name contains this text (any case), or whose id is exactly this.

Returns

200 object Datasets.

2 fields
  • dataarray of Datasetrequired
    9 child fields
    • idstringrequired

      Dataset id (ds_ and 24 hex characters).

    • workspace_idstringrequired
    • namestringrequired≤ 64 chars

      Dataset name, unique in the workspace.

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • versionintegerrequired≥ 0

      Current version. Every push, import, score or sync that changes records adds one; runs and evals pin a version.

    • record_countintegerrequired≥ 0

      Records in the current version after merging: score updates fold into their records, and a full source sync restarts the count. A record pushed again with an id it already has counts again.

    • metadatamap of anyrequired

      Free-form metadata you set at creation.

    • created_atstring (date-time)required
    • updated_atstring (date-time)required
    • console_urlstringnullable

      Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for dataset in client.datasets.list(search="support"):
    print(dataset.name, dataset.version, dataset.record_count)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "data": [
    {
      "id": "ds_933362777156d207844b5d12",
      "workspace_id": "ws_e2e",
      "name": "support-good",
      "version": 1,
      "record_count": 1,
      "metadata": {
        "view": {
          "filter": {
            "scores": {
              "resolved": ">=0.8"
            }
          },
          "source": "support-prod",
          "version": 1
        }
      },
      "created_at": "2026-12-02T15:48:59.845Z",
      "updated_at": "2026-12-02T15:48:59.847Z"
    },
    {
      "id": "ds_c66d7ad841f251049ca0e550",
      "workspace_id": "ws_e2e",
      "name": "support-prod",
      "version": 2,
      "record_count": 1,
      "metadata": {},
      "created_at": "2026-12-02T15:48:59.567Z",
      "updated_at": "2026-12-02T15:49:00.345Z"
    }
  ],
  "next_cursor": null
}

Create an empty dataset#

POST/v1/datasets

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body CreateDatasetRequest

  • namestringrequired≤ 64 chars

    Dataset name: lowercase letters, digits, ., _ and -, unique in the workspace.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • metadatamap of any

    Free-form metadata stored on the dataset.

Returns

201 Dataset Created dataset (version 0).

9 fields
  • idstringrequired

    Dataset id (ds_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Dataset name, unique in the workspace.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • versionintegerrequired≥ 0

    Current version. Every push, import, score or sync that changes records adds one; runs and evals pin a version.

  • record_countintegerrequired≥ 0

    Records in the current version after merging: score updates fold into their records, and a full source sync restarts the count. A record pushed again with an id it already has counts again.

  • metadatamap of anyrequired

    Free-form metadata you set at creation.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required
  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
dataset = client.datasets.create("support-prod")
Response 201 CreatedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "ds_c66d7ad841f251049ca0e550",
  "workspace_id": "ws_e2e",
  "name": "support-prod",
  "version": 0,
  "record_count": 0,
  "metadata": {},
  "created_at": "2026-12-02T15:48:59.567Z",
  "updated_at": "2026-12-02T15:48:59.567Z"
}

Get a dataset by name#

GET/v1/datasets/{name}

Path parameters

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Returns

200 Dataset Dataset metadata.

9 fields
  • idstringrequired

    Dataset id (ds_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Dataset name, unique in the workspace.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • versionintegerrequired≥ 0

    Current version. Every push, import, score or sync that changes records adds one; runs and evals pin a version.

  • record_countintegerrequired≥ 0

    Records in the current version after merging: score updates fold into their records, and a full source sync restarts the count. A record pushed again with an id it already has counts again.

  • metadatamap of anyrequired

    Free-form metadata you set at creation.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required
  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
dataset = client.datasets.get("support-prod")
print(dataset.version, dataset.record_count)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "ds_c66d7ad841f251049ca0e550",
  "workspace_id": "ws_e2e",
  "name": "support-prod",
  "version": 2,
  "record_count": 1,
  "metadata": {},
  "created_at": "2026-12-02T15:48:59.567Z",
  "updated_at": "2026-12-02T15:49:00.345Z"
}

Delete a dataset and its versions#

DELETE/v1/datasets/{name}

409 while referenced by runs, evals, sources, or active imports.

Path parameters

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Returns

204 Deleted.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
client.datasets.delete("support-prod")
Response 204 No Content

Deleted.

Append records as a new dataset version#

POST/v1/datasets/{name}/records

Creates the dataset if needed.

Path parameters

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body PushDatasetRequest

  • recordsarray of DatasetRecord1–50000 items

    Records to append inline; together they become the next dataset version. Mutually exclusive with upload_id.

    24 child fields
    • schema"grad.trajectory/1"

      "grad.trajectory/1"

    • idstring≤ 160 chars
    • session_idstringnullable≤ 160 chars
    • group_idstringnullable≤ 160 chars
    • roleenumnullable

      "chosen""rejected""anchor""positive""negative""desirable""undesirable""rollout"null

    • sourcestringnullable≤ 80 chars
    • timestampstringnullable≤ 64 chars
    • messagesarray of ChatMessage
      7 child fields
      • roleenumrequired

        "system""user""assistant""tool"

      • contentstring or array of map of anynullable
        One of 2 shapes
        1. string
        2. array of map of any
      • reasoning_contentstring
      • tool_callsarray of map of any
      • tool_call_idstring
      • namestring
      • trainboolean
    • toolsarray of map of any
    • inputTrajectoryInput
      5 child fields
      • messagesarray of ChatMessage
        7 child fields
        • roleenumrequired

          "system""user""assistant""tool"

        • contentstring or array of map of anynullable
          One of 2 shapes
          1. string
          2. array of map of any
        • reasoning_contentstring
        • tool_callsarray of map of any
        • tool_call_idstring
        • namestring
        • trainboolean
      • toolsarray of map of any
      • mediaarray of map of any
      • featuresmap of any
      • payloadany
    • outputTrajectoryOutputnullable
    • promptstring or array of ChatMessage
      One of 2 shapes
      1. string
      2. array of ChatMessage
        • roleenumrequired

          "system""user""assistant""tool"

        • contentstring or array of map of anynullable
          One of 2 shapes
          1. string
          2. array of map of any
        • reasoning_contentstring
        • tool_callsarray of map of any
        • tool_call_idstring
        • namestring
        • trainboolean
    • completionstring or array of ChatMessage
      One of 2 shapes
      1. string
      2. array of ChatMessage
        • roleenumrequired

          "system""user""assistant""tool"

        • contentstring or array of map of anynullable
          One of 2 shapes
          1. string
          2. array of map of any
        • reasoning_contentstring
        • tool_callsarray of map of any
        • tool_call_idstring
        • namestring
        • trainboolean
    • chosenstring or array of ChatMessage
      One of 2 shapes
      1. string
      2. array of ChatMessage
        • roleenumrequired

          "system""user""assistant""tool"

        • contentstring or array of map of anynullable
          One of 2 shapes
          1. string
          2. array of map of any
        • reasoning_contentstring
        • tool_callsarray of map of any
        • tool_call_idstring
        • namestring
        • trainboolean
    • rejectedstring or array of ChatMessage
      One of 2 shapes
      1. string
      2. array of ChatMessage
        • roleenumrequired

          "system""user""assistant""tool"

        • contentstring or array of map of anynullable
          One of 2 shapes
          1. string
          2. array of map of any
        • reasoning_contentstring
        • tool_callsarray of map of any
        • tool_call_idstring
        • namestring
        • trainboolean
    • querystring
    • positivestring
    • negativesarray of string
    • stateany
    • questionsmap of any
    • expected_outputany
    • scoresmap of number
    • metricsmap of number
    • metadatamap of any
  • upload_idstring

    Staged JSONL or gzipped JSONL uploaded via POST /v1/uploads (purpose: "dataset_import"). Commits all records atomically as one dataset version; mutually exclusive with records.

    Matches ^[0-9a-f]{64}$

  • formatPushDatasetFormat

    Format of the staged upload (jsonl or jsonl.gz); only valid with upload_id. Defaults to auto-detection via gzip magic bytes.

    "jsonl""jsonl.gz"

  • metadatamap of any

    Keys merged into the dataset's metadata.

Returns

200 Dataset Updated dataset.

9 fields
  • idstringrequired

    Dataset id (ds_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Dataset name, unique in the workspace.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • versionintegerrequired≥ 0

    Current version. Every push, import, score or sync that changes records adds one; runs and evals pin a version.

  • record_countintegerrequired≥ 0

    Records in the current version after merging: score updates fold into their records, and a full source sync restarts the count. A record pushed again with an id it already has counts again.

  • metadatamap of anyrequired

    Free-form metadata you set at creation.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required
  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
dataset = client.datasets.push("support-prod", [
    {
        "messages": [
            {"role": "user", "content": "Where is my order #4512?"},
            {"role": "assistant", "content": "It shipped this morning; here is the tracking link."},
        ],
        "scores": {"resolved": 1},
        "metadata": {"route": "support"},
    },
])
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "ds_c66d7ad841f251049ca0e550",
  "workspace_id": "ws_e2e",
  "name": "support-prod",
  "version": 1,
  "record_count": 1,
  "metadata": {},
  "created_at": "2026-12-02T15:48:59.567Z",
  "updated_at": "2026-12-02T15:48:59.803Z"
}

Read records of a dataset version#

GET/v1/datasets/{name}/records

Path parameters

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Query parameters

  • versionintegernullable≥ 0
  • limitinteger1–1000default 100

    Page size (default 100). Values above 1000 are clamped to 1000.

  • cursorstring≤ 512 chars

Returns

200 DatasetRecordsPage Dataset records page.

5 fields
  • datasetstringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • versionintegerrequired≥ 0
  • totalintegerrequired≥ 0
  • dataarray of DatasetRecordrequired
    24 child fields
    • schema"grad.trajectory/1"

      "grad.trajectory/1"

    • idstring≤ 160 chars
    • session_idstringnullable≤ 160 chars
    • group_idstringnullable≤ 160 chars
    • roleenumnullable

      "chosen""rejected""anchor""positive""negative""desirable""undesirable""rollout"null

    • sourcestringnullable≤ 80 chars
    • timestampstringnullable≤ 64 chars
    • messagesarray of ChatMessage
      7 child fields
      • roleenumrequired

        "system""user""assistant""tool"

      • contentstring or array of map of anynullable
        One of 2 shapes
        1. string
        2. array of map of any
      • reasoning_contentstring
      • tool_callsarray of map of any
      • tool_call_idstring
      • namestring
      • trainboolean
    • toolsarray of map of any
    • inputTrajectoryInput
      5 child fields
      • messagesarray of ChatMessage
        7 child fields
        • roleenumrequired

          "system""user""assistant""tool"

        • contentstring or array of map of anynullable
          One of 2 shapes
          1. string
          2. array of map of any
        • reasoning_contentstring
        • tool_callsarray of map of any
        • tool_call_idstring
        • namestring
        • trainboolean
      • toolsarray of map of any
      • mediaarray of map of any
      • featuresmap of any
      • payloadany
    • outputTrajectoryOutputnullable
    • promptstring or array of ChatMessage
      One of 2 shapes
      1. string
      2. array of ChatMessage
        • roleenumrequired

          "system""user""assistant""tool"

        • contentstring or array of map of anynullable
          One of 2 shapes
          1. string
          2. array of map of any
        • reasoning_contentstring
        • tool_callsarray of map of any
        • tool_call_idstring
        • namestring
        • trainboolean
    • completionstring or array of ChatMessage
      One of 2 shapes
      1. string
      2. array of ChatMessage
        • roleenumrequired

          "system""user""assistant""tool"

        • contentstring or array of map of anynullable
          One of 2 shapes
          1. string
          2. array of map of any
        • reasoning_contentstring
        • tool_callsarray of map of any
        • tool_call_idstring
        • namestring
        • trainboolean
    • chosenstring or array of ChatMessage
      One of 2 shapes
      1. string
      2. array of ChatMessage
        • roleenumrequired

          "system""user""assistant""tool"

        • contentstring or array of map of anynullable
          One of 2 shapes
          1. string
          2. array of map of any
        • reasoning_contentstring
        • tool_callsarray of map of any
        • tool_call_idstring
        • namestring
        • trainboolean
    • rejectedstring or array of ChatMessage
      One of 2 shapes
      1. string
      2. array of ChatMessage
        • roleenumrequired

          "system""user""assistant""tool"

        • contentstring or array of map of anynullable
          One of 2 shapes
          1. string
          2. array of map of any
        • reasoning_contentstring
        • tool_callsarray of map of any
        • tool_call_idstring
        • namestring
        • trainboolean
    • querystring
    • positivestring
    • negativesarray of string
    • stateany
    • questionsmap of any
    • expected_outputany
    • scoresmap of number
    • metricsmap of number
    • metadatamap of any
  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for record in client.datasets.records("support-prod", limit=100):
    print(record["messages"][-1]["content"])
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "dataset": "support-prod",
  "version": 2,
  "total": 1,
  "data": [
    {
      "messages": [
        {
          "role": "user",
          "content": "Where is my order #4512?"
        },
        {
          "role": "assistant",
          "content": "It shipped this morning; here is the tracking link."
        }
      ],
      "scores": {
        "resolved": 1,
        "polite": 0
      },
      "metadata": {
        "route": "support"
      },
      "id": "rec_0918892977163ffc"
    }
  ],
  "next_cursor": null
}

Score a dataset's records with a rubric#

POST/v1/datasets/{name}/score

Async; the scores become the next version.

Runs the rubric (judges, validators, regexes, code scorers) on each record's own answer, skipping records that already have every score. It is an eval with mode: "score": poll it at /v1/evals/{id}, and it is billed like one. On completion the scores are appended as a score-update part, so the dataset's next version (scored_dataset_version) carries them in record.scores.

Path parameters

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body ScoreDatasetRequest

  • rubricarray of EvalRubricItemrequired1–32 items
    9 child fields
    • namestringrequired≤ 80 chars

      Matches ^[A-Za-z0-9_.:-]+$

    • kindenumrequired

      "regex""validator""code""judge"

    • weightnumber> 0default 1
    • patternstring≤ 256 chars
    • flagsstring≤ 4 chars

      Matches ^[imsu]*$

    • validatorenum

      "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

    • modelstring≤ 160 chars
    • promptstring≤ 8000 chars
    • runtime"local"

      Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

      "local"

  • versioninteger≥ 1

    Dataset version to score (default: the current version).

  • namestring≤ 64 chars

    Name of the scoring job (default <dataset>-score).

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • limitinteger1–100000

Returns

202 EvalRun Queued scoring job.

29 fields
  • idstringrequired

    Eval id (eval_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • statusEvalStatusrequired

    "queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"

  • modeEvalModerequired

    eval generates outputs from models; score (dataset.score()) grades each record's own output (model record) and writes the scores to the dataset's next version; env is a client-driven agent evaluation whose rollouts post outputs via /outputs and /complete.

    "eval""score""env"

  • modelsarray of stringrequired

    The models evaluated: catalog ids, artifacts (name@version), models the inference endpoint serves, or policy labels in env mode.

  • baselinestringrequirednullable

    The model the summary compares the others with (vs_baseline); null for none.

  • baseline_evalEvalBaselineRefrequirednullable
  • envEvalEnvConfigrequirednullable
  • gateEvalGateResultrequirednullable
  • task_sourceobjectrequired
    3 child fields
    • kind"dataset"required

      "dataset"

    • datasetstringrequired
    • versionintegerrequired≥ 1
  • rubricarray of EvalRubricItemrequired
    9 child fields
    • namestringrequired≤ 80 chars

      Matches ^[A-Za-z0-9_.:-]+$

    • kindenumrequired

      "regex""validator""code""judge"

    • weightnumber> 0default 1
    • patternstring≤ 256 chars
    • flagsstring≤ 4 chars

      Matches ^[imsu]*$

    • validatorenum

      "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

    • modelstring≤ 160 chars
    • promptstring≤ 8000 chars
    • runtime"local"

      Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

      "local"

  • samplesintegerrequired≥ 1

    Answers generated per task and model.

  • temperaturenumberrequired0–2

    Sampling temperature of the model calls.

  • max_tokensintegerrequired≥ 1

    The most tokens each answer may have.

  • pass_thresholdnumberrequired0–1

    Score at or above which a task passes.

  • judge_modelsarray of stringrequired

    The judge models the rubric calls.

  • local_scorersarray of stringrequired

    Code scorers that run in the SDK process; the eval waits in awaiting_scores until they post their scores.

  • progressobjectrequired
    3 child fields
    • total_outputsintegerrequired≥ 0
    • generatedintegerrequired≥ 0
    • pending_local_scoresintegerrequired≥ 0
  • summaryarray of EvalModelSummaryrequired
    12 child fields
    • modelstringrequired

      The model this summary is for.

    • overallnumberrequired

      Mean task score (each task's score averages its samples).

    • ci_lownumberrequired

      Lower bound of the bootstrap 95% confidence interval on overall.

    • ci_highnumberrequired

      Upper bound of the bootstrap 95% confidence interval on overall.

    • pass_at_kmap of numberrequired

      Unbiased pass@k per k (pass@1, ...): the chance that one of k samples scores at least pass_threshold.

    • vs_baselineobjectrequirednullable

      The mean paired difference from the baseline over the tasks both answered, with a bootstrap 95% interval; null for the baseline itself or without one.

      3 child fields
      • deltanumberrequired
      • ci_lownumberrequired
      • ci_highnumberrequired
    • tasksintegerrequired≥ 0

      Tasks this model answered.

    • errorsintegerrequired≥ 0

      Model or judge calls that failed.

    • tokens_per_tasknumberrequired

      Mean tokens per task.

    • cost_per_1k_tasks_usdnumberrequirednullable

      Cost per 1,000 tasks in USD; null when the model has no price.

    • by_scorermap of number

      Mean score per rubric scorer over outputs carrying that scorer.

    • mean_turnsnumbernullable

      Mean agent turns per rollout (present when outputs include trajectories with turns).

  • total_cost_usdnumberrequired≥ 0

    Cost of the model and judge calls so far, in USD.

  • scored_dataset_versionintegerrequirednullable≥ 1

    Scoring jobs: the dataset version holding the new scores (the source version when every record was already scored); null until completed.

  • errorstringrequirednullable

    Why the eval failed; null otherwise.

  • waiting_reasonenumrequirednullable

    While running: the eval's model calls are waiting for capacity (a serving pool at zero that has not woken yet), for a rate limit (a full eval lane), or for an inference endpoint that is down. The worker keeps its lease and retries; this is not counted as a failed attempt. null otherwise.

    "capacity_unavailable""rate_limited""inference_unavailable"null

  • last_output_atstring (date-time)requirednullable

    When the last client output was received in env mode; null otherwise.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required
  • completed_atstring (date-time)requirednullable

    When the eval reached a final status; null until then.

  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad, Scorer
from grad.validators import Regex

client = Grad()
polite = Scorer("polite", fn=Regex("thank", flags="i"))  # runs on the server
scoring = client.datasets.score("support-prod", [polite])
scored = scoring.wait()  # the version with the scores
Response 202 AcceptedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "eval_c13bd1724f656bf328ba0115",
  "workspace_id": "ws_e2e",
  "name": "support-prod-score",
  "status": "queued",
  "mode": "score",
  "models": [
    "record"
  ],
  "baseline": null,
  "baseline_eval": null,
  "env": null,
  "gate": null,
  "task_source": {
    "kind": "dataset",
    "dataset": "support-prod",
    "version": 1
  },
  "rubric": [
    {
      "kind": "regex",
      "name": "polite",
      "flags": "i",
      "weight": 1,
      "pattern": "thank"
    }
  ],
  "samples": 1,
  "temperature": 0,
  "max_tokens": 1,
  "pass_threshold": 1,
  "judge_models": [],
  "local_scorers": [],
  "progress": {
    "total_outputs": 1,
    "generated": 0,
    "pending_local_scores": 0
  },
  "summary": [],
  "total_cost_usd": 0,
  "scored_dataset_version": null,
  "error": null,
  "waiting_reason": null,
  "last_output_at": null,
  "created_at": "2026-12-02T15:48:59.828Z",
  "updated_at": "2026-12-02T15:48:59.828Z",
  "completed_at": null
}

Save a filtered view of a dataset version#

POST/v1/datasets/{name}/filter

Keeps the records whose stored scores, metadata, timestamp or id match, and saves them as a dataset named <dataset>-f-<hash> (or name). The same filter on the same version returns the same view (200) without recomputing; a new threshold is a new view (201). Filtering calls no model and costs nothing.

Path parameters

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body FilterDatasetRequest

  • scoresmap of string or number

    Conditions on stored scores, {name: "<op><number>"} with op one of >=, <=, >, <, ==, != (a bare number means ==). A record without the score does not match.

  • metadatamap of string or number or boolean

    Exact matches on metadata fields.

  • created_afterstring (date-time) or string (date)

    Records whose timestamp is at or after this time (a timestamp with offset, or a UTC date YYYY-MM-DD).

    One of 2 shapes
    1. string (date-time)
    2. string (date)
  • created_beforestring (date-time) or string (date)

    Records whose timestamp is before this time.

    One of 2 shapes
    1. string (date-time)
    2. string (date)
  • idsarray of string≤ 200000 items

    Keep only these record ids (what the SDKs send for a filter function they ran locally).

  • versioninteger≥ 1

    Source version to filter (default: the current version).

  • namestring≤ 64 chars

    Name of the view. Default: <dataset>-f-<hash of source, version and filter>, so the same filter returns the same view.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Returns

200 Dataset The existing view.

201 Dataset Created view.

9 fields
  • idstringrequired

    Dataset id (ds_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Dataset name, unique in the workspace.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • versionintegerrequired≥ 0

    Current version. Every push, import, score or sync that changes records adds one; runs and evals pin a version.

  • record_countintegerrequired≥ 0

    Records in the current version after merging: score updates fold into their records, and a full source sync restarts the count. A record pushed again with an id it already has counts again.

  • metadatamap of anyrequired

    Free-form metadata you set at creation.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required
  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
view = client.datasets.filter("support-prod", scores={"resolved": ">=0.8"}, name="support-good")
print(view.name, view.record_count)
Response 201 CreatedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "ds_933362777156d207844b5d12",
  "workspace_id": "ws_e2e",
  "name": "support-good",
  "version": 1,
  "record_count": 1,
  "metadata": {
    "view": {
      "filter": {
        "scores": {
          "resolved": ">=0.8"
        }
      },
      "source": "support-prod",
      "version": 1
    }
  },
  "created_at": "2026-12-02T15:48:59.845Z",
  "updated_at": "2026-12-02T15:48:59.847Z"
}

Preview chat-template rendering and loss masks#

POST/v1/datasets/{name}/render

Estimated token counts.

Path parameters

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body RenderDatasetRequest

  • modelstring≤ 160 charsdefault "qwen/qwen3-8b"
  • train_onenumdefault "last"

    "last""all_assistant"

  • thinkingenumdefault "auto"

    "auto""on""off"

  • preserve_thinkingbooleandefault false
  • limitinteger1–20default 3

Returns

200 RenderDatasetResponse Rendered examples.

5 fields
  • datasetstringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • modelstringrequired
  • template_revisionstringrequired
  • token_counts"estimated"required

    Token counts (total, trained and per span) are estimates (about 4 characters per token); the trainer tokenizes with the model's pinned tokenizer, and the run's metrics report the exact tokens.

    "estimated"

  • examplesarray of objectrequired
    6 child fields
    • record_idstringrequired
    • template_revisionstringrequired
    • total_tokensintegerrequired≥ 0
    • trained_tokensintegerrequired≥ 0
    • trained_fractionnumberrequired0–1
    • spansarray of objectrequired
      3 child fields
      • textstringrequired
      • trainedbooleanrequired
      • tokensintegerrequired≥ 0

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
preview = client.datasets.render("support-prod", model="qwen/qwen3-8b", limit=1)
print(preview)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "dataset": "support-prod",
  "model": "qwen/qwen3-8b",
  "template_revision": "qwen3@3",
  "token_counts": "estimated",
  "examples": [
    {
      "record_id": "rec_0918892977163ffc",
      "template_revision": "qwen3@3",
      "total_tokens": 33,
      "trained_tokens": 14,
      "trained_fraction": 0.42424242424242425,
      "spans": [
        {
          "text": "<|im_start|>user\nWhere is my order #4512?<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
          "trained": false,
          "tokens": 18
        },
        {
          "text": "It shipped this morning; here is the tracking link.<|im_end|>",
          "trained": true,
          "tokens": 14
        }
      ]
    }
  ]
}

Get an upload URL for a file to import#

POST/v1/uploads

PUT the bytes, then create a dataset import, artifact import, or environment.

The staged file expires after 7 days unless an import or environment uses it.

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body CreateUploadRequest

  • purposeenumrequired

    dataset_import (needs datasets:write), artifact_import (artifacts:write), or environment_bundle (runs:write).

    "dataset_import""artifact_import""environment_bundle"

  • filenamestringrequired≤ 255 chars
  • size_bytesintegerrequired1–5368709120
  • sha256stringrequired

    Matches ^[0-9a-f]{64}$

Returns

201 UploadTicket Upload ticket.

5 fields
  • upload_idstringrequired

    The file's sha256: uploads are content-addressed, so re-uploading the same bytes is harmless.

  • method"PUT"required

    "PUT"

  • urlstringrequired

    Presigned S3 PUT URL; send exactly headers (they bind the length and sha256).

  • headersmap of stringrequired
  • expires_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
# Uploads the file (POST /v1/uploads, then a PUT to the returned URL) and imports it.
job = client.datasets.import_file("support-prod", "./traces.jsonl")
print(job.wait().status)
Response 201 CreatedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "upload_id": "9f2c4e1ab0d3c5e7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c9d1e3f5a7b9c1d3e5",
  "method": "PUT",
  "url": "https://storage.example.com/grad-test/uploads/ws_e2e/9f2c4e1ab0d3c5e7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c9d1e3f5a7b9c1d3e5?X-Amz-Algorithm=…&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=…&X-Amz-Date=…&X-Amz-Expires=…&X-Amz-Signature=…&X-Amz-SignedHeaders=…&x-id=PutObject",
  "headers": {
    "content-length": "52431",
    "x-amz-checksum-sha256": "nyxOGrDTxef5obPF1+nxo7XH2eHzpbfJ0eP1p7nB0+U="
  },
  "expires_at": "2026-12-02T21:48:59.857Z"
}

Import an uploaded file or a Hugging Face dataset into a dataset#

POST/v1/datasets/{name}/imports

Async job.

Path parameters

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body CreateImportRequest

  • sourceImportSourcerequired
    One of 3 shapes
    1. object
      • kind"upload"required

        "upload"

      • upload_idstringrequired≤ 160 chars
      • formatenumdefault "auto"

        "auto""jsonl""json""parquet"

    2. object
      • kind"hf"required

        "hf"

      • repostringrequired≤ 200 chars

        Matches ^[A-Za-z0-9](?:[\w-]|\.(?!\.))*(\/[A-Za-z0-9](?:[\w-]|\.(?!\.))*)?$

      • splitstring≤ 64 charsdefault "train"
      • configstring≤ 128 chars
      • revisionstring≤ 128 chars

        Matches ^(?!.*\.\.)[A-Za-z0-9][A-Za-z0-9._/-]*$

      • columnsHfColumnMappingdefault {}
        19 child fields
        • messagesstring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • systemstring≤ 128 chars

          System prompt column; prepended to messages or combined with prompt/completion into messages.

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • promptstring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • completionstring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • inputstring≤ 128 chars

          Alpaca-style secondary input (appended to prompt when both are strings, or mapped to prompt/record input).

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • outputstring≤ 128 chars

          Output column (mapped to completion unless completion is also set, or preserved as structured record output).

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • chosenstring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • rejectedstring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • answerstring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • expected_outputstring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • toolsstring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • querystring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • positivestring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • negativesstring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • scoresstring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • labelstring≤ 128 chars

          Numeric or boolean label column mapped into scores.label when scores is not explicitly set.

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • idstring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • group_idstring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

        • session_idstring≤ 128 chars

          Matches ^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$

      • metadata_columnsmap of string

        Map of metadata key to Hugging Face column name (or dotted nested path) to preserve in each record's metadata object.

      • keep_extra_metadataboolean

        Preserve all unmapped Hugging Face columns in each record's metadata object.

      • limitinteger1–10000000
      • integrationstring≤ 64 chars

        A huggingface integration whose token reads gated or private datasets. Default: the workspace's only huggingface integration; with none, public access.

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    3. object
      • kind"benchmark"required

        "benchmark"

      • benchmarkenumrequired

        A built-in benchmark, imported from Hugging Face at a pinned revision with fixed prompts; evals on the dataset default to its answer check.

        "gsm8k""mmlu""mmlu_pro""arc_challenge""arc_easy""hellaswag""winogrande""truthfulqa_mc1""boolq""openbookqa""commonsense_qa""math500""ifeval"

      • limitinteger1–10000000

        Import the first N problems (the same ones every time).

  • connectorenumdefault "auto"

    "auto""grad_trajectories""openai_chat""gradiated""otel""langfuse""posthog""braintrust""langsmith"

Returns

202 ImportJob Queued import job.

15 fields
  • idstringrequired

    Import job id (imp_ and 24 hex characters).

  • workspace_idstringrequired
  • datasetstringrequired≤ 64 chars

    The dataset the records go into.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • statusImportStatusrequired

    "queued""running""completed""failed"

  • sourcemap of anyrequired

    Where the records come from: an upload, a Hugging Face dataset, a benchmark, or a source sync.

  • connectorenumrequired

    The parser requested for the records (auto detects it from the file).

    "auto""grad_trajectories""openai_chat""gradiated""otel""langfuse""posthog""braintrust""langsmith"

  • attemptintegerrequired≥ 0

    Attempts started so far.

  • imported_countintegerrequired≥ 0

    Records this import added to the dataset (score updates for existing records add none).

  • dropped_countintegerrequired≥ 0

    Rows that couldn't be imported; drop_reasons says why.

  • detected_scoresarray of stringrequired

    Score names found on the imported records.

  • drop_reasonsarray of stringrequired

    Why rows were dropped, one line per row (line 12: invalid JSON), capped at 100 entries.

  • dataset_versionintegerrequirednullable≥ 0

    The dataset version this import produced; null until then.

  • errorstringrequirednullable

    Why the import failed; null otherwise.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
dataset = client.datasets.from_hf(
    "HuggingFaceH4/ultrachat_200k", split="train_sft", limit=1000, name="support-prod"
)
Response 202 AcceptedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "imp_235ef2625ab31d7d988bab19",
  "workspace_id": "ws_e2e",
  "dataset": "support-prod",
  "status": "queued",
  "source": {
    "kind": "hf",
    "repo": "HuggingFaceH4/ultrachat_200k",
    "limit": 1000,
    "split": "train_sft",
    "columns": {}
  },
  "connector": "auto",
  "attempt": 0,
  "imported_count": 0,
  "dropped_count": 0,
  "detected_scores": [],
  "drop_reasons": [],
  "dataset_version": null,
  "error": null,
  "created_at": "2026-12-02T15:48:59.865Z",
  "updated_at": "2026-12-02T15:48:59.865Z"
}

List dataset import jobs#

GET/v1/imports

Newest first.

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • statusstring

    Only these statuses, comma-separated: queued, running, completed, failed.

  • datasetstring≤ 64 chars

    Only imports into this dataset.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Returns

200 object Import jobs.

2 fields
  • dataarray of ImportJobrequired
    15 child fields
    • idstringrequired

      Import job id (imp_ and 24 hex characters).

    • workspace_idstringrequired
    • datasetstringrequired≤ 64 chars

      The dataset the records go into.

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • statusImportStatusrequired

      "queued""running""completed""failed"

    • sourcemap of anyrequired

      Where the records come from: an upload, a Hugging Face dataset, a benchmark, or a source sync.

    • connectorenumrequired

      The parser requested for the records (auto detects it from the file).

      "auto""grad_trajectories""openai_chat""gradiated""otel""langfuse""posthog""braintrust""langsmith"

    • attemptintegerrequired≥ 0

      Attempts started so far.

    • imported_countintegerrequired≥ 0

      Records this import added to the dataset (score updates for existing records add none).

    • dropped_countintegerrequired≥ 0

      Rows that couldn't be imported; drop_reasons says why.

    • detected_scoresarray of stringrequired

      Score names found on the imported records.

    • drop_reasonsarray of stringrequired

      Why rows were dropped, one line per row (line 12: invalid JSON), capped at 100 entries.

    • dataset_versionintegerrequirednullable≥ 0

      The dataset version this import produced; null until then.

    • errorstringrequirednullable

      Why the import failed; null otherwise.

    • created_atstring (date-time)required
    • updated_atstring (date-time)required
  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for job in client.imports.list(status="failed", dataset="support-prod"):
    print(job.id, job.error)
Response 200 OKGenerated from the schema
JSON
{
  "data": [
    {
      "id": "imp_3f9c0a1b2c3d4e5f60718293",
      "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
      "dataset": "support-prod",
      "status": "queued",
      "source": {},
      "connector": "auto",
      "attempt": 0,
      "imported_count": 0,
      "dropped_count": 0,
      "detected_scores": [
        "string"
      ],
      "drop_reasons": [
        "string"
      ],
      "dataset_version": 0,
      "error": "…",
      "created_at": "2026-11-28T09:30:00.000Z",
      "updated_at": "2026-11-28T09:30:00.000Z"
    }
  ],
  "next_cursor": "string"
}

Get a dataset import job#

GET/v1/imports/{id}

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 ImportJob Import job.

15 fields
  • idstringrequired

    Import job id (imp_ and 24 hex characters).

  • workspace_idstringrequired
  • datasetstringrequired≤ 64 chars

    The dataset the records go into.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • statusImportStatusrequired

    "queued""running""completed""failed"

  • sourcemap of anyrequired

    Where the records come from: an upload, a Hugging Face dataset, a benchmark, or a source sync.

  • connectorenumrequired

    The parser requested for the records (auto detects it from the file).

    "auto""grad_trajectories""openai_chat""gradiated""otel""langfuse""posthog""braintrust""langsmith"

  • attemptintegerrequired≥ 0

    Attempts started so far.

  • imported_countintegerrequired≥ 0

    Records this import added to the dataset (score updates for existing records add none).

  • dropped_countintegerrequired≥ 0

    Rows that couldn't be imported; drop_reasons says why.

  • detected_scoresarray of stringrequired

    Score names found on the imported records.

  • drop_reasonsarray of stringrequired

    Why rows were dropped, one line per row (line 12: invalid JSON), capped at 100 entries.

  • dataset_versionintegerrequirednullable≥ 0

    The dataset version this import produced; null until then.

  • errorstringrequirednullable

    Why the import failed; null otherwise.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
job = client.imports.get("imp_3f9c0a1b2c3d4e5f60718293")
print(job.status, job.imported_count)
Response 200 OKGenerated from the schema
JSON
{
  "id": "imp_3f9c0a1b2c3d4e5f60718293",
  "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
  "dataset": "support-prod",
  "status": "queued",
  "source": {},
  "connector": "auto",
  "attempt": 0,
  "imported_count": 0,
  "dropped_count": 0,
  "detected_scores": [
    "string"
  ],
  "drop_reasons": [
    "string"
  ],
  "dataset_version": 0,
  "error": "…",
  "created_at": "2026-11-28T09:30:00.000Z",
  "updated_at": "2026-11-28T09:30:00.000Z"
}

Runs#

Dry-run a training recipe at zero cost#

POST/v1/runs/plan

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body PlanRunRequest

  • datasetstringrequired≤ 64 chars

    Dataset to train on. The run pins its current version.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • namestringrequired≤ 64 chars

    Run name; the artifact it produces is released as name@version.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • recipeRecipeSpecrequired
    50 child fields
    • kindRecipeKindrequired

      "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

    • modelstring≤ 160 chars
    • adapterAdapterSpec
      One of 3 shapes
      1. object
        • kind"lora"required

          "lora"

        • rankinteger1–256default 32
        • alphainteger1–512default 32
        • merge_on_exportbooleandefault false
        • train_multimodal_projectorbooleandefault false

          Also attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).

      2. object
        • kind"prefix_kv"required

          "prefix_kv"

        • num_tokensinteger16–4096default 256
      3. object
        • kind"frozen_head"required

          "frozen_head"

    • lr"auto" or numberdefault "auto"
      One of 2 shapes
      1. "auto"
      2. number
    • lr_scalenumber> 0≤ 100default 1
    • batch_sizeinteger1–4096
    • epochsinteger1–20default 1
    • scheduleenumdefault "linear"

      "linear""cosine""constant"

    • warmupnumber0–0.5default 0.03
    • train_onenum

      Which assistant turns are trained (default 'last'; LLM recipes only).

      "last""all_assistant"

    • thinkingenum

      Thinking mode for chat rendering (default 'auto'; LLM recipes only).

      "auto""on""off"

    • preserve_thinkingboolean

      Whether earlier assistant turns keep their reasoning in the prompt (default false; LLM recipes only).

    • reductionenum

      Default per_example (LLM recipes only).

      "per_example""per_token"

    • selectenumdefault "best"

      "best""last"

    • checkpoint_ttl_daysinteger1–365default 30
    • betanumber> 0
    • modelsarray of string
    • max_quality_dropnumber0–0.5
    • context_textstring≤ 4000000 chars
    • num_tokensinteger16–4096
    • tempnumber> 0
    • teacherstring≤ 160 chars

      CartridgeRecipe and DistillRecipe: the model to learn from. DistillRecipe also takes an artifact (name@version) with rollout off_policy.

    • rolloutRolloutSpec

      DistillRecipe: on_policy (default) samples answers from the student and the trainer scores them with the teacher's top-k logits; off_policy has the teacher answer each prompt once through the inference endpoint and trains the student on those answers.

      One of 2 shapes
      1. object
        • kind"on_policy"required

          "on_policy"

        • max_new_tokens"auto" or integer

          Length of each student answer; auto (default) sizes it from the assistant turns in your records (256 without any).

          One of 2 shapes
          1. "auto"
          2. integer
      2. object
        • kind"off_policy"required

          "off_policy"

        • max_new_tokensinteger1–8192
    • optimizerOptimizerSpec
      4 child fields
      • kind"adamw"default "adamw"

        "adamw"

      • betasarray of anydefault [0.9,0.95]
      • weight_decaynumber0–1default 0
      • grad_clipnumber0–1000default 1

        Max global gradient norm; 0 disables clipping.

    • eval_every"auto" or integerdefault "auto"

      Optimizer steps between held-out evaluations; auto = every 25% of the run, at most every 20 steps; each eval step is also a checkpoint.

      One of 2 shapes
      1. "auto"
      2. integer
    • lossLossSpec
      One of 5 shapes
      1. object
        • kind"cross_entropy"required

          "cross_entropy"

        • reductionenum

          "per_example""per_token"

      2. object
        • kind"dpo"required

          "dpo"

        • betanumber> 0
      3. object
        • kind"infonce"required

          "infonce"

        • tempnumber> 0
      4. object
        • kind"top_k_kl_distill"required

          "top_k_kl_distill"

        • top_kinteger1–256
      5. object
        • kind"grpo"required

          "grpo"

        • clip_lownumber0–1
        • clip_highnumber0–1
    • poolPoolingSpec
      1 child fields
      • kindenumrequired

        "mean""cls""last_token"

    • matryoshka_dimsarray of integer1–16 items

      EmbeddingRecipe: Matryoshka Representation Learning truncation dimensions (e.g. [64, 128, 256, 512]).

    • query_prefixstring≤ 512 chars

      EmbeddingRecipe: text prepended to every query before tokenization.

    • doc_prefixstring≤ 512 chars

      EmbeddingRecipe: text prepended to every positive and negative document before tokenization.

    • max_seq_leninteger16–32768

      EmbeddingRecipe: maximum token length per text (capped at the encoder's context window).

    • rubricstring or array of EvalRubricItem

      RouterRecipe: a score name on your records (scores[rubric]), or Judge/validator items: the server then replays each prompt against recipe.models and scores the answers in a labeling eval before training. RewardModelRecipe: a score name in [0, 1] on records ending in an assistant turn, trained pointwise next to the chosen/rejected pairs.

      One of 2 shapes
      1. string
      2. array of EvalRubricItem
        • namestringrequired≤ 80 chars

          Matches ^[A-Za-z0-9_.:-]+$

        • kindenumrequired

          "regex""validator""code""judge"

        • weightnumber> 0default 1
        • patternstring≤ 256 chars
        • flagsstring≤ 4 chars

          Matches ^[imsu]*$

        • validatorenum

          "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

        • modelstring≤ 160 chars
        • promptstring≤ 8000 chars
        • runtime"local"

          Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

          "local"

    • pricingmap of number

      RouterRecipe: USD per request for each candidate; overrides metrics.cost_usd on your records.

    • fallbackstring≤ 160 chars

      RouterRecipe: the candidate that gets every request the router does not offload (default: the best-scoring candidate).

    • max_new_tokensinteger1–8192

      CartridgeRecipe: teacher answer length per prompt during distillation (default 256).

    • slot_tokenstring≤ 64 chars

      CartridgeRecipe: a reserved token that marks where the cartridge goes (default: the first reserved token that tokenizes atomically).

    • validatorenum

      GRPORecipe: built-in deterministic reward validator (default 'exact_match'; 'math' aliases 'math_equivalence', 'json_valid' aliases 'json').

      "exact_match""contains""math""math_equivalence""final_number""choice""json""json_valid""non_empty""regex"

    • validator_patternstring≤ 256 chars

      GRPORecipe: regular expression pattern used when validator is 'regex'.

    • system_promptstring≤ 16384 chars

      GRPORecipe: optional system prompt prepended to every prompt before rollout generation.

    • group_sizeinteger2–64

      GRPORecipe: completions sampled per prompt in each rollout group (default 8, min 2).

    • max_tokensinteger1–8192

      GRPORecipe: maximum generated tokens per sampled completion (default 1024).

    • temperaturenumber> 0≤ 2

      GRPORecipe: rollout sampling temperature in (0, 2] (default 1.0; top_p is fixed at 1.0 for exact importance sampling).

    • advantageenum

      GRPORecipe: group advantage estimator: 'group_std' (GRPO, default), 'dr_grpo' (mean-centered without std division), or 'rloo' (leave-one-out).

      "group_std""dr_grpo""rloo"

    • kl_coefnumber0–10

      GRPORecipe: Schulman k3 KL penalty coefficient against initial/base weights (default 0.04; 0 disables KL).

    • clip_lownumber0–1

      GRPORecipe: lower PPO/GRPO importance-ratio clip epsilon (default 0.2).

    • clip_highnumber0–1

      GRPORecipe: upper PPO/GRPO importance-ratio clip epsilon (default 0.2; e.g. 0.28 for DAPO Clip-Higher).

    • skip_zero_varboolean

      GRPORecipe: skip prompt groups whose rollout rewards have near-zero variance (default true).

    • max_stepsinteger1–100000

      GRPORecipe: optional maximum number of optimizer steps (caps epochs * steps_per_epoch).

    • evalsarray of RecipeEval1–4 items

      Extra evals on each checkpoint during training (the eval executor, billed like any eval). Results are in run.checkpoint_evals, the run's checkpoint_eval events and eval_report.checkpoint_evals.

      5 child fields
      • datasetstringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • versioninteger≥ 1

        Dataset version (default: the current one, pinned at plan time).

      • rubricarray of EvalRubricItem1–32 items

        Judges, regexes and validators (default: the dataset's own rubric, such as a benchmark's answer check). Code scorers can't run during training.

        9 child fields
        • namestringrequired≤ 80 chars

          Matches ^[A-Za-z0-9_.:-]+$

        • kindenumrequired

          "regex""validator""code""judge"

        • weightnumber> 0default 1
        • patternstring≤ 256 chars
        • flagsstring≤ 4 chars

          Matches ^[imsu]*$

        • validatorenum

          "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

        • modelstring≤ 160 chars
        • promptstring≤ 8000 chars
        • runtime"local"

          Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

          "local"

      • limitinteger1–100000

        Evaluate the first N tasks at each checkpoint.

      • namestring≤ 64 chars

        Name of this eval in the report (default: the dataset name).

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • loggersarray of LoggerSpec1–4 items

      Experiment trackers that receive the run's metrics. A tracker that fails is reported and dropped; it never fails the run.

  • splitSplitSpec
    3 child fields
    • strategyenumdefault "by_session"

      "by_session""by_group""random"

    • eval_fractionnumber0–0.5
    • seedintegerdefault 42
  • max_cost_usdnumber> 0

    Hard spend cap in USD. The run stops with stopped_budget and keeps its checkpoint when it reaches the cap, and is never billed past it. Default: no cap.

Returns

200 PlanRunResponse Resolved defaults and cost estimate.

16 fields
  • resolved_configResolvedRunConfigrequired
    29 child fields
    • rule_versionstringrequired

      The version of the rules that resolved the auto defaults (auto@2); a config keeps resolving the same way.

    • datasetstringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • dataset_versionintegerrequired≥ 0

      The pinned dataset version.

    • namestringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • recipe_kindRecipeKindrequired

      "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

    • modelstringrequired

      The base model trained.

    • template_revisionstringrequired

      The pinned chat template (qwen3@3); evals of the run's checkpoints use it too.

    • adapterobject or object or object or objectrequired
      One of 4 shapes
      1. object
        • kind"lora"required

          "lora"

        • rankinteger1–256default 32
        • alphainteger1–512default 32
        • merge_on_exportbooleandefault false
        • train_multimodal_projectorbooleandefault false

          Also attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).

      2. object
        • kind"prefix_kv"required

          "prefix_kv"

        • num_tokensinteger16–4096default 256
      3. object
        • kind"frozen_head"required

          "frozen_head"

      4. object
        • kind"encoder_full"required

          "encoder_full"

    • lrnumberrequired> 0

      The resolved learning rate.

    • lr_sourcestringrequired

      Where lr came from: the calibrated rule (auto@2: calibrated for ... at batch 128, sqrt batch scaling) or the value you passed.

    • batch_sizeintegerrequired≥ 1

      Training examples per optimizer step.

    • epochsintegerrequired≥ 1

      Passes over the training split.

    • scheduleenumrequired

      Learning-rate schedule after warmup.

      "linear""cosine""constant"

    • warmupnumberrequired

      The fraction of steps spent warming up the learning rate.

    • train_onenumrequired

      Which assistant turns are trained: the last one, or every one.

      "last""all_assistant"

    • thinkingenumrequired

      Thinking mode the records are rendered with.

      "auto""on""off"

    • preserve_thinkingbooleanrequired

      Whether earlier assistant turns keep their reasoning in the prompt.

    • reductionenumrequired

      How the loss averages: per example, then across the batch, or per token.

      "per_example""per_token"

    • selectenumrequired

      Which checkpoint becomes the artifact: the best by the held-out metric, or the last.

      "best""last"

    • checkpoint_every_stepsintegerrequired≥ 1

      Steps between checkpoints.

    • eval_every_stepsintegerrequired≥ 1

      Steps between held-out evaluations.

    • optimizerOptimizerSpecrequired
      4 child fields
      • kind"adamw"default "adamw"

        "adamw"

      • betasarray of anydefault [0.9,0.95]
      • weight_decaynumber0–1default 0
      • grad_clipnumber0–1000default 1

        Max global gradient norm; 0 disables clipping.

    • checkpoint_ttl_daysintegerrequired≥ 1

      Days an intermediate checkpoint is kept; the best and final never expire.

    • splitobjectrequired
      5 child fields
      • strategyenumrequired

        "by_session""by_group""random"

      • eval_fractionnumberrequired
      • seedintegerrequired
      • train_recordsintegerrequired≥ 0
      • eval_recordsintegerrequired≥ 0
    • label_eval_idstringrequirednullable

      The labeling eval whose answers the run trains on: router runs with a Judge/validator rubric, and off-policy distill runs (the teacher's answers).

    • base_artifactBaseArtifactrequirednullable

      Continued training: the artifact whose adapter the run starts from (recipe.model was an artifact reference).

    • recipe_paramsmap of anyrequired

      The recipe's own settings (router candidates, DPO beta, a cartridge's context, ...).

    • checkpoint_evalsarray of object

      recipe.evals, with the dataset version and rubric pinned.

      5 child fields
      • namestringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • datasetstringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • dataset_versionintegerrequired≥ 1
      • rubricarray of EvalRubricItemrequired
        9 child fields
        • namestringrequired≤ 80 chars

          Matches ^[A-Za-z0-9_.:-]+$

        • kindenumrequired

          "regex""validator""code""judge"

        • weightnumber> 0default 1
        • patternstring≤ 256 chars
        • flagsstring≤ 4 chars

          Matches ^[imsu]*$

        • validatorenum

          "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

        • modelstring≤ 160 chars
        • promptstring≤ 8000 chars
        • runtime"local"

          Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

          "local"

      • limitintegerrequirednullable≥ 1
    • loggersarray of LoggerSpec
  • dataset_versionintegerrequired≥ 0

    The dataset version the run would pin.

  • usable_recordsintegerrequired≥ 0

    Records the recipe can train on (the rest are skipped; a warning says why).

  • total_recordsintegerrequired≥ 0

    Records in the dataset version.

  • estimated_stepsintegerrequired≥ 0

    Optimizer steps the run would take.

  • estimated_tokensintegerrequired≥ 0

    Tokens the run would process (billed tokens).

  • estimated_cost_usdnumberrequired≥ 0

    Everything the run is expected to bill: training (and teacher) tokens, plus the evals it starts (labeling, recipe.evals). See cost_breakdown.

  • estimated_duration_sintegerrequired≥ 0

    Wall-clock estimate in seconds on one H100 80 GB: model load and export, training at the measured tokens/s for this base and recipe, evaluations and checkpoints. Excludes queueing and any labeling eval.

  • min_gpu_memory_gbnumberrequirednullable> 0

    GPU memory (GB) this run needs: the base's min_gpu_memory_gb plus a teacher loaded beside it. Null when the base's requirement is unknown.

  • price_per_million_tokensnumberrequired> 0

    The base model's price, USD per million tokens.

  • trained_token_fractionnumberrequired0–1

    The share of tokens that are trained on (the loss mask), the rest being prompt context.

  • labelingobjectrequirednullable

    The labeling eval that runs before training (billed as an eval, included in estimated_cost_usd): router runs with a Judge/validator rubric replay prompts against the candidates; off-policy distill runs have the teacher answer each prompt.

    3 child fields
    • estimated_model_callsintegerrequired≥ 0
    • estimated_judge_callsintegerrequired≥ 0
    • estimated_cost_usdnumberrequired≥ 0
  • teacherobjectrequirednullable

    On-policy distill runs: the teacher's scoring tokens at the teacher's price (included in estimated_tokens as student-price tokens, and in estimated_cost_usd).

    4 child fields
    • modelstringrequired
    • price_per_million_tokensnumberrequired≥ 0
    • estimated_tokensintegerrequired≥ 0
    • estimated_cost_usdnumberrequired≥ 0
  • cost_breakdownPlanCostBreakdownrequired

    estimated_cost_usd split by what bills it; the parts sum to it (to rounding).

    3 child fields
    • train_usdnumberrequired≥ 0

      The base model's tokens on every training step: each record (or both sides of a preference pair) once per epoch, at price_per_million_tokens. Held-out evaluation during training is not billed.

    • teacher_usdnumberrequired≥ 0

      The teacher's tokens (on-policy distill), at its price.

    • eval_usdnumberrequired≥ 0

      Evals the run starts, billed as evals: the labeling eval before training and recipe.evals on every checkpoint.

  • router_summaryRouterPlanSummarynullable

    Pre-flight router data health summary (populated for router recipes; null otherwise).

  • warningsarray of stringrequired

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad
from grad.recipes import SFTRecipe

client = Grad()
plan = client.runs.plan(
    dataset="support-prod",
    name="support-sft",
    recipe=SFTRecipe(model="qwen/qwen3-8b"),
    max_cost_usd=5,
)
print(plan)  # steps, tokens, cost and warnings; nothing is billed
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "resolved_config": {
    "rule_version": "auto@2",
    "dataset": "support-prod",
    "dataset_version": 1,
    "name": "support-sft",
    "recipe_kind": "sft",
    "model": "qwen/qwen3-8b",
    "template_revision": "qwen3@3",
    "adapter": {
      "kind": "lora",
      "rank": 32,
      "alpha": 32,
      "merge_on_export": false,
      "train_multimodal_projector": false
    },
    "lr": 0.000125,
    "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
    "batch_size": 8,
    "epochs": 1,
    "schedule": "linear",
    "warmup": 0.03,
    "train_on": "last",
    "thinking": "auto",
    "preserve_thinking": false,
    "reduction": "per_example",
    "select": "best",
    "checkpoint_every_steps": 1,
    "eval_every_steps": 1,
    "optimizer": {
      "kind": "adamw",
      "betas": [
        0.9,
        0.95
      ],
      "weight_decay": 0,
      "grad_clip": 1
    },
    "checkpoint_ttl_days": 30,
    "split": {
      "strategy": "by_session",
      "eval_fraction": 0.1,
      "seed": 42,
      "train_records": 1,
      "eval_records": 0
    },
    "label_eval_id": null,
    "base_artifact": null,
    "recipe_params": {}
  },
  "dataset_version": 1,
  "usable_records": 1,
  "total_records": 1,
  "estimated_steps": 1,
  "estimated_tokens": 33,
  "estimated_cost_usd": 0,
  "estimated_duration_s": 97,
  "min_gpu_memory_gb": 36,
  "price_per_million_tokens": 0.4,
  "trained_token_fraction": 0.4242,
  "labeling": null,
  "teacher": null,
  "cost_breakdown": {
    "train_usd": 0,
    "teacher_usd": 0,
    "eval_usd": 0
  },
  "router_summary": null,
  "warnings": [
    "The eval split is empty; eval metrics will be unavailable. Add records or raise split.eval_fraction.",
    "Training thinking model 'qwen/qwen3-8b' with thinking='auto', but 0% of assistant turns contain <think> reasoning. Pass thinking='off' if non-thinking answers are intended, or verify your traces include <think>...</think> reasoning."
  ]
}

Create and enqueue a training run#

POST/v1/runs

Pins the dataset version.

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body PlanRunRequest

  • datasetstringrequired≤ 64 chars

    Dataset to train on. The run pins its current version.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • namestringrequired≤ 64 chars

    Run name; the artifact it produces is released as name@version.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • recipeRecipeSpecrequired
    50 child fields
    • kindRecipeKindrequired

      "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

    • modelstring≤ 160 chars
    • adapterAdapterSpec
      One of 3 shapes
      1. object
        • kind"lora"required

          "lora"

        • rankinteger1–256default 32
        • alphainteger1–512default 32
        • merge_on_exportbooleandefault false
        • train_multimodal_projectorbooleandefault false

          Also attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).

      2. object
        • kind"prefix_kv"required

          "prefix_kv"

        • num_tokensinteger16–4096default 256
      3. object
        • kind"frozen_head"required

          "frozen_head"

    • lr"auto" or numberdefault "auto"
      One of 2 shapes
      1. "auto"
      2. number
    • lr_scalenumber> 0≤ 100default 1
    • batch_sizeinteger1–4096
    • epochsinteger1–20default 1
    • scheduleenumdefault "linear"

      "linear""cosine""constant"

    • warmupnumber0–0.5default 0.03
    • train_onenum

      Which assistant turns are trained (default 'last'; LLM recipes only).

      "last""all_assistant"

    • thinkingenum

      Thinking mode for chat rendering (default 'auto'; LLM recipes only).

      "auto""on""off"

    • preserve_thinkingboolean

      Whether earlier assistant turns keep their reasoning in the prompt (default false; LLM recipes only).

    • reductionenum

      Default per_example (LLM recipes only).

      "per_example""per_token"

    • selectenumdefault "best"

      "best""last"

    • checkpoint_ttl_daysinteger1–365default 30
    • betanumber> 0
    • modelsarray of string
    • max_quality_dropnumber0–0.5
    • context_textstring≤ 4000000 chars
    • num_tokensinteger16–4096
    • tempnumber> 0
    • teacherstring≤ 160 chars

      CartridgeRecipe and DistillRecipe: the model to learn from. DistillRecipe also takes an artifact (name@version) with rollout off_policy.

    • rolloutRolloutSpec

      DistillRecipe: on_policy (default) samples answers from the student and the trainer scores them with the teacher's top-k logits; off_policy has the teacher answer each prompt once through the inference endpoint and trains the student on those answers.

      One of 2 shapes
      1. object
        • kind"on_policy"required

          "on_policy"

        • max_new_tokens"auto" or integer

          Length of each student answer; auto (default) sizes it from the assistant turns in your records (256 without any).

          One of 2 shapes
          1. "auto"
          2. integer
      2. object
        • kind"off_policy"required

          "off_policy"

        • max_new_tokensinteger1–8192
    • optimizerOptimizerSpec
      4 child fields
      • kind"adamw"default "adamw"

        "adamw"

      • betasarray of anydefault [0.9,0.95]
      • weight_decaynumber0–1default 0
      • grad_clipnumber0–1000default 1

        Max global gradient norm; 0 disables clipping.

    • eval_every"auto" or integerdefault "auto"

      Optimizer steps between held-out evaluations; auto = every 25% of the run, at most every 20 steps; each eval step is also a checkpoint.

      One of 2 shapes
      1. "auto"
      2. integer
    • lossLossSpec
      One of 5 shapes
      1. object
        • kind"cross_entropy"required

          "cross_entropy"

        • reductionenum

          "per_example""per_token"

      2. object
        • kind"dpo"required

          "dpo"

        • betanumber> 0
      3. object
        • kind"infonce"required

          "infonce"

        • tempnumber> 0
      4. object
        • kind"top_k_kl_distill"required

          "top_k_kl_distill"

        • top_kinteger1–256
      5. object
        • kind"grpo"required

          "grpo"

        • clip_lownumber0–1
        • clip_highnumber0–1
    • poolPoolingSpec
      1 child fields
      • kindenumrequired

        "mean""cls""last_token"

    • matryoshka_dimsarray of integer1–16 items

      EmbeddingRecipe: Matryoshka Representation Learning truncation dimensions (e.g. [64, 128, 256, 512]).

    • query_prefixstring≤ 512 chars

      EmbeddingRecipe: text prepended to every query before tokenization.

    • doc_prefixstring≤ 512 chars

      EmbeddingRecipe: text prepended to every positive and negative document before tokenization.

    • max_seq_leninteger16–32768

      EmbeddingRecipe: maximum token length per text (capped at the encoder's context window).

    • rubricstring or array of EvalRubricItem

      RouterRecipe: a score name on your records (scores[rubric]), or Judge/validator items: the server then replays each prompt against recipe.models and scores the answers in a labeling eval before training. RewardModelRecipe: a score name in [0, 1] on records ending in an assistant turn, trained pointwise next to the chosen/rejected pairs.

      One of 2 shapes
      1. string
      2. array of EvalRubricItem
        • namestringrequired≤ 80 chars

          Matches ^[A-Za-z0-9_.:-]+$

        • kindenumrequired

          "regex""validator""code""judge"

        • weightnumber> 0default 1
        • patternstring≤ 256 chars
        • flagsstring≤ 4 chars

          Matches ^[imsu]*$

        • validatorenum

          "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

        • modelstring≤ 160 chars
        • promptstring≤ 8000 chars
        • runtime"local"

          Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

          "local"

    • pricingmap of number

      RouterRecipe: USD per request for each candidate; overrides metrics.cost_usd on your records.

    • fallbackstring≤ 160 chars

      RouterRecipe: the candidate that gets every request the router does not offload (default: the best-scoring candidate).

    • max_new_tokensinteger1–8192

      CartridgeRecipe: teacher answer length per prompt during distillation (default 256).

    • slot_tokenstring≤ 64 chars

      CartridgeRecipe: a reserved token that marks where the cartridge goes (default: the first reserved token that tokenizes atomically).

    • validatorenum

      GRPORecipe: built-in deterministic reward validator (default 'exact_match'; 'math' aliases 'math_equivalence', 'json_valid' aliases 'json').

      "exact_match""contains""math""math_equivalence""final_number""choice""json""json_valid""non_empty""regex"

    • validator_patternstring≤ 256 chars

      GRPORecipe: regular expression pattern used when validator is 'regex'.

    • system_promptstring≤ 16384 chars

      GRPORecipe: optional system prompt prepended to every prompt before rollout generation.

    • group_sizeinteger2–64

      GRPORecipe: completions sampled per prompt in each rollout group (default 8, min 2).

    • max_tokensinteger1–8192

      GRPORecipe: maximum generated tokens per sampled completion (default 1024).

    • temperaturenumber> 0≤ 2

      GRPORecipe: rollout sampling temperature in (0, 2] (default 1.0; top_p is fixed at 1.0 for exact importance sampling).

    • advantageenum

      GRPORecipe: group advantage estimator: 'group_std' (GRPO, default), 'dr_grpo' (mean-centered without std division), or 'rloo' (leave-one-out).

      "group_std""dr_grpo""rloo"

    • kl_coefnumber0–10

      GRPORecipe: Schulman k3 KL penalty coefficient against initial/base weights (default 0.04; 0 disables KL).

    • clip_lownumber0–1

      GRPORecipe: lower PPO/GRPO importance-ratio clip epsilon (default 0.2).

    • clip_highnumber0–1

      GRPORecipe: upper PPO/GRPO importance-ratio clip epsilon (default 0.2; e.g. 0.28 for DAPO Clip-Higher).

    • skip_zero_varboolean

      GRPORecipe: skip prompt groups whose rollout rewards have near-zero variance (default true).

    • max_stepsinteger1–100000

      GRPORecipe: optional maximum number of optimizer steps (caps epochs * steps_per_epoch).

    • evalsarray of RecipeEval1–4 items

      Extra evals on each checkpoint during training (the eval executor, billed like any eval). Results are in run.checkpoint_evals, the run's checkpoint_eval events and eval_report.checkpoint_evals.

      5 child fields
      • datasetstringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • versioninteger≥ 1

        Dataset version (default: the current one, pinned at plan time).

      • rubricarray of EvalRubricItem1–32 items

        Judges, regexes and validators (default: the dataset's own rubric, such as a benchmark's answer check). Code scorers can't run during training.

        9 child fields
        • namestringrequired≤ 80 chars

          Matches ^[A-Za-z0-9_.:-]+$

        • kindenumrequired

          "regex""validator""code""judge"

        • weightnumber> 0default 1
        • patternstring≤ 256 chars
        • flagsstring≤ 4 chars

          Matches ^[imsu]*$

        • validatorenum

          "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

        • modelstring≤ 160 chars
        • promptstring≤ 8000 chars
        • runtime"local"

          Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

          "local"

      • limitinteger1–100000

        Evaluate the first N tasks at each checkpoint.

      • namestring≤ 64 chars

        Name of this eval in the report (default: the dataset name).

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • loggersarray of LoggerSpec1–4 items

      Experiment trackers that receive the run's metrics. A tracker that fails is reported and dropped; it never fails the run.

  • splitSplitSpec
    3 child fields
    • strategyenumdefault "by_session"

      "by_session""by_group""random"

    • eval_fractionnumber0–0.5
    • seedintegerdefault 42
  • max_cost_usdnumber> 0

    Hard spend cap in USD. The run stops with stopped_budget and keeps its checkpoint when it reaches the cap, and is never billed past it. Default: no cap.

Returns

202 Run Enqueued training run.

35 fields
  • idstringrequired

    Run id (run_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Run name; its artifact is released as name@version.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • dataset_idstringrequired

    Id of the dataset trained on.

  • dataset_namestringrequired≤ 64 chars

    Name of the dataset trained on.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • dataset_versionintegerrequired≥ 0

    The dataset version the run pinned when it was created.

  • recipe_kindRecipeKindrequired

    "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

  • statusRunStatusrequired

    stopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.

    "queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"

  • resolved_configResolvedRunConfigrequired
    29 child fields
    • rule_versionstringrequired

      The version of the rules that resolved the auto defaults (auto@2); a config keeps resolving the same way.

    • datasetstringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • dataset_versionintegerrequired≥ 0

      The pinned dataset version.

    • namestringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • recipe_kindRecipeKindrequired

      "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

    • modelstringrequired

      The base model trained.

    • template_revisionstringrequired

      The pinned chat template (qwen3@3); evals of the run's checkpoints use it too.

    • adapterobject or object or object or objectrequired
      One of 4 shapes
      1. object
        • kind"lora"required

          "lora"

        • rankinteger1–256default 32
        • alphainteger1–512default 32
        • merge_on_exportbooleandefault false
        • train_multimodal_projectorbooleandefault false

          Also attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).

      2. object
        • kind"prefix_kv"required

          "prefix_kv"

        • num_tokensinteger16–4096default 256
      3. object
        • kind"frozen_head"required

          "frozen_head"

      4. object
        • kind"encoder_full"required

          "encoder_full"

    • lrnumberrequired> 0

      The resolved learning rate.

    • lr_sourcestringrequired

      Where lr came from: the calibrated rule (auto@2: calibrated for ... at batch 128, sqrt batch scaling) or the value you passed.

    • batch_sizeintegerrequired≥ 1

      Training examples per optimizer step.

    • epochsintegerrequired≥ 1

      Passes over the training split.

    • scheduleenumrequired

      Learning-rate schedule after warmup.

      "linear""cosine""constant"

    • warmupnumberrequired

      The fraction of steps spent warming up the learning rate.

    • train_onenumrequired

      Which assistant turns are trained: the last one, or every one.

      "last""all_assistant"

    • thinkingenumrequired

      Thinking mode the records are rendered with.

      "auto""on""off"

    • preserve_thinkingbooleanrequired

      Whether earlier assistant turns keep their reasoning in the prompt.

    • reductionenumrequired

      How the loss averages: per example, then across the batch, or per token.

      "per_example""per_token"

    • selectenumrequired

      Which checkpoint becomes the artifact: the best by the held-out metric, or the last.

      "best""last"

    • checkpoint_every_stepsintegerrequired≥ 1

      Steps between checkpoints.

    • eval_every_stepsintegerrequired≥ 1

      Steps between held-out evaluations.

    • optimizerOptimizerSpecrequired
      4 child fields
      • kind"adamw"default "adamw"

        "adamw"

      • betasarray of anydefault [0.9,0.95]
      • weight_decaynumber0–1default 0
      • grad_clipnumber0–1000default 1

        Max global gradient norm; 0 disables clipping.

    • checkpoint_ttl_daysintegerrequired≥ 1

      Days an intermediate checkpoint is kept; the best and final never expire.

    • splitobjectrequired
      5 child fields
      • strategyenumrequired

        "by_session""by_group""random"

      • eval_fractionnumberrequired
      • seedintegerrequired
      • train_recordsintegerrequired≥ 0
      • eval_recordsintegerrequired≥ 0
    • label_eval_idstringrequirednullable

      The labeling eval whose answers the run trains on: router runs with a Judge/validator rubric, and off-policy distill runs (the teacher's answers).

    • base_artifactBaseArtifactrequirednullable

      Continued training: the artifact whose adapter the run starts from (recipe.model was an artifact reference).

    • recipe_paramsmap of anyrequired

      The recipe's own settings (router candidates, DPO beta, a cartridge's context, ...).

    • checkpoint_evalsarray of object

      recipe.evals, with the dataset version and rubric pinned.

      5 child fields
      • namestringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • datasetstringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • dataset_versionintegerrequired≥ 1
      • rubricarray of EvalRubricItemrequired
        9 child fields
        • namestringrequired≤ 80 chars

          Matches ^[A-Za-z0-9_.:-]+$

        • kindenumrequired

          "regex""validator""code""judge"

        • weightnumber> 0default 1
        • patternstring≤ 256 chars
        • flagsstring≤ 4 chars

          Matches ^[imsu]*$

        • validatorenum

          "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

        • modelstring≤ 160 chars
        • promptstring≤ 8000 chars
        • runtime"local"

          Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

          "local"

      • limitintegerrequirednullable≥ 1
    • loggersarray of LoggerSpec
  • max_cost_usdnumberrequirednullable> 0

    Hard spend cap in USD (null: none). The run is never billed past it.

  • price_per_million_tokensnumberrequired> 0

    USD per million tokens processed, fixed when the run was created.

  • tokens_processedintegerrequired≥ 0

    Training tokens processed so far, over every attempt.

  • cost_usdnumberrequired≥ 0

    Cost of the tokens processed so far, in USD. It counts the whole step that crossed max_cost_usd; billing stops at the cap.

  • current_stepintegerrequired≥ 0

    Last optimizer step reported.

  • total_stepsintegerrequired≥ 0

    Planned optimizer steps.

  • attemptintegerrequired≥ 0

    Attempts started so far (every start on a worker counts, including ones whose GPU was reclaimed).

  • max_attemptsintegerrequired≥ 1

    The run fails once this many attempts end without a result (lost worker, worker error, OOM). Attempts whose GPU was reclaimed don't count toward it.

  • phaseenumrequirednullable

    What the run is doing now; null once it has finished (finished_at is set). A cancelled run whose worker hasn't stopped yet reads stopping. The run's events keep every phase it went through.

    "queued""waiting_for_compute""starting""loading_model""training""evaluating""checkpointing""uploading""completing""stopping"null

  • phase_sincestring (date-time)requirednullable

    When the run entered its phase; null with phase.

  • last_interruptionRunInterruptionrequirednullable
  • workers_onlineintegerrequirednullable≥ 0

    While queued: workers of this kind holding a lease (all busy). Null otherwise.

  • autoscalingbooleanrequirednullable

    While queued: true when workers scale from zero (KEDA), so a worker is starting. Null otherwise.

  • queue_positionintegerrequirednullable≥ 0

    While queued for a worker: about how many runs start before this one. Claims are fair across workspaces (the workspace with the fewest running runs goes next), so this counts other workspaces' runs too. Approximate; null otherwise.

  • queue_messagestringrequirednullable

    While queued for a worker: why it waits, ready to show: "Queued behind 3 runs", "Queued: workspace concurrency limit (8 running)" (the workspace runs as many as it may at once), or "Waiting for a GPU with ≥46 GB; online workers have 24 GB". Null when it is next in line, and once it is claimed.

  • min_gpu_memory_gbnumberrequirednullable> 0

    GPU memory (GB) the run needs (its plan's min_gpu_memory_gb): only workers with at least this much claim it. Null when unknown.

  • latest_metricMetricPointrequirednullable
  • eval_reportEvalReportrequirednullable
  • checkpoint_evalsarray of CheckpointEvalResultrequired

    recipe.evals results, one per finished eval: a checkpoint (step) on a dataset.

    10 child fields
    • namestringrequired
    • stepintegerrequired≥ 0
    • checkpoint_idstringrequired
    • eval_idstringrequirednullable
    • datasetstringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • dataset_versionintegerrequired≥ 1
    • statusenumrequired

      "completed""failed""cancelled"

    • scorenumberrequirednullable

      The checkpoint's overall rubric score (null unless completed).

    • cost_usdnumberrequired≥ 0
    • errorstringrequirednullable
  • artifact_idstringrequirednullable

    The released artifact (name@version) once the run completes; null before.

  • errorstringrequirednullable

    Why the run failed or stopped; null otherwise.

  • created_atstring (date-time)required

    When the run was created.

  • updated_atstring (date-time)required

    When the run last changed.

  • finished_atstring (date-time)requirednullable

    When the run reached a final status; null while it is queued or running.

  • warningsarray of string

    Only on the response that created the run (POST /v1/runs): the plan's warnings, such as another queued or running run with the same name. They're also the run's first warning events.

  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad
from grad.recipes import SFTRecipe

client = Grad()
run = client.runs.create(
    dataset="support-prod",
    name="support-sft",
    recipe=SFTRecipe(model="qwen/qwen3-8b"),
    max_cost_usd=5,
)
run.wait()  # streams progress; raises if the run fails
Response 202 AcceptedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "run_ed1c235f0c631d8f209e22a5",
  "workspace_id": "ws_e2e",
  "name": "support-sft",
  "dataset_id": "ds_c66d7ad841f251049ca0e550",
  "dataset_name": "support-prod",
  "dataset_version": 1,
  "recipe_kind": "sft",
  "status": "queued",
  "resolved_config": {
    "lr": 0.000125,
    "name": "support-sft",
    "model": "qwen/qwen3-8b",
    "split": {
      "seed": 42,
      "strategy": "by_session",
      "eval_records": 0,
      "eval_fraction": 0.1,
      "train_records": 1
    },
    "epochs": 1,
    "select": "best",
    "warmup": 0.03,
    "adapter": {
      "kind": "lora",
      "rank": 32,
      "alpha": 32,
      "merge_on_export": false,
      "train_multimodal_projector": false
    },
    "dataset": "support-prod",
    "schedule": "linear",
    "thinking": "auto",
    "train_on": "last",
    "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
    "optimizer": {
      "kind": "adamw",
      "betas": [
        0.9,
        0.95
      ],
      "grad_clip": 1,
      "weight_decay": 0
    },
    "reduction": "per_example",
    "batch_size": 8,
    "recipe_kind": "sft",
    "rule_version": "auto@2",
    "base_artifact": null,
    "label_eval_id": null,
    "recipe_params": {},
    "dataset_version": 1,
    "eval_every_steps": 1,
    "preserve_thinking": false,
    "template_revision": "qwen3@3",
    "checkpoint_ttl_days": 30,
    "checkpoint_every_steps": 1
  },
  "max_cost_usd": 5,
  "price_per_million_tokens": 0.4,
  "tokens_processed": 0,
  "cost_usd": 0,
  "current_step": 0,
  "total_steps": 1,
  "attempt": 0,
  "max_attempts": 10,
  "phase": "queued",
  "phase_since": "2026-12-02T15:48:59.895Z",
  "last_interruption": null,
  "workers_online": 0,
  "autoscaling": false,
  "queue_position": 0,
  "queue_message": null,
  "min_gpu_memory_gb": 36,
  "latest_metric": null,
  "eval_report": null,
  "checkpoint_evals": [],
  "artifact_id": null,
  "error": null,
  "created_at": "2026-12-02T15:48:59.888Z",
  "updated_at": "2026-12-02T15:48:59.888Z",
  "finished_at": null,
  "warnings": [
    "The eval split is empty; eval metrics will be unavailable. Add records or raise split.eval_fraction.",
    "Training thinking model 'qwen/qwen3-8b' with thinking='auto', but 0% of assistant turns contain <think> reasoning. Pass thinking='off' if non-thinking answers are intended, or verify your traces include <think>...</think> reasoning."
  ]
}

List training runs#

GET/v1/runs

Newest first.

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • statusstring

    Only these statuses, comma-separated: queued, running, completed, failed, cancelled, stopped_budget, stopped_balance.

  • qstring≤ 200 chars

    Only items whose name contains this text (any case), or whose id is exactly this.

Returns

200 object Training runs.

2 fields
  • dataarray of Runrequired
    35 child fields
    • idstringrequired

      Run id (run_ and 24 hex characters).

    • workspace_idstringrequired
    • namestringrequired≤ 64 chars

      Run name; its artifact is released as name@version.

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • dataset_idstringrequired

      Id of the dataset trained on.

    • dataset_namestringrequired≤ 64 chars

      Name of the dataset trained on.

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • dataset_versionintegerrequired≥ 0

      The dataset version the run pinned when it was created.

    • recipe_kindRecipeKindrequired

      "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

    • statusRunStatusrequired

      stopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.

      "queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"

    • resolved_configResolvedRunConfigrequired
      29 child fields
      • rule_versionstringrequired

        The version of the rules that resolved the auto defaults (auto@2); a config keeps resolving the same way.

      • datasetstringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • dataset_versionintegerrequired≥ 0

        The pinned dataset version.

      • namestringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • recipe_kindRecipeKindrequired

        "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

      • modelstringrequired

        The base model trained.

      • template_revisionstringrequired

        The pinned chat template (qwen3@3); evals of the run's checkpoints use it too.

      • adapterobject or object or object or objectrequired
        One of 4 shapes
        1. object
          • kind"lora"required

            "lora"

          • rankinteger1–256default 32
          • alphainteger1–512default 32
          • merge_on_exportbooleandefault false
          • train_multimodal_projectorbooleandefault false

            Also attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).

        2. object
          • kind"prefix_kv"required

            "prefix_kv"

          • num_tokensinteger16–4096default 256
        3. object
          • kind"frozen_head"required

            "frozen_head"

        4. object
          • kind"encoder_full"required

            "encoder_full"

      • lrnumberrequired> 0

        The resolved learning rate.

      • lr_sourcestringrequired

        Where lr came from: the calibrated rule (auto@2: calibrated for ... at batch 128, sqrt batch scaling) or the value you passed.

      • batch_sizeintegerrequired≥ 1

        Training examples per optimizer step.

      • epochsintegerrequired≥ 1

        Passes over the training split.

      • scheduleenumrequired

        Learning-rate schedule after warmup.

        "linear""cosine""constant"

      • warmupnumberrequired

        The fraction of steps spent warming up the learning rate.

      • train_onenumrequired

        Which assistant turns are trained: the last one, or every one.

        "last""all_assistant"

      • thinkingenumrequired

        Thinking mode the records are rendered with.

        "auto""on""off"

      • preserve_thinkingbooleanrequired

        Whether earlier assistant turns keep their reasoning in the prompt.

      • reductionenumrequired

        How the loss averages: per example, then across the batch, or per token.

        "per_example""per_token"

      • selectenumrequired

        Which checkpoint becomes the artifact: the best by the held-out metric, or the last.

        "best""last"

      • checkpoint_every_stepsintegerrequired≥ 1

        Steps between checkpoints.

      • eval_every_stepsintegerrequired≥ 1

        Steps between held-out evaluations.

      • optimizerOptimizerSpecrequired
        4 child fields
        • kind"adamw"default "adamw"

          "adamw"

        • betasarray of anydefault [0.9,0.95]
        • weight_decaynumber0–1default 0
        • grad_clipnumber0–1000default 1

          Max global gradient norm; 0 disables clipping.

      • checkpoint_ttl_daysintegerrequired≥ 1

        Days an intermediate checkpoint is kept; the best and final never expire.

      • splitobjectrequired
        5 child fields
        • strategyenumrequired

          "by_session""by_group""random"

        • eval_fractionnumberrequired
        • seedintegerrequired
        • train_recordsintegerrequired≥ 0
        • eval_recordsintegerrequired≥ 0
      • label_eval_idstringrequirednullable

        The labeling eval whose answers the run trains on: router runs with a Judge/validator rubric, and off-policy distill runs (the teacher's answers).

      • base_artifactBaseArtifactrequirednullable

        Continued training: the artifact whose adapter the run starts from (recipe.model was an artifact reference).

      • recipe_paramsmap of anyrequired

        The recipe's own settings (router candidates, DPO beta, a cartridge's context, ...).

      • checkpoint_evalsarray of object

        recipe.evals, with the dataset version and rubric pinned.

        5 child fields
        • namestringrequired≤ 64 chars

          Matches ^[a-z0-9][a-z0-9._-]{0,63}$

        • datasetstringrequired≤ 64 chars

          Matches ^[a-z0-9][a-z0-9._-]{0,63}$

        • dataset_versionintegerrequired≥ 1
        • rubricarray of EvalRubricItemrequired
          9 child fields
          • namestringrequired≤ 80 chars

            Matches ^[A-Za-z0-9_.:-]+$

          • kindenumrequired

            "regex""validator""code""judge"

          • weightnumber> 0default 1
          • patternstring≤ 256 chars
          • flagsstring≤ 4 chars

            Matches ^[imsu]*$

          • validatorenum

            "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

          • modelstring≤ 160 chars
          • promptstring≤ 8000 chars
          • runtime"local"

            Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

            "local"

        • limitintegerrequirednullable≥ 1
      • loggersarray of LoggerSpec
    • max_cost_usdnumberrequirednullable> 0

      Hard spend cap in USD (null: none). The run is never billed past it.

    • price_per_million_tokensnumberrequired> 0

      USD per million tokens processed, fixed when the run was created.

    • tokens_processedintegerrequired≥ 0

      Training tokens processed so far, over every attempt.

    • cost_usdnumberrequired≥ 0

      Cost of the tokens processed so far, in USD. It counts the whole step that crossed max_cost_usd; billing stops at the cap.

    • current_stepintegerrequired≥ 0

      Last optimizer step reported.

    • total_stepsintegerrequired≥ 0

      Planned optimizer steps.

    • attemptintegerrequired≥ 0

      Attempts started so far (every start on a worker counts, including ones whose GPU was reclaimed).

    • max_attemptsintegerrequired≥ 1

      The run fails once this many attempts end without a result (lost worker, worker error, OOM). Attempts whose GPU was reclaimed don't count toward it.

    • phaseenumrequirednullable

      What the run is doing now; null once it has finished (finished_at is set). A cancelled run whose worker hasn't stopped yet reads stopping. The run's events keep every phase it went through.

      "queued""waiting_for_compute""starting""loading_model""training""evaluating""checkpointing""uploading""completing""stopping"null

    • phase_sincestring (date-time)requirednullable

      When the run entered its phase; null with phase.

    • last_interruptionRunInterruptionrequirednullable
    • workers_onlineintegerrequirednullable≥ 0

      While queued: workers of this kind holding a lease (all busy). Null otherwise.

    • autoscalingbooleanrequirednullable

      While queued: true when workers scale from zero (KEDA), so a worker is starting. Null otherwise.

    • queue_positionintegerrequirednullable≥ 0

      While queued for a worker: about how many runs start before this one. Claims are fair across workspaces (the workspace with the fewest running runs goes next), so this counts other workspaces' runs too. Approximate; null otherwise.

    • queue_messagestringrequirednullable

      While queued for a worker: why it waits, ready to show: "Queued behind 3 runs", "Queued: workspace concurrency limit (8 running)" (the workspace runs as many as it may at once), or "Waiting for a GPU with ≥46 GB; online workers have 24 GB". Null when it is next in line, and once it is claimed.

    • min_gpu_memory_gbnumberrequirednullable> 0

      GPU memory (GB) the run needs (its plan's min_gpu_memory_gb): only workers with at least this much claim it. Null when unknown.

    • latest_metricMetricPointrequirednullable
    • eval_reportEvalReportrequirednullable
    • checkpoint_evalsarray of CheckpointEvalResultrequired

      recipe.evals results, one per finished eval: a checkpoint (step) on a dataset.

      10 child fields
      • namestringrequired
      • stepintegerrequired≥ 0
      • checkpoint_idstringrequired
      • eval_idstringrequirednullable
      • datasetstringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • dataset_versionintegerrequired≥ 1
      • statusenumrequired

        "completed""failed""cancelled"

      • scorenumberrequirednullable

        The checkpoint's overall rubric score (null unless completed).

      • cost_usdnumberrequired≥ 0
      • errorstringrequirednullable
    • artifact_idstringrequirednullable

      The released artifact (name@version) once the run completes; null before.

    • errorstringrequirednullable

      Why the run failed or stopped; null otherwise.

    • created_atstring (date-time)required

      When the run was created.

    • updated_atstring (date-time)required

      When the run last changed.

    • finished_atstring (date-time)requirednullable

      When the run reached a final status; null while it is queued or running.

    • warningsarray of string

      Only on the response that created the run (POST /v1/runs): the plan's warnings, such as another queued or running run with the same name. They're also the run's first warning events.

    • console_urlstringnullable

      Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for run in client.runs.list(status=["failed", "cancelled"], search="support"):
    print(run.id, run.name, run.status)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "data": [
    {
      "id": "run_ed1c235f0c631d8f209e22a5",
      "workspace_id": "ws_e2e",
      "name": "support-sft",
      "dataset_id": "ds_c66d7ad841f251049ca0e550",
      "dataset_name": "support-prod",
      "dataset_version": 1,
      "recipe_kind": "sft",
      "status": "completed",
      "resolved_config": {
        "lr": 0.000125,
        "name": "support-sft",
        "model": "qwen/qwen3-8b",
        "split": {
          "seed": 42,
          "strategy": "by_session",
          "eval_records": 0,
          "eval_fraction": 0.1,
          "train_records": 1
        },
        "epochs": 1,
        "select": "best",
        "warmup": 0.03,
        "adapter": {
          "kind": "lora",
          "rank": 32,
          "alpha": 32,
          "merge_on_export": false,
          "train_multimodal_projector": false
        },
        "dataset": "support-prod",
        "schedule": "linear",
        "thinking": "auto",
        "train_on": "last",
        "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
        "optimizer": {
          "kind": "adamw",
          "betas": [
            0.9,
            0.95
          ],
          "grad_clip": 1,
          "weight_decay": 0
        },
        "reduction": "per_example",
        "batch_size": 8,
        "recipe_kind": "sft",
        "rule_version": "auto@2",
        "base_artifact": null,
        "label_eval_id": null,
        "recipe_params": {},
        "dataset_version": 1,
        "eval_every_steps": 1,
        "preserve_thinking": false,
        "template_revision": "qwen3@3",
        "checkpoint_ttl_days": 30,
        "checkpoint_every_steps": 1
      },
      "max_cost_usd": 5,
      "price_per_million_tokens": 0.4,
      "tokens_processed": 21,
      "cost_usd": 0.000008,
      "current_step": 1,
      "total_steps": 1,
      "attempt": 1,
      "max_attempts": 10,
      "phase": null,
      "phase_since": null,
      "last_interruption": null,
      "workers_online": null,
      "autoscaling": null,
      "queue_position": null,
      "queue_message": null,
      "min_gpu_memory_gb": 36,
      "latest_metric": {
        "lr": 0.000125,
        "seq": 13,
        "loss": 0.6931471805599453,
        "step": 1,
        "epoch": 0,
        "tokens": 21,
        "attempt": 1,
        "cost_usd": 0.000008,
        "grad_norm": 0.7071067811865476,
        "timestamp": "2026-12-02T15:49:00.078009Z",
        "tokens_per_sec": 254684.0341332008
      },
      "eval_report": {
        "warnings": [
          "Reference test backend: the base model was not trained; the artifact is not deployable.",
          "No held-out examples: eval metrics are null and select='last' was used."
        ],
        "best_step": null,
        "eval_loss": null,
        "final_step": 1,
        "metric_mode": "min",
        "metric_name": "eval_loss",
        "eval_records": 0,
        "eval_examples": 0,
        "selected_step": 1,
        "train_records": 1,
        "train_examples": 1,
        "reference_backend": true
      },
      "checkpoint_evals": [],
      "artifact_id": "support-sft@2026-12-02-1",
      "error": null,
      "created_at": "2026-12-02T15:48:59.888Z",
      "updated_at": "2026-12-02T15:49:00.207Z",
      "finished_at": "2026-12-02T15:49:00.191Z"
    }
  ],
  "next_cursor": null
}

Count the workspace's runs per status#

GET/v1/runs/counts

One count per status (the web console's status tabs), narrowed by q like GET /v1/runs.

Query parameters

  • qstring≤ 200 chars

    Only items whose name contains this text (any case), or whose id is exactly this.

Returns

200 RunCounts Runs per status.

2 fields
  • totalintegerrequired≥ 0
  • by_statusobjectrequired

    Runs per status (0 when none).

    7 child fields
    • queuedintegerrequired≥ 0
    • runningintegerrequired≥ 0
    • completedintegerrequired≥ 0
    • failedintegerrequired≥ 0
    • cancelledintegerrequired≥ 0
    • stopped_budgetintegerrequired≥ 0
    • stopped_balanceintegerrequired≥ 0

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
counts = client.runs.counts(search="support")
print(counts["total"], counts["by_status"]["running"])
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "total": 1,
  "by_status": {
    "queued": 0,
    "running": 0,
    "completed": 1,
    "failed": 0,
    "cancelled": 0,
    "stopped_budget": 0,
    "stopped_balance": 0
  }
}

Get a training run#

GET/v1/runs/{id}

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 Run Training run.

35 fields
  • idstringrequired

    Run id (run_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Run name; its artifact is released as name@version.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • dataset_idstringrequired

    Id of the dataset trained on.

  • dataset_namestringrequired≤ 64 chars

    Name of the dataset trained on.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • dataset_versionintegerrequired≥ 0

    The dataset version the run pinned when it was created.

  • recipe_kindRecipeKindrequired

    "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

  • statusRunStatusrequired

    stopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.

    "queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"

  • resolved_configResolvedRunConfigrequired
    29 child fields
    • rule_versionstringrequired

      The version of the rules that resolved the auto defaults (auto@2); a config keeps resolving the same way.

    • datasetstringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • dataset_versionintegerrequired≥ 0

      The pinned dataset version.

    • namestringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • recipe_kindRecipeKindrequired

      "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

    • modelstringrequired

      The base model trained.

    • template_revisionstringrequired

      The pinned chat template (qwen3@3); evals of the run's checkpoints use it too.

    • adapterobject or object or object or objectrequired
      One of 4 shapes
      1. object
        • kind"lora"required

          "lora"

        • rankinteger1–256default 32
        • alphainteger1–512default 32
        • merge_on_exportbooleandefault false
        • train_multimodal_projectorbooleandefault false

          Also attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).

      2. object
        • kind"prefix_kv"required

          "prefix_kv"

        • num_tokensinteger16–4096default 256
      3. object
        • kind"frozen_head"required

          "frozen_head"

      4. object
        • kind"encoder_full"required

          "encoder_full"

    • lrnumberrequired> 0

      The resolved learning rate.

    • lr_sourcestringrequired

      Where lr came from: the calibrated rule (auto@2: calibrated for ... at batch 128, sqrt batch scaling) or the value you passed.

    • batch_sizeintegerrequired≥ 1

      Training examples per optimizer step.

    • epochsintegerrequired≥ 1

      Passes over the training split.

    • scheduleenumrequired

      Learning-rate schedule after warmup.

      "linear""cosine""constant"

    • warmupnumberrequired

      The fraction of steps spent warming up the learning rate.

    • train_onenumrequired

      Which assistant turns are trained: the last one, or every one.

      "last""all_assistant"

    • thinkingenumrequired

      Thinking mode the records are rendered with.

      "auto""on""off"

    • preserve_thinkingbooleanrequired

      Whether earlier assistant turns keep their reasoning in the prompt.

    • reductionenumrequired

      How the loss averages: per example, then across the batch, or per token.

      "per_example""per_token"

    • selectenumrequired

      Which checkpoint becomes the artifact: the best by the held-out metric, or the last.

      "best""last"

    • checkpoint_every_stepsintegerrequired≥ 1

      Steps between checkpoints.

    • eval_every_stepsintegerrequired≥ 1

      Steps between held-out evaluations.

    • optimizerOptimizerSpecrequired
      4 child fields
      • kind"adamw"default "adamw"

        "adamw"

      • betasarray of anydefault [0.9,0.95]
      • weight_decaynumber0–1default 0
      • grad_clipnumber0–1000default 1

        Max global gradient norm; 0 disables clipping.

    • checkpoint_ttl_daysintegerrequired≥ 1

      Days an intermediate checkpoint is kept; the best and final never expire.

    • splitobjectrequired
      5 child fields
      • strategyenumrequired

        "by_session""by_group""random"

      • eval_fractionnumberrequired
      • seedintegerrequired
      • train_recordsintegerrequired≥ 0
      • eval_recordsintegerrequired≥ 0
    • label_eval_idstringrequirednullable

      The labeling eval whose answers the run trains on: router runs with a Judge/validator rubric, and off-policy distill runs (the teacher's answers).

    • base_artifactBaseArtifactrequirednullable

      Continued training: the artifact whose adapter the run starts from (recipe.model was an artifact reference).

    • recipe_paramsmap of anyrequired

      The recipe's own settings (router candidates, DPO beta, a cartridge's context, ...).

    • checkpoint_evalsarray of object

      recipe.evals, with the dataset version and rubric pinned.

      5 child fields
      • namestringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • datasetstringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • dataset_versionintegerrequired≥ 1
      • rubricarray of EvalRubricItemrequired
        9 child fields
        • namestringrequired≤ 80 chars

          Matches ^[A-Za-z0-9_.:-]+$

        • kindenumrequired

          "regex""validator""code""judge"

        • weightnumber> 0default 1
        • patternstring≤ 256 chars
        • flagsstring≤ 4 chars

          Matches ^[imsu]*$

        • validatorenum

          "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

        • modelstring≤ 160 chars
        • promptstring≤ 8000 chars
        • runtime"local"

          Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

          "local"

      • limitintegerrequirednullable≥ 1
    • loggersarray of LoggerSpec
  • max_cost_usdnumberrequirednullable> 0

    Hard spend cap in USD (null: none). The run is never billed past it.

  • price_per_million_tokensnumberrequired> 0

    USD per million tokens processed, fixed when the run was created.

  • tokens_processedintegerrequired≥ 0

    Training tokens processed so far, over every attempt.

  • cost_usdnumberrequired≥ 0

    Cost of the tokens processed so far, in USD. It counts the whole step that crossed max_cost_usd; billing stops at the cap.

  • current_stepintegerrequired≥ 0

    Last optimizer step reported.

  • total_stepsintegerrequired≥ 0

    Planned optimizer steps.

  • attemptintegerrequired≥ 0

    Attempts started so far (every start on a worker counts, including ones whose GPU was reclaimed).

  • max_attemptsintegerrequired≥ 1

    The run fails once this many attempts end without a result (lost worker, worker error, OOM). Attempts whose GPU was reclaimed don't count toward it.

  • phaseenumrequirednullable

    What the run is doing now; null once it has finished (finished_at is set). A cancelled run whose worker hasn't stopped yet reads stopping. The run's events keep every phase it went through.

    "queued""waiting_for_compute""starting""loading_model""training""evaluating""checkpointing""uploading""completing""stopping"null

  • phase_sincestring (date-time)requirednullable

    When the run entered its phase; null with phase.

  • last_interruptionRunInterruptionrequirednullable
  • workers_onlineintegerrequirednullable≥ 0

    While queued: workers of this kind holding a lease (all busy). Null otherwise.

  • autoscalingbooleanrequirednullable

    While queued: true when workers scale from zero (KEDA), so a worker is starting. Null otherwise.

  • queue_positionintegerrequirednullable≥ 0

    While queued for a worker: about how many runs start before this one. Claims are fair across workspaces (the workspace with the fewest running runs goes next), so this counts other workspaces' runs too. Approximate; null otherwise.

  • queue_messagestringrequirednullable

    While queued for a worker: why it waits, ready to show: "Queued behind 3 runs", "Queued: workspace concurrency limit (8 running)" (the workspace runs as many as it may at once), or "Waiting for a GPU with ≥46 GB; online workers have 24 GB". Null when it is next in line, and once it is claimed.

  • min_gpu_memory_gbnumberrequirednullable> 0

    GPU memory (GB) the run needs (its plan's min_gpu_memory_gb): only workers with at least this much claim it. Null when unknown.

  • latest_metricMetricPointrequirednullable
  • eval_reportEvalReportrequirednullable
  • checkpoint_evalsarray of CheckpointEvalResultrequired

    recipe.evals results, one per finished eval: a checkpoint (step) on a dataset.

    10 child fields
    • namestringrequired
    • stepintegerrequired≥ 0
    • checkpoint_idstringrequired
    • eval_idstringrequirednullable
    • datasetstringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • dataset_versionintegerrequired≥ 1
    • statusenumrequired

      "completed""failed""cancelled"

    • scorenumberrequirednullable

      The checkpoint's overall rubric score (null unless completed).

    • cost_usdnumberrequired≥ 0
    • errorstringrequirednullable
  • artifact_idstringrequirednullable

    The released artifact (name@version) once the run completes; null before.

  • errorstringrequirednullable

    Why the run failed or stopped; null otherwise.

  • created_atstring (date-time)required

    When the run was created.

  • updated_atstring (date-time)required

    When the run last changed.

  • finished_atstring (date-time)requirednullable

    When the run reached a final status; null while it is queued or running.

  • warningsarray of string

    Only on the response that created the run (POST /v1/runs): the plan's warnings, such as another queued or running run with the same name. They're also the run's first warning events.

  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
run = client.runs.get("run_3f9c0a1b2c3d4e5f60718293")
print(run.status, run.cost_usd)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "run_ed1c235f0c631d8f209e22a5",
  "workspace_id": "ws_e2e",
  "name": "support-sft",
  "dataset_id": "ds_c66d7ad841f251049ca0e550",
  "dataset_name": "support-prod",
  "dataset_version": 1,
  "recipe_kind": "sft",
  "status": "completed",
  "resolved_config": {
    "lr": 0.000125,
    "name": "support-sft",
    "model": "qwen/qwen3-8b",
    "split": {
      "seed": 42,
      "strategy": "by_session",
      "eval_records": 0,
      "eval_fraction": 0.1,
      "train_records": 1
    },
    "epochs": 1,
    "select": "best",
    "warmup": 0.03,
    "adapter": {
      "kind": "lora",
      "rank": 32,
      "alpha": 32,
      "merge_on_export": false,
      "train_multimodal_projector": false
    },
    "dataset": "support-prod",
    "schedule": "linear",
    "thinking": "auto",
    "train_on": "last",
    "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
    "optimizer": {
      "kind": "adamw",
      "betas": [
        0.9,
        0.95
      ],
      "grad_clip": 1,
      "weight_decay": 0
    },
    "reduction": "per_example",
    "batch_size": 8,
    "recipe_kind": "sft",
    "rule_version": "auto@2",
    "base_artifact": null,
    "label_eval_id": null,
    "recipe_params": {},
    "dataset_version": 1,
    "eval_every_steps": 1,
    "preserve_thinking": false,
    "template_revision": "qwen3@3",
    "checkpoint_ttl_days": 30,
    "checkpoint_every_steps": 1
  },
  "max_cost_usd": 5,
  "price_per_million_tokens": 0.4,
  "tokens_processed": 21,
  "cost_usd": 0.000008,
  "current_step": 1,
  "total_steps": 1,
  "attempt": 1,
  "max_attempts": 10,
  "phase": null,
  "phase_since": null,
  "last_interruption": null,
  "workers_online": null,
  "autoscaling": null,
  "queue_position": null,
  "queue_message": null,
  "min_gpu_memory_gb": 36,
  "latest_metric": {
    "lr": 0.000125,
    "seq": 13,
    "loss": 0.6931471805599453,
    "step": 1,
    "epoch": 0,
    "tokens": 21,
    "attempt": 1,
    "cost_usd": 0.000008,
    "grad_norm": 0.7071067811865476,
    "timestamp": "2026-12-02T15:49:00.078009Z",
    "tokens_per_sec": 254684.0341332008
  },
  "eval_report": {
    "warnings": [
      "Reference test backend: the base model was not trained; the artifact is not deployable.",
      "No held-out examples: eval metrics are null and select='last' was used."
    ],
    "best_step": null,
    "eval_loss": null,
    "final_step": 1,
    "metric_mode": "min",
    "metric_name": "eval_loss",
    "eval_records": 0,
    "eval_examples": 0,
    "selected_step": 1,
    "train_records": 1,
    "train_examples": 1,
    "reference_backend": true
  },
  "checkpoint_evals": [],
  "artifact_id": "support-sft@2026-12-02-1",
  "error": null,
  "created_at": "2026-12-02T15:48:59.888Z",
  "updated_at": "2026-12-02T15:49:00.207Z",
  "finished_at": "2026-12-02T15:49:00.191Z"
}

Training step metrics as JSON pages#

GET/v1/runs/{id}/metrics

next_cursor pages through the points written so far (null on the last page, like every list), and tail_cursor polls for points written later. To follow a run live, stream its events (GET /v1/runs/{id}/events, metric events).

Path parameters

  • idstringrequired≤ 200 chars

Query parameters

  • cursorstring≤ 512 chars
  • after_stepintegernullable≥ -1
  • limitinteger1–5000default 1000

    Page size (default 1000). Values above 5000 are clamped to 5000.

  • max_pointsinteger2–5000

    Return the whole curve after cursor as one page, thinned to at most this many points spaced evenly from the newest (plus as many eval points, thinned the same way). Points a resumed attempt replayed are left out, so steps only increase. limit is ignored and next_cursor is null. Compare runs or draw a long run without paging every point.

Returns

200 MetricsPage Metric points.

5 fields
  • run_idstringrequired
  • statusRunStatusrequired

    stopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.

    "queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"

  • dataarray of MetricPointrequired
    12 child fields
    • seqintegerrequired≥ 1
    • attemptintegerrequired≥ 1
    • stepintegerrequired≥ 0
    • lossnumberrequired
    • eval_lossnumbernullable
    • eval_metricsmap of numbernullable

      Held-out metrics of an eval step by name (including the recipe's selection metric, eval_report.metric_name); absent on steps without an eval.

    • grad_normnumbernullable
    • lrnumbernullable
    • tokens_per_secnumbernullable
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • timestampstring (date-time)required
  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

  • tail_cursorstringrequired

    Cursor after the newest point returned so far; pass it back as cursor to poll for points written later (tailing a running run).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for point in client.runs.metrics("run_3f9c0a1b2c3d4e5f60718293"):
    print(point.step, point.loss, point.eval_loss)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "run_id": "run_ed1c235f0c631d8f209e22a5",
  "status": "completed",
  "data": [
    {
      "lr": 0.000125,
      "loss": 0.6931471805599453,
      "step": 1,
      "epoch": 0,
      "tokens": 21,
      "cost_usd": 0.000008,
      "grad_norm": 0.7071067811865476,
      "timestamp": "2026-12-02T15:49:00.078009Z",
      "tokens_per_sec": 254684.0341332008,
      "seq": 13,
      "attempt": 1
    }
  ],
  "next_cursor": null,
  "tail_cursor": "WzEzXQ"
}

A run's lifecycle events#

GET/v1/runs/{id}/events

Phases, metrics, checkpoints, attempts, warnings, logs.

Every event is a RunEvent discriminated by type; a terminal run's stream ends with one completed event. With Accept: text/event-stream the response is a Server-Sent Events stream: the SSE event name is the event's type and its id is seq (none on completed); reconnect with Last-Event-ID to resume. Otherwise returns a JSON page: next_cursor pages through the events written so far, tail_cursor polls for later ones.

Path parameters

  • idstringrequired≤ 200 chars

Query parameters

  • cursorstring≤ 512 chars
  • limitinteger1–5000default 1000

    Page size (default 1000). Values above 5000 are clamped to 5000.

Returns

200 RunEventsPage Run events.

5 fields
  • run_idstringrequired
  • statusRunStatusrequired

    stopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.

    "queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"

  • dataarray of RunEventrequired
  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

  • tail_cursorstringrequired

    Cursor after the newest event returned so far; pass it back as cursor to poll for later events.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for event in client.runs.events("run_3f9c0a1b2c3d4e5f60718293", follow=True):
    print(event.type, event)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "run_id": "run_ed1c235f0c631d8f209e22a5",
  "status": "completed",
  "data": [
    {
      "type": "phase",
      "run_id": "run_ed1c235f0c631d8f209e22a5",
      "seq": 1,
      "attempt": 1,
      "timestamp": "2026-12-02T15:48:59.895Z",
      "phase": "queued",
      "step": 0,
      "workers_online": 0,
      "autoscaling": false,
      "queue_position": 0,
      "message": null,
      "gpu": null
    },
    {
      "type": "warning",
      "run_id": "run_ed1c235f0c631d8f209e22a5",
      "seq": 2,
      "attempt": 1,
      "timestamp": "2026-12-02T15:48:59.896Z",
      "step": null,
      "message": "The eval split is empty; eval metrics will be unavailable. Add records or raise split.eval_fraction."
    }
  ],
  "next_cursor": null,
  "tail_cursor": "WzIxXQ"
}

Cancel a training run#

POST/v1/runs/{id}/cancel

A running attempt is stopped and billed.

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Returns

200 Run Cancelled training run.

35 fields
  • idstringrequired

    Run id (run_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Run name; its artifact is released as name@version.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • dataset_idstringrequired

    Id of the dataset trained on.

  • dataset_namestringrequired≤ 64 chars

    Name of the dataset trained on.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • dataset_versionintegerrequired≥ 0

    The dataset version the run pinned when it was created.

  • recipe_kindRecipeKindrequired

    "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

  • statusRunStatusrequired

    stopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.

    "queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"

  • resolved_configResolvedRunConfigrequired
    29 child fields
    • rule_versionstringrequired

      The version of the rules that resolved the auto defaults (auto@2); a config keeps resolving the same way.

    • datasetstringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • dataset_versionintegerrequired≥ 0

      The pinned dataset version.

    • namestringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • recipe_kindRecipeKindrequired

      "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

    • modelstringrequired

      The base model trained.

    • template_revisionstringrequired

      The pinned chat template (qwen3@3); evals of the run's checkpoints use it too.

    • adapterobject or object or object or objectrequired
      One of 4 shapes
      1. object
        • kind"lora"required

          "lora"

        • rankinteger1–256default 32
        • alphainteger1–512default 32
        • merge_on_exportbooleandefault false
        • train_multimodal_projectorbooleandefault false

          Also attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).

      2. object
        • kind"prefix_kv"required

          "prefix_kv"

        • num_tokensinteger16–4096default 256
      3. object
        • kind"frozen_head"required

          "frozen_head"

      4. object
        • kind"encoder_full"required

          "encoder_full"

    • lrnumberrequired> 0

      The resolved learning rate.

    • lr_sourcestringrequired

      Where lr came from: the calibrated rule (auto@2: calibrated for ... at batch 128, sqrt batch scaling) or the value you passed.

    • batch_sizeintegerrequired≥ 1

      Training examples per optimizer step.

    • epochsintegerrequired≥ 1

      Passes over the training split.

    • scheduleenumrequired

      Learning-rate schedule after warmup.

      "linear""cosine""constant"

    • warmupnumberrequired

      The fraction of steps spent warming up the learning rate.

    • train_onenumrequired

      Which assistant turns are trained: the last one, or every one.

      "last""all_assistant"

    • thinkingenumrequired

      Thinking mode the records are rendered with.

      "auto""on""off"

    • preserve_thinkingbooleanrequired

      Whether earlier assistant turns keep their reasoning in the prompt.

    • reductionenumrequired

      How the loss averages: per example, then across the batch, or per token.

      "per_example""per_token"

    • selectenumrequired

      Which checkpoint becomes the artifact: the best by the held-out metric, or the last.

      "best""last"

    • checkpoint_every_stepsintegerrequired≥ 1

      Steps between checkpoints.

    • eval_every_stepsintegerrequired≥ 1

      Steps between held-out evaluations.

    • optimizerOptimizerSpecrequired
      4 child fields
      • kind"adamw"default "adamw"

        "adamw"

      • betasarray of anydefault [0.9,0.95]
      • weight_decaynumber0–1default 0
      • grad_clipnumber0–1000default 1

        Max global gradient norm; 0 disables clipping.

    • checkpoint_ttl_daysintegerrequired≥ 1

      Days an intermediate checkpoint is kept; the best and final never expire.

    • splitobjectrequired
      5 child fields
      • strategyenumrequired

        "by_session""by_group""random"

      • eval_fractionnumberrequired
      • seedintegerrequired
      • train_recordsintegerrequired≥ 0
      • eval_recordsintegerrequired≥ 0
    • label_eval_idstringrequirednullable

      The labeling eval whose answers the run trains on: router runs with a Judge/validator rubric, and off-policy distill runs (the teacher's answers).

    • base_artifactBaseArtifactrequirednullable

      Continued training: the artifact whose adapter the run starts from (recipe.model was an artifact reference).

    • recipe_paramsmap of anyrequired

      The recipe's own settings (router candidates, DPO beta, a cartridge's context, ...).

    • checkpoint_evalsarray of object

      recipe.evals, with the dataset version and rubric pinned.

      5 child fields
      • namestringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • datasetstringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • dataset_versionintegerrequired≥ 1
      • rubricarray of EvalRubricItemrequired
        9 child fields
        • namestringrequired≤ 80 chars

          Matches ^[A-Za-z0-9_.:-]+$

        • kindenumrequired

          "regex""validator""code""judge"

        • weightnumber> 0default 1
        • patternstring≤ 256 chars
        • flagsstring≤ 4 chars

          Matches ^[imsu]*$

        • validatorenum

          "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

        • modelstring≤ 160 chars
        • promptstring≤ 8000 chars
        • runtime"local"

          Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

          "local"

      • limitintegerrequirednullable≥ 1
    • loggersarray of LoggerSpec
  • max_cost_usdnumberrequirednullable> 0

    Hard spend cap in USD (null: none). The run is never billed past it.

  • price_per_million_tokensnumberrequired> 0

    USD per million tokens processed, fixed when the run was created.

  • tokens_processedintegerrequired≥ 0

    Training tokens processed so far, over every attempt.

  • cost_usdnumberrequired≥ 0

    Cost of the tokens processed so far, in USD. It counts the whole step that crossed max_cost_usd; billing stops at the cap.

  • current_stepintegerrequired≥ 0

    Last optimizer step reported.

  • total_stepsintegerrequired≥ 0

    Planned optimizer steps.

  • attemptintegerrequired≥ 0

    Attempts started so far (every start on a worker counts, including ones whose GPU was reclaimed).

  • max_attemptsintegerrequired≥ 1

    The run fails once this many attempts end without a result (lost worker, worker error, OOM). Attempts whose GPU was reclaimed don't count toward it.

  • phaseenumrequirednullable

    What the run is doing now; null once it has finished (finished_at is set). A cancelled run whose worker hasn't stopped yet reads stopping. The run's events keep every phase it went through.

    "queued""waiting_for_compute""starting""loading_model""training""evaluating""checkpointing""uploading""completing""stopping"null

  • phase_sincestring (date-time)requirednullable

    When the run entered its phase; null with phase.

  • last_interruptionRunInterruptionrequirednullable
  • workers_onlineintegerrequirednullable≥ 0

    While queued: workers of this kind holding a lease (all busy). Null otherwise.

  • autoscalingbooleanrequirednullable

    While queued: true when workers scale from zero (KEDA), so a worker is starting. Null otherwise.

  • queue_positionintegerrequirednullable≥ 0

    While queued for a worker: about how many runs start before this one. Claims are fair across workspaces (the workspace with the fewest running runs goes next), so this counts other workspaces' runs too. Approximate; null otherwise.

  • queue_messagestringrequirednullable

    While queued for a worker: why it waits, ready to show: "Queued behind 3 runs", "Queued: workspace concurrency limit (8 running)" (the workspace runs as many as it may at once), or "Waiting for a GPU with ≥46 GB; online workers have 24 GB". Null when it is next in line, and once it is claimed.

  • min_gpu_memory_gbnumberrequirednullable> 0

    GPU memory (GB) the run needs (its plan's min_gpu_memory_gb): only workers with at least this much claim it. Null when unknown.

  • latest_metricMetricPointrequirednullable
  • eval_reportEvalReportrequirednullable
  • checkpoint_evalsarray of CheckpointEvalResultrequired

    recipe.evals results, one per finished eval: a checkpoint (step) on a dataset.

    10 child fields
    • namestringrequired
    • stepintegerrequired≥ 0
    • checkpoint_idstringrequired
    • eval_idstringrequirednullable
    • datasetstringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • dataset_versionintegerrequired≥ 1
    • statusenumrequired

      "completed""failed""cancelled"

    • scorenumberrequirednullable

      The checkpoint's overall rubric score (null unless completed).

    • cost_usdnumberrequired≥ 0
    • errorstringrequirednullable
  • artifact_idstringrequirednullable

    The released artifact (name@version) once the run completes; null before.

  • errorstringrequirednullable

    Why the run failed or stopped; null otherwise.

  • created_atstring (date-time)required

    When the run was created.

  • updated_atstring (date-time)required

    When the run last changed.

  • finished_atstring (date-time)requirednullable

    When the run reached a final status; null while it is queued or running.

  • warningsarray of string

    Only on the response that created the run (POST /v1/runs): the plan's warnings, such as another queued or running run with the same name. They're also the run's first warning events.

  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
run = client.runs.cancel("run_3f9c0a1b2c3d4e5f60718293")
Response 200 OKGenerated from the schema
JSON
{
  "id": "run_3f9c0a1b2c3d4e5f60718293",
  "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
  "name": "support-prod",
  "dataset_id": "ds_3f9c0a1b2c3d4e5f60718293",
  "dataset_name": "support-prod",
  "dataset_version": 0,
  "recipe_kind": "sft",
  "status": "queued",
  "resolved_config": {
    "rule_version": "string",
    "dataset": "support-prod",
    "dataset_version": 0,
    "name": "support-prod",
    "recipe_kind": "sft",
    "model": "qwen/qwen3-8b",
    "template_revision": "string",
    "adapter": {
      "kind": "lora",
      "rank": 32,
      "alpha": 32,
      "merge_on_export": false,
      "train_multimodal_projector": false
    },
    "lr": 1,
    "lr_source": "string",
    "batch_size": 1,
    "epochs": 1,
    "schedule": "linear",
    "warmup": 0,
    "train_on": "last",
    "thinking": "auto",
    "preserve_thinking": false,
    "reduction": "per_example",
    "select": "best",
    "checkpoint_every_steps": 1,
    "eval_every_steps": 1,
    "optimizer": {
      "kind": "adamw",
      "betas": [
        0.9,
        0.95
      ],
      "weight_decay": 0,
      "grad_clip": 1
    },
    "checkpoint_ttl_days": 1,
    "split": {
      "strategy": "by_session",
      "eval_fraction": 0,
      "seed": 0,
      "train_records": 0,
      "eval_records": 0
    },
    "label_eval_id": "obj_3f9c0a1b2c3d4e5f60718293",
    "base_artifact": {
      "id": "obj_3f9c0a1b2c3d4e5f60718293",
      "recipe_kind": "sft",
      "format": "peft_lora",
      "sha256": "9f2c4e1ab0d3c5e7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c9d1e3f5a7b9c1d3e5"
    },
    "recipe_params": {},
    "checkpoint_evals": [
      {
        "name": "support-prod",
        "dataset": "support-prod",
        "dataset_version": 1,
        "rubric": [
          {}
        ],
        "limit": 1
      }
    ],
    "loggers": [
      {
        "kind": "wandb",
        "project": "string",
        "entity": "string",
        "integration": "string",
        "run_name": "support-prod"
      }
    ]
  },
  "max_cost_usd": 1,
  "price_per_million_tokens": 1,
  "tokens_processed": 0,
  "cost_usd": 0,
  "current_step": 0,
  "total_steps": 0,
  "attempt": 0,
  "max_attempts": 1,
  "phase": "queued",
  "phase_since": "2026-11-28T09:30:00.000Z",
  "last_interruption": {
    "attempt": 1,
    "reason": "lease_lost",
    "step": 0,
    "resume_step": 0,
    "at": "2026-11-28T09:30:00.000Z",
    "message": "…"
  },
  "workers_online": 0,
  "autoscaling": false,
  "queue_position": 0,
  "queue_message": "string",
  "min_gpu_memory_gb": 1,
  "latest_metric": {
    "seq": 1,
    "attempt": 1,
    "step": 0,
    "loss": 0,
    "eval_loss": 0,
    "eval_metrics": {},
    "grad_norm": 0,
    "lr": 0,
    "tokens_per_sec": 0,
    "tokens": 0,
    "cost_usd": 0,
    "timestamp": "2026-11-28T09:30:00.000Z"
  },
  "eval_report": {
    "metric_name": "support-prod",
    "metric_mode": "min",
    "selected_step": 0,
    "best_step": 0,
    "final_step": 0,
    "train_records": 0,
    "eval_records": 0,
    "warnings": [
      "string"
    ],
    "eval_loss": 0,
    "eval_token_accuracy": 0,
    "trained_token_fraction": 0,
    "train_examples": 0,
    "eval_examples": 0,
    "selection_examples": 0,
    "truncated": 0,
    "preference_accuracy": 0,
    "reward_margin": 0,
    "beta": 0,
    "train_pairs": 0,
    "eval_pairs": 0,
    "dropped_records": 0,
    "train_points": 0,
    "eval_points": 0,
    "pointwise_brier": 0,
    "eval_kl": 0,
    "base_kl": 0,
    "no_context_kl": 0,
    "kl_reduction": 0,
    "num_tokens": 0,
    "teacher": "string",
    "rollout": "on_policy",
    "candidates": [
      "string"
    ],
    "fallback_model": "string",
    "fallback_quality": 0,
    "routes_any_traffic": false,
    "pareto_summary": {
      "target_max_drop": 0,
      "routed_quality": 0,
      "quality_drop": 0,
      "quality_drop_ci95": [
        0
      ],
      "offload_rate": 0,
      "cost_savings_pct": 0,
      "ece": 0,
      "threshold": 0,
      "temperature": 0
    },
    "ece": 0,
    "heads": {},
    "recall_at_1": 0,
    "recall_at_5": 0,
    "recall_at_10": 0,
    "ndcg_at_10": 0,
    "mrr": 0,
    "corpus_size": 0,
    "baseline": {
      "recall_at_1": 0,
      "recall_at_5": 0,
      "recall_at_10": 0,
      "ndcg_at_10": 0,
      "mrr": 0
    },
    "eval_reward": 0,
    "eval_pass_at_1": 0,
    "baseline_reward": 0,
    "baseline_pass_at_1": 0,
    "final_train_reward": 0,
    "mean_train_reward": 0,
    "zero_var_skip_rate": 0,
    "mean_completion_tokens": 0,
    "mean_kl_ref": 0,
    "validator": "string",
    "advantage": "string",
    "group_size": 0,
    "kl_coef": 0,
    "clip_low": 0,
    "clip_high": 0
  },
  "checkpoint_evals": [
    {
      "name": "support-prod",
      "step": 0,
      "checkpoint_id": "ckpt_3f9c0a1b2c3d4e5f60718293",
      "eval_id": "obj_3f9c0a1b2c3d4e5f60718293",
      "dataset": "support-prod",
      "dataset_version": 1,
      "status": "completed",
      "score": 0,
      "cost_usd": 0,
      "error": "…"
    }
  ],
  "artifact_id": "support-sft@2026-11-28-1",
  "error": "…",
  "created_at": "2026-11-28T09:30:00.000Z",
  "updated_at": "2026-11-28T09:30:00.000Z",
  "finished_at": "2026-11-28T09:30:00.000Z",
  "warnings": [
    "string"
  ],
  "console_url": "string"
}

Resume a stopped, failed or cancelled run from its latest checkpoint#

POST/v1/runs/{id}/resume

A run that is already queued or running is returned as it is, so a retried resume is a no-op. A resume queues the run again, so it counts toward the workspace's queued cap (429 queue_limit) like a new run.

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body ResumeRunRequest

  • max_cost_usdnumber> 0

Returns

200 Run Re-queued training run.

35 fields
  • idstringrequired

    Run id (run_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Run name; its artifact is released as name@version.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • dataset_idstringrequired

    Id of the dataset trained on.

  • dataset_namestringrequired≤ 64 chars

    Name of the dataset trained on.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • dataset_versionintegerrequired≥ 0

    The dataset version the run pinned when it was created.

  • recipe_kindRecipeKindrequired

    "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

  • statusRunStatusrequired

    stopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.

    "queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"

  • resolved_configResolvedRunConfigrequired
    29 child fields
    • rule_versionstringrequired

      The version of the rules that resolved the auto defaults (auto@2); a config keeps resolving the same way.

    • datasetstringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • dataset_versionintegerrequired≥ 0

      The pinned dataset version.

    • namestringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • recipe_kindRecipeKindrequired

      "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

    • modelstringrequired

      The base model trained.

    • template_revisionstringrequired

      The pinned chat template (qwen3@3); evals of the run's checkpoints use it too.

    • adapterobject or object or object or objectrequired
      One of 4 shapes
      1. object
        • kind"lora"required

          "lora"

        • rankinteger1–256default 32
        • alphainteger1–512default 32
        • merge_on_exportbooleandefault false
        • train_multimodal_projectorbooleandefault false

          Also attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).

      2. object
        • kind"prefix_kv"required

          "prefix_kv"

        • num_tokensinteger16–4096default 256
      3. object
        • kind"frozen_head"required

          "frozen_head"

      4. object
        • kind"encoder_full"required

          "encoder_full"

    • lrnumberrequired> 0

      The resolved learning rate.

    • lr_sourcestringrequired

      Where lr came from: the calibrated rule (auto@2: calibrated for ... at batch 128, sqrt batch scaling) or the value you passed.

    • batch_sizeintegerrequired≥ 1

      Training examples per optimizer step.

    • epochsintegerrequired≥ 1

      Passes over the training split.

    • scheduleenumrequired

      Learning-rate schedule after warmup.

      "linear""cosine""constant"

    • warmupnumberrequired

      The fraction of steps spent warming up the learning rate.

    • train_onenumrequired

      Which assistant turns are trained: the last one, or every one.

      "last""all_assistant"

    • thinkingenumrequired

      Thinking mode the records are rendered with.

      "auto""on""off"

    • preserve_thinkingbooleanrequired

      Whether earlier assistant turns keep their reasoning in the prompt.

    • reductionenumrequired

      How the loss averages: per example, then across the batch, or per token.

      "per_example""per_token"

    • selectenumrequired

      Which checkpoint becomes the artifact: the best by the held-out metric, or the last.

      "best""last"

    • checkpoint_every_stepsintegerrequired≥ 1

      Steps between checkpoints.

    • eval_every_stepsintegerrequired≥ 1

      Steps between held-out evaluations.

    • optimizerOptimizerSpecrequired
      4 child fields
      • kind"adamw"default "adamw"

        "adamw"

      • betasarray of anydefault [0.9,0.95]
      • weight_decaynumber0–1default 0
      • grad_clipnumber0–1000default 1

        Max global gradient norm; 0 disables clipping.

    • checkpoint_ttl_daysintegerrequired≥ 1

      Days an intermediate checkpoint is kept; the best and final never expire.

    • splitobjectrequired
      5 child fields
      • strategyenumrequired

        "by_session""by_group""random"

      • eval_fractionnumberrequired
      • seedintegerrequired
      • train_recordsintegerrequired≥ 0
      • eval_recordsintegerrequired≥ 0
    • label_eval_idstringrequirednullable

      The labeling eval whose answers the run trains on: router runs with a Judge/validator rubric, and off-policy distill runs (the teacher's answers).

    • base_artifactBaseArtifactrequirednullable

      Continued training: the artifact whose adapter the run starts from (recipe.model was an artifact reference).

    • recipe_paramsmap of anyrequired

      The recipe's own settings (router candidates, DPO beta, a cartridge's context, ...).

    • checkpoint_evalsarray of object

      recipe.evals, with the dataset version and rubric pinned.

      5 child fields
      • namestringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • datasetstringrequired≤ 64 chars

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

      • dataset_versionintegerrequired≥ 1
      • rubricarray of EvalRubricItemrequired
        9 child fields
        • namestringrequired≤ 80 chars

          Matches ^[A-Za-z0-9_.:-]+$

        • kindenumrequired

          "regex""validator""code""judge"

        • weightnumber> 0default 1
        • patternstring≤ 256 chars
        • flagsstring≤ 4 chars

          Matches ^[imsu]*$

        • validatorenum

          "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

        • modelstring≤ 160 chars
        • promptstring≤ 8000 chars
        • runtime"local"

          Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

          "local"

      • limitintegerrequirednullable≥ 1
    • loggersarray of LoggerSpec
  • max_cost_usdnumberrequirednullable> 0

    Hard spend cap in USD (null: none). The run is never billed past it.

  • price_per_million_tokensnumberrequired> 0

    USD per million tokens processed, fixed when the run was created.

  • tokens_processedintegerrequired≥ 0

    Training tokens processed so far, over every attempt.

  • cost_usdnumberrequired≥ 0

    Cost of the tokens processed so far, in USD. It counts the whole step that crossed max_cost_usd; billing stops at the cap.

  • current_stepintegerrequired≥ 0

    Last optimizer step reported.

  • total_stepsintegerrequired≥ 0

    Planned optimizer steps.

  • attemptintegerrequired≥ 0

    Attempts started so far (every start on a worker counts, including ones whose GPU was reclaimed).

  • max_attemptsintegerrequired≥ 1

    The run fails once this many attempts end without a result (lost worker, worker error, OOM). Attempts whose GPU was reclaimed don't count toward it.

  • phaseenumrequirednullable

    What the run is doing now; null once it has finished (finished_at is set). A cancelled run whose worker hasn't stopped yet reads stopping. The run's events keep every phase it went through.

    "queued""waiting_for_compute""starting""loading_model""training""evaluating""checkpointing""uploading""completing""stopping"null

  • phase_sincestring (date-time)requirednullable

    When the run entered its phase; null with phase.

  • last_interruptionRunInterruptionrequirednullable
  • workers_onlineintegerrequirednullable≥ 0

    While queued: workers of this kind holding a lease (all busy). Null otherwise.

  • autoscalingbooleanrequirednullable

    While queued: true when workers scale from zero (KEDA), so a worker is starting. Null otherwise.

  • queue_positionintegerrequirednullable≥ 0

    While queued for a worker: about how many runs start before this one. Claims are fair across workspaces (the workspace with the fewest running runs goes next), so this counts other workspaces' runs too. Approximate; null otherwise.

  • queue_messagestringrequirednullable

    While queued for a worker: why it waits, ready to show: "Queued behind 3 runs", "Queued: workspace concurrency limit (8 running)" (the workspace runs as many as it may at once), or "Waiting for a GPU with ≥46 GB; online workers have 24 GB". Null when it is next in line, and once it is claimed.

  • min_gpu_memory_gbnumberrequirednullable> 0

    GPU memory (GB) the run needs (its plan's min_gpu_memory_gb): only workers with at least this much claim it. Null when unknown.

  • latest_metricMetricPointrequirednullable
  • eval_reportEvalReportrequirednullable
  • checkpoint_evalsarray of CheckpointEvalResultrequired

    recipe.evals results, one per finished eval: a checkpoint (step) on a dataset.

    10 child fields
    • namestringrequired
    • stepintegerrequired≥ 0
    • checkpoint_idstringrequired
    • eval_idstringrequirednullable
    • datasetstringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • dataset_versionintegerrequired≥ 1
    • statusenumrequired

      "completed""failed""cancelled"

    • scorenumberrequirednullable

      The checkpoint's overall rubric score (null unless completed).

    • cost_usdnumberrequired≥ 0
    • errorstringrequirednullable
  • artifact_idstringrequirednullable

    The released artifact (name@version) once the run completes; null before.

  • errorstringrequirednullable

    Why the run failed or stopped; null otherwise.

  • created_atstring (date-time)required

    When the run was created.

  • updated_atstring (date-time)required

    When the run last changed.

  • finished_atstring (date-time)requirednullable

    When the run reached a final status; null while it is queued or running.

  • warningsarray of string

    Only on the response that created the run (POST /v1/runs): the plan's warnings, such as another queued or running run with the same name. They're also the run's first warning events.

  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
run = client.runs.resume("run_3f9c0a1b2c3d4e5f60718293", max_cost_usd=10)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "run_ed1c235f0c631d8f209e22a5",
  "workspace_id": "ws_e2e",
  "name": "support-sft",
  "dataset_id": "ds_c66d7ad841f251049ca0e550",
  "dataset_name": "support-prod",
  "dataset_version": 1,
  "recipe_kind": "sft",
  "status": "queued",
  "resolved_config": {
    "lr": 0.000125,
    "name": "support-sft",
    "model": "qwen/qwen3-8b",
    "split": {
      "seed": 42,
      "strategy": "by_session",
      "eval_records": 0,
      "eval_fraction": 0.1,
      "train_records": 1
    },
    "epochs": 1,
    "select": "best",
    "warmup": 0.03,
    "adapter": {
      "kind": "lora",
      "rank": 32,
      "alpha": 32,
      "merge_on_export": false,
      "train_multimodal_projector": false
    },
    "dataset": "support-prod",
    "schedule": "linear",
    "thinking": "auto",
    "train_on": "last",
    "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
    "optimizer": {
      "kind": "adamw",
      "betas": [
        0.9,
        0.95
      ],
      "grad_clip": 1,
      "weight_decay": 0
    },
    "reduction": "per_example",
    "batch_size": 8,
    "recipe_kind": "sft",
    "rule_version": "auto@2",
    "base_artifact": null,
    "label_eval_id": null,
    "recipe_params": {},
    "dataset_version": 1,
    "eval_every_steps": 1,
    "preserve_thinking": false,
    "template_revision": "qwen3@3",
    "checkpoint_ttl_days": 30,
    "checkpoint_every_steps": 1
  },
  "max_cost_usd": 5,
  "price_per_million_tokens": 0.4,
  "tokens_processed": 0,
  "cost_usd": 0,
  "current_step": 0,
  "total_steps": 1,
  "attempt": 0,
  "max_attempts": 10,
  "phase": "queued",
  "phase_since": "2026-12-02T15:48:59.895Z",
  "last_interruption": null,
  "workers_online": 0,
  "autoscaling": false,
  "queue_position": 0,
  "queue_message": null,
  "min_gpu_memory_gb": 36,
  "latest_metric": null,
  "eval_report": null,
  "checkpoint_evals": [],
  "artifact_id": null,
  "error": null,
  "created_at": "2026-12-02T15:48:59.888Z",
  "updated_at": "2026-12-02T15:48:59.888Z",
  "finished_at": null
}

Trainers#

Start a trainer: a LoRA on one GPU that you drive op by op#

POST/v1/trainers

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body CreateTrainerRequest

  • modelstring≤ 160 chars

    A trainable causal-LM catalog id (qwen/qwen3-8b), or any catalog LLM when mode is sample.

  • modeTrainerModedefault "train"

    train (default): full LoRA training and sampling; sample: inference-only sampling session (no optimizer/gradients, higher vLLM KV-cache headroom, allows sampling any catalog LLM).

    "train""sample"

  • from_artifactstring≤ 200 chars

    Start from a peft_lora artifact's weights (id or name@version) with a fresh optimizer: a stage transition.

  • from_checkpointstring≤ 200 chars

    Resume a trainer's save_state checkpoint: its weights, optimizer, gradients and step.

  • adapterTrainerAdapter

    The LoRA a trainer trains (on every linear layer of the language model, plus multimodal projector/merger layers when train_multimodal_projector is true). A trainer from an artifact or checkpoint keeps that adapter's settings.

    4 child fields
    • kind"lora"default "lora"

      "lora"

    • rankinteger1–256default 32
    • alphainteger1–512default 32
    • train_multimodal_projectorbooleandefault false

      Also attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).

  • max_cost_usdnumberrequired> 0

    Hard cap on what the trainer may spend. An op that could pass it is refused (budget_exceeded) before it runs.

  • idle_timeout_sinteger30–900default 300

    Seconds without an op after which the trainer parks: it saves its state and gives the GPU back (nothing is billed while parked). The next op resumes it.

  • namestring≤ 128 chars
  • autosave_everyinteger1–1000000

    Save the state every N optimizer steps (between ops), so a lost worker costs at most N steps.

  • max_snapshotsinteger1–8default 4

    Snapshots (frozen copies of the adapter to sample from) it may hold at once, pending or live; one more is 409 too_many_snapshots. Each is an adapter-sized copy in GPU memory (about 350 MB at 8B rank 32).

  • snapshot_ttl_sinteger30–86400default 600

    A snapshot with no sample queued or running for this long is released (a crashed client's snapshots don't hold the slots).

  • checkpoint_ttl_sinteger300–7776000

    TTL in seconds (300 to 7776000) for automatic autosave and park checkpoints. Explicit save_state (without ttl_s) and final close checkpoints stay permanent.

  • total_stepsinteger1–10000000

    Optional target optimizer step count used for progress indicators in the web console and grad trainers watch TUI.

Returns

202 Trainer The trainer, queued for a GPU.

36 fields
  • idstringrequired

    trn_ and 24 hex.

  • namestringrequired
  • modelstringrequired

    The base model.

  • modalitiesarray of Modalityrequired≥ 1 items

    Input modalities accepted by this trainer's base model (text, image, audio).

  • modeTrainerModerequireddefault "train"

    train (default): full LoRA training and sampling; sample: inference-only sampling session (no optimizer/gradients, higher vLLM KV-cache headroom, allows sampling any catalog LLM).

    "train""sample"

  • adapterobjectrequired
    4 child fields
    • kind"lora"required

      "lora"

    • rankintegerrequired≥ 1
    • alphaintegerrequired≥ 1
    • train_multimodal_projectorboolean
  • statusTrainerStatusrequired

    queued (waiting for a GPU), loading (a worker is loading the base and adapter), ready (running ops), parked (idle: its state is saved and no GPU is held; the next op resumes it), closed, failed (see error).

    "queued""loading""ready""parked""closed""failed"

  • stepintegerrequired≥ 0

    Optimizer steps taken.

  • total_stepsintegernullable

    Optional target optimizer step count configured at creation (null if unset).

  • next_seqintegerrequired≥ 1

    The seq the next op must carry.

  • pending_opsintegerrequired≥ 0

    Train-lane ops (the seq-ordered ones) submitted and not finished yet.

  • closingbooleanrequired

    close was called: the ops already submitted run (with abort, the ones the worker has not taken fail), then it closes. It takes no new op.

  • max_snapshotsintegerrequired≥ 1
  • snapshot_ttl_sintegerrequired≥ 1
  • checkpoint_ttl_sintegernullable

    Configured TTL in seconds for automatic autosave/park checkpoints (null: server default retention).

  • sample_queueobjectrequired

    Sample-lane ops (snapshot samples) waiting and running. At most 1024 together (429 sample_queue_full).

    2 child fields
    • queuedintegerrequired≥ 0
    • runningintegerrequired≥ 0
  • utilizationobjectrequired

    Cumulative worker compute time per lane (train_s: train-lane ops, sample_s: sample-lane batches) and wall time spent loaded (ready_s). The GPU's busy fraction over an interval is the change in train_s + sample_s over the change in ready_s.

    3 child fields
    • train_snumberrequired≥ 0
    • sample_snumberrequired≥ 0
    • ready_snumberrequired≥ 0
  • usageTrainerUsagerequired
    4 child fields
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • prompt_tokensinteger≥ 0
    • sampled_tokensinteger≥ 0
  • max_cost_usdnumberrequired> 0
  • reserved_cost_usdnumberrequired≥ 0

    The worst-case cost of the pending ops. An op is refused (budget_exceeded) when spent + reserved + its worst case would pass max_cost_usd.

  • price_per_million_tokensnumberrequired≥ 0
  • calibrated_lrsmap of numberrequired

    Calibrated learning rates for this trainer's base model by objective (sft, rl, dpo, ...); empty when uncalibrated.

  • idle_timeout_sintegerrequired≥ 1
  • max_seq_lenintegerrequired≥ 1

    The longest datum (and sample prompt + max_tokens) it takes.

  • tokenizerobjectrequirednullable

    The base's tokenizer (Hugging Face repo and revision) for raw-token clients; null until a worker has loaded the trainer once.

  • template_revisionstringrequirednullable
  • stop_token_idsarray of integerrequirednullable

    Where sample stops by default (end of turn, end of text).

  • queue_messagestringrequirednullable

    While queued: why it waits (GPU capacity, the workspace's limit).

  • from_artifactstringrequirednullable
  • from_checkpointstringrequirednullable
  • last_checkpointstringrequirednullable

    The latest saved state (a save_state, an autosave, a park or the close): what from_checkpoint resumes after a failure.

  • errorstringrequirednullable
  • created_atstring (date-time)required
  • closed_atstring (date-time)requirednullable
  • logged_metricsarray of TrainerMetricPoint

    Recent client-logged scalar metrics series, ordered oldest to newest (included on GET /v1/trainers/{id}).

    3 child fields
    • stepintegerrequired≥ 0
    • metricsmap of numberrequired
    • timestampstring (date-time)required
  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.create(
    model="qwen/qwen3-8b",
    max_cost_usd=20,
    name="support-loop",
)
print(trainer.id, trainer.status)
Response 202 AcceptedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "trn_1672e418bf19834898de1278",
  "name": "support-loop",
  "model": "qwen/qwen3-8b",
  "modalities": [
    "text"
  ],
  "mode": "train",
  "adapter": {
    "kind": "lora",
    "rank": 32,
    "alpha": 32
  },
  "status": "queued",
  "step": 0,
  "total_steps": null,
  "next_seq": 1,
  "pending_ops": 0,
  "closing": false,
  "max_snapshots": 4,
  "snapshot_ttl_s": 600,
  "checkpoint_ttl_s": null,
  "sample_queue": {
    "queued": 0,
    "running": 0
  },
  "utilization": {
    "train_s": 0,
    "sample_s": 0,
    "ready_s": 0
  },
  "usage": {
    "tokens": 0,
    "cost_usd": 0
  },
  "max_cost_usd": 20,
  "reserved_cost_usd": 0,
  "price_per_million_tokens": 0.4,
  "calibrated_lrs": {
    "sft": 0.0005,
    "rl": 0.000025,
    "grpo": 0.000025,
    "dpo": 0.00002,
    "router": 0.0003,
    "cartridge": 0.01,
    "distill": 0.0002,
    "reward": 0.0001
  },
  "idle_timeout_s": 300,
  "max_seq_len": 32768,
  "tokenizer": null,
  "template_revision": "qwen3@3",
  "stop_token_ids": null,
  "queue_message": "Waiting for a GPU worker",
  "from_artifact": null,
  "from_checkpoint": null,
  "last_checkpoint": null,
  "error": null,
  "created_at": "2026-12-02T15:49:00.029Z",
  "closed_at": null
}

List trainers#

GET/v1/trainers

Newest first.

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • qstring≤ 200 chars

    Only items whose name contains this text (any case), or whose id is exactly this.

Returns

200 object Trainers.

2 fields
  • dataarray of Trainerrequired
    36 child fields
    • idstringrequired

      trn_ and 24 hex.

    • namestringrequired
    • modelstringrequired

      The base model.

    • modalitiesarray of Modalityrequired≥ 1 items

      Input modalities accepted by this trainer's base model (text, image, audio).

    • modeTrainerModerequireddefault "train"

      train (default): full LoRA training and sampling; sample: inference-only sampling session (no optimizer/gradients, higher vLLM KV-cache headroom, allows sampling any catalog LLM).

      "train""sample"

    • adapterobjectrequired
      4 child fields
      • kind"lora"required

        "lora"

      • rankintegerrequired≥ 1
      • alphaintegerrequired≥ 1
      • train_multimodal_projectorboolean
    • statusTrainerStatusrequired

      queued (waiting for a GPU), loading (a worker is loading the base and adapter), ready (running ops), parked (idle: its state is saved and no GPU is held; the next op resumes it), closed, failed (see error).

      "queued""loading""ready""parked""closed""failed"

    • stepintegerrequired≥ 0

      Optimizer steps taken.

    • total_stepsintegernullable

      Optional target optimizer step count configured at creation (null if unset).

    • next_seqintegerrequired≥ 1

      The seq the next op must carry.

    • pending_opsintegerrequired≥ 0

      Train-lane ops (the seq-ordered ones) submitted and not finished yet.

    • closingbooleanrequired

      close was called: the ops already submitted run (with abort, the ones the worker has not taken fail), then it closes. It takes no new op.

    • max_snapshotsintegerrequired≥ 1
    • snapshot_ttl_sintegerrequired≥ 1
    • checkpoint_ttl_sintegernullable

      Configured TTL in seconds for automatic autosave/park checkpoints (null: server default retention).

    • sample_queueobjectrequired

      Sample-lane ops (snapshot samples) waiting and running. At most 1024 together (429 sample_queue_full).

      2 child fields
      • queuedintegerrequired≥ 0
      • runningintegerrequired≥ 0
    • utilizationobjectrequired

      Cumulative worker compute time per lane (train_s: train-lane ops, sample_s: sample-lane batches) and wall time spent loaded (ready_s). The GPU's busy fraction over an interval is the change in train_s + sample_s over the change in ready_s.

      3 child fields
      • train_snumberrequired≥ 0
      • sample_snumberrequired≥ 0
      • ready_snumberrequired≥ 0
    • usageTrainerUsagerequired
      4 child fields
      • tokensintegerrequired≥ 0
      • cost_usdnumberrequired≥ 0
      • prompt_tokensinteger≥ 0
      • sampled_tokensinteger≥ 0
    • max_cost_usdnumberrequired> 0
    • reserved_cost_usdnumberrequired≥ 0

      The worst-case cost of the pending ops. An op is refused (budget_exceeded) when spent + reserved + its worst case would pass max_cost_usd.

    • price_per_million_tokensnumberrequired≥ 0
    • calibrated_lrsmap of numberrequired

      Calibrated learning rates for this trainer's base model by objective (sft, rl, dpo, ...); empty when uncalibrated.

    • idle_timeout_sintegerrequired≥ 1
    • max_seq_lenintegerrequired≥ 1

      The longest datum (and sample prompt + max_tokens) it takes.

    • tokenizerobjectrequirednullable

      The base's tokenizer (Hugging Face repo and revision) for raw-token clients; null until a worker has loaded the trainer once.

    • template_revisionstringrequirednullable
    • stop_token_idsarray of integerrequirednullable

      Where sample stops by default (end of turn, end of text).

    • queue_messagestringrequirednullable

      While queued: why it waits (GPU capacity, the workspace's limit).

    • from_artifactstringrequirednullable
    • from_checkpointstringrequirednullable
    • last_checkpointstringrequirednullable

      The latest saved state (a save_state, an autosave, a park or the close): what from_checkpoint resumes after a failure.

    • errorstringrequirednullable
    • created_atstring (date-time)required
    • closed_atstring (date-time)requirednullable
    • logged_metricsarray of TrainerMetricPoint

      Recent client-logged scalar metrics series, ordered oldest to newest (included on GET /v1/trainers/{id}).

      3 child fields
      • stepintegerrequired≥ 0
      • metricsmap of numberrequired
      • timestampstring (date-time)required
    • console_urlstringnullable

      Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for trainer in client.trainers.list(search="support"):
    print(trainer.id, trainer.status, trainer.step)
Response 200 OKGenerated from the schema
JSON
{
  "data": [
    {
      "id": "trn_3f9c0a1b2c3d4e5f60718293",
      "name": "support-prod",
      "model": "qwen/qwen3-8b",
      "modalities": [
        "text"
      ],
      "mode": "train",
      "adapter": {
        "kind": "lora",
        "rank": 1,
        "alpha": 1,
        "train_multimodal_projector": false
      },
      "status": "queued",
      "step": 0,
      "total_steps": 1,
      "next_seq": 1,
      "pending_ops": 0,
      "closing": false,
      "max_snapshots": 1,
      "snapshot_ttl_s": 1,
      "checkpoint_ttl_s": 300,
      "sample_queue": {
        "queued": 0,
        "running": 0
      },
      "utilization": {
        "train_s": 0,
        "sample_s": 0,
        "ready_s": 0
      },
      "usage": {
        "tokens": 0,
        "cost_usd": 0,
        "prompt_tokens": 0,
        "sampled_tokens": 0
      },
      "max_cost_usd": 1,
      "reserved_cost_usd": 0,
      "price_per_million_tokens": 0,
      "calibrated_lrs": {},
      "idle_timeout_s": 1,
      "max_seq_len": 1,
      "tokenizer": {
        "repo": "string",
        "revision": "string"
      },
      "template_revision": "string",
      "stop_token_ids": [
        0
      ],
      "queue_message": "string",
      "from_artifact": "string",
      "from_checkpoint": "string",
      "last_checkpoint": "string",
      "error": "…",
      "created_at": "2026-11-28T09:30:00.000Z",
      "closed_at": "2026-11-28T09:30:00.000Z",
      "logged_metrics": [
        {
          "step": 0,
          "metrics": {},
          "timestamp": "2026-11-28T09:30:00.000Z"
        }
      ],
      "console_url": "string"
    }
  ],
  "next_cursor": "string"
}

Get a trainer#

GET/v1/trainers/{id}

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 Trainer The trainer.

36 fields
  • idstringrequired

    trn_ and 24 hex.

  • namestringrequired
  • modelstringrequired

    The base model.

  • modalitiesarray of Modalityrequired≥ 1 items

    Input modalities accepted by this trainer's base model (text, image, audio).

  • modeTrainerModerequireddefault "train"

    train (default): full LoRA training and sampling; sample: inference-only sampling session (no optimizer/gradients, higher vLLM KV-cache headroom, allows sampling any catalog LLM).

    "train""sample"

  • adapterobjectrequired
    4 child fields
    • kind"lora"required

      "lora"

    • rankintegerrequired≥ 1
    • alphaintegerrequired≥ 1
    • train_multimodal_projectorboolean
  • statusTrainerStatusrequired

    queued (waiting for a GPU), loading (a worker is loading the base and adapter), ready (running ops), parked (idle: its state is saved and no GPU is held; the next op resumes it), closed, failed (see error).

    "queued""loading""ready""parked""closed""failed"

  • stepintegerrequired≥ 0

    Optimizer steps taken.

  • total_stepsintegernullable

    Optional target optimizer step count configured at creation (null if unset).

  • next_seqintegerrequired≥ 1

    The seq the next op must carry.

  • pending_opsintegerrequired≥ 0

    Train-lane ops (the seq-ordered ones) submitted and not finished yet.

  • closingbooleanrequired

    close was called: the ops already submitted run (with abort, the ones the worker has not taken fail), then it closes. It takes no new op.

  • max_snapshotsintegerrequired≥ 1
  • snapshot_ttl_sintegerrequired≥ 1
  • checkpoint_ttl_sintegernullable

    Configured TTL in seconds for automatic autosave/park checkpoints (null: server default retention).

  • sample_queueobjectrequired

    Sample-lane ops (snapshot samples) waiting and running. At most 1024 together (429 sample_queue_full).

    2 child fields
    • queuedintegerrequired≥ 0
    • runningintegerrequired≥ 0
  • utilizationobjectrequired

    Cumulative worker compute time per lane (train_s: train-lane ops, sample_s: sample-lane batches) and wall time spent loaded (ready_s). The GPU's busy fraction over an interval is the change in train_s + sample_s over the change in ready_s.

    3 child fields
    • train_snumberrequired≥ 0
    • sample_snumberrequired≥ 0
    • ready_snumberrequired≥ 0
  • usageTrainerUsagerequired
    4 child fields
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • prompt_tokensinteger≥ 0
    • sampled_tokensinteger≥ 0
  • max_cost_usdnumberrequired> 0
  • reserved_cost_usdnumberrequired≥ 0

    The worst-case cost of the pending ops. An op is refused (budget_exceeded) when spent + reserved + its worst case would pass max_cost_usd.

  • price_per_million_tokensnumberrequired≥ 0
  • calibrated_lrsmap of numberrequired

    Calibrated learning rates for this trainer's base model by objective (sft, rl, dpo, ...); empty when uncalibrated.

  • idle_timeout_sintegerrequired≥ 1
  • max_seq_lenintegerrequired≥ 1

    The longest datum (and sample prompt + max_tokens) it takes.

  • tokenizerobjectrequirednullable

    The base's tokenizer (Hugging Face repo and revision) for raw-token clients; null until a worker has loaded the trainer once.

  • template_revisionstringrequirednullable
  • stop_token_idsarray of integerrequirednullable

    Where sample stops by default (end of turn, end of text).

  • queue_messagestringrequirednullable

    While queued: why it waits (GPU capacity, the workspace's limit).

  • from_artifactstringrequirednullable
  • from_checkpointstringrequirednullable
  • last_checkpointstringrequirednullable

    The latest saved state (a save_state, an autosave, a park or the close): what from_checkpoint resumes after a failure.

  • errorstringrequirednullable
  • created_atstring (date-time)required
  • closed_atstring (date-time)requirednullable
  • logged_metricsarray of TrainerMetricPoint

    Recent client-logged scalar metrics series, ordered oldest to newest (included on GET /v1/trainers/{id}).

    3 child fields
    • stepintegerrequired≥ 0
    • metricsmap of numberrequired
    • timestampstring (date-time)required
  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
print(trainer.status, trainer.step, trainer.usage().cost_usd)
Response 200 OKGenerated from the schema
JSON
{
  "id": "trn_3f9c0a1b2c3d4e5f60718293",
  "name": "support-prod",
  "model": "qwen/qwen3-8b",
  "modalities": [
    "text"
  ],
  "mode": "train",
  "adapter": {
    "kind": "lora",
    "rank": 1,
    "alpha": 1,
    "train_multimodal_projector": false
  },
  "status": "queued",
  "step": 0,
  "total_steps": 1,
  "next_seq": 1,
  "pending_ops": 0,
  "closing": false,
  "max_snapshots": 1,
  "snapshot_ttl_s": 1,
  "checkpoint_ttl_s": 300,
  "sample_queue": {
    "queued": 0,
    "running": 0
  },
  "utilization": {
    "train_s": 0,
    "sample_s": 0,
    "ready_s": 0
  },
  "usage": {
    "tokens": 0,
    "cost_usd": 0,
    "prompt_tokens": 0,
    "sampled_tokens": 0
  },
  "max_cost_usd": 1,
  "reserved_cost_usd": 0,
  "price_per_million_tokens": 0,
  "calibrated_lrs": {},
  "idle_timeout_s": 1,
  "max_seq_len": 1,
  "tokenizer": {
    "repo": "string",
    "revision": "string"
  },
  "template_revision": "string",
  "stop_token_ids": [
    0
  ],
  "queue_message": "string",
  "from_artifact": "string",
  "from_checkpoint": "string",
  "last_checkpoint": "string",
  "error": "…",
  "created_at": "2026-11-28T09:30:00.000Z",
  "closed_at": "2026-11-28T09:30:00.000Z",
  "logged_metrics": [
    {
      "step": 0,
      "metrics": {},
      "timestamp": "2026-11-28T09:30:00.000Z"
    }
  ],
  "console_url": "string"
}

Log client-side scalar metrics (e.g. mean_reward, mean_turns) for a trainer step#

POST/v1/trainers/{id}/metrics

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body LogTrainerMetricsRequest

  • stepintegerrequired0–2147483647
  • metricsmap of numberrequired
  • timestampstring (date-time)

Returns

201 TrainerMetricPoint Logged metrics point.

3 fields
  • stepintegerrequired≥ 0
  • metricsmap of numberrequired
  • timestampstring (date-time)required

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
point = trainer.log_metrics(10, {"mean_reward": 0.75})
print(point.step, point.metrics)
Response 201 CreatedGenerated from the schema
JSON
{
  "step": 0,
  "metrics": {},
  "timestamp": "2026-11-28T09:30:00.000Z"
}

Close a trainer: run the ops already submitted (or fail them with abort), save the final state, release the GPU#

POST/v1/trainers/{id}/close

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body CloseTrainerRequest

  • abortbooleandefault false

    Fail the ops the worker has not taken yet (trainer_closed) instead of running them; the ones it took (the one running, and the next it prefetched) finish.

Returns

200 Trainer The trainer (closing or closed).

36 fields
  • idstringrequired

    trn_ and 24 hex.

  • namestringrequired
  • modelstringrequired

    The base model.

  • modalitiesarray of Modalityrequired≥ 1 items

    Input modalities accepted by this trainer's base model (text, image, audio).

  • modeTrainerModerequireddefault "train"

    train (default): full LoRA training and sampling; sample: inference-only sampling session (no optimizer/gradients, higher vLLM KV-cache headroom, allows sampling any catalog LLM).

    "train""sample"

  • adapterobjectrequired
    4 child fields
    • kind"lora"required

      "lora"

    • rankintegerrequired≥ 1
    • alphaintegerrequired≥ 1
    • train_multimodal_projectorboolean
  • statusTrainerStatusrequired

    queued (waiting for a GPU), loading (a worker is loading the base and adapter), ready (running ops), parked (idle: its state is saved and no GPU is held; the next op resumes it), closed, failed (see error).

    "queued""loading""ready""parked""closed""failed"

  • stepintegerrequired≥ 0

    Optimizer steps taken.

  • total_stepsintegernullable

    Optional target optimizer step count configured at creation (null if unset).

  • next_seqintegerrequired≥ 1

    The seq the next op must carry.

  • pending_opsintegerrequired≥ 0

    Train-lane ops (the seq-ordered ones) submitted and not finished yet.

  • closingbooleanrequired

    close was called: the ops already submitted run (with abort, the ones the worker has not taken fail), then it closes. It takes no new op.

  • max_snapshotsintegerrequired≥ 1
  • snapshot_ttl_sintegerrequired≥ 1
  • checkpoint_ttl_sintegernullable

    Configured TTL in seconds for automatic autosave/park checkpoints (null: server default retention).

  • sample_queueobjectrequired

    Sample-lane ops (snapshot samples) waiting and running. At most 1024 together (429 sample_queue_full).

    2 child fields
    • queuedintegerrequired≥ 0
    • runningintegerrequired≥ 0
  • utilizationobjectrequired

    Cumulative worker compute time per lane (train_s: train-lane ops, sample_s: sample-lane batches) and wall time spent loaded (ready_s). The GPU's busy fraction over an interval is the change in train_s + sample_s over the change in ready_s.

    3 child fields
    • train_snumberrequired≥ 0
    • sample_snumberrequired≥ 0
    • ready_snumberrequired≥ 0
  • usageTrainerUsagerequired
    4 child fields
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • prompt_tokensinteger≥ 0
    • sampled_tokensinteger≥ 0
  • max_cost_usdnumberrequired> 0
  • reserved_cost_usdnumberrequired≥ 0

    The worst-case cost of the pending ops. An op is refused (budget_exceeded) when spent + reserved + its worst case would pass max_cost_usd.

  • price_per_million_tokensnumberrequired≥ 0
  • calibrated_lrsmap of numberrequired

    Calibrated learning rates for this trainer's base model by objective (sft, rl, dpo, ...); empty when uncalibrated.

  • idle_timeout_sintegerrequired≥ 1
  • max_seq_lenintegerrequired≥ 1

    The longest datum (and sample prompt + max_tokens) it takes.

  • tokenizerobjectrequirednullable

    The base's tokenizer (Hugging Face repo and revision) for raw-token clients; null until a worker has loaded the trainer once.

  • template_revisionstringrequirednullable
  • stop_token_idsarray of integerrequirednullable

    Where sample stops by default (end of turn, end of text).

  • queue_messagestringrequirednullable

    While queued: why it waits (GPU capacity, the workspace's limit).

  • from_artifactstringrequirednullable
  • from_checkpointstringrequirednullable
  • last_checkpointstringrequirednullable

    The latest saved state (a save_state, an autosave, a park or the close): what from_checkpoint resumes after a failure.

  • errorstringrequirednullable
  • created_atstring (date-time)required
  • closed_atstring (date-time)requirednullable
  • logged_metricsarray of TrainerMetricPoint

    Recent client-logged scalar metrics series, ordered oldest to newest (included on GET /v1/trainers/{id}).

    3 child fields
    • stepintegerrequired≥ 0
    • metricsmap of numberrequired
    • timestampstring (date-time)required
  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
trainer.close(abort=False)
Response 200 OKGenerated from the schema
JSON
{
  "id": "trn_3f9c0a1b2c3d4e5f60718293",
  "name": "support-prod",
  "model": "qwen/qwen3-8b",
  "modalities": [
    "text"
  ],
  "mode": "train",
  "adapter": {
    "kind": "lora",
    "rank": 1,
    "alpha": 1,
    "train_multimodal_projector": false
  },
  "status": "queued",
  "step": 0,
  "total_steps": 1,
  "next_seq": 1,
  "pending_ops": 0,
  "closing": false,
  "max_snapshots": 1,
  "snapshot_ttl_s": 1,
  "checkpoint_ttl_s": 300,
  "sample_queue": {
    "queued": 0,
    "running": 0
  },
  "utilization": {
    "train_s": 0,
    "sample_s": 0,
    "ready_s": 0
  },
  "usage": {
    "tokens": 0,
    "cost_usd": 0,
    "prompt_tokens": 0,
    "sampled_tokens": 0
  },
  "max_cost_usd": 1,
  "reserved_cost_usd": 0,
  "price_per_million_tokens": 0,
  "calibrated_lrs": {},
  "idle_timeout_s": 1,
  "max_seq_len": 1,
  "tokenizer": {
    "repo": "string",
    "revision": "string"
  },
  "template_revision": "string",
  "stop_token_ids": [
    0
  ],
  "queue_message": "string",
  "from_artifact": "string",
  "from_checkpoint": "string",
  "last_checkpoint": "string",
  "error": "…",
  "created_at": "2026-11-28T09:30:00.000Z",
  "closed_at": "2026-11-28T09:30:00.000Z",
  "logged_metrics": [
    {
      "step": 0,
      "metrics": {},
      "timestamp": "2026-11-28T09:30:00.000Z"
    }
  ],
  "console_url": "string"
}

Add the gradient of a loss over a batch#

POST/v1/trainers/{id}/forward_backward

Gradients accumulate until optim_step.

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body ForwardBackwardRequest

  • seqintegerrequired1–2147483647

    This op's place in the trainer's order: the trainer's next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409 seq_conflict.

  • dataarray of Datumrequired≤ 4096 items
  • lossTrainerLossrequired

    A weighted sum over tokens, additive over datums: scale * sum(w * term).

    One of 12 shapes
    1. CrossEntropyLoss
      • type"cross_entropy"required

        "cross_entropy"

      • scalenumber> 0

        Multiplies sum(weights * -logprobs). Default 1 / sum(weights) of this call (the mean over trained tokens, SFTRecipe's per_token). Splitting one batch across calls: pass 1 / sum(weights) of the whole batch.

    2. LinearLoss
      • type"linear"required

        "linear"

      • scalenumber> 0

        Multiplies sum(coefficients * logprobs) (default 1).

    3. ImportanceSamplingLoss
      • type"importance_sampling"required

        "importance_sampling"

      • scalenumber> 0

        Default 1 / sum(weights) of this call.

    4. PpoLoss
      • type"ppo"required

        "ppo"

      • scalenumber> 0

        Default 1 / sum(weights) of this call.

      • clip_lownumber0–1default 0.2
      • clip_highnumber0–1default 0.2
    5. CispoLoss
      • type"cispo"required

        "cispo"

      • scalenumber> 0

        Default 1 / sum(weights) of this call.

      • clip_lownumber0–1default 0.2
      • clip_highnumber0–1default 0.2
    6. DroLoss
      • type"dro"required

        "dro"

      • scalenumber> 0

        Default 1 / sum(weights) of this call.

      • betanumber> 0≤ 10default 0.05
    7. StableReinforceLoss
      • type"stable_reinforce"required

        "stable_reinforce"

      • scalenumber> 0

        Default 1 / sum(weights) of this call.

      • clip_lownumber0–1default 0.2
      • clip_highnumber0–1default 0.28
      • kl_coefnumber0–10default 0
    8. SimpoLoss
      • type"simpo"required

        "simpo"

      • scalenumber> 0

        Default 1 / num_pairs of this call.

      • betanumber> 0≤ 100default 2
      • gammanumber0–100default 0.5
    9. OrpoLoss
      • type"orpo"required

        "orpo"

      • scalenumber> 0

        Default 1 / num_pairs of this call.

      • betanumber> 0≤ 100default 0.1
    10. KtoLoss
      • type"kto"required

        "kto"

      • scalenumber> 0

        Default 1 / num_active_datums of this call.

      • betanumber> 0≤ 10default 0.1
      • desirable_weightnumber> 0≤ 100default 1
      • undesirable_weightnumber> 0≤ 100default 1
    11. NpoLoss
      • type"npo"required

        "npo"

      • scalenumber> 0

        Default 1 / num_active_datums of this call.

      • betanumber> 0≤ 10default 0.1
    12. KlAnchorLoss
      • type"kl_anchor"required

        "kl_anchor"

      • scalenumber> 0

        Default 1 / sum(weights) of this call.

      • betanumber0–100default 0.1
      • modeenumdefault "k3"

        "k3""mse"

  • temperaturenumber> 0≤ 2default 1

    Divides the (soft-capped) logits before the log-softmax: the log-probs are those of the distribution sampled at this temperature. The RL losses need the sampling temperature here.

Returns

200 TrainerOp A resend: the op this seq created.

202 TrainerOp Queued: the op (its future).

16 fields
  • idstringrequired

    op_ and 24 hex.

  • trainer_idstringrequired
  • seqintegerrequirednullable

    Its place in the train lane; null on the sample lane.

  • laneTrainerOpLanerequired

    train: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.

    "train""sample"

  • snapshot_seqintegerrequirednullable

    A snapshot sample: the snapshot it samples from.

  • request_keystringrequirednullable

    A snapshot sample's idempotency key.

  • typeTrainerOpTyperequired

    "forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"

  • statusTrainerOpStatusrequired

    "queued""running""done""failed"

  • resultTrainerOpResult

    An op's result once it is done (by type); absent while it is pending, and when it is large (then result_url).

    One of 8 shapes
    1. ForwardBackwardResult
      • type"forward_backward"required

        "forward_backward"

      • lossnumberrequired

        scale * loss_sum.

      • loss_sumnumberrequired

        sum(w * term) before scale.

      • weight_sumnumberrequired

        sum(w): the weights (or coefficients) the loss read.

      • metricsTrainerLossMetricsrequired

        Over the tokens or datums the loss reads. The RL fields come with importance_sampling, ppo, cispo, dro and stable_reinforce; preference and reference diagnostics come with simpo, orpo, kto, npo and kl_anchor.

        19 child fields
        • tokensintegerrequired≥ 0
        • trained_tokensintegerrequired≥ 0

          Tokens the loss reads (nonzero weight or coefficient).

        • token_accuracynumberrequired0–1
        • truncatedinteger≥ 0
        • kl_sample_trainnumber

          RL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).

        • kl_sample_train_v2number≥ 0

          RL losses: 0.5 * mean((sampling_logprob - logprob)^2).

        • sample_train_max_diffnumber≥ 0

          RL losses: max |sampling_logprob - logprob|.

        • entropynumber

          RL losses: mean token-level Shannon entropy (-sum(p * log p)) of the current policy over the trained tokens.

        • ratio_meannumber≥ 0
        • ratio_maxnumber≥ 0
        • clip_fractionnumber0–1

          ppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.

        • preference_accuracynumber0–1

          simpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.

        • margin_meannumber

          simpo and orpo: mean reward margin (beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).

        • chosen_reward_meannumber

          simpo and kto: mean implicit reward on chosen / desirable sequences.

        • rejected_reward_meannumber

          simpo and kto: mean implicit reward on rejected / undesirable sequences.

        • sft_loss_meannumber

          orpo and kl_anchor: mean SFT negative log-likelihood component.

        • or_loss_meannumber

          orpo: mean odds-ratio preference loss component.

        • kl_refnumber

          kto, npo and kl_anchor: reference divergence diagnostic (batch z_ref for kto, mean log-ratio for npo, mean KL penalty for kl_anchor).

        • ref_diff_maxnumber≥ 0

          kto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.

    2. ForwardResult
      • type"forward"required

        "forward"

      • logprobsarray of Tensorrequired
        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • lossnumberrequirednullable
      • loss_sumnumberrequirednullable
      • weight_sumnumberrequirednullable
      • metricsTrainerLossMetricsrequirednullable
    3. OptimStepResult
      • type"optim_step"required

        "optim_step"

      • stepintegerrequired≥ 0
      • grad_normnumberrequirednullable
      • skippedbooleanrequired

        No gradients were pending: nothing changed.

      • lrnumber> 0

        The numeric learning rate applied (resolved when lr: "auto" was requested).

    4. SampleResult
      • type"sample"required

        "sample"

      • resultsarray of objectrequired
        4 child fields
        • prompt_tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • prompt_logprobsTensor

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • resetbooleanrequired

          A continue whose template rewrote history: prompt_tokens are a fresh render, not tokens plus a delta (the trajectory starts a new segment). False for other prompts.

        • samplesarray of TrainerSamplerequired
          7 child fields
          • tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • logprobsTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • top_logprobsarray of array of TopLogprob

            Present when top_logprobs > 0: for each sampled token, up to K (token_id, logprob) pairs ordered highest logprob first.

          • textstringrequired
          • finish_reasonenumrequired

            stop: a stop token or string; length: max_tokens (or, on a continue, the room left in max_seq_len); context_full: a continue with no room left, no tokens.

            "stop""length""context_full"

          • messageSampledAssistantMessagerequired

            The sample parsed with the base's template (reasoning and OpenAI-style tool calls, arguments a JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays in content and parsed is false.

            4 child fields
            • role"assistant"required

              "assistant"

            • contentstringrequired
            • reasoning_contentstring
            • tool_callsarray of object
              3 child fields
              • idstringrequired
              • type"function"required

                "function"

              • functionobjectrequired
          • parsedbooleanrequired

            The reply parsed cleanly (no malformed tool call). False: message.content holds the raw text, which an environment gets as text.

    5. SaveStateResult
      • type"save_state"required

        "save_state"

      • checkpointobjectrequired
        5 child fields
        • idstringrequired
        • stepintegerrequired≥ 0
        • namestringnullable
        • expires_atstring (date-time)nullable
        • metadatamap of any
    6. ExportResult
      • type"export"required

        "export"

      • artifactArtifactrequired
        16 child fields
        • idstringrequired

          Artifact id: name@version.

        • workspace_idstringrequired
        • namestringrequired≤ 64 chars

          Artifact name, usually the run name.

          Matches ^[a-z0-9][a-z0-9._-]{0,63}$

        • versionstringrequired

          Version, YYYY-MM-DD-N: the release date and its sequence that day.

        • run_idstringrequirednullable

          The run that trained it; null for uploads and imports.

        • checkpoint_idstringrequirednullable

          The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

        • base_modelstringrequired

          The base model the weights apply to.

        • recipe_kindRecipeKindrequired

          "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

        • formatArtifactFormatrequired

          "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

        • sha256stringrequired

          SHA-256 of the bundle; downloads verify it.

          Matches ^[0-9a-f]{64}$

        • size_bytesintegerrequired≥ 0

          Bundle size in bytes.

        • manifestmap of anyrequired

          The bundle's manifest.json: format, base model, adapter and training settings.

        • provenanceArtifactProvenancerequired
          5 child fields
          • sourceenumrequired

            run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

            "run""trainer""upload""import"

          • run_idstringrequirednullable

            source=run: the run that trained it.

          • trainer_idstringrequirednullable

            source=trainer: the trainer that exported it.

          • uploaderstringrequirednullable

            source=upload: the API key (principal) that uploaded it.

          • uristringrequirednullable

            source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

        • eval_reportEvalReportrequirednullable
        • created_atstring (date-time)required

          When it was released.

        • console_urlstringnullable

          Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

    7. RenderResult
      • type"render"required

        "render"

      • dataarray of RenderedDatumrequired
        4 child fields
        • tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • weightsTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • truncatedbooleanrequired
        • mediaarray of MediaItem
          4 child fields
          • kindenumrequired

            "image""audio"

          • mimeenumrequired

            "image/png""image/jpeg""image/webp""audio/wav"

          • datastring≥ 4 chars

            Matches ^[A-Za-z0-9+/]+={0,2}$

          • media_idstring

            Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

            Matches ^med_[0-9a-f]{24}$

    8. SnapshotResult
      • type"snapshot"required

        "snapshot"

      • snapshotobjectrequired
        2 child fields
        • seqintegerrequired≥ 1
        • stepintegerrequired≥ 0
  • result_urlstringrequirednullable

    A result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.

  • errorTrainerOpErrorrequirednullable

    Why it failed: invalid_datum, invalid_continuation, trainer_lost (the worker died; ops after its last saved state are gone), trainer_closed, op_failed, result_expired, snapshot_released, deadline_exceeded, result_too_large.

  • usageTrainerUsagerequired
    4 child fields
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • prompt_tokensinteger≥ 0
    • sampled_tokensinteger≥ 0
  • compute_msintegerrequirednullable

    Worker compute time (a sample-lane op: its batch's, shared by the ops batched together). started_at is when the worker took the op, which may be before it ran (prefetch).

  • created_atstring (date-time)required
  • started_atstring (date-time)requirednullable
  • finished_atstring (date-time)requirednullable

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad, Record, losses

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
out = trainer.forward_backward(
    [
        Record(messages=[
            {"role": "user", "content": "Translate 'good morning' to French."},
            {"role": "assistant", "content": "Bonjour."},
        ])
    ],
    loss=losses.CrossEntropy(),
).result()
print(out.loss)
Response 200 OKGenerated from the schema
JSON
{
  "id": "op_3f9c0a1b2c3d4e5f60718293",
  "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
  "seq": 1,
  "lane": "train",
  "snapshot_seq": 1,
  "request_key": "string",
  "type": "forward_backward",
  "status": "queued",
  "result": {
    "type": "forward_backward",
    "loss": 0,
    "loss_sum": 0,
    "weight_sum": 0,
    "metrics": {
      "tokens": 0,
      "trained_tokens": 0,
      "token_accuracy": 0,
      "truncated": 0,
      "kl_sample_train": 0,
      "kl_sample_train_v2": 0,
      "sample_train_max_diff": 0,
      "entropy": 0,
      "ratio_mean": 0,
      "ratio_max": 0,
      "clip_fraction": 0,
      "preference_accuracy": 0,
      "margin_mean": 0,
      "chosen_reward_mean": 0,
      "rejected_reward_mean": 0,
      "sft_loss_mean": 0,
      "or_loss_mean": 0,
      "kl_ref": 0,
      "ref_diff_max": 0
    }
  },
  "result_url": "string",
  "error": {
    "code": "string",
    "message": "…"
  },
  "usage": {
    "tokens": 0,
    "cost_usd": 0,
    "prompt_tokens": 0,
    "sampled_tokens": 0
  },
  "compute_ms": 0,
  "created_at": "2026-11-28T09:30:00.000Z",
  "started_at": "2026-11-28T09:30:00.000Z",
  "finished_at": "2026-11-28T09:30:00.000Z"
}

Per-token log-probs of a batch (current, base or initial weights); no gradient#

POST/v1/trainers/{id}/forward

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body ForwardRequest

  • seqintegerrequired1–2147483647

    This op's place in the trainer's order: the trainer's next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409 seq_conflict.

  • dataarray of Datumrequired≤ 4096 items
  • weightsstringdefault "current"

    current: the trained adapter; base: the base model (the LoRA disabled in place); initial: the adapter the trainer started from (a from_artifact's; a fresh LoRA's is the base); snapshot:<seq>: a live snapshot's frozen weights (exact PPO ratios against the weights that sampled). Reference log-probs without a second model.

    Matches ^(current|base|initial|snapshot:[1-9][0-9]{0,9})$

  • temperaturenumber> 0≤ 2default 1

    Divides the (soft-capped) logits before the log-softmax: the log-probs are those of the distribution sampled at this temperature. The RL losses need the sampling temperature here.

Returns

200 TrainerOp A resend: the op this seq created.

202 TrainerOp Queued: the op (its future).

16 fields
  • idstringrequired

    op_ and 24 hex.

  • trainer_idstringrequired
  • seqintegerrequirednullable

    Its place in the train lane; null on the sample lane.

  • laneTrainerOpLanerequired

    train: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.

    "train""sample"

  • snapshot_seqintegerrequirednullable

    A snapshot sample: the snapshot it samples from.

  • request_keystringrequirednullable

    A snapshot sample's idempotency key.

  • typeTrainerOpTyperequired

    "forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"

  • statusTrainerOpStatusrequired

    "queued""running""done""failed"

  • resultTrainerOpResult

    An op's result once it is done (by type); absent while it is pending, and when it is large (then result_url).

    One of 8 shapes
    1. ForwardBackwardResult
      • type"forward_backward"required

        "forward_backward"

      • lossnumberrequired

        scale * loss_sum.

      • loss_sumnumberrequired

        sum(w * term) before scale.

      • weight_sumnumberrequired

        sum(w): the weights (or coefficients) the loss read.

      • metricsTrainerLossMetricsrequired

        Over the tokens or datums the loss reads. The RL fields come with importance_sampling, ppo, cispo, dro and stable_reinforce; preference and reference diagnostics come with simpo, orpo, kto, npo and kl_anchor.

        19 child fields
        • tokensintegerrequired≥ 0
        • trained_tokensintegerrequired≥ 0

          Tokens the loss reads (nonzero weight or coefficient).

        • token_accuracynumberrequired0–1
        • truncatedinteger≥ 0
        • kl_sample_trainnumber

          RL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).

        • kl_sample_train_v2number≥ 0

          RL losses: 0.5 * mean((sampling_logprob - logprob)^2).

        • sample_train_max_diffnumber≥ 0

          RL losses: max |sampling_logprob - logprob|.

        • entropynumber

          RL losses: mean token-level Shannon entropy (-sum(p * log p)) of the current policy over the trained tokens.

        • ratio_meannumber≥ 0
        • ratio_maxnumber≥ 0
        • clip_fractionnumber0–1

          ppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.

        • preference_accuracynumber0–1

          simpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.

        • margin_meannumber

          simpo and orpo: mean reward margin (beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).

        • chosen_reward_meannumber

          simpo and kto: mean implicit reward on chosen / desirable sequences.

        • rejected_reward_meannumber

          simpo and kto: mean implicit reward on rejected / undesirable sequences.

        • sft_loss_meannumber

          orpo and kl_anchor: mean SFT negative log-likelihood component.

        • or_loss_meannumber

          orpo: mean odds-ratio preference loss component.

        • kl_refnumber

          kto, npo and kl_anchor: reference divergence diagnostic (batch z_ref for kto, mean log-ratio for npo, mean KL penalty for kl_anchor).

        • ref_diff_maxnumber≥ 0

          kto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.

    2. ForwardResult
      • type"forward"required

        "forward"

      • logprobsarray of Tensorrequired
        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • lossnumberrequirednullable
      • loss_sumnumberrequirednullable
      • weight_sumnumberrequirednullable
      • metricsTrainerLossMetricsrequirednullable
    3. OptimStepResult
      • type"optim_step"required

        "optim_step"

      • stepintegerrequired≥ 0
      • grad_normnumberrequirednullable
      • skippedbooleanrequired

        No gradients were pending: nothing changed.

      • lrnumber> 0

        The numeric learning rate applied (resolved when lr: "auto" was requested).

    4. SampleResult
      • type"sample"required

        "sample"

      • resultsarray of objectrequired
        4 child fields
        • prompt_tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • prompt_logprobsTensor

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • resetbooleanrequired

          A continue whose template rewrote history: prompt_tokens are a fresh render, not tokens plus a delta (the trajectory starts a new segment). False for other prompts.

        • samplesarray of TrainerSamplerequired
          7 child fields
          • tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • logprobsTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • top_logprobsarray of array of TopLogprob

            Present when top_logprobs > 0: for each sampled token, up to K (token_id, logprob) pairs ordered highest logprob first.

          • textstringrequired
          • finish_reasonenumrequired

            stop: a stop token or string; length: max_tokens (or, on a continue, the room left in max_seq_len); context_full: a continue with no room left, no tokens.

            "stop""length""context_full"

          • messageSampledAssistantMessagerequired

            The sample parsed with the base's template (reasoning and OpenAI-style tool calls, arguments a JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays in content and parsed is false.

            4 child fields
            • role"assistant"required

              "assistant"

            • contentstringrequired
            • reasoning_contentstring
            • tool_callsarray of object
              3 child fields
              • idstringrequired
              • type"function"required

                "function"

              • functionobjectrequired
          • parsedbooleanrequired

            The reply parsed cleanly (no malformed tool call). False: message.content holds the raw text, which an environment gets as text.

    5. SaveStateResult
      • type"save_state"required

        "save_state"

      • checkpointobjectrequired
        5 child fields
        • idstringrequired
        • stepintegerrequired≥ 0
        • namestringnullable
        • expires_atstring (date-time)nullable
        • metadatamap of any
    6. ExportResult
      • type"export"required

        "export"

      • artifactArtifactrequired
        16 child fields
        • idstringrequired

          Artifact id: name@version.

        • workspace_idstringrequired
        • namestringrequired≤ 64 chars

          Artifact name, usually the run name.

          Matches ^[a-z0-9][a-z0-9._-]{0,63}$

        • versionstringrequired

          Version, YYYY-MM-DD-N: the release date and its sequence that day.

        • run_idstringrequirednullable

          The run that trained it; null for uploads and imports.

        • checkpoint_idstringrequirednullable

          The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

        • base_modelstringrequired

          The base model the weights apply to.

        • recipe_kindRecipeKindrequired

          "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

        • formatArtifactFormatrequired

          "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

        • sha256stringrequired

          SHA-256 of the bundle; downloads verify it.

          Matches ^[0-9a-f]{64}$

        • size_bytesintegerrequired≥ 0

          Bundle size in bytes.

        • manifestmap of anyrequired

          The bundle's manifest.json: format, base model, adapter and training settings.

        • provenanceArtifactProvenancerequired
          5 child fields
          • sourceenumrequired

            run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

            "run""trainer""upload""import"

          • run_idstringrequirednullable

            source=run: the run that trained it.

          • trainer_idstringrequirednullable

            source=trainer: the trainer that exported it.

          • uploaderstringrequirednullable

            source=upload: the API key (principal) that uploaded it.

          • uristringrequirednullable

            source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

        • eval_reportEvalReportrequirednullable
        • created_atstring (date-time)required

          When it was released.

        • console_urlstringnullable

          Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

    7. RenderResult
      • type"render"required

        "render"

      • dataarray of RenderedDatumrequired
        4 child fields
        • tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • weightsTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • truncatedbooleanrequired
        • mediaarray of MediaItem
          4 child fields
          • kindenumrequired

            "image""audio"

          • mimeenumrequired

            "image/png""image/jpeg""image/webp""audio/wav"

          • datastring≥ 4 chars

            Matches ^[A-Za-z0-9+/]+={0,2}$

          • media_idstring

            Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

            Matches ^med_[0-9a-f]{24}$

    8. SnapshotResult
      • type"snapshot"required

        "snapshot"

      • snapshotobjectrequired
        2 child fields
        • seqintegerrequired≥ 1
        • stepintegerrequired≥ 0
  • result_urlstringrequirednullable

    A result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.

  • errorTrainerOpErrorrequirednullable

    Why it failed: invalid_datum, invalid_continuation, trainer_lost (the worker died; ops after its last saved state are gone), trainer_closed, op_failed, result_expired, snapshot_released, deadline_exceeded, result_too_large.

  • usageTrainerUsagerequired
    4 child fields
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • prompt_tokensinteger≥ 0
    • sampled_tokensinteger≥ 0
  • compute_msintegerrequirednullable

    Worker compute time (a sample-lane op: its batch's, shared by the ops batched together). started_at is when the worker took the op, which may be before it ran (prefetch).

  • created_atstring (date-time)required
  • started_atstring (date-time)requirednullable
  • finished_atstring (date-time)requirednullable

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad, Record

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
out = trainer.forward(
    [
        Record(messages=[
            {"role": "user", "content": "Translate 'good morning' to French."},
            {"role": "assistant", "content": "Bonjour."},
        ])
    ],
    weights="current",
).result()
print(out.loss)
Response 200 OKGenerated from the schema
JSON
{
  "id": "op_3f9c0a1b2c3d4e5f60718293",
  "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
  "seq": 1,
  "lane": "train",
  "snapshot_seq": 1,
  "request_key": "string",
  "type": "forward_backward",
  "status": "queued",
  "result": {
    "type": "forward_backward",
    "loss": 0,
    "loss_sum": 0,
    "weight_sum": 0,
    "metrics": {
      "tokens": 0,
      "trained_tokens": 0,
      "token_accuracy": 0,
      "truncated": 0,
      "kl_sample_train": 0,
      "kl_sample_train_v2": 0,
      "sample_train_max_diff": 0,
      "entropy": 0,
      "ratio_mean": 0,
      "ratio_max": 0,
      "clip_fraction": 0,
      "preference_accuracy": 0,
      "margin_mean": 0,
      "chosen_reward_mean": 0,
      "rejected_reward_mean": 0,
      "sft_loss_mean": 0,
      "or_loss_mean": 0,
      "kl_ref": 0,
      "ref_diff_max": 0
    }
  },
  "result_url": "string",
  "error": {
    "code": "string",
    "message": "…"
  },
  "usage": {
    "tokens": 0,
    "cost_usd": 0,
    "prompt_tokens": 0,
    "sampled_tokens": 0
  },
  "compute_ms": 0,
  "created_at": "2026-11-28T09:30:00.000Z",
  "started_at": "2026-11-28T09:30:00.000Z",
  "finished_at": "2026-11-28T09:30:00.000Z"
}

One AdamW step from the accumulated gradients#

POST/v1/trainers/{id}/optim_step

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body OptimStepRequest

  • seqintegerrequired1–2147483647

    This op's place in the trainer's order: the trainer's next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409 seq_conflict.

  • lrnumber or "auto"required

    Positive learning rate (<= 1), or "auto" to resolve from the base model's calibrated learning rate for objective (refused with 422 uncalibrated_model when uncalibrated).

    One of 2 shapes
    1. number
    2. "auto"
  • objectiveOptimStepObjective

    Training objective used to resolve lr: "auto" (sft, rl, dpo; defaults to sft).

    "sft""rl""dpo"

  • beta1number≥ 0default 0.9
  • beta2number≥ 0default 0.95
  • epsnumber> 0default 1e-8
  • weight_decaynumber≥ 0default 0
  • grad_clip_normnumber≥ 0default 1

    Clip the gradient's global norm to this (0: no clipping).

Returns

200 TrainerOp A resend: the op this seq created.

202 TrainerOp Queued: the op (its future).

16 fields
  • idstringrequired

    op_ and 24 hex.

  • trainer_idstringrequired
  • seqintegerrequirednullable

    Its place in the train lane; null on the sample lane.

  • laneTrainerOpLanerequired

    train: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.

    "train""sample"

  • snapshot_seqintegerrequirednullable

    A snapshot sample: the snapshot it samples from.

  • request_keystringrequirednullable

    A snapshot sample's idempotency key.

  • typeTrainerOpTyperequired

    "forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"

  • statusTrainerOpStatusrequired

    "queued""running""done""failed"

  • resultTrainerOpResult

    An op's result once it is done (by type); absent while it is pending, and when it is large (then result_url).

    One of 8 shapes
    1. ForwardBackwardResult
      • type"forward_backward"required

        "forward_backward"

      • lossnumberrequired

        scale * loss_sum.

      • loss_sumnumberrequired

        sum(w * term) before scale.

      • weight_sumnumberrequired

        sum(w): the weights (or coefficients) the loss read.

      • metricsTrainerLossMetricsrequired

        Over the tokens or datums the loss reads. The RL fields come with importance_sampling, ppo, cispo, dro and stable_reinforce; preference and reference diagnostics come with simpo, orpo, kto, npo and kl_anchor.

        19 child fields
        • tokensintegerrequired≥ 0
        • trained_tokensintegerrequired≥ 0

          Tokens the loss reads (nonzero weight or coefficient).

        • token_accuracynumberrequired0–1
        • truncatedinteger≥ 0
        • kl_sample_trainnumber

          RL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).

        • kl_sample_train_v2number≥ 0

          RL losses: 0.5 * mean((sampling_logprob - logprob)^2).

        • sample_train_max_diffnumber≥ 0

          RL losses: max |sampling_logprob - logprob|.

        • entropynumber

          RL losses: mean token-level Shannon entropy (-sum(p * log p)) of the current policy over the trained tokens.

        • ratio_meannumber≥ 0
        • ratio_maxnumber≥ 0
        • clip_fractionnumber0–1

          ppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.

        • preference_accuracynumber0–1

          simpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.

        • margin_meannumber

          simpo and orpo: mean reward margin (beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).

        • chosen_reward_meannumber

          simpo and kto: mean implicit reward on chosen / desirable sequences.

        • rejected_reward_meannumber

          simpo and kto: mean implicit reward on rejected / undesirable sequences.

        • sft_loss_meannumber

          orpo and kl_anchor: mean SFT negative log-likelihood component.

        • or_loss_meannumber

          orpo: mean odds-ratio preference loss component.

        • kl_refnumber

          kto, npo and kl_anchor: reference divergence diagnostic (batch z_ref for kto, mean log-ratio for npo, mean KL penalty for kl_anchor).

        • ref_diff_maxnumber≥ 0

          kto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.

    2. ForwardResult
      • type"forward"required

        "forward"

      • logprobsarray of Tensorrequired
        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • lossnumberrequirednullable
      • loss_sumnumberrequirednullable
      • weight_sumnumberrequirednullable
      • metricsTrainerLossMetricsrequirednullable
    3. OptimStepResult
      • type"optim_step"required

        "optim_step"

      • stepintegerrequired≥ 0
      • grad_normnumberrequirednullable
      • skippedbooleanrequired

        No gradients were pending: nothing changed.

      • lrnumber> 0

        The numeric learning rate applied (resolved when lr: "auto" was requested).

    4. SampleResult
      • type"sample"required

        "sample"

      • resultsarray of objectrequired
        4 child fields
        • prompt_tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • prompt_logprobsTensor

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • resetbooleanrequired

          A continue whose template rewrote history: prompt_tokens are a fresh render, not tokens plus a delta (the trajectory starts a new segment). False for other prompts.

        • samplesarray of TrainerSamplerequired
          7 child fields
          • tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • logprobsTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • top_logprobsarray of array of TopLogprob

            Present when top_logprobs > 0: for each sampled token, up to K (token_id, logprob) pairs ordered highest logprob first.

          • textstringrequired
          • finish_reasonenumrequired

            stop: a stop token or string; length: max_tokens (or, on a continue, the room left in max_seq_len); context_full: a continue with no room left, no tokens.

            "stop""length""context_full"

          • messageSampledAssistantMessagerequired

            The sample parsed with the base's template (reasoning and OpenAI-style tool calls, arguments a JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays in content and parsed is false.

            4 child fields
            • role"assistant"required

              "assistant"

            • contentstringrequired
            • reasoning_contentstring
            • tool_callsarray of object
              3 child fields
              • idstringrequired
              • type"function"required

                "function"

              • functionobjectrequired
          • parsedbooleanrequired

            The reply parsed cleanly (no malformed tool call). False: message.content holds the raw text, which an environment gets as text.

    5. SaveStateResult
      • type"save_state"required

        "save_state"

      • checkpointobjectrequired
        5 child fields
        • idstringrequired
        • stepintegerrequired≥ 0
        • namestringnullable
        • expires_atstring (date-time)nullable
        • metadatamap of any
    6. ExportResult
      • type"export"required

        "export"

      • artifactArtifactrequired
        16 child fields
        • idstringrequired

          Artifact id: name@version.

        • workspace_idstringrequired
        • namestringrequired≤ 64 chars

          Artifact name, usually the run name.

          Matches ^[a-z0-9][a-z0-9._-]{0,63}$

        • versionstringrequired

          Version, YYYY-MM-DD-N: the release date and its sequence that day.

        • run_idstringrequirednullable

          The run that trained it; null for uploads and imports.

        • checkpoint_idstringrequirednullable

          The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

        • base_modelstringrequired

          The base model the weights apply to.

        • recipe_kindRecipeKindrequired

          "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

        • formatArtifactFormatrequired

          "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

        • sha256stringrequired

          SHA-256 of the bundle; downloads verify it.

          Matches ^[0-9a-f]{64}$

        • size_bytesintegerrequired≥ 0

          Bundle size in bytes.

        • manifestmap of anyrequired

          The bundle's manifest.json: format, base model, adapter and training settings.

        • provenanceArtifactProvenancerequired
          5 child fields
          • sourceenumrequired

            run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

            "run""trainer""upload""import"

          • run_idstringrequirednullable

            source=run: the run that trained it.

          • trainer_idstringrequirednullable

            source=trainer: the trainer that exported it.

          • uploaderstringrequirednullable

            source=upload: the API key (principal) that uploaded it.

          • uristringrequirednullable

            source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

        • eval_reportEvalReportrequirednullable
        • created_atstring (date-time)required

          When it was released.

        • console_urlstringnullable

          Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

    7. RenderResult
      • type"render"required

        "render"

      • dataarray of RenderedDatumrequired
        4 child fields
        • tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • weightsTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • truncatedbooleanrequired
        • mediaarray of MediaItem
          4 child fields
          • kindenumrequired

            "image""audio"

          • mimeenumrequired

            "image/png""image/jpeg""image/webp""audio/wav"

          • datastring≥ 4 chars

            Matches ^[A-Za-z0-9+/]+={0,2}$

          • media_idstring

            Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

            Matches ^med_[0-9a-f]{24}$

    8. SnapshotResult
      • type"snapshot"required

        "snapshot"

      • snapshotobjectrequired
        2 child fields
        • seqintegerrequired≥ 1
        • stepintegerrequired≥ 0
  • result_urlstringrequirednullable

    A result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.

  • errorTrainerOpErrorrequirednullable

    Why it failed: invalid_datum, invalid_continuation, trainer_lost (the worker died; ops after its last saved state are gone), trainer_closed, op_failed, result_expired, snapshot_released, deadline_exceeded, result_too_large.

  • usageTrainerUsagerequired
    4 child fields
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • prompt_tokensinteger≥ 0
    • sampled_tokensinteger≥ 0
  • compute_msintegerrequirednullable

    Worker compute time (a sample-lane op: its batch's, shared by the ops batched together). started_at is when the worker took the op, which may be before it ran (prefetch).

  • created_atstring (date-time)required
  • started_atstring (date-time)requirednullable
  • finished_atstring (date-time)requirednullable

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad, optim

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
step = trainer.optim_step(optim.AdamW(lr="auto", objective="sft")).result()
print(step.step, step.lr, step.grad_norm)
Response 200 OKGenerated from the schema
JSON
{
  "id": "op_3f9c0a1b2c3d4e5f60718293",
  "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
  "seq": 1,
  "lane": "train",
  "snapshot_seq": 1,
  "request_key": "string",
  "type": "forward_backward",
  "status": "queued",
  "result": {
    "type": "forward_backward",
    "loss": 0,
    "loss_sum": 0,
    "weight_sum": 0,
    "metrics": {
      "tokens": 0,
      "trained_tokens": 0,
      "token_accuracy": 0,
      "truncated": 0,
      "kl_sample_train": 0,
      "kl_sample_train_v2": 0,
      "sample_train_max_diff": 0,
      "entropy": 0,
      "ratio_mean": 0,
      "ratio_max": 0,
      "clip_fraction": 0,
      "preference_accuracy": 0,
      "margin_mean": 0,
      "chosen_reward_mean": 0,
      "rejected_reward_mean": 0,
      "sft_loss_mean": 0,
      "or_loss_mean": 0,
      "kl_ref": 0,
      "ref_diff_max": 0
    }
  },
  "result_url": "string",
  "error": {
    "code": "string",
    "message": "…"
  },
  "usage": {
    "tokens": 0,
    "cost_usd": 0,
    "prompt_tokens": 0,
    "sampled_tokens": 0
  },
  "compute_ms": 0,
  "created_at": "2026-11-28T09:30:00.000Z",
  "started_at": "2026-11-28T09:30:00.000Z",
  "finished_at": "2026-11-28T09:30:00.000Z"
}

Sample from the current weights, in op order#

POST/v1/trainers/{id}/sample

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body SampleRequest

  • seqintegerrequired1–2147483647

    This op's place in the trainer's order: the trainer's next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409 seq_conflict.

  • promptsarray of SamplePromptrequired1–1024 items
  • num_samplesinteger1–64default 1
  • max_tokensintegerrequired1–32768
  • temperaturenumber0–2default 1
  • top_pnumber> 0≤ 1default 1
  • top_kintegernullable

    Keep only the top K tokens before sampling (omitted or null: disabled).

  • top_logprobsinteger0–20

    Number of highest-probability (token_id, logprob) pairs to return per generated token from the processed distribution (default 0: omitted).

  • prompt_logprobsboolean

    Return per-prompt-token logprobs under the active weights (float32 length len(prompt_tokens), index 0 is 0.0; default false).

  • stoparray of string or integer≤ 16 items

    Stop strings and token ids; they replace the base's stop tokens (the trainer's stop_token_ids). []: run to max_tokens. A stop token is kept in tokens.

  • seedinteger0–2147483647

    Reproducible sampling for the same request. On a snapshot, a seeded op runs alone (not batched with others).

  • streamboolean

    Emit incremental token deltas to GET /v1/trainers/{id}/ops/{op_id}/stream (SSE) while generating. Streaming snapshot samples run alone (never coalesced) for minimal time-to-first-token.

  • weightsstring

    Weights to sample with (default "current"). "base" disables the LoRA; "initial" uses the starting adapter; "checkpoint:<id>" or "artifact:<id>" hot-swaps a compatible PEFT LoRA adapter on a mode: "sample" session.

    Matches ^(current|base|initial|(?:checkpoint|artifact):[A-Za-z0-9._@:-]{1,200})$

Returns

200 TrainerOp A resend: the op this seq created.

202 TrainerOp Queued: the op (its future).

16 fields
  • idstringrequired

    op_ and 24 hex.

  • trainer_idstringrequired
  • seqintegerrequirednullable

    Its place in the train lane; null on the sample lane.

  • laneTrainerOpLanerequired

    train: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.

    "train""sample"

  • snapshot_seqintegerrequirednullable

    A snapshot sample: the snapshot it samples from.

  • request_keystringrequirednullable

    A snapshot sample's idempotency key.

  • typeTrainerOpTyperequired

    "forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"

  • statusTrainerOpStatusrequired

    "queued""running""done""failed"

  • resultTrainerOpResult

    An op's result once it is done (by type); absent while it is pending, and when it is large (then result_url).

    One of 8 shapes
    1. ForwardBackwardResult
      • type"forward_backward"required

        "forward_backward"

      • lossnumberrequired

        scale * loss_sum.

      • loss_sumnumberrequired

        sum(w * term) before scale.

      • weight_sumnumberrequired

        sum(w): the weights (or coefficients) the loss read.

      • metricsTrainerLossMetricsrequired

        Over the tokens or datums the loss reads. The RL fields come with importance_sampling, ppo, cispo, dro and stable_reinforce; preference and reference diagnostics come with simpo, orpo, kto, npo and kl_anchor.

        19 child fields
        • tokensintegerrequired≥ 0
        • trained_tokensintegerrequired≥ 0

          Tokens the loss reads (nonzero weight or coefficient).

        • token_accuracynumberrequired0–1
        • truncatedinteger≥ 0
        • kl_sample_trainnumber

          RL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).

        • kl_sample_train_v2number≥ 0

          RL losses: 0.5 * mean((sampling_logprob - logprob)^2).

        • sample_train_max_diffnumber≥ 0

          RL losses: max |sampling_logprob - logprob|.

        • entropynumber

          RL losses: mean token-level Shannon entropy (-sum(p * log p)) of the current policy over the trained tokens.

        • ratio_meannumber≥ 0
        • ratio_maxnumber≥ 0
        • clip_fractionnumber0–1

          ppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.

        • preference_accuracynumber0–1

          simpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.

        • margin_meannumber

          simpo and orpo: mean reward margin (beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).

        • chosen_reward_meannumber

          simpo and kto: mean implicit reward on chosen / desirable sequences.

        • rejected_reward_meannumber

          simpo and kto: mean implicit reward on rejected / undesirable sequences.

        • sft_loss_meannumber

          orpo and kl_anchor: mean SFT negative log-likelihood component.

        • or_loss_meannumber

          orpo: mean odds-ratio preference loss component.

        • kl_refnumber

          kto, npo and kl_anchor: reference divergence diagnostic (batch z_ref for kto, mean log-ratio for npo, mean KL penalty for kl_anchor).

        • ref_diff_maxnumber≥ 0

          kto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.

    2. ForwardResult
      • type"forward"required

        "forward"

      • logprobsarray of Tensorrequired
        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • lossnumberrequirednullable
      • loss_sumnumberrequirednullable
      • weight_sumnumberrequirednullable
      • metricsTrainerLossMetricsrequirednullable
    3. OptimStepResult
      • type"optim_step"required

        "optim_step"

      • stepintegerrequired≥ 0
      • grad_normnumberrequirednullable
      • skippedbooleanrequired

        No gradients were pending: nothing changed.

      • lrnumber> 0

        The numeric learning rate applied (resolved when lr: "auto" was requested).

    4. SampleResult
      • type"sample"required

        "sample"

      • resultsarray of objectrequired
        4 child fields
        • prompt_tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • prompt_logprobsTensor

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • resetbooleanrequired

          A continue whose template rewrote history: prompt_tokens are a fresh render, not tokens plus a delta (the trajectory starts a new segment). False for other prompts.

        • samplesarray of TrainerSamplerequired
          7 child fields
          • tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • logprobsTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • top_logprobsarray of array of TopLogprob

            Present when top_logprobs > 0: for each sampled token, up to K (token_id, logprob) pairs ordered highest logprob first.

          • textstringrequired
          • finish_reasonenumrequired

            stop: a stop token or string; length: max_tokens (or, on a continue, the room left in max_seq_len); context_full: a continue with no room left, no tokens.

            "stop""length""context_full"

          • messageSampledAssistantMessagerequired

            The sample parsed with the base's template (reasoning and OpenAI-style tool calls, arguments a JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays in content and parsed is false.

            4 child fields
            • role"assistant"required

              "assistant"

            • contentstringrequired
            • reasoning_contentstring
            • tool_callsarray of object
              3 child fields
              • idstringrequired
              • type"function"required

                "function"

              • functionobjectrequired
          • parsedbooleanrequired

            The reply parsed cleanly (no malformed tool call). False: message.content holds the raw text, which an environment gets as text.

    5. SaveStateResult
      • type"save_state"required

        "save_state"

      • checkpointobjectrequired
        5 child fields
        • idstringrequired
        • stepintegerrequired≥ 0
        • namestringnullable
        • expires_atstring (date-time)nullable
        • metadatamap of any
    6. ExportResult
      • type"export"required

        "export"

      • artifactArtifactrequired
        16 child fields
        • idstringrequired

          Artifact id: name@version.

        • workspace_idstringrequired
        • namestringrequired≤ 64 chars

          Artifact name, usually the run name.

          Matches ^[a-z0-9][a-z0-9._-]{0,63}$

        • versionstringrequired

          Version, YYYY-MM-DD-N: the release date and its sequence that day.

        • run_idstringrequirednullable

          The run that trained it; null for uploads and imports.

        • checkpoint_idstringrequirednullable

          The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

        • base_modelstringrequired

          The base model the weights apply to.

        • recipe_kindRecipeKindrequired

          "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

        • formatArtifactFormatrequired

          "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

        • sha256stringrequired

          SHA-256 of the bundle; downloads verify it.

          Matches ^[0-9a-f]{64}$

        • size_bytesintegerrequired≥ 0

          Bundle size in bytes.

        • manifestmap of anyrequired

          The bundle's manifest.json: format, base model, adapter and training settings.

        • provenanceArtifactProvenancerequired
          5 child fields
          • sourceenumrequired

            run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

            "run""trainer""upload""import"

          • run_idstringrequirednullable

            source=run: the run that trained it.

          • trainer_idstringrequirednullable

            source=trainer: the trainer that exported it.

          • uploaderstringrequirednullable

            source=upload: the API key (principal) that uploaded it.

          • uristringrequirednullable

            source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

        • eval_reportEvalReportrequirednullable
        • created_atstring (date-time)required

          When it was released.

        • console_urlstringnullable

          Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

    7. RenderResult
      • type"render"required

        "render"

      • dataarray of RenderedDatumrequired
        4 child fields
        • tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • weightsTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • truncatedbooleanrequired
        • mediaarray of MediaItem
          4 child fields
          • kindenumrequired

            "image""audio"

          • mimeenumrequired

            "image/png""image/jpeg""image/webp""audio/wav"

          • datastring≥ 4 chars

            Matches ^[A-Za-z0-9+/]+={0,2}$

          • media_idstring

            Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

            Matches ^med_[0-9a-f]{24}$

    8. SnapshotResult
      • type"snapshot"required

        "snapshot"

      • snapshotobjectrequired
        2 child fields
        • seqintegerrequired≥ 1
        • stepintegerrequired≥ 0
  • result_urlstringrequirednullable

    A result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.

  • errorTrainerOpErrorrequirednullable

    Why it failed: invalid_datum, invalid_continuation, trainer_lost (the worker died; ops after its last saved state are gone), trainer_closed, op_failed, result_expired, snapshot_released, deadline_exceeded, result_too_large.

  • usageTrainerUsagerequired
    4 child fields
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • prompt_tokensinteger≥ 0
    • sampled_tokensinteger≥ 0
  • compute_msintegerrequirednullable

    Worker compute time (a sample-lane op: its batch's, shared by the ops batched together). started_at is when the worker took the op, which may be before it ran (prefetch).

  • created_atstring (date-time)required
  • started_atstring (date-time)requirednullable
  • finished_atstring (date-time)requirednullable

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
out = trainer.sample(
    [{"messages": [{"role": "user", "content": "What is 12 * 7?"}]}],
    max_tokens=128,
).result()
print(out.results[0].samples[0].text)
Response 200 OKGenerated from the schema
JSON
{
  "id": "op_3f9c0a1b2c3d4e5f60718293",
  "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
  "seq": 1,
  "lane": "train",
  "snapshot_seq": 1,
  "request_key": "string",
  "type": "forward_backward",
  "status": "queued",
  "result": {
    "type": "forward_backward",
    "loss": 0,
    "loss_sum": 0,
    "weight_sum": 0,
    "metrics": {
      "tokens": 0,
      "trained_tokens": 0,
      "token_accuracy": 0,
      "truncated": 0,
      "kl_sample_train": 0,
      "kl_sample_train_v2": 0,
      "sample_train_max_diff": 0,
      "entropy": 0,
      "ratio_mean": 0,
      "ratio_max": 0,
      "clip_fraction": 0,
      "preference_accuracy": 0,
      "margin_mean": 0,
      "chosen_reward_mean": 0,
      "rejected_reward_mean": 0,
      "sft_loss_mean": 0,
      "or_loss_mean": 0,
      "kl_ref": 0,
      "ref_diff_max": 0
    }
  },
  "result_url": "string",
  "error": {
    "code": "string",
    "message": "…"
  },
  "usage": {
    "tokens": 0,
    "cost_usd": 0,
    "prompt_tokens": 0,
    "sampled_tokens": 0
  },
  "compute_ms": 0,
  "created_at": "2026-11-28T09:30:00.000Z",
  "started_at": "2026-11-28T09:30:00.000Z",
  "finished_at": "2026-11-28T09:30:00.000Z"
}

Save the weights, optimizer, pending gradients and step as a checkpoint#

POST/v1/trainers/{id}/save_state

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body SaveStateRequest

  • seqintegerrequired1–2147483647

    This op's place in the trainer's order: the trainer's next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409 seq_conflict.

  • namestring≤ 128 chars
  • ttl_sintegernullable

    Optional TTL in seconds (300 to 7776000). Omitted or null keeps this checkpoint permanent.

  • metadatamap of any

    Optional user metadata JSON object (at most 16 KiB serialized UTF-8) stored on the checkpoint.

Returns

200 TrainerOp A resend: the op this seq created.

202 TrainerOp Queued: the op (its future).

16 fields
  • idstringrequired

    op_ and 24 hex.

  • trainer_idstringrequired
  • seqintegerrequirednullable

    Its place in the train lane; null on the sample lane.

  • laneTrainerOpLanerequired

    train: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.

    "train""sample"

  • snapshot_seqintegerrequirednullable

    A snapshot sample: the snapshot it samples from.

  • request_keystringrequirednullable

    A snapshot sample's idempotency key.

  • typeTrainerOpTyperequired

    "forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"

  • statusTrainerOpStatusrequired

    "queued""running""done""failed"

  • resultTrainerOpResult

    An op's result once it is done (by type); absent while it is pending, and when it is large (then result_url).

    One of 8 shapes
    1. ForwardBackwardResult
      • type"forward_backward"required

        "forward_backward"

      • lossnumberrequired

        scale * loss_sum.

      • loss_sumnumberrequired

        sum(w * term) before scale.

      • weight_sumnumberrequired

        sum(w): the weights (or coefficients) the loss read.

      • metricsTrainerLossMetricsrequired

        Over the tokens or datums the loss reads. The RL fields come with importance_sampling, ppo, cispo, dro and stable_reinforce; preference and reference diagnostics come with simpo, orpo, kto, npo and kl_anchor.

        19 child fields
        • tokensintegerrequired≥ 0
        • trained_tokensintegerrequired≥ 0

          Tokens the loss reads (nonzero weight or coefficient).

        • token_accuracynumberrequired0–1
        • truncatedinteger≥ 0
        • kl_sample_trainnumber

          RL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).

        • kl_sample_train_v2number≥ 0

          RL losses: 0.5 * mean((sampling_logprob - logprob)^2).

        • sample_train_max_diffnumber≥ 0

          RL losses: max |sampling_logprob - logprob|.

        • entropynumber

          RL losses: mean token-level Shannon entropy (-sum(p * log p)) of the current policy over the trained tokens.

        • ratio_meannumber≥ 0
        • ratio_maxnumber≥ 0
        • clip_fractionnumber0–1

          ppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.

        • preference_accuracynumber0–1

          simpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.

        • margin_meannumber

          simpo and orpo: mean reward margin (beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).

        • chosen_reward_meannumber

          simpo and kto: mean implicit reward on chosen / desirable sequences.

        • rejected_reward_meannumber

          simpo and kto: mean implicit reward on rejected / undesirable sequences.

        • sft_loss_meannumber

          orpo and kl_anchor: mean SFT negative log-likelihood component.

        • or_loss_meannumber

          orpo: mean odds-ratio preference loss component.

        • kl_refnumber

          kto, npo and kl_anchor: reference divergence diagnostic (batch z_ref for kto, mean log-ratio for npo, mean KL penalty for kl_anchor).

        • ref_diff_maxnumber≥ 0

          kto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.

    2. ForwardResult
      • type"forward"required

        "forward"

      • logprobsarray of Tensorrequired
        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • lossnumberrequirednullable
      • loss_sumnumberrequirednullable
      • weight_sumnumberrequirednullable
      • metricsTrainerLossMetricsrequirednullable
    3. OptimStepResult
      • type"optim_step"required

        "optim_step"

      • stepintegerrequired≥ 0
      • grad_normnumberrequirednullable
      • skippedbooleanrequired

        No gradients were pending: nothing changed.

      • lrnumber> 0

        The numeric learning rate applied (resolved when lr: "auto" was requested).

    4. SampleResult
      • type"sample"required

        "sample"

      • resultsarray of objectrequired
        4 child fields
        • prompt_tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • prompt_logprobsTensor

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • resetbooleanrequired

          A continue whose template rewrote history: prompt_tokens are a fresh render, not tokens plus a delta (the trajectory starts a new segment). False for other prompts.

        • samplesarray of TrainerSamplerequired
          7 child fields
          • tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • logprobsTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • top_logprobsarray of array of TopLogprob

            Present when top_logprobs > 0: for each sampled token, up to K (token_id, logprob) pairs ordered highest logprob first.

          • textstringrequired
          • finish_reasonenumrequired

            stop: a stop token or string; length: max_tokens (or, on a continue, the room left in max_seq_len); context_full: a continue with no room left, no tokens.

            "stop""length""context_full"

          • messageSampledAssistantMessagerequired

            The sample parsed with the base's template (reasoning and OpenAI-style tool calls, arguments a JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays in content and parsed is false.

            4 child fields
            • role"assistant"required

              "assistant"

            • contentstringrequired
            • reasoning_contentstring
            • tool_callsarray of object
              3 child fields
              • idstringrequired
              • type"function"required

                "function"

              • functionobjectrequired
          • parsedbooleanrequired

            The reply parsed cleanly (no malformed tool call). False: message.content holds the raw text, which an environment gets as text.

    5. SaveStateResult
      • type"save_state"required

        "save_state"

      • checkpointobjectrequired
        5 child fields
        • idstringrequired
        • stepintegerrequired≥ 0
        • namestringnullable
        • expires_atstring (date-time)nullable
        • metadatamap of any
    6. ExportResult
      • type"export"required

        "export"

      • artifactArtifactrequired
        16 child fields
        • idstringrequired

          Artifact id: name@version.

        • workspace_idstringrequired
        • namestringrequired≤ 64 chars

          Artifact name, usually the run name.

          Matches ^[a-z0-9][a-z0-9._-]{0,63}$

        • versionstringrequired

          Version, YYYY-MM-DD-N: the release date and its sequence that day.

        • run_idstringrequirednullable

          The run that trained it; null for uploads and imports.

        • checkpoint_idstringrequirednullable

          The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

        • base_modelstringrequired

          The base model the weights apply to.

        • recipe_kindRecipeKindrequired

          "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

        • formatArtifactFormatrequired

          "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

        • sha256stringrequired

          SHA-256 of the bundle; downloads verify it.

          Matches ^[0-9a-f]{64}$

        • size_bytesintegerrequired≥ 0

          Bundle size in bytes.

        • manifestmap of anyrequired

          The bundle's manifest.json: format, base model, adapter and training settings.

        • provenanceArtifactProvenancerequired
          5 child fields
          • sourceenumrequired

            run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

            "run""trainer""upload""import"

          • run_idstringrequirednullable

            source=run: the run that trained it.

          • trainer_idstringrequirednullable

            source=trainer: the trainer that exported it.

          • uploaderstringrequirednullable

            source=upload: the API key (principal) that uploaded it.

          • uristringrequirednullable

            source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

        • eval_reportEvalReportrequirednullable
        • created_atstring (date-time)required

          When it was released.

        • console_urlstringnullable

          Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

    7. RenderResult
      • type"render"required

        "render"

      • dataarray of RenderedDatumrequired
        4 child fields
        • tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • weightsTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • truncatedbooleanrequired
        • mediaarray of MediaItem
          4 child fields
          • kindenumrequired

            "image""audio"

          • mimeenumrequired

            "image/png""image/jpeg""image/webp""audio/wav"

          • datastring≥ 4 chars

            Matches ^[A-Za-z0-9+/]+={0,2}$

          • media_idstring

            Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

            Matches ^med_[0-9a-f]{24}$

    8. SnapshotResult
      • type"snapshot"required

        "snapshot"

      • snapshotobjectrequired
        2 child fields
        • seqintegerrequired≥ 1
        • stepintegerrequired≥ 0
  • result_urlstringrequirednullable

    A result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.

  • errorTrainerOpErrorrequirednullable

    Why it failed: invalid_datum, invalid_continuation, trainer_lost (the worker died; ops after its last saved state are gone), trainer_closed, op_failed, result_expired, snapshot_released, deadline_exceeded, result_too_large.

  • usageTrainerUsagerequired
    4 child fields
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • prompt_tokensinteger≥ 0
    • sampled_tokensinteger≥ 0
  • compute_msintegerrequirednullable

    Worker compute time (a sample-lane op: its batch's, shared by the ops batched together). started_at is when the worker took the op, which may be before it ran (prefetch).

  • created_atstring (date-time)required
  • started_atstring (date-time)requirednullable
  • finished_atstring (date-time)requirednullable

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
saved = trainer.save_state(name="step-1", ttl_s=86400).result()
print(saved.checkpoint.id, saved.checkpoint.expires_at)
Response 200 OKGenerated from the schema
JSON
{
  "id": "op_3f9c0a1b2c3d4e5f60718293",
  "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
  "seq": 1,
  "lane": "train",
  "snapshot_seq": 1,
  "request_key": "string",
  "type": "forward_backward",
  "status": "queued",
  "result": {
    "type": "forward_backward",
    "loss": 0,
    "loss_sum": 0,
    "weight_sum": 0,
    "metrics": {
      "tokens": 0,
      "trained_tokens": 0,
      "token_accuracy": 0,
      "truncated": 0,
      "kl_sample_train": 0,
      "kl_sample_train_v2": 0,
      "sample_train_max_diff": 0,
      "entropy": 0,
      "ratio_mean": 0,
      "ratio_max": 0,
      "clip_fraction": 0,
      "preference_accuracy": 0,
      "margin_mean": 0,
      "chosen_reward_mean": 0,
      "rejected_reward_mean": 0,
      "sft_loss_mean": 0,
      "or_loss_mean": 0,
      "kl_ref": 0,
      "ref_diff_max": 0
    }
  },
  "result_url": "string",
  "error": {
    "code": "string",
    "message": "…"
  },
  "usage": {
    "tokens": 0,
    "cost_usd": 0,
    "prompt_tokens": 0,
    "sampled_tokens": 0
  },
  "compute_ms": 0,
  "created_at": "2026-11-28T09:30:00.000Z",
  "started_at": "2026-11-28T09:30:00.000Z",
  "finished_at": "2026-11-28T09:30:00.000Z"
}

Release the current adapter as a peft_lora artifact#

POST/v1/trainers/{id}/export

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body TrainerExportRequest

  • seqintegerrequired1–2147483647

    This op's place in the trainer's order: the trainer's next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409 seq_conflict.

  • namestring≤ 128 chars

    The artifact's name (default: the trainer's).

Returns

200 TrainerOp A resend: the op this seq created.

202 TrainerOp Queued: the op (its future).

16 fields
  • idstringrequired

    op_ and 24 hex.

  • trainer_idstringrequired
  • seqintegerrequirednullable

    Its place in the train lane; null on the sample lane.

  • laneTrainerOpLanerequired

    train: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.

    "train""sample"

  • snapshot_seqintegerrequirednullable

    A snapshot sample: the snapshot it samples from.

  • request_keystringrequirednullable

    A snapshot sample's idempotency key.

  • typeTrainerOpTyperequired

    "forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"

  • statusTrainerOpStatusrequired

    "queued""running""done""failed"

  • resultTrainerOpResult

    An op's result once it is done (by type); absent while it is pending, and when it is large (then result_url).

    One of 8 shapes
    1. ForwardBackwardResult
      • type"forward_backward"required

        "forward_backward"

      • lossnumberrequired

        scale * loss_sum.

      • loss_sumnumberrequired

        sum(w * term) before scale.

      • weight_sumnumberrequired

        sum(w): the weights (or coefficients) the loss read.

      • metricsTrainerLossMetricsrequired

        Over the tokens or datums the loss reads. The RL fields come with importance_sampling, ppo, cispo, dro and stable_reinforce; preference and reference diagnostics come with simpo, orpo, kto, npo and kl_anchor.

        19 child fields
        • tokensintegerrequired≥ 0
        • trained_tokensintegerrequired≥ 0

          Tokens the loss reads (nonzero weight or coefficient).

        • token_accuracynumberrequired0–1
        • truncatedinteger≥ 0
        • kl_sample_trainnumber

          RL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).

        • kl_sample_train_v2number≥ 0

          RL losses: 0.5 * mean((sampling_logprob - logprob)^2).

        • sample_train_max_diffnumber≥ 0

          RL losses: max |sampling_logprob - logprob|.

        • entropynumber

          RL losses: mean token-level Shannon entropy (-sum(p * log p)) of the current policy over the trained tokens.

        • ratio_meannumber≥ 0
        • ratio_maxnumber≥ 0
        • clip_fractionnumber0–1

          ppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.

        • preference_accuracynumber0–1

          simpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.

        • margin_meannumber

          simpo and orpo: mean reward margin (beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).

        • chosen_reward_meannumber

          simpo and kto: mean implicit reward on chosen / desirable sequences.

        • rejected_reward_meannumber

          simpo and kto: mean implicit reward on rejected / undesirable sequences.

        • sft_loss_meannumber

          orpo and kl_anchor: mean SFT negative log-likelihood component.

        • or_loss_meannumber

          orpo: mean odds-ratio preference loss component.

        • kl_refnumber

          kto, npo and kl_anchor: reference divergence diagnostic (batch z_ref for kto, mean log-ratio for npo, mean KL penalty for kl_anchor).

        • ref_diff_maxnumber≥ 0

          kto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.

    2. ForwardResult
      • type"forward"required

        "forward"

      • logprobsarray of Tensorrequired
        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • lossnumberrequirednullable
      • loss_sumnumberrequirednullable
      • weight_sumnumberrequirednullable
      • metricsTrainerLossMetricsrequirednullable
    3. OptimStepResult
      • type"optim_step"required

        "optim_step"

      • stepintegerrequired≥ 0
      • grad_normnumberrequirednullable
      • skippedbooleanrequired

        No gradients were pending: nothing changed.

      • lrnumber> 0

        The numeric learning rate applied (resolved when lr: "auto" was requested).

    4. SampleResult
      • type"sample"required

        "sample"

      • resultsarray of objectrequired
        4 child fields
        • prompt_tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • prompt_logprobsTensor

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • resetbooleanrequired

          A continue whose template rewrote history: prompt_tokens are a fresh render, not tokens plus a delta (the trajectory starts a new segment). False for other prompts.

        • samplesarray of TrainerSamplerequired
          7 child fields
          • tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • logprobsTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • top_logprobsarray of array of TopLogprob

            Present when top_logprobs > 0: for each sampled token, up to K (token_id, logprob) pairs ordered highest logprob first.

          • textstringrequired
          • finish_reasonenumrequired

            stop: a stop token or string; length: max_tokens (or, on a continue, the room left in max_seq_len); context_full: a continue with no room left, no tokens.

            "stop""length""context_full"

          • messageSampledAssistantMessagerequired

            The sample parsed with the base's template (reasoning and OpenAI-style tool calls, arguments a JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays in content and parsed is false.

            4 child fields
            • role"assistant"required

              "assistant"

            • contentstringrequired
            • reasoning_contentstring
            • tool_callsarray of object
              3 child fields
              • idstringrequired
              • type"function"required

                "function"

              • functionobjectrequired
          • parsedbooleanrequired

            The reply parsed cleanly (no malformed tool call). False: message.content holds the raw text, which an environment gets as text.

    5. SaveStateResult
      • type"save_state"required

        "save_state"

      • checkpointobjectrequired
        5 child fields
        • idstringrequired
        • stepintegerrequired≥ 0
        • namestringnullable
        • expires_atstring (date-time)nullable
        • metadatamap of any
    6. ExportResult
      • type"export"required

        "export"

      • artifactArtifactrequired
        16 child fields
        • idstringrequired

          Artifact id: name@version.

        • workspace_idstringrequired
        • namestringrequired≤ 64 chars

          Artifact name, usually the run name.

          Matches ^[a-z0-9][a-z0-9._-]{0,63}$

        • versionstringrequired

          Version, YYYY-MM-DD-N: the release date and its sequence that day.

        • run_idstringrequirednullable

          The run that trained it; null for uploads and imports.

        • checkpoint_idstringrequirednullable

          The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

        • base_modelstringrequired

          The base model the weights apply to.

        • recipe_kindRecipeKindrequired

          "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

        • formatArtifactFormatrequired

          "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

        • sha256stringrequired

          SHA-256 of the bundle; downloads verify it.

          Matches ^[0-9a-f]{64}$

        • size_bytesintegerrequired≥ 0

          Bundle size in bytes.

        • manifestmap of anyrequired

          The bundle's manifest.json: format, base model, adapter and training settings.

        • provenanceArtifactProvenancerequired
          5 child fields
          • sourceenumrequired

            run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

            "run""trainer""upload""import"

          • run_idstringrequirednullable

            source=run: the run that trained it.

          • trainer_idstringrequirednullable

            source=trainer: the trainer that exported it.

          • uploaderstringrequirednullable

            source=upload: the API key (principal) that uploaded it.

          • uristringrequirednullable

            source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

        • eval_reportEvalReportrequirednullable
        • created_atstring (date-time)required

          When it was released.

        • console_urlstringnullable

          Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

    7. RenderResult
      • type"render"required

        "render"

      • dataarray of RenderedDatumrequired
        4 child fields
        • tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • weightsTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • truncatedbooleanrequired
        • mediaarray of MediaItem
          4 child fields
          • kindenumrequired

            "image""audio"

          • mimeenumrequired

            "image/png""image/jpeg""image/webp""audio/wav"

          • datastring≥ 4 chars

            Matches ^[A-Za-z0-9+/]+={0,2}$

          • media_idstring

            Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

            Matches ^med_[0-9a-f]{24}$

    8. SnapshotResult
      • type"snapshot"required

        "snapshot"

      • snapshotobjectrequired
        2 child fields
        • seqintegerrequired≥ 1
        • stepintegerrequired≥ 0
  • result_urlstringrequirednullable

    A result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.

  • errorTrainerOpErrorrequirednullable

    Why it failed: invalid_datum, invalid_continuation, trainer_lost (the worker died; ops after its last saved state are gone), trainer_closed, op_failed, result_expired, snapshot_released, deadline_exceeded, result_too_large.

  • usageTrainerUsagerequired
    4 child fields
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • prompt_tokensinteger≥ 0
    • sampled_tokensinteger≥ 0
  • compute_msintegerrequirednullable

    Worker compute time (a sample-lane op: its batch's, shared by the ops batched together). started_at is when the worker took the op, which may be before it ran (prefetch).

  • created_atstring (date-time)required
  • started_atstring (date-time)requirednullable
  • finished_atstring (date-time)requirednullable

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
exported = trainer.export(name="support-loop-lora").result()
assert exported.artifact is not None
print(exported.artifact.id)
Response 200 OKGenerated from the schema
JSON
{
  "id": "op_3f9c0a1b2c3d4e5f60718293",
  "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
  "seq": 1,
  "lane": "train",
  "snapshot_seq": 1,
  "request_key": "string",
  "type": "forward_backward",
  "status": "queued",
  "result": {
    "type": "forward_backward",
    "loss": 0,
    "loss_sum": 0,
    "weight_sum": 0,
    "metrics": {
      "tokens": 0,
      "trained_tokens": 0,
      "token_accuracy": 0,
      "truncated": 0,
      "kl_sample_train": 0,
      "kl_sample_train_v2": 0,
      "sample_train_max_diff": 0,
      "entropy": 0,
      "ratio_mean": 0,
      "ratio_max": 0,
      "clip_fraction": 0,
      "preference_accuracy": 0,
      "margin_mean": 0,
      "chosen_reward_mean": 0,
      "rejected_reward_mean": 0,
      "sft_loss_mean": 0,
      "or_loss_mean": 0,
      "kl_ref": 0,
      "ref_diff_max": 0
    }
  },
  "result_url": "string",
  "error": {
    "code": "string",
    "message": "…"
  },
  "usage": {
    "tokens": 0,
    "cost_usd": 0,
    "prompt_tokens": 0,
    "sampled_tokens": 0
  },
  "compute_ms": 0,
  "created_at": "2026-11-28T09:30:00.000Z",
  "started_at": "2026-11-28T09:30:00.000Z",
  "finished_at": "2026-11-28T09:30:00.000Z"
}

Render chats with the base's chat template: the exact tokens and weights a messages datum trains#

POST/v1/trainers/{id}/render

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body TrainerRenderRequest

  • seqintegerrequired1–2147483647

    This op's place in the trainer's order: the trainer's next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409 seq_conflict.

  • dataarray of objectrequired1–256 items
    4 child fields
    • messagesarray of ChatMessagerequired≥ 1 items
      7 child fields
      • roleenumrequired

        "system""user""assistant""tool"

      • contentstring or array of map of anynullable
        One of 2 shapes
        1. string
        2. array of map of any
      • reasoning_contentstring
      • tool_callsarray of map of any
      • tool_call_idstring
      • namestring
      • trainboolean
    • toolsarray of map of any
    • train_onenumdefault "last"

      Which assistant turns get weight 1 (the rest of the chat is context), as in recipes.

      "last""all_assistant"

    • thinkingenumdefault "auto"

      "auto""on""off"

Returns

200 TrainerOp A resend: the op this seq created.

202 TrainerOp Queued: the op (its future).

16 fields
  • idstringrequired

    op_ and 24 hex.

  • trainer_idstringrequired
  • seqintegerrequirednullable

    Its place in the train lane; null on the sample lane.

  • laneTrainerOpLanerequired

    train: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.

    "train""sample"

  • snapshot_seqintegerrequirednullable

    A snapshot sample: the snapshot it samples from.

  • request_keystringrequirednullable

    A snapshot sample's idempotency key.

  • typeTrainerOpTyperequired

    "forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"

  • statusTrainerOpStatusrequired

    "queued""running""done""failed"

  • resultTrainerOpResult

    An op's result once it is done (by type); absent while it is pending, and when it is large (then result_url).

    One of 8 shapes
    1. ForwardBackwardResult
      • type"forward_backward"required

        "forward_backward"

      • lossnumberrequired

        scale * loss_sum.

      • loss_sumnumberrequired

        sum(w * term) before scale.

      • weight_sumnumberrequired

        sum(w): the weights (or coefficients) the loss read.

      • metricsTrainerLossMetricsrequired

        Over the tokens or datums the loss reads. The RL fields come with importance_sampling, ppo, cispo, dro and stable_reinforce; preference and reference diagnostics come with simpo, orpo, kto, npo and kl_anchor.

        19 child fields
        • tokensintegerrequired≥ 0
        • trained_tokensintegerrequired≥ 0

          Tokens the loss reads (nonzero weight or coefficient).

        • token_accuracynumberrequired0–1
        • truncatedinteger≥ 0
        • kl_sample_trainnumber

          RL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).

        • kl_sample_train_v2number≥ 0

          RL losses: 0.5 * mean((sampling_logprob - logprob)^2).

        • sample_train_max_diffnumber≥ 0

          RL losses: max |sampling_logprob - logprob|.

        • entropynumber

          RL losses: mean token-level Shannon entropy (-sum(p * log p)) of the current policy over the trained tokens.

        • ratio_meannumber≥ 0
        • ratio_maxnumber≥ 0
        • clip_fractionnumber0–1

          ppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.

        • preference_accuracynumber0–1

          simpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.

        • margin_meannumber

          simpo and orpo: mean reward margin (beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).

        • chosen_reward_meannumber

          simpo and kto: mean implicit reward on chosen / desirable sequences.

        • rejected_reward_meannumber

          simpo and kto: mean implicit reward on rejected / undesirable sequences.

        • sft_loss_meannumber

          orpo and kl_anchor: mean SFT negative log-likelihood component.

        • or_loss_meannumber

          orpo: mean odds-ratio preference loss component.

        • kl_refnumber

          kto, npo and kl_anchor: reference divergence diagnostic (batch z_ref for kto, mean log-ratio for npo, mean KL penalty for kl_anchor).

        • ref_diff_maxnumber≥ 0

          kto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.

    2. ForwardResult
      • type"forward"required

        "forward"

      • logprobsarray of Tensorrequired
        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • lossnumberrequirednullable
      • loss_sumnumberrequirednullable
      • weight_sumnumberrequirednullable
      • metricsTrainerLossMetricsrequirednullable
    3. OptimStepResult
      • type"optim_step"required

        "optim_step"

      • stepintegerrequired≥ 0
      • grad_normnumberrequirednullable
      • skippedbooleanrequired

        No gradients were pending: nothing changed.

      • lrnumber> 0

        The numeric learning rate applied (resolved when lr: "auto" was requested).

    4. SampleResult
      • type"sample"required

        "sample"

      • resultsarray of objectrequired
        4 child fields
        • prompt_tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • prompt_logprobsTensor

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • resetbooleanrequired

          A continue whose template rewrote history: prompt_tokens are a fresh render, not tokens plus a delta (the trajectory starts a new segment). False for other prompts.

        • samplesarray of TrainerSamplerequired
          7 child fields
          • tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • logprobsTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • top_logprobsarray of array of TopLogprob

            Present when top_logprobs > 0: for each sampled token, up to K (token_id, logprob) pairs ordered highest logprob first.

          • textstringrequired
          • finish_reasonenumrequired

            stop: a stop token or string; length: max_tokens (or, on a continue, the room left in max_seq_len); context_full: a continue with no room left, no tokens.

            "stop""length""context_full"

          • messageSampledAssistantMessagerequired

            The sample parsed with the base's template (reasoning and OpenAI-style tool calls, arguments a JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays in content and parsed is false.

            4 child fields
            • role"assistant"required

              "assistant"

            • contentstringrequired
            • reasoning_contentstring
            • tool_callsarray of object
              3 child fields
              • idstringrequired
              • type"function"required

                "function"

              • functionobjectrequired
          • parsedbooleanrequired

            The reply parsed cleanly (no malformed tool call). False: message.content holds the raw text, which an environment gets as text.

    5. SaveStateResult
      • type"save_state"required

        "save_state"

      • checkpointobjectrequired
        5 child fields
        • idstringrequired
        • stepintegerrequired≥ 0
        • namestringnullable
        • expires_atstring (date-time)nullable
        • metadatamap of any
    6. ExportResult
      • type"export"required

        "export"

      • artifactArtifactrequired
        16 child fields
        • idstringrequired

          Artifact id: name@version.

        • workspace_idstringrequired
        • namestringrequired≤ 64 chars

          Artifact name, usually the run name.

          Matches ^[a-z0-9][a-z0-9._-]{0,63}$

        • versionstringrequired

          Version, YYYY-MM-DD-N: the release date and its sequence that day.

        • run_idstringrequirednullable

          The run that trained it; null for uploads and imports.

        • checkpoint_idstringrequirednullable

          The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

        • base_modelstringrequired

          The base model the weights apply to.

        • recipe_kindRecipeKindrequired

          "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

        • formatArtifactFormatrequired

          "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

        • sha256stringrequired

          SHA-256 of the bundle; downloads verify it.

          Matches ^[0-9a-f]{64}$

        • size_bytesintegerrequired≥ 0

          Bundle size in bytes.

        • manifestmap of anyrequired

          The bundle's manifest.json: format, base model, adapter and training settings.

        • provenanceArtifactProvenancerequired
          5 child fields
          • sourceenumrequired

            run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

            "run""trainer""upload""import"

          • run_idstringrequirednullable

            source=run: the run that trained it.

          • trainer_idstringrequirednullable

            source=trainer: the trainer that exported it.

          • uploaderstringrequirednullable

            source=upload: the API key (principal) that uploaded it.

          • uristringrequirednullable

            source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

        • eval_reportEvalReportrequirednullable
        • created_atstring (date-time)required

          When it was released.

        • console_urlstringnullable

          Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

    7. RenderResult
      • type"render"required

        "render"

      • dataarray of RenderedDatumrequired
        4 child fields
        • tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • weightsTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • truncatedbooleanrequired
        • mediaarray of MediaItem
          4 child fields
          • kindenumrequired

            "image""audio"

          • mimeenumrequired

            "image/png""image/jpeg""image/webp""audio/wav"

          • datastring≥ 4 chars

            Matches ^[A-Za-z0-9+/]+={0,2}$

          • media_idstring

            Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

            Matches ^med_[0-9a-f]{24}$

    8. SnapshotResult
      • type"snapshot"required

        "snapshot"

      • snapshotobjectrequired
        2 child fields
        • seqintegerrequired≥ 1
        • stepintegerrequired≥ 0
  • result_urlstringrequirednullable

    A result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.

  • errorTrainerOpErrorrequirednullable

    Why it failed: invalid_datum, invalid_continuation, trainer_lost (the worker died; ops after its last saved state are gone), trainer_closed, op_failed, result_expired, snapshot_released, deadline_exceeded, result_too_large.

  • usageTrainerUsagerequired
    4 child fields
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • prompt_tokensinteger≥ 0
    • sampled_tokensinteger≥ 0
  • compute_msintegerrequirednullable

    Worker compute time (a sample-lane op: its batch's, shared by the ops batched together). started_at is when the worker took the op, which may be before it ran (prefetch).

  • created_atstring (date-time)required
  • started_atstring (date-time)requirednullable
  • finished_atstring (date-time)requirednullable

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad, Record

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
rendered = trainer.render([
    Record(messages=[
        {"role": "user", "content": "Translate 'good morning' to French."},
        {"role": "assistant", "content": "Bonjour."},
    ])
]).result()
print(len(rendered.data[0].tokens))
Response 200 OKGenerated from the schema
JSON
{
  "id": "op_3f9c0a1b2c3d4e5f60718293",
  "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
  "seq": 1,
  "lane": "train",
  "snapshot_seq": 1,
  "request_key": "string",
  "type": "forward_backward",
  "status": "queued",
  "result": {
    "type": "forward_backward",
    "loss": 0,
    "loss_sum": 0,
    "weight_sum": 0,
    "metrics": {
      "tokens": 0,
      "trained_tokens": 0,
      "token_accuracy": 0,
      "truncated": 0,
      "kl_sample_train": 0,
      "kl_sample_train_v2": 0,
      "sample_train_max_diff": 0,
      "entropy": 0,
      "ratio_mean": 0,
      "ratio_max": 0,
      "clip_fraction": 0,
      "preference_accuracy": 0,
      "margin_mean": 0,
      "chosen_reward_mean": 0,
      "rejected_reward_mean": 0,
      "sft_loss_mean": 0,
      "or_loss_mean": 0,
      "kl_ref": 0,
      "ref_diff_max": 0
    }
  },
  "result_url": "string",
  "error": {
    "code": "string",
    "message": "…"
  },
  "usage": {
    "tokens": 0,
    "cost_usd": 0,
    "prompt_tokens": 0,
    "sampled_tokens": 0
  },
  "compute_ms": 0,
  "created_at": "2026-11-28T09:30:00.000Z",
  "started_at": "2026-11-28T09:30:00.000Z",
  "finished_at": "2026-11-28T09:30:00.000Z"
}

Freeze the adapter as a snapshot to sample from while training goes on#

POST/v1/trainers/{id}/snapshot

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body SnapshotRequest

  • seqintegerrequired1–2147483647

    This op's place in the trainer's order: the trainer's next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409 seq_conflict.

Returns

200 TrainerOp A resend: the op this seq created.

202 TrainerOp Queued: the op (its future).

16 fields
  • idstringrequired

    op_ and 24 hex.

  • trainer_idstringrequired
  • seqintegerrequirednullable

    Its place in the train lane; null on the sample lane.

  • laneTrainerOpLanerequired

    train: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.

    "train""sample"

  • snapshot_seqintegerrequirednullable

    A snapshot sample: the snapshot it samples from.

  • request_keystringrequirednullable

    A snapshot sample's idempotency key.

  • typeTrainerOpTyperequired

    "forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"

  • statusTrainerOpStatusrequired

    "queued""running""done""failed"

  • resultTrainerOpResult

    An op's result once it is done (by type); absent while it is pending, and when it is large (then result_url).

    One of 8 shapes
    1. ForwardBackwardResult
      • type"forward_backward"required

        "forward_backward"

      • lossnumberrequired

        scale * loss_sum.

      • loss_sumnumberrequired

        sum(w * term) before scale.

      • weight_sumnumberrequired

        sum(w): the weights (or coefficients) the loss read.

      • metricsTrainerLossMetricsrequired

        Over the tokens or datums the loss reads. The RL fields come with importance_sampling, ppo, cispo, dro and stable_reinforce; preference and reference diagnostics come with simpo, orpo, kto, npo and kl_anchor.

        19 child fields
        • tokensintegerrequired≥ 0
        • trained_tokensintegerrequired≥ 0

          Tokens the loss reads (nonzero weight or coefficient).

        • token_accuracynumberrequired0–1
        • truncatedinteger≥ 0
        • kl_sample_trainnumber

          RL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).

        • kl_sample_train_v2number≥ 0

          RL losses: 0.5 * mean((sampling_logprob - logprob)^2).

        • sample_train_max_diffnumber≥ 0

          RL losses: max |sampling_logprob - logprob|.

        • entropynumber

          RL losses: mean token-level Shannon entropy (-sum(p * log p)) of the current policy over the trained tokens.

        • ratio_meannumber≥ 0
        • ratio_maxnumber≥ 0
        • clip_fractionnumber0–1

          ppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.

        • preference_accuracynumber0–1

          simpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.

        • margin_meannumber

          simpo and orpo: mean reward margin (beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).

        • chosen_reward_meannumber

          simpo and kto: mean implicit reward on chosen / desirable sequences.

        • rejected_reward_meannumber

          simpo and kto: mean implicit reward on rejected / undesirable sequences.

        • sft_loss_meannumber

          orpo and kl_anchor: mean SFT negative log-likelihood component.

        • or_loss_meannumber

          orpo: mean odds-ratio preference loss component.

        • kl_refnumber

          kto, npo and kl_anchor: reference divergence diagnostic (batch z_ref for kto, mean log-ratio for npo, mean KL penalty for kl_anchor).

        • ref_diff_maxnumber≥ 0

          kto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.

    2. ForwardResult
      • type"forward"required

        "forward"

      • logprobsarray of Tensorrequired
        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • lossnumberrequirednullable
      • loss_sumnumberrequirednullable
      • weight_sumnumberrequirednullable
      • metricsTrainerLossMetricsrequirednullable
    3. OptimStepResult
      • type"optim_step"required

        "optim_step"

      • stepintegerrequired≥ 0
      • grad_normnumberrequirednullable
      • skippedbooleanrequired

        No gradients were pending: nothing changed.

      • lrnumber> 0

        The numeric learning rate applied (resolved when lr: "auto" was requested).

    4. SampleResult
      • type"sample"required

        "sample"

      • resultsarray of objectrequired
        4 child fields
        • prompt_tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • prompt_logprobsTensor

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • resetbooleanrequired

          A continue whose template rewrote history: prompt_tokens are a fresh render, not tokens plus a delta (the trajectory starts a new segment). False for other prompts.

        • samplesarray of TrainerSamplerequired
          7 child fields
          • tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • logprobsTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • top_logprobsarray of array of TopLogprob

            Present when top_logprobs > 0: for each sampled token, up to K (token_id, logprob) pairs ordered highest logprob first.

          • textstringrequired
          • finish_reasonenumrequired

            stop: a stop token or string; length: max_tokens (or, on a continue, the room left in max_seq_len); context_full: a continue with no room left, no tokens.

            "stop""length""context_full"

          • messageSampledAssistantMessagerequired

            The sample parsed with the base's template (reasoning and OpenAI-style tool calls, arguments a JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays in content and parsed is false.

            4 child fields
            • role"assistant"required

              "assistant"

            • contentstringrequired
            • reasoning_contentstring
            • tool_callsarray of object
              3 child fields
              • idstringrequired
              • type"function"required

                "function"

              • functionobjectrequired
          • parsedbooleanrequired

            The reply parsed cleanly (no malformed tool call). False: message.content holds the raw text, which an environment gets as text.

    5. SaveStateResult
      • type"save_state"required

        "save_state"

      • checkpointobjectrequired
        5 child fields
        • idstringrequired
        • stepintegerrequired≥ 0
        • namestringnullable
        • expires_atstring (date-time)nullable
        • metadatamap of any
    6. ExportResult
      • type"export"required

        "export"

      • artifactArtifactrequired
        16 child fields
        • idstringrequired

          Artifact id: name@version.

        • workspace_idstringrequired
        • namestringrequired≤ 64 chars

          Artifact name, usually the run name.

          Matches ^[a-z0-9][a-z0-9._-]{0,63}$

        • versionstringrequired

          Version, YYYY-MM-DD-N: the release date and its sequence that day.

        • run_idstringrequirednullable

          The run that trained it; null for uploads and imports.

        • checkpoint_idstringrequirednullable

          The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

        • base_modelstringrequired

          The base model the weights apply to.

        • recipe_kindRecipeKindrequired

          "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

        • formatArtifactFormatrequired

          "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

        • sha256stringrequired

          SHA-256 of the bundle; downloads verify it.

          Matches ^[0-9a-f]{64}$

        • size_bytesintegerrequired≥ 0

          Bundle size in bytes.

        • manifestmap of anyrequired

          The bundle's manifest.json: format, base model, adapter and training settings.

        • provenanceArtifactProvenancerequired
          5 child fields
          • sourceenumrequired

            run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

            "run""trainer""upload""import"

          • run_idstringrequirednullable

            source=run: the run that trained it.

          • trainer_idstringrequirednullable

            source=trainer: the trainer that exported it.

          • uploaderstringrequirednullable

            source=upload: the API key (principal) that uploaded it.

          • uristringrequirednullable

            source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

        • eval_reportEvalReportrequirednullable
        • created_atstring (date-time)required

          When it was released.

        • console_urlstringnullable

          Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

    7. RenderResult
      • type"render"required

        "render"

      • dataarray of RenderedDatumrequired
        4 child fields
        • tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • weightsTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • truncatedbooleanrequired
        • mediaarray of MediaItem
          4 child fields
          • kindenumrequired

            "image""audio"

          • mimeenumrequired

            "image/png""image/jpeg""image/webp""audio/wav"

          • datastring≥ 4 chars

            Matches ^[A-Za-z0-9+/]+={0,2}$

          • media_idstring

            Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

            Matches ^med_[0-9a-f]{24}$

    8. SnapshotResult
      • type"snapshot"required

        "snapshot"

      • snapshotobjectrequired
        2 child fields
        • seqintegerrequired≥ 1
        • stepintegerrequired≥ 0
  • result_urlstringrequirednullable

    A result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.

  • errorTrainerOpErrorrequirednullable

    Why it failed: invalid_datum, invalid_continuation, trainer_lost (the worker died; ops after its last saved state are gone), trainer_closed, op_failed, result_expired, snapshot_released, deadline_exceeded, result_too_large.

  • usageTrainerUsagerequired
    4 child fields
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • prompt_tokensinteger≥ 0
    • sampled_tokensinteger≥ 0
  • compute_msintegerrequirednullable

    Worker compute time (a sample-lane op: its batch's, shared by the ops batched together). started_at is when the worker took the op, which may be before it ran (prefetch).

  • created_atstring (date-time)required
  • started_atstring (date-time)requirednullable
  • finished_atstring (date-time)requirednullable

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
with trainer.snapshot() as snap:
    print(snap.seq)
Response 200 OKGenerated from the schema
JSON
{
  "id": "op_3f9c0a1b2c3d4e5f60718293",
  "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
  "seq": 1,
  "lane": "train",
  "snapshot_seq": 1,
  "request_key": "string",
  "type": "forward_backward",
  "status": "queued",
  "result": {
    "type": "forward_backward",
    "loss": 0,
    "loss_sum": 0,
    "weight_sum": 0,
    "metrics": {
      "tokens": 0,
      "trained_tokens": 0,
      "token_accuracy": 0,
      "truncated": 0,
      "kl_sample_train": 0,
      "kl_sample_train_v2": 0,
      "sample_train_max_diff": 0,
      "entropy": 0,
      "ratio_mean": 0,
      "ratio_max": 0,
      "clip_fraction": 0,
      "preference_accuracy": 0,
      "margin_mean": 0,
      "chosen_reward_mean": 0,
      "rejected_reward_mean": 0,
      "sft_loss_mean": 0,
      "or_loss_mean": 0,
      "kl_ref": 0,
      "ref_diff_max": 0
    }
  },
  "result_url": "string",
  "error": {
    "code": "string",
    "message": "…"
  },
  "usage": {
    "tokens": 0,
    "cost_usd": 0,
    "prompt_tokens": 0,
    "sampled_tokens": 0
  },
  "compute_ms": 0,
  "created_at": "2026-11-28T09:30:00.000Z",
  "started_at": "2026-11-28T09:30:00.000Z",
  "finished_at": "2026-11-28T09:30:00.000Z"
}

List a trainer's ops (newest first), or with after_seq the finished ones after it, in order, waiting for the first#

GET/v1/trainers/{id}/ops

Path parameters

  • idstringrequired≤ 200 chars

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • after_seqintegernullable0–2147483647

    Only finished ops after this seq, ascending; with wait, answers once the first is done (one long-poll resolves every future).

  • waitnumbernullable0–30default 0

    Seconds to wait for the op to finish (long-poll, at most 30); it answers as soon as it is done or failed.

Returns

200 object Ops.

2 fields
  • dataarray of TrainerOprequired
    16 child fields
    • idstringrequired

      op_ and 24 hex.

    • trainer_idstringrequired
    • seqintegerrequirednullable

      Its place in the train lane; null on the sample lane.

    • laneTrainerOpLanerequired

      train: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.

      "train""sample"

    • snapshot_seqintegerrequirednullable

      A snapshot sample: the snapshot it samples from.

    • request_keystringrequirednullable

      A snapshot sample's idempotency key.

    • typeTrainerOpTyperequired

      "forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"

    • statusTrainerOpStatusrequired

      "queued""running""done""failed"

    • resultTrainerOpResult

      An op's result once it is done (by type); absent while it is pending, and when it is large (then result_url).

      One of 8 shapes
      1. ForwardBackwardResult
        • type"forward_backward"required

          "forward_backward"

        • lossnumberrequired

          scale * loss_sum.

        • loss_sumnumberrequired

          sum(w * term) before scale.

        • weight_sumnumberrequired

          sum(w): the weights (or coefficients) the loss read.

        • metricsTrainerLossMetricsrequired

          Over the tokens or datums the loss reads. The RL fields come with importance_sampling, ppo, cispo, dro and stable_reinforce; preference and reference diagnostics come with simpo, orpo, kto, npo and kl_anchor.

          19 child fields
          • tokensintegerrequired≥ 0
          • trained_tokensintegerrequired≥ 0

            Tokens the loss reads (nonzero weight or coefficient).

          • token_accuracynumberrequired0–1
          • truncatedinteger≥ 0
          • kl_sample_trainnumber

            RL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).

          • kl_sample_train_v2number≥ 0

            RL losses: 0.5 * mean((sampling_logprob - logprob)^2).

          • sample_train_max_diffnumber≥ 0

            RL losses: max |sampling_logprob - logprob|.

          • entropynumber

            RL losses: mean token-level Shannon entropy (-sum(p * log p)) of the current policy over the trained tokens.

          • ratio_meannumber≥ 0
          • ratio_maxnumber≥ 0
          • clip_fractionnumber0–1

            ppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.

          • preference_accuracynumber0–1

            simpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.

          • margin_meannumber

            simpo and orpo: mean reward margin (beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).

          • chosen_reward_meannumber

            simpo and kto: mean implicit reward on chosen / desirable sequences.

          • rejected_reward_meannumber

            simpo and kto: mean implicit reward on rejected / undesirable sequences.

          • sft_loss_meannumber

            orpo and kl_anchor: mean SFT negative log-likelihood component.

          • or_loss_meannumber

            orpo: mean odds-ratio preference loss component.

          • kl_refnumber

            kto, npo and kl_anchor: reference divergence diagnostic (batch z_ref for kto, mean log-ratio for npo, mean KL penalty for kl_anchor).

          • ref_diff_maxnumber≥ 0

            kto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.

      2. ForwardResult
        • type"forward"required

          "forward"

        • logprobsarray of Tensorrequired
          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • lossnumberrequirednullable
        • loss_sumnumberrequirednullable
        • weight_sumnumberrequirednullable
        • metricsTrainerLossMetricsrequirednullable
      3. OptimStepResult
        • type"optim_step"required

          "optim_step"

        • stepintegerrequired≥ 0
        • grad_normnumberrequirednullable
        • skippedbooleanrequired

          No gradients were pending: nothing changed.

        • lrnumber> 0

          The numeric learning rate applied (resolved when lr: "auto" was requested).

      4. SampleResult
        • type"sample"required

          "sample"

        • resultsarray of objectrequired
          4 child fields
          • prompt_tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • prompt_logprobsTensor

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • resetbooleanrequired

            A continue whose template rewrote history: prompt_tokens are a fresh render, not tokens plus a delta (the trajectory starts a new segment). False for other prompts.

          • samplesarray of TrainerSamplerequired
            7 child fields
            • tokensTensorrequired

              A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

              2 child fields
              • dtypeenumrequired

                "int32""float32"

              • b64stringrequired

                Matches ^[A-Za-z0-9+/]*={0,2}$

            • logprobsTensorrequired

              A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

              2 child fields
              • dtypeenumrequired

                "int32""float32"

              • b64stringrequired

                Matches ^[A-Za-z0-9+/]*={0,2}$

            • top_logprobsarray of array of TopLogprob

              Present when top_logprobs > 0: for each sampled token, up to K (token_id, logprob) pairs ordered highest logprob first.

            • textstringrequired
            • finish_reasonenumrequired

              stop: a stop token or string; length: max_tokens (or, on a continue, the room left in max_seq_len); context_full: a continue with no room left, no tokens.

              "stop""length""context_full"

            • messageSampledAssistantMessagerequired

              The sample parsed with the base's template (reasoning and OpenAI-style tool calls, arguments a JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays in content and parsed is false.

              4 child fields
              • role"assistant"required

                "assistant"

              • contentstringrequired
              • reasoning_contentstring
              • tool_callsarray of object
            • parsedbooleanrequired

              The reply parsed cleanly (no malformed tool call). False: message.content holds the raw text, which an environment gets as text.

      5. SaveStateResult
        • type"save_state"required

          "save_state"

        • checkpointobjectrequired
          5 child fields
          • idstringrequired
          • stepintegerrequired≥ 0
          • namestringnullable
          • expires_atstring (date-time)nullable
          • metadatamap of any
      6. ExportResult
        • type"export"required

          "export"

        • artifactArtifactrequired
          16 child fields
          • idstringrequired

            Artifact id: name@version.

          • workspace_idstringrequired
          • namestringrequired≤ 64 chars

            Artifact name, usually the run name.

            Matches ^[a-z0-9][a-z0-9._-]{0,63}$

          • versionstringrequired

            Version, YYYY-MM-DD-N: the release date and its sequence that day.

          • run_idstringrequirednullable

            The run that trained it; null for uploads and imports.

          • checkpoint_idstringrequirednullable

            The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

          • base_modelstringrequired

            The base model the weights apply to.

          • recipe_kindRecipeKindrequired

            "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

          • formatArtifactFormatrequired

            "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

          • sha256stringrequired

            SHA-256 of the bundle; downloads verify it.

            Matches ^[0-9a-f]{64}$

          • size_bytesintegerrequired≥ 0

            Bundle size in bytes.

          • manifestmap of anyrequired

            The bundle's manifest.json: format, base model, adapter and training settings.

          • provenanceArtifactProvenancerequired
            5 child fields
            • sourceenumrequired

              run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

              "run""trainer""upload""import"

            • run_idstringrequirednullable

              source=run: the run that trained it.

            • trainer_idstringrequirednullable

              source=trainer: the trainer that exported it.

            • uploaderstringrequirednullable

              source=upload: the API key (principal) that uploaded it.

            • uristringrequirednullable

              source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

          • eval_reportEvalReportrequirednullable
          • created_atstring (date-time)required

            When it was released.

          • console_urlstringnullable

            Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

      7. RenderResult
        • type"render"required

          "render"

        • dataarray of RenderedDatumrequired
          4 child fields
          • tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • weightsTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • truncatedbooleanrequired
          • mediaarray of MediaItem
            4 child fields
            • kindenumrequired

              "image""audio"

            • mimeenumrequired

              "image/png""image/jpeg""image/webp""audio/wav"

            • datastring≥ 4 chars

              Matches ^[A-Za-z0-9+/]+={0,2}$

            • media_idstring

              Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

              Matches ^med_[0-9a-f]{24}$

      8. SnapshotResult
        • type"snapshot"required

          "snapshot"

        • snapshotobjectrequired
          2 child fields
          • seqintegerrequired≥ 1
          • stepintegerrequired≥ 0
    • result_urlstringrequirednullable

      A result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.

    • errorTrainerOpErrorrequirednullable

      Why it failed: invalid_datum, invalid_continuation, trainer_lost (the worker died; ops after its last saved state are gone), trainer_closed, op_failed, result_expired, snapshot_released, deadline_exceeded, result_too_large.

    • usageTrainerUsagerequired
      4 child fields
      • tokensintegerrequired≥ 0
      • cost_usdnumberrequired≥ 0
      • prompt_tokensinteger≥ 0
      • sampled_tokensinteger≥ 0
    • compute_msintegerrequirednullable

      Worker compute time (a sample-lane op: its batch's, shared by the ops batched together). started_at is when the worker took the op, which may be before it ran (prefetch).

    • created_atstring (date-time)required
    • started_atstring (date-time)requirednullable
    • finished_atstring (date-time)requirednullable
  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
cURL
curl "$GRADIATED_BASE_URL/v1/trainers/trn_3f9c0a1b2c3d4e5f60718293/ops" \
  -H "Authorization: Bearer $GRADIATED_API_KEY"
Response 200 OKGenerated from the schema
JSON
{
  "data": [
    {
      "id": "op_3f9c0a1b2c3d4e5f60718293",
      "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
      "seq": 1,
      "lane": "train",
      "snapshot_seq": 1,
      "request_key": "string",
      "type": "forward_backward",
      "status": "queued",
      "result": {
        "type": "forward_backward",
        "loss": 0,
        "loss_sum": 0,
        "weight_sum": 0,
        "metrics": {
          "tokens": 0,
          "trained_tokens": 0,
          "token_accuracy": 0,
          "truncated": 0,
          "kl_sample_train": 0,
          "kl_sample_train_v2": 0,
          "sample_train_max_diff": 0,
          "entropy": 0,
          "ratio_mean": 0,
          "ratio_max": 0,
          "clip_fraction": 0,
          "preference_accuracy": 0,
          "margin_mean": 0,
          "chosen_reward_mean": 0,
          "rejected_reward_mean": 0,
          "sft_loss_mean": 0,
          "or_loss_mean": 0,
          "kl_ref": 0,
          "ref_diff_max": 0
        }
      },
      "result_url": "string",
      "error": {
        "code": "string",
        "message": "…"
      },
      "usage": {
        "tokens": 0,
        "cost_usd": 0,
        "prompt_tokens": 0,
        "sampled_tokens": 0
      },
      "compute_ms": 0,
      "created_at": "2026-11-28T09:30:00.000Z",
      "started_at": "2026-11-28T09:30:00.000Z",
      "finished_at": "2026-11-28T09:30:00.000Z"
    }
  ],
  "next_cursor": "string"
}

Get an op; with wait, long-poll until it finishes#

GET/v1/trainers/{id}/ops/{op_id}

Path parameters

  • idstringrequired≤ 200 chars
  • op_idstringrequired≤ 200 chars

Query parameters

  • waitnumbernullable0–30default 0

    Seconds to wait for the op to finish (long-poll, at most 30); it answers as soon as it is done or failed.

Returns

200 TrainerOp The op.

16 fields
  • idstringrequired

    op_ and 24 hex.

  • trainer_idstringrequired
  • seqintegerrequirednullable

    Its place in the train lane; null on the sample lane.

  • laneTrainerOpLanerequired

    train: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.

    "train""sample"

  • snapshot_seqintegerrequirednullable

    A snapshot sample: the snapshot it samples from.

  • request_keystringrequirednullable

    A snapshot sample's idempotency key.

  • typeTrainerOpTyperequired

    "forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"

  • statusTrainerOpStatusrequired

    "queued""running""done""failed"

  • resultTrainerOpResult

    An op's result once it is done (by type); absent while it is pending, and when it is large (then result_url).

    One of 8 shapes
    1. ForwardBackwardResult
      • type"forward_backward"required

        "forward_backward"

      • lossnumberrequired

        scale * loss_sum.

      • loss_sumnumberrequired

        sum(w * term) before scale.

      • weight_sumnumberrequired

        sum(w): the weights (or coefficients) the loss read.

      • metricsTrainerLossMetricsrequired

        Over the tokens or datums the loss reads. The RL fields come with importance_sampling, ppo, cispo, dro and stable_reinforce; preference and reference diagnostics come with simpo, orpo, kto, npo and kl_anchor.

        19 child fields
        • tokensintegerrequired≥ 0
        • trained_tokensintegerrequired≥ 0

          Tokens the loss reads (nonzero weight or coefficient).

        • token_accuracynumberrequired0–1
        • truncatedinteger≥ 0
        • kl_sample_trainnumber

          RL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).

        • kl_sample_train_v2number≥ 0

          RL losses: 0.5 * mean((sampling_logprob - logprob)^2).

        • sample_train_max_diffnumber≥ 0

          RL losses: max |sampling_logprob - logprob|.

        • entropynumber

          RL losses: mean token-level Shannon entropy (-sum(p * log p)) of the current policy over the trained tokens.

        • ratio_meannumber≥ 0
        • ratio_maxnumber≥ 0
        • clip_fractionnumber0–1

          ppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.

        • preference_accuracynumber0–1

          simpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.

        • margin_meannumber

          simpo and orpo: mean reward margin (beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).

        • chosen_reward_meannumber

          simpo and kto: mean implicit reward on chosen / desirable sequences.

        • rejected_reward_meannumber

          simpo and kto: mean implicit reward on rejected / undesirable sequences.

        • sft_loss_meannumber

          orpo and kl_anchor: mean SFT negative log-likelihood component.

        • or_loss_meannumber

          orpo: mean odds-ratio preference loss component.

        • kl_refnumber

          kto, npo and kl_anchor: reference divergence diagnostic (batch z_ref for kto, mean log-ratio for npo, mean KL penalty for kl_anchor).

        • ref_diff_maxnumber≥ 0

          kto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.

    2. ForwardResult
      • type"forward"required

        "forward"

      • logprobsarray of Tensorrequired
        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • lossnumberrequirednullable
      • loss_sumnumberrequirednullable
      • weight_sumnumberrequirednullable
      • metricsTrainerLossMetricsrequirednullable
    3. OptimStepResult
      • type"optim_step"required

        "optim_step"

      • stepintegerrequired≥ 0
      • grad_normnumberrequirednullable
      • skippedbooleanrequired

        No gradients were pending: nothing changed.

      • lrnumber> 0

        The numeric learning rate applied (resolved when lr: "auto" was requested).

    4. SampleResult
      • type"sample"required

        "sample"

      • resultsarray of objectrequired
        4 child fields
        • prompt_tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • prompt_logprobsTensor

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • resetbooleanrequired

          A continue whose template rewrote history: prompt_tokens are a fresh render, not tokens plus a delta (the trajectory starts a new segment). False for other prompts.

        • samplesarray of TrainerSamplerequired
          7 child fields
          • tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • logprobsTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • top_logprobsarray of array of TopLogprob

            Present when top_logprobs > 0: for each sampled token, up to K (token_id, logprob) pairs ordered highest logprob first.

          • textstringrequired
          • finish_reasonenumrequired

            stop: a stop token or string; length: max_tokens (or, on a continue, the room left in max_seq_len); context_full: a continue with no room left, no tokens.

            "stop""length""context_full"

          • messageSampledAssistantMessagerequired

            The sample parsed with the base's template (reasoning and OpenAI-style tool calls, arguments a JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays in content and parsed is false.

            4 child fields
            • role"assistant"required

              "assistant"

            • contentstringrequired
            • reasoning_contentstring
            • tool_callsarray of object
              3 child fields
              • idstringrequired
              • type"function"required

                "function"

              • functionobjectrequired
          • parsedbooleanrequired

            The reply parsed cleanly (no malformed tool call). False: message.content holds the raw text, which an environment gets as text.

    5. SaveStateResult
      • type"save_state"required

        "save_state"

      • checkpointobjectrequired
        5 child fields
        • idstringrequired
        • stepintegerrequired≥ 0
        • namestringnullable
        • expires_atstring (date-time)nullable
        • metadatamap of any
    6. ExportResult
      • type"export"required

        "export"

      • artifactArtifactrequired
        16 child fields
        • idstringrequired

          Artifact id: name@version.

        • workspace_idstringrequired
        • namestringrequired≤ 64 chars

          Artifact name, usually the run name.

          Matches ^[a-z0-9][a-z0-9._-]{0,63}$

        • versionstringrequired

          Version, YYYY-MM-DD-N: the release date and its sequence that day.

        • run_idstringrequirednullable

          The run that trained it; null for uploads and imports.

        • checkpoint_idstringrequirednullable

          The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

        • base_modelstringrequired

          The base model the weights apply to.

        • recipe_kindRecipeKindrequired

          "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

        • formatArtifactFormatrequired

          "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

        • sha256stringrequired

          SHA-256 of the bundle; downloads verify it.

          Matches ^[0-9a-f]{64}$

        • size_bytesintegerrequired≥ 0

          Bundle size in bytes.

        • manifestmap of anyrequired

          The bundle's manifest.json: format, base model, adapter and training settings.

        • provenanceArtifactProvenancerequired
          5 child fields
          • sourceenumrequired

            run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

            "run""trainer""upload""import"

          • run_idstringrequirednullable

            source=run: the run that trained it.

          • trainer_idstringrequirednullable

            source=trainer: the trainer that exported it.

          • uploaderstringrequirednullable

            source=upload: the API key (principal) that uploaded it.

          • uristringrequirednullable

            source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

        • eval_reportEvalReportrequirednullable
        • created_atstring (date-time)required

          When it was released.

        • console_urlstringnullable

          Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

    7. RenderResult
      • type"render"required

        "render"

      • dataarray of RenderedDatumrequired
        4 child fields
        • tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • weightsTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • truncatedbooleanrequired
        • mediaarray of MediaItem
          4 child fields
          • kindenumrequired

            "image""audio"

          • mimeenumrequired

            "image/png""image/jpeg""image/webp""audio/wav"

          • datastring≥ 4 chars

            Matches ^[A-Za-z0-9+/]+={0,2}$

          • media_idstring

            Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

            Matches ^med_[0-9a-f]{24}$

    8. SnapshotResult
      • type"snapshot"required

        "snapshot"

      • snapshotobjectrequired
        2 child fields
        • seqintegerrequired≥ 1
        • stepintegerrequired≥ 0
  • result_urlstringrequirednullable

    A result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.

  • errorTrainerOpErrorrequirednullable

    Why it failed: invalid_datum, invalid_continuation, trainer_lost (the worker died; ops after its last saved state are gone), trainer_closed, op_failed, result_expired, snapshot_released, deadline_exceeded, result_too_large.

  • usageTrainerUsagerequired
    4 child fields
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • prompt_tokensinteger≥ 0
    • sampled_tokensinteger≥ 0
  • compute_msintegerrequirednullable

    Worker compute time (a sample-lane op: its batch's, shared by the ops batched together). started_at is when the worker took the op, which may be before it ran (prefetch).

  • created_atstring (date-time)required
  • started_atstring (date-time)requirednullable
  • finished_atstring (date-time)requirednullable

Errors: 400 401 403 404 409 422 500 503

Request
cURL
curl "$GRADIATED_BASE_URL/v1/trainers/trn_3f9c0a1b2c3d4e5f60718293/ops/op_3f9c0a1b2c3d4e5f60718293" \
  -H "Authorization: Bearer $GRADIATED_API_KEY"
Response 200 OKGenerated from the schema
JSON
{
  "id": "op_3f9c0a1b2c3d4e5f60718293",
  "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
  "seq": 1,
  "lane": "train",
  "snapshot_seq": 1,
  "request_key": "string",
  "type": "forward_backward",
  "status": "queued",
  "result": {
    "type": "forward_backward",
    "loss": 0,
    "loss_sum": 0,
    "weight_sum": 0,
    "metrics": {
      "tokens": 0,
      "trained_tokens": 0,
      "token_accuracy": 0,
      "truncated": 0,
      "kl_sample_train": 0,
      "kl_sample_train_v2": 0,
      "sample_train_max_diff": 0,
      "entropy": 0,
      "ratio_mean": 0,
      "ratio_max": 0,
      "clip_fraction": 0,
      "preference_accuracy": 0,
      "margin_mean": 0,
      "chosen_reward_mean": 0,
      "rejected_reward_mean": 0,
      "sft_loss_mean": 0,
      "or_loss_mean": 0,
      "kl_ref": 0,
      "ref_diff_max": 0
    }
  },
  "result_url": "string",
  "error": {
    "code": "string",
    "message": "…"
  },
  "usage": {
    "tokens": 0,
    "cost_usd": 0,
    "prompt_tokens": 0,
    "sampled_tokens": 0
  },
  "compute_ms": 0,
  "created_at": "2026-11-28T09:30:00.000Z",
  "started_at": "2026-11-28T09:30:00.000Z",
  "finished_at": "2026-11-28T09:30:00.000Z"
}

Stream incremental token deltas of a sample op as Server-Sent Events#

GET/v1/trainers/{id}/ops/{op_id}/stream

Emits event: delta JSON frames in seq order (id = chunk seq; pass Last-Event-ID to resume) and terminates with event: done carrying the final TrainerOp, or event: error on failure.

Path parameters

  • idstringrequired≤ 200 chars
  • op_idstringrequired≤ 200 chars

Returns

200 string SSE stream of sample deltas and terminal op event.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
stream = trainer.sample_stream(
    [{"messages": [{"role": "user", "content": "What is 12 * 7?"}]}],
    max_tokens=128,
)
for delta in stream:
    print(delta.text, end="", flush=True)
Response 200 OK

text/event-stream: SSE stream of sample deltas and terminal op event.

Long-poll many ops (either lane): the finished ones among ids, as soon as there is one#

POST/v1/trainers/{id}/ops/wait

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body WaitTrainerOpsRequest

  • idsarray of stringrequired1–1024 items
  • wait_snumber0–30default 20

Returns

200 object The finished ops among ids (none after wait_s).

1 fields
  • dataarray of TrainerOprequired
    16 child fields
    • idstringrequired

      op_ and 24 hex.

    • trainer_idstringrequired
    • seqintegerrequirednullable

      Its place in the train lane; null on the sample lane.

    • laneTrainerOpLanerequired

      train: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.

      "train""sample"

    • snapshot_seqintegerrequirednullable

      A snapshot sample: the snapshot it samples from.

    • request_keystringrequirednullable

      A snapshot sample's idempotency key.

    • typeTrainerOpTyperequired

      "forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"

    • statusTrainerOpStatusrequired

      "queued""running""done""failed"

    • resultTrainerOpResult

      An op's result once it is done (by type); absent while it is pending, and when it is large (then result_url).

      One of 8 shapes
      1. ForwardBackwardResult
        • type"forward_backward"required

          "forward_backward"

        • lossnumberrequired

          scale * loss_sum.

        • loss_sumnumberrequired

          sum(w * term) before scale.

        • weight_sumnumberrequired

          sum(w): the weights (or coefficients) the loss read.

        • metricsTrainerLossMetricsrequired

          Over the tokens or datums the loss reads. The RL fields come with importance_sampling, ppo, cispo, dro and stable_reinforce; preference and reference diagnostics come with simpo, orpo, kto, npo and kl_anchor.

          19 child fields
          • tokensintegerrequired≥ 0
          • trained_tokensintegerrequired≥ 0

            Tokens the loss reads (nonzero weight or coefficient).

          • token_accuracynumberrequired0–1
          • truncatedinteger≥ 0
          • kl_sample_trainnumber

            RL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).

          • kl_sample_train_v2number≥ 0

            RL losses: 0.5 * mean((sampling_logprob - logprob)^2).

          • sample_train_max_diffnumber≥ 0

            RL losses: max |sampling_logprob - logprob|.

          • entropynumber

            RL losses: mean token-level Shannon entropy (-sum(p * log p)) of the current policy over the trained tokens.

          • ratio_meannumber≥ 0
          • ratio_maxnumber≥ 0
          • clip_fractionnumber0–1

            ppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.

          • preference_accuracynumber0–1

            simpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.

          • margin_meannumber

            simpo and orpo: mean reward margin (beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).

          • chosen_reward_meannumber

            simpo and kto: mean implicit reward on chosen / desirable sequences.

          • rejected_reward_meannumber

            simpo and kto: mean implicit reward on rejected / undesirable sequences.

          • sft_loss_meannumber

            orpo and kl_anchor: mean SFT negative log-likelihood component.

          • or_loss_meannumber

            orpo: mean odds-ratio preference loss component.

          • kl_refnumber

            kto, npo and kl_anchor: reference divergence diagnostic (batch z_ref for kto, mean log-ratio for npo, mean KL penalty for kl_anchor).

          • ref_diff_maxnumber≥ 0

            kto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.

      2. ForwardResult
        • type"forward"required

          "forward"

        • logprobsarray of Tensorrequired
          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • lossnumberrequirednullable
        • loss_sumnumberrequirednullable
        • weight_sumnumberrequirednullable
        • metricsTrainerLossMetricsrequirednullable
      3. OptimStepResult
        • type"optim_step"required

          "optim_step"

        • stepintegerrequired≥ 0
        • grad_normnumberrequirednullable
        • skippedbooleanrequired

          No gradients were pending: nothing changed.

        • lrnumber> 0

          The numeric learning rate applied (resolved when lr: "auto" was requested).

      4. SampleResult
        • type"sample"required

          "sample"

        • resultsarray of objectrequired
          4 child fields
          • prompt_tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • prompt_logprobsTensor

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • resetbooleanrequired

            A continue whose template rewrote history: prompt_tokens are a fresh render, not tokens plus a delta (the trajectory starts a new segment). False for other prompts.

          • samplesarray of TrainerSamplerequired
            7 child fields
            • tokensTensorrequired

              A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

              2 child fields
              • dtypeenumrequired

                "int32""float32"

              • b64stringrequired

                Matches ^[A-Za-z0-9+/]*={0,2}$

            • logprobsTensorrequired

              A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

              2 child fields
              • dtypeenumrequired

                "int32""float32"

              • b64stringrequired

                Matches ^[A-Za-z0-9+/]*={0,2}$

            • top_logprobsarray of array of TopLogprob

              Present when top_logprobs > 0: for each sampled token, up to K (token_id, logprob) pairs ordered highest logprob first.

            • textstringrequired
            • finish_reasonenumrequired

              stop: a stop token or string; length: max_tokens (or, on a continue, the room left in max_seq_len); context_full: a continue with no room left, no tokens.

              "stop""length""context_full"

            • messageSampledAssistantMessagerequired

              The sample parsed with the base's template (reasoning and OpenAI-style tool calls, arguments a JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays in content and parsed is false.

              4 child fields
              • role"assistant"required

                "assistant"

              • contentstringrequired
              • reasoning_contentstring
              • tool_callsarray of object
            • parsedbooleanrequired

              The reply parsed cleanly (no malformed tool call). False: message.content holds the raw text, which an environment gets as text.

      5. SaveStateResult
        • type"save_state"required

          "save_state"

        • checkpointobjectrequired
          5 child fields
          • idstringrequired
          • stepintegerrequired≥ 0
          • namestringnullable
          • expires_atstring (date-time)nullable
          • metadatamap of any
      6. ExportResult
        • type"export"required

          "export"

        • artifactArtifactrequired
          16 child fields
          • idstringrequired

            Artifact id: name@version.

          • workspace_idstringrequired
          • namestringrequired≤ 64 chars

            Artifact name, usually the run name.

            Matches ^[a-z0-9][a-z0-9._-]{0,63}$

          • versionstringrequired

            Version, YYYY-MM-DD-N: the release date and its sequence that day.

          • run_idstringrequirednullable

            The run that trained it; null for uploads and imports.

          • checkpoint_idstringrequirednullable

            The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

          • base_modelstringrequired

            The base model the weights apply to.

          • recipe_kindRecipeKindrequired

            "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

          • formatArtifactFormatrequired

            "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

          • sha256stringrequired

            SHA-256 of the bundle; downloads verify it.

            Matches ^[0-9a-f]{64}$

          • size_bytesintegerrequired≥ 0

            Bundle size in bytes.

          • manifestmap of anyrequired

            The bundle's manifest.json: format, base model, adapter and training settings.

          • provenanceArtifactProvenancerequired
            5 child fields
            • sourceenumrequired

              run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

              "run""trainer""upload""import"

            • run_idstringrequirednullable

              source=run: the run that trained it.

            • trainer_idstringrequirednullable

              source=trainer: the trainer that exported it.

            • uploaderstringrequirednullable

              source=upload: the API key (principal) that uploaded it.

            • uristringrequirednullable

              source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

          • eval_reportEvalReportrequirednullable
          • created_atstring (date-time)required

            When it was released.

          • console_urlstringnullable

            Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

      7. RenderResult
        • type"render"required

          "render"

        • dataarray of RenderedDatumrequired
          4 child fields
          • tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • weightsTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • truncatedbooleanrequired
          • mediaarray of MediaItem
            4 child fields
            • kindenumrequired

              "image""audio"

            • mimeenumrequired

              "image/png""image/jpeg""image/webp""audio/wav"

            • datastring≥ 4 chars

              Matches ^[A-Za-z0-9+/]+={0,2}$

            • media_idstring

              Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

              Matches ^med_[0-9a-f]{24}$

      8. SnapshotResult
        • type"snapshot"required

          "snapshot"

        • snapshotobjectrequired
          2 child fields
          • seqintegerrequired≥ 1
          • stepintegerrequired≥ 0
    • result_urlstringrequirednullable

      A result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.

    • errorTrainerOpErrorrequirednullable

      Why it failed: invalid_datum, invalid_continuation, trainer_lost (the worker died; ops after its last saved state are gone), trainer_closed, op_failed, result_expired, snapshot_released, deadline_exceeded, result_too_large.

    • usageTrainerUsagerequired
      4 child fields
      • tokensintegerrequired≥ 0
      • cost_usdnumberrequired≥ 0
      • prompt_tokensinteger≥ 0
      • sampled_tokensinteger≥ 0
    • compute_msintegerrequirednullable

      Worker compute time (a sample-lane op: its batch's, shared by the ops batched together). started_at is when the worker took the op, which may be before it ran (prefetch).

    • created_atstring (date-time)required
    • started_atstring (date-time)requirednullable
    • finished_atstring (date-time)requirednullable

Errors: 400 401 403 404 409 422 500 503

Request
cURL
curl -X POST "$GRADIATED_BASE_URL/v1/trainers/trn_3f9c0a1b2c3d4e5f60718293/ops/wait" \
  -H "Authorization: Bearer $GRADIATED_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "ids": [
      "op_3f9c0a1b2c3d4e5f60718293"
    ],
    "wait_s": 30
  }'
Response 200 OKGenerated from the schema
JSON
{
  "data": [
    {
      "id": "op_3f9c0a1b2c3d4e5f60718293",
      "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
      "seq": 1,
      "lane": "train",
      "snapshot_seq": 1,
      "request_key": "string",
      "type": "forward_backward",
      "status": "queued",
      "result": {
        "type": "forward_backward",
        "loss": 0,
        "loss_sum": 0,
        "weight_sum": 0,
        "metrics": {
          "tokens": 0,
          "trained_tokens": 0,
          "token_accuracy": 0,
          "truncated": 0,
          "kl_sample_train": 0,
          "kl_sample_train_v2": 0,
          "sample_train_max_diff": 0,
          "entropy": 0,
          "ratio_mean": 0,
          "ratio_max": 0,
          "clip_fraction": 0,
          "preference_accuracy": 0,
          "margin_mean": 0,
          "chosen_reward_mean": 0,
          "rejected_reward_mean": 0,
          "sft_loss_mean": 0,
          "or_loss_mean": 0,
          "kl_ref": 0,
          "ref_diff_max": 0
        }
      },
      "result_url": "string",
      "error": {
        "code": "string",
        "message": "…"
      },
      "usage": {
        "tokens": 0,
        "cost_usd": 0,
        "prompt_tokens": 0,
        "sampled_tokens": 0
      },
      "compute_ms": 0,
      "created_at": "2026-11-28T09:30:00.000Z",
      "started_at": "2026-11-28T09:30:00.000Z",
      "finished_at": "2026-11-28T09:30:00.000Z"
    }
  ]
}

List a trainer's pending and live snapshots#

GET/v1/trainers/{id}/snapshots

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 object Snapshots, oldest first.

1 fields
  • dataarray of Snapshotrequired
    7 child fields
    • trainer_idstringrequired
    • seqintegerrequired≥ 1

      The snapshot op's seq: its id within the trainer.

    • stepintegerrequirednullable

      The optimizer step it froze (null while pending).

    • statusSnapshotStatusrequired

      pending: its op has not run yet (samples queue and run once it has); live: frozen weights on the worker; released: gone (its queued samples failed snapshot_released).

      "pending""live""released"

    • created_atstring (date-time)required
    • last_sample_atstring (date-time)requirednullable
    • released_atstring (date-time)requirednullable

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
for snap in trainer.snapshots():
    print(snap.seq, snap.status, snap.step)
Response 200 OKGenerated from the schema
JSON
{
  "data": [
    {
      "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
      "seq": 1,
      "step": 0,
      "status": "pending",
      "created_at": "2026-11-28T09:30:00.000Z",
      "last_sample_at": "2026-11-28T09:30:00.000Z",
      "released_at": "2026-11-28T09:30:00.000Z"
    }
  ]
}

Release a snapshot (idempotent): its queued samples fail snapshot_released#

DELETE/v1/trainers/{id}/snapshots/{seq}

Path parameters

  • idstringrequired≤ 200 chars
  • seqintegerrequired1–2147483647

Returns

200 Snapshot The snapshot, released.

7 fields
  • trainer_idstringrequired
  • seqintegerrequired≥ 1

    The snapshot op's seq: its id within the trainer.

  • stepintegerrequirednullable

    The optimizer step it froze (null while pending).

  • statusSnapshotStatusrequired

    pending: its op has not run yet (samples queue and run once it has); live: frozen weights on the worker; released: gone (its queued samples failed snapshot_released).

    "pending""live""released"

  • created_atstring (date-time)required
  • last_sample_atstring (date-time)requirednullable
  • released_atstring (date-time)requirednullable

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
snap = trainer.snapshot()
snap.release()
Response 200 OKGenerated from the schema
JSON
{
  "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
  "seq": 1,
  "step": 0,
  "status": "pending",
  "created_at": "2026-11-28T09:30:00.000Z",
  "last_sample_at": "2026-11-28T09:30:00.000Z",
  "released_at": "2026-11-28T09:30:00.000Z"
}

Sample from a snapshot on the sample lane#

POST/v1/trainers/{id}/snapshots/{seq}/sample

No seq; runs between train ops.

Path parameters

  • idstringrequired≤ 200 chars
  • seqintegerrequired1–2147483647

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body SnapshotSampleRequest

  • promptsarray of SamplePromptrequired1–1024 items
  • num_samplesinteger1–64default 1
  • max_tokensintegerrequired1–32768
  • temperaturenumber0–2default 1
  • top_pnumber> 0≤ 1default 1
  • top_kintegernullable

    Keep only the top K tokens before sampling (omitted or null: disabled).

  • top_logprobsinteger0–20

    Number of highest-probability (token_id, logprob) pairs to return per generated token from the processed distribution (default 0: omitted).

  • prompt_logprobsboolean

    Return per-prompt-token logprobs under the active weights (float32 length len(prompt_tokens), index 0 is 0.0; default false).

  • stoparray of string or integer≤ 16 items

    Stop strings and token ids; they replace the base's stop tokens (the trainer's stop_token_ids). []: run to max_tokens. A stop token is kept in tokens.

  • seedinteger0–2147483647

    Reproducible sampling for the same request. On a snapshot, a seeded op runs alone (not batched with others).

  • streamboolean

    Emit incremental token deltas to GET /v1/trainers/{id}/ops/{op_id}/stream (SSE) while generating. Streaming snapshot samples run alone (never coalesced) for minimal time-to-first-token.

  • request_keystringrequired≤ 128 chars

    Makes the POST idempotent: a resend with the same key and body returns the op it created (200); the same key with another body is 409 request_key_conflict.

  • deadline_sinteger1–3600default 900

    A sample still queued this long after its POST fails deadline_exceeded, unrun and unbilled (a crashed client's turns don't run).

Returns

200 TrainerOp A resend: the op this request_key created.

202 TrainerOp Queued: the op (its future).

16 fields
  • idstringrequired

    op_ and 24 hex.

  • trainer_idstringrequired
  • seqintegerrequirednullable

    Its place in the train lane; null on the sample lane.

  • laneTrainerOpLanerequired

    train: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.

    "train""sample"

  • snapshot_seqintegerrequirednullable

    A snapshot sample: the snapshot it samples from.

  • request_keystringrequirednullable

    A snapshot sample's idempotency key.

  • typeTrainerOpTyperequired

    "forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"

  • statusTrainerOpStatusrequired

    "queued""running""done""failed"

  • resultTrainerOpResult

    An op's result once it is done (by type); absent while it is pending, and when it is large (then result_url).

    One of 8 shapes
    1. ForwardBackwardResult
      • type"forward_backward"required

        "forward_backward"

      • lossnumberrequired

        scale * loss_sum.

      • loss_sumnumberrequired

        sum(w * term) before scale.

      • weight_sumnumberrequired

        sum(w): the weights (or coefficients) the loss read.

      • metricsTrainerLossMetricsrequired

        Over the tokens or datums the loss reads. The RL fields come with importance_sampling, ppo, cispo, dro and stable_reinforce; preference and reference diagnostics come with simpo, orpo, kto, npo and kl_anchor.

        19 child fields
        • tokensintegerrequired≥ 0
        • trained_tokensintegerrequired≥ 0

          Tokens the loss reads (nonzero weight or coefficient).

        • token_accuracynumberrequired0–1
        • truncatedinteger≥ 0
        • kl_sample_trainnumber

          RL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).

        • kl_sample_train_v2number≥ 0

          RL losses: 0.5 * mean((sampling_logprob - logprob)^2).

        • sample_train_max_diffnumber≥ 0

          RL losses: max |sampling_logprob - logprob|.

        • entropynumber

          RL losses: mean token-level Shannon entropy (-sum(p * log p)) of the current policy over the trained tokens.

        • ratio_meannumber≥ 0
        • ratio_maxnumber≥ 0
        • clip_fractionnumber0–1

          ppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.

        • preference_accuracynumber0–1

          simpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.

        • margin_meannumber

          simpo and orpo: mean reward margin (beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).

        • chosen_reward_meannumber

          simpo and kto: mean implicit reward on chosen / desirable sequences.

        • rejected_reward_meannumber

          simpo and kto: mean implicit reward on rejected / undesirable sequences.

        • sft_loss_meannumber

          orpo and kl_anchor: mean SFT negative log-likelihood component.

        • or_loss_meannumber

          orpo: mean odds-ratio preference loss component.

        • kl_refnumber

          kto, npo and kl_anchor: reference divergence diagnostic (batch z_ref for kto, mean log-ratio for npo, mean KL penalty for kl_anchor).

        • ref_diff_maxnumber≥ 0

          kto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.

    2. ForwardResult
      • type"forward"required

        "forward"

      • logprobsarray of Tensorrequired
        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • lossnumberrequirednullable
      • loss_sumnumberrequirednullable
      • weight_sumnumberrequirednullable
      • metricsTrainerLossMetricsrequirednullable
    3. OptimStepResult
      • type"optim_step"required

        "optim_step"

      • stepintegerrequired≥ 0
      • grad_normnumberrequirednullable
      • skippedbooleanrequired

        No gradients were pending: nothing changed.

      • lrnumber> 0

        The numeric learning rate applied (resolved when lr: "auto" was requested).

    4. SampleResult
      • type"sample"required

        "sample"

      • resultsarray of objectrequired
        4 child fields
        • prompt_tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • prompt_logprobsTensor

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • resetbooleanrequired

          A continue whose template rewrote history: prompt_tokens are a fresh render, not tokens plus a delta (the trajectory starts a new segment). False for other prompts.

        • samplesarray of TrainerSamplerequired
          7 child fields
          • tokensTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • logprobsTensorrequired

            A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

            2 child fields
            • dtypeenumrequired

              "int32""float32"

            • b64stringrequired

              Matches ^[A-Za-z0-9+/]*={0,2}$

          • top_logprobsarray of array of TopLogprob

            Present when top_logprobs > 0: for each sampled token, up to K (token_id, logprob) pairs ordered highest logprob first.

          • textstringrequired
          • finish_reasonenumrequired

            stop: a stop token or string; length: max_tokens (or, on a continue, the room left in max_seq_len); context_full: a continue with no room left, no tokens.

            "stop""length""context_full"

          • messageSampledAssistantMessagerequired

            The sample parsed with the base's template (reasoning and OpenAI-style tool calls, arguments a JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays in content and parsed is false.

            4 child fields
            • role"assistant"required

              "assistant"

            • contentstringrequired
            • reasoning_contentstring
            • tool_callsarray of object
              3 child fields
              • idstringrequired
              • type"function"required

                "function"

              • functionobjectrequired
          • parsedbooleanrequired

            The reply parsed cleanly (no malformed tool call). False: message.content holds the raw text, which an environment gets as text.

    5. SaveStateResult
      • type"save_state"required

        "save_state"

      • checkpointobjectrequired
        5 child fields
        • idstringrequired
        • stepintegerrequired≥ 0
        • namestringnullable
        • expires_atstring (date-time)nullable
        • metadatamap of any
    6. ExportResult
      • type"export"required

        "export"

      • artifactArtifactrequired
        16 child fields
        • idstringrequired

          Artifact id: name@version.

        • workspace_idstringrequired
        • namestringrequired≤ 64 chars

          Artifact name, usually the run name.

          Matches ^[a-z0-9][a-z0-9._-]{0,63}$

        • versionstringrequired

          Version, YYYY-MM-DD-N: the release date and its sequence that day.

        • run_idstringrequirednullable

          The run that trained it; null for uploads and imports.

        • checkpoint_idstringrequirednullable

          The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

        • base_modelstringrequired

          The base model the weights apply to.

        • recipe_kindRecipeKindrequired

          "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

        • formatArtifactFormatrequired

          "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

        • sha256stringrequired

          SHA-256 of the bundle; downloads verify it.

          Matches ^[0-9a-f]{64}$

        • size_bytesintegerrequired≥ 0

          Bundle size in bytes.

        • manifestmap of anyrequired

          The bundle's manifest.json: format, base model, adapter and training settings.

        • provenanceArtifactProvenancerequired
          5 child fields
          • sourceenumrequired

            run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

            "run""trainer""upload""import"

          • run_idstringrequirednullable

            source=run: the run that trained it.

          • trainer_idstringrequirednullable

            source=trainer: the trainer that exported it.

          • uploaderstringrequirednullable

            source=upload: the API key (principal) that uploaded it.

          • uristringrequirednullable

            source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

        • eval_reportEvalReportrequirednullable
        • created_atstring (date-time)required

          When it was released.

        • console_urlstringnullable

          Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

    7. RenderResult
      • type"render"required

        "render"

      • dataarray of RenderedDatumrequired
        4 child fields
        • tokensTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • weightsTensorrequired

          A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

          2 child fields
          • dtypeenumrequired

            "int32""float32"

          • b64stringrequired

            Matches ^[A-Za-z0-9+/]*={0,2}$

        • truncatedbooleanrequired
        • mediaarray of MediaItem
          4 child fields
          • kindenumrequired

            "image""audio"

          • mimeenumrequired

            "image/png""image/jpeg""image/webp""audio/wav"

          • datastring≥ 4 chars

            Matches ^[A-Za-z0-9+/]+={0,2}$

          • media_idstring

            Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

            Matches ^med_[0-9a-f]{24}$

    8. SnapshotResult
      • type"snapshot"required

        "snapshot"

      • snapshotobjectrequired
        2 child fields
        • seqintegerrequired≥ 1
        • stepintegerrequired≥ 0
  • result_urlstringrequirednullable

    A result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.

  • errorTrainerOpErrorrequirednullable

    Why it failed: invalid_datum, invalid_continuation, trainer_lost (the worker died; ops after its last saved state are gone), trainer_closed, op_failed, result_expired, snapshot_released, deadline_exceeded, result_too_large.

  • usageTrainerUsagerequired
    4 child fields
    • tokensintegerrequired≥ 0
    • cost_usdnumberrequired≥ 0
    • prompt_tokensinteger≥ 0
    • sampled_tokensinteger≥ 0
  • compute_msintegerrequirednullable

    Worker compute time (a sample-lane op: its batch's, shared by the ops batched together). started_at is when the worker took the op, which may be before it ran (prefetch).

  • created_atstring (date-time)required
  • started_atstring (date-time)requirednullable
  • finished_atstring (date-time)requirednullable

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
with trainer.snapshot() as snap:
    out = snap.sample(
        [{"messages": [{"role": "user", "content": "What is 12 * 7?"}]}],
        max_tokens=128,
        request_key="ep-1-turn-0",
    ).result()
    print(out.results[0].samples[0].text)
Response 200 OKGenerated from the schema
JSON
{
  "id": "op_3f9c0a1b2c3d4e5f60718293",
  "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
  "seq": 1,
  "lane": "train",
  "snapshot_seq": 1,
  "request_key": "string",
  "type": "forward_backward",
  "status": "queued",
  "result": {
    "type": "forward_backward",
    "loss": 0,
    "loss_sum": 0,
    "weight_sum": 0,
    "metrics": {
      "tokens": 0,
      "trained_tokens": 0,
      "token_accuracy": 0,
      "truncated": 0,
      "kl_sample_train": 0,
      "kl_sample_train_v2": 0,
      "sample_train_max_diff": 0,
      "entropy": 0,
      "ratio_mean": 0,
      "ratio_max": 0,
      "clip_fraction": 0,
      "preference_accuracy": 0,
      "margin_mean": 0,
      "chosen_reward_mean": 0,
      "rejected_reward_mean": 0,
      "sft_loss_mean": 0,
      "or_loss_mean": 0,
      "kl_ref": 0,
      "ref_diff_max": 0
    }
  },
  "result_url": "string",
  "error": {
    "code": "string",
    "message": "…"
  },
  "usage": {
    "tokens": 0,
    "cost_usd": 0,
    "prompt_tokens": 0,
    "sampled_tokens": 0
  },
  "compute_ms": 0,
  "created_at": "2026-11-28T09:30:00.000Z",
  "started_at": "2026-11-28T09:30:00.000Z",
  "finished_at": "2026-11-28T09:30:00.000Z"
}

Mint a short-lived token scoped strictly to OpenAI/Anthropic sampling on this trainer#

POST/v1/trainers/{id}/endpoint-tokens

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body CreateTrainerEndpointTokenRequest

  • snapshot_seqinteger1–2147483647

    Optional snapshot seq to bind this token to. When set, the token can only sample from that snapshot.

  • ttl_sinteger60–86400default 3600

    Token lifetime in seconds (60..86400, default 3600). Automatically invalid once the trainer closes.

  • thinkingenumdefault "auto"

    Default thinking mode applied to OpenAI/Anthropic requests authenticated with this token.

    "auto""on""off"

  • preserve_thinkingbooleandefault false

    Default preserve_thinking flag applied to multi-turn continuations authenticated with this token.

Returns

201 TrainerEndpointTokenResponse Scoped endpoint token and OpenAI/Anthropic base URLs.

6 fields
  • tokenstringrequired

    Short-lived bearer / x-api-key token scoped strictly to OpenAI/Anthropic sampling on this trainer (and optional snapshot).

  • expires_atstring (date-time)required
  • trainer_idstringrequired
  • snapshot_seqintegerrequirednullable
  • openai_base_urlstringrequired

    OpenAI-compatible base URL (pass as OPENAI_BASE_URL; SDK appends /chat/completions).

  • anthropic_base_urlstringrequired

    Anthropic-compatible base URL (pass as ANTHROPIC_BASE_URL; SDK appends /v1/messages).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
ep = trainer.endpoint(ttl_s=3600, thinking="auto")
print(ep.openai_base_url, ep.anthropic_base_url, ep.expires_at)
Response 201 CreatedGenerated from the schema
JSON
{
  "token": "string",
  "expires_at": "2026-11-28T09:30:00.000Z",
  "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
  "snapshot_seq": 1,
  "openai_base_url": "string",
  "anthropic_base_url": "string"
}

List recorded token-aligned trajectories from this trainer's OpenAI/Anthropic endpoint#

GET/v1/trainers/{id}/sessions

Path parameters

  • idstringrequired≤ 200 chars

Query parameters

  • sessionstring≤ 200 chars

Returns

200 TrainerSessionsResponse Recorded session trajectories.

1 fields
  • dataarray of TrainerSessionTrajectoryrequired
    11 child fields
    • rollout_idstringrequired
    • session_idstringrequired
    • messagesarray of map of anyrequired
    • toolsarray of map of anynullable
    • segmentsarray of TrainerSessionSegmentrequired
      5 child fields
      • tokensTensorrequired

        A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • weightsTensorrequired

        A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • sampling_logprobsTensorrequired

        A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • turn_idsTensorrequired

        A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • mediaarray of MediaItem
        4 child fields
        • kindenumrequired

          "image""audio"

        • mimeenumrequired

          "image/png""image/jpeg""image/webp""audio/wav"

        • datastring≥ 4 chars

          Matches ^[A-Za-z0-9+/]+={0,2}$

        • media_idstring

          Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

          Matches ^med_[0-9a-f]{24}$

    • turnsintegerrequired≥ 0
    • finish_reasonstringrequired
    • policymap of anyrequired
    • samplingmap of anyrequired
    • usageobjectrequired
      3 child fields
      • prompt_tokensintegerrequired≥ 0
      • completion_tokensintegerrequired≥ 0
      • cost_usdnumberrequired≥ 0
    • metricsmap of numberrequired

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
trajs = trainer.trajectories()
print(len(trajs))
Response 200 OKGenerated from the schema
JSON
{
  "data": [
    {
      "rollout_id": "obj_3f9c0a1b2c3d4e5f60718293",
      "session_id": "obj_3f9c0a1b2c3d4e5f60718293",
      "messages": [
        {}
      ],
      "tools": [
        {}
      ],
      "segments": [
        {
          "tokens": {},
          "weights": {},
          "sampling_logprobs": {},
          "turn_ids": {},
          "media": []
        }
      ],
      "turns": 0,
      "finish_reason": "string",
      "policy": {},
      "sampling": {},
      "usage": {
        "prompt_tokens": 0,
        "completion_tokens": 0,
        "cost_usd": 0
      },
      "metrics": {}
    }
  ]
}

Clear recorded trajectories for all sessions (or one ?session=...) on a trainer#

DELETE/v1/trainers/{id}/sessions

Path parameters

  • idstringrequired≤ 200 chars

Query parameters

  • sessionstring≤ 200 chars

Returns

200 ClearTrainerSessionsResponse Cleared session count.

1 fields
  • clearedintegerrequired≥ 0

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
cleared = trainer.clear_sessions()
print(cleared)
Response 200 OKGenerated from the schema
JSON
{
  "cleared": 0
}

Get recorded token-aligned trajectories for one trainer session#

GET/v1/trainers/{id}/sessions/{session_id}/trajectories

Path parameters

  • idstringrequired≤ 200 chars
  • session_idstringrequired≤ 200 chars

Returns

200 TrainerSessionsResponse Trajectories recorded for this session.

1 fields
  • dataarray of TrainerSessionTrajectoryrequired
    11 child fields
    • rollout_idstringrequired
    • session_idstringrequired
    • messagesarray of map of anyrequired
    • toolsarray of map of anynullable
    • segmentsarray of TrainerSessionSegmentrequired
      5 child fields
      • tokensTensorrequired

        A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • weightsTensorrequired

        A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • sampling_logprobsTensorrequired

        A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • turn_idsTensorrequired

        A 1-D array: dtype (int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.

        2 child fields
        • dtypeenumrequired

          "int32""float32"

        • b64stringrequired

          Matches ^[A-Za-z0-9+/]*={0,2}$

      • mediaarray of MediaItem
        4 child fields
        • kindenumrequired

          "image""audio"

        • mimeenumrequired

          "image/png""image/jpeg""image/webp""audio/wav"

        • datastring≥ 4 chars

          Matches ^[A-Za-z0-9+/]+={0,2}$

        • media_idstring

          Content-addressed media upload id (med_... from POST /v1/media); mutually exclusive with data.

          Matches ^med_[0-9a-f]{24}$

    • turnsintegerrequired≥ 0
    • finish_reasonstringrequired
    • policymap of anyrequired
    • samplingmap of anyrequired
    • usageobjectrequired
      3 child fields
      • prompt_tokensintegerrequired≥ 0
      • completion_tokensintegerrequired≥ 0
      • cost_usdnumberrequired≥ 0
    • metricsmap of numberrequired

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
trajs = trainer.trajectories("ep-1")
print(len(trajs))
Response 200 OKGenerated from the schema
JSON
{
  "data": [
    {
      "rollout_id": "obj_3f9c0a1b2c3d4e5f60718293",
      "session_id": "obj_3f9c0a1b2c3d4e5f60718293",
      "messages": [
        {}
      ],
      "tools": [
        {}
      ],
      "segments": [
        {
          "tokens": {},
          "weights": {},
          "sampling_logprobs": {},
          "turn_ids": {},
          "media": []
        }
      ],
      "turns": 0,
      "finish_reason": "string",
      "policy": {},
      "sampling": {},
      "usage": {
        "prompt_tokens": 0,
        "completion_tokens": 0,
        "cost_usd": 0
      },
      "metrics": {}
    }
  ]
}

Clear recorded trajectories for one trainer session#

DELETE/v1/trainers/{id}/sessions/{session_id}

Path parameters

  • idstringrequired≤ 200 chars
  • session_idstringrequired≤ 200 chars

Returns

200 ClearTrainerSessionsResponse Cleared session count.

1 fields
  • clearedintegerrequired≥ 0

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
cleared = trainer.clear_sessions("ep-1")
print(cleared)
Response 200 OKGenerated from the schema
JSON
{
  "cleared": 0
}

Environments#

Register a versioned Harbor or sandbox environment bundle#

POST/v1/environments

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body CreateEnvironmentRequest

  • namestringrequired≤ 64 chars

    Environment name slug (unique per workspace with version).

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • versionstring≤ 64 chars

    Optional version tag; auto-increments v1, v2, ... when omitted.

    Matches ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$

  • formatEnvironmentFormat

    Environment bundle format: harbor (Harbor task or benchmark suite) or sandbox (Dockerfile/Compose workspace).

    "harbor""sandbox"

  • upload_idstring

    Staged .tar.gz bundle uploaded via POST /v1/uploads (purpose: "environment_bundle", max 64 MiB). Mutually exclusive with bundle_tar_gz_b64.

    Matches ^[0-9a-f]{64}$

  • bundle_tar_gz_b64string

    Base64-encoded gzipped tar archive for small inline uploads (max 2 MiB decoded). Prefer upload_id for larger bundles; mutually exclusive with upload_id.

  • default_specmap of any

    Optional default sandbox spec overrides (cpus, memory_mb, network, env, workdir, etc.).

Returns

201 Environment Created environment.

13 fields
  • idstringrequired

    Environment id (env_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • versionstringrequired
  • formatEnvironmentFormatrequired

    Environment bundle format: harbor (Harbor task or benchmark suite) or sandbox (Dockerfile/Compose workspace).

    "harbor""sandbox"

  • bundle_sha256stringrequired

    Matches ^[0-9a-f]{64}$

  • bundle_bytesintegerrequired≥ 0
  • task_countintegerrequired≥ 0
  • tasks_metaarray of EnvironmentTaskMetarequired
    6 child fields
    • namestringrequired
    • instruction_summarystringrequired
    • timeout_snumberrequired> 0
    • cpusnumberrequired> 0
    • memory_mbintegerrequired> 0
    • requires_composebooleanrequired
  • default_specmap of anyrequired
  • requires_composebooleanrequired
  • created_atstring (date-time)required
  • bundle_urlstringnullable

    Short-lived presigned bundle download URL (returned only when include_bundle_url=true).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
env = client.environments.push("./fix-bug", name="fix-bug", version="v1", format="harbor")
print(env.id, env.ref)
Response 201 CreatedGenerated from the schema
JSON
{
  "id": "env_3f9c0a1b2c3d4e5f60718293",
  "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
  "name": "support-prod",
  "version": "string",
  "format": "harbor",
  "bundle_sha256": "string",
  "bundle_bytes": 0,
  "task_count": 0,
  "tasks_meta": [
    {
      "name": "support-prod",
      "instruction_summary": "string",
      "timeout_s": 1,
      "cpus": 1,
      "memory_mb": 1,
      "requires_compose": false
    }
  ],
  "default_spec": {},
  "requires_compose": false,
  "created_at": "2026-11-28T09:30:00.000Z",
  "bundle_url": "string"
}

List registered environments#

GET/v1/environments

Newest first.

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • namestring≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • qstring≤ 200 chars

    Only items whose name contains this text (any case), or whose id is exactly this.

Returns

200 object Environments.

2 fields
  • dataarray of Environmentrequired
    13 child fields
    • idstringrequired

      Environment id (env_ and 24 hex characters).

    • workspace_idstringrequired
    • namestringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • versionstringrequired
    • formatEnvironmentFormatrequired

      Environment bundle format: harbor (Harbor task or benchmark suite) or sandbox (Dockerfile/Compose workspace).

      "harbor""sandbox"

    • bundle_sha256stringrequired

      Matches ^[0-9a-f]{64}$

    • bundle_bytesintegerrequired≥ 0
    • task_countintegerrequired≥ 0
    • tasks_metaarray of EnvironmentTaskMetarequired
      6 child fields
      • namestringrequired
      • instruction_summarystringrequired
      • timeout_snumberrequired> 0
      • cpusnumberrequired> 0
      • memory_mbintegerrequired> 0
      • requires_composebooleanrequired
    • default_specmap of anyrequired
    • requires_composebooleanrequired
    • created_atstring (date-time)required
    • bundle_urlstringnullable

      Short-lived presigned bundle download URL (returned only when include_bundle_url=true).

  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for env in client.environments.list():
    print(env.id, env.ref, env.task_count)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "data": [],
  "next_cursor": null
}

Get an environment by id (`env_...`) or `name@version` / `name@latest`#

GET/v1/environments/{id}

Path parameters

  • idstringrequired≤ 200 chars

Query parameters

  • include_bundle_urlboolean

    When true, include a short-lived presigned S3 download URL (bundle_url) for the .tar.gz bundle.

Returns

200 Environment Environment metadata.

13 fields
  • idstringrequired

    Environment id (env_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • versionstringrequired
  • formatEnvironmentFormatrequired

    Environment bundle format: harbor (Harbor task or benchmark suite) or sandbox (Dockerfile/Compose workspace).

    "harbor""sandbox"

  • bundle_sha256stringrequired

    Matches ^[0-9a-f]{64}$

  • bundle_bytesintegerrequired≥ 0
  • task_countintegerrequired≥ 0
  • tasks_metaarray of EnvironmentTaskMetarequired
    6 child fields
    • namestringrequired
    • instruction_summarystringrequired
    • timeout_snumberrequired> 0
    • cpusnumberrequired> 0
    • memory_mbintegerrequired> 0
    • requires_composebooleanrequired
  • default_specmap of anyrequired
  • requires_composebooleanrequired
  • created_atstring (date-time)required
  • bundle_urlstringnullable

    Short-lived presigned bundle download URL (returned only when include_bundle_url=true).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
env = client.environments.get("env_3f9c0a1b2c3d4e5f60718293")
print(env.ref, env.format, env.task_count)
Response 200 OKGenerated from the schema
JSON
{
  "id": "env_3f9c0a1b2c3d4e5f60718293",
  "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
  "name": "support-prod",
  "version": "string",
  "format": "harbor",
  "bundle_sha256": "string",
  "bundle_bytes": 0,
  "task_count": 0,
  "tasks_meta": [
    {
      "name": "support-prod",
      "instruction_summary": "string",
      "timeout_s": 1,
      "cpus": 1,
      "memory_mb": 1,
      "requires_compose": false
    }
  ],
  "default_spec": {},
  "requires_compose": false,
  "created_at": "2026-11-28T09:30:00.000Z",
  "bundle_url": "string"
}

Soft-delete a registered environment#

DELETE/v1/environments/{id}

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 DeleteEnvironmentResponse Deleted environment.

2 fields
  • idstringrequired
  • deletedbooleanrequired

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
client.environments.delete("env_3f9c0a1b2c3d4e5f60718293")
Response 200 OKGenerated from the schema
JSON
{
  "id": "obj_3f9c0a1b2c3d4e5f60718293",
  "deleted": false
}

Media#

Upload a content-addressed image or WAV audio blob for multimodal trainer ops#

POST/v1/media

Idempotent per workspace by SHA-256. Accepts JSON ({ kind, mime, data }) or raw binary bytes with Content-Type: image/png, image/jpeg, image/webp, or audio/wav. Reference the returned id as grad://media/<id> in image_url.url or media_id in input_audio / MediaItem.

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body UploadMediaRequest

  • kindMediaKindrequired

    "image""audio"

  • mimeMediaMimerequired

    "image/png""image/jpeg""image/webp""audio/wav"

  • datastringrequired≥ 4 chars

    Matches ^[A-Za-z0-9+/]+={0,2}$

Returns

201 MediaObject Uploaded (or existing) media.

6 fields
  • idstringrequired

    med_ and 24 hex.

    Matches ^med_[0-9a-f]{24}$

  • kindMediaKindrequired

    "image""audio"

  • mimeMediaMimerequired

    "image/png""image/jpeg""image/webp""audio/wav"

  • size_bytesintegerrequired≥ 1
  • sha256stringrequired

    Matches ^[0-9a-f]{64}$

  • created_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 503

Request
Python
import base64
from grad import Grad

client = Grad()
raw = base64.b64decode(
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
)
media = client.media.upload(raw, mime="image/png")
print(media.id)
Response 201 CreatedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "med_586752718400c4c6dccc2db3",
  "kind": "image",
  "mime": "image/png",
  "size_bytes": 68,
  "sha256": "431ced6916a2a21a156e38701afe55bbd7f88969fbbfc56d7fe099d47f265460",
  "created_at": "2026-12-02T15:49:00.022Z"
}

Get metadata for an uploaded media blob#

GET/v1/media/{id}

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 MediaObject Media metadata.

6 fields
  • idstringrequired

    med_ and 24 hex.

    Matches ^med_[0-9a-f]{24}$

  • kindMediaKindrequired

    "image""audio"

  • mimeMediaMimerequired

    "image/png""image/jpeg""image/webp""audio/wav"

  • size_bytesintegerrequired≥ 1
  • sha256stringrequired

    Matches ^[0-9a-f]{64}$

  • created_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
media = client.media.get("med_3f9c0a1b2c3d4e5f60718293")
print(media.mime, media.size_bytes)
Response 200 OKGenerated from the schema
JSON
{
  "id": "med_3f9c0a1b2c3d4e5f60718293",
  "kind": "image",
  "mime": "image/png",
  "size_bytes": 1,
  "sha256": "9f2c4e1ab0d3c5e7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c9d1e3f5a7b9c1d3e5",
  "created_at": "2026-11-28T09:30:00.000Z"
}

Checkpoints#

List unexpired checkpoints of a run#

GET/v1/runs/{id}/checkpoints

Best and final never expire.

Path parameters

  • idstringrequired≤ 200 chars

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars

Returns

200 object Checkpoints by step.

2 fields
  • dataarray of Checkpointrequired
    17 child fields
    • idstringrequired

      Checkpoint id (ckpt_ and 24 hex characters).

    • workspace_idstringrequired
    • run_idstringrequirednullable

      The run that saved it (null for a trainer's).

    • trainer_idstringrequirednullable

      The trainer that saved it (a save_state, autosave, park or close); null for a run's.

    • namestringnullable

      Optional human-readable label passed to trainer.save_state(name=...).

    • attemptintegerrequired≥ 1

      The attempt that saved it.

    • stepintegerrequired≥ 0

      Optimizer step it was saved at.

    • eval_scorenumberrequirednullable

      Held-out score at this step; null when it wasn't evaluated.

    • formatCheckpointFormatrequirednullable

      Artifact format when this checkpoint is exportable (promotable); trainer_state for an interactive trainer's optimizer-bearing saved state (export weights via trainer.export()), or null for training state only.

    • sha256stringrequired

      SHA-256 of the checkpoint bundle.

      Matches ^[0-9a-f]{64}$

    • size_bytesintegerrequired≥ 0

      Bundle size in bytes.

    • metadatamap of anyrequired
    • bestbooleanrequired

      True for the checkpoint select="best" picks; it never expires.

    • finalbooleanrequired

      True for the run's last checkpoint; it never expires.

    • expires_atstring (date-time)requirednullable

      When it expires (after checkpoint_ttl_days, 30 by default); null for checkpoints that never expire, such as the best and final.

    • created_atstring (date-time)required
    • console_urlstringnullable

      Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for checkpoint in client.runs.checkpoints("run_3f9c0a1b2c3d4e5f60718293"):
    print(checkpoint.id, checkpoint.step, checkpoint.eval_score)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "data": [
    {
      "id": "ckpt_066d90a41b4c935f305b88d3",
      "workspace_id": "ws_e2e",
      "run_id": "run_ed1c235f0c631d8f209e22a5",
      "trainer_id": null,
      "name": null,
      "attempt": 1,
      "step": 1,
      "eval_score": null,
      "format": "reference",
      "base_model": "qwen/qwen3-8b",
      "sha256": "a53f5b288340a261253b968d4a0252a8200e51ee95a5087124af049cd1f2b480",
      "size_bytes": 10263,
      "metadata": {
        "lr": 0.000125,
        "seed": 42,
        "step": 1,
        "select": "best",
        "backend": "reference",
        "manifest": {
          "lr": 0.000125,
          "seed": 42,
          "format": "reference",
          "select": "best",
          "backend": "reference",
          "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
          "base_model": "qwen/qwen3-8b",
          "deployable": false,
          "recipe_kind": "sft",
          "rule_version": "auto@2",
          "base_artifact": null,
          "base_model_repo": null,
          "checkpoint_step": 1,
          "base_model_revision": null
        },
        "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
        "base_model": "qwen/qwen3-8b",
        "deployable": false,
        "metric_mode": "min",
        "metric_name": "eval_loss",
        "recipe_kind": "sft",
        "eval_metrics": null,
        "rule_version": "auto@2",
        "tokens_total": 21,
        "base_artifact": null,
        "upload_seconds": 0.01,
        "base_model_repo": null,
        "base_model_revision": null
      },
      "best": false,
      "final": true,
      "expires_at": null,
      "created_at": "2026-12-02T15:49:00.146Z"
    }
  ],
  "next_cursor": null
}

Get an active checkpoint by id#

GET/v1/checkpoints/{id}

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 Checkpoint Checkpoint.

17 fields
  • idstringrequired

    Checkpoint id (ckpt_ and 24 hex characters).

  • workspace_idstringrequired
  • run_idstringrequirednullable

    The run that saved it (null for a trainer's).

  • trainer_idstringrequirednullable

    The trainer that saved it (a save_state, autosave, park or close); null for a run's.

  • namestringnullable

    Optional human-readable label passed to trainer.save_state(name=...).

  • attemptintegerrequired≥ 1

    The attempt that saved it.

  • stepintegerrequired≥ 0

    Optimizer step it was saved at.

  • eval_scorenumberrequirednullable

    Held-out score at this step; null when it wasn't evaluated.

  • formatCheckpointFormatrequirednullable

    Artifact format when this checkpoint is exportable (promotable); trainer_state for an interactive trainer's optimizer-bearing saved state (export weights via trainer.export()), or null for training state only.

  • sha256stringrequired

    SHA-256 of the checkpoint bundle.

    Matches ^[0-9a-f]{64}$

  • size_bytesintegerrequired≥ 0

    Bundle size in bytes.

  • metadatamap of anyrequired
  • bestbooleanrequired

    True for the checkpoint select="best" picks; it never expires.

  • finalbooleanrequired

    True for the run's last checkpoint; it never expires.

  • expires_atstring (date-time)requirednullable

    When it expires (after checkpoint_ttl_days, 30 by default); null for checkpoints that never expire, such as the best and final.

  • created_atstring (date-time)required
  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
checkpoint = client.checkpoints.get("ckpt_3f9c0a1b2c3d4e5f60718293")
print(checkpoint.id, checkpoint.step, checkpoint.eval_score)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "ckpt_066d90a41b4c935f305b88d3",
  "workspace_id": "ws_e2e",
  "run_id": "run_ed1c235f0c631d8f209e22a5",
  "trainer_id": null,
  "name": null,
  "attempt": 1,
  "step": 1,
  "eval_score": null,
  "format": "reference",
  "base_model": "qwen/qwen3-8b",
  "sha256": "a53f5b288340a261253b968d4a0252a8200e51ee95a5087124af049cd1f2b480",
  "size_bytes": 10263,
  "metadata": {
    "lr": 0.000125,
    "seed": 42,
    "step": 1,
    "select": "best",
    "backend": "reference",
    "manifest": {
      "lr": 0.000125,
      "seed": 42,
      "format": "reference",
      "select": "best",
      "backend": "reference",
      "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
      "base_model": "qwen/qwen3-8b",
      "deployable": false,
      "recipe_kind": "sft",
      "rule_version": "auto@2",
      "base_artifact": null,
      "base_model_repo": null,
      "checkpoint_step": 1,
      "base_model_revision": null
    },
    "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
    "base_model": "qwen/qwen3-8b",
    "deployable": false,
    "metric_mode": "min",
    "metric_name": "eval_loss",
    "recipe_kind": "sft",
    "eval_metrics": null,
    "rule_version": "auto@2",
    "tokens_total": 21,
    "base_artifact": null,
    "upload_seconds": 0.01,
    "base_model_repo": null,
    "base_model_revision": null
  },
  "best": false,
  "final": true,
  "expires_at": null,
  "created_at": "2026-12-02T15:49:00.146Z"
}

Update an active checkpoint's TTL and/or user metadata#

PATCH/v1/checkpoints/{id}

Path parameters

  • idstringrequired≤ 200 chars

Body UpdateCheckpointRequest

  • ttl_sintegernullable

    New TTL in seconds (300 to 7776000) from now, or null to make the checkpoint permanent (never expires).

  • metadatamap of any

    Replacement user metadata JSON object (at most 16 KiB serialized UTF-8).

Returns

200 Checkpoint Updated checkpoint.

17 fields
  • idstringrequired

    Checkpoint id (ckpt_ and 24 hex characters).

  • workspace_idstringrequired
  • run_idstringrequirednullable

    The run that saved it (null for a trainer's).

  • trainer_idstringrequirednullable

    The trainer that saved it (a save_state, autosave, park or close); null for a run's.

  • namestringnullable

    Optional human-readable label passed to trainer.save_state(name=...).

  • attemptintegerrequired≥ 1

    The attempt that saved it.

  • stepintegerrequired≥ 0

    Optimizer step it was saved at.

  • eval_scorenumberrequirednullable

    Held-out score at this step; null when it wasn't evaluated.

  • formatCheckpointFormatrequirednullable

    Artifact format when this checkpoint is exportable (promotable); trainer_state for an interactive trainer's optimizer-bearing saved state (export weights via trainer.export()), or null for training state only.

  • sha256stringrequired

    SHA-256 of the checkpoint bundle.

    Matches ^[0-9a-f]{64}$

  • size_bytesintegerrequired≥ 0

    Bundle size in bytes.

  • metadatamap of anyrequired
  • bestbooleanrequired

    True for the checkpoint select="best" picks; it never expires.

  • finalbooleanrequired

    True for the run's last checkpoint; it never expires.

  • expires_atstring (date-time)requirednullable

    When it expires (after checkpoint_ttl_days, 30 by default); null for checkpoints that never expire, such as the best and final.

  • created_atstring (date-time)required
  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
checkpoint = client.checkpoints.update(
    "ckpt_3f9c0a1b2c3d4e5f60718293",
    ttl_s=86400,
    metadata={"stage": "eval-pass"},
)
print(checkpoint.expires_at)
Response 200 OKGenerated from the schema
JSON
{
  "id": "ckpt_3f9c0a1b2c3d4e5f60718293",
  "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
  "run_id": "run_3f9c0a1b2c3d4e5f60718293",
  "trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
  "name": "support-prod",
  "attempt": 1,
  "step": 0,
  "eval_score": 0,
  "format": "peft_lora",
  "sha256": "9f2c4e1ab0d3c5e7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c9d1e3f5a7b9c1d3e5",
  "size_bytes": 0,
  "metadata": {},
  "best": false,
  "final": false,
  "expires_at": "2026-11-28T09:30:00.000Z",
  "created_at": "2026-11-28T09:30:00.000Z",
  "console_url": "string"
}

Release an exportable checkpoint as a named, versioned artifact#

POST/v1/checkpoints/{id}/promote

Promoting it again under the same name returns that release.

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body PromoteCheckpointRequest

  • namestring≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Returns

201 Artifact Promoted artifact.

16 fields
  • idstringrequired

    Artifact id: name@version.

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Artifact name, usually the run name.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • versionstringrequired

    Version, YYYY-MM-DD-N: the release date and its sequence that day.

  • run_idstringrequirednullable

    The run that trained it; null for uploads and imports.

  • checkpoint_idstringrequirednullable

    The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

  • base_modelstringrequired

    The base model the weights apply to.

  • recipe_kindRecipeKindrequired

    "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

  • formatArtifactFormatrequired

    "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

  • sha256stringrequired

    SHA-256 of the bundle; downloads verify it.

    Matches ^[0-9a-f]{64}$

  • size_bytesintegerrequired≥ 0

    Bundle size in bytes.

  • manifestmap of anyrequired

    The bundle's manifest.json: format, base model, adapter and training settings.

  • provenanceArtifactProvenancerequired
    5 child fields
    • sourceenumrequired

      run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

      "run""trainer""upload""import"

    • run_idstringrequirednullable

      source=run: the run that trained it.

    • trainer_idstringrequirednullable

      source=trainer: the trainer that exported it.

    • uploaderstringrequirednullable

      source=upload: the API key (principal) that uploaded it.

    • uristringrequirednullable

      source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

  • eval_reportEvalReportrequirednullable
  • created_atstring (date-time)required

    When it was released.

  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
artifact = client.checkpoints.promote("ckpt_3f9c0a1b2c3d4e5f60718293", name="support-sft-step-400")
print(artifact.id)
Response 201 CreatedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "support-sft-step-400@2026-12-02-1",
  "workspace_id": "ws_e2e",
  "name": "support-sft-step-400",
  "version": "2026-12-02-1",
  "run_id": "run_ed1c235f0c631d8f209e22a5",
  "checkpoint_id": "ckpt_066d90a41b4c935f305b88d3",
  "base_model": "qwen/qwen3-8b",
  "recipe_kind": "sft",
  "format": "reference",
  "sha256": "a53f5b288340a261253b968d4a0252a8200e51ee95a5087124af049cd1f2b480",
  "size_bytes": 10263,
  "manifest": {
    "lr": 0.000125,
    "seed": 42,
    "step": 1,
    "run_id": "run_ed1c235f0c631d8f209e22a5",
    "schema": "grad.artifact/1",
    "select": "best",
    "attempt": 1,
    "backend": "reference",
    "manifest": {
      "lr": 0.000125,
      "seed": 42,
      "format": "reference",
      "select": "best",
      "backend": "reference",
      "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
      "base_model": "qwen/qwen3-8b",
      "deployable": false,
      "recipe_kind": "sft",
      "rule_version": "auto@2",
      "base_artifact": null,
      "base_model_repo": null,
      "checkpoint_step": 1,
      "base_model_revision": null
    },
    "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
    "base_model": "qwen/qwen3-8b",
    "deployable": false,
    "provenance": {
      "run_id": "run_ed1c235f0c631d8f209e22a5",
      "source": "run"
    },
    "metric_mode": "min",
    "metric_name": "eval_loss",
    "recipe_kind": "sft",
    "eval_metrics": null,
    "rule_version": "auto@2",
    "tokens_total": 21,
    "base_artifact": null,
    "upload_seconds": 0.01,
    "base_model_repo": null,
    "resolved_config": {
      "lr": 0.000125,
      "name": "support-sft",
      "model": "qwen/qwen3-8b",
      "split": {
        "seed": 42,
        "strategy": "by_session",
        "eval_records": 0,
        "eval_fraction": 0.1,
        "train_records": 1
      },
      "epochs": 1,
      "select": "best",
      "warmup": 0.03,
      "adapter": {
        "kind": "lora",
        "rank": 32,
        "alpha": 32,
        "merge_on_export": false,
        "train_multimodal_projector": false
      },
      "dataset": "support-prod",
      "schedule": "linear",
      "thinking": "auto",
      "train_on": "last",
      "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
      "optimizer": {
        "kind": "adamw",
        "betas": [
          0.9,
          0.95
        ],
        "grad_clip": 1,
        "weight_decay": 0
      },
      "reduction": "per_example",
      "batch_size": 8,
      "recipe_kind": "sft",
      "rule_version": "auto@2",
      "base_artifact": null,
      "label_eval_id": null,
      "recipe_params": {},
      "dataset_version": 1,
      "eval_every_steps": 1,
      "preserve_thinking": false,
      "template_revision": "qwen3@3",
      "checkpoint_ttl_days": 30,
      "checkpoint_every_steps": 1
    },
    "base_model_revision": null,
    "promoted_from_checkpoint": "ckpt_066d90a41b4c935f305b88d3"
  },
  "provenance": {
    "source": "run",
    "run_id": "run_ed1c235f0c631d8f209e22a5",
    "trainer_id": null,
    "uploader": null,
    "uri": null
  },
  "eval_report": null,
  "created_at": "2026-12-02T15:49:01.130Z"
}

Artifacts#

List immutable artifacts#

GET/v1/artifacts

Newest first.

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • namestring≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • qstring≤ 200 chars

    Only items whose name contains this text (any case), or whose id is exactly this.

Returns

200 object Artifacts.

2 fields
  • dataarray of Artifactrequired
    16 child fields
    • idstringrequired

      Artifact id: name@version.

    • workspace_idstringrequired
    • namestringrequired≤ 64 chars

      Artifact name, usually the run name.

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • versionstringrequired

      Version, YYYY-MM-DD-N: the release date and its sequence that day.

    • run_idstringrequirednullable

      The run that trained it; null for uploads and imports.

    • checkpoint_idstringrequirednullable

      The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

    • base_modelstringrequired

      The base model the weights apply to.

    • recipe_kindRecipeKindrequired

      "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

    • formatArtifactFormatrequired

      "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

    • sha256stringrequired

      SHA-256 of the bundle; downloads verify it.

      Matches ^[0-9a-f]{64}$

    • size_bytesintegerrequired≥ 0

      Bundle size in bytes.

    • manifestmap of anyrequired

      The bundle's manifest.json: format, base model, adapter and training settings.

    • provenanceArtifactProvenancerequired
      5 child fields
      • sourceenumrequired

        run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

        "run""trainer""upload""import"

      • run_idstringrequirednullable

        source=run: the run that trained it.

      • trainer_idstringrequirednullable

        source=trainer: the trainer that exported it.

      • uploaderstringrequirednullable

        source=upload: the API key (principal) that uploaded it.

      • uristringrequirednullable

        source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

    • eval_reportEvalReportrequirednullable
    • created_atstring (date-time)required

      When it was released.

    • console_urlstringnullable

      Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for artifact in client.artifacts.list(search="support"):
    print(artifact.id, artifact.base_model)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "data": [
    {
      "id": "support-sft-step-400@2026-12-02-1",
      "workspace_id": "ws_e2e",
      "name": "support-sft-step-400",
      "version": "2026-12-02-1",
      "run_id": "run_ed1c235f0c631d8f209e22a5",
      "checkpoint_id": "ckpt_066d90a41b4c935f305b88d3",
      "base_model": "qwen/qwen3-8b",
      "recipe_kind": "sft",
      "format": "reference",
      "sha256": "a53f5b288340a261253b968d4a0252a8200e51ee95a5087124af049cd1f2b480",
      "size_bytes": 10263,
      "manifest": {
        "lr": 0.000125,
        "seed": 42,
        "step": 1,
        "run_id": "run_ed1c235f0c631d8f209e22a5",
        "schema": "grad.artifact/1",
        "select": "best",
        "attempt": 1,
        "backend": "reference",
        "manifest": {
          "lr": 0.000125,
          "seed": 42,
          "format": "reference",
          "select": "best",
          "backend": "reference",
          "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
          "base_model": "qwen/qwen3-8b",
          "deployable": false,
          "recipe_kind": "sft",
          "rule_version": "auto@2",
          "base_artifact": null,
          "base_model_repo": null,
          "checkpoint_step": 1,
          "base_model_revision": null
        },
        "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
        "base_model": "qwen/qwen3-8b",
        "deployable": false,
        "provenance": {
          "run_id": "run_ed1c235f0c631d8f209e22a5",
          "source": "run"
        },
        "metric_mode": "min",
        "metric_name": "eval_loss",
        "recipe_kind": "sft",
        "eval_metrics": null,
        "rule_version": "auto@2",
        "tokens_total": 21,
        "base_artifact": null,
        "upload_seconds": 0.01,
        "base_model_repo": null,
        "resolved_config": {
          "lr": 0.000125,
          "name": "support-sft",
          "model": "qwen/qwen3-8b",
          "split": {
            "seed": 42,
            "strategy": "by_session",
            "eval_records": 0,
            "eval_fraction": 0.1,
            "train_records": 1
          },
          "epochs": 1,
          "select": "best",
          "warmup": 0.03,
          "adapter": {
            "kind": "lora",
            "rank": 32,
            "alpha": 32,
            "merge_on_export": false,
            "train_multimodal_projector": false
          },
          "dataset": "support-prod",
          "schedule": "linear",
          "thinking": "auto",
          "train_on": "last",
          "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
          "optimizer": {
            "kind": "adamw",
            "betas": [
              0.9,
              0.95
            ],
            "grad_clip": 1,
            "weight_decay": 0
          },
          "reduction": "per_example",
          "batch_size": 8,
          "recipe_kind": "sft",
          "rule_version": "auto@2",
          "base_artifact": null,
          "label_eval_id": null,
          "recipe_params": {},
          "dataset_version": 1,
          "eval_every_steps": 1,
          "preserve_thinking": false,
          "template_revision": "qwen3@3",
          "checkpoint_ttl_days": 30,
          "checkpoint_every_steps": 1
        },
        "base_model_revision": null,
        "promoted_from_checkpoint": "ckpt_066d90a41b4c935f305b88d3"
      },
      "provenance": {
        "source": "run",
        "run_id": "run_ed1c235f0c631d8f209e22a5",
        "trainer_id": null,
        "uploader": null,
        "uri": null
      },
      "eval_report": null,
      "created_at": "2026-12-02T15:49:01.130Z"
    },
    {
      "id": "support-sft@2026-12-02-1",
      "workspace_id": "ws_e2e",
      "name": "support-sft",
      "version": "2026-12-02-1",
      "run_id": "run_ed1c235f0c631d8f209e22a5",
      "checkpoint_id": null,
      "base_model": "qwen/qwen3-8b",
      "recipe_kind": "sft",
      "format": "reference",
      "sha256": "144d0e25503494bfce90a8919a295505ac2759b0ae331e45ea16fade495c137c",
      "size_bytes": 10263,
      "manifest": {
        "lr": 0.000125,
        "kind": "final",
        "seed": 42,
        "files": {
          "reference_model.json": "59abd7749fec876cab4e168ea5a73ba432cbd5b568a7c8070258ec7f945b454b"
        },
        "format": "reference",
        "run_id": "run_ed1c235f0c631d8f209e22a5",
        "schema": "grad.artifact/1",
        "select": "last",
        "status": "completed",
        "attempt": 1,
        "backend": "reference",
        "dataset": "support-prod",
        "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
        "base_model": "qwen/qwen3-8b",
        "created_by": {
          "name": "grad-trainer",
          "version": "0.2.0-alpha.15"
        },
        "deployable": false,
        "provenance": {
          "run_id": "run_ed1c235f0c631d8f209e22a5",
          "source": "run"
        },
        "recipe_kind": "sft",
        "total_steps": 1,
        "rule_version": "auto@2",
        "tokens_total": 21,
        "base_artifact": null,
        "selected_step": 1,
        "format_version": 2,
        "base_model_repo": null,
        "dataset_version": 1,
        "resolved_config": {
          "lr": 0.000125,
          "name": "support-sft",
          "model": "qwen/qwen3-8b",
          "split": {
            "seed": 42,
            "strategy": "by_session",
            "eval_records": 0,
            "eval_fraction": 0.1,
            "train_records": 1
          },
          "epochs": 1,
          "select": "best",
          "warmup": 0.03,
          "adapter": {
            "kind": "lora",
            "rank": 32,
            "alpha": 32,
            "merge_on_export": false,
            "train_multimodal_projector": false
          },
          "dataset": "support-prod",
          "schedule": "linear",
          "thinking": "auto",
          "train_on": "last",
          "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
          "optimizer": {
            "kind": "adamw",
            "betas": [
              0.9,
              0.95
            ],
            "grad_clip": 1,
            "weight_decay": 0
          },
          "reduction": "per_example",
          "batch_size": 8,
          "recipe_kind": "sft",
          "rule_version": "auto@2",
          "base_artifact": null,
          "label_eval_id": null,
          "recipe_params": {},
          "dataset_version": 1,
          "eval_every_steps": 1,
          "preserve_thinking": false,
          "template_revision": "qwen3@3",
          "checkpoint_ttl_days": 30,
          "checkpoint_every_steps": 1
        },
        "steps_completed": 1,
        "eval_report_sha256": "782d3768b9a29b35b624e5fb6e013ad89598c2cd770421c0a5b7db8be230d56c",
        "base_model_revision": null
      },
      "provenance": {
        "source": "run",
        "run_id": "run_ed1c235f0c631d8f209e22a5",
        "trainer_id": null,
        "uploader": null,
        "uri": null
      },
      "eval_report": {
        "warnings": [
          "Reference test backend: the base model was not trained; the artifact is not deployable.",
          "No held-out examples: eval metrics are null and select='last' was used."
        ],
        "best_step": null,
        "eval_loss": null,
        "final_step": 1,
        "metric_mode": "min",
        "metric_name": "eval_loss",
        "eval_records": 0,
        "eval_examples": 0,
        "selected_step": 1,
        "train_records": 1,
        "train_examples": 1,
        "reference_backend": true
      },
      "created_at": "2026-12-02T15:49:00.199Z"
    }
  ],
  "next_cursor": null
}

Get an artifact by id or name@latest#

GET/v1/artifacts/{id}

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 Artifact Artifact metadata.

16 fields
  • idstringrequired

    Artifact id: name@version.

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Artifact name, usually the run name.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • versionstringrequired

    Version, YYYY-MM-DD-N: the release date and its sequence that day.

  • run_idstringrequirednullable

    The run that trained it; null for uploads and imports.

  • checkpoint_idstringrequirednullable

    The checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.

  • base_modelstringrequired

    The base model the weights apply to.

  • recipe_kindRecipeKindrequired

    "sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"

  • formatArtifactFormatrequired

    "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

  • sha256stringrequired

    SHA-256 of the bundle; downloads verify it.

    Matches ^[0-9a-f]{64}$

  • size_bytesintegerrequired≥ 0

    Bundle size in bytes.

  • manifestmap of anyrequired

    The bundle's manifest.json: format, base model, adapter and training settings.

  • provenanceArtifactProvenancerequired
    5 child fields
    • sourceenumrequired

      run: trained by a grad run; trainer: exported by a trainer (trainer.export); upload: files uploaded with grad artifacts upload; import: pulled from the Hugging Face Hub with grad artifacts import.

      "run""trainer""upload""import"

    • run_idstringrequirednullable

      source=run: the run that trained it.

    • trainer_idstringrequirednullable

      source=trainer: the trainer that exported it.

    • uploaderstringrequirednullable

      source=upload: the API key (principal) that uploaded it.

    • uristringrequirednullable

      source=import: hf://owner/name@<40-hex commit>, the pinned revision it was imported from.

  • eval_reportEvalReportrequirednullable
  • created_atstring (date-time)required

    When it was released.

  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
artifact = client.artifacts.get("support-sft@2026-11-28-1")
print(artifact.base_model, artifact.size_bytes)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "support-sft@2026-12-02-1",
  "workspace_id": "ws_e2e",
  "name": "support-sft",
  "version": "2026-12-02-1",
  "run_id": "run_ed1c235f0c631d8f209e22a5",
  "checkpoint_id": null,
  "base_model": "qwen/qwen3-8b",
  "recipe_kind": "sft",
  "format": "reference",
  "sha256": "144d0e25503494bfce90a8919a295505ac2759b0ae331e45ea16fade495c137c",
  "size_bytes": 10263,
  "manifest": {
    "lr": 0.000125,
    "kind": "final",
    "seed": 42,
    "files": {
      "reference_model.json": "59abd7749fec876cab4e168ea5a73ba432cbd5b568a7c8070258ec7f945b454b"
    },
    "format": "reference",
    "run_id": "run_ed1c235f0c631d8f209e22a5",
    "schema": "grad.artifact/1",
    "select": "last",
    "status": "completed",
    "attempt": 1,
    "backend": "reference",
    "dataset": "support-prod",
    "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
    "base_model": "qwen/qwen3-8b",
    "created_by": {
      "name": "grad-trainer",
      "version": "0.2.0-alpha.15"
    },
    "deployable": false,
    "provenance": {
      "run_id": "run_ed1c235f0c631d8f209e22a5",
      "source": "run"
    },
    "recipe_kind": "sft",
    "total_steps": 1,
    "rule_version": "auto@2",
    "tokens_total": 21,
    "base_artifact": null,
    "selected_step": 1,
    "format_version": 2,
    "base_model_repo": null,
    "dataset_version": 1,
    "resolved_config": {
      "lr": 0.000125,
      "name": "support-sft",
      "model": "qwen/qwen3-8b",
      "split": {
        "seed": 42,
        "strategy": "by_session",
        "eval_records": 0,
        "eval_fraction": 0.1,
        "train_records": 1
      },
      "epochs": 1,
      "select": "best",
      "warmup": 0.03,
      "adapter": {
        "kind": "lora",
        "rank": 32,
        "alpha": 32,
        "merge_on_export": false,
        "train_multimodal_projector": false
      },
      "dataset": "support-prod",
      "schedule": "linear",
      "thinking": "auto",
      "train_on": "last",
      "lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
      "optimizer": {
        "kind": "adamw",
        "betas": [
          0.9,
          0.95
        ],
        "grad_clip": 1,
        "weight_decay": 0
      },
      "reduction": "per_example",
      "batch_size": 8,
      "recipe_kind": "sft",
      "rule_version": "auto@2",
      "base_artifact": null,
      "label_eval_id": null,
      "recipe_params": {},
      "dataset_version": 1,
      "eval_every_steps": 1,
      "preserve_thinking": false,
      "template_revision": "qwen3@3",
      "checkpoint_ttl_days": 30,
      "checkpoint_every_steps": 1
    },
    "steps_completed": 1,
    "eval_report_sha256": "782d3768b9a29b35b624e5fb6e013ad89598c2cd770421c0a5b7db8be230d56c",
    "base_model_revision": null
  },
  "provenance": {
    "source": "run",
    "run_id": "run_ed1c235f0c631d8f209e22a5",
    "trainer_id": null,
    "uploader": null,
    "uri": null
  },
  "eval_report": {
    "warnings": [
      "Reference test backend: the base model was not trained; the artifact is not deployable.",
      "No held-out examples: eval metrics are null and select='last' was used."
    ],
    "best_step": null,
    "eval_loss": null,
    "final_step": 1,
    "metric_mode": "min",
    "metric_name": "eval_loss",
    "eval_records": 0,
    "eval_examples": 0,
    "selected_step": 1,
    "train_records": 1,
    "train_examples": 1,
    "reference_backend": true
  },
  "created_at": "2026-12-02T15:49:00.199Z"
}

A short-lived presigned URL of an artifact bundle#

GET/v1/artifacts/{id}/download-url

Browsers download straight from storage.

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 ArtifactDownloadUrl Presigned download.

5 fields
  • urlstring (uri)required

    A presigned GET of the bundle (.grad.tar.gz) straight from storage; no Authorization header. Verify its SHA-256.

  • expires_atstring (date-time)required
  • sha256stringrequired

    Matches ^[0-9a-f]{64}$

  • size_bytesintegerrequired≥ 0
  • filenamestringrequired

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
link = client.artifacts.download_url("support-sft@2026-11-28-1")
print(link["url"], link["expires_at"])
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "url": "https://storage.example.com/grad-test/artifacts/ws_e2e/144d0e25503494bfce90a8919a295505ac2759b0ae331e45ea16fade495c137c?X-Amz-Algorithm=…&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=…&X-Amz-Date=…&X-Amz-Expires=…&X-Amz-Signature=…&X-Amz-SignedHeaders=…&response-content-disposition=attachment%3B%20filename%3D%22support-sft-2026-12-02-1.grad.tar.gz%22%3B%20filename%2A%3DUTF-8%27%27support…",
  "expires_at": "2026-12-02T16:04:01.192Z",
  "sha256": "144d0e25503494bfce90a8919a295505ac2759b0ae331e45ea16fade495c137c",
  "size_bytes": 10263,
  "filename": "support-sft-2026-12-02-1.grad.tar.gz"
}

Download an artifact bundle (.grad.tar.gz); verify X-Artifact-Sha256#

GET/v1/artifacts/{id}/download

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 string (binary) Artifact bundle.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
path = client.artifacts.download("support-sft@2026-11-28-1", "./support-sft")  # verified PEFT directory
Response 200 OK

application/octet-stream: Artifact bundle.

Register uploaded files or a Hugging Face repo as an artifact#

POST/v1/artifact-imports

Async import job.

An import worker validates the files against docs/ARTIFACT_FORMATS.md and the base model's config.json, bundles them as grad.artifact/1 and releases them as name@YYYY-MM-DD-n. A validation failure fails the import with error_code invalid_artifact and an error that names the file.

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body CreateArtifactImportRequest

  • sourceArtifactImportSourcerequired
    One of 2 shapes
    1. object
      • kind"upload"required

        "upload"

      • upload_idstringrequired

        A tar (optionally gzip) of the artifact's files, uploaded with POST /v1/uploads.

        Matches ^[0-9a-f]{64}$

    2. object
      • kind"hf"required

        "hf"

      • repostringrequired≤ 200 chars

        Matches ^[A-Za-z0-9](?:[\w-]|\.(?!\.))*(\/[A-Za-z0-9](?:[\w-]|\.(?!\.))*)?$

      • revisionstring≤ 128 chars

        Branch, tag or commit (default main). The import pins the commit it resolves.

        Matches ^(?!.*\.\.)[A-Za-z0-9][A-Za-z0-9._/-]*$

      • integrationstring≤ 64 chars

        A huggingface integration whose token reads gated or private repos. Default: the workspace's only huggingface integration; with none, public access.

        Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • base_modelstringrequired≤ 160 chars

    The catalog base model (GET /v1/base-models) the files were trained on.

  • formatImportableArtifactFormatdefault "peft_lora"

    "peft_lora""merged_safetensors""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle"

  • namestring≤ 64 chars

    The artifact name (name@YYYY-MM-DD-n). Required for uploads; HF imports default to the repo's name.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Returns

202 ArtifactImport Queued import.

13 fields
  • idstringrequired
  • workspace_idstringrequired
  • statusArtifactImportStatusrequired

    "queued""running""completed""failed"

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • base_modelstringrequired
  • formatArtifactFormatrequired

    "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

  • sourceobjectrequired
    5 child fields
    • kindenumrequired

      "upload""hf"

    • upload_idstringrequirednullable
    • repostringrequirednullable
    • revisionstringrequirednullable

      HF imports: the requested revision, then the pinned commit once imported.

    • integrationstringrequirednullable

      HF imports: the huggingface integration used, if any.

  • artifact_idstringrequirednullable

    The artifact (name@version) once the import completed.

  • errorstringrequirednullable

    Why it failed. Validation failures name the file and the problem (adapter_config.json: ...).

  • error_codestringrequirednullable

    invalid_artifact (the files don't match the format spec or the base model), source_unavailable, or null.

  • attemptintegerrequired≥ 0
  • created_atstring (date-time)required
  • updated_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
pending = client.artifacts.from_hf(
    "hf://acme/support-lora", base="qwen/qwen3-8b", revision="main", name="support-lora"
)
artifact = pending.wait()
Response 202 AcceptedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "imp_fbde7c15de104d8eb2e3abbf",
  "workspace_id": "ws_e2e",
  "status": "queued",
  "name": "support-lora",
  "base_model": "qwen/qwen3-8b",
  "format": "peft_lora",
  "source": {
    "kind": "hf",
    "upload_id": null,
    "repo": "acme/support-lora",
    "revision": "main",
    "integration": null
  },
  "artifact_id": null,
  "error": null,
  "error_code": null,
  "attempt": 0,
  "created_at": "2026-12-02T15:48:59.921Z",
  "updated_at": "2026-12-02T15:48:59.921Z"
}

List artifact imports#

GET/v1/artifact-imports

Newest first.

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • statusstring

    Only these statuses, comma-separated: queued, running, completed, failed.

Returns

200 object Artifact imports.

2 fields
  • dataarray of ArtifactImportrequired
    13 child fields
    • idstringrequired
    • workspace_idstringrequired
    • statusArtifactImportStatusrequired

      "queued""running""completed""failed"

    • namestringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • base_modelstringrequired
    • formatArtifactFormatrequired

      "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

    • sourceobjectrequired
      5 child fields
      • kindenumrequired

        "upload""hf"

      • upload_idstringrequirednullable
      • repostringrequirednullable
      • revisionstringrequirednullable

        HF imports: the requested revision, then the pinned commit once imported.

      • integrationstringrequirednullable

        HF imports: the huggingface integration used, if any.

    • artifact_idstringrequirednullable

      The artifact (name@version) once the import completed.

    • errorstringrequirednullable

      Why it failed. Validation failures name the file and the problem (adapter_config.json: ...).

    • error_codestringrequirednullable

      invalid_artifact (the files don't match the format spec or the base model), source_unavailable, or null.

    • attemptintegerrequired≥ 0
    • created_atstring (date-time)required
    • updated_atstring (date-time)required
  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for job in client.artifacts.list_imports():
    print(job.id, job.status, job.artifact_id)
Response 200 OKGenerated from the schema
JSON
{
  "data": [
    {
      "id": "imp_3f9c0a1b2c3d4e5f60718293",
      "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
      "status": "queued",
      "name": "support-prod",
      "base_model": "qwen/qwen3-8b",
      "format": "peft_lora",
      "source": {
        "kind": "upload",
        "upload_id": "obj_3f9c0a1b2c3d4e5f60718293",
        "repo": "string",
        "revision": "string",
        "integration": "string"
      },
      "artifact_id": "support-sft@2026-11-28-1",
      "error": "…",
      "error_code": "string",
      "attempt": 0,
      "created_at": "2026-11-28T09:30:00.000Z",
      "updated_at": "2026-11-28T09:30:00.000Z"
    }
  ],
  "next_cursor": "string"
}

Get an artifact import#

GET/v1/artifact-imports/{id}

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 ArtifactImport Artifact import.

13 fields
  • idstringrequired
  • workspace_idstringrequired
  • statusArtifactImportStatusrequired

    "queued""running""completed""failed"

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • base_modelstringrequired
  • formatArtifactFormatrequired

    "peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"

  • sourceobjectrequired
    5 child fields
    • kindenumrequired

      "upload""hf"

    • upload_idstringrequirednullable
    • repostringrequirednullable
    • revisionstringrequirednullable

      HF imports: the requested revision, then the pinned commit once imported.

    • integrationstringrequirednullable

      HF imports: the huggingface integration used, if any.

  • artifact_idstringrequirednullable

    The artifact (name@version) once the import completed.

  • errorstringrequirednullable

    Why it failed. Validation failures name the file and the problem (adapter_config.json: ...).

  • error_codestringrequirednullable

    invalid_artifact (the files don't match the format spec or the base model), source_unavailable, or null.

  • attemptintegerrequired≥ 0
  • created_atstring (date-time)required
  • updated_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
job = client.artifacts.get_import("imp_3f9c0a1b2c3d4e5f60718293")
print(job.status, job.artifact_id)
Response 200 OKGenerated from the schema
JSON
{
  "id": "imp_3f9c0a1b2c3d4e5f60718293",
  "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
  "status": "queued",
  "name": "support-prod",
  "base_model": "qwen/qwen3-8b",
  "format": "peft_lora",
  "source": {
    "kind": "upload",
    "upload_id": "obj_3f9c0a1b2c3d4e5f60718293",
    "repo": "string",
    "revision": "string",
    "integration": "string"
  },
  "artifact_id": "support-sft@2026-11-28-1",
  "error": "…",
  "error_code": "string",
  "attempt": 0,
  "created_at": "2026-11-28T09:30:00.000Z",
  "updated_at": "2026-11-28T09:30:00.000Z"
}

Evals#

Estimate tasks, model/judge calls, and cost before running an eval#

POST/v1/evals/plan

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body PlanEvalRequest

  • namestring≤ 64 charsdefault "eval-run"

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • modelsarray of stringrequired1–16 items

    The models to evaluate: catalog ids, artifacts (name@version), models your inference endpoint serves, or policy labels when env is set.

  • baselinestring≤ 200 chars

    One of models; the summary reports every other model's difference from it. Mutually exclusive with baseline_eval.

  • baseline_evalEvalBaselineRef
    2 child fields
    • idstringrequired≤ 128 chars

      Completed eval id to pair per-task scores against.

    • modelstringrequired≤ 200 chars

      Model label inside id whose scores form the baseline.

  • gateEvalGateInput
    2 child fields
    • max_dropnumber0–1default 0
    • ruleEvalGateRule

      significant fails when the paired 95% CI upper bound is below -max_drop (requires at least 30 paired tasks); delta fails when the point estimate is below -max_drop (works on any non-empty paired set).

      "significant""delta"

  • envEvalEnvConfig
    3 child fields
    • namestringrequired≤ 200 chars

      Display name of the client environment (module:attr).

    • max_turnsintegerrequired1–256

      Maximum agent turns per rollout.

    • fingerprintstring≤ 128 chars

      Client-computed hash of tool schemas and optional environment version, checked when pairing against a baseline_eval.

  • datasetstringrequired≤ 64 chars

    The dataset whose records are the tasks.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • dataset_versioninteger≥ 1

    The version to evaluate. Default: the current one, pinned when the eval is created.

  • rubricarray of EvalRubricItem1–32 items

    Default: the dataset's own rubric (a benchmark's answer check), else a non_empty validator.

    9 child fields
    • namestringrequired≤ 80 chars

      Matches ^[A-Za-z0-9_.:-]+$

    • kindenumrequired

      "regex""validator""code""judge"

    • weightnumber> 0default 1
    • patternstring≤ 256 chars
    • flagsstring≤ 4 chars

      Matches ^[imsu]*$

    • validatorenum

      "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

    • modelstring≤ 160 chars
    • promptstring≤ 8000 chars
    • runtime"local"

      Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

      "local"

  • samplesinteger1–32default 1

    Answers per task and model; 3 or more for decisions you will act on.

  • temperaturenumber0–2default 0.7

    Sampling temperature of the model calls.

  • max_tokensinteger1–32768default 1024

    The most tokens each answer may have.

  • limitinteger1–100000

    Evaluate only the first limit tasks.

  • pass_thresholdnumbernullable0–1default null

    Defaults to 1.0 when every rubric item is binary (regex/validator) and 0.5 otherwise.

Returns

200 PlanEvalResponse Estimated eval plan.

10 fields
  • task_source_kind"dataset"required

    "dataset"

  • dataset_versionintegerrequired≥ 1
  • estimated_tasksintegerrequired≥ 0
  • estimated_model_callsintegerrequired≥ 0
  • estimated_judge_callsintegerrequired≥ 0
  • estimated_cost_usdnumberrequired≥ 0
  • judge_modelsarray of stringrequired
  • local_scorersarray of stringrequired
  • pass_thresholdnumberrequired0–1
  • warningsarray of stringrequired

Errors: 400 401 403 404 409 422 500 501 503

Request
Python
from grad import Grad, Judge

client = Grad()
helpful = Judge(
    name="helpful",
    model="qwen/qwen3-32b",
    prompt="Score 1 if the answer resolves the request, else 0.",
)
plan = client.evals.plan(
    name="sft-vs-base",
    models=["support-sft@latest", "qwen/qwen3-8b"],
    baseline="qwen/qwen3-8b",
    dataset="support-prod",
    rubric=[helpful],
    limit=200,
)
print(plan.estimated_cost_usd)
Response 200 OKGenerated from the schema
JSON
{
  "task_source_kind": "dataset",
  "dataset_version": 1,
  "estimated_tasks": 0,
  "estimated_model_calls": 0,
  "estimated_judge_calls": 0,
  "estimated_cost_usd": 0,
  "judge_models": [
    "string"
  ],
  "local_scorers": [
    "string"
  ],
  "pass_threshold": 0,
  "warnings": [
    "string"
  ]
}

Queue an evaluation across models on a pinned dataset version#

POST/v1/evals

Executed by the server.

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body PlanEvalRequest

  • namestring≤ 64 charsdefault "eval-run"

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • modelsarray of stringrequired1–16 items

    The models to evaluate: catalog ids, artifacts (name@version), models your inference endpoint serves, or policy labels when env is set.

  • baselinestring≤ 200 chars

    One of models; the summary reports every other model's difference from it. Mutually exclusive with baseline_eval.

  • baseline_evalEvalBaselineRef
    2 child fields
    • idstringrequired≤ 128 chars

      Completed eval id to pair per-task scores against.

    • modelstringrequired≤ 200 chars

      Model label inside id whose scores form the baseline.

  • gateEvalGateInput
    2 child fields
    • max_dropnumber0–1default 0
    • ruleEvalGateRule

      significant fails when the paired 95% CI upper bound is below -max_drop (requires at least 30 paired tasks); delta fails when the point estimate is below -max_drop (works on any non-empty paired set).

      "significant""delta"

  • envEvalEnvConfig
    3 child fields
    • namestringrequired≤ 200 chars

      Display name of the client environment (module:attr).

    • max_turnsintegerrequired1–256

      Maximum agent turns per rollout.

    • fingerprintstring≤ 128 chars

      Client-computed hash of tool schemas and optional environment version, checked when pairing against a baseline_eval.

  • datasetstringrequired≤ 64 chars

    The dataset whose records are the tasks.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • dataset_versioninteger≥ 1

    The version to evaluate. Default: the current one, pinned when the eval is created.

  • rubricarray of EvalRubricItem1–32 items

    Default: the dataset's own rubric (a benchmark's answer check), else a non_empty validator.

    9 child fields
    • namestringrequired≤ 80 chars

      Matches ^[A-Za-z0-9_.:-]+$

    • kindenumrequired

      "regex""validator""code""judge"

    • weightnumber> 0default 1
    • patternstring≤ 256 chars
    • flagsstring≤ 4 chars

      Matches ^[imsu]*$

    • validatorenum

      "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

    • modelstring≤ 160 chars
    • promptstring≤ 8000 chars
    • runtime"local"

      Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

      "local"

  • samplesinteger1–32default 1

    Answers per task and model; 3 or more for decisions you will act on.

  • temperaturenumber0–2default 0.7

    Sampling temperature of the model calls.

  • max_tokensinteger1–32768default 1024

    The most tokens each answer may have.

  • limitinteger1–100000

    Evaluate only the first limit tasks.

  • pass_thresholdnumbernullable0–1default null

    Defaults to 1.0 when every rubric item is binary (regex/validator) and 0.5 otherwise.

Returns

202 EvalRun Queued evaluation run.

29 fields
  • idstringrequired

    Eval id (eval_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • statusEvalStatusrequired

    "queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"

  • modeEvalModerequired

    eval generates outputs from models; score (dataset.score()) grades each record's own output (model record) and writes the scores to the dataset's next version; env is a client-driven agent evaluation whose rollouts post outputs via /outputs and /complete.

    "eval""score""env"

  • modelsarray of stringrequired

    The models evaluated: catalog ids, artifacts (name@version), models the inference endpoint serves, or policy labels in env mode.

  • baselinestringrequirednullable

    The model the summary compares the others with (vs_baseline); null for none.

  • baseline_evalEvalBaselineRefrequirednullable
  • envEvalEnvConfigrequirednullable
  • gateEvalGateResultrequirednullable
  • task_sourceobjectrequired
    3 child fields
    • kind"dataset"required

      "dataset"

    • datasetstringrequired
    • versionintegerrequired≥ 1
  • rubricarray of EvalRubricItemrequired
    9 child fields
    • namestringrequired≤ 80 chars

      Matches ^[A-Za-z0-9_.:-]+$

    • kindenumrequired

      "regex""validator""code""judge"

    • weightnumber> 0default 1
    • patternstring≤ 256 chars
    • flagsstring≤ 4 chars

      Matches ^[imsu]*$

    • validatorenum

      "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

    • modelstring≤ 160 chars
    • promptstring≤ 8000 chars
    • runtime"local"

      Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

      "local"

  • samplesintegerrequired≥ 1

    Answers generated per task and model.

  • temperaturenumberrequired0–2

    Sampling temperature of the model calls.

  • max_tokensintegerrequired≥ 1

    The most tokens each answer may have.

  • pass_thresholdnumberrequired0–1

    Score at or above which a task passes.

  • judge_modelsarray of stringrequired

    The judge models the rubric calls.

  • local_scorersarray of stringrequired

    Code scorers that run in the SDK process; the eval waits in awaiting_scores until they post their scores.

  • progressobjectrequired
    3 child fields
    • total_outputsintegerrequired≥ 0
    • generatedintegerrequired≥ 0
    • pending_local_scoresintegerrequired≥ 0
  • summaryarray of EvalModelSummaryrequired
    12 child fields
    • modelstringrequired

      The model this summary is for.

    • overallnumberrequired

      Mean task score (each task's score averages its samples).

    • ci_lownumberrequired

      Lower bound of the bootstrap 95% confidence interval on overall.

    • ci_highnumberrequired

      Upper bound of the bootstrap 95% confidence interval on overall.

    • pass_at_kmap of numberrequired

      Unbiased pass@k per k (pass@1, ...): the chance that one of k samples scores at least pass_threshold.

    • vs_baselineobjectrequirednullable

      The mean paired difference from the baseline over the tasks both answered, with a bootstrap 95% interval; null for the baseline itself or without one.

      3 child fields
      • deltanumberrequired
      • ci_lownumberrequired
      • ci_highnumberrequired
    • tasksintegerrequired≥ 0

      Tasks this model answered.

    • errorsintegerrequired≥ 0

      Model or judge calls that failed.

    • tokens_per_tasknumberrequired

      Mean tokens per task.

    • cost_per_1k_tasks_usdnumberrequirednullable

      Cost per 1,000 tasks in USD; null when the model has no price.

    • by_scorermap of number

      Mean score per rubric scorer over outputs carrying that scorer.

    • mean_turnsnumbernullable

      Mean agent turns per rollout (present when outputs include trajectories with turns).

  • total_cost_usdnumberrequired≥ 0

    Cost of the model and judge calls so far, in USD.

  • scored_dataset_versionintegerrequirednullable≥ 1

    Scoring jobs: the dataset version holding the new scores (the source version when every record was already scored); null until completed.

  • errorstringrequirednullable

    Why the eval failed; null otherwise.

  • waiting_reasonenumrequirednullable

    While running: the eval's model calls are waiting for capacity (a serving pool at zero that has not woken yet), for a rate limit (a full eval lane), or for an inference endpoint that is down. The worker keeps its lease and retries; this is not counted as a failed attempt. null otherwise.

    "capacity_unavailable""rate_limited""inference_unavailable"null

  • last_output_atstring (date-time)requirednullable

    When the last client output was received in env mode; null otherwise.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required
  • completed_atstring (date-time)requirednullable

    When the eval reached a final status; null until then.

  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 501 503

Request
Python
from grad import Grad, Judge

client = Grad()
helpful = Judge(
    name="helpful",
    model="qwen/qwen3-32b",
    prompt="Score 1 if the answer resolves the request, else 0.",
)
ev = client.evals.create(
    name="sft-vs-base",
    models=["support-sft@latest", "qwen/qwen3-8b"],
    baseline="qwen/qwen3-8b",
    dataset="support-prod",
    rubric=[helpful],
    limit=200,
)
ev.wait()
print(ev.summary_table())
Response 202 AcceptedGenerated from the schema
JSON
{
  "id": "eval_3f9c0a1b2c3d4e5f60718293",
  "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
  "name": "support-prod",
  "status": "queued",
  "mode": "eval",
  "models": [
    "string"
  ],
  "baseline": "string",
  "baseline_eval": {
    "id": "obj_3f9c0a1b2c3d4e5f60718293",
    "model": "qwen/qwen3-8b"
  },
  "env": {
    "name": "support-prod",
    "max_turns": 1,
    "fingerprint": "string"
  },
  "gate": {
    "max_drop": 0,
    "rule": "significant",
    "passed": false,
    "regressed": [
      "string"
    ],
    "paired_tasks": 0,
    "min_detectable_drop": 0
  },
  "task_source": {
    "kind": "dataset",
    "dataset": "support-prod",
    "version": 1
  },
  "rubric": [
    {
      "name": "support-prod",
      "kind": "regex",
      "weight": 1,
      "pattern": "string",
      "flags": "string",
      "validator": "json",
      "model": "qwen/qwen3-8b",
      "prompt": "string",
      "runtime": "local"
    }
  ],
  "samples": 1,
  "temperature": 0,
  "max_tokens": 1,
  "pass_threshold": 0,
  "judge_models": [
    "string"
  ],
  "local_scorers": [
    "string"
  ],
  "progress": {
    "total_outputs": 0,
    "generated": 0,
    "pending_local_scores": 0
  },
  "summary": [
    {
      "model": "qwen/qwen3-8b",
      "overall": 0,
      "ci_low": 0,
      "ci_high": 0,
      "pass_at_k": {},
      "vs_baseline": {
        "delta": 0,
        "ci_low": 0,
        "ci_high": 0
      },
      "tasks": 0,
      "errors": 0,
      "tokens_per_task": 0,
      "cost_per_1k_tasks_usd": 0,
      "by_scorer": {},
      "mean_turns": 0
    }
  ],
  "total_cost_usd": 0,
  "scored_dataset_version": 1,
  "error": "…",
  "waiting_reason": "capacity_unavailable",
  "last_output_at": "2026-11-28T09:30:00.000Z",
  "created_at": "2026-11-28T09:30:00.000Z",
  "updated_at": "2026-11-28T09:30:00.000Z",
  "completed_at": "2026-11-28T09:30:00.000Z",
  "console_url": "string"
}

List evaluation runs#

GET/v1/evals

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • statusstring

    Only these statuses, comma-separated: queued, running, awaiting_outputs, awaiting_scores, completed, failed, cancelled.

  • qstring≤ 200 chars

    Only items whose name contains this text (any case), or whose id is exactly this.

Returns

200 object Evaluation runs.

2 fields
  • dataarray of EvalRunrequired
    29 child fields
    • idstringrequired

      Eval id (eval_ and 24 hex characters).

    • workspace_idstringrequired
    • namestringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • statusEvalStatusrequired

      "queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"

    • modeEvalModerequired

      eval generates outputs from models; score (dataset.score()) grades each record's own output (model record) and writes the scores to the dataset's next version; env is a client-driven agent evaluation whose rollouts post outputs via /outputs and /complete.

      "eval""score""env"

    • modelsarray of stringrequired

      The models evaluated: catalog ids, artifacts (name@version), models the inference endpoint serves, or policy labels in env mode.

    • baselinestringrequirednullable

      The model the summary compares the others with (vs_baseline); null for none.

    • baseline_evalEvalBaselineRefrequirednullable
    • envEvalEnvConfigrequirednullable
    • gateEvalGateResultrequirednullable
    • task_sourceobjectrequired
      3 child fields
      • kind"dataset"required

        "dataset"

      • datasetstringrequired
      • versionintegerrequired≥ 1
    • rubricarray of EvalRubricItemrequired
      9 child fields
      • namestringrequired≤ 80 chars

        Matches ^[A-Za-z0-9_.:-]+$

      • kindenumrequired

        "regex""validator""code""judge"

      • weightnumber> 0default 1
      • patternstring≤ 256 chars
      • flagsstring≤ 4 chars

        Matches ^[imsu]*$

      • validatorenum

        "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

      • modelstring≤ 160 chars
      • promptstring≤ 8000 chars
      • runtime"local"

        Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

        "local"

    • samplesintegerrequired≥ 1

      Answers generated per task and model.

    • temperaturenumberrequired0–2

      Sampling temperature of the model calls.

    • max_tokensintegerrequired≥ 1

      The most tokens each answer may have.

    • pass_thresholdnumberrequired0–1

      Score at or above which a task passes.

    • judge_modelsarray of stringrequired

      The judge models the rubric calls.

    • local_scorersarray of stringrequired

      Code scorers that run in the SDK process; the eval waits in awaiting_scores until they post their scores.

    • progressobjectrequired
      3 child fields
      • total_outputsintegerrequired≥ 0
      • generatedintegerrequired≥ 0
      • pending_local_scoresintegerrequired≥ 0
    • summaryarray of EvalModelSummaryrequired
      12 child fields
      • modelstringrequired

        The model this summary is for.

      • overallnumberrequired

        Mean task score (each task's score averages its samples).

      • ci_lownumberrequired

        Lower bound of the bootstrap 95% confidence interval on overall.

      • ci_highnumberrequired

        Upper bound of the bootstrap 95% confidence interval on overall.

      • pass_at_kmap of numberrequired

        Unbiased pass@k per k (pass@1, ...): the chance that one of k samples scores at least pass_threshold.

      • vs_baselineobjectrequirednullable

        The mean paired difference from the baseline over the tasks both answered, with a bootstrap 95% interval; null for the baseline itself or without one.

        3 child fields
        • deltanumberrequired
        • ci_lownumberrequired
        • ci_highnumberrequired
      • tasksintegerrequired≥ 0

        Tasks this model answered.

      • errorsintegerrequired≥ 0

        Model or judge calls that failed.

      • tokens_per_tasknumberrequired

        Mean tokens per task.

      • cost_per_1k_tasks_usdnumberrequirednullable

        Cost per 1,000 tasks in USD; null when the model has no price.

      • by_scorermap of number

        Mean score per rubric scorer over outputs carrying that scorer.

      • mean_turnsnumbernullable

        Mean agent turns per rollout (present when outputs include trajectories with turns).

    • total_cost_usdnumberrequired≥ 0

      Cost of the model and judge calls so far, in USD.

    • scored_dataset_versionintegerrequirednullable≥ 1

      Scoring jobs: the dataset version holding the new scores (the source version when every record was already scored); null until completed.

    • errorstringrequirednullable

      Why the eval failed; null otherwise.

    • waiting_reasonenumrequirednullable

      While running: the eval's model calls are waiting for capacity (a serving pool at zero that has not woken yet), for a rate limit (a full eval lane), or for an inference endpoint that is down. The worker keeps its lease and retries; this is not counted as a failed attempt. null otherwise.

      "capacity_unavailable""rate_limited""inference_unavailable"null

    • last_output_atstring (date-time)requirednullable

      When the last client output was received in env mode; null otherwise.

    • created_atstring (date-time)required
    • updated_atstring (date-time)required
    • completed_atstring (date-time)requirednullable

      When the eval reached a final status; null until then.

    • console_urlstringnullable

      Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for ev in client.evals.list(status="running", search="sft-vs-base"):
    print(ev.id, ev.name, ev.status)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "data": [
    {
      "id": "eval_c13bd1724f656bf328ba0115",
      "workspace_id": "ws_e2e",
      "name": "support-prod-score",
      "status": "completed",
      "mode": "score",
      "models": [
        "record"
      ],
      "baseline": null,
      "baseline_eval": null,
      "env": null,
      "gate": null,
      "task_source": {
        "kind": "dataset",
        "dataset": "support-prod",
        "version": 1
      },
      "rubric": [
        {
          "kind": "regex",
          "name": "polite",
          "flags": "i",
          "weight": 1,
          "pattern": "thank"
        }
      ],
      "samples": 1,
      "temperature": 0,
      "max_tokens": 1,
      "pass_threshold": 1,
      "judge_models": [],
      "local_scorers": [],
      "progress": {
        "total_outputs": 1,
        "generated": 1,
        "pending_local_scores": 0
      },
      "summary": [
        {
          "model": "record",
          "tasks": 1,
          "ci_low": 0,
          "errors": 0,
          "ci_high": 0,
          "overall": 0,
          "by_scorer": {
            "polite": 0
          },
          "pass_at_k": {
            "pass@1": 0
          },
          "vs_baseline": null,
          "tokens_per_task": 0,
          "cost_per_1k_tasks_usd": 0
        }
      ],
      "total_cost_usd": 0,
      "scored_dataset_version": 2,
      "error": null,
      "waiting_reason": null,
      "last_output_at": null,
      "created_at": "2026-12-02T15:48:59.828Z",
      "updated_at": "2026-12-02T15:49:00.347Z",
      "completed_at": "2026-12-02T15:49:00.346Z"
    }
  ],
  "next_cursor": null
}

Get an evaluation run by ID#

GET/v1/evals/{id}

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 EvalRun Evaluation run.

29 fields
  • idstringrequired

    Eval id (eval_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • statusEvalStatusrequired

    "queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"

  • modeEvalModerequired

    eval generates outputs from models; score (dataset.score()) grades each record's own output (model record) and writes the scores to the dataset's next version; env is a client-driven agent evaluation whose rollouts post outputs via /outputs and /complete.

    "eval""score""env"

  • modelsarray of stringrequired

    The models evaluated: catalog ids, artifacts (name@version), models the inference endpoint serves, or policy labels in env mode.

  • baselinestringrequirednullable

    The model the summary compares the others with (vs_baseline); null for none.

  • baseline_evalEvalBaselineRefrequirednullable
  • envEvalEnvConfigrequirednullable
  • gateEvalGateResultrequirednullable
  • task_sourceobjectrequired
    3 child fields
    • kind"dataset"required

      "dataset"

    • datasetstringrequired
    • versionintegerrequired≥ 1
  • rubricarray of EvalRubricItemrequired
    9 child fields
    • namestringrequired≤ 80 chars

      Matches ^[A-Za-z0-9_.:-]+$

    • kindenumrequired

      "regex""validator""code""judge"

    • weightnumber> 0default 1
    • patternstring≤ 256 chars
    • flagsstring≤ 4 chars

      Matches ^[imsu]*$

    • validatorenum

      "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

    • modelstring≤ 160 chars
    • promptstring≤ 8000 chars
    • runtime"local"

      Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

      "local"

  • samplesintegerrequired≥ 1

    Answers generated per task and model.

  • temperaturenumberrequired0–2

    Sampling temperature of the model calls.

  • max_tokensintegerrequired≥ 1

    The most tokens each answer may have.

  • pass_thresholdnumberrequired0–1

    Score at or above which a task passes.

  • judge_modelsarray of stringrequired

    The judge models the rubric calls.

  • local_scorersarray of stringrequired

    Code scorers that run in the SDK process; the eval waits in awaiting_scores until they post their scores.

  • progressobjectrequired
    3 child fields
    • total_outputsintegerrequired≥ 0
    • generatedintegerrequired≥ 0
    • pending_local_scoresintegerrequired≥ 0
  • summaryarray of EvalModelSummaryrequired
    12 child fields
    • modelstringrequired

      The model this summary is for.

    • overallnumberrequired

      Mean task score (each task's score averages its samples).

    • ci_lownumberrequired

      Lower bound of the bootstrap 95% confidence interval on overall.

    • ci_highnumberrequired

      Upper bound of the bootstrap 95% confidence interval on overall.

    • pass_at_kmap of numberrequired

      Unbiased pass@k per k (pass@1, ...): the chance that one of k samples scores at least pass_threshold.

    • vs_baselineobjectrequirednullable

      The mean paired difference from the baseline over the tasks both answered, with a bootstrap 95% interval; null for the baseline itself or without one.

      3 child fields
      • deltanumberrequired
      • ci_lownumberrequired
      • ci_highnumberrequired
    • tasksintegerrequired≥ 0

      Tasks this model answered.

    • errorsintegerrequired≥ 0

      Model or judge calls that failed.

    • tokens_per_tasknumberrequired

      Mean tokens per task.

    • cost_per_1k_tasks_usdnumberrequirednullable

      Cost per 1,000 tasks in USD; null when the model has no price.

    • by_scorermap of number

      Mean score per rubric scorer over outputs carrying that scorer.

    • mean_turnsnumbernullable

      Mean agent turns per rollout (present when outputs include trajectories with turns).

  • total_cost_usdnumberrequired≥ 0

    Cost of the model and judge calls so far, in USD.

  • scored_dataset_versionintegerrequirednullable≥ 1

    Scoring jobs: the dataset version holding the new scores (the source version when every record was already scored); null until completed.

  • errorstringrequirednullable

    Why the eval failed; null otherwise.

  • waiting_reasonenumrequirednullable

    While running: the eval's model calls are waiting for capacity (a serving pool at zero that has not woken yet), for a rate limit (a full eval lane), or for an inference endpoint that is down. The worker keeps its lease and retries; this is not counted as a failed attempt. null otherwise.

    "capacity_unavailable""rate_limited""inference_unavailable"null

  • last_output_atstring (date-time)requirednullable

    When the last client output was received in env mode; null otherwise.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required
  • completed_atstring (date-time)requirednullable

    When the eval reached a final status; null until then.

  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
ev = client.evals.get("eval_3f9c0a1b2c3d4e5f60718293")
print(ev.summary_table())
Response 200 OKGenerated from the schema
JSON
{
  "id": "eval_3f9c0a1b2c3d4e5f60718293",
  "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
  "name": "support-prod",
  "status": "queued",
  "mode": "eval",
  "models": [
    "string"
  ],
  "baseline": "string",
  "baseline_eval": {
    "id": "obj_3f9c0a1b2c3d4e5f60718293",
    "model": "qwen/qwen3-8b"
  },
  "env": {
    "name": "support-prod",
    "max_turns": 1,
    "fingerprint": "string"
  },
  "gate": {
    "max_drop": 0,
    "rule": "significant",
    "passed": false,
    "regressed": [
      "string"
    ],
    "paired_tasks": 0,
    "min_detectable_drop": 0
  },
  "task_source": {
    "kind": "dataset",
    "dataset": "support-prod",
    "version": 1
  },
  "rubric": [
    {
      "name": "support-prod",
      "kind": "regex",
      "weight": 1,
      "pattern": "string",
      "flags": "string",
      "validator": "json",
      "model": "qwen/qwen3-8b",
      "prompt": "string",
      "runtime": "local"
    }
  ],
  "samples": 1,
  "temperature": 0,
  "max_tokens": 1,
  "pass_threshold": 0,
  "judge_models": [
    "string"
  ],
  "local_scorers": [
    "string"
  ],
  "progress": {
    "total_outputs": 0,
    "generated": 0,
    "pending_local_scores": 0
  },
  "summary": [
    {
      "model": "qwen/qwen3-8b",
      "overall": 0,
      "ci_low": 0,
      "ci_high": 0,
      "pass_at_k": {},
      "vs_baseline": {
        "delta": 0,
        "ci_low": 0,
        "ci_high": 0
      },
      "tasks": 0,
      "errors": 0,
      "tokens_per_task": 0,
      "cost_per_1k_tasks_usd": 0,
      "by_scorer": {},
      "mean_turns": 0
    }
  ],
  "total_cost_usd": 0,
  "scored_dataset_version": 1,
  "error": "…",
  "waiting_reason": "capacity_unavailable",
  "last_output_at": "2026-11-28T09:30:00.000Z",
  "created_at": "2026-11-28T09:30:00.000Z",
  "updated_at": "2026-11-28T09:30:00.000Z",
  "completed_at": "2026-11-28T09:30:00.000Z",
  "console_url": "string"
}

Page through generated model outputs#

GET/v1/evals/{id}/outputs

Filter by model or by a code scorer that still needs a score.

Path parameters

  • idstringrequired≤ 200 chars

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • modelstring≤ 200 chars
  • missing_scorerstring≤ 80 chars
  • fields"key"

    "key"

Returns

200 object Eval outputs.

2 fields
  • dataarray of EvalOutputrequired
    16 child fields
    • idstringrequired
    • eval_idstringrequired
    • task_indexintegerrequired≥ 0
    • task_idstringrequired
    • modelstringrequired
    • sample_indexintegerrequired≥ 0
    • inputarray of ChatMessagerequired
      7 child fields
      • roleenumrequired

        "system""user""assistant""tool"

      • contentstring or array of map of anynullable
        One of 2 shapes
        1. string
        2. array of map of any
      • reasoning_contentstring
      • tool_callsarray of map of any
      • tool_call_idstring
      • namestring
      • trainboolean
    • outputstringrequirednullable
    • expected_outputany
    • recordDatasetRecordrequired
      24 child fields
      • schema"grad.trajectory/1"

        "grad.trajectory/1"

      • idstring≤ 160 chars
      • session_idstringnullable≤ 160 chars
      • group_idstringnullable≤ 160 chars
      • roleenumnullable

        "chosen""rejected""anchor""positive""negative""desirable""undesirable""rollout"null

      • sourcestringnullable≤ 80 chars
      • timestampstringnullable≤ 64 chars
      • messagesarray of ChatMessage
        7 child fields
        • roleenumrequired

          "system""user""assistant""tool"

        • contentstring or array of map of anynullable
          One of 2 shapes
          1. string
          2. array of map of any
        • reasoning_contentstring
        • tool_callsarray of map of any
        • tool_call_idstring
        • namestring
        • trainboolean
      • toolsarray of map of any
      • inputTrajectoryInput
        5 child fields
        • messagesarray of ChatMessage
          7 child fields
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
        • toolsarray of map of any
        • mediaarray of map of any
        • featuresmap of any
        • payloadany
      • outputTrajectoryOutputnullable
      • promptstring or array of ChatMessage
        One of 2 shapes
        1. string
        2. array of ChatMessage
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
      • completionstring or array of ChatMessage
        One of 2 shapes
        1. string
        2. array of ChatMessage
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
      • chosenstring or array of ChatMessage
        One of 2 shapes
        1. string
        2. array of ChatMessage
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
      • rejectedstring or array of ChatMessage
        One of 2 shapes
        1. string
        2. array of ChatMessage
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
      • querystring
      • positivestring
      • negativesarray of string
      • stateany
      • questionsmap of any
      • expected_outputany
      • scoresmap of number
      • metricsmap of number
      • metadatamap of any
    • scorenumbernullable

      Combined rubric score for this output (null until scored/finalized).

    • scoresmap of numberrequired
    • errorstringrequirednullable
    • usageobjectrequired
      2 child fields
      • prompt_tokensintegerrequired≥ 0
      • completion_tokensintegerrequired≥ 0
    • trajectoryEvalTrajectorynullable
    • trajectory_urlstringnullable
  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for output in client.evals.outputs("eval_3f9c0a1b2c3d4e5f60718293", missing_scorer="sql_runs"):
    print(output.id, output.model, output.output)
Response 200 OKGenerated from the schema
JSON
{
  "data": [
    {
      "id": "evout_3f9c0a1b2c3d4e5f60718293",
      "eval_id": "obj_3f9c0a1b2c3d4e5f60718293",
      "task_index": 0,
      "task_id": "obj_3f9c0a1b2c3d4e5f60718293",
      "model": "qwen/qwen3-8b",
      "sample_index": 0,
      "input": [
        {
          "role": "system",
          "content": "Count active users from yesterday.",
          "reasoning_content": "string",
          "tool_calls": [],
          "tool_call_id": "obj_3f9c0a1b2c3d4e5f60718293",
          "name": "support-prod",
          "train": false
        }
      ],
      "output": "string",
      "expected_output": null,
      "record": {
        "schema": "grad.trajectory/1",
        "id": "obj_3f9c0a1b2c3d4e5f60718293",
        "session_id": "obj_3f9c0a1b2c3d4e5f60718293",
        "group_id": "obj_3f9c0a1b2c3d4e5f60718293",
        "role": "chosen",
        "source": "string",
        "timestamp": "string",
        "messages": [
          {}
        ],
        "tools": [
          {}
        ],
        "input": {
          "messages": [],
          "tools": [],
          "media": [],
          "features": {},
          "payload": null
        },
        "output": {
          "turns": [],
          "payload": null
        },
        "prompt": "string",
        "completion": "string",
        "chosen": "string",
        "rejected": "string",
        "query": "string",
        "positive": "string",
        "negatives": [
          "string"
        ],
        "state": null,
        "questions": {},
        "expected_output": null,
        "scores": {},
        "metrics": {},
        "metadata": {}
      },
      "score": 0,
      "scores": {},
      "error": "…",
      "usage": {
        "prompt_tokens": 0,
        "completion_tokens": 0
      },
      "trajectory": {
        "messages": [
          {}
        ],
        "turns": 0,
        "finish_reason": "string",
        "policy": {},
        "error": "…"
      },
      "trajectory_url": "string"
    }
  ],
  "next_cursor": "string"
}

Post client-side rollout outputs and trajectories for an env-mode eval#

POST/v1/evals/{id}/outputs

Idempotent per cell.

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body PostEvalOutputsRequest

  • outputsarray of ClientEvalOutputInputrequired1–256 items
    12 child fields
    • modelstringrequired≤ 200 chars
    • task_indexintegerrequired≥ 0
    • task_idstringrequired≤ 512 chars
    • sample_indexintegerrequired≥ 0
    • recordmap of anyrequired
    • inputarray of map of anyrequired
    • outputstringrequirednullable
    • expected_outputany
    • scoresmap of numberdefault {}
    • errorstringnullable≤ 2000 charsdefault null
    • trajectoryEvalTrajectorynullable
    • usageobject
      3 child fields
      • prompt_tokensinteger≥ 0default 0
      • completion_tokensinteger≥ 0default 0
      • cost_usdnumber≥ 0

Returns

200 PostEvalOutputsResponse Accepted outputs.

2 fields
  • acceptedintegerrequired≥ 0
  • generatedintegerrequired≥ 0

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
res = client.wire.post_eval_outputs(
    "eval_3f9c0a1b2c3d4e5f60718293",
    {
        "outputs": [
            {
                "model": "qwen/qwen3-8b",
                "task_index": 0,
                "task_id": "task-1",
                "sample_index": 0,
                "record": {"messages": [{"role": "user", "content": "What is 12 * 7?"}]},
                "input": [{"role": "user", "content": "What is 12 * 7?"}],
                "output": "84",
                "scores": {"correct": 1},
            }
        ]
    },
)
print(res["accepted"])
Response 200 OKGenerated from the schema
JSON
{
  "accepted": 0,
  "generated": 0
}

Finalize an env-mode eval once all expected outputs are posted#

POST/v1/evals/{id}/complete

Or queue it for judge scoring.

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Returns

200 EvalRun Completed or queued evaluation run.

29 fields
  • idstringrequired

    Eval id (eval_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • statusEvalStatusrequired

    "queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"

  • modeEvalModerequired

    eval generates outputs from models; score (dataset.score()) grades each record's own output (model record) and writes the scores to the dataset's next version; env is a client-driven agent evaluation whose rollouts post outputs via /outputs and /complete.

    "eval""score""env"

  • modelsarray of stringrequired

    The models evaluated: catalog ids, artifacts (name@version), models the inference endpoint serves, or policy labels in env mode.

  • baselinestringrequirednullable

    The model the summary compares the others with (vs_baseline); null for none.

  • baseline_evalEvalBaselineRefrequirednullable
  • envEvalEnvConfigrequirednullable
  • gateEvalGateResultrequirednullable
  • task_sourceobjectrequired
    3 child fields
    • kind"dataset"required

      "dataset"

    • datasetstringrequired
    • versionintegerrequired≥ 1
  • rubricarray of EvalRubricItemrequired
    9 child fields
    • namestringrequired≤ 80 chars

      Matches ^[A-Za-z0-9_.:-]+$

    • kindenumrequired

      "regex""validator""code""judge"

    • weightnumber> 0default 1
    • patternstring≤ 256 chars
    • flagsstring≤ 4 chars

      Matches ^[imsu]*$

    • validatorenum

      "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

    • modelstring≤ 160 chars
    • promptstring≤ 8000 chars
    • runtime"local"

      Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

      "local"

  • samplesintegerrequired≥ 1

    Answers generated per task and model.

  • temperaturenumberrequired0–2

    Sampling temperature of the model calls.

  • max_tokensintegerrequired≥ 1

    The most tokens each answer may have.

  • pass_thresholdnumberrequired0–1

    Score at or above which a task passes.

  • judge_modelsarray of stringrequired

    The judge models the rubric calls.

  • local_scorersarray of stringrequired

    Code scorers that run in the SDK process; the eval waits in awaiting_scores until they post their scores.

  • progressobjectrequired
    3 child fields
    • total_outputsintegerrequired≥ 0
    • generatedintegerrequired≥ 0
    • pending_local_scoresintegerrequired≥ 0
  • summaryarray of EvalModelSummaryrequired
    12 child fields
    • modelstringrequired

      The model this summary is for.

    • overallnumberrequired

      Mean task score (each task's score averages its samples).

    • ci_lownumberrequired

      Lower bound of the bootstrap 95% confidence interval on overall.

    • ci_highnumberrequired

      Upper bound of the bootstrap 95% confidence interval on overall.

    • pass_at_kmap of numberrequired

      Unbiased pass@k per k (pass@1, ...): the chance that one of k samples scores at least pass_threshold.

    • vs_baselineobjectrequirednullable

      The mean paired difference from the baseline over the tasks both answered, with a bootstrap 95% interval; null for the baseline itself or without one.

      3 child fields
      • deltanumberrequired
      • ci_lownumberrequired
      • ci_highnumberrequired
    • tasksintegerrequired≥ 0

      Tasks this model answered.

    • errorsintegerrequired≥ 0

      Model or judge calls that failed.

    • tokens_per_tasknumberrequired

      Mean tokens per task.

    • cost_per_1k_tasks_usdnumberrequirednullable

      Cost per 1,000 tasks in USD; null when the model has no price.

    • by_scorermap of number

      Mean score per rubric scorer over outputs carrying that scorer.

    • mean_turnsnumbernullable

      Mean agent turns per rollout (present when outputs include trajectories with turns).

  • total_cost_usdnumberrequired≥ 0

    Cost of the model and judge calls so far, in USD.

  • scored_dataset_versionintegerrequirednullable≥ 1

    Scoring jobs: the dataset version holding the new scores (the source version when every record was already scored); null until completed.

  • errorstringrequirednullable

    Why the eval failed; null otherwise.

  • waiting_reasonenumrequirednullable

    While running: the eval's model calls are waiting for capacity (a serving pool at zero that has not woken yet), for a rate limit (a full eval lane), or for an inference endpoint that is down. The worker keeps its lease and retries; this is not counted as a failed attempt. null otherwise.

    "capacity_unavailable""rate_limited""inference_unavailable"null

  • last_output_atstring (date-time)requirednullable

    When the last client output was received in env mode; null otherwise.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required
  • completed_atstring (date-time)requirednullable

    When the eval reached a final status; null until then.

  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
ev = client.wire.complete_eval("eval_3f9c0a1b2c3d4e5f60718293", {})
print(ev["status"])
Response 200 OKGenerated from the schema
JSON
{
  "id": "eval_3f9c0a1b2c3d4e5f60718293",
  "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
  "name": "support-prod",
  "status": "queued",
  "mode": "eval",
  "models": [
    "string"
  ],
  "baseline": "string",
  "baseline_eval": {
    "id": "obj_3f9c0a1b2c3d4e5f60718293",
    "model": "qwen/qwen3-8b"
  },
  "env": {
    "name": "support-prod",
    "max_turns": 1,
    "fingerprint": "string"
  },
  "gate": {
    "max_drop": 0,
    "rule": "significant",
    "passed": false,
    "regressed": [
      "string"
    ],
    "paired_tasks": 0,
    "min_detectable_drop": 0
  },
  "task_source": {
    "kind": "dataset",
    "dataset": "support-prod",
    "version": 1
  },
  "rubric": [
    {
      "name": "support-prod",
      "kind": "regex",
      "weight": 1,
      "pattern": "string",
      "flags": "string",
      "validator": "json",
      "model": "qwen/qwen3-8b",
      "prompt": "string",
      "runtime": "local"
    }
  ],
  "samples": 1,
  "temperature": 0,
  "max_tokens": 1,
  "pass_threshold": 0,
  "judge_models": [
    "string"
  ],
  "local_scorers": [
    "string"
  ],
  "progress": {
    "total_outputs": 0,
    "generated": 0,
    "pending_local_scores": 0
  },
  "summary": [
    {
      "model": "qwen/qwen3-8b",
      "overall": 0,
      "ci_low": 0,
      "ci_high": 0,
      "pass_at_k": {},
      "vs_baseline": {
        "delta": 0,
        "ci_low": 0,
        "ci_high": 0
      },
      "tasks": 0,
      "errors": 0,
      "tokens_per_task": 0,
      "cost_per_1k_tasks_usd": 0,
      "by_scorer": {},
      "mean_turns": 0
    }
  ],
  "total_cost_usd": 0,
  "scored_dataset_version": 1,
  "error": "…",
  "waiting_reason": "capacity_unavailable",
  "last_output_at": "2026-11-28T09:30:00.000Z",
  "created_at": "2026-11-28T09:30:00.000Z",
  "updated_at": "2026-11-28T09:30:00.000Z",
  "completed_at": "2026-11-28T09:30:00.000Z",
  "console_url": "string"
}

Post scores computed by local (SDK-side) code scorers; the eval completes when none are missing#

POST/v1/evals/{id}/scores

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body PostEvalScoresRequest

  • scoresarray of objectrequired1–10000 items
    3 child fields
    • output_idstringrequired
    • scorerstringrequired≤ 80 chars
    • scorenumberrequired0–1

Returns

200 PostEvalScoresResponse Accepted scores.

3 fields
  • acceptedintegerrequired≥ 0
  • statusEvalStatusrequired

    "queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"

  • pending_local_scoresintegerrequired≥ 0

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
result = client.evals.post_scores(
    "eval_3f9c0a1b2c3d4e5f60718293",
    [{"output_id": "evout_3f9c0a1b2c3d4e5f60718293", "scorer": "sql_runs", "score": 1}],
)
print(result["accepted"])
Response 200 OKGenerated from the schema
JSON
{
  "accepted": 0,
  "status": "queued",
  "pending_local_scores": 0
}

Per-task, per-model results of a completed evaluation#

GET/v1/evals/{id}/results

Path parameters

  • idstringrequired≤ 200 chars

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • modelstring≤ 200 chars

Returns

200 object Task outcomes.

2 fields
  • dataarray of EvalTaskOutcomerequired
    7 child fields
    • task_idstringrequired
    • modelstringrequired
    • scorenumberrequired
    • passedbooleanrequired
    • sample_scoresarray of numberrequired
    • judge_modelstringrequirednullable
    • recordDatasetRecordrequired
      24 child fields
      • schema"grad.trajectory/1"

        "grad.trajectory/1"

      • idstring≤ 160 chars
      • session_idstringnullable≤ 160 chars
      • group_idstringnullable≤ 160 chars
      • roleenumnullable

        "chosen""rejected""anchor""positive""negative""desirable""undesirable""rollout"null

      • sourcestringnullable≤ 80 chars
      • timestampstringnullable≤ 64 chars
      • messagesarray of ChatMessage
        7 child fields
        • roleenumrequired

          "system""user""assistant""tool"

        • contentstring or array of map of anynullable
          One of 2 shapes
          1. string
          2. array of map of any
        • reasoning_contentstring
        • tool_callsarray of map of any
        • tool_call_idstring
        • namestring
        • trainboolean
      • toolsarray of map of any
      • inputTrajectoryInput
        5 child fields
        • messagesarray of ChatMessage
          7 child fields
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
        • toolsarray of map of any
        • mediaarray of map of any
        • featuresmap of any
        • payloadany
      • outputTrajectoryOutputnullable
      • promptstring or array of ChatMessage
        One of 2 shapes
        1. string
        2. array of ChatMessage
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
      • completionstring or array of ChatMessage
        One of 2 shapes
        1. string
        2. array of ChatMessage
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
      • chosenstring or array of ChatMessage
        One of 2 shapes
        1. string
        2. array of ChatMessage
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
      • rejectedstring or array of ChatMessage
        One of 2 shapes
        1. string
        2. array of ChatMessage
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
      • querystring
      • positivestring
      • negativesarray of string
      • stateany
      • questionsmap of any
      • expected_outputany
      • scoresmap of number
      • metricsmap of number
      • metadatamap of any
  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for result in client.evals.results("eval_3f9c0a1b2c3d4e5f60718293", model="support-sft@latest"):
    print(result.task_id, result.score)
Response 200 OKGenerated from the schema
JSON
{
  "data": [
    {
      "task_id": "obj_3f9c0a1b2c3d4e5f60718293",
      "model": "qwen/qwen3-8b",
      "score": 0,
      "passed": false,
      "sample_scores": [
        0
      ],
      "judge_model": "string",
      "record": {
        "schema": "grad.trajectory/1",
        "id": "obj_3f9c0a1b2c3d4e5f60718293",
        "session_id": "obj_3f9c0a1b2c3d4e5f60718293",
        "group_id": "obj_3f9c0a1b2c3d4e5f60718293",
        "role": "chosen",
        "source": "string",
        "timestamp": "string",
        "messages": [
          {}
        ],
        "tools": [
          {}
        ],
        "input": {
          "messages": [],
          "tools": [],
          "media": [],
          "features": {},
          "payload": null
        },
        "output": {
          "turns": [],
          "payload": null
        },
        "prompt": "string",
        "completion": "string",
        "chosen": "string",
        "rejected": "string",
        "query": "string",
        "positive": "string",
        "negatives": [
          "string"
        ],
        "state": null,
        "questions": {},
        "expected_output": null,
        "scores": {},
        "metrics": {},
        "metadata": {}
      }
    }
  ],
  "next_cursor": "string"
}

List failing task records from an evaluation run for mining#

GET/v1/evals/{id}/failures

Path parameters

  • idstringrequired≤ 200 chars

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • modelstring≤ 200 chars
  • thresholdnumbernullable0–1

Returns

200 object Failing task outcomes.

3 fields
  • eval_idstringrequired
  • dataarray of EvalTaskOutcomerequired
    7 child fields
    • task_idstringrequired
    • modelstringrequired
    • scorenumberrequired
    • passedbooleanrequired
    • sample_scoresarray of numberrequired
    • judge_modelstringrequirednullable
    • recordDatasetRecordrequired
      24 child fields
      • schema"grad.trajectory/1"

        "grad.trajectory/1"

      • idstring≤ 160 chars
      • session_idstringnullable≤ 160 chars
      • group_idstringnullable≤ 160 chars
      • roleenumnullable

        "chosen""rejected""anchor""positive""negative""desirable""undesirable""rollout"null

      • sourcestringnullable≤ 80 chars
      • timestampstringnullable≤ 64 chars
      • messagesarray of ChatMessage
        7 child fields
        • roleenumrequired

          "system""user""assistant""tool"

        • contentstring or array of map of anynullable
          One of 2 shapes
          1. string
          2. array of map of any
        • reasoning_contentstring
        • tool_callsarray of map of any
        • tool_call_idstring
        • namestring
        • trainboolean
      • toolsarray of map of any
      • inputTrajectoryInput
        5 child fields
        • messagesarray of ChatMessage
          7 child fields
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
        • toolsarray of map of any
        • mediaarray of map of any
        • featuresmap of any
        • payloadany
      • outputTrajectoryOutputnullable
      • promptstring or array of ChatMessage
        One of 2 shapes
        1. string
        2. array of ChatMessage
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
      • completionstring or array of ChatMessage
        One of 2 shapes
        1. string
        2. array of ChatMessage
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
      • chosenstring or array of ChatMessage
        One of 2 shapes
        1. string
        2. array of ChatMessage
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
      • rejectedstring or array of ChatMessage
        One of 2 shapes
        1. string
        2. array of ChatMessage
          • roleenumrequired

            "system""user""assistant""tool"

          • contentstring or array of map of anynullable
            One of 2 shapes
            1. string
            2. array of map of any
          • reasoning_contentstring
          • tool_callsarray of map of any
          • tool_call_idstring
          • namestring
          • trainboolean
      • querystring
      • positivestring
      • negativesarray of string
      • stateany
      • questionsmap of any
      • expected_outputany
      • scoresmap of number
      • metricsmap of number
      • metadatamap of any
  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
failures = client.evals.failures("eval_3f9c0a1b2c3d4e5f60718293", threshold=0.8)
hard = failures.to_dataset("support-hard")  # mine them into a new dataset
Response 200 OKGenerated from the schema
JSON
{
  "eval_id": "obj_3f9c0a1b2c3d4e5f60718293",
  "data": [
    {
      "task_id": "obj_3f9c0a1b2c3d4e5f60718293",
      "model": "qwen/qwen3-8b",
      "score": 0,
      "passed": false,
      "sample_scores": [
        0
      ],
      "judge_model": "string",
      "record": {
        "schema": "grad.trajectory/1",
        "id": "obj_3f9c0a1b2c3d4e5f60718293",
        "session_id": "obj_3f9c0a1b2c3d4e5f60718293",
        "group_id": "obj_3f9c0a1b2c3d4e5f60718293",
        "role": "chosen",
        "source": "string",
        "timestamp": "string",
        "messages": [
          {}
        ],
        "tools": [
          {}
        ],
        "input": {
          "messages": [],
          "tools": [],
          "media": [],
          "features": {},
          "payload": null
        },
        "output": {
          "turns": [],
          "payload": null
        },
        "prompt": "string",
        "completion": "string",
        "chosen": "string",
        "rejected": "string",
        "query": "string",
        "positive": "string",
        "negatives": [
          "string"
        ],
        "state": null,
        "questions": {},
        "expected_output": null,
        "scores": {},
        "metrics": {},
        "metadata": {}
      }
    }
  ],
  "next_cursor": "string"
}

Cancel a queued, running, awaiting_outputs or awaiting_scores evaluation#

POST/v1/evals/{id}/cancel

An eval that is already cancelled is returned as it is, so a retried cancel is a no-op.

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Returns

200 EvalRun Cancelled evaluation run.

29 fields
  • idstringrequired

    Eval id (eval_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • statusEvalStatusrequired

    "queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"

  • modeEvalModerequired

    eval generates outputs from models; score (dataset.score()) grades each record's own output (model record) and writes the scores to the dataset's next version; env is a client-driven agent evaluation whose rollouts post outputs via /outputs and /complete.

    "eval""score""env"

  • modelsarray of stringrequired

    The models evaluated: catalog ids, artifacts (name@version), models the inference endpoint serves, or policy labels in env mode.

  • baselinestringrequirednullable

    The model the summary compares the others with (vs_baseline); null for none.

  • baseline_evalEvalBaselineRefrequirednullable
  • envEvalEnvConfigrequirednullable
  • gateEvalGateResultrequirednullable
  • task_sourceobjectrequired
    3 child fields
    • kind"dataset"required

      "dataset"

    • datasetstringrequired
    • versionintegerrequired≥ 1
  • rubricarray of EvalRubricItemrequired
    9 child fields
    • namestringrequired≤ 80 chars

      Matches ^[A-Za-z0-9_.:-]+$

    • kindenumrequired

      "regex""validator""code""judge"

    • weightnumber> 0default 1
    • patternstring≤ 256 chars
    • flagsstring≤ 4 chars

      Matches ^[imsu]*$

    • validatorenum

      "json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"

    • modelstring≤ 160 chars
    • promptstring≤ 8000 chars
    • runtime"local"

      Code scorers always run in the SDK process (local); the eval waits in awaiting_scores until the SDK posts their scores.

      "local"

  • samplesintegerrequired≥ 1

    Answers generated per task and model.

  • temperaturenumberrequired0–2

    Sampling temperature of the model calls.

  • max_tokensintegerrequired≥ 1

    The most tokens each answer may have.

  • pass_thresholdnumberrequired0–1

    Score at or above which a task passes.

  • judge_modelsarray of stringrequired

    The judge models the rubric calls.

  • local_scorersarray of stringrequired

    Code scorers that run in the SDK process; the eval waits in awaiting_scores until they post their scores.

  • progressobjectrequired
    3 child fields
    • total_outputsintegerrequired≥ 0
    • generatedintegerrequired≥ 0
    • pending_local_scoresintegerrequired≥ 0
  • summaryarray of EvalModelSummaryrequired
    12 child fields
    • modelstringrequired

      The model this summary is for.

    • overallnumberrequired

      Mean task score (each task's score averages its samples).

    • ci_lownumberrequired

      Lower bound of the bootstrap 95% confidence interval on overall.

    • ci_highnumberrequired

      Upper bound of the bootstrap 95% confidence interval on overall.

    • pass_at_kmap of numberrequired

      Unbiased pass@k per k (pass@1, ...): the chance that one of k samples scores at least pass_threshold.

    • vs_baselineobjectrequirednullable

      The mean paired difference from the baseline over the tasks both answered, with a bootstrap 95% interval; null for the baseline itself or without one.

      3 child fields
      • deltanumberrequired
      • ci_lownumberrequired
      • ci_highnumberrequired
    • tasksintegerrequired≥ 0

      Tasks this model answered.

    • errorsintegerrequired≥ 0

      Model or judge calls that failed.

    • tokens_per_tasknumberrequired

      Mean tokens per task.

    • cost_per_1k_tasks_usdnumberrequirednullable

      Cost per 1,000 tasks in USD; null when the model has no price.

    • by_scorermap of number

      Mean score per rubric scorer over outputs carrying that scorer.

    • mean_turnsnumbernullable

      Mean agent turns per rollout (present when outputs include trajectories with turns).

  • total_cost_usdnumberrequired≥ 0

    Cost of the model and judge calls so far, in USD.

  • scored_dataset_versionintegerrequirednullable≥ 1

    Scoring jobs: the dataset version holding the new scores (the source version when every record was already scored); null until completed.

  • errorstringrequirednullable

    Why the eval failed; null otherwise.

  • waiting_reasonenumrequirednullable

    While running: the eval's model calls are waiting for capacity (a serving pool at zero that has not woken yet), for a rate limit (a full eval lane), or for an inference endpoint that is down. The worker keeps its lease and retries; this is not counted as a failed attempt. null otherwise.

    "capacity_unavailable""rate_limited""inference_unavailable"null

  • last_output_atstring (date-time)requirednullable

    When the last client output was received in env mode; null otherwise.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required
  • completed_atstring (date-time)requirednullable

    When the eval reached a final status; null until then.

  • console_urlstringnullable

    Web console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
ev = client.evals.cancel("eval_3f9c0a1b2c3d4e5f60718293")
Response 200 OKGenerated from the schema
JSON
{
  "id": "eval_3f9c0a1b2c3d4e5f60718293",
  "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
  "name": "support-prod",
  "status": "queued",
  "mode": "eval",
  "models": [
    "string"
  ],
  "baseline": "string",
  "baseline_eval": {
    "id": "obj_3f9c0a1b2c3d4e5f60718293",
    "model": "qwen/qwen3-8b"
  },
  "env": {
    "name": "support-prod",
    "max_turns": 1,
    "fingerprint": "string"
  },
  "gate": {
    "max_drop": 0,
    "rule": "significant",
    "passed": false,
    "regressed": [
      "string"
    ],
    "paired_tasks": 0,
    "min_detectable_drop": 0
  },
  "task_source": {
    "kind": "dataset",
    "dataset": "support-prod",
    "version": 1
  },
  "rubric": [
    {
      "name": "support-prod",
      "kind": "regex",
      "weight": 1,
      "pattern": "string",
      "flags": "string",
      "validator": "json",
      "model": "qwen/qwen3-8b",
      "prompt": "string",
      "runtime": "local"
    }
  ],
  "samples": 1,
  "temperature": 0,
  "max_tokens": 1,
  "pass_threshold": 0,
  "judge_models": [
    "string"
  ],
  "local_scorers": [
    "string"
  ],
  "progress": {
    "total_outputs": 0,
    "generated": 0,
    "pending_local_scores": 0
  },
  "summary": [
    {
      "model": "qwen/qwen3-8b",
      "overall": 0,
      "ci_low": 0,
      "ci_high": 0,
      "pass_at_k": {},
      "vs_baseline": {
        "delta": 0,
        "ci_low": 0,
        "ci_high": 0
      },
      "tasks": 0,
      "errors": 0,
      "tokens_per_task": 0,
      "cost_per_1k_tasks_usd": 0,
      "by_scorer": {},
      "mean_turns": 0
    }
  ],
  "total_cost_usd": 0,
  "scored_dataset_version": 1,
  "error": "…",
  "waiting_reason": "capacity_unavailable",
  "last_output_at": "2026-11-28T09:30:00.000Z",
  "created_at": "2026-11-28T09:30:00.000Z",
  "updated_at": "2026-11-28T09:30:00.000Z",
  "completed_at": "2026-11-28T09:30:00.000Z",
  "console_url": "string"
}

Integrations#

Connect a provider#

POST/v1/integrations

Credentials are write-only.

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body CreateIntegrationRequest

  • providerIntegrationProviderrequired

    "langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"

  • namestring≤ 64 chars

    Unique per workspace; how sources, imports and loggers refer to it. Default: the provider (langfuse), then langfuse-2, langfuse-3, ...

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • hoststring≤ 2048 chars

    The provider's base URL (https). Defaults to its public host: https://cloud.langfuse.com, https://api.smith.langchain.com, https://api.braintrust.dev, https://us.posthog.com, https://huggingface.co, https://api.wandb.ai. Required for phoenix (your Phoenix Cloud space URL or self-hosted Phoenix) and mlflow (the tracking URI). Credentials are only ever sent to this host.

  • credentialsIntegrationCredentials

    Write-only: stored encrypted and never returned. Each provider takes its own fields: langfuse public_key + secret_key; langsmith, braintrust and wandb api_key; posthog personal_api_key; phoenix api_key (optional); huggingface token; mlflow token (optional). Any other field is 422 integration_credentials_invalid.

    5 child fields
    • public_keystring

      Langfuse public key (pk-lf-...).

    • secret_keystring

      Langfuse secret key (sk-lf-...).

    • api_keystring

      LangSmith, Braintrust or W&B API key; Phoenix API key (optional).

    • personal_api_keystring

      PostHog personal API key (phx_...).

    • tokenstring

      Hugging Face access token; MLflow tracking-server bearer token (optional).

Returns

201 Integration The new integration (pending).

11 fields
  • idstringrequired

    Opaque id: int_… on a self-hosted server, a UUID on Gradiated Cloud. Never parse it.

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • providerIntegrationProviderrequired

    "langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"

  • hoststringrequired

    Where its credentials go: the provider's base URL.

  • statusIntegrationStatusrequired

    pending: not verified yet (created or changed since its last connection test). active: the last connection test passed. failing: it failed (last_error says why).

    "pending""active""failing"

  • last_errorstringrequirednullable

    Why the last connection test failed (null otherwise).

  • last_checked_atstring (date-time)requirednullable

    When the connection was last tested.

  • used_byIntegrationUsagerequired
    4 child fields
    • countintegerrequired≥ 0

      Everything that uses the integration: sources, plus imports and runs that have not finished. At most 100 of each kind are listed.

    • sourcesarray of objectrequired

      Sources syncing through it.

      2 child fields
      • idstringrequired
      • datasetstringrequired
    • importsarray of objectrequired

      Queued or running HF imports.

      1 child fields
      • idstringrequired
    • runsarray of objectrequired

      Queued or running runs logging through it.

      2 child fields
      • idstringrequired
      • namestringrequired
  • created_atstring (date-time)required
  • updated_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 501 503

Request
Python
import os
from grad import Grad

client = Grad()
integration = client.integrations.create(
    "langfuse",
    credentials={
        "public_key": os.environ["LANGFUSE_PUBLIC_KEY"],
        "secret_key": os.environ["LANGFUSE_SECRET_KEY"],
    },
)
Response 201 CreatedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "int_9b9df9563dcef32c3fdff892",
  "workspace_id": "ws_e2e",
  "name": "langfuse",
  "provider": "langfuse",
  "host": "https://cloud.langfuse.com",
  "status": "untested",
  "last_error": null,
  "last_checked_at": null,
  "used_by": {
    "count": 0,
    "sources": [],
    "imports": [],
    "runs": []
  },
  "created_at": "2026-12-02T15:48:59.946Z",
  "updated_at": "2026-12-02T15:48:59.946Z"
}

List integrations#

GET/v1/integrations

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • providerenum

    "langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"

Returns

200 object Integrations.

2 fields
  • dataarray of Integrationrequired
    11 child fields
    • idstringrequired

      Opaque id: int_… on a self-hosted server, a UUID on Gradiated Cloud. Never parse it.

    • workspace_idstringrequired
    • namestringrequired≤ 64 chars

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • providerIntegrationProviderrequired

      "langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"

    • hoststringrequired

      Where its credentials go: the provider's base URL.

    • statusIntegrationStatusrequired

      pending: not verified yet (created or changed since its last connection test). active: the last connection test passed. failing: it failed (last_error says why).

      "pending""active""failing"

    • last_errorstringrequirednullable

      Why the last connection test failed (null otherwise).

    • last_checked_atstring (date-time)requirednullable

      When the connection was last tested.

    • used_byIntegrationUsagerequired
      4 child fields
      • countintegerrequired≥ 0

        Everything that uses the integration: sources, plus imports and runs that have not finished. At most 100 of each kind are listed.

      • sourcesarray of objectrequired

        Sources syncing through it.

        2 child fields
        • idstringrequired
        • datasetstringrequired
      • importsarray of objectrequired

        Queued or running HF imports.

        1 child fields
        • idstringrequired
      • runsarray of objectrequired

        Queued or running runs logging through it.

        2 child fields
        • idstringrequired
        • namestringrequired
    • created_atstring (date-time)required
    • updated_atstring (date-time)required
  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for integration in client.integrations.list():
    print(integration.name, integration.provider, integration.status)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "data": [
    {
      "id": "int_9b9df9563dcef32c3fdff892",
      "workspace_id": "ws_e2e",
      "name": "langfuse",
      "provider": "langfuse",
      "host": "https://cloud.langfuse.com",
      "status": "untested",
      "last_error": null,
      "last_checked_at": null,
      "used_by": {
        "count": 1,
        "sources": [
          {
            "id": "src_1456303e7610ad38945c8487",
            "dataset": "support-prod"
          }
        ],
        "imports": [],
        "runs": []
      },
      "created_at": "2026-12-02T15:48:59.946Z",
      "updated_at": "2026-12-02T15:48:59.968Z"
    }
  ],
  "next_cursor": null
}

Get an integration#

GET/v1/integrations/{name}

Never its credentials.

Path parameters

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Returns

200 Integration The integration.

11 fields
  • idstringrequired

    Opaque id: int_… on a self-hosted server, a UUID on Gradiated Cloud. Never parse it.

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • providerIntegrationProviderrequired

    "langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"

  • hoststringrequired

    Where its credentials go: the provider's base URL.

  • statusIntegrationStatusrequired

    pending: not verified yet (created or changed since its last connection test). active: the last connection test passed. failing: it failed (last_error says why).

    "pending""active""failing"

  • last_errorstringrequirednullable

    Why the last connection test failed (null otherwise).

  • last_checked_atstring (date-time)requirednullable

    When the connection was last tested.

  • used_byIntegrationUsagerequired
    4 child fields
    • countintegerrequired≥ 0

      Everything that uses the integration: sources, plus imports and runs that have not finished. At most 100 of each kind are listed.

    • sourcesarray of objectrequired

      Sources syncing through it.

      2 child fields
      • idstringrequired
      • datasetstringrequired
    • importsarray of objectrequired

      Queued or running HF imports.

      1 child fields
      • idstringrequired
    • runsarray of objectrequired

      Queued or running runs logging through it.

      2 child fields
      • idstringrequired
      • namestringrequired
  • created_atstring (date-time)required
  • updated_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
integration = client.integrations.get("langfuse")  # never its credentials
print(integration.status, integration.used_by)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "int_9b9df9563dcef32c3fdff892",
  "workspace_id": "ws_e2e",
  "name": "langfuse",
  "provider": "langfuse",
  "host": "https://cloud.langfuse.com",
  "status": "untested",
  "last_error": null,
  "last_checked_at": null,
  "used_by": {
    "count": 1,
    "sources": [
      {
        "id": "src_1456303e7610ad38945c8487",
        "dataset": "support-prod"
      }
    ],
    "imports": [],
    "runs": []
  },
  "created_at": "2026-12-02T15:48:59.946Z",
  "updated_at": "2026-12-02T15:48:59.968Z"
}

Rotate credentials or change the host#

PATCH/v1/integrations/{name}

Resumes paused sources that use it.

Path parameters

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Body UpdateIntegrationRequest

  • hoststringnullable≤ 2048 chars

    The provider's base URL (https). Defaults to its public host: https://cloud.langfuse.com, https://api.smith.langchain.com, https://api.braintrust.dev, https://us.posthog.com, https://huggingface.co, https://api.wandb.ai. Required for phoenix (your Phoenix Cloud space URL or self-hosted Phoenix) and mlflow (the tracking URI). Credentials are only ever sent to this host. Null resets it to the provider's public host. Changing the host of an integration that holds credentials needs every credential again, in this request.

  • credentialsIntegrationCredentials

    Write-only: stored encrypted and never returned. Each provider takes its own fields: langfuse public_key + secret_key; langsmith, braintrust and wandb api_key; posthog personal_api_key; phoenix api_key (optional); huggingface token; mlflow token (optional). Any other field is 422 integration_credentials_invalid.

    5 child fields
    • public_keystring

      Langfuse public key (pk-lf-...).

    • secret_keystring

      Langfuse secret key (sk-lf-...).

    • api_keystring

      LangSmith, Braintrust or W&B API key; Phoenix API key (optional).

    • personal_api_keystring

      PostHog personal API key (phx_...).

    • tokenstring

      Hugging Face access token; MLflow tracking-server bearer token (optional).

Returns

200 Integration The updated integration.

11 fields
  • idstringrequired

    Opaque id: int_… on a self-hosted server, a UUID on Gradiated Cloud. Never parse it.

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • providerIntegrationProviderrequired

    "langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"

  • hoststringrequired

    Where its credentials go: the provider's base URL.

  • statusIntegrationStatusrequired

    pending: not verified yet (created or changed since its last connection test). active: the last connection test passed. failing: it failed (last_error says why).

    "pending""active""failing"

  • last_errorstringrequirednullable

    Why the last connection test failed (null otherwise).

  • last_checked_atstring (date-time)requirednullable

    When the connection was last tested.

  • used_byIntegrationUsagerequired
    4 child fields
    • countintegerrequired≥ 0

      Everything that uses the integration: sources, plus imports and runs that have not finished. At most 100 of each kind are listed.

    • sourcesarray of objectrequired

      Sources syncing through it.

      2 child fields
      • idstringrequired
      • datasetstringrequired
    • importsarray of objectrequired

      Queued or running HF imports.

      1 child fields
      • idstringrequired
    • runsarray of objectrequired

      Queued or running runs logging through it.

      2 child fields
      • idstringrequired
      • namestringrequired
  • created_atstring (date-time)required
  • updated_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 501 503

Request
Python
import os
from grad import Grad

client = Grad()
integration = client.integrations.update(
    "langfuse", credentials={"secret_key": os.environ["LANGFUSE_SECRET_KEY"]}
)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "int_9b9df9563dcef32c3fdff892",
  "workspace_id": "ws_e2e",
  "name": "langfuse",
  "provider": "langfuse",
  "host": "https://cloud.langfuse.com",
  "status": "untested",
  "last_error": null,
  "last_checked_at": null,
  "used_by": {
    "count": 0,
    "sources": [],
    "imports": [],
    "runs": []
  },
  "created_at": "2026-12-02T15:48:59.946Z",
  "updated_at": "2026-12-02T15:48:59.968Z"
}

Delete an integration#

DELETE/v1/integrations/{name}

409 integration_in_use, with used_by, while anything uses it.

Path parameters

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Returns

204 Deleted.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
client.integrations.delete("langfuse")
Response 204 No Content

Deleted.

Test the connection: one cheap authenticated call to the provider; updates status#

POST/v1/integrations/{name}/test

Path parameters

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Returns

200 Integration The integration with the test's status (ok or failing, and last_error).

11 fields
  • idstringrequired

    Opaque id: int_… on a self-hosted server, a UUID on Gradiated Cloud. Never parse it.

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • providerIntegrationProviderrequired

    "langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"

  • hoststringrequired

    Where its credentials go: the provider's base URL.

  • statusIntegrationStatusrequired

    pending: not verified yet (created or changed since its last connection test). active: the last connection test passed. failing: it failed (last_error says why).

    "pending""active""failing"

  • last_errorstringrequirednullable

    Why the last connection test failed (null otherwise).

  • last_checked_atstring (date-time)requirednullable

    When the connection was last tested.

  • used_byIntegrationUsagerequired
    4 child fields
    • countintegerrequired≥ 0

      Everything that uses the integration: sources, plus imports and runs that have not finished. At most 100 of each kind are listed.

    • sourcesarray of objectrequired

      Sources syncing through it.

      2 child fields
      • idstringrequired
      • datasetstringrequired
    • importsarray of objectrequired

      Queued or running HF imports.

      1 child fields
      • idstringrequired
    • runsarray of objectrequired

      Queued or running runs logging through it.

      2 child fields
      • idstringrequired
      • namestringrequired
  • created_atstring (date-time)required
  • updated_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 501 503

Request
Python
from grad import Grad

client = Grad()
integration = client.integrations.test("langfuse")
print(integration.status, integration.last_error)
Response 200 OKGenerated from the schema
JSON
{
  "id": "obj_3f9c0a1b2c3d4e5f60718293",
  "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
  "name": "support-prod",
  "provider": "langfuse",
  "host": "string",
  "status": "pending",
  "last_error": "string",
  "last_checked_at": "2026-11-28T09:30:00.000Z",
  "used_by": {
    "count": 0,
    "sources": [
      {
        "id": "obj_3f9c0a1b2c3d4e5f60718293",
        "dataset": "support-prod"
      }
    ],
    "imports": [
      {
        "id": "obj_3f9c0a1b2c3d4e5f60718293"
      }
    ],
    "runs": [
      {
        "id": "obj_3f9c0a1b2c3d4e5f60718293",
        "name": "support-prod"
      }
    ]
  },
  "created_at": "2026-11-28T09:30:00.000Z",
  "updated_at": "2026-11-28T09:30:00.000Z"
}

Sources#

Connect an observability provider to a dataset#

POST/v1/datasets/{name}/sources

Path parameters

  • namestringrequired≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body CreateSourceRequest

  • providerSourceProviderrequired
    4 child fields
    • kindstring≤ 40 chars

      One of langfuse, langsmith, braintrust, posthog, phoenix, gradiated; anything else is 422 source_provider_unsupported. Optional with integration (the integration's provider); one of the two is required.

    • integrationstring≤ 64 chars

      Name of the integration to read through (its host and credentials). Optional when the workspace has exactly one integration of this provider; with several, 422 integration_ambiguous lists them. Not used by 'gradiated'.

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • projectstringnullable≤ 200 chars

      The provider project to read. Required for braintrust (project id or name) and posthog (numeric project id); optional elsewhere (LangSmith project, Phoenix project).

    • filtersmap of any

      Which traces to sync; a trace must match every key. Values are a string or a list (any of which matches) unless noted: tags (list: every tag), environment, model, version, release, name (trace name or route), user_id, session_id, metadata ({key: value}, each equal), from/to (ISO 8601: the trace started in [from, to)), has_feedback (true: a score or a correction) and min_score (a number every score must reach, or {name: number}). Score filters are judged on the merged dataset, so feedback that arrives later still counts. LangSmith also takes filter (a LangSmith filter expression, AND-ed); gradiated takes models, tasks and versions. Any other key is 422 source_filter_unsupported. The response holds the effective filters (single values as lists).

  • schedulestringnullable≤ 120 chars

    Five-field cron in UTC (*/15 * * * *); minute resolution, so it fires at most once a minute (a seconds field is rejected). Leave it out to sync only on request.

  • sample_ratenumber> 0≤ 1

    The share of traces to sync, chosen by a hash of the trace id: re-syncs keep the same sample, and a trace's feedback follows it. Default 1.

  • max_records_per_syncintegernullable1–1000000000

    At most this many new traces per sync; the rest are not synced (the sync's drop reasons count them). Feedback on traces already synced always lands. Null: no cap.

  • max_records_per_dayintegernullable1–1000000000

    At most this many new traces per UTC day; the rest are not synced (the sync's drop reasons count them). Feedback on traces already synced always lands. Null: no cap.

  • version_intervalinteger0–604800

    Seconds between the dataset versions scheduled syncs commit (default 900). A scheduled sync may fetch every minute; its parts wait, staged, until the interval has passed or enough records are waiting, so a busy source doesn't add a version a minute. 0: every sync commits. Manual and full syncs always commit, and so does removing the schedule or the source, or the source pausing.

Returns

201 Source Created source.

22 fields
  • idstringrequired

    Source id (src_ and 24 hex characters).

  • workspace_idstringrequired
  • datasetstringrequired≤ 64 chars

    The dataset the source syncs into (one per source).

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • providerobjectrequired
    4 child fields
    • kindenumrequired

      "langfuse""langsmith""braintrust""posthog""phoenix""gradiated"

    • integrationstringrequirednullable

      The integration it reads through (null for 'gradiated').

    • projectstringrequirednullable
    • filtersmap of anyrequired

      The effective filters: validated, with single values as lists.

  • schedulestringrequirednullable

    Five-field UTC cron; null when the source syncs only on request.

  • sample_ratenumberrequired

    The share of traces synced (1: all).

  • max_records_per_syncintegerrequirednullable

    At most this many new traces per sync; null for no cap.

  • max_records_per_dayintegerrequirednullable

    At most this many new traces per UTC day; null for no cap.

  • records_todayintegerrequired≥ 0

    New traces synced so far this UTC day (what max_records_per_day counts).

  • version_intervalintegerrequired≥ 0

    Seconds between the dataset versions scheduled syncs commit (0: every sync).

  • pending_recordsintegerrequired≥ 0

    Records scheduled syncs fetched that wait for the next dataset version.

  • next_sync_atstring (date-time)requirednullable

    When the schedule fires next (null without a schedule or while paused). After a failed sync the schedule backs off: twice its interval per consecutive failure, at most an hour.

  • statusenumrequired

    paused after 10 consecutive failed syncs: the schedule stops firing. A manual sync, or rotating its integration's credentials, resumes it.

    "active""paused"

  • paused_reasonstringrequirednullable

    Why the source is paused (null while active).

  • last_errorstringrequirednullable

    The error of the last failed sync (provider keys redacted); cleared by a successful sync.

  • last_error_atstring (date-time)requirednullable

    When the last sync failed; null if none has.

  • consecutive_failuresintegerrequired≥ 0

    Failed syncs since the last successful one.

  • pending_fullbooleanrequired

    A full sync was requested while another sync ran; it is queued as soon as that one ends.

  • last_synced_atstring (date-time)requirednullable

    When the last successful sync finished.

  • last_syncSourceSyncrequirednullable

    The most recent sync, running or finished.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 501 503

Request
Python
from grad import Grad

client = Grad()
source = client.datasets.get("support-prod").add_source(
    integration="langfuse",
    filters={"environment": "production", "has_feedback": True},
    schedule="*/15 * * * *",
)
Response 201 CreatedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "src_1456303e7610ad38945c8487",
  "workspace_id": "ws_e2e",
  "dataset": "support-prod",
  "provider": {
    "kind": "langfuse",
    "integration": "langfuse",
    "project": null,
    "filters": {
      "environment": [
        "production"
      ],
      "has_feedback": true
    }
  },
  "schedule": "*/15 * * * *",
  "sample_rate": 1,
  "max_records_per_sync": null,
  "max_records_per_day": null,
  "records_today": 0,
  "version_interval": 900,
  "pending_records": 0,
  "next_sync_at": "2026-12-02T16:00:00.000Z",
  "status": "active",
  "paused_reason": null,
  "last_error": null,
  "last_error_at": null,
  "consecutive_failures": 0,
  "pending_full": false,
  "last_synced_at": null,
  "last_sync": null,
  "created_at": "2026-12-02T15:48:59.980Z",
  "updated_at": "2026-12-02T15:48:59.980Z"
}

List sources (newest first), optionally for one dataset#

GET/v1/sources

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • datasetstring≤ 64 chars

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

Returns

200 object Sources.

2 fields
  • dataarray of Sourcerequired
    22 child fields
    • idstringrequired

      Source id (src_ and 24 hex characters).

    • workspace_idstringrequired
    • datasetstringrequired≤ 64 chars

      The dataset the source syncs into (one per source).

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • providerobjectrequired
      4 child fields
      • kindenumrequired

        "langfuse""langsmith""braintrust""posthog""phoenix""gradiated"

      • integrationstringrequirednullable

        The integration it reads through (null for 'gradiated').

      • projectstringrequirednullable
      • filtersmap of anyrequired

        The effective filters: validated, with single values as lists.

    • schedulestringrequirednullable

      Five-field UTC cron; null when the source syncs only on request.

    • sample_ratenumberrequired

      The share of traces synced (1: all).

    • max_records_per_syncintegerrequirednullable

      At most this many new traces per sync; null for no cap.

    • max_records_per_dayintegerrequirednullable

      At most this many new traces per UTC day; null for no cap.

    • records_todayintegerrequired≥ 0

      New traces synced so far this UTC day (what max_records_per_day counts).

    • version_intervalintegerrequired≥ 0

      Seconds between the dataset versions scheduled syncs commit (0: every sync).

    • pending_recordsintegerrequired≥ 0

      Records scheduled syncs fetched that wait for the next dataset version.

    • next_sync_atstring (date-time)requirednullable

      When the schedule fires next (null without a schedule or while paused). After a failed sync the schedule backs off: twice its interval per consecutive failure, at most an hour.

    • statusenumrequired

      paused after 10 consecutive failed syncs: the schedule stops firing. A manual sync, or rotating its integration's credentials, resumes it.

      "active""paused"

    • paused_reasonstringrequirednullable

      Why the source is paused (null while active).

    • last_errorstringrequirednullable

      The error of the last failed sync (provider keys redacted); cleared by a successful sync.

    • last_error_atstring (date-time)requirednullable

      When the last sync failed; null if none has.

    • consecutive_failuresintegerrequired≥ 0

      Failed syncs since the last successful one.

    • pending_fullbooleanrequired

      A full sync was requested while another sync ran; it is queued as soon as that one ends.

    • last_synced_atstring (date-time)requirednullable

      When the last successful sync finished.

    • last_syncSourceSyncrequirednullable

      The most recent sync, running or finished.

    • created_atstring (date-time)required
    • updated_atstring (date-time)required
  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for source in client.sources.list(dataset="support-prod"):
    print(source.id, source.status, source.last_error)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "data": [
    {
      "id": "src_1456303e7610ad38945c8487",
      "workspace_id": "ws_e2e",
      "dataset": "support-prod",
      "provider": {
        "kind": "langfuse",
        "integration": "langfuse",
        "project": null,
        "filters": {
          "environment": [
            "production"
          ],
          "has_feedback": true
        }
      },
      "schedule": "*/15 * * * *",
      "sample_rate": 0.5,
      "max_records_per_sync": null,
      "max_records_per_day": null,
      "records_today": 0,
      "version_interval": 900,
      "pending_records": 0,
      "next_sync_at": "2026-12-02T16:00:00.000Z",
      "status": "active",
      "paused_reason": null,
      "last_error": null,
      "last_error_at": null,
      "consecutive_failures": 0,
      "pending_full": false,
      "last_synced_at": null,
      "last_sync": {
        "import_id": "imp_2fa783bc75ee294eef1791f6",
        "status": "running",
        "full": false,
        "dataset_version": null,
        "error": null,
        "created_at": "2026-12-02T15:48:59.998Z",
        "finished_at": null
      },
      "created_at": "2026-12-02T15:48:59.980Z",
      "updated_at": "2026-12-02T15:49:00.001Z"
    }
  ],
  "next_cursor": null
}

Get a source and its latest sync#

GET/v1/sources/{id}

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 Source Source.

22 fields
  • idstringrequired

    Source id (src_ and 24 hex characters).

  • workspace_idstringrequired
  • datasetstringrequired≤ 64 chars

    The dataset the source syncs into (one per source).

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • providerobjectrequired
    4 child fields
    • kindenumrequired

      "langfuse""langsmith""braintrust""posthog""phoenix""gradiated"

    • integrationstringrequirednullable

      The integration it reads through (null for 'gradiated').

    • projectstringrequirednullable
    • filtersmap of anyrequired

      The effective filters: validated, with single values as lists.

  • schedulestringrequirednullable

    Five-field UTC cron; null when the source syncs only on request.

  • sample_ratenumberrequired

    The share of traces synced (1: all).

  • max_records_per_syncintegerrequirednullable

    At most this many new traces per sync; null for no cap.

  • max_records_per_dayintegerrequirednullable

    At most this many new traces per UTC day; null for no cap.

  • records_todayintegerrequired≥ 0

    New traces synced so far this UTC day (what max_records_per_day counts).

  • version_intervalintegerrequired≥ 0

    Seconds between the dataset versions scheduled syncs commit (0: every sync).

  • pending_recordsintegerrequired≥ 0

    Records scheduled syncs fetched that wait for the next dataset version.

  • next_sync_atstring (date-time)requirednullable

    When the schedule fires next (null without a schedule or while paused). After a failed sync the schedule backs off: twice its interval per consecutive failure, at most an hour.

  • statusenumrequired

    paused after 10 consecutive failed syncs: the schedule stops firing. A manual sync, or rotating its integration's credentials, resumes it.

    "active""paused"

  • paused_reasonstringrequirednullable

    Why the source is paused (null while active).

  • last_errorstringrequirednullable

    The error of the last failed sync (provider keys redacted); cleared by a successful sync.

  • last_error_atstring (date-time)requirednullable

    When the last sync failed; null if none has.

  • consecutive_failuresintegerrequired≥ 0

    Failed syncs since the last successful one.

  • pending_fullbooleanrequired

    A full sync was requested while another sync ran; it is queued as soon as that one ends.

  • last_synced_atstring (date-time)requirednullable

    When the last successful sync finished.

  • last_syncSourceSyncrequirednullable

    The most recent sync, running or finished.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
source = client.sources.get("src_3f9c0a1b2c3d4e5f60718293")
print(source.status, source.last_synced_at)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "src_1456303e7610ad38945c8487",
  "workspace_id": "ws_e2e",
  "dataset": "support-prod",
  "provider": {
    "kind": "langfuse",
    "integration": "langfuse",
    "project": null,
    "filters": {
      "environment": [
        "production"
      ],
      "has_feedback": true
    }
  },
  "schedule": "*/15 * * * *",
  "sample_rate": 0.5,
  "max_records_per_sync": null,
  "max_records_per_day": null,
  "records_today": 0,
  "version_interval": 900,
  "pending_records": 0,
  "next_sync_at": "2026-12-02T16:00:00.000Z",
  "status": "active",
  "paused_reason": null,
  "last_error": null,
  "last_error_at": null,
  "consecutive_failures": 0,
  "pending_full": false,
  "last_synced_at": null,
  "last_sync": {
    "import_id": "imp_2fa783bc75ee294eef1791f6",
    "status": "running",
    "full": false,
    "dataset_version": null,
    "error": null,
    "created_at": "2026-12-02T15:48:59.998Z",
    "finished_at": null
  },
  "created_at": "2026-12-02T15:48:59.980Z",
  "updated_at": "2026-12-02T15:49:00.001Z"
}

Change a source's filters, sampling, record caps or schedule#

PATCH/v1/sources/{id}

From its next sync.

Path parameters

  • idstringrequired≤ 200 chars

Body UpdateSourceRequest

  • filtersmap of any

    Replaces the source's filters ({} clears them). Which traces to sync; a trace must match every key. Values are a string or a list (any of which matches) unless noted: tags (list: every tag), environment, model, version, release, name (trace name or route), user_id, session_id, metadata ({key: value}, each equal), from/to (ISO 8601: the trace started in [from, to)), has_feedback (true: a score or a correction) and min_score (a number every score must reach, or {name: number}). Score filters are judged on the merged dataset, so feedback that arrives later still counts. LangSmith also takes filter (a LangSmith filter expression, AND-ed); gradiated takes models, tasks and versions. Any other key is 422 source_filter_unsupported. The response holds the effective filters (single values as lists).

  • schedulestringnullable≤ 120 chars

    Five-field cron in UTC (*/15 * * * *); minute resolution, so it fires at most once a minute (a seconds field is rejected). Leave it out to sync only on request.

  • sample_ratenumber> 0≤ 1

    The share of traces to sync, chosen by a hash of the trace id: re-syncs keep the same sample, and a trace's feedback follows it. Default 1.

  • max_records_per_syncintegernullable1–1000000000

    At most this many new traces per sync; the rest are not synced (the sync's drop reasons count them). Feedback on traces already synced always lands. Null: no cap.

  • max_records_per_dayintegernullable1–1000000000

    At most this many new traces per UTC day; the rest are not synced (the sync's drop reasons count them). Feedback on traces already synced always lands. Null: no cap.

  • version_intervalinteger0–604800

    Seconds between the dataset versions scheduled syncs commit (default 900). A scheduled sync may fetch every minute; its parts wait, staged, until the interval has passed or enough records are waiting, so a busy source doesn't add a version a minute. 0: every sync commits. Manual and full syncs always commit, and so does removing the schedule or the source, or the source pausing.

Returns

200 Source The updated source.

22 fields
  • idstringrequired

    Source id (src_ and 24 hex characters).

  • workspace_idstringrequired
  • datasetstringrequired≤ 64 chars

    The dataset the source syncs into (one per source).

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • providerobjectrequired
    4 child fields
    • kindenumrequired

      "langfuse""langsmith""braintrust""posthog""phoenix""gradiated"

    • integrationstringrequirednullable

      The integration it reads through (null for 'gradiated').

    • projectstringrequirednullable
    • filtersmap of anyrequired

      The effective filters: validated, with single values as lists.

  • schedulestringrequirednullable

    Five-field UTC cron; null when the source syncs only on request.

  • sample_ratenumberrequired

    The share of traces synced (1: all).

  • max_records_per_syncintegerrequirednullable

    At most this many new traces per sync; null for no cap.

  • max_records_per_dayintegerrequirednullable

    At most this many new traces per UTC day; null for no cap.

  • records_todayintegerrequired≥ 0

    New traces synced so far this UTC day (what max_records_per_day counts).

  • version_intervalintegerrequired≥ 0

    Seconds between the dataset versions scheduled syncs commit (0: every sync).

  • pending_recordsintegerrequired≥ 0

    Records scheduled syncs fetched that wait for the next dataset version.

  • next_sync_atstring (date-time)requirednullable

    When the schedule fires next (null without a schedule or while paused). After a failed sync the schedule backs off: twice its interval per consecutive failure, at most an hour.

  • statusenumrequired

    paused after 10 consecutive failed syncs: the schedule stops firing. A manual sync, or rotating its integration's credentials, resumes it.

    "active""paused"

  • paused_reasonstringrequirednullable

    Why the source is paused (null while active).

  • last_errorstringrequirednullable

    The error of the last failed sync (provider keys redacted); cleared by a successful sync.

  • last_error_atstring (date-time)requirednullable

    When the last sync failed; null if none has.

  • consecutive_failuresintegerrequired≥ 0

    Failed syncs since the last successful one.

  • pending_fullbooleanrequired

    A full sync was requested while another sync ran; it is queued as soon as that one ends.

  • last_synced_atstring (date-time)requirednullable

    When the last successful sync finished.

  • last_syncSourceSyncrequirednullable

    The most recent sync, running or finished.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
source = client.sources.update("src_3f9c0a1b2c3d4e5f60718293", sample_rate=0.5)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "src_1456303e7610ad38945c8487",
  "workspace_id": "ws_e2e",
  "dataset": "support-prod",
  "provider": {
    "kind": "langfuse",
    "integration": "langfuse",
    "project": null,
    "filters": {
      "environment": [
        "production"
      ],
      "has_feedback": true
    }
  },
  "schedule": "*/15 * * * *",
  "sample_rate": 0.5,
  "max_records_per_sync": null,
  "max_records_per_day": null,
  "records_today": 0,
  "version_interval": 900,
  "pending_records": 0,
  "next_sync_at": "2026-12-02T16:00:00.000Z",
  "status": "active",
  "paused_reason": null,
  "last_error": null,
  "last_error_at": null,
  "consecutive_failures": 0,
  "pending_full": false,
  "last_synced_at": null,
  "last_sync": null,
  "created_at": "2026-12-02T15:48:59.980Z",
  "updated_at": "2026-12-02T15:48:59.989Z"
}

Remove a source#

DELETE/v1/sources/{id}

Its dataset and versions stay.

Path parameters

  • idstringrequired≤ 200 chars

Returns

204 Removed.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
client.sources.delete("src_3f9c0a1b2c3d4e5f60718293")  # the dataset and its versions stay
Response 204 No Content

Removed.

Sync now: queue an import of new traces and scores#

POST/v1/sources/{id}/sync

Returns the running one if a sync is in progress.

A source starts at most one sync per minute. Within a minute of the last sync's start this returns that sync with a Retry-After header (seconds until a new one may start), so a retried or repeated call is safe. A full sync asked for while an incremental one is queued or running returns the running one and starts right after it (pending_full on the source). Syncing a paused source resumes it.

Path parameters

  • idstringrequired≤ 200 chars

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body SyncSourceRequest

  • fullbooleandefault false

    Rebuild the dataset from the provider as a new version (ignores the stored watermark).

Returns

202 ImportJob The sync's import job: new, running, or the last one when it started under a minute ago.

15 fields
  • idstringrequired

    Import job id (imp_ and 24 hex characters).

  • workspace_idstringrequired
  • datasetstringrequired≤ 64 chars

    The dataset the records go into.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • statusImportStatusrequired

    "queued""running""completed""failed"

  • sourcemap of anyrequired

    Where the records come from: an upload, a Hugging Face dataset, a benchmark, or a source sync.

  • connectorenumrequired

    The parser requested for the records (auto detects it from the file).

    "auto""grad_trajectories""openai_chat""gradiated""otel""langfuse""posthog""braintrust""langsmith"

  • attemptintegerrequired≥ 0

    Attempts started so far.

  • imported_countintegerrequired≥ 0

    Records this import added to the dataset (score updates for existing records add none).

  • dropped_countintegerrequired≥ 0

    Rows that couldn't be imported; drop_reasons says why.

  • detected_scoresarray of stringrequired

    Score names found on the imported records.

  • drop_reasonsarray of stringrequired

    Why rows were dropped, one line per row (line 12: invalid JSON), capped at 100 entries.

  • dataset_versionintegerrequirednullable≥ 0

    The dataset version this import produced; null until then.

  • errorstringrequirednullable

    Why the import failed; null otherwise.

  • created_atstring (date-time)required
  • updated_atstring (date-time)required

Errors: 400 401 403 404 409 422 500 501 503

Request
Python
from grad import Grad

client = Grad()
job = client.sources.sync("src_3f9c0a1b2c3d4e5f60718293", full=False)
print(job.wait().status)
Response 202 AcceptedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "id": "imp_2fa783bc75ee294eef1791f6",
  "workspace_id": "ws_e2e",
  "dataset": "support-prod",
  "status": "queued",
  "source": {
    "full": false,
    "kind": "provider",
    "provider": "langfuse",
    "source_id": "src_1456303e7610ad38945c8487"
  },
  "connector": "auto",
  "attempt": 0,
  "imported_count": 0,
  "dropped_count": 0,
  "detected_scores": [],
  "drop_reasons": [],
  "dataset_version": null,
  "error": null,
  "created_at": "2026-12-02T15:48:59.998Z",
  "updated_at": "2026-12-02T15:48:59.998Z"
}

Models#

List trainable base models#

GET/v1/base-models

The server catalog and price source.

Returns

200 object Trainable catalog models.

1 fields
  • dataarray of TrainableModelrequired
    13 child fields
    • idstringrequired≤ 160 chars
    • hf_repostringrequirednullable≤ 200 chars
    • familyenumrequired

      "llm""encoder"

    • modalitiesarray of Modalityrequired≥ 1 items

      Input modalities the model accepts (text, image, audio).

    • adaptersarray of enumrequired
    • recipesarray of RecipeKindrequired
    • default_forarray of RecipeKindrequired
    • price_per_million_tokens_usdnumberrequired> 0
    • max_context_tokensintegerrequired> 0
    • template_revisionstringrequired
    • calibrated_lrsmap of numberrequired
    • min_gpu_memory_gbnumberrequirednullable> 0

      GPU memory (GB) training this base needs at the recipe defaults, measured on an H100 80 GB. v0 trains on one GPU, and runs.plan refuses (422 model_exceeds_gpu_memory) a run that needs more than 80 GB. Null when unknown.

    • default_poolingenum

      Encoder models only: native pooling mode used when recipe.pool is omitted ('cls' for BGE, 'mean' for mean-pooled encoders, 'last_token' for causal-architecture encoders).

      "mean""cls""last_token"

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for model in client.models.list():
    print(model.id, model.recipes)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "data": [
    {
      "id": "qwen/qwen3-0.6b",
      "hf_repo": "Qwen/Qwen3-0.6B",
      "family": "llm",
      "modalities": [
        "text"
      ],
      "adapters": [
        "lora"
      ],
      "default_for": [
        "router"
      ],
      "price_per_million_tokens_usd": 0.15,
      "max_context_tokens": 32768,
      "template_revision": "qwen3@3",
      "calibrated_lrs": {
        "sft": 0.0008,
        "rl": 0.00005,
        "grpo": 0.00005,
        "dpo": 0.00003,
        "router": 0.0005,
        "decision": 0.0005,
        "distill": 0.0003,
        "reward": 0.00015
      },
      "min_gpu_memory_gb": 8,
      "recipes": [
        "decision",
        "distill"
      ]
    },
    {
      "id": "qwen/qwen3-1.7b",
      "hf_repo": "Qwen/Qwen3-1.7B",
      "family": "llm",
      "modalities": [
        "text"
      ],
      "adapters": [
        "lora"
      ],
      "default_for": [],
      "price_per_million_tokens_usd": 0.22,
      "max_context_tokens": 32768,
      "template_revision": "qwen3@3",
      "calibrated_lrs": {
        "sft": 0.0007,
        "rl": 0.00004,
        "grpo": 0.00004,
        "dpo": 0.00003,
        "router": 0.0005,
        "decision": 0.0004,
        "distill": 0.00025,
        "reward": 0.00012
      },
      "min_gpu_memory_gb": 12,
      "recipes": [
        "decision",
        "distill"
      ]
    }
  ]
}

Keys#

Create a scoped workspace API key#

POST/v1/keys

Trainer worker keys are platform config, not keys.

Headers

  • Idempotency-Keystring

    Up to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with Idempotent-Replayed: true; the same key with a different body is rejected with 422 idempotency_key_reused. The key is stored on the created resource, in the same transaction.

    Matches ^[\x21-\x7e]{1,255}$

Body CreateApiKeyRequest

  • namestringrequired≤ 64 chars

    Key name.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • scopesarray of ApiKeyScoperequired≥ 1 items

    The scopes the key gets (at least one); a :write scope includes its :read, and admin includes every workspace scope.

Returns

201 CreatedApiKey Created API key (secret returned once).

2 fields
  • keyApiKeyrequired
    7 child fields
    • idstringrequired

      Key id (key_ and 24 hex characters).

    • workspace_idstringrequired
    • namestringrequired≤ 64 chars

      Key name.

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • prefixstringrequired

      The first 12 characters of the secret, to tell keys apart.

    • scopesarray of ApiKeyScoperequired

      What the key may do; a :write scope includes its :read, and admin includes every workspace scope.

    • created_atstring (date-time)required
    • revoked_atstring (date-time)requirednullable

      When the key was revoked; null while it works.

  • secretstringrequired

    The full key (grad_ and 48 hex characters). Shown only in this response.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
created = client.keys.create(name="ci", scopes=["datasets:write", "runs:write"])
print(created.secret)  # shown once
Response 201 CreatedRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "key": {
    "id": "key_bd29ebeac8cb6a3f2ea88426",
    "workspace_id": "ws_e2e",
    "name": "ci",
    "prefix": "grad_c4d858d",
    "scopes": [
      "datasets:write",
      "runs:write"
    ],
    "created_at": "2026-12-02T15:48:59.560Z",
    "revoked_at": null
  },
  "secret": "grad_…"
}

List workspace API keys#

GET/v1/keys

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars

Returns

200 object Workspace keys.

2 fields
  • dataarray of ApiKeyrequired
    7 child fields
    • idstringrequired

      Key id (key_ and 24 hex characters).

    • workspace_idstringrequired
    • namestringrequired≤ 64 chars

      Key name.

      Matches ^[a-z0-9][a-z0-9._-]{0,63}$

    • prefixstringrequired

      The first 12 characters of the secret, to tell keys apart.

    • scopesarray of ApiKeyScoperequired

      What the key may do; a :write scope includes its :read, and admin includes every workspace scope.

    • created_atstring (date-time)required
    • revoked_atstring (date-time)requirednullable

      When the key was revoked; null while it works.

  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for key in client.keys.list():
    print(key.id, key.name, key.scopes)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "data": [
    {
      "id": "key_bd29ebeac8cb6a3f2ea88426",
      "workspace_id": "ws_e2e",
      "name": "ci",
      "prefix": "grad_c4d858d",
      "scopes": [
        "datasets:write",
        "runs:write"
      ],
      "created_at": "2026-12-02T15:48:59.560Z",
      "revoked_at": null
    }
  ],
  "next_cursor": null
}

Get a workspace API key by id#

GET/v1/keys/{id}

Metadata only.

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 ApiKey Workspace API key.

7 fields
  • idstringrequired

    Key id (key_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Key name.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • prefixstringrequired

    The first 12 characters of the secret, to tell keys apart.

  • scopesarray of ApiKeyScoperequired

    What the key may do; a :write scope includes its :read, and admin includes every workspace scope.

  • created_atstring (date-time)required
  • revoked_atstring (date-time)requirednullable

    When the key was revoked; null while it works.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
key = client.keys.get("key_3f9c0a1b2c3d4e5f60718293")
print(key.name, key.scopes)
Response 200 OKGenerated from the schema
JSON
{
  "id": "key_3f9c0a1b2c3d4e5f60718293",
  "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
  "name": "support-prod",
  "prefix": "string",
  "scopes": [
    "admin"
  ],
  "created_at": "2026-11-28T09:30:00.000Z",
  "revoked_at": "2026-11-28T09:30:00.000Z"
}

Revoke a workspace API key#

DELETE/v1/keys/{id}

Path parameters

  • idstringrequired≤ 200 chars

Returns

200 ApiKey Revoked API key.

7 fields
  • idstringrequired

    Key id (key_ and 24 hex characters).

  • workspace_idstringrequired
  • namestringrequired≤ 64 chars

    Key name.

    Matches ^[a-z0-9][a-z0-9._-]{0,63}$

  • prefixstringrequired

    The first 12 characters of the secret, to tell keys apart.

  • scopesarray of ApiKeyScoperequired

    What the key may do; a :write scope includes its :read, and admin includes every workspace scope.

  • created_atstring (date-time)required
  • revoked_atstring (date-time)requirednullable

    When the key was revoked; null while it works.

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
client.keys.revoke("key_3f9c0a1b2c3d4e5f60718293")
Response 200 OKGenerated from the schema
JSON
{
  "id": "key_3f9c0a1b2c3d4e5f60718293",
  "workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
  "name": "support-prod",
  "prefix": "string",
  "scopes": [
    "admin"
  ],
  "created_at": "2026-11-28T09:30:00.000Z",
  "revoked_at": "2026-11-28T09:30:00.000Z"
}

Usage#

List billed usage, newest first (filter by period, run, eval or kind): one record per billed increment of a run or eval attempt#

GET/v1/usage

Query parameters

  • limitinteger1–200default 50

    Page size (default 50). Values above 200 are clamped to 200.

  • cursorstring≤ 512 chars
  • fromstring≤ 40 chars

    Start of the period (inclusive): YYYY-MM-DD (UTC) or an ISO 8601 timestamp.

  • tostring≤ 40 chars

    End of the period: a date YYYY-MM-DD covers that whole UTC day; a timestamp is exclusive.

  • run_idstring≤ 64 chars

    Only usage billed for this run (its training and the evals it started: labeling, teacher answers, checkpoint evals) or trainer (trn_...).

  • eval_idstring≤ 64 chars
  • kindenum

    "training""trainer""eval""scoring""labeling""teacher"

Returns

200 object Usage records.

2 fields
  • dataarray of UsageRecordrequired
    16 child fields
    • idstringrequired

      Usage row id.

    • kindUsageKindrequired

      What the tokens paid for: training (a run's attempts), trainer (a trainer's ops), eval (evals, including a run's checkpoint evals), scoring (dataset.score), labeling (a router run's labeling eval) or teacher (an off-policy distill run's teacher answers).

      "training""trainer""eval""scoring""labeling""teacher"

    • ref_idstringrequired

      The run (kind training) or eval this usage belongs to.

    • ref_namestringrequirednullable

      The run's or eval's name.

    • run_idstringrequirednullable

      The run the usage was billed for: the run itself, or the run whose labeling, teacher or checkpoint eval it is.

    • attemptintegerrequired≥ 1

      The attempt the tokens belong to.

    • tokens_fromintegerrequired≥ 0

      The attempt's tokens this row starts after (usage is billed in increments while an attempt runs).

    • tokens_throughintegerrequired≥ 0

      The attempt's tokens this row ends at; tokens is the difference from tokens_from.

    • tokensintegerrequired≥ 0

      Tokens billed in this row.

    • prompt_tokensinteger≥ 0

      Prompt tokens processed by sample ops in this row (0 for non-sample usage).

    • sampled_tokensinteger≥ 0

      Generated/completion tokens produced by sample ops in this row (0 for non-sample usage).

    • cost_usdnumberrequired≥ 0

      The charge, in USD.

    • price_versionstringrequired

      The version of the catalog price the charge was computed with.

    • billed_byenumrequired

      Who bills this usage: grad (training, and evals on a self-hosted server) or gateway (on Gradiated Cloud, eval model and judge tokens are billed once by the inference gateway; shown here, not charged twice).

      "grad""gateway"

    • idempotency_keystringrequired

      run-usage:{id}:{attempt}:{tokens_through} (eval-usage: for evals); unique, so an increment is never billed twice.

    • created_atstring (date-time)required

      When the increment was billed.

  • next_cursorstringrequirednullable

    Pass back as cursor for the next page; null on the last page (every list endpoint).

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
for row in client.usage.list(from_="2026-11-01"):
    print(row.created_at, row.kind, row.cost_usd)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "data": [
    {
      "id": "use_1",
      "kind": "training",
      "ref_id": "run_ed1c235f0c631d8f209e22a5",
      "attempt": 1,
      "tokens_from": 0,
      "tokens_through": 21,
      "tokens": 21,
      "prompt_tokens": 0,
      "sampled_tokens": 0,
      "cost_usd": 0.000008,
      "price_version": "p_51c1854c0003",
      "billed_by": "grad",
      "idempotency_key": "run-usage:run_ed1c235f0c631d8f209e22a5:1:21",
      "created_at": "2026-12-02T15:49:00.151Z",
      "ref_name": "support-sft",
      "run_id": "run_ed1c235f0c631d8f209e22a5"
    }
  ],
  "next_cursor": null
}

Total cost and tokens over a period (default: this UTC month), by kind, the top runs and evals, and optional groups#

GET/v1/usage/summary

Query parameters

  • fromstring≤ 40 chars

    Start of the period (inclusive): YYYY-MM-DD (UTC) or an ISO 8601 timestamp.

  • tostring≤ 40 chars

    End of the period: a date YYYY-MM-DD covers that whole UTC day; a timestamp is exclusive.

  • group_byenum

    "day""week""month""model""recipe""kind"

Returns

200 UsageSummary Usage summary.

11 fields
  • fromstring (date-time)required

    Start of the period (inclusive).

  • tostring (date-time)required

    End of the period (exclusive).

  • cost_usdnumberrequired≥ 0
  • tokensintegerrequired≥ 0
  • sampled_tokensintegerrequired≥ 0

    Generated/completion tokens produced by trainer sample ops in this period.

  • recordsintegerrequired≥ 0
  • by_kindarray of UsageKindTotalrequired

    One entry per kind with usage, costliest first.

    4 child fields
    • kindUsageKindrequired

      What the tokens paid for: training (a run's attempts), trainer (a trainer's ops), eval (evals, including a run's checkpoint evals), scoring (dataset.score), labeling (a router run's labeling eval) or teacher (an off-policy distill run's teacher answers).

      "training""trainer""eval""scoring""labeling""teacher"

    • cost_usdnumberrequired≥ 0
    • tokensintegerrequired≥ 0
    • recordsintegerrequired≥ 0
  • top_runsarray of UsageRefTotalrequired

    The costliest runs' training in the period (up to 5).

    5 child fields
    • idstringrequired
    • namestringrequirednullable
    • kindUsageKindrequired

      What the tokens paid for: training (a run's attempts), trainer (a trainer's ops), eval (evals, including a run's checkpoint evals), scoring (dataset.score), labeling (a router run's labeling eval) or teacher (an off-policy distill run's teacher answers).

      "training""trainer""eval""scoring""labeling""teacher"

    • cost_usdnumberrequired≥ 0
    • tokensintegerrequired≥ 0
  • top_evalsarray of UsageRefTotalrequired

    The costliest evals, scoring, labeling and teacher jobs in the period (up to 5).

    5 child fields
    • idstringrequired
    • namestringrequirednullable
    • kindUsageKindrequired

      What the tokens paid for: training (a run's attempts), trainer (a trainer's ops), eval (evals, including a run's checkpoint evals), scoring (dataset.score), labeling (a router run's labeling eval) or teacher (an off-policy distill run's teacher answers).

      "training""trainer""eval""scoring""labeling""teacher"

    • cost_usdnumberrequired≥ 0
    • tokensintegerrequired≥ 0
  • group_byUsageGroupByrequirednullable
  • groupsarray of UsageGrouprequired

    With group_by: one entry per group with usage, oldest first for time groups and costliest first otherwise.

    4 child fields
    • keystringrequirednullable

      The group: a UTC day or week start (YYYY-MM-DD), a month (YYYY-MM), a model, a recipe or a kind. Null for usage with no recipe (plain evals, scoring).

    • cost_usdnumberrequired≥ 0
    • tokensintegerrequired≥ 0
    • recordsintegerrequired≥ 0

Errors: 400 401 403 404 409 422 500 503

Request
Python
from grad import Grad

client = Grad()
summary = client.usage.summary(from_="2026-11-01", group_by="model")
print(summary.cost_usd, summary.tokens)
Response 200 OKRecorded from grad-server 0.2.0-alpha.15
JSON
{
  "from": "2026-12-01T00:00:00.000Z",
  "to": "2027-01-01T00:00:00.000Z",
  "cost_usd": 0.000008,
  "tokens": 21,
  "records": 1,
  "sampled_tokens": 0,
  "by_kind": [
    {
      "kind": "training",
      "cost_usd": 0.000008,
      "tokens": 21,
      "records": 1
    }
  ],
  "top_runs": [
    {
      "id": "run_ed1c235f0c631d8f209e22a5",
      "name": "support-sft",
      "kind": "training",
      "cost_usd": 0.000008,
      "tokens": 21
    }
  ],
  "top_evals": [],
  "group_by": null,
  "groups": []
}