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]

fix(managed_files): cap batch list page size at 100 and bulk-resolve raw file ids in one query

mateo-berri59041240f036
diff --git a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
index 07a1f959940..6fa6ef46ad4 100644
--- a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
+++ b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
@@ -3,6 +3,7 @@
import base64
import json
+from collections.abc import Mapping
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Dict, Final, List, Literal, Optional, Union, cast
from uuid import NAMESPACE_URL, uuid5
@@ -31,10 +32,12 @@ from litellm.proxy._types import (
)
from litellm.proxy.openai_files_endpoints.common_utils import (
_is_base64_encoded_unified_file_id,
+ apply_unified_file_ids,
ensure_batch_response_managed_file_ids,
get_batch_id_from_unified_batch_id,
get_content_type_from_file_object,
get_model_id_from_unified_batch_id,
+ map_raw_file_ids_to_unified,
normalize_mime_type_for_provider,
resolve_managed_output_file_model_name,
)
@@ -62,6 +65,9 @@ if TYPE_CHECKING:
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
+ from prisma.models import (
+ LiteLLM_ManagedObjectTable as PrismaManagedObjectRow,
+ )
from litellm.proxy.utils import InternalUsageCache as _InternalUsageCache
from litellm.proxy.utils import PrismaClient as _PrismaClient
@@ -75,6 +81,20 @@ else:
PrismaClient = Any
+def _decode_json_blob(blob: object) -> object:
+ return json.loads(blob) if isinstance(blob, str) else blob
+
+
+def _parse_managed_batch_row(row: "PrismaManagedObjectRow") -> Optional[LiteLLMBatch]:
+ try:
+ batch_obj: Final = LiteLLMBatch.model_validate(_decode_json_blob(row.file_object))
+ except Exception as e:
+ verbose_logger.warning(f"Failed to parse batch object {row.unified_object_id}: {e}")
+ return None
+ batch_obj.id = row.unified_object_id
+ return batch_obj
+
+
class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
# Class variables or attributes
def __init__(
@@ -329,7 +349,7 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
detail=f"Invalid 'after' cursor: no batch found with id '{after}'.",
)
- page_size = limit or 20
+ page_size: Final = min(limit or 20, 100)
cursor_args: Dict[str, Any] = (
{"cursor": {"unified_object_id": after}, "skip": 1} if after else {}
)
@@ -343,36 +363,60 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
has_more = len(batches) > page_size
- batch_objects: List[LiteLLMBatch] = []
- for batch in batches[:page_size]:
- try:
- batch_data = (
- json.loads(batch.file_object)
- if isinstance(batch.file_object, str)
- else batch.file_object
- )
- batch_obj = LiteLLMBatch.model_validate(batch_data)
- batch_obj.id = batch.unified_object_id
- await ensure_batch_response_managed_file_ids(
- response=batch_obj,
- managed_files_obj=self,
- prisma_client=self.prisma_client,
- verbose_proxy_logger=verbose_logger,
- user_api_key_dict=user_api_key_dict,
- db_batch_object=batch,
- unified_batch_id=_is_base64_encoded_unified_file_id(
- batch.unified_object_id
- ),
- )
- batch_objects.append(batch_obj)
-
- except Exception as e:
- verbose_logger.warning(
- f"Failed to parse batch object {batch.unified_object_id}: {e}"
- )
- continue
+ parsed_rows: Final = tuple(
+ (row, batch_obj)
+ for row in batches[:page_size]
+ if (batch_obj := _parse_managed_batch_row(row)) is not None
+ )
+ unified_id_by_raw_id: Final = await map_raw_file_ids_to_unified(
+ raw_file_ids=frozenset(
+ file_id
+ for _, batch_obj in parsed_rows
+ for file_id in (batch_obj.input_file_id, batch_obj.output_file_id, batch_obj.error_file_id)
+ if file_id and not _is_base64_encoded_unified_file_id(file_id)
+ ),
+ prisma_client=self.prisma_client,
+ )
+ resolved_batches: Final = [
+ await self._resolve_listed_batch(
+ row=row,
+ batch_obj=batch_obj,
+ unified_id_by_raw_id=unified_id_by_raw_id,
+ user_api_key_dict=user_api_key_dict,
+ )
+ for row, batch_obj in parsed_rows
+ ]
+ return build_list_page(
+ [batch_obj for batch_obj in resolved_batches if batch_obj is not None],
+ has_more=has_more,
+ )
- return build_list_page(batch_objects, has_more=has_more)
+ async def _resolve_listed_batch(
+ self,
+ row: "PrismaManagedObjectRow",
+ batch_obj: LiteLLMBatch,
+ unified_id_by_raw_id: Mapping[str, str],
+ user_api_key_dict: UserAPIKeyAuth,
+ ) -> Optional[LiteLLMBatch]:
+ apply_unified_file_ids(batch_obj, unified_id_by_raw_id)
+ try:
+ await ensure_batch_response_managed_file_ids(
+ response=batch_obj,
+ managed_files_obj=self,
+ prisma_client=self.prisma_client,
+ verbose_proxy_logger=verbose_logger,
+ user_api_key_dict=user_api_key_dict,
+ db_batch_object=row,
+ unified_batch_id=_is_base64_encoded_unified_file_id(
+ row.unified_object_id
+ ),
+ )
+ except Exception as e:
+ verbose_logger.warning(
+ f"Failed to resolve managed file ids for batch {row.unified_object_id}: {e}"
+ )
+ return None
+ return batch_obj
async def get_user_created_file_ids(
self, user_api_key_dict: UserAPIKeyAuth, model_object_ids: List[str]
diff --git a/litellm/proxy/openai_files_endpoints/common_utils.py b/litellm/proxy/openai_files_endpoints/common_utils.py
index 080b8b80ae4..bf83a7cf25c 100644
--- a/litellm/proxy/openai_files_endpoints/common_utils.py
+++ b/litellm/proxy/openai_files_endpoints/common_utils.py
@@ -1,6 +1,7 @@
import base64
import mimetypes
import re
+from collections.abc import Mapping
from dataclasses import dataclass, field
from types import MappingProxyType
from typing import TYPE_CHECKING, Final, Literal, Optional
@@ -16,6 +17,7 @@ if TYPE_CHECKING:
from prisma.models import LiteLLM_ManagedObjectTable
from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.proxy.utils import PrismaClient
from litellm.router import Router
from litellm.types.utils import LiteLLMBatch
@@ -1002,6 +1004,34 @@ async def resolve_output_file_ids_to_unified(response, prisma_client) -> None:
pass
+async def map_raw_file_ids_to_unified(
+ raw_file_ids: frozenset[str], prisma_client: "PrismaClient | None"
+) -> Mapping[str, str]:
+ if not raw_file_ids or not prisma_client:
+ return MappingProxyType({})
+ managed_files: Final = await ManagedFileRepository(prisma_client).table.find_many(
+ where={"flat_model_file_ids": {"hasSome": sorted(raw_file_ids)}} # mutable-ok: prisma where is a plain dict
+ )
+ return MappingProxyType(
+ {
+ raw_id: managed_file.unified_file_id
+ for managed_file in managed_files
+ for raw_id in managed_file.flat_model_file_ids
+ if raw_id in raw_file_ids
+ }
+ )
+
+
+def apply_unified_file_ids(response: "LiteLLMBatch", unified_id_by_raw_id: Mapping[str, str]) -> None:
+ for file_attr, raw_id in (
+ ("input_file_id", getattr(response, "input_file_id", None)),
+ ("output_file_id", getattr(response, "output_file_id", None)),
+ ("error_file_id", getattr(response, "error_file_id", None)),
+ ):
+ if isinstance(raw_id, str) and raw_id in unified_id_by_raw_id:
+ setattr(response, file_attr, unified_id_by_raw_id[raw_id])
+
+
async def ensure_batch_response_managed_file_ids(
response,
managed_files_obj,
diff --git a/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py b/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py
index fc10a1257e1..e1e5cc6c532 100644
--- a/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py
+++ b/tests/enterprise/litellm_enterprise/proxy/hooks/test_managed_files.py
@@ -1869,15 +1869,12 @@ async def test_list_batches_registers_and_returns_unified_output_file_ids():
input_file_row = MagicMock()
input_file_row.unified_file_id = unified_input_file_id
+ input_file_row.flat_model_file_ids = [raw_input_file_id]
- def find_managed_file(where):
- if where["flat_model_file_ids"]["has"] == raw_input_file_id:
- return input_file_row
- return None
-
- prisma_client.db.litellm_managedfiletable.find_first = AsyncMock(
- side_effect=find_managed_file
+ prisma_client.db.litellm_managedfiletable.find_many = AsyncMock(
+ return_value=[input_file_row]
)
+ prisma_client.db.litellm_managedfiletable.find_first = AsyncMock(return_value=None)
proxy_managed_files = _PROXY_LiteLLMManagedFiles(
DualCache(), prisma_client=prisma_client
@@ -1892,6 +1889,13 @@ async def test_list_batches_registers_and_returns_unified_output_file_ids():
assert listed.id == unified_batch_uid
assert listed.input_file_id == unified_input_file_id
+ bulk_lookup = prisma_client.db.litellm_managedfiletable.find_many.await_args
+ assert set(bulk_lookup.kwargs["where"]["flat_model_file_ids"]["hasSome"]) == {
+ raw_input_file_id,
+ raw_output_file_id,
+ raw_error_file_id,
+ }
+
decoded_output = _decode_unified_id(listed.output_file_id)
assert decoded_output.startswith("litellm_proxy")
assert f"llm_output_file_id,{raw_output_file_id}" in decoded_output
@@ -1914,33 +1918,43 @@ async def test_list_batches_registers_and_returns_unified_output_file_ids():
@pytest.mark.asyncio
async def test_list_batches_resolves_existing_managed_rows_without_minting():
"""When the raw provider file IDs already have managed file rows, listing must
- swap in the existing unified IDs and must not upsert duplicate rows."""
+ swap in the existing unified IDs via one bulk lookup for the whole page, with
+ no per-row queries and no duplicate upserts."""
from litellm.proxy._types import UserAPIKeyAuth
- unified_batch_uid = _create_unified_batch_id("model-123", "batch-456")
- raw_output_file_id = "file-list-out-existing"
- existing_unified_output_id = base64.urlsafe_b64encode(
- f"litellm_proxy:application/json;unified_id,u-9;llm_output_file_id,{raw_output_file_id}".encode()
+ unified_input_file_id = base64.urlsafe_b64encode(
+ b"litellm_proxy:application/octet-stream;unified_id,in-9;target_model_names,gpt-5-batch"
).decode()
+ raw_output_file_ids = ["file-list-out-existing-1", "file-list-out-existing-2"]
+ existing_unified_output_ids = [
+ base64.urlsafe_b64encode(
+ f"litellm_proxy:application/json;unified_id,u-{i};llm_output_file_id,{raw_id}".encode()
+ ).decode()
+ for i, raw_id in enumerate(raw_output_file_ids)
+ ]
- record = _terminal_batch_record(
- unified_batch_uid, "file-list-in-9", raw_output_file_id, ""
- )
+ records = [
+ _terminal_batch_record(
+ _create_unified_batch_id("model-123", f"batch-{i}"),
+ unified_input_file_id,
+ raw_id,
+ "",
+ )
+ for i, raw_id in enumerate(raw_output_file_ids)
+ ]
prisma_client = AsyncMock()
- prisma_client.db.litellm_managedobjecttable.find_many.return_value = [record]
-
- existing_row = MagicMock()
- existing_row.unified_file_id = existing_unified_output_id
+ prisma_client.db.litellm_managedobjecttable.find_many.return_value = records
- def find_managed_file(where):
- if where["flat_model_file_ids"]["has"] == raw_output_file_id:
- return existing_row
- return None
+ existing_rows = [
+ MagicMock(unified_file_id=unified_id, flat_model_file_ids=[raw_id])
+ for raw_id, unified_id in zip(raw_output_file_ids, existing_unified_output_ids)
+ ]
- prisma_client.db.litellm_managedfiletable.find_first = AsyncMock(
- side_effect=find_managed_file
+ prisma_client.db.litellm_managedfiletable.find_many = AsyncMock(
+ return_value=existing_rows
)
+ prisma_client.db.litellm_managedfiletable.find_first = AsyncMock()
proxy_managed_files = _PROXY_LiteLLMManagedFiles(
DualCache(), prisma_client=prisma_client
@@ -1951,10 +1965,38 @@ async def test_list_batches_resolves_existing_managed_rows_without_minting():
limit=10,
)
- assert result["data"][0].output_file_id == existing_unified_output_id
+ assert [b.output_file_id for b in result["data"]] == existing_unified_output_ids
+ prisma_client.db.litellm_managedfiletable.find_many.assert_awaited_once()
+ prisma_client.db.litellm_managedfiletable.find_first.assert_not_awaited()
prisma_client.db.litellm_managedfiletable.upsert.assert_not_awaited()
+async def test_list_batches_caps_page_size_at_100():
+ """The list page size must be capped at 100 rows (matching OpenAI's limit)
+ even when the caller asks for more, so one request cannot fan out into an
+ unbounded scan."""
+ from litellm.proxy._types import UserAPIKeyAuth
+
+ prisma_client = AsyncMock()
+ prisma_client.db.litellm_managedobjecttable.find_many.return_value = []
+
+ proxy_managed_files = _PROXY_LiteLLMManagedFiles(
+ DualCache(), prisma_client=prisma_client
+ )
+
+ result = await proxy_managed_files.list_user_batches(
+ user_api_key_dict=UserAPIKeyAuth(user_id="owner-user"),
+ limit=100000,
+ )
+
+ assert (
+ prisma_client.db.litellm_managedobjecttable.find_many.await_args.kwargs["take"]
+ == 101
+ )
+ assert result["data"] == []
+
+
@pytest.mark.asyncio
async def test_list_batches_from_managed_objects_table_provider_filter_raises_exception():
from litellm.proxy._types import UserAPIKeyAuth