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] Dall-e-2 for Image Edits API (#15604)
Ishaan Jaff6f69b009c847
diff --git a/litellm/llms/openai/image_edit/__init__.py b/litellm/llms/openai/image_edit/__init__.pynew file mode 100644index 00000000000..c1898326b72--- /dev/null+++ b/litellm/llms/openai/image_edit/__init__.py@@ -0,0 +1,26 @@+from litellm.llms.base_llm.image_edit.transformation import BaseImageEditConfig++from .dalle2_transformation import DallE2ImageEditConfig+from .transformation import OpenAIImageEditConfig++__all__ = ["OpenAIImageEditConfig", "DallE2ImageEditConfig", "get_openai_image_edit_config"]+++def get_openai_image_edit_config(model: str) -> BaseImageEditConfig:+ """+ Get the appropriate OpenAI image edit config based on the model.++ Args:+ model: The model name (e.g., "dall-e-2", "gpt-image-1")++ Returns:+ The appropriate config instance for the model+ """+ model_normalized = model.lower().replace("-", "").replace("_", "")++ if model_normalized == "dalle2":+ return DallE2ImageEditConfig()+ else:+ # Default to standard OpenAI config for gpt-image-1 and other models+ return OpenAIImageEditConfig()+diff --git a/litellm/llms/openai/image_edit/dalle2_transformation.py b/litellm/llms/openai/image_edit/dalle2_transformation.pynew file mode 100644index 00000000000..37e92be17a8--- /dev/null+++ b/litellm/llms/openai/image_edit/dalle2_transformation.py@@ -0,0 +1,101 @@+from io import BufferedReader+from typing import TYPE_CHECKING, Any, Dict, List, Tuple, cast++from httpx._types import RequestFiles++import litellm+from litellm.images.utils import ImageEditRequestUtils+from litellm.types.images.main import ImageEditRequestParams+from litellm.types.llms.openai import FileTypes+from litellm.types.router import GenericLiteLLMParams++from .transformation import OpenAIImageEditConfig++if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj++ LiteLLMLoggingObj = _LiteLLMLoggingObj+else:+ LiteLLMLoggingObj = Any+++class DallE2ImageEditConfig(OpenAIImageEditConfig):+ """+ DALL-E-2 specific configuration for image edit API.++ DALL-E-2 only supports editing a single image (not an array).+ Uses "image" field name instead of "image[]".+ """++ def transform_image_edit_request(+ self,+ model: str,+ prompt: str,+ image: FileTypes,+ image_edit_optional_request_params: Dict,+ litellm_params: GenericLiteLLMParams,+ headers: dict,+ ) -> Tuple[Dict, RequestFiles]:+ """+ Transform image edit request for DALL-E-2.++ DALL-E-2 only accepts a single image with field name "image" (not "image[]").+ """+ request = ImageEditRequestParams(+ model=model,+ image=image,+ prompt=prompt,+ **image_edit_optional_request_params,+ )+ request_dict = cast(Dict, request)++ #########################################################+ # Separate images and masks as `files` and send other parameters as `data`+ #########################################################+ _image_list = request_dict.get("image")+ _mask = request_dict.get("mask")+ data_without_files = {+ k: v for k, v in request_dict.items() if k not in ["image", "mask"]+ }+ files_list: List[Tuple[str, Any]] = []++ # Handle image parameter - DALL-E-2 only supports single image+ if _image_list is not None:+ image_list = (+ [_image_list] if not isinstance(_image_list, list) else _image_list+ )++ # Validate only one image is provided+ if len(image_list) > 1:+ raise litellm.BadRequestError(+ message="DALL-E-2 only supports editing a single image. Please provide one image.",+ model=model,+ llm_provider="openai",+ )++ # Use "image" field name (singular) for DALL-E-2+ for _image in image_list:+ if _image is not None:+ self._add_image_to_files(+ files_list=files_list,+ image=_image,+ field_name="image",+ )++ # Handle mask parameter if provided+ if _mask is not None:+ # Handle case where mask can be a list (extract first mask)+ if isinstance(_mask, list):+ _mask = _mask[0] if _mask else None++ if _mask is not None:+ mask_content_type: str = ImageEditRequestUtils.get_image_content_type(+ _mask+ )+ if isinstance(_mask, BufferedReader):+ files_list.append(("mask", (_mask.name, _mask, mask_content_type)))+ else:+ files_list.append(("mask", ("mask.png", _mask, mask_content_type)))++ return data_without_files, files_list+diff --git a/litellm/llms/openai/image_edit/transformation.py b/litellm/llms/openai/image_edit/transformation.pyindex be960641154..1b90d96fa92 100644--- a/litellm/llms/openai/image_edit/transformation.py+++ b/litellm/llms/openai/image_edit/transformation.py@@ -27,6 +27,11 @@ else:class OpenAIImageEditConfig(BaseImageEditConfig):+ """+ Base configuration for OpenAI image edit API.+ Used for models like gpt-image-1 that support multiple images.+ """+def get_supported_openai_params(self, model: str) -> list:"""All OpenAI Image Edits params are supported@@ -57,6 +62,20 @@ class OpenAIImageEditConfig(BaseImageEditConfig):"""No mapping applied since inputs are in OpenAI spec already"""return dict(image_edit_optional_params)+ def _add_image_to_files(+ self,+ files_list: List[Tuple[str, Any]],+ image: Any,+ field_name: str,+ ) -> None:+ """Add an image to the files list with appropriate content type"""+ image_content_type = ImageEditRequestUtils.get_image_content_type(image)++ if isinstance(image, BufferedReader):+ files_list.append((field_name, (image.name, image, image_content_type)))+ else:+ files_list.append((field_name, ("image.png", image, image_content_type)))+def transform_image_edit_request(self,model: str,@@ -67,9 +86,10 @@ class OpenAIImageEditConfig(BaseImageEditConfig):headers: dict,) -> Tuple[Dict, RequestFiles]:"""- No transform applied since inputs are in OpenAI spec already+ Transform image edit request to OpenAI API format.- This handles buffered readers as images to be sent as multipart/form-data for OpenAI+ Handles multipart/form-data for images. Uses "image[]" field name+ to support multiple images (e.g., for gpt-image-1)."""request = ImageEditRequestParams(model=model,@@ -94,19 +114,14 @@ class OpenAIImageEditConfig(BaseImageEditConfig):image_list = ([_image_list] if not isinstance(_image_list, list) else _image_list)+for _image in image_list:if _image is not None:- image_content_type: str = (- ImageEditRequestUtils.get_image_content_type(_image)+ self._add_image_to_files(+ files_list=files_list,+ image=_image,+ field_name="image[]",)- if isinstance(_image, BufferedReader):- files_list.append(- ("image[]", (_image.name, _image, image_content_type))- )- else:- files_list.append(- ("image[]", ("image.png", _image, image_content_type))- )# Handle mask parameter if providedif _mask is not None:# Handle case where mask can be a list (extract first mask)diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex 209faf999d8..caca89d23f8 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -9604,6 +9604,54 @@"supports_vision": true,"supports_web_search": true},+ "gemini-2.5-flash-image": {+ "cache_read_input_token_cost": 3e-08,+ "input_cost_per_audio_token": 1e-06,+ "input_cost_per_token": 3e-07,+ "litellm_provider": "vertex_ai-language-models",+ "max_audio_length_hours": 8.4,+ "max_audio_per_prompt": 1,+ "max_images_per_prompt": 3000,+ "max_input_tokens": 32768,+ "max_output_tokens": 32768,+ "max_tokens": 32768,+ "max_pdf_size_mb": 30,+ "max_video_length": 1,+ "max_videos_per_prompt": 10,+ "mode": "image_generation",+ "output_cost_per_image": 0.039,+ "output_cost_per_reasoning_token": 2.5e-06,+ "output_cost_per_token": 2.5e-06,+ "rpm": 100000,+ "source": "https://ai.google.dev/gemini-api/docs/pricing#gemini-2.5-flash-image",+ "supported_endpoints": [+ "/v1/chat/completions",+ "/v1/completions",+ "/v1/batch"+ ],+ "supported_modalities": [+ "text",+ "image",+ "audio",+ "video"+ ],+ "supported_output_modalities": [+ "text",+ "image"+ ],+ "supports_audio_output": false,+ "supports_function_calling": true,+ "supports_parallel_function_calling": true,+ "supports_pdf_input": true,+ "supports_prompt_caching": true,+ "supports_response_schema": true,+ "supports_system_messages": true,+ "supports_tool_choice": true,+ "supports_url_context": true,+ "supports_vision": true,+ "supports_web_search": true,+ "tpm": 8000000+ },"gemini-2.5-flash-image-preview": {"cache_read_input_token_cost": 7.5e-08,"input_cost_per_audio_token": 1e-06,@@ -11057,6 +11105,54 @@"supports_web_search": true,"tpm": 8000000},+ "gemini/gemini-2.5-flash-image": {+ "cache_read_input_token_cost": 3e-08,+ "input_cost_per_audio_token": 1e-06,+ "input_cost_per_token": 3e-07,+ "litellm_provider": "vertex_ai-language-models",+ "max_audio_length_hours": 8.4,+ "max_audio_per_prompt": 1,+ "max_images_per_prompt": 3000,+ "max_input_tokens": 32768,+ "max_output_tokens": 32768,+ "max_tokens": 32768,+ "max_pdf_size_mb": 30,+ "max_video_length": 1,+ "max_videos_per_prompt": 10,+ "mode": "image_generation",+ "output_cost_per_image": 0.039,+ "output_cost_per_reasoning_token": 2.5e-06,+ "output_cost_per_token": 2.5e-06,+ "rpm": 100000,+ "source": "https://ai.google.dev/gemini-api/docs/pricing#gemini-2.5-flash-image",+ "supported_endpoints": [+ "/v1/chat/completions",+ "/v1/completions",+ "/v1/batch"+ ],+ "supported_modalities": [+ "text",+ "image",+ "audio",+ "video"+ ],+ "supported_output_modalities": [+ "text",+ "image"+ ],+ "supports_audio_output": false,+ "supports_function_calling": true,+ "supports_parallel_function_calling": true,+ "supports_pdf_input": true,+ "supports_prompt_caching": true,+ "supports_response_schema": true,+ "supports_system_messages": true,+ "supports_tool_choice": true,+ "supports_url_context": true,+ "supports_vision": true,+ "supports_web_search": true,+ "tpm": 8000000+ },"gemini/gemini-2.5-flash-image-preview": {"cache_read_input_token_cost": 7.5e-08,"input_cost_per_audio_token": 1e-06,@@ -13315,11 +13411,11 @@"text"],"supports_function_calling": true,- "supports_native_streaming": false,+ "supports_native_streaming": true,"supports_parallel_function_calling": true,"supports_pdf_input": true,"supports_prompt_caching": true,- "supports_reasoning": false,+ "supports_reasoning": true,"supports_response_schema": true,"supports_system_messages": false,"supports_tool_choice": true,diff --git a/litellm/utils.py b/litellm/utils.pyindex 45cc901a1a0..f017543ceaa 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -7559,11 +7559,9 @@ class ProviderConfigManager:provider: LlmProviders,) -> Optional[BaseImageEditConfig]:if LlmProviders.OPENAI == provider:- from litellm.llms.openai.image_edit.transformation import (- OpenAIImageEditConfig,- )+ from litellm.llms.openai.image_edit import get_openai_image_edit_config- return OpenAIImageEditConfig()+ return get_openai_image_edit_config(model=model)elif LlmProviders.AZURE == provider:from litellm.llms.azure.image_edit.transformation import (AzureImageEditConfig,diff --git a/test_image_edit.png b/test_image_edit.pngindex 0380114f241..0386d2af106 100644Binary files a/test_image_edit.png and b/test_image_edit.png differdiff --git a/tests/image_gen_tests/test_image_edits.py b/tests/image_gen_tests/test_image_edits.pyindex 74562c4648f..90544f747bb 100644--- a/tests/image_gen_tests/test_image_edits.py+++ b/tests/image_gen_tests/test_image_edits.py@@ -9,6 +9,7 @@ import base64from io import BytesIOfrom unittest.mock import patch, AsyncMockimport json+from abc import ABC, abstractmethodsys.path.insert(0, os.path.abspath("../..")@@ -30,6 +31,72 @@ class TestCustomLogger(CustomLogger):self.standard_logging_payload = kwargs.get("standard_logging_object", None)pass++class BaseLLMImageEditTest(ABC):+ """+ Abstract base test class that enforces a common test across all image edit test classes.+ """++ @property+ def image_edit_function(self):+ return litellm.image_edit++ @property+ def async_image_edit_function(self):+ return litellm.aimage_edit++ @abstractmethod+ def get_base_image_edit_call_args(self) -> dict:+ """Must return the base image edit call args"""+ pass++ @pytest.fixture(autouse=True)+ def _handle_rate_limits(self):+ """Fixture to handle rate limit errors for all test methods"""+ try:+ yield+ except litellm.RateLimitError:+ pytest.skip("Rate limit exceeded")+ except litellm.InternalServerError:+ pytest.skip("Model is overloaded")++ @pytest.mark.parametrize("sync_mode", [True, False])+ @pytest.mark.flaky(retries=3, delay=2)+ @pytest.mark.asyncio+ async def test_openai_image_edit_litellm_sdk(self, sync_mode):+ """+ Test image edit functionality with both sync and async modes.+ """+ litellm._turn_on_debug()+ try:+ prompt = """+ Create a studio ghibli style image that combines all the reference images. Make sure the person looks like a CTO.+ """++ call_args = self.get_base_image_edit_call_args()+ call_args["prompt"] = prompt++ if sync_mode:+ result = self.image_edit_function(**call_args)+ else:+ result = await self.async_image_edit_function(**call_args)++ print("result from image edit", result)++ # Validate the response meets expected schema+ ImageResponse.model_validate(result)++ if isinstance(result, ImageResponse) and result.data:+ image_base64 = result.data[0].b64_json+ if image_base64:+ image_bytes = base64.b64decode(image_base64)++ # Save the image to a file+ with open("test_image_edit.png", "wb") as f:+ f.write(image_bytes)+ except litellm.ContentPolicyViolationError as e:+ pass+# Get the current directory of the file being runpwd = os.path.dirname(os.path.realpath(__file__))@@ -49,45 +116,31 @@ def get_test_images_as_bytesio():bytesio_images.append(BytesIO(image_bytes))return bytesio_images[email protected]("sync_mode", [True, False])[email protected](retries=3, delay=2)-async def test_openai_image_edit_litellm_sdk(sync_mode):- from litellm import image_edit, aimage_edit- litellm._turn_on_debug()- try:- prompt = """- Create a studio ghibli style image that combines all the reference images. Make sure the person looks like a CTO.- """- if sync_mode:- result = image_edit(- prompt=prompt,- model="gpt-image-1",- image=TEST_IMAGES,- )- else:- result = await aimage_edit(- prompt=prompt,- model="gpt-image-1",- image=TEST_IMAGES,- )- print("result from image edit", result)+class TestOpenAIImageEditGPTImage1(BaseLLMImageEditTest):+ """+ Concrete implementation of BaseLLMImageEditTest for OpenAI image edits.+ """- # Validate the response meets expected schema- ImageResponse.model_validate(result)-- if isinstance(result, ImageResponse) and result.data:- image_base64 = result.data[0].b64_json- if image_base64:- image_bytes = base64.b64decode(image_base64)+ def get_base_image_edit_call_args(self) -> dict:+ """Return base call args for OpenAI image edit"""+ return {+ "model": "gpt-image-1",+ "image": TEST_IMAGES,+ }- # Save the image to a file- with open("test_image_edit.png", "wb") as f:- f.write(image_bytes)- except litellm.ContentPolicyViolationError as e:- pass+class TestOpenAIImageEditDallE2(BaseLLMImageEditTest):+ """+ Concrete implementation of BaseLLMImageEditTest for OpenAI DALL-E-2 image edits.+ DALL-E-2 only supports a single image (not an array).+ """+ def get_base_image_edit_call_args(self) -> dict:+ """Return base call args for OpenAI DALL-E-2 image edit (single image only)"""+ return {+ "model": "dall-e-2",+ "image": SINGLE_TEST_IMAGE,+ }@pytest.mark.flaky(retries=3, delay=2)