API reference
Inference endpoints#
You can use https://api.gradiated.com as the base URL in all SDKs.
| Method | Path | Purpose |
|---|---|---|
GET | /v1/models | List accessible models. |
POST | /v1/chat/completions | Send an OpenAI Chat Completions request. |
POST | /v1/responses | Send an OpenAI Responses request. |
POST | /v1/messages | Send an Anthropic Messages request. |
POST | /v1/systemone | Ask Linden-1 for choices, probabilities and scores. |
The model catalog is also available at /models. Use /v1/messages/count_tokens to count message input tokens.
For direct HTTP requests, send the API key as a bearer token:
Authorization: Bearer grad_...
See the SystemOne SDK guide for Linden-1 examples and supported parameters.
Training API#
Every endpoint, with its fields, an example request and response and the SDK call that sends it, is in the generated Training API reference. The training API (grad-server) is the same everywhere it runs: grad local up, the Helm chart and, soon, Gradiated Cloud. Its contract is spec/openapi.yaml, and the Python, TypeScript, Go and Rust SDK transports are generated from it. grad-server listens on port 8787 by default (grad local up serves it at http://127.0.0.1:18787) and serves the live spec at /openapi.json.
Every /v1/* call needs Authorization: Bearer <key>. GET /health/live and GET /health/ready (database reachable) need no key.
Models, keys and usage#
Endpoints: models, keys, usage.
With AUTH_MODE=cloud, /v1/keys answers 501 keys_managed_by_cloud: Gradiated Cloud keys are created and revoked in the console.
Datasets and imports#
Endpoints: datasets, uploads and imports.
Dataset reads need datasets:read, writes datasets:write. Scoring also needs runs:write, because it's a billed eval.
Integrations and sources#
Endpoints: integrations, sources.
An integration is a connection to one provider (langfuse, langsmith, braintrust, posthog, phoenix, huggingface, wandb or mlflow): a name unique in the workspace, a host, and write-only credentials with the provider's own fields (Langfuse public_key and secret_key; LangSmith, Braintrust and W&B api_key; PostHog personal_api_key; Phoenix api_key, optional; Hugging Face token; MLflow token, optional). Credentials are encrypted and never returned, and are only ever sent to the integration's host. POST /v1/integrations/{name}/test makes one authenticated call to the provider and sets status (active, or failing with last_error; pending until a test has run). PATCH keeps credential fields left out; changing the host needs every credential again. used_by lists the sources, running imports and running training jobs that use it, and DELETE answers 409 integration_in_use with used_by until there are none.
Sources, Hugging Face imports and training loggers name an integration with integration. Imports and loggers can leave it out to use the workspace's only integration of their provider; a source that leaves it out must name the provider (provider.kind) instead, and with neither the answer is 422 source_provider_required. With no integration of the provider, Hugging Face imports read public repos and the rest answer 422 integration_required; with several, 422 integration_ambiguous lists their names.
A source feeds exactly one dataset; a dataset can have several sources. A source starts at most one sync a minute: a manual sync within 60 seconds of the last one returns that sync with Retry-After. Schedules are five-field UTC cron; a scheduled sync commits a dataset version at most every version_interval seconds (default 900; 0 commits every sync). A failed sync sets last_error and backs the schedule off (twice its interval per consecutive failure, at most an hour); after 10 failures in a row the source's status becomes paused. A manual sync, or new credentials for its integration, resumes it.
Runs, checkpoints and artifacts#
Endpoints: runs, checkpoints, artifacts.
Run status is queued, running, completed, failed, cancelled, stopped_budget (hit its max_cost_usd; resume with a higher cap) or stopped_balance (the Cloud workspace ran out of balance; resume after a top-up with the same cap). A queued run also carries queue_position and queue_message (why it waits), and every run has min_gpu_memory_gb, the GPU memory its plan needs.
An artifact import takes {source, base_model, format?, name?}. source is {kind: "upload", upload_id} (a tar of the files from POST /v1/uploads) or {kind: "hf", repo, revision?, integration?} (a branch, tag or commit, pinned on import; integration names the Hugging Face integration for gated or private repos). format defaults to peft_lora; name is required for uploads and defaults to the repo's name for Hub imports. A worker checks the files against the format and the base model; if they don't match, the import fails with error_code: invalid_artifact and an error naming the file. Every artifact's provenance says where it came from: source is run (with run_id), trainer (with trainer_id), upload (with uploader) or import (with uri, hf://owner/name@<commit>). Released artifacts are immutable (there is no delete or pin API); checkpoints remain mutable via PATCH /v1/checkpoints/{id} and expire per TTL (410 checkpoint_expired).
Evaluations#
Endpoints: evals.
Eval status is queued, running, awaiting_scores, completed, failed or cancelled. While a model call waits for capacity, waiting_reason says why: capacity_unavailable (the model's serving pool is starting), rate_limited or inference_unavailable (the endpoint is down); the eval keeps its place and fails only after GRAD_EVAL_CAPACITY_WAIT_SECONDS (12 minutes by default) per call.
Runs and evals need runs:read to read and runs:write to create or change.
Serving#
The training API keeps no serving state. Publishing an artifact as a model version is Gradiated Cloud's Models API, not this one (see Deploying); self-hosted, download the artifact and serve it on vLLM or SGLang. grad has no routing, embedding or feedback API either. Call a published model through the inference endpoints above, and keep production outcomes in your observability tool (or the Gradiated gateway); a source syncs them into a dataset.
/v1/trainer-jobs/* is the internal protocol between the server and its workers, not part of the SDKs. Workers authenticate with a worker token (a static key, a Kubernetes service-account token or a lease token minted by an orchestrator), never a workspace key; see Deploying to production (Helm).
Usage#
GET /v1/usage (grad usage list, client.usage.list()) lists the workspace's billing ledger, newest first. A run or eval attempt is billed in increments while it runs: every million tokens or five minutes, at each checkpoint and when it ends. A worker killed outright is billed up to its last progress report. Filter with from, to, run_id (the run's training plus the evals it started), eval_id and kind.
| Field | Meaning |
|---|---|
kind | What the tokens paid for: training, eval (including a run's checkpoint evals), scoring (dataset.score()), labeling (a router run's labeling eval) or teacher (distillation's teacher answers). |
ref_id, ref_name, attempt | The run or eval, its name, and the attempt the tokens belong to. |
run_id | The run billed: the run itself, or the run whose labeling, teacher or checkpoint eval this is. |
tokens_from, tokens_through | The attempt's token range this row covers; tokens is the difference. |
cost_usd, price_version | The charge, and the version of the catalog price it was computed with. |
billed_by | grad, or gateway: on Gradiated Cloud, eval model and judge tokens are billed by the inference gateway with your inference usage, so they're listed here but not charged twice. |
idempotency_key | run-usage:{id}:{attempt}:{tokens_through} (eval-usage: for evals); unique. |
created_at | When the increment was billed. |
GET /v1/usage/summary (grad usage, client.usage.summary()) totals a period: from and to take YYYY-MM-DD or an ISO 8601 timestamp, in UTC. from is inclusive; a date to covers that whole day and a timestamp to is exclusive. The default is the current UTC month, and from at or after to is 422 invalid_period. It returns the resolved from and to, cost_usd, tokens and records, by_kind[] (costliest first), and top_runs[] and top_evals[] (up to 5 each, with id, name, kind, cost_usd and tokens). With group_by (day, week from Monday, month, model, recipe or kind), groups[] has one {key, cost_usd, tokens, records} per group, oldest first for time groups and costliest first otherwise; key is null for usage with no recipe.
API key scopes#
POST /v1/keys takes {name, scopes}. A :write scope includes its :read, and admin includes every workspace scope.
| Scope | Grants |
|---|---|
admin | Everything in the workspace, including key management. |
datasets:read, datasets:write | Datasets, records, render, uploads and imports. |
runs:read, runs:write | Runs, checkpoints, evals, dataset scoring and usage. |
artifacts:read, artifacts:write | Reading and downloading artifacts; promoting checkpoints, uploading and importing artifacts. |
artifacts:pin | Legacy / Gradiated Cloud compatibility scope; accepted on keys, not checked by any public endpoint (released artifacts are immutable). |
integrations:read, integrations:write | Reading integrations and naming one in a source, import or run logger; creating, testing, updating and deleting them. Credentials are never readable. |
sources:read, sources:write | Sources and syncs. |
trainer:worker is a platform scope for workers. admin never implies it, and /v1/keys can't mint it; self-hosted servers configure worker authentication instead.
On Gradiated Cloud, a key or console session gets the scopes of its member's role. admin can do everything. member can push and read datasets, create runs and evals, read, download, upload and promote artifacts, and read sources; integrations, source changes and publishing are admin-only.
Idempotency#
Every create accepts an Idempotency-Key header of up to 255 visible ASCII characters: datasets, record pushes, imports, artifact imports, sources, runs, evals and keys. The SDKs send a UUIDv4 on each call and reuse it on every retry, so POSTs are retried safely; pass your own key to make a rerun of your whole script safe too (Python idempotency_key=, TypeScript { idempotencyKey }, Go RunParams.IdempotencyKey / EvalParams.IdempotencyKey, Rust create(&req, &CreateOptions { idempotency_key: Some(key) }), CLI --idempotency-key).
- The key is stored on the resource the request creates, in the same transaction. A retry with the same key and body returns that resource in its current state, with
Idempotent-Replayed: true. - The same key with a different body is 422
idempotency_key_reused; a malformed key is 422idempotency_key_invalid. POST /v1/keyscan't replay, because the secret is shown only once: a repeat gets 409idempotency_replay_unavailable.- Every other POST is idempotent by nature (cancel, resume, scores, sync) or read-only (plan, render).
POST /v1/runs
Authorization: Bearer grad_...
Idempotency-Key: 5f0c8d1e-3b8a-4c39-9a4e-2f1f0b6f4a21
Pagination#
List endpoints take limit and cursor and return {"data": [...], "next_cursor": ...}. Pass next_cursor back as cursor for the next page; it is null on the last page. A limit above an endpoint's maximum is clamped, not rejected:
| Endpoint | Default | Maximum |
|---|---|---|
| Most lists | 50 | 200 |
/v1/datasets/{name}/records | 100 | 1000 |
/v1/runs/{id}/metrics, /v1/runs/{id}/events | 1000 | 5000 |
/v1/runs/{id}/metrics also returns tail_cursor, the position after the newest point so far. Pass it back as cursor to poll for points written later. For a live view, GET /v1/runs/{id}/events with Accept: text/event-stream sends every event as it happens (event name = its type, event id = seq, a final completed); reconnect with Last-Event-ID to resume. The SDKs' metrics(follow=True) reads that stream. Live token-by-token trainer sampling uses GET /v1/trainers/{id}/ops/{op_id}/stream (SSE event: delta / done / error, backed by Valkey/Redis Streams when REDIS_URL is configured or an in-memory fallback otherwise, with opaque <ms>-<seq> stream IDs for Last-Event-ID resume and deduplication).
Errors#
Every code, with what it means and how to fix it, is in Errors. Errors are application/problem+json with type, title, status, code, detail and request_id. On a validation failure, detail names each field with its path, separated by ; (recipe.epochs: Too small: expected number to be >=1), and the SDKs parse those into the ValidationError. The same request_id is in the x-request-id response header; quote it when reporting a problem.
Request bodies are strict, nested objects included (the recipe and its adapter, optimizer, loss, rollout, split, rubric items, eval and import sources, source providers and dataset filters). A field an endpoint doesn't declare is 422 unknown_field, whose detail names its path and the field it most likely meant (recipe.adapter.merge_on_exprot: unknown field (did you mean 'merge_on_export'?)); before 0.2.0-alpha.9, the server dropped it and the run trained with the default. Free-form maps take any key: metadata, pricing, score maps and record contents (messages, trajectory input and output). The worker protocol (/v1/trainer-jobs/*) still ignores unknown fields, so workers and servers can be upgraded in either order.
| Status | Codes |
|---|---|
| 400 | malformed_request: the body isn't valid JSON. |
| 401 | unauthorized: missing or invalid API key. |
| 403 | forbidden (the key lacks the scope the message names), host_not_allowed and cross_site_request (AUTH_MODE=none only: a public DNS name in Host, or a browser request from an origin outside GRAD_CORS_ORIGINS), billing_denied (Cloud: the workspace can't start billed work), workspace_suspended (Cloud: the organization or workspace is suspended; new jobs and resumes are refused, and running runs stop as stopped_balance, resumable once it's active again), workspace_deleted (Cloud). |
| 404 | cloud_training_unavailable (raised by the SDKs and CLI, not the server, as a FeatureUnavailableError with CLI exit 6 when a configured host returns a bare 404 on a training route; verify GRADIATED_BASE_URL or run grad local up), route_not_found, and <resource>_not_found for dataset, dataset_version, import, run, checkpoint, artifact, artifact_import, eval, integration, key and source. |
| 409 | Runs: run_not_cancellable, run_not_resumable, run_state_changed, run_unbuildable (something the run needs is gone), budget_exhausted (resume a stopped_budget run with a higher max_cost_usd), checkpoint_not_exportable, checkpoint_conflict. Evals: eval_not_cancellable, eval_not_completed, eval_not_awaiting_scores. Data: dataset_exists, dataset_in_use, records_batch_conflict, upload_incomplete. Integrations: integration_exists, integration_in_use (with used_by), integration_changed (Cloud: changed while the request ran; read it again and retry), integration_unreadable, integration_deleted. Keys: idempotency_replay_unavailable. |
| 413 | payload_too_large: JSON bodies are capped at 32 MiB, and each API replica reads at most two bodies over 1 MiB at once (the rest wait). The SDKs stage multi-chunk pushes atomically through /v1/uploads; use /v1/datasets/{name}/imports for very large files. |
| 422 | Requests: validation_error (each field and its path in detail), unknown_field (a field the endpoint doesn't take, with the one it most likely meant), invalid_cursor, idempotency_key_invalid, idempotency_key_reused. Models: unknown_model, model_exceeds_gpu_memory, merged_export_too_large (merge_on_export=true on a base over the 5 GiB artifact cap), recipe_not_supported_for_model, adapter_not_supported, adapter_conflict, continued_training_unsupported, artifact_not_servable (an artifact that can't be served for an eval or as a judge; on Cloud, one Gradiated Cloud can't serve), checkpoint_evals_unsupported_on_cloud (Cloud: a recipe with evals=; evaluate run.artifact after training). Artifact imports: name_required, format_base_mismatch. Recipes: recipe_deferred (Wave 2 recipes), recipe_param_unsupported, recipe_param_conflict, recipe_param_invalid, invalid_decision_schema, loss_unsupported, render_conflict, render_unsupported_model, cartridge_context_required, distill_teacher_required, distill_teacher_unsupported, distill_teacher_is_student, distill_tokenizer_mismatch, distill_context_needs_on_policy, router_candidates_required, router_fallback_not_candidate, router_pricing_not_candidate, reward_rubric_unsupported, scorer_sandbox_unavailable, checkpoint_eval_code_scorer, duplicate_checkpoint_eval. Data: empty_dataset, no_usable_records, router_score_out_of_range, reward_score_out_of_range, invalid_filter, invalid_format, unknown_upload, upload_integrity_error, upload_too_large, invalid_upload_format, too_many_records. Evals: empty_eval, duplicate_scorer, unknown_scorer, unknown_judge_model (a judge that's neither a priced catalog or judge model nor an artifact of the workspace). Sources: source_provider_unsupported, source_provider_required, source_integration_unsupported, source_project_required. Integrations: integration_not_found, integration_required, integration_ambiguous (with integrations), integration_provider_mismatch, integration_credentials_invalid, integration_credentials_required, integration_host_required, integration_host_invalid, integration_host_not_allowed (credentials only go to the integration's own host), invalid_schedule, source_filter_unsupported, source_filter_invalid. Usage: invalid_period. |
| 429 | queue_limit: the workspace already has the most queued runs, imports, evals and trainers it may have (500 by default); wait or cancel some, then retry. too_many_streams: the key already holds 20 open event streams; close one or poll the JSON page. |
| 500 | internal_error. |
| 501 | inference_unavailable (no inference endpoint configured for evals), keys_managed_by_cloud (/v1/keys with AUTH_MODE=cloud), secrets_unavailable (no GRAD_SECRETS_KEY, so integrations can't store credentials), source_unavailable (the gradiated source: Cloud-only, and coming soon there). |
| 502 | inference_error (the inference or judge endpoint failed), source_upstream_error. |
| 503 | database_unavailable and storage_unavailable (object storage unreachable; both with Retry-After: 1), billing_unavailable (Cloud: billing can't be reached, or the price list hasn't refreshed for 24 hours), auth_unavailable (Cloud: the control plane can't be reached and the key isn't cached; retry), source_upstream_unavailable. GET /health/ready answers store_unavailable. shutting_down (/health/ready on a draining replica); inference_unavailable when the endpoint is down for a moment (raised as InferenceUnavailableError too), integrations_unavailable (Cloud: the integrations store can't be reached or answered with an error; retry shortly). |
The SDKs retry twice (0.5 s, doubling up to 8 s, with jitter) on 408, 429, 500, 502, 503 and 504, and on a 409 that carries Retry-After, for every GET, PUT and DELETE and every public POST (one Idempotency-Key across the retries). They never retry 429 queue_limit, and a Retry-After over 60 s raises at once (Python err.retry_after, TypeScript err.retryAfterMs). They raise a typed error that carries status, code, message and request_id:
| Error | Python | TypeScript | Go | Rust |
|---|---|---|---|---|
| Base class | GradAPIError (GradError) | APIError (GradError) | *grad.APIError | grad::Error (err.api()) |
| 400 | BadRequestError | BadRequestError | *grad.BadRequestError | Error::Validation |
| 401 | AuthenticationError | AuthenticationError | *grad.AuthenticationError | Error::Authentication |
| 403 | PermissionDeniedError | PermissionDeniedError | *grad.PermissionDeniedError | Error::PermissionDenied |
| 404 | NotFoundError | NotFoundError | *grad.NotFoundError | Error::NotFound |
| 409 | ConflictError | ConflictError | *grad.ConflictError | Error::Conflict |
| 413 | PayloadTooLargeError | APIError | *grad.APIError | Error::Validation |
| 422 | ValidationError | ValidationError | *grad.ValidationError | Error::Validation |
| 429 | RateLimitError | RateLimitError | *grad.RateLimitError | Error::RateLimit |
501 inference_unavailable | InferenceUnavailableError | InferenceUnavailableError | *grad.InferenceUnavailableError | Error::InferenceUnavailable |
| Other 501 | FeatureUnavailableError | FeatureUnavailableError | *grad.FeatureUnavailableError | Error::FeatureUnavailable |
| Other 5xx | ServerError | ServerError | *grad.ServerError | Error::Server |
| Network, timeout | APIConnectionError, APITimeoutError | APIConnectionError, APITimeoutError | *grad.ConnectionError, *grad.TimeoutError | Error::Connection, Error::Timeout |
InferenceUnavailableError is a kind of FeatureUnavailableError, so catching the latter covers every 501 (in Rust, match both Error::InferenceUnavailable and Error::FeatureUnavailable). Rust has one grad::Error enum: Error::Api is only the fallback for statuses without a variant, so read any API error with err.api(), err.status() and err.code(). Every SDK raises QueueLimitError (Error::QueueLimit) for 429 queue_limit and never retries it. Before 0.2.0-alpha.5, TypeScript and Go raised a ServerError for other 501s, which read as "try again later".
wait() raises RunFailedError, EvalFailedError or ImportFailedError with the final object when a job ends unsuccessfully, and WaitTimeoutError when it gives up (after 24 hours by default). See the Primitives reference for the rest.
See the Primitives reference for the record and object schemas, and the CLI reference for the grad commands.