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]

Store batch output file id in DB + Store batch file status in DB + (experimental) BATCH API COST TRACKING

Krrish Dholakiac3857e60f2c4
diff --git a/enterprise/enterprise_hooks/__init__.py b/enterprise/enterprise_hooks/__init__.py
index 9cfe9218f00..9eb1c8960a6 100644
--- a/enterprise/enterprise_hooks/__init__.py
+++ b/enterprise/enterprise_hooks/__init__.py
@@ -1,8 +1,8 @@
from typing import Dict, Literal, Type, Union
-from litellm.integrations.custom_logger import CustomLogger
+from litellm_enterprise.proxy.hooks.managed_files import _PROXY_LiteLLMManagedFiles
-from .managed_files import _PROXY_LiteLLMManagedFiles
+from litellm.integrations.custom_logger import CustomLogger
ENTERPRISE_PROXY_HOOKS: Dict[str, Type[CustomLogger]] = {
"managed_files": _PROXY_LiteLLMManagedFiles,
@@ -16,7 +16,7 @@ def get_enterprise_proxy_hook(
"max_parallel_requests",
],
str,
- ]
+ ],
):
"""
Factory method to get a enterprise hook instance by name
diff --git a/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py
new file mode 100644
index 00000000000..9fb20224322
--- /dev/null
+++ b/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py
@@ -0,0 +1,134 @@
+"""
+Polls LiteLLM_ManagedObjectTable to check if the batch job is complete, and if the cost has been tracked.
+"""
+
+from typing import TYPE_CHECKING, Optional, cast
+
+from litellm._logging import verbose_proxy_logger
+
+if TYPE_CHECKING:
+ from litellm.proxy.utils import PrismaClient, ProxyLogging
+ from litellm.router import Router
+
+
+class CheckBatchCost:
+ def __init__(
+ self,
+ proxy_logging_obj: "ProxyLogging",
+ prisma_client: "PrismaClient",
+ llm_router: "Router",
+ ):
+ from litellm.proxy.utils import PrismaClient, ProxyLogging
+ from litellm.router import Router
+
+ self.proxy_logging_obj: ProxyLogging = proxy_logging_obj
+ self.prisma_client: PrismaClient = prisma_client
+ self.llm_router: Router = llm_router
+
+ async def check_batch_cost(self):
+ """
+ Check if the batch JOB has been tracked.
+ - get all status="validating" and file_purpose="batch" jobs
+ - check if batch is now complete
+ - if not, return False
+ - if so, return True
+ """
+ from litellm_enterprise.proxy.hooks.managed_files import (
+ _PROXY_LiteLLMManagedFiles,
+ )
+
+ from litellm.batches.batch_utils import (
+ _get_file_content_as_dictionary,
+ calculate_batch_cost_and_usage,
+ )
+ from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider
+ from litellm.proxy.openai_files_endpoints.common_utils import (
+ _is_base64_encoded_unified_file_id,
+ get_batch_id_from_unified_batch_id,
+ get_model_id_from_unified_batch_id,
+ )
+
+ jobs = await self.prisma_client.db.litellm_managedobjecttable.find_many(
+ where={
+ "status": "validating",
+ "file_purpose": "batch",
+ }
+ )
+
+ for job in jobs:
+ # get the model from the job
+ unified_object_id = job.unified_object_id
+ decoded_unified_object_id = _is_base64_encoded_unified_file_id(
+ unified_object_id
+ )
+ if not decoded_unified_object_id:
+ verbose_proxy_logger.info(
+ f"Skipping job {unified_object_id} because it is not a valid unified object id"
+ )
+ continue
+ else:
+ unified_object_id = decoded_unified_object_id
+
+ model_id = get_model_id_from_unified_batch_id(unified_object_id)
+ batch_id = get_batch_id_from_unified_batch_id(unified_object_id)
+
+ if model_id is None:
+ verbose_proxy_logger.info(
+ f"Skipping job {unified_object_id} because it is not a valid model id"
+ )
+ continue
+
+ response = await self.llm_router.aretrieve_batch(
+ model=model_id,
+ batch_id=batch_id,
+ )
+
+ ## RETRIEVE THE BATCH JOB OUTPUT FILE
+ managed_files_obj = cast(
+ Optional[_PROXY_LiteLLMManagedFiles],
+ self.proxy_logging_obj.get_proxy_hook("managed_files"),
+ )
+ if (
+ response.status == "completed"
+ and response.output_file_id is not None
+ and managed_files_obj is not None
+ ):
+ # track cost
+ model_file_id_mapping = {
+ response.output_file_id: {model_id: response.output_file_id}
+ }
+ _file_content = await managed_files_obj.afile_content(
+ file_id=response.output_file_id,
+ litellm_parent_otel_span=None,
+ llm_router=self.llm_router,
+ model_file_id_mapping=model_file_id_mapping,
+ )
+
+ file_content_as_dict = _get_file_content_as_dictionary(
+ _file_content.content
+ )
+
+ deployment_info = self.llm_router.get_deployment(model_id=model_id)
+ if deployment_info is None:
+ verbose_proxy_logger.info(
+ f"Skipping job {unified_object_id} because it is not a valid deployment info"
+ )
+ continue
+ custom_llm_provider = deployment_info.litellm_params.custom_llm_provider
+ litellm_model_name = deployment_info.litellm_params.model
+
+ _, llm_provider, _, _ = get_llm_provider(
+ model=litellm_model_name,
+ custom_llm_provider=custom_llm_provider,
+ )
+
+ batch_cost, batch_usage, batch_models = (
+ await calculate_batch_cost_and_usage(
+ file_content_dictionary=file_content_as_dict,
+ custom_llm_provider=llm_provider, # type: ignore
+ )
+ )
+
+ if response.status != "validating":
+ # mark for updating
+ pass
diff --git a/enterprise/enterprise_hooks/managed_files.py b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
similarity index 91%
rename from enterprise/enterprise_hooks/managed_files.py
rename to enterprise/litellm_enterprise/proxy/hooks/managed_files.py
index e06e83e272f..d5e8968464c 100644
--- a/enterprise/enterprise_hooks/managed_files.py
+++ b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
@@ -23,6 +23,8 @@ from litellm.proxy._types import (
from litellm.proxy.openai_files_endpoints.common_utils import (
_is_base64_encoded_unified_file_id,
convert_b64_uid_to_unified_uid,
+ get_batch_id_from_unified_batch_id,
+ get_model_id_from_unified_batch_id,
)
from litellm.types.llms.openai import (
AllMessageValues,
@@ -40,6 +42,10 @@ from litellm.types.utils import (
SpecialEnums,
)
+if TYPE_CHECKING:
+ from litellm.types.llms.openai import HttpxBinaryResponseContent
+
+
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
@@ -66,7 +72,7 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
async def store_unified_file_id(
self,
file_id: str,
- file_object: OpenAIFileObject,
+ file_object: Optional[OpenAIFileObject],
litellm_parent_otel_span: Optional[Span],
model_mappings: Dict[str, str],
user_api_key_dict: UserAPIKeyAuth,
@@ -74,31 +80,39 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
verbose_logger.info(
f"Storing LiteLLM Managed File object with id={file_id} in cache"
)
- litellm_managed_file_object = LiteLLM_ManagedFileTable(
- unified_file_id=file_id,
- file_object=file_object,
- model_mappings=model_mappings,
- flat_model_file_ids=list(model_mappings.values()),
- created_by=user_api_key_dict.user_id,
- updated_by=user_api_key_dict.user_id,
- )
- await self.internal_usage_cache.async_set_cache(
- key=file_id,
- value=litellm_managed_file_object.model_dump(),
- litellm_parent_otel_span=litellm_parent_otel_span,
- )
+ if file_object is not None:
+ litellm_managed_file_object = LiteLLM_ManagedFileTable(
+ unified_file_id=file_id,
+ file_object=file_object,
+ model_mappings=model_mappings,
+ flat_model_file_ids=list(model_mappings.values()),
+ created_by=user_api_key_dict.user_id,
+ updated_by=user_api_key_dict.user_id,
+ )
+ await self.internal_usage_cache.async_set_cache(
+ key=file_id,
+ value=litellm_managed_file_object.model_dump(),
+ litellm_parent_otel_span=litellm_parent_otel_span,
+ )
## STORE MODEL MAPPINGS IN DB
- await self.prisma_client.db.litellm_managedfiletable.create(
- data={
- "unified_file_id": file_id,
- "file_object": file_object.model_dump_json(),
- "model_mappings": json.dumps(model_mappings),
- "flat_model_file_ids": list(model_mappings.values()),
- "created_by": user_api_key_dict.user_id,
- "updated_by": user_api_key_dict.user_id,
- }
+ db_data = {
+ "unified_file_id": file_id,
+ "model_mappings": json.dumps(model_mappings),
+ "flat_model_file_ids": list(model_mappings.values()),
+ "created_by": user_api_key_dict.user_id,
+ "updated_by": user_api_key_dict.user_id,
+ }
+
+ if file_object is not None:
+ db_data["file_object"] = file_object.model_dump_json()
+
+ result = await self.prisma_client.db.litellm_managedfiletable.create(
+ data=db_data
+ )
+ verbose_logger.debug(
+ f"LiteLLM Managed File object with id={file_id} stored in db: {result}"
)
async def store_unified_object_id(
@@ -133,6 +147,7 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
"file_purpose": file_purpose,
"created_by": user_api_key_dict.user_id,
"updated_by": user_api_key_dict.user_id,
+ "status": file_object.status,
}
)
@@ -184,10 +199,12 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
self, unified_file_id: str, user_api_key_dict: UserAPIKeyAuth
) -> bool:
## check if the user has access to the unified file id
+
user_id = user_api_key_dict.user_id
managed_file = await self.prisma_client.db.litellm_managedfiletable.find_first(
where={"unified_file_id": unified_file_id}
)
+
if managed_file:
return managed_file.created_by == user_id
return False
@@ -349,7 +366,7 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
)
## for managed batch id - get the model id
- potential_model_id = self.get_model_id_from_unified_batch_id(
+ potential_model_id = get_model_id_from_unified_batch_id(
potential_llm_object_id
)
if potential_model_id is None:
@@ -357,7 +374,7 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
f"LiteLLM Managed {accessor_key} with id={retrieve_object_id} is invalid - does not contain encoded model_id."
)
data["model"] = potential_model_id
- data[accessor_key] = self.get_batch_id_from_unified_batch_id(
+ data[accessor_key] = get_batch_id_from_unified_batch_id(
potential_llm_object_id
)
elif call_type == CallTypes.acreate_fine_tuning_job.value:
@@ -613,13 +630,13 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
return base64.urlsafe_b64encode(unified_batch_id.encode()).decode().rstrip("=")
def get_unified_output_file_id(
- self, output_file_id: str, model_id: str, model_name: str
+ self, output_file_id: str, model_id: str, model_name: Optional[str]
) -> str:
unified_output_file_id = (
SpecialEnums.LITELLM_MANAGED_FILE_COMPLETE_STR.value.format(
"application/json",
str(uuid.uuid4()),
- model_name,
+ model_name or "",
output_file_id,
model_id,
)
@@ -636,25 +653,6 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
def get_output_file_id_from_unified_file_id(self, file_id: str) -> str:
return file_id.split("llm_output_file_id,")[1].split(";")[0]
- def get_model_id_from_unified_batch_id(self, file_id: str) -> Optional[str]:
- """
- Get the model_id from the file_id
-
- Expected format: litellm_proxy;model_id:{};llm_batch_id:{};llm_output_file_id:{}
- """
- ## use regex to get the model_id from the file_id
- try:
- return file_id.split("model_id:")[1].split(";")[0]
- except Exception:
- return None
-
- def get_batch_id_from_unified_batch_id(self, file_id: str) -> str:
- ## use regex to get the batch_id from the file_id
- if "llm_batch_id" in file_id:
- return file_id.split("llm_batch_id:")[1].split(",")[0]
- else:
- return file_id.split("generic_response_id:")[1].split(",")[0]
-
async def async_post_call_success_hook(
self, data: Dict, user_api_key_dict: UserAPIKeyAuth, response: LLMResponseTypes
) -> Any:
@@ -669,19 +667,28 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
model_id = cast(Optional[str], response._hidden_params.get("model_id"))
model_name = cast(Optional[str], response._hidden_params.get("model_name"))
original_response_id = response.id
+
if (unified_batch_id or unified_file_id) and model_id:
response.id = self.get_unified_batch_id(
batch_id=response.id, model_id=model_id
)
if (
- response.output_file_id and model_name and model_id
+ response.output_file_id and model_id
): # return a file id with the model_id and output_file_id
+ original_output_file_id = response.output_file_id
response.output_file_id = self.get_unified_output_file_id(
output_file_id=response.output_file_id,
model_id=model_id,
model_name=model_name,
)
+ await self.store_unified_file_id( # need to store otherwise any retrieve call will fail
+ file_id=response.output_file_id,
+ file_object=None,
+ litellm_parent_otel_span=user_api_key_dict.parent_otel_span,
+ model_mappings={model_id: original_output_file_id},
+ user_api_key_dict=user_api_key_dict,
+ )
asyncio.create_task(
self.store_unified_object_id(
unified_object_id=response.id,
@@ -793,12 +800,14 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
litellm_parent_otel_span: Optional[Span],
llm_router: Router,
**data: Dict,
- ) -> str:
+ ) -> "HttpxBinaryResponseContent":
"""
Get the content of a file from first model that has it
"""
- model_file_id_mapping = await self.get_model_file_id_mapping(
- [file_id], litellm_parent_otel_span
+ model_file_id_mapping = data.pop("model_file_id_mapping", None)
+ model_file_id_mapping = (
+ model_file_id_mapping
+ or await self.get_model_file_id_mapping([file_id], litellm_parent_otel_span)
)
specific_model_file_id_mapping = model_file_id_mapping.get(file_id)
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20250625145206_cascade_budget_and_loosen_managed_file_json/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20250625145206_cascade_budget_and_loosen_managed_file_json/migration.sql
new file mode 100644
index 00000000000..51461b82058
--- /dev/null
+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20250625145206_cascade_budget_and_loosen_managed_file_json/migration.sql
@@ -0,0 +1,9 @@
+-- DropForeignKey
+ALTER TABLE "LiteLLM_TeamMembership" DROP CONSTRAINT "LiteLLM_TeamMembership_budget_id_fkey";
+
+-- AlterTable
+ALTER TABLE "LiteLLM_ManagedFileTable" ALTER COLUMN "file_object" DROP NOT NULL;
+
+-- AddForeignKey
+ALTER TABLE "LiteLLM_TeamMembership" ADD CONSTRAINT "LiteLLM_TeamMembership_budget_id_fkey" FOREIGN KEY ("budget_id") REFERENCES "LiteLLM_BudgetTable"("budget_id") ON DELETE SET NULL ON UPDATE CASCADE;
+
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20250625213625_add_status_to_managed_object_table/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20250625213625_add_status_to_managed_object_table/migration.sql
new file mode 100644
index 00000000000..7ca7b2c3705
--- /dev/null
+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20250625213625_add_status_to_managed_object_table/migration.sql
@@ -0,0 +1,3 @@
+-- AlterTable
+ALTER TABLE "LiteLLM_ManagedObjectTable" ADD COLUMN "status" TEXT;
+
diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
index 1ea1987de67..9b0fbbaa8f2 100644
--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
@@ -156,7 +156,6 @@ model LiteLLM_ObjectPermissionTable {
object_permission_id String @id @default(uuid())
mcp_servers String[] @default([])
vector_stores String[] @default([])
-
teams LiteLLM_TeamTable[]
verification_tokens LiteLLM_VerificationToken[]
organizations LiteLLM_OrganizationTable[]
@@ -453,8 +452,8 @@ enum JobStatus {
model LiteLLM_ManagedFileTable {
id String @id @default(uuid())
unified_file_id String @unique // The base64 encoded unified file ID
- file_object Json // Stores the OpenAIFileObject
- model_mappings Json
+ file_object Json? // Stores the OpenAIFileObject
+ model_mappings Json
flat_model_file_ids String[] @default([]) // Flat list of model file id's - for faster querying of model id -> unified file id
created_at DateTime @default(now())
created_by String?
@@ -469,7 +468,8 @@ model LiteLLM_ManagedObjectTable { // for batches or finetuning jobs which use t
unified_object_id String @unique // The base64 encoded unified file ID
model_object_id String @unique // the id returned by the backend API provider
file_object Json // Stores the OpenAIFileObject
- file_purpose String // either 'batch' or 'fine-tune'
+ file_purpose String // either 'batch' or 'fine-tune'
+ status String? // check if batch cost has been tracked
created_at DateTime @default(now())
created_by String?
updated_at DateTime @updatedAt
diff --git a/litellm/batches/batch_utils.py b/litellm/batches/batch_utils.py
index af53304e5a0..814851e560b 100644
--- a/litellm/batches/batch_utils.py
+++ b/litellm/batches/batch_utils.py
@@ -7,6 +7,28 @@ from litellm.types.llms.openai import Batch
from litellm.types.utils import CallTypes, Usage
+async def calculate_batch_cost_and_usage(
+ file_content_dictionary: List[dict],
+ custom_llm_provider: Literal["openai", "azure", "vertex_ai"],
+) -> Tuple[float, Usage, List[str]]:
+ """
+ Calculate the cost and usage of a batch
+ """
+ # Calculate costs and usage
+ batch_cost = _batch_cost_calculator(
+ custom_llm_provider=custom_llm_provider,
+ file_content_dictionary=file_content_dictionary,
+ )
+ batch_usage = _get_batch_job_total_usage_from_file_content(
+ file_content_dictionary=file_content_dictionary,
+ custom_llm_provider=custom_llm_provider,
+ )
+
+ batch_models = _get_batch_models_from_file_content(file_content_dictionary)
+
+ return batch_cost, batch_usage, batch_models
+
+
async def _handle_completed_batch(
batch: Batch,
custom_llm_provider: Literal["openai", "azure", "vertex_ai"],
@@ -18,7 +40,7 @@ async def _handle_completed_batch(
)
# Calculate costs and usage
- batch_cost = await _batch_cost_calculator(
+ batch_cost = _batch_cost_calculator(
custom_llm_provider=custom_llm_provider,
file_content_dictionary=file_content_dictionary,
)
@@ -48,7 +70,7 @@ def _get_batch_models_from_file_content(
return batch_models
-async def _batch_cost_calculator(
+def _batch_cost_calculator(
file_content_dictionary: List[dict],
custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai",
) -> float:
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 59b3e870c62..7e32c5c438b 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -1237,7 +1237,12 @@ class Logging(LiteLLMLoggingBaseClass):
return False
# Check for dynamically disabled callbacks via headers
- if EnterpriseCallbackControls is not None and EnterpriseCallbackControls.is_callback_disabled_via_headers(callback, litellm_params):
+ if (
+ EnterpriseCallbackControls is not None
+ and EnterpriseCallbackControls.is_callback_disabled_via_headers(
+ callback, litellm_params
+ )
+ ):
verbose_logger.debug(
f"Callback {callback} disabled via x-litellm-disable-callbacks header for {event_hook} event"
)
@@ -1912,16 +1917,27 @@ class Logging(LiteLLMLoggingBaseClass):
return
## CALCULATE COST FOR BATCH JOBS
- if self.call_type == CallTypes.aretrieve_batch.value and isinstance(
- result, LiteLLMBatch
+ if (
+ self.call_type == CallTypes.aretrieve_batch.value
+ and isinstance(result, LiteLLMBatch)
+ and result.status == "completed"
):
- response_cost, batch_usage, batch_models = await _handle_completed_batch(
- batch=result, custom_llm_provider=self.custom_llm_provider
+ from litellm.proxy.openai_files_endpoints.common_utils import (
+ _is_base64_encoded_unified_file_id,
)
- result._hidden_params["response_cost"] = response_cost
- result._hidden_params["batch_models"] = batch_models
- result.usage = batch_usage
+ # check if file id is a unified file id
+ is_base64_unified_file_id = _is_base64_encoded_unified_file_id(result.id)
+ if not is_base64_unified_file_id: # only run for non-unified file ids
+ response_cost, batch_usage, batch_models = (
+ await _handle_completed_batch(
+ batch=result, custom_llm_provider=self.custom_llm_provider
+ )
+ )
+
+ result._hidden_params["response_cost"] = response_cost
+ result._hidden_params["batch_models"] = batch_models
+ result.usage = batch_usage
start_time, end_time, result = self._success_handler_helper_fn(
start_time=start_time,
diff --git a/litellm/llms/base_llm/files/transformation.py b/litellm/llms/base_llm/files/transformation.py
index 38a6dc48092..5c37a8b7547 100644
--- a/litellm/llms/base_llm/files/transformation.py
+++ b/litellm/llms/base_llm/files/transformation.py
@@ -18,6 +18,7 @@ from ..chat.transformation import BaseConfig
if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
from litellm.router import Router as _Router
+ from litellm.types.llms.openai import HttpxBinaryResponseContent
LiteLLMLoggingObj = _LiteLLMLoggingObj
Span = Any
@@ -154,5 +155,5 @@ class BaseFileEndpoints(ABC):
litellm_parent_otel_span: Optional[Span],
llm_router: Router,
**data: Dict,
- ) -> str:
+ ) -> "HttpxBinaryResponseContent":
pass
diff --git a/litellm/proxy/batches_endpoints/endpoints.py b/litellm/proxy/batches_endpoints/endpoints.py
index 56b0677590f..66ba0800dac 100644
--- a/litellm/proxy/batches_endpoints/endpoints.py
+++ b/litellm/proxy/batches_endpoints/endpoints.py
@@ -500,7 +500,7 @@ async def cancel_batch(
_cancel_batch_data = CancelBatchRequest(batch_id=batch_id, **data)
response = await litellm.acancel_batch(
custom_llm_provider=custom_llm_provider, # type: ignore
- **_cancel_batch_data
+ **_cancel_batch_data,
)
### ALERTING ###
diff --git a/litellm/proxy/openai_files_endpoints/common_utils.py b/litellm/proxy/openai_files_endpoints/common_utils.py
index c176a383f1f..7e56e7f609a 100644
--- a/litellm/proxy/openai_files_endpoints/common_utils.py
+++ b/litellm/proxy/openai_files_endpoints/common_utils.py
@@ -1,6 +1,6 @@
import base64
import re
-from typing import List, Literal, Union
+from typing import List, Literal, Optional, Union
from litellm.types.utils import SpecialEnums
@@ -43,3 +43,24 @@ def get_models_from_unified_file_id(unified_file_id: str) -> List[str]:
return []
except Exception:
return []
+
+
+def get_model_id_from_unified_batch_id(file_id: str) -> Optional[str]:
+ """
+ Get the model_id from the file_id
+
+ Expected format: litellm_proxy;model_id:{};llm_batch_id:{};llm_output_file_id:{}
+ """
+ ## use regex to get the model_id from the file_id
+ try:
+ return file_id.split("model_id:")[1].split(";")[0]
+ except Exception:
+ return None
+
+
+def get_batch_id_from_unified_batch_id(file_id: str) -> str:
+ ## use regex to get the batch_id from the file_id
+ if "llm_batch_id" in file_id:
+ return file_id.split("llm_batch_id:")[1].split(",")[0]
+ else:
+ return file_id.split("generic_response_id:")[1].split(",")[0]
diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prisma
index 76f91aa1e4d..9b0fbbaa8f2 100644
--- a/litellm/proxy/schema.prisma
+++ b/litellm/proxy/schema.prisma
@@ -452,8 +452,8 @@ enum JobStatus {
model LiteLLM_ManagedFileTable {
id String @id @default(uuid())
unified_file_id String @unique // The base64 encoded unified file ID
- file_object Json // Stores the OpenAIFileObject
- model_mappings Json
+ file_object Json? // Stores the OpenAIFileObject
+ model_mappings Json
flat_model_file_ids String[] @default([]) // Flat list of model file id's - for faster querying of model id -> unified file id
created_at DateTime @default(now())
created_by String?
@@ -468,7 +468,8 @@ model LiteLLM_ManagedObjectTable { // for batches or finetuning jobs which use t
unified_object_id String @unique // The base64 encoded unified file ID
model_object_id String @unique // the id returned by the backend API provider
file_object Json // Stores the OpenAIFileObject
- file_purpose String // either 'batch' or 'fine-tune'
+ file_purpose String // either 'batch' or 'fine-tune'
+ status String? // check if batch cost has been tracked
created_at DateTime @default(now())
created_by String?
updated_at DateTime @updatedAt
diff --git a/litellm/router_utils/common_utils.py b/litellm/router_utils/common_utils.py
index 4f4cb8687ef..18658d951dc 100644
--- a/litellm/router_utils/common_utils.py
+++ b/litellm/router_utils/common_utils.py
@@ -1,10 +1,6 @@
import hashlib
import json
-<<<<<<< litellm_dev_06_25_2025_p2
from typing import TYPE_CHECKING, Dict, List, Optional, Union
-=======
-from typing import TYPE_CHECKING, Dict, List, Union
->>>>>>> main
if TYPE_CHECKING:
from litellm.types.llms.openai import OpenAIFileObject
@@ -42,7 +38,6 @@ def add_model_file_id_mappings(
for model_id, file_id in healthy_deployments.items():
model_file_id_mapping[model_id] = file_id
return model_file_id_mapping
-<<<<<<< litellm_dev_06_25_2025_p2
def filter_team_based_models(
@@ -78,5 +73,3 @@ def filter_team_based_models(
for deployment in healthy_deployments
if deployment.get("model_info", {}).get("id") not in ids_to_remove
]
-=======
->>>>>>> main
diff --git a/schema.prisma b/schema.prisma
index cff89a8cd94..9b0fbbaa8f2 100644
--- a/schema.prisma
+++ b/schema.prisma
@@ -16,7 +16,7 @@ model LiteLLM_BudgetTable {
tpm_limit BigInt?
rpm_limit BigInt?
model_max_budget Json?
- budget_duration String?
+ budget_duration String?
budget_reset_at DateTime?
created_at DateTime @default(now()) @map("created_at")
created_by String
@@ -25,8 +25,8 @@ model LiteLLM_BudgetTable {
organization LiteLLM_OrganizationTable[] // multiple orgs can have the same budget
keys LiteLLM_VerificationToken[] // multiple keys can have the same budget
end_users LiteLLM_EndUserTable[] // multiple end-users can have the same budget
- team_membership LiteLLM_TeamMembership[] // budgets of Users within a Team
- organization_membership LiteLLM_OrganizationMembership[] // budgets of Users within a Organization
+ team_membership LiteLLM_TeamMembership[] // budgets of Users within a Team
+ organization_membership LiteLLM_OrganizationMembership[] // budgets of Users within a Organization
}
// Models on proxy
@@ -34,7 +34,7 @@ model LiteLLM_CredentialsTable {
credential_id String @id @default(uuid())
credential_name String @unique
credential_values Json
- credential_info Json?
+ credential_info Json?
created_at DateTime @default(now()) @map("created_at")
created_by String
updated_at DateTime @default(now()) @updatedAt @map("updated_at")
@@ -44,9 +44,9 @@ model LiteLLM_CredentialsTable {
// Models on proxy
model LiteLLM_ProxyModelTable {
model_id String @id @default(uuid())
- model_name String
+ model_name String
litellm_params Json
- model_info Json?
+ model_info Json?
created_at DateTime @default(now()) @map("created_at")
created_by String
updated_at DateTime @default(now()) @updatedAt @map("updated_at")
@@ -67,7 +67,7 @@ model LiteLLM_OrganizationTable {
updated_at DateTime @default(now()) @updatedAt @map("updated_at")
updated_by String
litellm_budget_table LiteLLM_BudgetTable? @relation(fields: [budget_id], references: [budget_id])
- teams LiteLLM_TeamTable[]
+ teams LiteLLM_TeamTable[]
users LiteLLM_UserTable[]
keys LiteLLM_VerificationToken[]
members LiteLLM_OrganizationMembership[] @relation("OrganizationToMembership")
@@ -86,10 +86,10 @@ model LiteLLM_ModelTable {
}
-// Assign prod keys to groups, not individuals
+// Assign prod keys to groups, not individuals
model LiteLLM_TeamTable {
team_id String @id @default(uuid())
- team_alias String?
+ team_alias String?
organization_id String?
object_permission_id String?
admins String[]
@@ -102,7 +102,7 @@ model LiteLLM_TeamTable {
max_parallel_requests Int?
tpm_limit BigInt?
rpm_limit BigInt?
- budget_duration String?
+ budget_duration String?
budget_reset_at DateTime?
blocked Boolean @default(false)
created_at DateTime @default(now()) @map("created_at")
@@ -119,7 +119,7 @@ model LiteLLM_TeamTable {
// Track spend, rate limit, budget Users
model LiteLLM_UserTable {
user_id String @id
- user_alias String?
+ user_alias String?
team_id String?
sso_user_id String? @unique
organization_id String?
@@ -135,7 +135,7 @@ model LiteLLM_UserTable {
max_parallel_requests Int?
tpm_limit BigInt?
rpm_limit BigInt?
- budget_duration String?
+ budget_duration String?
budget_reset_at DateTime?
allowed_cache_controls String[] @default([])
model_spend Json @default("{}")
@@ -162,7 +162,7 @@ model LiteLLM_ObjectPermissionTable {
users LiteLLM_UserTable[]
}
-// Holds the MCP server configuration
+// Holds the MCP server configuration
model LiteLLM_MCPServerTable {
server_id String @id @default(uuid())
alias String?
@@ -170,7 +170,7 @@ model LiteLLM_MCPServerTable {
url String
transport String @default("sse")
spec_version String @default("2025-03-26")
- auth_type String?
+ auth_type String?
created_at DateTime? @default(now()) @map("created_at")
created_by String?
updated_at DateTime? @default(now()) @updatedAt @map("updated_at")
@@ -196,8 +196,8 @@ model LiteLLM_VerificationToken {
blocked Boolean?
tpm_limit BigInt?
rpm_limit BigInt?
- max_budget Float?
- budget_duration String?
+ max_budget Float?
+ budget_duration String?
budget_reset_at DateTime?
allowed_cache_controls String[] @default([])
allowed_routes String[] @default([])
@@ -254,7 +254,7 @@ model LiteLLM_SpendLogs {
cache_hit String? @default("")
cache_key String? @default("")
request_tags Json? @default("[]")
- team_id String?
+ team_id String?
end_user String?
requester_ip_address String?
messages Json? @default("{}")
@@ -272,7 +272,7 @@ model LiteLLM_ErrorLogs {
request_id String @id @default(uuid())
startTime DateTime // Assuming start_time is a DateTime field
endTime DateTime // Assuming end_time is a DateTime field
- api_base String @default("")
+ api_base String @default("")
model_group String @default("") // public model_name / model_group
litellm_model_name String @default("") // model passed to litellm
model_id String @default("") // ID of model in ProxyModelTable
@@ -285,7 +285,7 @@ model LiteLLM_ErrorLogs {
// Beta - allow team members to request access to a model
model LiteLLM_UserNotifications {
request_id String @id
- user_id String
+ user_id String
models String[]
justification String
status String // approved, disapproved, pending
@@ -297,7 +297,7 @@ model LiteLLM_TeamMembership {
team_id String
spend Float @default(0.0)
budget_id String?
- litellm_budget_table LiteLLM_BudgetTable? @relation(fields: [budget_id], references: [budget_id], onDelete: Cascade, onUpdate: Cascade)
+ litellm_budget_table LiteLLM_BudgetTable? @relation(fields: [budget_id], references: [budget_id])
@@id([user_id, team_id])
}
@@ -315,8 +315,8 @@ model LiteLLM_OrganizationMembership {
user LiteLLM_UserTable @relation(fields: [user_id], references: [user_id])
organization LiteLLM_OrganizationTable @relation("OrganizationToMembership", fields: [organization_id], references: [organization_id])
litellm_budget_table LiteLLM_BudgetTable? @relation(fields: [budget_id], references: [budget_id])
-
-
+
+
@@id([user_id, organization_id])
@@unique([user_id, organization_id])
@@ -349,19 +349,19 @@ model LiteLLM_AuditLog {
action String // create, update, delete
table_name String // on of LitellmTableNames.TEAM_TABLE_NAME, LitellmTableNames.USER_TABLE_NAME, LitellmTableNames.PROXY_MODEL_TABLE_NAME,
object_id String // id of the object being audited. This can be the key id, team id, user id, model id
- before_value Json? // value of the row
+ before_value Json? // value of the row
updated_values Json? // value of the row after change
}
// Track daily user spend metrics per model and key
model LiteLLM_DailyUserSpend {
id String @id @default(uuid())
- user_id String?
+ user_id String?
date String
- api_key String
- model String
- model_group String?
- custom_llm_provider String?
+ api_key String
+ model String
+ model_group String?
+ custom_llm_provider String?
prompt_tokens BigInt @default(0)
completion_tokens BigInt @default(0)
cache_read_input_tokens BigInt @default(0)
@@ -385,10 +385,10 @@ model LiteLLM_DailyTeamSpend {
id String @id @default(uuid())
team_id String?
date String
- api_key String
- model String
- model_group String?
- custom_llm_provider String?
+ api_key String
+ model String
+ model_group String?
+ custom_llm_provider String?
prompt_tokens BigInt @default(0)
completion_tokens BigInt @default(0)
cache_read_input_tokens BigInt @default(0)
@@ -410,12 +410,12 @@ model LiteLLM_DailyTeamSpend {
// Track daily team spend metrics per model and key
model LiteLLM_DailyTagSpend {
id String @id @default(uuid())
- tag String?
+ tag String?
date String
- api_key String
- model String
- model_group String?
- custom_llm_provider String?
+ api_key String
+ model String
+ model_group String?
+ custom_llm_provider String?
prompt_tokens BigInt @default(0)
completion_tokens BigInt @default(0)
cache_read_input_tokens BigInt @default(0)
@@ -452,27 +452,28 @@ enum JobStatus {
model LiteLLM_ManagedFileTable {
id String @id @default(uuid())
unified_file_id String @unique // The base64 encoded unified file ID
- file_object Json // Stores the OpenAIFileObject
+ file_object Json? // Stores the OpenAIFileObject
model_mappings Json
flat_model_file_ids String[] @default([]) // Flat list of model file id's - for faster querying of model id -> unified file id
created_at DateTime @default(now())
- created_by String?
+ created_by String?
updated_at DateTime @updatedAt
updated_by String?
@@index([unified_file_id])
}
-model LiteLLM_ManagedObjectTable { // for batches or finetuning jobs which use the
+model LiteLLM_ManagedObjectTable { // for batches or finetuning jobs which use the
id String @id @default(uuid())
unified_object_id String @unique // The base64 encoded unified file ID
- model_object_id String @unique // the id returned by the backend API provider
+ model_object_id String @unique // the id returned by the backend API provider
file_object Json // Stores the OpenAIFileObject
file_purpose String // either 'batch' or 'fine-tune'
+ status String? // check if batch cost has been tracked
created_at DateTime @default(now())
created_by String?
updated_at DateTime @updatedAt
- updated_by String?
+ updated_by String?
@@index([unified_object_id])
@@index([model_object_id])
diff --git a/tests/batches_tests/test_batches_logging_unit_tests.py b/tests/batches_tests/test_batches_logging_unit_tests.py
index 1ec4087794d..281624cd594 100644
--- a/tests/batches_tests/test_batches_logging_unit_tests.py
+++ b/tests/batches_tests/test_batches_logging_unit_tests.py
@@ -157,7 +157,7 @@ async def test_batch_cost_calculator(sample_file_content_dict):
so we expect the cost to be 0.5 * 2 = 1.0
"""
with patch("litellm.completion_cost", return_value=0.5):
- cost = await _batch_cost_calculator(
+ cost = _batch_cost_calculator(
file_content_dictionary=sample_file_content_dict,
custom_llm_provider="openai",
)
diff --git a/tests/enterprise/enterprise_hooks/test_managed_files.py b/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py
similarity index 85%
rename from tests/enterprise/enterprise_hooks/test_managed_files.py
rename to tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py
index 76ebcb9fb94..355e999bccf 100644
--- a/tests/enterprise/enterprise_hooks/test_managed_files.py
+++ b/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py
@@ -1,18 +1,13 @@
import json
import os
import sys
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import HTTPException
from fastapi.testclient import TestClient
+from litellm_enterprise.proxy.hooks.managed_files import _PROXY_LiteLLMManagedFiles
-sys.path.insert(
- 0, os.path.abspath("../../..")
-) # Adds the parent directory to the system path
-
-from unittest.mock import AsyncMock, MagicMock, patch
-
-from enterprise.enterprise_hooks.managed_files import _PROXY_LiteLLMManagedFiles
from litellm.caching import DualCache
from litellm.proxy.openai_files_endpoints.common_utils import (
_is_base64_encoded_unified_file_id,
@@ -323,3 +318,61 @@ async def test_router_acreate_batch_only_selects_from_file_id_mapping(monkeypatc
mock_acreate_batch.assert_called()
assert "5678" in json.dumps(mock_acreate_batch.call_args.kwargs)
+
+
+async def test_output_file_id_for_batch_retrieve():
+ """
+ Test that the output file id is the same as the input file id
+ """
+ from typing import cast
+
+ from openai.types.batch import BatchRequestCounts
+
+ from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.types.utils import LiteLLMBatch
+
+ batch = LiteLLMBatch(
+ id="bGl0ZWxsbV9wcm94eTttb2RlbF9pZDoxMjM0NTY3OTtsbG1fYmF0Y2hfaWQ6YmF0Y2hfNjg1YzVlNWQ2Mzk4ODE5MGI4NWJkYjIxNDdiYTEzMWQ",
+ completion_window="24h",
+ created_at=1750883933,
+ endpoint="/v1/chat/completions",
+ input_file_id="file-8ci8gux8s7oES7GydYvnMG",
+ object="batch",
+ status="completed",
+ cancelled_at=None,
+ cancelling_at=None,
+ completed_at=1750883939,
+ error_file_id=None,
+ errors=None,
+ expired_at=None,
+ expires_at=1750970333,
+ failed_at=None,
+ finalizing_at=1750883938,
+ in_progress_at=1750883934,
+ metadata={"description": "nightly eval job"},
+ output_file_id="file-3BZYhmdJQ3V2oZPAtQsEax",
+ request_counts=BatchRequestCounts(completed=1, failed=0, total=1),
+ usage=None,
+ )
+
+ batch._hidden_params = {
+ "litellm_call_id": "dcd789e0-c0ad-4244-9564-4e611448d650",
+ "api_base": "https://api.openai.com",
+ "model_id": "12345679",
+ "response_cost": 0.0,
+ "additional_headers": {},
+ "litellm_model_name": "gpt-4o",
+ "unified_batch_id": "litellm_proxy;model_id:12345679;llm_batch_id:batch_685c5e5d63988190b85bdb2147ba131d",
+ }
+ proxy_managed_files = _PROXY_LiteLLMManagedFiles(
+ DualCache(), prisma_client=AsyncMock()
+ )
+
+ response = await proxy_managed_files.async_post_call_success_hook(
+ data={},
+ user_api_key_dict=MagicMock(),
+ response=batch,
+ )
+
+ assert not cast(LiteLLMBatch, response).output_file_id.startswith("file-")
diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.py
index 5682a51144f..6752d79224f 100644
--- a/tests/test_litellm/test_router.py
+++ b/tests/test_litellm/test_router.py
@@ -425,7 +425,6 @@ async def test_router_aretrieve_file_content():
assert mock_afile_content.call_args.kwargs["api_base"] == "my-custom-base"
-
@pytest.mark.asyncio
async def test_router_filter_team_based_models():
"""