Developer Dashboard

Fine-tuning API

Warning

Feature Not Implemented!

This functionality is currently under development and not yet available in AvalAI. This reference is retained as a future compatibility map; examples will not work until AvalAI announces supported fine-tuning routes and base models.

The Fine-tuning API allows you to customize models for your specific use case by training on your data.

Tip

OpenAI's current supervised fine-tuning docs recommend setting up evals before training, starting with high-quality JSONL chat examples, and using default hyperparameters until evals show a reason to change them. The current AvalAI data/models.json source does not advertise fine-tunable base models.

Endpoint

POST https://api.avalai.ir/v1/fine-tuning/jobs

Request Body

ParameterTypeRequiredDescription
modelstringYesID of a supported fine-tunable base model. No current AvalAI base model should be assumed fine-tunable until announced.
training_filestringYesThe ID of an uploaded file that contains training data.
validation_filestringNoThe ID of an uploaded file that contains validation data.
hyperparametersobjectNoThe hyperparameters used for the fine-tuning job.
suffixstringNoA string of up to 64 characters that will be added to your fine-tuned model name when supported.
methodobjectNoFine-tuning method, such as supervised fine-tuning, when supported by the route.

Method Object

method is route- and model-dependent. Keep examples behind a feature flag until AvalAI publishes supported methods.

Method typeTraining signalPlanning notes
supervisedPrompt and ideal assistant response examples.Best for consistent format, style, and instruction-following.
dpoPreferred and rejected response pairs.Best when humans can compare outputs but there is no single ground-truth answer.
reinforcementA grader produces a numeric reward for sampled responses.Best for measurable reasoning tasks; requires evals, grader validation, and safety checks.

For RFT-style jobs, design the grader before uploading data, keep validation prompts separate from training prompts, and confirm the base model has partial success before attempting training. A model that never solves the task cannot usually be bootstrapped by RFT.

Hyperparameters Object

ParameterTypeRequiredDescription
n_epochsinteger or stringNoThe number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. Default is "auto".
batch_sizeinteger or stringNoNumber of examples in each batch. Default is "auto".
learning_rate_multipliernumber or stringNoScaling factor for the learning rate. Default is "auto".

Examples

Creating a Fine-tuning Job

bash
curl https://api.avalai.ir/v1/fine-tuning/jobs \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
  "model": "fine-tunable-model-id",
  "training_file": "file-abc123",
  "validation_file": "file-def456",
  "hyperparameters": {
    "n_epochs": 4
  }
}'
python
from openai import OpenAI

client = OpenAI(
    api_key="your-avalai-api-key",  # Replace with your actual API key
    base_url="https://api.avalai.ir/v1",  # AvalAI API endpoint
)

response = client.fine_tuning.jobs.create(
    model="fine-tunable-model-id",
    training_file="file-abc123",
    validation_file="file-def456",
    hyperparameters={"n_epochs": 4},
)

print(response)
javascript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.fineTuning.jobs.create({
  model: "fine-tunable-model-id",
  training_file: "file-abc123",
  validation_file: "file-def456",
  hyperparameters: {
    n_epochs: 4,
  },
});

console.log(response);
go
// Go Example: Creating a Fine-tuning Job via AvalAI
package main

import (
	"context"
	"fmt"
	"os"

	openai "github.com/openai/openai-go"
)

func main() {
	apiKey := os.Getenv("AVALAI_API_KEY") // Or replace with your key
	if apiKey == "" {
		fmt.Println("Error: AVALAI_API_KEY environment variable not set.")
		return
	}
	baseURL := "https://api.avalai.ir/v1" // Use AvalAI base URL

	config := openai.DefaultConfig(apiKey)
	config.BaseURL = baseURL
	client := openai.NewClientWithConfig(config)

	req := openai.FineTuningJobRequest{
		Model:          "fine-tunable-model-id",
		TrainingFile:   "file-abc123",
		ValidationFile: "file-def456", // Optional
		Hyperparameters: &openai.Hyperparameters{
			NEpochs: 4, // Optional, example value
		},
		// Suffix: "my-custom-model", // Optional
	}

	resp, err := client.CreateFineTuningJob(context.Background(), req)
	if err != nil {
		fmt.Printf("FineTuningJob creation error: %v\n", err)
		return
	}

	fmt.Printf("Fine-tuning job created: %+v\n", resp)
}
php
<?php
// PHP Example: Creating a Fine-tuning Job via AvalAI

$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your key directly
$apiUrl = 'https://api.avalai.ir/v1/fine-tuning/jobs'; // Use AvalAI base URL

$data = [
'model' => 'fine-tunable-model-id',
'training_file' => 'file-abc123',
'validation_file' => 'file-def456', // Optional
'hyperparameters' => [ // Optional
'n_epochs' => 4
]
// 'suffix' => 'my-custom-model' // Optional
];

