"use strict";
/**
 * This file was auto-generated by Fern from our API Definition.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FineTune = void 0;
const core = __importStar(require("../../../../core"));
const OpenAI = __importStar(require("../../.."));
const environments = __importStar(require("../../../../environments"));
const url_join_1 = __importDefault(require("url-join"));
const serializers = __importStar(require("../../../../serialization"));
const errors = __importStar(require("../../../../errors"));
const url_search_params_1 = __importDefault(require("@ungap/url-search-params"));
class FineTune {
    options;
    constructor(options) {
        this.options = options;
    }
    /**
     * List your organization's fine-tuning jobs
     * @throws {OpenAI.UnauthorizedError}
     * @throws {OpenAI.RateLimitError}
     * @throws {OpenAI.InternalServerError}
     */
    async list() {
        const _response = await (this.options.fetcher ?? core.fetcher)({
            url: (0, url_join_1.default)(environments.OpenAIEnvironment.Production, "/fine-tunes"),
            method: "GET",
            headers: {
                Authorization: await this._getAuthorizationHeader(),
                "OpenAI-Organization": await core.Supplier.get(this.options.organization),
                "X-Fern-Language": "JavaScript",
                "X-Fern-SDK-Name": "@fern-api/openai",
                "X-Fern-SDK-Version": "0.0.29",
            },
            contentType: "application/json",
            timeoutMs: 60000,
        });
        if (_response.ok) {
            return await serializers.ListFineTunesResponse.parseOrThrow(_response.body, {
                unrecognizedObjectKeys: "passthrough",
                allowUnrecognizedUnionMembers: true,
                allowUnrecognizedEnumValues: true,
            });
        }
        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new OpenAI.UnauthorizedError();
                case 429:
                    throw new OpenAI.RateLimitError();
                case 500:
                    throw new OpenAI.InternalServerError();
                default:
                    throw new errors.OpenAIError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                    });
            }
        }
        switch (_response.error.reason) {
            case "non-json":
                throw new errors.OpenAIError({
                    statusCode: _response.error.statusCode,
                    body: _response.error.rawBody,
                });
            case "timeout":
                throw new errors.OpenAITimeoutError();
            case "unknown":
                throw new errors.OpenAIError({
                    message: _response.error.errorMessage,
                });
        }
    }
    /**
     * Creates a job that fine-tunes a specified model from a given dataset. Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. [Learn more about Fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
     *
     * @throws {OpenAI.UnauthorizedError}
     * @throws {OpenAI.RateLimitError}
     * @throws {OpenAI.InternalServerError}
     */
    async create(request) {
        const _response = await (this.options.fetcher ?? core.fetcher)({
            url: (0, url_join_1.default)(environments.OpenAIEnvironment.Production, "/fine-tunes"),
            method: "POST",
            headers: {
                Authorization: await this._getAuthorizationHeader(),
                "OpenAI-Organization": await core.Supplier.get(this.options.organization),
                "X-Fern-Language": "JavaScript",
                "X-Fern-SDK-Name": "@fern-api/openai",
                "X-Fern-SDK-Version": "0.0.29",
            },
            contentType: "application/json",
            body: await serializers.CreateFineTuneRequest.jsonOrThrow(request, { unrecognizedObjectKeys: "strip" }),
            timeoutMs: 60000,
        });
        if (_response.ok) {
            return await serializers.FineTune.parseOrThrow(_response.body, {
                unrecognizedObjectKeys: "passthrough",
                allowUnrecognizedUnionMembers: true,
                allowUnrecognizedEnumValues: true,
            });
        }
        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new OpenAI.UnauthorizedError();
                case 429:
                    throw new OpenAI.RateLimitError();
                case 500:
                    throw new OpenAI.InternalServerError();
                default:
                    throw new errors.OpenAIError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                    });
            }
        }
        switch (_response.error.reason) {
            case "non-json":
                throw new errors.OpenAIError({
                    statusCode: _response.error.statusCode,
                    body: _response.error.rawBody,
                });
            case "timeout":
                throw new errors.OpenAITimeoutError();
            case "unknown":
                throw new errors.OpenAIError({
                    message: _response.error.errorMessage,
                });
        }
    }
    /**
     * Gets info about the fine-tune job.
     * [Learn more about Fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)
     *
     * @throws {OpenAI.UnauthorizedError}
     * @throws {OpenAI.RateLimitError}
     * @throws {OpenAI.InternalServerError}
     */
    async retrieve(fineTuneId) {
        const _response = await (this.options.fetcher ?? core.fetcher)({
            url: (0, url_join_1.default)(environments.OpenAIEnvironment.Production, `/fine-tunes/${await serializers.FineTuneId.jsonOrThrow(fineTuneId)}`),
            method: "GET",
            headers: {
                Authorization: await this._getAuthorizationHeader(),
                "OpenAI-Organization": await core.Supplier.get(this.options.organization),
                "X-Fern-Language": "JavaScript",
                "X-Fern-SDK-Name": "@fern-api/openai",
                "X-Fern-SDK-Version": "0.0.29",
            },
            contentType: "application/json",
            timeoutMs: 60000,
        });
        if (_response.ok) {
            return await serializers.FineTune.parseOrThrow(_response.body, {
                unrecognizedObjectKeys: "passthrough",
                allowUnrecognizedUnionMembers: true,
                allowUnrecognizedEnumValues: true,
            });
        }
        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new OpenAI.UnauthorizedError();
                case 429:
                    throw new OpenAI.RateLimitError();
                case 500:
                    throw new OpenAI.InternalServerError();
                default:
                    throw new errors.OpenAIError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                    });
            }
        }
        switch (_response.error.reason) {
            case "non-json":
                throw new errors.OpenAIError({
                    statusCode: _response.error.statusCode,
                    body: _response.error.rawBody,
                });
            case "timeout":
                throw new errors.OpenAITimeoutError();
            case "unknown":
                throw new errors.OpenAIError({
                    message: _response.error.errorMessage,
                });
        }
    }
    /**
     * Immediately cancel a fine-tune job.
     * @throws {OpenAI.UnauthorizedError}
     * @throws {OpenAI.RateLimitError}
     * @throws {OpenAI.InternalServerError}
     */
    async cancel(fineTuneId) {
        const _response = await (this.options.fetcher ?? core.fetcher)({
            url: (0, url_join_1.default)(environments.OpenAIEnvironment.Production, `/fine-tunes/${await serializers.FineTuneId.jsonOrThrow(fineTuneId)}/cancel`),
            method: "POST",
            headers: {
                Authorization: await this._getAuthorizationHeader(),
                "OpenAI-Organization": await core.Supplier.get(this.options.organization),
                "X-Fern-Language": "JavaScript",
                "X-Fern-SDK-Name": "@fern-api/openai",
                "X-Fern-SDK-Version": "0.0.29",
            },
            contentType: "application/json",
            timeoutMs: 60000,
        });
        if (_response.ok) {
            return await serializers.FineTune.parseOrThrow(_response.body, {
                unrecognizedObjectKeys: "passthrough",
                allowUnrecognizedUnionMembers: true,
                allowUnrecognizedEnumValues: true,
            });
        }
        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new OpenAI.UnauthorizedError();
                case 429:
                    throw new OpenAI.RateLimitError();
                case 500:
                    throw new OpenAI.InternalServerError();
                default:
                    throw new errors.OpenAIError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                    });
            }
        }
        switch (_response.error.reason) {
            case "non-json":
                throw new errors.OpenAIError({
                    statusCode: _response.error.statusCode,
                    body: _response.error.rawBody,
                });
            case "timeout":
                throw new errors.OpenAITimeoutError();
            case "unknown":
                throw new errors.OpenAIError({
                    message: _response.error.errorMessage,
                });
        }
    }
    async listEvents(fineTuneId, request = {}, cb, opts) {
        const { stream } = request;
        const _queryParams = new url_search_params_1.default();
        if (stream != null) {
            _queryParams.append("stream", stream.toString());
        }
        if (stream) {
            const _queue = new core.CallbackQueue();
            return await (this.options.streamingFetcher ?? core.streamingFetcher)({
                url: (0, url_join_1.default)(environments.OpenAIEnvironment.Production, `/fine-tunes/${await serializers.FineTuneId.jsonOrThrow(fineTuneId)}/events`),
                method: "GET",
                headers: {
                    Authorization: await this._getAuthorizationHeader(),
                    "OpenAI-Organization": await core.Supplier.get(this.options.organization),
                    "X-Fern-Language": "JavaScript",
                    "X-Fern-SDK-Name": "@fern-api/openai",
                    "X-Fern-SDK-Version": "0.0.29",
                },
                queryParameters: _queryParams,
                timeoutMs: 60000,
                onData: _queue.wrap(async (data) => {
                    const parsed = await serializers.FineTune.parse(data, {
                        unrecognizedObjectKeys: "passthrough",
                        allowUnrecognizedUnionMembers: true,
                        allowUnrecognizedEnumValues: true,
                    });
                    if (parsed.ok) {
                        cb?.(parsed.value);
                    }
                    else {
                        opts?.onError?.(parsed.errors);
                    }
                }),
                onError: opts?.onError != null ? _queue.wrap(opts.onError) : undefined,
                onFinish: opts?.onFinish != null ? _queue.wrap(opts.onFinish) : undefined,
                abortController: opts?.abortController,
                terminator: "[DONE]",
            });
        }
        else {
            const _response = await (this.options.fetcher ?? core.fetcher)({
                url: (0, url_join_1.default)(environments.OpenAIEnvironment.Production, `/fine-tunes/${await serializers.FineTuneId.jsonOrThrow(fineTuneId)}/events`),
                method: "GET",
                headers: {
                    Authorization: await this._getAuthorizationHeader(),
                    "OpenAI-Organization": await core.Supplier.get(this.options.organization),
                    "X-Fern-Language": "JavaScript",
                    "X-Fern-SDK-Name": "@fern-api/openai",
                    "X-Fern-SDK-Version": "0.0.29",
                },
                contentType: "application/json",
                queryParameters: _queryParams,
                timeoutMs: 60000,
            });
            if (_response.ok) {
                return await serializers.ListFineTuneEventsResponse.parseOrThrow(_response.body, {
                    unrecognizedObjectKeys: "passthrough",
                    allowUnrecognizedUnionMembers: true,
                    allowUnrecognizedEnumValues: true,
                });
            }
            if (_response.error.reason === "status-code") {
                switch (_response.error.statusCode) {
                    case 401:
                        throw new OpenAI.UnauthorizedError();
                    case 429:
                        throw new OpenAI.RateLimitError();
                    case 500:
                        throw new OpenAI.InternalServerError();
                    default:
                        throw new errors.OpenAIError({
                            statusCode: _response.error.statusCode,
                            body: _response.error.body,
                        });
                }
            }
            switch (_response.error.reason) {
                case "non-json":
                    throw new errors.OpenAIError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.rawBody,
                    });
                case "timeout":
                    throw new errors.OpenAITimeoutError();
                case "unknown":
                    throw new errors.OpenAIError({
                        message: _response.error.errorMessage,
                    });
            }
        }
    }
    async _getAuthorizationHeader() {
        const bearer = await core.Supplier.get(this.options.token);
        if (bearer != null) {
            return `Bearer ${bearer}`;
        }
        return undefined;
    }
}
exports.FineTune = FineTune;
