Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

24.9 KB
Raw Blame
import asyncio
import json
from typing import Optional
from unittest.mock import AsyncMock, MagicMock, patch

import google.auth
import google.auth.credentials
import httpx
import pytest
import respx

import litellm
from tests._vcr_conftest_common import install_live_call_probe, record_vcr_outcome

from litellm.integrations.custom_logger import CustomLogger
from litellm.llms.vertex_ai.fine_tuning.handler import (
    FineTuningJobCreate,
    VertexFineTuningAPI,
)
from litellm.types.llms.openai import Hyperparameters
from litellm.types.utils import StandardLoggingPayload


@pytest.fixture(autouse=True)
def isolate_fine_tuning_retries(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(litellm, "num_retries", 0)


vertex_finetune_api = VertexFineTuningAPI()


class TestCustomLogger(CustomLogger):
    def __init__(self):
        super().__init__()
        self.standard_logging_object: Optional[StandardLoggingPayload] = None

    async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
        print(
            "Success event logged with kwargs=",
            kwargs,
            "and response_obj=",
            response_obj,
        )
        self.standard_logging_object = kwargs["standard_logging_object"]


@pytest.mark.asyncio()
@pytest.mark.parametrize("model_prefix", ["", "vertex_ai/"], ids=["bare", "provider-prefixed"])
async def test_create_vertex_fine_tune_jobs_mocked(model_prefix: str):
    # Define reusable variables for the test
    project_id = "633608382793"
    location = "us-central1"
    job_id = "3978211980451250176"
    base_model = "gemini-1.0-pro-002"
    tuned_model_name = f"{base_model}-f9259f2c-3fdf-4dd3-9413-afef2bfd24f5"
    training_file = "gs://cloud-samples-data/ai-platform/generative_ai/sft_train_data.jsonl"
    create_time = "2024-12-31T22:40:20.211140Z"

    mock_response = AsyncMock()
    mock_response.status_code = 200
    mock_response.json = MagicMock(
        return_value={
            "name": f"projects/{project_id}/locations/{location}/tuningJobs/{job_id}",
            "tunedModelDisplayName": tuned_model_name,
            "baseModel": base_model,
            "supervisedTuningSpec": {"trainingDatasetUri": training_file},
            "state": "JOB_STATE_PENDING",
            "createTime": create_time,
            "updateTime": create_time,
        }
    )

    # Save original callbacks to restore later
    original_callbacks = litellm.callbacks
    original_success_callback = litellm.success_callback
    original_async_success_callback = litellm._async_success_callback
    # Disable all callbacks to avoid Datadog/other loggers interfering with the mock
    litellm.callbacks = []
    litellm.success_callback = []
    litellm._async_success_callback = []

    try:
        with (
            patch(
                "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.post",
                return_value=mock_response,
            ) as mock_post,
            patch(
                "litellm.llms.vertex_ai.vertex_llm_base.VertexBase._ensure_access_token",
                return_value=("fake-token", project_id),
            ),
        ):
            create_fine_tuning_response = await litellm.acreate_fine_tuning_job(
                model=f"{model_prefix}{base_model}",
                custom_llm_provider="vertex_ai",
                training_file=training_file,
                vertex_project=project_id,
                vertex_location=location,
            )

            # Verify the request - filter to only Vertex AI calls (Datadog batch logger
            # may flush in the background and make additional POST calls)
            vertex_calls = [
                c for c in mock_post.call_args_list if "aiplatform.googleapis.com" in str(c.kwargs.get("url", ""))
            ]
            assert len(vertex_calls) == 1

            # Validate the request
            assert vertex_calls[0].kwargs["json"] == {
                "baseModel": base_model,
                "supervisedTuningSpec": {"training_dataset_uri": training_file},
                "tunedModelDisplayName": None,
            }

            # Verify the response
            response_json = json.loads(create_fine_tuning_response.model_dump_json())
            assert response_json["id"] == f"projects/{project_id}/locations/{location}/tuningJobs/{job_id}"
            assert response_json["model"] == base_model
            assert response_json["object"] == "fine_tuning.job"
            assert response_json["fine_tuned_model"] == tuned_model_name
            assert response_json["status"] == "queued"
            assert response_json["training_file"] == training_file
            assert response_json["created_at"] == 1735684820  # Unix timestamp for create_time
            assert response_json["error"] is None
            assert response_json["finished_at"] is None
            assert response_json["validation_file"] is None
            assert response_json["trained_tokens"] is None
            assert response_json["estimated_finish"] is None
            assert response_json["integrations"] == []
    finally:
        # Restore original callbacks
        litellm.callbacks = original_callbacks
        litellm.success_callback = original_success_callback
        litellm._async_success_callback = original_async_success_callback


@pytest.mark.asyncio()
async def test_create_vertex_fine_tune_jobs_mocked_with_hyperparameters():
    # Define reusable variables for the test
    project_id = "633608382793"
    location = "us-central1"
    job_id = "3978211980451250176"
    base_model = "gemini-1.0-pro-002"
    tuned_model_name = f"{base_model}-f9259f2c-3fdf-4dd3-9413-afef2bfd24f5"
    training_file = "gs://cloud-samples-data/ai-platform/generative_ai/sft_train_data.jsonl"
    create_time = "2024-12-31T22:40:20.211140Z"

    mock_response = AsyncMock()
    mock_response.status_code = 200
    mock_response.json = MagicMock(
        return_value={
            "name": f"projects/{project_id}/locations/{location}/tuningJobs/{job_id}",
            "tunedModelDisplayName": tuned_model_name,
            "baseModel": base_model,
            "supervisedTuningSpec": {"trainingDatasetUri": training_file},
            "state": "JOB_STATE_PENDING",
            "createTime": create_time,
            "updateTime": create_time,
        }
    )

    # Save original callbacks to restore later
    original_callbacks = litellm.callbacks
    original_success_callback = litellm.success_callback
    original_async_success_callback = litellm._async_success_callback
    # Disable all callbacks to avoid Datadog/other loggers interfering with the mock
    litellm.callbacks = []
    litellm.success_callback = []
    litellm._async_success_callback = []

    try:
        with (
            patch(
                "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.post",
                return_value=mock_response,
            ) as mock_post,
            patch(
                "litellm.llms.vertex_ai.vertex_llm_base.VertexBase._ensure_access_token",
                return_value=("fake-token", project_id),
            ),
        ):
            create_fine_tuning_response = await litellm.acreate_fine_tuning_job(
                model=base_model,
                custom_llm_provider="vertex_ai",
                training_file=training_file,
                vertex_project=project_id,
                vertex_location=location,
                hyperparameters={
                    "n_epochs": 5,
                    "learning_rate_multiplier": 0.2,
                    "adapter_size": "SMALL",
                },
            )

            # Verify the request - filter to only Vertex AI calls (Datadog batch logger
            # may flush in the background and make additional POST calls)
            vertex_calls = [
                c for c in mock_post.call_args_list if "aiplatform.googleapis.com" in str(c.kwargs.get("url", ""))
            ]
            assert len(vertex_calls) == 1

            # Validate the request
            assert vertex_calls[0].kwargs["json"] == {
                "baseModel": base_model,
                "supervisedTuningSpec": {
                    "training_dataset_uri": training_file,
                    "hyperParameters": {
                        "epoch_count": 5,
                        "learning_rate_multiplier": 0.2,
                        "adapter_size": "SMALL",
                    },
                },
                "tunedModelDisplayName": None,
            }

            # Verify the response
            response_json = json.loads(create_fine_tuning_response.model_dump_json())
            assert response_json["id"] == f"projects/{project_id}/locations/{location}/tuningJobs/{job_id}"
            assert response_json["model"] == base_model
            assert response_json["object"] == "fine_tuning.job"
            assert response_json["fine_tuned_model"] == tuned_model_name
            assert response_json["status"] == "queued"
            assert response_json["training_file"] == training_file
            assert response_json["created_at"] == 1735684820  # Unix timestamp for create_time
            assert response_json["error"] is None
            assert response_json["finished_at"] is None
            assert response_json["validation_file"] is None
            assert response_json["trained_tokens"] is None
            assert response_json["estimated_finish"] is None
            assert response_json["integrations"] == []
    finally:
        # Restore original callbacks
        litellm.callbacks = original_callbacks
        litellm.success_callback = original_success_callback
        litellm._async_success_callback = original_async_success_callback


# Testing OpenAI -> Vertex AI param mapping


def test_convert_openai_request_to_vertex_basic():
    openai_data = FineTuningJobCreate(
        training_file="gs://bucket/train.jsonl",
        validation_file="gs://bucket/val.jsonl",
        model="text-davinci-002",
        hyperparameters={"n_epochs": 3, "learning_rate_multiplier": 0.1},
        suffix="my_fine_tuned_model",
    )

    result = vertex_finetune_api.convert_openai_request_to_vertex(openai_data)

    print("converted vertex ai result=", json.dumps(result, indent=4))

    assert result["baseModel"] == "text-davinci-002"
    assert result["tunedModelDisplayName"] == "my_fine_tuned_model"
    assert result["supervisedTuningSpec"]["training_dataset_uri"] == "gs://bucket/train.jsonl"
    assert result["supervisedTuningSpec"]["validation_dataset"] == "gs://bucket/val.jsonl"
    assert result["supervisedTuningSpec"]["hyperParameters"]["epoch_count"] == 3
    assert result["supervisedTuningSpec"]["hyperParameters"]["learning_rate_multiplier"] == 0.1


def test_convert_openai_request_to_vertex_with_adapter_size():
    original_hyperparameters = {
        "n_epochs": 5,
        "learning_rate_multiplier": 0.2,
        "adapter_size": "SMALL",
    }
    openai_data = FineTuningJobCreate(
        training_file="gs://bucket/train.jsonl",
        model="text-davinci-002",
        hyperparameters=Hyperparameters(**original_hyperparameters),
        suffix="custom_model",
    )

    result = vertex_finetune_api.convert_openai_request_to_vertex(
        openai_data, original_hyperparameters=original_hyperparameters
    )

    print("converted vertex ai result=", json.dumps(result, indent=4))

    assert result["baseModel"] == "text-davinci-002"
    assert result["tunedModelDisplayName"] == "custom_model"
    assert result["supervisedTuningSpec"]["training_dataset_uri"] == "gs://bucket/train.jsonl"
    assert result["supervisedTuningSpec"]["hyperParameters"]["epoch_count"] == 5
    assert result["supervisedTuningSpec"]["hyperParameters"]["learning_rate_multiplier"] == 0.2
    assert result["supervisedTuningSpec"]["hyperParameters"]["adapter_size"] == "SMALL"


def test_convert_basic_openai_request_to_vertex_request():
    openai_data = FineTuningJobCreate(
        training_file="gs://bucket/train.jsonl",
        model="gemini-1.0-pro-002",
    )

    result = vertex_finetune_api.convert_openai_request_to_vertex(
        openai_data,
    )

    print("converted vertex ai result=", json.dumps(result, indent=4))

    assert result["baseModel"] == "gemini-1.0-pro-002"
    assert result["tunedModelDisplayName"] == None
    assert result["supervisedTuningSpec"]["training_dataset_uri"] == "gs://bucket/train.jsonl"


@pytest.mark.asyncio
async def test_mock_openai_create_fine_tune_job():
    """Test that create_fine_tuning_job sends correct parameters to OpenAI"""
    from openai import AsyncOpenAI
    from openai.types.fine_tuning.fine_tuning_job import FineTuningJob, Hyperparameters

    custom_logger = TestCustomLogger()
    previous_callbacks = litellm.callbacks
    litellm.callbacks = [custom_logger]
    client = AsyncOpenAI(api_key="fake-api-key")

    with patch.object(client.fine_tuning.jobs, "create") as mock_create:
        mock_create.return_value = FineTuningJob(
            id="ft-123",
            model="gpt-4o-mini-2024-07-18",
            created_at=1677610602,
            status="validating_files",
            fine_tuned_model="ft:gpt-4o-mini-2024-07-18:org:custom_suffix:id",
            object="fine_tuning.job",
            hyperparameters=Hyperparameters(
                n_epochs=3,
            ),
            organization_id="org-123",
            seed=42,
            training_file="file-123",
            result_files=[],
        )

        response = await litellm.acreate_fine_tuning_job(
            model="gpt-4o-mini-2024-07-18",
            training_file="file-123",
            hyperparameters={"n_epochs": 3},
            suffix="custom_suffix",
            client=client,
        )

        # Verify the request
        mock_create.assert_called_once()
        request_params = mock_create.call_args.kwargs

        assert request_params["model"] == "gpt-4o-mini-2024-07-18"
        assert request_params["training_file"] == "file-123"
        assert request_params["hyperparameters"] == {"n_epochs": 3}
        assert request_params["suffix"] == "custom_suffix"

        # Verify the response
        assert response.id == "ft-123"
        assert response.model == "gpt-4o-mini-2024-07-18"
        assert response.status == "validating_files"
        assert response.fine_tuned_model == "ft:gpt-4o-mini-2024-07-18:org:custom_suffix:id"

    try:
        for _ in range(20):
            if custom_logger.standard_logging_object is not None:
                break
            await asyncio.sleep(0.25)
        logged = custom_logger.standard_logging_object
        assert logged is not None
        assert logged["model"] == "gpt-4o-mini-2024-07-18"
        assert logged["id"] == response.id
        assert logged["call_type"] == "acreate_fine_tuning_job"
    finally:
        litellm.callbacks = previous_callbacks


@pytest.mark.asyncio
async def test_mock_openai_list_fine_tune_jobs():
    """Test that list_fine_tuning_jobs sends correct parameters to OpenAI"""
    from unittest.mock import AsyncMock

    from openai import AsyncOpenAI

    client = AsyncOpenAI(api_key="fake-api-key")

    with patch.object(client.fine_tuning.jobs, "list", new_callable=AsyncMock) as mock_list:
        # Simple mock return value - actual structure doesn't matter for this test
        mock_list.return_value = []

        await litellm.alist_fine_tuning_jobs(limit=2, after="ft-000", client=client)

        # Only verify that the client was called with correct parameters
        mock_list.assert_called_once()
        request_params = mock_list.call_args.kwargs

        assert request_params["limit"] == 2
        assert request_params["after"] == "ft-000"


@pytest.mark.asyncio
async def test_mock_openai_cancel_fine_tune_job():
    """Test that cancel_fine_tuning_job sends correct parameters to OpenAI"""
    from openai import AsyncOpenAI

    client = AsyncOpenAI(api_key="fake-api-key")

    with patch.object(client.fine_tuning.jobs, "cancel") as mock_cancel:
        try:
            await litellm.acancel_fine_tuning_job(fine_tuning_job_id="ft-123", client=client)
        except Exception as e:
            print("error=", e)

        # Only verify that the client was called with correct parameters
        mock_cancel.assert_called_once_with(fine_tuning_job_id="ft-123")


@pytest.mark.asyncio
async def test_mock_openai_retrieve_fine_tune_job():
    """Test that retrieve_fine_tuning_job sends correct parameters to OpenAI"""
    from openai import AsyncOpenAI

    client = AsyncOpenAI(api_key="fake-api-key")

    with patch.object(client.fine_tuning.jobs, "retrieve") as mock_retrieve:
        try:
            response = await litellm.aretrieve_fine_tuning_job(fine_tuning_job_id="ft-123", client=client)
        except Exception as e:
            print("error=", e)

        # Verify the request
        mock_retrieve.assert_called_once_with(fine_tuning_job_id="ft-123")


@pytest.mark.asyncio
async def test_mock_azure_create_fine_tune_job_with_azure_specific_params():
    """Test that Azure-specific parameters are passed through extra_body"""
    from openai.types.fine_tuning.fine_tuning_job import (
        Hyperparameters as OAIHyperparameters,
    )

    from litellm.types.utils import LiteLLMFineTuningJob

    mock_response = LiteLLMFineTuningJob(
        id="ft-azure-123",
        model="gpt-4.1-mini-2025-04-14",
        created_at=1677610602,
        status="validating_files",
        fine_tuned_model=None,
        object="fine_tuning.job",
        hyperparameters=OAIHyperparameters(n_epochs=3),
        organization_id="org-123",
        seed=42,
        training_file="file-123",
        result_files=[],
    )

    async def mock_async_create(*args, **kwargs):
        return mock_response

    with patch("litellm.llms.azure.fine_tuning.handler.AzureOpenAIFineTuningAPI.create_fine_tuning_job") as mock_create:
        mock_create.return_value = mock_async_create()

        response = await litellm.acreate_fine_tuning_job(
            model="gpt-4.1-mini-2025-04-14",
            training_file="file-123",
            custom_llm_provider="azure",
            api_base="https://test.openai.azure.com",
            api_key="test-key",
            api_version="2025-04-01-preview",
            trainingType=1,
            hyperparameters={"n_epochs": 3, "prompt_loss_weight": 0.1},
        )

        # Verify the request
        mock_create.assert_called_once()
        request_params = mock_create.call_args.kwargs

        # Check that create_fine_tuning_job_data contains the correct structure
        create_data = request_params["create_fine_tuning_job_data"]
        assert create_data["model"] == "gpt-4.1-mini-2025-04-14"
        assert create_data["training_file"] == "file-123"
        assert create_data["hyperparameters"] == {"n_epochs": 3}

        # Azure-specific parameters should be in extra_body
        assert "extra_body" in create_data
        assert create_data["extra_body"]["trainingType"] == 1
        assert create_data["extra_body"]["prompt_loss_weight"] == 0.1

        # Verify the response
        assert response.id == "ft-azure-123"
        assert response.model == "gpt-4.1-mini-2025-04-14"


@pytest.fixture(autouse=True)
def _vcr_outcome_gate(request, vcr):
    install_live_call_probe(request, vcr)
    yield
    record_vcr_outcome(request, vcr)


@pytest.fixture(scope="session")
def event_loop():
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = asyncio.new_event_loop()
    yield loop
    loop.close()


@pytest.fixture(scope="function", autouse=True)
def setup_and_teardown(event_loop):
    original_state = _copy_litellm_state()
    _clear_logging_queue(event_loop)
    _reset_litellm_callbacks()
    asyncio.set_event_loop(event_loop)
    yield
    _clear_logging_queue(event_loop)
    _reset_litellm_callbacks()
    _restore_litellm_state(original_state)
    pending = asyncio.all_tasks(event_loop)
    for task in pending:
        task.cancel()
    if pending:
        event_loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))


