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.
{
"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"
}
| Field | Type | Purpose |
|---|---|---|
id | string | Your record ID; errors and eval results name it. |
session_id | string | null | Groups multi-turn conversations so train/eval splits never leak turns across splits. |
group_id | string | null | Keeps paired or grouped examples on one side of the split (DPO pairs, splits.ByGroup). |
role | string | null | chosen, rejected, anchor, positive, negative, desirable, undesirable, or rollout. DPO pairs records that share a group_id by chosen and rejected. |
source, timestamp | string | null | Where the record came from and when. |
input | object | messages[], 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. |
output | object | null | turns[] (the assistant answer) and optional payload. |
expected_output | any | Gold correction or ground-truth label ({ label } or { content }) used by SFTRecipe and DecisionModelRecipe, and as the reference answer in evals. |
scores | Record<string, number> | Named scalar outcomes (task_success, tests_passed, reward, etc.). Routers read them, or scores keyed by model ID. |
metrics | Record<string, number> | Request telemetry (cost_usd, latency_ms, input_tokens, output_tokens). |
metadata | Record<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:
| Shape | Fields | Used by |
|---|---|---|
| Chat | messages[], optional tools[] | SFT, routers, cartridge prompts |
| Prompt/completion | prompt, completion (string or messages) | SFT, evals |
| Preference pair | prompt, chosen, rejected | DPO |
| Triplet | query, positive, optional negatives[] | Embeddings |
| Decision | state (or messages), questions{}, expected_output | Decision 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.turnsandtraj.textsplit a trajectory into its prompt turns, its trailing assistant turns and the final answer's text. LocalScorerfunctions receive aTrajectory.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)andTriplet(query, positive, negatives)build the flat shapes;Task(prompt=..., expected_output=...)is one prompt to attempt.Context.from_text(text)andContext.from_file(path)hold the document aCartridgeRecipecompresses.
Typed SDK entities & interfaces (grad.*)#
The SDK has resource objects returned by the API, value specs (pure configuration) and recipe classes:
| Category | Classes |
|---|---|
| Records | Trajectory, Record, PreferencePair, Triplet, Task, Context |
| Resource objects | Model, 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 & pooling | adapters.LoRA(rank=32, alpha=32, merge_on_export=False), adapters.PrefixKV(num_tokens=256), adapters.FrozenHead(); pooling.Mean(), pooling.CLS() |
| Optimizers | optim.AdamW(lr="auto", betas=(0.9, 0.95), weight_decay=0.0, grad_clip=1.0) |
| Losses | losses.CrossEntropy, losses.DPO, losses.InfoNCE, losses.TopKKLDistill, losses.BCEWithLogits, losses.OrdinalBCE |
| Splits | splits.BySession, splits.ByGroup, splits.Random |
| Rubrics & validators | Rubric, Scorer, Judge; validators.JSON(), validators.NonEmpty(), validators.ExactMatch(), validators.Regex(pattern) |
| Sources & trackers | sources.Langfuse, sources.LangSmith, sources.Braintrust, sources.PostHog, sources.Phoenix, sources.Gradiated; loggers.WandB(project, secret=...), loggers.MLflow(tracking_uri, ...) |
| Recipes | SFTRecipe, 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"), aModelfromclient.models.get(...), or a finishedArtifact(sent asname@version). - To train on a finished run's output, wait for it and pass
run.artifact:run.artifactisNoneuntil 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:
| Resource | Methods |
|---|---|
client.models | list(), get(id) |
client.datasets | create(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.imports | get(id), list(), wait(id) |
client.runs | plan(...), 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.checkpoints | promote(id, name=) |
client.artifacts | get(ref), list(name=), download(ref, path), download_url(ref), upload(path, base=, format=, name=), from_hf(uri, base=, secret=), delete(ref) |
client.evals | plan(...), create(...), get(id), list(), wait(id), outputs(id), results(id), failures(id), post_scores(id, scores), score_pending(id, rubric), cancel(id) |
client.secrets | set(name, value), get(name) (a SecretRef, never the value), list(), delete(name) |
client.sources | create(dataset, provider, schedule=, sample_rate=, ...), get(id), list(dataset=), update(id, filters=, schedule=, ...), sync(id, full=), remove(id) |
client.usage | summary(from_=, to=, group_by=), list(from_=, to=, run_id=, eval_id=, kind=) |
client.keys | create(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().
| Object | Wire fields |
|---|---|
Model | id, hf_repo, family (llm or encoder), adapters, recipes, default_for, price_per_million_tokens_usd, max_context_tokens, template_revision, calibrated_lrs |
Run | id, 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 |
MetricPoint | seq, attempt, step, loss, eval_loss, eval_metrics, grad_norm, lr, tokens_per_sec, tokens, cost_usd, timestamp |
Checkpoint | id, run_id, attempt, step, eval_score, format, sha256, size_bytes, metadata, best, final, expires_at; ckpt.promote(name=...) turns it into an artifact |
Artifact | id 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 |
Eval | id, 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 |
Dataset | id, name, version, record_count (merged records), metadata, created_at, updated_at |
ImportJob | id, dataset, status, source, connector, attempt, imported_count, dropped_count, detected_scores, drop_reasons, dataset_version, error |
Source | id, 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 |
SecretRef | name, created_at, updated_at; the value is never returned |
UsageRecord | id, 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 |
ApiKey | id, name, prefix, scopes, created_at, revoked_at; CreatedApiKey is {key, secret} |
- An
Artifactis immutable and versionedname@YYYY-MM-DD-n. Itsformatispeft_loraormerged_safetensors(SFT, DPO, distillation),cartridge(cartridges),encoder_safetensors(embeddings),router_bundle,decision_bundleorreward_bundle(reward models).run.eval_reportandartifact.eval_reportcarry the held-out report:metric_name,selected_step,best_step,final_step,train_records,eval_records,warningsand the recipe's own metrics (for routers,pareto_summary). run.wait(),run.metrics(follow=True),run.cancel(),run.resume(max_cost_usd=...)andrun.checkpoints()manage a run;run.artifactfetches its artifact.- Serving: download the weights with
artifact.download(path)orgrad artifacts downloadand 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:
| Python | Raised when |
|---|---|
GradConfigError | No API key or a bad profile or config file (it names GRADIATED_API_KEY and grad login). |
RunFailedError, EvalFailedError, ImportFailedError, ArtifactImportFailedError | wait() 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. |
WaitTimeoutError | wait() gave up (24 hours by default; pass timeout=). The job keeps running. |
APIConnectionError, APITimeoutError | The server couldn't be reached, or a request timed out after the retries. |
ChecksumMismatchError, UnsafeArchiveError | A downloaded artifact failed its SHA-256 check, or its archive holds an unsafe path. Nothing is extracted. |
PaginationLoopError | The server repeated a cursor; iteration stops instead of looping. |
ScorerError | A local Scorer function raised, or returned something other than a score in [0, 1]. |
NotAvailableInV0Error | A 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, ...).