Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: Use via API button on the Train page (#15996)

Daniel Hanedc13e6540d8
diff --git a/studio/backend/tests/fixtures/training_api_job_bodies.json b/studio/backend/tests/fixtures/training_api_job_bodies.json
new file mode 100644
index 00000000000..81a8704c58e
--- /dev/null
+++ b/studio/backend/tests/fixtures/training_api_job_bodies.json
@@ -0,0 +1,227 @@
+{
+ "lora": {
+ "model": "unsloth/Qwen3-0.6B",
+ "hyperparameters": {
+ "n_epochs": 3,
+ "batch_size": 4
+ },
+ "seed": 3407,
+ "suffix": "my run",
+ "learning_rate": "0.0002",
+ "load_in_4bit": false,
+ "max_seq_length": 4096,
+ "gradient_accumulation_steps": 2,
+ "warmup_steps": 5,
+ "weight_decay": 0.001,
+ "optim": "adamw_8bit",
+ "lr_scheduler_type": "linear",
+ "packing": false,
+ "lora_r": 16,
+ "lora_alpha": 32,
+ "lora_dropout": 0,
+ "target_modules": [
+ "q_proj",
+ "v_proj"
+ ],
+ "use_dora": true,
+ "gradient_checkpointing": "unsloth",
+ "train_on_completions": true
+ },
+ "fullFinetuning": {
+ "model": "unsloth/Qwen3-0.6B",
+ "hyperparameters": {
+ "n_epochs": 3,
+ "batch_size": 4
+ },
+ "seed": 3407,
+ "learning_rate": "0.0002",
+ "max_steps": 60,
+ "training_type": "Full Finetuning",
+ "load_in_4bit": false,
+ "max_seq_length": 4096,
+ "gradient_accumulation_steps": 2,
+ "warmup_ratio": 0.03,
+ "weight_decay": 0.001,
+ "optim": "adamw_8bit",
+ "lr_scheduler_type": "linear",
+ "packing": false,
+ "gradient_checkpointing": "unsloth",
+ "train_on_completions": true,
+ "format_type": "alpaca"
+ },
+ "qloraMapping": {
+ "model": "unsloth/Qwen3-0.6B",
+ "hyperparameters": {
+ "n_epochs": 3,
+ "batch_size": 4
+ },
+ "seed": 3407,
+ "suffix": "my run",
+ "learning_rate": "1e-5",
+ "load_in_4bit": true,
+ "max_seq_length": 4096,
+ "gradient_accumulation_steps": 2,
+ "warmup_steps": 5,
+ "weight_decay": 0.001,
+ "optim": "adamw_8bit",
+ "lr_scheduler_type": "linear",
+ "packing": false,
+ "lora_r": 16,
+ "lora_alpha": 32,
+ "lora_dropout": 0,
+ "target_modules": [
+ "q_proj",
+ "v_proj"
+ ],
+ "use_rslora": true,
+ "gradient_checkpointing": "unsloth",
+ "train_on_completions": false,
+ "custom_format_mapping": {
+ "question": "user",
+ "answer": "assistant",
+ "__system_prompt": "Answer in one word.",
+ "__label_mapping": {
+ "answer": {
+ "0": "no",
+ "1": "yes"
+ }
+ }
+ }
+ },
+ "continuedPretraining": {
+ "model": "unsloth/Qwen3-0.6B",
+ "hyperparameters": {
+ "n_epochs": 3,
+ "batch_size": 4
+ },
+ "seed": 3407,
+ "suffix": "my run",
+ "learning_rate": "0.0002",
+ "training_type": "Continued Pretraining",
+ "load_in_4bit": false,
+ "max_seq_length": 4096,
+ "gradient_accumulation_steps": 2,
+ "warmup_steps": 5,
+ "weight_decay": 0.001,
+ "optim": "adamw_8bit",
+ "lr_scheduler_type": "linear",
+ "packing": false,
+ "lora_r": 16,
+ "lora_alpha": 32,
+ "lora_dropout": 0,
+ "target_modules": [
+ "q_proj",
+ "v_proj"
+ ],
+ "use_loftq": true,
+ "gradient_checkpointing": "unsloth",
+ "train_on_completions": true
+ },
+ "decision": {
+ "model": "unsloth/Qwen3-0.6B",
+ "hyperparameters": {
+ "n_epochs": 3,
+ "batch_size": 4
+ },
+ "seed": 3407,
+ "suffix": "my run",
+ "learning_rate": "0.0002",
+ "load_in_4bit": false,
+ "max_seq_length": 4096,
+ "gradient_accumulation_steps": 2,
+ "warmup_steps": 5,
+ "weight_decay": 0.001,
+ "optim": "adamw_8bit",
+ "lr_scheduler_type": "linear",
+ "packing": false,
+ "lora_r": 16,
+ "lora_alpha": 32,
+ "lora_dropout": 0,
+ "target_modules": [
+ "q_proj",
+ "v_proj"
+ ],
+ "gradient_checkpointing": "unsloth",
+ "model_subfolder": "multilingual",
+ "is_decision": true,
+ "train_on_completions": true
+ },
+ "vision": {
+ "model": "unsloth/Qwen3-0.6B",
+ "hyperparameters": {
+ "n_epochs": 3,
+ "batch_size": 4
+ },
+ "seed": 3407,
+ "suffix": "my run",
+ "learning_rate": "0.0002",
+ "load_in_4bit": false,
+ "max_seq_length": 4096,
+ "gradient_accumulation_steps": 2,
+ "warmup_steps": 5,
+ "weight_decay": 0.001,
+ "optim": "adamw_8bit",
+ "lr_scheduler_type": "linear",
+ "packing": false,
+ "lora_r": 16,
+ "lora_alpha": 32,
+ "lora_dropout": 0,
+ "target_modules": [
+ "q_proj",
+ "v_proj"
+ ],
+ "gradient_checkpointing": "unsloth",
+ "is_dataset_image": true,
+ "finetune_vision_layers": true,
+ "train_on_completions": true
+ },
+ "everySetting": {
+ "model": "unsloth/Qwen3-0.6B",
+ "hyperparameters": {
+ "n_epochs": 3,
+ "batch_size": 4
+ },
+ "seed": 3407,
+ "suffix": "my run",
+ "learning_rate": "0.0002",
+ "training_type": "Continued Pretraining",
+ "load_in_4bit": false,
+ "max_seq_length": 4096,
+ "gradient_accumulation_steps": 2,
+ "warmup_steps": 5,
+ "weight_decay": 0.001,
+ "optim": "adamw_8bit",
+ "lr_scheduler_type": "linear",
+ "packing": false,
+ "lora_r": 16,
+ "lora_alpha": 32,
+ "lora_dropout": 0,
+ "target_modules": [
+ "q_proj",
+ "v_proj"
+ ],
+ "vision_image_size": 448,
+ "trust_remote_code": true,
+ "dataset_slice_start": 10,
+ "dataset_slice_end": 500,
+ "embedding_learning_rate": 0.000005,
+ "save_steps": 25,
+ "gradient_checkpointing": "true",
+ "max_grad_norm": 0.5,
+ "max_grad_value": 2,
+ "train_on_completions": true
+ },
+ "example": {
+ "model": "unsloth/Qwen3-0.6B",
+ "hyperparameters": {
+ "n_epochs": 1,
+ "batch_size": 2
+ },
+ "seed": 3407,
+ "learning_rate": "2e-4",
+ "load_in_4bit": true,
+ "max_seq_length": 2048,
+ "lora_r": 16,
+ "lora_alpha": 16
+ }
+}
diff --git a/studio/backend/tests/test_training_api_snippet_contract.py b/studio/backend/tests/test_training_api_snippet_contract.py
new file mode 100644
index 00000000000..6065159d43b
--- /dev/null
+++ b/studio/backend/tests/test_training_api_snippet_contract.py
@@ -0,0 +1,68 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The Train page's API examples create jobs the fine-tuning route accepts, with the form's settings.
+
+The bodies are the ones the frontend generator sends (``tests/training-api-snippets.test.ts`` keeps the
+fixture in step with it)."""
+
+import json
+from pathlib import Path
+
+import pytest
+from fastapi import HTTPException
+
+from models.training import TrainingStartRequest
+from routes import openai_fine_tuning
+
+BODIES = json.loads(
+ (Path(__file__).parent / "fixtures" / "training_api_job_bodies.json").read_text()
+)
+FILE_ID = "file-0123456789abcdef0123456789abcdef"
+UPLOADED = Path(f"/uploads/{FILE_ID}.jsonl")
+OPENAI_FIELDS = {"model", "hyperparameters", "seed", "suffix"}
+
+
[email protected](autouse = True)
+def uploaded_file(monkeypatch):
+ monkeypatch.setattr(openai_fine_tuning, "_find_file", lambda file_id: UPLOADED)
+
+
+def _request(body: dict) -> TrainingStartRequest:
+ create = openai_fine_tuning.FineTuningJobCreate.model_validate(
+ {**body, "training_file": FILE_ID}
+ )
+ return TrainingStartRequest.model_validate(openai_fine_tuning._training_config(create))
+
+
[email protected]("name", sorted(BODIES))
+def test_generated_body_is_accepted_with_its_settings(name):
+ body = BODIES[name]
+ request = _request(body)
+ assert request.model_name == body["model"]
+ assert request.local_datasets == [str(UPLOADED)]
+ assert request.num_epochs == body["hyperparameters"]["n_epochs"]
+ assert request.batch_size == body["hyperparameters"]["batch_size"]
+ assert request.random_seed == body["seed"]
+ assert request.project_name == body.get("suffix")
+ # The route normalises the string ("2e-4" -> "0.0002"); the rate itself must not change.
+ assert float(request.learning_rate) == float(body["learning_rate"])
+ extras = {
+ key: value
+ for key, value in body.items()
+ if key not in OPENAI_FIELDS and key != "learning_rate"
+ }
+ assert extras
+ for key, value in extras.items():
+ assert getattr(request, key) == value, key
+ assert request.training_type == body.get("training_type", "LoRA/QLoRA")
+ assert request.format_type == body.get("format_type", "auto")
+ assert request.hf_token is None and request.hf_dataset is None
+
+
[email protected]("key", ["model_name", "local_datasets", "project_name", "not_a_setting"])
+def test_a_key_outside_the_contract_is_refused(key):
+ with pytest.raises(HTTPException) as caught:
+ _request({**BODIES["lora"], key: "x"})
+ assert caught.value.status_code == 400
+ assert caught.value.detail == f"Unknown parameter(s): {key}"
diff --git a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
index ebd89d033ed..4e3e6d0f3f3 100644
--- a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
+++ b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
@@ -44,6 +44,7 @@ import {
import { AudioApiExamples } from "@/features/settings/components/audio-api-examples";
import { DecisionApiSection } from "@/features/settings/components/decision-api-section";
import { MediaApiExamples } from "@/features/settings/components/media-api-examples";
+import { TrainingApiExamples } from "@/features/settings/components/training-api-examples";
import { useApiTunnelPref } from "@/features/settings/components/usage-examples";
import { remoteApiOrigin } from "@/features/settings/api/remote-access-state";
import { getApiBase, isTauri } from "@/lib/api-base";
@@ -967,6 +968,12 @@ function QuickStart({
useTunnel={useTunnel}
showHeading={false}
/>
+ ) : kind === "training" ? (
+ <TrainingApiExamples
+ apiKey={freshKey}
+ useTunnel={useTunnel}
+ showHeading={false}
+ />
) : (
<DecisionApiSection showHeading={false} />
)}
diff --git a/studio/frontend/src/features/settings/components/api-example-tabs.tsx b/studio/frontend/src/features/settings/components/api-example-tabs.tsx
index f7ddf3fa1db..c44582e8d41 100644
--- a/studio/frontend/src/features/settings/components/api-example-tabs.tsx
+++ b/studio/frontend/src/features/settings/components/api-example-tabs.tsx
@@ -5,7 +5,11 @@ import { useIsAccountOwner } from "@/features/auth";
import { type TranslationKey, useT } from "@/i18n";
// Not through the barrel: it pulls in chat, which every barrel importer would then load.
import { RAISED_SURFACE } from "@/features/library/surface";
-import { AiSpeechIcon, MessageCircleIcon } from "@/lib/hugeicons-derived";
+import {
+ AiSpeechIcon,
+ MessageCircleIcon,
+ TestTubeOutlineIcon,
+} from "@/lib/hugeicons-derived";
import { cn } from "@/lib/utils";
import {
BotIcon,
@@ -32,9 +36,16 @@ import {
import { AudioApiExamples } from "./audio-api-examples";
import { DecisionApiSection } from "./decision-api-section";
import { MediaApiExamples } from "./media-api-examples";
+import { TrainingApiExamples } from "./training-api-examples";
import { UsageExamples } from "./usage-examples";
-export type ApiExampleKind = "chat" | "media" | "audio" | "decision" | "agents";
+export type ApiExampleKind =
+ | "chat"
+ | "media"
+ | "audio"
+ | "training"
+ | "decision"
+ | "agents";
export function useApiExampleKinds(): {
id: ApiExampleKind;
@@ -58,6 +69,12 @@ export function useApiExampleKinds(): {
icon: AiSpeechIcon,
searchLabel: "settings.apiKeys.audioApi.title",
},
+ {
+ id: "training",
+ label: "Training",
+ icon: TestTubeOutlineIcon,
+ searchLabel: "settings.apiKeys.trainingApi.title",
+ },
...(isOwner
? [
{
@@ -119,6 +136,7 @@ export function ApiExampleTabNav({
const TAB_FOR_TARGET: Partial<Record<SettingsScrollTarget, ApiExampleKind>> = {
"api-keys-media-api": "media",
"api-keys-audio-api": "audio",
+ "api-keys-training-api": "training",
"api-keys-decision-api": "decision",
};
@@ -206,6 +224,13 @@ export function ApiExamplesPanel({
showHeading={false}
{...keyless}
/>
+ ) : kind === "training" ? (
+ <TrainingApiExamples
+ apiKey={apiKey}
+ useTunnel={useTunnel}
+ showHeading={false}
+ {...keyless}
+ />
) : (
<DecisionApiSection showHeading={false} />
)}
diff --git a/studio/frontend/src/features/settings/components/training-api-examples.tsx b/studio/frontend/src/features/settings/components/training-api-examples.tsx
new file mode 100644
index 00000000000..c16c43607fe
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/training-api-examples.tsx
@@ -0,0 +1,174 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { usePlatformStore } from "@/config/env";
+import { useT } from "@/i18n";
+import { isTauri } from "@/lib/api-base";
+import { TestTubeOutlineIcon } from "@/lib/hugeicons-derived";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useEffect, useMemo, useState } from "react";
+import type {
+ KeylessApiAccessExposure,
+ KeylessApiAccessScope,
+} from "../api/keyless-api-access";
+import {
+ type TrainingApiRequest,
+ useSettingsDialogStore,
+} from "../stores/settings-dialog-store";
+import { useSettingsPanelPrefsStore } from "../stores/settings-panel-prefs-store";
+import {
+ ExampleCodeBox,
+ ExampleToggle,
+ useExampleOs,
+} from "./api-example-parts";
+import {
+ type AudioApiLang,
+ audioApiKey,
+ audioLangToStore,
+ langFromStored,
+} from "./audio-api-snippets";
+import {
+ EXAMPLE_TRAINING_API_REQUEST,
+ buildTrainingApiSnippet,
+ buildTrainingCancelSnippet,
+} from "./training-api-snippets";
+
+const LANGS: { id: AudioApiLang; label: string }[] = [
+ { id: "curl", label: "curl" },
+ { id: "python", label: "Python" },
+ { id: "javascript", label: "JavaScript" },
+];
+
+export function TrainingApiExamples({
+ apiKey,
+ useTunnel,
+ keylessScope = "off",
+ keylessExposure = null,
+ showHeading = true,
+}: {
+ apiKey?: string | null;
+ showHeading?: boolean;
+ useTunnel: boolean;
+ keylessScope?: KeylessApiAccessScope;
+ keylessExposure?: KeylessApiAccessExposure | null;
+}) {
+ const t = useT();
+ const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);
+ const serverUrl = usePlatformStore((s) => s.serverUrl);
+ const setStoredLang = useSettingsPanelPrefsStore((s) => s.setApiExampleLang);
+ const [storedPrefs] = useState(() => useSettingsPanelPrefsStore.getState());
+ const [lang, setLang] = useState<AudioApiLang>(
+ langFromStored(storedPrefs.apiExampleLang),
+ );
+ const [request, setRequest] = useState<TrainingApiRequest | null>(null);
+ const trainingApiRequested = useSettingsDialogStore(
+ (s) => s.trainingApiRequested,
+ );
+
+ useEffect(() => {
+ if (!trainingApiRequested) return;
+ setRequest(trainingApiRequested);
+ useSettingsDialogStore.getState().consumeTrainingApiRequest();
+ }, [trainingApiRequested]);
+
+ const origin = typeof window !== "undefined" ? window.location.origin : "";
+ const base =
+ useTunnel && cloudflareUrl
+ ? cloudflareUrl
+ : isTauri
+ ? (serverUrl ?? origin)
+ : origin;
+ const [os, setOs] = useExampleOs(base);
+ const key = audioApiKey(apiKey, {
+ base,
+ tunnel: useTunnel && !!cloudflareUrl,
+ scope: keylessScope,
+ exposure: keylessExposure,
+ });
+ const shown = request ?? EXAMPLE_TRAINING_API_REQUEST;
+ const snippet = useMemo(
+ () => buildTrainingApiSnippet(shown, { base, apiKey: key, lang, os }),
+ [base, key, lang, os, shown],
+ );
+ const cancelSnippet = useMemo(
+ () => buildTrainingCancelSnippet({ base, apiKey: key, lang, os }),
+ [base, key, lang, os],
+ );
+ const shikiLang =
+ lang === "curl" ? (os === "windows" ? "powershell" : "bash") : lang;
+
+ const pickLang = (next: AudioApiLang) => {
+ setLang(next);
+ const stored = audioLangToStore(
+ useSettingsPanelPrefsStore.getState().apiExampleLang,
+ next,
+ );
+ if (stored) setStoredLang(stored);
+ };
+
+ const notes = [
+ request == null || request.model == null
+ ? t("settings.apiKeys.trainingApi.placeholder")
+ : null,
+ request?.datasetFromHub ? t("settings.apiKeys.trainingApi.hubDataset") : null,
+ t("settings.apiKeys.trainingApi.batching"),
+ t("settings.apiKeys.trainingApi.chatNote"),
+ ].filter((note): note is string => note != null);
+
+ return (
+ <section
+ data-settings-label={t("settings.apiKeys.trainingApi.title")}
+ className="flex min-w-0 max-w-full scroll-mt-6 flex-col gap-4"
+ >
+ <div className="flex flex-col gap-1">
+ {showHeading && (
+ <h2 className="settings-heading flex items-center gap-2 text-base font-semibold font-heading">
+ <HugeiconsIcon icon={TestTubeOutlineIcon} strokeWidth={1.75} className="size-[calc(18px*var(--ui-space-scale,1))] shrink-0 text-muted-foreground" />
+ {t("settings.apiKeys.trainingApi.title")}
+ </h2>
+ )}
+ <p className="text-xs leading-relaxed text-muted-foreground">
+ {t("settings.apiKeys.trainingApi.description")}
+ </p>
+ </div>
+ <div className="flex min-w-0 flex-col gap-1 text-ui-11 leading-relaxed text-muted-foreground">
+ {notes.map((note) => (
+ <p key={note}>{note}</p>
+ ))}
+ </div>
+ <ExampleCodeBox
+ code={snippet}
+ language={shikiLang}
+ label={t("settings.apiKeys.trainingApi.title")}
+ redactFromReload={Boolean(apiKey)}
+ pills={
+ <ExampleToggle
+ label={t("settings.apiKeys.exampleLanguage")}
+ value={lang}
+ options={LANGS}
+ onChange={pickLang}
+ />
+ }
+ os={os}
+ onOsChange={setOs}
+ />
+ <div className="flex flex-col gap-1">
+ <h3 className="text-sm font-medium text-foreground">
+ {t("settings.apiKeys.trainingApi.cancelTitle")}
+ </h3>
+ <p className="text-xs leading-relaxed text-muted-foreground">
+ {t("settings.apiKeys.trainingApi.cancelDescription")}
+ </p>
+ </div>
+ <ExampleCodeBox
+ code={cancelSnippet}
+ language={shikiLang}
+ label={t("settings.apiKeys.trainingApi.cancelTitle")}
+ redactFromReload={Boolean(apiKey)}
+ pills={null}
+ os={os}
+ onOsChange={setOs}
+ />
+ </section>
+ );
+}
diff --git a/studio/frontend/src/features/settings/components/training-api-snippets.ts b/studio/frontend/src/features/settings/components/training-api-snippets.ts
new file mode 100644
index 00000000000..614a4a343d5
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/training-api-snippets.ts
@@ -0,0 +1,500 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { TrainingStartRequest } from "@/features/training/types/api";
+import type { TrainingApiRequest } from "../stores/settings-dialog-store";
+import { psSingle, shSingle } from "./agent-command.ts";
+import type { AudioApiLang, AudioApiOs } from "./audio-api-snippets";
+
+export const TRAINING_API_PLACEHOLDER_MODEL = "unsloth/Qwen3-0.6B";
+export const TRAINING_API_DEFAULT_DATASET = "train.jsonl";
+
+export interface TrainingApiSnippetInput {
+ base: string;
+ apiKey: string;
+ lang: AudioApiLang;
+ os: AudioApiOs;
+}
+
+const LORA = "LoRA/QLoRA";
+
+/**
+ * Where each field Start sends goes in the example. Exhaustive over the request type, so a new
+ * field fails typecheck until it is placed: "openai" fields map to the OpenAI job fields, "extra"
+ * ones are sent as Studio settings, "derived" ones follow from another field, and "host" ones
+ * (secrets, this machine's paths and caches, offload, eval, logging, Hub / S3 data, resume) stay out.
+ */
+export const TRAINING_FIELD_ROUTE: Record<keyof TrainingStartRequest, "openai" | "extra" | "derived" | "host"> = {
+ model_name: "openai",
+ project_name: "openai",
+ num_epochs: "openai",
+ batch_size: "openai",
+ random_seed: "openai",
+ local_datasets: "openai",
+ learning_rate: "extra",
+ max_steps: "extra",
+ training_type: "extra",
+ load_in_4bit: "extra",
+ max_seq_length: "extra",
+ vision_image_size: "extra",
+ trust_remote_code: "extra",
+ dataset_slice_start: "extra",
+ dataset_slice_end: "extra",
+ format_type: "extra",
+ custom_format_mapping: "extra",
+ embedding_learning_rate: "extra",
+ gradient_accumulation_steps: "extra",
+ warmup_steps: "extra",
+ warmup_ratio: "extra",
+ save_steps: "extra",
+ weight_decay: "extra",
+ max_grad_norm: "extra",
+ max_grad_value: "extra",
+ packing: "extra",
+ optim: "extra",
+ lr_scheduler_type: "extra",
+ lora_r: "extra",
+ lora_alpha: "extra",
+ lora_dropout: "extra",
+ target_modules: "extra",
+ gradient_checkpointing: "extra",
+ use_rslora: "extra",
+ use_loftq: "extra",
+ use_dora: "extra",
+ train_on_completions: "extra",
+ finetune_vision_layers: "extra",
+ finetune_language_layers: "extra",
+ finetune_attention_modules: "extra",
+ finetune_mlp_modules: "extra",
+ is_dataset_image: "extra",
+ is_dataset_audio: "extra",
+ is_embedding: "extra",
+ is_decision: "extra",
+ model_subfolder: "extra",
+ use_lora: "derived",
+ actual_model_repo_id: "host",
+ hf_token: "host",
+ model_known_cached: "host",
+ model_local_path: "host",
+ model_format: "host",
+ model_snapshot_path: "host",
+ approved_remote_code_fingerprint: "host",
+ hf_dataset: "host",
+ dataset_known_cached: "host",
+ dataset_local_path: "host",
+ dataset_snapshot_path: "host",
+ subset: "host",
+ train_split: "host",
+ eval_split: "host",
+ dataset_streaming: "host",
+ local_eval_datasets: "host",
+ s3_config: "host",
+ eval_steps: "host",
+ early_stopping_patience: "host",
+ offload_layers: "host",
+ offload_vram_gb: "host",
+ offload_vram_gb_per_device: "host",
+ prefetch_depth: "host",
+ enable_wandb: "host",
+ wandb_token: "host",
+ wandb_project: "host",
+ enable_tensorboard: "host",
+ tensorboard_dir: "host",
+ resume_from_checkpoint: "host",
+ drafter: "host",
+};
+
+/** Extras sent only where they differ from the route's defaults (null = sent whenever set). */
+const EXTRA_DEFAULTS = {
+ "vision_image_size": null,
+ "trust_remote_code": false,
+ "dataset_slice_start": null,
+ "dataset_slice_end": null,
+ "embedding_learning_rate": null,
+ "save_steps": 100,
+ "gradient_checkpointing": "",
+ "max_grad_norm": null,
+ "max_grad_value": null,
+ "model_subfolder": null,
+ "is_dataset_image": false,
+ "is_dataset_audio": false,
+ "is_embedding": false,
+ "is_decision": false,
+ "finetune_vision_layers": false,
+ "finetune_language_layers": true,
+ "finetune_attention_modules": true,
+ "finetune_mlp_modules": true,
+} as const;
+
+/**
+ * The "extra" fields of `TRAINING_FIELD_ROUTE`, as the Studio settings a fine-tuning job takes beyond
+ * the OpenAI fields.
+ */
+function trainingExtras(payload: TrainingStartRequest): Record<string, unknown> {
+ const extras: Record<string, unknown> = {
+ "learning_rate": payload.learning_rate,
+ };
+ if (payload.max_steps != null && payload.max_steps > 0) {
+ extras.max_steps = payload.max_steps;
+ }
+ const lora = payload.training_type === LORA;
+ if (!lora) extras.training_type = payload.training_type;
+ extras.load_in_4bit = payload.load_in_4bit;
+ extras.max_seq_length = payload.max_seq_length;
+ extras.gradient_accumulation_steps = payload.gradient_accumulation_steps;
+ if (payload.warmup_steps != null) {
+ extras.warmup_steps = payload.warmup_steps;
+ } else if (payload.warmup_ratio != null) {
+ extras.warmup_ratio = payload.warmup_ratio;
+ }
+ extras.weight_decay = payload.weight_decay;
+ extras.optim = payload.optim;
+ extras.lr_scheduler_type = payload.lr_scheduler_type;
+ extras.packing = payload.packing;
+ if (payload.use_lora) {
+ extras.lora_r = payload.lora_r;
+ extras.lora_alpha = payload.lora_alpha;
+ extras.lora_dropout = payload.lora_dropout;
+ if (payload.target_modules.length > 0) {
+ extras.target_modules = [...payload.target_modules];
+ }
+ for (const flag of ["use_rslora", "use_dora", "use_loftq"] as const) {
+ if (payload[flag]) extras[flag] = true;
+ }
+ }
+ for (const [key, fallback] of Object.entries(EXTRA_DEFAULTS)) {
+ const value = payload[key as keyof typeof EXTRA_DEFAULTS];
+ if (value != null && value !== "" && value !== fallback) extras[key] = value;
+ }
+ extras.train_on_completions = payload.train_on_completions;
+ if (payload.format_type && payload.format_type !== "auto") {
+ extras.format_type = payload.format_type;
+ }
+ if (
+ payload.custom_format_mapping &&
+ Object.keys(payload.custom_format_mapping).length > 0
+ ) {
+ extras.custom_format_mapping = payload.custom_format_mapping;
+ }
+ return extras;
+}
+
+/** `payload` is what Start would send; `datasetName` the uploaded file's display name. */
+export function trainingApiRequestFromPayload(
+ payload: TrainingStartRequest,
+ datasetName: string | null,
+): TrainingApiRequest {
+ return {
+ model: payload.model_name || null,
+ datasetName: payload.local_datasets.length > 0 ? datasetName : null,
+ datasetFromHub:
+ payload.local_datasets.length === 0 && (Boolean(payload.hf_dataset) || payload.s3_config != null),
+ nEpochs: payload.num_epochs,
+ batchSize: payload.batch_size,
+ seed: payload.random_seed,
+ suffix: payload.project_name?.trim() || null,
+ extras: trainingExtras(payload),
+ };
+}
+
+export const EXAMPLE_TRAINING_API_REQUEST: TrainingApiRequest = {
+ model: null,
+ datasetName: null,
+ datasetFromHub: false,
+ nEpochs: 1,
+ batchSize: 2,
+ seed: 3407,
+ suffix: null,
+ extras: {
+ "learning_rate": "2e-4",
+ "load_in_4bit": true,
+ "max_seq_length": 2048,
+ "lora_r": 16,
+ "lora_alpha": 16,
+ },
+};
+
+const j = (value: unknown) => JSON.stringify(value);
+
+function py(value: unknown): string {
+ if (value === null || value === undefined) return "None";
+ if (typeof value === "boolean") return value ? "True" : "False";
+ if (Array.isArray(value)) return `[${value.map(py).join(", ")}]`;
+ if (typeof value === "object") {
+ const entries = Object.entries(value as Record<string, unknown>);
+ return `{${entries.map(([key, item]) => `${j(key)}: ${py(item)}`).join(", ")}}`;
+ }
+ return j(value);
+}
+
+const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
+const jsKey = (key: string) => (IDENTIFIER.test(key) ? key : j(key));
+
+/** The create-job fields in wire order, the training file excluded. */
+function jobFields(request: TrainingApiRequest) {
+ return {
+ model: request.model ?? TRAINING_API_PLACEHOLDER_MODEL,
+ hyperparameters: { "n_epochs": request.nEpochs, "batch_size": request.batchSize },
+ seed: request.seed,
+ suffix: request.suffix,
+ };
+}
+
+function datasetFile(request: TrainingApiRequest): string {
+ return request.datasetName || TRAINING_API_DEFAULT_DATASET;
+}
+
+function pythonSnippet(request: TrainingApiRequest, base: string, apiKey: string) {
+ const { model, hyperparameters, seed, suffix } = jobFields(request);
+ const args = [
+ ` model=${j(model)},`,
+ " training_file=training_file.id,",
+ ` hyperparameters=${py(hyperparameters)},`,
+ ` seed=${seed},`,
+ ];
+ if (suffix) args.push(` suffix=${j(suffix)},`);
+ const extras = Object.entries(request.extras);
+ if (extras.length > 0) {
+ args.push(
+ " extra_body={",
+ ...extras.map(([key, value]) => ` ${j(key)}: ${py(value)},`),
+ " },",
+ );
+ }
+ return `import time
+
+from openai import OpenAI
+
+client = OpenAI(base_url=${j(`${base}/v1`)}, api_key=${j(apiKey)})
+
+with open(${j(datasetFile(request))}, "rb") as dataset:
+ training_file = client.files.create(file=dataset, purpose="fine-tune")
+
+job = client.fine_tuning.jobs.create(
+${args.join("\n")}
+)
+print(job.id, job.status)
+
+seen = set()
+while True:
+ job = client.fine_tuning.jobs.retrieve(job.id)
+ events = client.fine_tuning.jobs.list_events(job.id, limit=100).data
+ for event in reversed(events):
+ if event.id not in seen:
+ seen.add(event.id)
+ print(event.message)
+ if job.status in ("succeeded", "failed", "cancelled"):
+ break
+ time.sleep(10)
+if job.status != "succeeded":
+ raise RuntimeError(job.error)
+
+reply = client.chat.completions.create(
+ model=job.fine_tuned_model,
+ messages=[{"role": "user", "content": "Hello!"}],
+)
+print(reply.choices[0].message.content)`;
+}
+
+function javascriptSnippet(
+ request: TrainingApiRequest,
+ base: string,
+ apiKey: string,
+) {
+ const { model, hyperparameters, seed, suffix } = jobFields(request);
+ const fields = [
+ ` model: ${j(model)},`,
+ " training_file: trainingFile.id,",
+ ` hyperparameters: { n_epochs: ${hyperparameters.n_epochs}, batch_size: ${hyperparameters.batch_size} },`,
+ ` seed: ${seed},`,
+ ];
+ if (suffix) fields.push(` suffix: ${j(suffix)},`);
+ for (const [key, value] of Object.entries(request.extras)) {
+ fields.push(` ${jsKey(key)}: ${j(value)},`);
+ }
+ return `import fs from "node:fs";
+import OpenAI from "openai";
+
+const client = new OpenAI({ baseURL: ${j(`${base}/v1`)}, apiKey: ${j(apiKey)} });
+
+const trainingFile = await client.files.create({
+ file: fs.createReadStream(${j(datasetFile(request))}),
+ purpose: "fine-tune",
+});
+
+let job = await client.fineTuning.jobs.create({
+${fields.join("\n")}
+});
+console.log(job.id, job.status);
+
+const seen = new Set();
+while (true) {
+ job = await client.fineTuning.jobs.retrieve(job.id);
+ const events = await client.fineTuning.jobs.listEvents(job.id, { limit: 100 });
+ for (const event of [...events.data].reverse()) {
+ if (seen.has(event.id)) continue;
+ seen.add(event.id);
+ console.log(event.message);
+ }
+ if (["succeeded", "failed", "cancelled"].includes(job.status)) break;
+ await new Promise((resolve) => setTimeout(resolve, 10000));
+}
+if (job.status !== "succeeded") throw new Error(JSON.stringify(job.error));
+
+const reply = await client.chat.completions.create({
+ model: job.fine_tuned_model,
+ messages: [{ role: "user", content: "Hello!" }],
+});
+console.log(reply.choices[0].message.content);`;
+}
+
+/** The create-job body without `training_file`, as every language sends it: extras flat, no `extra_body` key. */
+export function trainingApiJobBody(
+ request: TrainingApiRequest,
+): Record<string, unknown> {
+ const { model, hyperparameters, seed, suffix } = jobFields(request);
+ const body: Record<string, unknown> = { model, hyperparameters, seed };
+ if (suffix) body.suffix = suffix;
+ return { ...body, ...request.extras };
+}
+
+function bodyLines(request: TrainingApiRequest): string[] {
+ return Object.entries(trainingApiJobBody(request)).map(
+ ([key, value]) => ` ${j(key)}: ${j(value)}`,
+ );
+}
+
+function bashSnippet(request: TrainingApiRequest, base: string, apiKey: string) {
+ const lines = bodyLines(request).map(shSingle);
+ return `BASE='${shSingle(base)}'
+KEY='${shSingle(apiKey)}'
+FILE_ID=$(curl -sSf "$BASE/v1/files" \\
+ -H "Authorization: Bearer $KEY" \\
+ -F purpose=fine-tune \\
+ -F 'file=@${shSingle(datasetFile(request))}' | jq -r .id)
+JOB=$(curl -sSf "$BASE/v1/fine_tuning/jobs" \\
+ -H "Authorization: Bearer $KEY" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "training_file": "'"$FILE_ID"'",
+${lines.join(",\n")}
+}')
+JOB_ID=$(jq -r .id <<<"$JOB")
+STATUS=$(jq -r .status <<<"$JOB")
+echo "$JOB_ID $STATUS"
+SEEN=" "
+while :; do
+ JOB=$(curl -sSf "$BASE/v1/fine_tuning/jobs/$JOB_ID" -H "Authorization: Bearer $KEY")
+ STATUS=$(jq -r .status <<<"$JOB")
+ while read -r EVENT_ID MESSAGE; do
+ case "$SEEN" in
+ *" $EVENT_ID "*) ;;
+ *) SEEN="$SEEN$EVENT_ID "; echo "$MESSAGE" ;;
+ esac
+ done < <(curl -sSf "$BASE/v1/fine_tuning/jobs/$JOB_ID/events?limit=100" \\
+ -H "Authorization: Bearer $KEY" \\
+ | jq -r '.data | reverse[] | "\\(.id) \\(.message | gsub("\\n"; " "))"')
+ case "$STATUS" in succeeded|failed|cancelled|"") break ;; esac
+ sleep 10
+done
+if [ "$STATUS" = succeeded ]; then
+ MODEL=$(jq -r .fine_tuned_model <<<"$JOB")
+ curl -sSf "$BASE/v1/chat/completions" \\
+ -H "Authorization: Bearer $KEY" \\
+ -H "Content-Type: application/json" \\
+ -d "$(jq -n --arg model "$MODEL" '{model: $model, messages: [{role: "user", content: "Hello!"}]}')" \\
+ | jq -r '.choices[0].message.content'
+else
+ jq .error <<<"$JOB"
+fi`;
+}
+
+function powershellSnippet(
+ request: TrainingApiRequest,
+ base: string,
+ apiKey: string,
+) {
+ return `$base = '${psSingle(base)}'
+$key = '${psSingle(apiKey)}'
+$file = curl.exe -sSf "$base/v1/files" \`
+ -H "Authorization: Bearer $key" \`
+ -F purpose=fine-tune \`
+ -F 'file=@${psSingle(datasetFile(request))}' | ConvertFrom-Json
+$settings = @'
+${bodyLines(request).join(",\n")}
+'@
+$body = "{\`n \`"training_file\`": \`"$($file.id)\`",\`n$settings\`n}"
+[IO.File]::WriteAllText("$PWD\\body.json", $body)
+$job = curl.exe -sSf "$base/v1/fine_tuning/jobs" \`
+ -H "Authorization: Bearer $key" \`
+ -H "Content-Type: application/json" \`
+ -d "@body.json" | ConvertFrom-Json
+"$($job.id) $($job.status)"
+$seen = @{}
+while ($true) {
+ $job = curl.exe -sSf "$base/v1/fine_tuning/jobs/$($job.id)" -H "Authorization: Bearer $key" | ConvertFrom-Json
+ if (-not $job) { break }
+ $events = @((curl.exe -sSf "$base/v1/fine_tuning/jobs/$($job.id)/events?limit=100" -H "Authorization: Bearer $key" | ConvertFrom-Json).data)
+ [array]::Reverse($events)
+ foreach ($item in $events) {
+ if (-not $seen.ContainsKey($item.id)) {
+ $seen[$item.id] = $true
+ $item.message
+ }
+ }
+ if ($job.status -in "succeeded", "failed", "cancelled") { break }
+ Start-Sleep -Seconds 10
+}
+if ($job.status -eq "succeeded") {
+ $chat = @{ model = $job.fine_tuned_model; messages = @(@{ role = "user"; content = "Hello!" }) } | ConvertTo-Json -Depth 5
+ [IO.File]::WriteAllText("$PWD\\chat.json", $chat)
+ $reply = curl.exe -sSf "$base/v1/chat/completions" \`
+ -H "Authorization: Bearer $key" \`
+ -H "Content-Type: application/json" \`
+ -d "@chat.json" | ConvertFrom-Json
+ $reply.choices[0].message.content
+} else {
+ $job.error
+}`;
+}
+
+/** Upload, create, follow the job's events until it ends, then chat with the trained model. */
+export function buildTrainingApiSnippet(
+ request: TrainingApiRequest,
+ { base, apiKey, lang, os }: TrainingApiSnippetInput,
+): string {
+ if (lang === "python") return pythonSnippet(request, base, apiKey);
+ if (lang === "javascript") return javascriptSnippet(request, base, apiKey);
+ return os === "windows"
+ ? powershellSnippet(request, base, apiKey)
+ : bashSnippet(request, base, apiKey);
+}
+
+export function buildTrainingCancelSnippet({
+ base,
+ apiKey,
+ lang,
+ os,
+}: TrainingApiSnippetInput): string {
+ const jobId = "ftjob-YOUR_JOB_ID";
+ if (lang === "python") {
+ return `from openai import OpenAI
+
+client = OpenAI(base_url=${j(`${base}/v1`)}, api_key=${j(apiKey)})
+print(client.fine_tuning.jobs.cancel(${j(jobId)}).status)`;
+ }
+ if (lang === "javascript") {
+ return `import OpenAI from "openai";
+
+const client = new OpenAI({ baseURL: ${j(`${base}/v1`)}, apiKey: ${j(apiKey)} });
+console.log((await client.fineTuning.jobs.cancel(${j(jobId)})).status);`;
+ }
+ if (os === "windows") {
+ return `$base = '${psSingle(base)}'
+$key = '${psSingle(apiKey)}'
+(curl.exe -sSf -X POST "$base/v1/fine_tuning/jobs/${jobId}/cancel" -H "Authorization: Bearer $key" | ConvertFrom-Json).status`;
+ }
+ return `BASE='${shSingle(base)}'
+KEY='${shSingle(apiKey)}'
+curl -sSf -X POST "$BASE/v1/fine_tuning/jobs/${jobId}/cancel" -H "Authorization: Bearer $KEY" | jq -r .status`;
+}
diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.ts
index e8779bba092..fe79986214e 100644
--- a/studio/frontend/src/features/settings/index.ts
+++ b/studio/frontend/src/features/settings/index.ts
@@ -121,6 +121,7 @@ export {
} from "./stores/keyboard-shortcuts-store";
export type { ShortcutId } from "./lib/keyboard-shortcuts";
export { SETTINGS_TABS, useSettingsDialogStore } from "./stores/settings-dialog-store";
+export { trainingApiRequestFromPayload } from "./components/training-api-snippets";
export { settingsTabVisible } from "./settings-tab-visibility";
export { DIALOG_SETTINGS_SEARCH_INDEX } from "./dialog-search-index";
export type { SettingsTab } from "./stores/settings-dialog-store";
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 785e8bdbb74..72fff2f0c32 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -228,6 +228,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.apiKeys.description",
"settings.apiKeys.accessTokens",
"settings.apiKeys.audioApi.title",
+ "settings.apiKeys.trainingApi.title",
"settings.apiKeys.decisionApi.title",
"settings.apiKeys.mcp.title",
"settings.general.modelAutoSwitch.keepKv",
diff --git a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
index 45f9ada495c..4ba69d45570 100644
--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts
@@ -31,6 +31,7 @@ export type SettingsScrollTarget =
| "about-updates"
| "api-keys-audio-api"
| "api-keys-media-api"
+ | "api-keys-training-api"
| "api-keys-decision-api"
| "api-keys-agents"
| "api-keys-mcp"
@@ -65,6 +66,19 @@ export interface MediaApiRequest {
model: string | null;
}
+/** The Train page's form, already narrowed to what the fine-tuning API takes. */
+export interface TrainingApiRequest {
+ model: string | null;
+ /** The uploaded dataset's file name; null for a Hugging Face or S3 dataset. */
+ datasetName: string | null;
+ datasetFromHub: boolean;
+ nEpochs: number;
+ batchSize: number;
+ seed: number;
+ suffix: string | null;
+ extras: Record<string, unknown>;
+}
+
/** Which archive the Data tab should open straight into. */
export type ArchivedShelf = "chats" | "images" | "videos" | "audio";
@@ -94,6 +108,7 @@ interface SettingsDialogState {
audioApiRequested: AudioApiRequest | null;
decisionTryRequested: string | null;
mediaApiRequested: MediaApiRequest | null;
+ trainingApiRequested: TrainingApiRequest | null;
openDialog: (tab?: SettingsTab, options?: OpenDialogOptions) => void;
openArchivedChats: () => void;
openArchivedMedia: (shelf: Exclude<ArchivedShelf, "chats">) => void;
@@ -108,6 +123,8 @@ interface SettingsDialogState {
consumeDecisionTryRequest: () => void;
openMediaApi: (request: MediaApiRequest) => void;
consumeMediaApiRequest: () => void;
+ openTrainingApi: (request: TrainingApiRequest) => void;
+ consumeTrainingApiRequest: () => void;
consumeScrollTarget: (target: SettingsScrollTarget) => void;
closeDialog: () => void;
setActiveTab: (tab: SettingsTab) => void;
@@ -167,6 +184,7 @@ const SCROLL_TARGET_TAB: Record<SettingsScrollTarget, SettingsTab> = {
"about-updates": "about",
"api-keys-audio-api": "api-keys",
"api-keys-media-api": "api-keys",
+ "api-keys-training-api": "api-keys",
"api-keys-decision-api": "api-keys",
"api-keys-agents": "api-keys",
"api-keys-mcp": "api-keys",
@@ -241,6 +259,7 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
audioApiRequested: null,
decisionTryRequested: null,
mediaApiRequested: null,
+ trainingApiRequested: null,
openDialog: (requestedTab, options) =>
set((state) => {
const { tab, target } = resolveScrollRequest(requestedTab, options?.scrollTarget);
@@ -349,9 +368,25 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
connectionRequested: null,
audioApiRequested: null,
mediaApiRequested: request,
+ trainingApiRequested: null,
...focusForOpen(state),
})),
consumeMediaApiRequest: () => set({ mediaApiRequested: null }),
+ openTrainingApi: (request) =>
+ set((state) => ({
+ open: true,
+ activeTab: "api-keys",
+ scrollTarget: "api-keys-training-api",
+ archivedRequested: null,
+ logFamilyRequested: null,
+ logSourcePathRequested: null,
+ connectionRequested: null,
+ audioApiRequested: null,
+ mediaApiRequested: null,
+ trainingApiRequested: request,
+ ...focusForOpen(state),
+ })),
+ consumeTrainingApiRequest: () => set({ trainingApiRequested: null }),
consumeScrollTarget: (target) =>
set((state) => ({
scrollTarget: state.scrollTarget === target ? null : state.scrollTarget,
@@ -368,6 +403,7 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({
audioApiRequested: null,
decisionTryRequested: null,
mediaApiRequested: null,
+ trainingApiRequested: null,
}),
setActiveTab: (tab) => {
try {
diff --git a/studio/frontend/src/features/studio/studio-page.tsx b/studio/frontend/src/features/studio/studio-page.tsx
index 53e84b2c97d..5d892308359 100644
--- a/studio/frontend/src/features/studio/studio-page.tsx
+++ b/studio/frontend/src/features/studio/studio-page.tsx
@@ -37,6 +37,7 @@ import { useTrainingCacheReconciliation } from "./hooks/use-training-cache-recon
import { LiveTrainingView } from "./live-training-view";
import { DatasetPreviewDialog } from "./sections/dataset-preview-dialog";
import { TrainSubNav } from "./studio-navigation";
+import { TrainingApiButton } from "./training-api-button";
import {
studioHistoryTourSteps,
studioTourSteps,
@@ -209,6 +210,7 @@ export function StudioPage(): ReactElement {
showTrainingView={showTrainingView}
/>
<div className="ml-auto flex items-center gap-2">
+ <TrainingApiButton />
<MediaPageLink
to="/images"
label={t("studio.imageTraining")}
diff --git a/studio/frontend/src/features/studio/training-api-button.tsx b/studio/frontend/src/features/studio/training-api-button.tsx
new file mode 100644
index 00000000000..d6eec316910
--- /dev/null
+++ b/studio/frontend/src/features/studio/training-api-button.tsx
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { HEADER_ICON_BUTTON } from "@/components/media-page-link";
+import { datasetDisplayName } from "@/components/resource-picker/dataset-display-name";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import {
+ trainingApiRequestFromPayload,
+ useSettingsDialogStore,
+} from "@/features/settings";
+import { useTrainingConfigStore } from "@/features/training";
+import { buildTrainingStartPayload } from "@/features/training/api/mappers";
+import { useT } from "@/i18n";
+import { ApiIcon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import type { ReactElement } from "react";
+
+/** Opens Settings > API on the Training example, filled from the form as Start would send it. */
+export function TrainingApiButton(): ReactElement {
+ const t = useT();
+ const label = t("settings.apiKeys.audioApi.useViaApi");
+ const openTrainingApi = () => {
+ const config = useTrainingConfigStore.getState();
+ const payload = buildTrainingStartPayload(config, null);
+ const uploaded = config.datasetSource === "upload" ? config.uploadedFile : null;
+ useSettingsDialogStore
+ .getState()
+ .openTrainingApi(
+ trainingApiRequestFromPayload(
+ payload,
+ uploaded ? datasetDisplayName(uploaded) : null,
+ ),
+ );
+ };
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ <button
+ type="button"
+ aria-label={label}
+ onClick={openTrainingApi}
+ className={HEADER_ICON_BUTTON}
+ >
+ <HugeiconsIcon icon={ApiIcon} strokeWidth={1.75} className="size-icon" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" sideOffset={6} className="tooltip-compact">
+ {label}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index e62f51ae18a..5ceb29ae380 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -3338,6 +3338,16 @@ export const en = {
placeholderModel: "The model shown is an example. Load a model on the Images or Video page and open this from its API button to fill it in.",
autoSwitchOff: "Media auto-switch is off, so requests run on the model the page has loaded, whatever they name.",
},
+ trainingApi: {
+ title: "Training API",
+ description: "Fine-tune models from your own code with the OpenAI-compatible fine-tuning endpoints: upload a JSONL file, create a job, follow its events, then chat with the trained model.",
+ placeholder: "The model and settings shown are an example. Open this from the API button on the Train page to fill in your current setup.",
+ hubDataset: "Your Train page uses a Hugging Face or S3 dataset. The API trains on uploaded files, so save the dataset as JSONL and upload that.",
+ batching: "Compatible jobs waiting in the queue train together automatically.",
+ chatNote: "Chatting with the trained model by name needs Model auto-switch on, or load it on the Chat page first.",
+ cancelTitle: "Cancel a job",
+ cancelDescription: "Stops a queued or running job. Not part of the example above.",
+ },
decisionApi: {
title: "Decision API",
docs: "Docs",
diff --git a/studio/frontend/tests/training-api-snippets.test.ts b/studio/frontend/tests/training-api-snippets.test.ts
new file mode 100644
index 00000000000..bd1c46a2711
--- /dev/null
+++ b/studio/frontend/tests/training-api-snippets.test.ts
@@ -0,0 +1,458 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The Training API card's examples carry the Train page's settings, never its secrets or host paths.
+
+import assert from "node:assert/strict";
+import { readFileSync, writeFileSync } from "node:fs";
+import test from "node:test";
+import {
+ EXAMPLE_TRAINING_API_REQUEST,
+ TRAINING_FIELD_ROUTE,
+ buildTrainingApiSnippet,
+ buildTrainingCancelSnippet,
+ trainingApiJobBody,
+ trainingApiRequestFromPayload,
+} from "../src/features/settings/components/training-api-snippets.ts";
+import type { TrainingStartRequest } from "../src/features/training/types/api.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+const BASE = "http://127.0.0.1:8888";
+const KEY = "sk-unsloth-YOUR_KEY";
+const HOSTILE = "$(calc) it's";
+
+function payload(overrides: Partial<TrainingStartRequest> = {}): TrainingStartRequest {
+ return {
+ model_name: "unsloth/Qwen3-0.6B",
+ project_name: "my run",
+ training_type: "LoRA/QLoRA",
+ hf_token: "hf_SECRET",
+ model_known_cached: true,
+ model_local_path: "/home/me/.cache/models/qwen",
+ model_format: "safetensors",
+ load_in_4bit: false,
+ max_seq_length: 4096,
+ vision_image_size: null,
+ trust_remote_code: false,
+ approved_remote_code_fingerprint: "abc",
+ hf_dataset: null,
+ dataset_known_cached: false,
+ dataset_local_path: null,
+ subset: null,
+ train_split: null,
+ eval_split: null,
+ dataset_streaming: false,
+ dataset_slice_start: null,
+ dataset_slice_end: null,
+ local_datasets: ["/home/me/.unsloth/uploads/0123456789abcdef0123456789abcdef_chats.jsonl"],
+ local_eval_datasets: [],
+ s3_config: null,
+ format_type: "auto",
+ custom_format_mapping: undefined,
+ num_epochs: 3,
+ learning_rate: "0.0002",
+ batch_size: 4,
+ gradient_accumulation_steps: 2,
+ warmup_steps: 5,
+ warmup_ratio: null,
+ max_steps: 0,
+ save_steps: 100,
+ eval_steps: 0,
+ weight_decay: 0.001,
+ random_seed: 3407,
+ packing: false,
+ optim: "adamw_8bit",
+ lr_scheduler_type: "linear",
+ use_lora: true,
+ lora_r: 16,
+ lora_alpha: 32,
+ lora_dropout: 0,
+ target_modules: ["q_proj", "v_proj"],
+ gradient_checkpointing: "unsloth",
+ use_rslora: false,
+ use_loftq: false,
+ use_dora: true,
+ train_on_completions: true,
+ finetune_vision_layers: false,
+ finetune_language_layers: true,
+ finetune_attention_modules: true,
+ finetune_mlp_modules: true,
+ is_dataset_image: false,
+ is_dataset_audio: false,
+ is_embedding: false,
+ is_decision: false,
+ model_subfolder: null,
+ enable_wandb: true,
+ wandb_token: "wandb_SECRET",
+ enable_tensorboard: true,
+ tensorboard_dir: "/home/me/tb",
+ ...overrides,
+ } as TrainingStartRequest;
+}
+
+const ALLOWED = new Set(
+ Object.entries(TRAINING_FIELD_ROUTE)
+ .filter(([, route]) => route === "extra")
+ .map(([key]) => key),
+);
+
+const SECRETS = ["hf_SECRET", "wandb_SECRET", "/home/me", "abc\"", "tensorboard", "offload", "drafter"];
+
+const LANGS = [
+ ["python", "unix"],
+ ["javascript", "unix"],
+ ["curl", "unix"],
+ ["curl", "windows"],
+] as const;
+
+test("the snapshot keeps only the allowlist and maps the OpenAI fields", () => {
+ const request = trainingApiRequestFromPayload(payload(), "chats.jsonl");
+ assert.equal(request.model, "unsloth/Qwen3-0.6B");
+ assert.equal(request.datasetName, "chats.jsonl");
+ assert.equal(request.datasetFromHub, false);
+ assert.equal(request.nEpochs, 3);
+ assert.equal(request.batchSize, 4);
+ assert.equal(request.seed, 3407);
+ assert.equal(request.suffix, "my run");
+ for (const key of Object.keys(request.extras)) assert.ok(ALLOWED.has(key), key);
+ assert.equal(request.extras.learning_rate, "0.0002");
+ assert.equal(request.extras.use_dora, true);
+ assert.ok(!("use_rslora" in request.extras));
+ assert.ok(!("max_steps" in request.extras));
+ assert.ok(!("training_type" in request.extras));
+ assert.ok(!("format_type" in request.extras));
+ assert.deepEqual(request.extras.target_modules, ["q_proj", "v_proj"]);
+});
+
+test("every extra setting the form changes reaches the example, and nothing host-side does", () => {
+ // A non-default value per extra field, with what its condition needs (LoRA on, warmup steps unset).
+ const changed: Partial<TrainingStartRequest> = {
+ learning_rate: "1e-5",
+ max_steps: 60,
+ training_type: "Continued Pretraining",
+ load_in_4bit: true,
+ max_seq_length: 8192,
+ vision_image_size: 448,
+ trust_remote_code: true,
+ dataset_slice_start: 10,
+ dataset_slice_end: 500,
+ format_type: "chatml",
+ custom_format_mapping: { text: "body" },
+ embedding_learning_rate: 5e-6,
+ gradient_accumulation_steps: 8,
+ warmup_steps: null,
+ warmup_ratio: 0.1,
+ save_steps: 25,
+ weight_decay: 0.1,
+ max_grad_norm: 0.5,
+ max_grad_value: 2,
+ packing: true,
+ optim: "adamw_torch",
+ lr_scheduler_type: "cosine",
+ lora_r: 64,
+ lora_alpha: 128,
+ lora_dropout: 0.05,
+ target_modules: ["q_proj"],
+ gradient_checkpointing: "true",
+ use_rslora: true,
+ use_loftq: true,
+ use_dora: true,
+ train_on_completions: false,
+ finetune_vision_layers: true,
+ finetune_language_layers: false,
+ finetune_attention_modules: false,
+ finetune_mlp_modules: false,
+ is_dataset_image: true,
+ is_dataset_audio: true,
+ is_embedding: true,
+ is_decision: true,
+ model_subfolder: "multilingual",
+ };
+ const full = payload({
+ ...changed,
+ hf_dataset: "org/data",
+ s3_config: { bucket: "b" } as TrainingStartRequest["s3_config"],
+ eval_steps: 10,
+ offload_layers: 4,
+ resume_from_checkpoint: "/home/me/ckpt",
+ });
+ const { extras } = trainingApiRequestFromPayload(full, null);
+ for (const [key, route] of Object.entries(TRAINING_FIELD_ROUTE)) {
+ const value = changed[key as keyof TrainingStartRequest];
+ if (route === "extra" && value != null) {
+ assert.deepEqual(extras[key], value, key);
+ } else {
+ assert.ok(!(key in extras), key);
+ }
+ }
+ for (const key of ALLOWED) assert.ok(key in changed, `${key} has no test value`);
+});
+
+test("full finetuning names its training type and drops the LoRA settings", () => {
+ const request = trainingApiRequestFromPayload(
+ payload({ training_type: "Full Finetuning", use_lora: false, target_modules: [], max_steps: 60 }),
+ null,
+ );
+ assert.equal(request.extras.training_type, "Full Finetuning");
+ assert.equal(request.extras.max_steps, 60);
+ for (const key of ["lora_r", "lora_alpha", "lora_dropout", "target_modules", "use_dora"]) {
+ assert.ok(!(key in request.extras), key);
+ }
+});
+
+test("a vision, audio, embedding or decision run keeps its run type and layer choices", () => {
+ const plain = trainingApiRequestFromPayload(payload(), "chats.jsonl");
+ for (const key of ["is_dataset_image", "finetune_vision_layers", "finetune_mlp_modules"]) {
+ assert.ok(!(key in plain.extras), key);
+ }
+ const vision = trainingApiRequestFromPayload(
+ payload({ is_dataset_image: true, finetune_vision_layers: true, finetune_mlp_modules: false }),
+ "images.zip",
+ );
+ assert.equal(vision.extras.is_dataset_image, true);
+ assert.equal(vision.extras.finetune_vision_layers, true);
+ assert.equal(vision.extras.finetune_mlp_modules, false);
+ assert.ok(!("finetune_language_layers" in vision.extras));
+ const decision = trainingApiRequestFromPayload(
+ payload({ is_decision: true, model_subfolder: "multilingual" }),
+ null,
+ );
+ assert.equal(decision.extras.model_subfolder, "multilingual");
+ assert.ok(!("model_subfolder" in plain.extras));
+ for (const flag of ["is_dataset_audio", "is_embedding", "is_decision"] as const) {
+ const request = trainingApiRequestFromPayload(payload({ [flag]: true }), null);
+ assert.equal(request.extras[flag], true, flag);
+ }
+});
+
+test("no dataset picked yet is not mistaken for a Hub dataset", () => {
+ const request = trainingApiRequestFromPayload(payload({ local_datasets: [] }), null);
+ assert.equal(request.datasetFromHub, false);
+ assert.equal(request.datasetName, null);
+ const s3 = trainingApiRequestFromPayload(
+ payload({ local_datasets: [], s3_config: { bucket: "b" } as TrainingStartRequest["s3_config"] }),
+ null,
+ );
+ assert.equal(s3.datasetFromHub, true);
+});
+
+test("a Hub or S3 dataset is flagged, and its fields never reach the example", () => {
+ const request = trainingApiRequestFromPayload(
+ payload({ hf_dataset: "org/data", subset: "x", local_datasets: [], format_type: "sharegpt" }),
+ null,
+ );
+ assert.equal(request.datasetFromHub, true);
+ assert.equal(request.datasetName, null);
+ assert.equal(request.extras.format_type, "sharegpt");
+ for (const [lang, os] of LANGS) {
+ const snippet = buildTrainingApiSnippet(request, { base: BASE, apiKey: KEY, lang, os });
+ assert.ok(snippet.includes("train.jsonl"), `${lang} ${os}`);
+ assert.ok(!snippet.includes("org/data"), `${lang} ${os}`);
+ }
+});
+
+for (const [lang, os] of LANGS) {
+ const label = `${lang} ${os}`;
+ const request = trainingApiRequestFromPayload(
+ payload({ custom_format_mapping: { instruction: "user", __system_prompt: "Be brief" } }),
+ "chats.jsonl",
+ );
+ const snippet = buildTrainingApiSnippet(request, { base: BASE, apiKey: KEY, lang, os });
+
+ test(`${label}: uploads, creates, follows events, then chats with the trained model`, () => {
+ assert.ok(snippet.includes("chats.jsonl"));
+ assert.ok(snippet.includes("fine-tune"));
+ assert.ok(snippet.includes("unsloth/Qwen3-0.6B"));
+ assert.ok(snippet.includes("my run"));
+ assert.ok(snippet.includes("0.0002"));
+ assert.match(snippet, /fine_tuned_model/);
+ assert.match(snippet, /succeeded/);
+ assert.match(snippet, /cancelled/);
+ assert.ok(!snippet.includes("cancel("), "cancel is a separate example");
+ assert.ok(!snippet.includes("/cancel"), "cancel is a separate example");
+ for (const secret of SECRETS) assert.ok(!snippet.includes(secret), secret);
+ });
+
+ test(`${label}: the extras go on the wire flat, never inside an extra_body key`, () => {
+ if (lang === "python") {
+ assert.match(snippet, /extra_body=\{\n {8}"learning_rate": "0\.0002",/);
+ assert.match(snippet, /"use_dora": True,/);
+ assert.match(snippet, /"train_on_completions": True,/);
+ assert.match(snippet, /"packing": False,/);
+ assert.match(snippet, /hyperparameters=\{"n_epochs": 3, "batch_size": 4\}/);
+ assert.match(snippet, /"__system_prompt": "Be brief"/);
+ return;
+ }
+ assert.ok(!snippet.includes("extra_body"));
+ if (lang === "javascript") {
+ assert.match(snippet, /\n {2}learning_rate: "0\.0002",\n/);
+ assert.match(snippet, /\n {2}use_dora: true,\n/);
+ assert.match(snippet, /hyperparameters: \{ n_epochs: 3, batch_size: 4 \}/);
+ return;
+ }
+ assert.match(snippet, /\n {2}"learning_rate": "0\.0002"/);
+ assert.match(snippet, /\n {2}"hyperparameters": \{"n_epochs":3,"batch_size":4\}/);
+ assert.match(snippet, /\n {2}"use_dora": true/);
+ });
+}
+
+test("events are read newest first, de-duplicated and printed oldest first", () => {
+ const request = EXAMPLE_TRAINING_API_REQUEST;
+ const python = buildTrainingApiSnippet(request, { base: BASE, apiKey: KEY, lang: "python", os: "unix" });
+ assert.match(python, /for event in reversed\(events\):\n\s+if event\.id not in seen:/);
+ const js = buildTrainingApiSnippet(request, { base: BASE, apiKey: KEY, lang: "javascript", os: "unix" });
+ assert.match(js, /\[\.\.\.events\.data\]\.reverse\(\)/);
+ assert.match(js, /if \(seen\.has\(event\.id\)\) continue;/);
+ const bash = buildTrainingApiSnippet(request, { base: BASE, apiKey: KEY, lang: "curl", os: "unix" });
+ assert.match(bash, /\.data \| reverse\[\]/);
+ assert.match(bash, /\*" \$EVENT_ID "\*\) ;;/);
+ const ps = buildTrainingApiSnippet(request, { base: BASE, apiKey: KEY, lang: "curl", os: "windows" });
+ assert.match(ps, /\[array\]::Reverse\(\$events\)/);
+ assert.match(ps, /if \(-not \$seen\.ContainsKey\(\$item\.id\)\)/);
+});
+
+test("the PowerShell body is a literal here-string, so $(...) in a setting stays text", () => {
+ const request = trainingApiRequestFromPayload(
+ payload({ model_name: HOSTILE, project_name: HOSTILE }),
+ HOSTILE,
+ );
+ const snippet = buildTrainingApiSnippet(request, { base: BASE, apiKey: KEY, lang: "curl", os: "windows" });
+ assert.match(snippet, /\$settings = @'\n {2}"model": "\$\(calc\) it's",\n/);
+ assert.match(snippet, /\n'@\n/);
+ assert.ok(snippet.includes(`-F 'file=@$(calc) it''s'`));
+ assert.ok(snippet.includes('"{`n `"training_file`": `"$($file.id)`",`n$settings`n}"'));
+});
+
+test("the bash body stays inside single quotes and splices only the file id", () => {
+ const request = trainingApiRequestFromPayload(
+ payload({ model_name: HOSTILE, project_name: HOSTILE }),
+ HOSTILE,
+ );
+ const snippet = buildTrainingApiSnippet(request, { base: BASE, apiKey: KEY, lang: "curl", os: "unix" });
+ assert.ok(snippet.includes(` "model": "$(calc) it'\\''s",`));
+ assert.ok(snippet.includes(` "suffix": "$(calc) it'\\''s",`));
+ assert.ok(snippet.includes(` "training_file": "'"$FILE_ID"'",`));
+ assert.ok(snippet.includes(`-F 'file=@$(calc) it'\\''s'`));
+});
+
+test("python and javascript strings are escaped literals", () => {
+ const request = trainingApiRequestFromPayload(
+ payload({ model_name: 'a"b\\c', project_name: null }),
+ null,
+ );
+ for (const lang of ["python", "javascript"] as const) {
+ const snippet = buildTrainingApiSnippet(request, { base: BASE, apiKey: KEY, lang, os: "unix" });
+ assert.ok(snippet.includes('"a\\"b\\\\c"'), lang);
+ assert.ok(!snippet.includes("suffix"), lang);
+ }
+});
+
+test("the placeholder example and the cancel example render for every language", () => {
+ for (const [lang, os] of LANGS) {
+ const snippet = buildTrainingApiSnippet(EXAMPLE_TRAINING_API_REQUEST, { base: BASE, apiKey: KEY, lang, os });
+ assert.ok(snippet.includes("unsloth/Qwen3-0.6B"));
+ assert.ok(snippet.includes("train.jsonl"));
+ const cancel = buildTrainingCancelSnippet({ base: BASE, apiKey: KEY, lang, os });
+ assert.match(cancel, /cancel/);
+ assert.ok(cancel.includes(KEY));
+ }
+});
+
+test("the Train header leads its page links with the API button, and the API tab has a Training kind", () => {
+ const page = readSrc("features/studio/studio-page.tsx");
+ assert.match(page, /<div className="ml-auto flex items-center gap-2">\s*<TrainingApiButton \/>\s*<MediaPageLink\b[^]*?to="\/library"/);
+ const button = readSrc("features/studio/training-api-button.tsx");
+ assert.match(button, /className=\{HEADER_ICON_BUTTON\}/);
+ assert.match(button, /buildTrainingStartPayload\(config, null\)/);
+ assert.match(button, /\.openTrainingApi\(/);
+ const tabs = readSrc("features/settings/components/api-example-tabs.tsx");
+ assert.match(tabs, /"api-keys-training-api": "training"/);
+ assert.match(tabs, /<TrainingApiExamples[^>]*showHeading=\{false\}/);
+ const monitor = readSrc("features/api-monitor/api-monitor-page.tsx");
+ assert.match(monitor, /kind === "training" \? \(\s*<TrainingApiExamples/);
+});
+
+// studio/backend/tests/test_training_api_snippet_contract.py sends these bodies through the fine-tuning
+// route's validation; UPDATE_TRAINING_API_BODIES=1 rewrites them after an intended change.
+const BODIES = new URL("../../backend/tests/fixtures/training_api_job_bodies.json", import.meta.url);
+
+test("the backend contract fixture is what the examples send", () => {
+ const bodies = {
+ lora: trainingApiJobBody(trainingApiRequestFromPayload(payload(), "chats.jsonl")),
+ fullFinetuning: trainingApiJobBody(
+ trainingApiRequestFromPayload(
+ payload({
+ training_type: "Full Finetuning",
+ use_lora: false,
+ target_modules: [],
+ use_dora: false,
+ max_steps: 60,
+ warmup_steps: null,
+ warmup_ratio: 0.03,
+ format_type: "alpaca",
+ project_name: null,
+ }),
+ null,
+ ),
+ ),
+ qloraMapping: trainingApiJobBody(
+ trainingApiRequestFromPayload(
+ payload({
+ load_in_4bit: true,
+ use_dora: false,
+ use_rslora: true,
+ learning_rate: "1e-5",
+ train_on_completions: false,
+ custom_format_mapping: {
+ question: "user",
+ answer: "assistant",
+ __system_prompt: "Answer in one word.",
+ __label_mapping: { answer: { "0": "no", "1": "yes" } },
+ },
+ }),
+ null,
+ ),
+ ),
+ continuedPretraining: trainingApiJobBody(
+ trainingApiRequestFromPayload(
+ payload({ training_type: "Continued Pretraining", use_dora: false, use_loftq: true }),
+ null,
+ ),
+ ),
+ decision: trainingApiJobBody(
+ trainingApiRequestFromPayload(
+ payload({ is_decision: true, model_subfolder: "multilingual", use_dora: false }),
+ null,
+ ),
+ ),
+ vision: trainingApiJobBody(
+ trainingApiRequestFromPayload(
+ payload({ is_dataset_image: true, finetune_vision_layers: true, use_dora: false }),
+ null,
+ ),
+ ),
+ everySetting: trainingApiJobBody(
+ trainingApiRequestFromPayload(
+ payload({
+ training_type: "Continued Pretraining",
+ embedding_learning_rate: 5e-6,
+ dataset_slice_start: 10,
+ dataset_slice_end: 500,
+ save_steps: 25,
+ max_grad_norm: 0.5,
+ max_grad_value: 2,
+ gradient_checkpointing: "true",
+ vision_image_size: 448,
+ trust_remote_code: true,
+ use_dora: false,
+ }),
+ null,
+ ),
+ ),
+ example: trainingApiJobBody(EXAMPLE_TRAINING_API_REQUEST),
+ };
+ if (process.env.UPDATE_TRAINING_API_BODIES === "1") {
+ writeFileSync(BODIES, `${JSON.stringify(bodies, null, 2)}\n`);
+ }
+ assert.deepEqual(bodies, JSON.parse(readFileSync(BODIES, "utf8")));
+});