def _copy_litellm_state():
    state = {}
    for attr in _CALLBACK_ATTRS:
        if hasattr(litellm, attr):
            value = getattr(litellm, attr)
            state[attr] = value.copy() if isinstance(value, list) else value
    for attr in _SCALAR_ATTRS:
        if hasattr(litellm, attr):
            state[attr] = getattr(litellm, attr)
    return state


_CALLBACK_ATTRS = (
    "callbacks",
    "success_callback",
    "failure_callback",
    "_async_success_callback",
    "_async_failure_callback",
)

_SCALAR_ATTRS = (
    "num_retries",
    "set_verbose",
    "cache",
    "allowed_fails",
    "disable_aiohttp_transport",
    "force_ipv4",
    "drop_params",
    "modify_params",
    "api_base",
    "api_key",
    "cohere_key",
)


def _clear_logging_queue(loop=None) -> None:
    from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER

    if loop is not None and (not loop.is_closed()) and (not loop.is_running()):
        loop.run_until_complete(GLOBAL_LOGGING_WORKER.clear_queue())
        return
    asyncio.run(GLOBAL_LOGGING_WORKER.clear_queue())


def _reset_litellm_callbacks() -> None:
    for attr in _CALLBACK_ATTRS:
        if hasattr(litellm, attr):
            setattr(litellm, attr, [])
    manager = getattr(litellm, "logging_callback_manager", None)
    reset = getattr(manager, "_reset_all_callbacks", None)
    if callable(reset):
        reset()


