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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(managed_files): send provider file ids when creating a fine-tuning job from managed files (#46552)
yucheng-berri6162184b1ce2
diff --git a/.github/workflows/test-unit.yml b/.github/workflows/test-unit.ymlindex cb1b595f3f0..5e42f182345 100644--- a/.github/workflows/test-unit.yml+++ b/.github/workflows/test-unit.yml@@ -410,6 +410,7 @@ jobs:tests/unit/embeddingstests/unit/endpointstests/unit/files+ tests/unit/fine_tuningtests/unit/imagestests/unit/interactionstests/unit/messagesdiff --git a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py b/enterprise/litellm_enterprise/proxy/hooks/managed_files.pyindex 439770390f8..bc35c4a0aba 100644--- a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py+++ b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py@@ -6,6 +6,7 @@ import base64import jsonimport timefrom collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence+from itertools import chainfrom types import MappingProxyTypefrom typing import (TYPE_CHECKING,@@ -479,6 +480,13 @@ def _with_managed_background_marker(request: Mapping[str, object]) -> dict[str,_MANAGED_FILES_TARGET: Final = "managed_files"+_PROVIDER_FILE_ID_KWARGS: Final = MappingProxyType(+ {+ CallTypes.acreate_batch: ("input_file_id",),+ CallTypes.acreate_fine_tuning_job: ("training_file", "validation_file"),+ }+)+_PROVIDER_FILE_ID_KEYS: Final = tuple(dict.fromkeys(chain.from_iterable(_PROVIDER_FILE_ID_KWARGS.values())))_PROVIDER_FILE_RETRIEVE_RETRY_DELAYS_SECONDS: Final = (0.5, 1.0, 2.0)@@ -1562,6 +1570,10 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):if isinstance(file_id, str) and file_id)await self.check_file_ids_access(fine_tuning_file_ids, user_api_key_dict)+ if fine_tuning_file_ids:+ data["model_file_id_mapping"] = await self.get_model_file_id_mapping(+ fine_tuning_file_ids, user_api_key_dict.parent_otel_span+ )return data@@ -1576,24 +1588,27 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):if request_kwargs is None:return healthy_deployments- input_file_id = cast(Optional[str], request_kwargs.get("input_file_id"))- model_file_id_mapping = cast(- Optional[Dict[str, Dict[str, str]]],- request_kwargs.get("model_file_id_mapping"),+ request: Final = cast(Mapping[str, object], request_kwargs)+ model_file_id_mapping: Final = cast(Mapping[str, Mapping[str, str]], request.get("model_file_id_mapping") or {})+ requested_file_ids: Final = (request.get(key) for key in _PROVIDER_FILE_ID_KEYS)+ model_ids_per_file: Final = tuple(+ frozenset(model_file_id_mapping[file_id])+ for file_id in requested_file_ids+ if isinstance(file_id, str) and file_id in model_file_id_mapping+ )+ allowed_model_ids: Final[frozenset[str]] = (+ model_ids_per_file[0].intersection(*model_ids_per_file[1:]) if model_ids_per_file else frozenset())- allowed_model_ids = []- if input_file_id and model_file_id_mapping:- model_id_dict = model_file_id_mapping.get(input_file_id, {})- allowed_model_ids = list(model_id_dict.keys())if len(allowed_model_ids) == 0:return healthy_deployments- return [+ holders: Final[list[dict[str, object]]] = [deploymentfor deployment in healthy_deploymentsif deployment.get("model_info", {}).get("id") in allowed_model_ids]+ return holders if holders or "input_file_id" in request else healthy_deploymentsasync def async_pre_call_deployment_hook(self, kwargs: Dict[str, Any], call_type: Optional[CallTypes]@@ -1601,25 +1616,21 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):"""Allow modifying the request just before it's sent to the deployment."""- accessor_key: Optional[str] = None- if call_type and call_type == CallTypes.acreate_batch:- accessor_key = "input_file_id"- elif call_type and call_type == CallTypes.acreate_fine_tuning_job:- accessor_key = "training_file"- else:+ accessor_keys: Final = _PROVIDER_FILE_ID_KWARGS.get(call_type) if call_type else None+ if accessor_keys is None:return kwargs- if accessor_key:+ model_file_id_mapping = cast(Optional[Dict[str, Dict[str, str]]], kwargs.get("model_file_id_mapping"))+ # model_info may be at top-level or nested under litellm_metadata+ # (batch/file operations use litellm_metadata)+ model_id = cast(Optional[str], kwargs.get("model_info", {}).get("id", None))+ if model_id is None:+ model_id = cast(+ Optional[str],+ kwargs.get("litellm_metadata", {}).get("model_info", {}).get("id", None),+ )+ for accessor_key in accessor_keys:input_file_id = cast(Optional[str], kwargs.get(accessor_key))- model_file_id_mapping = cast(Optional[Dict[str, Dict[str, str]]], kwargs.get("model_file_id_mapping"))- # model_info may be at top-level or nested under litellm_metadata- # (batch/file operations use litellm_metadata)- model_id = cast(Optional[str], kwargs.get("model_info", {}).get("id", None))- if model_id is None:- model_id = cast(- Optional[str],- kwargs.get("litellm_metadata", {}).get("model_info", {}).get("id", None),- )mapped_file_id: Optional[str] = Noneif input_file_id and model_file_id_mapping and model_id:mapped_file_id = model_file_id_mapping.get(input_file_id, {}).get(model_id, None)@@ -1813,7 +1824,7 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):),)- async def get_model_file_id_mapping(self, file_ids: List[str], litellm_parent_otel_span: Span) -> dict:+ async def get_model_file_id_mapping(self, file_ids: Sequence[str], litellm_parent_otel_span: Span) -> dict:"""Get model-specific file IDs for a list of proxy file IDs.Returns a dictionary mapping litellm_proxy/ file_id -> model_id -> model_file_iddiff --git a/litellm/fine_tuning/main.py b/litellm/fine_tuning/main.pyindex 5297a8215be..f49f069b83f 100644--- a/litellm/fine_tuning/main.py+++ b/litellm/fine_tuning/main.py@@ -173,6 +173,7 @@ def create_fine_tuning_job(try:_is_async: Final = kwargs.pop("acreate_fine_tuning_job", False) is Trueoptional_params: Final = GenericLiteLLMParams(**kwargs)+ provider_model: Final = model.removeprefix(f"{custom_llm_provider}/")# handle hyperparametershyperparameters = hyperparameters or {} # original hyperparameters@@ -218,7 +219,7 @@ def create_fine_tuning_job()create_fine_tuning_job_data_dict = _build_fine_tuning_job_data(- model,+ provider_model,training_file,_oai_hyperparameters,suffix,@@ -263,7 +264,7 @@ def create_fine_tuning_job(extra_body = _prepare_azure_extra_body(extra_body, kwargs, azure_specific_hyperparams)create_fine_tuning_job_data_dict = _build_fine_tuning_job_data(- model,+ provider_model,training_file,_oai_hyperparameters,suffix,@@ -298,7 +299,7 @@ def create_fine_tuning_job(response = vertex_fine_tuning_apis_instance.create_fine_tuning_job(_is_async=_is_async,create_fine_tuning_job_data=_build_fine_tuning_job_data(- model,+ provider_model,training_file,_oai_hyperparameters,suffix,diff --git a/litellm/proxy/fine_tuning_endpoints/endpoints.py b/litellm/proxy/fine_tuning_endpoints/endpoints.pyindex d015112cf3a..030f8d7a46a 100644--- a/litellm/proxy/fine_tuning_endpoints/endpoints.py+++ b/litellm/proxy/fine_tuning_endpoints/endpoints.py@@ -164,7 +164,8 @@ async def create_fine_tuning_job()response = cast(LiteLLMFineTuningJob, await llm_router.acreate_fine_tuning_job(**data))- response.training_file = unified_file_id+ response.training_file = training_file+ response.validation_file = fine_tuning_request.validation_fileset_hidden_param(response, "unified_file_id", unified_file_id)## ELSE, Route based on custom_llm_providerelif fine_tuning_request.custom_llm_provider:diff --git a/tests/integration/compatibility/test_fine_tuning_jobs.py b/tests/integration/compatibility/test_fine_tuning_jobs.pyindex 9678198352f..1eff386b8ba 100644--- a/tests/integration/compatibility/test_fine_tuning_jobs.py+++ b/tests/integration/compatibility/test_fine_tuning_jobs.py@@ -27,7 +27,6 @@ MANAGED_MODEL: Final = "gpt-4.1-openai"DEPLOYMENT_KEYS: Final = ("sk-fine-tuning-deployment-a", "sk-fine-tuning-deployment-b")PROVIDER_JOB: Final = "ftjob-provider-123"RUN: Final = uuid.uuid4().hex[:12]-MANAGED_JOB: Final = f"ftjob-managed-{RUN}"TRAINING_LINE: Final = b'{"messages": [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"}]}\n'JOB_PATH: Final = re.compile(r"^/(?:openai/)?(?:v1/)?fine_tuning/jobs/([^/]+)(/cancel)?$")JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])@@ -88,8 +87,18 @@ def _job(job_id: str, status: str, training_file: str = "file-abc123", **fields:}-def _provider_file_id(bearer: str) -> str:- return f"file-{RUN}-" + bearer.removeprefix("sk-fine-tuning-")+def _provider_file_id(bearer: str, filename: str) -> str:+ return f"file-{RUN}-" + bearer.removeprefix("sk-fine-tuning-") + "-" + filename.removesuffix(".jsonl")+++def _managed_job_id(provider_training_file: str) -> str:+ return provider_training_file.replace("file-", "ftjob-managed-", 1)+++def _uploaded_filename(request: Request) -> str:+ names: Final = [part.get_filename() for part in _multipart_parts(request) if part.get_filename()]+ assert len(names) == 1, request.body[:300]+ return str(names[0])def _bearer(request: Request) -> str:@@ -118,19 +127,27 @@ def _respond(request: Request) -> Reply:if (request.method, path) == ("POST", "/v1/files"):return _reply({- "id": _provider_file_id(_bearer(request)),+ "id": _provider_file_id(_bearer(request), _uploaded_filename(request)),"object": "file","bytes": len(TRAINING_LINE),"created_at": 1700000000,- "filename": "train.jsonl",+ "filename": _uploaded_filename(request),"purpose": "fine-tune","status": "processed",})if (request.method, path) in {("POST", "/v1/fine_tuning/jobs"), ("POST", "/openai/fine_tuning/jobs")}:sent: Final = JSON_OBJECT.validate_json(request.body)- job_id: Final = MANAGED_JOB if _bearer(request) in DEPLOYMENT_KEYS else PROVIDER_JOB- return _reply(_job(job_id, "validating_files", str(sent["training_file"])))+ managed: Final = _bearer(request) in DEPLOYMENT_KEYS+ echoed: Final = {"validation_file": sent.get("validation_file")} if managed else {}+ return _reply(+ _job(+ _managed_job_id(str(sent["training_file"])) if managed else PROVIDER_JOB,+ "validating_files",+ str(sent["training_file"]),+ **echoed,+ )+ )matched: Final = JOB_PATH.match(path)if matched and matched.group(1) and request.method == "GET":return _reply(_job(matched.group(1), "running"))@@ -329,6 +346,30 @@ def test_azure_create_merges_finetune_settings_and_keeps_azure_fields(rig: Rig)assert Job.model_validate_json(raw.text) == _client_job(PROVIDER_JOB, "validating_files", "file-abc"), raw.text+ ("provider", "target", "provider_defaults"),+ [+ ("openai", "/v1/fine_tuning/jobs", {}),+ ("azure", f"/openai/fine_tuning/jobs?api-version={AZURE_API_VERSION}", {"trainingType": 1}),+ ],+)+def test_create_sends_the_model_without_its_provider_prefix(+ rig: Rig, provider: str, target: str, provider_defaults: Mapping[str, JsonValue]+) -> None:+ with rig.sdk("/v1") as client:+ raw: Final = client.fine_tuning.jobs.with_raw_response.create(+ model=f"{provider}/gpt-4o-mini", training_file="file-abc123", extra_body={"custom_llm_provider": provider}+ )+ sent: Final = _only(_drained(rig), "POST", target)+ assert JSON_OBJECT.validate_json(sent.body) == {+ "model": "gpt-4o-mini",+ "training_file": "file-abc123",+ "hyperparameters": {},+ **provider_defaults,+ }, sent.body+ assert raw.status_code == 200, raw.text++def test_azure_cancel_merges_finetune_settings(rig: Rig) -> None:with rig.sdk("/v1") as client:raw: Final = client.fine_tuning.jobs.with_raw_response.cancel(@@ -400,10 +441,6 @@ def test_retrieve_reads_the_documented_custom_llm_provider_header(rig: Rig) -> Ndef test_managed_create_sends_the_provider_file_id_of_the_pinned_deployment(rig: Rig) -> None:- pytest.skip(- "BUG: managed create sends the base64 LiteLLM file id and the prefixed model openai/gpt-4.1 to the provider"- " and returns the decoded unified id as training_file"- )with rig.sdk("/v1") as client:uploaded: Final = client.files.with_raw_response.create(file=("train.jsonl", TRAINING_LINE, "application/jsonl"),@@ -431,12 +468,48 @@ def test_managed_create_sends_the_provider_file_id_of_the_pinned_deployment(rig:assert deployment_key in DEPLOYMENT_KEYS, sent.headersassert JSON_OBJECT.validate_json(sent.body) == {"model": "gpt-4.1",- "training_file": _provider_file_id(deployment_key),+ "training_file": _provider_file_id(deployment_key, "train.jsonl"),"hyperparameters": {},}, sent.bodyassert raw.status_code == 200, raw.textjob: Final = Job.model_validate_json(raw.text)assert re.fullmatch(- rf"litellm_proxy;model_id:[0-9a-f]{{64}};generic_response_id:{MANAGED_JOB}", _decoded(job.id)+ rf"litellm_proxy;model_id:[0-9a-f]{{64}};generic_response_id:"+ rf"{_managed_job_id(_provider_file_id(deployment_key, 'train.jsonl'))}",+ _decoded(job.id),), raw.textassert job.training_file == managed_file, raw.text+++def _managed_upload(rig: Rig, client: OpenAI, filename: str) -> str:+ uploaded: Final = client.files.with_raw_response.create(+ file=(filename, TRAINING_LINE, "application/jsonl"),+ purpose="fine-tune",+ extra_body={"target_model_names": MANAGED_MODEL},+ )+ assert uploaded.status_code == 200, uploaded.text+ assert sorted((request.method, request.target, _bearer(request)) for request in _drained(rig)) == [+ ("POST", "/v1/files", key) for key in DEPLOYMENT_KEYS+ ]+ return str(JSON_OBJECT.validate_json(uploaded.text)["id"])+++def test_managed_create_sends_the_provider_ids_of_managed_training_and_validation_files(rig: Rig) -> None:+ with rig.sdk("/v1") as client:+ training_file: Final = _managed_upload(rig, client, "tune.jsonl")+ validation_file: Final = _managed_upload(rig, client, "validate.jsonl")+ raw: Final = client.fine_tuning.jobs.with_raw_response.create(+ model=MANAGED_MODEL, training_file=training_file, validation_file=validation_file+ )+ sent: Final = _only(_drained(rig), "POST", "/v1/fine_tuning/jobs")+ deployment_key: Final = _bearer(sent)+ assert deployment_key in DEPLOYMENT_KEYS, sent.headers+ assert JSON_OBJECT.validate_json(sent.body) == {+ "model": "gpt-4.1",+ "training_file": _provider_file_id(deployment_key, "tune.jsonl"),+ "validation_file": _provider_file_id(deployment_key, "validate.jsonl"),+ "hyperparameters": {},+ }, sent.body+ assert raw.status_code == 200, raw.text+ job: Final = Job.model_validate_json(raw.text)+ assert (job.training_file, job.validation_file) == (training_file, validation_file), raw.textdiff --git a/tests/integration/compatibility/test_fine_tuning_managed_files_chaos.py b/tests/integration/compatibility/test_fine_tuning_managed_files_chaos.pynew file mode 100644index 00000000000..54794fe29b9--- /dev/null+++ b/tests/integration/compatibility/test_fine_tuning_managed_files_chaos.py@@ -0,0 +1,289 @@+"""Managed fine-tuning creates on a two-worker proxy whose model group has two deployments: a concurrent burst from+sync and async clients, traffic pinned to each worker in turn, and a worker killed and replaced, all send every+deployment its own provider file ids and hand the caller back its own managed ids. A deployment added to the group+after the upload holds no copy of the files, so it never receives the create even when the router prefers it. A model+group the files were never uploaded for still gets the create and the provider's own 400, as before routing checked+which deployments hold the files."""++from __future__ import annotations++import asyncio+import json+import uuid+from collections.abc import Iterator, Mapping+from concurrent.futures import ThreadPoolExecutor+from dataclasses import dataclass+from pathlib import Path+from typing import Final+from urllib.parse import urlsplit++import pytest+import yaml+from integration._support.client import eventually, gateway_from_environment+from integration._support.database import scratch_database+from integration._support.process import OwnedProxy, WorkerHealthcheck, owned_proxy_process+from integration._support.wire import Reply, Request, Wire, wire_server+from openai import AsyncOpenAI, BadRequestError, OpenAI+from pydantic import JsonValue, TypeAdapter++pytestmark: Final = pytest.mark.timeout(480)++MODEL: Final = "gpt-4.1-chaos"+DEPLOYMENT_KEYS: Final = ("sk-chaos-deployment-a", "sk-chaos-deployment-b")+LATE_DEPLOYMENT_KEY: Final = "sk-chaos-deployment-late"+OTHER_MODEL: Final = "gpt-4.1-chaos-other"+OTHER_DEPLOYMENT_KEY: Final = "sk-chaos-deployment-other"+RUN: Final = uuid.uuid4().hex[:12]+TRAINING_LINE: Final = b'{"messages": [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"}]}\n'+JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])+BURST: Final = 20+CREATE: Final = ("POST", "/v1/fine_tuning/jobs")+WORKER_BOOT_DISCOVERY: Final = ("GET", "/v1/models")+++@dataclass(frozen=True, slots=True)+class Rig:+ owned: OwnedProxy+ wire: Wire+ training_file: str+ validation_file: str++ def base_url(self) -> str:+ return f"{str(self.owned.gateway.client.base_url).rstrip('/')}/v1"++ def sdk(self) -> OpenAI:+ return OpenAI(base_url=self.base_url(), api_key=self.owned.gateway.key, max_retries=0)++ def async_sdk(self) -> AsyncOpenAI:+ return AsyncOpenAI(base_url=self.base_url(), api_key=self.owned.gateway.key, max_retries=0)+++def _bearer(request: Request) -> str:+ return request.headers.get("authorization", "").removeprefix("Bearer ")+++def _provider_file_id(bearer: str, purpose: str) -> str:+ return f"file-{RUN}-{bearer.removeprefix('sk-chaos-')}-{purpose}"+++def _uploaded_purpose(request: Request) -> str:+ return "validate" if b'filename="validate.jsonl"' in request.body else "train"+++def _invalid_training_file(training_file: str) -> Reply:+ error: Final = {+ "message": f"invalid training_file: {training_file}",+ "type": "invalid_request_error",+ "param": "training_file",+ "code": None,+ }+ return Reply(status=400, body=json.dumps({"error": error}).encode())+++def _respond(request: Request) -> Reply:+ path: Final = urlsplit(request.target).path+ if (request.method, path) == ("POST", "/v1/files"):+ return Reply(+ body=json.dumps(+ {+ "id": _provider_file_id(_bearer(request), _uploaded_purpose(request)),+ "object": "file",+ "bytes": len(TRAINING_LINE),+ "created_at": 1700000000,+ "filename": f"{_uploaded_purpose(request)}.jsonl",+ "purpose": "fine-tune",+ "status": "processed",+ }+ ).encode()+ )+ if (request.method, path) == ("POST", "/v1/fine_tuning/jobs"):+ sent: Final = JSON_OBJECT.validate_json(request.body)+ if not str(sent["training_file"]).startswith(f"file-{RUN}-"):+ return _invalid_training_file(str(sent["training_file"]))+ return Reply(+ body=json.dumps(+ {+ "id": f"ftjob-{uuid.uuid4().hex}",+ "object": "fine_tuning.job",+ "created_at": 1700000000,+ "error": None,+ "fine_tuned_model": None,+ "finished_at": None,+ "hyperparameters": {"n_epochs": 3},+ "model": sent["model"],+ "organization_id": "org-chaos",+ "result_files": [],+ "seed": 42,+ "status": "validating_files",+ "trained_tokens": None,+ "training_file": sent["training_file"],+ "validation_file": sent.get("validation_file"),+ }+ ).encode()+ )+ return Reply(body=json.dumps({"object": "list", "data": []}).encode())+++def _deployment(wire: Wire, key: str, routing: Mapping[str, JsonValue], model: str = MODEL) -> dict[str, JsonValue]:+ return {+ "model_name": model,+ "litellm_params": {"model": "openai/gpt-4.1", "api_key": key, "api_base": f"{wire.url}/v1", **routing},+ "model_info": {"supported_endpoints": ["/chat/completions", "/fine_tuning"]},+ }+++def _config(wire: Wire, late_preferred_deployment: bool = False) -> dict[str, JsonValue]:+ late: Final = (_deployment(wire, LATE_DEPLOYMENT_KEY, {"order": 1}),) if late_preferred_deployment else ()+ return {+ "model_list": [+ *(_deployment(wire, key, {}) for key in DEPLOYMENT_KEYS),+ *late,+ _deployment(wire, OTHER_DEPLOYMENT_KEY, {}, OTHER_MODEL),+ ],+ "router_settings": {"num_retries": 0, "disable_cooldowns": True},+ "general_settings": {"master_key": "os.environ/LITELLM_MASTER_KEY", "database_url": "os.environ/DATABASE_URL"},+ }+++def _config_file(directory: Path, wire: Wire, late_preferred_deployment: bool = False) -> Path:+ directory.mkdir(parents=True, exist_ok=True)+ config: Final = directory / "config.yaml"+ config.write_text(yaml.safe_dump(_config(wire, late_preferred_deployment)))+ return config+++def _upload(client: OpenAI, purpose: str) -> str:+ uploaded: Final = client.files.with_raw_response.create(+ file=(f"{purpose}.jsonl", TRAINING_LINE, "application/jsonl"),+ purpose="fine-tune",+ extra_body={"target_model_names": MODEL},+ )+ assert uploaded.status_code == 200, uploaded.text+ return str(JSON_OBJECT.validate_json(uploaded.text)["id"])++[email protected](scope="module")+def rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Rig]:+ directory: Final = tmp_path_factory.mktemp("fine-tuning-chaos")+ with gateway_from_environment() as shared, wire_server(_respond) as wire:+ config: Final = _config_file(directory, wire)+ with owned_proxy_process(+ shared, directory, {}, config=config, workers=2, healthcheck=WorkerHealthcheck.LENIENT+ ) as owned:+ eventually(owned.worker_pids, lambda pids: len(pids) == 2, seconds=120)+ unloaded: Final = Rig(owned, wire, "", "")+ with unloaded.sdk() as client:+ training_file: Final = _upload(client, "train")+ validation_file: Final = _upload(client, "validate")+ wire.drain()+ yield Rig(owned, wire, training_file, validation_file)+++def _create(rig: Rig) -> tuple[int, Mapping[str, JsonValue]]:+ with rig.sdk() as client:+ raw: Final = client.fine_tuning.jobs.with_raw_response.create(+ model=MODEL, training_file=rig.training_file, validation_file=rig.validation_file+ )+ return raw.status_code, JSON_OBJECT.validate_json(raw.text)+++async def _async_creates(rig: Rig, count: int) -> tuple[tuple[int, Mapping[str, JsonValue]], ...]:+ async with rig.async_sdk() as client:+ raws: Final = await asyncio.gather(+ *(+ client.fine_tuning.jobs.with_raw_response.create(+ model=MODEL, training_file=rig.training_file, validation_file=rig.validation_file+ )+ for _ in range(count)+ )+ )+ return tuple((raw.status_code, JSON_OBJECT.validate_json(raw.text)) for raw in raws)+++def _sent_creates(rig: Rig, expected: int) -> tuple[Request, ...]:+ collected: Final[list[Request]] = []++ def creates() -> tuple[Request, ...]:+ collected.extend(rig.wire.drain())+ return tuple(request for request in collected if (request.method, request.target) == CREATE)++ sent: Final = eventually(creates, lambda found: len(found) >= expected, seconds=30)+ assert len(sent) == expected, [(request.method, request.target) for request in collected]+ assert {(request.method, request.target) for request in collected} <= {CREATE, WORKER_BOOT_DISCOVERY}, collected+ return sent+++def _assert_each_deployment_got_its_own_ids(creates: tuple[Request, ...]) -> None:+ for request in creates:+ bearer = _bearer(request)+ assert bearer in DEPLOYMENT_KEYS, request.headers+ assert JSON_OBJECT.validate_json(request.body) == {+ "model": "gpt-4.1",+ "training_file": _provider_file_id(bearer, "train"),+ "validation_file": _provider_file_id(bearer, "validate"),+ "hyperparameters": {},+ }, request.body+++def _assert_caller_gets_its_own_ids(rig: Rig, outcomes: tuple[tuple[int, Mapping[str, JsonValue]], ...]) -> None:+ received: Final = [(status, body.get("training_file"), body.get("validation_file")) for status, body in outcomes]+ assert received == [(200, rig.training_file, rig.validation_file)] * len(outcomes), outcomes+++def test_concurrent_sync_and_async_burst_sends_each_deployment_its_own_file_ids(rig: Rig) -> None:+ rig.wire.drain()+ with ThreadPoolExecutor(max_workers=BURST // 2) as pool:+ synced: Final = tuple(pool.map(_create, (rig,) * (BURST // 2)))+ awaited: Final = asyncio.run(_async_creates(rig, BURST // 2))+ creates: Final = _sent_creates(rig, BURST)+ _assert_each_deployment_got_its_own_ids(creates)+ assert {_bearer(request) for request in creates} == set(DEPLOYMENT_KEYS)+ _assert_caller_gets_its_own_ids(rig, synced + awaited)+++def test_each_worker_alone_sends_the_provider_file_ids(rig: Rig) -> None:+ rig.wire.drain()+ for paused in sorted(rig.owned.worker_pids()):+ with rig.owned.suspended(paused):+ outcomes = tuple(_create(rig) for _ in range(4))+ _assert_caller_gets_its_own_ids(rig, outcomes)+ _assert_each_deployment_got_its_own_ids(_sent_creates(rig, 4))+++def test_a_replaced_worker_still_sends_the_provider_file_ids(rig: Rig) -> None:+ rig.wire.drain()+ for victim in sorted(rig.owned.worker_pids()):+ rig.owned.kill_worker(victim)+ outcomes: Final = tuple(_create(rig) for _ in range(6))+ _assert_caller_gets_its_own_ids(rig, outcomes)+ _assert_each_deployment_got_its_own_ids(_sent_creates(rig, 6))+++def test_a_deployment_added_after_the_upload_never_receives_the_create(tmp_path: Path) -> None:+ with gateway_from_environment() as shared, wire_server(_respond) as wire, scratch_database() as database_url:+ one_database: Final = {"DATABASE_URL": database_url}+ before: Final = tmp_path / "before"+ with owned_proxy_process(shared, before, one_database, config=_config_file(before, wire)) as uploader:+ with Rig(uploader, wire, "", "").sdk() as client:+ training_file: Final = _upload(client, "train")+ validation_file: Final = _upload(client, "validate")+ after: Final = tmp_path / "after"+ with owned_proxy_process(+ shared, after, one_database, config=_config_file(after, wire, late_preferred_deployment=True), workers=2+ ) as owned:+ eventually(owned.worker_pids, lambda pids: len(pids) == 2, seconds=120)+ wire.drain()+ rig: Final = Rig(owned, wire, training_file, validation_file)+ outcomes: Final = tuple(_create(rig) for _ in range(6))+ creates: Final = _sent_creates(rig, 6)+ _assert_caller_gets_its_own_ids(rig, outcomes)+ _assert_each_deployment_got_its_own_ids(creates)+++def test_a_model_group_without_a_copy_of_the_files_still_gets_the_providers_400(rig: Rig) -> None:+ rig.wire.drain()+ with rig.sdk() as client, pytest.raises(BadRequestError) as rejected:+ client.fine_tuning.jobs.create(model=OTHER_MODEL, training_file=rig.training_file)+ creates: Final = _sent_creates(rig, 1)+ assert rejected.value.status_code == 400, rejected.value.response.text+ assert [_bearer(request) for request in creates] == [OTHER_DEPLOYMENT_KEY], createsdiff --git a/tests/integration/security/test_fine_tuning_managed_ids.py b/tests/integration/security/test_fine_tuning_managed_ids.pyindex 8f179e5a25f..791dd1d1e75 100644--- a/tests/integration/security/test_fine_tuning_managed_ids.py+++ b/tests/integration/security/test_fine_tuning_managed_ids.py@@ -294,13 +294,9 @@ def test_owner_create_returns_the_unified_job_id(fixture: str, request: pytest.Fbuilt: Final[Rig] = request.getfixturevalue(fixture)created: Final = Job.model_validate_json(built.created_text)expected: Final = _client_job(- _unified_job_id(built.deployment_id, built.provider_job), "validating_files", built.provider_file- )- assert created.model_dump(exclude={"training_file"}) == expected.model_dump(exclude={"training_file"}), (- "training_file is excluded because test_managed_create_sends_the_provider_file_id_of_the_pinned_deployment "- "documents the known managed-create bug",- built.created_text,+ _unified_job_id(built.deployment_id, built.provider_job), "validating_files", built.managed_file)+ assert created == expected, built.created_textdef test_another_key_cannot_create_with_or_cancel_the_owners_managed_ids(rig: Rig) -> None:diff --git a/tests/unit/enterprise/proxy/hooks/test_managed_files.py b/tests/unit/enterprise/proxy/hooks/test_managed_files.pyindex 91f6593575e..20ed8ac0c10 100644--- a/tests/unit/enterprise/proxy/hooks/test_managed_files.py+++ b/tests/unit/enterprise/proxy/hooks/test_managed_files.py@@ -3,6 +3,7 @@ import jsonimport loggingimport timeimport asyncio+import uuidfrom collections.abc import Awaitable, Callable, Mappingfrom types import SimpleNamespacefrom typing import TYPE_CHECKING, Final, cast@@ -13,6 +14,7 @@ import pytestimport respxfrom fastapi import HTTPExceptionfrom openai import APIConnectionError+from pydantic import TypeAdapterif TYPE_CHECKING:from litellm.types.utils import LiteLLMBatch@@ -22,7 +24,7 @@ from litellm_enterprise.proxy.hooks.managed_files import (_provider_file_retrieve_credentials,)from litellm.caching import DualCache-from litellm.proxy._types import CallTypes, LiteLLM_ManagedFileTable+from litellm.proxy._types import CallTypes, LiteLLM_ManagedFileTable, UserAPIKeyAuthfrom litellm.proxy.openai_files_endpoints.common_utils import (BATCH_CREATE_HIDDEN_PARAM,is_base64_encoded_unified_file_id,@@ -6050,6 +6052,164 @@ async def test_create_from_raw_provider_file_id_skips_managed_ownership_lookup(cassert not any("unified_file_id" in where for where in table.find_first_calls), table.find_first_calls+def _owned_managed_file(unified_uuid: str, model_mappings: Mapping[str, str]) -> tuple[str, LiteLLM_ManagedFileTable]:+ raw: Final = f"litellm_proxy:application/jsonl;unified_id,{unified_uuid};target_model_names,gpt-4o-mini"+ unified_file_id: Final = base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=")+ return unified_file_id, LiteLLM_ManagedFileTable(+ unified_file_id=unified_file_id,+ file_object=None,+ model_mappings=dict(model_mappings),+ flat_model_file_ids=list(model_mappings.values()),+ created_by="user_a",+ team_id="team_a",+ )+++async def _provider_kwargs(+ managed_files: PROXY_LiteLLMManagedFiles, call_type: str, request: Mapping[str, str], deployment_id: str+) -> Mapping[str, object]:+ prepared: Final = await managed_files.async_pre_call_hook(+ user_api_key_dict=UserAPIKeyAuth(user_id="user_a", team_id="team_a", parent_otel_span=MagicMock()),+ cache=MagicMock(),+ data=dict(request),+ call_type=call_type,+ )+ assert isinstance(prepared, dict), prepared+ sent: Final = await managed_files.async_pre_call_deployment_hook(+ kwargs={**prepared, "litellm_metadata": {"model_info": {"id": deployment_id}}}, call_type=CallTypes(call_type)+ )+ assert sent is not None+ return sent++[email protected](("call_type", "file_field"), _INPUT_FILE_CREATE_CALLS)[email protected](("deployment_id", "provider_file_id"), [("model-a", "file-a"), ("model-b", "file-b")])+async def test_create_from_managed_file_sends_the_routed_deployments_provider_file_id(+ call_type: str, file_field: str, deployment_id: str, provider_file_id: str+) -> None:+ unified_file_id, row = _owned_managed_file(+ "0b6f2c1e-9a4d-4c3e-8f71-2d5a6b7c8d90", {"model-a": "file-a", "model-b": "file-b"}+ )+ managed_files, _ = _managed_files_with_fake_prisma(row)++ sent: Final = await _provider_kwargs(+ managed_files, call_type, {"model": "gpt-4o-mini", file_field: unified_file_id}, deployment_id+ )++ assert sent[file_field] == provider_file_id, sent+++async def test_fine_tuning_create_swaps_managed_training_and_validation_files_independently() -> None:+ training_file, training_row = _owned_managed_file("5c1d9e0a-3b7f-4e2a-9c6d-1f8e7a6b5c40", {"model-a": "file-train"})+ validation_file, validation_row = _owned_managed_file(+ "8e2f4a6c-1d3b-4f5e-a7c9-0b2d4f6a8c10", {"model-a": "file-validate"}+ )+ managed_files, _ = _managed_files_with_fake_prisma(training_row, validation_row)++ sent: Final = await _provider_kwargs(+ managed_files,+ "acreate_fine_tuning_job",+ {"model": "gpt-4o-mini", "training_file": training_file, "validation_file": validation_file},+ "model-a",+ )++ assert (sent["training_file"], sent["validation_file"]) == ("file-train", "file-validate"), sent+++async def test_fine_tuning_create_keeps_a_raw_validation_file_next_to_a_managed_training_file() -> None:+ training_file, training_row = _owned_managed_file("5c1d9e0a-3b7f-4e2a-9c6d-1f8e7a6b5c40", {"model-a": "file-train"})+ managed_files, _ = _managed_files_with_fake_prisma(training_row)++ sent: Final = await _provider_kwargs(+ managed_files,+ "acreate_fine_tuning_job",+ {"model": "gpt-4o-mini", "training_file": training_file, "validation_file": "file-raw-validate"},+ "model-a",+ )++ assert (sent["training_file"], sent["validation_file"]) == ("file-train", "file-raw-validate"), sent+++_REQUEST_KWARGS: Final = TypeAdapter(dict[str, object])+_DEPLOYMENTS: Final = TypeAdapter(list[dict[str, dict[str, str]]])+++async def _routable_deployment_ids(+ managed_files: PROXY_LiteLLMManagedFiles, call_type: str, request: Mapping[str, str]+) -> tuple[str, ...]:+ prepared: Final = _REQUEST_KWARGS.validate_python(+ await managed_files.async_pre_call_hook(+ user_api_key_dict=UserAPIKeyAuth(user_id="user_a", team_id="team_a", parent_otel_span=MagicMock()),+ cache=MagicMock(),+ data=dict(request),+ call_type=call_type,+ )+ )+ routable: Final = _DEPLOYMENTS.validate_python(+ await managed_files.async_filter_deployments(+ model="gpt-4o-mini",+ healthy_deployments=[{"model_info": {"id": model_id}} for model_id in ("model-a", "model-b", "model-c")],+ messages=None,+ request_kwargs=prepared,+ )+ )+ return tuple(deployment["model_info"]["id"] for deployment in routable)+++ ("call_type", "files", "expected"),+ [+ pytest.param(+ "acreate_fine_tuning_job",+ {"training_file": {"model-a": "f-1", "model-b": "f-2"}, "validation_file": {"model-b": "f-3"}},+ ("model-b",),+ id="fine-tune-routes-to-the-deployment-holding-both-files",+ ),+ pytest.param(+ "acreate_fine_tuning_job",+ {"training_file": {"model-a": "f-1", "model-b": "f-2"}, "validation_file": "file-raw-validate"},+ ("model-a", "model-b"),+ id="fine-tune-raw-validation-file-does-not-narrow",+ ),+ pytest.param(+ "acreate_fine_tuning_job",+ {"training_file": {"model-a": "f-1"}, "validation_file": {"model-b": "f-3"}},+ ("model-a", "model-b", "model-c"),+ id="fine-tune-files-on-disjoint-deployments-keep-every-deployment",+ ),+ pytest.param(+ "acreate_fine_tuning_job",+ {"training_file": {"model-z": "f-5"}},+ ("model-a", "model-b", "model-c"),+ id="fine-tune-file-of-another-model-group-keeps-every-deployment",+ ),+ pytest.param("acreate_batch", {"input_file_id": {"model-c": "f-4"}}, ("model-c",), id="batch-input-file"),+ pytest.param(+ "acreate_batch", {"input_file_id": {"model-z": "f-6"}}, (), id="batch-input-file-of-another-model-group"+ ),+ ],+)+async def test_create_from_managed_files_routes_only_to_deployments_holding_every_file(+ call_type: str, files: Mapping[str, Mapping[str, str] | str], expected: tuple[str, ...]+) -> None:+ owned: Final = {+ field: _owned_managed_file(str(uuid.uuid5(uuid.NAMESPACE_URL, field)), mappings)+ for field, mappings in files.items()+ if not isinstance(mappings, str)+ }+ managed_files, _ = _managed_files_with_fake_prisma(*(row for _, row in owned.values()))+ request: Final = {+ "model": "gpt-4o-mini",+ **{field: owned[field][0] if field in owned else str(mappings) for field, mappings in files.items()},+ }++ assert await _routable_deployment_ids(managed_files, call_type, request) == expected++_MANAGED_READ_SALT_KEY: Final = "managed-read-unit-test-salt-key"diff --git a/tests/unit/fine_tuning/__init__.py b/tests/unit/fine_tuning/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/unit/fine_tuning/test_main.py b/tests/unit/fine_tuning/test_main.pynew file mode 100644index 00000000000..57c845c6e1a--- /dev/null+++ b/tests/unit/fine_tuning/test_main.py@@ -0,0 +1,54 @@+import json+from typing import Final++import httpx+import pytest+import respx++import litellm++API_BASE: Final = "https://fine-tuning.test"+BASE_MODEL: Final = "gpt-4.1-nano-2025-04-14"+PROVIDER_JOB: Final = {+ "id": "ftjob-abc123",+ "object": "fine_tuning.job",+ "created_at": 1700000000,+ "error": None,+ "fine_tuned_model": None,+ "finished_at": None,+ "hyperparameters": {"n_epochs": 3},+ "model": BASE_MODEL,+ "organization_id": "org-test",+ "result_files": [],+ "seed": 42,+ "status": "validating_files",+ "trained_tokens": None,+ "training_file": "file-abc123",+ "validation_file": None,+}+++ ("custom_llm_provider", "route"),+ [("openai", f"{API_BASE}/v1/fine_tuning/jobs"), ("azure", f"{API_BASE}/openai/fine_tuning/jobs")],+)[email protected]("prefixed", [True, False], ids=["provider-prefixed", "bare"])+async def test_create_sends_the_model_without_the_provider_prefix(+ monkeypatch: pytest.MonkeyPatch, custom_llm_provider: str, route: str, prefixed: bool+) -> None:+ sent: Final = respx.post(url__startswith=route).mock(return_value=httpx.Response(200, json=PROVIDER_JOB))++ async with httpx.AsyncClient() as session:+ monkeypatch.setattr(litellm, "aclient_session", session)+ await litellm.acreate_fine_tuning_job(+ model=f"{custom_llm_provider}/{BASE_MODEL}" if prefixed else BASE_MODEL,+ training_file="file-abc123",+ custom_llm_provider=custom_llm_provider,+ api_key="sk-test",+ api_base=f"{API_BASE}/v1" if custom_llm_provider == "openai" else API_BASE,+ **({"api_version": "2024-10-21"} if custom_llm_provider == "azure" else {}),+ )++ assert json.loads(sent.calls.last.request.content)["model"] == BASE_MODELdiff --git a/tests/unit/llms/vertex_ai/fine_tuning/test_handler.py b/tests/unit/llms/vertex_ai/fine_tuning/test_handler.pyindex 5447d553f30..79c96b8970a 100644--- a/tests/unit/llms/vertex_ai/fine_tuning/test_handler.py+++ b/tests/unit/llms/vertex_ai/fine_tuning/test_handler.py@@ -45,7 +45,8 @@ class TestCustomLogger(CustomLogger):@pytest.mark.asyncio()-async def test_create_vertex_fine_tune_jobs_mocked():[email protected]("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 testproject_id = "633608382793"location = "us-central1"@@ -90,7 +91,7 @@ async def test_create_vertex_fine_tune_jobs_mocked():),):create_fine_tuning_response = await litellm.acreate_fine_tuning_job(- model=base_model,+ model=f"{model_prefix}{base_model}",custom_llm_provider="vertex_ai",training_file=training_file,vertex_project=project_id,diff --git a/tests/unit/proxy/fine_tuning_endpoints/test_endpoints.py b/tests/unit/proxy/fine_tuning_endpoints/test_endpoints.pyindex 99a79801698..06ac56b09ad 100644--- a/tests/unit/proxy/fine_tuning_endpoints/test_endpoints.py+++ b/tests/unit/proxy/fine_tuning_endpoints/test_endpoints.py@@ -37,9 +37,9 @@ RAW_FILE_ID = "file-victim-abc123"RAW_JOB_ID = "ftjob-victim-abc123"-def _unified_file_id() -> str:+def _unified_file_id(unified_id: str = "victim-unified-id", provider_file_id: str = RAW_FILE_ID) -> str:unified = SpecialEnums.LITELLM_MANAGED_FILE_COMPLETE_STR.value.format(- "application/json", "victim-unified-id", "gpt-4o-mini", RAW_FILE_ID, "gpt-4o-mini-id"+ "application/json", unified_id, "gpt-4o-mini", provider_file_id, "gpt-4o-mini-id")return base64.urlsafe_b64encode(unified.encode()).decode().rstrip("=")@@ -54,7 +54,7 @@ def _decode_unified_id(encoded_id: str) -> str:return base64.urlsafe_b64decode(f"{encoded_id}{padding}").decode()-def _job() -> LiteLLMFineTuningJob:+def _job(validation_file: str | None = None) -> LiteLLMFineTuningJob:job = LiteLLMFineTuningJob(id=RAW_JOB_ID,created_at=1234567890,@@ -69,7 +69,7 @@ def _job() -> LiteLLMFineTuningJob:status="running",trained_tokens=None,training_file=RAW_FILE_ID,- validation_file=None,+ validation_file=validation_file,)job._hidden_params = {}return job@@ -225,6 +225,31 @@ async def test_create__unified_training_file_allowed_when_managed_files_requiredassert response.hidden_params["unified_file_id"] == _decode_unified_id(unified_file_id)+MANAGED_VALIDATION_FILE_ID: Final = _unified_file_id("validation-unified-id", "file-provider-validation")+++ ("validation_file", "provider_validation_file", "expected_validation_file"),+ [+ (None, None, None),+ (RAW_FILE_ID, RAW_FILE_ID, RAW_FILE_ID),+ (MANAGED_VALIDATION_FILE_ID, "file-provider-validation", MANAGED_VALIDATION_FILE_ID),+ ],+ ids=["no-validation-file", "raw-validation-file", "managed-validation-file"],+)+async def test_create__managed_job_returns_the_callers_file_ids(+ seams, validation_file: str | None, provider_validation_file: str | None, expected_validation_file: str | None+):+ seams.logging.get_proxy_hook.return_value = ManagedResourceAccessCheckerStub()+ seams.router.acreate_fine_tuning_job.return_value = _job(validation_file=provider_validation_file)+ training_file: Final = _unified_file_id()++ response: Final = await _create(training_file, validation_file=validation_file)++ assert (response.training_file, response.validation_file) == (training_file, expected_validation_file)++@pytest.mark.asyncioasync def test_create__other_teams_unified_training_file_rejected(seams):seams.logging.get_proxy_hook.return_value = ManagedResourceAccessCheckerStub(file_access=False)