Primitives reference

Reference for the core objects and JSON schemas used across the Gradiated SDKs and API.

These wire schemas mirror the OpenAPI 3.1 contract (spec/openapi.yaml) used across the server, CLI, and Python, TypeScript, Go, and Rust SDKs. See API reference for HTTP routes.

Trajectory (grad.trajectory/1)#

Universal model-agnostic record for production traces, supervised (input, expected_output) pairs and multi-turn agent traces. Every dataset record (DatasetRecord on the wire) is either this shape or one of the flat shapes below.

JSON
{
  "schema": "grad.trajectory/1",
  "id": "traj_9f82a1",
  "session_id": "sess_42",
  "group_id": "grp_prompt_42",
  "role": "rollout",
  "source": "otel",
  "input": {
    "messages": [{ "role": "user", "content": "Refund order #8821" }],
    "tools": [{ "name": "issue_refund" }],
    "features": { "customer_tier": "enterprise", "turn_index": 0 }
  },
  "output": {
    "turns": [{ "role": "assistant", "content": "Refund issued." }]
  },
  "expected_output": null,
  "scores": { "task_success": 1.0, "user_thumbs": 1.0 },
  "metrics": {
    "cost_usd": 0.01105,
    "latency_ms": 4210,
    "input_tokens": 1820,
    "output_tokens": 240
  },
  "metadata": {
    "endpoint": "support-router",
    "artifact": "support-router@2026-11-25-1",
    "inference_id": "inf_01J9Y",
    "model": "qwen/qwen3-8b"
  },
  "timestamp": "2026-11-25T18:00:05Z"
}
FieldTypePurpose
idstringYour record ID; errors and eval results name it.
session_idstring | nullGroups multi-turn conversations so train/eval splits never leak turns across splits.
group_idstring | nullKeeps paired or grouped examples on one side of the split (DPO pairs, splits.ByGroup).
rolestring | nullchosen, rejected, anchor, positive, negative, desirable, undesirable, or rollout. DPO pairs records that share a group_id by chosen and rejected.
source, timestampstring | nullWhere the record came from and when.
inputobjectmessages[], tools[], media[], features{} (tabular signals kept with the record), and optional arbitrary payload. Decision models read the flat state field (or messages), not input.features.
outputobject | nullturns[] (the assistant answer) and optional payload.
expected_outputanyGold correction or ground-truth label ({ label } or { content }) used by SFTRecipe and DecisionModelRecipe, and as the reference answer in evals.
scoresRecord<string, number>Named scalar outcomes (task_success, tests_passed, reward, etc.). Routers read them, or scores keyed by model ID.
metricsRecord<string, number>Request telemetry (cost_usd, latency_ms, input_tokens, output_tokens).
metadataRecord<string, any>Serving provenance (endpoint, artifact, inference_id, model). Routers find candidate models in metadata.model.

The flat shapes use the same envelope fields (id, session_id, group_id, scores, metrics, metadata) with one of:

ShapeFieldsUsed by
Chatmessages[], optional tools[]SFT, routers, cartridge prompts
Prompt/completionprompt, completion (string or messages)SFT, evals
Preference pairprompt, chosen, rejectedDPO
Tripletquery, positive, optional negatives[]Embeddings
Decisionstate (or messages), questions{}, expected_outputDecision models

A chat message is { role, content, tool_calls?, tool_call_id?, name?, train? } with role one of system, user, assistant or tool; "train": false keeps a message out of the loss.

SDK record helpers#

Every helper serializes to a DatasetRecord with to_dict(), and plain dicts work anywhere a record does.

  • Trajectory.from_messages(messages, session_id=..., scores=..., metadata=..., expected_output=...) builds a trajectory from OpenAI-format chat messages; Trajectory.from_record(record) reads one back from the API.
  • traj.input.messages, traj.output.turns and traj.text split a trajectory into its prompt turns, its trailing assistant turns and the final answer's text. Local Scorer functions receive a Trajectory.
  • traj.append_env_tokens(content, role="tool") appends a tool or environment observation with "train": false.
  • traj.with_targets(scores=..., expected_output=...) attaches outcome scores or a gold answer and returns the trajectory.
  • Record(...), PreferencePair(prompt, chosen, rejected) and Triplet(query, positive, negatives) build the flat shapes; Task(prompt=..., expected_output=...) is one prompt to attempt.
  • Context.from_text(text) and Context.from_file(path) hold the document a CartridgeRecipe compresses.

Typed SDK entities & interfaces (grad.*)#

The SDK has resource objects returned by the API, value specs (pure configuration) and recipe classes:

