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(proxy): keep every value of a repeated form key in get_form_data
ryan-crabbe-berrib57367938428
diff --git a/litellm/proxy/common_utils/http_parsing_utils.py b/litellm/proxy/common_utils/http_parsing_utils.pyindex 1e4344a71f4..4cb55f6966e 100644--- a/litellm/proxy/common_utils/http_parsing_utils.py+++ b/litellm/proxy/common_utils/http_parsing_utils.py@@ -274,10 +274,10 @@ async def get_form_data(request: Request) -> dict[str, Any]:Handles when OpenAI SDKs pass form keys as `timestamp_granularities[]="word"` instead of `timestamp_granularities=["word", "sentence"]`"""form: Final = await request.form()- form_data: Final = dict(form)parsed_form_data: Final[dict[str, Any]] = {}- for key, value in form_data.items():- # OpenAI SDKs pass form keys as `timestamp_granularities[]="word"` instead of `timestamp_granularities=["word", "sentence"]`+ # multi_items(), not dict(form): a dict drops every value but the last of a repeated key,+ # which is the whole array this function exists to rebuild+ for key, value in form.multi_items():if key.endswith("[]"):clean_key = key[:-2]parsed_form_data.setdefault(clean_key, []).append(value)diff --git a/tests/test_litellm/ocr/test_ocr_file_input.py b/tests/test_litellm/ocr/test_ocr_file_input.pyindex e6216d7c580..feb98d14c03 100644--- a/tests/test_litellm/ocr/test_ocr_file_input.py+++ b/tests/test_litellm/ocr/test_ocr_file_input.py@@ -18,6 +18,7 @@ from unittest.mock import AsyncMock, MagicMockimport orjsonimport pytest+from starlette.datastructures import FormDatafrom litellm.ocr.main import convert_file_document_to_url_document, get_mime_type@@ -470,7 +471,7 @@ class TestProxySecurityGuard:mock_request = MagicMock()mock_request.headers = {"content-type": "multipart/form-data; boundary=---"}- mock_request.form = AsyncMock(return_value=mock_form)+ mock_request.form = AsyncMock(return_value=FormData(mock_form))result = await self._parse_multipart(mock_request)diff --git a/tests/test_litellm/proxy/common_utils/test_http_parsing_utils.py b/tests/test_litellm/proxy/common_utils/test_http_parsing_utils.pyindex 869d228d5a4..98af1fb7ce2 100644--- a/tests/test_litellm/proxy/common_utils/test_http_parsing_utils.py+++ b/tests/test_litellm/proxy/common_utils/test_http_parsing_utils.py@@ -7,6 +7,7 @@ import orjsonimport pytestfrom fastapi import Requestfrom fastapi.testclient import TestClient+from starlette.datastructures import FormDatasys.path.insert(0, os.path.abspath("../../../..")@@ -73,7 +74,7 @@ async def test_form_data_parsing():test_data = {"name": "test_user", "message": "hello world"}# Mock the form method to return the test data as an awaitable- mock_request.form = AsyncMock(return_value=test_data)+ mock_request.form = AsyncMock(return_value=FormData(test_data))mock_request.headers = {"content-type": "application/x-www-form-urlencoded"}mock_request.scope = {}mock_request.state._cached_headers = None@@ -124,7 +125,7 @@ async def test_form_data_with_json_metadata():}# Mock the form method to return the test data as an awaitable- mock_request.form = AsyncMock(return_value=test_data)+ mock_request.form = AsyncMock(return_value=FormData(test_data))mock_request.headers = {"content-type": "multipart/form-data"}mock_request.scope = {}mock_request.state._cached_headers = None@@ -165,7 +166,7 @@ async def test_form_data_with_invalid_json_metadata():}# Mock the form method to return the test data- mock_request.form = AsyncMock(return_value=test_data)+ mock_request.form = AsyncMock(return_value=FormData(test_data))mock_request.headers = {"content-type": "multipart/form-data"}mock_request.scope = {}mock_request.state._cached_headers = None@@ -188,7 +189,7 @@ async def test_form_data_without_metadata():test_data = {"model": "whisper-1", "file": "audio.mp3", "language": "en"}# Mock the form method to return the test data- mock_request.form = AsyncMock(return_value=test_data)+ mock_request.form = AsyncMock(return_value=FormData(test_data))mock_request.headers = {"content-type": "application/x-www-form-urlencoded"}mock_request.scope = {}mock_request.state._cached_headers = None@@ -219,7 +220,7 @@ async def test_form_data_with_empty_metadata():}# Mock the form method to return the test data- mock_request.form = AsyncMock(return_value=test_data)+ mock_request.form = AsyncMock(return_value=FormData(test_data))mock_request.headers = {"content-type": "multipart/form-data"}mock_request.scope = {}mock_request.state._cached_headers = None@@ -254,7 +255,7 @@ async def test_form_data_with_dict_metadata():}# Mock the form method to return the test data- mock_request.form = AsyncMock(return_value=test_data)+ mock_request.form = AsyncMock(return_value=FormData(test_data))mock_request.headers = {"content-type": "multipart/form-data"}mock_request.scope = {}mock_request.state._cached_headers = None@@ -285,7 +286,7 @@ async def test_form_data_with_none_metadata():}# Mock the form method to return the test data- mock_request.form = AsyncMock(return_value=test_data)+ mock_request.form = AsyncMock(return_value=FormData(test_data))mock_request.headers = {"content-type": "multipart/form-data"}mock_request.scope = {}mock_request.state._cached_headers = None@@ -500,33 +501,29 @@ async def test_surrogate_repair_skipped_above_size_limit(monkeypatch):@pytest.mark.asyncioasync def test_get_form_data():"""- Test that get_form_data correctly handles form data with array notation.- Tests audio transcription parameters as a specific example.+ A repeated `foo[]` key is how the OpenAI SDKs send a list, so every value has to+ survive. `FormData`, not a dict: a dict cannot even hold the duplicate key."""- # Create a mock request with transcription form datamock_request = MagicMock()+ mock_request.form = AsyncMock(+ return_value=FormData(+ [+ ("file", "file_object"),+ ("model", "gpt-4o-transcribe"),+ ("include[]", "logprobs"),+ ("language", "en"),+ ("prompt", "Transcribe this audio file"),+ ("response_format", "json"),+ ("stream", "false"),+ ("temperature", "0.2"),+ ("timestamp_granularities[]", "word"),+ ("timestamp_granularities[]", "segment"),+ ]+ )+ )- # Create mock form data with array notation for timestamp_granularities- mock_form_data = {- "file": "file_object", # In a real request this would be an UploadFile- "model": "gpt-4o-transcribe",- "include[]": "logprobs", # Array notation- "language": "en",- "prompt": "Transcribe this audio file",- "response_format": "json",- "stream": "false",- "temperature": "0.2",- "timestamp_granularities[]": "word", # First array item- "timestamp_granularities[]": "segment", # Second array item (would overwrite in dict, but handled by the function)- }-- # Mock the form method to return the test data- mock_request.form = AsyncMock(return_value=mock_form_data)-- # Call the function being testedresult = await get_form_data(mock_request)- # Verify regular form fields are preservedassert result["file"] == "file_object"assert result["model"] == "gpt-4o-transcribe"assert result["language"] == "en"@@ -534,17 +531,8 @@ async def test_get_form_data():assert result["response_format"] == "json"assert result["stream"] == "false"assert result["temperature"] == "0.2"-- # Verify array fields are correctly parsed- assert "include" in result- assert isinstance(result["include"], list)- assert "logprobs" in result["include"]-- assert "timestamp_granularities" in result- assert isinstance(result["timestamp_granularities"], list)- # Note: In a real MultiDict, both values would be present- # But in our mock dictionary the second value overwrites the first- assert "segment" in result["timestamp_granularities"]+ assert result["include"] == ["logprobs"]+ assert result["timestamp_granularities"] == ["word", "segment"]def test_get_tags_from_request_body_with_metadata_tags():@@ -958,7 +946,7 @@ class TestReadRequestBodyNonCanonicalContentType:mock_request = MagicMock()mock_request.body = AsyncMock(return_value=orjson.dumps(payload))- mock_request.form = AsyncMock(return_value={})+ mock_request.form = AsyncMock(return_value=FormData({}))mock_request.headers = {"content-type": content_type}mock_request.scope = {}@@ -969,7 +957,7 @@ class TestReadRequestBodyNonCanonicalContentType:@pytest.mark.asyncioasync def test_real_form_post_still_parsed_as_form(self):mock_request = MagicMock()- mock_request.form = AsyncMock(return_value={"k": "v"})+ mock_request.form = AsyncMock(return_value=FormData({"k": "v"}))mock_request.body = AsyncMock(return_value=b"")mock_request.headers = {"content-type": "application/x-www-form-urlencoded"}mock_request.scope = {}@@ -1025,7 +1013,7 @@ class TestGetRequestBody:mock_request = MagicMock()mock_request.method = "POST"mock_request.headers = {"content-type": "multipart/form-data; boundary=x"}- mock_request.form = AsyncMock(return_value={"k": "v"})+ mock_request.form = AsyncMock(return_value=FormData({"k": "v"}))mock_request.scope = {}result = await get_request_body(mock_request)diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.pyindex 6568f6aeacf..88141fd1c90 100644--- a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py@@ -13,6 +13,7 @@ import httpximport pytestfrom fastapi import HTTPException, Request, Responsefrom fastapi.testclient import TestClient+from starlette.datastructures import FormDatasys.path.insert(0, os.path.abspath("../../../..")@@ -1384,7 +1385,7 @@ async def test_is_streaming_request_fn():mock_request = Mock()mock_request.method = "POST"mock_request.headers = {"content-type": "multipart/form-data"}- mock_request.form = AsyncMock(return_value={"stream": "true"})+ mock_request.form = AsyncMock(return_value=FormData({"stream": "true"}))assert await is_streaming_request_fn(mock_request) is True