def _restore_litellm_state(state) -> None:
    for attr, value in state.items():
        if hasattr(litellm, attr):
            setattr(litellm, attr, value)


_VERTEX_TUNING_JOB = {
    "name": "projects/test-project/locations/us-central1/tuningJobs/42",
    "tunedModelDisplayName": "gemini-1.0-pro-002-tuned",
    "baseModel": "gemini-1.0-pro-002",
    "supervisedTuningSpec": {"trainingDatasetUri": "gs://bucket/train.jsonl"},
    "state": "JOB_STATE_RUNNING",
    "createTime": "2024-12-31T22:40:20.211140Z",
    "updateTime": "2024-12-31T22:40:20.211140Z",
}
_BOTH_CALL_STYLES = pytest.mark.parametrize("run_async", [False, True], ids=["sync", "async"])


class _StaticGoogleCredentials(google.auth.credentials.Credentials):
    def refresh(self, request):
        self.token = "test-token"


@pytest.fixture
def vertex_tuning_endpoint(respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch) -> respx.Route:
    monkeypatch.setattr(google.auth, "default", lambda scopes: (_StaticGoogleCredentials(), "test-project"))
    monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
    return respx_mock.post(host="us-central1-aiplatform.googleapis.com")


def _vertex_json_response(payload: object) -> httpx.Response:
    return httpx.Response(200, content=json.dumps(payload).encode())