CategoryClasses
RecordsTrajectory, Record, PreferencePair, Triplet, Task, Context
Resource objectsModel, Dataset, DatasetScoring (.wait() returns the scored Dataset), ImportJob, Plan, Run, MetricPoint, EvalReport, Checkpoint, Artifact, Eval, EvalPlan, EvalOutput, EvalResult, EvalFailures, ArtifactImport (.wait() returns the Artifact), SecretRef, Source, UsageRecord, UsageSummary, ApiKey, CreatedApiKey; lists return a Page
Adapters & poolingadapters.LoRA(rank=32, alpha=32, merge_on_export=False), adapters.PrefixKV(num_tokens=256), adapters.FrozenHead(); pooling.Mean(), pooling.CLS()
Optimizersoptim.AdamW(lr="auto", betas=(0.9, 0.95), weight_decay=0.0, grad_clip=1.0)
Losseslosses.CrossEntropy, losses.DPO, losses.InfoNCE, losses.TopKKLDistill, losses.BCEWithLogits, losses.OrdinalBCE
Splitssplits.BySession, splits.ByGroup, splits.Random
Rubrics & validatorsRubric, Scorer, Judge; validators.JSON(), validators.NonEmpty(), validators.ExactMatch(), validators.Regex(pattern)
Sources & trackerssources.Langfuse, sources.LangSmith, sources.Braintrust, sources.PostHog, sources.Phoenix, sources.Gradiated; loggers.WandB(project, secret=...), loggers.MLflow(tracking_uri, ...)
RecipesSFTRecipe, DPORecipe, RouterRecipe, DecisionModelRecipe, CartridgeRecipe(context=Context.from_file(...), num_tokens=256), EmbeddingRecipe, DistillRecipe(teacher=..., rollout=OnPolicy() | OffPolicy()), RewardModelRecipe; EvalSpec(dataset, rubric=...) for a recipe's evals=

GRPORecipe, environments.Tools, StatefulScorer, losses.GRPO, losses.CISPO, losses.CustomLoss and advantages.* are typed for RL for agents, which is coming soon; the server rejects them today.

  • Model arguments (model=, teacher=, fallback=, models=, Judge(model=)) accept a model ID string ("qwen/qwen3-8b"), a Model from client.models.get(...), or a finished Artifact (sent as name@version).
  • To train on a finished run's output, wait for it and pass run.artifact: run.artifact is None until the run has an artifact.

Client resources#

Grad(api_key=None, *, base_url=None, profile=None, timeout=60.0, max_retries=2, default_headers=None, config_path=None) reads GRADIATED_API_KEY, GRADIATED_BASE_URL and the grad login config file when you leave them out. Its resources, in Python:

ResourceMethods
client.modelslist(), get(id)
client.datasetscreate(name), get(name), list(), push(name, records_or_path), import_file(name, path), from_hf(repo, ...), from_benchmark(name), records(name, version=), count(name), render(name, model=), score(name, rubric), filter(name, scores=, metadata=, ...)
client.importsget(id), list(), wait(id)
client.runsplan(...), create(...), get(id), list(), wait(id, on_event=, on_metric=, on_status=, progress=), events(id, follow=), metrics(id, follow=, after_step=), cancel(id), resume(id, max_cost_usd=), checkpoints(id)
client.checkpointspromote(id, name=)
client.artifactsget(ref), list(name=), download(ref, path), download_url(ref), upload(path, base=, format=, name=), from_hf(uri, base=, secret=), delete(ref)
client.evalsplan(...), create(...), get(id), list(), wait(id), outputs(id), results(id), failures(id), post_scores(id, scores), score_pending(id, rubric), cancel(id)
client.secretsset(name, value), get(name) (a SecretRef, never the value), list(), delete(name)
client.sourcescreate(dataset, provider, schedule=, sample_rate=, ...), get(id), list(dataset=), update(id, filters=, schedule=, ...), sync(id, full=), remove(id)
client.usagesummary(from_=, to=, group_by=), list(from_=, to=, run_id=, eval_id=, kind=)
client.keyscreate(name=, scopes=) (a CreatedApiKey whose secret is shown once), list(), revoke(id)

The objects carry the same verbs: dataset.push(), .import_file(), .records(), .score(), .filter(), .add_source(), .sources(); run.wait(), .metrics(), .cancel(), .resume(), .checkpoints(), .artifact; artifact.download(); ckpt.promote(); ev.wait(), .summary_table(), .results(), .failures(); source.sync(), .remove(). The TypeScript, Go and Rust SDKs have the same resources with each language's casing (client.datasets.fromHf, client.Datasets.FromHF, client.datasets().from_hf; artifacts.downloadUrl, Artifacts.DownloadURL; artifacts.waitImport(id) in TypeScript, as wait_import / WaitImport elsewhere), and every create takes an optional idempotency key.

Model, Run, Checkpoint and Artifact#

