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(files): hand post-call hooks a page object, not a bare dict

mateo-berri56953707767e
diff --git a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
index a70d85cf59c..e71b520d27f 100644
--- a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
+++ b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
@@ -57,6 +57,7 @@ from litellm.proxy.openai_files_endpoints.common_utils import (
normalize_mime_type_for_provider,
resolve_managed_output_file_model_name,
validate_file_list_limit,
+ validate_file_list_purpose,
)
from litellm.proxy.pass_through_endpoints.llm_provider_handlers.batch_attribution import (
request_tags_from_metadata,
@@ -66,6 +67,7 @@ from litellm.types.llms.openai import ( # pyright: ignore[reportAttributeAccess
AsyncCursorPage,
ChatCompletionFileObject,
CreateFileRequest,
+ FileListPage,
FileObject,
OpenAIFileObject,
ResponsesAPIResponse,
@@ -1380,7 +1382,7 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
limit: Optional[int] = None,
after: Optional[str] = None,
**data: Dict,
- ) -> Dict[str, object]:
+ ) -> FileListPage:
"""List the managed files the caller owns, newest first.
Pagination is keyset based on ``unified_file_id`` so a key that owns
@@ -1397,10 +1399,11 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
behind the newest rows cannot degenerate into thousands of queries.
"""
validate_file_list_limit(limit)
+ validate_file_list_purpose(purpose)
owner_filter: Final = build_owner_filter(user_api_key_dict)
if owner_filter is None:
- return build_list_page([])
+ return FileListPage(**build_list_page([]))
if after:
cursor_row = await _managed_file_table(self.prisma_client).find_first(
@@ -1439,7 +1442,7 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
cursor_id = chunk[-1].unified_file_id
chunk_size = max(chunk_size, FILE_LIST_CONTINUATION_CHUNK_SIZE)
- return build_list_page(matches[:page_size], has_more=len(matches) > page_size)
+ return FileListPage(**build_list_page(matches[:page_size], has_more=len(matches) > page_size))
def _is_batch_polling_enabled(self) -> bool:
"""
diff --git a/litellm/llms/base_llm/files/transformation.py b/litellm/llms/base_llm/files/transformation.py
index 1576af41e76..b20fe0f1560 100644
--- a/litellm/llms/base_llm/files/transformation.py
+++ b/litellm/llms/base_llm/files/transformation.py
@@ -11,6 +11,7 @@ from litellm.types.llms.openai import (
AllMessageValues,
CreateFileRequest,
FileContentRequest,
+ FileListPage,
OpenAICreateFileRequestOptionalParams,
OpenAIFileObject,
)
@@ -245,7 +246,7 @@ class BaseFileEndpoints(ABC):
limit: int | None = None,
after: str | None = None,
**data: dict,
- ) -> dict[str, object]:
+ ) -> FileListPage:
pass
@abstractmethod
diff --git a/litellm/proxy/openai_files_endpoints/common_utils.py b/litellm/proxy/openai_files_endpoints/common_utils.py
index 837b4c43652..c5213d842a3 100644
--- a/litellm/proxy/openai_files_endpoints/common_utils.py
+++ b/litellm/proxy/openai_files_endpoints/common_utils.py
@@ -4,13 +4,14 @@ import re
from collections.abc import Mapping
from dataclasses import dataclass, field
from types import MappingProxyType
-from typing import TYPE_CHECKING, Final, Literal, Optional, Protocol, runtime_checkable
+from typing import TYPE_CHECKING, Final, Literal, Optional, Protocol, get_args, runtime_checkable
from litellm.proxy._types import ProxyException
from litellm.repositories.table_repositories import (
ManagedFileRepository,
ManagedObjectRepository,
)
+from litellm.types.llms.openai import OpenAIFilesPurpose
from litellm.types.utils import SpecialEnums
if TYPE_CHECKING:
@@ -46,6 +47,25 @@ def validate_file_list_limit(limit: int | None) -> None:
)
+def validate_file_list_purpose(purpose: str | None) -> None:
+ """Reject a ``purpose`` filter the Files API never accepts.
+
+ An unknown purpose matches no file, so filtering on it would report an
+ empty page for what is really a bad request. Rejecting it keeps a managed
+ listing consistent with the upload route and with the provider-backed
+ listings, which both refuse the same values.
+ """
+ valid_purposes: Final = get_args(OpenAIFilesPurpose)
+ if purpose is None or purpose in valid_purposes:
+ return
+ raise ProxyException(
+ message=f"Invalid purpose: {purpose}. Must be one of: {valid_purposes}",
+ type="invalid_request_error",
+ param="purpose",
+ code=400,
+ )
+
+
@runtime_checkable
class ManagedResourceAccessChecker(Protocol):
async def can_user_call_unified_file_id(
diff --git a/litellm/proxy/openai_files_endpoints/files_endpoints.py b/litellm/proxy/openai_files_endpoints/files_endpoints.py
index c9c794d94e3..92bbd58ed90 100644
--- a/litellm/proxy/openai_files_endpoints/files_endpoints.py
+++ b/litellm/proxy/openai_files_endpoints/files_endpoints.py
@@ -69,7 +69,7 @@ from litellm.proxy.openai_files_endpoints.common_utils import (
validate_managed_files_requirement,
validate_managed_id_requirement,
)
-from litellm.proxy.utils import ProxyLogging, handle_exception_on_proxy, is_known_model
+from litellm.proxy.utils import ProxyLogging, is_known_model
from litellm.repositories.table_repositories import ManagedFileRepository
from litellm.router import Router
from litellm.types.llms.openai import (
@@ -1572,4 +1572,20 @@ async def list_files(
)
verbose_proxy_logger.error("litellm.proxy.proxy_server.list_files(): Exception occured - %s", e)
verbose_proxy_logger.debug(traceback.format_exc())
- raise handle_exception_on_proxy(e)
+ if isinstance(e, ProxyException):
+ raise
+ if isinstance(e, HTTPException):
+ raise ProxyException(
+ message=getattr(e, "message", str(e.detail)),
+ type=getattr(e, "type", "None"),
+ param=getattr(e, "param", "None"),
+ code=getattr(e, "status_code", status.HTTP_400_BAD_REQUEST),
+ )
+ else:
+ error_msg: Final = f"{e}"
+ raise ProxyException(
+ message=getattr(e, "message", error_msg),
+ type=getattr(e, "type", "None"),
+ param=getattr(e, "param", "None"),
+ code=getattr(e, "status_code", 500),
+ )
diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.py
index 1588c650177..37de518b231 100644
--- a/litellm/types/llms/openai.py
+++ b/litellm/types/llms/openai.py
@@ -65,6 +65,7 @@ from pydantic import (
BaseModel,
ConfigDict,
Discriminator,
+ Field,
PrivateAttr,
field_serializer,
field_validator,
@@ -381,6 +382,21 @@ class OpenAIFileObject(BaseModel):
return self.dict()
+class FileListPage(BaseModel):
+ """A page of files, as `GET /v1/files` returns it.
+
+ Post-call hooks and logging callbacks are handed the listing response, and
+ the provider SDKs hand them a page object rather than a mapping, so this
+ exposes the same ``.data`` attribute while serializing to an identical body.
+ """
+
+ object: Literal["list"] = "list"
+ data: list[OpenAIFileObject] = Field(default_factory=list)
+ first_id: str | None = None
+ last_id: str | None = None
+ has_more: bool = False
+
+
CREATE_FILE_REQUESTS_PURPOSE = Literal["assistants", "batch", "fine-tune", "messages"]
diff --git a/tests/test_litellm/enterprise/proxy/test_managed_files_hook.py b/tests/test_litellm/enterprise/proxy/test_managed_files_hook.py
index 0b81c1d23e3..1cd6813b065 100644
--- a/tests/test_litellm/enterprise/proxy/test_managed_files_hook.py
+++ b/tests/test_litellm/enterprise/proxy/test_managed_files_hook.py
@@ -14,8 +14,8 @@ import pytest
from typing import Optional
from unittest.mock import AsyncMock, MagicMock, patch
-from litellm.proxy._types import UserAPIKeyAuth
-from litellm.types.llms.openai import OpenAIFileObject
+from litellm.proxy._types import ProxyException, UserAPIKeyAuth
+from litellm.types.llms.openai import FileListPage, OpenAIFileObject
from litellm.types.utils import LiteLLMBatch
@@ -283,10 +283,70 @@ async def test_afile_list_returns_owner_scoped_managed_files():
take=10001,
order=[{"created_at": "desc"}, {"unified_file_id": "desc"}],
)
- assert [file.id for file in response["data"]] == ["unified-file-id"]
- assert response["first_id"] == "unified-file-id"
- assert response["last_id"] == "unified-file-id"
- assert response["has_more"] is False
+ assert [file.id for file in response.data] == ["unified-file-id"]
+ assert response.first_id == "unified-file-id"
+ assert response.last_id == "unified-file-id"
+ assert response.has_more is False
+
+
+async def test_afile_list_returns_a_page_object_callbacks_can_read():
+ """Post-call hooks receive the listing and read ``.data`` off it, the way the
+ provider SDK's page lets them. The body on the wire stays a plain list page."""
+ from fastapi.encoders import jsonable_encoder
+
+ managed_files, _ = _make_managed_files_over_rows([_make_managed_file_row("unified-file-id")])
+
+ page = await managed_files.afile_list(
+ purpose=None,
+ litellm_parent_otel_span=None,
+ user_api_key_dict=_make_user_api_key_dict(),
+ )
+
+ assert isinstance(page, FileListPage)
+ assert [file.id for file in page.data] == ["unified-file-id"]
+
+ body = jsonable_encoder(page)
+ assert list(body) == ["object", "data", "first_id", "last_id", "has_more"]
+ assert body["object"] == "list"
+ assert [file["id"] for file in body["data"]] == ["unified-file-id"]
+ assert body["first_id"] == "unified-file-id"
+ assert body["last_id"] == "unified-file-id"
+ assert body["has_more"] is False
+
+
[email protected]("purpose", ["nonexistent_purpose", "EVALS", "batch "])
+async def test_afile_list_rejects_a_purpose_the_files_api_never_accepts(purpose):
+ """No stored file can carry an undocumented purpose, so filtering on one is a
+ bad request rather than a legitimately empty page."""
+ managed_files, table = _make_managed_files_over_rows([_make_managed_file_row("unified-file-id")])
+
+ with pytest.raises(ProxyException) as exc_info:
+ await managed_files.afile_list(
+ purpose=purpose,
+ litellm_parent_otel_span=None,
+ user_api_key_dict=_make_user_api_key_dict(),
+ )
+
+ assert exc_info.value.code == "400"
+ assert exc_info.value.type == "invalid_request_error"
+ assert exc_info.value.param == "purpose"
+ assert table.find_many_calls == []
+
+
[email protected]("purpose", ["batch", "assistants", "fine-tune", None])
+async def test_afile_list_accepts_every_documented_purpose(purpose):
+ managed_files, _ = _make_managed_files_over_rows([_make_managed_file_row("unified-file-id")])
+
+ page = await managed_files.afile_list(
+ purpose=purpose,
+ litellm_parent_otel_span=None,
+ user_api_key_dict=_make_user_api_key_dict(),
+ )
+
+ assert isinstance(page, FileListPage)
@pytest.mark.asyncio
@@ -305,7 +365,7 @@ async def test_afile_list_does_not_leak_another_callers_files():
user_api_key_dict=_make_user_api_key_dict(),
)
- assert [file.id for file in response["data"]] == ["unified-mine-2", "unified-mine-1"]
+ assert [file.id for file in response.data] == ["unified-mine-2", "unified-mine-1"]
assert table.find_many_calls[0]["where"] == {"created_by": "test-user"}
@@ -319,8 +379,8 @@ async def test_afile_list_denies_a_caller_without_a_user_or_team():
user_api_key_dict=UserAPIKeyAuth(api_key="sk-test", parent_otel_span=None),
)
- assert response["data"] == []
- assert response["has_more"] is False
+ assert response.data == []
+ assert response.has_more is False
assert table.find_many_calls == []
@@ -339,7 +399,7 @@ async def test_afile_list_filters_by_purpose():
user_api_key_dict=_make_user_api_key_dict(),
)
- assert [file.id for file in response["data"]] == ["unified-batch"]
+ assert [file.id for file in response.data] == ["unified-batch"]
async def _walk_afile_list(managed_files, user_api_key_dict, purpose, limit):
@@ -354,10 +414,10 @@ async def _walk_afile_list(managed_files, user_api_key_dict, purpose, limit):
limit=limit,
after=after,
)
- page_ids = [file.id for file in page["data"]]
+ page_ids = [file.id for file in page.data]
assert not set(page_ids) & set(seen)
seen.extend(page_ids)
- if not page["has_more"]:
+ if not page.has_more:
return seen
assert page_ids, "an SDK stops paging on an empty page, so has_more must never ride one"
after = page_ids[-1]
@@ -384,20 +444,20 @@ async def test_afile_list_fills_a_page_past_rows_the_purpose_filter_drops():
limit=1,
)
- assert [file.id for file in first_page["data"]] == ["unified-2"]
- assert first_page["has_more"] is True
- assert first_page["last_id"] == "unified-2"
+ assert [file.id for file in first_page.data] == ["unified-2"]
+ assert first_page.has_more is True
+ assert first_page.last_id == "unified-2"
second_page = await managed_files.afile_list(
purpose="batch",
litellm_parent_otel_span=None,
user_api_key_dict=user_api_key_dict,
limit=1,
- after=first_page["last_id"],
+ after=first_page.last_id,
)
- assert [file.id for file in second_page["data"]] == ["unified-4"]
- assert second_page["has_more"] is False
+ assert [file.id for file in second_page.data] == ["unified-4"]
+ assert second_page.has_more is False
@pytest.mark.parametrize("limit", [1, 2, 3])
@@ -437,8 +497,8 @@ async def test_afile_list_fills_a_page_past_rows_that_do_not_parse():
limit=1,
)
- assert [file.id for file in page["data"]] == ["unified-2"]
- assert page["has_more"] is False
+ assert [file.id for file in page.data] == ["unified-2"]
+ assert page.has_more is False
_DEEP_SCAN_ROW_COUNT = 2000
@@ -460,8 +520,8 @@ async def test_afile_list_bounds_the_queries_a_deep_purpose_match_costs():
limit=1,
)
- assert [file.id for file in page["data"]] == ["unified-match"]
- assert page["has_more"] is False
+ assert [file.id for file in page.data] == ["unified-match"]
+ assert page.has_more is False
assert len(table.find_many_calls) <= _DEEP_SCAN_QUERY_BUDGET
@@ -480,8 +540,8 @@ async def test_afile_list_bounds_the_queries_a_deep_unparseable_run_costs():
limit=1,
)
- assert [file.id for file in page["data"]] == ["unified-parses"]
- assert page["has_more"] is False
+ assert [file.id for file in page.data] == ["unified-parses"]
+ assert page.has_more is False
assert len(table.find_many_calls) <= _DEEP_SCAN_QUERY_BUDGET
@@ -499,8 +559,8 @@ async def test_afile_list_reads_one_chunk_when_the_first_one_fills_the_page():
limit=2,
)
- assert [file.id for file in page["data"]] == ["unified-00000", "unified-00001"]
- assert page["has_more"] is True
+ assert [file.id for file in page.data] == ["unified-00000", "unified-00001"]
+ assert page.has_more is True
assert [call["take"] for call in table.find_many_calls] == [3]
@@ -517,10 +577,10 @@ async def test_afile_list_reports_no_more_pages_when_nothing_matches():
limit=2,
)
- assert page["data"] == []
- assert page["has_more"] is False
- assert page["first_id"] is None
- assert page["last_id"] is None
+ assert page.data == []
+ assert page.has_more is False
+ assert page.first_id is None
+ assert page.last_id is None
@pytest.mark.asyncio
@@ -536,8 +596,8 @@ async def test_afile_list_honors_limit_and_reports_more_pages():
limit=2,
)
- assert [file.id for file in response["data"]] == ["unified-0", "unified-1"]
- assert response["has_more"] is True
+ assert [file.id for file in response.data] == ["unified-0", "unified-1"]
+ assert response.has_more is True
assert table.find_many_calls[0]["take"] == 3
@@ -558,12 +618,12 @@ async def test_afile_list_pages_through_every_file_without_overlap():
limit=2,
after=after,
)
- page_ids = [file.id for file in page["data"]]
+ page_ids = [file.id for file in page.data]
assert not set(page_ids) & set(seen)
seen.extend(page_ids)
- if not page["has_more"]:
+ if not page.has_more:
break
- after = page["last_id"]
+ after = page.last_id
assert seen == [f"unified-{index}" for index in range(5)]
assert table.find_many_calls[1]["cursor"] == {"unified_file_id": "unified-1"}
@@ -648,8 +708,8 @@ async def test_afile_list_accepts_the_ends_of_the_openai_limit_range(limit):
limit=limit,
)
- assert [file.id for file in response["data"]] == ["unified-mine"]
- assert response["has_more"] is False
+ assert [file.id for file in response.data] == ["unified-mine"]
+ assert response.has_more is False
assert table.find_many_calls[0]["take"] == limit + 1
diff --git a/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py b/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py
index 5bc77f1bd7a..fbee23108cf 100644
--- a/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py
+++ b/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py
@@ -24,7 +24,11 @@ from litellm.proxy.openai_files_endpoints.file_content_streaming_handler import
FileContentStreamingHandler,
)
from litellm.proxy.proxy_server import app
-from litellm.types.llms.openai import HttpxBinaryResponseContent, OpenAIFileObject
+from litellm.types.llms.openai import (
+ FileListPage,
+ HttpxBinaryResponseContent,
+ OpenAIFileObject,
+)
client = TestClient(app)
from litellm.caching.caching import DualCache
@@ -2640,16 +2644,20 @@ _EMPTY_FILE_LIST_PAGE: Final = {
async def _validating_afile_list(**kwargs):
- """Stand in for the managed file store, applying the real limit validation."""
- from litellm.proxy.openai_files_endpoints.common_utils import validate_file_list_limit
+ """Stand in for the managed file store, applying the real request validation."""
+ from litellm.proxy.openai_files_endpoints.common_utils import (
+ validate_file_list_limit,
+ validate_file_list_purpose,
+ )
validate_file_list_limit(kwargs.get("limit"))
- return dict(_EMPTY_FILE_LIST_PAGE)
+ validate_file_list_purpose(kwargs.get("purpose"))
+ return FileListPage(**_EMPTY_FILE_LIST_PAGE)
async def _permissive_afile_list(**kwargs):
"""Stand in for a file store that validates nothing, so only the route can reject."""
- return dict(_EMPTY_FILE_LIST_PAGE)
+ return FileListPage(**_EMPTY_FILE_LIST_PAGE)
@pytest.mark.parametrize(
@@ -2748,6 +2756,119 @@ def test_unscoped_list_files_returns_400_for_an_unknown_after_cursor(
}
+def _managed_file(file_id: str) -> OpenAIFileObject:
+ return OpenAIFileObject(
+ id=file_id,
+ bytes=17,
+ created_at=1700000000,
+ filename="batch_input.jsonl",
+ object="file",
+ purpose="batch",
+ status="uploaded",
+ )
+
+
+def test_unscoped_list_files_hands_post_call_hooks_a_page_object(
+ mocker: MockerFixture, monkeypatch, llm_router: Router
+):
+ """Logging callbacks read ``response.data`` off a listing, so the managed
+ branch has to hand them the same page shape the provider branch does. A bare
+ mapping turns every registered callback into a 500 on this route."""
+ import litellm.proxy.proxy_server as ps
+
+ seen_by_callback: list[list[str]] = []
+
+ async def _reads_response_data(data, user_api_key_dict, response):
+ seen_by_callback.append([file.id for file in response.data])
+ return None
+
+ async def _one_managed_file(**kwargs):
+ return FileListPage(
+ data=[_managed_file("unified-file-id")],
+ first_id="unified-file-id",
+ last_id="unified-file-id",
+ )
+
+ _setup_unscoped_list_files_route(mocker, monkeypatch, llm_router, _one_managed_file)
+ ps.proxy_logging_obj.post_call_success_hook = _reads_response_data
+
+ response = _get_unscoped_list_files("")
+
+ assert response.status_code == 200, response.text
+ assert seen_by_callback == [["unified-file-id"]]
+ body = response.json()
+ assert list(body) == ["object", "data", "first_id", "last_id", "has_more"]
+ assert body["object"] == "list"
+ assert [file["id"] for file in body["data"]] == ["unified-file-id"]
+ assert body["has_more"] is False
+
+
[email protected]("purpose", ["nonexistent_purpose", "EVALS", "batch "])
+def test_unscoped_list_files_returns_400_for_a_purpose_the_api_never_accepts(
+ mocker: MockerFixture, monkeypatch, llm_router: Router, purpose
+):
+ """An unknown purpose matches nothing, so reporting an empty page would dress
+ a bad request up as a successful one. The provider-backed branches reject the
+ same values, and so does the upload route."""
+ from urllib.parse import quote
+
+ _setup_unscoped_list_files_route(mocker, monkeypatch, llm_router, _validating_afile_list)
+
+ response = _get_list_files(f"/v1/files?purpose={quote(purpose)}")
+
+ assert response.status_code == 400, response.text
+ assert response.json()["error"]["param"] == "purpose"
+ assert response.json()["error"]["type"] == "invalid_request_error"
+ assert response.json()["error"]["message"].startswith(f"Invalid purpose: {purpose}. Must be one of: ")
+
+
[email protected]("purpose", ["batch", "assistants", "fine-tune"])
+def test_unscoped_list_files_accepts_every_documented_purpose(
+ mocker: MockerFixture, monkeypatch, llm_router: Router, purpose
+):
+ managed_files = _setup_unscoped_list_files_route(mocker, monkeypatch, llm_router, _validating_afile_list)
+
+ response = _get_list_files(f"/v1/files?purpose={purpose}")
+
+ assert response.status_code == 200, response.text
+ assert managed_files.afile_list.await_args.kwargs["purpose"] == purpose
+
+
+def test_list_files_reports_a_bad_target_model_names_as_a_400(
+ mocker: MockerFixture, monkeypatch, llm_router: Router
+):
+ """The exception tail reports an HTTPException with its own status and error
+ type rather than relabelling it, so a client that branches on either keeps
+ reading the same thing off a bad request."""
+ _setup_unscoped_list_files_route(mocker, monkeypatch, llm_router, _permissive_afile_list)
+
+ response = _get_list_files("/v1/files?target_model_names=gpt-3.5-turbo,gpt-4o")
+
+ assert response.status_code == 400, response.text
+ assert response.json() == {
+ "error": {
+ "message": "target_model_names on list files must be a list of one model name. Example: ['gpt-4o']",
+ "type": "None",
+ "param": "None",
+ "code": "400",
+ }
+ }
+
+
+def test_list_files_reports_an_unexpected_file_store_error_as_a_500(
+ mocker: MockerFixture, monkeypatch, llm_router: Router
+):
+ async def _blows_up(**kwargs):
+ raise RuntimeError("managed file table is unreachable")
+
+ _setup_unscoped_list_files_route(mocker, monkeypatch, llm_router, _blows_up)
+
+ response = _get_unscoped_list_files("")
+
+ assert response.status_code == 500, response.text
+ assert response.json()["error"]["message"] == "managed file table is unreachable"
+
+
def test_list_files_restricted_team_does_not_leak_global_openai_credentials(
mocker: MockerFixture, monkeypatch
):