async def _created_vertex_tuning_job(run_async: bool, endpoint: respx.Route, payload: object):
    endpoint.mock(return_value=_vertex_json_response(payload))
    pending = VertexFineTuningAPI().create_fine_tuning_job(
        _is_async=run_async,
        create_fine_tuning_job_data=FineTuningJobCreate(
            training_file="gs://bucket/train.jsonl", model="gemini-1.0-pro-002"
        ),
        vertex_project="test-project",
        vertex_location="us-central1",
        vertex_credentials=None,
        api_base=None,
        timeout=600.0,
    )
    return await pending if run_async else pending


@_BOTH_CALL_STYLES
@pytest.mark.asyncio()
async def test_vertex_fine_tuning_job_creation_returns_the_tuning_job_as_an_openai_job(
    run_async: bool, vertex_tuning_endpoint: respx.Route
):
    job = await _created_vertex_tuning_job(run_async, vertex_tuning_endpoint, _VERTEX_TUNING_JOB)

    assert (job.id, job.created_at, job.fine_tuned_model, job.model, job.status, job.training_file) == (
        "projects/test-project/locations/us-central1/tuningJobs/42",
        1735684820,
        "gemini-1.0-pro-002-tuned",
        "gemini-1.0-pro-002",
        "running",
        "gs://bucket/train.jsonl",
    )


