Skip to main content

FineTuning

Struct FineTuning 

Source
pub struct FineTuning { /* private fields */ }
Expand description

Client for interacting with the OpenAI Fine-tuning API.

This struct provides methods to create, list, retrieve, and cancel fine-tuning jobs, as well as access training events and checkpoints.

§Example

use openai_tools::fine_tuning::request::{FineTuning, CreateFineTuningJobRequest};
use openai_tools::fine_tuning::response::Hyperparameters;
use openai_tools::common::models::FineTuningModel;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let fine_tuning = FineTuning::new()?;

    // Create a fine-tuning job
    let hyperparams = Hyperparameters {
        n_epochs: Some(3),
        batch_size: None,
        learning_rate_multiplier: None,
    };

    let request = CreateFineTuningJobRequest::new(
            FineTuningModel::Gpt4oMini_2024_07_18,
            "file-abc123"
        )
        .with_suffix("my-custom-model")
        .with_supervised_method(Some(hyperparams));

    let job = fine_tuning.create(request).await?;
    println!("Created job: {} ({:?})", job.id, job.status);

    Ok(())
}

Implementations§

Source§

impl FineTuning

Source

pub fn new() -> Result<Self>

Creates a new FineTuning client for OpenAI API.

Initializes the client by loading the OpenAI API key from the environment variable OPENAI_API_KEY. Supports .env file loading via dotenvy.

§Returns
  • Ok(FineTuning) - A new FineTuning client ready for use
  • Err(OpenAIToolError) - If the API key is not found in the environment
§Example
use openai_tools::fine_tuning::request::FineTuning;

let fine_tuning = FineTuning::new().expect("API key should be set");
Source

pub fn with_auth(auth: AuthProvider) -> Self

Creates a new FineTuning client with a custom authentication provider

Source

pub fn azure() -> Result<Self>

Creates a new FineTuning client for Azure OpenAI API

Source

pub fn detect_provider() -> Result<Self>

Creates a new FineTuning client by auto-detecting the provider

Source

pub fn with_url<S: Into<String>>(base_url: S, api_key: S) -> Self

Creates a new FineTuning client with URL-based provider detection

Source

pub fn from_url<S: Into<String>>(url: S) -> Result<Self>

Creates a new FineTuning client from URL using environment variables

Source

pub fn auth(&self) -> &AuthProvider

Returns the authentication provider

Source

pub fn timeout(&mut self, timeout: Duration) -> &mut Self

Sets the request timeout duration.

§Arguments
  • timeout - The maximum time to wait for a response
§Returns

A mutable reference to self for method chaining

Source

pub async fn create( &self, request: CreateFineTuningJobRequest, ) -> Result<FineTuningJob>

Creates a new fine-tuning job.

§Arguments
  • request - The fine-tuning job creation request
§Returns
  • Ok(FineTuningJob) - The created job object
  • Err(OpenAIToolError) - If the request fails
§Example
use openai_tools::fine_tuning::request::{FineTuning, CreateFineTuningJobRequest};
use openai_tools::common::models::FineTuningModel;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let fine_tuning = FineTuning::new()?;

    let request = CreateFineTuningJobRequest::new(
            FineTuningModel::Gpt4oMini_2024_07_18,
            "file-abc123"
        )
        .with_suffix("my-model");

    let job = fine_tuning.create(request).await?;
    println!("Created job: {}", job.id);
    Ok(())
}
Source

pub async fn retrieve(&self, job_id: &str) -> Result<FineTuningJob>

Retrieves details of a specific fine-tuning job.

§Arguments
  • job_id - The ID of the job to retrieve
§Returns
  • Ok(FineTuningJob) - The job details
  • Err(OpenAIToolError) - If the job is not found or the request fails
§Example
use openai_tools::fine_tuning::request::FineTuning;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let fine_tuning = FineTuning::new()?;
    let job = fine_tuning.retrieve("ftjob-abc123").await?;

    println!("Status: {:?}", job.status);
    if let Some(model) = &job.fine_tuned_model {
        println!("Fine-tuned model: {}", model);
    }
    Ok(())
}
Source

pub async fn cancel(&self, job_id: &str) -> Result<FineTuningJob>

Cancels an in-progress fine-tuning job.

§Arguments
  • job_id - The ID of the job to cancel
§Returns
  • Ok(FineTuningJob) - The updated job object
  • Err(OpenAIToolError) - If the job cannot be cancelled or the request fails
§Example
use openai_tools::fine_tuning::request::FineTuning;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let fine_tuning = FineTuning::new()?;
    let job = fine_tuning.cancel("ftjob-abc123").await?;

    println!("Job status: {:?}", job.status);
    Ok(())
}
Source

pub async fn list( &self, limit: Option<u32>, after: Option<&str>, ) -> Result<FineTuningJobListResponse>

Lists all fine-tuning jobs.

Supports pagination through limit and after parameters.

§Arguments
  • limit - Maximum number of jobs to return (default: 20)
  • after - Cursor for pagination (job ID to start after)
§Returns
  • Ok(FineTuningJobListResponse) - The list of jobs
  • Err(OpenAIToolError) - If the request fails
§Example
use openai_tools::fine_tuning::request::FineTuning;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let fine_tuning = FineTuning::new()?;

    let response = fine_tuning.list(Some(10), None).await?;
    for job in &response.data {
        println!("{}: {:?}", job.id, job.status);
    }

    Ok(())
}
Source

pub async fn list_events( &self, job_id: &str, limit: Option<u32>, after: Option<&str>, ) -> Result<FineTuningEventListResponse>

Lists events for a fine-tuning job.

Events provide insight into the training process.

§Arguments
  • job_id - The ID of the fine-tuning job
  • limit - Maximum number of events to return (default: 20)
  • after - Cursor for pagination (event ID to start after)
§Returns
  • Ok(FineTuningEventListResponse) - The list of events
  • Err(OpenAIToolError) - If the request fails
§Example
use openai_tools::fine_tuning::request::FineTuning;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let fine_tuning = FineTuning::new()?;

    let response = fine_tuning.list_events("ftjob-abc123", Some(10), None).await?;
    for event in &response.data {
        println!("[{}] {}: {}", event.level, event.event_type, event.message);
    }

    Ok(())
}
Source

pub async fn list_checkpoints( &self, job_id: &str, limit: Option<u32>, after: Option<&str>, ) -> Result<FineTuningCheckpointListResponse>

Lists checkpoints for a fine-tuning job.

Checkpoints are saved at the end of each training epoch. Only the last 3 checkpoints are available.

§Arguments
  • job_id - The ID of the fine-tuning job
  • limit - Maximum number of checkpoints to return (default: 10)
  • after - Cursor for pagination (checkpoint ID to start after)
§Returns
  • Ok(FineTuningCheckpointListResponse) - The list of checkpoints
  • Err(OpenAIToolError) - If the request fails
§Example
use openai_tools::fine_tuning::request::FineTuning;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let fine_tuning = FineTuning::new()?;

    let response = fine_tuning.list_checkpoints("ftjob-abc123", None, None).await?;
    for checkpoint in &response.data {
        println!("Step {}: loss={}", checkpoint.step_number, checkpoint.metrics.train_loss);
    }

    Ok(())
}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more