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
chore: merge main into litellm_fix_image_edits_bracketed_alias
Devin AIa295f3f0c9d2
diff --cc litellm/proxy/image_endpoints/endpoints.pyindex 7d6d37c7c75,3f044855ce8..7fcbc75dd65--- a/litellm/proxy/image_endpoints/endpoints.py+++ b/litellm/proxy/image_endpoints/endpoints.py@@@ -21,10 -31,8 +31,12 @@@ from litellm.types.llms.openai import Crouter: Final = APIRouter()+ IMAGE_EDIT_NUMERIC_FORM_FIELDS: Final = numeric_form_fields(get_type_hints(ImageEditRequestParams))++IMAGE_ARRAY_FIELD: Final = "image[]"+MASK_ARRAY_FIELD: Final = "mask[]"+BRACKETED_FILE_FIELDS: Final = frozenset({IMAGE_ARRAY_FIELD, MASK_ARRAY_FIELD})+async def uploadfile_to_bytesio(upload: UploadFile) -> io.BytesIO:"""@@@ -283,11 -291,12 +295,16 @@@ async def image_edit_api########################################################## Read request body and convert UploadFiles to BytesIO#########################################################- data: Final = dict(- coerce_numeric_form_fields(- parsed_body=await _read_request_body(request=request),- numeric_fields=IMAGE_EDIT_NUMERIC_FORM_FIELDS,- )- )+ data: Final = {+ key: value- for key, value in (await _read_request_body(request=request)).items()++ for key, value in dict(++ coerce_numeric_form_fields(++ parsed_body=await _read_request_body(request=request),++ numeric_fields=IMAGE_EDIT_NUMERIC_FORM_FIELDS,++ )++ ).items()+ if key not in BRACKETED_FILE_FIELDS+ }image_files: Final = await batch_to_bytesio(image)mask_files: Final = await batch_to_bytesio(mask)if image_files:diff --cc tests/test_litellm/proxy/image_endpoints/test_endpoints.pyindex 65524b54742,d8b3eef98bd..7d774d6ed81--- a/tests/test_litellm/proxy/image_endpoints/test_endpoints.py+++ b/tests/test_litellm/proxy/image_endpoints/test_endpoints.py@@@ -92,18 -92,18 +92,14 @@@ async def test_image_generation_prompt_monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)monkeypatch.setattr("litellm.proxy.proxy_server.proxy_config", {})-- monkeypatch.setattr(-- "litellm.proxy.proxy_server.proxy_logging_obj", fake_proxy_logger-- )++ monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", fake_proxy_logger)monkeypatch.setattr("litellm.proxy.proxy_server.user_model", None)monkeypatch.setattr("litellm.proxy.proxy_server.version", "test-version")monkeypatch.setattr("litellm.proxy.common_request_processing.ProxyBaseLLMRequestProcessing.get_custom_headers",classmethod(lambda *args, **kwargs: {}),)-- monkeypatch.setattr(-- "litellm.proxy.image_endpoints.endpoints.route_request", fake_route_request-- )++ monkeypatch.setattr("litellm.proxy.image_endpoints.endpoints.route_request", fake_route_request)result = await endpoints.image_generation(request=request,@@@ -138,55 -138,76 +134,134 @@@ def _image_edit_client(monkeypatch, capreturn TestClient(app)+def test_image_edit_image_array_alias_is_not_forwarded(monkeypatch):+ """The documented `image[]` alias must reach the provider only as `image`."""+ captured: Dict[str, Any] = {}++ response = _image_edit_client(monkeypatch, captured).post(+ "/v1/images/edits",+ files={"image[]": ("tree.png", b"\x89PNG\r\n\x1a\ntree", "image/png")},+ data={"model": "gpt-image-1", "prompt": "add a hat"},+ )++ assert response.status_code == 200+ assert "image[]" not in captured+ assert [buffer.getvalue() for buffer in captured["image"]] == [b"\x89PNG\r\n\x1a\ntree"]+ assert [buffer.name for buffer in captured["image"]] == ["tree.png"]+++def test_image_edit_mask_array_alias_is_not_forwarded(monkeypatch):+ """`mask[]` has the same shape as `image[]` and must be dropped the same way."""+ captured: Dict[str, Any] = {}++ response = _image_edit_client(monkeypatch, captured).post(+ "/v1/images/edits",+ files={+ "image": ("tree.png", b"\x89PNG\r\n\x1a\ntree", "image/png"),+ "mask[]": ("mask.png", b"\x89PNG\r\n\x1a\nmask", "image/png"),+ },+ data={"model": "gpt-image-1", "prompt": "add a hat"},+ )++ assert response.status_code == 200+ assert "mask[]" not in captured+ assert [buffer.getvalue() for buffer in captured["mask"]] == [b"\x89PNG\r\n\x1a\nmask"]+ assert [buffer.getvalue() for buffer in captured["image"]] == [b"\x89PNG\r\n\x1a\ntree"]+++def test_image_edit_canonical_file_fields_still_reach_the_provider(monkeypatch):+ """Dropping the bracketed aliases must not touch the canonical fields."""+ captured: Dict[str, Any] = {}++ response = _image_edit_client(monkeypatch, captured).post(+ "/v1/images/edits",+ files={+ "image": ("tree.png", b"\x89PNG\r\n\x1a\ntree", "image/png"),+ "mask": ("mask.png", b"\x89PNG\r\n\x1a\nmask", "image/png"),+ },+ data={"model": "gpt-image-1", "prompt": "add a hat"},+ )++ assert response.status_code == 200+ assert [buffer.getvalue() for buffer in captured["image"]] == [b"\x89PNG\r\n\x1a\ntree"]+ assert [buffer.getvalue() for buffer in captured["mask"]] == [b"\x89PNG\r\n\x1a\nmask"]+ assert captured["prompt"] == "add a hat"+++++ def test_image_edit_multipart_n_reaches_the_provider_as_an_int(monkeypatch):+ """A multipart `n` must not arrive as the string Starlette parsed it into."""+ captured: Dict[str, Any] = {}++ response = _image_edit_client(monkeypatch, captured).post(+ "/v1/images/edits",+ files={"image": ("tree.png", b"\x89PNG\r\n\x1a\n", "image/png")},+ data={"model": "nova-canvas", "prompt": "add a hat", "n": "2", "size": "1024x1024"},+ )++ assert response.status_code == 200+ assert captured["n"] == 2+ assert isinstance(captured["n"], int)+ assert captured["size"] == "1024x1024"+ assert captured["prompt"] == "add a hat"+++ def test_image_edit_multipart_n_that_is_not_a_number_is_left_alone(monkeypatch):+ """An unparseable `n` still reaches the provider, which rejects it as before."""+ captured: Dict[str, Any] = {}++ response = _image_edit_client(monkeypatch, captured).post(+ "/v1/images/edits",+ files={"image": ("tree.png", b"\x89PNG\r\n\x1a\n", "image/png")},+ data={"model": "nova-canvas", "prompt": "add a hat", "n": "two"},+ )++ assert response.status_code == 200+ assert captured["n"] == "two"+++ @pytest.mark.asyncio+ async def test_a_model_the_router_cannot_serve_answers_an_openai_typed_error(monkeypatch: pytest.MonkeyPatch):+ """A bare HTTPException carries no type or param, so the tail used to ship the+ literal string "None" in both fields."""++ async def fake_add_litellm_data_to_request(**kwargs: object) -> object:+ return kwargs["data"]+- async def fake_pre_call_hook(*, user_api_key_dict: UserAPIKeyAuth, data: dict[str, object], call_type: str) -> dict[str, object]:++ async def fake_pre_call_hook(++ *, user_api_key_dict: UserAPIKeyAuth, data: dict[str, object], call_type: str++ ) -> dict[str, object]:+ return data++ async def fake_post_call_failure_hook(**_: object) -> None:+ return None++ async def failing_route_request(**_: object) -> None:+ raise HTTPException(+ status_code=404, detail={"error": "image_generation: Invalid model name passed in model=dall-e-3"}+ )++ monkeypatch.setattr("litellm.proxy.proxy_server.add_litellm_data_to_request", fake_add_litellm_data_to_request)+ monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.proxy_config", {})+ monkeypatch.setattr(+ "litellm.proxy.proxy_server.proxy_logging_obj",+ SimpleNamespace(pre_call_hook=fake_pre_call_hook, post_call_failure_hook=fake_post_call_failure_hook),+ )+ monkeypatch.setattr("litellm.proxy.proxy_server.user_model", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.version", "test-version")+ monkeypatch.setattr("litellm.proxy.image_endpoints.endpoints.route_request", failing_route_request)++ body = orjson.dumps({"model": "dall-e-3", "prompt": "a lighthouse at dusk"})++ async def receive() -> dict[str, object]:+ return {"type": "http.request", "body": body, "more_body": False}++ request = Request({"type": "http", "method": "POST", "path": "/v1/images/generations", "headers": []}, receive)++ with pytest.raises(ProxyException) as raised:- await endpoints.image_generation(request=request, fastapi_response=Response(), user_api_key_dict=UserAPIKeyAuth())++ await endpoints.image_generation(++ request=request, fastapi_response=Response(), user_api_key_dict=UserAPIKeyAuth()++ )++ assert (raised.value.type, raised.value.param, raised.value.code) == ("invalid_request_error", None, "404")