# Trajectory > This file is very large and may be truncated. For an index of this content, please refer to https://docs.trajectory.ai/llms.txt instead. > Train, evaluate, and deploy models with specs. Explore production learning in private beta. # Attach Agent Training Run Source: https://docs.trajectory.ai/api-reference/agents/attach-agent-training-run /openapi.json post /api/v1/agents/{agent_id}/training-runs Claim an unassigned training run without changing existing ownership. # Create Agent Source: https://docs.trajectory.ai/api-reference/agents/create-agent /openapi.json post /api/v1/agents Register an agent for the authenticated organization. # Delete Agent Source: https://docs.trajectory.ai/api-reference/agents/delete-agent /openapi.json delete /api/v1/agents/{agent_id} Delete an agent and its benchmarks after all runs and cleanup have finished. It disappears at once, and its benchmarks, datasets, runs, evaluations and deployments are deleted permanently 30 days later. The request succeeds if the agent was already deleted. # Delete Benchmark By Name Source: https://docs.trajectory.ai/api-reference/agents/delete-benchmark-by-name /openapi.json delete /api/v1/agents/{agent_id}/benchmarks Delete a benchmark under this agent, including all prior versions. They disappear at once, and their tasks and files are deleted permanently 30 days later. # Get Agent Source: https://docs.trajectory.ai/api-reference/agents/get-agent /openapi.json get /api/v1/agents/{agent_id} Retrieve an agent by ID. # Get Agent By Name Source: https://docs.trajectory.ai/api-reference/agents/get-agent-by-name /openapi.json get /api/v1/agents/name/{name} Retrieve an agent by its exact organization-scoped name. # Get Agent Evaluation Run Source: https://docs.trajectory.ai/api-reference/agents/get-agent-evaluation-run /openapi.json get /api/v1/agents/{agent_id}/evaluation-runs/{eval_run_id} # Get Agent Training Evaluation Series Source: https://docs.trajectory.ai/api-reference/agents/get-agent-training-evaluation-series /openapi.json get /api/v1/agents/{agent_id}/training-runs/{training_run_id}/evaluation-series Latest scored checkpoint evaluation reward for a training run, in ascending training-step order. # Get Benchmark By Name Source: https://docs.trajectory.ai/api-reference/agents/get-benchmark-by-name /openapi.json get /api/v1/agents/{agent_id}/benchmarks/latest Retrieve the latest benchmark by agent ID and benchmark name. # Get Production Trace Source: https://docs.trajectory.ai/api-reference/agents/get-production-trace /openapi.json get /api/v1/agents/{agent_id}/traces/{trajectory_id} # List Agent Benchmarks Source: https://docs.trajectory.ai/api-reference/agents/list-agent-benchmarks /openapi.json get /api/v1/agents/{agent_id}/benchmarks List the latest snapshot for each benchmark name under an agent. # List Agent Deployments Source: https://docs.trajectory.ai/api-reference/agents/list-agent-deployments /openapi.json get /api/v1/agents/{agent_id}/deployments # List Agent Evaluation Runs Source: https://docs.trajectory.ai/api-reference/agents/list-agent-evaluation-runs /openapi.json get /api/v1/agents/{agent_id}/evaluation-runs # List Agent Training Runs Source: https://docs.trajectory.ai/api-reference/agents/list-agent-training-runs /openapi.json get /api/v1/agents/{agent_id}/training-runs # List Agents Source: https://docs.trajectory.ai/api-reference/agents/list-agents /openapi.json get /api/v1/agents List the authenticated organization's agents, newest first unless `sort` is given (created_at, updated_at, name, agent_id or benchmark_count). # List Benchmark Versions By Name Source: https://docs.trajectory.ai/api-reference/agents/list-benchmark-versions-by-name /openapi.json get /api/v1/agents/{agent_id}/benchmarks/versions Page benchmark snapshots by creation time and benchmark ID, both descending. Cursors are opaque and bound to the organization, agent, and name. Traversal is not a snapshot; use next_cursor while has_more is true. An existing agent with no matching snapshots returns an empty page. # List Production Traces Source: https://docs.trajectory.ai/api-reference/agents/list-production-traces /openapi.json get /api/v1/agents/{agent_id}/traces # Update Agent Source: https://docs.trajectory.ai/api-reference/agents/update-agent /openapi.json patch /api/v1/agents/{agent_id} Update an agent's name or description. # Update Production Trace Feedback Source: https://docs.trajectory.ai/api-reference/agents/update-production-trace-feedback /openapi.json patch /api/v1/agents/{agent_id}/traces/{trajectory_id} Record delayed customer feedback, including after a trajectory completes. Omitted fields are preserved; null clears a field. Feedback does not change recorded trajectory rewards or launch training. # Get Training Reward History Source: https://docs.trajectory.ai/api-reference/aperture/get-training-reward-history /openapi.json get /api/v1/train/{training_run_id}/trajectory-view/reward-history Mean trajectory reward by policy step, matching the product reward chart. Includes trajectory and pending counts; distinct from trainer collection metrics. # Decide Artemis Request Source: https://docs.trajectory.ai/api-reference/artemis/decide-artemis-request /openapi.json post /api/v1/artemis/sessions/{session_id}/decisions Approve or reject one pending request, named by its request_id and digest, and wake the session. A request takes one decision; the turn it runs reads like any other. Any API key of the organization can decide, with no person involved: decide on the request's command, config and files, never on its model-written description. # Get Artemis Session Source: https://docs.trajectory.ai/api-reference/artemis/get-artemis-session /openapi.json get /api/v1/artemis/sessions/{session_id} A session's latest 20 turns: each completed turn's answer, links and saved files, then a running or failed turn while messages wait. Poll until running is false. # Send Artemis Message Source: https://docs.trajectory.ai/api-reference/artemis/send-artemis-message /openapi.json post /api/v1/artemis/sessions/messages Store a message for Artemis, starting a session or continuing one, and wake the session. Answers at once; read the session to follow its turns. Retrying with the same Idempotency-Key stores and answers the message once. # Complete an artifact upload Source: https://docs.trajectory.ai/api-reference/artifacts/complete-an-artifact-upload /openapi.json post /api/v1/trajectories/{trajectory_id}/artifacts/{artifact_id}/complete Verify an uploaded artifact and attach its metadata to the trajectory. # Create an artifact upload Source: https://docs.trajectory.ai/api-reference/artifacts/create-an-artifact-upload /openapi.json post /api/v1/trajectories/{trajectory_id}/artifacts Reserve an artifact upload for a trajectory. Upload the file with PUT to the returned URL, then complete the upload. # Get an artifact download URL Source: https://docs.trajectory.ai/api-reference/artifacts/get-an-artifact-download-url /openapi.json get /api/v1/artifacts/{artifact_id} Get a download URL for an artifact you are authorized to read. # Store artifact content Source: https://docs.trajectory.ai/api-reference/artifacts/store-artifact-content /openapi.json post /api/v1/trajectories/{trajectory_id}/artifacts/content Upload up to 16 MiB of binary content directly through the API and attach it to a trajectory. Use this when your runtime cannot upload directly to storage. # Allocate Source: https://docs.trajectory.ai/api-reference/benchmark-ingestion/allocate /openapi.json post /api/v1/benchmark-ingestion/sessions/{operation_id}/uploads # Cancel Source: https://docs.trajectory.ai/api-reference/benchmark-ingestion/cancel /openapi.json post /api/v1/benchmark-ingestion/sessions/{operation_id}/cancel Cancel an uploading, queued, or running submission; finished submissions return 409. # Create Session Source: https://docs.trajectory.ai/api-reference/benchmark-ingestion/create-session /openapi.json post /api/v1/benchmark-ingestion/sessions # Finalize Source: https://docs.trajectory.ai/api-reference/benchmark-ingestion/finalize /openapi.json post /api/v1/benchmark-ingestion/sessions/{operation_id}/finalize # Items Source: https://docs.trajectory.ai/api-reference/benchmark-ingestion/items /openapi.json get /api/v1/benchmark-ingestion/operations/{operation_id}/{kind} # Status Source: https://docs.trajectory.ai/api-reference/benchmark-ingestion/status /openapi.json get /api/v1/benchmark-ingestion/operations/{operation_id} # Upload Failures Source: https://docs.trajectory.ai/api-reference/benchmark-ingestion/upload-failures /openapi.json get /api/v1/benchmark-ingestion/upload-failures # Benchmark Spec Source: https://docs.trajectory.ai/api-reference/benchmarks/benchmark-spec /openapi.json get /api/v1/benchmarks/{bench_id}/spec # Benchmark Task Count Source: https://docs.trajectory.ai/api-reference/benchmarks/benchmark-task-count /openapi.json get /api/v1/benchmarks/{bench_id}/task-count # Build Benchmark Images Source: https://docs.trajectory.ai/api-reference/benchmarks/build-benchmark-images /openapi.json post /api/v1/benchmarks/{bench_id}/images/build Trigger provider image builds for every unbuilt task image of the bench and acknowledge the request. Build completion is asynchronous; poll listBenchmarkImages, reading every page through next_cursor, until no image reports build_status=building. # Commit Benchmark Task Append Source: https://docs.trajectory.ai/api-reference/benchmarks/commit-benchmark-task-append /openapi.json post /api/v1/benchmarks/{bench_id}/tasks/append/{batch_id}/commit Persist and validate the request manifest, publish new tasks, and replace live tasks whose names are stored with different content. Each changed task commits independently before the batch receipt is recorded. Task names already stored with identical content are skipped. A finalized batch replays its original receipt; after an uncertain response, use the read-only batch result endpoint to check for that receipt. # Create Benchmark Task Append Source: https://docs.trajectory.ai/api-reference/benchmarks/create-benchmark-task-append /openapi.json post /api/v1/benchmarks/{bench_id}/tasks/append Return signed artifact URLs for one append batch, staged under a prefix derived from the Idempotency-Key. Commit the returned batch_id to publish the batch's tasks. # Create Benchmark Upload Source: https://docs.trajectory.ai/api-reference/benchmarks/create-benchmark-upload /openapi.json post /api/v1/benchmarks/uploads Allocate signed GCS PUT URLs for one batch of benchmark artifacts. Omit bench_id to mint a new benchmark; pass the returned bench_id on later calls to add more files to the same benchmark, which is how a file set over the per-request limit is uploaded. No rows are written until the ingest call. # Delete Benchmark Spec Source: https://docs.trajectory.ai/api-reference/benchmarks/delete-benchmark-spec /openapi.json delete /api/v1/benchmarks/{bench_id} Delete this benchmark version. It disappears at once, and its tasks and files are deleted permanently 30 days later. # Delete Benchmark Task Source: https://docs.trajectory.ai/api-reference/benchmarks/delete-benchmark-task /openapi.json delete /api/v1/benchmarks/{bench_id}/tasks/{task_id} Delete one benchmark task. It disappears at once and its own files are removed 30 days later, unless another task still uses them. Refused while an evaluation or training run on the benchmark, or a grade of one of the task's trajectories, has not finished. # Diff Benchmark Tasks Source: https://docs.trajectory.ai/api-reference/benchmarks/diff-benchmark-tasks /openapi.json post /api/v1/benchmarks/{bench_id}/tasks/diff Split submitted tasks into new tasks, tasks already stored with identical content, and updates whose names are stored with different content. Lets a client upload only what is missing or changed. # Get Benchmark Source: https://docs.trajectory.ai/api-reference/benchmarks/get-benchmark /openapi.json get /api/v1/benchmarks/{bench_id} # Get Benchmark Readiness Source: https://docs.trajectory.ai/api-reference/benchmarks/get-benchmark-readiness /openapi.json get /api/v1/benchmarks/{bench_id}/readiness Return whether a benchmark is ready to launch. A benchmark is ready when it is fully ingested, all required organization secrets are available, and all task environments are built. When it is not ready, the response identifies the remaining blockers. # Get Benchmark Task Append Result Source: https://docs.trajectory.ai/api-reference/benchmarks/get-benchmark-task-append-result /openapi.json get /api/v1/benchmarks/{bench_id}/tasks/append/{batch_id}/result Read the original finalized append receipt after losing a commit response, without resubmitting the commit. not_finalized means no receipt is recorded and the outcome is unknown: some or all tasks may already be applied. It does not establish whether the batch was submitted or is still running. Keep polling this read-only endpoint for a finalized receipt rather than resubmitting an uncertain commit. # Get Benchmark Task Env Resources Source: https://docs.trajectory.ai/api-reference/benchmarks/get-benchmark-task-env-resources /openapi.json get /api/v1/benchmarks/{bench_id}/tasks/{task_id}/env_resources Return the CPU, memory, GPU and network settings of one benchmark task's sandbox. # Get Benchmark Task Readiness Source: https://docs.trajectory.ai/api-reference/benchmarks/get-benchmark-task-readiness /openapi.json get /api/v1/benchmarks/{bench_id}/task-readiness # Ingest Benchmark Source: https://docs.trajectory.ai/api-reference/benchmarks/ingest-benchmark /openapi.json post /api/v1/benchmarks/{bench_id}/ingest Validate a benchmark manifest for a bench_id allocated by createBenchmarkUpload, persist it canonically, and write the bench, task, and runtime rows. # List Benchmark Images Source: https://docs.trajectory.ai/api-reference/benchmarks/list-benchmark-images /openapi.json get /api/v1/benchmarks/{bench_id}/images List the bench's task images with build status in ascending task-ID order, refreshing in-flight provider builds on the returned page (building -> ready/failed) as a side effect. # List Benchmark Runtimes Source: https://docs.trajectory.ai/api-reference/benchmarks/list-benchmark-runtimes /openapi.json get /api/v1/benchmarks/runtimes List the caller's organization-scoped benchmark runtimes. # List Benchmark Spec Runtimes Source: https://docs.trajectory.ai/api-reference/benchmarks/list-benchmark-spec-runtimes /openapi.json get /api/v1/benchmarks/{bench_id}/runtimes Runtimes used by the benchmark's tasks, in ascending runtime-ID order. Build status is the stored value; listBenchmarkImages refreshes in-flight provider builds. # List Benchmark Spec Tasks Source: https://docs.trajectory.ai/api-reference/benchmarks/list-benchmark-spec-tasks /openapi.json get /api/v1/benchmarks/{bench_id}/tasks Lists the benchmark's tasks in upload order, with appended tasks after earlier ones. Tasks uploaded before upload order was recorded come first, in creation order. `order=desc` reverses the list. # List Benchmark Spec Tools Source: https://docs.trajectory.ai/api-reference/benchmarks/list-benchmark-spec-tools /openapi.json get /api/v1/benchmarks/{bench_id}/tools Tools bound to any task of the benchmark, in ascending tool-ID order. # List Benchmarks Source: https://docs.trajectory.ai/api-reference/benchmarks/list-benchmarks /openapi.json get /api/v1/benchmarks List benchmarks newest first; `search` matches the name or benchmark ID. # Update Benchmark Source: https://docs.trajectory.ai/api-reference/benchmarks/update-benchmark /openapi.json patch /api/v1/benchmarks/{bench_id} # Update Benchmark Task Env Resources Source: https://docs.trajectory.ai/api-reference/benchmarks/update-benchmark-task-env-resources /openapi.json patch /api/v1/benchmarks/{bench_id}/tasks/{task_id}/env_resources Change the CPU, memory, GPU or network settings of one benchmark task's sandbox without uploading the task again. Only the fields in the request change. Rollouts that start after the change use it; sandboxes already running keep the settings they started with. # Get Billing Run Costs Source: https://docs.trajectory.ai/api-reference/billing/get-billing-run-costs /openapi.json get /api/v1/billing/usage/runs List this organization's cached run costs in USD cents over the last 30 calendar days. Includes training, inference, grading, and sandbox costs; older runs show only costs incurred within that window. Free organizations show usage at list price, not charges. # Delete Checkpoint Source: https://docs.trajectory.ai/api-reference/checkpoints/delete-checkpoint /openapi.json delete /api/v1/checkpoints/{checkpoint_id} Delete a service-generated Tinker checkpoint. It disappears at once, and its weights and exports are removed 30 days later. Legacy and externally registered checkpoints, and checkpoints with an active run, an unfinished export, or a child checkpoint, training run, deployment or model endpoint that uses them, return a conflict that names what blocks the delete. # Get Checkpoint Deletion Source: https://docs.trajectory.ai/api-reference/checkpoints/get-checkpoint-deletion /openapi.json get /api/v1/checkpoints/{checkpoint_id}/deletion # Add Dataset Trajectories Source: https://docs.trajectory.ai/api-reference/datasets/add-dataset-trajectories /openapi.json post /api/v1/datasets/{dataset_id}/trajectories Add a training/eval run's trajectories to a draft dataset. Poll the returned operation. # Copy Dataset Source: https://docs.trajectory.ai/api-reference/datasets/copy-dataset /openapi.json post /api/v1/datasets/{dataset_id}/copy Copy a finalized dataset's trajectories into this draft. Poll the returned operation. # Create Dataset Source: https://docs.trajectory.ai/api-reference/datasets/create-dataset /openapi.json post /api/v1/datasets Create an empty draft dataset. When finished adding trajectories, call finalize to use the dataset. # Delete Dataset Source: https://docs.trajectory.ai/api-reference/datasets/delete-dataset /openapi.json delete /api/v1/datasets/{dataset_id} Delete a dataset; refused while a training or evaluation run reads it. It disappears at once and is deleted permanently 30 days later. # Finalize Dataset Source: https://docs.trajectory.ai/api-reference/datasets/finalize-dataset /openapi.json post /api/v1/datasets/{dataset_id}/finalize Finalize a dataset to make it usable for training. # Get Dataset Source: https://docs.trajectory.ai/api-reference/datasets/get-dataset /openapi.json get /api/v1/datasets/{dataset_id} Retrieve a draft or finalized dataset with its metadata and split counts. # Get Dataset By Name Source: https://docs.trajectory.ai/api-reference/datasets/get-dataset-by-name /openapi.json get /api/v1/datasets/latest Retrieve the latest finalized dataset by agent ID and dataset name. # Get Dataset Operation Source: https://docs.trajectory.ai/api-reference/datasets/get-dataset-operation /openapi.json get /api/v1/datasets/operations/{operation_id} Retrieve the status of an add of trajectories to a draft dataset. # List Dataset Members Source: https://docs.trajectory.ai/api-reference/datasets/list-dataset-members /openapi.json get /api/v1/datasets/{dataset_id}/members List a dataset's members in trajectory ID order, with their train or test split. # List Dataset Versions Source: https://docs.trajectory.ai/api-reference/datasets/list-dataset-versions /openapi.json get /api/v1/datasets List the versions of a dataset name, newest first. # Set Dataset Member Split Source: https://docs.trajectory.ai/api-reference/datasets/set-dataset-member-split /openapi.json post /api/v1/datasets/{dataset_id}/members/split Set train/test splits for up to 5,000 draft members by trajectory ID. Non-members reject the whole batch; finalized datasets or pending adds/copies return 409. To edit a finalized version, copy it to a draft, wait, update splits, then finalize. Idempotency keys prevent reapplying changes for two days; conflicting reuse returns 409. # Cancel Deployment Route Source: https://docs.trajectory.ai/api-reference/deployments/cancel-deployment-route /openapi.json post /api/v1/deploy/{deployment_id}/cancel # Deployment Chat Completion Source: https://docs.trajectory.ai/api-reference/deployments/deployment-chat-completion /openapi.json post /api/v1/deploy/{deployment_id}/chat/completions Test this exact deployment without changing the slug's production target. # Get a deployment Source: https://docs.trajectory.ai/api-reference/deployments/get-deployment-route /openapi.json get /api/v1/deploy/{deployment_id} Retrieve a deployment’s status, serving role, endpoint details, and any failure. # List deployments Source: https://docs.trajectory.ai/api-reference/deployments/list-deployments-route /openapi.json get /api/v1/deploy List your organization’s deployments, with an optional lifecycle status filter. # Retry Deployment Route Source: https://docs.trajectory.ai/api-reference/deployments/retry-deployment-route /openapi.json post /api/v1/deploy/{deployment_id}/retry Retry a failed or cancelled deployment in place after cleanup. Keeps its deployment ID, test model slug, checkpoint, and saved configuration. # Create a deployment Source: https://docs.trajectory.ai/api-reference/deployments/start /openapi.json post /api/v1/deploy Start serving a committed checkpoint backed by restorable Tinker training state through Model Endpoint. The request returns a deployment ID before the endpoint is ready; retrieve the deployment until it is DEPLOYED or fails. # Delete a deployment Source: https://docs.trajectory.ai/api-reference/deployments/undeploy /openapi.json delete /api/v1/deploy/{deployment_id} Delete the deployment’s Model Endpoint, then remove its deployment record. # Create Device Auth Session Source: https://docs.trajectory.ai/api-reference/device-auth/create-device-auth-session /openapi.json post /api/v1/device/auth/sessions Start a sign-in the user approves in the browser at `verification_url`. # Logout Device Source: https://docs.trajectory.ai/api-reference/device-auth/logout-device /openapi.json post /api/v1/device/auth/logout Revoke the API key that authenticates this request; other keys keep working. # Poll Device Auth Token Source: https://docs.trajectory.ai/api-reference/device-auth/poll-device-auth-token /openapi.json post /api/v1/device/auth/token Poll until the user approves; the approved response carries the API key exactly once. # Get Benchmark Diagnostics Source: https://docs.trajectory.ai/api-reference/diagnostics/get-benchmark-diagnostics /openapi.json get /api/v1/diagnostics/{benchmark_diagnostic_id} Get task outcomes and failure reasons after a benchmark diagnostic finishes. # Get Benchmark Diagnostics Status Source: https://docs.trajectory.ai/api-reference/diagnostics/get-benchmark-diagnostics-status /openapi.json get /api/v1/diagnostics/{benchmark_diagnostic_id}/status Poll the status of a benchmark diagnostic. # Ingest Task For Diagnostics Source: https://docs.trajectory.ai/api-reference/diagnostics/ingest-task-for-diagnostics /openapi.json post /api/v1/diagnostics/task/ingest Register one task as a private benchmark and return its ingestion result. Call buildBenchmarkImages, poll every page of listBenchmarkImages until each image is ready, then call startTaskDiagnostics with the returned bench_id. # Start Benchmark Diagnostics Source: https://docs.trajectory.ai/api-reference/diagnostics/start-benchmark-diagnostics /openapi.json post /api/v1/diagnostics/benchmark/run Start diagnostics for an existing benchmark after its images are ready. Defaults to Nemotron 3.5 Lightning. # Start Task Diagnostics Source: https://docs.trajectory.ai/api-reference/diagnostics/start-task-diagnostics /openapi.json post /api/v1/diagnostics/task/run Start diagnostics for up to 10 tasks in an existing benchmark after its images are ready. # Cancel an evaluation Source: https://docs.trajectory.ai/api-reference/eval/cancel-an-evaluation /openapi.json post /api/v1/eval/{run_id}/cancel Request cancellation of a pending or running evaluation. # Delete an evaluation run Source: https://docs.trajectory.ai/api-reference/eval/delete-eval-run-route /openapi.json delete /api/v1/eval/{run_id} Delete an evaluation by its run ID. # Get evaluation options Source: https://docs.trajectory.ai/api-reference/eval/get-eval-options-route /openapi.json get /api/v1/eval/options Retrieve evaluation models and their supported shared RunOptions settings, bounds, and fixed or computed defaults. Filter by base_model_slug for one model. # Get evaluation progress Source: https://docs.trajectory.ai/api-reference/eval/get-eval-progress-route /openapi.json get /api/v1/eval/{run_id}/progress Retrieve an evaluation’s lifecycle status, trajectory counts, and any failure. # Get Eval Remaining Work Route Source: https://docs.trajectory.ai/api-reference/eval/get-eval-remaining-work-route /openapi.json get /api/v1/eval/{eval_run_id}/remaining-work # Get evaluation rollout statistics Source: https://docs.trajectory.ai/api-reference/eval/get-eval-rollout-statistics-route /openapi.json get /api/v1/eval/{run_id}/rollout-statistics Retrieve recorded distributions of trajectory settings and runtime measurements for an evaluation. # Get an evaluation run Source: https://docs.trajectory.ai/api-reference/eval/get-eval-run-route /openapi.json get /api/v1/eval/{run_id} Retrieve an evaluation by its run ID, including base_model_slug, typed options, parent_checkpoint_id, status, and recorded results. # Get evaluation rewards Source: https://docs.trajectory.ai/api-reference/eval/get-eval-trajectory-rewards-route /openapi.json get /api/v1/eval/{run_id}/trajectory-rewards Retrieve the reward of each scored trajectory in an evaluation run, the values its mean reward averages. Attempts that finished normally (`ENV_DONE`) report their reward and truncated attempts (`TRUNCATION`) score at most 0. Attempts with any other termination reason, such as an error, timeout, or cancellation, are omitted. Trajectories without a task come first, then results are ordered by task ID and trajectory ID. # List evaluation runs Source: https://docs.trajectory.ai/api-reference/eval/list-eval-runs-route /openapi.json get /api/v1/eval/{bench_id}/runs List evaluation runs and their recorded results for a spec. # Resume Eval Route Source: https://docs.trajectory.ai/api-reference/eval/resume-eval-route /openapi.json post /api/v1/eval/{run_id}/resume Resume a failed, cancelled, or completed standalone native evaluation, preserving its evaluation ID. The rerun_* flags select which attempts run again, by termination reason; other attempts keep their results. By default, errored, cancelled, and never-started attempts rerun (rerun_error and rerun_cancelled are true; rerun_timeout, rerun_truncation, and rerun_stale are false). To rerun only errored attempts, set rerun_cancelled=false. At least one flag must be true. If cleanup is pending, wait and retry with the same Idempotency-Key. # Start an evaluation Source: https://docs.trajectory.ai/api-reference/eval/start-eval-route /openapi.json post /api/v1/eval Create an evaluation with bench_id, base_model_slug, shared options, and an optional parent_checkpoint_id. Save the returned evaluation run ID to inspect progress and results. # Create Feedback Source: https://docs.trajectory.ai/api-reference/feedback/create-feedback /openapi.json post /api/v1/feedback Share feedback, suggestions, or observations about Trajectory's API, SDK, documentation, or workflow. A free-text message or any substantive report detail is enough. Structured details and category are optional; custom category labels are accepted. Text fields are trimmed before validation. Limits are measured in characters: message 2,000; summary, operation, and outcome 200 each; category 64; goal, expected_behavior, actual_behavior, and workaround 1,000 each; sdk_version 100. request_ids and resource_ids each accept at most 10 IDs of 1–200 characters. At least one of message, summary, goal, expected_behavior, actual_behavior, or workaround must contain non-whitespace text. Invalid reports return 422 before quota consumption or delivery. These bounds keep reports within the Slack message layout limits. Organizations may submit 10 attempts per one-hour window, including failed deliveries. Exclude credentials and private conversation contents. Success confirms delivery to the Trajectory team. Reports are not deduplicated; do not automatically retry a submission. # Create a chat completion Source: https://docs.trajectory.ai/api-reference/inference/create-chat-completion-1 /openapi.json post /v1/chat/completions Request a response from a model served by your organization. Use the active model slug as model. Serving a spec-trained model is part of the public workflow. Every request requires a trajectory ID in X-Trajectory-Id. # Create Decision Source: https://docs.trajectory.ai/api-reference/inference/create-decision /openapi.json post /v1/decisions # Create Response Source: https://docs.trajectory.ai/api-reference/inference/create-response /openapi.json post /v1/responses # Get By Inference Operation Source: https://docs.trajectory.ai/api-reference/inference/get-by-inference-operation /openapi.json get /api/v1/inference/operations/{inference_operation_id} # Get a served model Source: https://docs.trajectory.ai/api-reference/inference/get-model-1 /openapi.json get /v1/models/{model} Retrieve an active served model by name. The model must have a configured model endpoint. # List served models Source: https://docs.trajectory.ai/api-reference/inference/list-models-1 /openapi.json get /v1/models List the active models your organization can address by serving name. # Submit Inference Operation Source: https://docs.trajectory.ai/api-reference/inference/submit-inference-operation /openapi.json post /api/v1/inference/operations # Create a model endpoint Source: https://docs.trajectory.ai/api-reference/model-endpoints/create-a-model-endpoint /openapi.json post /api/v1/model-endpoints Create or reuse the model endpoint for an active deployment’s model slug. Check that the returned status is ready before using the model for inference. # Get a model endpoint Source: https://docs.trajectory.ai/api-reference/model-endpoints/get-a-model-endpoint /openapi.json get /api/v1/model-endpoints/{production_model_slug} Retrieve the model endpoint and its readiness state for an active deployment’s model slug. The active deployment must already have a model endpoint. # Create Production Model Slug Source: https://docs.trajectory.ai/api-reference/model-slugs/create-production-model-slug /openapi.json post /api/v1/model-slugs/production/{agent_id} # Get Production Model Slug Source: https://docs.trajectory.ai/api-reference/model-slugs/get-production-model-slug /openapi.json get /api/v1/model-slugs/production/{agent_id} # Update Production Model Slug Source: https://docs.trajectory.ai/api-reference/model-slugs/update-production-model-slug /openapi.json patch /api/v1/model-slugs/production/{agent_id} # Get the current organization Source: https://docs.trajectory.ai/api-reference/organizations/current-organization /openapi.json get /api/v1/organizations/current Identify the organization associated with your credentials. # Attach Project Training Run Source: https://docs.trajectory.ai/api-reference/projects/attach-project-training-run /openapi.json post /api/v1/projects/{project_id}/training-runs Claim an unassigned training run without changing existing ownership. # Create a project Source: https://docs.trajectory.ai/api-reference/projects/create-a-project /openapi.json post /api/v1/projects Create a project in your organization. # Delete a project Source: https://docs.trajectory.ai/api-reference/projects/delete-a-project /openapi.json delete /api/v1/projects/{project_id} Delete a project that has no dependent resources. The request also succeeds if the project was already deleted. # Delete Project Specs By Name Source: https://docs.trajectory.ai/api-reference/projects/delete-project-specs-by-name /openapi.json delete /api/v1/projects/{project_id}/specs Delete a spec under this project, including all prior versions. They disappear at once, and their tasks and files are deleted permanently 30 days later. # Get a project Source: https://docs.trajectory.ai/api-reference/projects/get-a-project /openapi.json get /api/v1/projects/{project_id} Retrieve a project by its ID. # Get Latest Project Spec Source: https://docs.trajectory.ai/api-reference/projects/get-latest-project-spec /openapi.json get /api/v1/projects/{project_id}/specs/latest Retrieve the latest spec by project ID and spec name. # Get Project By Name Source: https://docs.trajectory.ai/api-reference/projects/get-project-by-name /openapi.json get /api/v1/projects/name/{name} Retrieve a project by its exact organization-scoped name. # Get Project Evaluation Run Source: https://docs.trajectory.ai/api-reference/projects/get-project-evaluation-run /openapi.json get /api/v1/projects/{project_id}/evaluation-runs/{eval_run_id} # Get Project Trace Source: https://docs.trajectory.ai/api-reference/projects/get-project-trace /openapi.json get /api/v1/projects/{project_id}/traces/{trajectory_id} # Get Project Training Evaluation Series Source: https://docs.trajectory.ai/api-reference/projects/get-project-training-evaluation-series /openapi.json get /api/v1/projects/{project_id}/training-runs/{training_run_id}/evaluation-series Latest scored checkpoint evaluation reward for a training run, in ascending training-step order. # List Project Deployments Source: https://docs.trajectory.ai/api-reference/projects/list-project-deployments /openapi.json get /api/v1/projects/{project_id}/deployments # List Project Evaluation Runs Source: https://docs.trajectory.ai/api-reference/projects/list-project-evaluation-runs /openapi.json get /api/v1/projects/{project_id}/evaluation-runs # List Project Spec Versions Source: https://docs.trajectory.ai/api-reference/projects/list-project-spec-versions /openapi.json get /api/v1/projects/{project_id}/specs/versions Page spec snapshots by creation time and spec ID, both descending. Cursors are opaque and bound to the organization, project, and name. Traversal is not a snapshot; use next_cursor while has_more is true. An existing project with no matching snapshots returns an empty page. # List Project Specs Source: https://docs.trajectory.ai/api-reference/projects/list-project-specs /openapi.json get /api/v1/projects/{project_id}/specs List the latest snapshot for each spec name under a project. # List Project Traces Source: https://docs.trajectory.ai/api-reference/projects/list-project-traces /openapi.json get /api/v1/projects/{project_id}/traces # List Project Training Runs Source: https://docs.trajectory.ai/api-reference/projects/list-project-training-runs /openapi.json get /api/v1/projects/{project_id}/training-runs # List projects Source: https://docs.trajectory.ai/api-reference/projects/list-projects /openapi.json get /api/v1/projects List your organization’s projects, newest first. # Update a project Source: https://docs.trajectory.ai/api-reference/projects/update-a-project /openapi.json patch /api/v1/projects/{project_id} Change a project’s name or description. # Update Project Trace Feedback Source: https://docs.trajectory.ai/api-reference/projects/update-project-trace-feedback /openapi.json patch /api/v1/projects/{project_id}/traces/{trajectory_id} Record delayed customer feedback, including after a trajectory completes. Omitted fields are preserved; null clears a field. Feedback does not change recorded trajectory rewards or launch training. # Copy Spec To Project Source: https://docs.trajectory.ai/api-reference/public-specs/copy-spec-to-project /openapi.json post /api/v1/projects/{project_id}/specs/copy Copy a public spec version into this project as a new, editable spec, in the background: poll getSpecOperation until it succeeds. Retrying with the same Idempotency-Key returns the same operation; the key with a different request returns 409. # List Public Specs Source: https://docs.trajectory.ai/api-reference/public-specs/list-public-specs /openapi.json get /api/v1/public-specs List all published spec versions, marking the latest within each spec. # Create a secret Source: https://docs.trajectory.ai/api-reference/secrets/create-secret /openapi.json post /api/v1/secrets Store a named credential in your organization for use by spec runtimes. # List secrets Source: https://docs.trajectory.ai/api-reference/secrets/list-user-secrets /openapi.json get /api/v1/secrets List your organization’s stored secret names and metadata. Secret values are not returned. # Revoke a secret Source: https://docs.trajectory.ai/api-reference/secrets/revoke-secret /openapi.json delete /api/v1/secrets/{secret_id} Revoke a stored organization secret by its ID. # Count Spec Findings Source: https://docs.trajectory.ai/api-reference/spec-findings/count-spec-findings /openapi.json post /api/v1/specs/diagnostics/findings/counts Read open and resolved counts for up to 200 targets in one consistent snapshot. Results follow the request order and include targets with zero findings. # Create Spec Finding Source: https://docs.trajectory.ai/api-reference/spec-findings/create-spec-finding /openapi.json post /api/v1/specs/diagnostics/findings Create a finding attached to a spec, one of its tasks, or a trajectory for that task. Evidence can cite other resources in the same organization. Retrying with the same Idempotency-Key and request content returns the original finding. # Get Spec Finding Source: https://docs.trajectory.ai/api-reference/spec-findings/get-spec-finding /openapi.json get /api/v1/specs/diagnostics/findings/{finding_id} # List Spec Findings Source: https://docs.trajectory.ai/api-reference/spec-findings/list-spec-findings /openapi.json get /api/v1/specs/diagnostics/findings List findings for an exact spec, task, or trajectory target. Set include_descendants to also include findings on its child resources. Results are ordered newest first. # Resolve Spec Finding Source: https://docs.trajectory.ai/api-reference/spec-findings/resolve-spec-finding /openapi.json post /api/v1/specs/diagnostics/findings/{finding_id}/resolve Resolve a finding. Send an empty JSON object to omit the note. Repeated calls return the original resolution. # Allocate submission uploads Source: https://docs.trajectory.ai/api-reference/spec-ingestion/allocate /openapi.json post /api/v1/specs/ingestion/sessions/{operation_id}/uploads Request upload URLs for files declared in a spec submission. # Cancel a spec upload Source: https://docs.trajectory.ai/api-reference/spec-ingestion/cancel /openapi.json post /api/v1/specs/ingestion/sessions/{operation_id}/cancel Cancel an uploading session; finalized submissions cannot be cancelled. # Create a spec submission Source: https://docs.trajectory.ai/api-reference/spec-ingestion/create-session /openapi.json post /api/v1/specs/ingestion/sessions Create or resume an asynchronous spec submission. Use the session ID to allocate uploads, finalize the submission, and inspect its operation. # Finalize a spec submission Source: https://docs.trajectory.ai/api-reference/spec-ingestion/finalize /openapi.json post /api/v1/specs/ingestion/sessions/{operation_id}/finalize Finish submitting uploaded files and request processing of the spec package. Inspect the operation to follow registration and any requested environment builds. # List submission results Source: https://docs.trajectory.ai/api-reference/spec-ingestion/items /openapi.json get /api/v1/specs/ingestion/operations/{operation_id}/{kind} List task, runtime, or failure results for a spec submission, using kind to select the result type. # Get submission progress Source: https://docs.trajectory.ai/api-reference/spec-ingestion/status /openapi.json get /api/v1/specs/ingestion/operations/{operation_id} Retrieve a spec submission’s status, processing stage, progress counts, and failures. # Upload Failures Source: https://docs.trajectory.ai/api-reference/spec-ingestion/upload-failures /openapi.json get /api/v1/specs/ingestion/upload-failures # Build spec environments Source: https://docs.trajectory.ai/api-reference/specs/build-spec-images /openapi.json post /api/v1/specs/{spec_id}/images/build Start building the spec’s unbuilt task environment images. Builds run asynchronously; inspect image status or spec readiness before launching a run. # Commit a task append Source: https://docs.trajectory.ai/api-reference/specs/commit-spec-task-append /openapi.json post /api/v1/specs/{spec_id}/tasks/append/{batch_id}/commit Validate and publish the submitted tasks. New tasks are added, changed tasks replace the matching names, and identical tasks are skipped. Committing the same batch again does not duplicate its tasks. # Create a task append upload Source: https://docs.trajectory.ai/api-reference/specs/create-spec-task-append /openapi.json post /api/v1/specs/{spec_id}/tasks/append Allocate upload URLs for a batch of spec task files. Commit the returned batch ID to publish the tasks. # Create a spec upload Source: https://docs.trajectory.ai/api-reference/specs/create-spec-upload /openapi.json post /api/v1/specs/uploads Allocate upload URLs for a batch of spec files. Omit bench_id for a new spec, or reuse the returned ID for subsequent batches. Uploading files does not register the spec; submit its manifest to the ingestion operation afterward. # Delete a spec Source: https://docs.trajectory.ai/api-reference/specs/delete-spec /openapi.json delete /api/v1/specs/{spec_id} Delete a spec, its tasks and associated results, and runtimes no longer used by another spec. Shared runtimes, pipeline execution records, and stored artifacts are preserved. # Delete a spec task Source: https://docs.trajectory.ai/api-reference/specs/delete-spec-task /openapi.json delete /api/v1/specs/{spec_id}/tasks/{task_id} Delete one task and its associated task metadata. Stored artifacts are preserved because other spec snapshots may still reference them. # Compare spec tasks Source: https://docs.trajectory.ai/api-reference/specs/diff-spec-tasks /openapi.json post /api/v1/specs/{spec_id}/tasks/diff Compare submitted tasks with the stored spec and identify new tasks, unchanged tasks, and tasks with updated content. # Get a spec Source: https://docs.trajectory.ai/api-reference/specs/get-spec /openapi.json get /api/v1/specs/{spec_id} Retrieve a spec’s details by ID. # Get Spec Operation Source: https://docs.trajectory.ai/api-reference/specs/get-spec-operation /openapi.json get /api/v1/specs/operations/{operation_id} Get a spec split change or public spec copy, which runs in the background. # Check spec readiness Source: https://docs.trajectory.ai/api-reference/specs/get-spec-readiness /openapi.json get /api/v1/specs/{spec_id}/readiness Check whether ingestion is complete, required secrets are available, and task environments are built. The response identifies any remaining blockers. # Get Spec Task Append Result Source: https://docs.trajectory.ai/api-reference/specs/get-spec-task-append-result /openapi.json get /api/v1/specs/{spec_id}/tasks/append/{batch_id}/result Read the original finalized append receipt after losing a commit response, without resubmitting the commit. not_finalized means no receipt is recorded and the outcome is unknown: some or all tasks may already be applied. It does not establish whether the batch was submitted or is still running. Keep polling this read-only endpoint for a finalized receipt rather than resubmitting an uncertain commit. # Get Spec Task Env Resources Source: https://docs.trajectory.ai/api-reference/specs/get-spec-task-env-resources /openapi.json get /api/v1/specs/{spec_id}/tasks/{task_id}/env_resources Return the CPU, memory, GPU and network settings of one spec task's sandbox. # Get Spec Task Readiness Source: https://docs.trajectory.ai/api-reference/specs/get-spec-task-readiness /openapi.json get /api/v1/specs/{spec_id}/task-readiness # Register a spec manifest Source: https://docs.trajectory.ai/api-reference/specs/ingest-spec /openapi.json post /api/v1/specs/{spec_id}/ingest Validate and register a spec manifest after uploading its files. Use the spec ID returned when you created the upload. # List spec images Source: https://docs.trajectory.ai/api-reference/specs/list-spec-images /openapi.json get /api/v1/specs/{spec_id}/images List task environment images and their build states. This request also refreshes the status of builds that are in progress. # List Spec Runtimes Source: https://docs.trajectory.ai/api-reference/specs/list-spec-runtimes /openapi.json get /api/v1/specs/{spec_id}/runtimes Runtimes used by the spec's tasks, in ascending runtime-ID order. Build status is the stored value; listBenchmarkImages refreshes in-flight provider builds. # List spec runtimes Source: https://docs.trajectory.ai/api-reference/specs/list-spec-runtimes-1 /openapi.json get /api/v1/specs/runtimes List registered spec runtimes in your organization. # List Spec Tasks Source: https://docs.trajectory.ai/api-reference/specs/list-spec-tasks /openapi.json get /api/v1/specs/{spec_id}/tasks Lists the spec's tasks in upload order, with appended tasks after earlier ones. Tasks uploaded before upload order was recorded come first, in creation order. `order=desc` reverses the list. # List Spec Tools Source: https://docs.trajectory.ai/api-reference/specs/list-spec-tools /openapi.json get /api/v1/specs/{spec_id}/tools Tools bound to any task of the spec, in ascending tool-ID order. # List specs Source: https://docs.trajectory.ai/api-reference/specs/list-specs /openapi.json get /api/v1/specs List the specs available to your organization. # Set Spec Task Split Source: https://docs.trajectory.ai/api-reference/specs/set-spec-task-split /openapi.json post /api/v1/specs/{spec_id}/tasks/split Move up to 5,000 tasks into train or test by creating a new latest version of the spec, with new task IDs; the spec itself is unchanged. Any unknown task ID refuses the request. The version is copied in the background: poll getSpecOperation until it succeeds. # Get a spec Source: https://docs.trajectory.ai/api-reference/specs/spec-details /openapi.json get /api/v1/specs/{spec_id}/details Retrieve a spec’s recorded tasks, tools, and runtimes. # Get a spec task count Source: https://docs.trajectory.ai/api-reference/specs/spec-task-count /openapi.json get /api/v1/specs/{spec_id}/task-count Retrieve the number of tasks in a spec. # Update Spec Task Env Resources Source: https://docs.trajectory.ai/api-reference/specs/update-spec-task-env-resources /openapi.json patch /api/v1/specs/{spec_id}/tasks/{task_id}/env_resources Change the CPU, memory, GPU or network settings of one spec task's sandbox without uploading the task again. Only the fields in the request change. Rollouts that start after the change use it; sandboxes already running keep the settings they started with. # List evaluation models Source: https://docs.trajectory.ai/api-reference/supported-models/list-supported-eval-models /openapi.json get /api/v1/models/supported-eval-models List the supported model slugs available for evaluation. # List training models Source: https://docs.trajectory.ai/api-reference/supported-models/list-supported-training-models /openapi.json get /api/v1/models/supported-training-models List the model catalog supported for training. Use training options to inspect settings for a model and spec. # Ingest telemetry events Source: https://docs.trajectory.ai/api-reference/telemetry/ingest-events /openapi.json post /api/v1/telemetry/events Record application events independently of trajectory completion. Use stable event IDs for retry deduplication and trajectory_id to link known trajectories. Telemetry does not automatically become a training reward. Using these events for production learning, with or without an existing grader, requires private-beta access. # Complete Trace Upload Source: https://docs.trajectory.ai/api-reference/trace-sources/complete-trace-upload /openapi.json post /api/v1/trace-sources/{source_id}/uploads/{upload_id}/complete Notify the platform that the batch file has been pushed to its signed GCS URL. Verifies the stored object and starts trace ingestion; poll the upload for per-trace outcomes. # Create Trace Source Source: https://docs.trajectory.ai/api-reference/trace-sources/create-trace-source /openapi.json post /api/v1/trace-sources Create a source whose OpenTelemetry traces become trajectories of an agent. # Create Trace Upload Source: https://docs.trajectory.ai/api-reference/trace-sources/create-trace-upload /openapi.json post /api/v1/trace-sources/{source_id}/uploads Reserve a direct GCS upload for OTLP JSON or JSONL traces, at most 32 MiB, 1,000 traces, and 50,000 spans per file. PUT the file to `upload_url` with `upload_headers`, then call complete to begin ingestion. # Get Trace Source Source: https://docs.trajectory.ai/api-reference/trace-sources/get-trace-source /openapi.json get /api/v1/trace-sources/{source_id} Retrieve a trace source. # Get Trace Upload Source: https://docs.trajectory.ai/api-reference/trace-sources/get-trace-upload /openapi.json get /api/v1/trace-uploads/{upload_id} Retrieve a trace upload's status and per-trace outcomes. # Add training samples Source: https://docs.trajectory.ai/api-reference/training/add-training-samples /openapi.json post /api/v1/train/{run_id}/samples Private beta: add completed, graded production trajectories to a streaming training run. Both production learning workflows, with or without an existing grader, require private-beta access. Traces need validated grading criteria before they can supply a learning signal. # Cancel a training run Source: https://docs.trajectory.ai/api-reference/training/cancel-training-run-route /openapi.json post /api/v1/train/{run_id}/cancel Request cancellation of a pending or running training run. # Create Sft Training Run Route Source: https://docs.trajectory.ai/api-reference/training/create-sft-training-run-route /openapi.json post /api/v1/train_sft Create and launch a supervised fine-tuning run on a finalized dataset version: it trains on the version's train trajectories and reports held-out loss on its test trajectories. # Create Training Run Route Source: https://docs.trajectory.ai/api-reference/training/create-training-run-route /openapi.json post /api/v1/train_rl Create and launch a reinforcement learning run. # Start a training run Source: https://docs.trajectory.ai/api-reference/training/create-training-run-route-1 /openapi.json post /api/v1/train Create and launch a training run. Spec training is part of the public workflow; training from production traces requires private-beta access, with or without an existing grader. Save the returned run ID and inspect progress before using a candidate checkpoint. # Delete a training run Source: https://docs.trajectory.ai/api-reference/training/delete-training-run-route /openapi.json delete /api/v1/train/{run_id} Delete a terminal training run. Cancel a pending or active run before deleting it. # Get Held Out Losses By Step Source: https://docs.trajectory.ai/api-reference/training/get-held-out-losses-by-step /openapi.json get /api/v1/train/{run_id}/step/held-out-loss-by-step Held-out loss and sample coverage for a supervised fine-tuning run, in ascending training-step order. Step 0 scores the starting weights. Runs that score held-out rollouts by reward report them through the held-out reward route instead. # Get held-out rewards by step Source: https://docs.trajectory.ai/api-reference/training/get-held-out-rewards-by-step /openapi.json get /api/v1/train/{run_id}/step/held-out-reward-by-step Retrieve validation rewards and trajectory counts grouped by training step. # Get SFT Step Metrics Source: https://docs.trajectory.ai/api-reference/training/get-sft-step-metrics /openapi.json get /api/v1/train_sft/{run_id}/step-metrics Trainer timing, throughput, learning rate and training loss for each committed SFT update. # Get Sft Training Options Route Source: https://docs.trajectory.ai/api-reference/training/get-sft-training-options-route /openapi.json get /api/v1/train_sft/options Return the models SFT can fine-tune and each SFT option's limits and default. # Get a training checkpoint Source: https://docs.trajectory.ai/api-reference/training/get-training-checkpoint-route /openapi.json get /api/v1/train/{run_id}/checkpoints/{step_index} Resolve a committed checkpoint at a selected training step. Use its checkpoint ID for evaluation or deployment. # Get training options Source: https://docs.trajectory.ai/api-reference/training/get-training-options-route /openapi.json get /api/v1/train/options Retrieve supported training models and the allowed ranges and defaults for their settings. # Get training progress Source: https://docs.trajectory.ai/api-reference/training/get-training-progress-route /openapi.json get /api/v1/train/{run_id}/progress Retrieve a training run’s status, reported step counts, and any failure. # Get a training run Source: https://docs.trajectory.ai/api-reference/training/get-training-run-route /openapi.json get /api/v1/train/{run_id} Retrieve a training run’s configuration, recorded status, and any failure. # Get Training Step Group Stats Route Source: https://docs.trajectory.ai/api-reference/training/get-training-step-group-stats-route /openapi.json get /api/v1/train/{run_id}/steps/{step}/group-stats Authoritative task-group outcome counts across the optimizer batch and checkpoint samples, independent of loaded pages. Diagnostic group counts may overlap. # Get Training Step Metrics Source: https://docs.trajectory.ai/api-reference/training/get-training-step-metrics /openapi.json get /api/v1/train/{run_id}/step-metrics Trainer timing, throughput, sequences per trajectory and k3 KL estimates for each committed update of a training run, in ascending training-step order. Steps trained before these metrics were recorded do not appear, and fields added later are null on earlier steps. # Get training step summaries Source: https://docs.trajectory.ai/api-reference/training/get-training-step-summaries /openapi.json get /api/v1/train/{run_id}/step-summaries Retrieve trajectory, group, and termination summaries for each recorded training step. # Get training trajectory rewards Source: https://docs.trajectory.ai/api-reference/training/get-training-trajectory-rewards-route /openapi.json get /api/v1/train/{run_id}/steps/{step}/trajectory-rewards Retrieve recorded trajectory rewards for one training step. # List Training Checkpoints Route Source: https://docs.trajectory.ai/api-reference/training/list-training-checkpoints-route /openapi.json get /api/v1/train/{run_id}/checkpoints List committed checkpoints in ascending step and checkpoint-ID order. # List Training Presets Route Source: https://docs.trajectory.ai/api-reference/training/list-training-presets-route /openapi.json get /api/v1/train/presets List named training presets. Pass a preset_id as `preset` when creating a training run; explicit options override the preset's values. # List training runs Source: https://docs.trajectory.ai/api-reference/training/list-training-runs-route /openapi.json get /api/v1/train/{bench_id}/runs List the training runs associated with a spec. # List Training Step Groups Route Source: https://docs.trajectory.ai/api-reference/training/list-training-step-groups-route /openapi.json get /api/v1/train/{run_id}/steps/{step}/groups Complete task groups, with the selected optimizer step's batch first and other checkpoint samples afterward. Limit counts groups; every attempt in a selected group is returned together. Filters include whole matching groups. Cursors retain a read snapshot for 30 minutes. # List training step trajectories Source: https://docs.trajectory.ai/api-reference/training/list-training-step-trajectories /openapi.json get /api/v1/train/{run_id}/steps/{step}/trajectories Retrieve a page of one training step’s trajectories, including rewards, termination reasons, tool failures, and group outcomes. The sort presets are errors, mixed, success, and failed. The search parameter is currently ignored. # Update Training Run Route Source: https://docs.trajectory.ai/api-reference/training/update-training-run-route /openapi.json patch /api/v1/train/{training_run_id} Update a training run. # Complete a trajectory Source: https://docs.trajectory.ai/api-reference/trajectories/complete-trajectory-route /openapi.json post /api/v1/trajectories/{trajectory_id}/complete Finish a trajectory after its model calls, reward writes, and event writes have ended. The termination reason records how the interaction ended; normal completion does not imply a positive reward. # Create a trajectory Source: https://docs.trajectory.ai/api-reference/trajectories/create-a-trajectory /openapi.json post /api/v1/trajectories Create a trajectory for the supplied project or the organization’s default project and return its ID. In a managed run, return the run’s existing trajectory ID. Reuse the same idempotency key when retrying the same creation request. Production learning workflows require private-beta access. # Delete Trajectory Source: https://docs.trajectory.ai/api-reference/trajectories/delete-trajectory /openapi.json delete /api/v1/trajectories/{trajectory_id} Delete a finished capture; one still in use by a run, grade or dataset conflicts. # Get a trajectory Source: https://docs.trajectory.ai/api-reference/trajectories/detail /openapi.json get /api/v1/trajectories/{trajectory_id} Retrieve a trajectory by ID. Set include_steps to include its recorded steps. # Get Trajectory Deletion Source: https://docs.trajectory.ai/api-reference/trajectories/get-trajectory-deletion /openapi.json get /api/v1/trajectories/{trajectory_id}/deletion Read a deleted capture's deletion status; shared artifacts retain their other owners. # List trajectories Source: https://docs.trajectory.ai/api-reference/trajectories/list-trajectories-route /openapi.json get /api/v1/trajectories List accessible trajectories with optional training run and search filters. # List trajectory events Source: https://docs.trajectory.ai/api-reference/trajectories/list-trajectory-events /openapi.json get /api/v1/trajectories/{trajectory_id}/events Read events submitted to a trajectory, newest first. The response contains event payloads without telemetry metadata. # Record a trajectory event Source: https://docs.trajectory.ai/api-reference/trajectories/log-trajectory-event /openapi.json post /api/v1/trajectories/{trajectory_id}/events Record a named event while the trajectory is running. Reuse the event ID for retries. Event payloads do not affect the training reward. # Record a trajectory reward Source: https://docs.trajectory.ai/api-reference/trajectories/log-trajectory-reward /openapi.json post /api/v1/trajectories/{trajectory_id}/rewards Record a numeric reward component before the trajectory is complete. Reuse the reward ID when retrying the same component. # List trajectory steps Source: https://docs.trajectory.ai/api-reference/trajectories/steps /openapi.json get /api/v1/trajectories/{trajectory_id}/steps Read the recorded model steps for a trajectory. # Authentication Source: https://docs.trajectory.ai/authentication Sign in from your terminal, reuse saved credentials in Python, switch organization profiles, and configure API keys for unattended jobs. Run `tj login` to authorize your terminal in the browser. Your Python code can then use `Client()` without copying a key into a script or a coding-agent prompt. ## Sign in ```bash theme={null} tj login tj whoami ``` Open the displayed link, sign in, complete any required account setup, and approve the code shown in your terminal for the intended organization. Login saves a credential locally. On first login, an interactive terminal offers project setup; you can skip it and run `tj init` later. Setup can open Claude Code, Codex, or Gemini CLI in your project with the integration instructions and this login profile. See [assistant setup](/guides/cli#continue-with-a-coding-assistant). ```python theme={null} from trajectory import Client with Client() as client: organization = client.organizations.retrieve_current() print(organization["organization_key"]) ``` `retrieve_current()` returns a dictionary with `organization_key` and `organization_id`. For an SSH session or a machine without a browser: ```bash theme={null} tj login --no-browser ``` Open the displayed URL on another device. The CLI waits up to 600 seconds by default. Use `--timeout SECONDS` to shorten the wait. The server expires the code after ten minutes, even if you pass a larger timeout. An expired login needs a new code. If the CLI reports an uncertain redemption after losing its connection, review and revoke the new CLI key in **Settings → API keys** before trying again. ## Organization profiles Create a named profile when authorizing another organization or API: ```bash theme={null} tj login --profile work --expected-organization-key acme tj profiles list tj profiles use work tj whoami --json ``` Use `--profile work` on a command or set `TRAJECTORY_PROFILE=work` to select it without changing the saved default. Python also accepts `Client(profile="work")`. `whoami` verifies the credential and reports its organization and source. A profile name is a local label. The organization you approve in the browser determines the credential's scope. Pass `--expected-organization-key` to check the organization key before accepting or saving a login. If the check fails, see [organization mismatch recovery](/reference/troubleshooting#login-reports-organization_mismatch). A saved profile belongs to one API origin. Selecting another `--base-url` cannot send that saved credential to the new destination. An explicitly selected profile with a mismatched origin returns an error. ## API keys and automated jobs For CI or another unattended environment, supply an API key from **Settings → API keys** through your environment's secret management: ```bash theme={null} export TRAJECTORY_API_KEY="YOUR_TRAJECTORY_API_KEY" tj whoami --json ``` Credential precedence is an explicit `Client(api_key=...)`, then `TRAJECTORY_API_KEY`, then the selected saved profile. An environment key continues to take precedence after switching profiles. The CLI never prints the credential. The login check applies to the profile. Unset `TRAJECTORY_API_KEY` and run `tj whoami` to verify that profile before using it. `Client()` sends the key as `X-API-Key`. Without a saved profile or explicit destination, the API is `https://api.trajectory.ai`. Set `TRAJECTORY_BASE_URL` or pass `base_url` for another destination. Saved login files live under `$XDG_CONFIG_HOME/trajectory`, or `~/.config/trajectory`. Set `TRAJECTORY_CONFIG_HOME` to choose the directory directly. Keep that directory private and outside your project; it contains credentials. On POSIX systems, the directory has mode `700` and credential files have mode `600`. ## Sign out ```bash theme={null} tj logout ``` Logout revokes the selected saved profile's key and removes that profile locally. If revocation fails, the CLI retains the credential so you can retry. Environment credentials are managed separately and are not revoked by this command. ## Managed spec sessions A spec task receives a scoped `TRAJECTORY_API_KEY`. Use `Client()` for model calls and writes. Pass the ID from `trajectories.create()` to model, reward, and completion calls. To read the event journal, [use an external reader](/guides/telemetry#read-managed-task-events). [Production traces](/guides/production-traces) use the organization API key throughout. # Use a coding agent Source: https://docs.trajectory.ai/coding-agents Install Trajectory skills and get platform links as your agent works. The `trajectory` skill guides SDK work and reports progress with platform links. The separate `agent-feedback` skill handles product feedback when you authorize it. ## Install Add the latest `trajectory-sdk` to your project, then install both skills: ```bash theme={null} npx skills add https://docs.trajectory.ai --skill trajectory --skill agent-feedback ``` Choose your coding agent when prompted. Skill installation does not install or upgrade the Python SDK. Set `TRAJECTORY_API_KEY` before making API calls. > [accordion] Python-only installation > > The SDK also bundles both complete skill folders. > Find them from your project's Python environment: > > ```bash theme={null} > python -c "import importlib.metadata as m; print('\n'.join(str(f.locate().resolve().parent) for f in m.files('trajectory-sdk') if f.name == 'SKILL.md'))" > ``` > > Copy both folders into your coding agent's project skills directory: `.agents/skills/` > for Codex, `.claude/skills/` for Claude Code, or `.cursor/skills/` for Cursor. > Review local edits before replacing existing files. ## Refresh Run `npx skills update`, or recopy the bundled folders after upgrading the SDK. Ask an active agent to reload the skills. Keep project-specific instructions in your project's agent instructions file. ## Start a task Use the platform's **Copy setup prompt**, or ask your agent to read the `trajectory` skill and perform your task. Include the selected project or spec. Expect a platform link when work starts, then the outcome and a link to inspect the result. See [platform links](/platform) or the [GSM8K walkthrough](https://github.com/Trajectorylabs/trajectory-cookbook/tree/main/examples/gsm8k). # Core concepts Source: https://docs.trajectory.ai/concepts Projects, specs, trajectories, and the model you serve. ## Project A [project](/projects) holds specs, training history, and the serving model for one behavior. Your harness runs the agent loop and tools. ## Spec A spec is tasks, a runtime, and a grader. Each task is one problem and the inputs the harness needs. Train on the train split. Evaluate on the test split. Wait until the uploaded spec is ready before you start a run. ## Trajectory A trajectory is one attempt at a task: messages, model responses, tool calls, and rewards. A **step** is one model decision. Call `complete` when the attempt is finished. Spec runs create trajectories for tasks. In the private beta, production traces are trajectories from your application, stored on the project. ## Reward and telemetry A **reward** is the grader's score for an attempt. Use the same grader when you compare models. **Telemetry** records what happened around the attempt, such as a tool result or a user action. [Record telemetry](/guides/telemetry). ## Training, evaluation, and deployment A **training run** produces **checkpoints** and, by default, runs **validation** on held-out tasks as it goes. An **evaluation** scores a model, checkpoint, or deployment on a spec. A **deployment** serves a checkpoint. Promote the one your application should call. ```mermaid theme={null} flowchart LR B[Ready spec] --> E[Optional baseline] B --> T[Training] T --> C[Checkpoint] C --> V[Checkpoint evaluation] E -. compare on the same spec .-> V V --> D[Deploy] ``` # Download a checkpoint Source: https://docs.trajectory.ai/guides/checkpoint-downloads Private beta: download a checkpoint's LoRA adapter or merged model. > [!NOTE] > > Private beta. Your organization needs access; otherwise these calls return 403 `beta_not_enabled`. Contact Trajectory to request it. These helpers may change in a minor release. Requires `trajectory-sdk` 0.10.11 or later. Download a [checkpoint](/guides/training) to use its weights outside Trajectory. You can download its LoRA adapter, or for supported base models, the full model merged with its base. ## Download with the SDK ```python theme={null} from trajectory import Client from trajectory.lib.beta import download_checkpoint client = Client() checkpoints = client.rl.checkpoints.list("YOUR_TRAINING_RUN_ID") checkpoint = max(checkpoints, key=lambda c: c.step_index) path = download_checkpoint(client, checkpoint.checkpoint_id, "models/") print(path) # models// ``` The first request for a checkpoint prepares its export, which can take several minutes for a large adapter. Later requests reuse it. The directory holds the adapter files and `manifest.json`. | Argument | Default | Behavior | | - | - | - | | `output_dir` | `.` | Parent directory for `/`. | | `overwrite` | `False` | Replace an existing target. Otherwise `FileExistsError` is raised before any request. | | `timeout` | `3600` | Seconds to wait for the export to be ready. `None` waits indefinitely. | | `poll_interval` | `5` | Seconds between status checks. | | `http_client` | New client | Your own `httpx2.Client` for the download. | A failed call leaves nothing behind and starts over the next time. Downloads do not resume. ## Download from the platform Open the training run, select a checkpoint, and choose **Download weights**. The button appears for deployable checkpoints when your organization has access. ## Use the download link yourself `wait_for_checkpoint_export` returns the ready export with a signed link, without downloading anything: ```python theme={null} from trajectory.lib.beta import wait_for_checkpoint_export export = wait_for_checkpoint_export(client, "YOUR_CHECKPOINT_ID") print(export.download.url, export.download.size_bytes, export.download.url_expires_at) ``` The link lasts one hour. `client.beta.checkpoint_exports.retrieve(export.export_id)` returns a new one. `client.beta.checkpoint_exports` also has `create` and `list`, and sends the beta opt-in header for you. ## Handle errors | Error | Meaning | What to do | | - | - | - | | `trajectory.lib.beta.CheckpointExportError` | The export failed or has no download link. The error's `export` attribute holds it. | Call again to retry. | | `TimeoutError` | The wait ended first. The server keeps preparing the export. | Call again to pick it up. | | `zipfile.BadZipFile` | The downloaded ZIP is corrupt. | Call again to download it again. | | 403 `beta_not_enabled` | Your organization doesn't have access. | Contact Trajectory. | | 409 | This checkpoint can't be downloaded. | Only Tinker checkpoints are supported. | ## Download a merged model A merged model is the base model with the adapter merged in, stored as a Hugging Face folder of files. Merged exports work like a batch job: queue the export, poll it, and pull it down once it's ready. Merging can take hours, and a model can be hundreds of gigabytes, so nothing here needs a process that stays open. Your organization needs merged exports enabled separately. ```python theme={null} from trajectory import Client from trajectory.lib.beta import download_merged_export client = Client() # Queue it; this returns right away, and repeat calls reuse the same export export = client.beta.checkpoint_exports.create( "YOUR_CHECKPOINT_ID", body={"export_type": "merged_model", "precision": "bf16"} ) # Poll later, even from another process or machine export = client.beta.checkpoint_exports.retrieve(export.export_id) # Pull it down once it's ready if export.state == "ready": path = download_merged_export(client, export.export_id, "models/") print(path) # models/-merged-bf16/ ``` There's no webhook, and a queued export can't be cancelled. `download_merged_export` downloads files in parallel and checks each against its MD5. If a call fails, for example because a link expired during a long download, call it again: files it finished stay in a hidden `..partial` folder next to the target, and the next call downloads only the rest with fresh links. | Argument | Default | Behavior | | - | - | - | | `output_dir` | `.` | Parent directory for the model folder. | | `overwrite` | `False` | Replace an existing target. Otherwise `FileExistsError` is raised before any file request. | | `max_workers` | `8` | Files downloaded at once. | ### Supported models `client.beta.checkpoint_exports.list(checkpoint_id).available_merge_precisions` lists the formats a checkpoint can use, with each one's size and known limits. | Base model | Precision | Merged size | | - | - | - | | `Qwen/Qwen3.5-4B` | `bf16` | 9.3 GB | | `nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16` | `bf16` | 66 GB | | `z-ai/glm-5.3-flash` | `bf16` | 643 GB | Exports expire after 28 days. A retrieved export then reports `failed`, and queueing it again rebuilds it. ### Merged export errors | Error | Meaning | What to do | | - | - | - | | `CheckpointExportError` | The export isn't a ready merged export. The error's `export` attribute holds it. | Check its state. | | `ValueError` | A file failed its MD5 check and wasn't kept. | Call again to fetch it. | | `requests.HTTPError` or `requests.ConnectionError` | A file failed to download, or its link expired. | Call again; finished files are kept. | | 409 | This base model or precision isn't available, or your organization doesn't have merged exports. | Check the supported models. | Evaluate a merged model on your own serving stack before relying on it, because merging can reduce accuracy, especially at low precision. ## Build a full model yourself For other base models, merging the adapter happens on your side. Tinker's [merge guide](https://tinker-docs.thinkingmachines.ai/cookbook/deployment/export-hf/) covers how, and its supported models are listed in the [Cookbook](https://github.com/thinking-machines-lab/tinker-cookbook/blob/main/tinker_cookbook/weights/README.md). Evaluate the result on your own serving stack, because merging can reduce accuracy, especially at low precision. # Run Trajectory from your terminal Source: https://docs.trajectory.ai/guides/cli Use the Trajectory CLI to sign in, prepare a spec, validate tasks, launch evaluations and training, and reconnect to work from scripts or agents. The Trajectory CLI shares credentials and workflows with the Python SDK. Start with a small spec and a recorded grade, then use the same commands from a coding agent or a script. The primary command is `tj`; `trajectory` remains available as an alias. ## Install and sign in You need Python 3.11 or later. Install the executable with either command: ```bash theme={null} uv tool install trajectory-sdk ``` ```bash theme={null} pip install --upgrade trajectory-sdk ``` ```bash theme={null} tj login tj whoami ``` If you installed with `uv add trajectory-sdk` in a project, use `uv run tj`. See [Authentication](/authentication) for profiles, SSH sessions, and CI credentials. ## Prepare a project ```bash theme={null} tj init ``` Interactive setup verifies your current API key or saved login and shows the organization you are using. If you have no saved login, it opens browser sign-in first; an expired saved login also asks you to sign in again. `TRAJECTORY_API_KEY` takes precedence over profiles. If that key is rejected, replace it or unset it before signing in. After authentication, choose: * **Try an open-source spec**: choose a cookbook example and follow its diagnostic, evaluation, and training steps where supported. * **Bring your own spec**: use the current directory, choose another local directory, or provide a repository URL. The current directory is selected by default. Install `trajectory-sdk[tui]` for the arrow-key menus. Use `--directory PATH` to select a project directly. When this directory has saved setup, **Resume saved setup** appears first. Press Esc to cancel without changing project settings. Explicit source or assistant flags skip the first menu; scripts continue to use saved setup without prompting. For a script, supply the source explicitly. `--json`, `--non-interactive`, and piped input skip authentication and browser login, so local setup can run without credentials: ```bash theme={null} tj init --cookbook gsm8k --assistant copy --json ``` Setup creates `trajectory.toml` and starts no remote work. You can provide `--agent-id` to save the owner for subsequent uploads. ### Bring a customer spec Point setup at the real spec and choose the assistant you want to work with: ```bash theme={null} tj init --repo ./customer-benchmark --assistant codex tj init --repo https://github.com/organization/benchmark --assistant claude tj init --repo git@github.com:organization/private-benchmark.git --assistant gemini ``` A local source becomes the working directory, so you are not asked to select it again. If the project and spec live in separate directories, use `--directory ./my-agent --repo ./customer-benchmark`. The spec directory does not need to be a Git checkout. For a repository link, select a working directory after choosing the assistant. The assistant looks for an existing checkout or prepares one in a new subdirectory using your existing Git authentication. HTTPS links and Git SSH addresses are supported; use links without embedded tokens, query parameters, or fragments. A link to a branch or subdirectory stays in the prompt so the assistant can resolve the intended revision and path. Setup saves the source in `trajectory.toml`; `tj init` offers to resume it. It does not clone or run repository code itself. Use a separate setup directory to switch sources. For a prompt you can use in an existing assistant session: ```bash theme={null} tj init --repo ./customer-benchmark --assistant copy --json ``` The assistant inspects your task loader, agent entry point, tools, runtime, grader, and result reader before asking for missing inputs. It helps reproduce one native task, package the real harness, compare a [managed diagnostic](/guides/spec) with the [native grade](/guides/source-graders), and run a small [held-out evaluation](/guides/evaluations). It preserves your agent and grading behavior, reviews remote submissions with you, and reports observed results and commands to resume. Private data access or missing runtime dependencies may still need your input. ### Continue with a coding assistant Choose **Claude Code**, **Codex**, or **Gemini CLI**. If you chose the current directory or a local spec directory, the assistant opens there. For a cookbook example or repository URL, select a project directory after choosing the assistant; `--directory PATH` skips that prompt. Copy/manual setup uses the current directory unless you supply `--directory`. Installed assistants appear first. Trajectory opens the selected assistant in your project directory with the bundled integration skill, the setup task, and the selected profile and API origin. The assistant uses its existing login and normal permission settings. Your Trajectory credential is not included in the prompt. Spec setup follows the platform's setup prompt: choose the missing spec and model details, confirm a costed plan, then upload, diagnose, and compare two models. For trainable data, the plan includes a small smoke training run and a final-checkpoint evaluation. Evaluation-only data skips training. Your chosen source and saved project are included, so the assistant can reuse those decisions. Select an assistant directly: ```bash theme={null} tj init --assistant codex tj init --directory ./my-agent --template benchmark --assistant claude --profile staging tj init --directory ./my-agent --assistant gemini ``` The assistant inspects your code, helps adapt and validate the integration, and asks before submitting remote work. Closing its session returns to the CLI; `finished` means the assistant exited successfully, not that an evaluation passed. Run `tj init` again to continue, including when the project already has a saved setup choice. Choose **Copy setup prompt** to use another assistant or an existing session. If the local clipboard is unavailable, the CLI prints the prompt. Missing assistants show their installation link and the same prompt. **Continue manually** (or `--assistant manual`) keeps the command-based instructions. Interactive assistants never launch with `--json`, `--non-interactive`, or piped input/output. To generate a prompt for automation: ```bash theme={null} tj init --directory ./my-agent --template benchmark --assistant copy --json ``` The JSON result includes `assistant.prompt`. It does not access the clipboard or start an assistant. A failed assistant launch retains the project files so you can retry; a successful login remains saved even if its subsequent setup is interrupted. For an existing repository, you can also ask your coding agent to follow the bundled integration skill: ```bash theme={null} tj docs --topic skill ``` Your agent still needs to adapt and verify the spec's native tools and grader. The setup command does not automatically convert an arbitrary repository. ## Start from the cookbook Choose **Try an open-source spec** in `tj init`, or select an example directly: ```bash theme={null} tj init --cookbook gsm8k --assistant codex ``` Choose your assistant before selecting the project directory. Setup saves the example in `trajectory.toml`, so `tj init` can resume it. Use another directory to start a different example. The assistant locates an existing cookbook checkout or helps clone one into a new subdirectory, then reads the example's current guide and code. | `--cookbook` value | Example | What to expect | | - | - | - | | `gsm8k` | [GSM8K](https://github.com/Trajectorylabs/trajectory-cookbook/blob/main/examples/gsm8k/README.md) | Recommended first training run: math tasks with an answer-submission tool. | | `t-factory` | [T Factory](https://github.com/Trajectorylabs/trajectory-cookbook/blob/main/examples/t_factory/README.md) | A smaller introduction to responses, rewards, and training. | | `harvey-lab` | [Harvey LAB](https://github.com/Trajectorylabs/trajectory-cookbook/blob/main/examples/harvey_labs/README.md) | Legal research with external judge credentials and nested Podman. | | `tau3-banking` | [Tau 3 Banking](https://github.com/Trajectorylabs/trajectory-cookbook/blob/main/examples/tau3_banking/README.md) | Multi-turn banking with an external user simulator and judge. | | `swe-bench-pro` | [SWE-Bench Pro](https://github.com/Trajectorylabs/trajectory-cookbook/blob/main/examples/swe_bench_pro/README.md) | Code repair with large images and long-running tasks. | | `terminal-bench-4` | [Terminal-Bench 4.0](https://github.com/Trajectorylabs/trajectory-cookbook/blob/main/examples/terminal_bench_4/README.md) | Evaluation only; this example has no official training split. | To get the same example-specific prompt for another coding assistant: ```bash theme={null} tj init --cookbook gsm8k --assistant copy --json --directory ./my-project ``` Read `assistant.prompt` in the JSON result. This command prepares local settings and guidance; it does not clone a repository, access the clipboard, or submit remote work. Use `--assistant manual --non-interactive` for a list of next steps instead. The prompt guides you through prerequisites, a [graded diagnostic](/guides/spec), a small [baseline evaluation](/guides/evaluations), and, for examples with training support, a [training run and checkpoint comparison](/guides/training). It asks you to review the model, task selection, run settings, and budget before submitting work. Some cookbook scripts combine ingestion with diagnostics or evaluation with training; the assistant checks those side effects before recommending a command. Setup and assistant output link to the relevant Trajectory guides as you progress. Training is opt-in, and a small smoke run does not establish that a model improved. ## Upload and validate For cookbook examples, follow the selected example's guide to create and upload its spec. If it already returned a spec ID, use that ID for the readiness and diagnostic commands below. For a customer spec, prepare a [BenchmarkSpec](/guides/spec) from your real tasks, runtime, harness, and grader. Ask your coding assistant to save it as a JSON manifest, or serialize your `BenchmarkSpec` with `spec.model_dump_json(indent=2)`. `tj init` saves project settings; it does not generate this manifest for cookbook or customer specs. The upload command below assumes you saved it as `manifest.json`. List projects and reuse a suitable one, or create one for this work: ```bash theme={null} tj projects list --json tj projects create --name customer-support ``` `tj specs list` returns specs across projects and does not accept `--agent-id`. To find every version for one project, iterate the paginated SDK response with `latest_only=False`, then filter by each spec's `agent_id`. Iterating the page fetches all remaining pages automatically: ```python theme={null} from trajectory import Client client = Client() for spec in client.specs.list(latest_only=False): if spec.agent_id != "PROJECT_ID": continue readiness = client.specs.retrieve_readiness(spec.bench_id, refresh=False) print(spec.bench_id, spec.name, readiness.ready) ``` `refresh=False` reads the stored readiness status without refreshing in-flight builds. This can show a build as still in progress if it has just finished. Replace `AGENT_ID` with the returned project ID and `manifest.json` with your manifest's path: ```bash theme={null} tj specs push --manifest manifest.json --agent-id AGENT_ID --json ``` The response includes an `operation_id`. Wait for registration and image building, then inspect readiness using the operation's `bench_id`: ```bash theme={null} tj operations watch OPERATION_ID --timeout 300 tj specs readiness BENCH_ID tj specs diagnose BENCH_ID --json ``` Use the returned `benchmark_diagnostic_id` to inspect the diagnostic: ```bash theme={null} tj diagnostics watch DIAGNOSTIC_ID --timeout 300 tj diagnostics results DIAGNOSTIC_ID ``` Check recorded outcomes and failures before scaling up. A successful image build alone does not verify the harness or grader. Diagnostics are explicit submissions and do not automatically retry a lost submission response. ### Set diagnostic limits Discover diagnostic models and options, excluding the task counts controlled by the service: ```bash theme={null} tj diagnostics models --json tj diagnostics options --bench-id BENCH_ID --json ``` Save `diagnostic.json` with a model from discovery and limits appropriate to your harness: ```json diagnostic.json theme={null} { "base_model_slug": "MODEL_FROM_OPTIONS", "options": { "max_turns_per_trajectory": 4, "max_output_tokens_per_turn": 2048 } } ``` Validate locally, then submit when ready: ```bash theme={null} tj specs diagnose BENCH_ID --config diagnostic.json --dry-run --json tj specs diagnose BENCH_ID --config diagnostic.json --json tj diagnostics watch DIAGNOSTIC_ID --timeout 300 tj diagnostics results DIAGNOSTIC_ID --json ``` The example limits above are a small smoke budget; preserve your source agent's budgets for a comparable evaluation. Diagnostics run up to ten tasks with one attempt each. Omit `val_num_tasks` and `val_trajectories_per_task`. You can set `val_max_concurrent_trajectories` to limit concurrency; the service caps it at the number of diagnostic tasks. This requires an API release that supports diagnostic concurrency. A dry run validates the local schema without contacting the API; model availability, option bounds, and spec readiness are checked by the service. An HTTP 409 from `diagnostics results` means the diagnostic has not finished. Reconnect with `watch`, then request results; do not submit another diagnostic to poll. ## Run a baseline evaluation Discover models and the selected spec's supported options: ```bash theme={null} tj evals models --json tj evals options --bench-id BENCH_ID --json ``` Create `eval.json`. Replace `BENCH_ID` and `MODEL_FROM_OPTIONS` with values from those responses and use options within the returned bounds: ```json eval.json theme={null} { "bench_id": "BENCH_ID", "base_model_slug": "MODEL_FROM_OPTIONS", "options": { "val_num_tasks": 1, "val_trajectories_per_task": 1 } } ``` Validate the local schema without submitting, then launch: ```bash theme={null} tj evals create --config eval.json --dry-run --json tj evals create --config eval.json --json tj evals watch EVAL_RUN_ID --timeout 300 tj evals details EVAL_RUN_ID --json ``` `--dry-run` checks the local request schema. It does not prove that a spec is ready, a model is available, or your account has sufficient capacity or credits. ## Train and inspect Start from a successful baseline and discover training-specific models and options: ```bash theme={null} tj training options --bench-id BENCH_ID --json tj schema training --json ``` Prepare a training JSON file using that schema and the returned option bounds. Training is a separate explicit action: ```bash theme={null} tj training create --config training.json --dry-run tj training create --config training.json --json tj training watch TRAINING_RUN_ID --timeout 300 tj training details TRAINING_RUN_ID --json ``` Run lists require a spec selection: ```bash theme={null} tj evals list --bench-id BENCH_ID --json tj training list --bench-id BENCH_ID --json ``` Use `--cursor` with the returned pagination cursor for later pages. To request cancellation: ```bash theme={null} tj training cancel TRAINING_RUN_ID ``` Stopping a local `watch` command or closing the terminal does not cancel the remote run. ## Recover a submission The CLI records a request ID before submitting an eval, training run, or spec upload. Repeat the same command to recover that submission, including after a lost connection. An identical run configuration reuses its receipt even after the submission succeeded. To intentionally launch another run with the same config, choose a new request ID: ```bash theme={null} tj evals create --config eval.json --request-id baseline-repeat-2 --json ``` Do not reuse that ID for a different configuration. Spec upload identity also includes packaged file contents, so a changed harness creates a new upload. Receipts are scoped to the credential and API destination and live outside the project. `tj operations list` shows only receipts recorded locally; it does not discover all remote uploads or operations. `get` and `watch` retrieve remote ingestion operations when you already have an operation ID. ## Coding agents and scripts Use `--json` for one JSON result on stdout. Progress and login instructions go to stderr. Ordinary commands never prompt when stdin is not a terminal; `--non-interactive` also disables prompts explicitly. Authentication approval still requires a person. ```bash theme={null} tj schema --json tj schema spec --json tj schema evals --json tj docs --json tj docs --topic index --json ``` The `directory` field from `docs --topic index` locates bundled guides in both wheel and editable installs. In the cookbook picker, Esc returns to source selection; Ctrl+C exits without writing setup files. | Exit code | Meaning | | - | - | | `0` | Command succeeded. A submission may still be running remotely. | | `1` | API, connection, dependency, or local error, or a watched operation finished failed, cancelled, or partially failed. | | `2` | Invalid arguments or configuration. | | `3` | Authentication or access error. | | `4` | Local wait deadline expired; inspect the remote operation before retrying. | | `130` | Interrupted locally. | ## Capture traces or generate a test fixture To instrument an existing project for [production trace capture](/guides/production-traces), start that separate flow explicitly: ```bash theme={null} tj init --template connect --assistant codex ``` Capture requires private-beta access. The assistant checks availability and helps verify one captured trace; selecting this flow does not automatically connect or evaluate the project. For a small local test fixture, `tj init --template example --non-interactive` generates an additional spec under `trajectory-example/`. Repeating setup preserves existing files. These specialized flows are available through flags rather than the spec selection menu. # Train decision models Source: https://docs.trajectory.ai/guides/decision-training Train decision models on labeled choices with RLCD and Brier loss. Train a decision model to choose among fixed answers using labeled examples. Your harness calls the decision API and records an outcome for each choice; RLCD uses those outcomes to train the model's probabilities with Brier loss. The examples below use support-ticket routing to show the workflow. ## What are we training? For each ticket, the model assigns probabilities to `["billing", "technical"]`. The answer it selects is the one with the higher probability. A billing ticket's label is `[1, 0]`; a technical ticket's is `[0, 1]`. Keep that label out of the input you send to the model. RLCD adjusts those probabilities using Brier loss: `0.5 * sum((p[i] - y[i]) ** 2)`, averaged over decisions. Here `p` is the model's probability vector and `y` is the label. The trainer recomputes probabilities at the captured decision position and differentiates through all the choices. Labels can be soft, too: `[0.8, 0.2]` is valid. Values must be finite, between zero and one, and sum to one. A scalar reward can't replace this vector. The SDK supports text and image inputs. Training takes exactly one trainable decision step per trajectory; groups of one are fine. Repeated rollouts and variation in scalar reward aren't needed. ## Inference limits and workarounds Use one `type="choice"` question per request, with 2–26 distinct, nonempty choice values. A decision must be the only inference step in its trajectory, including in evaluation. A second inference step returns HTTP 409. For an evaluation with several decisions, give each decision its own task and trajectory. `predicate` and `score` aren't supported question types. For yes/no, supply those two choices and read the probability of yes. For a numeric rating, supply the rating levels as choices and calculate their probability-weighted average yourself. The API returns a choice and probabilities, not a numeric score. Objects and arrays must be serialized to text, such as `json.dumps(data)`, and sent as `input`: there is no `input_json` part. More than 26 choices won't work in one request. The renderer's labels are the single tokens A–Z. ## 1. Write the harness Save the following as `spec/harness.py`. It reads the ticket and label from environment variables, makes a decision, and records both the training labels and an accuracy reward. ```python harness.py theme={null} import os from trajectory import Client client = Client() tid = client.trajectories.create().tid choices = ["billing", "technical"] expected = os.environ["EXPECTED_CATEGORY"] if expected not in choices: raise ValueError("EXPECTED_CATEGORY must be one of the choices") response = client.decisions.create( model="policy", input=os.environ["TICKET_TEXT"], questions=[{ "type": "choice", "name": "category", "instructions": "Route this support ticket to the appropriate team.", "choices": [{"value": value} for value in choices], }], x_trajectory_id=tid, idempotency_key=f"{tid}:category", ) if response.result is None: raise RuntimeError("Decision did not return a result") for index, value in enumerate(choices): client.trajectories.log_reward( tid, name=f"decision.outcome.{index}", value=float(value == expected), min_value=0, max_value=1, weight=0, extra_body={"reward_id": f"{tid}:outcome:{index}"}, ) client.trajectories.log_reward( tid, name="accuracy", value=float(response.result.choice == expected), weight=1, extra_body={"reward_id": f"{tid}:accuracy"}, ) client.trajectories.complete(tid, termination_reason="ENV_DONE") ``` Trajectory supplies credentials to `Client()` during the run. Use `model="policy"` to call the model being trained or evaluated. Here, "policy" is an alias for that model. This calls `POST /v1/decisions` with `X-Trajectory-Id`. The response's `result` has `choice`, `probabilities`, and `confidence`. Confidence is adjusted for the number of choices: `(max_probability - 1/N) / (1 - 1/N)`. It isn't the selected answer's probability. For a pending request, use the recovery procedure in [errors and retries](/reference/errors). Keep the same idempotency key; don't start a second logical decision. ### The labels to log For our billing ticket, log `decision.outcome.0=1` and `decision.outcome.1=0`. In general, log exactly one `decision.outcome.` per choice, in the original zero-based order, before completing the trajectory. Set each component's weight to zero and bounds to `[0, 1]`. Zero weight keeps labels out of the reported reward. Training reads their raw values anyway. Accuracy is a separate reward for comparing evaluations and doesn't affect the Brier gradient. With only zero-weight components, even a correct answer has an aggregate reward of zero. Don't substitute the chosen answer's reward or a precomputed Brier score for the labels. For retries, reuse each component's distinct `reward_id` through `extra_body`. Leaving it out creates a new ID on each call. ## 2. Upload a decision spec Put this Dockerfile beside the harness: ```dockerfile Dockerfile theme={null} FROM python:3.12-slim WORKDIR /app RUN pip install --no-cache-dir trajectory-sdk COPY harness.py /app/harness.py ``` Save `upload.py` next to the `spec/` directory. Replace `YOUR_AGENT_ID` with a project you've [created or chosen](/projects). ```python upload.py theme={null} from pathlib import Path from trajectory import BenchmarkSpec, Client, TaskSpec from trajectory.lib import DockerfileBuild, push client = Client() spec = BenchmarkSpec( name="Support routing decisions", benchmark_type="decision", runtime=DockerfileBuild("Dockerfile"), tasks=[ TaskSpec( name="billing-training", split="train", run_command="python /app/harness.py", env_vars={ "TICKET_TEXT": "My card was charged twice for the same invoice.", "EXPECTED_CATEGORY": "billing", }, ), TaskSpec( name="technical-held-out", split="test", run_command="python /app/harness.py", env_vars={ "TICKET_TEXT": "The application crashes when I open settings.", "EXPECTED_CATEGORY": "technical", }, ), ], ) uploaded = push( client, spec, agent_id="YOUR_AGENT_ID", root=Path("spec"), build_images=True ) print(uploaded.bench_id) ``` The important field is `benchmark_type="decision"`. A call to the decision API won't turn a generative spec into a decision spec. Only decision specs accept RLCD. These two tickets exercise the workflow; they can't tell you whether training improves a model. Use your own dataset and an independent held-out split for that. Before a full run, check [readiness and diagnostics](/guides/spec). If you add tools to this harness, keep them from reading `EXPECTED_CATEGORY`. ## 3. Evaluate, then train Use the uploaded spec ID and a model that supports decision training. This prints the spec/model's available algorithms, bounds, and defaults, then starts a baseline: ```python theme={null} from trajectory import Client client = Client() bench_id = "YOUR_DECISION_SPEC_ID" model = "YOUR_SUPPORTED_TRAINING_MODEL_SLUG" print(client.rl.list_options(bench_id=bench_id, base_model_slug=model)) baseline = client.evals.create(bench_id=bench_id, base_model_slug=model) print("Baseline:", baseline.eval_run_id) ``` [Wait for it to finish](/guides/evaluations) and check the captured decisions, outcomes, and accuracy. A successful container build doesn't check label logging. Then try a two-step training run: ```python theme={null} run = client.rl.train( bench_id=bench_id, base_model_slug=model, options={ "algorithm": "rlcd", "num_steps": 2, "batch_size": 1, "group_size": 1, "min_trajectories_per_group": 1, "train_on_all_fail": True, "train_on_all_pass": True, "train_on_zero_advantage": True, }, ) print("Training:", run.training_run_id) ``` Leave the three `train_on_*` filters enabled. Groups with identical scalar rewards can still produce Brier updates. `batch_size` counts eligible task groups per update. Check [optimizer steps and checkpoints](/guides/training#3-watch-progress-and-pick-a-checkpoint), not just reward. Cancel if the run exceeds your budget. [Evaluate the checkpoint](/guides/evaluations#3-score-a-checkpoint) on the baseline's spec version and held-out split. Compare your accuracy reward together with the completed and failed counts. The two-ticket example isn't evidence of improvement. To use a checkpoint from another algorithm, set `algorithm="rlcd"` and `load_weights_only=True` in `options`. Full resume needs a compatible algorithm; loading weights alone gives you fresh training state. See [resume](/guides/training#4-resume-from-a-checkpoint). ## Image decisions Use a model whose `input_modalities` includes `image`. [Upload the image](/guides/images) to the same trajectory, then put its artifact ID in the ordered list of input parts: ```json theme={null} { "model": "policy", "input": [ {"type": "text", "text": "Which category describes this picture?"}, {"type": "image", "artifact_id": "YOUR_IMAGE_ARTIFACT_ID"} ], "questions": [{ "type": "choice", "name": "category", "instructions": "Choose the matching category.", "choices": [{"value": "cat"}, {"value": "dog"}] }] } ``` The labels and Brier loss work the same way. Training retains the captured image inputs. ## Troubleshooting See [decision training troubleshooting](/reference/troubleshooting#decision-training-rejects-outcomes-or-captures) for rejected outcomes, missing capture metadata, and training configuration issues. # Deploy and promote Source: https://docs.trajectory.ai/guides/deployments Serve a checkpoint and make it the active model. A deployment serves a [checkpoint](/guides/training) at an OpenAI-compatible endpoint. Deployments accept text only; requests with [image parts](/guides/images) return 400. ## 1. Create a deployment To deploy the exact weights you [evaluated](/guides/evaluations#3-score-a-checkpoint), use the recorded run ID, step, and checkpoint ID. Selecting the latest checkpoint again can pick different weights. For fresh base weights, use an existing deployable step 0 checkpoint from a run whose `client.rl.runs.retrieve(run_id).parent_checkpoint_id` is `None`. ```python theme={null} from trajectory import Client client = Client() checkpoint_step = 0 # Replace with the step you recorded for the selected checkpoint. checkpoint = client.rl.checkpoints.retrieve( "YOUR_TRAINING_RUN_ID", step_index=checkpoint_step, ) if checkpoint.checkpoint_id != "YOUR_CHECKPOINT_ID": raise RuntimeError("This checkpoint does not match the recorded ID") if not checkpoint.is_deployable: raise RuntimeError("This checkpoint has no saved weights for serving") deployment = client.deployments.create( checkpoint_id=checkpoint.checkpoint_id, test_model_slug="my-agent-test", ) print(deployment.deployment_id) ``` ## 2. Test the deployment In the same Python session, wait for `DEPLOYED` and check the returned `checkpoint_id`, `base_model_slug`, and `checkpoint_step` against the checkpoint you selected. ```python theme={null} import time deadline = time.monotonic() + 900 while True: state = client.deployments.retrieve(deployment.deployment_id) if state.status == "DEPLOYED": break if state.status in {"FAILED", "CANCELLED"}: raise RuntimeError(f"Deployment {state.status}. Check deployment status in the console.") if time.monotonic() >= deadline: raise TimeoutError(f"Deployment still {state.status} after 15 minutes") time.sleep(10) if ( state.checkpoint_id != checkpoint.checkpoint_id or state.base_model_slug != checkpoint.base_model_slug or state.checkpoint_step != checkpoint.step_index ): raise RuntimeError("Deployment source does not match the selected checkpoint") ``` To [evaluate the deployed checkpoint](/guides/evaluations#1-start-a-baseline), pass `deployment_id=state.deployment_id` with a spec owned by the deployment's project. For a fair comparison, use the same spec version, tasks, and grader, and match the checkpoint evaluation to the deployment's generation settings. Until it is promoted, a deployment answers only on its own test slug. Install `openai` for this optional smoke test, then query the exact route with a new trajectory ID: ```python theme={null} import os from contextlib import suppress from openai import OpenAI from trajectory import Client trajectory = Client() tid = trajectory.trajectories.create().tid api_origin = os.environ.get("TRAJECTORY_BASE_URL", "https://api.trajectory.ai").rstrip("/") inference = OpenAI( api_key=os.environ["TRAJECTORY_API_KEY"], base_url=f"{api_origin}/api/v1/deploy/{deployment.deployment_id}", ) try: response = inference.chat.completions.create( model=state.test_model_slug, messages=[{"role": "user", "content": "Hello!"}], extra_headers={"X-Trajectory-Id": tid}, ) choice = response.choices[0] answer = (choice.message.content or "").strip() except Exception: with suppress(Exception): trajectory.trajectories.complete(tid, termination_reason="ERROR") raise reason = ( "TRUNCATION" if choice.finish_reason in ("length", "max_tokens") else "ENV_DONE" if choice.finish_reason == "stop" and answer else "ERROR" ) trajectory.trajectories.complete(tid, termination_reason=reason) if reason != "ENV_DONE": raise RuntimeError(f"No complete answer: {choice.finish_reason}") print(answer) ``` The OpenAI-compatible route accepts the organization key as Bearer authentication and requires `X-Trajectory-Id`; SDK resource calls use `X-API-Key`. ### Disable thinking for deployment chat Deployment chat rejects the managed training and evaluation setting `reasoning_effort="off"`. To disable thinking on a supported model, omit `reasoning_effort` and add `extra_body={"disable_thinking": True}` to the OpenAI Python call above. When calling the production slug with `client.chat.completions.create`, pass `disable_thinking=True` directly. A thinking setting configured on the deployment takes precedence over the request. ## 3. Promote Callers reach production through the owning project's production model slug, which is separate from each deployment's test slug. Set it once per project, then promote. Promotion points that slug at this deployment; no separate model-endpoint creation is needed. Both steps are also available from **Deployments** in the platform. ```python theme={null} from trajectory import Client client = Client() state = client.deployments.retrieve(deployment.deployment_id) if state.production_model_slug is None: client.model_slugs.create_production(state.agent_id, production_model_slug="my-agent") # Pass the current production deployment ID instead of None when replacing one. client.deployments.promote(state.deployment_id, expected_deployment_id=None) ``` Call the production slug through the SDK, again with a new trajectory: ```python theme={null} from contextlib import suppress from trajectory import Client client = Client() tid = client.trajectories.create().tid try: response = client.chat.completions.create( model="my-agent", messages=[{"role": "user", "content": "Hello!"}], x_trajectory_id=tid, ) choice = response.choices[0] answer = (choice.message.content or "").strip() except Exception: with suppress(Exception): client.trajectories.complete(tid, termination_reason="ERROR") raise reason = ( "TRUNCATION" if choice.finish_reason in ("length", "max_tokens") else "ENV_DONE" if choice.finish_reason == "stop" and answer else "ERROR" ) client.trajectories.complete(tid, termination_reason=reason) if reason != "ENV_DONE": raise RuntimeError(f"No complete answer: {choice.finish_reason}") print(answer) ``` [Collect production traces](/guides/production-traces) to learn from the application after it is serving. # Keep diagnostic files with a trajectory Source: https://docs.trajectory.ai/guides/diagnostic-artifacts Attach task logs and reports without changing the reward. Use `log_event` for structured JSON and artifacts for files such as test logs or reports. Write events and finish uploads before completing the trajectory. A distinct event needs a distinct `event_id`; reuse an ID only when retrying the same write, because an existing ID is deduplicated rather than updated. To list events from a managed task, see [Read managed task events](/guides/telemetry#read-managed-task-events). ## Upload through the Trajectory API When a task can reach the Trajectory API but can't reach the storage host, use [Store artifact content](/api-reference/artifacts/store-artifact-content). This endpoint accepts managed task credentials and attaches the file in one request. Each upload can contain at most 16 MiB. Compress larger text reports or split them into smaller files. With an active trajectory ID `tid`, upload a compressed report and log its artifact ID: ```python theme={null} import gzip import logging from pathlib import Path from trajectory import Client, TrajectoryError from trajectory.types.artifacts import Artifact logger = logging.getLogger(__name__) client = Client() artifact = None try: content = gzip.compress(Path("report.json").read_bytes(), mtime=0) artifact = client.post( f"/api/v1/trajectories/{tid}/artifacts/content", cast_to=Artifact, content=content, options={ "headers": {"Content-Type": "application/octet-stream"}, "params": {"media_type": "application/gzip"}, }, ) except (OSError, TrajectoryError) as exc: logger.warning("Diagnostic upload failed (%s)", type(exc).__name__) if artifact is not None: try: client.trajectories.log_event( tid, event_id="diagnostic-report", name="diagnostic_report", payload={"artifact_id": artifact.artifact_id, "filename": "report.json.gz"}, ) except TrajectoryError as exc: logger.warning("Diagnostic event failed (%s)", type(exc).__name__) ``` Keep grading, reward reporting, and trajectory completion outside these exception handlers. If a diagnostic write fails, report the actual task result and termination reason as usual. ## Upload directly to storage If the task can reach the storage host, call `client.trajectories.artifacts.create_upload(...)`, send the bytes with `PUT` to `upload.upload_url` using `upload.headers`, then call `client.trajectories.artifacts.complete_upload(tid, upload.artifact_id)`. Handle failures in these steps as diagnostic errors too. Use `client.artifacts.retrieve(artifact_id)` to get the file's `download_url`. Downloading requires access to the storage host. Keep signed URLs out of logs. # Evaluate and compare Source: https://docs.trajectory.ai/guides/evaluations Score a model or checkpoint on a spec. An evaluation runs a [spec](/guides/spec) and reads the grader's rewards. Use `bench_id` to select an exact spec version. `agent_name` with `benchmark_name` selects that project's latest version; `agent_id` identifies ownership but does not select a spec by itself. A baseline scores a selected model or ready deployment on a ready spec before training. Run it when you want a score to compare with later checkpoints. The **Evaluation** tab records managed evaluation scores. Measure scripted or replayed trials separately. ## 1. Start a baseline Before uploading a spec, use `list_models()` to choose an evaluation model and estimate token costs. Each item includes `base_model_slug`, `model_name`, and input/output pricing in USD per million tokens. Evaluation and training catalogs can have different models and prices. See [pricing](/pricing) for other charges. ```python theme={null} from trajectory import Client from trajectory.lib.platform_links import PlatformLinks client = Client() links = PlatformLinks.from_client(client) for model in client.evals.list_models().items: print(model.base_model_slug, model.model_name, model.pricing.input, model.pricing.output) ``` Check each entry's `input_modalities` before uploading. The catalog describes the hosted configuration, which can differ from the model publisher's capabilities. Managed actor audio input is unsupported. See [managed actor input modalities](/guides/spec#managed-actor-input-modalities). Use `list_options()` for supported settings, bounds, and defaults, without pricing. It also works before a spec exists; `bench_id` is deprecated and ignored. Pass `base_model_slug` to filter to one model, or omit it to list all evaluation models: ```python theme={null} for model in client.evals.list_options().models: print(model.base_model_slug, model.options) ``` Once the spec is ready, use its `bench_id` to start the baseline: ```python theme={null} bench_id = "YOUR_BENCHMARK_ID" run = client.evals.create( bench_id=bench_id, base_model_slug="YOUR_SUPPORTED_MODEL_SLUG", options={"val_num_tasks": 16}, display_name="Baseline", ) print("Evaluation:", run.eval_run_id, links.evaluation(run.eval_run_id)) ``` An evaluation accepts these `options` ([training options](/guides/training#training-options) describes each): `val_num_tasks`, `val_trajectories_per_task`, `val_max_concurrent_trajectories`, `val_final_wait_timeout_seconds`, `reasoning_effort`, `temperature`, `top_p`, `top_k`, `trajectory_timeout_seconds`, `max_output_tokens_per_turn`, `max_output_tokens_per_trajectory`, `max_turns_per_trajectory`, and `image_max_pixels`. Other options return 422\. Use `list_options` to read evaluation defaults, or omit `options` to use them. See [managed model calls](/guides/spec#call-the-model-using-trajectory-client) for how `max_output_tokens_per_turn` applies to each request. Training and standalone evaluation both default to 200 turns per trajectory. For base-model evaluation, use `options={"reasoning_effort": "off"}` at launch to disable thinking if the model advertises `off` in `list_options()`. The configured reasoning settings take precedence over request flags. If a reply ends with `finish_reason="length"`, check for a complete answer before grading it. An evaluation runs the spec's `test` tasks by default; pass `task_split="train"` for train-only evaluation or `task_split="all"` for both splits. This selects tasks for the evaluation, but it does not change the dataset split for its trajectories: `datasets.add_trajectories(eval_run_ids=...)` always adds scored attempts from completed eval runs to `heldout`, and the public API has no destination split override. Omit `val_num_tasks` to run every selected task. To evaluate a ready deployment owned by the spec's project, pass `deployment_id=` instead of `base_model_slug`; it uses the deployment's sampling, token, and turn settings, so those options return 422. For a frozen task roster, publish a spec version whose `test` split contains exactly the intended tasks. Pass that version's `bench_id` and omit `val_num_tasks`. The evaluation API accepts neither a list of task IDs nor a third split. Keep validation and final-test rosters in separate spec versions or specs, and pin their IDs to avoid evaluating the final test during development. After task diagnostics, run a small evaluation to check the managed model, grader, and published reward before a larger held-out baseline. ## 2. Read the score ```python theme={null} progress = client.evals.runs.progress(run.eval_run_id) print(progress.status, progress.terminal_rollouts, progress.total_rollouts) result = client.evals.runs.retrieve(run.eval_run_id) print(result.status, result.reward_mean) for item in client.evals.rewards.list_trajectory_rewards(run.eval_run_id): print(item.task_id, item.reward) ``` Poll progress until `status` is `completed`; failed or cancelled runs are terminal too. Read the mean reward after completion. A failed run can contain graded trajectories without a published mean. Count attempted, graded, failed, and unfinished tasks before comparing means, and retrieve a trajectory with `include_reward_components=True` to check its native score, ending, and failure. `client.evals.runs.list(bench_id)` lists the spec's evaluations. Open the project's **Evaluation** tab for the same scores. See [Use the platform](/platform) for direct run links. `progress.live`, when present, reports `scored_rollouts`, `failed_rollouts`, `cancelled_rollouts`, and a `provisional_reward_mean` over scored attempts. This provisional mean is not a completed evaluation result. Scored attempts can include zero assigned to an ungraded ending; inspect reward components to distinguish those from native grades. `terminal_rollouts` includes historical failed attempts and is not logical completion progress. Use `remaining_rollouts` and the run status to assess remaining work. `client.trajectories.list(eval_run_id=...)` includes ungraded and failed trajectories too. To audit timeouts, iterate all pages of that list and check each trajectory's `termination_reason` for `TIMEOUT`. A timeout can be counted in `scored_rollouts`, so `failed_rollouts` alone cannot tell you how many timed out. To check for a complete decision grade, retrieve each affected trajectory with `include_reward_components=True` and compare the stored component names with the ones your grader records. A run can be `completed` with `failure=None` even if some attempts ended in `ERROR` before grading finished. Check `remaining_rollouts` and the affected trajectories to find these gaps. You can [retry those attempts](#recover-ungraded-attempts) without rerunning attempts that were already scored. To read what the model said, take a trajectory ID from those rewards and read its steps. Each step holds the conversation so far, so the last step is the full transcript: ```python theme={null} tid = item.trajectory_id print("Trajectory:", links.evaluation(run.eval_run_id, trajectory_id=tid)) num_steps = client.trajectories.retrieve(tid).num_steps if num_steps: # A trajectory that failed before its first model call has no steps. last = client.trajectories.steps.list(tid, start_step_index=num_steps - 1, limit=1).items[0] for message in last.messages or []: print(message.role, message.content) # Every step, for per-step rewards; iterating fetches each following page. for step in client.trajectories.steps.list(tid): print(step.step_index, step.reward) ``` `client.trajectories.retrieve(tid, include_steps=True)` returns every step in one response; for long trajectories, page with `steps.list`. ### Decode native tool-call records In native managed traces, `message.tool_calls` is `None` or a JSON string containing an array of records. Each record has top-level `id`, `name`, and `arguments`. When `is_parsed_successfully` is true, `arguments` is already a dictionary and may be empty. Chat Completions uses a different shape with the name and JSON-string arguments nested under `function`. Collect the parsed calls from the final step above. Keep arguments and raw trace content out of shared logs. ```python theme={null} import json parsed_calls = [] if num_steps: for message in last.messages or []: try: calls = json.loads(message.tool_calls or "[]") except json.JSONDecodeError: continue if not isinstance(calls, list): continue for call in calls: if not isinstance(call, dict) or call.get("is_parsed_successfully") is not True: continue name, arguments = call.get("name"), call.get("arguments") if isinstance(name, str) and isinstance(arguments, dict): parsed_calls.append((name, arguments)) ``` ### Recover ungraded attempts Use `resume()` to rerun selected attempts in a standalone evaluation. The run must have status `failed`, `cancelled`, or `completed`. To rerun only attempts that ended in an error: ```python theme={null} recovered = client.evals.runs.resume( run.eval_run_id, idempotency_key="YOUR_RECOVERY_REQUEST_KEY", rerun_cancelled=False, ) print(recovered.eval_run_id, recovered.status) ``` The `rerun_*` flags choose attempts by how they ended: | Flag | Default | Reruns attempts that | | - | - | - | | `rerun_error` | `True` | ended in an error | | `rerun_cancelled` | `True` | were cancelled or never started | | `rerun_timeout` | `False` | timed out | | `rerun_truncation` | `False` | were truncated | | `rerun_stale` | `False` | went stale | With no flags, `resume()` reruns errored, cancelled, and never-started attempts. At least one flag must be `True`; otherwise the request returns HTTP 400. This keeps the same evaluation ID and the results of every attempt you don't rerun, including answers that received a score of zero. Poll progress again and check the new attempts' grades when the run finishes. You can't resume deployment-backed or pipeline evaluations this way. Cleanup can continue after the evaluation finishes. If `resume()` returns HTTP 409 because cleanup is pending, wait and try again with the same run ID, `rerun_*` flags, and idempotency key. See [troubleshooting](/reference/troubleshooting#evaluation-resume-returns-http-409-while-cleanup-is-pending) for the error messages and retry details. ## 3. Score a checkpoint Retrieve the run to check that it uses the selected checkpoint and base model. ```python theme={null} checkpoint = max( client.rl.checkpoints.list("YOUR_TRAINING_RUN_ID"), key=lambda c: c.step_index, ) checkpoint_eval_receipt = client.evals.create( # Use the spec version whose test split contains the frozen roster. bench_id="YOUR_FROZEN_SPEC_VERSION_BENCH_ID", base_model_slug=checkpoint.base_model_slug, parent_checkpoint_id=checkpoint.checkpoint_id, # Omit val_num_tasks to run every task in that split. display_name="Checkpoint comparison", ) eval_run_id = checkpoint_eval_receipt.eval_run_id # Persist eval_run_id with your job or results record before retrieving the run. checkpoint_eval_run = client.evals.runs.retrieve(eval_run_id) if ( checkpoint_eval_run.parent_checkpoint_id != checkpoint.checkpoint_id or checkpoint_eval_run.base_model_slug != checkpoint.base_model_slug ): raise RuntimeError("Evaluation does not match the selected checkpoint") print("Checkpoint evaluation:", links.evaluation(eval_run_id)) ``` `client.evals.create()` launches the evaluation. Retrieving the run checks the checkpoint after trajectories may have started. Compare against the same spec version, held-out task IDs, grader, and effective generation limits. A checkpoint evaluation inherits the training run's resolved validation sampling, token, turn, and timeout settings, including its `val_*` overrides. Explicit evaluation `options` take precedence. A base-model evaluation uses evaluation defaults, so pass the same explicit `options` to runs you compare. A capped evaluation on a new spec version may select different tasks. Report per-task scores and coverage alongside the mean. Then [deploy](/guides/deployments) a checkpoint that meets your criteria. Record the training run ID, `checkpoint.step_index`, and `checkpoint.checkpoint_id` with your evaluation results so you can deploy the same checkpoint. # Send images to a model Source: https://docs.trajectory.ai/guides/images Show vision models PNG and JPEG images in evaluations and training. In training and evaluation, vision models can read images in chat completion messages. The `input_modalities` field in those model catalogs describes model-level capability; it does not guarantee that a trained checkpoint accepts images in deployment chat. Checkpoint deployments currently accept text only; requests with image parts return HTTP 400. See [deployments](/guides/deployments). Your harness can show the model a screenshot, chart, or photo in a user message or a tool result. Evaluations score those trajectories, and training learns from them like any other turn. For fixed-choice image classification, see [image decisions](/guides/decision-training#image-decisions). That endpoint accepts image parts in `input`, rather than chat `messages`; check the decision API and installed SDK support before reusing a chat example. ## Choose a vision model A model reads images when its `input_modalities` includes `"image"`: ```python theme={null} from trajectory import Client client = Client() for model in client.evals.list_models().items: if "image" in model.input_modalities: print(model.base_model_slug) ``` `client.rl.list_models()` reports the same field for training models. Vision models include the Qwen 3.5, 3.6, and 3.8 models, Inkling, and the hosted GPT, Claude, Gemini, and Kimi baselines. A request with an image for a text-only model returns 400 `Model does not accept image inputs.` ## Add an image to a message Build an image part with `ImageInput` and put it in the message's `content` list, next to any text parts: ```python harness.py theme={null} from trajectory import Client from trajectory.lib import ImageInput client = Client() tid = client.trajectories.create().tid response = client.chat.completions.create( model="policy", messages=[ { "role": "user", "content": [ {"type": "text", "text": "What is the total on this receipt?"}, ImageInput.from_path("receipt.png").part(), ], } ], x_trajectory_id=tid, ) ``` `part()` returns the OpenAI image part with the image as a base64 data URL: ```json theme={null} {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo..."}} ``` Harnesses that call the OpenAI client directly can send the same part. The API also accepts the `input_image` type and a plain string `image_url`. It ignores `detail`. Images may appear in `user` and `tool` messages. To return a screenshot from a tool, put the image part in the tool message's `content` list with its `tool_call_id`. Images in `system`, `developer`, or `assistant` messages return 400. ### Upload large or repeated images Inline images travel in the request body, which is capped at 32 MiB, about 24 MiB of images after base64 encoding. A conversation also resends earlier images on every turn. For large images, or ones the model sees on many turns, attach the image to the trajectory once and send a part that names it: ```python theme={null} image = ImageInput.from_path("page.png").upload(client, tid) # {"type": "image", "artifact_id": "..."} ``` The returned part works only in requests for that trajectory. Uploads use the [artifact upload](/guides/diagnostic-artifacts) flow, so the image is also kept with the trajectory. ## Formats and limits | Limit | Value | | - | - | | Formats | PNG or JPEG, a single frame. The data URL's media type must match the bytes. | | Source | Base64 `data:` URLs or uploaded artifacts. Remote `https://` image URLs are not fetched. | | One image | 16 MiB and 50,331,648 pixels. | | One request | 64 MiB of images, counting a repeated image each time it appears. | | Aspect ratio | Qwen models accept at most 200:1. | The platform resizes each image to fit the model before the model reads it, keeping its aspect ratio. Qwen models read at most 16,777,216 pixels, with sides rounded to multiples of 32. Inkling reads a long side of at most 4,096 pixels. The resized copy applies EXIF rotation, converts colors to sRGB, and places transparent areas on white. Images that already fit pass through unchanged. Image tokens count as input tokens. Fewer pixels cost fewer tokens, so set the `image_max_pixels` run option to downscale images further: ```python theme={null} run = client.evals.create( bench_id="YOUR_BENCHMARK_ID", base_model_slug="Qwen/Qwen3.6-35B-A3B", options={"image_max_pixels": 1_048_576}, ) ``` `image_max_pixels` accepts 1 to 16,777,216 and can only lower the model's own limit. A training run's checkpoints keep its value in later evaluations and deployments unless you set it again. Retaining the value does not enable image input for checkpoint deployment chat, which currently accepts text only. # Connect an Inspect harness Source: https://docs.trajectory.ai/guides/inspect Route Inspect actors through Trajectory while keeping its task and scorer. For an [Inspect](https://inspect.aisi.org.uk/) harness using the OpenAI provider, configure the actor at `eval_async` with `model_base_url` and `model_args`. Keep the source task, solver, sandbox, and scorer. Other provider protocols need a compatible adapter; changing the provider prefix can change how Inspect interprets model settings. Pass a string model identifier; an existing `Model` keeps its original provider and transport. This example expects one sample and a scorer named `accuracy`. Replace those assumptions with the source harness's result reader. Inspect's `value_to_float()` converts `C` to 1, `I` to 0, `P` to 0.5, and `N` to 0; custom labels or structured scores need their own conversion. Merge the credentials and header into any existing `model_args`. This adapter runs and scores a sample, then reads its score from a full sample log. ```python theme={null} import logging import math from pathlib import Path import yaml from inspect_ai import eval_async from inspect_ai.scorer import value_to_float from trajectory import Client if not isinstance(model, str) or not model.startswith("openai/"): raise TypeError("Pass an Inspect openai/... model identifier") client = Client() actor_options = dict(eval_options) actor_options.update(run_samples=True, score=True, log_samples=True, log_header_only=False) actor_options.pop("model", None) existing_args = actor_options.pop("model_args", None) or {} if isinstance(existing_args, str): existing_args = yaml.safe_load(Path(existing_args).read_text()) or {} model_args = dict(existing_args) headers = dict(model_args.pop("default_headers", None) or {}) actor_options.pop("model_base_url", None) tid = client.trajectories.create().tid headers["X-Trajectory-Id"] = tid model_args.update(api_key=client.api_key, default_headers=headers) try: logs = await eval_async( task, model=model, model_base_url=f"{str(client.base_url).rstrip('/')}/v1", model_args=model_args, **actor_options, ) if len(logs) != 1 or logs[0].status != "success": raise RuntimeError("Inspect did not complete successfully") samples = logs[0].samples if ( samples is None or len(samples) != 1 or samples[0].error is not None or samples[0].output is None ): raise RuntimeError("Expected one completed Inspect sample") value = samples[0].scores["accuracy"].value if not isinstance(value, (str, int, float)): raise ValueError("Use the benchmark's conversion for structured scores") if ( isinstance(value, str) and value not in {"C", "I", "P", "N"} and value.lower() not in {"yes", "no", "true", "false"} ): value = float(value) reward = value_to_float()(value) if not math.isfinite(reward): raise ValueError("Inspect did not produce a finite score") termination_reason = ( "TRUNCATION" if samples[0].output.stop_reason in {"max_tokens", "model_length"} else "ENV_DONE" ) client.trajectories.log_reward(tid, name="reward_accuracy", value=reward) except Exception: try: client.trajectories.complete(tid, termination_reason="ERROR") except Exception: logging.exception("Failed to report trajectory failure") raise else: client.trajectories.complete(tid, termination_reason=termination_reason) ``` An output stopped at `max_tokens` or `model_length` keeps its native score but ends the trajectory as `TRUNCATION` rather than a normal completion. A managed Trajectory run selects the actor model even if the request names another model. Keep Inspect's model identifier when it affects prompts or other behavior. Pass these transport settings through wrappers around `eval_async`, but configure LLM judges and other auxiliary clients separately. Changing process-wide `OPENAI_API_KEY` or `OPENAI_BASE_URL` to redirect the actor can unintentionally redirect a judge too. Store auxiliary credentials as [organization secrets](/guides/spec) and pass `SecretRef` values in the task's `env_vars`. Use credentials that remain valid when later evaluation or training runs schedule the task. If you implement an Inspect provider adapter, register it with [`@modelapi`](https://inspect.aisi.org.uk/extensions-model-api.html) and obtain it with `get_model(...)`. Its `should_retry` hook should honor `Trajectory-Should-Retry: false` on an `APIStatusError` response. Otherwise, keep the provider's retry policy. # Collect production traces Source: https://docs.trajectory.ai/guides/production-traces Private beta: record model calls and outcomes from your application. > [!NOTE] > > Private beta. For runnable tasks and a grader, start with [specs](/guides/spec). A production trace belongs to a [project](/concepts). Your application creates a trajectory, sends model calls through Trajectory, and marks it complete. To fine-tune on trajectories from existing training or evaluation runs, see [SFT datasets](/guides/training#sft-datasets). ```python theme={null} from trajectory import Client request_id = "request-example-001" with Client() as client: session = client.trajectories.create( body={"agent_id": ""}, idempotency_key=request_id, ) response = client.chat.completions.create( model="", x_trajectory_id=session.tid, messages=[ {"role": "system", "content": "Return only the numeric answer."}, {"role": "user", "content": "What is 19 times 23?"}, ], ) answer = response.choices[0].message.content client.trajectories.log_reward( session.tid, name="answer_correct", value=float(answer is not None and answer.strip() == "437"), explanation="Exact match against the expected answer, 437.", ) client.trajectories.complete( session.tid, termination_reason="ENV_DONE", ) ``` Replace the project, model, and grader with yours. Use the organization key throughout the trajectory lifecycle. Save the explicit create `idempotency_key` before submitting and the returned `tid` as soon as it is available. Pass that ID to each trajectory operation. After an uncertain create, event, or inference request, follow [journal recovery and auxiliary cleanup](/reference/troubleshooting#journal-writes-fail-or-an-auxiliary-capture-stays-in_progress) before sending another write. Log a reward when you have a grader. Otherwise complete the trajectory and attach later events with [telemetry](/guides/telemetry). # Adapt an existing grader Source: https://docs.trajectory.ai/guides/source-graders Preserve a benchmark's published score when reporting Trajectory rewards. Read the source evaluator's **result reader** before choosing a reward. Identify the score it publishes, its range, and whether partial credit contributes. A successful grader command does not establish which score the benchmark reports. Select the score in the task harness, after grading. Do not choose it in the upload script, clamp it, or turn a missing score into zero: ```python theme={null} import math def select_score(scores: dict[str, object], key: str) -> float: if key not in scores: raise ValueError(f"Missing score {key!r}; available: {sorted(scores)}") value = scores[key] if isinstance(value, bool) or not isinstance(value, (int, float)): raise ValueError(f"Score {key!r} must be numeric") score = float(value) if not math.isfinite(score): raise ValueError(f"Score {key!r} must be finite") return score report = grade_answer(model_answer, expected_answer) score = select_score(report, "accuracy") # Use the source reader's primary field. client.trajectories.log_reward(tid, name="accuracy", value=score) ``` Parse the source grader's documented format first if it returns strings, booleans, or nested data. Declare the actual bounds in `log_reward` when they differ from `[0, 1]`. Publish either the native total once or components that reproduce it, not both. A wrong answer can have a valid zero; an unrecovered model, environment, or grader failure should end as `ERROR`. Don't log a reward for it, even if the grader returned a score. For a secondary score, `weight=0` makes it visible without changing the effective reward. Use it only when the harness owns reward publication; even a zero-weight component can prevent automatic grading. An event can hold grader details without affecting reward: ```python theme={null} fraction = select_score(report, "criteria_fraction") client.trajectories.log_reward( tid, name="criteria_fraction", value=fraction, weight=0, ) client.trajectories.log_event( tid, event_id="rubric", name="rubric", payload={"criteria_fraction": fraction}, ) ``` Keep private grader references out of events. Retrieve the trajectory with `include_reward_components=True` to check names, values, bounds, and weights. Compare wrong, partial, and correct outputs against the source evaluator, including its aggregation. Then run a [task diagnostic](/guides/spec#validate-one-task-before-uploading) through the packaged runtime and inspect the reward, ending, and failures. Repeat for each distinct grading schema. # Bring your spec Source: https://docs.trajectory.ai/guides/spec Bring your own tasks, agent harness, and grading. A spec contains tasks for the model to solve. Each task uses an image containing its dependencies, files and your harness. The harness reads the instructions, runs the model, grades its work and reports the result to Trajectory through the Python SDK. Each task specifies the command that starts the harness and any inputs or settings it needs. Multiple tasks can share an image, with different inputs for each task. For quick debugging, diagnose a representative task, then upload a small spec and [evaluate](/guides/evaluations) it to confirm a recorded grade. When ready to expand, upload the full spec and diagnose a subset of its tasks before training. The [cookbook](https://github.com/Trajectorylabs/trajectory-cookbook) has worked integrations. You'll write two Python scripts: * **`harness.py`** runs inside the image. It reads the task instructions, calls the model, grades its work and reports the result. * **`upload.py`** runs on your computer. It defines the tasks and uploads the spec and its image files. The examples below show the relevant pieces of each script. The "Update your spec" section is optional; use it when you want to update an existing spec. Before running the examples, [choose or create a project](/projects) and use its ID (`agt_...`) wherever `YOUR_AGENT_ID` appears. If onboarding gives you a project ID, pass it directly as `agent_id` to `push()`, `start_push()`, or `start_task_diagnostic()`; no name lookup is needed. These helpers also accept `agent_name` when selecting a project by name. Generally, projects should have a clear grouping of similar specs and tasks. For fixed-choice tasks, set `BenchmarkSpec(benchmark_type="decision", ...)` and follow [Train decision models](/guides/decision-training) for the decision harness and required categorical outcome labels. The default spec type is `generative`. ## Define your tasks Use `BenchmarkSpec` to describe the spec and `TaskSpec` for each task. Each task needs a unique name, a runtime (its own or the spec's shared runtime), and a `run_command` that starts your harness inside that runtime. `split` is optional; tasks without one are assigned by a seeded shuffle, about 15% to `test` and the rest to `train`. If needed, you can pass task-specific inputs through `env_vars`: ```python upload.py theme={null} from trajectory import TaskSpec task = TaskSpec( name="repair-config", split="test", run_command="python /app/harness.py", env_vars={"TASK_INSTRUCTIONS": "Fix the invalid configuration in /workspace/config.json."}, ) ``` Your harness can read these environment variables with `os.environ`. For larger inputs, package the files in the image and have your harness read them. If tasks share an image, use task-specific settings—such as environment variables or command-line arguments in `run_command`—to select the right files and execute the task. Task variable names cannot start with `TRAJECTORY_` or be `MODEL_ENDPOINT_ID`, `MODEL_ENDPOINT_ACCESS_TOKEN`, or `MODEL_ENDPOINT_URL`. Use `SecretRef` for credentials; managed tasks receive their Trajectory session key and base URL automatically. Set CPU and memory through `env_resources`. Keep training and test tasks in their respective splits, and retain the source task IDs when selecting a subset. If a task runs Docker containers, set `env_resources.docker_engine=True`. The execution environment must be able to start a Docker daemon and pass `docker info`; installing only the Docker CLI is not enough. The Docker check confirms daemon access. Use a [task diagnostic](#validate-one-task-before-uploading) to verify kernel features your harness requires, such as Landlock ABI 3 or later. ### Network access on Modal The default `env_resources.network_mode="no-network"` allows only the platform endpoints a managed task uses. For known external hosts, set `env_resources.network_mode="allowlist"` and list their hostnames in `env_resources.allowed_hosts`. Modal's hostname allowlist matches TLS SNI and permits TLS only on TCP 443. DNS can resolve a hostname even when the connection is blocked. With hostname allowlisting, PostgreSQL connections on TCP 5432 fail even with TLS. See [Modal's networking documentation](https://modal.com/docs/guide/sandbox-networking). Use `env_resources.network_mode="public"` only when unrestricted outbound internet access is explicitly approved. Omit `allowed_hosts` in public mode. Use least-privilege credentials and apply destination controls outside Trajectory where available. Changes apply to new rollouts, so start a new rollout after changing network settings. ## Call the model using Trajectory Client In managed runs, Trajectory provides credentials and the API URL, so your harness can use `Client()` without configuring them. Create the trajectory before task setup and keep its ID for the whole attempt. Pass it with each model request: ```python harness.py theme={null} import os from trajectory import Client client = Client() tid = client.trajectories.create().tid response = client.chat.completions.create( model="policy", messages=[{"role": "user", "content": os.environ["TASK_INSTRUCTIONS"]}], x_trajectory_id=tid, ) ``` In a managed evaluation or training run, the run selects the actor model; changing the request's `model` does not select a different actor. Generation settings come from the run's `options`, set when you start an [evaluation](/guides/evaluations#1-start-a-baseline) or [training run](/guides/training#training-options). The run's `max_output_tokens_per_turn` replaces the request's `max_tokens`. If the option is omitted or `null`, the run's default cap applies. Managed evaluations do not support different caps per request. The run's `temperature`, `top_p`, `top_k`, and `reasoning_effort` also override request values. Your harness decides whether one response is enough or whether the model needs more turns. When using Trajectory for a source-fixed judge or other auxiliary model, use an organization-key client and a separate trajectory. `trajectories.create()` with the managed session key reuses the actor's trajectory. Pass the separate trajectory's ID with each auxiliary model request: `x_trajectory_id` in the Trajectory SDK or `X-Trajectory-Id` in direct HTTP calls. Keep the organization key out of actor-visible tools. You can give the model tools if your harness supports executing tool calls and returning their results to the model. Each tool describes an action the model can request, such as running a shell command or reading a file. Include any software those tools need in the image and provide the harness code that executes them. Pass tool definitions through `extra_body={"tools": tools}`; this SDK's chat method has no `tools=` keyword. Preserve the assistant's tool calls in the conversation, append each result with its `tool_call_id`, and send that conversation on the next request. Check `finish_reason` before dispatching tools; see [termination reasons](/guides/termination-reasons) for cut-off replies. Keep source-fixed judge calls separate from the managed actor trajectory. ### Managed actor input modalities Managed actors in task diagnostics, evaluations, and training accept text and, for vision models, images. Audio input, including `input_audio`, is unsupported. This is a managed actor input limitation, not an SDK typing omission; changing the request's `model` cannot bypass the run's actor selection or enable audio input. Before uploading a spec, check each model's `input_modalities` in `client.evals.list_models()` or `client.rl.list_models()`. These catalogs currently advertise only `"text"` and `"image"`; see [image capability discovery](/guides/images#choose-a-vision-model). If your benchmark requires the actor to hear audio, it cannot run as specified with a managed actor. Substituting a transcript changes the benchmark's semantics. ### JSON and structured outputs Managed actor calls in task diagnostics, evaluations, and training don't support JSON mode or schema-constrained output. The API ignores `response_format` and `json_schema` on these calls, including when passed through `extra_body`. Function tools with `strict=True` are also unsupported. If your task needs JSON, ask for it in the prompt and validate the response in your harness. Prompting doesn't guarantee valid JSON. ## Report the grade through the SDK Your verifier decides how to grade the model's work. It might compare an answer with an expected value, run a test suite or inspect files and running services. For an existing spec, trace the score field or formula its evaluation reader uses. Keep the native scale and grading rule, including partial credit when that is the reported score; a successful grader command alone does not identify the score. Once your verifier produces a valid numeric `grade`, report it against the same trajectory ID, then mark the attempt complete: ```python harness.py theme={null} client.trajectories.log_reward( tid, name="reward_accuracy", value=grade, ) client.trajectories.complete(tid) ``` Rewards default to `[0, 1]`. For a different scale, declare its bounds when logging: ```python harness.py theme={null} client.trajectories.log_reward( tid, name="score", value=-0.5, min_value=-1, max_value=1, ) ``` The effective reward is the weighted average of components scaled to `[0, 1]` by their declared bounds. Use `weight=0` for a secondary score you want to inspect without changing that reward. Retrieve components with `include_reward_components=True`; `trajectory.reward` alone can be zero without a native grade. The [source-grader guide](/guides/source-graders) shows a worked mapping and grader-output event. These snippets show the SDK calls to place in your harness; they are not a complete program. `complete()` defaults to `ENV_DONE`, which means the attempt finished normally. When it did not, pass the reason. For an unrecovered model, environment, or grader failure, report `ERROR`. Don't log a reward for it, even if the grader returned a score: ```python harness.py theme={null} client.trajectories.complete(tid, termination_reason="ERROR") ``` [Termination reasons](/guides/termination-reasons) explains reason selection, including cut-off replies and how endings affect training and evaluation. A completed attempt can have an incorrect answer. An error means the harness could not produce a valid grade. Upload any outputs and logs you need before completion, because the sandbox may be cleaned up afterward. ## Package the harness in an image Include your harness, task files and dependencies in the image. This Dockerfile installs the latest SDK and copies your application files into `/app`: ```dockerfile Dockerfile theme={null} FROM python:3.11-slim WORKDIR /app RUN pip install --no-cache-dir --upgrade trajectory-sdk COPY . /app/ ``` Here, `run_command="python /app/harness.py"` assumes `harness.py` is in that build context. Check that paths in your task instructions and commands match where the Dockerfile copies files. For the `/workspace/...` paths above, you could put the task files under `spec/workspace/` locally and add `COPY workspace/ /workspace/` to the Dockerfile. `COPY . /app/` alone would put them under `/app/workspace/` instead. A build context holds at most 4,096 files. For a larger task set, archive the task files, `COPY` the archive, and unpack it in a `RUN` step that creates the destination first: ```dockerfile theme={null} COPY tasks.tar.gz /tmp/tasks.tar.gz RUN mkdir -p /opt/tasks && tar -xf /tmp/tasks.tar.gz -C /opt/tasks && rm /tmp/tasks.tar.gz ``` `ADD` accepts only a single `http://` or `https://` URL, not local files or archives. Add the tools and verifier dependencies your task needs, keeping held-out tests out of any environment the model can inspect. Keep credentials out of the image. Test that separation through the actor's actual file and shell tools; hiding a path from its prompt does not make the path private. `DockerfileBuild` uploads files under the Dockerfile's directory. Scope that context to at most 4,096 files and 3 GiB; use `.dockerignore` or a smaller runtime directory when the checkout is larger. `COPY` paths are relative to that context. Expanded images and runtime files have separate storage requirements. Before scaling up, check free disk space and try the workload's downloads and archive extraction in a [task diagnostic](#validate-one-task-before-uploading). For harnesses that run Docker containers, such as Harbor, install and verify the Docker daemon, CLI and Compose during the image build. On Debian Trixie: ```dockerfile Dockerfile theme={null} RUN apt-get update \ && apt-get install -y --no-install-recommends \ docker.io docker-cli docker-compose \ && docker --version \ && docker compose version \ && dockerd --version \ && rm -rf /var/lib/apt/lists/* ``` ## Validate one task before uploading For quick debugging, run `start_task_diagnostic()` on one representative task. A diagnostic reports each task's status and, for a failed task, its failure: a code, plus the rollout and trajectory IDs, termination reason, and a redacted summary of any harness exception when the task got that far: ```bash theme={null} pip install --upgrade trajectory-sdk export TRAJECTORY_API_KEY="YOUR_TRAJECTORY_API_KEY" ``` ```python theme={null} import time from pathlib import Path from trajectory import Client, TaskSpec from trajectory.lib import DockerfileBuild, start_task_diagnostic client = Client() task = TaskSpec( name="repair-config", runtime=DockerfileBuild("Dockerfile"), run_command="python /app/harness.py", env_vars={"TASK_INSTRUCTIONS": "Fix the invalid configuration in /workspace/config.json."}, ) diagnostic = start_task_diagnostic( client, task, agent_id="YOUR_AGENT_ID", root=Path("spec"), options={"max_output_tokens_per_turn": 4096}, ) while True: status = client.diagnostics.get_status(diagnostic.benchmark_diagnostic_id) if status.status in {"completed", "failed", "cancelled"}: break time.sleep(5) result = client.diagnostics.get_diagnostics(diagnostic.benchmark_diagnostic_id) print(result.status, result.task_counts, result.failure) for task_result in result.tasks: print( task_result.task_id, task_result.status, task_result.termination_reason, task_result.reward, task_result.failure, ) ``` The helper handles uploads and runtime builds without an existing spec ID, then returns once the diagnostic is started. Its `timeout_seconds` bounds only the image-build wait, not task execution. Poll `get_status()` until the status is `completed`, `failed`, or `cancelled` before calling `get_diagnostics()`. Fetching the report while the diagnostic is pending or running returns HTTP 409. `ImageRef(...)` and `RuntimeRef(...)` also work if you already have an image or runtime. Check each task's failure and the run-wide `result.failure` before moving on. A diagnostic makes one attempt per task on the API's default diagnostic model, reported as `result.base_model_slug`; pass `base_model_slug` to choose another. `options` takes the settings an [evaluation](/guides/evaluations#1-start-a-baseline) accepts, except the sample counts, which the diagnostic sets. Pass the model and settings you will evaluate and train with, so the diagnostic generates replies the same way. Each task reports its `trajectory_id`, the `termination_reason` it ended with, and its `reward`, which is null when the trajectory ended before the harness recorded one. ## Upload the spec and build its image Put your Dockerfile, harness and task files in a local `spec/` directory. The example below uploads the `task` defined above to your chosen project: ```python upload.py theme={null} from pathlib import Path from trajectory import BenchmarkSpec, Client from trajectory.lib import DockerfileBuild, push from trajectory.lib.platform_links import PlatformLinks client = Client() spec = BenchmarkSpec( name="Configuration repair", runtime=DockerfileBuild("Dockerfile"), tasks=[task], ) uploaded = push( client, spec, agent_id="YOUR_AGENT_ID", root=Path("spec"), build_images=True ) links = PlatformLinks.from_client(client) agent_id = client.specs.retrieve(uploaded.bench_id).agent_id print("Spec:", uploaded.bench_id, links.spec(agent_id, uploaded.bench_id)) ``` Spec names are 3 to 1024 characters of ASCII letters, digits, spaces, `.`, `_`, and `-`; `push()` and `start_push()` reject other names before uploading anything. This uploads your tasks and files and waits for the image build. If registration or building fails, `push()` raises `BenchmarkOperationError`, which you can import from `trajectory.lib`; inspect its `failures` for the affected runtime and build error. For an upload that may outlive your client, use `start_push()` and save its returned operation `id`. A local timeout does not stop ingestion: reconnect with `get_operation(client, operation_id)`, then inspect `refresh()` and `pages("failure")` before retrying. A failed runtime blocks evaluation of that spec version; correct it and upload a new version rather than creating a second, partial spec. To use this reconnectable form instead of the `push()` call above: ```python theme={null} from trajectory.lib import start_push operation = start_push( client, spec, agent_id="YOUR_AGENT_ID", root=Path("spec"), build_images=True ) print(operation.id) result = operation.result(timeout=45 * 60) print(result.status.bench_id) readiness = client.specs.retrieve_readiness(result.status.bench_id) print(readiness.ready, readiness.missing_secret_names, readiness.unready_task_image_counts) ``` After the upload succeeds, check `client.specs.retrieve_readiness(bench_id)` before starting a run. If `ready` is `False`, `missing_secret_names` and `unready_task_image_counts` tell you what still needs attention. `ready=True` confirms that required secrets exist, but an invalid key can still cause HTTP 401 when the grader calls an external provider. A ready spec can contain only `test` tasks. [Check the training split](/guides/training#check-the-training-split) before starting rollout training. The upload operation's `ready` field only covers builds requested with `build_images=True`. When reusing a `RuntimeRef` with `build_images=False`, the operation can succeed with `ready=False` and `ready_runtimes=0` even if the spec is ready to run. `client.specs.list()` has no `agent_id` filter. To find every spec version for a project, use `latest_only=False`, iterate the paginated result, and filter on `spec.agent_id`; see the [CLI guide's project filtering example](/guides/cli#upload-and-validate). ### Build images for an existing spec To build task images for an existing spec version, call `build()` with its `bench_id` and inspect each image's `build_status`: ```python theme={null} from trajectory import Client client = Client() bench_id = "YOUR_BENCH_ID" client.specs.images.build(bench_id) for image in client.specs.images.list(bench_id): print(image.task_id, image.build_status) ``` Build completion is asynchronous, and the build call is not a completion signal. Iterating the list fetches every page. The status field is `build_status`, not `status`. For blocking polling, use the existing [`wait_for_benchmark_images()`](/reference/client#update-an-existing-spec) helper from `trajectory.lib`; it requests builds and polls every page for you. Uploading does not run the tasks. After the diagnostic passes, run a small [evaluation](/guides/evaluations) and confirm a recorded grade. A graded zero is valid; use held-out tasks when comparing checkpoints. `push()`, `start_push()`, and `start_task_diagnostic()` accept `upload_timeout` in seconds for blob store uploads, defaulting to `3600` (one hour). Pass `upload_timeout=None` to disable blob store timeouts. These apply to individual HTTP operations against the blob store, separately from API request timeouts, image-build waits, and signed-URL expiry. They do not set a total upload deadline. `push()` and `start_push()` also accept `upload_max_retries`, the retries for each upload request (default `32`, within 4.5 minutes of waiting). See [Errors and retries](/reference/errors). You can share a runtime across tasks or set `runtime` on individual tasks: | Runtime definition | What you provide | | - | - | | `DockerfileBuild("Dockerfile")` | A Dockerfile and the files in its directory. | | `ImageRef("registry.example.com/agent@sha256:...")` | An existing image pinned to a digest. | | `RuntimeRef("YOUR_RUNTIME_ID")` | A runtime already registered in your organization. | For both `ImageRef` and Dockerfile `FROM`, use images the platform can pull without customer registry credentials. Organization secrets are available to tasks at runtime. Import the runtime helpers above from `trajectory.lib`. For secret task inputs, import `SecretRef` from `trajectory` and use it in `env_vars` instead of packaging secret values: ```python theme={null} from trajectory import SecretRef env_vars = {"API_TOKEN": SecretRef(secret_ref="SECRET_NAME")} ``` To download private assets at runtime, configure [network access](#network-access-on-modal) for the asset host and use an [organization secret](#create-an-organization-secret) for the download credential. Actors and tools that can read the task environment or filesystem can also read secrets or assets stored there. ### Create an organization secret In the organization that owns the spec, open **Settings → Secrets → Add secret**. Enter a name that exactly matches `secret_ref`. Have the key holder enter the value directly and keep it out of prompts, source files, and logs. The key holder can also run this from a terminal signed in to that organization: ```python theme={null} from getpass import getpass from trajectory import Client with Client() as client: client.secrets.create( name="SECRET_NAME", value=getpass("Secret value: "), ) ``` Rerun `client.specs.retrieve_readiness(bench_id)` on the existing spec and check `missing_secret_names`. Test the credential with its service separately. Adding the secret requires no reupload or rebuild. ## Upload and diagnose the full spec Expand `BenchmarkSpec.tasks` to the full task set and upload it with `push()`. Once `push()` finishes, call `client.diagnostics.start_benchmark()` using that upload's `bench_id`. It runs up to 10 tasks, one attempt each, starting with one task per runtime, and reports the same task outcomes and failures as the single-task diagnostic. You need not repeat the single-task diagnostic for an unchanged runtime. Like `start_task_diagnostic()`, `start_benchmark()` accepts `base_model_slug` to choose the diagnostic model. Omit it to use the API's default diagnostic model; the report includes the resolved `base_model_slug`. Use the model and generation settings you plan to evaluate and train with. The diagnostic sets its own sample counts. ```python theme={null} import time diagnostic = client.diagnostics.start_benchmark( bench_id=uploaded.bench_id, base_model_slug="YOUR_SUPPORTED_MODEL_SLUG", options={"max_output_tokens_per_turn": 4096}, ) while True: status = client.diagnostics.get_status(diagnostic.benchmark_diagnostic_id) if status.status in {"completed", "failed", "cancelled"}: break time.sleep(5) report = client.diagnostics.get_diagnostics(diagnostic.benchmark_diagnostic_id) print(report.status, report.task_counts, report.failure) for task_result in report.tasks: print( task_result.task_id, task_result.status, task_result.termination_reason, task_result.reward, task_result.failure, ) ``` Inspect the run-wide failure and every task's outcome, ending, and reward. If the diagnostic fails, fix the reported problem, upload the revised full spec, and diagnose that version. After it passes, run an [evaluation](/guides/evaluations) to confirm a recorded reward before [training](/guides/training). Evaluation and training accept `agent_name` and `benchmark_name` together to select the latest version by name. Use `bench_id` when you need a specific version; spec diagnostics require the ID returned by the upload helper. ## Record a data quality finding Use `client.specs.diagnostics.findings` to record an issue on a specific spec version, task, or recorded trajectory. Use the IDs returned by the API. A trajectory target requires both its `spec_id` and `task_id`. Your own code detects issues and publishes findings; these methods store and review the diagnostics you submit. ```python theme={null} findings = client.specs.diagnostics.findings finding = findings.create( spec_id=uploaded.bench_id, task_id=task_id, title="Verifier accepts an empty result", explanation="The verifier awards credit when the response contains no result.", suggested_fix="Require a result before evaluating its contents.", detector_name="verifier-contract", evidence=[ { "kind": "task", "bench_id": uploaded.bench_id, "task_id": task_id, "explanation": "The task grader grants credit for an empty result.", }, { "kind": "trajectory", "trajectory_id": trajectory_id, "step_indices": [3], "explanation": "This step records the empty result.", } ], ) for item in findings.list(spec_id=uploaded.bench_id, include_descendants=True): print(item.finding_id, item.title) findings.resolve(finding.finding_id, note="Updated and verified the grader.") ``` List results default to open findings for the exact target. Use `include_descendants=True` to include child targets or `state="all"` to include resolved findings. Use `findings.retrieve(finding_id)` for one finding or `findings.counts(targets=[{"bench_id": bench_id, "include_descendants": True}])` for open and resolved counts across multiple targets in one read. The SDK generates one idempotency key per create call and reuses it for automatic retries. To retry a submission in a separate call or process, supply and reuse an explicit `idempotency_key` with the same request. Evidence can cite a spec, task, or trajectory in your organization. For configuration and grading issues, use task evidence and describe the relevant setting or behavior in its explanation. Tool call IDs require the corresponding step indices. The platform displays the explanation and references you submit. Your code supplies the evidence and runs any checks needed to verify it. ## Update your spec Use `client.specs.update(bench_id, name=..., description=...)` for metadata changes only; it does not update tasks or runtime files. To add or replace tasks while keeping the same `bench_id`, use the [HTTP task diff, append, file upload, and commit workflow](/reference/client#add-or-replace-tasks-under-the-same-id). Changed content under an existing task name replaces that task with a new task ID; omitted tasks remain. Inspect `failed_tasks` because a commit can partially succeed. Legacy tasks without content hashes and active evaluation resource cleanup can block replacement. For changed runtime source, supply `runtime.source` and its files; reusing an old `runtime_id` keeps that runtime's source. To publish a new version, call `push()` or `start_push()` with the same spec name and project and include the full set of tasks you want. These helpers create a new `bench_id`; they do not accept an existing ID. Earlier versions remain available. Evaluation and training by name select the latest version, so finish a baseline/checkpoint comparison before uploading another version under the same name. ## Tips for adapting existing specs Your harness implements the deadlines, grading environments and evidence uploads below. * **Bring the verifier as well as the task environment.** Check that its scripts, dependencies and expected paths are available when grading starts. A ready image does not prove the verifier can run; test one task before launching the full set. * **Give the agent and verifier separate time limits.** When the agent runs out of time, stop its model calls and tools, then grade the work completed so far. Leave the verifier its full allowance and account for both phases in the rollout timeout. * **Follow the spec's grading rules.** Preserve resource limits, startup commands and environment settings. Some specs grade in the same running container; others require applying the model's changes to a fresh one. If the model has shell or file access, your harness must keep held-out tests outside the environment those tools can inspect. Uploading an image does not automatically provide this separation. * **Keep enough evidence to explain a result.** Save the generated output, verifier logs and error details as artifacts before completing the trajectory. Report missing logs separately from missing grades, and state any changes to the original spec. # Record telemetry Source: https://docs.trajectory.ai/guides/telemetry Private beta: attach application events to a trajectory. > [!NOTE] > > Private beta. A telemetry event records what happened. A reward is the grader's score. Use `log_event` during the trajectory. Use `client.telemetry.ingest_events` for events that arrive later, with your organization API key. ## During the trajectory Persist each `log_event` ID, name, and payload before sending. The service deduplicates by trajectory ID and event ID. If the outcome is uncertain, use [read-only journal recovery](/reference/troubleshooting#journal-writes-fail-or-an-auxiliary-capture-stays-in_progress). ```python theme={null} from trajectory import Client with Client() as runtime: runtime.trajectories.log_event( "", event_id="search-result-001", name="tool.result", payload={"tool": "search", "results": 3}, ) ``` Write runtime events before `complete`. Reuse `event_id` when retrying the same event. ## Read managed task events A managed task's `Client()` can write events with its scoped key. Listing events with that key currently returns HTTP 401, including for its own trajectory. Read the journal from a trusted process outside the managed task. Use an API key from the same organization and set `base_url` to the environment where the trajectory ran. Keep the organization key outside the task and its tools. ```python theme={null} import os from trajectory import Client with Client( api_key=os.environ["TRAJECTORY_ORG_API_KEY"], base_url="https://api.trajectory.ai", ) as reader: for event in reader.trajectories.list_events(""): print(event.event_id) ``` Events are returned newest first. Events are not reward components. The [source-grader guide](/guides/source-graders) logs grader details as an event; the [diagnostic-artifact guide](/guides/diagnostic-artifacts) attaches a file to a trajectory. ## Later application events Required fields are `event_id`, `event_type`, `timestamp`, `session_id`, and `source`. Set `trajectory_id` when you have `session.tid`. ```python theme={null} from datetime import datetime, timezone from trajectory import Client events = [ { "event_id": "request-example-001:answer-accepted", "event_type": "answer.accepted", "timestamp": datetime.now(timezone.utc).isoformat(), "session_id": "session-example-001", "source": "support-app", "trajectory_id": "", "properties": {"surface": "chat"}, } ] with Client() as client: result = client.telemetry.ingest_events(events=events) ``` `result` reports `ingested`, `skipped`, and `failures`. # Termination reasons Source: https://docs.trajectory.ai/guides/termination-reasons Record why a trajectory stopped and how that affects training and evaluations. Trajectory relies on your harness to send `termination_reason`; Trajectory does not infer it from model replies. Log a valid native grade, including zero, before calling `client.trajectories.complete(tid, termination_reason=...)`. The harness can exit after calling complete. | Reason | When the harness sends it | | - | - | | `ENV_DONE` | The trajectory finished normally, including a graded wrong answer. This is the default. | | `ERROR` | A model, environment, or grader failure prevented a valid trajectory. Don't log a reward for it, even if the grader returned a score. | | `TIMEOUT` | The harness stopped the actor at its time limit. | | `TRUNCATION` | A turn, step, output-token, or context limit may have stopped the actor. The task may have required a submission and the actor stopped without one. | The trajectory platform can also record `LIMIT_REACHED` for token or context limits, `MAX_STEPS` for its turn limit, and `STALE`, `CANCELLED`, or `SANDBOX_*` for execution failures. We preserve a platform ending event even if the harness later calls `complete()`. The [completion API reference](/api-reference/trajectories/complete-trajectory-route) lists all reasons. ## Training Training utilizes graded `ENV_DONE` trajectories by default. Training option `train_on_truncation` opts into utilizing truncated trajectories, including ones that hit token limits, turn limits, and missing submissions; `train_on_timeout` opts into timeouts; `train_on_error` opts into execution errors, grading errors, and missing grades. All three default to `false`. Be aware that when `density_aware_training` is on, it sets `train_on_truncation` to `true`. ## Evaluations Trajectories with `LIMIT_REACHED` and `MAX_STEPS` show up as `TRUNCATION` errors. These are given a reward of zero if ungraded and cap positive rewards at zero. `SANDBOX_*` are labeled as `ERROR` which counts as failed in an eval (even when training admits it). Additionally it counts toward the training failure limit unless `train_on_error` is enabled. ## Helpful Harness Tips Check `response.choices[0].finish_reason` before dispatching tool calls. A value of `"length"` or `"max_tokens"` means the reply was cut off - do not execute tool calls from that reply. If you grade the partial answer, log its native grade and complete with `TRUNCATION`. After a platform limit (turn, token, context), model requests may return an empty reply with `metadata.trajectory_termination_reason: "trajectory_cancelled"`. Inspect the recorded reason on the trajectory. When setting training options, leave room between `max_output_tokens_per_turn` and `max_output_tokens_per_trajectory`, especially if the harness must grade a reply that fills its per-turn allowance. # Train a model Source: https://docs.trajectory.ai/guides/training Train on a spec or a finalized SFT dataset and pick a checkpoint. Training uses a ready [spec](/guides/spec) and its rewards. For a comparison point, run an optional [evaluation baseline](/guides/evaluations) before training. For supervised fine-tuning (SFT) on existing run trajectories, see [SFT datasets](#sft-datasets). The workflow below uses reinforcement learning (RL). ## 1. Choose a model Before uploading a spec, use `list_models()` to choose a training model and estimate token costs. Each item includes `base_model_slug`, `model_name`, and input/output pricing in USD per million tokens. See [pricing](/pricing) for other charges. ```python theme={null} from trajectory import Client from trajectory.lib.platform_links import PlatformLinks client = Client() links = PlatformLinks.from_client(client) for model in client.rl.list_models().items: print(model.base_model_slug, model.model_name, model.pricing.input, model.pricing.output) ``` Check each entry's `input_modalities` before uploading: managed actor audio input, including `input_audio`, is unsupported. See [managed actor input modalities](/guides/spec#managed-actor-input-modalities) for the current text/image capabilities and actor selection limits. ### Check the training split Rollout training with optimizer steps needs at least one task in the spec's `train` split. Runtime readiness checks whether tasks can execute. The model options are based on the spec type and can be available even when the training split is empty. Check the count after upload: ```python theme={null} bench_id = "YOUR_BENCHMARK_ID" train_task_count = client.specs.tasks.count(bench_id, split="train").task_count if train_task_count == 0: raise ValueError("Add training tasks to the spec's train split before launching a run.") catalog = client.rl.list_options(bench_id=bench_id) for model in catalog.models: print(model.base_model_slug, model.options) ``` Use a returned `base_model_slug`. Each entry describes supported settings, bounds, and defaults. Omit `bench_id` for generative spec options or pass `base_model_slug` to filter to one model. For pricing, use `list_models()`. A computed default has `default_kind="computed"` and a `null` `default`. Leave the option unset to use it. If the training count is zero, upload a spec version with tasks intended for training in `train`. Keep held-out tasks in `test`. When validation is enabled, its configured split also needs tasks. ## 2. Start ```python theme={null} bench_id = "YOUR_BENCHMARK_ID" run = client.rl.train( bench_id=bench_id, base_model_slug="YOUR_SUPPORTED_TRAINING_MODEL_SLUG", options={"num_steps": 20}, ) print("Training:", run.training_run_id, links.training(run.training_run_id)) ``` Training and evaluation take `RunOptions` fields through `options`; a standalone evaluation accepts [a subset](/guides/evaluations#1-start-a-baseline). Omit `options`, or pass `{}`, to use the selected model's defaults. Check `list_options()` for the settings and bounds your model supports in each mode. Training also accepts `load_weights_only`, although it isn't listed; see [resume from a checkpoint](#4-resume-from-a-checkpoint). `batch_size` counts eligible task groups per optimizer step, and `group_size` counts trajectories within a group. For a short test run, lower both; default concurrency scales with them. Nothing here caps total trajectories, so plan a budget before you start. See [training options](#training-options) for every setting and [reduce trajectory spend](#reduce-trajectory-spend) for the ones that control token use. ## 3. Watch progress and pick a checkpoint ```python theme={null} import time while True: training = client.rl.runs.retrieve(run.training_run_id) progress = client.rl.runs.progress(run.training_run_id) print(training.status, progress.completed_steps, progress.total_steps) if training.status in {"succeeded", "failed", "cancelled"}: break time.sleep(30) if training.status != "succeeded": raise RuntimeError(f"Training {training.status}: {training.failure}") ``` An ID means the run was accepted. A pending run with zero completed steps is waiting; increasing step counts show progress. Watch attempted and graded trajectories as well. If trajectories accumulate without an update, inspect their endings and reward components; cancel a test run that has exceeded its planned budget. Check completed steps and checkpoints before concluding that training updated the model. See [termination reasons](/guides/termination-reasons) for which endings training admits. For a small test run, inspect trajectories and group counts: ```python theme={null} trajectories = list(client.trajectories.list(training_run_id=run.training_run_id)) print(len(trajectories), [(item.trajectory_id, item.status) for item in trajectories]) for step in client.rl.runs.list_step_summaries(run.training_run_id): print(step.step, step.no_signal_groups, step.used_groups, step.pending_groups) ``` Iterate the returned page to fetch every step. Its `.items` attribute contains only the current page. The same applies to trainer metrics such as Brier loss: ```python theme={null} for step in client.rl.runs.list_step_metrics(run.training_run_id): print(step.step, step.brier_loss) ``` For group-relative training, `no_signal_groups` counts completed groups with identical rewards. `used_groups` counts consumed groups with reward contrast and can differ from the optimizer batch size. For RLCD, `used_groups` counts consumed decision groups, including singleton and identical-reward groups. Check completed steps, trainer rewards, and checkpoints to confirm an update. After the run succeeds, inspect its rewards and choose a checkpoint. `list_held_out_rewards` returns the validation reward for each step: ```python theme={null} for point in client.rl.rewards.list_history(run.training_run_id): print(point.step, point.avg_reward) for point in client.rl.rewards.list_held_out_rewards(run.training_run_id): print(point.step, point.held_out_reward, point.round_completed, point.completed_samples, point.expected_samples) checkpoints = client.rl.checkpoints.list(run.training_run_id) checkpoint = max(checkpoints, key=lambda c: c.step_index) print(checkpoint.step_index, checkpoint.checkpoint_id, checkpoint.base_model_slug) ``` Check `round_completed`, and `completed_samples` against `expected_samples`, before comparing validation means. The project's **Training** tab shows run progress and checkpoints. [Evaluate that checkpoint](/guides/evaluations#3-score-a-checkpoint) before you deploy it. To use its weights outside Trajectory, [download it](/guides/checkpoint-downloads) (private beta). ## 4. Resume from a checkpoint ```python theme={null} resumed = client.rl.train( bench_id=bench_id, base_model_slug=checkpoint.base_model_slug, parent_checkpoint_id=checkpoint.checkpoint_id, options={"num_steps": 20}, display_name="Resumed training", ) print("Resumed training:", resumed.training_run_id, links.training(resumed.training_run_id)) ``` The checkpoint must match the selected base model and, for full resume, its training algorithm must be compatible. When changing to RLCD from another algorithm, explicitly choose `load_weights_only=True`. Use `parent_checkpoint_id` for both resumed training and checkpoint evaluation. Resuming restores the optimizer, LR schedule, and global step; set `load_weights_only` to `true` to start from the checkpoint's weights with fresh training state. `load_weights_only` defaults to `False` and is accepted even though it isn't in `training.list_options()`. Pass it in `options`: ```python theme={null} fresh = client.rl.train( bench_id=bench_id, base_model_slug=checkpoint.base_model_slug, parent_checkpoint_id=checkpoint.checkpoint_id, options={"num_steps": 20, "load_weights_only": True}, ) ``` For a fork that keeps the parent's launch settings, start with the source run's recorded options. Remove its old checkpoint-state flags before choosing which state the new fork should load. When loading the LR schedule, omit LR and schedule options: the checkpoint supplies them. ```python theme={null} parent = client.rl.runs.retrieve(run.training_run_id) options = parent.options.model_dump( exclude={ "load_weights_only", "load_optimizer", "load_scheduler", "load_dataset", "learning_rate", "lr_warmup_steps", "lr_hold_steps", "lr_min_ratio", }, exclude_none=True, ) options.update( num_steps=10, load_weights_only=True, load_optimizer=True, load_scheduler=True, load_dataset=True, ) continued = client.rl.train( bench_id=bench_id, base_model_slug=checkpoint.base_model_slug, parent_checkpoint_id=checkpoint.checkpoint_id, options=options, ) ``` This fork runs 10 new steps. Leave `load_scheduler` off and set `learning_rate` to start a new schedule at a different rate. Leave `load_dataset` off when changing the dataset or batch settings; restoring its position requires those settings to match. ## SFT datasets The public dataset API selects trajectories from existing training and evaluation runs. Offline prompt/response imports and edits to stored input context are unavailable through this API. [Production traces](/guides/production-traces) capture live model calls. ### Choose run sources Choose runs from the dataset's project and organization. | Source | Eligible attempts | Default dataset split | | - | - | - | | `training_run_ids` | Completed train attempts with rewards from successful or cancelled runs. | Training | | `eval_run_ids` | Scored attempts from completed evaluations. | Validation | Pass up to 30 source run IDs per add request and choose a `filter`. Use `no_errors` to exclude errors, `reward_threshold` with a numeric `value` to set a minimum reward, or `best_per_task` to keep the top-scoring attempt per task in each run. ### Create and finalize a dataset SFT needs a finalized dataset with nonempty training and validation splits, even when validation is disabled. Wait for the add to finish, then check both splits. Use `trajectory-sdk` 0.11.9 or later for this example. ```python theme={null} import time from trajectory import Client client = Client() dataset = client.datasets.create(name="sft-examples", agent_id="YOUR_PROJECT_ID") operation = client.datasets.add_trajectories( dataset.dataset_id, training_run_ids=["YOUR_TRAINING_RUN_ID"], eval_run_ids=["YOUR_EVAL_RUN_ID"], filter={"type": "no_errors"}, ) while operation.status in {"queued", "running"}: time.sleep(5) operation = client.datasets.operations.retrieve(operation.operation_id) if operation.status != "succeeded" or operation.source_errors: raise RuntimeError(operation.source_errors or operation.error or operation.status) dataset = client.datasets.retrieve(dataset.dataset_id) if not dataset.train_count or not dataset.test_count: raise ValueError("Choose source runs that populate both dataset splits.") dataset = client.datasets.finalize(dataset.dataset_id) ``` If an add fails, earlier additions can remain in the draft. Inspect the dataset with `client.datasets.members.list(dataset.dataset_id)` before retrying or finalizing it. ### Start SFT Use `client.sft.list_options()` to choose a supported model. SFT uses the validation split to score checkpoints when validation is enabled. ```python theme={null} run = client.sft.train( dataset_id=dataset.dataset_id, base_model_slug="YOUR_SUPPORTED_SFT_MODEL_SLUG", ) print(run.training_run_id) ``` Check run status with `client.rl.runs.retrieve(run.training_run_id)`. ## Training options For RL training, pass these keys in `options`. The defaults below apply to every supported model unless noted; `client.rl.list_options()` reports its bounds and defaults. A default written as `null` → a value is computed when you leave the option unset. With the default `batch_size` of 32 and `group_size` of 8, that resolves to 512 concurrent training trajectories and a minimum of 4 eligible trajectories per group. ### Optimization | Option | Default | What it controls | | - | - | - | | `num_steps` | `100` | Number of optimizer steps to run (1–100,000). | | `algorithm` | Spec/model default | Use `list_options(bench_id=..., base_model_slug=...)` for supported choices. Decision specs default to and require `rlcd` ([Brier training](/guides/decision-training)); generative specs exclude it. | | `batch_size` | `32` | Eligible task-instance groups per optimizer update (1–256). | | `group_size` | `8` | Trajectories generated for each training instance; GSPO and GRPO require at least 2 (at most 32); RLCD supports 1. | | `min_trajectories_per_group` | `null` → `group_size // 2` | Minimum eligible trajectories per training group. `null` uses half of `group_size`, rounded down (1–32); RLCD clamps this default to at least 1. | | `learning_rate` | `1e-4` | Base optimizer learning rate (1e-8–1e-2). | | `lr_warmup_steps` | `15` | Reported training steps used for warmup, including skipped optimizer updates. | | `lr_hold_steps` | `135` | Training steps to hold the base rate after warmup, including skipped updates, before cosine decay. | | `lr_min_ratio` | `0.1` | Cosine decay floor as a fraction of the base learning rate (0–1). | | `max_staleness` | `3` | Maximum optimizer steps a training trajectory's starting policy may trail the current policy (0–100). Older in-flight trajectories are cancelled and older completed trajectories are discarded; `0` trains only on trajectories started from the current policy. | | `load_weights_only` | `false` | Load parent checkpoint weights with fresh training state. Defaults to `false`, which resumes the optimizer, LR schedule, and global step. With validation enabled, evaluate the starting policy, run validation when `global_step % val_interval_steps == 0`, and evaluate the final policy on normal completion. Resuming preserves the global step and validation cadence. | | `load_optimizer` | `false` | With `load_weights_only`, also restore the parent's optimizer state, keeping the requested learning rate. | | `load_scheduler` | `false` | With `load_weights_only`, also restore the parent's learning rate and LR schedule. Explicitly different LR or schedule options are rejected. | | `load_dataset` | `false` | With `load_weights_only`, also restore the parent's dataset position; dataset and batch settings must match. | | `density_aware_training` | `false` | Train each task at four output-token budgets, with `group_size` trajectories per budget. Turns on `train_on_truncation`, which must stay `true` except when resuming a checkpoint with its training state. `batch_size` sets the total number of task groups per batch; each budget counts as a separate group. [Learn more](https://www.trajectory.ai/field-notes/intelligence-density). | The learning rate rises linearly to `learning_rate` over `lr_warmup_steps`, holds until step `lr_warmup_steps + lr_hold_steps`, then follows a cosine curve down to `learning_rate × lr_min_ratio` at the final step. ![Learning rate by training step: a linear rise to the base rate by step 15, flat until step 150, then a cosine curve down to 10% of the base rate at the final step of a 400-step example. A default 100-step run ends during the flat section.](https://mintcdn.com/trajectory/U_ViD_ffmPwHpDb1/images/lr-schedule-light.svg?fit=max\&auto=format\&n=U_ViD_ffmPwHpDb1\&q=85\&s=6d9127a7c8f533d6f81c85f37c4fe1f2) With the defaults, decay starts at step 150, so a default 100-step run ends at the base rate. To use the decay, set `num_steps` above 150 or lower `lr_hold_steps`. ### Training filters | Option | Default | What it controls | | - | - | - | | `train_on_truncation` | `false`; `true` with `density_aware_training` | Include trajectories that hit token or turn limits in training, with reward 0. Defaults to `false`, or `true` with `density_aware_training`; set to `true` to discourage reward hacking through truncated submissions. | | `train_on_timeout` | `false` | Include timed-out trajectories in training, with reward 0. Defaults to `false`; set to `true` to discourage reward hacking through timed-out submissions. | | `train_on_error` | `false` | Train on errored trajectories, including execution errors, grading errors, and missing grades, with reward 0. | | `train_on_all_fail` | `false` for generative; `true` for decision training | Train on groups whose eligible rewards are all at or below zero; `false` excludes them. | | `train_on_all_pass` | `false` for generative; `true` for decision training | Train on groups whose eligible rewards are all at or above one; `false` excludes them. | | `train_on_zero_advantage` | `false` for generative; `true` for decision training | Train on groups with identical eligible rewards; `false` excludes them. | Reward 0 applies to training only; the recorded trajectory reward stays as logged. See [termination reasons](/guides/termination-reasons). ### Trajectories | Option | Default | What it controls | | - | - | - | | `max_concurrent_trajectories` | `null` → `batch_size × group_size × 2` | Maximum active training trajectories (1–1,024). `null` uses `batch_size × group_size × 2`, allowing 2× batch oversampling for throughput and asynchronous RL. Recommended: set above `batch_size × group_size` to keep collection ahead of training. | | `max_turns_per_trajectory` | `200` | Maximum agent and environment turns allowed in each trajectory (1–500). | | `max_output_tokens_per_turn` | `null` → model maximum | Maximum output tokens per model response. `null` uses the model's maximum, bounded by remaining context. | | `max_output_tokens_per_trajectory` | `null` → model maximum context length | Maximum output tokens across one trajectory, including after context compaction (1–2,097,152). `null` uses the model's maximum supported context length. | | `trajectory_timeout_seconds` | `7200` | Maximum execution seconds per trajectory, including grading (1–36,000). Excludes queueing and sandbox startup. Collection timeouts must cover this budget. | | `batch_timeout_seconds` | `9600` | Wall-clock threshold for reporting slow training batch collection (1–38,400). It doesn't end or fail the batch: collection continues past the threshold and is reported again after each additional interval. | ### Sampling | Option | Default | What it controls | | - | - | - | | `reasoning_effort` | `null` → lowest supported thinking level | Model reasoning effort. `null` selects the lowest supported thinking level; `off` disables thinking where supported. Levels: `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, depending on the model. Qwen3.5-4B, Qwen3.6-35B-A3B, Qwen3.5-397B-A17B, and Nemotron-3.5-Lightning-30B-A3B support only on/off; `null` selects `on`. `list_options` reports each model's `choices`; other values return 422. | | `temperature` | `1.0` | Sampling temperature; defaults to 1.0 (0–2). | | `top_p` | `1.0` | Nucleus sampling probability; `null` preserves the model default (0–1). | | `top_k` | `-1` | Sample from the top k tokens; `-1` disables the limit, and `null` preserves the model default. | Thinking tokens count toward output-token limits. Inspect diagnostic replies before choosing a budget; a small cap can end a reasoning reply before its answer. Use the model's supported `reasoning_effort` to control thinking. Managed runs resolve this option and apply it ahead of request-level `disable_thinking`. ### Images | Option | Default | What it controls | | - | - | - | | `image_max_pixels` | `null` → model limit | Downscale [input images](/guides/images) above this many pixels, keeping their aspect ratio, before the model reads them (1–16,777,216). Fewer pixels cost fewer image tokens. Checkpoint evaluations and deployments keep the training run's value unless you set it; retaining it does not enable image input in checkpoint deployment chat, which currently accepts text only. | ### Validation during training | Option | Default | What it controls | | - | - | - | | `val_enabled` | `true` | Enable validation during training. | | `val_interval_steps` | `1` | Training steps between validations; `0` disables validation (0–100). When using `0`, omit `val_enabled`; an explicit `true` is rejected. | | `val_num_tasks` | `50` | Maximum distinct tasks per evaluation. Standalone evals run every task in the selected scope when omitted. | | `val_trajectories_per_task` | `1` | Number of trajectories generated for each task in a validation round. | | `val_max_concurrent_trajectories` | `50` | Maximum number of validation trajectories running concurrently. | | `val_final_wait_timeout_seconds` | `7200` | Maximum seconds to wait for outstanding validation rounds at training end; `0` stops waiting immediately. | | `val_reasoning_effort` | `null` → training setting | Validation reasoning effort. `null` inherits training defaults. Supports the same model-specific levels and on/off options as `reasoning_effort`. | | `val_temperature` | `null` → training setting | Validation sampling temperature (0–2). `null` inherits training defaults. | | `val_top_p` | `null` → training setting | Validation nucleus sampling probability (0–1). `null` inherits training defaults. | | `val_top_k` | `null` → training setting | Validation top-k token limit. `null` inherits training defaults; `-1` disables it. | | `val_max_output_tokens_per_turn` | `null` → training setting | Maximum output tokens per turn in each validation trajectory. `null` inherits training defaults. | | `val_max_output_tokens_per_trajectory` | `null` → training setting | Maximum output tokens across one validation trajectory. `null` inherits training defaults. | | `val_max_turns_per_trajectory` | `null` → training setting | Maximum agent and environment turns per validation trajectory. `null` inherits training defaults. | | `val_trajectory_timeout_seconds` | `null` → training setting | Maximum execution seconds per validation trajectory, including grading. `null` inherits training defaults. | ## Reduce trajectory spend Training is asynchronous: trajectories keep running up to `max_concurrent_trajectories`, including while an optimizer step is in progress. Each step trains on `batch_size` complete groups that pass filtering. Groups whose trajectories all pass, all fail, or tie carry no learning signal, so by default they are discarded after using tokens. * **Concurrency.** The default oversamples by 2×. Lower `max_concurrent_trajectories` to spend less on trajectories the trainer may not use, but keep it above `batch_size × group_size` so collection stays ahead of training. * **Staleness.** Trajectories that started more than `max_staleness` steps before the current step are discarded: running ones are cancelled and finished ones are skipped. Lower values keep training closer to on-policy but discard more work. `0` cancels every trajectory still running when a step finishes. * **Validation.** With the defaults, a 100-step run validates 101 times on up to 50 tasks, about 5,000 extra trajectories. Set `val_interval_steps` to `5` or `10`, lower `val_num_tasks`, or set `val_interval_steps` to `0` and [evaluate checkpoints](/guides/evaluations#3-score-a-checkpoint) after training. ```python theme={null} run = client.rl.train( bench_id=bench_id, base_model_slug="YOUR_SUPPORTED_TRAINING_MODEL_SLUG", options={ "num_steps": 50, "max_concurrent_trajectories": 384, "val_interval_steps": 10, "val_num_tasks": 25, }, ) ``` # Introduction Source: https://docs.trajectory.ai/introduction Improve models from the specs you already have, and from production. Trajectory provides the easiest most intuitive way to train your own models. All it takes is a few lines of code to wrap your LLM calls and log a reward. This gives our training platform signal for what the model should learn in your domain of interest. During training, you can tune just about anything: token budget, max turns, reasoning effort, even the Reinforcement Learning algorithm used to train. The platform takes care of the difficult parts of training like sandboxing, high throughput rollouts, and observability, all so you don't have to. Using a coding agent? [Install the SDK skills](/coding-agents) to give it the integration guides and reporting behavior for your project. ## From a spec A Spec is how you tell Trajectory what to get better at, and what good looks like for your domain. A **project** owns this definition: its specs, its production traces, its training history, and the models it serves. Bring the tasks, harness, and grader you already run. Trajectory supplies the model endpoint, records each reward, and carries a model from a baseline to the checkpoint the project serves. 1. **Evaluate** a base model. 2. **Train** on your tasks. 3. **Compare** the checkpoint on held-out tasks. 4. **Deploy** the model you want to serve. > [card] [Run your first evaluation](/quickstart) > > Install the client, pick a spec, and read the score. > [card] [Bring your spec](/guides/spec) > > Point your harness at Trajectory and upload your tasks. ## From production > [!NOTE] > > Private beta. Your application keeps running in your own infrastructure. Trajectory records each attempt as a trace in the project, then turns that experience into a model you can train and promote. * **With a grader.** Collect traces and scores, train, and evaluate on a spec before you promote. * **Without a grader.** Collect traces first. Trajectory helps you define the learning signal, then you train and evaluate the same way. A spec remains how you measure a candidate. Production traces are the experience the model learns from. > [card] [Collect production traces](/guides/production-traces) > > Record model calls and outcomes from your application. # Use the platform Source: https://docs.trajectory.ai/platform Where to find a project's specs, runs, and serving model. Select the organization and project. **Settings** holds API keys and secrets. | Tab | What you do there | | - | - | | **Specs** | Inspect tasks and their runtimes. [Bring your spec](/guides/spec). | | **Evaluation** | Read evaluation scores. [Evaluate](/guides/evaluations). | | **Training** | Start a training run on a trainable model or pick a checkpoint to start at. [Train](/guides/training). | | **Deployments** | Test and promote a model to serve inference after training. [Deploy](/guides/deployments). | ## Find a resource Platform links start with `https://platform.trajectory.ai/`. The organization key is the first part of the path in your browser. | Page | Path after `/` | | - | - | | Project | `/agents/` | | Spec version | `/agents//benchmarks/` | | Evaluation results | `/evaluate/runs//trajectories` | | Compare evaluations | `/agents//evaluation/?run=&run=` | | Training run | `/models/` | | Deployment | `/deployments/` | | Production trajectories | `/agents//production-trajectories` | An evaluation link can select a trajectory with `?tid=`. A training link can select one with `?step=&trajectory=`. ## Build links from the SDK `PlatformLinks` builds these URLs and encodes IDs and selections. With an existing SDK client: ```python theme={null} from trajectory.lib.platform_links import PlatformLinks links = PlatformLinks.from_client(client) print("Training:", links.training(training_run_id)) # https://platform.trajectory.ai//models/ ``` `from_client` looks up your organization once. If you already know its key, use `PlatformLinks(organization_key)` instead. > [accordion] SDK methods and trajectory selections > > | What to inspect | Link helper | > | - | - | > | Project | `links.agent(agent_id)` | > | Spec version | `links.spec(agent_id, bench_id)` | > | Evaluation | `links.evaluation(eval_run_id)` | > | Evaluation trajectory | `links.evaluation(eval_run_id, trajectory_id=trajectory_id)` | > | Compare evaluations of one spec | `links.comparison(agent_id, bench_id, [baseline_id, checkpoint_eval_id])` | > | Training run | `links.training(training_run_id)` | > | Training trajectory | `links.training(training_run_id, step=step, trajectory_id=trajectory_id)` | > | Validation trajectory in training | `links.training(training_run_id, step=step, trajectory_id=trajectory_id, source="validation")` | > | Deployment | `links.deployment(deployment_id)` | > | Production trajectories | `links.production(agent_id)` | > | Production conversation | `links.production(agent_id, trajectory_id=trajectory_id)` | > > Training links also accept `task_uid` to select a trajectory's task and `focus="errors"` > to filter the view. Use the step reported by the run, including step zero; a trajectory > selection requires that step. Deployment links use the deployment ID returned by the API. > [accordion] Internal staging and local development > > Production links use `https://platform.trajectory.ai` by default. For internal staging > or local development, pass the platform URL used in your browser: > > ```python theme={null} > links = PlatformLinks.from_client(client, platform_url="https://staging.platform.trajectory.ai") > ``` > > If the client's API URL differs from `https://api.trajectory.ai`, supply `platform_url` > explicitly. The API URL alone does not identify which UI serves those resources. Share the run link when work starts. When reporting results, include a link to the trajectory or comparison that supports them and state whether the run has finished. # Models and pricing Source: https://docs.trajectory.ai/pricing Per-token prices for training, evaluation, grading, and inference, plus compute and storage. Prices are in USD per million tokens unless noted. ## Trainable models Every trainable model can also be evaluated and deployed. Evaluation uses the same rates, without the train charge. | Model | Slug | Prefill | Cached prefill | Sample | Train | | - | - | -: | -: | -: | -: | | GLM 5.3 | `z-ai/glm-5.3` | \$3.6288 | \$0.4864 | \$11.664 | \$13.9968 | | Qwen 3.5 397B | `Qwen/Qwen3.5-397B-A17B` | \$1.584 | \$0.2112 | \$7.20 | \$11.52 | | Nemotron 3 Ultra | `nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16` | \$1.98 | \$0.288 | \$6.8475 | \$10.956 | | Qwen 3.8 27B | `Qwen/Qwen3.8-27B` | \$0.672 | \$0.0896 | \$5.376 | \$7.1616 | | DeepSeek V4.1 Flash | `deepseek-ai/DeepSeek-V4.1-Flash` | \$0.66 | \$0.132 | \$3.96 | \$5.478 | | GLM 5.3 Flash | `z-ai/glm-5.3-flash` | \$0.8064 | \$0.1088 | \$2.0256 | \$5.3568 | | Inkling Small | `thinkingmachines/Inkling-Small` | \$0.638 | \$0.0928 | \$1.584 | \$3.817 | | Nemotron 3.5 Super | `nvidia/NVIDIA-Nemotron-3.5-Super-120B-A12B-BF16` | \$0.627 | \$0.0912 | \$1.584 | \$2.552 | | Nemotron 3 Super | `nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16` | \$0.627 | \$0.0912 | \$1.584 | \$2.552 | | Qwen 3.6 35B | `Qwen/Qwen3.6-35B-A3B` | \$0.432 | \$0.0576 | \$1.2864 | \$2.0544 | | Inkling 2 Small | `thinkingmachines/Inkling-2-Small` | \$0.33 | \$0.033 | \$1.10 | \$3.30 | | Qwen 3.5 4B | `Qwen/Qwen3.5-4B` | \$0.3168 | \$0.0416 | \$0.9696 | \$1.2864 | | Inkling 2 Mini | `thinkingmachines/Inkling-2-Mini` | \$0.165 | \$0.0165 | \$0.55 | \$1.65 | | Nemotron 3.5 Lightning | `nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16` | \$0.2024 | \$0.0288 | \$0.5445 | \$0.88 | ### Deployments [Deployments](/guides/deployments) are billed per token at the base model's prefill, cached prefill, and sample rates. There is no hourly charge. ## Evaluation models These models can't be trained. Use them for evaluation and grading. GPT-6 Astra, GPT-5.6 Sol, GPT-5.6 Luna, GPT-5.4 Mini, Claude Opus 5.5, and Claude Sonnet 5.5 are also on the [inference API](/api-reference/inference/create-chat-completion-1). GPT-5.6 Terra is available on the inference API, but not for evaluation or grading. | Model | Slug | Prefill | Cached prefill | Cache write | Sample | | - | - | -: | -: | -: | -: | | GPT-6 Astra | `openai/gpt-6-astra` | \$13.00 | \$1.30 | \$16.25 | \$65.00 | | GPT-5.5 | `openai/gpt-5.5` | \$6.50 | \$0.65 | \$6.50 | \$39.00 | | GPT-5.6 Sol | `openai/gpt-5.6-sol` | \$5.20 | \$0.52 | \$6.50 | \$26.00 | | Claude Opus 5.5 | `anthropic/claude-opus-5.5` | \$5.20 | \$0.26 | \$6.50 | \$26.00 | | Claude Sonnet 4.6 | `anthropic/claude-sonnet-4.6` | \$3.90 | \$0.39 | \$4.875 | \$19.50 | | Kimi K3 | `moonshotai/kimi-k3` | \$3.90 | \$0.39 | \$3.90 | \$19.50 | | Gemini 3 Pro | `google/gemini-3.1-pro-preview` | \$2.60 | \$0.26 | \$0.4875 | \$15.60 | | GPT-5.6 Terra | `openai/gpt-5.6-terra` | \$2.60 | \$0.26 | \$3.25 | \$15.60 | | GPT-6.1 Sol | `openai/gpt-6.1-sol` | \$2.60 | \$0.13 | \$3.25 | \$13.00 | | GPT-6 Sol | `openai/gpt-6-sol` | \$2.60 | \$0.26 | \$3.25 | \$13.00 | | Claude Sonnet 5.5 | `anthropic/claude-sonnet-5.5` | \$2.60 | \$0.13 | \$3.25 | \$13.00 | | GPT-5.4 Mini | `openai/gpt-5.4-mini` | \$0.975 | \$0.0975 | \$0.975 | \$5.85 | | GPT-5 Mini | `openai/gpt-5-mini` | \$0.325 | \$0.0325 | \$0.325 | \$2.60 | | GPT-5.6 Luna | `openai/gpt-5.6-luna` | \$0.26 | \$0.026 | \$0.325 | \$1.56 | | GPT-6 Luna | `openai/gpt-6-luna` | \$0.13 | \$0.013 | \$0.1625 | \$0.65 | Claude cache writes are 5-minute; 1-hour writes cost 2× prefill. ### Long-context prompts Requests whose prompt exceeds the threshold are billed entirely at these rates. | Model | Slug | Prompt above | Prefill | Cached prefill | Cache write | Sample | | - | - | -: | -: | -: | -: | -: | | GPT-6 Astra | `openai/gpt-6-astra` | 272K tokens | \$26.00 | \$2.60 | \$32.50 | \$97.50 | | GPT-5.5 | `openai/gpt-5.5` | 272K tokens | \$13.00 | \$1.30 | \$13.00 | \$58.50 | | GPT-5.6 Sol | `openai/gpt-5.6-sol` | 272K tokens | \$10.40 | \$1.04 | \$13.00 | \$39.00 | | Gemini 3 Pro | `google/gemini-3.1-pro-preview` | 200K tokens | \$5.20 | \$0.52 | \$0.4875 | \$23.40 | | GPT-5.6 Terra | `openai/gpt-5.6-terra` | 272K tokens | \$5.20 | \$0.52 | \$6.50 | \$23.40 | | GPT-6.1 Sol | `openai/gpt-6.1-sol` | 272K tokens | \$5.20 | \$0.26 | \$6.50 | \$19.50 | | GPT-6 Sol | `openai/gpt-6-sol` | 272K tokens | \$5.20 | \$0.52 | \$6.50 | \$19.50 | | GPT-5.6 Luna | `openai/gpt-5.6-luna` | 272K tokens | \$0.52 | \$0.052 | \$0.65 | \$2.34 | | GPT-6 Luna | `openai/gpt-6-luna` | 272K tokens | \$0.26 | \$0.026 | \$0.325 | \$0.975 | ## Grading Model-based graders are billed at the grader model's token rates above. ## Sandbox environments Each trajectory runs in its own sandbox, billed per second from ready to stop. | Resource | Price | | - | -: | | CPU | \$0.20 per CPU-hour | | Memory | \$0.04 per GiB-hour | Set `cpus` and `memory_mb` in [`env_resources`](/guides/spec). Sandboxes can burst above their request, so you can size below peak. Each second is billed at the greater of the request and actual usage. Example: 1 CPU and 4 GiB cost $0.36/hour, so 1,000 ten-minute trajectories cost $60. ## Trace storage First 10 GB free each month, then \$0.15 per GB-month. ## Pricing terms | Term | Meaning | | - | - | | Prefill | Prompt tokens the model processes. | | Cached prefill | Prompt tokens served from the cache. | | Cache write | Prompt tokens an evaluation model writes to its cache. | | Sample | Tokens the model generates, including reasoning tokens. | | Train | Tokens fed to the training model, counted once for native loss and twice for custom loss. | Train includes masked tokens and cached prompt prefixes. Each update counts its inputs again. A standard next-token training sequence of `N` tokens has `N - 1` input positions because the last token is only a prediction target. ### Train tokens in multi-turn rollouts For managed token-based RL, turns share a training sequence while each new turn extends the previous token sequence, training mask, and image inputs. Editing or compacting earlier messages can start a new sequence. Training counts each sequence with trainable output, including its masked prompt and tool context. For example, if two turns contain 1,000 and 1,500 tokens, and the second extends the first, the sequence contributes 1,499 input positions for native loss. If the turns form separate sequences and both are used, they contribute 999 + 1,499 positions. Custom loss counts each total twice. This is separate from the prefill, cached prefill, and sample tokens the model uses during generation. After a training update, [step metrics](/guides/training#3-watch-progress-and-pick-a-checkpoint) report how many sequences were trained per trajectory. # Projects Source: https://docs.trajectory.ai/projects Group related specs and choose a project. A project groups specs, training history, and the serving model for one use case. ## Group specs by relevance Keep specs together when they measure capabilities you want to improve in the same project. For example, ticket routing and response quality specs can belong to one customer-support project. A code-repair spec for a separate coding assistant belongs to a different project. Adding a dataset, testing another capability, or uploading a new spec version for the same use case can use the same project. A distinct project or use case is a reason to create another one. Choose a descriptive name and description so the grouping is clear to others. ## Choose or create a project * Use the project selected for your work when one is provided. * Reuse a project when its purpose fits the specs you want to group together. * Create a project when no existing one fits, whether the organization is empty or has projects for unrelated work. Inspect the organization's projects by name and description to find a relevant destination: ```python theme={null} from trajectory import Client client = Client() for candidate in client.projects.list(): print(candidate.agent_id, candidate.name, candidate.description) ``` For a new use case, create a project: ```python theme={null} project = client.projects.create( name="customer-support", description="Ticket routing and response quality for customer support", ) print(project.agent_id) ``` Use the selected or newly created project's ID as `agent_id` in uploads and task diagnostics. Create the project before uploading if needed; upload helpers associate the spec with the project you choose. Continue with [Bring your spec](/guides/spec). # Quickstart Source: https://docs.trajectory.ai/quickstart Install the client and run a baseline evaluation. This starts an evaluation on a spec you already uploaded. To upload one, [choose or create a project](/projects), then follow [Bring your spec](/guides/spec). The [cookbook](https://github.com/Trajectorylabs/trajectory-cookbook) has worked spec integrations. Using a coding agent? [Install the SDK skills](/coding-agents) first. ## 1. Install You need Python 3.11 or later and a Trajectory account. For a new spec, the [command-line guide](/guides/cli) can scaffold a small runnable example. ```bash pip theme={null} pip install --upgrade trajectory-sdk ``` ```bash uv theme={null} uv add trajectory-sdk ``` ```bash theme={null} tj login tj whoami ``` For unattended jobs, set `TRAJECTORY_API_KEY` as described in [Authentication](/authentication). ```python theme={null} from trajectory import Client client = Client() print(client.organizations.retrieve_current()) ``` ## 2. Choose a spec and model Use the project and spec names from your upload. The pair selects the latest uploaded version under that project. List the available base models: ```python theme={null} from trajectory import Client client = Client() for model in client.evals.list_models().items: print(model.base_model_slug) ``` ## 3. Start the evaluation ```python theme={null} from uuid import uuid4 from trajectory import Client from trajectory.lib.platform_links import PlatformLinks client = Client() links = PlatformLinks.from_client(client) agent_name = "YOUR_AGENT_NAME" bench_name = "YOUR_BENCHMARK_NAME" base_model_slug = "Qwen/Qwen3.5-4B" run = client.evals.create( agent_name=agent_name, benchmark_name=bench_name, base_model_slug=base_model_slug, display_name="Baseline evaluation", idempotency_key=str(uuid4()), ) print("Evaluation:", run.eval_run_id, links.evaluation(run.eval_run_id)) print(client.evals.runs.progress(run.eval_run_id).status) ``` Poll progress until the evaluation is `completed`, `failed`, or `cancelled`. After completion, retrieve the recorded score: ```python theme={null} result = client.evals.runs.retrieve(run.eval_run_id) print("Mean reward:", result.reward_mean) ``` Finish a baseline/checkpoint comparison before uploading another version under the same name. Use `bench_id` instead of the name pair when selecting a specific spec version. Open the run in the platform to read trajectories; [Use the platform](/platform) shows the run URL. Next: [Train a model](/guides/training), then [Deploy a model](/guides/deployments). ## Send product feedback Share feedback, suggestions, or positive observations with the [agent-feedback skill](/.well-known/skills/agent-feedback/SKILL.md) when reporting is authorized. A short prose message is enough; supporting details are optional. Both skills are installed through [coding-agent setup](/coding-agents). # Client reference Source: https://docs.trajectory.ai/reference/client Configure the Python client and page through results. Install `trajectory-sdk` and import `Client` from `trajectory`. ```python theme={null} from trajectory import Client with Client() as client: page = client.projects.list(limit=20) for project in page.items: print(project.name, project.description) ``` ## Configuration | Option | Behavior | | - | - | | `api_key` | Explicit key, then `TRAJECTORY_API_KEY`, then the selected saved login. | | `profile` | Saved login profile; defaults to `TRAJECTORY_PROFILE`, then the active profile. | | `base_url` | Explicit URL, then `TRAJECTORY_BASE_URL`, then the saved profile destination or `https://api.trajectory.ai`. | | `timeout` | Seconds, an `httpx2.Timeout`, or `None`. | | `max_retries` | Retries after the first attempt. Defaults to `2`. | | `http_client` | Your own `httpx2.Client`. | ```python theme={null} from trajectory import Client client = Client() page = client.with_options(timeout=30, max_retries=0).specs.list(limit=10) print(page.model_dump()) ``` Run `tj login` to save a credential for `Client()`. Saved credentials are bound to their API origin; changing a copied client to a different origin drops inherited credentials. See [Authentication](/authentication) for profiles and unattended jobs. Use the [current organization dictionary](/authentication#sign-in) to verify your login. ## Resources | Resource | Use | | - | - | | `client.projects` | Projects that own specs, runs, and deployments. | | `client.specs` | Specs, tasks, and readiness. | | `client.diagnostics` | Task and spec diagnostics. | | `client.specs.diagnostics.findings` | [Data quality findings](/guides/spec#record-a-data-quality-finding) on specs, tasks, and trajectories. | | `client.evals` | Evaluations. | | `client.rl` | Training runs and checkpoints. | | `client.datasets` | [SFT datasets](/guides/training#sft-datasets): select existing run trajectories, inspect splits, and finalize. | | `client.sft` | [Supervised fine-tuning](/guides/training#start-sft) on finalized datasets with training and validation trajectories. | | `client.deployments` | Deployments. | | `client.model_slugs` | Each project's production model slug. | | `client.chat.completions` | Model calls. Model Endpoint chat calls require a trajectory ID. Pass `x_trajectory_id` or set `X-Trajectory-Id` in the client's default headers. | | `client.responses` | Model calls in the Responses format. | | `client.inference` | Models your organization can call. | | `client.trajectories` | Rewards, events, and completion. | | `client.artifacts` | Artifact downloads by ID. | | `client.telemetry` | Application events. | | `client.billing` | Run costs over the last 30 days. | | `client.organizations` | The current organization. | | `client.secrets` | [Create an organization secret](/guides/spec#create-an-organization-secret) for `SecretRef`. | | `client.beta.checkpoint_exports` | Private beta: [checkpoint downloads](/guides/checkpoint-downloads). | `trajectory.lib` provides two forms of the same spec upload workflow: | Helper | Returns when | Result | | - | - | - | | `push(...)` | Registration and any requested image builds finish. | Spec result with `bench_id`. | | `start_push(...)` | Files are uploaded and processing is accepted. | Operation you can wait on or reconnect to later. | `push()` calls `start_push()` and waits with `operation.result()` internally. Both accept the same arguments. `start_push()` is a regular Python function; background processing happens on the server. See the [spec guide](/guides/spec). `ImageInput` builds chat image parts for vision models, inline or uploaded to a trajectory. See [Send images to a model](/guides/images). ## Update an existing spec Choose the operation for the change you need: | Change | Operation | | - | - | | Edit the name or description | `client.specs.update(bench_id, name=..., description=...)` updates metadata only. It does not change tasks or runtime files. | | Add or replace tasks while retaining `bench_id` | Use the HTTP task append workflow below. | | Publish a new version with the full desired task set | Use `push()` or `start_push()` with the same project and spec name. These helpers have no existing-ID parameter. See [Update your spec](/guides/spec#update-your-spec). | ### Add or replace tasks under the same ID The current Python `client.specs.tasks` resource exposes `list()`, `count()`, and `diff()`. It has no `append()` or `commit()` methods; use HTTP for staging and commit. Do not use the initial `create_upload` path for an already-ingested ID: its HTTP 409 `BENCH_ALREADY_INGESTED` guard protects the original upload. 1. `POST /api/v1/specs/{bench_id}/tasks/diff` with a `manifest` (`BenchmarkSpec`) and an `artifacts` map of relative file paths to base64-encoded MD5 digests. The response contains `bench_id`, `new`, `present`, `updated`, and `task_count`. Task names (stored as labels) with identical content are `present`; changed content under the same name is `updated`. 2. `POST /api/v1/specs/{bench_id}/tasks/append` with a required `Idempotency-Key` header (1–128 characters) and `files`, each with `path`, `content_type`, and `size_bytes`. The HTTP 201 response contains `bench_id`, `batch_id`, `urls`, and `expires_at`. Each URL entry has `path`, `url`, and `headers`. Files are staged under a separate batch storage prefix. 3. Before `expires_at`, `PUT` each file's bytes to its returned `url` using the returned `headers`. Send the API key only to the API, not to signed storage URLs. 4. `POST /api/v1/specs/{bench_id}/tasks/append/{batch_id}/commit` with the `BenchmarkSpec` JSON as the request body directly, without a `manifest` wrapper. Inspect `added_count`, `updated_count`, `skipped_count`, and `failed_tasks` in the response; `bench_id` stays the same. Tasks omitted from the manifest are retained. For example, save a valid `BenchmarkSpec` as `manifest.json`, containing the tasks you intend to add or replace. Keep existing task names to replace them. Set `TRAJECTORY_API_KEY`, `BENCH_ID`, and `APPEND_IDEMPOTENCY_KEY`; reuse that key for retries of the same batch and use a new key for a different batch. Adapt `paths` to include every runtime build-context and task file referenced by your manifest. For a Dockerfile runtime, place the Dockerfile in a subdirectory such as `runtime/Dockerfile` and use that path in the manifest. The append API rejects Dockerfiles at the upload root. This example submits the whole manifest. ```python theme={null} import base64 import hashlib import json import mimetypes import os from pathlib import Path import httpx2 root = Path("spec") manifest = json.loads(Path("manifest.json").read_text()) paths = ["runtime/Dockerfile", "runtime/agent.py"] contents = {path: (root / path).read_bytes() for path in paths} files = [ { "path": path, "content_type": mimetypes.guess_type(path)[0] or "application/octet-stream", "size_bytes": len(data), } for path, data in contents.items() ] base_url = os.environ.get("TRAJECTORY_BASE_URL", "https://api.trajectory.ai") endpoint = f"{base_url.rstrip('/')}/api/v1/specs/{os.environ['BENCH_ID']}/tasks" with httpx2.Client(headers={"X-API-Key": os.environ["TRAJECTORY_API_KEY"]}) as api: diff = api.post(f"{endpoint}/diff", json={ "manifest": manifest, "artifacts": { path: base64.b64encode(hashlib.md5(data, usedforsecurity=False).digest()).decode("ascii") for path, data in contents.items() }, }) diff.raise_for_status() print(diff.json()) staged = api.post(f"{endpoint}/append", json={"files": files}, headers={ "Idempotency-Key": os.environ["APPEND_IDEMPOTENCY_KEY"], }) staged.raise_for_status() batch = staged.json() for upload in batch["urls"]: uploaded = httpx2.put( upload["url"], content=contents[upload["path"]], headers=upload["headers"], timeout=3600, ) uploaded.raise_for_status() committed = api.post(f"{endpoint}/append/{batch['batch_id']}/commit", json=manifest) committed.raise_for_status() result = committed.json() print(result) if result.get("failed_tasks"): raise RuntimeError(result["failed_tasks"]) ``` Replacement assigns **new task IDs**. A commit can partially succeed. Inspect `failed_tasks` for each task's `task_id`, optional `label`, and `error`. Repeating a commit for the same batch returns its original result. A new batch skips tasks whose content already matches. Replacement requires existing content hashes and can be blocked while active evaluation resources are being cleaned up. When runtime source changes, provide `runtime.source` with a path such as `{"dockerfile_path": "runtime/Dockerfile"}`, omit the old `runtime_id`, and upload the build-context files. An existing `runtime_id` references its existing source. After the commit succeeds, build and check readiness using the same spec ID: ```python theme={null} import os from trajectory import Client from trajectory.lib import wait_for_benchmark_images client = Client() bench_id = os.environ["BENCH_ID"] wait_for_benchmark_images(client, bench_id) readiness = client.specs.retrieve_readiness(bench_id) print(readiness.ready, readiness.missing_secret_names, readiness.unready_task_image_counts) ``` `wait_for_benchmark_images()` calls `client.specs.images.build(bench_id)` and reads every page of `client.specs.images.list(bench_id)` on each poll. It raises `BenchmarkImageBuildError` with the failed task IDs in `failures` or `BenchmarkImageBuildTimeoutError` if builds are still pending at the timeout. Start another run once `readiness.ready` is true. If it is false, check `missing_secret_names` and `unready_task_image_counts`. ## Training and evaluation Both resources accept `create(agent_name=..., benchmark_name=..., base_model_slug=..., options=...)` to select the latest spec version under that project. Pass `bench_id` instead of the name pair to select a specific version. Finish a baseline/checkpoint comparison before publishing another version under the same name. Use `parent_checkpoint_id` to resume training or evaluate a checkpoint. Request `options` dictionaries follow the shared `RunOptionsParam` type; run responses expose typed `RunOptions` values. Omitted, null, and empty options preserve defaults. ```python theme={null} from trajectory.types.run_options_param import RunOptionsParam options: RunOptionsParam = {"reasoning_effort": "off"} run = client.evals.create( agent_name="YOUR_AGENT_NAME", benchmark_name="YOUR_BENCHMARK_NAME", base_model_slug="Qwen/Qwen3.5-4B", options=options, ) result = client.evals.runs.retrieve(run.eval_run_id) print(result.base_model_slug, result.options.reasoning_effort) ``` ### Discover models and options Before uploading a spec, use `client.rl.list_models()` or `client.evals.list_models()` to choose a supported model and estimate token costs. Each response's `items` contains `base_model_slug`, `model_name`, and `pricing.input` / `pricing.output` in USD per million tokens. Training and evaluation can have different models and prices; use the catalog for the mode you plan to run. See [pricing](/pricing) for training, grading, sandbox, and other charges. ```python theme={null} for model in client.rl.list_models().items: print(model.base_model_slug, model.model_name, model.pricing.input, model.pricing.output) ``` Use `client.rl.list_options(...)` or `client.evals.list_options(...)` to discover supported settings for that mode, optionally filtering by `base_model_slug`. The response's `models` contains `base_model_slug` and an `options` map with types, bounds, descriptions, and fixed or computed defaults, without pricing. Training and evaluation may have different bounds for the same setting. For training, pass `bench_id` to get algorithms compatible with your spec; omitting it returns options for generative specs. Evaluation option discovery ignores `bench_id`. Training also accepts `options={"load_weights_only": True}` with `parent_checkpoint_id`, even though this option isn't listed. This loads checkpoint weights with fresh training state; see [resume from a checkpoint](/guides/training#4-resume-from-a-checkpoint). ## Run costs Use `client.billing.list_run_costs()` to read run costs: ```python theme={null} costs = client.billing.list_run_costs( offset=0, limit=50, sort="launch_at", order="desc", ) for run in costs.items: print(run.run_id, run.cents, run.training_cents, run.inference_cents, run.sandbox_cents) ``` Costs are in USD cents for the last 30 UTC calendar days. Page with `offset` and a `limit` of 1–50 (default 20). For a training run, `training_cents` includes model generation (prefill, cached prefill, and sample) and [Train tokens](/pricing#pricing-terms). Grading and sandbox costs are separate. For the USD estimate, let `P`, `C`, `S`, and `T` be your effective rates per million tokens for prefill, cached prefill, sample, and Train. ```text theme={null} (prefill_tokens * P + cached_prefill_tokens * C + sample_tokens * S + train_tokens * T) / 1,000,000 ``` For a run that trains on existing data without generating responses, use just the Train term. If the run generates a 100-token response to a 1,000-token prompt (800 cached) and trains on that sequence once with native loss, the estimate is `(200P + 800C + 100S + 1099T) / 1,000,000` USD. Custom loss counts 2,198 Train tokens. Costs may take several minutes to appear after a run finishes and can change as usage is processed. Charges for deleted runs remain listed under the run ID until they fall outside the 30-day window. ## Pagination Omit `cursor` for the first page. Passing `cursor=None` or `trajectory.omit` also omits the pagination cursor. An explicit empty string (`cursor=""`) is sent unchanged and the API rejects it with HTTP 400 `invalid_cursor`. For methods returning `SyncPage`, `.items` is the current page. Iterating the page automatically fetches the rest using the server-provided `next_cursor`. ```python theme={null} from trajectory import Client client = Client() for spec in client.specs.list(limit=20): print(spec.name) ``` Use `.has_next_page()` and `.get_next_page()` to request the next page yourself. For manual cursor pagination, pass the response's `next_cursor` only while `has_more` is true; stop when there are no more pages. ## Raw response ```python theme={null} from trajectory import Client client = Client() response = client.specs.with_raw_response.list(limit=10) print(response.headers.get("x-request-id")) page = response.parse() print(page.model_dump()) ``` # Errors and retries Source: https://docs.trajectory.ai/reference/errors Read a failed request and retry the same submission. HTTP failures raise `APIStatusError` with `status_code`, `code`, `message`, and `request_id`. Network failures raise `APIConnectionError`. ```python theme={null} from trajectory import APIConnectionError, APIStatusError, Client client = Client() try: spec = client.specs.retrieve("YOUR_BENCHMARK_ID") except APIStatusError as error: print(error.status_code, error.code, error.message) print(error.request_id) except APIConnectionError as error: print(error) else: print(spec.model_dump()) ``` The client retries connection failures, timeouts, `408`, `429`, and `5xx` twice. Set `max_retries=0` to turn that off. When adapting a harness that handles its own retries, preserve the SDK error's status, headers, and body. In particular, pass through `Trajectory-Should-Retry: false` so the harness does not retry an attempt the service has already rejected. Spec uploads retry longer, to ride out signing throttling: `push()` and `start_push()` retry each upload request up to `upload_max_retries` times (default `32`) or for 4.5 minutes of waiting, whichever comes first. The client's `max_retries` does not apply to them. Pass `upload_max_retries=0` to turn that off. Reuse an `idempotency_key` only when repeating the same submission. A new evaluation or training run needs a new key. A timeout or `503` can leave a write or inference request's outcome unknown. Use [read-only journal recovery](/reference/troubleshooting#journal-writes-fail-or-an-auxiliary-capture-stays-in_progress) to check what was recorded. Errors inside a trajectory, such as a model request your harness cannot recover from, are reported through the trajectory's termination reason. See [Termination reasons](/guides/termination-reasons). For specific error messages and symptoms, see [Troubleshooting](/reference/troubleshooting). # Troubleshooting Source: https://docs.trajectory.ai/reference/troubleshooting Find a symptom or error message, its cause, and how to confirm the fix. Search this page for the error text or the symptom you see. For how the SDK reports request failures, see [Errors and retries](/reference/errors). ## Training returns HTTP 400 requiring TRAIN tasks [Check the training split](/guides/training#check-the-training-split) for the exact `bench_id` in the request. If the count is zero, upload a spec version with training tasks in `train` and retry with the returned spec ID. Keep held-out tasks in `test`. ## PostgreSQL connections fail with hostname allowlisting If DNS resolves but a Modal task cannot connect to PostgreSQL on TCP port 5432, check [Network access on Modal](/guides/spec#network-access-on-modal) for supported connections and when to use public networking. ## Login reports a TLS certificate verification failure `auth_connection_failed: TLS certificate verification failed` means the CLI could not verify the API server's certificate. This can happen behind a corporate proxy that inspects HTTPS traffic. The failure happens before an API request can be handled; check certificate trust with your IT team. Use your organization's approved OS trust configuration, or ask IT for an approved PEM CA bundle. The CLI's HTTP client (`httpx2`) uses the OS trust store by default and honors `SSL_CERT_FILE` and `SSL_CERT_DIR`. It does **not** read `REQUESTS_CA_BUNDLE`. If IT supplies a proxy root CA separately, combine it with your approved public CA bundle in a new file, keeping the original bundle intact. For example, on macOS or Linux: ```bash theme={null} cat /path/to/approved-public-ca-bundle.pem /path/to/approved-proxy-root-ca.pem > /path/to/combined-ca-bundle.pem export SSL_CERT_FILE=/path/to/combined-ca-bundle.pem tj login ``` Use actual paths supplied or approved by IT. `SSL_CERT_FILE` replaces the default CA source, so the combined bundle must retain the public roots needed for other HTTPS connections. Alternatively, IT can provide an OpenSSL-compatible hashed certificate directory for `SSL_CERT_DIR`; unset `SSL_CERT_FILE` to use it. Restart login after changing the trust configuration. Never disable certificate verification or trust a certificate obtained from an unverified source. If the error occurs during polling and reports `login_redemption_uncertain`, first review and revoke any newly issued CLI key under **Settings → API keys** in the web app, then restart login with the approved trust configuration. The CLI does not retry an uncertain one-time redemption. ## Login reports `organization_mismatch` The organization key differed from the one you requested, or the API supplied no key. Check the expected key, then select the intended organization in the browser. * For a new login, retry with the expected key. If revocation was unconfirmed, open **Settings → API keys** in the organization you approved and revoke the new CLI key first. * For a saved login, use `tj whoami --profile work --json` to check the profile. Unset `TRAJECTORY_API_KEY` first if it is set. To sign in to a different organization, choose a new profile name or sign out with `tj logout --profile work` before retrying. ## Rewards are flat at zero A zero can mean a graded wrong answer, or no grade at all. `trajectory.reward` can be zero without a native grade, and a step summary's `incorrect_count` counts finished rollouts with reward 0, so neither shows that a grader ran. A harness that catches a grader failure and then calls `complete()` records `ENV_DONE` with no grade. Retrieve an affected trajectory with `include_reward_components=True`. Use `client.trajectories.list(training_run_id=...)` or `eval_run_id=...` to find attempts. Inspect `termination_reason`, `reward`, and `reward_components` together. | What you see | What it means | What to do | | - | - | - | | No components | No grade was recorded. | Fix the grader or harness. | | Components with a real score of zero | The answers were graded wrong. | Read the transcript and check the task and grader. | | `ERROR` or another non-`ENV_DONE` ending | The attempt did not finish normally. | See [Termination reasons](/guides/termination-reasons). | Check that the verifier and its dependencies are in the image. When grading fails, complete with `ERROR` and publish no reward. Options such as `train_on_all_fail` and `train_on_zero_advantage` change which groups training admits; they do not repair grading. Upload the fix as a new version and [diagnose one task](/guides/spec#validate-one-task-before-uploading). Check that it reports the ending and reward you expect, and that its reward components are present. ## Training attempts keep growing with no completed steps Attempts run up to `max_concurrent_trajectories` even when no group can be trained on. Groups with identical rewards carry no learning signal under GSPO and GRPO. When these groups are filtered out, training keeps collecting attempts to fill the batch. Compare `client.rl.runs.progress(run_id)` with `client.rl.runs.list_step_summaries(run_id)`. Inspect `completed_steps`, `trajectory_count`, `no_signal_groups`, `used_groups`, and `termination_reasons`. `used_groups` counts consumed groups with differing rewards, not every optimizer input. Check completed steps, trainer rewards, and checkpoints before concluding that the model updated. If every group has no signal, start with [flat rewards](#rewards-are-flat-at-zero). Stopping your client does not stop a run. Cancel a validation run that has exceeded its planned budget with `client.rl.runs.cancel(run_id)`, then fix the cause. See [Reduce trajectory spend](/guides/training#reduce-trajectory-spend) for the settings that bound attempts before you restart. Poll until the run is terminal; a cancellation request alone is not confirmation. On the next run, check optimizer progress before scaling up. ## `TimeoutError: Timed out waiting for ...; server processing continues` The client stopped waiting for a spec upload. Ingestion continues on the server, so running the upload again can create a second version. Reconnect with the operation ID in the message, then read its state before retrying: ```python theme={null} from trajectory import Client from trajectory.lib import get_operation client = Client() operation = get_operation(client, "YOUR_OPERATION_ID") status = operation.refresh() print(status.status, status.stage, status.bench_id) for failure in operation.pages("failure"): print(failure["resource_id"], failure["code"], failure["message"]) ``` If it is still running, wait with `status = operation.result().status`. If it succeeded, use its `bench_id`. If it failed, continue with [`BenchmarkOperationError`](#benchmarkoperationerror-or-a-failed-image-build). Confirm `status.status` is `succeeded`, then check `client.specs.retrieve_readiness(status.bench_id)`. If its `ready` field is `False`, look at `missing_secret_names` and `unready_task_image_counts` to see what's missing. The upload operation's `status.ready` only covers requested image builds. With `build_images=False`, it stays `False` even when a reused `RuntimeRef` is ready. To keep the ID for next time, upload with `start_push()` and save `operation.id` before waiting. ## Evaluation resume returns HTTP 409 while cleanup is pending `resume()` can return HTTP 409 while resources from the previous execution are still being cleaned up, even after the run's status changes to `completed`, `failed`, or `cancelled`. The error is `evaluation cleanup is pending; retry the same resume request later`. Older API deployments use `evaluation cleanup is pending; cancel active evaluations before deletion`, even when you called `resume()`. Wait for cleanup, then try `client.evals.runs.resume()` again with the same evaluation ID, `rerun_*` flags, and `idempotency_key`. Resuming the existing evaluation preserves its scored results and history. For the rerun flags and an example, see [evaluation recovery](/guides/evaluations#recover-ungraded-attempts). ## `BenchmarkOperationError` or a failed image build Registration or a runtime build failed. The exception's `failures` name each affected resource and its error. A failed runtime blocks evaluation of that spec version. Correct the problem, then upload a new version with the same spec name and project. Do not create a second, partial spec. The new upload returns a new `bench_id`. Diagnose one task before running it at scale. ## `Runtime context ... exceeds the 4,096-file limit` `DockerfileBuild` uploads every file under the Dockerfile's directory, up to 4,096 files and 3 GiB. Keep only that runtime's files in its directory, or exclude the rest with `.dockerignore` at the spec root passed to `push()` or `start_push()`, with patterns relative to that root. For a larger task set, archive the files, `COPY` the archive, and unpack it in a `RUN` step that creates the destination first (`mkdir -p && tar -xf -C `). After uploading, diagnose one task to check that its files are available. ## `Runtime Dockerfile ...: ADD supports only a single http:// or https:// URL source` The image builder runs `ADD` only for one `http://` or `https://` URL. The SDK checks each runtime Dockerfile before it uploads anything and names the line to change. Replace `ADD` of a file or directory with `COPY`. `ADD` of a local archive also unpacked it, so `COPY` the archive and unpack it in a `RUN` step that creates the destination first: ```dockerfile theme={null} COPY data.tar /tmp/data.tar RUN mkdir -p /app/data && tar -xf /tmp/data.tar -C /app/data && rm /tmp/data.tar ``` The same check logs a warning, without stopping the upload, for instructions the image builder does not implement (`EXPOSE`, `HEALTHCHECK`, `LABEL`, `ONBUILD`, `STOPSIGNAL`, `VOLUME`), for `USER`, which it ignores, and for `ENV` default values such as `${VAR:-default}`. ## A model request returns an empty reply After a platform turn, token, or context limit, model requests may return an empty reply with `metadata.trajectory_termination_reason: "trajectory_cancelled"`. Stop calling the model and retrieve the trajectory to read its recorded reason. If the harness must grade a reply that fills its per-step allowance, leave room between `max_output_tokens_per_turn` and `max_output_tokens_per_trajectory`. Check `client.trajectories.retrieve(tid).termination_reason` for the platform's reason. ## Deployment chat rejects `reasoning_effort="off"` with HTTP 400 For `invalid_inference_input`, see [how to disable thinking for deployment chat](/guides/deployments#disable-thinking-for-deployment-chat). ## A harness keeps retrying a rejected attempt A harness with its own retries can lose the service's decision when it replaces an SDK error with its own. Preserve the SDK error's status, headers, and body. In particular, pass through `Trajectory-Should-Retry: false` so the harness does not retry that attempt. Verify that the harness does not retry a response with that header. ## Journal writes fail or an auxiliary capture stays `in_progress` A timeout or `503` can leave the outcome of a create or event write unknown. A capture can show zero steps while a model request is still in flight. ### Reconcile with read-only requests Save the explicit create `idempotency_key` before submitting. Keep the returned `tid`, event IDs, inference request or operation IDs, and the original error. An SDK-generated create key is reused within one SDK call. A new call gets a new key. Pause application retries for uncertain writes and inference. For calls that cannot be replayed safely, disable SDK retries with `client.with_options(max_retries=0)`. Use a trusted process outside the managed task with a same-organization API key and the public `base_url` for the environment that ran the capture. A `401` leaves the journal state unknown. This example reads the capture and one page of events: ```python theme={null} import os from trajectory import Client tid = "" with Client( api_key=os.environ["TRAJECTORY_ORG_API_KEY"], base_url="", max_retries=0, timeout=5.0, ) as reader: capture = reader.trajectories.retrieve(tid, include_steps=False) page = reader.trajectories.list_events(tid, limit=100) ``` Set a deadline and a maximum number of reads. While `page.has_more` is true, use `page.next_cursor` within that budget. Compare stored event IDs and contents with the intended write. A matching event confirms only that write. If the trajectory ID is missing or reads are inconclusive, keep the outcome unresolved. Share IDs, timestamps, and redacted errors with support. ### Complete an abandoned auxiliary capture Verify all three conditions immediately before completing the capture: * Your application created and exclusively owns the capture. * The parent has ended, and no worker or queued retry can resume work on the capture. * A fresh read shows the capture is still `in_progress`. The operation status or your dispatch records confirm no inference is pending. If any condition is unknown, leave the capture alone. Skip shared and platform-managed captures. Keep ownership exclusive through completion. For an abandoned failure, call `client.with_options(max_retries=0).trajectories.complete(tid, termination_reason="ERROR")`. If the response is lost or the status is `finalizing`, use bounded reads to check for `completed`. ## `HARNESS_FAILED` before the first model call Read the task diagnostic's failure and logs. A trajectory can have no steps if imports, task setup, or a model-call argument failed before inference. Retrieve the trajectory's `error` and inspect its rollout diagnostic; do not assume an empty transcript is a model failure. Save diagnostic events and artifacts before the harness exits; see [diagnostic artifacts](/guides/diagnostic-artifacts). After fixing the cause, rerun that task with the same model and options, and check its ending and native grade. ## A managed task gets 401 from `list_events` Follow [Read managed task events](/guides/telemetry#read-managed-task-events) to list events from outside the task. ## Git reports `detected dubious ownership` Image-built repositories can be owned by a different user from the runtime harness. Set the expected ownership during image construction, or trust the specific repository with `git config --global --add safe.directory /workspace/repo` in the runtime user context. Use the actual repository path rather than trusting every directory. Confirm the harness and grader can run their Git commands as that user. ## Decision training rejects outcomes or captures RLCD/Brier training needs exactly one trainable decision step per trajectory and one zero-weight `decision.outcome.` component per choice in its original order. Check for missing/duplicate components, nonzero weights, values outside `[0, 1]`, or a distribution that does not sum to one. A scalar accuracy reward alone is insufficient. See [outcome logging](/guides/decision-training#the-labels-to-log). If validation reports missing decision position or choice token IDs, rerun an evaluation of your decision spec to record fresh trajectories with the required metadata. Existing trajectories cannot be repaired by guessing these values. If the new trajectories have the same error, contact support. Check that the trajectory contains one question and no mixed-in chat turns. If there are no eligible groups, inspect termination reasons and filters. Identical or zero scalar rewards don't rule out learning from the labels. If the backend or algorithm is rejected, check that the model supports decision training, the spec is a decision spec, and the algorithm is RLCD. Full resume requires a compatible checkpoint. Explicitly load weights only when changing from a checkpoint trained with an incompatible algorithm.