$jsonData = json_encode($data);

$ch = curl_init($apiUrl);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
'Content-Length: ' . strlen($jsonData)
]);

$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);

curl_close($ch);

if ($err) {
  echo "cURL Error #:" . $err;
} elseif ($httpcode >= 400) {
  echo "HTTP Error: " . $httpcode . "\n";
  echo "Response: " . $response;
} else {
  echo "Fine-tuning job creation response:\n";
  echo $response;
  // $responseData = json_decode($response, true);
  // print_r($responseData);
}
?>

Response Format

json
{
  "id": "ftjob-abc123",
  "object": "fine_tuning.job",
  "model": "fine-tunable-model-id",
  "created_at": 1677858242,
  "finished_at": null,
  "fine_tuned_model": null,
  "organization_id": "org-123",
  "status": "running",
  "hyperparameters": {
    "n_epochs": 4
  },
  "training_file": "file-abc123",
  "validation_file": "file-def456",
  "result_files": [],
  "trained_tokens": null
}

Response Parameters

ParameterTypeDescription
idstringThe identifier for the fine-tuning job.
objectstringThe object type, which is always "fine_tuning.job".
modelstringThe base model that is being fine-tuned.
created_atintegerThe Unix timestamp (in seconds) of when the fine-tuning job was created.
finished_atinteger or nullThe Unix timestamp (in seconds) of when the fine-tuning job was finished.
fine_tuned_modelstring or nullThe name of the fine-tuned model, if the job has completed successfully.
organization_idstringThe organization that owns the fine-tuning job.
statusstringThe status of the fine-tuning job. Can be "validating", "preparing", "queued", "running", "succeeded", "failed", or "cancelled".
hyperparametersobjectThe hyperparameters used for the fine-tuning job.
training_filestringThe ID of the file used for training.
validation_filestring or nullThe ID of the file used for validation.
result_filesarrayArray of file IDs generated during the fine-tuning job.
trained_tokensinteger or nullThe number of tokens trained on during the fine-tuning job.

List Fine-tuning Jobs

GET https://api.avalai.ir/v1/fine-tuning/jobs

Query Parameters

ParameterTypeRequiredDescription
limitintegerNoNumber of fine-tuning jobs to retrieve. Default is 20.
afterstringNoIdentifier for the last job from the previous pagination request.

Retrieve Fine-tuning Job

GET https://api.avalai.ir/v1/fine-tuning/jobs/{fine_tuning_job_id}

Cancel Fine-tuning Job

POST https://api.avalai.ir/v1/fine-tuning/jobs/{fine_tuning_job_id}/cancel

List Fine-tuning Events

GET https://api.avalai.ir/v1/fine-tuning/jobs/{fine_tuning_job_id}/events

Query Parameters

ParameterTypeRequiredDescription
limitintegerNoNumber of events to retrieve. Default is 20.
afterstringNoIdentifier for the last event from the previous pagination request.

Event and Metrics Notes

Event payloads are provider- and method-dependent. When exposed, use them to debug the job rather than relying on the final status alone:

Metric familyUseful for
train_loss, valid_loss, token accuracySFT convergence and overfitting checks.
train_reward_mean, valid_reward_meanRFT reward progress and validation drift.
grader-specific scores and usageFinding weak, slow, or expensive graders.
parse and runtime error ratesDetecting invalid response schemas, bad grader variables, or tool-call format errors.

Training metrics are not deployment approval. Run your external eval suite and safety checks before using any fine_tuned_model in production.

Conditional Lifecycle Endpoints

Some upstream fine-tuning systems expose additional lifecycle controls such as pause, resume, and checkpoints. These are not guaranteed AvalAI endpoints; use them only if AvalAI announces support for your route and model.

OperationConditional path shapePurpose
Pause jobPOST /v1/fine-tuning/jobs/{fine_tuning_job_id}/pauseStop training and create a checkpoint for evaluation when supported.
Resume jobPOST /v1/fine-tuning/jobs/{fine_tuning_job_id}/resumeContinue training from the last checkpoint when supported.
List checkpointsGET /v1/fine-tuning/jobs/{fine_tuning_job_id}/checkpointsCompare intermediate candidate models against the final model and base model.

Checkpoint objects commonly include a checkpoint model ID, step number, creation time, and metrics. Treat each checkpoint model ID as a candidate: evaluate it on a held-out set, run safety checks, and keep rollback to the previous production model.

Error Handling

The API may return various error codes:

Status CodeDescription
400Bad Request - Your request is invalid.
401Unauthorized - Your API key is wrong.
403Forbidden - You don't have permission to access this resource.
404Not Found - The specified resource could not be found.
429Too Many Requests - You have exceeded your rate limit.
500Internal Server Error - We had a problem with our server.

For more information on handling errors, see the Error Handling guide.