The SDK objects expose the wire fields as attributes, plus .raw (the JSON the server sent) and to_dict().

ObjectWire fields
Modelid, hf_repo, family (llm or encoder), adapters, recipes, default_for, price_per_million_tokens_usd, max_context_tokens, template_revision, calibrated_lrs
Runid, name, status (queued, running, completed, failed, cancelled, stopped_budget, stopped_balance), dataset_name, dataset_version, recipe_kind, resolved_config, max_cost_usd, price_per_million_tokens, cost_usd, tokens_processed, current_step, total_steps, attempt, max_attempts, latest_metric, eval_report, checkpoint_evals, artifact_id, error, created_at, finished_at
MetricPointseq, attempt, step, loss, eval_loss, eval_metrics, grad_norm, lr, tokens_per_sec, tokens, cost_usd, timestamp
Checkpointid, run_id, attempt, step, eval_score, format, sha256, size_bytes, metadata, best, final, expires_at; ckpt.promote(name=...) turns it into an artifact
Artifactid and ref (name@version), name, version, run_id, checkpoint_id, base_model, recipe_kind, format, sha256, size_bytes, manifest, provenance (source: run, upload or import), eval_report, created_at
Evalid, name, status (queued, running, awaiting_scores, completed, failed, cancelled), mode (eval or score), models, baseline, rubric, samples, temperature, max_tokens, pass_threshold, judge_models, local_scorers, progress, waiting_reason (capacity_unavailable, rate_limited or inference_unavailable while a model call waits; else null), summary (per-model overall, ci_low, ci_high, pass_at_k, vs_baseline, cost_per_1k_tasks_usd), total_cost_usd, scored_dataset_version, error
Datasetid, name, version, record_count (merged records), metadata, created_at, updated_at
ImportJobid, dataset, status, source, connector, attempt, imported_count, dropped_count, detected_scores, drop_reasons, dataset_version, error
Sourceid, dataset, provider (kind, host, secret, project, filters), schedule, status (active or paused), paused_reason, last_error, last_error_at, consecutive_failures, pending_full, next_sync_at, last_synced_at, last_sync
SecretRefname, created_at, updated_at; the value is never returned
UsageRecordid, kind (training, eval, scoring, labeling or teacher), ref_id, ref_name, run_id, attempt, tokens_from, tokens_through, tokens, cost_usd, price_version, billed_by (grad, or gateway for eval tokens on Gradiated Cloud), idempotency_key, created_at
ApiKeyid, name, prefix, scopes, created_at, revoked_at; CreatedApiKey is {key, secret}
  • An Artifact is immutable and versioned name@YYYY-MM-DD-n. Its format is peft_lora or merged_safetensors (SFT, DPO, distillation), cartridge (cartridges), encoder_safetensors (embeddings), router_bundle, decision_bundle or reward_bundle (reward models). run.eval_report and artifact.eval_report carry the held-out report: metric_name, selected_step, best_step, final_step, train_records, eval_records, warnings and the recipe's own metrics (for routers, pareto_summary).
  • run.wait(), run.metrics(follow=True), run.cancel(), run.resume(max_cost_usd=...) and run.checkpoints() manage a run; run.artifact fetches its artifact.
  • Serving: download the weights with artifact.download(path) or grad artifacts download and serve them on vLLM or SGLang. See Artifacts and Deploying.

Errors#

Every SDK error subclasses GradError. API errors (GradAPIError) carry status, code, message, detail, request_id and field errors; the API reference maps statuses to classes in each language. The rest are raised by the SDK itself:

PythonRaised when
GradConfigErrorNo API key or a bad profile or config file (it names GRADIATED_API_KEY and grad login).
RunFailedError, EvalFailedError, ImportFailedError, ArtifactImportFailedErrorwait() saw the job end without a result (a run also on cancelled, stopped_budget or stopped_balance; an artifact upload or import whose files failed validation, invalid_artifact); .run, .eval or .job holds its final state.
WaitTimeoutErrorwait() gave up (24 hours by default; pass timeout=). The job keeps running.
APIConnectionError, APITimeoutErrorThe server couldn't be reached, or a request timed out after the retries.
ChecksumMismatchError, UnsafeArchiveErrorA downloaded artifact failed its SHA-256 check, or its archive holds an unsafe path. Nothing is extracted.
PaginationLoopErrorThe server repeated a cursor; iteration stops instead of looping.
ScorerErrorA local Scorer function raised, or returned something other than a score in [0, 1].
NotAvailableInV0ErrorA typed feature that's coming soon (GRPO, environments, custom losses) was used.

TypeScript, Go and Rust raise the same set under their own names (RunFailedError, *grad.RunFailedError, Error::RunFailed, ...).