@_BOTH_CALL_STYLES
@pytest.mark.parametrize("body", [[_VERTEX_TUNING_JOB], [["state", "JOB_STATE_RUNNING"]], "state", 403, 2.5, None])
@pytest.mark.asyncio()
async def test_vertex_fine_tuning_job_creation_reports_a_tuning_job_body_that_is_not_an_object_as_a_type_error(
    run_async: bool, vertex_tuning_endpoint: respx.Route, body: object
):
    with pytest.raises(TypeError, match=r"argument after \*\* must be a mapping"):
        await _created_vertex_tuning_job(run_async, vertex_tuning_endpoint, body)


@pytest.mark.parametrize(
    "body",
    [
        _VERTEX_TUNING_JOB,
        {"candidates": [{"content": {"parts": [{"text": "hello"}]}}], "usageMetadata": {"totalTokenCount": 3}},
        {},
        [{"a": 1}, 2, "x", None],
        "text",
        403,
        2.5,
        True,
        None,
    ],
)
@pytest.mark.asyncio()
async def test_vertex_passthrough_post_returns_the_upstream_json_body_unchanged(
    vertex_tuning_endpoint: respx.Route, body: object
):
    vertex_tuning_endpoint.mock(return_value=_vertex_json_response(body))

    returned = await VertexFineTuningAPI().pass_through_vertex_ai_POST_request(
        request_data={"baseModel": "gemini-1.0-pro-002"},
        vertex_project="test-project",
        vertex_location="us-central1",
        vertex_credentials=None,
        request_route="/tuningJobs",
    )

    assert (type(returned), returned) == (type(body), body)